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 routing::scorer::Scorer;
1477 use chain::transaction::OutPoint;
1478 use ln::features::{ChannelFeatures, InitFeatures, InvoiceFeatures, NodeFeatures};
1479 use ln::msgs::{ErrorAction, LightningError, OptionalField, UnsignedChannelAnnouncement, ChannelAnnouncement, RoutingMessageHandler,
1480 NodeAnnouncement, UnsignedNodeAnnouncement, ChannelUpdate, UnsignedChannelUpdate};
1481 use ln::channelmanager;
1482 use util::test_utils;
1483 use util::ser::Writeable;
1485 use bitcoin::hashes::sha256d::Hash as Sha256dHash;
1486 use bitcoin::hashes::Hash;
1487 use bitcoin::network::constants::Network;
1488 use bitcoin::blockdata::constants::genesis_block;
1489 use bitcoin::blockdata::script::Builder;
1490 use bitcoin::blockdata::opcodes;
1491 use bitcoin::blockdata::transaction::TxOut;
1495 use bitcoin::secp256k1::key::{PublicKey,SecretKey};
1496 use bitcoin::secp256k1::{Secp256k1, All};
1499 use sync::{self, Arc};
1501 fn get_channel_details(short_channel_id: Option<u64>, node_id: PublicKey,
1502 features: InitFeatures, outbound_capacity_msat: u64) -> channelmanager::ChannelDetails {
1503 channelmanager::ChannelDetails {
1504 channel_id: [0; 32],
1505 counterparty: channelmanager::ChannelCounterparty {
1508 unspendable_punishment_reserve: 0,
1509 forwarding_info: None,
1511 funding_txo: Some(OutPoint { txid: bitcoin::Txid::from_slice(&[0; 32]).unwrap(), index: 0 }),
1513 channel_value_satoshis: 0,
1515 outbound_capacity_msat,
1516 inbound_capacity_msat: 42,
1517 unspendable_punishment_reserve: None,
1518 confirmations_required: None,
1519 force_close_spend_delay: None,
1520 is_outbound: true, is_funding_locked: true,
1521 is_usable: true, is_public: true,
1525 // Using the same keys for LN and BTC ids
1527 net_graph_msg_handler: &NetGraphMsgHandler<Arc<test_utils::TestChainSource>, Arc<test_utils::TestLogger>>,
1528 secp_ctx: &Secp256k1<All>, node_1_privkey: &SecretKey, node_2_privkey: &SecretKey, features: ChannelFeatures, short_channel_id: u64
1530 let node_id_1 = PublicKey::from_secret_key(&secp_ctx, node_1_privkey);
1531 let node_id_2 = PublicKey::from_secret_key(&secp_ctx, node_2_privkey);
1533 let unsigned_announcement = UnsignedChannelAnnouncement {
1535 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1539 bitcoin_key_1: node_id_1,
1540 bitcoin_key_2: node_id_2,
1541 excess_data: Vec::new(),
1544 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1545 let valid_announcement = ChannelAnnouncement {
1546 node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
1547 node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
1548 bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
1549 bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
1550 contents: unsigned_announcement.clone(),
1552 match net_graph_msg_handler.handle_channel_announcement(&valid_announcement) {
1553 Ok(res) => assert!(res),
1559 net_graph_msg_handler: &NetGraphMsgHandler<Arc<test_utils::TestChainSource>, Arc<test_utils::TestLogger>>,
1560 secp_ctx: &Secp256k1<All>, node_privkey: &SecretKey, update: UnsignedChannelUpdate
1562 let msghash = hash_to_message!(&Sha256dHash::hash(&update.encode()[..])[..]);
1563 let valid_channel_update = ChannelUpdate {
1564 signature: secp_ctx.sign(&msghash, node_privkey),
1565 contents: update.clone()
1568 match net_graph_msg_handler.handle_channel_update(&valid_channel_update) {
1569 Ok(res) => assert!(res),
1574 fn add_or_update_node(
1575 net_graph_msg_handler: &NetGraphMsgHandler<Arc<test_utils::TestChainSource>, Arc<test_utils::TestLogger>>,
1576 secp_ctx: &Secp256k1<All>, node_privkey: &SecretKey, features: NodeFeatures, timestamp: u32
1578 let node_id = PublicKey::from_secret_key(&secp_ctx, node_privkey);
1579 let unsigned_announcement = UnsignedNodeAnnouncement {
1585 addresses: Vec::new(),
1586 excess_address_data: Vec::new(),
1587 excess_data: Vec::new(),
1589 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1590 let valid_announcement = NodeAnnouncement {
1591 signature: secp_ctx.sign(&msghash, node_privkey),
1592 contents: unsigned_announcement.clone()
1595 match net_graph_msg_handler.handle_node_announcement(&valid_announcement) {
1601 fn get_nodes(secp_ctx: &Secp256k1<All>) -> (SecretKey, PublicKey, Vec<SecretKey>, Vec<PublicKey>) {
1602 let privkeys: Vec<SecretKey> = (2..10).map(|i| {
1603 SecretKey::from_slice(&hex::decode(format!("{:02}", i).repeat(32)).unwrap()[..]).unwrap()
1606 let pubkeys = privkeys.iter().map(|secret| PublicKey::from_secret_key(&secp_ctx, secret)).collect();
1608 let our_privkey = SecretKey::from_slice(&hex::decode("01".repeat(32)).unwrap()[..]).unwrap();
1609 let our_id = PublicKey::from_secret_key(&secp_ctx, &our_privkey);
1611 (our_privkey, our_id, privkeys, pubkeys)
1614 fn id_to_feature_flags(id: u8) -> Vec<u8> {
1615 // Set the feature flags to the id'th odd (ie non-required) feature bit so that we can
1616 // test for it later.
1617 let idx = (id - 1) * 2 + 1;
1619 vec![1 << (idx - 8*3), 0, 0, 0]
1620 } else if idx > 8*2 {
1621 vec![1 << (idx - 8*2), 0, 0]
1622 } else if idx > 8*1 {
1623 vec![1 << (idx - 8*1), 0]
1629 fn build_graph() -> (Secp256k1<All>, NetGraphMsgHandler<sync::Arc<test_utils::TestChainSource>, sync::Arc<crate::util::test_utils::TestLogger>>, sync::Arc<test_utils::TestChainSource>, sync::Arc<test_utils::TestLogger>) {
1630 let secp_ctx = Secp256k1::new();
1631 let logger = Arc::new(test_utils::TestLogger::new());
1632 let chain_monitor = Arc::new(test_utils::TestChainSource::new(Network::Testnet));
1633 let network_graph = NetworkGraph::new(genesis_block(Network::Testnet).header.block_hash());
1634 let net_graph_msg_handler = NetGraphMsgHandler::new(network_graph, None, Arc::clone(&logger));
1635 // Build network from our_id to node6:
1637 // -1(1)2- node0 -1(3)2-
1639 // our_id -1(12)2- node7 -1(13)2--- node2
1641 // -1(2)2- node1 -1(4)2-
1644 // chan1 1-to-2: disabled
1645 // chan1 2-to-1: enabled, 0 fee
1647 // chan2 1-to-2: enabled, ignored fee
1648 // chan2 2-to-1: enabled, 0 fee
1650 // chan3 1-to-2: enabled, 0 fee
1651 // chan3 2-to-1: enabled, 100 msat fee
1653 // chan4 1-to-2: enabled, 100% fee
1654 // chan4 2-to-1: enabled, 0 fee
1656 // chan12 1-to-2: enabled, ignored fee
1657 // chan12 2-to-1: enabled, 0 fee
1659 // chan13 1-to-2: enabled, 200% fee
1660 // chan13 2-to-1: enabled, 0 fee
1663 // -1(5)2- node3 -1(8)2--
1667 // node2--1(6)2- node4 -1(9)2--- node6 (not in global route map)
1669 // -1(7)2- node5 -1(10)2-
1671 // Channels 5, 8, 9 and 10 are private channels.
1673 // chan5 1-to-2: enabled, 100 msat fee
1674 // chan5 2-to-1: enabled, 0 fee
1676 // chan6 1-to-2: enabled, 0 fee
1677 // chan6 2-to-1: enabled, 0 fee
1679 // chan7 1-to-2: enabled, 100% fee
1680 // chan7 2-to-1: enabled, 0 fee
1682 // chan8 1-to-2: enabled, variable fee (0 then 1000 msat)
1683 // chan8 2-to-1: enabled, 0 fee
1685 // chan9 1-to-2: enabled, 1001 msat fee
1686 // chan9 2-to-1: enabled, 0 fee
1688 // chan10 1-to-2: enabled, 0 fee
1689 // chan10 2-to-1: enabled, 0 fee
1691 // chan11 1-to-2: enabled, 0 fee
1692 // chan11 2-to-1: enabled, 0 fee
1694 let (our_privkey, _, privkeys, _) = get_nodes(&secp_ctx);
1696 add_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, &privkeys[0], ChannelFeatures::from_le_bytes(id_to_feature_flags(1)), 1);
1697 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
1698 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1699 short_channel_id: 1,
1702 cltv_expiry_delta: 0,
1703 htlc_minimum_msat: 0,
1704 htlc_maximum_msat: OptionalField::Absent,
1706 fee_proportional_millionths: 0,
1707 excess_data: Vec::new()
1710 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[0], NodeFeatures::from_le_bytes(id_to_feature_flags(1)), 0);
1712 add_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, &privkeys[1], ChannelFeatures::from_le_bytes(id_to_feature_flags(2)), 2);
1713 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
1714 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1715 short_channel_id: 2,
1718 cltv_expiry_delta: u16::max_value(),
1719 htlc_minimum_msat: 0,
1720 htlc_maximum_msat: OptionalField::Absent,
1721 fee_base_msat: u32::max_value(),
1722 fee_proportional_millionths: u32::max_value(),
1723 excess_data: Vec::new()
1725 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
1726 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1727 short_channel_id: 2,
1730 cltv_expiry_delta: 0,
1731 htlc_minimum_msat: 0,
1732 htlc_maximum_msat: OptionalField::Absent,
1734 fee_proportional_millionths: 0,
1735 excess_data: Vec::new()
1738 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[1], NodeFeatures::from_le_bytes(id_to_feature_flags(2)), 0);
1740 add_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, &privkeys[7], ChannelFeatures::from_le_bytes(id_to_feature_flags(12)), 12);
1741 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
1742 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1743 short_channel_id: 12,
1746 cltv_expiry_delta: u16::max_value(),
1747 htlc_minimum_msat: 0,
1748 htlc_maximum_msat: OptionalField::Absent,
1749 fee_base_msat: u32::max_value(),
1750 fee_proportional_millionths: u32::max_value(),
1751 excess_data: Vec::new()
1753 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
1754 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1755 short_channel_id: 12,
1758 cltv_expiry_delta: 0,
1759 htlc_minimum_msat: 0,
1760 htlc_maximum_msat: OptionalField::Absent,
1762 fee_proportional_millionths: 0,
1763 excess_data: Vec::new()
1766 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[7], NodeFeatures::from_le_bytes(id_to_feature_flags(8)), 0);
1768 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], &privkeys[2], ChannelFeatures::from_le_bytes(id_to_feature_flags(3)), 3);
1769 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
1770 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1771 short_channel_id: 3,
1774 cltv_expiry_delta: (3 << 8) | 1,
1775 htlc_minimum_msat: 0,
1776 htlc_maximum_msat: OptionalField::Absent,
1778 fee_proportional_millionths: 0,
1779 excess_data: Vec::new()
1781 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
1782 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1783 short_channel_id: 3,
1786 cltv_expiry_delta: (3 << 8) | 2,
1787 htlc_minimum_msat: 0,
1788 htlc_maximum_msat: OptionalField::Absent,
1790 fee_proportional_millionths: 0,
1791 excess_data: Vec::new()
1794 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], &privkeys[2], ChannelFeatures::from_le_bytes(id_to_feature_flags(4)), 4);
1795 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
1796 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1797 short_channel_id: 4,
1800 cltv_expiry_delta: (4 << 8) | 1,
1801 htlc_minimum_msat: 0,
1802 htlc_maximum_msat: OptionalField::Absent,
1804 fee_proportional_millionths: 1000000,
1805 excess_data: Vec::new()
1807 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
1808 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1809 short_channel_id: 4,
1812 cltv_expiry_delta: (4 << 8) | 2,
1813 htlc_minimum_msat: 0,
1814 htlc_maximum_msat: OptionalField::Absent,
1816 fee_proportional_millionths: 0,
1817 excess_data: Vec::new()
1820 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], &privkeys[2], ChannelFeatures::from_le_bytes(id_to_feature_flags(13)), 13);
1821 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
1822 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1823 short_channel_id: 13,
1826 cltv_expiry_delta: (13 << 8) | 1,
1827 htlc_minimum_msat: 0,
1828 htlc_maximum_msat: OptionalField::Absent,
1830 fee_proportional_millionths: 2000000,
1831 excess_data: Vec::new()
1833 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
1834 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1835 short_channel_id: 13,
1838 cltv_expiry_delta: (13 << 8) | 2,
1839 htlc_minimum_msat: 0,
1840 htlc_maximum_msat: OptionalField::Absent,
1842 fee_proportional_millionths: 0,
1843 excess_data: Vec::new()
1846 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[2], NodeFeatures::from_le_bytes(id_to_feature_flags(3)), 0);
1848 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], &privkeys[4], ChannelFeatures::from_le_bytes(id_to_feature_flags(6)), 6);
1849 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
1850 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1851 short_channel_id: 6,
1854 cltv_expiry_delta: (6 << 8) | 1,
1855 htlc_minimum_msat: 0,
1856 htlc_maximum_msat: OptionalField::Absent,
1858 fee_proportional_millionths: 0,
1859 excess_data: Vec::new()
1861 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
1862 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1863 short_channel_id: 6,
1866 cltv_expiry_delta: (6 << 8) | 2,
1867 htlc_minimum_msat: 0,
1868 htlc_maximum_msat: OptionalField::Absent,
1870 fee_proportional_millionths: 0,
1871 excess_data: Vec::new(),
1874 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(11)), 11);
1875 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
1876 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1877 short_channel_id: 11,
1880 cltv_expiry_delta: (11 << 8) | 1,
1881 htlc_minimum_msat: 0,
1882 htlc_maximum_msat: OptionalField::Absent,
1884 fee_proportional_millionths: 0,
1885 excess_data: Vec::new()
1887 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[3], UnsignedChannelUpdate {
1888 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1889 short_channel_id: 11,
1892 cltv_expiry_delta: (11 << 8) | 2,
1893 htlc_minimum_msat: 0,
1894 htlc_maximum_msat: OptionalField::Absent,
1896 fee_proportional_millionths: 0,
1897 excess_data: Vec::new()
1900 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[4], NodeFeatures::from_le_bytes(id_to_feature_flags(5)), 0);
1902 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[3], NodeFeatures::from_le_bytes(id_to_feature_flags(4)), 0);
1904 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], &privkeys[5], ChannelFeatures::from_le_bytes(id_to_feature_flags(7)), 7);
1905 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
1906 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1907 short_channel_id: 7,
1910 cltv_expiry_delta: (7 << 8) | 1,
1911 htlc_minimum_msat: 0,
1912 htlc_maximum_msat: OptionalField::Absent,
1914 fee_proportional_millionths: 1000000,
1915 excess_data: Vec::new()
1917 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[5], UnsignedChannelUpdate {
1918 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1919 short_channel_id: 7,
1922 cltv_expiry_delta: (7 << 8) | 2,
1923 htlc_minimum_msat: 0,
1924 htlc_maximum_msat: OptionalField::Absent,
1926 fee_proportional_millionths: 0,
1927 excess_data: Vec::new()
1930 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[5], NodeFeatures::from_le_bytes(id_to_feature_flags(6)), 0);
1932 (secp_ctx, net_graph_msg_handler, chain_monitor, logger)
1936 fn simple_route_test() {
1937 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
1938 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
1939 let payee = Payee::new(nodes[2]);
1940 let scorer = Scorer::with_fixed_penalty(0);
1942 // Simple route to 2 via 1
1944 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id, &payee, &net_graph_msg_handler.network_graph, None, 0, 42, Arc::clone(&logger), &scorer) {
1945 assert_eq!(err, "Cannot send a payment of 0 msat");
1946 } else { panic!(); }
1948 let route = get_route(&our_id, &payee, &net_graph_msg_handler.network_graph, None, 100, 42, Arc::clone(&logger), &scorer).unwrap();
1949 assert_eq!(route.paths[0].len(), 2);
1951 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
1952 assert_eq!(route.paths[0][0].short_channel_id, 2);
1953 assert_eq!(route.paths[0][0].fee_msat, 100);
1954 assert_eq!(route.paths[0][0].cltv_expiry_delta, (4 << 8) | 1);
1955 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
1956 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
1958 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
1959 assert_eq!(route.paths[0][1].short_channel_id, 4);
1960 assert_eq!(route.paths[0][1].fee_msat, 100);
1961 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
1962 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
1963 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
1967 fn invalid_first_hop_test() {
1968 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
1969 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
1970 let payee = Payee::new(nodes[2]);
1971 let scorer = Scorer::with_fixed_penalty(0);
1973 // Simple route to 2 via 1
1975 let our_chans = vec![get_channel_details(Some(2), our_id, InitFeatures::from_le_bytes(vec![0b11]), 100000)];
1977 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id, &payee, &net_graph_msg_handler.network_graph, Some(&our_chans.iter().collect::<Vec<_>>()), 100, 42, Arc::clone(&logger), &scorer) {
1978 assert_eq!(err, "First hop cannot have our_node_pubkey as a destination.");
1979 } else { panic!(); }
1981 let route = get_route(&our_id, &payee, &net_graph_msg_handler.network_graph, None, 100, 42, Arc::clone(&logger), &scorer).unwrap();
1982 assert_eq!(route.paths[0].len(), 2);
1986 fn htlc_minimum_test() {
1987 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
1988 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
1989 let payee = Payee::new(nodes[2]);
1990 let scorer = Scorer::with_fixed_penalty(0);
1992 // Simple route to 2 via 1
1994 // Disable other paths
1995 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
1996 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1997 short_channel_id: 12,
1999 flags: 2, // to disable
2000 cltv_expiry_delta: 0,
2001 htlc_minimum_msat: 0,
2002 htlc_maximum_msat: OptionalField::Absent,
2004 fee_proportional_millionths: 0,
2005 excess_data: Vec::new()
2007 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
2008 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2009 short_channel_id: 3,
2011 flags: 2, // to disable
2012 cltv_expiry_delta: 0,
2013 htlc_minimum_msat: 0,
2014 htlc_maximum_msat: OptionalField::Absent,
2016 fee_proportional_millionths: 0,
2017 excess_data: Vec::new()
2019 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
2020 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2021 short_channel_id: 13,
2023 flags: 2, // to disable
2024 cltv_expiry_delta: 0,
2025 htlc_minimum_msat: 0,
2026 htlc_maximum_msat: OptionalField::Absent,
2028 fee_proportional_millionths: 0,
2029 excess_data: Vec::new()
2031 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
2032 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2033 short_channel_id: 6,
2035 flags: 2, // to disable
2036 cltv_expiry_delta: 0,
2037 htlc_minimum_msat: 0,
2038 htlc_maximum_msat: OptionalField::Absent,
2040 fee_proportional_millionths: 0,
2041 excess_data: Vec::new()
2043 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
2044 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2045 short_channel_id: 7,
2047 flags: 2, // to disable
2048 cltv_expiry_delta: 0,
2049 htlc_minimum_msat: 0,
2050 htlc_maximum_msat: OptionalField::Absent,
2052 fee_proportional_millionths: 0,
2053 excess_data: Vec::new()
2056 // Check against amount_to_transfer_over_msat.
2057 // Set minimal HTLC of 200_000_000 msat.
2058 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2059 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2060 short_channel_id: 2,
2063 cltv_expiry_delta: 0,
2064 htlc_minimum_msat: 200_000_000,
2065 htlc_maximum_msat: OptionalField::Absent,
2067 fee_proportional_millionths: 0,
2068 excess_data: Vec::new()
2071 // Second hop only allows to forward 199_999_999 at most, thus not allowing the first hop to
2073 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
2074 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2075 short_channel_id: 4,
2078 cltv_expiry_delta: 0,
2079 htlc_minimum_msat: 0,
2080 htlc_maximum_msat: OptionalField::Present(199_999_999),
2082 fee_proportional_millionths: 0,
2083 excess_data: Vec::new()
2086 // Not possible to send 199_999_999, because the minimum on channel=2 is 200_000_000.
2087 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id, &payee, &net_graph_msg_handler.network_graph, None, 199_999_999, 42, Arc::clone(&logger), &scorer) {
2088 assert_eq!(err, "Failed to find a path to the given destination");
2089 } else { panic!(); }
2091 // Lift the restriction on the first hop.
2092 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2093 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2094 short_channel_id: 2,
2097 cltv_expiry_delta: 0,
2098 htlc_minimum_msat: 0,
2099 htlc_maximum_msat: OptionalField::Absent,
2101 fee_proportional_millionths: 0,
2102 excess_data: Vec::new()
2105 // A payment above the minimum should pass
2106 let route = get_route(&our_id, &payee, &net_graph_msg_handler.network_graph, None, 199_999_999, 42, Arc::clone(&logger), &scorer).unwrap();
2107 assert_eq!(route.paths[0].len(), 2);
2111 fn htlc_minimum_overpay_test() {
2112 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
2113 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
2114 let payee = Payee::new(nodes[2]).with_features(InvoiceFeatures::known());
2115 let scorer = Scorer::with_fixed_penalty(0);
2117 // A route to node#2 via two paths.
2118 // One path allows transferring 35-40 sats, another one also allows 35-40 sats.
2119 // Thus, they can't send 60 without overpaying.
2120 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2121 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2122 short_channel_id: 2,
2125 cltv_expiry_delta: 0,
2126 htlc_minimum_msat: 35_000,
2127 htlc_maximum_msat: OptionalField::Present(40_000),
2129 fee_proportional_millionths: 0,
2130 excess_data: Vec::new()
2132 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2133 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2134 short_channel_id: 12,
2137 cltv_expiry_delta: 0,
2138 htlc_minimum_msat: 35_000,
2139 htlc_maximum_msat: OptionalField::Present(40_000),
2141 fee_proportional_millionths: 0,
2142 excess_data: Vec::new()
2146 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
2147 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2148 short_channel_id: 13,
2151 cltv_expiry_delta: 0,
2152 htlc_minimum_msat: 0,
2153 htlc_maximum_msat: OptionalField::Absent,
2155 fee_proportional_millionths: 0,
2156 excess_data: Vec::new()
2158 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
2159 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2160 short_channel_id: 4,
2163 cltv_expiry_delta: 0,
2164 htlc_minimum_msat: 0,
2165 htlc_maximum_msat: OptionalField::Absent,
2167 fee_proportional_millionths: 0,
2168 excess_data: Vec::new()
2171 // Disable other paths
2172 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2173 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2174 short_channel_id: 1,
2176 flags: 2, // to disable
2177 cltv_expiry_delta: 0,
2178 htlc_minimum_msat: 0,
2179 htlc_maximum_msat: OptionalField::Absent,
2181 fee_proportional_millionths: 0,
2182 excess_data: Vec::new()
2185 let route = get_route(&our_id, &payee, &net_graph_msg_handler.network_graph, None, 60_000, 42, Arc::clone(&logger), &scorer).unwrap();
2186 // Overpay fees to hit htlc_minimum_msat.
2187 let overpaid_fees = route.paths[0][0].fee_msat + route.paths[1][0].fee_msat;
2188 // TODO: this could be better balanced to overpay 10k and not 15k.
2189 assert_eq!(overpaid_fees, 15_000);
2191 // Now, test that if there are 2 paths, a "cheaper" by fee path wouldn't be prioritized
2192 // while taking even more fee to match htlc_minimum_msat.
2193 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2194 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2195 short_channel_id: 12,
2198 cltv_expiry_delta: 0,
2199 htlc_minimum_msat: 65_000,
2200 htlc_maximum_msat: OptionalField::Present(80_000),
2202 fee_proportional_millionths: 0,
2203 excess_data: Vec::new()
2205 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2206 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2207 short_channel_id: 2,
2210 cltv_expiry_delta: 0,
2211 htlc_minimum_msat: 0,
2212 htlc_maximum_msat: OptionalField::Absent,
2214 fee_proportional_millionths: 0,
2215 excess_data: Vec::new()
2217 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
2218 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2219 short_channel_id: 4,
2222 cltv_expiry_delta: 0,
2223 htlc_minimum_msat: 0,
2224 htlc_maximum_msat: OptionalField::Absent,
2226 fee_proportional_millionths: 100_000,
2227 excess_data: Vec::new()
2230 let route = get_route(&our_id, &payee, &net_graph_msg_handler.network_graph, None, 60_000, 42, Arc::clone(&logger), &scorer).unwrap();
2231 // Fine to overpay for htlc_minimum_msat if it allows us to save fee.
2232 assert_eq!(route.paths.len(), 1);
2233 assert_eq!(route.paths[0][0].short_channel_id, 12);
2234 let fees = route.paths[0][0].fee_msat;
2235 assert_eq!(fees, 5_000);
2237 let route = get_route(&our_id, &payee, &net_graph_msg_handler.network_graph, None, 50_000, 42, Arc::clone(&logger), &scorer).unwrap();
2238 // Not fine to overpay for htlc_minimum_msat if it requires paying more than fee on
2239 // the other channel.
2240 assert_eq!(route.paths.len(), 1);
2241 assert_eq!(route.paths[0][0].short_channel_id, 2);
2242 let fees = route.paths[0][0].fee_msat;
2243 assert_eq!(fees, 5_000);
2247 fn disable_channels_test() {
2248 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
2249 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
2250 let payee = Payee::new(nodes[2]);
2251 let scorer = Scorer::with_fixed_penalty(0);
2253 // // Disable channels 4 and 12 by flags=2
2254 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
2255 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2256 short_channel_id: 4,
2258 flags: 2, // to disable
2259 cltv_expiry_delta: 0,
2260 htlc_minimum_msat: 0,
2261 htlc_maximum_msat: OptionalField::Absent,
2263 fee_proportional_millionths: 0,
2264 excess_data: Vec::new()
2266 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2267 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2268 short_channel_id: 12,
2270 flags: 2, // to disable
2271 cltv_expiry_delta: 0,
2272 htlc_minimum_msat: 0,
2273 htlc_maximum_msat: OptionalField::Absent,
2275 fee_proportional_millionths: 0,
2276 excess_data: Vec::new()
2279 // If all the channels require some features we don't understand, route should fail
2280 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id, &payee, &net_graph_msg_handler.network_graph, None, 100, 42, Arc::clone(&logger), &scorer) {
2281 assert_eq!(err, "Failed to find a path to the given destination");
2282 } else { panic!(); }
2284 // If we specify a channel to node7, that overrides our local channel view and that gets used
2285 let our_chans = vec![get_channel_details(Some(42), nodes[7].clone(), InitFeatures::from_le_bytes(vec![0b11]), 250_000_000)];
2286 let route = get_route(&our_id, &payee, &net_graph_msg_handler.network_graph, Some(&our_chans.iter().collect::<Vec<_>>()), 100, 42, Arc::clone(&logger), &scorer).unwrap();
2287 assert_eq!(route.paths[0].len(), 2);
2289 assert_eq!(route.paths[0][0].pubkey, nodes[7]);
2290 assert_eq!(route.paths[0][0].short_channel_id, 42);
2291 assert_eq!(route.paths[0][0].fee_msat, 200);
2292 assert_eq!(route.paths[0][0].cltv_expiry_delta, (13 << 8) | 1);
2293 assert_eq!(route.paths[0][0].node_features.le_flags(), &vec![0b11]); // it should also override our view of their features
2294 assert_eq!(route.paths[0][0].channel_features.le_flags(), &Vec::<u8>::new()); // No feature flags will meet the relevant-to-channel conversion
2296 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2297 assert_eq!(route.paths[0][1].short_channel_id, 13);
2298 assert_eq!(route.paths[0][1].fee_msat, 100);
2299 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
2300 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2301 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(13));
2305 fn disable_node_test() {
2306 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
2307 let (_, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
2308 let payee = Payee::new(nodes[2]);
2309 let scorer = Scorer::with_fixed_penalty(0);
2311 // Disable nodes 1, 2, and 8 by requiring unknown feature bits
2312 let unknown_features = NodeFeatures::known().set_unknown_feature_required();
2313 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[0], unknown_features.clone(), 1);
2314 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[1], unknown_features.clone(), 1);
2315 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[7], unknown_features.clone(), 1);
2317 // If all nodes require some features we don't understand, route should fail
2318 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id, &payee, &net_graph_msg_handler.network_graph, None, 100, 42, Arc::clone(&logger), &scorer) {
2319 assert_eq!(err, "Failed to find a path to the given destination");
2320 } else { panic!(); }
2322 // If we specify a channel to node7, that overrides our local channel view and that gets used
2323 let our_chans = vec![get_channel_details(Some(42), nodes[7].clone(), InitFeatures::from_le_bytes(vec![0b11]), 250_000_000)];
2324 let route = get_route(&our_id, &payee, &net_graph_msg_handler.network_graph, Some(&our_chans.iter().collect::<Vec<_>>()), 100, 42, Arc::clone(&logger), &scorer).unwrap();
2325 assert_eq!(route.paths[0].len(), 2);
2327 assert_eq!(route.paths[0][0].pubkey, nodes[7]);
2328 assert_eq!(route.paths[0][0].short_channel_id, 42);
2329 assert_eq!(route.paths[0][0].fee_msat, 200);
2330 assert_eq!(route.paths[0][0].cltv_expiry_delta, (13 << 8) | 1);
2331 assert_eq!(route.paths[0][0].node_features.le_flags(), &vec![0b11]); // it should also override our view of their features
2332 assert_eq!(route.paths[0][0].channel_features.le_flags(), &Vec::<u8>::new()); // No feature flags will meet the relevant-to-channel conversion
2334 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2335 assert_eq!(route.paths[0][1].short_channel_id, 13);
2336 assert_eq!(route.paths[0][1].fee_msat, 100);
2337 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
2338 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2339 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(13));
2341 // Note that we don't test disabling node 3 and failing to route to it, as we (somewhat
2342 // naively) assume that the user checked the feature bits on the invoice, which override
2343 // the node_announcement.
2347 fn our_chans_test() {
2348 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
2349 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
2350 let scorer = Scorer::with_fixed_penalty(0);
2352 // Route to 1 via 2 and 3 because our channel to 1 is disabled
2353 let payee = Payee::new(nodes[0]);
2354 let route = get_route(&our_id, &payee, &net_graph_msg_handler.network_graph, None, 100, 42, Arc::clone(&logger), &scorer).unwrap();
2355 assert_eq!(route.paths[0].len(), 3);
2357 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
2358 assert_eq!(route.paths[0][0].short_channel_id, 2);
2359 assert_eq!(route.paths[0][0].fee_msat, 200);
2360 assert_eq!(route.paths[0][0].cltv_expiry_delta, (4 << 8) | 1);
2361 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
2362 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
2364 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2365 assert_eq!(route.paths[0][1].short_channel_id, 4);
2366 assert_eq!(route.paths[0][1].fee_msat, 100);
2367 assert_eq!(route.paths[0][1].cltv_expiry_delta, (3 << 8) | 2);
2368 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2369 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
2371 assert_eq!(route.paths[0][2].pubkey, nodes[0]);
2372 assert_eq!(route.paths[0][2].short_channel_id, 3);
2373 assert_eq!(route.paths[0][2].fee_msat, 100);
2374 assert_eq!(route.paths[0][2].cltv_expiry_delta, 42);
2375 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(1));
2376 assert_eq!(route.paths[0][2].channel_features.le_flags(), &id_to_feature_flags(3));
2378 // If we specify a channel to node7, that overrides our local channel view and that gets used
2379 let payee = Payee::new(nodes[2]);
2380 let our_chans = vec![get_channel_details(Some(42), nodes[7].clone(), InitFeatures::from_le_bytes(vec![0b11]), 250_000_000)];
2381 let route = get_route(&our_id, &payee, &net_graph_msg_handler.network_graph, Some(&our_chans.iter().collect::<Vec<_>>()), 100, 42, Arc::clone(&logger), &scorer).unwrap();
2382 assert_eq!(route.paths[0].len(), 2);
2384 assert_eq!(route.paths[0][0].pubkey, nodes[7]);
2385 assert_eq!(route.paths[0][0].short_channel_id, 42);
2386 assert_eq!(route.paths[0][0].fee_msat, 200);
2387 assert_eq!(route.paths[0][0].cltv_expiry_delta, (13 << 8) | 1);
2388 assert_eq!(route.paths[0][0].node_features.le_flags(), &vec![0b11]);
2389 assert_eq!(route.paths[0][0].channel_features.le_flags(), &Vec::<u8>::new()); // No feature flags will meet the relevant-to-channel conversion
2391 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2392 assert_eq!(route.paths[0][1].short_channel_id, 13);
2393 assert_eq!(route.paths[0][1].fee_msat, 100);
2394 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
2395 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2396 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(13));
2399 fn last_hops(nodes: &Vec<PublicKey>) -> Vec<RouteHint> {
2400 let zero_fees = RoutingFees {
2402 proportional_millionths: 0,
2404 vec![RouteHint(vec![RouteHintHop {
2405 src_node_id: nodes[3],
2406 short_channel_id: 8,
2408 cltv_expiry_delta: (8 << 8) | 1,
2409 htlc_minimum_msat: None,
2410 htlc_maximum_msat: None,
2412 ]), RouteHint(vec![RouteHintHop {
2413 src_node_id: nodes[4],
2414 short_channel_id: 9,
2417 proportional_millionths: 0,
2419 cltv_expiry_delta: (9 << 8) | 1,
2420 htlc_minimum_msat: None,
2421 htlc_maximum_msat: None,
2422 }]), RouteHint(vec![RouteHintHop {
2423 src_node_id: nodes[5],
2424 short_channel_id: 10,
2426 cltv_expiry_delta: (10 << 8) | 1,
2427 htlc_minimum_msat: None,
2428 htlc_maximum_msat: None,
2432 fn last_hops_multi_private_channels(nodes: &Vec<PublicKey>) -> Vec<RouteHint> {
2433 let zero_fees = RoutingFees {
2435 proportional_millionths: 0,
2437 vec![RouteHint(vec![RouteHintHop {
2438 src_node_id: nodes[2],
2439 short_channel_id: 5,
2442 proportional_millionths: 0,
2444 cltv_expiry_delta: (5 << 8) | 1,
2445 htlc_minimum_msat: None,
2446 htlc_maximum_msat: None,
2448 src_node_id: nodes[3],
2449 short_channel_id: 8,
2451 cltv_expiry_delta: (8 << 8) | 1,
2452 htlc_minimum_msat: None,
2453 htlc_maximum_msat: None,
2455 ]), RouteHint(vec![RouteHintHop {
2456 src_node_id: nodes[4],
2457 short_channel_id: 9,
2460 proportional_millionths: 0,
2462 cltv_expiry_delta: (9 << 8) | 1,
2463 htlc_minimum_msat: None,
2464 htlc_maximum_msat: None,
2465 }]), RouteHint(vec![RouteHintHop {
2466 src_node_id: nodes[5],
2467 short_channel_id: 10,
2469 cltv_expiry_delta: (10 << 8) | 1,
2470 htlc_minimum_msat: None,
2471 htlc_maximum_msat: None,
2476 fn partial_route_hint_test() {
2477 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
2478 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
2479 let scorer = Scorer::with_fixed_penalty(0);
2481 // Simple test across 2, 3, 5, and 4 via a last_hop channel
2482 // Tests the behaviour when the RouteHint contains a suboptimal hop.
2483 // RouteHint may be partially used by the algo to build the best path.
2485 // First check that last hop can't have its source as the payee.
2486 let invalid_last_hop = RouteHint(vec![RouteHintHop {
2487 src_node_id: nodes[6],
2488 short_channel_id: 8,
2491 proportional_millionths: 0,
2493 cltv_expiry_delta: (8 << 8) | 1,
2494 htlc_minimum_msat: None,
2495 htlc_maximum_msat: None,
2498 let mut invalid_last_hops = last_hops_multi_private_channels(&nodes);
2499 invalid_last_hops.push(invalid_last_hop);
2501 let payee = Payee::new(nodes[6]).with_route_hints(invalid_last_hops);
2502 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id, &payee, &net_graph_msg_handler.network_graph, None, 100, 42, Arc::clone(&logger), &scorer) {
2503 assert_eq!(err, "Route hint cannot have the payee as the source.");
2504 } else { panic!(); }
2507 let payee = Payee::new(nodes[6]).with_route_hints(last_hops_multi_private_channels(&nodes));
2508 let route = get_route(&our_id, &payee, &net_graph_msg_handler.network_graph, None, 100, 42, Arc::clone(&logger), &scorer).unwrap();
2509 assert_eq!(route.paths[0].len(), 5);
2511 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
2512 assert_eq!(route.paths[0][0].short_channel_id, 2);
2513 assert_eq!(route.paths[0][0].fee_msat, 100);
2514 assert_eq!(route.paths[0][0].cltv_expiry_delta, (4 << 8) | 1);
2515 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
2516 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
2518 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2519 assert_eq!(route.paths[0][1].short_channel_id, 4);
2520 assert_eq!(route.paths[0][1].fee_msat, 0);
2521 assert_eq!(route.paths[0][1].cltv_expiry_delta, (6 << 8) | 1);
2522 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2523 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
2525 assert_eq!(route.paths[0][2].pubkey, nodes[4]);
2526 assert_eq!(route.paths[0][2].short_channel_id, 6);
2527 assert_eq!(route.paths[0][2].fee_msat, 0);
2528 assert_eq!(route.paths[0][2].cltv_expiry_delta, (11 << 8) | 1);
2529 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(5));
2530 assert_eq!(route.paths[0][2].channel_features.le_flags(), &id_to_feature_flags(6));
2532 assert_eq!(route.paths[0][3].pubkey, nodes[3]);
2533 assert_eq!(route.paths[0][3].short_channel_id, 11);
2534 assert_eq!(route.paths[0][3].fee_msat, 0);
2535 assert_eq!(route.paths[0][3].cltv_expiry_delta, (8 << 8) | 1);
2536 // If we have a peer in the node map, we'll use their features here since we don't have
2537 // a way of figuring out their features from the invoice:
2538 assert_eq!(route.paths[0][3].node_features.le_flags(), &id_to_feature_flags(4));
2539 assert_eq!(route.paths[0][3].channel_features.le_flags(), &id_to_feature_flags(11));
2541 assert_eq!(route.paths[0][4].pubkey, nodes[6]);
2542 assert_eq!(route.paths[0][4].short_channel_id, 8);
2543 assert_eq!(route.paths[0][4].fee_msat, 100);
2544 assert_eq!(route.paths[0][4].cltv_expiry_delta, 42);
2545 assert_eq!(route.paths[0][4].node_features.le_flags(), &Vec::<u8>::new()); // We dont pass flags in from invoices yet
2546 assert_eq!(route.paths[0][4].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
2549 fn empty_last_hop(nodes: &Vec<PublicKey>) -> Vec<RouteHint> {
2550 let zero_fees = RoutingFees {
2552 proportional_millionths: 0,
2554 vec![RouteHint(vec![RouteHintHop {
2555 src_node_id: nodes[3],
2556 short_channel_id: 8,
2558 cltv_expiry_delta: (8 << 8) | 1,
2559 htlc_minimum_msat: None,
2560 htlc_maximum_msat: None,
2561 }]), RouteHint(vec![
2563 ]), RouteHint(vec![RouteHintHop {
2564 src_node_id: nodes[5],
2565 short_channel_id: 10,
2567 cltv_expiry_delta: (10 << 8) | 1,
2568 htlc_minimum_msat: None,
2569 htlc_maximum_msat: None,
2574 fn ignores_empty_last_hops_test() {
2575 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
2576 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
2577 let payee = Payee::new(nodes[6]).with_route_hints(empty_last_hop(&nodes));
2578 let scorer = Scorer::with_fixed_penalty(0);
2580 // Test handling of an empty RouteHint passed in Invoice.
2582 let route = get_route(&our_id, &payee, &net_graph_msg_handler.network_graph, None, 100, 42, Arc::clone(&logger), &scorer).unwrap();
2583 assert_eq!(route.paths[0].len(), 5);
2585 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
2586 assert_eq!(route.paths[0][0].short_channel_id, 2);
2587 assert_eq!(route.paths[0][0].fee_msat, 100);
2588 assert_eq!(route.paths[0][0].cltv_expiry_delta, (4 << 8) | 1);
2589 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
2590 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
2592 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2593 assert_eq!(route.paths[0][1].short_channel_id, 4);
2594 assert_eq!(route.paths[0][1].fee_msat, 0);
2595 assert_eq!(route.paths[0][1].cltv_expiry_delta, (6 << 8) | 1);
2596 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2597 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
2599 assert_eq!(route.paths[0][2].pubkey, nodes[4]);
2600 assert_eq!(route.paths[0][2].short_channel_id, 6);
2601 assert_eq!(route.paths[0][2].fee_msat, 0);
2602 assert_eq!(route.paths[0][2].cltv_expiry_delta, (11 << 8) | 1);
2603 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(5));
2604 assert_eq!(route.paths[0][2].channel_features.le_flags(), &id_to_feature_flags(6));
2606 assert_eq!(route.paths[0][3].pubkey, nodes[3]);
2607 assert_eq!(route.paths[0][3].short_channel_id, 11);
2608 assert_eq!(route.paths[0][3].fee_msat, 0);
2609 assert_eq!(route.paths[0][3].cltv_expiry_delta, (8 << 8) | 1);
2610 // If we have a peer in the node map, we'll use their features here since we don't have
2611 // a way of figuring out their features from the invoice:
2612 assert_eq!(route.paths[0][3].node_features.le_flags(), &id_to_feature_flags(4));
2613 assert_eq!(route.paths[0][3].channel_features.le_flags(), &id_to_feature_flags(11));
2615 assert_eq!(route.paths[0][4].pubkey, nodes[6]);
2616 assert_eq!(route.paths[0][4].short_channel_id, 8);
2617 assert_eq!(route.paths[0][4].fee_msat, 100);
2618 assert_eq!(route.paths[0][4].cltv_expiry_delta, 42);
2619 assert_eq!(route.paths[0][4].node_features.le_flags(), &Vec::<u8>::new()); // We dont pass flags in from invoices yet
2620 assert_eq!(route.paths[0][4].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
2623 fn multi_hint_last_hops(nodes: &Vec<PublicKey>) -> Vec<RouteHint> {
2624 let zero_fees = RoutingFees {
2626 proportional_millionths: 0,
2628 vec![RouteHint(vec![RouteHintHop {
2629 src_node_id: nodes[2],
2630 short_channel_id: 5,
2633 proportional_millionths: 0,
2635 cltv_expiry_delta: (5 << 8) | 1,
2636 htlc_minimum_msat: None,
2637 htlc_maximum_msat: None,
2639 src_node_id: nodes[3],
2640 short_channel_id: 8,
2642 cltv_expiry_delta: (8 << 8) | 1,
2643 htlc_minimum_msat: None,
2644 htlc_maximum_msat: None,
2645 }]), RouteHint(vec![RouteHintHop {
2646 src_node_id: nodes[5],
2647 short_channel_id: 10,
2649 cltv_expiry_delta: (10 << 8) | 1,
2650 htlc_minimum_msat: None,
2651 htlc_maximum_msat: None,
2656 fn multi_hint_last_hops_test() {
2657 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
2658 let (_, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
2659 let payee = Payee::new(nodes[6]).with_route_hints(multi_hint_last_hops(&nodes));
2660 let scorer = Scorer::with_fixed_penalty(0);
2661 // Test through channels 2, 3, 5, 8.
2662 // Test shows that multiple hop hints are considered.
2664 // Disabling channels 6 & 7 by flags=2
2665 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
2666 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2667 short_channel_id: 6,
2669 flags: 2, // to disable
2670 cltv_expiry_delta: 0,
2671 htlc_minimum_msat: 0,
2672 htlc_maximum_msat: OptionalField::Absent,
2674 fee_proportional_millionths: 0,
2675 excess_data: Vec::new()
2677 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
2678 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2679 short_channel_id: 7,
2681 flags: 2, // to disable
2682 cltv_expiry_delta: 0,
2683 htlc_minimum_msat: 0,
2684 htlc_maximum_msat: OptionalField::Absent,
2686 fee_proportional_millionths: 0,
2687 excess_data: Vec::new()
2690 let route = get_route(&our_id, &payee, &net_graph_msg_handler.network_graph, None, 100, 42, Arc::clone(&logger), &scorer).unwrap();
2691 assert_eq!(route.paths[0].len(), 4);
2693 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
2694 assert_eq!(route.paths[0][0].short_channel_id, 2);
2695 assert_eq!(route.paths[0][0].fee_msat, 200);
2696 assert_eq!(route.paths[0][0].cltv_expiry_delta, 1025);
2697 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
2698 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
2700 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2701 assert_eq!(route.paths[0][1].short_channel_id, 4);
2702 assert_eq!(route.paths[0][1].fee_msat, 100);
2703 assert_eq!(route.paths[0][1].cltv_expiry_delta, 1281);
2704 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2705 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
2707 assert_eq!(route.paths[0][2].pubkey, nodes[3]);
2708 assert_eq!(route.paths[0][2].short_channel_id, 5);
2709 assert_eq!(route.paths[0][2].fee_msat, 0);
2710 assert_eq!(route.paths[0][2].cltv_expiry_delta, 2049);
2711 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(4));
2712 assert_eq!(route.paths[0][2].channel_features.le_flags(), &Vec::<u8>::new());
2714 assert_eq!(route.paths[0][3].pubkey, nodes[6]);
2715 assert_eq!(route.paths[0][3].short_channel_id, 8);
2716 assert_eq!(route.paths[0][3].fee_msat, 100);
2717 assert_eq!(route.paths[0][3].cltv_expiry_delta, 42);
2718 assert_eq!(route.paths[0][3].node_features.le_flags(), &Vec::<u8>::new()); // We dont pass flags in from invoices yet
2719 assert_eq!(route.paths[0][3].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
2722 fn last_hops_with_public_channel(nodes: &Vec<PublicKey>) -> Vec<RouteHint> {
2723 let zero_fees = RoutingFees {
2725 proportional_millionths: 0,
2727 vec![RouteHint(vec![RouteHintHop {
2728 src_node_id: nodes[4],
2729 short_channel_id: 11,
2731 cltv_expiry_delta: (11 << 8) | 1,
2732 htlc_minimum_msat: None,
2733 htlc_maximum_msat: None,
2735 src_node_id: nodes[3],
2736 short_channel_id: 8,
2738 cltv_expiry_delta: (8 << 8) | 1,
2739 htlc_minimum_msat: None,
2740 htlc_maximum_msat: None,
2741 }]), RouteHint(vec![RouteHintHop {
2742 src_node_id: nodes[4],
2743 short_channel_id: 9,
2746 proportional_millionths: 0,
2748 cltv_expiry_delta: (9 << 8) | 1,
2749 htlc_minimum_msat: None,
2750 htlc_maximum_msat: None,
2751 }]), RouteHint(vec![RouteHintHop {
2752 src_node_id: nodes[5],
2753 short_channel_id: 10,
2755 cltv_expiry_delta: (10 << 8) | 1,
2756 htlc_minimum_msat: None,
2757 htlc_maximum_msat: None,
2762 fn last_hops_with_public_channel_test() {
2763 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
2764 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
2765 let payee = Payee::new(nodes[6]).with_route_hints(last_hops_with_public_channel(&nodes));
2766 let scorer = Scorer::with_fixed_penalty(0);
2767 // This test shows that public routes can be present in the invoice
2768 // which would be handled in the same manner.
2770 let route = get_route(&our_id, &payee, &net_graph_msg_handler.network_graph, None, 100, 42, Arc::clone(&logger), &scorer).unwrap();
2771 assert_eq!(route.paths[0].len(), 5);
2773 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
2774 assert_eq!(route.paths[0][0].short_channel_id, 2);
2775 assert_eq!(route.paths[0][0].fee_msat, 100);
2776 assert_eq!(route.paths[0][0].cltv_expiry_delta, (4 << 8) | 1);
2777 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
2778 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
2780 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2781 assert_eq!(route.paths[0][1].short_channel_id, 4);
2782 assert_eq!(route.paths[0][1].fee_msat, 0);
2783 assert_eq!(route.paths[0][1].cltv_expiry_delta, (6 << 8) | 1);
2784 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2785 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
2787 assert_eq!(route.paths[0][2].pubkey, nodes[4]);
2788 assert_eq!(route.paths[0][2].short_channel_id, 6);
2789 assert_eq!(route.paths[0][2].fee_msat, 0);
2790 assert_eq!(route.paths[0][2].cltv_expiry_delta, (11 << 8) | 1);
2791 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(5));
2792 assert_eq!(route.paths[0][2].channel_features.le_flags(), &id_to_feature_flags(6));
2794 assert_eq!(route.paths[0][3].pubkey, nodes[3]);
2795 assert_eq!(route.paths[0][3].short_channel_id, 11);
2796 assert_eq!(route.paths[0][3].fee_msat, 0);
2797 assert_eq!(route.paths[0][3].cltv_expiry_delta, (8 << 8) | 1);
2798 // If we have a peer in the node map, we'll use their features here since we don't have
2799 // a way of figuring out their features from the invoice:
2800 assert_eq!(route.paths[0][3].node_features.le_flags(), &id_to_feature_flags(4));
2801 assert_eq!(route.paths[0][3].channel_features.le_flags(), &Vec::<u8>::new());
2803 assert_eq!(route.paths[0][4].pubkey, nodes[6]);
2804 assert_eq!(route.paths[0][4].short_channel_id, 8);
2805 assert_eq!(route.paths[0][4].fee_msat, 100);
2806 assert_eq!(route.paths[0][4].cltv_expiry_delta, 42);
2807 assert_eq!(route.paths[0][4].node_features.le_flags(), &Vec::<u8>::new()); // We dont pass flags in from invoices yet
2808 assert_eq!(route.paths[0][4].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
2812 fn our_chans_last_hop_connect_test() {
2813 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
2814 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
2815 let scorer = Scorer::with_fixed_penalty(0);
2817 // Simple test with outbound channel to 4 to test that last_hops and first_hops connect
2818 let our_chans = vec![get_channel_details(Some(42), nodes[3].clone(), InitFeatures::from_le_bytes(vec![0b11]), 250_000_000)];
2819 let mut last_hops = last_hops(&nodes);
2820 let payee = Payee::new(nodes[6]).with_route_hints(last_hops.clone());
2821 let route = get_route(&our_id, &payee, &net_graph_msg_handler.network_graph, Some(&our_chans.iter().collect::<Vec<_>>()), 100, 42, Arc::clone(&logger), &scorer).unwrap();
2822 assert_eq!(route.paths[0].len(), 2);
2824 assert_eq!(route.paths[0][0].pubkey, nodes[3]);
2825 assert_eq!(route.paths[0][0].short_channel_id, 42);
2826 assert_eq!(route.paths[0][0].fee_msat, 0);
2827 assert_eq!(route.paths[0][0].cltv_expiry_delta, (8 << 8) | 1);
2828 assert_eq!(route.paths[0][0].node_features.le_flags(), &vec![0b11]);
2829 assert_eq!(route.paths[0][0].channel_features.le_flags(), &Vec::<u8>::new()); // No feature flags will meet the relevant-to-channel conversion
2831 assert_eq!(route.paths[0][1].pubkey, nodes[6]);
2832 assert_eq!(route.paths[0][1].short_channel_id, 8);
2833 assert_eq!(route.paths[0][1].fee_msat, 100);
2834 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
2835 assert_eq!(route.paths[0][1].node_features.le_flags(), &Vec::<u8>::new()); // We dont pass flags in from invoices yet
2836 assert_eq!(route.paths[0][1].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
2838 last_hops[0].0[0].fees.base_msat = 1000;
2840 // Revert to via 6 as the fee on 8 goes up
2841 let payee = Payee::new(nodes[6]).with_route_hints(last_hops);
2842 let route = get_route(&our_id, &payee, &net_graph_msg_handler.network_graph, None, 100, 42, Arc::clone(&logger), &scorer).unwrap();
2843 assert_eq!(route.paths[0].len(), 4);
2845 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
2846 assert_eq!(route.paths[0][0].short_channel_id, 2);
2847 assert_eq!(route.paths[0][0].fee_msat, 200); // fee increased as its % of value transferred across node
2848 assert_eq!(route.paths[0][0].cltv_expiry_delta, (4 << 8) | 1);
2849 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
2850 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
2852 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2853 assert_eq!(route.paths[0][1].short_channel_id, 4);
2854 assert_eq!(route.paths[0][1].fee_msat, 100);
2855 assert_eq!(route.paths[0][1].cltv_expiry_delta, (7 << 8) | 1);
2856 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2857 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
2859 assert_eq!(route.paths[0][2].pubkey, nodes[5]);
2860 assert_eq!(route.paths[0][2].short_channel_id, 7);
2861 assert_eq!(route.paths[0][2].fee_msat, 0);
2862 assert_eq!(route.paths[0][2].cltv_expiry_delta, (10 << 8) | 1);
2863 // If we have a peer in the node map, we'll use their features here since we don't have
2864 // a way of figuring out their features from the invoice:
2865 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(6));
2866 assert_eq!(route.paths[0][2].channel_features.le_flags(), &id_to_feature_flags(7));
2868 assert_eq!(route.paths[0][3].pubkey, nodes[6]);
2869 assert_eq!(route.paths[0][3].short_channel_id, 10);
2870 assert_eq!(route.paths[0][3].fee_msat, 100);
2871 assert_eq!(route.paths[0][3].cltv_expiry_delta, 42);
2872 assert_eq!(route.paths[0][3].node_features.le_flags(), &Vec::<u8>::new()); // We dont pass flags in from invoices yet
2873 assert_eq!(route.paths[0][3].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
2875 // ...but still use 8 for larger payments as 6 has a variable feerate
2876 let route = get_route(&our_id, &payee, &net_graph_msg_handler.network_graph, None, 2000, 42, Arc::clone(&logger), &scorer).unwrap();
2877 assert_eq!(route.paths[0].len(), 5);
2879 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
2880 assert_eq!(route.paths[0][0].short_channel_id, 2);
2881 assert_eq!(route.paths[0][0].fee_msat, 3000);
2882 assert_eq!(route.paths[0][0].cltv_expiry_delta, (4 << 8) | 1);
2883 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
2884 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
2886 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2887 assert_eq!(route.paths[0][1].short_channel_id, 4);
2888 assert_eq!(route.paths[0][1].fee_msat, 0);
2889 assert_eq!(route.paths[0][1].cltv_expiry_delta, (6 << 8) | 1);
2890 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2891 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
2893 assert_eq!(route.paths[0][2].pubkey, nodes[4]);
2894 assert_eq!(route.paths[0][2].short_channel_id, 6);
2895 assert_eq!(route.paths[0][2].fee_msat, 0);
2896 assert_eq!(route.paths[0][2].cltv_expiry_delta, (11 << 8) | 1);
2897 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(5));
2898 assert_eq!(route.paths[0][2].channel_features.le_flags(), &id_to_feature_flags(6));
2900 assert_eq!(route.paths[0][3].pubkey, nodes[3]);
2901 assert_eq!(route.paths[0][3].short_channel_id, 11);
2902 assert_eq!(route.paths[0][3].fee_msat, 1000);
2903 assert_eq!(route.paths[0][3].cltv_expiry_delta, (8 << 8) | 1);
2904 // If we have a peer in the node map, we'll use their features here since we don't have
2905 // a way of figuring out their features from the invoice:
2906 assert_eq!(route.paths[0][3].node_features.le_flags(), &id_to_feature_flags(4));
2907 assert_eq!(route.paths[0][3].channel_features.le_flags(), &id_to_feature_flags(11));
2909 assert_eq!(route.paths[0][4].pubkey, nodes[6]);
2910 assert_eq!(route.paths[0][4].short_channel_id, 8);
2911 assert_eq!(route.paths[0][4].fee_msat, 2000);
2912 assert_eq!(route.paths[0][4].cltv_expiry_delta, 42);
2913 assert_eq!(route.paths[0][4].node_features.le_flags(), &Vec::<u8>::new()); // We dont pass flags in from invoices yet
2914 assert_eq!(route.paths[0][4].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
2917 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> {
2918 let source_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&hex::decode(format!("{:02}", 41).repeat(32)).unwrap()[..]).unwrap());
2919 let middle_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&hex::decode(format!("{:02}", 42).repeat(32)).unwrap()[..]).unwrap());
2920 let target_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&hex::decode(format!("{:02}", 43).repeat(32)).unwrap()[..]).unwrap());
2922 // If we specify a channel to a middle hop, that overrides our local channel view and that gets used
2923 let last_hops = RouteHint(vec![RouteHintHop {
2924 src_node_id: middle_node_id,
2925 short_channel_id: 8,
2928 proportional_millionths: last_hop_fee_prop,
2930 cltv_expiry_delta: (8 << 8) | 1,
2931 htlc_minimum_msat: None,
2932 htlc_maximum_msat: last_hop_htlc_max,
2934 let payee = Payee::new(target_node_id).with_route_hints(vec![last_hops]);
2935 let our_chans = vec![get_channel_details(Some(42), middle_node_id, InitFeatures::from_le_bytes(vec![0b11]), outbound_capacity_msat)];
2936 let scorer = Scorer::with_fixed_penalty(0);
2937 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)
2941 fn unannounced_path_test() {
2942 // We should be able to send a payment to a destination without any help of a routing graph
2943 // if we have a channel with a common counterparty that appears in the first and last hop
2945 let route = do_unannounced_path_test(None, 1, 2000000, 1000000).unwrap();
2947 let middle_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&hex::decode(format!("{:02}", 42).repeat(32)).unwrap()[..]).unwrap());
2948 let target_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&hex::decode(format!("{:02}", 43).repeat(32)).unwrap()[..]).unwrap());
2949 assert_eq!(route.paths[0].len(), 2);
2951 assert_eq!(route.paths[0][0].pubkey, middle_node_id);
2952 assert_eq!(route.paths[0][0].short_channel_id, 42);
2953 assert_eq!(route.paths[0][0].fee_msat, 1001);
2954 assert_eq!(route.paths[0][0].cltv_expiry_delta, (8 << 8) | 1);
2955 assert_eq!(route.paths[0][0].node_features.le_flags(), &[0b11]);
2956 assert_eq!(route.paths[0][0].channel_features.le_flags(), &[0; 0]); // We can't learn any flags from invoices, sadly
2958 assert_eq!(route.paths[0][1].pubkey, target_node_id);
2959 assert_eq!(route.paths[0][1].short_channel_id, 8);
2960 assert_eq!(route.paths[0][1].fee_msat, 1000000);
2961 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
2962 assert_eq!(route.paths[0][1].node_features.le_flags(), &[0; 0]); // We dont pass flags in from invoices yet
2963 assert_eq!(route.paths[0][1].channel_features.le_flags(), &[0; 0]); // We can't learn any flags from invoices, sadly
2967 fn overflow_unannounced_path_test_liquidity_underflow() {
2968 // Previously, when we had a last-hop hint connected directly to a first-hop channel, where
2969 // the last-hop had a fee which overflowed a u64, we'd panic.
2970 // This was due to us adding the first-hop from us unconditionally, causing us to think
2971 // we'd built a path (as our node is in the "best candidate" set), when we had not.
2972 // In this test, we previously hit a subtraction underflow due to having less available
2973 // liquidity at the last hop than 0.
2974 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());
2978 fn overflow_unannounced_path_test_feerate_overflow() {
2979 // This tests for the same case as above, except instead of hitting a subtraction
2980 // underflow, we hit a case where the fee charged at a hop overflowed.
2981 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());
2985 fn available_amount_while_routing_test() {
2986 // Tests whether we choose the correct available channel amount while routing.
2988 let (secp_ctx, mut net_graph_msg_handler, chain_monitor, logger) = build_graph();
2989 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
2990 let scorer = Scorer::with_fixed_penalty(0);
2991 let payee = Payee::new(nodes[2]).with_features(InvoiceFeatures::known());
2993 // We will use a simple single-path route from
2994 // our node to node2 via node0: channels {1, 3}.
2996 // First disable all other paths.
2997 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2998 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2999 short_channel_id: 2,
3002 cltv_expiry_delta: 0,
3003 htlc_minimum_msat: 0,
3004 htlc_maximum_msat: OptionalField::Present(100_000),
3006 fee_proportional_millionths: 0,
3007 excess_data: Vec::new()
3009 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3010 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3011 short_channel_id: 12,
3014 cltv_expiry_delta: 0,
3015 htlc_minimum_msat: 0,
3016 htlc_maximum_msat: OptionalField::Present(100_000),
3018 fee_proportional_millionths: 0,
3019 excess_data: Vec::new()
3022 // Make the first channel (#1) very permissive,
3023 // and we will be testing all limits on the second channel.
3024 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3025 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3026 short_channel_id: 1,
3029 cltv_expiry_delta: 0,
3030 htlc_minimum_msat: 0,
3031 htlc_maximum_msat: OptionalField::Present(1_000_000_000),
3033 fee_proportional_millionths: 0,
3034 excess_data: Vec::new()
3037 // First, let's see if routing works if we have absolutely no idea about the available amount.
3038 // In this case, it should be set to 250_000 sats.
3039 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3040 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3041 short_channel_id: 3,
3044 cltv_expiry_delta: 0,
3045 htlc_minimum_msat: 0,
3046 htlc_maximum_msat: OptionalField::Absent,
3048 fee_proportional_millionths: 0,
3049 excess_data: Vec::new()
3053 // Attempt to route more than available results in a failure.
3054 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
3055 &our_id, &payee, &net_graph_msg_handler.network_graph, None, 250_000_001, 42, Arc::clone(&logger), &scorer) {
3056 assert_eq!(err, "Failed to find a sufficient route to the given destination");
3057 } else { panic!(); }
3061 // Now, attempt to route an exact amount we have should be fine.
3062 let route = get_route(&our_id, &payee, &net_graph_msg_handler.network_graph, None, 250_000_000, 42, Arc::clone(&logger), &scorer).unwrap();
3063 assert_eq!(route.paths.len(), 1);
3064 let path = route.paths.last().unwrap();
3065 assert_eq!(path.len(), 2);
3066 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
3067 assert_eq!(path.last().unwrap().fee_msat, 250_000_000);
3070 // Check that setting outbound_capacity_msat in first_hops limits the channels.
3071 // Disable channel #1 and use another first hop.
3072 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3073 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3074 short_channel_id: 1,
3077 cltv_expiry_delta: 0,
3078 htlc_minimum_msat: 0,
3079 htlc_maximum_msat: OptionalField::Present(1_000_000_000),
3081 fee_proportional_millionths: 0,
3082 excess_data: Vec::new()
3085 // Now, limit the first_hop by the outbound_capacity_msat of 200_000 sats.
3086 let our_chans = vec![get_channel_details(Some(42), nodes[0].clone(), InitFeatures::from_le_bytes(vec![0b11]), 200_000_000)];
3089 // Attempt to route more than available results in a failure.
3090 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
3091 &our_id, &payee, &net_graph_msg_handler.network_graph, Some(&our_chans.iter().collect::<Vec<_>>()), 200_000_001, 42, Arc::clone(&logger), &scorer) {
3092 assert_eq!(err, "Failed to find a sufficient route to the given destination");
3093 } else { panic!(); }
3097 // Now, attempt to route an exact amount we have should be fine.
3098 let route = get_route(&our_id, &payee, &net_graph_msg_handler.network_graph, Some(&our_chans.iter().collect::<Vec<_>>()), 200_000_000, 42, Arc::clone(&logger), &scorer).unwrap();
3099 assert_eq!(route.paths.len(), 1);
3100 let path = route.paths.last().unwrap();
3101 assert_eq!(path.len(), 2);
3102 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
3103 assert_eq!(path.last().unwrap().fee_msat, 200_000_000);
3106 // Enable channel #1 back.
3107 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3108 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3109 short_channel_id: 1,
3112 cltv_expiry_delta: 0,
3113 htlc_minimum_msat: 0,
3114 htlc_maximum_msat: OptionalField::Present(1_000_000_000),
3116 fee_proportional_millionths: 0,
3117 excess_data: Vec::new()
3121 // Now let's see if routing works if we know only htlc_maximum_msat.
3122 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3123 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3124 short_channel_id: 3,
3127 cltv_expiry_delta: 0,
3128 htlc_minimum_msat: 0,
3129 htlc_maximum_msat: OptionalField::Present(15_000),
3131 fee_proportional_millionths: 0,
3132 excess_data: Vec::new()
3136 // Attempt to route more than available results in a failure.
3137 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
3138 &our_id, &payee, &net_graph_msg_handler.network_graph, None, 15_001, 42, Arc::clone(&logger), &scorer) {
3139 assert_eq!(err, "Failed to find a sufficient route to the given destination");
3140 } else { panic!(); }
3144 // Now, attempt to route an exact amount we have should be fine.
3145 let route = get_route(&our_id, &payee, &net_graph_msg_handler.network_graph, None, 15_000, 42, Arc::clone(&logger), &scorer).unwrap();
3146 assert_eq!(route.paths.len(), 1);
3147 let path = route.paths.last().unwrap();
3148 assert_eq!(path.len(), 2);
3149 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
3150 assert_eq!(path.last().unwrap().fee_msat, 15_000);
3153 // Now let's see if routing works if we know only capacity from the UTXO.
3155 // We can't change UTXO capacity on the fly, so we'll disable
3156 // the existing channel and add another one with the capacity we need.
3157 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3158 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3159 short_channel_id: 3,
3162 cltv_expiry_delta: 0,
3163 htlc_minimum_msat: 0,
3164 htlc_maximum_msat: OptionalField::Absent,
3166 fee_proportional_millionths: 0,
3167 excess_data: Vec::new()
3170 let good_script = Builder::new().push_opcode(opcodes::all::OP_PUSHNUM_2)
3171 .push_slice(&PublicKey::from_secret_key(&secp_ctx, &privkeys[0]).serialize())
3172 .push_slice(&PublicKey::from_secret_key(&secp_ctx, &privkeys[2]).serialize())
3173 .push_opcode(opcodes::all::OP_PUSHNUM_2)
3174 .push_opcode(opcodes::all::OP_CHECKMULTISIG).into_script().to_v0_p2wsh();
3176 *chain_monitor.utxo_ret.lock().unwrap() = Ok(TxOut { value: 15, script_pubkey: good_script.clone() });
3177 net_graph_msg_handler.add_chain_access(Some(chain_monitor));
3179 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], &privkeys[2], ChannelFeatures::from_le_bytes(id_to_feature_flags(3)), 333);
3180 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3181 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3182 short_channel_id: 333,
3185 cltv_expiry_delta: (3 << 8) | 1,
3186 htlc_minimum_msat: 0,
3187 htlc_maximum_msat: OptionalField::Absent,
3189 fee_proportional_millionths: 0,
3190 excess_data: Vec::new()
3192 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3193 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3194 short_channel_id: 333,
3197 cltv_expiry_delta: (3 << 8) | 2,
3198 htlc_minimum_msat: 0,
3199 htlc_maximum_msat: OptionalField::Absent,
3201 fee_proportional_millionths: 0,
3202 excess_data: Vec::new()
3206 // Attempt to route more than available results in a failure.
3207 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
3208 &our_id, &payee, &net_graph_msg_handler.network_graph, None, 15_001, 42, Arc::clone(&logger), &scorer) {
3209 assert_eq!(err, "Failed to find a sufficient route to the given destination");
3210 } else { panic!(); }
3214 // Now, attempt to route an exact amount we have should be fine.
3215 let route = get_route(&our_id, &payee, &net_graph_msg_handler.network_graph, None, 15_000, 42, Arc::clone(&logger), &scorer).unwrap();
3216 assert_eq!(route.paths.len(), 1);
3217 let path = route.paths.last().unwrap();
3218 assert_eq!(path.len(), 2);
3219 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
3220 assert_eq!(path.last().unwrap().fee_msat, 15_000);
3223 // Now let's see if routing chooses htlc_maximum_msat over UTXO capacity.
3224 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3225 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3226 short_channel_id: 333,
3229 cltv_expiry_delta: 0,
3230 htlc_minimum_msat: 0,
3231 htlc_maximum_msat: OptionalField::Present(10_000),
3233 fee_proportional_millionths: 0,
3234 excess_data: Vec::new()
3238 // Attempt to route more than available results in a failure.
3239 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
3240 &our_id, &payee, &net_graph_msg_handler.network_graph, None, 10_001, 42, Arc::clone(&logger), &scorer) {
3241 assert_eq!(err, "Failed to find a sufficient route to the given destination");
3242 } else { panic!(); }
3246 // Now, attempt to route an exact amount we have should be fine.
3247 let route = get_route(&our_id, &payee, &net_graph_msg_handler.network_graph, None, 10_000, 42, Arc::clone(&logger), &scorer).unwrap();
3248 assert_eq!(route.paths.len(), 1);
3249 let path = route.paths.last().unwrap();
3250 assert_eq!(path.len(), 2);
3251 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
3252 assert_eq!(path.last().unwrap().fee_msat, 10_000);
3257 fn available_liquidity_last_hop_test() {
3258 // Check that available liquidity properly limits the path even when only
3259 // one of the latter hops is limited.
3260 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
3261 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3262 let scorer = Scorer::with_fixed_penalty(0);
3263 let payee = Payee::new(nodes[3]).with_features(InvoiceFeatures::known());
3265 // Path via {node7, node2, node4} is channels {12, 13, 6, 11}.
3266 // {12, 13, 11} have the capacities of 100, {6} has a capacity of 50.
3267 // Total capacity: 50 sats.
3269 // Disable other potential paths.
3270 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3271 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3272 short_channel_id: 2,
3275 cltv_expiry_delta: 0,
3276 htlc_minimum_msat: 0,
3277 htlc_maximum_msat: OptionalField::Present(100_000),
3279 fee_proportional_millionths: 0,
3280 excess_data: Vec::new()
3282 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3283 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3284 short_channel_id: 7,
3287 cltv_expiry_delta: 0,
3288 htlc_minimum_msat: 0,
3289 htlc_maximum_msat: OptionalField::Present(100_000),
3291 fee_proportional_millionths: 0,
3292 excess_data: Vec::new()
3297 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3298 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3299 short_channel_id: 12,
3302 cltv_expiry_delta: 0,
3303 htlc_minimum_msat: 0,
3304 htlc_maximum_msat: OptionalField::Present(100_000),
3306 fee_proportional_millionths: 0,
3307 excess_data: Vec::new()
3309 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
3310 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3311 short_channel_id: 13,
3314 cltv_expiry_delta: 0,
3315 htlc_minimum_msat: 0,
3316 htlc_maximum_msat: OptionalField::Present(100_000),
3318 fee_proportional_millionths: 0,
3319 excess_data: Vec::new()
3322 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3323 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3324 short_channel_id: 6,
3327 cltv_expiry_delta: 0,
3328 htlc_minimum_msat: 0,
3329 htlc_maximum_msat: OptionalField::Present(50_000),
3331 fee_proportional_millionths: 0,
3332 excess_data: Vec::new()
3334 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
3335 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3336 short_channel_id: 11,
3339 cltv_expiry_delta: 0,
3340 htlc_minimum_msat: 0,
3341 htlc_maximum_msat: OptionalField::Present(100_000),
3343 fee_proportional_millionths: 0,
3344 excess_data: Vec::new()
3347 // Attempt to route more than available results in a failure.
3348 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
3349 &our_id, &payee, &net_graph_msg_handler.network_graph, None, 60_000, 42, Arc::clone(&logger), &scorer) {
3350 assert_eq!(err, "Failed to find a sufficient route to the given destination");
3351 } else { panic!(); }
3355 // Now, attempt to route 49 sats (just a bit below the capacity).
3356 let route = get_route(&our_id, &payee, &net_graph_msg_handler.network_graph, None, 49_000, 42, Arc::clone(&logger), &scorer).unwrap();
3357 assert_eq!(route.paths.len(), 1);
3358 let mut total_amount_paid_msat = 0;
3359 for path in &route.paths {
3360 assert_eq!(path.len(), 4);
3361 assert_eq!(path.last().unwrap().pubkey, nodes[3]);
3362 total_amount_paid_msat += path.last().unwrap().fee_msat;
3364 assert_eq!(total_amount_paid_msat, 49_000);
3368 // Attempt to route an exact amount is also fine
3369 let route = get_route(&our_id, &payee, &net_graph_msg_handler.network_graph, None, 50_000, 42, Arc::clone(&logger), &scorer).unwrap();
3370 assert_eq!(route.paths.len(), 1);
3371 let mut total_amount_paid_msat = 0;
3372 for path in &route.paths {
3373 assert_eq!(path.len(), 4);
3374 assert_eq!(path.last().unwrap().pubkey, nodes[3]);
3375 total_amount_paid_msat += path.last().unwrap().fee_msat;
3377 assert_eq!(total_amount_paid_msat, 50_000);
3382 fn ignore_fee_first_hop_test() {
3383 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
3384 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3385 let scorer = Scorer::with_fixed_penalty(0);
3386 let payee = Payee::new(nodes[2]);
3388 // Path via node0 is channels {1, 3}. Limit them to 100 and 50 sats (total limit 50).
3389 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3390 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3391 short_channel_id: 1,
3394 cltv_expiry_delta: 0,
3395 htlc_minimum_msat: 0,
3396 htlc_maximum_msat: OptionalField::Present(100_000),
3397 fee_base_msat: 1_000_000,
3398 fee_proportional_millionths: 0,
3399 excess_data: Vec::new()
3401 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3402 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3403 short_channel_id: 3,
3406 cltv_expiry_delta: 0,
3407 htlc_minimum_msat: 0,
3408 htlc_maximum_msat: OptionalField::Present(50_000),
3410 fee_proportional_millionths: 0,
3411 excess_data: Vec::new()
3415 let route = get_route(&our_id, &payee, &net_graph_msg_handler.network_graph, None, 50_000, 42, Arc::clone(&logger), &scorer).unwrap();
3416 assert_eq!(route.paths.len(), 1);
3417 let mut total_amount_paid_msat = 0;
3418 for path in &route.paths {
3419 assert_eq!(path.len(), 2);
3420 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
3421 total_amount_paid_msat += path.last().unwrap().fee_msat;
3423 assert_eq!(total_amount_paid_msat, 50_000);
3428 fn simple_mpp_route_test() {
3429 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
3430 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3431 let scorer = Scorer::with_fixed_penalty(0);
3432 let payee = Payee::new(nodes[2]).with_features(InvoiceFeatures::known());
3434 // We need a route consisting of 3 paths:
3435 // From our node to node2 via node0, node7, node1 (three paths one hop each).
3436 // To achieve this, the amount being transferred should be around
3437 // the total capacity of these 3 paths.
3439 // First, we set limits on these (previously unlimited) channels.
3440 // Their aggregate capacity will be 50 + 60 + 180 = 290 sats.
3442 // Path via node0 is channels {1, 3}. Limit them to 100 and 50 sats (total limit 50).
3443 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3444 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3445 short_channel_id: 1,
3448 cltv_expiry_delta: 0,
3449 htlc_minimum_msat: 0,
3450 htlc_maximum_msat: OptionalField::Present(100_000),
3452 fee_proportional_millionths: 0,
3453 excess_data: Vec::new()
3455 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3456 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3457 short_channel_id: 3,
3460 cltv_expiry_delta: 0,
3461 htlc_minimum_msat: 0,
3462 htlc_maximum_msat: OptionalField::Present(50_000),
3464 fee_proportional_millionths: 0,
3465 excess_data: Vec::new()
3468 // Path via node7 is channels {12, 13}. Limit them to 60 and 60 sats
3469 // (total limit 60).
3470 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3471 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3472 short_channel_id: 12,
3475 cltv_expiry_delta: 0,
3476 htlc_minimum_msat: 0,
3477 htlc_maximum_msat: OptionalField::Present(60_000),
3479 fee_proportional_millionths: 0,
3480 excess_data: Vec::new()
3482 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
3483 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3484 short_channel_id: 13,
3487 cltv_expiry_delta: 0,
3488 htlc_minimum_msat: 0,
3489 htlc_maximum_msat: OptionalField::Present(60_000),
3491 fee_proportional_millionths: 0,
3492 excess_data: Vec::new()
3495 // Path via node1 is channels {2, 4}. Limit them to 200 and 180 sats
3496 // (total capacity 180 sats).
3497 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3498 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3499 short_channel_id: 2,
3502 cltv_expiry_delta: 0,
3503 htlc_minimum_msat: 0,
3504 htlc_maximum_msat: OptionalField::Present(200_000),
3506 fee_proportional_millionths: 0,
3507 excess_data: Vec::new()
3509 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
3510 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3511 short_channel_id: 4,
3514 cltv_expiry_delta: 0,
3515 htlc_minimum_msat: 0,
3516 htlc_maximum_msat: OptionalField::Present(180_000),
3518 fee_proportional_millionths: 0,
3519 excess_data: Vec::new()
3523 // Attempt to route more than available results in a failure.
3524 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
3525 &our_id, &payee, &net_graph_msg_handler.network_graph, None, 300_000, 42, Arc::clone(&logger), &scorer) {
3526 assert_eq!(err, "Failed to find a sufficient route to the given destination");
3527 } else { panic!(); }
3531 // Now, attempt to route 250 sats (just a bit below the capacity).
3532 // Our algorithm should provide us with these 3 paths.
3533 let route = get_route(&our_id, &payee, &net_graph_msg_handler.network_graph, None, 250_000, 42, Arc::clone(&logger), &scorer).unwrap();
3534 assert_eq!(route.paths.len(), 3);
3535 let mut total_amount_paid_msat = 0;
3536 for path in &route.paths {
3537 assert_eq!(path.len(), 2);
3538 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
3539 total_amount_paid_msat += path.last().unwrap().fee_msat;
3541 assert_eq!(total_amount_paid_msat, 250_000);
3545 // Attempt to route an exact amount is also fine
3546 let route = get_route(&our_id, &payee, &net_graph_msg_handler.network_graph, None, 290_000, 42, Arc::clone(&logger), &scorer).unwrap();
3547 assert_eq!(route.paths.len(), 3);
3548 let mut total_amount_paid_msat = 0;
3549 for path in &route.paths {
3550 assert_eq!(path.len(), 2);
3551 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
3552 total_amount_paid_msat += path.last().unwrap().fee_msat;
3554 assert_eq!(total_amount_paid_msat, 290_000);
3559 fn long_mpp_route_test() {
3560 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
3561 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3562 let scorer = Scorer::with_fixed_penalty(0);
3563 let payee = Payee::new(nodes[3]).with_features(InvoiceFeatures::known());
3565 // We need a route consisting of 3 paths:
3566 // From our node to node3 via {node0, node2}, {node7, node2, node4} and {node7, node2}.
3567 // Note that these paths overlap (channels 5, 12, 13).
3568 // We will route 300 sats.
3569 // Each path will have 100 sats capacity, those channels which
3570 // are used twice will have 200 sats capacity.
3572 // Disable other potential paths.
3573 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3574 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3575 short_channel_id: 2,
3578 cltv_expiry_delta: 0,
3579 htlc_minimum_msat: 0,
3580 htlc_maximum_msat: OptionalField::Present(100_000),
3582 fee_proportional_millionths: 0,
3583 excess_data: Vec::new()
3585 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3586 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3587 short_channel_id: 7,
3590 cltv_expiry_delta: 0,
3591 htlc_minimum_msat: 0,
3592 htlc_maximum_msat: OptionalField::Present(100_000),
3594 fee_proportional_millionths: 0,
3595 excess_data: Vec::new()
3598 // Path via {node0, node2} is channels {1, 3, 5}.
3599 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3600 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3601 short_channel_id: 1,
3604 cltv_expiry_delta: 0,
3605 htlc_minimum_msat: 0,
3606 htlc_maximum_msat: OptionalField::Present(100_000),
3608 fee_proportional_millionths: 0,
3609 excess_data: Vec::new()
3611 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3612 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3613 short_channel_id: 3,
3616 cltv_expiry_delta: 0,
3617 htlc_minimum_msat: 0,
3618 htlc_maximum_msat: OptionalField::Present(100_000),
3620 fee_proportional_millionths: 0,
3621 excess_data: Vec::new()
3624 // Capacity of 200 sats because this channel will be used by 3rd path as well.
3625 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(5)), 5);
3626 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3627 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3628 short_channel_id: 5,
3631 cltv_expiry_delta: 0,
3632 htlc_minimum_msat: 0,
3633 htlc_maximum_msat: OptionalField::Present(200_000),
3635 fee_proportional_millionths: 0,
3636 excess_data: Vec::new()
3639 // Path via {node7, node2, node4} is channels {12, 13, 6, 11}.
3640 // Add 100 sats to the capacities of {12, 13}, because these channels
3641 // are also used for 3rd path. 100 sats for the rest. Total capacity: 100 sats.
3642 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3643 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3644 short_channel_id: 12,
3647 cltv_expiry_delta: 0,
3648 htlc_minimum_msat: 0,
3649 htlc_maximum_msat: OptionalField::Present(200_000),
3651 fee_proportional_millionths: 0,
3652 excess_data: Vec::new()
3654 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
3655 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3656 short_channel_id: 13,
3659 cltv_expiry_delta: 0,
3660 htlc_minimum_msat: 0,
3661 htlc_maximum_msat: OptionalField::Present(200_000),
3663 fee_proportional_millionths: 0,
3664 excess_data: Vec::new()
3667 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3668 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3669 short_channel_id: 6,
3672 cltv_expiry_delta: 0,
3673 htlc_minimum_msat: 0,
3674 htlc_maximum_msat: OptionalField::Present(100_000),
3676 fee_proportional_millionths: 0,
3677 excess_data: Vec::new()
3679 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
3680 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3681 short_channel_id: 11,
3684 cltv_expiry_delta: 0,
3685 htlc_minimum_msat: 0,
3686 htlc_maximum_msat: OptionalField::Present(100_000),
3688 fee_proportional_millionths: 0,
3689 excess_data: Vec::new()
3692 // Path via {node7, node2} is channels {12, 13, 5}.
3693 // We already limited them to 200 sats (they are used twice for 100 sats).
3694 // Nothing to do here.
3697 // Attempt to route more than available results in a failure.
3698 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
3699 &our_id, &payee, &net_graph_msg_handler.network_graph, None, 350_000, 42, Arc::clone(&logger), &scorer) {
3700 assert_eq!(err, "Failed to find a sufficient route to the given destination");
3701 } else { panic!(); }
3705 // Now, attempt to route 300 sats (exact amount we can route).
3706 // Our algorithm should provide us with these 3 paths, 100 sats each.
3707 let route = get_route(&our_id, &payee, &net_graph_msg_handler.network_graph, None, 300_000, 42, Arc::clone(&logger), &scorer).unwrap();
3708 assert_eq!(route.paths.len(), 3);
3710 let mut total_amount_paid_msat = 0;
3711 for path in &route.paths {
3712 assert_eq!(path.last().unwrap().pubkey, nodes[3]);
3713 total_amount_paid_msat += path.last().unwrap().fee_msat;
3715 assert_eq!(total_amount_paid_msat, 300_000);
3721 fn mpp_cheaper_route_test() {
3722 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
3723 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3724 let scorer = Scorer::with_fixed_penalty(0);
3725 let payee = Payee::new(nodes[3]).with_features(InvoiceFeatures::known());
3727 // This test checks that if we have two cheaper paths and one more expensive path,
3728 // so that liquidity-wise any 2 of 3 combination is sufficient,
3729 // two cheaper paths will be taken.
3730 // These paths have equal available liquidity.
3732 // We need a combination of 3 paths:
3733 // From our node to node3 via {node0, node2}, {node7, node2, node4} and {node7, node2}.
3734 // Note that these paths overlap (channels 5, 12, 13).
3735 // Each path will have 100 sats capacity, those channels which
3736 // are used twice will have 200 sats capacity.
3738 // Disable other potential paths.
3739 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3740 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3741 short_channel_id: 2,
3744 cltv_expiry_delta: 0,
3745 htlc_minimum_msat: 0,
3746 htlc_maximum_msat: OptionalField::Present(100_000),
3748 fee_proportional_millionths: 0,
3749 excess_data: Vec::new()
3751 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3752 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3753 short_channel_id: 7,
3756 cltv_expiry_delta: 0,
3757 htlc_minimum_msat: 0,
3758 htlc_maximum_msat: OptionalField::Present(100_000),
3760 fee_proportional_millionths: 0,
3761 excess_data: Vec::new()
3764 // Path via {node0, node2} is channels {1, 3, 5}.
3765 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3766 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3767 short_channel_id: 1,
3770 cltv_expiry_delta: 0,
3771 htlc_minimum_msat: 0,
3772 htlc_maximum_msat: OptionalField::Present(100_000),
3774 fee_proportional_millionths: 0,
3775 excess_data: Vec::new()
3777 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3778 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3779 short_channel_id: 3,
3782 cltv_expiry_delta: 0,
3783 htlc_minimum_msat: 0,
3784 htlc_maximum_msat: OptionalField::Present(100_000),
3786 fee_proportional_millionths: 0,
3787 excess_data: Vec::new()
3790 // Capacity of 200 sats because this channel will be used by 3rd path as well.
3791 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(5)), 5);
3792 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3793 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3794 short_channel_id: 5,
3797 cltv_expiry_delta: 0,
3798 htlc_minimum_msat: 0,
3799 htlc_maximum_msat: OptionalField::Present(200_000),
3801 fee_proportional_millionths: 0,
3802 excess_data: Vec::new()
3805 // Path via {node7, node2, node4} is channels {12, 13, 6, 11}.
3806 // Add 100 sats to the capacities of {12, 13}, because these channels
3807 // are also used for 3rd path. 100 sats for the rest. Total capacity: 100 sats.
3808 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3809 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3810 short_channel_id: 12,
3813 cltv_expiry_delta: 0,
3814 htlc_minimum_msat: 0,
3815 htlc_maximum_msat: OptionalField::Present(200_000),
3817 fee_proportional_millionths: 0,
3818 excess_data: Vec::new()
3820 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
3821 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3822 short_channel_id: 13,
3825 cltv_expiry_delta: 0,
3826 htlc_minimum_msat: 0,
3827 htlc_maximum_msat: OptionalField::Present(200_000),
3829 fee_proportional_millionths: 0,
3830 excess_data: Vec::new()
3833 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3834 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3835 short_channel_id: 6,
3838 cltv_expiry_delta: 0,
3839 htlc_minimum_msat: 0,
3840 htlc_maximum_msat: OptionalField::Present(100_000),
3841 fee_base_msat: 1_000,
3842 fee_proportional_millionths: 0,
3843 excess_data: Vec::new()
3845 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
3846 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3847 short_channel_id: 11,
3850 cltv_expiry_delta: 0,
3851 htlc_minimum_msat: 0,
3852 htlc_maximum_msat: OptionalField::Present(100_000),
3854 fee_proportional_millionths: 0,
3855 excess_data: Vec::new()
3858 // Path via {node7, node2} is channels {12, 13, 5}.
3859 // We already limited them to 200 sats (they are used twice for 100 sats).
3860 // Nothing to do here.
3863 // Now, attempt to route 180 sats.
3864 // Our algorithm should provide us with these 2 paths.
3865 let route = get_route(&our_id, &payee, &net_graph_msg_handler.network_graph, None, 180_000, 42, Arc::clone(&logger), &scorer).unwrap();
3866 assert_eq!(route.paths.len(), 2);
3868 let mut total_value_transferred_msat = 0;
3869 let mut total_paid_msat = 0;
3870 for path in &route.paths {
3871 assert_eq!(path.last().unwrap().pubkey, nodes[3]);
3872 total_value_transferred_msat += path.last().unwrap().fee_msat;
3874 total_paid_msat += hop.fee_msat;
3877 // If we paid fee, this would be higher.
3878 assert_eq!(total_value_transferred_msat, 180_000);
3879 let total_fees_paid = total_paid_msat - total_value_transferred_msat;
3880 assert_eq!(total_fees_paid, 0);
3885 fn fees_on_mpp_route_test() {
3886 // This test makes sure that MPP algorithm properly takes into account
3887 // fees charged on the channels, by making the fees impactful:
3888 // if the fee is not properly accounted for, the behavior is different.
3889 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
3890 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3891 let scorer = Scorer::with_fixed_penalty(0);
3892 let payee = Payee::new(nodes[3]).with_features(InvoiceFeatures::known());
3894 // We need a route consisting of 2 paths:
3895 // From our node to node3 via {node0, node2} and {node7, node2, node4}.
3896 // We will route 200 sats, Each path will have 100 sats capacity.
3898 // This test is not particularly stable: e.g.,
3899 // there's a way to route via {node0, node2, node4}.
3900 // It works while pathfinding is deterministic, but can be broken otherwise.
3901 // It's fine to ignore this concern for now.
3903 // Disable other potential paths.
3904 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3905 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3906 short_channel_id: 2,
3909 cltv_expiry_delta: 0,
3910 htlc_minimum_msat: 0,
3911 htlc_maximum_msat: OptionalField::Present(100_000),
3913 fee_proportional_millionths: 0,
3914 excess_data: Vec::new()
3917 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3918 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3919 short_channel_id: 7,
3922 cltv_expiry_delta: 0,
3923 htlc_minimum_msat: 0,
3924 htlc_maximum_msat: OptionalField::Present(100_000),
3926 fee_proportional_millionths: 0,
3927 excess_data: Vec::new()
3930 // Path via {node0, node2} is channels {1, 3, 5}.
3931 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3932 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3933 short_channel_id: 1,
3936 cltv_expiry_delta: 0,
3937 htlc_minimum_msat: 0,
3938 htlc_maximum_msat: OptionalField::Present(100_000),
3940 fee_proportional_millionths: 0,
3941 excess_data: Vec::new()
3943 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3944 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3945 short_channel_id: 3,
3948 cltv_expiry_delta: 0,
3949 htlc_minimum_msat: 0,
3950 htlc_maximum_msat: OptionalField::Present(100_000),
3952 fee_proportional_millionths: 0,
3953 excess_data: Vec::new()
3956 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(5)), 5);
3957 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3958 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3959 short_channel_id: 5,
3962 cltv_expiry_delta: 0,
3963 htlc_minimum_msat: 0,
3964 htlc_maximum_msat: OptionalField::Present(100_000),
3966 fee_proportional_millionths: 0,
3967 excess_data: Vec::new()
3970 // Path via {node7, node2, node4} is channels {12, 13, 6, 11}.
3971 // All channels should be 100 sats capacity. But for the fee experiment,
3972 // we'll add absolute fee of 150 sats paid for the use channel 6 (paid to node2 on channel 13).
3973 // Since channel 12 allows to deliver only 250 sats to channel 13, channel 13 can transfer only
3974 // 100 sats (and pay 150 sats in fees for the use of channel 6),
3975 // so no matter how large are other channels,
3976 // the whole path will be limited by 100 sats with just these 2 conditions:
3977 // - channel 12 capacity is 250 sats
3978 // - fee for channel 6 is 150 sats
3979 // Let's test this by enforcing these 2 conditions and removing other limits.
3980 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3981 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3982 short_channel_id: 12,
3985 cltv_expiry_delta: 0,
3986 htlc_minimum_msat: 0,
3987 htlc_maximum_msat: OptionalField::Present(250_000),
3989 fee_proportional_millionths: 0,
3990 excess_data: Vec::new()
3992 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
3993 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3994 short_channel_id: 13,
3997 cltv_expiry_delta: 0,
3998 htlc_minimum_msat: 0,
3999 htlc_maximum_msat: OptionalField::Absent,
4001 fee_proportional_millionths: 0,
4002 excess_data: Vec::new()
4005 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4006 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4007 short_channel_id: 6,
4010 cltv_expiry_delta: 0,
4011 htlc_minimum_msat: 0,
4012 htlc_maximum_msat: OptionalField::Absent,
4013 fee_base_msat: 150_000,
4014 fee_proportional_millionths: 0,
4015 excess_data: Vec::new()
4017 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
4018 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4019 short_channel_id: 11,
4022 cltv_expiry_delta: 0,
4023 htlc_minimum_msat: 0,
4024 htlc_maximum_msat: OptionalField::Absent,
4026 fee_proportional_millionths: 0,
4027 excess_data: Vec::new()
4031 // Attempt to route more than available results in a failure.
4032 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
4033 &our_id, &payee, &net_graph_msg_handler.network_graph, None, 210_000, 42, Arc::clone(&logger), &scorer) {
4034 assert_eq!(err, "Failed to find a sufficient route to the given destination");
4035 } else { panic!(); }
4039 // Now, attempt to route 200 sats (exact amount we can route).
4040 let route = get_route(&our_id, &payee, &net_graph_msg_handler.network_graph, None, 200_000, 42, Arc::clone(&logger), &scorer).unwrap();
4041 assert_eq!(route.paths.len(), 2);
4043 let mut total_amount_paid_msat = 0;
4044 for path in &route.paths {
4045 assert_eq!(path.last().unwrap().pubkey, nodes[3]);
4046 total_amount_paid_msat += path.last().unwrap().fee_msat;
4048 assert_eq!(total_amount_paid_msat, 200_000);
4049 assert_eq!(route.get_total_fees(), 150_000);
4055 fn drop_lowest_channel_mpp_route_test() {
4056 // This test checks that low-capacity channel is dropped when after
4057 // path finding we realize that we found more capacity than we need.
4058 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
4059 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
4060 let scorer = Scorer::with_fixed_penalty(0);
4061 let payee = Payee::new(nodes[2]).with_features(InvoiceFeatures::known());
4063 // We need a route consisting of 3 paths:
4064 // From our node to node2 via node0, node7, node1 (three paths one hop each).
4066 // The first and the second paths should be sufficient, but the third should be
4067 // cheaper, so that we select it but drop later.
4069 // First, we set limits on these (previously unlimited) channels.
4070 // Their aggregate capacity will be 50 + 60 + 20 = 130 sats.
4072 // Path via node0 is channels {1, 3}. Limit them to 100 and 50 sats (total limit 50);
4073 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4074 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4075 short_channel_id: 1,
4078 cltv_expiry_delta: 0,
4079 htlc_minimum_msat: 0,
4080 htlc_maximum_msat: OptionalField::Present(100_000),
4082 fee_proportional_millionths: 0,
4083 excess_data: Vec::new()
4085 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
4086 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4087 short_channel_id: 3,
4090 cltv_expiry_delta: 0,
4091 htlc_minimum_msat: 0,
4092 htlc_maximum_msat: OptionalField::Present(50_000),
4094 fee_proportional_millionths: 0,
4095 excess_data: Vec::new()
4098 // Path via node7 is channels {12, 13}. Limit them to 60 and 60 sats (total limit 60);
4099 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4100 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4101 short_channel_id: 12,
4104 cltv_expiry_delta: 0,
4105 htlc_minimum_msat: 0,
4106 htlc_maximum_msat: OptionalField::Present(60_000),
4108 fee_proportional_millionths: 0,
4109 excess_data: Vec::new()
4111 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
4112 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4113 short_channel_id: 13,
4116 cltv_expiry_delta: 0,
4117 htlc_minimum_msat: 0,
4118 htlc_maximum_msat: OptionalField::Present(60_000),
4120 fee_proportional_millionths: 0,
4121 excess_data: Vec::new()
4124 // Path via node1 is channels {2, 4}. Limit them to 20 and 20 sats (total capacity 20 sats).
4125 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4126 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4127 short_channel_id: 2,
4130 cltv_expiry_delta: 0,
4131 htlc_minimum_msat: 0,
4132 htlc_maximum_msat: OptionalField::Present(20_000),
4134 fee_proportional_millionths: 0,
4135 excess_data: Vec::new()
4137 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
4138 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4139 short_channel_id: 4,
4142 cltv_expiry_delta: 0,
4143 htlc_minimum_msat: 0,
4144 htlc_maximum_msat: OptionalField::Present(20_000),
4146 fee_proportional_millionths: 0,
4147 excess_data: Vec::new()
4151 // Attempt to route more than available results in a failure.
4152 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
4153 &our_id, &payee, &net_graph_msg_handler.network_graph, None, 150_000, 42, Arc::clone(&logger), &scorer) {
4154 assert_eq!(err, "Failed to find a sufficient route to the given destination");
4155 } else { panic!(); }
4159 // Now, attempt to route 125 sats (just a bit below the capacity of 3 channels).
4160 // Our algorithm should provide us with these 3 paths.
4161 let route = get_route(&our_id, &payee, &net_graph_msg_handler.network_graph, None, 125_000, 42, Arc::clone(&logger), &scorer).unwrap();
4162 assert_eq!(route.paths.len(), 3);
4163 let mut total_amount_paid_msat = 0;
4164 for path in &route.paths {
4165 assert_eq!(path.len(), 2);
4166 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
4167 total_amount_paid_msat += path.last().unwrap().fee_msat;
4169 assert_eq!(total_amount_paid_msat, 125_000);
4173 // Attempt to route without the last small cheap channel
4174 let route = get_route(&our_id, &payee, &net_graph_msg_handler.network_graph, None, 90_000, 42, Arc::clone(&logger), &scorer).unwrap();
4175 assert_eq!(route.paths.len(), 2);
4176 let mut total_amount_paid_msat = 0;
4177 for path in &route.paths {
4178 assert_eq!(path.len(), 2);
4179 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
4180 total_amount_paid_msat += path.last().unwrap().fee_msat;
4182 assert_eq!(total_amount_paid_msat, 90_000);
4187 fn min_criteria_consistency() {
4188 // Test that we don't use an inconsistent metric between updating and walking nodes during
4189 // our Dijkstra's pass. In the initial version of MPP, the "best source" for a given node
4190 // was updated with a different criterion from the heap sorting, resulting in loops in
4191 // calculated paths. We test for that specific case here.
4193 // We construct a network that looks like this:
4195 // node2 -1(3)2- node3
4199 // node1 -1(5)2- node4 -1(1)2- node6
4205 // We create a loop on the side of our real path - our destination is node 6, with a
4206 // previous hop of node 4. From 4, the cheapest previous path is channel 2 from node 2,
4207 // followed by node 3 over channel 3. Thereafter, the cheapest next-hop is back to node 4
4208 // (this time over channel 4). Channel 4 has 0 htlc_minimum_msat whereas channel 1 (the
4209 // other channel with a previous-hop of node 4) has a high (but irrelevant to the overall
4210 // payment) htlc_minimum_msat. In the original algorithm, this resulted in node4's
4211 // "previous hop" being set to node 3, creating a loop in the path.
4212 let secp_ctx = Secp256k1::new();
4213 let logger = Arc::new(test_utils::TestLogger::new());
4214 let network_graph = NetworkGraph::new(genesis_block(Network::Testnet).header.block_hash());
4215 let net_graph_msg_handler = NetGraphMsgHandler::new(network_graph, None, Arc::clone(&logger));
4216 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
4217 let scorer = Scorer::with_fixed_penalty(0);
4218 let payee = Payee::new(nodes[6]);
4220 add_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, &privkeys[1], ChannelFeatures::from_le_bytes(id_to_feature_flags(6)), 6);
4221 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4222 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4223 short_channel_id: 6,
4226 cltv_expiry_delta: (6 << 8) | 0,
4227 htlc_minimum_msat: 0,
4228 htlc_maximum_msat: OptionalField::Absent,
4230 fee_proportional_millionths: 0,
4231 excess_data: Vec::new()
4233 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[1], NodeFeatures::from_le_bytes(id_to_feature_flags(1)), 0);
4235 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], &privkeys[4], ChannelFeatures::from_le_bytes(id_to_feature_flags(5)), 5);
4236 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
4237 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4238 short_channel_id: 5,
4241 cltv_expiry_delta: (5 << 8) | 0,
4242 htlc_minimum_msat: 0,
4243 htlc_maximum_msat: OptionalField::Absent,
4245 fee_proportional_millionths: 0,
4246 excess_data: Vec::new()
4248 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[4], NodeFeatures::from_le_bytes(id_to_feature_flags(4)), 0);
4250 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(4)), 4);
4251 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
4252 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4253 short_channel_id: 4,
4256 cltv_expiry_delta: (4 << 8) | 0,
4257 htlc_minimum_msat: 0,
4258 htlc_maximum_msat: OptionalField::Absent,
4260 fee_proportional_millionths: 0,
4261 excess_data: Vec::new()
4263 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[3], NodeFeatures::from_le_bytes(id_to_feature_flags(3)), 0);
4265 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[3], &privkeys[2], ChannelFeatures::from_le_bytes(id_to_feature_flags(3)), 3);
4266 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[3], UnsignedChannelUpdate {
4267 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4268 short_channel_id: 3,
4271 cltv_expiry_delta: (3 << 8) | 0,
4272 htlc_minimum_msat: 0,
4273 htlc_maximum_msat: OptionalField::Absent,
4275 fee_proportional_millionths: 0,
4276 excess_data: Vec::new()
4278 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[2], NodeFeatures::from_le_bytes(id_to_feature_flags(2)), 0);
4280 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], &privkeys[4], ChannelFeatures::from_le_bytes(id_to_feature_flags(2)), 2);
4281 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4282 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4283 short_channel_id: 2,
4286 cltv_expiry_delta: (2 << 8) | 0,
4287 htlc_minimum_msat: 0,
4288 htlc_maximum_msat: OptionalField::Absent,
4290 fee_proportional_millionths: 0,
4291 excess_data: Vec::new()
4294 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], &privkeys[6], ChannelFeatures::from_le_bytes(id_to_feature_flags(1)), 1);
4295 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
4296 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4297 short_channel_id: 1,
4300 cltv_expiry_delta: (1 << 8) | 0,
4301 htlc_minimum_msat: 100,
4302 htlc_maximum_msat: OptionalField::Absent,
4304 fee_proportional_millionths: 0,
4305 excess_data: Vec::new()
4307 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[6], NodeFeatures::from_le_bytes(id_to_feature_flags(6)), 0);
4310 // Now ensure the route flows simply over nodes 1 and 4 to 6.
4311 let route = get_route(&our_id, &payee, &net_graph_msg_handler.network_graph, None, 10_000, 42, Arc::clone(&logger), &scorer).unwrap();
4312 assert_eq!(route.paths.len(), 1);
4313 assert_eq!(route.paths[0].len(), 3);
4315 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
4316 assert_eq!(route.paths[0][0].short_channel_id, 6);
4317 assert_eq!(route.paths[0][0].fee_msat, 100);
4318 assert_eq!(route.paths[0][0].cltv_expiry_delta, (5 << 8) | 0);
4319 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(1));
4320 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(6));
4322 assert_eq!(route.paths[0][1].pubkey, nodes[4]);
4323 assert_eq!(route.paths[0][1].short_channel_id, 5);
4324 assert_eq!(route.paths[0][1].fee_msat, 0);
4325 assert_eq!(route.paths[0][1].cltv_expiry_delta, (1 << 8) | 0);
4326 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(4));
4327 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(5));
4329 assert_eq!(route.paths[0][2].pubkey, nodes[6]);
4330 assert_eq!(route.paths[0][2].short_channel_id, 1);
4331 assert_eq!(route.paths[0][2].fee_msat, 10_000);
4332 assert_eq!(route.paths[0][2].cltv_expiry_delta, 42);
4333 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(6));
4334 assert_eq!(route.paths[0][2].channel_features.le_flags(), &id_to_feature_flags(1));
4340 fn exact_fee_liquidity_limit() {
4341 // Test that if, while walking the graph, we find a hop that has exactly enough liquidity
4342 // for us, including later hop fees, we take it. In the first version of our MPP algorithm
4343 // we calculated fees on a higher value, resulting in us ignoring such paths.
4344 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
4345 let (our_privkey, our_id, _, nodes) = get_nodes(&secp_ctx);
4346 let scorer = Scorer::with_fixed_penalty(0);
4347 let payee = Payee::new(nodes[2]);
4349 // We modify the graph to set the htlc_maximum of channel 2 to below the value we wish to
4351 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4352 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4353 short_channel_id: 2,
4356 cltv_expiry_delta: 0,
4357 htlc_minimum_msat: 0,
4358 htlc_maximum_msat: OptionalField::Present(85_000),
4360 fee_proportional_millionths: 0,
4361 excess_data: Vec::new()
4364 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4365 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4366 short_channel_id: 12,
4369 cltv_expiry_delta: (4 << 8) | 1,
4370 htlc_minimum_msat: 0,
4371 htlc_maximum_msat: OptionalField::Present(270_000),
4373 fee_proportional_millionths: 1000000,
4374 excess_data: Vec::new()
4378 // Now, attempt to route 90 sats, which is exactly 90 sats at the last hop, plus the
4379 // 200% fee charged channel 13 in the 1-to-2 direction.
4380 let route = get_route(&our_id, &payee, &net_graph_msg_handler.network_graph, None, 90_000, 42, Arc::clone(&logger), &scorer).unwrap();
4381 assert_eq!(route.paths.len(), 1);
4382 assert_eq!(route.paths[0].len(), 2);
4384 assert_eq!(route.paths[0][0].pubkey, nodes[7]);
4385 assert_eq!(route.paths[0][0].short_channel_id, 12);
4386 assert_eq!(route.paths[0][0].fee_msat, 90_000*2);
4387 assert_eq!(route.paths[0][0].cltv_expiry_delta, (13 << 8) | 1);
4388 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(8));
4389 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(12));
4391 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
4392 assert_eq!(route.paths[0][1].short_channel_id, 13);
4393 assert_eq!(route.paths[0][1].fee_msat, 90_000);
4394 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
4395 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
4396 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(13));
4401 fn htlc_max_reduction_below_min() {
4402 // Test that if, while walking the graph, we reduce the value being sent to meet an
4403 // htlc_maximum_msat, we don't end up undershooting a later htlc_minimum_msat. In the
4404 // initial version of MPP we'd accept such routes but reject them while recalculating fees,
4405 // resulting in us thinking there is no possible path, even if other paths exist.
4406 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
4407 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
4408 let scorer = Scorer::with_fixed_penalty(0);
4409 let payee = Payee::new(nodes[2]).with_features(InvoiceFeatures::known());
4411 // We modify the graph to set the htlc_minimum of channel 2 and 4 as needed - channel 2
4412 // gets an htlc_maximum_msat of 80_000 and channel 4 an htlc_minimum_msat of 90_000. We
4413 // then try to send 90_000.
4414 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4415 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4416 short_channel_id: 2,
4419 cltv_expiry_delta: 0,
4420 htlc_minimum_msat: 0,
4421 htlc_maximum_msat: OptionalField::Present(80_000),
4423 fee_proportional_millionths: 0,
4424 excess_data: Vec::new()
4426 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
4427 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4428 short_channel_id: 4,
4431 cltv_expiry_delta: (4 << 8) | 1,
4432 htlc_minimum_msat: 90_000,
4433 htlc_maximum_msat: OptionalField::Absent,
4435 fee_proportional_millionths: 0,
4436 excess_data: Vec::new()
4440 // Now, attempt to route 90 sats, hitting the htlc_minimum on channel 4, but
4441 // overshooting the htlc_maximum on channel 2. Thus, we should pick the (absurdly
4442 // expensive) channels 12-13 path.
4443 let route = get_route(&our_id, &payee, &net_graph_msg_handler.network_graph, None, 90_000, 42, Arc::clone(&logger), &scorer).unwrap();
4444 assert_eq!(route.paths.len(), 1);
4445 assert_eq!(route.paths[0].len(), 2);
4447 assert_eq!(route.paths[0][0].pubkey, nodes[7]);
4448 assert_eq!(route.paths[0][0].short_channel_id, 12);
4449 assert_eq!(route.paths[0][0].fee_msat, 90_000*2);
4450 assert_eq!(route.paths[0][0].cltv_expiry_delta, (13 << 8) | 1);
4451 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(8));
4452 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(12));
4454 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
4455 assert_eq!(route.paths[0][1].short_channel_id, 13);
4456 assert_eq!(route.paths[0][1].fee_msat, 90_000);
4457 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
4458 assert_eq!(route.paths[0][1].node_features.le_flags(), InvoiceFeatures::known().le_flags());
4459 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(13));
4464 fn multiple_direct_first_hops() {
4465 // Previously we'd only ever considered one first hop path per counterparty.
4466 // However, as we don't restrict users to one channel per peer, we really need to support
4467 // looking at all first hop paths.
4468 // Here we test that we do not ignore all-but-the-last first hop paths per counterparty (as
4469 // we used to do by overwriting the `first_hop_targets` hashmap entry) and that we can MPP
4470 // route over multiple channels with the same first hop.
4471 let secp_ctx = Secp256k1::new();
4472 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
4473 let logger = Arc::new(test_utils::TestLogger::new());
4474 let network_graph = NetworkGraph::new(genesis_block(Network::Testnet).header.block_hash());
4475 let scorer = Scorer::with_fixed_penalty(0);
4476 let payee = Payee::new(nodes[0]).with_features(InvoiceFeatures::known());
4479 let route = get_route(&our_id, &payee, &network_graph, Some(&[
4480 &get_channel_details(Some(3), nodes[0], InitFeatures::known(), 200_000),
4481 &get_channel_details(Some(2), nodes[0], InitFeatures::known(), 10_000),
4482 ]), 100_000, 42, Arc::clone(&logger), &scorer).unwrap();
4483 assert_eq!(route.paths.len(), 1);
4484 assert_eq!(route.paths[0].len(), 1);
4486 assert_eq!(route.paths[0][0].pubkey, nodes[0]);
4487 assert_eq!(route.paths[0][0].short_channel_id, 3);
4488 assert_eq!(route.paths[0][0].fee_msat, 100_000);
4491 let route = get_route(&our_id, &payee, &network_graph, Some(&[
4492 &get_channel_details(Some(3), nodes[0], InitFeatures::known(), 50_000),
4493 &get_channel_details(Some(2), nodes[0], InitFeatures::known(), 50_000),
4494 ]), 100_000, 42, Arc::clone(&logger), &scorer).unwrap();
4495 assert_eq!(route.paths.len(), 2);
4496 assert_eq!(route.paths[0].len(), 1);
4497 assert_eq!(route.paths[1].len(), 1);
4499 assert_eq!(route.paths[0][0].pubkey, nodes[0]);
4500 assert_eq!(route.paths[0][0].short_channel_id, 3);
4501 assert_eq!(route.paths[0][0].fee_msat, 50_000);
4503 assert_eq!(route.paths[1][0].pubkey, nodes[0]);
4504 assert_eq!(route.paths[1][0].short_channel_id, 2);
4505 assert_eq!(route.paths[1][0].fee_msat, 50_000);
4510 fn prefers_shorter_route_with_higher_fees() {
4511 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
4512 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
4513 let payee = Payee::new(nodes[6]).with_route_hints(last_hops(&nodes));
4515 // Without penalizing each hop 100 msats, a longer path with lower fees is chosen.
4516 let scorer = Scorer::with_fixed_penalty(0);
4517 let route = get_route(
4518 &our_id, &payee, &net_graph_msg_handler.network_graph, None, 100, 42,
4519 Arc::clone(&logger), &scorer
4521 let path = route.paths[0].iter().map(|hop| hop.short_channel_id).collect::<Vec<_>>();
4523 assert_eq!(route.get_total_fees(), 100);
4524 assert_eq!(route.get_total_amount(), 100);
4525 assert_eq!(path, vec![2, 4, 6, 11, 8]);
4527 // Applying a 100 msat penalty to each hop results in taking channels 7 and 10 to nodes[6]
4528 // from nodes[2] rather than channel 6, 11, and 8, even though the longer path is cheaper.
4529 let scorer = Scorer::with_fixed_penalty(100);
4530 let route = get_route(
4531 &our_id, &payee, &net_graph_msg_handler.network_graph, None, 100, 42,
4532 Arc::clone(&logger), &scorer
4534 let path = route.paths[0].iter().map(|hop| hop.short_channel_id).collect::<Vec<_>>();
4536 assert_eq!(route.get_total_fees(), 300);
4537 assert_eq!(route.get_total_amount(), 100);
4538 assert_eq!(path, vec![2, 4, 7, 10]);
4541 struct BadChannelScorer {
4542 short_channel_id: u64,
4545 impl routing::Score for BadChannelScorer {
4546 fn channel_penalty_msat(&self, short_channel_id: u64, _source: &NodeId, _target: &NodeId) -> u64 {
4547 if short_channel_id == self.short_channel_id { u64::max_value() } else { 0 }
4550 fn payment_path_failed(&mut self, _path: &Vec<RouteHop>, _short_channel_id: u64) {}
4553 struct BadNodeScorer {
4557 impl routing::Score for BadNodeScorer {
4558 fn channel_penalty_msat(&self, _short_channel_id: u64, _source: &NodeId, target: &NodeId) -> u64 {
4559 if *target == self.node_id { u64::max_value() } else { 0 }
4562 fn payment_path_failed(&mut self, _path: &Vec<RouteHop>, _short_channel_id: u64) {}
4566 fn avoids_routing_through_bad_channels_and_nodes() {
4567 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
4568 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
4569 let payee = Payee::new(nodes[6]).with_route_hints(last_hops(&nodes));
4571 // A path to nodes[6] exists when no penalties are applied to any channel.
4572 let scorer = Scorer::with_fixed_penalty(0);
4573 let route = get_route(
4574 &our_id, &payee, &net_graph_msg_handler.network_graph, None, 100, 42,
4575 Arc::clone(&logger), &scorer
4577 let path = route.paths[0].iter().map(|hop| hop.short_channel_id).collect::<Vec<_>>();
4579 assert_eq!(route.get_total_fees(), 100);
4580 assert_eq!(route.get_total_amount(), 100);
4581 assert_eq!(path, vec![2, 4, 6, 11, 8]);
4583 // A different path to nodes[6] exists if channel 6 cannot be routed over.
4584 let scorer = BadChannelScorer { short_channel_id: 6 };
4585 let route = get_route(
4586 &our_id, &payee, &net_graph_msg_handler.network_graph, None, 100, 42,
4587 Arc::clone(&logger), &scorer
4589 let path = route.paths[0].iter().map(|hop| hop.short_channel_id).collect::<Vec<_>>();
4591 assert_eq!(route.get_total_fees(), 300);
4592 assert_eq!(route.get_total_amount(), 100);
4593 assert_eq!(path, vec![2, 4, 7, 10]);
4595 // A path to nodes[6] does not exist if nodes[2] cannot be routed through.
4596 let scorer = BadNodeScorer { node_id: NodeId::from_pubkey(&nodes[2]) };
4598 &our_id, &payee, &net_graph_msg_handler.network_graph, None, 100, 42,
4599 Arc::clone(&logger), &scorer
4601 Err(LightningError { err, .. } ) => {
4602 assert_eq!(err, "Failed to find a path to the given destination");
4604 Ok(_) => panic!("Expected error"),
4609 fn total_fees_single_path() {
4613 pubkey: PublicKey::from_slice(&hex::decode("02eec7245d6b7d2ccb30380bfbe2a3648cd7a942653f5aa340edcea1f283686619").unwrap()[..]).unwrap(),
4614 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
4615 short_channel_id: 0, fee_msat: 100, cltv_expiry_delta: 0
4618 pubkey: PublicKey::from_slice(&hex::decode("0324653eac434488002cc06bbfb7f10fe18991e35f9fe4302dbea6d2353dc0ab1c").unwrap()[..]).unwrap(),
4619 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
4620 short_channel_id: 0, fee_msat: 150, cltv_expiry_delta: 0
4623 pubkey: PublicKey::from_slice(&hex::decode("027f31ebc5462c1fdce1b737ecff52d37d75dea43ce11c74d25aa297165faa2007").unwrap()[..]).unwrap(),
4624 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
4625 short_channel_id: 0, fee_msat: 225, cltv_expiry_delta: 0
4631 assert_eq!(route.get_total_fees(), 250);
4632 assert_eq!(route.get_total_amount(), 225);
4636 fn total_fees_multi_path() {
4640 pubkey: PublicKey::from_slice(&hex::decode("02eec7245d6b7d2ccb30380bfbe2a3648cd7a942653f5aa340edcea1f283686619").unwrap()[..]).unwrap(),
4641 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
4642 short_channel_id: 0, fee_msat: 100, cltv_expiry_delta: 0
4645 pubkey: PublicKey::from_slice(&hex::decode("0324653eac434488002cc06bbfb7f10fe18991e35f9fe4302dbea6d2353dc0ab1c").unwrap()[..]).unwrap(),
4646 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
4647 short_channel_id: 0, fee_msat: 150, cltv_expiry_delta: 0
4651 pubkey: PublicKey::from_slice(&hex::decode("02eec7245d6b7d2ccb30380bfbe2a3648cd7a942653f5aa340edcea1f283686619").unwrap()[..]).unwrap(),
4652 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
4653 short_channel_id: 0, fee_msat: 100, cltv_expiry_delta: 0
4656 pubkey: PublicKey::from_slice(&hex::decode("0324653eac434488002cc06bbfb7f10fe18991e35f9fe4302dbea6d2353dc0ab1c").unwrap()[..]).unwrap(),
4657 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
4658 short_channel_id: 0, fee_msat: 150, cltv_expiry_delta: 0
4664 assert_eq!(route.get_total_fees(), 200);
4665 assert_eq!(route.get_total_amount(), 300);
4669 fn total_empty_route_no_panic() {
4670 // In an earlier version of `Route::get_total_fees` and `Route::get_total_amount`, they
4671 // would both panic if the route was completely empty. We test to ensure they return 0
4672 // here, even though its somewhat nonsensical as a route.
4673 let route = Route { paths: Vec::new(), payee: None };
4675 assert_eq!(route.get_total_fees(), 0);
4676 assert_eq!(route.get_total_amount(), 0);
4679 #[cfg(not(feature = "no-std"))]
4680 pub(super) fn random_init_seed() -> u64 {
4681 // Because the default HashMap in std pulls OS randomness, we can use it as a (bad) RNG.
4682 use core::hash::{BuildHasher, Hasher};
4683 let seed = std::collections::hash_map::RandomState::new().build_hasher().finish();
4684 println!("Using seed of {}", seed);
4687 #[cfg(not(feature = "no-std"))]
4688 use util::ser::Readable;
4691 #[cfg(not(feature = "no-std"))]
4692 fn generate_routes() {
4693 let mut d = match super::test_utils::get_route_file() {
4700 let graph = NetworkGraph::read(&mut d).unwrap();
4701 let scorer = Scorer::with_fixed_penalty(0);
4703 // First, get 100 (source, destination) pairs for which route-getting actually succeeds...
4704 let mut seed = random_init_seed() as usize;
4705 let nodes = graph.read_only().nodes().clone();
4706 'load_endpoints: for _ in 0..10 {
4708 seed = seed.overflowing_mul(0xdeadbeef).0;
4709 let src = &PublicKey::from_slice(nodes.keys().skip(seed % nodes.len()).next().unwrap().as_slice()).unwrap();
4710 seed = seed.overflowing_mul(0xdeadbeef).0;
4711 let dst = PublicKey::from_slice(nodes.keys().skip(seed % nodes.len()).next().unwrap().as_slice()).unwrap();
4712 let payee = Payee::new(dst);
4713 let amt = seed as u64 % 200_000_000;
4714 if get_route(src, &payee, &graph, None, amt, 42, &test_utils::TestLogger::new(), &scorer).is_ok() {
4715 continue 'load_endpoints;
4722 #[cfg(not(feature = "no-std"))]
4723 fn generate_routes_mpp() {
4724 let mut d = match super::test_utils::get_route_file() {
4731 let graph = NetworkGraph::read(&mut d).unwrap();
4732 let scorer = Scorer::with_fixed_penalty(0);
4734 // First, get 100 (source, destination) pairs for which route-getting actually succeeds...
4735 let mut seed = random_init_seed() as usize;
4736 let nodes = graph.read_only().nodes().clone();
4737 'load_endpoints: for _ in 0..10 {
4739 seed = seed.overflowing_mul(0xdeadbeef).0;
4740 let src = &PublicKey::from_slice(nodes.keys().skip(seed % nodes.len()).next().unwrap().as_slice()).unwrap();
4741 seed = seed.overflowing_mul(0xdeadbeef).0;
4742 let dst = PublicKey::from_slice(nodes.keys().skip(seed % nodes.len()).next().unwrap().as_slice()).unwrap();
4743 let payee = Payee::new(dst).with_features(InvoiceFeatures::known());
4744 let amt = seed as u64 % 200_000_000;
4745 if get_route(src, &payee, &graph, None, amt, 42, &test_utils::TestLogger::new(), &scorer).is_ok() {
4746 continue 'load_endpoints;
4753 #[cfg(all(test, not(feature = "no-std")))]
4754 pub(crate) mod test_utils {
4756 /// Tries to open a network graph file, or panics with a URL to fetch it.
4757 pub(crate) fn get_route_file() -> Result<std::fs::File, &'static str> {
4758 let res = File::open("net_graph-2021-05-31.bin") // By default we're run in RL/lightning
4759 .or_else(|_| File::open("lightning/net_graph-2021-05-31.bin")) // We may be run manually in RL/
4760 .or_else(|_| { // Fall back to guessing based on the binary location
4761 // path is likely something like .../rust-lightning/target/debug/deps/lightning-...
4762 let mut path = std::env::current_exe().unwrap();
4763 path.pop(); // lightning-...
4765 path.pop(); // debug
4766 path.pop(); // target
4767 path.push("lightning");
4768 path.push("net_graph-2021-05-31.bin");
4769 eprintln!("{}", path.to_str().unwrap());
4772 .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");
4773 #[cfg(require_route_graph_test)]
4774 return Ok(res.unwrap());
4775 #[cfg(not(require_route_graph_test))]
4780 #[cfg(all(test, feature = "unstable", not(feature = "no-std")))]
4783 use routing::scorer::Scorer;
4784 use util::logger::{Logger, Record};
4788 struct DummyLogger {}
4789 impl Logger for DummyLogger {
4790 fn log(&self, _record: &Record) {}
4794 fn generate_routes(bench: &mut Bencher) {
4795 let mut d = test_utils::get_route_file().unwrap();
4796 let graph = NetworkGraph::read(&mut d).unwrap();
4797 let nodes = graph.read_only().nodes().clone();
4798 let scorer = Scorer::with_fixed_penalty(0);
4800 // First, get 100 (source, destination) pairs for which route-getting actually succeeds...
4801 let mut path_endpoints = Vec::new();
4802 let mut seed: usize = 0xdeadbeef;
4803 'load_endpoints: for _ in 0..100 {
4806 let src = PublicKey::from_slice(nodes.keys().skip(seed % nodes.len()).next().unwrap().as_slice()).unwrap();
4808 let dst = PublicKey::from_slice(nodes.keys().skip(seed % nodes.len()).next().unwrap().as_slice()).unwrap();
4809 let payee = Payee::new(dst);
4810 let amt = seed as u64 % 1_000_000;
4811 if get_route(&src, &payee, &graph, None, amt, 42, &DummyLogger{}, &scorer).is_ok() {
4812 path_endpoints.push((src, dst, amt));
4813 continue 'load_endpoints;
4818 // ...then benchmark finding paths between the nodes we learned.
4821 let (src, dst, amt) = path_endpoints[idx % path_endpoints.len()];
4822 let payee = Payee::new(dst);
4823 assert!(get_route(&src, &payee, &graph, None, amt, 42, &DummyLogger{}, &scorer).is_ok());
4829 fn generate_mpp_routes(bench: &mut Bencher) {
4830 let mut d = test_utils::get_route_file().unwrap();
4831 let graph = NetworkGraph::read(&mut d).unwrap();
4832 let nodes = graph.read_only().nodes().clone();
4833 let scorer = Scorer::with_fixed_penalty(0);
4835 // First, get 100 (source, destination) pairs for which route-getting actually succeeds...
4836 let mut path_endpoints = Vec::new();
4837 let mut seed: usize = 0xdeadbeef;
4838 'load_endpoints: for _ in 0..100 {
4841 let src = PublicKey::from_slice(nodes.keys().skip(seed % nodes.len()).next().unwrap().as_slice()).unwrap();
4843 let dst = PublicKey::from_slice(nodes.keys().skip(seed % nodes.len()).next().unwrap().as_slice()).unwrap();
4844 let payee = Payee::new(dst).with_features(InvoiceFeatures::known());
4845 let amt = seed as u64 % 1_000_000;
4846 if get_route(&src, &payee, &graph, None, amt, 42, &DummyLogger{}, &scorer).is_ok() {
4847 path_endpoints.push((src, dst, amt));
4848 continue 'load_endpoints;
4853 // ...then benchmark finding paths between the nodes we learned.
4856 let (src, dst, amt) = path_endpoints[idx % path_endpoints.len()];
4857 let payee = Payee::new(dst).with_features(InvoiceFeatures::known());
4858 assert!(get_route(&src, &payee, &graph, None, amt, 42, &DummyLogger{}, &scorer).is_ok());