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 [`get_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>,
82 /// Returns the total amount of fees paid on this [`Route`].
84 /// This doesn't include any extra payment made to the recipient, which can happen in excess of
85 /// the amount passed to [`get_route`]'s `final_value_msat`.
86 pub fn get_total_fees(&self) -> u64 {
87 // Do not count last hop of each path since that's the full value of the payment
88 return self.paths.iter()
89 .flat_map(|path| path.split_last().map(|(_, path_prefix)| path_prefix).unwrap_or(&[]))
90 .map(|hop| &hop.fee_msat)
94 /// Returns the total amount paid on this [`Route`], excluding the fees.
95 pub fn get_total_amount(&self) -> u64 {
96 return self.paths.iter()
97 .map(|path| path.split_last().map(|(hop, _)| hop.fee_msat).unwrap_or(0))
102 const SERIALIZATION_VERSION: u8 = 1;
103 const MIN_SERIALIZATION_VERSION: u8 = 1;
105 impl Writeable for Route {
106 fn write<W: ::util::ser::Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
107 write_ver_prefix!(writer, SERIALIZATION_VERSION, MIN_SERIALIZATION_VERSION);
108 (self.paths.len() as u64).write(writer)?;
109 for hops in self.paths.iter() {
110 (hops.len() as u8).write(writer)?;
111 for hop in hops.iter() {
115 write_tlv_fields!(writer, {
116 (1, self.payee, option),
122 impl Readable for Route {
123 fn read<R: io::Read>(reader: &mut R) -> Result<Route, DecodeError> {
124 let _ver = read_ver_prefix!(reader, SERIALIZATION_VERSION);
125 let path_count: u64 = Readable::read(reader)?;
126 let mut paths = Vec::with_capacity(cmp::min(path_count, 128) as usize);
127 for _ in 0..path_count {
128 let hop_count: u8 = Readable::read(reader)?;
129 let mut hops = Vec::with_capacity(hop_count as usize);
130 for _ in 0..hop_count {
131 hops.push(Readable::read(reader)?);
135 let mut payee = None;
136 read_tlv_fields!(reader, {
139 Ok(Route { paths, payee })
143 /// Parameters needed to re-compute a [`Route`] for retrying a failed payment path.
145 /// Provided in [`Event::PaymentPathFailed`] and passed to [`get_retry_route`].
147 /// [`Event::PaymentPathFailed`]: crate::util::events::Event::PaymentPathFailed
148 #[derive(Clone, Debug)]
149 pub struct PaymentPathRetry {
150 /// The recipient of the failed payment path.
153 /// The amount in msats sent on the failed payment path.
154 pub final_value_msat: u64,
156 /// The CLTV on the final hop of the failed payment path.
157 pub final_cltv_expiry_delta: u32,
160 impl_writeable_tlv_based!(PaymentPathRetry, {
161 (0, payee, required),
162 (2, final_value_msat, required),
163 (4, final_cltv_expiry_delta, required),
166 /// The recipient of a payment.
167 #[derive(Clone, Debug, Hash, PartialEq, Eq)]
169 /// The node id of the payee.
170 pub pubkey: PublicKey,
172 /// Features supported by the payee.
174 /// May be set from the payee's invoice or via [`for_keysend`]. May be `None` if the invoice
175 /// does not contain any features.
177 /// [`for_keysend`]: Self::for_keysend
178 pub features: Option<InvoiceFeatures>,
180 /// Hints for routing to the payee, containing channels connecting the payee to public nodes.
181 pub route_hints: Vec<RouteHint>,
184 impl_writeable_tlv_based!(Payee, {
185 (0, pubkey, required),
186 (2, features, option),
187 (4, route_hints, vec_type),
191 /// Creates a payee with the node id of the given `pubkey`.
192 pub fn new(pubkey: PublicKey) -> Self {
200 /// Creates a payee with the node id of the given `pubkey` to use for keysend payments.
201 pub fn for_keysend(pubkey: PublicKey) -> Self {
202 Self::new(pubkey).with_features(InvoiceFeatures::for_keysend())
205 /// Includes the payee's features.
207 /// (C-not exported) since bindings don't support move semantics
208 pub fn with_features(self, features: InvoiceFeatures) -> Self {
209 Self { features: Some(features), ..self }
212 /// Includes hints for routing to the payee.
214 /// (C-not exported) since bindings don't support move semantics
215 pub fn with_route_hints(self, route_hints: Vec<RouteHint>) -> Self {
216 Self { route_hints, ..self }
220 /// A list of hops along a payment path terminating with a channel to the recipient.
221 #[derive(Clone, Debug, Hash, Eq, PartialEq)]
222 pub struct RouteHint(pub Vec<RouteHintHop>);
225 impl Writeable for RouteHint {
226 fn write<W: ::util::ser::Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
227 (self.0.len() as u64).write(writer)?;
228 for hop in self.0.iter() {
235 impl Readable for RouteHint {
236 fn read<R: io::Read>(reader: &mut R) -> Result<Self, DecodeError> {
237 let hop_count: u64 = Readable::read(reader)?;
238 let mut hops = Vec::with_capacity(cmp::min(hop_count, 16) as usize);
239 for _ in 0..hop_count {
240 hops.push(Readable::read(reader)?);
246 /// A channel descriptor for a hop along a payment path.
247 #[derive(Clone, Debug, Hash, Eq, PartialEq)]
248 pub struct RouteHintHop {
249 /// The node_id of the non-target end of the route
250 pub src_node_id: PublicKey,
251 /// The short_channel_id of this channel
252 pub short_channel_id: u64,
253 /// The fees which must be paid to use this channel
254 pub fees: RoutingFees,
255 /// The difference in CLTV values between this node and the next node.
256 pub cltv_expiry_delta: u16,
257 /// The minimum value, in msat, which must be relayed to the next hop.
258 pub htlc_minimum_msat: Option<u64>,
259 /// The maximum value in msat available for routing with a single HTLC.
260 pub htlc_maximum_msat: Option<u64>,
263 impl_writeable_tlv_based!(RouteHintHop, {
264 (0, src_node_id, required),
265 (1, htlc_minimum_msat, option),
266 (2, short_channel_id, required),
267 (3, htlc_maximum_msat, option),
269 (6, cltv_expiry_delta, required),
272 #[derive(Eq, PartialEq)]
273 struct RouteGraphNode {
275 lowest_fee_to_peer_through_node: u64,
276 lowest_fee_to_node: u64,
277 // The maximum value a yet-to-be-constructed payment path might flow through this node.
278 // This value is upper-bounded by us by:
279 // - how much is needed for a path being constructed
280 // - how much value can channels following this node (up to the destination) can contribute,
281 // considering their capacity and fees
282 value_contribution_msat: u64,
283 /// The effective htlc_minimum_msat at this hop. If a later hop on the path had a higher HTLC
284 /// minimum, we use it, plus the fees required at each earlier hop to meet it.
285 path_htlc_minimum_msat: u64,
286 /// All penalties incurred from this hop on the way to the destination, as calculated using
288 path_penalty_msat: u64,
291 impl cmp::Ord for RouteGraphNode {
292 fn cmp(&self, other: &RouteGraphNode) -> cmp::Ordering {
293 let other_score = cmp::max(other.lowest_fee_to_peer_through_node, other.path_htlc_minimum_msat)
294 .checked_add(other.path_penalty_msat)
295 .unwrap_or_else(|| u64::max_value());
296 let self_score = cmp::max(self.lowest_fee_to_peer_through_node, self.path_htlc_minimum_msat)
297 .checked_add(self.path_penalty_msat)
298 .unwrap_or_else(|| u64::max_value());
299 other_score.cmp(&self_score).then_with(|| other.node_id.cmp(&self.node_id))
303 impl cmp::PartialOrd for RouteGraphNode {
304 fn partial_cmp(&self, other: &RouteGraphNode) -> Option<cmp::Ordering> {
305 Some(self.cmp(other))
309 struct DummyDirectionalChannelInfo {
310 cltv_expiry_delta: u32,
311 htlc_minimum_msat: u64,
312 htlc_maximum_msat: Option<u64>,
316 /// It's useful to keep track of the hops associated with the fees required to use them,
317 /// so that we can choose cheaper paths (as per Dijkstra's algorithm).
318 /// Fee values should be updated only in the context of the whole path, see update_value_and_recompute_fees.
319 /// These fee values are useful to choose hops as we traverse the graph "payee-to-payer".
320 #[derive(Clone, Debug)]
321 struct PathBuildingHop<'a> {
322 // The RouteHintHop fields which will eventually be used if this hop is used in a final Route.
323 // Note that node_features is calculated separately after our initial graph walk.
325 short_channel_id: u64,
326 channel_features: &'a ChannelFeatures,
328 cltv_expiry_delta: u32,
330 /// Minimal fees required to route to the source node of the current hop via any of its inbound channels.
331 src_lowest_inbound_fees: RoutingFees,
332 /// Fees of the channel used in this hop.
333 channel_fees: RoutingFees,
334 /// All the fees paid *after* this channel on the way to the destination
335 next_hops_fee_msat: u64,
336 /// Fee paid for the use of the current channel (see channel_fees).
337 /// The value will be actually deducted from the counterparty balance on the previous link.
338 hop_use_fee_msat: u64,
339 /// Used to compare channels when choosing the for routing.
340 /// Includes paying for the use of a hop and the following hops, as well as
341 /// an estimated cost of reaching this hop.
342 /// Might get stale when fees are recomputed. Primarily for internal use.
344 /// This is useful for update_value_and_recompute_fees to make sure
345 /// we don't fall below the minimum. Should not be updated manually and
346 /// generally should not be accessed.
347 htlc_minimum_msat: u64,
348 /// A mirror of the same field in RouteGraphNode. Note that this is only used during the graph
349 /// walk and may be invalid thereafter.
350 path_htlc_minimum_msat: u64,
351 /// All penalties incurred from this channel on the way to the destination, as calculated using
353 path_penalty_msat: u64,
354 /// If we've already processed a node as the best node, we shouldn't process it again. Normally
355 /// we'd just ignore it if we did as all channels would have a higher new fee, but because we
356 /// may decrease the amounts in use as we walk the graph, the actual calculated fee may
357 /// decrease as well. Thus, we have to explicitly track which nodes have been processed and
358 /// avoid processing them again.
360 #[cfg(any(test, feature = "fuzztarget"))]
361 // In tests, we apply further sanity checks on cases where we skip nodes we already processed
362 // to ensure it is specifically in cases where the fee has gone down because of a decrease in
363 // value_contribution_msat, which requires tracking it here. See comments below where it is
364 // used for more info.
365 value_contribution_msat: u64,
368 // Instantiated with a list of hops with correct data in them collected during path finding,
369 // an instance of this struct should be further modified only via given methods.
371 struct PaymentPath<'a> {
372 hops: Vec<(PathBuildingHop<'a>, NodeFeatures)>,
375 impl<'a> PaymentPath<'a> {
376 // TODO: Add a value_msat field to PaymentPath and use it instead of this function.
377 fn get_value_msat(&self) -> u64 {
378 self.hops.last().unwrap().0.fee_msat
381 fn get_total_fee_paid_msat(&self) -> u64 {
382 if self.hops.len() < 1 {
386 // Can't use next_hops_fee_msat because it gets outdated.
387 for (i, (hop, _)) in self.hops.iter().enumerate() {
388 if i != self.hops.len() - 1 {
389 result += hop.fee_msat;
395 // If the amount transferred by the path is updated, the fees should be adjusted. Any other way
396 // to change fees may result in an inconsistency.
398 // Sometimes we call this function right after constructing a path which is inconsistent in
399 // that it the value being transferred has decreased while we were doing path finding, leading
400 // to the fees being paid not lining up with the actual limits.
402 // Note that this function is not aware of the available_liquidity limit, and thus does not
403 // support increasing the value being transferred.
404 fn update_value_and_recompute_fees(&mut self, value_msat: u64) {
405 assert!(value_msat <= self.hops.last().unwrap().0.fee_msat);
407 let mut total_fee_paid_msat = 0 as u64;
408 for i in (0..self.hops.len()).rev() {
409 let last_hop = i == self.hops.len() - 1;
411 // For non-last-hop, this value will represent the fees paid on the current hop. It
412 // will consist of the fees for the use of the next hop, and extra fees to match
413 // htlc_minimum_msat of the current channel. Last hop is handled separately.
414 let mut cur_hop_fees_msat = 0;
416 cur_hop_fees_msat = self.hops.get(i + 1).unwrap().0.hop_use_fee_msat;
419 let mut cur_hop = &mut self.hops.get_mut(i).unwrap().0;
420 cur_hop.next_hops_fee_msat = total_fee_paid_msat;
421 // Overpay in fees if we can't save these funds due to htlc_minimum_msat.
422 // We try to account for htlc_minimum_msat in scoring (add_entry!), so that nodes don't
423 // set it too high just to maliciously take more fees by exploiting this
424 // match htlc_minimum_msat logic.
425 let mut cur_hop_transferred_amount_msat = total_fee_paid_msat + value_msat;
426 if let Some(extra_fees_msat) = cur_hop.htlc_minimum_msat.checked_sub(cur_hop_transferred_amount_msat) {
427 // Note that there is a risk that *previous hops* (those closer to us, as we go
428 // payee->our_node here) would exceed their htlc_maximum_msat or available balance.
430 // This might make us end up with a broken route, although this should be super-rare
431 // in practice, both because of how healthy channels look like, and how we pick
432 // channels in add_entry.
433 // Also, this can't be exploited more heavily than *announce a free path and fail
435 cur_hop_transferred_amount_msat += extra_fees_msat;
436 total_fee_paid_msat += extra_fees_msat;
437 cur_hop_fees_msat += extra_fees_msat;
441 // Final hop is a special case: it usually has just value_msat (by design), but also
442 // it still could overpay for the htlc_minimum_msat.
443 cur_hop.fee_msat = cur_hop_transferred_amount_msat;
445 // Propagate updated fees for the use of the channels to one hop back, where they
446 // will be actually paid (fee_msat). The last hop is handled above separately.
447 cur_hop.fee_msat = cur_hop_fees_msat;
450 // Fee for the use of the current hop which will be deducted on the previous hop.
451 // Irrelevant for the first hop, as it doesn't have the previous hop, and the use of
452 // this channel is free for us.
454 if let Some(new_fee) = compute_fees(cur_hop_transferred_amount_msat, cur_hop.channel_fees) {
455 cur_hop.hop_use_fee_msat = new_fee;
456 total_fee_paid_msat += new_fee;
458 // It should not be possible because this function is called only to reduce the
459 // value. In that case, compute_fee was already called with the same fees for
460 // larger amount and there was no overflow.
468 fn compute_fees(amount_msat: u64, channel_fees: RoutingFees) -> Option<u64> {
469 let proportional_fee_millions =
470 amount_msat.checked_mul(channel_fees.proportional_millionths as u64);
471 if let Some(new_fee) = proportional_fee_millions.and_then(|part| {
472 (channel_fees.base_msat as u64).checked_add(part / 1_000_000) }) {
476 // This function may be (indirectly) called without any verification,
477 // with channel_fees provided by a caller. We should handle it gracefully.
482 /// Gets a keysend route from us (payer) to the given target node (payee). This is needed because
483 /// keysend payments do not have an invoice from which to pull the payee's supported features, which
484 /// makes it tricky to otherwise supply the `payee` parameter of `get_route`.
485 pub fn get_keysend_route<L: Deref, S: routing::Score>(
486 our_node_pubkey: &PublicKey, network: &NetworkGraph, payee: &PublicKey,
487 first_hops: Option<&[&ChannelDetails]>, last_hops: &[&RouteHint], final_value_msat: u64,
488 final_cltv_expiry_delta: u32, logger: L, scorer: &S
489 ) -> Result<Route, LightningError>
490 where L::Target: Logger {
491 let route_hints = last_hops.iter().map(|hint| (*hint).clone()).collect();
492 let payee = Payee::for_keysend(*payee).with_route_hints(route_hints);
494 our_node_pubkey, &payee, network, first_hops, final_value_msat, final_cltv_expiry_delta,
499 /// Gets a route suitable for retrying a failed payment path.
501 /// Used to re-compute a [`Route`] when handling a [`Event::PaymentPathFailed`]. Any adjustments to
502 /// the [`NetworkGraph`] and channel scores should be made prior to calling this function.
504 /// [`Event::PaymentPathFailed`]: crate::util::events::Event::PaymentPathFailed
505 pub fn get_retry_route<L: Deref, S: routing::Score>(
506 our_node_pubkey: &PublicKey, retry: &PaymentPathRetry, network: &NetworkGraph,
507 first_hops: Option<&[&ChannelDetails]>, logger: L, scorer: &S
508 ) -> Result<Route, LightningError>
509 where L::Target: Logger {
511 our_node_pubkey, &retry.payee, network, first_hops, retry.final_value_msat,
512 retry.final_cltv_expiry_delta, logger, scorer
516 /// Gets a route from us (payer) to the given target node (payee).
518 /// If the payee provided features in their invoice, they should be provided via `payee`. Without
519 /// this, MPP will only be used if the payee's features are available in the network graph.
521 /// Private routing paths between a public node and the target may be included in `payee`.
523 /// If some channels aren't announced, it may be useful to fill in a first_hops with the
524 /// results from a local ChannelManager::list_usable_channels() call. If it is filled in, our
525 /// view of our local channels (from net_graph_msg_handler) will be ignored, and only those
526 /// in first_hops will be used.
528 /// Panics if first_hops contains channels without short_channel_ids
529 /// (ChannelManager::list_usable_channels will never include such channels).
531 /// The fees on channels from us to next-hops are ignored (as they are assumed to all be
532 /// equal), however the enabled/disabled bit on such channels as well as the
533 /// htlc_minimum_msat/htlc_maximum_msat *are* checked as they may change based on the receiving node.
534 pub fn get_route<L: Deref, S: routing::Score>(
535 our_node_pubkey: &PublicKey, payee: &Payee, network: &NetworkGraph,
536 first_hops: Option<&[&ChannelDetails]>, final_value_msat: u64, final_cltv_expiry_delta: u32,
537 logger: L, scorer: &S
538 ) -> Result<Route, LightningError>
539 where L::Target: Logger {
540 let payee_node_id = NodeId::from_pubkey(&payee.pubkey);
541 let our_node_id = NodeId::from_pubkey(&our_node_pubkey);
543 if payee_node_id == our_node_id {
544 return Err(LightningError{err: "Cannot generate a route to ourselves".to_owned(), action: ErrorAction::IgnoreError});
547 if final_value_msat > MAX_VALUE_MSAT {
548 return Err(LightningError{err: "Cannot generate a route of more value than all existing satoshis".to_owned(), action: ErrorAction::IgnoreError});
551 if final_value_msat == 0 {
552 return Err(LightningError{err: "Cannot send a payment of 0 msat".to_owned(), action: ErrorAction::IgnoreError});
555 for route in payee.route_hints.iter() {
556 for hop in &route.0 {
557 if hop.src_node_id == payee.pubkey {
558 return Err(LightningError{err: "Route hint cannot have the payee as the source.".to_owned(), action: ErrorAction::IgnoreError});
563 // The general routing idea is the following:
564 // 1. Fill first/last hops communicated by the caller.
565 // 2. Attempt to construct a path from payer to payee for transferring
566 // any ~sufficient (described later) value.
567 // If succeed, remember which channels were used and how much liquidity they have available,
568 // so that future paths don't rely on the same liquidity.
569 // 3. Prooceed to the next step if:
570 // - we hit the recommended target value;
571 // - OR if we could not construct a new path. Any next attempt will fail too.
572 // Otherwise, repeat step 2.
573 // 4. See if we managed to collect paths which aggregately are able to transfer target value
574 // (not recommended value). If yes, proceed. If not, fail routing.
575 // 5. Randomly combine paths into routes having enough to fulfill the payment. (TODO: knapsack)
576 // 6. Of all the found paths, select only those with the lowest total fee.
577 // 7. The last path in every selected route is likely to be more than we need.
578 // Reduce its value-to-transfer and recompute fees.
579 // 8. Choose the best route by the lowest total fee.
581 // As for the actual search algorithm,
582 // we do a payee-to-payer pseudo-Dijkstra's sorting by each node's distance from the payee
583 // plus the minimum per-HTLC fee to get from it to another node (aka "shitty pseudo-A*").
585 // We are not a faithful Dijkstra's implementation because we can change values which impact
586 // earlier nodes while processing later nodes. Specifically, if we reach a channel with a lower
587 // liquidity limit (via htlc_maximum_msat, on-chain capacity or assumed liquidity limits) then
588 // the value we are currently attempting to send over a path, we simply reduce the value being
589 // sent along the path for any hops after that channel. This may imply that later fees (which
590 // we've already tabulated) are lower because a smaller value is passing through the channels
591 // (and the proportional fee is thus lower). There isn't a trivial way to recalculate the
592 // channels which were selected earlier (and which may still be used for other paths without a
593 // lower liquidity limit), so we simply accept that some liquidity-limited paths may be
596 // One potentially problematic case for this algorithm would be if there are many
597 // liquidity-limited paths which are liquidity-limited near the destination (ie early in our
598 // graph walking), we may never find a path which is not liquidity-limited and has lower
599 // proportional fee (and only lower absolute fee when considering the ultimate value sent).
600 // Because we only consider paths with at least 5% of the total value being sent, the damage
601 // from such a case should be limited, however this could be further reduced in the future by
602 // calculating fees on the amount we wish to route over a path, ie ignoring the liquidity
603 // limits for the purposes of fee calculation.
605 // Alternatively, we could store more detailed path information in the heap (targets, below)
606 // and index the best-path map (dist, below) by node *and* HTLC limits, however that would blow
607 // up the runtime significantly both algorithmically (as we'd traverse nodes multiple times)
608 // and practically (as we would need to store dynamically-allocated path information in heap
609 // objects, increasing malloc traffic and indirect memory access significantly). Further, the
610 // results of such an algorithm would likely be biased towards lower-value paths.
612 // Further, we could return to a faithful Dijkstra's algorithm by rejecting paths with limits
613 // outside of our current search value, running a path search more times to gather candidate
614 // paths at different values. While this may be acceptable, further path searches may increase
615 // runtime for little gain. Specifically, the current algorithm rather efficiently explores the
616 // graph for candidate paths, calculating the maximum value which can realistically be sent at
617 // the same time, remaining generic across different payment values.
619 // TODO: There are a few tweaks we could do, including possibly pre-calculating more stuff
620 // to use as the A* heuristic beyond just the cost to get one node further than the current
623 let network_graph = network.read_only();
624 let network_channels = network_graph.channels();
625 let network_nodes = network_graph.nodes();
626 let dummy_directional_info = DummyDirectionalChannelInfo { // used for first_hops routes
627 cltv_expiry_delta: 0,
628 htlc_minimum_msat: 0,
629 htlc_maximum_msat: None,
632 proportional_millionths: 0,
636 // Allow MPP only if we have a features set from somewhere that indicates the payee supports
637 // it. If the payee supports it they're supposed to include it in the invoice, so that should
639 let allow_mpp = if let Some(features) = &payee.features {
640 features.supports_basic_mpp()
641 } else if let Some(node) = network_nodes.get(&payee_node_id) {
642 if let Some(node_info) = node.announcement_info.as_ref() {
643 node_info.features.supports_basic_mpp()
646 log_trace!(logger, "Searching for a route from payer {} to payee {} {} MPP", our_node_pubkey,
647 payee.pubkey, if allow_mpp { "with" } else { "without" });
650 // Prepare the data we'll use for payee-to-payer search by
651 // inserting first hops suggested by the caller as targets.
652 // Our search will then attempt to reach them while traversing from the payee node.
653 let mut first_hop_targets: HashMap<_, Vec<(_, ChannelFeatures, _, NodeFeatures)>> =
654 HashMap::with_capacity(if first_hops.is_some() { first_hops.as_ref().unwrap().len() } else { 0 });
655 if let Some(hops) = first_hops {
657 let short_channel_id = chan.short_channel_id.expect("first_hops should be filled in with usable channels, not pending ones");
658 if chan.counterparty.node_id == *our_node_pubkey {
659 return Err(LightningError{err: "First hop cannot have our_node_pubkey as a destination.".to_owned(), action: ErrorAction::IgnoreError});
661 first_hop_targets.entry(NodeId::from_pubkey(&chan.counterparty.node_id)).or_insert(Vec::new())
662 .push((short_channel_id, chan.counterparty.features.to_context(), chan.outbound_capacity_msat, chan.counterparty.features.to_context()));
664 if first_hop_targets.is_empty() {
665 return Err(LightningError{err: "Cannot route when there are no outbound routes away from us".to_owned(), action: ErrorAction::IgnoreError});
669 let empty_channel_features = ChannelFeatures::empty();
671 // The main heap containing all candidate next-hops sorted by their score (max(A* fee,
672 // htlc_minimum)). Ideally this would be a heap which allowed cheap score reduction instead of
673 // adding duplicate entries when we find a better path to a given node.
674 let mut targets = BinaryHeap::new();
676 // Map from node_id to information about the best current path to that node, including feerate
678 let mut dist = HashMap::with_capacity(network_nodes.len());
680 // During routing, if we ignore a path due to an htlc_minimum_msat limit, we set this,
681 // indicating that we may wish to try again with a higher value, potentially paying to meet an
682 // htlc_minimum with extra fees while still finding a cheaper path.
683 let mut hit_minimum_limit;
685 // When arranging a route, we select multiple paths so that we can make a multi-path payment.
686 // We start with a path_value of the exact amount we want, and if that generates a route we may
687 // return it immediately. Otherwise, we don't stop searching for paths until we have 3x the
688 // amount we want in total across paths, selecting the best subset at the end.
689 const ROUTE_CAPACITY_PROVISION_FACTOR: u64 = 3;
690 let recommended_value_msat = final_value_msat * ROUTE_CAPACITY_PROVISION_FACTOR as u64;
691 let mut path_value_msat = final_value_msat;
693 // We don't want multiple paths (as per MPP) share liquidity of the same channels.
694 // This map allows paths to be aware of the channel use by other paths in the same call.
695 // This would help to make a better path finding decisions and not "overbook" channels.
696 // It is unaware of the directions (except for `outbound_capacity_msat` in `first_hops`).
697 let mut bookkeeped_channels_liquidity_available_msat = HashMap::with_capacity(network_nodes.len());
699 // Keeping track of how much value we already collected across other paths. Helps to decide:
700 // - how much a new path should be transferring (upper bound);
701 // - whether a channel should be disregarded because
702 // it's available liquidity is too small comparing to how much more we need to collect;
703 // - when we want to stop looking for new paths.
704 let mut already_collected_value_msat = 0;
706 log_trace!(logger, "Building path from {} (payee) to {} (us/payer) for value {} msat.", payee.pubkey, our_node_pubkey, final_value_msat);
708 macro_rules! add_entry {
709 // Adds entry which goes from $src_node_id to $dest_node_id
710 // over the channel with id $chan_id with fees described in
711 // $directional_info.
712 // $next_hops_fee_msat represents the fees paid for using all the channel *after* this one,
713 // since that value has to be transferred over this channel.
714 // Returns whether this channel caused an update to `targets`.
715 ( $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,
716 $next_hops_value_contribution: expr, $next_hops_path_htlc_minimum_msat: expr, $next_hops_path_penalty_msat: expr ) => { {
717 // We "return" whether we updated the path at the end, via this:
718 let mut did_add_update_path_to_src_node = false;
719 // Channels to self should not be used. This is more of belt-and-suspenders, because in
720 // practice these cases should be caught earlier:
721 // - for regular channels at channel announcement (TODO)
722 // - for first and last hops early in get_route
723 if $src_node_id != $dest_node_id.clone() {
724 let available_liquidity_msat = bookkeeped_channels_liquidity_available_msat.entry($chan_id.clone()).or_insert_with(|| {
725 let mut initial_liquidity_available_msat = None;
726 if let Some(capacity_sats) = $capacity_sats {
727 initial_liquidity_available_msat = Some(capacity_sats * 1000);
730 if let Some(htlc_maximum_msat) = $directional_info.htlc_maximum_msat {
731 if let Some(available_msat) = initial_liquidity_available_msat {
732 initial_liquidity_available_msat = Some(cmp::min(available_msat, htlc_maximum_msat));
734 initial_liquidity_available_msat = Some(htlc_maximum_msat);
738 match initial_liquidity_available_msat {
739 Some(available_msat) => available_msat,
740 // We assume channels with unknown balance have
741 // a capacity of 0.0025 BTC (or 250_000 sats).
742 None => 250_000 * 1000
746 // It is tricky to substract $next_hops_fee_msat from available liquidity here.
747 // It may be misleading because we might later choose to reduce the value transferred
748 // over these channels, and the channel which was insufficient might become sufficient.
749 // Worst case: we drop a good channel here because it can't cover the high following
750 // fees caused by one expensive channel, but then this channel could have been used
751 // if the amount being transferred over this path is lower.
752 // We do this for now, but this is a subject for removal.
753 if let Some(available_value_contribution_msat) = available_liquidity_msat.checked_sub($next_hops_fee_msat) {
755 // Routing Fragmentation Mitigation heuristic:
757 // Routing fragmentation across many payment paths increases the overall routing
758 // fees as you have irreducible routing fees per-link used (`fee_base_msat`).
759 // Taking too many smaller paths also increases the chance of payment failure.
760 // Thus to avoid this effect, we require from our collected links to provide
761 // at least a minimal contribution to the recommended value yet-to-be-fulfilled.
763 // This requirement is currently 5% of the remaining-to-be-collected value.
764 // This means as we successfully advance in our collection,
765 // the absolute liquidity contribution is lowered,
766 // thus increasing the number of potential channels to be selected.
768 // Derive the minimal liquidity contribution with a ratio of 20 (5%, rounded up)
769 // or 100% if we're not allowed to do multipath payments.
770 let minimal_value_contribution_msat: u64 = if allow_mpp {
771 (recommended_value_msat - already_collected_value_msat + 19) / 20
775 // Verify the liquidity offered by this channel complies to the minimal contribution.
776 let contributes_sufficient_value = available_value_contribution_msat >= minimal_value_contribution_msat;
778 let value_contribution_msat = cmp::min(available_value_contribution_msat, $next_hops_value_contribution);
779 // Includes paying fees for the use of the following channels.
780 let amount_to_transfer_over_msat: u64 = match value_contribution_msat.checked_add($next_hops_fee_msat) {
781 Some(result) => result,
782 // Can't overflow due to how the values were computed right above.
783 None => unreachable!(),
785 #[allow(unused_comparisons)] // $next_hops_path_htlc_minimum_msat is 0 in some calls so rustc complains
786 let over_path_minimum_msat = amount_to_transfer_over_msat >= $directional_info.htlc_minimum_msat &&
787 amount_to_transfer_over_msat >= $next_hops_path_htlc_minimum_msat;
789 // If HTLC minimum is larger than the amount we're going to transfer, we shouldn't
790 // bother considering this channel.
791 // Since we're choosing amount_to_transfer_over_msat as maximum possible, it can
792 // be only reduced later (not increased), so this channel should just be skipped
793 // as not sufficient.
794 if !over_path_minimum_msat {
795 hit_minimum_limit = true;
796 } else if contributes_sufficient_value {
797 // Note that low contribution here (limited by available_liquidity_msat)
798 // might violate htlc_minimum_msat on the hops which are next along the
799 // payment path (upstream to the payee). To avoid that, we recompute path
800 // path fees knowing the final path contribution after constructing it.
801 let path_htlc_minimum_msat = compute_fees($next_hops_path_htlc_minimum_msat, $directional_info.fees)
802 .and_then(|fee_msat| fee_msat.checked_add($next_hops_path_htlc_minimum_msat))
803 .map(|fee_msat| cmp::max(fee_msat, $directional_info.htlc_minimum_msat))
804 .unwrap_or_else(|| u64::max_value());
805 let hm_entry = dist.entry($src_node_id);
806 let old_entry = hm_entry.or_insert_with(|| {
807 // If there was previously no known way to access
808 // the source node (recall it goes payee-to-payer) of $chan_id, first add
809 // a semi-dummy record just to compute the fees to reach the source node.
810 // This will affect our decision on selecting $chan_id
811 // as a way to reach the $dest_node_id.
812 let mut fee_base_msat = u32::max_value();
813 let mut fee_proportional_millionths = u32::max_value();
814 if let Some(Some(fees)) = network_nodes.get(&$src_node_id).map(|node| node.lowest_inbound_channel_fees) {
815 fee_base_msat = fees.base_msat;
816 fee_proportional_millionths = fees.proportional_millionths;
819 node_id: $dest_node_id.clone(),
821 channel_features: $chan_features,
823 cltv_expiry_delta: 0,
824 src_lowest_inbound_fees: RoutingFees {
825 base_msat: fee_base_msat,
826 proportional_millionths: fee_proportional_millionths,
828 channel_fees: $directional_info.fees,
829 next_hops_fee_msat: u64::max_value(),
830 hop_use_fee_msat: u64::max_value(),
831 total_fee_msat: u64::max_value(),
832 htlc_minimum_msat: $directional_info.htlc_minimum_msat,
833 path_htlc_minimum_msat,
834 path_penalty_msat: u64::max_value(),
835 was_processed: false,
836 #[cfg(any(test, feature = "fuzztarget"))]
837 value_contribution_msat,
841 #[allow(unused_mut)] // We only use the mut in cfg(test)
842 let mut should_process = !old_entry.was_processed;
843 #[cfg(any(test, feature = "fuzztarget"))]
845 // In test/fuzzing builds, we do extra checks to make sure the skipping
846 // of already-seen nodes only happens in cases we expect (see below).
847 if !should_process { should_process = true; }
851 let mut hop_use_fee_msat = 0;
852 let mut total_fee_msat = $next_hops_fee_msat;
854 // Ignore hop_use_fee_msat for channel-from-us as we assume all channels-from-us
855 // will have the same effective-fee
856 if $src_node_id != our_node_id {
857 match compute_fees(amount_to_transfer_over_msat, $directional_info.fees) {
858 // max_value means we'll always fail
859 // the old_entry.total_fee_msat > total_fee_msat check
860 None => total_fee_msat = u64::max_value(),
862 hop_use_fee_msat = fee_msat;
863 total_fee_msat += hop_use_fee_msat;
864 // When calculating the lowest inbound fees to a node, we
865 // calculate fees here not based on the actual value we think
866 // will flow over this channel, but on the minimum value that
867 // we'll accept flowing over it. The minimum accepted value
868 // is a constant through each path collection run, ensuring
869 // consistent basis. Otherwise we may later find a
870 // different path to the source node that is more expensive,
871 // but which we consider to be cheaper because we are capacity
872 // constrained and the relative fee becomes lower.
873 match compute_fees(minimal_value_contribution_msat, old_entry.src_lowest_inbound_fees)
874 .map(|a| a.checked_add(total_fee_msat)) {
879 total_fee_msat = u64::max_value();
886 let path_penalty_msat = $next_hops_path_penalty_msat
887 .checked_add(scorer.channel_penalty_msat($chan_id.clone(), &$src_node_id, &$dest_node_id))
888 .unwrap_or_else(|| u64::max_value());
889 let new_graph_node = RouteGraphNode {
890 node_id: $src_node_id,
891 lowest_fee_to_peer_through_node: total_fee_msat,
892 lowest_fee_to_node: $next_hops_fee_msat as u64 + hop_use_fee_msat,
893 value_contribution_msat: value_contribution_msat,
894 path_htlc_minimum_msat,
898 // Update the way of reaching $src_node_id with the given $chan_id (from $dest_node_id),
899 // if this way is cheaper than the already known
900 // (considering the cost to "reach" this channel from the route destination,
901 // the cost of using this channel,
902 // and the cost of routing to the source node of this channel).
903 // Also, consider that htlc_minimum_msat_difference, because we might end up
904 // paying it. Consider the following exploit:
905 // we use 2 paths to transfer 1.5 BTC. One of them is 0-fee normal 1 BTC path,
906 // and for the other one we picked a 1sat-fee path with htlc_minimum_msat of
907 // 1 BTC. Now, since the latter is more expensive, we gonna try to cut it
908 // by 0.5 BTC, but then match htlc_minimum_msat by paying a fee of 0.5 BTC
910 // Ideally the scoring could be smarter (e.g. 0.5*htlc_minimum_msat here),
911 // but it may require additional tracking - we don't want to double-count
912 // the fees included in $next_hops_path_htlc_minimum_msat, but also
913 // can't use something that may decrease on future hops.
914 let old_cost = cmp::max(old_entry.total_fee_msat, old_entry.path_htlc_minimum_msat)
915 .checked_add(old_entry.path_penalty_msat)
916 .unwrap_or_else(|| u64::max_value());
917 let new_cost = cmp::max(total_fee_msat, path_htlc_minimum_msat)
918 .checked_add(path_penalty_msat)
919 .unwrap_or_else(|| u64::max_value());
921 if !old_entry.was_processed && new_cost < old_cost {
922 targets.push(new_graph_node);
923 old_entry.next_hops_fee_msat = $next_hops_fee_msat;
924 old_entry.hop_use_fee_msat = hop_use_fee_msat;
925 old_entry.total_fee_msat = total_fee_msat;
926 old_entry.node_id = $dest_node_id.clone();
927 old_entry.short_channel_id = $chan_id.clone();
928 old_entry.channel_features = $chan_features;
929 old_entry.fee_msat = 0; // This value will be later filled with hop_use_fee_msat of the following channel
930 old_entry.cltv_expiry_delta = $directional_info.cltv_expiry_delta as u32;
931 old_entry.channel_fees = $directional_info.fees;
932 old_entry.htlc_minimum_msat = $directional_info.htlc_minimum_msat;
933 old_entry.path_htlc_minimum_msat = path_htlc_minimum_msat;
934 old_entry.path_penalty_msat = path_penalty_msat;
935 #[cfg(any(test, feature = "fuzztarget"))]
937 old_entry.value_contribution_msat = value_contribution_msat;
939 did_add_update_path_to_src_node = true;
940 } else if old_entry.was_processed && new_cost < old_cost {
941 #[cfg(any(test, feature = "fuzztarget"))]
943 // If we're skipping processing a node which was previously
944 // processed even though we found another path to it with a
945 // cheaper fee, check that it was because the second path we
946 // found (which we are processing now) has a lower value
947 // contribution due to an HTLC minimum limit.
949 // e.g. take a graph with two paths from node 1 to node 2, one
950 // through channel A, and one through channel B. Channel A and
951 // B are both in the to-process heap, with their scores set by
952 // a higher htlc_minimum than fee.
953 // Channel A is processed first, and the channels onwards from
954 // node 1 are added to the to-process heap. Thereafter, we pop
955 // Channel B off of the heap, note that it has a much more
956 // restrictive htlc_maximum_msat, and recalculate the fees for
957 // all of node 1's channels using the new, reduced, amount.
959 // This would be bogus - we'd be selecting a higher-fee path
960 // with a lower htlc_maximum_msat instead of the one we'd
961 // already decided to use.
962 debug_assert!(path_htlc_minimum_msat < old_entry.path_htlc_minimum_msat);
964 value_contribution_msat + path_penalty_msat <
965 old_entry.value_contribution_msat + old_entry.path_penalty_msat
973 did_add_update_path_to_src_node
977 let empty_node_features = NodeFeatures::empty();
978 // Find ways (channels with destination) to reach a given node and store them
979 // in the corresponding data structures (routing graph etc).
980 // $fee_to_target_msat represents how much it costs to reach to this node from the payee,
981 // meaning how much will be paid in fees after this node (to the best of our knowledge).
982 // This data can later be helpful to optimize routing (pay lower fees).
983 macro_rules! add_entries_to_cheapest_to_target_node {
984 ( $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 ) => {
985 let skip_node = if let Some(elem) = dist.get_mut(&$node_id) {
986 let was_processed = elem.was_processed;
987 elem.was_processed = true;
990 // Entries are added to dist in add_entry!() when there is a channel from a node.
991 // Because there are no channels from payee, it will not have a dist entry at this point.
992 // If we're processing any other node, it is always be the result of a channel from it.
993 assert_eq!($node_id, payee_node_id);
998 if let Some(first_channels) = first_hop_targets.get(&$node_id) {
999 for (ref first_hop, ref features, ref outbound_capacity_msat, _) in first_channels {
1000 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);
1004 let features = if let Some(node_info) = $node.announcement_info.as_ref() {
1007 &empty_node_features
1010 if !features.requires_unknown_bits() {
1011 for chan_id in $node.channels.iter() {
1012 let chan = network_channels.get(chan_id).unwrap();
1013 if !chan.features.requires_unknown_bits() {
1014 if chan.node_one == $node_id {
1015 // ie $node is one, ie next hop in A* is two, via the two_to_one channel
1016 if first_hops.is_none() || chan.node_two != our_node_id {
1017 if let Some(two_to_one) = chan.two_to_one.as_ref() {
1018 if two_to_one.enabled {
1019 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);
1024 if first_hops.is_none() || chan.node_one != our_node_id{
1025 if let Some(one_to_two) = chan.one_to_two.as_ref() {
1026 if one_to_two.enabled {
1027 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);
1039 let mut payment_paths = Vec::<PaymentPath>::new();
1041 // TODO: diversify by nodes (so that all paths aren't doomed if one node is offline).
1042 'paths_collection: loop {
1043 // For every new path, start from scratch, except
1044 // bookkeeped_channels_liquidity_available_msat, which will improve
1045 // the further iterations of path finding. Also don't erase first_hop_targets.
1048 hit_minimum_limit = false;
1050 // If first hop is a private channel and the only way to reach the payee, this is the only
1051 // place where it could be added.
1052 if let Some(first_channels) = first_hop_targets.get(&payee_node_id) {
1053 for (ref first_hop, ref features, ref outbound_capacity_msat, _) in first_channels {
1054 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);
1055 log_trace!(logger, "{} direct route to payee via SCID {}", if added { "Added" } else { "Skipped" }, first_hop);
1059 // Add the payee as a target, so that the payee-to-payer
1060 // search algorithm knows what to start with.
1061 match network_nodes.get(&payee_node_id) {
1062 // The payee is not in our network graph, so nothing to add here.
1063 // There is still a chance of reaching them via last_hops though,
1064 // so don't yet fail the payment here.
1065 // If not, targets.pop() will not even let us enter the loop in step 2.
1068 add_entries_to_cheapest_to_target_node!(node, payee_node_id, 0, path_value_msat, 0, 0u64);
1073 // If a caller provided us with last hops, add them to routing targets. Since this happens
1074 // earlier than general path finding, they will be somewhat prioritized, although currently
1075 // it matters only if the fees are exactly the same.
1076 for route in payee.route_hints.iter().filter(|route| !route.0.is_empty()) {
1077 let first_hop_in_route = &(route.0)[0];
1078 let have_hop_src_in_graph =
1079 // Only add the hops in this route to our candidate set if either
1080 // we have a direct channel to the first hop or the first hop is
1081 // in the regular network graph.
1082 first_hop_targets.get(&NodeId::from_pubkey(&first_hop_in_route.src_node_id)).is_some() ||
1083 network_nodes.get(&NodeId::from_pubkey(&first_hop_in_route.src_node_id)).is_some();
1084 if have_hop_src_in_graph {
1085 // We start building the path from reverse, i.e., from payee
1086 // to the first RouteHintHop in the path.
1087 let hop_iter = route.0.iter().rev();
1088 let prev_hop_iter = core::iter::once(&payee.pubkey).chain(
1089 route.0.iter().skip(1).rev().map(|hop| &hop.src_node_id));
1090 let mut hop_used = true;
1091 let mut aggregate_next_hops_fee_msat: u64 = 0;
1092 let mut aggregate_next_hops_path_htlc_minimum_msat: u64 = 0;
1093 let mut aggregate_next_hops_path_penalty_msat: u64 = 0;
1095 for (idx, (hop, prev_hop_id)) in hop_iter.zip(prev_hop_iter).enumerate() {
1096 // BOLT 11 doesn't allow inclusion of features for the last hop hints, which
1097 // really sucks, cause we're gonna need that eventually.
1098 let hop_htlc_minimum_msat: u64 = hop.htlc_minimum_msat.unwrap_or(0);
1100 let directional_info = DummyDirectionalChannelInfo {
1101 cltv_expiry_delta: hop.cltv_expiry_delta as u32,
1102 htlc_minimum_msat: hop_htlc_minimum_msat,
1103 htlc_maximum_msat: hop.htlc_maximum_msat,
1107 let reqd_channel_cap = if let Some (val) = final_value_msat.checked_add(match idx {
1109 _ => aggregate_next_hops_fee_msat.checked_add(999).unwrap_or(u64::max_value())
1110 }) { Some( val / 1000 ) } else { break; }; // converting from msat or breaking if max ~ infinity
1112 let src_node_id = NodeId::from_pubkey(&hop.src_node_id);
1113 let dest_node_id = NodeId::from_pubkey(&prev_hop_id);
1114 aggregate_next_hops_path_penalty_msat = aggregate_next_hops_path_penalty_msat
1115 .checked_add(scorer.channel_penalty_msat(hop.short_channel_id, &src_node_id, &dest_node_id))
1116 .unwrap_or_else(|| u64::max_value());
1118 // We assume that the recipient only included route hints for routes which had
1119 // sufficient value to route `final_value_msat`. Note that in the case of "0-value"
1120 // invoices where the invoice does not specify value this may not be the case, but
1121 // better to include the hints than not.
1122 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) {
1123 // If this hop was not used then there is no use checking the preceding hops
1124 // in the RouteHint. We can break by just searching for a direct channel between
1125 // last checked hop and first_hop_targets
1129 // Searching for a direct channel between last checked hop and first_hop_targets
1130 if let Some(first_channels) = first_hop_targets.get(&NodeId::from_pubkey(&prev_hop_id)) {
1131 for (ref first_hop, ref features, ref outbound_capacity_msat, _) in first_channels {
1132 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);
1140 // In the next values of the iterator, the aggregate fees already reflects
1141 // the sum of value sent from payer (final_value_msat) and routing fees
1142 // for the last node in the RouteHint. We need to just add the fees to
1143 // route through the current node so that the preceeding node (next iteration)
1145 let hops_fee = compute_fees(aggregate_next_hops_fee_msat + final_value_msat, hop.fees)
1146 .map_or(None, |inc| inc.checked_add(aggregate_next_hops_fee_msat));
1147 aggregate_next_hops_fee_msat = if let Some(val) = hops_fee { val } else { break; };
1149 let hop_htlc_minimum_msat_inc = if let Some(val) = compute_fees(aggregate_next_hops_path_htlc_minimum_msat, hop.fees) { val } else { break; };
1150 let hops_path_htlc_minimum = aggregate_next_hops_path_htlc_minimum_msat
1151 .checked_add(hop_htlc_minimum_msat_inc);
1152 aggregate_next_hops_path_htlc_minimum_msat = if let Some(val) = hops_path_htlc_minimum { cmp::max(hop_htlc_minimum_msat, val) } else { break; };
1154 if idx == route.0.len() - 1 {
1155 // The last hop in this iterator is the first hop in
1156 // overall RouteHint.
1157 // If this hop connects to a node with which we have a direct channel,
1158 // ignore the network graph and, if the last hop was added, add our
1159 // direct channel to the candidate set.
1161 // Note that we *must* check if the last hop was added as `add_entry`
1162 // always assumes that the third argument is a node to which we have a
1164 if let Some(first_channels) = first_hop_targets.get(&NodeId::from_pubkey(&hop.src_node_id)) {
1165 for (ref first_hop, ref features, ref outbound_capacity_msat, _) in first_channels {
1166 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);
1174 log_trace!(logger, "Starting main path collection loop with {} nodes pre-filled from first/last hops.", targets.len());
1176 // At this point, targets are filled with the data from first and
1177 // last hops communicated by the caller, and the payment receiver.
1178 let mut found_new_path = false;
1181 // If this loop terminates due the exhaustion of targets, two situations are possible:
1182 // - not enough outgoing liquidity:
1183 // 0 < already_collected_value_msat < final_value_msat
1184 // - enough outgoing liquidity:
1185 // final_value_msat <= already_collected_value_msat < recommended_value_msat
1186 // Both these cases (and other cases except reaching recommended_value_msat) mean that
1187 // paths_collection will be stopped because found_new_path==false.
1188 // This is not necessarily a routing failure.
1189 'path_construction: while let Some(RouteGraphNode { node_id, lowest_fee_to_node, value_contribution_msat, path_htlc_minimum_msat, path_penalty_msat, .. }) = targets.pop() {
1191 // Since we're going payee-to-payer, hitting our node as a target means we should stop
1192 // traversing the graph and arrange the path out of what we found.
1193 if node_id == our_node_id {
1194 let mut new_entry = dist.remove(&our_node_id).unwrap();
1195 let mut ordered_hops = vec!((new_entry.clone(), NodeFeatures::empty()));
1198 let mut features_set = false;
1199 if let Some(first_channels) = first_hop_targets.get(&ordered_hops.last().unwrap().0.node_id) {
1200 for (scid, _, _, ref features) in first_channels {
1201 if *scid == ordered_hops.last().unwrap().0.short_channel_id {
1202 ordered_hops.last_mut().unwrap().1 = features.clone();
1203 features_set = true;
1209 if let Some(node) = network_nodes.get(&ordered_hops.last().unwrap().0.node_id) {
1210 if let Some(node_info) = node.announcement_info.as_ref() {
1211 ordered_hops.last_mut().unwrap().1 = node_info.features.clone();
1213 ordered_hops.last_mut().unwrap().1 = NodeFeatures::empty();
1216 // We should be able to fill in features for everything except the last
1217 // hop, if the last hop was provided via a BOLT 11 invoice (though we
1218 // should be able to extend it further as BOLT 11 does have feature
1219 // flags for the last hop node itself).
1220 assert!(ordered_hops.last().unwrap().0.node_id == payee_node_id);
1224 // Means we succesfully traversed from the payer to the payee, now
1225 // save this path for the payment route. Also, update the liquidity
1226 // remaining on the used hops, so that we take them into account
1227 // while looking for more paths.
1228 if ordered_hops.last().unwrap().0.node_id == payee_node_id {
1232 new_entry = match dist.remove(&ordered_hops.last().unwrap().0.node_id) {
1233 Some(payment_hop) => payment_hop,
1234 // We can't arrive at None because, if we ever add an entry to targets,
1235 // we also fill in the entry in dist (see add_entry!).
1236 None => unreachable!(),
1238 // We "propagate" the fees one hop backward (topologically) here,
1239 // so that fees paid for a HTLC forwarding on the current channel are
1240 // associated with the previous channel (where they will be subtracted).
1241 ordered_hops.last_mut().unwrap().0.fee_msat = new_entry.hop_use_fee_msat;
1242 ordered_hops.last_mut().unwrap().0.cltv_expiry_delta = new_entry.cltv_expiry_delta;
1243 ordered_hops.push((new_entry.clone(), NodeFeatures::empty()));
1245 ordered_hops.last_mut().unwrap().0.fee_msat = value_contribution_msat;
1246 ordered_hops.last_mut().unwrap().0.hop_use_fee_msat = 0;
1247 ordered_hops.last_mut().unwrap().0.cltv_expiry_delta = final_cltv_expiry_delta;
1249 log_trace!(logger, "Found a path back to us from the target with {} hops contributing up to {} msat: {:?}",
1250 ordered_hops.len(), value_contribution_msat, ordered_hops);
1252 let mut payment_path = PaymentPath {hops: ordered_hops};
1254 // We could have possibly constructed a slightly inconsistent path: since we reduce
1255 // value being transferred along the way, we could have violated htlc_minimum_msat
1256 // on some channels we already passed (assuming dest->source direction). Here, we
1257 // recompute the fees again, so that if that's the case, we match the currently
1258 // underpaid htlc_minimum_msat with fees.
1259 payment_path.update_value_and_recompute_fees(cmp::min(value_contribution_msat, final_value_msat));
1261 // Since a path allows to transfer as much value as
1262 // the smallest channel it has ("bottleneck"), we should recompute
1263 // the fees so sender HTLC don't overpay fees when traversing
1264 // larger channels than the bottleneck. This may happen because
1265 // when we were selecting those channels we were not aware how much value
1266 // this path will transfer, and the relative fee for them
1267 // might have been computed considering a larger value.
1268 // Remember that we used these channels so that we don't rely
1269 // on the same liquidity in future paths.
1270 let mut prevented_redundant_path_selection = false;
1271 for (payment_hop, _) in payment_path.hops.iter() {
1272 let channel_liquidity_available_msat = bookkeeped_channels_liquidity_available_msat.get_mut(&payment_hop.short_channel_id).unwrap();
1273 let mut spent_on_hop_msat = value_contribution_msat;
1274 let next_hops_fee_msat = payment_hop.next_hops_fee_msat;
1275 spent_on_hop_msat += next_hops_fee_msat;
1276 if spent_on_hop_msat == *channel_liquidity_available_msat {
1277 // If this path used all of this channel's available liquidity, we know
1278 // this path will not be selected again in the next loop iteration.
1279 prevented_redundant_path_selection = true;
1281 *channel_liquidity_available_msat -= spent_on_hop_msat;
1283 if !prevented_redundant_path_selection {
1284 // If we weren't capped by hitting a liquidity limit on a channel in the path,
1285 // we'll probably end up picking the same path again on the next iteration.
1286 // Decrease the available liquidity of a hop in the middle of the path.
1287 let victim_scid = payment_path.hops[(payment_path.hops.len() - 1) / 2].0.short_channel_id;
1288 log_trace!(logger, "Disabling channel {} for future path building iterations to avoid duplicates.", victim_scid);
1289 let victim_liquidity = bookkeeped_channels_liquidity_available_msat.get_mut(&victim_scid).unwrap();
1290 *victim_liquidity = 0;
1293 // Track the total amount all our collected paths allow to send so that we:
1294 // - know when to stop looking for more paths
1295 // - know which of the hops are useless considering how much more sats we need
1296 // (contributes_sufficient_value)
1297 already_collected_value_msat += value_contribution_msat;
1299 payment_paths.push(payment_path);
1300 found_new_path = true;
1301 break 'path_construction;
1304 // If we found a path back to the payee, we shouldn't try to process it again. This is
1305 // the equivalent of the `elem.was_processed` check in
1306 // add_entries_to_cheapest_to_target_node!() (see comment there for more info).
1307 if node_id == payee_node_id { continue 'path_construction; }
1309 // Otherwise, since the current target node is not us,
1310 // keep "unrolling" the payment graph from payee to payer by
1311 // finding a way to reach the current target from the payer side.
1312 match network_nodes.get(&node_id) {
1315 add_entries_to_cheapest_to_target_node!(node, node_id, lowest_fee_to_node, value_contribution_msat, path_htlc_minimum_msat, path_penalty_msat);
1321 // If we don't support MPP, no use trying to gather more value ever.
1322 break 'paths_collection;
1326 // Stop either when the recommended value is reached or if no new path was found in this
1328 // In the latter case, making another path finding attempt won't help,
1329 // because we deterministically terminated the search due to low liquidity.
1330 if already_collected_value_msat >= recommended_value_msat || !found_new_path {
1331 log_trace!(logger, "Have now collected {} msat (seeking {} msat) in paths. Last path loop {} a new path.",
1332 already_collected_value_msat, recommended_value_msat, if found_new_path { "found" } else { "did not find" });
1333 break 'paths_collection;
1334 } else if found_new_path && already_collected_value_msat == final_value_msat && payment_paths.len() == 1 {
1335 // Further, if this was our first walk of the graph, and we weren't limited by an
1336 // htlc_minimum_msat, return immediately because this path should suffice. If we were
1337 // limited by an htlc_minimum_msat value, find another path with a higher value,
1338 // potentially allowing us to pay fees to meet the htlc_minimum on the new path while
1339 // still keeping a lower total fee than this path.
1340 if !hit_minimum_limit {
1341 log_trace!(logger, "Collected exactly our payment amount on the first pass, without hitting an htlc_minimum_msat limit, exiting.");
1342 break 'paths_collection;
1344 log_trace!(logger, "Collected our payment amount on the first pass, but running again to collect extra paths with a potentially higher limit.");
1345 path_value_msat = recommended_value_msat;
1350 if payment_paths.len() == 0 {
1351 return Err(LightningError{err: "Failed to find a path to the given destination".to_owned(), action: ErrorAction::IgnoreError});
1354 if already_collected_value_msat < final_value_msat {
1355 return Err(LightningError{err: "Failed to find a sufficient route to the given destination".to_owned(), action: ErrorAction::IgnoreError});
1358 // Sort by total fees and take the best paths.
1359 payment_paths.sort_by_key(|path| path.get_total_fee_paid_msat());
1360 if payment_paths.len() > 50 {
1361 payment_paths.truncate(50);
1364 // Draw multiple sufficient routes by randomly combining the selected paths.
1365 let mut drawn_routes = Vec::new();
1366 for i in 0..payment_paths.len() {
1367 let mut cur_route = Vec::<PaymentPath>::new();
1368 let mut aggregate_route_value_msat = 0;
1371 // TODO: real random shuffle
1372 // Currently just starts with i_th and goes up to i-1_th in a looped way.
1373 let cur_payment_paths = [&payment_paths[i..], &payment_paths[..i]].concat();
1376 for payment_path in cur_payment_paths {
1377 cur_route.push(payment_path.clone());
1378 aggregate_route_value_msat += payment_path.get_value_msat();
1379 if aggregate_route_value_msat > final_value_msat {
1380 // Last path likely overpaid. Substract it from the most expensive
1381 // (in terms of proportional fee) path in this route and recompute fees.
1382 // This might be not the most economically efficient way, but fewer paths
1383 // also makes routing more reliable.
1384 let mut overpaid_value_msat = aggregate_route_value_msat - final_value_msat;
1386 // First, drop some expensive low-value paths entirely if possible.
1387 // Sort by value so that we drop many really-low values first, since
1388 // fewer paths is better: the payment is less likely to fail.
1389 // TODO: this could also be optimized by also sorting by feerate_per_sat_routed,
1390 // so that the sender pays less fees overall. And also htlc_minimum_msat.
1391 cur_route.sort_by_key(|path| path.get_value_msat());
1392 // We should make sure that at least 1 path left.
1393 let mut paths_left = cur_route.len();
1394 cur_route.retain(|path| {
1395 if paths_left == 1 {
1398 let mut keep = true;
1399 let path_value_msat = path.get_value_msat();
1400 if path_value_msat <= overpaid_value_msat {
1402 overpaid_value_msat -= path_value_msat;
1408 if overpaid_value_msat == 0 {
1412 assert!(cur_route.len() > 0);
1415 // Now, substract the overpaid value from the most-expensive path.
1416 // TODO: this could also be optimized by also sorting by feerate_per_sat_routed,
1417 // so that the sender pays less fees overall. And also htlc_minimum_msat.
1418 cur_route.sort_by_key(|path| { path.hops.iter().map(|hop| hop.0.channel_fees.proportional_millionths as u64).sum::<u64>() });
1419 let expensive_payment_path = cur_route.first_mut().unwrap();
1420 // We already dropped all the small channels above, meaning all the
1421 // remaining channels are larger than remaining overpaid_value_msat.
1422 // Thus, this can't be negative.
1423 let expensive_path_new_value_msat = expensive_payment_path.get_value_msat() - overpaid_value_msat;
1424 expensive_payment_path.update_value_and_recompute_fees(expensive_path_new_value_msat);
1428 drawn_routes.push(cur_route);
1432 // Select the best route by lowest total fee.
1433 drawn_routes.sort_by_key(|paths| paths.iter().map(|path| path.get_total_fee_paid_msat()).sum::<u64>());
1434 let mut selected_paths = Vec::<Vec<Result<RouteHop, LightningError>>>::new();
1435 for payment_path in drawn_routes.first().unwrap() {
1436 selected_paths.push(payment_path.hops.iter().map(|(payment_hop, node_features)| {
1438 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)})?,
1439 node_features: node_features.clone(),
1440 short_channel_id: payment_hop.short_channel_id,
1441 channel_features: payment_hop.channel_features.clone(),
1442 fee_msat: payment_hop.fee_msat,
1443 cltv_expiry_delta: payment_hop.cltv_expiry_delta,
1448 if let Some(features) = &payee.features {
1449 for path in selected_paths.iter_mut() {
1450 if let Ok(route_hop) = path.last_mut().unwrap() {
1451 route_hop.node_features = features.to_context();
1457 paths: selected_paths.into_iter().map(|path| path.into_iter().collect()).collect::<Result<Vec<_>, _>>()?,
1458 payee: Some(payee.clone()),
1460 log_info!(logger, "Got route to {}: {}", payee.pubkey, log_route!(route));
1467 use routing::network_graph::{NetworkGraph, NetGraphMsgHandler, NodeId};
1468 use routing::router::{get_route, Payee, Route, RouteHint, RouteHintHop, RouteHop, RoutingFees};
1469 use routing::scorer::Scorer;
1470 use chain::transaction::OutPoint;
1471 use ln::features::{ChannelFeatures, InitFeatures, InvoiceFeatures, NodeFeatures};
1472 use ln::msgs::{ErrorAction, LightningError, OptionalField, UnsignedChannelAnnouncement, ChannelAnnouncement, RoutingMessageHandler,
1473 NodeAnnouncement, UnsignedNodeAnnouncement, ChannelUpdate, UnsignedChannelUpdate};
1474 use ln::channelmanager;
1475 use util::test_utils;
1476 use util::ser::Writeable;
1478 use bitcoin::hashes::sha256d::Hash as Sha256dHash;
1479 use bitcoin::hashes::Hash;
1480 use bitcoin::network::constants::Network;
1481 use bitcoin::blockdata::constants::genesis_block;
1482 use bitcoin::blockdata::script::Builder;
1483 use bitcoin::blockdata::opcodes;
1484 use bitcoin::blockdata::transaction::TxOut;
1488 use bitcoin::secp256k1::key::{PublicKey,SecretKey};
1489 use bitcoin::secp256k1::{Secp256k1, All};
1492 use sync::{self, Arc};
1494 fn get_channel_details(short_channel_id: Option<u64>, node_id: PublicKey,
1495 features: InitFeatures, outbound_capacity_msat: u64) -> channelmanager::ChannelDetails {
1496 channelmanager::ChannelDetails {
1497 channel_id: [0; 32],
1498 counterparty: channelmanager::ChannelCounterparty {
1501 unspendable_punishment_reserve: 0,
1502 forwarding_info: None,
1504 funding_txo: Some(OutPoint { txid: bitcoin::Txid::from_slice(&[0; 32]).unwrap(), index: 0 }),
1506 channel_value_satoshis: 0,
1508 outbound_capacity_msat,
1509 inbound_capacity_msat: 42,
1510 unspendable_punishment_reserve: None,
1511 confirmations_required: None,
1512 force_close_spend_delay: None,
1513 is_outbound: true, is_funding_locked: true,
1514 is_usable: true, is_public: true,
1518 // Using the same keys for LN and BTC ids
1520 net_graph_msg_handler: &NetGraphMsgHandler<Arc<test_utils::TestChainSource>, Arc<test_utils::TestLogger>>,
1521 secp_ctx: &Secp256k1<All>, node_1_privkey: &SecretKey, node_2_privkey: &SecretKey, features: ChannelFeatures, short_channel_id: u64
1523 let node_id_1 = PublicKey::from_secret_key(&secp_ctx, node_1_privkey);
1524 let node_id_2 = PublicKey::from_secret_key(&secp_ctx, node_2_privkey);
1526 let unsigned_announcement = UnsignedChannelAnnouncement {
1528 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1532 bitcoin_key_1: node_id_1,
1533 bitcoin_key_2: node_id_2,
1534 excess_data: Vec::new(),
1537 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1538 let valid_announcement = ChannelAnnouncement {
1539 node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
1540 node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
1541 bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
1542 bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
1543 contents: unsigned_announcement.clone(),
1545 match net_graph_msg_handler.handle_channel_announcement(&valid_announcement) {
1546 Ok(res) => assert!(res),
1552 net_graph_msg_handler: &NetGraphMsgHandler<Arc<test_utils::TestChainSource>, Arc<test_utils::TestLogger>>,
1553 secp_ctx: &Secp256k1<All>, node_privkey: &SecretKey, update: UnsignedChannelUpdate
1555 let msghash = hash_to_message!(&Sha256dHash::hash(&update.encode()[..])[..]);
1556 let valid_channel_update = ChannelUpdate {
1557 signature: secp_ctx.sign(&msghash, node_privkey),
1558 contents: update.clone()
1561 match net_graph_msg_handler.handle_channel_update(&valid_channel_update) {
1562 Ok(res) => assert!(res),
1567 fn add_or_update_node(
1568 net_graph_msg_handler: &NetGraphMsgHandler<Arc<test_utils::TestChainSource>, Arc<test_utils::TestLogger>>,
1569 secp_ctx: &Secp256k1<All>, node_privkey: &SecretKey, features: NodeFeatures, timestamp: u32
1571 let node_id = PublicKey::from_secret_key(&secp_ctx, node_privkey);
1572 let unsigned_announcement = UnsignedNodeAnnouncement {
1578 addresses: Vec::new(),
1579 excess_address_data: Vec::new(),
1580 excess_data: Vec::new(),
1582 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1583 let valid_announcement = NodeAnnouncement {
1584 signature: secp_ctx.sign(&msghash, node_privkey),
1585 contents: unsigned_announcement.clone()
1588 match net_graph_msg_handler.handle_node_announcement(&valid_announcement) {
1594 fn get_nodes(secp_ctx: &Secp256k1<All>) -> (SecretKey, PublicKey, Vec<SecretKey>, Vec<PublicKey>) {
1595 let privkeys: Vec<SecretKey> = (2..10).map(|i| {
1596 SecretKey::from_slice(&hex::decode(format!("{:02}", i).repeat(32)).unwrap()[..]).unwrap()
1599 let pubkeys = privkeys.iter().map(|secret| PublicKey::from_secret_key(&secp_ctx, secret)).collect();
1601 let our_privkey = SecretKey::from_slice(&hex::decode("01".repeat(32)).unwrap()[..]).unwrap();
1602 let our_id = PublicKey::from_secret_key(&secp_ctx, &our_privkey);
1604 (our_privkey, our_id, privkeys, pubkeys)
1607 fn id_to_feature_flags(id: u8) -> Vec<u8> {
1608 // Set the feature flags to the id'th odd (ie non-required) feature bit so that we can
1609 // test for it later.
1610 let idx = (id - 1) * 2 + 1;
1612 vec![1 << (idx - 8*3), 0, 0, 0]
1613 } else if idx > 8*2 {
1614 vec![1 << (idx - 8*2), 0, 0]
1615 } else if idx > 8*1 {
1616 vec![1 << (idx - 8*1), 0]
1622 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>) {
1623 let secp_ctx = Secp256k1::new();
1624 let logger = Arc::new(test_utils::TestLogger::new());
1625 let chain_monitor = Arc::new(test_utils::TestChainSource::new(Network::Testnet));
1626 let network_graph = NetworkGraph::new(genesis_block(Network::Testnet).header.block_hash());
1627 let net_graph_msg_handler = NetGraphMsgHandler::new(network_graph, None, Arc::clone(&logger));
1628 // Build network from our_id to node6:
1630 // -1(1)2- node0 -1(3)2-
1632 // our_id -1(12)2- node7 -1(13)2--- node2
1634 // -1(2)2- node1 -1(4)2-
1637 // chan1 1-to-2: disabled
1638 // chan1 2-to-1: enabled, 0 fee
1640 // chan2 1-to-2: enabled, ignored fee
1641 // chan2 2-to-1: enabled, 0 fee
1643 // chan3 1-to-2: enabled, 0 fee
1644 // chan3 2-to-1: enabled, 100 msat fee
1646 // chan4 1-to-2: enabled, 100% fee
1647 // chan4 2-to-1: enabled, 0 fee
1649 // chan12 1-to-2: enabled, ignored fee
1650 // chan12 2-to-1: enabled, 0 fee
1652 // chan13 1-to-2: enabled, 200% fee
1653 // chan13 2-to-1: enabled, 0 fee
1656 // -1(5)2- node3 -1(8)2--
1660 // node2--1(6)2- node4 -1(9)2--- node6 (not in global route map)
1662 // -1(7)2- node5 -1(10)2-
1664 // Channels 5, 8, 9 and 10 are private channels.
1666 // chan5 1-to-2: enabled, 100 msat fee
1667 // chan5 2-to-1: enabled, 0 fee
1669 // chan6 1-to-2: enabled, 0 fee
1670 // chan6 2-to-1: enabled, 0 fee
1672 // chan7 1-to-2: enabled, 100% fee
1673 // chan7 2-to-1: enabled, 0 fee
1675 // chan8 1-to-2: enabled, variable fee (0 then 1000 msat)
1676 // chan8 2-to-1: enabled, 0 fee
1678 // chan9 1-to-2: enabled, 1001 msat fee
1679 // chan9 2-to-1: enabled, 0 fee
1681 // chan10 1-to-2: enabled, 0 fee
1682 // chan10 2-to-1: enabled, 0 fee
1684 // chan11 1-to-2: enabled, 0 fee
1685 // chan11 2-to-1: enabled, 0 fee
1687 let (our_privkey, _, privkeys, _) = get_nodes(&secp_ctx);
1689 add_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, &privkeys[0], ChannelFeatures::from_le_bytes(id_to_feature_flags(1)), 1);
1690 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
1691 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1692 short_channel_id: 1,
1695 cltv_expiry_delta: 0,
1696 htlc_minimum_msat: 0,
1697 htlc_maximum_msat: OptionalField::Absent,
1699 fee_proportional_millionths: 0,
1700 excess_data: Vec::new()
1703 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[0], NodeFeatures::from_le_bytes(id_to_feature_flags(1)), 0);
1705 add_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, &privkeys[1], ChannelFeatures::from_le_bytes(id_to_feature_flags(2)), 2);
1706 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
1707 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1708 short_channel_id: 2,
1711 cltv_expiry_delta: u16::max_value(),
1712 htlc_minimum_msat: 0,
1713 htlc_maximum_msat: OptionalField::Absent,
1714 fee_base_msat: u32::max_value(),
1715 fee_proportional_millionths: u32::max_value(),
1716 excess_data: Vec::new()
1718 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
1719 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1720 short_channel_id: 2,
1723 cltv_expiry_delta: 0,
1724 htlc_minimum_msat: 0,
1725 htlc_maximum_msat: OptionalField::Absent,
1727 fee_proportional_millionths: 0,
1728 excess_data: Vec::new()
1731 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[1], NodeFeatures::from_le_bytes(id_to_feature_flags(2)), 0);
1733 add_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, &privkeys[7], ChannelFeatures::from_le_bytes(id_to_feature_flags(12)), 12);
1734 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
1735 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1736 short_channel_id: 12,
1739 cltv_expiry_delta: u16::max_value(),
1740 htlc_minimum_msat: 0,
1741 htlc_maximum_msat: OptionalField::Absent,
1742 fee_base_msat: u32::max_value(),
1743 fee_proportional_millionths: u32::max_value(),
1744 excess_data: Vec::new()
1746 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
1747 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1748 short_channel_id: 12,
1751 cltv_expiry_delta: 0,
1752 htlc_minimum_msat: 0,
1753 htlc_maximum_msat: OptionalField::Absent,
1755 fee_proportional_millionths: 0,
1756 excess_data: Vec::new()
1759 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[7], NodeFeatures::from_le_bytes(id_to_feature_flags(8)), 0);
1761 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], &privkeys[2], ChannelFeatures::from_le_bytes(id_to_feature_flags(3)), 3);
1762 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
1763 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1764 short_channel_id: 3,
1767 cltv_expiry_delta: (3 << 8) | 1,
1768 htlc_minimum_msat: 0,
1769 htlc_maximum_msat: OptionalField::Absent,
1771 fee_proportional_millionths: 0,
1772 excess_data: Vec::new()
1774 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
1775 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1776 short_channel_id: 3,
1779 cltv_expiry_delta: (3 << 8) | 2,
1780 htlc_minimum_msat: 0,
1781 htlc_maximum_msat: OptionalField::Absent,
1783 fee_proportional_millionths: 0,
1784 excess_data: Vec::new()
1787 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], &privkeys[2], ChannelFeatures::from_le_bytes(id_to_feature_flags(4)), 4);
1788 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
1789 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1790 short_channel_id: 4,
1793 cltv_expiry_delta: (4 << 8) | 1,
1794 htlc_minimum_msat: 0,
1795 htlc_maximum_msat: OptionalField::Absent,
1797 fee_proportional_millionths: 1000000,
1798 excess_data: Vec::new()
1800 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
1801 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1802 short_channel_id: 4,
1805 cltv_expiry_delta: (4 << 8) | 2,
1806 htlc_minimum_msat: 0,
1807 htlc_maximum_msat: OptionalField::Absent,
1809 fee_proportional_millionths: 0,
1810 excess_data: Vec::new()
1813 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], &privkeys[2], ChannelFeatures::from_le_bytes(id_to_feature_flags(13)), 13);
1814 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
1815 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1816 short_channel_id: 13,
1819 cltv_expiry_delta: (13 << 8) | 1,
1820 htlc_minimum_msat: 0,
1821 htlc_maximum_msat: OptionalField::Absent,
1823 fee_proportional_millionths: 2000000,
1824 excess_data: Vec::new()
1826 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
1827 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1828 short_channel_id: 13,
1831 cltv_expiry_delta: (13 << 8) | 2,
1832 htlc_minimum_msat: 0,
1833 htlc_maximum_msat: OptionalField::Absent,
1835 fee_proportional_millionths: 0,
1836 excess_data: Vec::new()
1839 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[2], NodeFeatures::from_le_bytes(id_to_feature_flags(3)), 0);
1841 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], &privkeys[4], ChannelFeatures::from_le_bytes(id_to_feature_flags(6)), 6);
1842 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
1843 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1844 short_channel_id: 6,
1847 cltv_expiry_delta: (6 << 8) | 1,
1848 htlc_minimum_msat: 0,
1849 htlc_maximum_msat: OptionalField::Absent,
1851 fee_proportional_millionths: 0,
1852 excess_data: Vec::new()
1854 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
1855 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1856 short_channel_id: 6,
1859 cltv_expiry_delta: (6 << 8) | 2,
1860 htlc_minimum_msat: 0,
1861 htlc_maximum_msat: OptionalField::Absent,
1863 fee_proportional_millionths: 0,
1864 excess_data: Vec::new(),
1867 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(11)), 11);
1868 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
1869 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1870 short_channel_id: 11,
1873 cltv_expiry_delta: (11 << 8) | 1,
1874 htlc_minimum_msat: 0,
1875 htlc_maximum_msat: OptionalField::Absent,
1877 fee_proportional_millionths: 0,
1878 excess_data: Vec::new()
1880 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[3], UnsignedChannelUpdate {
1881 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1882 short_channel_id: 11,
1885 cltv_expiry_delta: (11 << 8) | 2,
1886 htlc_minimum_msat: 0,
1887 htlc_maximum_msat: OptionalField::Absent,
1889 fee_proportional_millionths: 0,
1890 excess_data: Vec::new()
1893 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[4], NodeFeatures::from_le_bytes(id_to_feature_flags(5)), 0);
1895 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[3], NodeFeatures::from_le_bytes(id_to_feature_flags(4)), 0);
1897 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], &privkeys[5], ChannelFeatures::from_le_bytes(id_to_feature_flags(7)), 7);
1898 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
1899 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1900 short_channel_id: 7,
1903 cltv_expiry_delta: (7 << 8) | 1,
1904 htlc_minimum_msat: 0,
1905 htlc_maximum_msat: OptionalField::Absent,
1907 fee_proportional_millionths: 1000000,
1908 excess_data: Vec::new()
1910 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[5], UnsignedChannelUpdate {
1911 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1912 short_channel_id: 7,
1915 cltv_expiry_delta: (7 << 8) | 2,
1916 htlc_minimum_msat: 0,
1917 htlc_maximum_msat: OptionalField::Absent,
1919 fee_proportional_millionths: 0,
1920 excess_data: Vec::new()
1923 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[5], NodeFeatures::from_le_bytes(id_to_feature_flags(6)), 0);
1925 (secp_ctx, net_graph_msg_handler, chain_monitor, logger)
1929 fn simple_route_test() {
1930 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
1931 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
1932 let payee = Payee::new(nodes[2]);
1933 let scorer = Scorer::new(0);
1935 // Simple route to 2 via 1
1937 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) {
1938 assert_eq!(err, "Cannot send a payment of 0 msat");
1939 } else { panic!(); }
1941 let route = get_route(&our_id, &payee, &net_graph_msg_handler.network_graph, None, 100, 42, Arc::clone(&logger), &scorer).unwrap();
1942 assert_eq!(route.paths[0].len(), 2);
1944 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
1945 assert_eq!(route.paths[0][0].short_channel_id, 2);
1946 assert_eq!(route.paths[0][0].fee_msat, 100);
1947 assert_eq!(route.paths[0][0].cltv_expiry_delta, (4 << 8) | 1);
1948 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
1949 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
1951 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
1952 assert_eq!(route.paths[0][1].short_channel_id, 4);
1953 assert_eq!(route.paths[0][1].fee_msat, 100);
1954 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
1955 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
1956 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
1960 fn invalid_first_hop_test() {
1961 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
1962 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
1963 let payee = Payee::new(nodes[2]);
1964 let scorer = Scorer::new(0);
1966 // Simple route to 2 via 1
1968 let our_chans = vec![get_channel_details(Some(2), our_id, InitFeatures::from_le_bytes(vec![0b11]), 100000)];
1970 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) {
1971 assert_eq!(err, "First hop cannot have our_node_pubkey as a destination.");
1972 } else { panic!(); }
1974 let route = get_route(&our_id, &payee, &net_graph_msg_handler.network_graph, None, 100, 42, Arc::clone(&logger), &scorer).unwrap();
1975 assert_eq!(route.paths[0].len(), 2);
1979 fn htlc_minimum_test() {
1980 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
1981 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
1982 let payee = Payee::new(nodes[2]);
1983 let scorer = Scorer::new(0);
1985 // Simple route to 2 via 1
1987 // Disable other paths
1988 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
1989 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1990 short_channel_id: 12,
1992 flags: 2, // to disable
1993 cltv_expiry_delta: 0,
1994 htlc_minimum_msat: 0,
1995 htlc_maximum_msat: OptionalField::Absent,
1997 fee_proportional_millionths: 0,
1998 excess_data: Vec::new()
2000 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
2001 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2002 short_channel_id: 3,
2004 flags: 2, // to disable
2005 cltv_expiry_delta: 0,
2006 htlc_minimum_msat: 0,
2007 htlc_maximum_msat: OptionalField::Absent,
2009 fee_proportional_millionths: 0,
2010 excess_data: Vec::new()
2012 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
2013 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2014 short_channel_id: 13,
2016 flags: 2, // to disable
2017 cltv_expiry_delta: 0,
2018 htlc_minimum_msat: 0,
2019 htlc_maximum_msat: OptionalField::Absent,
2021 fee_proportional_millionths: 0,
2022 excess_data: Vec::new()
2024 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
2025 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2026 short_channel_id: 6,
2028 flags: 2, // to disable
2029 cltv_expiry_delta: 0,
2030 htlc_minimum_msat: 0,
2031 htlc_maximum_msat: OptionalField::Absent,
2033 fee_proportional_millionths: 0,
2034 excess_data: Vec::new()
2036 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
2037 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2038 short_channel_id: 7,
2040 flags: 2, // to disable
2041 cltv_expiry_delta: 0,
2042 htlc_minimum_msat: 0,
2043 htlc_maximum_msat: OptionalField::Absent,
2045 fee_proportional_millionths: 0,
2046 excess_data: Vec::new()
2049 // Check against amount_to_transfer_over_msat.
2050 // Set minimal HTLC of 200_000_000 msat.
2051 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2052 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2053 short_channel_id: 2,
2056 cltv_expiry_delta: 0,
2057 htlc_minimum_msat: 200_000_000,
2058 htlc_maximum_msat: OptionalField::Absent,
2060 fee_proportional_millionths: 0,
2061 excess_data: Vec::new()
2064 // Second hop only allows to forward 199_999_999 at most, thus not allowing the first hop to
2066 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
2067 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2068 short_channel_id: 4,
2071 cltv_expiry_delta: 0,
2072 htlc_minimum_msat: 0,
2073 htlc_maximum_msat: OptionalField::Present(199_999_999),
2075 fee_proportional_millionths: 0,
2076 excess_data: Vec::new()
2079 // Not possible to send 199_999_999, because the minimum on channel=2 is 200_000_000.
2080 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) {
2081 assert_eq!(err, "Failed to find a path to the given destination");
2082 } else { panic!(); }
2084 // Lift the restriction on the first hop.
2085 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2086 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2087 short_channel_id: 2,
2090 cltv_expiry_delta: 0,
2091 htlc_minimum_msat: 0,
2092 htlc_maximum_msat: OptionalField::Absent,
2094 fee_proportional_millionths: 0,
2095 excess_data: Vec::new()
2098 // A payment above the minimum should pass
2099 let route = get_route(&our_id, &payee, &net_graph_msg_handler.network_graph, None, 199_999_999, 42, Arc::clone(&logger), &scorer).unwrap();
2100 assert_eq!(route.paths[0].len(), 2);
2104 fn htlc_minimum_overpay_test() {
2105 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
2106 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
2107 let payee = Payee::new(nodes[2]).with_features(InvoiceFeatures::known());
2108 let scorer = Scorer::new(0);
2110 // A route to node#2 via two paths.
2111 // One path allows transferring 35-40 sats, another one also allows 35-40 sats.
2112 // Thus, they can't send 60 without overpaying.
2113 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2114 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2115 short_channel_id: 2,
2118 cltv_expiry_delta: 0,
2119 htlc_minimum_msat: 35_000,
2120 htlc_maximum_msat: OptionalField::Present(40_000),
2122 fee_proportional_millionths: 0,
2123 excess_data: Vec::new()
2125 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2126 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2127 short_channel_id: 12,
2130 cltv_expiry_delta: 0,
2131 htlc_minimum_msat: 35_000,
2132 htlc_maximum_msat: OptionalField::Present(40_000),
2134 fee_proportional_millionths: 0,
2135 excess_data: Vec::new()
2139 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
2140 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2141 short_channel_id: 13,
2144 cltv_expiry_delta: 0,
2145 htlc_minimum_msat: 0,
2146 htlc_maximum_msat: OptionalField::Absent,
2148 fee_proportional_millionths: 0,
2149 excess_data: Vec::new()
2151 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
2152 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2153 short_channel_id: 4,
2156 cltv_expiry_delta: 0,
2157 htlc_minimum_msat: 0,
2158 htlc_maximum_msat: OptionalField::Absent,
2160 fee_proportional_millionths: 0,
2161 excess_data: Vec::new()
2164 // Disable other paths
2165 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2166 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2167 short_channel_id: 1,
2169 flags: 2, // to disable
2170 cltv_expiry_delta: 0,
2171 htlc_minimum_msat: 0,
2172 htlc_maximum_msat: OptionalField::Absent,
2174 fee_proportional_millionths: 0,
2175 excess_data: Vec::new()
2178 let route = get_route(&our_id, &payee, &net_graph_msg_handler.network_graph, None, 60_000, 42, Arc::clone(&logger), &scorer).unwrap();
2179 // Overpay fees to hit htlc_minimum_msat.
2180 let overpaid_fees = route.paths[0][0].fee_msat + route.paths[1][0].fee_msat;
2181 // TODO: this could be better balanced to overpay 10k and not 15k.
2182 assert_eq!(overpaid_fees, 15_000);
2184 // Now, test that if there are 2 paths, a "cheaper" by fee path wouldn't be prioritized
2185 // while taking even more fee to match htlc_minimum_msat.
2186 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2187 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2188 short_channel_id: 12,
2191 cltv_expiry_delta: 0,
2192 htlc_minimum_msat: 65_000,
2193 htlc_maximum_msat: OptionalField::Present(80_000),
2195 fee_proportional_millionths: 0,
2196 excess_data: Vec::new()
2198 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2199 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2200 short_channel_id: 2,
2203 cltv_expiry_delta: 0,
2204 htlc_minimum_msat: 0,
2205 htlc_maximum_msat: OptionalField::Absent,
2207 fee_proportional_millionths: 0,
2208 excess_data: Vec::new()
2210 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
2211 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2212 short_channel_id: 4,
2215 cltv_expiry_delta: 0,
2216 htlc_minimum_msat: 0,
2217 htlc_maximum_msat: OptionalField::Absent,
2219 fee_proportional_millionths: 100_000,
2220 excess_data: Vec::new()
2223 let route = get_route(&our_id, &payee, &net_graph_msg_handler.network_graph, None, 60_000, 42, Arc::clone(&logger), &scorer).unwrap();
2224 // Fine to overpay for htlc_minimum_msat if it allows us to save fee.
2225 assert_eq!(route.paths.len(), 1);
2226 assert_eq!(route.paths[0][0].short_channel_id, 12);
2227 let fees = route.paths[0][0].fee_msat;
2228 assert_eq!(fees, 5_000);
2230 let route = get_route(&our_id, &payee, &net_graph_msg_handler.network_graph, None, 50_000, 42, Arc::clone(&logger), &scorer).unwrap();
2231 // Not fine to overpay for htlc_minimum_msat if it requires paying more than fee on
2232 // the other channel.
2233 assert_eq!(route.paths.len(), 1);
2234 assert_eq!(route.paths[0][0].short_channel_id, 2);
2235 let fees = route.paths[0][0].fee_msat;
2236 assert_eq!(fees, 5_000);
2240 fn disable_channels_test() {
2241 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
2242 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
2243 let payee = Payee::new(nodes[2]);
2244 let scorer = Scorer::new(0);
2246 // // Disable channels 4 and 12 by flags=2
2247 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
2248 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2249 short_channel_id: 4,
2251 flags: 2, // to disable
2252 cltv_expiry_delta: 0,
2253 htlc_minimum_msat: 0,
2254 htlc_maximum_msat: OptionalField::Absent,
2256 fee_proportional_millionths: 0,
2257 excess_data: Vec::new()
2259 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2260 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2261 short_channel_id: 12,
2263 flags: 2, // to disable
2264 cltv_expiry_delta: 0,
2265 htlc_minimum_msat: 0,
2266 htlc_maximum_msat: OptionalField::Absent,
2268 fee_proportional_millionths: 0,
2269 excess_data: Vec::new()
2272 // If all the channels require some features we don't understand, route should fail
2273 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) {
2274 assert_eq!(err, "Failed to find a path to the given destination");
2275 } else { panic!(); }
2277 // If we specify a channel to node7, that overrides our local channel view and that gets used
2278 let our_chans = vec![get_channel_details(Some(42), nodes[7].clone(), InitFeatures::from_le_bytes(vec![0b11]), 250_000_000)];
2279 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();
2280 assert_eq!(route.paths[0].len(), 2);
2282 assert_eq!(route.paths[0][0].pubkey, nodes[7]);
2283 assert_eq!(route.paths[0][0].short_channel_id, 42);
2284 assert_eq!(route.paths[0][0].fee_msat, 200);
2285 assert_eq!(route.paths[0][0].cltv_expiry_delta, (13 << 8) | 1);
2286 assert_eq!(route.paths[0][0].node_features.le_flags(), &vec![0b11]); // it should also override our view of their features
2287 assert_eq!(route.paths[0][0].channel_features.le_flags(), &Vec::<u8>::new()); // No feature flags will meet the relevant-to-channel conversion
2289 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2290 assert_eq!(route.paths[0][1].short_channel_id, 13);
2291 assert_eq!(route.paths[0][1].fee_msat, 100);
2292 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
2293 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2294 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(13));
2298 fn disable_node_test() {
2299 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
2300 let (_, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
2301 let payee = Payee::new(nodes[2]);
2302 let scorer = Scorer::new(0);
2304 // Disable nodes 1, 2, and 8 by requiring unknown feature bits
2305 let unknown_features = NodeFeatures::known().set_unknown_feature_required();
2306 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[0], unknown_features.clone(), 1);
2307 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[1], unknown_features.clone(), 1);
2308 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[7], unknown_features.clone(), 1);
2310 // If all nodes require some features we don't understand, route should fail
2311 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) {
2312 assert_eq!(err, "Failed to find a path to the given destination");
2313 } else { panic!(); }
2315 // If we specify a channel to node7, that overrides our local channel view and that gets used
2316 let our_chans = vec![get_channel_details(Some(42), nodes[7].clone(), InitFeatures::from_le_bytes(vec![0b11]), 250_000_000)];
2317 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();
2318 assert_eq!(route.paths[0].len(), 2);
2320 assert_eq!(route.paths[0][0].pubkey, nodes[7]);
2321 assert_eq!(route.paths[0][0].short_channel_id, 42);
2322 assert_eq!(route.paths[0][0].fee_msat, 200);
2323 assert_eq!(route.paths[0][0].cltv_expiry_delta, (13 << 8) | 1);
2324 assert_eq!(route.paths[0][0].node_features.le_flags(), &vec![0b11]); // it should also override our view of their features
2325 assert_eq!(route.paths[0][0].channel_features.le_flags(), &Vec::<u8>::new()); // No feature flags will meet the relevant-to-channel conversion
2327 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2328 assert_eq!(route.paths[0][1].short_channel_id, 13);
2329 assert_eq!(route.paths[0][1].fee_msat, 100);
2330 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
2331 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2332 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(13));
2334 // Note that we don't test disabling node 3 and failing to route to it, as we (somewhat
2335 // naively) assume that the user checked the feature bits on the invoice, which override
2336 // the node_announcement.
2340 fn our_chans_test() {
2341 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
2342 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
2343 let scorer = Scorer::new(0);
2345 // Route to 1 via 2 and 3 because our channel to 1 is disabled
2346 let payee = Payee::new(nodes[0]);
2347 let route = get_route(&our_id, &payee, &net_graph_msg_handler.network_graph, None, 100, 42, Arc::clone(&logger), &scorer).unwrap();
2348 assert_eq!(route.paths[0].len(), 3);
2350 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
2351 assert_eq!(route.paths[0][0].short_channel_id, 2);
2352 assert_eq!(route.paths[0][0].fee_msat, 200);
2353 assert_eq!(route.paths[0][0].cltv_expiry_delta, (4 << 8) | 1);
2354 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
2355 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
2357 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2358 assert_eq!(route.paths[0][1].short_channel_id, 4);
2359 assert_eq!(route.paths[0][1].fee_msat, 100);
2360 assert_eq!(route.paths[0][1].cltv_expiry_delta, (3 << 8) | 2);
2361 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2362 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
2364 assert_eq!(route.paths[0][2].pubkey, nodes[0]);
2365 assert_eq!(route.paths[0][2].short_channel_id, 3);
2366 assert_eq!(route.paths[0][2].fee_msat, 100);
2367 assert_eq!(route.paths[0][2].cltv_expiry_delta, 42);
2368 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(1));
2369 assert_eq!(route.paths[0][2].channel_features.le_flags(), &id_to_feature_flags(3));
2371 // If we specify a channel to node7, that overrides our local channel view and that gets used
2372 let payee = Payee::new(nodes[2]);
2373 let our_chans = vec![get_channel_details(Some(42), nodes[7].clone(), InitFeatures::from_le_bytes(vec![0b11]), 250_000_000)];
2374 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();
2375 assert_eq!(route.paths[0].len(), 2);
2377 assert_eq!(route.paths[0][0].pubkey, nodes[7]);
2378 assert_eq!(route.paths[0][0].short_channel_id, 42);
2379 assert_eq!(route.paths[0][0].fee_msat, 200);
2380 assert_eq!(route.paths[0][0].cltv_expiry_delta, (13 << 8) | 1);
2381 assert_eq!(route.paths[0][0].node_features.le_flags(), &vec![0b11]);
2382 assert_eq!(route.paths[0][0].channel_features.le_flags(), &Vec::<u8>::new()); // No feature flags will meet the relevant-to-channel conversion
2384 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2385 assert_eq!(route.paths[0][1].short_channel_id, 13);
2386 assert_eq!(route.paths[0][1].fee_msat, 100);
2387 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
2388 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2389 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(13));
2392 fn last_hops(nodes: &Vec<PublicKey>) -> Vec<RouteHint> {
2393 let zero_fees = RoutingFees {
2395 proportional_millionths: 0,
2397 vec![RouteHint(vec![RouteHintHop {
2398 src_node_id: nodes[3],
2399 short_channel_id: 8,
2401 cltv_expiry_delta: (8 << 8) | 1,
2402 htlc_minimum_msat: None,
2403 htlc_maximum_msat: None,
2405 ]), RouteHint(vec![RouteHintHop {
2406 src_node_id: nodes[4],
2407 short_channel_id: 9,
2410 proportional_millionths: 0,
2412 cltv_expiry_delta: (9 << 8) | 1,
2413 htlc_minimum_msat: None,
2414 htlc_maximum_msat: None,
2415 }]), RouteHint(vec![RouteHintHop {
2416 src_node_id: nodes[5],
2417 short_channel_id: 10,
2419 cltv_expiry_delta: (10 << 8) | 1,
2420 htlc_minimum_msat: None,
2421 htlc_maximum_msat: None,
2425 fn last_hops_multi_private_channels(nodes: &Vec<PublicKey>) -> Vec<RouteHint> {
2426 let zero_fees = RoutingFees {
2428 proportional_millionths: 0,
2430 vec![RouteHint(vec![RouteHintHop {
2431 src_node_id: nodes[2],
2432 short_channel_id: 5,
2435 proportional_millionths: 0,
2437 cltv_expiry_delta: (5 << 8) | 1,
2438 htlc_minimum_msat: None,
2439 htlc_maximum_msat: None,
2441 src_node_id: nodes[3],
2442 short_channel_id: 8,
2444 cltv_expiry_delta: (8 << 8) | 1,
2445 htlc_minimum_msat: None,
2446 htlc_maximum_msat: None,
2448 ]), RouteHint(vec![RouteHintHop {
2449 src_node_id: nodes[4],
2450 short_channel_id: 9,
2453 proportional_millionths: 0,
2455 cltv_expiry_delta: (9 << 8) | 1,
2456 htlc_minimum_msat: None,
2457 htlc_maximum_msat: None,
2458 }]), RouteHint(vec![RouteHintHop {
2459 src_node_id: nodes[5],
2460 short_channel_id: 10,
2462 cltv_expiry_delta: (10 << 8) | 1,
2463 htlc_minimum_msat: None,
2464 htlc_maximum_msat: None,
2469 fn partial_route_hint_test() {
2470 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
2471 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
2472 let scorer = Scorer::new(0);
2474 // Simple test across 2, 3, 5, and 4 via a last_hop channel
2475 // Tests the behaviour when the RouteHint contains a suboptimal hop.
2476 // RouteHint may be partially used by the algo to build the best path.
2478 // First check that last hop can't have its source as the payee.
2479 let invalid_last_hop = RouteHint(vec![RouteHintHop {
2480 src_node_id: nodes[6],
2481 short_channel_id: 8,
2484 proportional_millionths: 0,
2486 cltv_expiry_delta: (8 << 8) | 1,
2487 htlc_minimum_msat: None,
2488 htlc_maximum_msat: None,
2491 let mut invalid_last_hops = last_hops_multi_private_channels(&nodes);
2492 invalid_last_hops.push(invalid_last_hop);
2494 let payee = Payee::new(nodes[6]).with_route_hints(invalid_last_hops);
2495 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) {
2496 assert_eq!(err, "Route hint cannot have the payee as the source.");
2497 } else { panic!(); }
2500 let payee = Payee::new(nodes[6]).with_route_hints(last_hops_multi_private_channels(&nodes));
2501 let route = get_route(&our_id, &payee, &net_graph_msg_handler.network_graph, None, 100, 42, Arc::clone(&logger), &scorer).unwrap();
2502 assert_eq!(route.paths[0].len(), 5);
2504 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
2505 assert_eq!(route.paths[0][0].short_channel_id, 2);
2506 assert_eq!(route.paths[0][0].fee_msat, 100);
2507 assert_eq!(route.paths[0][0].cltv_expiry_delta, (4 << 8) | 1);
2508 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
2509 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
2511 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2512 assert_eq!(route.paths[0][1].short_channel_id, 4);
2513 assert_eq!(route.paths[0][1].fee_msat, 0);
2514 assert_eq!(route.paths[0][1].cltv_expiry_delta, (6 << 8) | 1);
2515 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2516 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
2518 assert_eq!(route.paths[0][2].pubkey, nodes[4]);
2519 assert_eq!(route.paths[0][2].short_channel_id, 6);
2520 assert_eq!(route.paths[0][2].fee_msat, 0);
2521 assert_eq!(route.paths[0][2].cltv_expiry_delta, (11 << 8) | 1);
2522 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(5));
2523 assert_eq!(route.paths[0][2].channel_features.le_flags(), &id_to_feature_flags(6));
2525 assert_eq!(route.paths[0][3].pubkey, nodes[3]);
2526 assert_eq!(route.paths[0][3].short_channel_id, 11);
2527 assert_eq!(route.paths[0][3].fee_msat, 0);
2528 assert_eq!(route.paths[0][3].cltv_expiry_delta, (8 << 8) | 1);
2529 // If we have a peer in the node map, we'll use their features here since we don't have
2530 // a way of figuring out their features from the invoice:
2531 assert_eq!(route.paths[0][3].node_features.le_flags(), &id_to_feature_flags(4));
2532 assert_eq!(route.paths[0][3].channel_features.le_flags(), &id_to_feature_flags(11));
2534 assert_eq!(route.paths[0][4].pubkey, nodes[6]);
2535 assert_eq!(route.paths[0][4].short_channel_id, 8);
2536 assert_eq!(route.paths[0][4].fee_msat, 100);
2537 assert_eq!(route.paths[0][4].cltv_expiry_delta, 42);
2538 assert_eq!(route.paths[0][4].node_features.le_flags(), &Vec::<u8>::new()); // We dont pass flags in from invoices yet
2539 assert_eq!(route.paths[0][4].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
2542 fn empty_last_hop(nodes: &Vec<PublicKey>) -> Vec<RouteHint> {
2543 let zero_fees = RoutingFees {
2545 proportional_millionths: 0,
2547 vec![RouteHint(vec![RouteHintHop {
2548 src_node_id: nodes[3],
2549 short_channel_id: 8,
2551 cltv_expiry_delta: (8 << 8) | 1,
2552 htlc_minimum_msat: None,
2553 htlc_maximum_msat: None,
2554 }]), RouteHint(vec![
2556 ]), RouteHint(vec![RouteHintHop {
2557 src_node_id: nodes[5],
2558 short_channel_id: 10,
2560 cltv_expiry_delta: (10 << 8) | 1,
2561 htlc_minimum_msat: None,
2562 htlc_maximum_msat: None,
2567 fn ignores_empty_last_hops_test() {
2568 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
2569 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
2570 let payee = Payee::new(nodes[6]).with_route_hints(empty_last_hop(&nodes));
2571 let scorer = Scorer::new(0);
2573 // Test handling of an empty RouteHint passed in Invoice.
2575 let route = get_route(&our_id, &payee, &net_graph_msg_handler.network_graph, None, 100, 42, Arc::clone(&logger), &scorer).unwrap();
2576 assert_eq!(route.paths[0].len(), 5);
2578 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
2579 assert_eq!(route.paths[0][0].short_channel_id, 2);
2580 assert_eq!(route.paths[0][0].fee_msat, 100);
2581 assert_eq!(route.paths[0][0].cltv_expiry_delta, (4 << 8) | 1);
2582 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
2583 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
2585 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2586 assert_eq!(route.paths[0][1].short_channel_id, 4);
2587 assert_eq!(route.paths[0][1].fee_msat, 0);
2588 assert_eq!(route.paths[0][1].cltv_expiry_delta, (6 << 8) | 1);
2589 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2590 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
2592 assert_eq!(route.paths[0][2].pubkey, nodes[4]);
2593 assert_eq!(route.paths[0][2].short_channel_id, 6);
2594 assert_eq!(route.paths[0][2].fee_msat, 0);
2595 assert_eq!(route.paths[0][2].cltv_expiry_delta, (11 << 8) | 1);
2596 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(5));
2597 assert_eq!(route.paths[0][2].channel_features.le_flags(), &id_to_feature_flags(6));
2599 assert_eq!(route.paths[0][3].pubkey, nodes[3]);
2600 assert_eq!(route.paths[0][3].short_channel_id, 11);
2601 assert_eq!(route.paths[0][3].fee_msat, 0);
2602 assert_eq!(route.paths[0][3].cltv_expiry_delta, (8 << 8) | 1);
2603 // If we have a peer in the node map, we'll use their features here since we don't have
2604 // a way of figuring out their features from the invoice:
2605 assert_eq!(route.paths[0][3].node_features.le_flags(), &id_to_feature_flags(4));
2606 assert_eq!(route.paths[0][3].channel_features.le_flags(), &id_to_feature_flags(11));
2608 assert_eq!(route.paths[0][4].pubkey, nodes[6]);
2609 assert_eq!(route.paths[0][4].short_channel_id, 8);
2610 assert_eq!(route.paths[0][4].fee_msat, 100);
2611 assert_eq!(route.paths[0][4].cltv_expiry_delta, 42);
2612 assert_eq!(route.paths[0][4].node_features.le_flags(), &Vec::<u8>::new()); // We dont pass flags in from invoices yet
2613 assert_eq!(route.paths[0][4].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
2616 fn multi_hint_last_hops(nodes: &Vec<PublicKey>) -> Vec<RouteHint> {
2617 let zero_fees = RoutingFees {
2619 proportional_millionths: 0,
2621 vec![RouteHint(vec![RouteHintHop {
2622 src_node_id: nodes[2],
2623 short_channel_id: 5,
2626 proportional_millionths: 0,
2628 cltv_expiry_delta: (5 << 8) | 1,
2629 htlc_minimum_msat: None,
2630 htlc_maximum_msat: None,
2632 src_node_id: nodes[3],
2633 short_channel_id: 8,
2635 cltv_expiry_delta: (8 << 8) | 1,
2636 htlc_minimum_msat: None,
2637 htlc_maximum_msat: None,
2638 }]), RouteHint(vec![RouteHintHop {
2639 src_node_id: nodes[5],
2640 short_channel_id: 10,
2642 cltv_expiry_delta: (10 << 8) | 1,
2643 htlc_minimum_msat: None,
2644 htlc_maximum_msat: None,
2649 fn multi_hint_last_hops_test() {
2650 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
2651 let (_, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
2652 let payee = Payee::new(nodes[6]).with_route_hints(multi_hint_last_hops(&nodes));
2653 let scorer = Scorer::new(0);
2654 // Test through channels 2, 3, 5, 8.
2655 // Test shows that multiple hop hints are considered.
2657 // Disabling channels 6 & 7 by flags=2
2658 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
2659 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2660 short_channel_id: 6,
2662 flags: 2, // to disable
2663 cltv_expiry_delta: 0,
2664 htlc_minimum_msat: 0,
2665 htlc_maximum_msat: OptionalField::Absent,
2667 fee_proportional_millionths: 0,
2668 excess_data: Vec::new()
2670 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
2671 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2672 short_channel_id: 7,
2674 flags: 2, // to disable
2675 cltv_expiry_delta: 0,
2676 htlc_minimum_msat: 0,
2677 htlc_maximum_msat: OptionalField::Absent,
2679 fee_proportional_millionths: 0,
2680 excess_data: Vec::new()
2683 let route = get_route(&our_id, &payee, &net_graph_msg_handler.network_graph, None, 100, 42, Arc::clone(&logger), &scorer).unwrap();
2684 assert_eq!(route.paths[0].len(), 4);
2686 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
2687 assert_eq!(route.paths[0][0].short_channel_id, 2);
2688 assert_eq!(route.paths[0][0].fee_msat, 200);
2689 assert_eq!(route.paths[0][0].cltv_expiry_delta, 1025);
2690 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
2691 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
2693 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2694 assert_eq!(route.paths[0][1].short_channel_id, 4);
2695 assert_eq!(route.paths[0][1].fee_msat, 100);
2696 assert_eq!(route.paths[0][1].cltv_expiry_delta, 1281);
2697 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2698 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
2700 assert_eq!(route.paths[0][2].pubkey, nodes[3]);
2701 assert_eq!(route.paths[0][2].short_channel_id, 5);
2702 assert_eq!(route.paths[0][2].fee_msat, 0);
2703 assert_eq!(route.paths[0][2].cltv_expiry_delta, 2049);
2704 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(4));
2705 assert_eq!(route.paths[0][2].channel_features.le_flags(), &Vec::<u8>::new());
2707 assert_eq!(route.paths[0][3].pubkey, nodes[6]);
2708 assert_eq!(route.paths[0][3].short_channel_id, 8);
2709 assert_eq!(route.paths[0][3].fee_msat, 100);
2710 assert_eq!(route.paths[0][3].cltv_expiry_delta, 42);
2711 assert_eq!(route.paths[0][3].node_features.le_flags(), &Vec::<u8>::new()); // We dont pass flags in from invoices yet
2712 assert_eq!(route.paths[0][3].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
2715 fn last_hops_with_public_channel(nodes: &Vec<PublicKey>) -> Vec<RouteHint> {
2716 let zero_fees = RoutingFees {
2718 proportional_millionths: 0,
2720 vec![RouteHint(vec![RouteHintHop {
2721 src_node_id: nodes[4],
2722 short_channel_id: 11,
2724 cltv_expiry_delta: (11 << 8) | 1,
2725 htlc_minimum_msat: None,
2726 htlc_maximum_msat: None,
2728 src_node_id: nodes[3],
2729 short_channel_id: 8,
2731 cltv_expiry_delta: (8 << 8) | 1,
2732 htlc_minimum_msat: None,
2733 htlc_maximum_msat: None,
2734 }]), RouteHint(vec![RouteHintHop {
2735 src_node_id: nodes[4],
2736 short_channel_id: 9,
2739 proportional_millionths: 0,
2741 cltv_expiry_delta: (9 << 8) | 1,
2742 htlc_minimum_msat: None,
2743 htlc_maximum_msat: None,
2744 }]), RouteHint(vec![RouteHintHop {
2745 src_node_id: nodes[5],
2746 short_channel_id: 10,
2748 cltv_expiry_delta: (10 << 8) | 1,
2749 htlc_minimum_msat: None,
2750 htlc_maximum_msat: None,
2755 fn last_hops_with_public_channel_test() {
2756 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
2757 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
2758 let payee = Payee::new(nodes[6]).with_route_hints(last_hops_with_public_channel(&nodes));
2759 let scorer = Scorer::new(0);
2760 // This test shows that public routes can be present in the invoice
2761 // which would be handled in the same manner.
2763 let route = get_route(&our_id, &payee, &net_graph_msg_handler.network_graph, None, 100, 42, Arc::clone(&logger), &scorer).unwrap();
2764 assert_eq!(route.paths[0].len(), 5);
2766 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
2767 assert_eq!(route.paths[0][0].short_channel_id, 2);
2768 assert_eq!(route.paths[0][0].fee_msat, 100);
2769 assert_eq!(route.paths[0][0].cltv_expiry_delta, (4 << 8) | 1);
2770 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
2771 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
2773 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2774 assert_eq!(route.paths[0][1].short_channel_id, 4);
2775 assert_eq!(route.paths[0][1].fee_msat, 0);
2776 assert_eq!(route.paths[0][1].cltv_expiry_delta, (6 << 8) | 1);
2777 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2778 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
2780 assert_eq!(route.paths[0][2].pubkey, nodes[4]);
2781 assert_eq!(route.paths[0][2].short_channel_id, 6);
2782 assert_eq!(route.paths[0][2].fee_msat, 0);
2783 assert_eq!(route.paths[0][2].cltv_expiry_delta, (11 << 8) | 1);
2784 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(5));
2785 assert_eq!(route.paths[0][2].channel_features.le_flags(), &id_to_feature_flags(6));
2787 assert_eq!(route.paths[0][3].pubkey, nodes[3]);
2788 assert_eq!(route.paths[0][3].short_channel_id, 11);
2789 assert_eq!(route.paths[0][3].fee_msat, 0);
2790 assert_eq!(route.paths[0][3].cltv_expiry_delta, (8 << 8) | 1);
2791 // If we have a peer in the node map, we'll use their features here since we don't have
2792 // a way of figuring out their features from the invoice:
2793 assert_eq!(route.paths[0][3].node_features.le_flags(), &id_to_feature_flags(4));
2794 assert_eq!(route.paths[0][3].channel_features.le_flags(), &Vec::<u8>::new());
2796 assert_eq!(route.paths[0][4].pubkey, nodes[6]);
2797 assert_eq!(route.paths[0][4].short_channel_id, 8);
2798 assert_eq!(route.paths[0][4].fee_msat, 100);
2799 assert_eq!(route.paths[0][4].cltv_expiry_delta, 42);
2800 assert_eq!(route.paths[0][4].node_features.le_flags(), &Vec::<u8>::new()); // We dont pass flags in from invoices yet
2801 assert_eq!(route.paths[0][4].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
2805 fn our_chans_last_hop_connect_test() {
2806 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
2807 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
2808 let scorer = Scorer::new(0);
2810 // Simple test with outbound channel to 4 to test that last_hops and first_hops connect
2811 let our_chans = vec![get_channel_details(Some(42), nodes[3].clone(), InitFeatures::from_le_bytes(vec![0b11]), 250_000_000)];
2812 let mut last_hops = last_hops(&nodes);
2813 let payee = Payee::new(nodes[6]).with_route_hints(last_hops.clone());
2814 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();
2815 assert_eq!(route.paths[0].len(), 2);
2817 assert_eq!(route.paths[0][0].pubkey, nodes[3]);
2818 assert_eq!(route.paths[0][0].short_channel_id, 42);
2819 assert_eq!(route.paths[0][0].fee_msat, 0);
2820 assert_eq!(route.paths[0][0].cltv_expiry_delta, (8 << 8) | 1);
2821 assert_eq!(route.paths[0][0].node_features.le_flags(), &vec![0b11]);
2822 assert_eq!(route.paths[0][0].channel_features.le_flags(), &Vec::<u8>::new()); // No feature flags will meet the relevant-to-channel conversion
2824 assert_eq!(route.paths[0][1].pubkey, nodes[6]);
2825 assert_eq!(route.paths[0][1].short_channel_id, 8);
2826 assert_eq!(route.paths[0][1].fee_msat, 100);
2827 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
2828 assert_eq!(route.paths[0][1].node_features.le_flags(), &Vec::<u8>::new()); // We dont pass flags in from invoices yet
2829 assert_eq!(route.paths[0][1].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
2831 last_hops[0].0[0].fees.base_msat = 1000;
2833 // Revert to via 6 as the fee on 8 goes up
2834 let payee = Payee::new(nodes[6]).with_route_hints(last_hops);
2835 let route = get_route(&our_id, &payee, &net_graph_msg_handler.network_graph, None, 100, 42, Arc::clone(&logger), &scorer).unwrap();
2836 assert_eq!(route.paths[0].len(), 4);
2838 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
2839 assert_eq!(route.paths[0][0].short_channel_id, 2);
2840 assert_eq!(route.paths[0][0].fee_msat, 200); // fee increased as its % of value transferred across node
2841 assert_eq!(route.paths[0][0].cltv_expiry_delta, (4 << 8) | 1);
2842 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
2843 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
2845 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2846 assert_eq!(route.paths[0][1].short_channel_id, 4);
2847 assert_eq!(route.paths[0][1].fee_msat, 100);
2848 assert_eq!(route.paths[0][1].cltv_expiry_delta, (7 << 8) | 1);
2849 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2850 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
2852 assert_eq!(route.paths[0][2].pubkey, nodes[5]);
2853 assert_eq!(route.paths[0][2].short_channel_id, 7);
2854 assert_eq!(route.paths[0][2].fee_msat, 0);
2855 assert_eq!(route.paths[0][2].cltv_expiry_delta, (10 << 8) | 1);
2856 // If we have a peer in the node map, we'll use their features here since we don't have
2857 // a way of figuring out their features from the invoice:
2858 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(6));
2859 assert_eq!(route.paths[0][2].channel_features.le_flags(), &id_to_feature_flags(7));
2861 assert_eq!(route.paths[0][3].pubkey, nodes[6]);
2862 assert_eq!(route.paths[0][3].short_channel_id, 10);
2863 assert_eq!(route.paths[0][3].fee_msat, 100);
2864 assert_eq!(route.paths[0][3].cltv_expiry_delta, 42);
2865 assert_eq!(route.paths[0][3].node_features.le_flags(), &Vec::<u8>::new()); // We dont pass flags in from invoices yet
2866 assert_eq!(route.paths[0][3].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
2868 // ...but still use 8 for larger payments as 6 has a variable feerate
2869 let route = get_route(&our_id, &payee, &net_graph_msg_handler.network_graph, None, 2000, 42, Arc::clone(&logger), &scorer).unwrap();
2870 assert_eq!(route.paths[0].len(), 5);
2872 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
2873 assert_eq!(route.paths[0][0].short_channel_id, 2);
2874 assert_eq!(route.paths[0][0].fee_msat, 3000);
2875 assert_eq!(route.paths[0][0].cltv_expiry_delta, (4 << 8) | 1);
2876 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
2877 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
2879 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2880 assert_eq!(route.paths[0][1].short_channel_id, 4);
2881 assert_eq!(route.paths[0][1].fee_msat, 0);
2882 assert_eq!(route.paths[0][1].cltv_expiry_delta, (6 << 8) | 1);
2883 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2884 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
2886 assert_eq!(route.paths[0][2].pubkey, nodes[4]);
2887 assert_eq!(route.paths[0][2].short_channel_id, 6);
2888 assert_eq!(route.paths[0][2].fee_msat, 0);
2889 assert_eq!(route.paths[0][2].cltv_expiry_delta, (11 << 8) | 1);
2890 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(5));
2891 assert_eq!(route.paths[0][2].channel_features.le_flags(), &id_to_feature_flags(6));
2893 assert_eq!(route.paths[0][3].pubkey, nodes[3]);
2894 assert_eq!(route.paths[0][3].short_channel_id, 11);
2895 assert_eq!(route.paths[0][3].fee_msat, 1000);
2896 assert_eq!(route.paths[0][3].cltv_expiry_delta, (8 << 8) | 1);
2897 // If we have a peer in the node map, we'll use their features here since we don't have
2898 // a way of figuring out their features from the invoice:
2899 assert_eq!(route.paths[0][3].node_features.le_flags(), &id_to_feature_flags(4));
2900 assert_eq!(route.paths[0][3].channel_features.le_flags(), &id_to_feature_flags(11));
2902 assert_eq!(route.paths[0][4].pubkey, nodes[6]);
2903 assert_eq!(route.paths[0][4].short_channel_id, 8);
2904 assert_eq!(route.paths[0][4].fee_msat, 2000);
2905 assert_eq!(route.paths[0][4].cltv_expiry_delta, 42);
2906 assert_eq!(route.paths[0][4].node_features.le_flags(), &Vec::<u8>::new()); // We dont pass flags in from invoices yet
2907 assert_eq!(route.paths[0][4].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
2910 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> {
2911 let source_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&hex::decode(format!("{:02}", 41).repeat(32)).unwrap()[..]).unwrap());
2912 let middle_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&hex::decode(format!("{:02}", 42).repeat(32)).unwrap()[..]).unwrap());
2913 let target_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&hex::decode(format!("{:02}", 43).repeat(32)).unwrap()[..]).unwrap());
2915 // If we specify a channel to a middle hop, that overrides our local channel view and that gets used
2916 let last_hops = RouteHint(vec![RouteHintHop {
2917 src_node_id: middle_node_id,
2918 short_channel_id: 8,
2921 proportional_millionths: last_hop_fee_prop,
2923 cltv_expiry_delta: (8 << 8) | 1,
2924 htlc_minimum_msat: None,
2925 htlc_maximum_msat: last_hop_htlc_max,
2927 let payee = Payee::new(target_node_id).with_route_hints(vec![last_hops]);
2928 let our_chans = vec![get_channel_details(Some(42), middle_node_id, InitFeatures::from_le_bytes(vec![0b11]), outbound_capacity_msat)];
2929 let scorer = Scorer::new(0);
2930 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)
2934 fn unannounced_path_test() {
2935 // We should be able to send a payment to a destination without any help of a routing graph
2936 // if we have a channel with a common counterparty that appears in the first and last hop
2938 let route = do_unannounced_path_test(None, 1, 2000000, 1000000).unwrap();
2940 let middle_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&hex::decode(format!("{:02}", 42).repeat(32)).unwrap()[..]).unwrap());
2941 let target_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&hex::decode(format!("{:02}", 43).repeat(32)).unwrap()[..]).unwrap());
2942 assert_eq!(route.paths[0].len(), 2);
2944 assert_eq!(route.paths[0][0].pubkey, middle_node_id);
2945 assert_eq!(route.paths[0][0].short_channel_id, 42);
2946 assert_eq!(route.paths[0][0].fee_msat, 1001);
2947 assert_eq!(route.paths[0][0].cltv_expiry_delta, (8 << 8) | 1);
2948 assert_eq!(route.paths[0][0].node_features.le_flags(), &[0b11]);
2949 assert_eq!(route.paths[0][0].channel_features.le_flags(), &[0; 0]); // We can't learn any flags from invoices, sadly
2951 assert_eq!(route.paths[0][1].pubkey, target_node_id);
2952 assert_eq!(route.paths[0][1].short_channel_id, 8);
2953 assert_eq!(route.paths[0][1].fee_msat, 1000000);
2954 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
2955 assert_eq!(route.paths[0][1].node_features.le_flags(), &[0; 0]); // We dont pass flags in from invoices yet
2956 assert_eq!(route.paths[0][1].channel_features.le_flags(), &[0; 0]); // We can't learn any flags from invoices, sadly
2960 fn overflow_unannounced_path_test_liquidity_underflow() {
2961 // Previously, when we had a last-hop hint connected directly to a first-hop channel, where
2962 // the last-hop had a fee which overflowed a u64, we'd panic.
2963 // This was due to us adding the first-hop from us unconditionally, causing us to think
2964 // we'd built a path (as our node is in the "best candidate" set), when we had not.
2965 // In this test, we previously hit a subtraction underflow due to having less available
2966 // liquidity at the last hop than 0.
2967 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());
2971 fn overflow_unannounced_path_test_feerate_overflow() {
2972 // This tests for the same case as above, except instead of hitting a subtraction
2973 // underflow, we hit a case where the fee charged at a hop overflowed.
2974 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());
2978 fn available_amount_while_routing_test() {
2979 // Tests whether we choose the correct available channel amount while routing.
2981 let (secp_ctx, mut net_graph_msg_handler, chain_monitor, logger) = build_graph();
2982 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
2983 let scorer = Scorer::new(0);
2984 let payee = Payee::new(nodes[2]).with_features(InvoiceFeatures::known());
2986 // We will use a simple single-path route from
2987 // our node to node2 via node0: channels {1, 3}.
2989 // First disable all other paths.
2990 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2991 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2992 short_channel_id: 2,
2995 cltv_expiry_delta: 0,
2996 htlc_minimum_msat: 0,
2997 htlc_maximum_msat: OptionalField::Present(100_000),
2999 fee_proportional_millionths: 0,
3000 excess_data: Vec::new()
3002 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3003 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3004 short_channel_id: 12,
3007 cltv_expiry_delta: 0,
3008 htlc_minimum_msat: 0,
3009 htlc_maximum_msat: OptionalField::Present(100_000),
3011 fee_proportional_millionths: 0,
3012 excess_data: Vec::new()
3015 // Make the first channel (#1) very permissive,
3016 // and we will be testing all limits on the second channel.
3017 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3018 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3019 short_channel_id: 1,
3022 cltv_expiry_delta: 0,
3023 htlc_minimum_msat: 0,
3024 htlc_maximum_msat: OptionalField::Present(1_000_000_000),
3026 fee_proportional_millionths: 0,
3027 excess_data: Vec::new()
3030 // First, let's see if routing works if we have absolutely no idea about the available amount.
3031 // In this case, it should be set to 250_000 sats.
3032 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3033 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3034 short_channel_id: 3,
3037 cltv_expiry_delta: 0,
3038 htlc_minimum_msat: 0,
3039 htlc_maximum_msat: OptionalField::Absent,
3041 fee_proportional_millionths: 0,
3042 excess_data: Vec::new()
3046 // Attempt to route more than available results in a failure.
3047 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
3048 &our_id, &payee, &net_graph_msg_handler.network_graph, None, 250_000_001, 42, Arc::clone(&logger), &scorer) {
3049 assert_eq!(err, "Failed to find a sufficient route to the given destination");
3050 } else { panic!(); }
3054 // Now, attempt to route an exact amount we have should be fine.
3055 let route = get_route(&our_id, &payee, &net_graph_msg_handler.network_graph, None, 250_000_000, 42, Arc::clone(&logger), &scorer).unwrap();
3056 assert_eq!(route.paths.len(), 1);
3057 let path = route.paths.last().unwrap();
3058 assert_eq!(path.len(), 2);
3059 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
3060 assert_eq!(path.last().unwrap().fee_msat, 250_000_000);
3063 // Check that setting outbound_capacity_msat in first_hops limits the channels.
3064 // Disable channel #1 and use another first hop.
3065 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3066 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3067 short_channel_id: 1,
3070 cltv_expiry_delta: 0,
3071 htlc_minimum_msat: 0,
3072 htlc_maximum_msat: OptionalField::Present(1_000_000_000),
3074 fee_proportional_millionths: 0,
3075 excess_data: Vec::new()
3078 // Now, limit the first_hop by the outbound_capacity_msat of 200_000 sats.
3079 let our_chans = vec![get_channel_details(Some(42), nodes[0].clone(), InitFeatures::from_le_bytes(vec![0b11]), 200_000_000)];
3082 // Attempt to route more than available results in a failure.
3083 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
3084 &our_id, &payee, &net_graph_msg_handler.network_graph, Some(&our_chans.iter().collect::<Vec<_>>()), 200_000_001, 42, Arc::clone(&logger), &scorer) {
3085 assert_eq!(err, "Failed to find a sufficient route to the given destination");
3086 } else { panic!(); }
3090 // Now, attempt to route an exact amount we have should be fine.
3091 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();
3092 assert_eq!(route.paths.len(), 1);
3093 let path = route.paths.last().unwrap();
3094 assert_eq!(path.len(), 2);
3095 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
3096 assert_eq!(path.last().unwrap().fee_msat, 200_000_000);
3099 // Enable channel #1 back.
3100 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3101 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3102 short_channel_id: 1,
3105 cltv_expiry_delta: 0,
3106 htlc_minimum_msat: 0,
3107 htlc_maximum_msat: OptionalField::Present(1_000_000_000),
3109 fee_proportional_millionths: 0,
3110 excess_data: Vec::new()
3114 // Now let's see if routing works if we know only htlc_maximum_msat.
3115 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3116 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3117 short_channel_id: 3,
3120 cltv_expiry_delta: 0,
3121 htlc_minimum_msat: 0,
3122 htlc_maximum_msat: OptionalField::Present(15_000),
3124 fee_proportional_millionths: 0,
3125 excess_data: Vec::new()
3129 // Attempt to route more than available results in a failure.
3130 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
3131 &our_id, &payee, &net_graph_msg_handler.network_graph, None, 15_001, 42, Arc::clone(&logger), &scorer) {
3132 assert_eq!(err, "Failed to find a sufficient route to the given destination");
3133 } else { panic!(); }
3137 // Now, attempt to route an exact amount we have should be fine.
3138 let route = get_route(&our_id, &payee, &net_graph_msg_handler.network_graph, None, 15_000, 42, Arc::clone(&logger), &scorer).unwrap();
3139 assert_eq!(route.paths.len(), 1);
3140 let path = route.paths.last().unwrap();
3141 assert_eq!(path.len(), 2);
3142 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
3143 assert_eq!(path.last().unwrap().fee_msat, 15_000);
3146 // Now let's see if routing works if we know only capacity from the UTXO.
3148 // We can't change UTXO capacity on the fly, so we'll disable
3149 // the existing channel and add another one with the capacity we need.
3150 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3151 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3152 short_channel_id: 3,
3155 cltv_expiry_delta: 0,
3156 htlc_minimum_msat: 0,
3157 htlc_maximum_msat: OptionalField::Absent,
3159 fee_proportional_millionths: 0,
3160 excess_data: Vec::new()
3163 let good_script = Builder::new().push_opcode(opcodes::all::OP_PUSHNUM_2)
3164 .push_slice(&PublicKey::from_secret_key(&secp_ctx, &privkeys[0]).serialize())
3165 .push_slice(&PublicKey::from_secret_key(&secp_ctx, &privkeys[2]).serialize())
3166 .push_opcode(opcodes::all::OP_PUSHNUM_2)
3167 .push_opcode(opcodes::all::OP_CHECKMULTISIG).into_script().to_v0_p2wsh();
3169 *chain_monitor.utxo_ret.lock().unwrap() = Ok(TxOut { value: 15, script_pubkey: good_script.clone() });
3170 net_graph_msg_handler.add_chain_access(Some(chain_monitor));
3172 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], &privkeys[2], ChannelFeatures::from_le_bytes(id_to_feature_flags(3)), 333);
3173 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3174 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3175 short_channel_id: 333,
3178 cltv_expiry_delta: (3 << 8) | 1,
3179 htlc_minimum_msat: 0,
3180 htlc_maximum_msat: OptionalField::Absent,
3182 fee_proportional_millionths: 0,
3183 excess_data: Vec::new()
3185 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3186 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3187 short_channel_id: 333,
3190 cltv_expiry_delta: (3 << 8) | 2,
3191 htlc_minimum_msat: 0,
3192 htlc_maximum_msat: OptionalField::Absent,
3194 fee_proportional_millionths: 0,
3195 excess_data: Vec::new()
3199 // Attempt to route more than available results in a failure.
3200 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
3201 &our_id, &payee, &net_graph_msg_handler.network_graph, None, 15_001, 42, Arc::clone(&logger), &scorer) {
3202 assert_eq!(err, "Failed to find a sufficient route to the given destination");
3203 } else { panic!(); }
3207 // Now, attempt to route an exact amount we have should be fine.
3208 let route = get_route(&our_id, &payee, &net_graph_msg_handler.network_graph, None, 15_000, 42, Arc::clone(&logger), &scorer).unwrap();
3209 assert_eq!(route.paths.len(), 1);
3210 let path = route.paths.last().unwrap();
3211 assert_eq!(path.len(), 2);
3212 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
3213 assert_eq!(path.last().unwrap().fee_msat, 15_000);
3216 // Now let's see if routing chooses htlc_maximum_msat over UTXO capacity.
3217 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3218 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3219 short_channel_id: 333,
3222 cltv_expiry_delta: 0,
3223 htlc_minimum_msat: 0,
3224 htlc_maximum_msat: OptionalField::Present(10_000),
3226 fee_proportional_millionths: 0,
3227 excess_data: Vec::new()
3231 // Attempt to route more than available results in a failure.
3232 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
3233 &our_id, &payee, &net_graph_msg_handler.network_graph, None, 10_001, 42, Arc::clone(&logger), &scorer) {
3234 assert_eq!(err, "Failed to find a sufficient route to the given destination");
3235 } else { panic!(); }
3239 // Now, attempt to route an exact amount we have should be fine.
3240 let route = get_route(&our_id, &payee, &net_graph_msg_handler.network_graph, None, 10_000, 42, Arc::clone(&logger), &scorer).unwrap();
3241 assert_eq!(route.paths.len(), 1);
3242 let path = route.paths.last().unwrap();
3243 assert_eq!(path.len(), 2);
3244 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
3245 assert_eq!(path.last().unwrap().fee_msat, 10_000);
3250 fn available_liquidity_last_hop_test() {
3251 // Check that available liquidity properly limits the path even when only
3252 // one of the latter hops is limited.
3253 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
3254 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3255 let scorer = Scorer::new(0);
3256 let payee = Payee::new(nodes[3]).with_features(InvoiceFeatures::known());
3258 // Path via {node7, node2, node4} is channels {12, 13, 6, 11}.
3259 // {12, 13, 11} have the capacities of 100, {6} has a capacity of 50.
3260 // Total capacity: 50 sats.
3262 // Disable other potential paths.
3263 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3264 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3265 short_channel_id: 2,
3268 cltv_expiry_delta: 0,
3269 htlc_minimum_msat: 0,
3270 htlc_maximum_msat: OptionalField::Present(100_000),
3272 fee_proportional_millionths: 0,
3273 excess_data: Vec::new()
3275 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3276 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3277 short_channel_id: 7,
3280 cltv_expiry_delta: 0,
3281 htlc_minimum_msat: 0,
3282 htlc_maximum_msat: OptionalField::Present(100_000),
3284 fee_proportional_millionths: 0,
3285 excess_data: Vec::new()
3290 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3291 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3292 short_channel_id: 12,
3295 cltv_expiry_delta: 0,
3296 htlc_minimum_msat: 0,
3297 htlc_maximum_msat: OptionalField::Present(100_000),
3299 fee_proportional_millionths: 0,
3300 excess_data: Vec::new()
3302 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
3303 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3304 short_channel_id: 13,
3307 cltv_expiry_delta: 0,
3308 htlc_minimum_msat: 0,
3309 htlc_maximum_msat: OptionalField::Present(100_000),
3311 fee_proportional_millionths: 0,
3312 excess_data: Vec::new()
3315 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3316 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3317 short_channel_id: 6,
3320 cltv_expiry_delta: 0,
3321 htlc_minimum_msat: 0,
3322 htlc_maximum_msat: OptionalField::Present(50_000),
3324 fee_proportional_millionths: 0,
3325 excess_data: Vec::new()
3327 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
3328 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3329 short_channel_id: 11,
3332 cltv_expiry_delta: 0,
3333 htlc_minimum_msat: 0,
3334 htlc_maximum_msat: OptionalField::Present(100_000),
3336 fee_proportional_millionths: 0,
3337 excess_data: Vec::new()
3340 // Attempt to route more than available results in a failure.
3341 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
3342 &our_id, &payee, &net_graph_msg_handler.network_graph, None, 60_000, 42, Arc::clone(&logger), &scorer) {
3343 assert_eq!(err, "Failed to find a sufficient route to the given destination");
3344 } else { panic!(); }
3348 // Now, attempt to route 49 sats (just a bit below the capacity).
3349 let route = get_route(&our_id, &payee, &net_graph_msg_handler.network_graph, None, 49_000, 42, Arc::clone(&logger), &scorer).unwrap();
3350 assert_eq!(route.paths.len(), 1);
3351 let mut total_amount_paid_msat = 0;
3352 for path in &route.paths {
3353 assert_eq!(path.len(), 4);
3354 assert_eq!(path.last().unwrap().pubkey, nodes[3]);
3355 total_amount_paid_msat += path.last().unwrap().fee_msat;
3357 assert_eq!(total_amount_paid_msat, 49_000);
3361 // Attempt to route an exact amount is also fine
3362 let route = get_route(&our_id, &payee, &net_graph_msg_handler.network_graph, None, 50_000, 42, Arc::clone(&logger), &scorer).unwrap();
3363 assert_eq!(route.paths.len(), 1);
3364 let mut total_amount_paid_msat = 0;
3365 for path in &route.paths {
3366 assert_eq!(path.len(), 4);
3367 assert_eq!(path.last().unwrap().pubkey, nodes[3]);
3368 total_amount_paid_msat += path.last().unwrap().fee_msat;
3370 assert_eq!(total_amount_paid_msat, 50_000);
3375 fn ignore_fee_first_hop_test() {
3376 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
3377 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3378 let scorer = Scorer::new(0);
3379 let payee = Payee::new(nodes[2]);
3381 // Path via node0 is channels {1, 3}. Limit them to 100 and 50 sats (total limit 50).
3382 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3383 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3384 short_channel_id: 1,
3387 cltv_expiry_delta: 0,
3388 htlc_minimum_msat: 0,
3389 htlc_maximum_msat: OptionalField::Present(100_000),
3390 fee_base_msat: 1_000_000,
3391 fee_proportional_millionths: 0,
3392 excess_data: Vec::new()
3394 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3395 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3396 short_channel_id: 3,
3399 cltv_expiry_delta: 0,
3400 htlc_minimum_msat: 0,
3401 htlc_maximum_msat: OptionalField::Present(50_000),
3403 fee_proportional_millionths: 0,
3404 excess_data: Vec::new()
3408 let route = get_route(&our_id, &payee, &net_graph_msg_handler.network_graph, None, 50_000, 42, Arc::clone(&logger), &scorer).unwrap();
3409 assert_eq!(route.paths.len(), 1);
3410 let mut total_amount_paid_msat = 0;
3411 for path in &route.paths {
3412 assert_eq!(path.len(), 2);
3413 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
3414 total_amount_paid_msat += path.last().unwrap().fee_msat;
3416 assert_eq!(total_amount_paid_msat, 50_000);
3421 fn simple_mpp_route_test() {
3422 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
3423 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3424 let scorer = Scorer::new(0);
3425 let payee = Payee::new(nodes[2]).with_features(InvoiceFeatures::known());
3427 // We need a route consisting of 3 paths:
3428 // From our node to node2 via node0, node7, node1 (three paths one hop each).
3429 // To achieve this, the amount being transferred should be around
3430 // the total capacity of these 3 paths.
3432 // First, we set limits on these (previously unlimited) channels.
3433 // Their aggregate capacity will be 50 + 60 + 180 = 290 sats.
3435 // Path via node0 is channels {1, 3}. Limit them to 100 and 50 sats (total limit 50).
3436 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3437 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3438 short_channel_id: 1,
3441 cltv_expiry_delta: 0,
3442 htlc_minimum_msat: 0,
3443 htlc_maximum_msat: OptionalField::Present(100_000),
3445 fee_proportional_millionths: 0,
3446 excess_data: Vec::new()
3448 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3449 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3450 short_channel_id: 3,
3453 cltv_expiry_delta: 0,
3454 htlc_minimum_msat: 0,
3455 htlc_maximum_msat: OptionalField::Present(50_000),
3457 fee_proportional_millionths: 0,
3458 excess_data: Vec::new()
3461 // Path via node7 is channels {12, 13}. Limit them to 60 and 60 sats
3462 // (total limit 60).
3463 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3464 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3465 short_channel_id: 12,
3468 cltv_expiry_delta: 0,
3469 htlc_minimum_msat: 0,
3470 htlc_maximum_msat: OptionalField::Present(60_000),
3472 fee_proportional_millionths: 0,
3473 excess_data: Vec::new()
3475 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
3476 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3477 short_channel_id: 13,
3480 cltv_expiry_delta: 0,
3481 htlc_minimum_msat: 0,
3482 htlc_maximum_msat: OptionalField::Present(60_000),
3484 fee_proportional_millionths: 0,
3485 excess_data: Vec::new()
3488 // Path via node1 is channels {2, 4}. Limit them to 200 and 180 sats
3489 // (total capacity 180 sats).
3490 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3491 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3492 short_channel_id: 2,
3495 cltv_expiry_delta: 0,
3496 htlc_minimum_msat: 0,
3497 htlc_maximum_msat: OptionalField::Present(200_000),
3499 fee_proportional_millionths: 0,
3500 excess_data: Vec::new()
3502 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
3503 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3504 short_channel_id: 4,
3507 cltv_expiry_delta: 0,
3508 htlc_minimum_msat: 0,
3509 htlc_maximum_msat: OptionalField::Present(180_000),
3511 fee_proportional_millionths: 0,
3512 excess_data: Vec::new()
3516 // Attempt to route more than available results in a failure.
3517 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
3518 &our_id, &payee, &net_graph_msg_handler.network_graph, None, 300_000, 42, Arc::clone(&logger), &scorer) {
3519 assert_eq!(err, "Failed to find a sufficient route to the given destination");
3520 } else { panic!(); }
3524 // Now, attempt to route 250 sats (just a bit below the capacity).
3525 // Our algorithm should provide us with these 3 paths.
3526 let route = get_route(&our_id, &payee, &net_graph_msg_handler.network_graph, None, 250_000, 42, Arc::clone(&logger), &scorer).unwrap();
3527 assert_eq!(route.paths.len(), 3);
3528 let mut total_amount_paid_msat = 0;
3529 for path in &route.paths {
3530 assert_eq!(path.len(), 2);
3531 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
3532 total_amount_paid_msat += path.last().unwrap().fee_msat;
3534 assert_eq!(total_amount_paid_msat, 250_000);
3538 // Attempt to route an exact amount is also fine
3539 let route = get_route(&our_id, &payee, &net_graph_msg_handler.network_graph, None, 290_000, 42, Arc::clone(&logger), &scorer).unwrap();
3540 assert_eq!(route.paths.len(), 3);
3541 let mut total_amount_paid_msat = 0;
3542 for path in &route.paths {
3543 assert_eq!(path.len(), 2);
3544 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
3545 total_amount_paid_msat += path.last().unwrap().fee_msat;
3547 assert_eq!(total_amount_paid_msat, 290_000);
3552 fn long_mpp_route_test() {
3553 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
3554 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3555 let scorer = Scorer::new(0);
3556 let payee = Payee::new(nodes[3]).with_features(InvoiceFeatures::known());
3558 // We need a route consisting of 3 paths:
3559 // From our node to node3 via {node0, node2}, {node7, node2, node4} and {node7, node2}.
3560 // Note that these paths overlap (channels 5, 12, 13).
3561 // We will route 300 sats.
3562 // Each path will have 100 sats capacity, those channels which
3563 // are used twice will have 200 sats capacity.
3565 // Disable other potential paths.
3566 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3567 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3568 short_channel_id: 2,
3571 cltv_expiry_delta: 0,
3572 htlc_minimum_msat: 0,
3573 htlc_maximum_msat: OptionalField::Present(100_000),
3575 fee_proportional_millionths: 0,
3576 excess_data: Vec::new()
3578 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3579 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3580 short_channel_id: 7,
3583 cltv_expiry_delta: 0,
3584 htlc_minimum_msat: 0,
3585 htlc_maximum_msat: OptionalField::Present(100_000),
3587 fee_proportional_millionths: 0,
3588 excess_data: Vec::new()
3591 // Path via {node0, node2} is channels {1, 3, 5}.
3592 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3593 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3594 short_channel_id: 1,
3597 cltv_expiry_delta: 0,
3598 htlc_minimum_msat: 0,
3599 htlc_maximum_msat: OptionalField::Present(100_000),
3601 fee_proportional_millionths: 0,
3602 excess_data: Vec::new()
3604 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3605 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3606 short_channel_id: 3,
3609 cltv_expiry_delta: 0,
3610 htlc_minimum_msat: 0,
3611 htlc_maximum_msat: OptionalField::Present(100_000),
3613 fee_proportional_millionths: 0,
3614 excess_data: Vec::new()
3617 // Capacity of 200 sats because this channel will be used by 3rd path as well.
3618 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(5)), 5);
3619 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3620 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3621 short_channel_id: 5,
3624 cltv_expiry_delta: 0,
3625 htlc_minimum_msat: 0,
3626 htlc_maximum_msat: OptionalField::Present(200_000),
3628 fee_proportional_millionths: 0,
3629 excess_data: Vec::new()
3632 // Path via {node7, node2, node4} is channels {12, 13, 6, 11}.
3633 // Add 100 sats to the capacities of {12, 13}, because these channels
3634 // are also used for 3rd path. 100 sats for the rest. Total capacity: 100 sats.
3635 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3636 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3637 short_channel_id: 12,
3640 cltv_expiry_delta: 0,
3641 htlc_minimum_msat: 0,
3642 htlc_maximum_msat: OptionalField::Present(200_000),
3644 fee_proportional_millionths: 0,
3645 excess_data: Vec::new()
3647 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
3648 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3649 short_channel_id: 13,
3652 cltv_expiry_delta: 0,
3653 htlc_minimum_msat: 0,
3654 htlc_maximum_msat: OptionalField::Present(200_000),
3656 fee_proportional_millionths: 0,
3657 excess_data: Vec::new()
3660 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3661 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3662 short_channel_id: 6,
3665 cltv_expiry_delta: 0,
3666 htlc_minimum_msat: 0,
3667 htlc_maximum_msat: OptionalField::Present(100_000),
3669 fee_proportional_millionths: 0,
3670 excess_data: Vec::new()
3672 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
3673 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3674 short_channel_id: 11,
3677 cltv_expiry_delta: 0,
3678 htlc_minimum_msat: 0,
3679 htlc_maximum_msat: OptionalField::Present(100_000),
3681 fee_proportional_millionths: 0,
3682 excess_data: Vec::new()
3685 // Path via {node7, node2} is channels {12, 13, 5}.
3686 // We already limited them to 200 sats (they are used twice for 100 sats).
3687 // Nothing to do here.
3690 // Attempt to route more than available results in a failure.
3691 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
3692 &our_id, &payee, &net_graph_msg_handler.network_graph, None, 350_000, 42, Arc::clone(&logger), &scorer) {
3693 assert_eq!(err, "Failed to find a sufficient route to the given destination");
3694 } else { panic!(); }
3698 // Now, attempt to route 300 sats (exact amount we can route).
3699 // Our algorithm should provide us with these 3 paths, 100 sats each.
3700 let route = get_route(&our_id, &payee, &net_graph_msg_handler.network_graph, None, 300_000, 42, Arc::clone(&logger), &scorer).unwrap();
3701 assert_eq!(route.paths.len(), 3);
3703 let mut total_amount_paid_msat = 0;
3704 for path in &route.paths {
3705 assert_eq!(path.last().unwrap().pubkey, nodes[3]);
3706 total_amount_paid_msat += path.last().unwrap().fee_msat;
3708 assert_eq!(total_amount_paid_msat, 300_000);
3714 fn mpp_cheaper_route_test() {
3715 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
3716 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3717 let scorer = Scorer::new(0);
3718 let payee = Payee::new(nodes[3]).with_features(InvoiceFeatures::known());
3720 // This test checks that if we have two cheaper paths and one more expensive path,
3721 // so that liquidity-wise any 2 of 3 combination is sufficient,
3722 // two cheaper paths will be taken.
3723 // These paths have equal available liquidity.
3725 // We need a combination of 3 paths:
3726 // From our node to node3 via {node0, node2}, {node7, node2, node4} and {node7, node2}.
3727 // Note that these paths overlap (channels 5, 12, 13).
3728 // Each path will have 100 sats capacity, those channels which
3729 // are used twice will have 200 sats capacity.
3731 // Disable other potential paths.
3732 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3733 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3734 short_channel_id: 2,
3737 cltv_expiry_delta: 0,
3738 htlc_minimum_msat: 0,
3739 htlc_maximum_msat: OptionalField::Present(100_000),
3741 fee_proportional_millionths: 0,
3742 excess_data: Vec::new()
3744 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3745 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3746 short_channel_id: 7,
3749 cltv_expiry_delta: 0,
3750 htlc_minimum_msat: 0,
3751 htlc_maximum_msat: OptionalField::Present(100_000),
3753 fee_proportional_millionths: 0,
3754 excess_data: Vec::new()
3757 // Path via {node0, node2} is channels {1, 3, 5}.
3758 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3759 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3760 short_channel_id: 1,
3763 cltv_expiry_delta: 0,
3764 htlc_minimum_msat: 0,
3765 htlc_maximum_msat: OptionalField::Present(100_000),
3767 fee_proportional_millionths: 0,
3768 excess_data: Vec::new()
3770 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3771 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3772 short_channel_id: 3,
3775 cltv_expiry_delta: 0,
3776 htlc_minimum_msat: 0,
3777 htlc_maximum_msat: OptionalField::Present(100_000),
3779 fee_proportional_millionths: 0,
3780 excess_data: Vec::new()
3783 // Capacity of 200 sats because this channel will be used by 3rd path as well.
3784 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(5)), 5);
3785 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3786 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3787 short_channel_id: 5,
3790 cltv_expiry_delta: 0,
3791 htlc_minimum_msat: 0,
3792 htlc_maximum_msat: OptionalField::Present(200_000),
3794 fee_proportional_millionths: 0,
3795 excess_data: Vec::new()
3798 // Path via {node7, node2, node4} is channels {12, 13, 6, 11}.
3799 // Add 100 sats to the capacities of {12, 13}, because these channels
3800 // are also used for 3rd path. 100 sats for the rest. Total capacity: 100 sats.
3801 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3802 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3803 short_channel_id: 12,
3806 cltv_expiry_delta: 0,
3807 htlc_minimum_msat: 0,
3808 htlc_maximum_msat: OptionalField::Present(200_000),
3810 fee_proportional_millionths: 0,
3811 excess_data: Vec::new()
3813 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
3814 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3815 short_channel_id: 13,
3818 cltv_expiry_delta: 0,
3819 htlc_minimum_msat: 0,
3820 htlc_maximum_msat: OptionalField::Present(200_000),
3822 fee_proportional_millionths: 0,
3823 excess_data: Vec::new()
3826 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3827 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3828 short_channel_id: 6,
3831 cltv_expiry_delta: 0,
3832 htlc_minimum_msat: 0,
3833 htlc_maximum_msat: OptionalField::Present(100_000),
3834 fee_base_msat: 1_000,
3835 fee_proportional_millionths: 0,
3836 excess_data: Vec::new()
3838 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
3839 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3840 short_channel_id: 11,
3843 cltv_expiry_delta: 0,
3844 htlc_minimum_msat: 0,
3845 htlc_maximum_msat: OptionalField::Present(100_000),
3847 fee_proportional_millionths: 0,
3848 excess_data: Vec::new()
3851 // Path via {node7, node2} is channels {12, 13, 5}.
3852 // We already limited them to 200 sats (they are used twice for 100 sats).
3853 // Nothing to do here.
3856 // Now, attempt to route 180 sats.
3857 // Our algorithm should provide us with these 2 paths.
3858 let route = get_route(&our_id, &payee, &net_graph_msg_handler.network_graph, None, 180_000, 42, Arc::clone(&logger), &scorer).unwrap();
3859 assert_eq!(route.paths.len(), 2);
3861 let mut total_value_transferred_msat = 0;
3862 let mut total_paid_msat = 0;
3863 for path in &route.paths {
3864 assert_eq!(path.last().unwrap().pubkey, nodes[3]);
3865 total_value_transferred_msat += path.last().unwrap().fee_msat;
3867 total_paid_msat += hop.fee_msat;
3870 // If we paid fee, this would be higher.
3871 assert_eq!(total_value_transferred_msat, 180_000);
3872 let total_fees_paid = total_paid_msat - total_value_transferred_msat;
3873 assert_eq!(total_fees_paid, 0);
3878 fn fees_on_mpp_route_test() {
3879 // This test makes sure that MPP algorithm properly takes into account
3880 // fees charged on the channels, by making the fees impactful:
3881 // if the fee is not properly accounted for, the behavior is different.
3882 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
3883 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3884 let scorer = Scorer::new(0);
3885 let payee = Payee::new(nodes[3]).with_features(InvoiceFeatures::known());
3887 // We need a route consisting of 2 paths:
3888 // From our node to node3 via {node0, node2} and {node7, node2, node4}.
3889 // We will route 200 sats, Each path will have 100 sats capacity.
3891 // This test is not particularly stable: e.g.,
3892 // there's a way to route via {node0, node2, node4}.
3893 // It works while pathfinding is deterministic, but can be broken otherwise.
3894 // It's fine to ignore this concern for now.
3896 // Disable other potential paths.
3897 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3898 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3899 short_channel_id: 2,
3902 cltv_expiry_delta: 0,
3903 htlc_minimum_msat: 0,
3904 htlc_maximum_msat: OptionalField::Present(100_000),
3906 fee_proportional_millionths: 0,
3907 excess_data: Vec::new()
3910 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3911 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3912 short_channel_id: 7,
3915 cltv_expiry_delta: 0,
3916 htlc_minimum_msat: 0,
3917 htlc_maximum_msat: OptionalField::Present(100_000),
3919 fee_proportional_millionths: 0,
3920 excess_data: Vec::new()
3923 // Path via {node0, node2} is channels {1, 3, 5}.
3924 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3925 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3926 short_channel_id: 1,
3929 cltv_expiry_delta: 0,
3930 htlc_minimum_msat: 0,
3931 htlc_maximum_msat: OptionalField::Present(100_000),
3933 fee_proportional_millionths: 0,
3934 excess_data: Vec::new()
3936 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3937 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3938 short_channel_id: 3,
3941 cltv_expiry_delta: 0,
3942 htlc_minimum_msat: 0,
3943 htlc_maximum_msat: OptionalField::Present(100_000),
3945 fee_proportional_millionths: 0,
3946 excess_data: Vec::new()
3949 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(5)), 5);
3950 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3951 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3952 short_channel_id: 5,
3955 cltv_expiry_delta: 0,
3956 htlc_minimum_msat: 0,
3957 htlc_maximum_msat: OptionalField::Present(100_000),
3959 fee_proportional_millionths: 0,
3960 excess_data: Vec::new()
3963 // Path via {node7, node2, node4} is channels {12, 13, 6, 11}.
3964 // All channels should be 100 sats capacity. But for the fee experiment,
3965 // we'll add absolute fee of 150 sats paid for the use channel 6 (paid to node2 on channel 13).
3966 // Since channel 12 allows to deliver only 250 sats to channel 13, channel 13 can transfer only
3967 // 100 sats (and pay 150 sats in fees for the use of channel 6),
3968 // so no matter how large are other channels,
3969 // the whole path will be limited by 100 sats with just these 2 conditions:
3970 // - channel 12 capacity is 250 sats
3971 // - fee for channel 6 is 150 sats
3972 // Let's test this by enforcing these 2 conditions and removing other limits.
3973 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3974 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3975 short_channel_id: 12,
3978 cltv_expiry_delta: 0,
3979 htlc_minimum_msat: 0,
3980 htlc_maximum_msat: OptionalField::Present(250_000),
3982 fee_proportional_millionths: 0,
3983 excess_data: Vec::new()
3985 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
3986 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3987 short_channel_id: 13,
3990 cltv_expiry_delta: 0,
3991 htlc_minimum_msat: 0,
3992 htlc_maximum_msat: OptionalField::Absent,
3994 fee_proportional_millionths: 0,
3995 excess_data: Vec::new()
3998 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3999 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4000 short_channel_id: 6,
4003 cltv_expiry_delta: 0,
4004 htlc_minimum_msat: 0,
4005 htlc_maximum_msat: OptionalField::Absent,
4006 fee_base_msat: 150_000,
4007 fee_proportional_millionths: 0,
4008 excess_data: Vec::new()
4010 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
4011 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4012 short_channel_id: 11,
4015 cltv_expiry_delta: 0,
4016 htlc_minimum_msat: 0,
4017 htlc_maximum_msat: OptionalField::Absent,
4019 fee_proportional_millionths: 0,
4020 excess_data: Vec::new()
4024 // Attempt to route more than available results in a failure.
4025 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
4026 &our_id, &payee, &net_graph_msg_handler.network_graph, None, 210_000, 42, Arc::clone(&logger), &scorer) {
4027 assert_eq!(err, "Failed to find a sufficient route to the given destination");
4028 } else { panic!(); }
4032 // Now, attempt to route 200 sats (exact amount we can route).
4033 let route = get_route(&our_id, &payee, &net_graph_msg_handler.network_graph, None, 200_000, 42, Arc::clone(&logger), &scorer).unwrap();
4034 assert_eq!(route.paths.len(), 2);
4036 let mut total_amount_paid_msat = 0;
4037 for path in &route.paths {
4038 assert_eq!(path.last().unwrap().pubkey, nodes[3]);
4039 total_amount_paid_msat += path.last().unwrap().fee_msat;
4041 assert_eq!(total_amount_paid_msat, 200_000);
4042 assert_eq!(route.get_total_fees(), 150_000);
4048 fn drop_lowest_channel_mpp_route_test() {
4049 // This test checks that low-capacity channel is dropped when after
4050 // path finding we realize that we found more capacity than we need.
4051 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
4052 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
4053 let scorer = Scorer::new(0);
4054 let payee = Payee::new(nodes[2]).with_features(InvoiceFeatures::known());
4056 // We need a route consisting of 3 paths:
4057 // From our node to node2 via node0, node7, node1 (three paths one hop each).
4059 // The first and the second paths should be sufficient, but the third should be
4060 // cheaper, so that we select it but drop later.
4062 // First, we set limits on these (previously unlimited) channels.
4063 // Their aggregate capacity will be 50 + 60 + 20 = 130 sats.
4065 // Path via node0 is channels {1, 3}. Limit them to 100 and 50 sats (total limit 50);
4066 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4067 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4068 short_channel_id: 1,
4071 cltv_expiry_delta: 0,
4072 htlc_minimum_msat: 0,
4073 htlc_maximum_msat: OptionalField::Present(100_000),
4075 fee_proportional_millionths: 0,
4076 excess_data: Vec::new()
4078 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
4079 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4080 short_channel_id: 3,
4083 cltv_expiry_delta: 0,
4084 htlc_minimum_msat: 0,
4085 htlc_maximum_msat: OptionalField::Present(50_000),
4087 fee_proportional_millionths: 0,
4088 excess_data: Vec::new()
4091 // Path via node7 is channels {12, 13}. Limit them to 60 and 60 sats (total limit 60);
4092 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4093 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4094 short_channel_id: 12,
4097 cltv_expiry_delta: 0,
4098 htlc_minimum_msat: 0,
4099 htlc_maximum_msat: OptionalField::Present(60_000),
4101 fee_proportional_millionths: 0,
4102 excess_data: Vec::new()
4104 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
4105 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4106 short_channel_id: 13,
4109 cltv_expiry_delta: 0,
4110 htlc_minimum_msat: 0,
4111 htlc_maximum_msat: OptionalField::Present(60_000),
4113 fee_proportional_millionths: 0,
4114 excess_data: Vec::new()
4117 // Path via node1 is channels {2, 4}. Limit them to 20 and 20 sats (total capacity 20 sats).
4118 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4119 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4120 short_channel_id: 2,
4123 cltv_expiry_delta: 0,
4124 htlc_minimum_msat: 0,
4125 htlc_maximum_msat: OptionalField::Present(20_000),
4127 fee_proportional_millionths: 0,
4128 excess_data: Vec::new()
4130 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
4131 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4132 short_channel_id: 4,
4135 cltv_expiry_delta: 0,
4136 htlc_minimum_msat: 0,
4137 htlc_maximum_msat: OptionalField::Present(20_000),
4139 fee_proportional_millionths: 0,
4140 excess_data: Vec::new()
4144 // Attempt to route more than available results in a failure.
4145 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
4146 &our_id, &payee, &net_graph_msg_handler.network_graph, None, 150_000, 42, Arc::clone(&logger), &scorer) {
4147 assert_eq!(err, "Failed to find a sufficient route to the given destination");
4148 } else { panic!(); }
4152 // Now, attempt to route 125 sats (just a bit below the capacity of 3 channels).
4153 // Our algorithm should provide us with these 3 paths.
4154 let route = get_route(&our_id, &payee, &net_graph_msg_handler.network_graph, None, 125_000, 42, Arc::clone(&logger), &scorer).unwrap();
4155 assert_eq!(route.paths.len(), 3);
4156 let mut total_amount_paid_msat = 0;
4157 for path in &route.paths {
4158 assert_eq!(path.len(), 2);
4159 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
4160 total_amount_paid_msat += path.last().unwrap().fee_msat;
4162 assert_eq!(total_amount_paid_msat, 125_000);
4166 // Attempt to route without the last small cheap channel
4167 let route = get_route(&our_id, &payee, &net_graph_msg_handler.network_graph, None, 90_000, 42, Arc::clone(&logger), &scorer).unwrap();
4168 assert_eq!(route.paths.len(), 2);
4169 let mut total_amount_paid_msat = 0;
4170 for path in &route.paths {
4171 assert_eq!(path.len(), 2);
4172 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
4173 total_amount_paid_msat += path.last().unwrap().fee_msat;
4175 assert_eq!(total_amount_paid_msat, 90_000);
4180 fn min_criteria_consistency() {
4181 // Test that we don't use an inconsistent metric between updating and walking nodes during
4182 // our Dijkstra's pass. In the initial version of MPP, the "best source" for a given node
4183 // was updated with a different criterion from the heap sorting, resulting in loops in
4184 // calculated paths. We test for that specific case here.
4186 // We construct a network that looks like this:
4188 // node2 -1(3)2- node3
4192 // node1 -1(5)2- node4 -1(1)2- node6
4198 // We create a loop on the side of our real path - our destination is node 6, with a
4199 // previous hop of node 4. From 4, the cheapest previous path is channel 2 from node 2,
4200 // followed by node 3 over channel 3. Thereafter, the cheapest next-hop is back to node 4
4201 // (this time over channel 4). Channel 4 has 0 htlc_minimum_msat whereas channel 1 (the
4202 // other channel with a previous-hop of node 4) has a high (but irrelevant to the overall
4203 // payment) htlc_minimum_msat. In the original algorithm, this resulted in node4's
4204 // "previous hop" being set to node 3, creating a loop in the path.
4205 let secp_ctx = Secp256k1::new();
4206 let logger = Arc::new(test_utils::TestLogger::new());
4207 let network_graph = NetworkGraph::new(genesis_block(Network::Testnet).header.block_hash());
4208 let net_graph_msg_handler = NetGraphMsgHandler::new(network_graph, None, Arc::clone(&logger));
4209 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
4210 let scorer = Scorer::new(0);
4211 let payee = Payee::new(nodes[6]);
4213 add_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, &privkeys[1], ChannelFeatures::from_le_bytes(id_to_feature_flags(6)), 6);
4214 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4215 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4216 short_channel_id: 6,
4219 cltv_expiry_delta: (6 << 8) | 0,
4220 htlc_minimum_msat: 0,
4221 htlc_maximum_msat: OptionalField::Absent,
4223 fee_proportional_millionths: 0,
4224 excess_data: Vec::new()
4226 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[1], NodeFeatures::from_le_bytes(id_to_feature_flags(1)), 0);
4228 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], &privkeys[4], ChannelFeatures::from_le_bytes(id_to_feature_flags(5)), 5);
4229 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
4230 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4231 short_channel_id: 5,
4234 cltv_expiry_delta: (5 << 8) | 0,
4235 htlc_minimum_msat: 0,
4236 htlc_maximum_msat: OptionalField::Absent,
4238 fee_proportional_millionths: 0,
4239 excess_data: Vec::new()
4241 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[4], NodeFeatures::from_le_bytes(id_to_feature_flags(4)), 0);
4243 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(4)), 4);
4244 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
4245 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4246 short_channel_id: 4,
4249 cltv_expiry_delta: (4 << 8) | 0,
4250 htlc_minimum_msat: 0,
4251 htlc_maximum_msat: OptionalField::Absent,
4253 fee_proportional_millionths: 0,
4254 excess_data: Vec::new()
4256 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[3], NodeFeatures::from_le_bytes(id_to_feature_flags(3)), 0);
4258 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[3], &privkeys[2], ChannelFeatures::from_le_bytes(id_to_feature_flags(3)), 3);
4259 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[3], UnsignedChannelUpdate {
4260 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4261 short_channel_id: 3,
4264 cltv_expiry_delta: (3 << 8) | 0,
4265 htlc_minimum_msat: 0,
4266 htlc_maximum_msat: OptionalField::Absent,
4268 fee_proportional_millionths: 0,
4269 excess_data: Vec::new()
4271 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[2], NodeFeatures::from_le_bytes(id_to_feature_flags(2)), 0);
4273 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], &privkeys[4], ChannelFeatures::from_le_bytes(id_to_feature_flags(2)), 2);
4274 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4275 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4276 short_channel_id: 2,
4279 cltv_expiry_delta: (2 << 8) | 0,
4280 htlc_minimum_msat: 0,
4281 htlc_maximum_msat: OptionalField::Absent,
4283 fee_proportional_millionths: 0,
4284 excess_data: Vec::new()
4287 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], &privkeys[6], ChannelFeatures::from_le_bytes(id_to_feature_flags(1)), 1);
4288 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
4289 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4290 short_channel_id: 1,
4293 cltv_expiry_delta: (1 << 8) | 0,
4294 htlc_minimum_msat: 100,
4295 htlc_maximum_msat: OptionalField::Absent,
4297 fee_proportional_millionths: 0,
4298 excess_data: Vec::new()
4300 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[6], NodeFeatures::from_le_bytes(id_to_feature_flags(6)), 0);
4303 // Now ensure the route flows simply over nodes 1 and 4 to 6.
4304 let route = get_route(&our_id, &payee, &net_graph_msg_handler.network_graph, None, 10_000, 42, Arc::clone(&logger), &scorer).unwrap();
4305 assert_eq!(route.paths.len(), 1);
4306 assert_eq!(route.paths[0].len(), 3);
4308 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
4309 assert_eq!(route.paths[0][0].short_channel_id, 6);
4310 assert_eq!(route.paths[0][0].fee_msat, 100);
4311 assert_eq!(route.paths[0][0].cltv_expiry_delta, (5 << 8) | 0);
4312 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(1));
4313 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(6));
4315 assert_eq!(route.paths[0][1].pubkey, nodes[4]);
4316 assert_eq!(route.paths[0][1].short_channel_id, 5);
4317 assert_eq!(route.paths[0][1].fee_msat, 0);
4318 assert_eq!(route.paths[0][1].cltv_expiry_delta, (1 << 8) | 0);
4319 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(4));
4320 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(5));
4322 assert_eq!(route.paths[0][2].pubkey, nodes[6]);
4323 assert_eq!(route.paths[0][2].short_channel_id, 1);
4324 assert_eq!(route.paths[0][2].fee_msat, 10_000);
4325 assert_eq!(route.paths[0][2].cltv_expiry_delta, 42);
4326 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(6));
4327 assert_eq!(route.paths[0][2].channel_features.le_flags(), &id_to_feature_flags(1));
4333 fn exact_fee_liquidity_limit() {
4334 // Test that if, while walking the graph, we find a hop that has exactly enough liquidity
4335 // for us, including later hop fees, we take it. In the first version of our MPP algorithm
4336 // we calculated fees on a higher value, resulting in us ignoring such paths.
4337 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
4338 let (our_privkey, our_id, _, nodes) = get_nodes(&secp_ctx);
4339 let scorer = Scorer::new(0);
4340 let payee = Payee::new(nodes[2]);
4342 // We modify the graph to set the htlc_maximum of channel 2 to below the value we wish to
4344 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4345 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4346 short_channel_id: 2,
4349 cltv_expiry_delta: 0,
4350 htlc_minimum_msat: 0,
4351 htlc_maximum_msat: OptionalField::Present(85_000),
4353 fee_proportional_millionths: 0,
4354 excess_data: Vec::new()
4357 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4358 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4359 short_channel_id: 12,
4362 cltv_expiry_delta: (4 << 8) | 1,
4363 htlc_minimum_msat: 0,
4364 htlc_maximum_msat: OptionalField::Present(270_000),
4366 fee_proportional_millionths: 1000000,
4367 excess_data: Vec::new()
4371 // Now, attempt to route 90 sats, which is exactly 90 sats at the last hop, plus the
4372 // 200% fee charged channel 13 in the 1-to-2 direction.
4373 let route = get_route(&our_id, &payee, &net_graph_msg_handler.network_graph, None, 90_000, 42, Arc::clone(&logger), &scorer).unwrap();
4374 assert_eq!(route.paths.len(), 1);
4375 assert_eq!(route.paths[0].len(), 2);
4377 assert_eq!(route.paths[0][0].pubkey, nodes[7]);
4378 assert_eq!(route.paths[0][0].short_channel_id, 12);
4379 assert_eq!(route.paths[0][0].fee_msat, 90_000*2);
4380 assert_eq!(route.paths[0][0].cltv_expiry_delta, (13 << 8) | 1);
4381 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(8));
4382 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(12));
4384 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
4385 assert_eq!(route.paths[0][1].short_channel_id, 13);
4386 assert_eq!(route.paths[0][1].fee_msat, 90_000);
4387 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
4388 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
4389 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(13));
4394 fn htlc_max_reduction_below_min() {
4395 // Test that if, while walking the graph, we reduce the value being sent to meet an
4396 // htlc_maximum_msat, we don't end up undershooting a later htlc_minimum_msat. In the
4397 // initial version of MPP we'd accept such routes but reject them while recalculating fees,
4398 // resulting in us thinking there is no possible path, even if other paths exist.
4399 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
4400 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
4401 let scorer = Scorer::new(0);
4402 let payee = Payee::new(nodes[2]).with_features(InvoiceFeatures::known());
4404 // We modify the graph to set the htlc_minimum of channel 2 and 4 as needed - channel 2
4405 // gets an htlc_maximum_msat of 80_000 and channel 4 an htlc_minimum_msat of 90_000. We
4406 // then try to send 90_000.
4407 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4408 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4409 short_channel_id: 2,
4412 cltv_expiry_delta: 0,
4413 htlc_minimum_msat: 0,
4414 htlc_maximum_msat: OptionalField::Present(80_000),
4416 fee_proportional_millionths: 0,
4417 excess_data: Vec::new()
4419 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
4420 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4421 short_channel_id: 4,
4424 cltv_expiry_delta: (4 << 8) | 1,
4425 htlc_minimum_msat: 90_000,
4426 htlc_maximum_msat: OptionalField::Absent,
4428 fee_proportional_millionths: 0,
4429 excess_data: Vec::new()
4433 // Now, attempt to route 90 sats, hitting the htlc_minimum on channel 4, but
4434 // overshooting the htlc_maximum on channel 2. Thus, we should pick the (absurdly
4435 // expensive) channels 12-13 path.
4436 let route = get_route(&our_id, &payee, &net_graph_msg_handler.network_graph, None, 90_000, 42, Arc::clone(&logger), &scorer).unwrap();
4437 assert_eq!(route.paths.len(), 1);
4438 assert_eq!(route.paths[0].len(), 2);
4440 assert_eq!(route.paths[0][0].pubkey, nodes[7]);
4441 assert_eq!(route.paths[0][0].short_channel_id, 12);
4442 assert_eq!(route.paths[0][0].fee_msat, 90_000*2);
4443 assert_eq!(route.paths[0][0].cltv_expiry_delta, (13 << 8) | 1);
4444 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(8));
4445 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(12));
4447 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
4448 assert_eq!(route.paths[0][1].short_channel_id, 13);
4449 assert_eq!(route.paths[0][1].fee_msat, 90_000);
4450 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
4451 assert_eq!(route.paths[0][1].node_features.le_flags(), InvoiceFeatures::known().le_flags());
4452 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(13));
4457 fn multiple_direct_first_hops() {
4458 // Previously we'd only ever considered one first hop path per counterparty.
4459 // However, as we don't restrict users to one channel per peer, we really need to support
4460 // looking at all first hop paths.
4461 // Here we test that we do not ignore all-but-the-last first hop paths per counterparty (as
4462 // we used to do by overwriting the `first_hop_targets` hashmap entry) and that we can MPP
4463 // route over multiple channels with the same first hop.
4464 let secp_ctx = Secp256k1::new();
4465 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
4466 let logger = Arc::new(test_utils::TestLogger::new());
4467 let network_graph = NetworkGraph::new(genesis_block(Network::Testnet).header.block_hash());
4468 let scorer = Scorer::new(0);
4469 let payee = Payee::new(nodes[0]).with_features(InvoiceFeatures::known());
4472 let route = get_route(&our_id, &payee, &network_graph, Some(&[
4473 &get_channel_details(Some(3), nodes[0], InitFeatures::known(), 200_000),
4474 &get_channel_details(Some(2), nodes[0], InitFeatures::known(), 10_000),
4475 ]), 100_000, 42, Arc::clone(&logger), &scorer).unwrap();
4476 assert_eq!(route.paths.len(), 1);
4477 assert_eq!(route.paths[0].len(), 1);
4479 assert_eq!(route.paths[0][0].pubkey, nodes[0]);
4480 assert_eq!(route.paths[0][0].short_channel_id, 3);
4481 assert_eq!(route.paths[0][0].fee_msat, 100_000);
4484 let route = get_route(&our_id, &payee, &network_graph, Some(&[
4485 &get_channel_details(Some(3), nodes[0], InitFeatures::known(), 50_000),
4486 &get_channel_details(Some(2), nodes[0], InitFeatures::known(), 50_000),
4487 ]), 100_000, 42, Arc::clone(&logger), &scorer).unwrap();
4488 assert_eq!(route.paths.len(), 2);
4489 assert_eq!(route.paths[0].len(), 1);
4490 assert_eq!(route.paths[1].len(), 1);
4492 assert_eq!(route.paths[0][0].pubkey, nodes[0]);
4493 assert_eq!(route.paths[0][0].short_channel_id, 3);
4494 assert_eq!(route.paths[0][0].fee_msat, 50_000);
4496 assert_eq!(route.paths[1][0].pubkey, nodes[0]);
4497 assert_eq!(route.paths[1][0].short_channel_id, 2);
4498 assert_eq!(route.paths[1][0].fee_msat, 50_000);
4503 fn prefers_shorter_route_with_higher_fees() {
4504 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
4505 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
4506 let payee = Payee::new(nodes[6]).with_route_hints(last_hops(&nodes));
4508 // Without penalizing each hop 100 msats, a longer path with lower fees is chosen.
4509 let scorer = Scorer::new(0);
4510 let route = get_route(
4511 &our_id, &payee, &net_graph_msg_handler.network_graph, None, 100, 42,
4512 Arc::clone(&logger), &scorer
4514 let path = route.paths[0].iter().map(|hop| hop.short_channel_id).collect::<Vec<_>>();
4516 assert_eq!(route.get_total_fees(), 100);
4517 assert_eq!(route.get_total_amount(), 100);
4518 assert_eq!(path, vec![2, 4, 6, 11, 8]);
4520 // Applying a 100 msat penalty to each hop results in taking channels 7 and 10 to nodes[6]
4521 // from nodes[2] rather than channel 6, 11, and 8, even though the longer path is cheaper.
4522 let scorer = Scorer::new(100);
4523 let route = get_route(
4524 &our_id, &payee, &net_graph_msg_handler.network_graph, None, 100, 42,
4525 Arc::clone(&logger), &scorer
4527 let path = route.paths[0].iter().map(|hop| hop.short_channel_id).collect::<Vec<_>>();
4529 assert_eq!(route.get_total_fees(), 300);
4530 assert_eq!(route.get_total_amount(), 100);
4531 assert_eq!(path, vec![2, 4, 7, 10]);
4534 struct BadChannelScorer {
4535 short_channel_id: u64,
4538 impl routing::Score for BadChannelScorer {
4539 fn channel_penalty_msat(&self, short_channel_id: u64, _source: &NodeId, _target: &NodeId) -> u64 {
4540 if short_channel_id == self.short_channel_id { u64::max_value() } else { 0 }
4544 struct BadNodeScorer {
4548 impl routing::Score for BadNodeScorer {
4549 fn channel_penalty_msat(&self, _short_channel_id: u64, _source: &NodeId, target: &NodeId) -> u64 {
4550 if *target == self.node_id { u64::max_value() } else { 0 }
4555 fn avoids_routing_through_bad_channels_and_nodes() {
4556 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
4557 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
4558 let payee = Payee::new(nodes[6]).with_route_hints(last_hops(&nodes));
4560 // A path to nodes[6] exists when no penalties are applied to any channel.
4561 let scorer = Scorer::new(0);
4562 let route = get_route(
4563 &our_id, &payee, &net_graph_msg_handler.network_graph, None, 100, 42,
4564 Arc::clone(&logger), &scorer
4566 let path = route.paths[0].iter().map(|hop| hop.short_channel_id).collect::<Vec<_>>();
4568 assert_eq!(route.get_total_fees(), 100);
4569 assert_eq!(route.get_total_amount(), 100);
4570 assert_eq!(path, vec![2, 4, 6, 11, 8]);
4572 // A different path to nodes[6] exists if channel 6 cannot be routed over.
4573 let scorer = BadChannelScorer { short_channel_id: 6 };
4574 let route = get_route(
4575 &our_id, &payee, &net_graph_msg_handler.network_graph, None, 100, 42,
4576 Arc::clone(&logger), &scorer
4578 let path = route.paths[0].iter().map(|hop| hop.short_channel_id).collect::<Vec<_>>();
4580 assert_eq!(route.get_total_fees(), 300);
4581 assert_eq!(route.get_total_amount(), 100);
4582 assert_eq!(path, vec![2, 4, 7, 10]);
4584 // A path to nodes[6] does not exist if nodes[2] cannot be routed through.
4585 let scorer = BadNodeScorer { node_id: NodeId::from_pubkey(&nodes[2]) };
4587 &our_id, &payee, &net_graph_msg_handler.network_graph, None, 100, 42,
4588 Arc::clone(&logger), &scorer
4590 Err(LightningError { err, .. } ) => {
4591 assert_eq!(err, "Failed to find a path to the given destination");
4593 Ok(_) => panic!("Expected error"),
4598 fn total_fees_single_path() {
4602 pubkey: PublicKey::from_slice(&hex::decode("02eec7245d6b7d2ccb30380bfbe2a3648cd7a942653f5aa340edcea1f283686619").unwrap()[..]).unwrap(),
4603 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
4604 short_channel_id: 0, fee_msat: 100, cltv_expiry_delta: 0
4607 pubkey: PublicKey::from_slice(&hex::decode("0324653eac434488002cc06bbfb7f10fe18991e35f9fe4302dbea6d2353dc0ab1c").unwrap()[..]).unwrap(),
4608 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
4609 short_channel_id: 0, fee_msat: 150, cltv_expiry_delta: 0
4612 pubkey: PublicKey::from_slice(&hex::decode("027f31ebc5462c1fdce1b737ecff52d37d75dea43ce11c74d25aa297165faa2007").unwrap()[..]).unwrap(),
4613 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
4614 short_channel_id: 0, fee_msat: 225, cltv_expiry_delta: 0
4620 assert_eq!(route.get_total_fees(), 250);
4621 assert_eq!(route.get_total_amount(), 225);
4625 fn total_fees_multi_path() {
4629 pubkey: PublicKey::from_slice(&hex::decode("02eec7245d6b7d2ccb30380bfbe2a3648cd7a942653f5aa340edcea1f283686619").unwrap()[..]).unwrap(),
4630 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
4631 short_channel_id: 0, fee_msat: 100, cltv_expiry_delta: 0
4634 pubkey: PublicKey::from_slice(&hex::decode("0324653eac434488002cc06bbfb7f10fe18991e35f9fe4302dbea6d2353dc0ab1c").unwrap()[..]).unwrap(),
4635 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
4636 short_channel_id: 0, fee_msat: 150, cltv_expiry_delta: 0
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
4653 assert_eq!(route.get_total_fees(), 200);
4654 assert_eq!(route.get_total_amount(), 300);
4658 fn total_empty_route_no_panic() {
4659 // In an earlier version of `Route::get_total_fees` and `Route::get_total_amount`, they
4660 // would both panic if the route was completely empty. We test to ensure they return 0
4661 // here, even though its somewhat nonsensical as a route.
4662 let route = Route { paths: Vec::new(), payee: None };
4664 assert_eq!(route.get_total_fees(), 0);
4665 assert_eq!(route.get_total_amount(), 0);
4668 #[cfg(not(feature = "no-std"))]
4669 pub(super) fn random_init_seed() -> u64 {
4670 // Because the default HashMap in std pulls OS randomness, we can use it as a (bad) RNG.
4671 use core::hash::{BuildHasher, Hasher};
4672 let seed = std::collections::hash_map::RandomState::new().build_hasher().finish();
4673 println!("Using seed of {}", seed);
4676 #[cfg(not(feature = "no-std"))]
4677 use util::ser::Readable;
4680 #[cfg(not(feature = "no-std"))]
4681 fn generate_routes() {
4682 let mut d = match super::test_utils::get_route_file() {
4689 let graph = NetworkGraph::read(&mut d).unwrap();
4690 let scorer = Scorer::new(0);
4692 // First, get 100 (source, destination) pairs for which route-getting actually succeeds...
4693 let mut seed = random_init_seed() as usize;
4694 let nodes = graph.read_only().nodes().clone();
4695 'load_endpoints: for _ in 0..10 {
4697 seed = seed.overflowing_mul(0xdeadbeef).0;
4698 let src = &PublicKey::from_slice(nodes.keys().skip(seed % nodes.len()).next().unwrap().as_slice()).unwrap();
4699 seed = seed.overflowing_mul(0xdeadbeef).0;
4700 let dst = PublicKey::from_slice(nodes.keys().skip(seed % nodes.len()).next().unwrap().as_slice()).unwrap();
4701 let payee = Payee::new(dst);
4702 let amt = seed as u64 % 200_000_000;
4703 if get_route(src, &payee, &graph, None, amt, 42, &test_utils::TestLogger::new(), &scorer).is_ok() {
4704 continue 'load_endpoints;
4711 #[cfg(not(feature = "no-std"))]
4712 fn generate_routes_mpp() {
4713 let mut d = match super::test_utils::get_route_file() {
4720 let graph = NetworkGraph::read(&mut d).unwrap();
4721 let scorer = Scorer::new(0);
4723 // First, get 100 (source, destination) pairs for which route-getting actually succeeds...
4724 let mut seed = random_init_seed() as usize;
4725 let nodes = graph.read_only().nodes().clone();
4726 'load_endpoints: for _ in 0..10 {
4728 seed = seed.overflowing_mul(0xdeadbeef).0;
4729 let src = &PublicKey::from_slice(nodes.keys().skip(seed % nodes.len()).next().unwrap().as_slice()).unwrap();
4730 seed = seed.overflowing_mul(0xdeadbeef).0;
4731 let dst = PublicKey::from_slice(nodes.keys().skip(seed % nodes.len()).next().unwrap().as_slice()).unwrap();
4732 let payee = Payee::new(dst).with_features(InvoiceFeatures::known());
4733 let amt = seed as u64 % 200_000_000;
4734 if get_route(src, &payee, &graph, None, amt, 42, &test_utils::TestLogger::new(), &scorer).is_ok() {
4735 continue 'load_endpoints;
4742 #[cfg(all(test, not(feature = "no-std")))]
4743 pub(crate) mod test_utils {
4745 /// Tries to open a network graph file, or panics with a URL to fetch it.
4746 pub(crate) fn get_route_file() -> Result<std::fs::File, &'static str> {
4747 let res = File::open("net_graph-2021-05-31.bin") // By default we're run in RL/lightning
4748 .or_else(|_| File::open("lightning/net_graph-2021-05-31.bin")) // We may be run manually in RL/
4749 .or_else(|_| { // Fall back to guessing based on the binary location
4750 // path is likely something like .../rust-lightning/target/debug/deps/lightning-...
4751 let mut path = std::env::current_exe().unwrap();
4752 path.pop(); // lightning-...
4754 path.pop(); // debug
4755 path.pop(); // target
4756 path.push("lightning");
4757 path.push("net_graph-2021-05-31.bin");
4758 eprintln!("{}", path.to_str().unwrap());
4761 .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");
4762 #[cfg(require_route_graph_test)]
4763 return Ok(res.unwrap());
4764 #[cfg(not(require_route_graph_test))]
4769 #[cfg(all(test, feature = "unstable", not(feature = "no-std")))]
4772 use routing::scorer::Scorer;
4773 use util::logger::{Logger, Record};
4777 struct DummyLogger {}
4778 impl Logger for DummyLogger {
4779 fn log(&self, _record: &Record) {}
4783 fn generate_routes(bench: &mut Bencher) {
4784 let mut d = test_utils::get_route_file().unwrap();
4785 let graph = NetworkGraph::read(&mut d).unwrap();
4786 let nodes = graph.read_only().nodes().clone();
4787 let scorer = Scorer::new(0);
4789 // First, get 100 (source, destination) pairs for which route-getting actually succeeds...
4790 let mut path_endpoints = Vec::new();
4791 let mut seed: usize = 0xdeadbeef;
4792 'load_endpoints: for _ in 0..100 {
4795 let src = PublicKey::from_slice(nodes.keys().skip(seed % nodes.len()).next().unwrap().as_slice()).unwrap();
4797 let dst = PublicKey::from_slice(nodes.keys().skip(seed % nodes.len()).next().unwrap().as_slice()).unwrap();
4798 let payee = Payee::new(dst);
4799 let amt = seed as u64 % 1_000_000;
4800 if get_route(&src, &payee, &graph, None, amt, 42, &DummyLogger{}, &scorer).is_ok() {
4801 path_endpoints.push((src, dst, amt));
4802 continue 'load_endpoints;
4807 // ...then benchmark finding paths between the nodes we learned.
4810 let (src, dst, amt) = path_endpoints[idx % path_endpoints.len()];
4811 let payee = Payee::new(dst);
4812 assert!(get_route(&src, &payee, &graph, None, amt, 42, &DummyLogger{}, &scorer).is_ok());
4818 fn generate_mpp_routes(bench: &mut Bencher) {
4819 let mut d = test_utils::get_route_file().unwrap();
4820 let graph = NetworkGraph::read(&mut d).unwrap();
4821 let nodes = graph.read_only().nodes().clone();
4822 let scorer = Scorer::new(0);
4824 // First, get 100 (source, destination) pairs for which route-getting actually succeeds...
4825 let mut path_endpoints = Vec::new();
4826 let mut seed: usize = 0xdeadbeef;
4827 'load_endpoints: for _ in 0..100 {
4830 let src = PublicKey::from_slice(nodes.keys().skip(seed % nodes.len()).next().unwrap().as_slice()).unwrap();
4832 let dst = PublicKey::from_slice(nodes.keys().skip(seed % nodes.len()).next().unwrap().as_slice()).unwrap();
4833 let payee = Payee::new(dst).with_features(InvoiceFeatures::known());
4834 let amt = seed as u64 % 1_000_000;
4835 if get_route(&src, &payee, &graph, None, amt, 42, &DummyLogger{}, &scorer).is_ok() {
4836 path_endpoints.push((src, dst, amt));
4837 continue 'load_endpoints;
4842 // ...then benchmark finding paths between the nodes we learned.
4845 let (src, dst, amt) = path_endpoints[idx % path_endpoints.len()];
4846 let payee = Payee::new(dst).with_features(InvoiceFeatures::known());
4847 assert!(get_route(&src, &payee, &graph, None, amt, 42, &DummyLogger{}, &scorer).is_ok());