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};
20 use routing::scoring::Score;
21 use routing::network_graph::{NetworkGraph, NodeId, RoutingFees};
22 use util::ser::{Writeable, Readable};
23 use util::logger::{Level, Logger};
27 use alloc::collections::BinaryHeap;
32 #[derive(Clone, Debug, Hash, PartialEq, Eq)]
34 /// The node_id of the node at this hop.
35 pub pubkey: PublicKey,
36 /// The node_announcement features of the node at this hop. For the last hop, these may be
37 /// amended to match the features present in the invoice this node generated.
38 pub node_features: NodeFeatures,
39 /// The channel that should be used from the previous hop to reach this node.
40 pub short_channel_id: u64,
41 /// The channel_announcement features of the channel that should be used from the previous hop
42 /// to reach this node.
43 pub channel_features: ChannelFeatures,
44 /// The fee taken on this hop (for paying for the use of the *next* channel in the path).
45 /// For the last hop, this should be the full value of the payment (might be more than
46 /// requested if we had to match htlc_minimum_msat).
48 /// The CLTV delta added for this hop. For the last hop, this should be the full CLTV value
49 /// expected at the destination, in excess of the current block height.
50 pub cltv_expiry_delta: u32,
53 impl_writeable_tlv_based!(RouteHop, {
54 (0, pubkey, required),
55 (2, node_features, required),
56 (4, short_channel_id, required),
57 (6, channel_features, required),
58 (8, fee_msat, required),
59 (10, cltv_expiry_delta, required),
62 /// A route directs a payment from the sender (us) to the recipient. If the recipient supports MPP,
63 /// it can take multiple paths. Each path is composed of one or more hops through the network.
64 #[derive(Clone, Hash, PartialEq, Eq)]
66 /// The list of routes taken for a single (potentially-)multi-part payment. The pubkey of the
67 /// last RouteHop in each path must be the same.
68 /// Each entry represents a list of hops, NOT INCLUDING our own, where the last hop is the
69 /// destination. Thus, this must always be at least length one. While the maximum length of any
70 /// given path is variable, keeping the length of any path to less than 20 should currently
71 /// ensure it is viable.
72 pub paths: Vec<Vec<RouteHop>>,
73 /// The `payee` parameter passed to [`find_route`].
74 /// This is used by `ChannelManager` to track information which may be required for retries,
75 /// provided back to you via [`Event::PaymentPathFailed`].
77 /// [`Event::PaymentPathFailed`]: crate::util::events::Event::PaymentPathFailed
78 pub payee: Option<Payee>,
81 pub(crate) trait RoutePath {
82 /// Gets the fees for a given path, excluding any excess paid to the recipient.
83 fn get_path_fees(&self) -> u64;
85 impl RoutePath for Vec<RouteHop> {
86 fn get_path_fees(&self) -> u64 {
87 // Do not count last hop of each path since that's the full value of the payment
88 self.split_last().map(|(_, path_prefix)| path_prefix).unwrap_or(&[])
89 .iter().map(|hop| &hop.fee_msat)
95 /// Returns the total amount of fees paid on this [`Route`].
97 /// This doesn't include any extra payment made to the recipient, which can happen in excess of
98 /// the amount passed to [`find_route`]'s `params.final_value_msat`.
99 pub fn get_total_fees(&self) -> u64 {
100 self.paths.iter().map(|path| path.get_path_fees()).sum()
103 /// Returns the total amount paid on this [`Route`], excluding the fees.
104 pub fn get_total_amount(&self) -> u64 {
105 return self.paths.iter()
106 .map(|path| path.split_last().map(|(hop, _)| hop.fee_msat).unwrap_or(0))
111 const SERIALIZATION_VERSION: u8 = 1;
112 const MIN_SERIALIZATION_VERSION: u8 = 1;
114 impl Writeable for Route {
115 fn write<W: ::util::ser::Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
116 write_ver_prefix!(writer, SERIALIZATION_VERSION, MIN_SERIALIZATION_VERSION);
117 (self.paths.len() as u64).write(writer)?;
118 for hops in self.paths.iter() {
119 (hops.len() as u8).write(writer)?;
120 for hop in hops.iter() {
124 write_tlv_fields!(writer, {
125 (1, self.payee, option),
131 impl Readable for Route {
132 fn read<R: io::Read>(reader: &mut R) -> Result<Route, DecodeError> {
133 let _ver = read_ver_prefix!(reader, SERIALIZATION_VERSION);
134 let path_count: u64 = Readable::read(reader)?;
135 let mut paths = Vec::with_capacity(cmp::min(path_count, 128) as usize);
136 for _ in 0..path_count {
137 let hop_count: u8 = Readable::read(reader)?;
138 let mut hops = Vec::with_capacity(hop_count as usize);
139 for _ in 0..hop_count {
140 hops.push(Readable::read(reader)?);
144 let mut payee = None;
145 read_tlv_fields!(reader, {
148 Ok(Route { paths, payee })
152 /// Parameters needed to find a [`Route`] for paying a [`Payee`].
154 /// Passed to [`find_route`] and also provided in [`Event::PaymentPathFailed`] for retrying a failed
157 /// [`Event::PaymentPathFailed`]: crate::util::events::Event::PaymentPathFailed
158 #[derive(Clone, Debug)]
159 pub struct RouteParameters {
160 /// The recipient of the failed payment path.
163 /// The amount in msats sent on the failed payment path.
164 pub final_value_msat: u64,
166 /// The CLTV on the final hop of the failed payment path.
167 pub final_cltv_expiry_delta: u32,
170 impl_writeable_tlv_based!(RouteParameters, {
171 (0, payee, required),
172 (2, final_value_msat, required),
173 (4, final_cltv_expiry_delta, required),
176 /// Maximum total CTLV difference we allow for a full payment path.
177 pub const DEFAULT_MAX_TOTAL_CLTV_EXPIRY_DELTA: u32 = 1008;
179 /// The recipient of a payment.
180 #[derive(Clone, Debug, Hash, PartialEq, Eq)]
182 /// The node id of the payee.
183 pub pubkey: PublicKey,
185 /// Features supported by the payee.
187 /// May be set from the payee's invoice or via [`for_keysend`]. May be `None` if the invoice
188 /// does not contain any features.
190 /// [`for_keysend`]: Self::for_keysend
191 pub features: Option<InvoiceFeatures>,
193 /// Hints for routing to the payee, containing channels connecting the payee to public nodes.
194 pub route_hints: Vec<RouteHint>,
196 /// Expiration of a payment to the payee, in seconds relative to the UNIX epoch.
197 pub expiry_time: Option<u64>,
199 /// The maximum total CLTV delta we accept for the route.
200 pub max_total_cltv_expiry_delta: u32,
203 impl_writeable_tlv_based!(Payee, {
204 (0, pubkey, required),
205 (1, max_total_cltv_expiry_delta, (default_value, DEFAULT_MAX_TOTAL_CLTV_EXPIRY_DELTA)),
206 (2, features, option),
207 (4, route_hints, vec_type),
208 (6, expiry_time, option),
212 /// Creates a payee with the node id of the given `pubkey`.
213 pub fn from_node_id(pubkey: PublicKey) -> Self {
219 max_total_cltv_expiry_delta: DEFAULT_MAX_TOTAL_CLTV_EXPIRY_DELTA,
223 /// Creates a payee with the node id of the given `pubkey` to use for keysend payments.
224 pub fn for_keysend(pubkey: PublicKey) -> Self {
225 Self::from_node_id(pubkey).with_features(InvoiceFeatures::for_keysend())
228 /// Includes the payee's features.
230 /// (C-not exported) since bindings don't support move semantics
231 pub fn with_features(self, features: InvoiceFeatures) -> Self {
232 Self { features: Some(features), ..self }
235 /// Includes hints for routing to the payee.
237 /// (C-not exported) since bindings don't support move semantics
238 pub fn with_route_hints(self, route_hints: Vec<RouteHint>) -> Self {
239 Self { route_hints, ..self }
242 /// Includes a payment expiration in seconds relative to the UNIX epoch.
244 /// (C-not exported) since bindings don't support move semantics
245 pub fn with_expiry_time(self, expiry_time: u64) -> Self {
246 Self { expiry_time: Some(expiry_time), ..self }
249 /// Includes a limit for the total CLTV expiry delta which is considered during routing
251 /// (C-not exported) since bindings don't support move semantics
252 pub fn with_max_total_cltv_expiry_delta(self, max_total_cltv_expiry_delta: u32) -> Self {
253 Self { max_total_cltv_expiry_delta, ..self }
257 /// A list of hops along a payment path terminating with a channel to the recipient.
258 #[derive(Clone, Debug, Hash, Eq, PartialEq)]
259 pub struct RouteHint(pub Vec<RouteHintHop>);
262 impl Writeable for RouteHint {
263 fn write<W: ::util::ser::Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
264 (self.0.len() as u64).write(writer)?;
265 for hop in self.0.iter() {
272 impl Readable for RouteHint {
273 fn read<R: io::Read>(reader: &mut R) -> Result<Self, DecodeError> {
274 let hop_count: u64 = Readable::read(reader)?;
275 let mut hops = Vec::with_capacity(cmp::min(hop_count, 16) as usize);
276 for _ in 0..hop_count {
277 hops.push(Readable::read(reader)?);
283 /// A channel descriptor for a hop along a payment path.
284 #[derive(Clone, Debug, Hash, Eq, PartialEq)]
285 pub struct RouteHintHop {
286 /// The node_id of the non-target end of the route
287 pub src_node_id: PublicKey,
288 /// The short_channel_id of this channel
289 pub short_channel_id: u64,
290 /// The fees which must be paid to use this channel
291 pub fees: RoutingFees,
292 /// The difference in CLTV values between this node and the next node.
293 pub cltv_expiry_delta: u16,
294 /// The minimum value, in msat, which must be relayed to the next hop.
295 pub htlc_minimum_msat: Option<u64>,
296 /// The maximum value in msat available for routing with a single HTLC.
297 pub htlc_maximum_msat: Option<u64>,
300 impl_writeable_tlv_based!(RouteHintHop, {
301 (0, src_node_id, required),
302 (1, htlc_minimum_msat, option),
303 (2, short_channel_id, required),
304 (3, htlc_maximum_msat, option),
306 (6, cltv_expiry_delta, required),
309 #[derive(Eq, PartialEq)]
310 struct RouteGraphNode {
312 lowest_fee_to_peer_through_node: u64,
313 lowest_fee_to_node: u64,
314 total_cltv_delta: u32,
315 // The maximum value a yet-to-be-constructed payment path might flow through this node.
316 // This value is upper-bounded by us by:
317 // - how much is needed for a path being constructed
318 // - how much value can channels following this node (up to the destination) can contribute,
319 // considering their capacity and fees
320 value_contribution_msat: u64,
321 /// The effective htlc_minimum_msat at this hop. If a later hop on the path had a higher HTLC
322 /// minimum, we use it, plus the fees required at each earlier hop to meet it.
323 path_htlc_minimum_msat: u64,
324 /// All penalties incurred from this hop on the way to the destination, as calculated using
326 path_penalty_msat: u64,
329 impl cmp::Ord for RouteGraphNode {
330 fn cmp(&self, other: &RouteGraphNode) -> cmp::Ordering {
331 let other_score = cmp::max(other.lowest_fee_to_peer_through_node, other.path_htlc_minimum_msat)
332 .checked_add(other.path_penalty_msat)
333 .unwrap_or_else(|| u64::max_value());
334 let self_score = cmp::max(self.lowest_fee_to_peer_through_node, self.path_htlc_minimum_msat)
335 .checked_add(self.path_penalty_msat)
336 .unwrap_or_else(|| u64::max_value());
337 other_score.cmp(&self_score).then_with(|| other.node_id.cmp(&self.node_id))
341 impl cmp::PartialOrd for RouteGraphNode {
342 fn partial_cmp(&self, other: &RouteGraphNode) -> Option<cmp::Ordering> {
343 Some(self.cmp(other))
347 struct DummyDirectionalChannelInfo {
348 cltv_expiry_delta: u32,
349 htlc_minimum_msat: u64,
350 htlc_maximum_msat: Option<u64>,
354 /// It's useful to keep track of the hops associated with the fees required to use them,
355 /// so that we can choose cheaper paths (as per Dijkstra's algorithm).
356 /// Fee values should be updated only in the context of the whole path, see update_value_and_recompute_fees.
357 /// These fee values are useful to choose hops as we traverse the graph "payee-to-payer".
358 #[derive(Clone, Debug)]
359 struct PathBuildingHop<'a> {
360 // The RouteHintHop fields which will eventually be used if this hop is used in a final Route.
361 // Note that node_features is calculated separately after our initial graph walk.
363 short_channel_id: u64,
364 channel_features: &'a ChannelFeatures,
366 cltv_expiry_delta: u32,
368 /// Minimal fees required to route to the source node of the current hop via any of its inbound channels.
369 src_lowest_inbound_fees: RoutingFees,
370 /// Fees of the channel used in this hop.
371 channel_fees: RoutingFees,
372 /// All the fees paid *after* this channel on the way to the destination
373 next_hops_fee_msat: u64,
374 /// Fee paid for the use of the current channel (see channel_fees).
375 /// The value will be actually deducted from the counterparty balance on the previous link.
376 hop_use_fee_msat: u64,
377 /// Used to compare channels when choosing the for routing.
378 /// Includes paying for the use of a hop and the following hops, as well as
379 /// an estimated cost of reaching this hop.
380 /// Might get stale when fees are recomputed. Primarily for internal use.
382 /// This is useful for update_value_and_recompute_fees to make sure
383 /// we don't fall below the minimum. Should not be updated manually and
384 /// generally should not be accessed.
385 htlc_minimum_msat: u64,
386 /// A mirror of the same field in RouteGraphNode. Note that this is only used during the graph
387 /// walk and may be invalid thereafter.
388 path_htlc_minimum_msat: u64,
389 /// All penalties incurred from this channel on the way to the destination, as calculated using
391 path_penalty_msat: u64,
392 /// If we've already processed a node as the best node, we shouldn't process it again. Normally
393 /// we'd just ignore it if we did as all channels would have a higher new fee, but because we
394 /// may decrease the amounts in use as we walk the graph, the actual calculated fee may
395 /// decrease as well. Thus, we have to explicitly track which nodes have been processed and
396 /// avoid processing them again.
398 #[cfg(any(test, feature = "fuzztarget"))]
399 // In tests, we apply further sanity checks on cases where we skip nodes we already processed
400 // to ensure it is specifically in cases where the fee has gone down because of a decrease in
401 // value_contribution_msat, which requires tracking it here. See comments below where it is
402 // used for more info.
403 value_contribution_msat: u64,
406 // Instantiated with a list of hops with correct data in them collected during path finding,
407 // an instance of this struct should be further modified only via given methods.
409 struct PaymentPath<'a> {
410 hops: Vec<(PathBuildingHop<'a>, NodeFeatures)>,
413 impl<'a> PaymentPath<'a> {
414 // TODO: Add a value_msat field to PaymentPath and use it instead of this function.
415 fn get_value_msat(&self) -> u64 {
416 self.hops.last().unwrap().0.fee_msat
419 fn get_total_fee_paid_msat(&self) -> u64 {
420 if self.hops.len() < 1 {
424 // Can't use next_hops_fee_msat because it gets outdated.
425 for (i, (hop, _)) in self.hops.iter().enumerate() {
426 if i != self.hops.len() - 1 {
427 result += hop.fee_msat;
433 // If the amount transferred by the path is updated, the fees should be adjusted. Any other way
434 // to change fees may result in an inconsistency.
436 // Sometimes we call this function right after constructing a path which is inconsistent in
437 // that it the value being transferred has decreased while we were doing path finding, leading
438 // to the fees being paid not lining up with the actual limits.
440 // Note that this function is not aware of the available_liquidity limit, and thus does not
441 // support increasing the value being transferred.
442 fn update_value_and_recompute_fees(&mut self, value_msat: u64) {
443 assert!(value_msat <= self.hops.last().unwrap().0.fee_msat);
445 let mut total_fee_paid_msat = 0 as u64;
446 for i in (0..self.hops.len()).rev() {
447 let last_hop = i == self.hops.len() - 1;
449 // For non-last-hop, this value will represent the fees paid on the current hop. It
450 // will consist of the fees for the use of the next hop, and extra fees to match
451 // htlc_minimum_msat of the current channel. Last hop is handled separately.
452 let mut cur_hop_fees_msat = 0;
454 cur_hop_fees_msat = self.hops.get(i + 1).unwrap().0.hop_use_fee_msat;
457 let mut cur_hop = &mut self.hops.get_mut(i).unwrap().0;
458 cur_hop.next_hops_fee_msat = total_fee_paid_msat;
459 // Overpay in fees if we can't save these funds due to htlc_minimum_msat.
460 // We try to account for htlc_minimum_msat in scoring (add_entry!), so that nodes don't
461 // set it too high just to maliciously take more fees by exploiting this
462 // match htlc_minimum_msat logic.
463 let mut cur_hop_transferred_amount_msat = total_fee_paid_msat + value_msat;
464 if let Some(extra_fees_msat) = cur_hop.htlc_minimum_msat.checked_sub(cur_hop_transferred_amount_msat) {
465 // Note that there is a risk that *previous hops* (those closer to us, as we go
466 // payee->our_node here) would exceed their htlc_maximum_msat or available balance.
468 // This might make us end up with a broken route, although this should be super-rare
469 // in practice, both because of how healthy channels look like, and how we pick
470 // channels in add_entry.
471 // Also, this can't be exploited more heavily than *announce a free path and fail
473 cur_hop_transferred_amount_msat += extra_fees_msat;
474 total_fee_paid_msat += extra_fees_msat;
475 cur_hop_fees_msat += extra_fees_msat;
479 // Final hop is a special case: it usually has just value_msat (by design), but also
480 // it still could overpay for the htlc_minimum_msat.
481 cur_hop.fee_msat = cur_hop_transferred_amount_msat;
483 // Propagate updated fees for the use of the channels to one hop back, where they
484 // will be actually paid (fee_msat). The last hop is handled above separately.
485 cur_hop.fee_msat = cur_hop_fees_msat;
488 // Fee for the use of the current hop which will be deducted on the previous hop.
489 // Irrelevant for the first hop, as it doesn't have the previous hop, and the use of
490 // this channel is free for us.
492 if let Some(new_fee) = compute_fees(cur_hop_transferred_amount_msat, cur_hop.channel_fees) {
493 cur_hop.hop_use_fee_msat = new_fee;
494 total_fee_paid_msat += new_fee;
496 // It should not be possible because this function is called only to reduce the
497 // value. In that case, compute_fee was already called with the same fees for
498 // larger amount and there was no overflow.
506 fn compute_fees(amount_msat: u64, channel_fees: RoutingFees) -> Option<u64> {
507 let proportional_fee_millions =
508 amount_msat.checked_mul(channel_fees.proportional_millionths as u64);
509 if let Some(new_fee) = proportional_fee_millions.and_then(|part| {
510 (channel_fees.base_msat as u64).checked_add(part / 1_000_000) }) {
514 // This function may be (indirectly) called without any verification,
515 // with channel_fees provided by a caller. We should handle it gracefully.
520 /// Finds a route from us (payer) to the given target node (payee).
522 /// If the payee provided features in their invoice, they should be provided via `params.payee`.
523 /// Without this, MPP will only be used if the payee's features are available in the network graph.
525 /// Private routing paths between a public node and the target may be included in `params.payee`.
527 /// If some channels aren't announced, it may be useful to fill in `first_hops` with the results
528 /// from [`ChannelManager::list_usable_channels`]. If it is filled in, the view of our local
529 /// channels from [`NetworkGraph`] will be ignored, and only those in `first_hops` will be used.
531 /// The fees on channels from us to the next hop are ignored as they are assumed to all be equal.
532 /// However, the enabled/disabled bit on such channels as well as the `htlc_minimum_msat` /
533 /// `htlc_maximum_msat` *are* checked as they may change based on the receiving node.
537 /// May be used to re-compute a [`Route`] when handling a [`Event::PaymentPathFailed`]. Any
538 /// adjustments to the [`NetworkGraph`] and channel scores should be made prior to calling this
543 /// Panics if first_hops contains channels without short_channel_ids;
544 /// [`ChannelManager::list_usable_channels`] will never include such channels.
546 /// [`ChannelManager::list_usable_channels`]: crate::ln::channelmanager::ChannelManager::list_usable_channels
547 /// [`Event::PaymentPathFailed`]: crate::util::events::Event::PaymentPathFailed
548 pub fn find_route<L: Deref, S: Score>(
549 our_node_pubkey: &PublicKey, params: &RouteParameters, network: &NetworkGraph,
550 first_hops: Option<&[&ChannelDetails]>, logger: L, scorer: &S
551 ) -> Result<Route, LightningError>
552 where L::Target: Logger {
554 our_node_pubkey, ¶ms.payee, network, first_hops, params.final_value_msat,
555 params.final_cltv_expiry_delta, logger, scorer
559 pub(crate) fn get_route<L: Deref, S: Score>(
560 our_node_pubkey: &PublicKey, payee: &Payee, network: &NetworkGraph,
561 first_hops: Option<&[&ChannelDetails]>, final_value_msat: u64, final_cltv_expiry_delta: u32,
562 logger: L, scorer: &S
563 ) -> Result<Route, LightningError>
564 where L::Target: Logger {
565 let payee_node_id = NodeId::from_pubkey(&payee.pubkey);
566 let our_node_id = NodeId::from_pubkey(&our_node_pubkey);
568 if payee_node_id == our_node_id {
569 return Err(LightningError{err: "Cannot generate a route to ourselves".to_owned(), action: ErrorAction::IgnoreError});
572 if final_value_msat > MAX_VALUE_MSAT {
573 return Err(LightningError{err: "Cannot generate a route of more value than all existing satoshis".to_owned(), action: ErrorAction::IgnoreError});
576 if final_value_msat == 0 {
577 return Err(LightningError{err: "Cannot send a payment of 0 msat".to_owned(), action: ErrorAction::IgnoreError});
580 for route in payee.route_hints.iter() {
581 for hop in &route.0 {
582 if hop.src_node_id == payee.pubkey {
583 return Err(LightningError{err: "Route hint cannot have the payee as the source.".to_owned(), action: ErrorAction::IgnoreError});
588 // The general routing idea is the following:
589 // 1. Fill first/last hops communicated by the caller.
590 // 2. Attempt to construct a path from payer to payee for transferring
591 // any ~sufficient (described later) value.
592 // If succeed, remember which channels were used and how much liquidity they have available,
593 // so that future paths don't rely on the same liquidity.
594 // 3. Proceed to the next step if:
595 // - we hit the recommended target value;
596 // - OR if we could not construct a new path. Any next attempt will fail too.
597 // Otherwise, repeat step 2.
598 // 4. See if we managed to collect paths which aggregately are able to transfer target value
599 // (not recommended value). If yes, proceed. If not, fail routing.
600 // 5. Randomly combine paths into routes having enough to fulfill the payment. (TODO: knapsack)
601 // 6. Of all the found paths, select only those with the lowest total fee.
602 // 7. The last path in every selected route is likely to be more than we need.
603 // Reduce its value-to-transfer and recompute fees.
604 // 8. Choose the best route by the lowest total fee.
606 // As for the actual search algorithm,
607 // we do a payee-to-payer pseudo-Dijkstra's sorting by each node's distance from the payee
608 // plus the minimum per-HTLC fee to get from it to another node (aka "shitty pseudo-A*").
610 // We are not a faithful Dijkstra's implementation because we can change values which impact
611 // earlier nodes while processing later nodes. Specifically, if we reach a channel with a lower
612 // liquidity limit (via htlc_maximum_msat, on-chain capacity or assumed liquidity limits) than
613 // the value we are currently attempting to send over a path, we simply reduce the value being
614 // sent along the path for any hops after that channel. This may imply that later fees (which
615 // we've already tabulated) are lower because a smaller value is passing through the channels
616 // (and the proportional fee is thus lower). There isn't a trivial way to recalculate the
617 // channels which were selected earlier (and which may still be used for other paths without a
618 // lower liquidity limit), so we simply accept that some liquidity-limited paths may be
621 // One potentially problematic case for this algorithm would be if there are many
622 // liquidity-limited paths which are liquidity-limited near the destination (ie early in our
623 // graph walking), we may never find a path which is not liquidity-limited and has lower
624 // proportional fee (and only lower absolute fee when considering the ultimate value sent).
625 // Because we only consider paths with at least 5% of the total value being sent, the damage
626 // from such a case should be limited, however this could be further reduced in the future by
627 // calculating fees on the amount we wish to route over a path, ie ignoring the liquidity
628 // limits for the purposes of fee calculation.
630 // Alternatively, we could store more detailed path information in the heap (targets, below)
631 // and index the best-path map (dist, below) by node *and* HTLC limits, however that would blow
632 // up the runtime significantly both algorithmically (as we'd traverse nodes multiple times)
633 // and practically (as we would need to store dynamically-allocated path information in heap
634 // objects, increasing malloc traffic and indirect memory access significantly). Further, the
635 // results of such an algorithm would likely be biased towards lower-value paths.
637 // Further, we could return to a faithful Dijkstra's algorithm by rejecting paths with limits
638 // outside of our current search value, running a path search more times to gather candidate
639 // paths at different values. While this may be acceptable, further path searches may increase
640 // runtime for little gain. Specifically, the current algorithm rather efficiently explores the
641 // graph for candidate paths, calculating the maximum value which can realistically be sent at
642 // the same time, remaining generic across different payment values.
644 // TODO: There are a few tweaks we could do, including possibly pre-calculating more stuff
645 // to use as the A* heuristic beyond just the cost to get one node further than the current
648 let network_graph = network.read_only();
649 let network_channels = network_graph.channels();
650 let network_nodes = network_graph.nodes();
651 let dummy_directional_info = DummyDirectionalChannelInfo { // used for first_hops routes
652 cltv_expiry_delta: 0,
653 htlc_minimum_msat: 0,
654 htlc_maximum_msat: None,
657 proportional_millionths: 0,
661 // Allow MPP only if we have a features set from somewhere that indicates the payee supports
662 // it. If the payee supports it they're supposed to include it in the invoice, so that should
664 let allow_mpp = if let Some(features) = &payee.features {
665 features.supports_basic_mpp()
666 } else if let Some(node) = network_nodes.get(&payee_node_id) {
667 if let Some(node_info) = node.announcement_info.as_ref() {
668 node_info.features.supports_basic_mpp()
671 log_trace!(logger, "Searching for a route from payer {} to payee {} {} MPP", our_node_pubkey,
672 payee.pubkey, if allow_mpp { "with" } else { "without" });
675 // Prepare the data we'll use for payee-to-payer search by
676 // inserting first hops suggested by the caller as targets.
677 // Our search will then attempt to reach them while traversing from the payee node.
678 let mut first_hop_targets: HashMap<_, Vec<(_, ChannelFeatures, _, NodeFeatures)>> =
679 HashMap::with_capacity(if first_hops.is_some() { first_hops.as_ref().unwrap().len() } else { 0 });
680 if let Some(hops) = first_hops {
682 let short_channel_id = chan.short_channel_id.expect("first_hops should be filled in with usable channels, not pending ones");
683 if chan.counterparty.node_id == *our_node_pubkey {
684 return Err(LightningError{err: "First hop cannot have our_node_pubkey as a destination.".to_owned(), action: ErrorAction::IgnoreError});
686 first_hop_targets.entry(NodeId::from_pubkey(&chan.counterparty.node_id)).or_insert(Vec::new())
687 .push((short_channel_id, chan.counterparty.features.to_context(), chan.outbound_capacity_msat, chan.counterparty.features.to_context()));
689 if first_hop_targets.is_empty() {
690 return Err(LightningError{err: "Cannot route when there are no outbound routes away from us".to_owned(), action: ErrorAction::IgnoreError});
694 let empty_channel_features = ChannelFeatures::empty();
696 // The main heap containing all candidate next-hops sorted by their score (max(A* fee,
697 // htlc_minimum)). Ideally this would be a heap which allowed cheap score reduction instead of
698 // adding duplicate entries when we find a better path to a given node.
699 let mut targets = BinaryHeap::new();
701 // Map from node_id to information about the best current path to that node, including feerate
703 let mut dist = HashMap::with_capacity(network_nodes.len());
705 // During routing, if we ignore a path due to an htlc_minimum_msat limit, we set this,
706 // indicating that we may wish to try again with a higher value, potentially paying to meet an
707 // htlc_minimum with extra fees while still finding a cheaper path.
708 let mut hit_minimum_limit;
710 // When arranging a route, we select multiple paths so that we can make a multi-path payment.
711 // We start with a path_value of the exact amount we want, and if that generates a route we may
712 // return it immediately. Otherwise, we don't stop searching for paths until we have 3x the
713 // amount we want in total across paths, selecting the best subset at the end.
714 const ROUTE_CAPACITY_PROVISION_FACTOR: u64 = 3;
715 let recommended_value_msat = final_value_msat * ROUTE_CAPACITY_PROVISION_FACTOR as u64;
716 let mut path_value_msat = final_value_msat;
718 // We don't want multiple paths (as per MPP) share liquidity of the same channels.
719 // This map allows paths to be aware of the channel use by other paths in the same call.
720 // This would help to make a better path finding decisions and not "overbook" channels.
721 // It is unaware of the directions (except for `outbound_capacity_msat` in `first_hops`).
722 let mut bookkept_channels_liquidity_available_msat = HashMap::with_capacity(network_nodes.len());
724 // Keeping track of how much value we already collected across other paths. Helps to decide:
725 // - how much a new path should be transferring (upper bound);
726 // - whether a channel should be disregarded because
727 // it's available liquidity is too small comparing to how much more we need to collect;
728 // - when we want to stop looking for new paths.
729 let mut already_collected_value_msat = 0;
731 log_trace!(logger, "Building path from {} (payee) to {} (us/payer) for value {} msat.", payee.pubkey, our_node_pubkey, final_value_msat);
733 macro_rules! add_entry {
734 // Adds entry which goes from $src_node_id to $dest_node_id
735 // over the channel with id $chan_id with fees described in
736 // $directional_info.
737 // $next_hops_fee_msat represents the fees paid for using all the channels *after* this one,
738 // since that value has to be transferred over this channel.
739 // Returns whether this channel caused an update to `targets`.
740 ( $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,
741 $next_hops_value_contribution: expr, $next_hops_path_htlc_minimum_msat: expr, $next_hops_path_penalty_msat: expr, $next_hops_cltv_delta: expr ) => { {
742 // We "return" whether we updated the path at the end, via this:
743 let mut did_add_update_path_to_src_node = false;
744 // Channels to self should not be used. This is more of belt-and-suspenders, because in
745 // practice these cases should be caught earlier:
746 // - for regular channels at channel announcement (TODO)
747 // - for first and last hops early in get_route
748 if $src_node_id != $dest_node_id.clone() {
749 let available_liquidity_msat = bookkept_channels_liquidity_available_msat.entry($chan_id.clone()).or_insert_with(|| {
750 let mut initial_liquidity_available_msat = None;
751 if let Some(capacity_sats) = $capacity_sats {
752 initial_liquidity_available_msat = Some(capacity_sats * 1000);
755 if let Some(htlc_maximum_msat) = $directional_info.htlc_maximum_msat {
756 if let Some(available_msat) = initial_liquidity_available_msat {
757 initial_liquidity_available_msat = Some(cmp::min(available_msat, htlc_maximum_msat));
759 initial_liquidity_available_msat = Some(htlc_maximum_msat);
763 match initial_liquidity_available_msat {
764 Some(available_msat) => available_msat,
765 // We assume channels with unknown balance have
766 // a capacity of 0.0025 BTC (or 250_000 sats).
767 None => 250_000 * 1000
771 // It is tricky to substract $next_hops_fee_msat from available liquidity here.
772 // It may be misleading because we might later choose to reduce the value transferred
773 // over these channels, and the channel which was insufficient might become sufficient.
774 // Worst case: we drop a good channel here because it can't cover the high following
775 // fees caused by one expensive channel, but then this channel could have been used
776 // if the amount being transferred over this path is lower.
777 // We do this for now, but this is a subject for removal.
778 if let Some(available_value_contribution_msat) = available_liquidity_msat.checked_sub($next_hops_fee_msat) {
780 // Routing Fragmentation Mitigation heuristic:
782 // Routing fragmentation across many payment paths increases the overall routing
783 // fees as you have irreducible routing fees per-link used (`fee_base_msat`).
784 // Taking too many smaller paths also increases the chance of payment failure.
785 // Thus to avoid this effect, we require from our collected links to provide
786 // at least a minimal contribution to the recommended value yet-to-be-fulfilled.
788 // This requirement is currently 5% of the remaining-to-be-collected value.
789 // This means as we successfully advance in our collection,
790 // the absolute liquidity contribution is lowered,
791 // thus increasing the number of potential channels to be selected.
793 // Derive the minimal liquidity contribution with a ratio of 20 (5%, rounded up)
794 // or 100% if we're not allowed to do multipath payments.
795 let minimal_value_contribution_msat: u64 = if allow_mpp {
796 (recommended_value_msat - already_collected_value_msat + 19) / 20
800 // Verify the liquidity offered by this channel complies to the minimal contribution.
801 let contributes_sufficient_value = available_value_contribution_msat >= minimal_value_contribution_msat;
804 // Do not consider candidates that exceed the maximum total cltv expiry limit.
805 let max_total_cltv_expiry_delta = payee.max_total_cltv_expiry_delta;
806 let hop_total_cltv_delta = ($next_hops_cltv_delta as u32)
807 .checked_add($directional_info.cltv_expiry_delta as u32)
808 .unwrap_or(u32::max_value());
809 let doesnt_exceed_cltv_delta_limit = hop_total_cltv_delta <= max_total_cltv_expiry_delta;
811 let value_contribution_msat = cmp::min(available_value_contribution_msat, $next_hops_value_contribution);
812 // Includes paying fees for the use of the following channels.
813 let amount_to_transfer_over_msat: u64 = match value_contribution_msat.checked_add($next_hops_fee_msat) {
814 Some(result) => result,
815 // Can't overflow due to how the values were computed right above.
816 None => unreachable!(),
818 #[allow(unused_comparisons)] // $next_hops_path_htlc_minimum_msat is 0 in some calls so rustc complains
819 let over_path_minimum_msat = amount_to_transfer_over_msat >= $directional_info.htlc_minimum_msat &&
820 amount_to_transfer_over_msat >= $next_hops_path_htlc_minimum_msat;
822 // If HTLC minimum is larger than the amount we're going to transfer, we shouldn't
823 // bother considering this channel.
824 // Since we're choosing amount_to_transfer_over_msat as maximum possible, it can
825 // be only reduced later (not increased), so this channel should just be skipped
826 // as not sufficient.
827 if !over_path_minimum_msat && doesnt_exceed_cltv_delta_limit {
828 hit_minimum_limit = true;
829 } else if contributes_sufficient_value && doesnt_exceed_cltv_delta_limit {
830 // Note that low contribution here (limited by available_liquidity_msat)
831 // might violate htlc_minimum_msat on the hops which are next along the
832 // payment path (upstream to the payee). To avoid that, we recompute
833 // path fees knowing the final path contribution after constructing it.
834 let path_htlc_minimum_msat = compute_fees($next_hops_path_htlc_minimum_msat, $directional_info.fees)
835 .and_then(|fee_msat| fee_msat.checked_add($next_hops_path_htlc_minimum_msat))
836 .map(|fee_msat| cmp::max(fee_msat, $directional_info.htlc_minimum_msat))
837 .unwrap_or_else(|| u64::max_value());
838 let hm_entry = dist.entry($src_node_id);
839 let old_entry = hm_entry.or_insert_with(|| {
840 // If there was previously no known way to access
841 // the source node (recall it goes payee-to-payer) of $chan_id, first add
842 // a semi-dummy record just to compute the fees to reach the source node.
843 // This will affect our decision on selecting $chan_id
844 // as a way to reach the $dest_node_id.
845 let mut fee_base_msat = u32::max_value();
846 let mut fee_proportional_millionths = u32::max_value();
847 if let Some(Some(fees)) = network_nodes.get(&$src_node_id).map(|node| node.lowest_inbound_channel_fees) {
848 fee_base_msat = fees.base_msat;
849 fee_proportional_millionths = fees.proportional_millionths;
852 node_id: $dest_node_id.clone(),
854 channel_features: $chan_features,
856 cltv_expiry_delta: 0,
857 src_lowest_inbound_fees: RoutingFees {
858 base_msat: fee_base_msat,
859 proportional_millionths: fee_proportional_millionths,
861 channel_fees: $directional_info.fees,
862 next_hops_fee_msat: u64::max_value(),
863 hop_use_fee_msat: u64::max_value(),
864 total_fee_msat: u64::max_value(),
865 htlc_minimum_msat: $directional_info.htlc_minimum_msat,
866 path_htlc_minimum_msat,
867 path_penalty_msat: u64::max_value(),
868 was_processed: false,
869 #[cfg(any(test, feature = "fuzztarget"))]
870 value_contribution_msat,
874 #[allow(unused_mut)] // We only use the mut in cfg(test)
875 let mut should_process = !old_entry.was_processed;
876 #[cfg(any(test, feature = "fuzztarget"))]
878 // In test/fuzzing builds, we do extra checks to make sure the skipping
879 // of already-seen nodes only happens in cases we expect (see below).
880 if !should_process { should_process = true; }
884 let mut hop_use_fee_msat = 0;
885 let mut total_fee_msat = $next_hops_fee_msat;
887 // Ignore hop_use_fee_msat for channel-from-us as we assume all channels-from-us
888 // will have the same effective-fee
889 if $src_node_id != our_node_id {
890 match compute_fees(amount_to_transfer_over_msat, $directional_info.fees) {
891 // max_value means we'll always fail
892 // the old_entry.total_fee_msat > total_fee_msat check
893 None => total_fee_msat = u64::max_value(),
895 hop_use_fee_msat = fee_msat;
896 total_fee_msat += hop_use_fee_msat;
897 // When calculating the lowest inbound fees to a node, we
898 // calculate fees here not based on the actual value we think
899 // will flow over this channel, but on the minimum value that
900 // we'll accept flowing over it. The minimum accepted value
901 // is a constant through each path collection run, ensuring
902 // consistent basis. Otherwise we may later find a
903 // different path to the source node that is more expensive,
904 // but which we consider to be cheaper because we are capacity
905 // constrained and the relative fee becomes lower.
906 match compute_fees(minimal_value_contribution_msat, old_entry.src_lowest_inbound_fees)
907 .map(|a| a.checked_add(total_fee_msat)) {
912 total_fee_msat = u64::max_value();
919 let path_penalty_msat = $next_hops_path_penalty_msat.checked_add(
920 scorer.channel_penalty_msat($chan_id.clone(), amount_to_transfer_over_msat, Some(*available_liquidity_msat),
921 &$src_node_id, &$dest_node_id)).unwrap_or_else(|| u64::max_value());
922 let new_graph_node = RouteGraphNode {
923 node_id: $src_node_id,
924 lowest_fee_to_peer_through_node: total_fee_msat,
925 lowest_fee_to_node: $next_hops_fee_msat as u64 + hop_use_fee_msat,
926 total_cltv_delta: hop_total_cltv_delta,
927 value_contribution_msat: value_contribution_msat,
928 path_htlc_minimum_msat,
932 // Update the way of reaching $src_node_id with the given $chan_id (from $dest_node_id),
933 // if this way is cheaper than the already known
934 // (considering the cost to "reach" this channel from the route destination,
935 // the cost of using this channel,
936 // and the cost of routing to the source node of this channel).
937 // Also, consider that htlc_minimum_msat_difference, because we might end up
938 // paying it. Consider the following exploit:
939 // we use 2 paths to transfer 1.5 BTC. One of them is 0-fee normal 1 BTC path,
940 // and for the other one we picked a 1sat-fee path with htlc_minimum_msat of
941 // 1 BTC. Now, since the latter is more expensive, we gonna try to cut it
942 // by 0.5 BTC, but then match htlc_minimum_msat by paying a fee of 0.5 BTC
944 // Ideally the scoring could be smarter (e.g. 0.5*htlc_minimum_msat here),
945 // but it may require additional tracking - we don't want to double-count
946 // the fees included in $next_hops_path_htlc_minimum_msat, but also
947 // can't use something that may decrease on future hops.
948 let old_cost = cmp::max(old_entry.total_fee_msat, old_entry.path_htlc_minimum_msat)
949 .checked_add(old_entry.path_penalty_msat)
950 .unwrap_or_else(|| u64::max_value());
951 let new_cost = cmp::max(total_fee_msat, path_htlc_minimum_msat)
952 .checked_add(path_penalty_msat)
953 .unwrap_or_else(|| u64::max_value());
955 if !old_entry.was_processed && new_cost < old_cost {
956 targets.push(new_graph_node);
957 old_entry.next_hops_fee_msat = $next_hops_fee_msat;
958 old_entry.hop_use_fee_msat = hop_use_fee_msat;
959 old_entry.total_fee_msat = total_fee_msat;
960 old_entry.node_id = $dest_node_id.clone();
961 old_entry.short_channel_id = $chan_id.clone();
962 old_entry.channel_features = $chan_features;
963 old_entry.fee_msat = 0; // This value will be later filled with hop_use_fee_msat of the following channel
964 old_entry.cltv_expiry_delta = $directional_info.cltv_expiry_delta as u32;
965 old_entry.channel_fees = $directional_info.fees;
966 old_entry.htlc_minimum_msat = $directional_info.htlc_minimum_msat;
967 old_entry.path_htlc_minimum_msat = path_htlc_minimum_msat;
968 old_entry.path_penalty_msat = path_penalty_msat;
969 #[cfg(any(test, feature = "fuzztarget"))]
971 old_entry.value_contribution_msat = value_contribution_msat;
973 did_add_update_path_to_src_node = true;
974 } else if old_entry.was_processed && new_cost < old_cost {
975 #[cfg(any(test, feature = "fuzztarget"))]
977 // If we're skipping processing a node which was previously
978 // processed even though we found another path to it with a
979 // cheaper fee, check that it was because the second path we
980 // found (which we are processing now) has a lower value
981 // contribution due to an HTLC minimum limit.
983 // e.g. take a graph with two paths from node 1 to node 2, one
984 // through channel A, and one through channel B. Channel A and
985 // B are both in the to-process heap, with their scores set by
986 // a higher htlc_minimum than fee.
987 // Channel A is processed first, and the channels onwards from
988 // node 1 are added to the to-process heap. Thereafter, we pop
989 // Channel B off of the heap, note that it has a much more
990 // restrictive htlc_maximum_msat, and recalculate the fees for
991 // all of node 1's channels using the new, reduced, amount.
993 // This would be bogus - we'd be selecting a higher-fee path
994 // with a lower htlc_maximum_msat instead of the one we'd
995 // already decided to use.
996 debug_assert!(path_htlc_minimum_msat < old_entry.path_htlc_minimum_msat);
998 value_contribution_msat + path_penalty_msat <
999 old_entry.value_contribution_msat + old_entry.path_penalty_msat
1007 did_add_update_path_to_src_node
1011 let empty_node_features = NodeFeatures::empty();
1012 // Find ways (channels with destination) to reach a given node and store them
1013 // in the corresponding data structures (routing graph etc).
1014 // $fee_to_target_msat represents how much it costs to reach to this node from the payee,
1015 // meaning how much will be paid in fees after this node (to the best of our knowledge).
1016 // This data can later be helpful to optimize routing (pay lower fees).
1017 macro_rules! add_entries_to_cheapest_to_target_node {
1018 ( $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, $next_hops_cltv_delta: expr ) => {
1019 let skip_node = if let Some(elem) = dist.get_mut(&$node_id) {
1020 let was_processed = elem.was_processed;
1021 elem.was_processed = true;
1024 // Entries are added to dist in add_entry!() when there is a channel from a node.
1025 // Because there are no channels from payee, it will not have a dist entry at this point.
1026 // If we're processing any other node, it is always be the result of a channel from it.
1027 assert_eq!($node_id, payee_node_id);
1032 if let Some(first_channels) = first_hop_targets.get(&$node_id) {
1033 for (ref first_hop, ref features, ref outbound_capacity_msat, _) in first_channels {
1034 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, $next_hops_cltv_delta);
1038 let features = if let Some(node_info) = $node.announcement_info.as_ref() {
1041 &empty_node_features
1044 if !features.requires_unknown_bits() {
1045 for chan_id in $node.channels.iter() {
1046 let chan = network_channels.get(chan_id).unwrap();
1047 if !chan.features.requires_unknown_bits() {
1048 if chan.node_one == $node_id {
1049 // ie $node is one, ie next hop in A* is two, via the two_to_one channel
1050 if first_hops.is_none() || chan.node_two != our_node_id {
1051 if let Some(two_to_one) = chan.two_to_one.as_ref() {
1052 if two_to_one.enabled {
1053 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, $next_hops_cltv_delta);
1058 if first_hops.is_none() || chan.node_one != our_node_id{
1059 if let Some(one_to_two) = chan.one_to_two.as_ref() {
1060 if one_to_two.enabled {
1061 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, $next_hops_cltv_delta);
1073 let mut payment_paths = Vec::<PaymentPath>::new();
1075 // TODO: diversify by nodes (so that all paths aren't doomed if one node is offline).
1076 'paths_collection: loop {
1077 // For every new path, start from scratch, except
1078 // bookkept_channels_liquidity_available_msat, which will improve
1079 // the further iterations of path finding. Also don't erase first_hop_targets.
1082 hit_minimum_limit = false;
1084 // If first hop is a private channel and the only way to reach the payee, this is the only
1085 // place where it could be added.
1086 if let Some(first_channels) = first_hop_targets.get(&payee_node_id) {
1087 for (ref first_hop, ref features, ref outbound_capacity_msat, _) in first_channels {
1088 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, 0);
1089 log_trace!(logger, "{} direct route to payee via SCID {}", if added { "Added" } else { "Skipped" }, first_hop);
1093 // Add the payee as a target, so that the payee-to-payer
1094 // search algorithm knows what to start with.
1095 match network_nodes.get(&payee_node_id) {
1096 // The payee is not in our network graph, so nothing to add here.
1097 // There is still a chance of reaching them via last_hops though,
1098 // so don't yet fail the payment here.
1099 // If not, targets.pop() will not even let us enter the loop in step 2.
1102 add_entries_to_cheapest_to_target_node!(node, payee_node_id, 0, path_value_msat, 0, 0u64, 0);
1107 // If a caller provided us with last hops, add them to routing targets. Since this happens
1108 // earlier than general path finding, they will be somewhat prioritized, although currently
1109 // it matters only if the fees are exactly the same.
1110 for route in payee.route_hints.iter().filter(|route| !route.0.is_empty()) {
1111 let first_hop_in_route = &(route.0)[0];
1112 let have_hop_src_in_graph =
1113 // Only add the hops in this route to our candidate set if either
1114 // we have a direct channel to the first hop or the first hop is
1115 // in the regular network graph.
1116 first_hop_targets.get(&NodeId::from_pubkey(&first_hop_in_route.src_node_id)).is_some() ||
1117 network_nodes.get(&NodeId::from_pubkey(&first_hop_in_route.src_node_id)).is_some();
1118 if have_hop_src_in_graph {
1119 // We start building the path from reverse, i.e., from payee
1120 // to the first RouteHintHop in the path.
1121 let hop_iter = route.0.iter().rev();
1122 let prev_hop_iter = core::iter::once(&payee.pubkey).chain(
1123 route.0.iter().skip(1).rev().map(|hop| &hop.src_node_id));
1124 let mut hop_used = true;
1125 let mut aggregate_next_hops_fee_msat: u64 = 0;
1126 let mut aggregate_next_hops_path_htlc_minimum_msat: u64 = 0;
1127 let mut aggregate_next_hops_path_penalty_msat: u64 = 0;
1128 let mut aggregate_next_hops_cltv_delta: u32 = 0;
1130 for (idx, (hop, prev_hop_id)) in hop_iter.zip(prev_hop_iter).enumerate() {
1131 // BOLT 11 doesn't allow inclusion of features for the last hop hints, which
1132 // really sucks, cause we're gonna need that eventually.
1133 let hop_htlc_minimum_msat: u64 = hop.htlc_minimum_msat.unwrap_or(0);
1135 let directional_info = DummyDirectionalChannelInfo {
1136 cltv_expiry_delta: hop.cltv_expiry_delta as u32,
1137 htlc_minimum_msat: hop_htlc_minimum_msat,
1138 htlc_maximum_msat: hop.htlc_maximum_msat,
1142 // We want a value of final_value_msat * ROUTE_CAPACITY_PROVISION_FACTOR but we
1143 // need it to increment at each hop by the fee charged at later hops. Further,
1144 // we need to ensure we round up when we divide to get satoshis.
1145 let channel_cap_msat = final_value_msat
1146 .checked_mul(ROUTE_CAPACITY_PROVISION_FACTOR).and_then(|v| v.checked_add(aggregate_next_hops_fee_msat))
1147 .unwrap_or(u64::max_value());
1148 let channel_cap_sat = match channel_cap_msat.checked_add(999) {
1149 None => break, // We overflowed above, just ignore this route hint
1150 Some(val) => Some(val / 1000),
1153 let src_node_id = NodeId::from_pubkey(&hop.src_node_id);
1154 let dest_node_id = NodeId::from_pubkey(&prev_hop_id);
1155 aggregate_next_hops_path_penalty_msat = aggregate_next_hops_path_penalty_msat
1156 .checked_add(scorer.channel_penalty_msat(hop.short_channel_id, final_value_msat, None, &src_node_id, &dest_node_id))
1157 .unwrap_or_else(|| u64::max_value());
1159 aggregate_next_hops_cltv_delta = aggregate_next_hops_cltv_delta
1160 .checked_add(hop.cltv_expiry_delta as u32)
1161 .unwrap_or_else(|| u32::max_value());
1163 // We assume that the recipient only included route hints for routes which had
1164 // sufficient value to route `final_value_msat`. Note that in the case of "0-value"
1165 // invoices where the invoice does not specify value this may not be the case, but
1166 // better to include the hints than not.
1167 if !add_entry!(hop.short_channel_id, src_node_id, dest_node_id, directional_info, channel_cap_sat, &empty_channel_features, aggregate_next_hops_fee_msat, path_value_msat, aggregate_next_hops_path_htlc_minimum_msat, aggregate_next_hops_path_penalty_msat, aggregate_next_hops_cltv_delta) {
1168 // If this hop was not used then there is no use checking the preceding hops
1169 // in the RouteHint. We can break by just searching for a direct channel between
1170 // last checked hop and first_hop_targets
1174 // Searching for a direct channel between last checked hop and first_hop_targets
1175 if let Some(first_channels) = first_hop_targets.get(&NodeId::from_pubkey(&prev_hop_id)) {
1176 for (ref first_hop, ref features, ref outbound_capacity_msat, _) in first_channels {
1177 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, aggregate_next_hops_cltv_delta);
1185 // In the next values of the iterator, the aggregate fees already reflects
1186 // the sum of value sent from payer (final_value_msat) and routing fees
1187 // for the last node in the RouteHint. We need to just add the fees to
1188 // route through the current node so that the preceeding node (next iteration)
1190 let hops_fee = compute_fees(aggregate_next_hops_fee_msat + final_value_msat, hop.fees)
1191 .map_or(None, |inc| inc.checked_add(aggregate_next_hops_fee_msat));
1192 aggregate_next_hops_fee_msat = if let Some(val) = hops_fee { val } else { break; };
1194 let hop_htlc_minimum_msat_inc = if let Some(val) = compute_fees(aggregate_next_hops_path_htlc_minimum_msat, hop.fees) { val } else { break; };
1195 let hops_path_htlc_minimum = aggregate_next_hops_path_htlc_minimum_msat
1196 .checked_add(hop_htlc_minimum_msat_inc);
1197 aggregate_next_hops_path_htlc_minimum_msat = if let Some(val) = hops_path_htlc_minimum { cmp::max(hop_htlc_minimum_msat, val) } else { break; };
1199 if idx == route.0.len() - 1 {
1200 // The last hop in this iterator is the first hop in
1201 // overall RouteHint.
1202 // If this hop connects to a node with which we have a direct channel,
1203 // ignore the network graph and, if the last hop was added, add our
1204 // direct channel to the candidate set.
1206 // Note that we *must* check if the last hop was added as `add_entry`
1207 // always assumes that the third argument is a node to which we have a
1209 if let Some(first_channels) = first_hop_targets.get(&NodeId::from_pubkey(&hop.src_node_id)) {
1210 for (ref first_hop, ref features, ref outbound_capacity_msat, _) in first_channels {
1211 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, aggregate_next_hops_cltv_delta);
1219 log_trace!(logger, "Starting main path collection loop with {} nodes pre-filled from first/last hops.", targets.len());
1221 // At this point, targets are filled with the data from first and
1222 // last hops communicated by the caller, and the payment receiver.
1223 let mut found_new_path = false;
1226 // If this loop terminates due the exhaustion of targets, two situations are possible:
1227 // - not enough outgoing liquidity:
1228 // 0 < already_collected_value_msat < final_value_msat
1229 // - enough outgoing liquidity:
1230 // final_value_msat <= already_collected_value_msat < recommended_value_msat
1231 // Both these cases (and other cases except reaching recommended_value_msat) mean that
1232 // paths_collection will be stopped because found_new_path==false.
1233 // This is not necessarily a routing failure.
1234 'path_construction: while let Some(RouteGraphNode { node_id, lowest_fee_to_node, total_cltv_delta, value_contribution_msat, path_htlc_minimum_msat, path_penalty_msat, .. }) = targets.pop() {
1236 // Since we're going payee-to-payer, hitting our node as a target means we should stop
1237 // traversing the graph and arrange the path out of what we found.
1238 if node_id == our_node_id {
1239 let mut new_entry = dist.remove(&our_node_id).unwrap();
1240 let mut ordered_hops = vec!((new_entry.clone(), NodeFeatures::empty()));
1243 let mut features_set = false;
1244 if let Some(first_channels) = first_hop_targets.get(&ordered_hops.last().unwrap().0.node_id) {
1245 for (scid, _, _, ref features) in first_channels {
1246 if *scid == ordered_hops.last().unwrap().0.short_channel_id {
1247 ordered_hops.last_mut().unwrap().1 = features.clone();
1248 features_set = true;
1254 if let Some(node) = network_nodes.get(&ordered_hops.last().unwrap().0.node_id) {
1255 if let Some(node_info) = node.announcement_info.as_ref() {
1256 ordered_hops.last_mut().unwrap().1 = node_info.features.clone();
1258 ordered_hops.last_mut().unwrap().1 = NodeFeatures::empty();
1261 // We should be able to fill in features for everything except the last
1262 // hop, if the last hop was provided via a BOLT 11 invoice (though we
1263 // should be able to extend it further as BOLT 11 does have feature
1264 // flags for the last hop node itself).
1265 assert!(ordered_hops.last().unwrap().0.node_id == payee_node_id);
1269 // Means we succesfully traversed from the payer to the payee, now
1270 // save this path for the payment route. Also, update the liquidity
1271 // remaining on the used hops, so that we take them into account
1272 // while looking for more paths.
1273 if ordered_hops.last().unwrap().0.node_id == payee_node_id {
1277 new_entry = match dist.remove(&ordered_hops.last().unwrap().0.node_id) {
1278 Some(payment_hop) => payment_hop,
1279 // We can't arrive at None because, if we ever add an entry to targets,
1280 // we also fill in the entry in dist (see add_entry!).
1281 None => unreachable!(),
1283 // We "propagate" the fees one hop backward (topologically) here,
1284 // so that fees paid for a HTLC forwarding on the current channel are
1285 // associated with the previous channel (where they will be subtracted).
1286 ordered_hops.last_mut().unwrap().0.fee_msat = new_entry.hop_use_fee_msat;
1287 ordered_hops.last_mut().unwrap().0.cltv_expiry_delta = new_entry.cltv_expiry_delta;
1288 ordered_hops.push((new_entry.clone(), NodeFeatures::empty()));
1290 ordered_hops.last_mut().unwrap().0.fee_msat = value_contribution_msat;
1291 ordered_hops.last_mut().unwrap().0.hop_use_fee_msat = 0;
1292 ordered_hops.last_mut().unwrap().0.cltv_expiry_delta = final_cltv_expiry_delta;
1294 log_trace!(logger, "Found a path back to us from the target with {} hops contributing up to {} msat: {:?}",
1295 ordered_hops.len(), value_contribution_msat, ordered_hops);
1297 let mut payment_path = PaymentPath {hops: ordered_hops};
1299 // We could have possibly constructed a slightly inconsistent path: since we reduce
1300 // value being transferred along the way, we could have violated htlc_minimum_msat
1301 // on some channels we already passed (assuming dest->source direction). Here, we
1302 // recompute the fees again, so that if that's the case, we match the currently
1303 // underpaid htlc_minimum_msat with fees.
1304 payment_path.update_value_and_recompute_fees(cmp::min(value_contribution_msat, final_value_msat));
1306 // Since a path allows to transfer as much value as
1307 // the smallest channel it has ("bottleneck"), we should recompute
1308 // the fees so sender HTLC don't overpay fees when traversing
1309 // larger channels than the bottleneck. This may happen because
1310 // when we were selecting those channels we were not aware how much value
1311 // this path will transfer, and the relative fee for them
1312 // might have been computed considering a larger value.
1313 // Remember that we used these channels so that we don't rely
1314 // on the same liquidity in future paths.
1315 let mut prevented_redundant_path_selection = false;
1316 for (payment_hop, _) in payment_path.hops.iter() {
1317 let channel_liquidity_available_msat = bookkept_channels_liquidity_available_msat.get_mut(&payment_hop.short_channel_id).unwrap();
1318 let mut spent_on_hop_msat = value_contribution_msat;
1319 let next_hops_fee_msat = payment_hop.next_hops_fee_msat;
1320 spent_on_hop_msat += next_hops_fee_msat;
1321 if spent_on_hop_msat == *channel_liquidity_available_msat {
1322 // If this path used all of this channel's available liquidity, we know
1323 // this path will not be selected again in the next loop iteration.
1324 prevented_redundant_path_selection = true;
1326 *channel_liquidity_available_msat -= spent_on_hop_msat;
1328 if !prevented_redundant_path_selection {
1329 // If we weren't capped by hitting a liquidity limit on a channel in the path,
1330 // we'll probably end up picking the same path again on the next iteration.
1331 // Decrease the available liquidity of a hop in the middle of the path.
1332 let victim_scid = payment_path.hops[(payment_path.hops.len() - 1) / 2].0.short_channel_id;
1333 log_trace!(logger, "Disabling channel {} for future path building iterations to avoid duplicates.", victim_scid);
1334 let victim_liquidity = bookkept_channels_liquidity_available_msat.get_mut(&victim_scid).unwrap();
1335 *victim_liquidity = 0;
1338 // Track the total amount all our collected paths allow to send so that we:
1339 // - know when to stop looking for more paths
1340 // - know which of the hops are useless considering how much more sats we need
1341 // (contributes_sufficient_value)
1342 already_collected_value_msat += value_contribution_msat;
1344 payment_paths.push(payment_path);
1345 found_new_path = true;
1346 break 'path_construction;
1349 // If we found a path back to the payee, we shouldn't try to process it again. This is
1350 // the equivalent of the `elem.was_processed` check in
1351 // add_entries_to_cheapest_to_target_node!() (see comment there for more info).
1352 if node_id == payee_node_id { continue 'path_construction; }
1354 // Otherwise, since the current target node is not us,
1355 // keep "unrolling" the payment graph from payee to payer by
1356 // finding a way to reach the current target from the payer side.
1357 match network_nodes.get(&node_id) {
1360 add_entries_to_cheapest_to_target_node!(node, node_id, lowest_fee_to_node, value_contribution_msat, path_htlc_minimum_msat, path_penalty_msat, total_cltv_delta);
1366 // If we don't support MPP, no use trying to gather more value ever.
1367 break 'paths_collection;
1371 // Stop either when the recommended value is reached or if no new path was found in this
1373 // In the latter case, making another path finding attempt won't help,
1374 // because we deterministically terminated the search due to low liquidity.
1375 if already_collected_value_msat >= recommended_value_msat || !found_new_path {
1376 log_trace!(logger, "Have now collected {} msat (seeking {} msat) in paths. Last path loop {} a new path.",
1377 already_collected_value_msat, recommended_value_msat, if found_new_path { "found" } else { "did not find" });
1378 break 'paths_collection;
1379 } else if found_new_path && already_collected_value_msat == final_value_msat && payment_paths.len() == 1 {
1380 // Further, if this was our first walk of the graph, and we weren't limited by an
1381 // htlc_minimum_msat, return immediately because this path should suffice. If we were
1382 // limited by an htlc_minimum_msat value, find another path with a higher value,
1383 // potentially allowing us to pay fees to meet the htlc_minimum on the new path while
1384 // still keeping a lower total fee than this path.
1385 if !hit_minimum_limit {
1386 log_trace!(logger, "Collected exactly our payment amount on the first pass, without hitting an htlc_minimum_msat limit, exiting.");
1387 break 'paths_collection;
1389 log_trace!(logger, "Collected our payment amount on the first pass, but running again to collect extra paths with a potentially higher limit.");
1390 path_value_msat = recommended_value_msat;
1395 if payment_paths.len() == 0 {
1396 return Err(LightningError{err: "Failed to find a path to the given destination".to_owned(), action: ErrorAction::IgnoreError});
1399 if already_collected_value_msat < final_value_msat {
1400 return Err(LightningError{err: "Failed to find a sufficient route to the given destination".to_owned(), action: ErrorAction::IgnoreError});
1403 // Sort by total fees and take the best paths.
1404 payment_paths.sort_by_key(|path| path.get_total_fee_paid_msat());
1405 if payment_paths.len() > 50 {
1406 payment_paths.truncate(50);
1409 // Draw multiple sufficient routes by randomly combining the selected paths.
1410 let mut drawn_routes = Vec::new();
1411 for i in 0..payment_paths.len() {
1412 let mut cur_route = Vec::<PaymentPath>::new();
1413 let mut aggregate_route_value_msat = 0;
1416 // TODO: real random shuffle
1417 // Currently just starts with i_th and goes up to i-1_th in a looped way.
1418 let cur_payment_paths = [&payment_paths[i..], &payment_paths[..i]].concat();
1421 for payment_path in cur_payment_paths {
1422 cur_route.push(payment_path.clone());
1423 aggregate_route_value_msat += payment_path.get_value_msat();
1424 if aggregate_route_value_msat > final_value_msat {
1425 // Last path likely overpaid. Substract it from the most expensive
1426 // (in terms of proportional fee) path in this route and recompute fees.
1427 // This might be not the most economically efficient way, but fewer paths
1428 // also makes routing more reliable.
1429 let mut overpaid_value_msat = aggregate_route_value_msat - final_value_msat;
1431 // First, drop some expensive low-value paths entirely if possible.
1432 // Sort by value so that we drop many really-low values first, since
1433 // fewer paths is better: the payment is less likely to fail.
1434 // TODO: this could also be optimized by also sorting by feerate_per_sat_routed,
1435 // so that the sender pays less fees overall. And also htlc_minimum_msat.
1436 cur_route.sort_by_key(|path| path.get_value_msat());
1437 // We should make sure that at least 1 path left.
1438 let mut paths_left = cur_route.len();
1439 cur_route.retain(|path| {
1440 if paths_left == 1 {
1443 let mut keep = true;
1444 let path_value_msat = path.get_value_msat();
1445 if path_value_msat <= overpaid_value_msat {
1447 overpaid_value_msat -= path_value_msat;
1453 if overpaid_value_msat == 0 {
1457 assert!(cur_route.len() > 0);
1460 // Now, substract the overpaid value from the most-expensive path.
1461 // TODO: this could also be optimized by also sorting by feerate_per_sat_routed,
1462 // so that the sender pays less fees overall. And also htlc_minimum_msat.
1463 cur_route.sort_by_key(|path| { path.hops.iter().map(|hop| hop.0.channel_fees.proportional_millionths as u64).sum::<u64>() });
1464 let expensive_payment_path = cur_route.first_mut().unwrap();
1465 // We already dropped all the small channels above, meaning all the
1466 // remaining channels are larger than remaining overpaid_value_msat.
1467 // Thus, this can't be negative.
1468 let expensive_path_new_value_msat = expensive_payment_path.get_value_msat() - overpaid_value_msat;
1469 expensive_payment_path.update_value_and_recompute_fees(expensive_path_new_value_msat);
1473 drawn_routes.push(cur_route);
1477 // Select the best route by lowest total fee.
1478 drawn_routes.sort_by_key(|paths| paths.iter().map(|path| path.get_total_fee_paid_msat()).sum::<u64>());
1479 let mut selected_paths = Vec::<Vec<Result<RouteHop, LightningError>>>::new();
1480 for payment_path in drawn_routes.first().unwrap() {
1481 selected_paths.push(payment_path.hops.iter().map(|(payment_hop, node_features)| {
1483 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)})?,
1484 node_features: node_features.clone(),
1485 short_channel_id: payment_hop.short_channel_id,
1486 channel_features: payment_hop.channel_features.clone(),
1487 fee_msat: payment_hop.fee_msat,
1488 cltv_expiry_delta: payment_hop.cltv_expiry_delta,
1493 if let Some(features) = &payee.features {
1494 for path in selected_paths.iter_mut() {
1495 if let Ok(route_hop) = path.last_mut().unwrap() {
1496 route_hop.node_features = features.to_context();
1502 paths: selected_paths.into_iter().map(|path| path.into_iter().collect()).collect::<Result<Vec<_>, _>>()?,
1503 payee: Some(payee.clone()),
1505 log_info!(logger, "Got route to {}: {}", payee.pubkey, log_route!(route));
1511 use routing::scoring::Score;
1512 use routing::network_graph::{NetworkGraph, NetGraphMsgHandler, NodeId};
1513 use routing::router::{get_route, Payee, Route, RouteHint, RouteHintHop, RouteHop, RoutingFees};
1514 use chain::transaction::OutPoint;
1515 use ln::features::{ChannelFeatures, InitFeatures, InvoiceFeatures, NodeFeatures};
1516 use ln::msgs::{ErrorAction, LightningError, OptionalField, UnsignedChannelAnnouncement, ChannelAnnouncement, RoutingMessageHandler,
1517 NodeAnnouncement, UnsignedNodeAnnouncement, ChannelUpdate, UnsignedChannelUpdate};
1518 use ln::channelmanager;
1519 use util::test_utils;
1520 use util::ser::Writeable;
1522 use util::ser::Writer;
1524 use bitcoin::hashes::sha256d::Hash as Sha256dHash;
1525 use bitcoin::hashes::Hash;
1526 use bitcoin::network::constants::Network;
1527 use bitcoin::blockdata::constants::genesis_block;
1528 use bitcoin::blockdata::script::Builder;
1529 use bitcoin::blockdata::opcodes;
1530 use bitcoin::blockdata::transaction::TxOut;
1534 use bitcoin::secp256k1::key::{PublicKey,SecretKey};
1535 use bitcoin::secp256k1::{Secp256k1, All};
1538 use sync::{self, Arc};
1540 fn get_channel_details(short_channel_id: Option<u64>, node_id: PublicKey,
1541 features: InitFeatures, outbound_capacity_msat: u64) -> channelmanager::ChannelDetails {
1542 channelmanager::ChannelDetails {
1543 channel_id: [0; 32],
1544 counterparty: channelmanager::ChannelCounterparty {
1547 unspendable_punishment_reserve: 0,
1548 forwarding_info: None,
1550 funding_txo: Some(OutPoint { txid: bitcoin::Txid::from_slice(&[0; 32]).unwrap(), index: 0 }),
1552 channel_value_satoshis: 0,
1555 outbound_capacity_msat,
1556 inbound_capacity_msat: 42,
1557 unspendable_punishment_reserve: None,
1558 confirmations_required: None,
1559 force_close_spend_delay: None,
1560 is_outbound: true, is_funding_locked: true,
1561 is_usable: true, is_public: true,
1565 // Using the same keys for LN and BTC ids
1567 net_graph_msg_handler: &NetGraphMsgHandler<Arc<NetworkGraph>, Arc<test_utils::TestChainSource>, Arc<test_utils::TestLogger>>,
1568 secp_ctx: &Secp256k1<All>, node_1_privkey: &SecretKey, node_2_privkey: &SecretKey, features: ChannelFeatures, short_channel_id: u64
1570 let node_id_1 = PublicKey::from_secret_key(&secp_ctx, node_1_privkey);
1571 let node_id_2 = PublicKey::from_secret_key(&secp_ctx, node_2_privkey);
1573 let unsigned_announcement = UnsignedChannelAnnouncement {
1575 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1579 bitcoin_key_1: node_id_1,
1580 bitcoin_key_2: node_id_2,
1581 excess_data: Vec::new(),
1584 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1585 let valid_announcement = ChannelAnnouncement {
1586 node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
1587 node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
1588 bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
1589 bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
1590 contents: unsigned_announcement.clone(),
1592 match net_graph_msg_handler.handle_channel_announcement(&valid_announcement) {
1593 Ok(res) => assert!(res),
1599 net_graph_msg_handler: &NetGraphMsgHandler<Arc<NetworkGraph>, Arc<test_utils::TestChainSource>, Arc<test_utils::TestLogger>>,
1600 secp_ctx: &Secp256k1<All>, node_privkey: &SecretKey, update: UnsignedChannelUpdate
1602 let msghash = hash_to_message!(&Sha256dHash::hash(&update.encode()[..])[..]);
1603 let valid_channel_update = ChannelUpdate {
1604 signature: secp_ctx.sign(&msghash, node_privkey),
1605 contents: update.clone()
1608 match net_graph_msg_handler.handle_channel_update(&valid_channel_update) {
1609 Ok(res) => assert!(res),
1614 fn add_or_update_node(
1615 net_graph_msg_handler: &NetGraphMsgHandler<Arc<NetworkGraph>, Arc<test_utils::TestChainSource>, Arc<test_utils::TestLogger>>,
1616 secp_ctx: &Secp256k1<All>, node_privkey: &SecretKey, features: NodeFeatures, timestamp: u32
1618 let node_id = PublicKey::from_secret_key(&secp_ctx, node_privkey);
1619 let unsigned_announcement = UnsignedNodeAnnouncement {
1625 addresses: Vec::new(),
1626 excess_address_data: Vec::new(),
1627 excess_data: Vec::new(),
1629 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1630 let valid_announcement = NodeAnnouncement {
1631 signature: secp_ctx.sign(&msghash, node_privkey),
1632 contents: unsigned_announcement.clone()
1635 match net_graph_msg_handler.handle_node_announcement(&valid_announcement) {
1641 fn get_nodes(secp_ctx: &Secp256k1<All>) -> (SecretKey, PublicKey, Vec<SecretKey>, Vec<PublicKey>) {
1642 let privkeys: Vec<SecretKey> = (2..10).map(|i| {
1643 SecretKey::from_slice(&hex::decode(format!("{:02}", i).repeat(32)).unwrap()[..]).unwrap()
1646 let pubkeys = privkeys.iter().map(|secret| PublicKey::from_secret_key(&secp_ctx, secret)).collect();
1648 let our_privkey = SecretKey::from_slice(&hex::decode("01".repeat(32)).unwrap()[..]).unwrap();
1649 let our_id = PublicKey::from_secret_key(&secp_ctx, &our_privkey);
1651 (our_privkey, our_id, privkeys, pubkeys)
1654 fn id_to_feature_flags(id: u8) -> Vec<u8> {
1655 // Set the feature flags to the id'th odd (ie non-required) feature bit so that we can
1656 // test for it later.
1657 let idx = (id - 1) * 2 + 1;
1659 vec![1 << (idx - 8*3), 0, 0, 0]
1660 } else if idx > 8*2 {
1661 vec![1 << (idx - 8*2), 0, 0]
1662 } else if idx > 8*1 {
1663 vec![1 << (idx - 8*1), 0]
1669 fn build_graph() -> (
1671 sync::Arc<NetworkGraph>,
1672 NetGraphMsgHandler<sync::Arc<NetworkGraph>, sync::Arc<test_utils::TestChainSource>, sync::Arc<crate::util::test_utils::TestLogger>>,
1673 sync::Arc<test_utils::TestChainSource>,
1674 sync::Arc<test_utils::TestLogger>,
1676 let secp_ctx = Secp256k1::new();
1677 let logger = Arc::new(test_utils::TestLogger::new());
1678 let chain_monitor = Arc::new(test_utils::TestChainSource::new(Network::Testnet));
1679 let network_graph = Arc::new(NetworkGraph::new(genesis_block(Network::Testnet).header.block_hash()));
1680 let net_graph_msg_handler = NetGraphMsgHandler::new(Arc::clone(&network_graph), None, Arc::clone(&logger));
1681 // Build network from our_id to node6:
1683 // -1(1)2- node0 -1(3)2-
1685 // our_id -1(12)2- node7 -1(13)2--- node2
1687 // -1(2)2- node1 -1(4)2-
1690 // chan1 1-to-2: disabled
1691 // chan1 2-to-1: enabled, 0 fee
1693 // chan2 1-to-2: enabled, ignored fee
1694 // chan2 2-to-1: enabled, 0 fee
1696 // chan3 1-to-2: enabled, 0 fee
1697 // chan3 2-to-1: enabled, 100 msat fee
1699 // chan4 1-to-2: enabled, 100% fee
1700 // chan4 2-to-1: enabled, 0 fee
1702 // chan12 1-to-2: enabled, ignored fee
1703 // chan12 2-to-1: enabled, 0 fee
1705 // chan13 1-to-2: enabled, 200% fee
1706 // chan13 2-to-1: enabled, 0 fee
1709 // -1(5)2- node3 -1(8)2--
1713 // node2--1(6)2- node4 -1(9)2--- node6 (not in global route map)
1715 // -1(7)2- node5 -1(10)2-
1717 // Channels 5, 8, 9 and 10 are private channels.
1719 // chan5 1-to-2: enabled, 100 msat fee
1720 // chan5 2-to-1: enabled, 0 fee
1722 // chan6 1-to-2: enabled, 0 fee
1723 // chan6 2-to-1: enabled, 0 fee
1725 // chan7 1-to-2: enabled, 100% fee
1726 // chan7 2-to-1: enabled, 0 fee
1728 // chan8 1-to-2: enabled, variable fee (0 then 1000 msat)
1729 // chan8 2-to-1: enabled, 0 fee
1731 // chan9 1-to-2: enabled, 1001 msat fee
1732 // chan9 2-to-1: enabled, 0 fee
1734 // chan10 1-to-2: enabled, 0 fee
1735 // chan10 2-to-1: enabled, 0 fee
1737 // chan11 1-to-2: enabled, 0 fee
1738 // chan11 2-to-1: enabled, 0 fee
1740 let (our_privkey, _, privkeys, _) = get_nodes(&secp_ctx);
1742 add_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, &privkeys[0], ChannelFeatures::from_le_bytes(id_to_feature_flags(1)), 1);
1743 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
1744 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1745 short_channel_id: 1,
1748 cltv_expiry_delta: 0,
1749 htlc_minimum_msat: 0,
1750 htlc_maximum_msat: OptionalField::Absent,
1752 fee_proportional_millionths: 0,
1753 excess_data: Vec::new()
1756 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[0], NodeFeatures::from_le_bytes(id_to_feature_flags(1)), 0);
1758 add_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, &privkeys[1], ChannelFeatures::from_le_bytes(id_to_feature_flags(2)), 2);
1759 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
1760 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1761 short_channel_id: 2,
1764 cltv_expiry_delta: (5 << 4) | 3,
1765 htlc_minimum_msat: 0,
1766 htlc_maximum_msat: OptionalField::Absent,
1767 fee_base_msat: u32::max_value(),
1768 fee_proportional_millionths: u32::max_value(),
1769 excess_data: Vec::new()
1771 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
1772 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1773 short_channel_id: 2,
1776 cltv_expiry_delta: 0,
1777 htlc_minimum_msat: 0,
1778 htlc_maximum_msat: OptionalField::Absent,
1780 fee_proportional_millionths: 0,
1781 excess_data: Vec::new()
1784 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[1], NodeFeatures::from_le_bytes(id_to_feature_flags(2)), 0);
1786 add_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, &privkeys[7], ChannelFeatures::from_le_bytes(id_to_feature_flags(12)), 12);
1787 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
1788 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1789 short_channel_id: 12,
1792 cltv_expiry_delta: (5 << 4) | 3,
1793 htlc_minimum_msat: 0,
1794 htlc_maximum_msat: OptionalField::Absent,
1795 fee_base_msat: u32::max_value(),
1796 fee_proportional_millionths: u32::max_value(),
1797 excess_data: Vec::new()
1799 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
1800 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1801 short_channel_id: 12,
1804 cltv_expiry_delta: 0,
1805 htlc_minimum_msat: 0,
1806 htlc_maximum_msat: OptionalField::Absent,
1808 fee_proportional_millionths: 0,
1809 excess_data: Vec::new()
1812 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[7], NodeFeatures::from_le_bytes(id_to_feature_flags(8)), 0);
1814 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], &privkeys[2], ChannelFeatures::from_le_bytes(id_to_feature_flags(3)), 3);
1815 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
1816 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1817 short_channel_id: 3,
1820 cltv_expiry_delta: (3 << 4) | 1,
1821 htlc_minimum_msat: 0,
1822 htlc_maximum_msat: OptionalField::Absent,
1824 fee_proportional_millionths: 0,
1825 excess_data: Vec::new()
1827 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
1828 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1829 short_channel_id: 3,
1832 cltv_expiry_delta: (3 << 4) | 2,
1833 htlc_minimum_msat: 0,
1834 htlc_maximum_msat: OptionalField::Absent,
1836 fee_proportional_millionths: 0,
1837 excess_data: Vec::new()
1840 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], &privkeys[2], ChannelFeatures::from_le_bytes(id_to_feature_flags(4)), 4);
1841 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
1842 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1843 short_channel_id: 4,
1846 cltv_expiry_delta: (4 << 4) | 1,
1847 htlc_minimum_msat: 0,
1848 htlc_maximum_msat: OptionalField::Absent,
1850 fee_proportional_millionths: 1000000,
1851 excess_data: Vec::new()
1853 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
1854 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1855 short_channel_id: 4,
1858 cltv_expiry_delta: (4 << 4) | 2,
1859 htlc_minimum_msat: 0,
1860 htlc_maximum_msat: OptionalField::Absent,
1862 fee_proportional_millionths: 0,
1863 excess_data: Vec::new()
1866 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], &privkeys[2], ChannelFeatures::from_le_bytes(id_to_feature_flags(13)), 13);
1867 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
1868 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1869 short_channel_id: 13,
1872 cltv_expiry_delta: (13 << 4) | 1,
1873 htlc_minimum_msat: 0,
1874 htlc_maximum_msat: OptionalField::Absent,
1876 fee_proportional_millionths: 2000000,
1877 excess_data: Vec::new()
1879 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
1880 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1881 short_channel_id: 13,
1884 cltv_expiry_delta: (13 << 4) | 2,
1885 htlc_minimum_msat: 0,
1886 htlc_maximum_msat: OptionalField::Absent,
1888 fee_proportional_millionths: 0,
1889 excess_data: Vec::new()
1892 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[2], NodeFeatures::from_le_bytes(id_to_feature_flags(3)), 0);
1894 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], &privkeys[4], ChannelFeatures::from_le_bytes(id_to_feature_flags(6)), 6);
1895 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
1896 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1897 short_channel_id: 6,
1900 cltv_expiry_delta: (6 << 4) | 1,
1901 htlc_minimum_msat: 0,
1902 htlc_maximum_msat: OptionalField::Absent,
1904 fee_proportional_millionths: 0,
1905 excess_data: Vec::new()
1907 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
1908 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1909 short_channel_id: 6,
1912 cltv_expiry_delta: (6 << 4) | 2,
1913 htlc_minimum_msat: 0,
1914 htlc_maximum_msat: OptionalField::Absent,
1916 fee_proportional_millionths: 0,
1917 excess_data: Vec::new(),
1920 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(11)), 11);
1921 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
1922 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1923 short_channel_id: 11,
1926 cltv_expiry_delta: (11 << 4) | 1,
1927 htlc_minimum_msat: 0,
1928 htlc_maximum_msat: OptionalField::Absent,
1930 fee_proportional_millionths: 0,
1931 excess_data: Vec::new()
1933 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[3], UnsignedChannelUpdate {
1934 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1935 short_channel_id: 11,
1938 cltv_expiry_delta: (11 << 4) | 2,
1939 htlc_minimum_msat: 0,
1940 htlc_maximum_msat: OptionalField::Absent,
1942 fee_proportional_millionths: 0,
1943 excess_data: Vec::new()
1946 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[4], NodeFeatures::from_le_bytes(id_to_feature_flags(5)), 0);
1948 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[3], NodeFeatures::from_le_bytes(id_to_feature_flags(4)), 0);
1950 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], &privkeys[5], ChannelFeatures::from_le_bytes(id_to_feature_flags(7)), 7);
1951 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
1952 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1953 short_channel_id: 7,
1956 cltv_expiry_delta: (7 << 4) | 1,
1957 htlc_minimum_msat: 0,
1958 htlc_maximum_msat: OptionalField::Absent,
1960 fee_proportional_millionths: 1000000,
1961 excess_data: Vec::new()
1963 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[5], UnsignedChannelUpdate {
1964 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1965 short_channel_id: 7,
1968 cltv_expiry_delta: (7 << 4) | 2,
1969 htlc_minimum_msat: 0,
1970 htlc_maximum_msat: OptionalField::Absent,
1972 fee_proportional_millionths: 0,
1973 excess_data: Vec::new()
1976 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[5], NodeFeatures::from_le_bytes(id_to_feature_flags(6)), 0);
1978 (secp_ctx, network_graph, net_graph_msg_handler, chain_monitor, logger)
1982 fn simple_route_test() {
1983 let (secp_ctx, network_graph, _, _, logger) = build_graph();
1984 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
1985 let payee = Payee::from_node_id(nodes[2]);
1986 let scorer = test_utils::TestScorer::with_fixed_penalty(0);
1988 // Simple route to 2 via 1
1990 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id, &payee, &network_graph, None, 0, 42, Arc::clone(&logger), &scorer) {
1991 assert_eq!(err, "Cannot send a payment of 0 msat");
1992 } else { panic!(); }
1994 let route = get_route(&our_id, &payee, &network_graph, None, 100, 42, Arc::clone(&logger), &scorer).unwrap();
1995 assert_eq!(route.paths[0].len(), 2);
1997 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
1998 assert_eq!(route.paths[0][0].short_channel_id, 2);
1999 assert_eq!(route.paths[0][0].fee_msat, 100);
2000 assert_eq!(route.paths[0][0].cltv_expiry_delta, (4 << 4) | 1);
2001 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
2002 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
2004 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2005 assert_eq!(route.paths[0][1].short_channel_id, 4);
2006 assert_eq!(route.paths[0][1].fee_msat, 100);
2007 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
2008 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2009 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
2013 fn invalid_first_hop_test() {
2014 let (secp_ctx, network_graph, _, _, logger) = build_graph();
2015 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
2016 let payee = Payee::from_node_id(nodes[2]);
2017 let scorer = test_utils::TestScorer::with_fixed_penalty(0);
2019 // Simple route to 2 via 1
2021 let our_chans = vec![get_channel_details(Some(2), our_id, InitFeatures::from_le_bytes(vec![0b11]), 100000)];
2023 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id, &payee, &network_graph, Some(&our_chans.iter().collect::<Vec<_>>()), 100, 42, Arc::clone(&logger), &scorer) {
2024 assert_eq!(err, "First hop cannot have our_node_pubkey as a destination.");
2025 } else { panic!(); }
2027 let route = get_route(&our_id, &payee, &network_graph, None, 100, 42, Arc::clone(&logger), &scorer).unwrap();
2028 assert_eq!(route.paths[0].len(), 2);
2032 fn htlc_minimum_test() {
2033 let (secp_ctx, network_graph, net_graph_msg_handler, _, logger) = build_graph();
2034 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
2035 let payee = Payee::from_node_id(nodes[2]);
2036 let scorer = test_utils::TestScorer::with_fixed_penalty(0);
2038 // Simple route to 2 via 1
2040 // Disable other paths
2041 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2042 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2043 short_channel_id: 12,
2045 flags: 2, // to disable
2046 cltv_expiry_delta: 0,
2047 htlc_minimum_msat: 0,
2048 htlc_maximum_msat: OptionalField::Absent,
2050 fee_proportional_millionths: 0,
2051 excess_data: Vec::new()
2053 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
2054 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2055 short_channel_id: 3,
2057 flags: 2, // to disable
2058 cltv_expiry_delta: 0,
2059 htlc_minimum_msat: 0,
2060 htlc_maximum_msat: OptionalField::Absent,
2062 fee_proportional_millionths: 0,
2063 excess_data: Vec::new()
2065 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
2066 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2067 short_channel_id: 13,
2069 flags: 2, // to disable
2070 cltv_expiry_delta: 0,
2071 htlc_minimum_msat: 0,
2072 htlc_maximum_msat: OptionalField::Absent,
2074 fee_proportional_millionths: 0,
2075 excess_data: Vec::new()
2077 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
2078 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2079 short_channel_id: 6,
2081 flags: 2, // to disable
2082 cltv_expiry_delta: 0,
2083 htlc_minimum_msat: 0,
2084 htlc_maximum_msat: OptionalField::Absent,
2086 fee_proportional_millionths: 0,
2087 excess_data: Vec::new()
2089 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
2090 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2091 short_channel_id: 7,
2093 flags: 2, // to disable
2094 cltv_expiry_delta: 0,
2095 htlc_minimum_msat: 0,
2096 htlc_maximum_msat: OptionalField::Absent,
2098 fee_proportional_millionths: 0,
2099 excess_data: Vec::new()
2102 // Check against amount_to_transfer_over_msat.
2103 // Set minimal HTLC of 200_000_000 msat.
2104 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2105 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2106 short_channel_id: 2,
2109 cltv_expiry_delta: 0,
2110 htlc_minimum_msat: 200_000_000,
2111 htlc_maximum_msat: OptionalField::Absent,
2113 fee_proportional_millionths: 0,
2114 excess_data: Vec::new()
2117 // Second hop only allows to forward 199_999_999 at most, thus not allowing the first hop to
2119 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
2120 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2121 short_channel_id: 4,
2124 cltv_expiry_delta: 0,
2125 htlc_minimum_msat: 0,
2126 htlc_maximum_msat: OptionalField::Present(199_999_999),
2128 fee_proportional_millionths: 0,
2129 excess_data: Vec::new()
2132 // Not possible to send 199_999_999, because the minimum on channel=2 is 200_000_000.
2133 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id, &payee, &network_graph, None, 199_999_999, 42, Arc::clone(&logger), &scorer) {
2134 assert_eq!(err, "Failed to find a path to the given destination");
2135 } else { panic!(); }
2137 // Lift the restriction on the first hop.
2138 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2139 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2140 short_channel_id: 2,
2143 cltv_expiry_delta: 0,
2144 htlc_minimum_msat: 0,
2145 htlc_maximum_msat: OptionalField::Absent,
2147 fee_proportional_millionths: 0,
2148 excess_data: Vec::new()
2151 // A payment above the minimum should pass
2152 let route = get_route(&our_id, &payee, &network_graph, None, 199_999_999, 42, Arc::clone(&logger), &scorer).unwrap();
2153 assert_eq!(route.paths[0].len(), 2);
2157 fn htlc_minimum_overpay_test() {
2158 let (secp_ctx, network_graph, net_graph_msg_handler, _, logger) = build_graph();
2159 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
2160 let payee = Payee::from_node_id(nodes[2]).with_features(InvoiceFeatures::known());
2161 let scorer = test_utils::TestScorer::with_fixed_penalty(0);
2163 // A route to node#2 via two paths.
2164 // One path allows transferring 35-40 sats, another one also allows 35-40 sats.
2165 // Thus, they can't send 60 without overpaying.
2166 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2167 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2168 short_channel_id: 2,
2171 cltv_expiry_delta: 0,
2172 htlc_minimum_msat: 35_000,
2173 htlc_maximum_msat: OptionalField::Present(40_000),
2175 fee_proportional_millionths: 0,
2176 excess_data: Vec::new()
2178 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2179 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2180 short_channel_id: 12,
2183 cltv_expiry_delta: 0,
2184 htlc_minimum_msat: 35_000,
2185 htlc_maximum_msat: OptionalField::Present(40_000),
2187 fee_proportional_millionths: 0,
2188 excess_data: Vec::new()
2192 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
2193 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2194 short_channel_id: 13,
2197 cltv_expiry_delta: 0,
2198 htlc_minimum_msat: 0,
2199 htlc_maximum_msat: OptionalField::Absent,
2201 fee_proportional_millionths: 0,
2202 excess_data: Vec::new()
2204 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
2205 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2206 short_channel_id: 4,
2209 cltv_expiry_delta: 0,
2210 htlc_minimum_msat: 0,
2211 htlc_maximum_msat: OptionalField::Absent,
2213 fee_proportional_millionths: 0,
2214 excess_data: Vec::new()
2217 // Disable other paths
2218 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2219 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2220 short_channel_id: 1,
2222 flags: 2, // to disable
2223 cltv_expiry_delta: 0,
2224 htlc_minimum_msat: 0,
2225 htlc_maximum_msat: OptionalField::Absent,
2227 fee_proportional_millionths: 0,
2228 excess_data: Vec::new()
2231 let route = get_route(&our_id, &payee, &network_graph, None, 60_000, 42, Arc::clone(&logger), &scorer).unwrap();
2232 // Overpay fees to hit htlc_minimum_msat.
2233 let overpaid_fees = route.paths[0][0].fee_msat + route.paths[1][0].fee_msat;
2234 // TODO: this could be better balanced to overpay 10k and not 15k.
2235 assert_eq!(overpaid_fees, 15_000);
2237 // Now, test that if there are 2 paths, a "cheaper" by fee path wouldn't be prioritized
2238 // while taking even more fee to match htlc_minimum_msat.
2239 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2240 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2241 short_channel_id: 12,
2244 cltv_expiry_delta: 0,
2245 htlc_minimum_msat: 65_000,
2246 htlc_maximum_msat: OptionalField::Present(80_000),
2248 fee_proportional_millionths: 0,
2249 excess_data: Vec::new()
2251 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2252 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2253 short_channel_id: 2,
2256 cltv_expiry_delta: 0,
2257 htlc_minimum_msat: 0,
2258 htlc_maximum_msat: OptionalField::Absent,
2260 fee_proportional_millionths: 0,
2261 excess_data: Vec::new()
2263 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
2264 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2265 short_channel_id: 4,
2268 cltv_expiry_delta: 0,
2269 htlc_minimum_msat: 0,
2270 htlc_maximum_msat: OptionalField::Absent,
2272 fee_proportional_millionths: 100_000,
2273 excess_data: Vec::new()
2276 let route = get_route(&our_id, &payee, &network_graph, None, 60_000, 42, Arc::clone(&logger), &scorer).unwrap();
2277 // Fine to overpay for htlc_minimum_msat if it allows us to save fee.
2278 assert_eq!(route.paths.len(), 1);
2279 assert_eq!(route.paths[0][0].short_channel_id, 12);
2280 let fees = route.paths[0][0].fee_msat;
2281 assert_eq!(fees, 5_000);
2283 let route = get_route(&our_id, &payee, &network_graph, None, 50_000, 42, Arc::clone(&logger), &scorer).unwrap();
2284 // Not fine to overpay for htlc_minimum_msat if it requires paying more than fee on
2285 // the other channel.
2286 assert_eq!(route.paths.len(), 1);
2287 assert_eq!(route.paths[0][0].short_channel_id, 2);
2288 let fees = route.paths[0][0].fee_msat;
2289 assert_eq!(fees, 5_000);
2293 fn disable_channels_test() {
2294 let (secp_ctx, network_graph, net_graph_msg_handler, _, logger) = build_graph();
2295 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
2296 let payee = Payee::from_node_id(nodes[2]);
2297 let scorer = test_utils::TestScorer::with_fixed_penalty(0);
2299 // // Disable channels 4 and 12 by flags=2
2300 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
2301 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2302 short_channel_id: 4,
2304 flags: 2, // to disable
2305 cltv_expiry_delta: 0,
2306 htlc_minimum_msat: 0,
2307 htlc_maximum_msat: OptionalField::Absent,
2309 fee_proportional_millionths: 0,
2310 excess_data: Vec::new()
2312 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2313 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2314 short_channel_id: 12,
2316 flags: 2, // to disable
2317 cltv_expiry_delta: 0,
2318 htlc_minimum_msat: 0,
2319 htlc_maximum_msat: OptionalField::Absent,
2321 fee_proportional_millionths: 0,
2322 excess_data: Vec::new()
2325 // If all the channels require some features we don't understand, route should fail
2326 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id, &payee, &network_graph, None, 100, 42, Arc::clone(&logger), &scorer) {
2327 assert_eq!(err, "Failed to find a path to the given destination");
2328 } else { panic!(); }
2330 // If we specify a channel to node7, that overrides our local channel view and that gets used
2331 let our_chans = vec![get_channel_details(Some(42), nodes[7].clone(), InitFeatures::from_le_bytes(vec![0b11]), 250_000_000)];
2332 let route = get_route(&our_id, &payee, &network_graph, Some(&our_chans.iter().collect::<Vec<_>>()), 100, 42, Arc::clone(&logger), &scorer).unwrap();
2333 assert_eq!(route.paths[0].len(), 2);
2335 assert_eq!(route.paths[0][0].pubkey, nodes[7]);
2336 assert_eq!(route.paths[0][0].short_channel_id, 42);
2337 assert_eq!(route.paths[0][0].fee_msat, 200);
2338 assert_eq!(route.paths[0][0].cltv_expiry_delta, (13 << 4) | 1);
2339 assert_eq!(route.paths[0][0].node_features.le_flags(), &vec![0b11]); // it should also override our view of their features
2340 assert_eq!(route.paths[0][0].channel_features.le_flags(), &Vec::<u8>::new()); // No feature flags will meet the relevant-to-channel conversion
2342 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2343 assert_eq!(route.paths[0][1].short_channel_id, 13);
2344 assert_eq!(route.paths[0][1].fee_msat, 100);
2345 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
2346 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2347 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(13));
2351 fn disable_node_test() {
2352 let (secp_ctx, network_graph, net_graph_msg_handler, _, logger) = build_graph();
2353 let (_, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
2354 let payee = Payee::from_node_id(nodes[2]);
2355 let scorer = test_utils::TestScorer::with_fixed_penalty(0);
2357 // Disable nodes 1, 2, and 8 by requiring unknown feature bits
2358 let unknown_features = NodeFeatures::known().set_unknown_feature_required();
2359 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[0], unknown_features.clone(), 1);
2360 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[1], unknown_features.clone(), 1);
2361 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[7], unknown_features.clone(), 1);
2363 // If all nodes require some features we don't understand, route should fail
2364 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id, &payee, &network_graph, None, 100, 42, Arc::clone(&logger), &scorer) {
2365 assert_eq!(err, "Failed to find a path to the given destination");
2366 } else { panic!(); }
2368 // If we specify a channel to node7, that overrides our local channel view and that gets used
2369 let our_chans = vec![get_channel_details(Some(42), nodes[7].clone(), InitFeatures::from_le_bytes(vec![0b11]), 250_000_000)];
2370 let route = get_route(&our_id, &payee, &network_graph, Some(&our_chans.iter().collect::<Vec<_>>()), 100, 42, Arc::clone(&logger), &scorer).unwrap();
2371 assert_eq!(route.paths[0].len(), 2);
2373 assert_eq!(route.paths[0][0].pubkey, nodes[7]);
2374 assert_eq!(route.paths[0][0].short_channel_id, 42);
2375 assert_eq!(route.paths[0][0].fee_msat, 200);
2376 assert_eq!(route.paths[0][0].cltv_expiry_delta, (13 << 4) | 1);
2377 assert_eq!(route.paths[0][0].node_features.le_flags(), &vec![0b11]); // it should also override our view of their features
2378 assert_eq!(route.paths[0][0].channel_features.le_flags(), &Vec::<u8>::new()); // No feature flags will meet the relevant-to-channel conversion
2380 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2381 assert_eq!(route.paths[0][1].short_channel_id, 13);
2382 assert_eq!(route.paths[0][1].fee_msat, 100);
2383 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
2384 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2385 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(13));
2387 // Note that we don't test disabling node 3 and failing to route to it, as we (somewhat
2388 // naively) assume that the user checked the feature bits on the invoice, which override
2389 // the node_announcement.
2393 fn our_chans_test() {
2394 let (secp_ctx, network_graph, _, _, logger) = build_graph();
2395 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
2396 let scorer = test_utils::TestScorer::with_fixed_penalty(0);
2398 // Route to 1 via 2 and 3 because our channel to 1 is disabled
2399 let payee = Payee::from_node_id(nodes[0]);
2400 let route = get_route(&our_id, &payee, &network_graph, None, 100, 42, Arc::clone(&logger), &scorer).unwrap();
2401 assert_eq!(route.paths[0].len(), 3);
2403 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
2404 assert_eq!(route.paths[0][0].short_channel_id, 2);
2405 assert_eq!(route.paths[0][0].fee_msat, 200);
2406 assert_eq!(route.paths[0][0].cltv_expiry_delta, (4 << 4) | 1);
2407 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
2408 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
2410 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2411 assert_eq!(route.paths[0][1].short_channel_id, 4);
2412 assert_eq!(route.paths[0][1].fee_msat, 100);
2413 assert_eq!(route.paths[0][1].cltv_expiry_delta, (3 << 4) | 2);
2414 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2415 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
2417 assert_eq!(route.paths[0][2].pubkey, nodes[0]);
2418 assert_eq!(route.paths[0][2].short_channel_id, 3);
2419 assert_eq!(route.paths[0][2].fee_msat, 100);
2420 assert_eq!(route.paths[0][2].cltv_expiry_delta, 42);
2421 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(1));
2422 assert_eq!(route.paths[0][2].channel_features.le_flags(), &id_to_feature_flags(3));
2424 // If we specify a channel to node7, that overrides our local channel view and that gets used
2425 let payee = Payee::from_node_id(nodes[2]);
2426 let our_chans = vec![get_channel_details(Some(42), nodes[7].clone(), InitFeatures::from_le_bytes(vec![0b11]), 250_000_000)];
2427 let route = get_route(&our_id, &payee, &network_graph, Some(&our_chans.iter().collect::<Vec<_>>()), 100, 42, Arc::clone(&logger), &scorer).unwrap();
2428 assert_eq!(route.paths[0].len(), 2);
2430 assert_eq!(route.paths[0][0].pubkey, nodes[7]);
2431 assert_eq!(route.paths[0][0].short_channel_id, 42);
2432 assert_eq!(route.paths[0][0].fee_msat, 200);
2433 assert_eq!(route.paths[0][0].cltv_expiry_delta, (13 << 4) | 1);
2434 assert_eq!(route.paths[0][0].node_features.le_flags(), &vec![0b11]);
2435 assert_eq!(route.paths[0][0].channel_features.le_flags(), &Vec::<u8>::new()); // No feature flags will meet the relevant-to-channel conversion
2437 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2438 assert_eq!(route.paths[0][1].short_channel_id, 13);
2439 assert_eq!(route.paths[0][1].fee_msat, 100);
2440 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
2441 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2442 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(13));
2445 fn last_hops(nodes: &Vec<PublicKey>) -> Vec<RouteHint> {
2446 let zero_fees = RoutingFees {
2448 proportional_millionths: 0,
2450 vec![RouteHint(vec![RouteHintHop {
2451 src_node_id: nodes[3],
2452 short_channel_id: 8,
2454 cltv_expiry_delta: (8 << 4) | 1,
2455 htlc_minimum_msat: None,
2456 htlc_maximum_msat: None,
2458 ]), RouteHint(vec![RouteHintHop {
2459 src_node_id: nodes[4],
2460 short_channel_id: 9,
2463 proportional_millionths: 0,
2465 cltv_expiry_delta: (9 << 4) | 1,
2466 htlc_minimum_msat: None,
2467 htlc_maximum_msat: None,
2468 }]), RouteHint(vec![RouteHintHop {
2469 src_node_id: nodes[5],
2470 short_channel_id: 10,
2472 cltv_expiry_delta: (10 << 4) | 1,
2473 htlc_minimum_msat: None,
2474 htlc_maximum_msat: None,
2478 fn last_hops_multi_private_channels(nodes: &Vec<PublicKey>) -> Vec<RouteHint> {
2479 let zero_fees = RoutingFees {
2481 proportional_millionths: 0,
2483 vec![RouteHint(vec![RouteHintHop {
2484 src_node_id: nodes[2],
2485 short_channel_id: 5,
2488 proportional_millionths: 0,
2490 cltv_expiry_delta: (5 << 4) | 1,
2491 htlc_minimum_msat: None,
2492 htlc_maximum_msat: None,
2494 src_node_id: nodes[3],
2495 short_channel_id: 8,
2497 cltv_expiry_delta: (8 << 4) | 1,
2498 htlc_minimum_msat: None,
2499 htlc_maximum_msat: None,
2501 ]), RouteHint(vec![RouteHintHop {
2502 src_node_id: nodes[4],
2503 short_channel_id: 9,
2506 proportional_millionths: 0,
2508 cltv_expiry_delta: (9 << 4) | 1,
2509 htlc_minimum_msat: None,
2510 htlc_maximum_msat: None,
2511 }]), RouteHint(vec![RouteHintHop {
2512 src_node_id: nodes[5],
2513 short_channel_id: 10,
2515 cltv_expiry_delta: (10 << 4) | 1,
2516 htlc_minimum_msat: None,
2517 htlc_maximum_msat: None,
2522 fn partial_route_hint_test() {
2523 let (secp_ctx, network_graph, _, _, logger) = build_graph();
2524 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
2525 let scorer = test_utils::TestScorer::with_fixed_penalty(0);
2527 // Simple test across 2, 3, 5, and 4 via a last_hop channel
2528 // Tests the behaviour when the RouteHint contains a suboptimal hop.
2529 // RouteHint may be partially used by the algo to build the best path.
2531 // First check that last hop can't have its source as the payee.
2532 let invalid_last_hop = RouteHint(vec![RouteHintHop {
2533 src_node_id: nodes[6],
2534 short_channel_id: 8,
2537 proportional_millionths: 0,
2539 cltv_expiry_delta: (8 << 4) | 1,
2540 htlc_minimum_msat: None,
2541 htlc_maximum_msat: None,
2544 let mut invalid_last_hops = last_hops_multi_private_channels(&nodes);
2545 invalid_last_hops.push(invalid_last_hop);
2547 let payee = Payee::from_node_id(nodes[6]).with_route_hints(invalid_last_hops);
2548 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id, &payee, &network_graph, None, 100, 42, Arc::clone(&logger), &scorer) {
2549 assert_eq!(err, "Route hint cannot have the payee as the source.");
2550 } else { panic!(); }
2553 let payee = Payee::from_node_id(nodes[6]).with_route_hints(last_hops_multi_private_channels(&nodes));
2554 let route = get_route(&our_id, &payee, &network_graph, None, 100, 42, Arc::clone(&logger), &scorer).unwrap();
2555 assert_eq!(route.paths[0].len(), 5);
2557 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
2558 assert_eq!(route.paths[0][0].short_channel_id, 2);
2559 assert_eq!(route.paths[0][0].fee_msat, 100);
2560 assert_eq!(route.paths[0][0].cltv_expiry_delta, (4 << 4) | 1);
2561 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
2562 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
2564 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2565 assert_eq!(route.paths[0][1].short_channel_id, 4);
2566 assert_eq!(route.paths[0][1].fee_msat, 0);
2567 assert_eq!(route.paths[0][1].cltv_expiry_delta, (6 << 4) | 1);
2568 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2569 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
2571 assert_eq!(route.paths[0][2].pubkey, nodes[4]);
2572 assert_eq!(route.paths[0][2].short_channel_id, 6);
2573 assert_eq!(route.paths[0][2].fee_msat, 0);
2574 assert_eq!(route.paths[0][2].cltv_expiry_delta, (11 << 4) | 1);
2575 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(5));
2576 assert_eq!(route.paths[0][2].channel_features.le_flags(), &id_to_feature_flags(6));
2578 assert_eq!(route.paths[0][3].pubkey, nodes[3]);
2579 assert_eq!(route.paths[0][3].short_channel_id, 11);
2580 assert_eq!(route.paths[0][3].fee_msat, 0);
2581 assert_eq!(route.paths[0][3].cltv_expiry_delta, (8 << 4) | 1);
2582 // If we have a peer in the node map, we'll use their features here since we don't have
2583 // a way of figuring out their features from the invoice:
2584 assert_eq!(route.paths[0][3].node_features.le_flags(), &id_to_feature_flags(4));
2585 assert_eq!(route.paths[0][3].channel_features.le_flags(), &id_to_feature_flags(11));
2587 assert_eq!(route.paths[0][4].pubkey, nodes[6]);
2588 assert_eq!(route.paths[0][4].short_channel_id, 8);
2589 assert_eq!(route.paths[0][4].fee_msat, 100);
2590 assert_eq!(route.paths[0][4].cltv_expiry_delta, 42);
2591 assert_eq!(route.paths[0][4].node_features.le_flags(), &Vec::<u8>::new()); // We dont pass flags in from invoices yet
2592 assert_eq!(route.paths[0][4].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
2595 fn empty_last_hop(nodes: &Vec<PublicKey>) -> Vec<RouteHint> {
2596 let zero_fees = RoutingFees {
2598 proportional_millionths: 0,
2600 vec![RouteHint(vec![RouteHintHop {
2601 src_node_id: nodes[3],
2602 short_channel_id: 8,
2604 cltv_expiry_delta: (8 << 4) | 1,
2605 htlc_minimum_msat: None,
2606 htlc_maximum_msat: None,
2607 }]), RouteHint(vec![
2609 ]), RouteHint(vec![RouteHintHop {
2610 src_node_id: nodes[5],
2611 short_channel_id: 10,
2613 cltv_expiry_delta: (10 << 4) | 1,
2614 htlc_minimum_msat: None,
2615 htlc_maximum_msat: None,
2620 fn ignores_empty_last_hops_test() {
2621 let (secp_ctx, network_graph, _, _, logger) = build_graph();
2622 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
2623 let payee = Payee::from_node_id(nodes[6]).with_route_hints(empty_last_hop(&nodes));
2624 let scorer = test_utils::TestScorer::with_fixed_penalty(0);
2626 // Test handling of an empty RouteHint passed in Invoice.
2628 let route = get_route(&our_id, &payee, &network_graph, None, 100, 42, Arc::clone(&logger), &scorer).unwrap();
2629 assert_eq!(route.paths[0].len(), 5);
2631 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
2632 assert_eq!(route.paths[0][0].short_channel_id, 2);
2633 assert_eq!(route.paths[0][0].fee_msat, 100);
2634 assert_eq!(route.paths[0][0].cltv_expiry_delta, (4 << 4) | 1);
2635 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
2636 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
2638 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2639 assert_eq!(route.paths[0][1].short_channel_id, 4);
2640 assert_eq!(route.paths[0][1].fee_msat, 0);
2641 assert_eq!(route.paths[0][1].cltv_expiry_delta, (6 << 4) | 1);
2642 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2643 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
2645 assert_eq!(route.paths[0][2].pubkey, nodes[4]);
2646 assert_eq!(route.paths[0][2].short_channel_id, 6);
2647 assert_eq!(route.paths[0][2].fee_msat, 0);
2648 assert_eq!(route.paths[0][2].cltv_expiry_delta, (11 << 4) | 1);
2649 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(5));
2650 assert_eq!(route.paths[0][2].channel_features.le_flags(), &id_to_feature_flags(6));
2652 assert_eq!(route.paths[0][3].pubkey, nodes[3]);
2653 assert_eq!(route.paths[0][3].short_channel_id, 11);
2654 assert_eq!(route.paths[0][3].fee_msat, 0);
2655 assert_eq!(route.paths[0][3].cltv_expiry_delta, (8 << 4) | 1);
2656 // If we have a peer in the node map, we'll use their features here since we don't have
2657 // a way of figuring out their features from the invoice:
2658 assert_eq!(route.paths[0][3].node_features.le_flags(), &id_to_feature_flags(4));
2659 assert_eq!(route.paths[0][3].channel_features.le_flags(), &id_to_feature_flags(11));
2661 assert_eq!(route.paths[0][4].pubkey, nodes[6]);
2662 assert_eq!(route.paths[0][4].short_channel_id, 8);
2663 assert_eq!(route.paths[0][4].fee_msat, 100);
2664 assert_eq!(route.paths[0][4].cltv_expiry_delta, 42);
2665 assert_eq!(route.paths[0][4].node_features.le_flags(), &Vec::<u8>::new()); // We dont pass flags in from invoices yet
2666 assert_eq!(route.paths[0][4].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
2669 fn multi_hint_last_hops(nodes: &Vec<PublicKey>) -> Vec<RouteHint> {
2670 let zero_fees = RoutingFees {
2672 proportional_millionths: 0,
2674 vec![RouteHint(vec![RouteHintHop {
2675 src_node_id: nodes[2],
2676 short_channel_id: 5,
2679 proportional_millionths: 0,
2681 cltv_expiry_delta: (5 << 4) | 1,
2682 htlc_minimum_msat: None,
2683 htlc_maximum_msat: None,
2685 src_node_id: nodes[3],
2686 short_channel_id: 8,
2688 cltv_expiry_delta: (8 << 4) | 1,
2689 htlc_minimum_msat: None,
2690 htlc_maximum_msat: None,
2691 }]), RouteHint(vec![RouteHintHop {
2692 src_node_id: nodes[5],
2693 short_channel_id: 10,
2695 cltv_expiry_delta: (10 << 4) | 1,
2696 htlc_minimum_msat: None,
2697 htlc_maximum_msat: None,
2702 fn multi_hint_last_hops_test() {
2703 let (secp_ctx, network_graph, net_graph_msg_handler, _, logger) = build_graph();
2704 let (_, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
2705 let payee = Payee::from_node_id(nodes[6]).with_route_hints(multi_hint_last_hops(&nodes));
2706 let scorer = test_utils::TestScorer::with_fixed_penalty(0);
2707 // Test through channels 2, 3, 5, 8.
2708 // Test shows that multiple hop hints are considered.
2710 // Disabling channels 6 & 7 by flags=2
2711 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
2712 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2713 short_channel_id: 6,
2715 flags: 2, // to disable
2716 cltv_expiry_delta: 0,
2717 htlc_minimum_msat: 0,
2718 htlc_maximum_msat: OptionalField::Absent,
2720 fee_proportional_millionths: 0,
2721 excess_data: Vec::new()
2723 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
2724 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2725 short_channel_id: 7,
2727 flags: 2, // to disable
2728 cltv_expiry_delta: 0,
2729 htlc_minimum_msat: 0,
2730 htlc_maximum_msat: OptionalField::Absent,
2732 fee_proportional_millionths: 0,
2733 excess_data: Vec::new()
2736 let route = get_route(&our_id, &payee, &network_graph, None, 100, 42, Arc::clone(&logger), &scorer).unwrap();
2737 assert_eq!(route.paths[0].len(), 4);
2739 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
2740 assert_eq!(route.paths[0][0].short_channel_id, 2);
2741 assert_eq!(route.paths[0][0].fee_msat, 200);
2742 assert_eq!(route.paths[0][0].cltv_expiry_delta, 65);
2743 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
2744 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
2746 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2747 assert_eq!(route.paths[0][1].short_channel_id, 4);
2748 assert_eq!(route.paths[0][1].fee_msat, 100);
2749 assert_eq!(route.paths[0][1].cltv_expiry_delta, 81);
2750 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2751 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
2753 assert_eq!(route.paths[0][2].pubkey, nodes[3]);
2754 assert_eq!(route.paths[0][2].short_channel_id, 5);
2755 assert_eq!(route.paths[0][2].fee_msat, 0);
2756 assert_eq!(route.paths[0][2].cltv_expiry_delta, 129);
2757 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(4));
2758 assert_eq!(route.paths[0][2].channel_features.le_flags(), &Vec::<u8>::new());
2760 assert_eq!(route.paths[0][3].pubkey, nodes[6]);
2761 assert_eq!(route.paths[0][3].short_channel_id, 8);
2762 assert_eq!(route.paths[0][3].fee_msat, 100);
2763 assert_eq!(route.paths[0][3].cltv_expiry_delta, 42);
2764 assert_eq!(route.paths[0][3].node_features.le_flags(), &Vec::<u8>::new()); // We dont pass flags in from invoices yet
2765 assert_eq!(route.paths[0][3].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
2768 fn last_hops_with_public_channel(nodes: &Vec<PublicKey>) -> Vec<RouteHint> {
2769 let zero_fees = RoutingFees {
2771 proportional_millionths: 0,
2773 vec![RouteHint(vec![RouteHintHop {
2774 src_node_id: nodes[4],
2775 short_channel_id: 11,
2777 cltv_expiry_delta: (11 << 4) | 1,
2778 htlc_minimum_msat: None,
2779 htlc_maximum_msat: None,
2781 src_node_id: nodes[3],
2782 short_channel_id: 8,
2784 cltv_expiry_delta: (8 << 4) | 1,
2785 htlc_minimum_msat: None,
2786 htlc_maximum_msat: None,
2787 }]), RouteHint(vec![RouteHintHop {
2788 src_node_id: nodes[4],
2789 short_channel_id: 9,
2792 proportional_millionths: 0,
2794 cltv_expiry_delta: (9 << 4) | 1,
2795 htlc_minimum_msat: None,
2796 htlc_maximum_msat: None,
2797 }]), RouteHint(vec![RouteHintHop {
2798 src_node_id: nodes[5],
2799 short_channel_id: 10,
2801 cltv_expiry_delta: (10 << 4) | 1,
2802 htlc_minimum_msat: None,
2803 htlc_maximum_msat: None,
2808 fn last_hops_with_public_channel_test() {
2809 let (secp_ctx, network_graph, _, _, logger) = build_graph();
2810 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
2811 let payee = Payee::from_node_id(nodes[6]).with_route_hints(last_hops_with_public_channel(&nodes));
2812 let scorer = test_utils::TestScorer::with_fixed_penalty(0);
2813 // This test shows that public routes can be present in the invoice
2814 // which would be handled in the same manner.
2816 let route = get_route(&our_id, &payee, &network_graph, None, 100, 42, Arc::clone(&logger), &scorer).unwrap();
2817 assert_eq!(route.paths[0].len(), 5);
2819 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
2820 assert_eq!(route.paths[0][0].short_channel_id, 2);
2821 assert_eq!(route.paths[0][0].fee_msat, 100);
2822 assert_eq!(route.paths[0][0].cltv_expiry_delta, (4 << 4) | 1);
2823 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
2824 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
2826 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2827 assert_eq!(route.paths[0][1].short_channel_id, 4);
2828 assert_eq!(route.paths[0][1].fee_msat, 0);
2829 assert_eq!(route.paths[0][1].cltv_expiry_delta, (6 << 4) | 1);
2830 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2831 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
2833 assert_eq!(route.paths[0][2].pubkey, nodes[4]);
2834 assert_eq!(route.paths[0][2].short_channel_id, 6);
2835 assert_eq!(route.paths[0][2].fee_msat, 0);
2836 assert_eq!(route.paths[0][2].cltv_expiry_delta, (11 << 4) | 1);
2837 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(5));
2838 assert_eq!(route.paths[0][2].channel_features.le_flags(), &id_to_feature_flags(6));
2840 assert_eq!(route.paths[0][3].pubkey, nodes[3]);
2841 assert_eq!(route.paths[0][3].short_channel_id, 11);
2842 assert_eq!(route.paths[0][3].fee_msat, 0);
2843 assert_eq!(route.paths[0][3].cltv_expiry_delta, (8 << 4) | 1);
2844 // If we have a peer in the node map, we'll use their features here since we don't have
2845 // a way of figuring out their features from the invoice:
2846 assert_eq!(route.paths[0][3].node_features.le_flags(), &id_to_feature_flags(4));
2847 assert_eq!(route.paths[0][3].channel_features.le_flags(), &Vec::<u8>::new());
2849 assert_eq!(route.paths[0][4].pubkey, nodes[6]);
2850 assert_eq!(route.paths[0][4].short_channel_id, 8);
2851 assert_eq!(route.paths[0][4].fee_msat, 100);
2852 assert_eq!(route.paths[0][4].cltv_expiry_delta, 42);
2853 assert_eq!(route.paths[0][4].node_features.le_flags(), &Vec::<u8>::new()); // We dont pass flags in from invoices yet
2854 assert_eq!(route.paths[0][4].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
2858 fn our_chans_last_hop_connect_test() {
2859 let (secp_ctx, network_graph, _, _, logger) = build_graph();
2860 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
2861 let scorer = test_utils::TestScorer::with_fixed_penalty(0);
2863 // Simple test with outbound channel to 4 to test that last_hops and first_hops connect
2864 let our_chans = vec![get_channel_details(Some(42), nodes[3].clone(), InitFeatures::from_le_bytes(vec![0b11]), 250_000_000)];
2865 let mut last_hops = last_hops(&nodes);
2866 let payee = Payee::from_node_id(nodes[6]).with_route_hints(last_hops.clone());
2867 let route = get_route(&our_id, &payee, &network_graph, Some(&our_chans.iter().collect::<Vec<_>>()), 100, 42, Arc::clone(&logger), &scorer).unwrap();
2868 assert_eq!(route.paths[0].len(), 2);
2870 assert_eq!(route.paths[0][0].pubkey, nodes[3]);
2871 assert_eq!(route.paths[0][0].short_channel_id, 42);
2872 assert_eq!(route.paths[0][0].fee_msat, 0);
2873 assert_eq!(route.paths[0][0].cltv_expiry_delta, (8 << 4) | 1);
2874 assert_eq!(route.paths[0][0].node_features.le_flags(), &vec![0b11]);
2875 assert_eq!(route.paths[0][0].channel_features.le_flags(), &Vec::<u8>::new()); // No feature flags will meet the relevant-to-channel conversion
2877 assert_eq!(route.paths[0][1].pubkey, nodes[6]);
2878 assert_eq!(route.paths[0][1].short_channel_id, 8);
2879 assert_eq!(route.paths[0][1].fee_msat, 100);
2880 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
2881 assert_eq!(route.paths[0][1].node_features.le_flags(), &Vec::<u8>::new()); // We dont pass flags in from invoices yet
2882 assert_eq!(route.paths[0][1].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
2884 last_hops[0].0[0].fees.base_msat = 1000;
2886 // Revert to via 6 as the fee on 8 goes up
2887 let payee = Payee::from_node_id(nodes[6]).with_route_hints(last_hops);
2888 let route = get_route(&our_id, &payee, &network_graph, None, 100, 42, Arc::clone(&logger), &scorer).unwrap();
2889 assert_eq!(route.paths[0].len(), 4);
2891 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
2892 assert_eq!(route.paths[0][0].short_channel_id, 2);
2893 assert_eq!(route.paths[0][0].fee_msat, 200); // fee increased as its % of value transferred across node
2894 assert_eq!(route.paths[0][0].cltv_expiry_delta, (4 << 4) | 1);
2895 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
2896 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
2898 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2899 assert_eq!(route.paths[0][1].short_channel_id, 4);
2900 assert_eq!(route.paths[0][1].fee_msat, 100);
2901 assert_eq!(route.paths[0][1].cltv_expiry_delta, (7 << 4) | 1);
2902 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2903 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
2905 assert_eq!(route.paths[0][2].pubkey, nodes[5]);
2906 assert_eq!(route.paths[0][2].short_channel_id, 7);
2907 assert_eq!(route.paths[0][2].fee_msat, 0);
2908 assert_eq!(route.paths[0][2].cltv_expiry_delta, (10 << 4) | 1);
2909 // If we have a peer in the node map, we'll use their features here since we don't have
2910 // a way of figuring out their features from the invoice:
2911 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(6));
2912 assert_eq!(route.paths[0][2].channel_features.le_flags(), &id_to_feature_flags(7));
2914 assert_eq!(route.paths[0][3].pubkey, nodes[6]);
2915 assert_eq!(route.paths[0][3].short_channel_id, 10);
2916 assert_eq!(route.paths[0][3].fee_msat, 100);
2917 assert_eq!(route.paths[0][3].cltv_expiry_delta, 42);
2918 assert_eq!(route.paths[0][3].node_features.le_flags(), &Vec::<u8>::new()); // We dont pass flags in from invoices yet
2919 assert_eq!(route.paths[0][3].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
2921 // ...but still use 8 for larger payments as 6 has a variable feerate
2922 let route = get_route(&our_id, &payee, &network_graph, None, 2000, 42, Arc::clone(&logger), &scorer).unwrap();
2923 assert_eq!(route.paths[0].len(), 5);
2925 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
2926 assert_eq!(route.paths[0][0].short_channel_id, 2);
2927 assert_eq!(route.paths[0][0].fee_msat, 3000);
2928 assert_eq!(route.paths[0][0].cltv_expiry_delta, (4 << 4) | 1);
2929 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
2930 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
2932 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2933 assert_eq!(route.paths[0][1].short_channel_id, 4);
2934 assert_eq!(route.paths[0][1].fee_msat, 0);
2935 assert_eq!(route.paths[0][1].cltv_expiry_delta, (6 << 4) | 1);
2936 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2937 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
2939 assert_eq!(route.paths[0][2].pubkey, nodes[4]);
2940 assert_eq!(route.paths[0][2].short_channel_id, 6);
2941 assert_eq!(route.paths[0][2].fee_msat, 0);
2942 assert_eq!(route.paths[0][2].cltv_expiry_delta, (11 << 4) | 1);
2943 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(5));
2944 assert_eq!(route.paths[0][2].channel_features.le_flags(), &id_to_feature_flags(6));
2946 assert_eq!(route.paths[0][3].pubkey, nodes[3]);
2947 assert_eq!(route.paths[0][3].short_channel_id, 11);
2948 assert_eq!(route.paths[0][3].fee_msat, 1000);
2949 assert_eq!(route.paths[0][3].cltv_expiry_delta, (8 << 4) | 1);
2950 // If we have a peer in the node map, we'll use their features here since we don't have
2951 // a way of figuring out their features from the invoice:
2952 assert_eq!(route.paths[0][3].node_features.le_flags(), &id_to_feature_flags(4));
2953 assert_eq!(route.paths[0][3].channel_features.le_flags(), &id_to_feature_flags(11));
2955 assert_eq!(route.paths[0][4].pubkey, nodes[6]);
2956 assert_eq!(route.paths[0][4].short_channel_id, 8);
2957 assert_eq!(route.paths[0][4].fee_msat, 2000);
2958 assert_eq!(route.paths[0][4].cltv_expiry_delta, 42);
2959 assert_eq!(route.paths[0][4].node_features.le_flags(), &Vec::<u8>::new()); // We dont pass flags in from invoices yet
2960 assert_eq!(route.paths[0][4].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
2963 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> {
2964 let source_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&hex::decode(format!("{:02}", 41).repeat(32)).unwrap()[..]).unwrap());
2965 let middle_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&hex::decode(format!("{:02}", 42).repeat(32)).unwrap()[..]).unwrap());
2966 let target_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&hex::decode(format!("{:02}", 43).repeat(32)).unwrap()[..]).unwrap());
2968 // If we specify a channel to a middle hop, that overrides our local channel view and that gets used
2969 let last_hops = RouteHint(vec![RouteHintHop {
2970 src_node_id: middle_node_id,
2971 short_channel_id: 8,
2974 proportional_millionths: last_hop_fee_prop,
2976 cltv_expiry_delta: (8 << 4) | 1,
2977 htlc_minimum_msat: None,
2978 htlc_maximum_msat: last_hop_htlc_max,
2980 let payee = Payee::from_node_id(target_node_id).with_route_hints(vec![last_hops]);
2981 let our_chans = vec![get_channel_details(Some(42), middle_node_id, InitFeatures::from_le_bytes(vec![0b11]), outbound_capacity_msat)];
2982 let scorer = test_utils::TestScorer::with_fixed_penalty(0);
2983 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)
2987 fn unannounced_path_test() {
2988 // We should be able to send a payment to a destination without any help of a routing graph
2989 // if we have a channel with a common counterparty that appears in the first and last hop
2991 let route = do_unannounced_path_test(None, 1, 2000000, 1000000).unwrap();
2993 let middle_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&hex::decode(format!("{:02}", 42).repeat(32)).unwrap()[..]).unwrap());
2994 let target_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&hex::decode(format!("{:02}", 43).repeat(32)).unwrap()[..]).unwrap());
2995 assert_eq!(route.paths[0].len(), 2);
2997 assert_eq!(route.paths[0][0].pubkey, middle_node_id);
2998 assert_eq!(route.paths[0][0].short_channel_id, 42);
2999 assert_eq!(route.paths[0][0].fee_msat, 1001);
3000 assert_eq!(route.paths[0][0].cltv_expiry_delta, (8 << 4) | 1);
3001 assert_eq!(route.paths[0][0].node_features.le_flags(), &[0b11]);
3002 assert_eq!(route.paths[0][0].channel_features.le_flags(), &[0; 0]); // We can't learn any flags from invoices, sadly
3004 assert_eq!(route.paths[0][1].pubkey, target_node_id);
3005 assert_eq!(route.paths[0][1].short_channel_id, 8);
3006 assert_eq!(route.paths[0][1].fee_msat, 1000000);
3007 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
3008 assert_eq!(route.paths[0][1].node_features.le_flags(), &[0; 0]); // We dont pass flags in from invoices yet
3009 assert_eq!(route.paths[0][1].channel_features.le_flags(), &[0; 0]); // We can't learn any flags from invoices, sadly
3013 fn overflow_unannounced_path_test_liquidity_underflow() {
3014 // Previously, when we had a last-hop hint connected directly to a first-hop channel, where
3015 // the last-hop had a fee which overflowed a u64, we'd panic.
3016 // This was due to us adding the first-hop from us unconditionally, causing us to think
3017 // we'd built a path (as our node is in the "best candidate" set), when we had not.
3018 // In this test, we previously hit a subtraction underflow due to having less available
3019 // liquidity at the last hop than 0.
3020 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());
3024 fn overflow_unannounced_path_test_feerate_overflow() {
3025 // This tests for the same case as above, except instead of hitting a subtraction
3026 // underflow, we hit a case where the fee charged at a hop overflowed.
3027 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());
3031 fn available_amount_while_routing_test() {
3032 // Tests whether we choose the correct available channel amount while routing.
3034 let (secp_ctx, network_graph, mut net_graph_msg_handler, chain_monitor, logger) = build_graph();
3035 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3036 let scorer = test_utils::TestScorer::with_fixed_penalty(0);
3037 let payee = Payee::from_node_id(nodes[2]).with_features(InvoiceFeatures::known());
3039 // We will use a simple single-path route from
3040 // our node to node2 via node0: channels {1, 3}.
3042 // First disable all other paths.
3043 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3044 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3045 short_channel_id: 2,
3048 cltv_expiry_delta: 0,
3049 htlc_minimum_msat: 0,
3050 htlc_maximum_msat: OptionalField::Present(100_000),
3052 fee_proportional_millionths: 0,
3053 excess_data: Vec::new()
3055 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3056 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3057 short_channel_id: 12,
3060 cltv_expiry_delta: 0,
3061 htlc_minimum_msat: 0,
3062 htlc_maximum_msat: OptionalField::Present(100_000),
3064 fee_proportional_millionths: 0,
3065 excess_data: Vec::new()
3068 // Make the first channel (#1) very permissive,
3069 // and we will be testing all limits on the second channel.
3070 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3071 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3072 short_channel_id: 1,
3075 cltv_expiry_delta: 0,
3076 htlc_minimum_msat: 0,
3077 htlc_maximum_msat: OptionalField::Present(1_000_000_000),
3079 fee_proportional_millionths: 0,
3080 excess_data: Vec::new()
3083 // First, let's see if routing works if we have absolutely no idea about the available amount.
3084 // In this case, it should be set to 250_000 sats.
3085 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3086 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3087 short_channel_id: 3,
3090 cltv_expiry_delta: 0,
3091 htlc_minimum_msat: 0,
3092 htlc_maximum_msat: OptionalField::Absent,
3094 fee_proportional_millionths: 0,
3095 excess_data: Vec::new()
3099 // Attempt to route more than available results in a failure.
3100 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
3101 &our_id, &payee, &network_graph, None, 250_000_001, 42, Arc::clone(&logger), &scorer) {
3102 assert_eq!(err, "Failed to find a sufficient route to the given destination");
3103 } else { panic!(); }
3107 // Now, attempt to route an exact amount we have should be fine.
3108 let route = get_route(&our_id, &payee, &network_graph, None, 250_000_000, 42, Arc::clone(&logger), &scorer).unwrap();
3109 assert_eq!(route.paths.len(), 1);
3110 let path = route.paths.last().unwrap();
3111 assert_eq!(path.len(), 2);
3112 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
3113 assert_eq!(path.last().unwrap().fee_msat, 250_000_000);
3116 // Check that setting outbound_capacity_msat in first_hops limits the channels.
3117 // Disable channel #1 and use another first hop.
3118 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3119 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3120 short_channel_id: 1,
3123 cltv_expiry_delta: 0,
3124 htlc_minimum_msat: 0,
3125 htlc_maximum_msat: OptionalField::Present(1_000_000_000),
3127 fee_proportional_millionths: 0,
3128 excess_data: Vec::new()
3131 // Now, limit the first_hop by the outbound_capacity_msat of 200_000 sats.
3132 let our_chans = vec![get_channel_details(Some(42), nodes[0].clone(), InitFeatures::from_le_bytes(vec![0b11]), 200_000_000)];
3135 // Attempt to route more than available results in a failure.
3136 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
3137 &our_id, &payee, &network_graph, Some(&our_chans.iter().collect::<Vec<_>>()), 200_000_001, 42, Arc::clone(&logger), &scorer) {
3138 assert_eq!(err, "Failed to find a sufficient route to the given destination");
3139 } else { panic!(); }
3143 // Now, attempt to route an exact amount we have should be fine.
3144 let route = get_route(&our_id, &payee, &network_graph, Some(&our_chans.iter().collect::<Vec<_>>()), 200_000_000, 42, Arc::clone(&logger), &scorer).unwrap();
3145 assert_eq!(route.paths.len(), 1);
3146 let path = route.paths.last().unwrap();
3147 assert_eq!(path.len(), 2);
3148 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
3149 assert_eq!(path.last().unwrap().fee_msat, 200_000_000);
3152 // Enable channel #1 back.
3153 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3154 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3155 short_channel_id: 1,
3158 cltv_expiry_delta: 0,
3159 htlc_minimum_msat: 0,
3160 htlc_maximum_msat: OptionalField::Present(1_000_000_000),
3162 fee_proportional_millionths: 0,
3163 excess_data: Vec::new()
3167 // Now let's see if routing works if we know only htlc_maximum_msat.
3168 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3169 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3170 short_channel_id: 3,
3173 cltv_expiry_delta: 0,
3174 htlc_minimum_msat: 0,
3175 htlc_maximum_msat: OptionalField::Present(15_000),
3177 fee_proportional_millionths: 0,
3178 excess_data: Vec::new()
3182 // Attempt to route more than available results in a failure.
3183 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
3184 &our_id, &payee, &network_graph, None, 15_001, 42, Arc::clone(&logger), &scorer) {
3185 assert_eq!(err, "Failed to find a sufficient route to the given destination");
3186 } else { panic!(); }
3190 // Now, attempt to route an exact amount we have should be fine.
3191 let route = get_route(&our_id, &payee, &network_graph, None, 15_000, 42, Arc::clone(&logger), &scorer).unwrap();
3192 assert_eq!(route.paths.len(), 1);
3193 let path = route.paths.last().unwrap();
3194 assert_eq!(path.len(), 2);
3195 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
3196 assert_eq!(path.last().unwrap().fee_msat, 15_000);
3199 // Now let's see if routing works if we know only capacity from the UTXO.
3201 // We can't change UTXO capacity on the fly, so we'll disable
3202 // the existing channel and add another one with the capacity we need.
3203 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3204 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3205 short_channel_id: 3,
3208 cltv_expiry_delta: 0,
3209 htlc_minimum_msat: 0,
3210 htlc_maximum_msat: OptionalField::Absent,
3212 fee_proportional_millionths: 0,
3213 excess_data: Vec::new()
3216 let good_script = Builder::new().push_opcode(opcodes::all::OP_PUSHNUM_2)
3217 .push_slice(&PublicKey::from_secret_key(&secp_ctx, &privkeys[0]).serialize())
3218 .push_slice(&PublicKey::from_secret_key(&secp_ctx, &privkeys[2]).serialize())
3219 .push_opcode(opcodes::all::OP_PUSHNUM_2)
3220 .push_opcode(opcodes::all::OP_CHECKMULTISIG).into_script().to_v0_p2wsh();
3222 *chain_monitor.utxo_ret.lock().unwrap() = Ok(TxOut { value: 15, script_pubkey: good_script.clone() });
3223 net_graph_msg_handler.add_chain_access(Some(chain_monitor));
3225 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], &privkeys[2], ChannelFeatures::from_le_bytes(id_to_feature_flags(3)), 333);
3226 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3227 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3228 short_channel_id: 333,
3231 cltv_expiry_delta: (3 << 4) | 1,
3232 htlc_minimum_msat: 0,
3233 htlc_maximum_msat: OptionalField::Absent,
3235 fee_proportional_millionths: 0,
3236 excess_data: Vec::new()
3238 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3239 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3240 short_channel_id: 333,
3243 cltv_expiry_delta: (3 << 4) | 2,
3244 htlc_minimum_msat: 0,
3245 htlc_maximum_msat: OptionalField::Absent,
3247 fee_proportional_millionths: 0,
3248 excess_data: Vec::new()
3252 // Attempt to route more than available results in a failure.
3253 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
3254 &our_id, &payee, &network_graph, None, 15_001, 42, Arc::clone(&logger), &scorer) {
3255 assert_eq!(err, "Failed to find a sufficient route to the given destination");
3256 } else { panic!(); }
3260 // Now, attempt to route an exact amount we have should be fine.
3261 let route = get_route(&our_id, &payee, &network_graph, None, 15_000, 42, Arc::clone(&logger), &scorer).unwrap();
3262 assert_eq!(route.paths.len(), 1);
3263 let path = route.paths.last().unwrap();
3264 assert_eq!(path.len(), 2);
3265 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
3266 assert_eq!(path.last().unwrap().fee_msat, 15_000);
3269 // Now let's see if routing chooses htlc_maximum_msat over UTXO capacity.
3270 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3271 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3272 short_channel_id: 333,
3275 cltv_expiry_delta: 0,
3276 htlc_minimum_msat: 0,
3277 htlc_maximum_msat: OptionalField::Present(10_000),
3279 fee_proportional_millionths: 0,
3280 excess_data: Vec::new()
3284 // Attempt to route more than available results in a failure.
3285 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
3286 &our_id, &payee, &network_graph, None, 10_001, 42, Arc::clone(&logger), &scorer) {
3287 assert_eq!(err, "Failed to find a sufficient route to the given destination");
3288 } else { panic!(); }
3292 // Now, attempt to route an exact amount we have should be fine.
3293 let route = get_route(&our_id, &payee, &network_graph, None, 10_000, 42, Arc::clone(&logger), &scorer).unwrap();
3294 assert_eq!(route.paths.len(), 1);
3295 let path = route.paths.last().unwrap();
3296 assert_eq!(path.len(), 2);
3297 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
3298 assert_eq!(path.last().unwrap().fee_msat, 10_000);
3303 fn available_liquidity_last_hop_test() {
3304 // Check that available liquidity properly limits the path even when only
3305 // one of the latter hops is limited.
3306 let (secp_ctx, network_graph, net_graph_msg_handler, _, logger) = build_graph();
3307 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3308 let scorer = test_utils::TestScorer::with_fixed_penalty(0);
3309 let payee = Payee::from_node_id(nodes[3]).with_features(InvoiceFeatures::known());
3311 // Path via {node7, node2, node4} is channels {12, 13, 6, 11}.
3312 // {12, 13, 11} have the capacities of 100, {6} has a capacity of 50.
3313 // Total capacity: 50 sats.
3315 // Disable other potential paths.
3316 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3317 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3318 short_channel_id: 2,
3321 cltv_expiry_delta: 0,
3322 htlc_minimum_msat: 0,
3323 htlc_maximum_msat: OptionalField::Present(100_000),
3325 fee_proportional_millionths: 0,
3326 excess_data: Vec::new()
3328 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3329 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3330 short_channel_id: 7,
3333 cltv_expiry_delta: 0,
3334 htlc_minimum_msat: 0,
3335 htlc_maximum_msat: OptionalField::Present(100_000),
3337 fee_proportional_millionths: 0,
3338 excess_data: Vec::new()
3343 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3344 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3345 short_channel_id: 12,
3348 cltv_expiry_delta: 0,
3349 htlc_minimum_msat: 0,
3350 htlc_maximum_msat: OptionalField::Present(100_000),
3352 fee_proportional_millionths: 0,
3353 excess_data: Vec::new()
3355 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
3356 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3357 short_channel_id: 13,
3360 cltv_expiry_delta: 0,
3361 htlc_minimum_msat: 0,
3362 htlc_maximum_msat: OptionalField::Present(100_000),
3364 fee_proportional_millionths: 0,
3365 excess_data: Vec::new()
3368 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3369 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3370 short_channel_id: 6,
3373 cltv_expiry_delta: 0,
3374 htlc_minimum_msat: 0,
3375 htlc_maximum_msat: OptionalField::Present(50_000),
3377 fee_proportional_millionths: 0,
3378 excess_data: Vec::new()
3380 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
3381 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3382 short_channel_id: 11,
3385 cltv_expiry_delta: 0,
3386 htlc_minimum_msat: 0,
3387 htlc_maximum_msat: OptionalField::Present(100_000),
3389 fee_proportional_millionths: 0,
3390 excess_data: Vec::new()
3393 // Attempt to route more than available results in a failure.
3394 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
3395 &our_id, &payee, &network_graph, None, 60_000, 42, Arc::clone(&logger), &scorer) {
3396 assert_eq!(err, "Failed to find a sufficient route to the given destination");
3397 } else { panic!(); }
3401 // Now, attempt to route 49 sats (just a bit below the capacity).
3402 let route = get_route(&our_id, &payee, &network_graph, None, 49_000, 42, Arc::clone(&logger), &scorer).unwrap();
3403 assert_eq!(route.paths.len(), 1);
3404 let mut total_amount_paid_msat = 0;
3405 for path in &route.paths {
3406 assert_eq!(path.len(), 4);
3407 assert_eq!(path.last().unwrap().pubkey, nodes[3]);
3408 total_amount_paid_msat += path.last().unwrap().fee_msat;
3410 assert_eq!(total_amount_paid_msat, 49_000);
3414 // Attempt to route an exact amount is also fine
3415 let route = get_route(&our_id, &payee, &network_graph, None, 50_000, 42, Arc::clone(&logger), &scorer).unwrap();
3416 assert_eq!(route.paths.len(), 1);
3417 let mut total_amount_paid_msat = 0;
3418 for path in &route.paths {
3419 assert_eq!(path.len(), 4);
3420 assert_eq!(path.last().unwrap().pubkey, nodes[3]);
3421 total_amount_paid_msat += path.last().unwrap().fee_msat;
3423 assert_eq!(total_amount_paid_msat, 50_000);
3428 fn ignore_fee_first_hop_test() {
3429 let (secp_ctx, network_graph, net_graph_msg_handler, _, logger) = build_graph();
3430 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3431 let scorer = test_utils::TestScorer::with_fixed_penalty(0);
3432 let payee = Payee::from_node_id(nodes[2]);
3434 // Path via node0 is channels {1, 3}. Limit them to 100 and 50 sats (total limit 50).
3435 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3436 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3437 short_channel_id: 1,
3440 cltv_expiry_delta: 0,
3441 htlc_minimum_msat: 0,
3442 htlc_maximum_msat: OptionalField::Present(100_000),
3443 fee_base_msat: 1_000_000,
3444 fee_proportional_millionths: 0,
3445 excess_data: Vec::new()
3447 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3448 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3449 short_channel_id: 3,
3452 cltv_expiry_delta: 0,
3453 htlc_minimum_msat: 0,
3454 htlc_maximum_msat: OptionalField::Present(50_000),
3456 fee_proportional_millionths: 0,
3457 excess_data: Vec::new()
3461 let route = get_route(&our_id, &payee, &network_graph, None, 50_000, 42, Arc::clone(&logger), &scorer).unwrap();
3462 assert_eq!(route.paths.len(), 1);
3463 let mut total_amount_paid_msat = 0;
3464 for path in &route.paths {
3465 assert_eq!(path.len(), 2);
3466 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
3467 total_amount_paid_msat += path.last().unwrap().fee_msat;
3469 assert_eq!(total_amount_paid_msat, 50_000);
3474 fn simple_mpp_route_test() {
3475 let (secp_ctx, network_graph, net_graph_msg_handler, _, logger) = build_graph();
3476 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3477 let scorer = test_utils::TestScorer::with_fixed_penalty(0);
3478 let payee = Payee::from_node_id(nodes[2]).with_features(InvoiceFeatures::known());
3480 // We need a route consisting of 3 paths:
3481 // From our node to node2 via node0, node7, node1 (three paths one hop each).
3482 // To achieve this, the amount being transferred should be around
3483 // the total capacity of these 3 paths.
3485 // First, we set limits on these (previously unlimited) channels.
3486 // Their aggregate capacity will be 50 + 60 + 180 = 290 sats.
3488 // Path via node0 is channels {1, 3}. Limit them to 100 and 50 sats (total limit 50).
3489 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3490 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3491 short_channel_id: 1,
3494 cltv_expiry_delta: 0,
3495 htlc_minimum_msat: 0,
3496 htlc_maximum_msat: OptionalField::Present(100_000),
3498 fee_proportional_millionths: 0,
3499 excess_data: Vec::new()
3501 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3502 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3503 short_channel_id: 3,
3506 cltv_expiry_delta: 0,
3507 htlc_minimum_msat: 0,
3508 htlc_maximum_msat: OptionalField::Present(50_000),
3510 fee_proportional_millionths: 0,
3511 excess_data: Vec::new()
3514 // Path via node7 is channels {12, 13}. Limit them to 60 and 60 sats
3515 // (total limit 60).
3516 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3517 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3518 short_channel_id: 12,
3521 cltv_expiry_delta: 0,
3522 htlc_minimum_msat: 0,
3523 htlc_maximum_msat: OptionalField::Present(60_000),
3525 fee_proportional_millionths: 0,
3526 excess_data: Vec::new()
3528 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
3529 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3530 short_channel_id: 13,
3533 cltv_expiry_delta: 0,
3534 htlc_minimum_msat: 0,
3535 htlc_maximum_msat: OptionalField::Present(60_000),
3537 fee_proportional_millionths: 0,
3538 excess_data: Vec::new()
3541 // Path via node1 is channels {2, 4}. Limit them to 200 and 180 sats
3542 // (total capacity 180 sats).
3543 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3544 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3545 short_channel_id: 2,
3548 cltv_expiry_delta: 0,
3549 htlc_minimum_msat: 0,
3550 htlc_maximum_msat: OptionalField::Present(200_000),
3552 fee_proportional_millionths: 0,
3553 excess_data: Vec::new()
3555 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
3556 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3557 short_channel_id: 4,
3560 cltv_expiry_delta: 0,
3561 htlc_minimum_msat: 0,
3562 htlc_maximum_msat: OptionalField::Present(180_000),
3564 fee_proportional_millionths: 0,
3565 excess_data: Vec::new()
3569 // Attempt to route more than available results in a failure.
3570 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
3571 &our_id, &payee, &network_graph, None, 300_000, 42, Arc::clone(&logger), &scorer) {
3572 assert_eq!(err, "Failed to find a sufficient route to the given destination");
3573 } else { panic!(); }
3577 // Now, attempt to route 250 sats (just a bit below the capacity).
3578 // Our algorithm should provide us with these 3 paths.
3579 let route = get_route(&our_id, &payee, &network_graph, None, 250_000, 42, Arc::clone(&logger), &scorer).unwrap();
3580 assert_eq!(route.paths.len(), 3);
3581 let mut total_amount_paid_msat = 0;
3582 for path in &route.paths {
3583 assert_eq!(path.len(), 2);
3584 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
3585 total_amount_paid_msat += path.last().unwrap().fee_msat;
3587 assert_eq!(total_amount_paid_msat, 250_000);
3591 // Attempt to route an exact amount is also fine
3592 let route = get_route(&our_id, &payee, &network_graph, None, 290_000, 42, Arc::clone(&logger), &scorer).unwrap();
3593 assert_eq!(route.paths.len(), 3);
3594 let mut total_amount_paid_msat = 0;
3595 for path in &route.paths {
3596 assert_eq!(path.len(), 2);
3597 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
3598 total_amount_paid_msat += path.last().unwrap().fee_msat;
3600 assert_eq!(total_amount_paid_msat, 290_000);
3605 fn long_mpp_route_test() {
3606 let (secp_ctx, network_graph, net_graph_msg_handler, _, logger) = build_graph();
3607 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3608 let scorer = test_utils::TestScorer::with_fixed_penalty(0);
3609 let payee = Payee::from_node_id(nodes[3]).with_features(InvoiceFeatures::known());
3611 // We need a route consisting of 3 paths:
3612 // From our node to node3 via {node0, node2}, {node7, node2, node4} and {node7, node2}.
3613 // Note that these paths overlap (channels 5, 12, 13).
3614 // We will route 300 sats.
3615 // Each path will have 100 sats capacity, those channels which
3616 // are used twice will have 200 sats capacity.
3618 // Disable other potential paths.
3619 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3620 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3621 short_channel_id: 2,
3624 cltv_expiry_delta: 0,
3625 htlc_minimum_msat: 0,
3626 htlc_maximum_msat: OptionalField::Present(100_000),
3628 fee_proportional_millionths: 0,
3629 excess_data: Vec::new()
3631 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3632 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3633 short_channel_id: 7,
3636 cltv_expiry_delta: 0,
3637 htlc_minimum_msat: 0,
3638 htlc_maximum_msat: OptionalField::Present(100_000),
3640 fee_proportional_millionths: 0,
3641 excess_data: Vec::new()
3644 // Path via {node0, node2} is channels {1, 3, 5}.
3645 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3646 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3647 short_channel_id: 1,
3650 cltv_expiry_delta: 0,
3651 htlc_minimum_msat: 0,
3652 htlc_maximum_msat: OptionalField::Present(100_000),
3654 fee_proportional_millionths: 0,
3655 excess_data: Vec::new()
3657 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3658 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3659 short_channel_id: 3,
3662 cltv_expiry_delta: 0,
3663 htlc_minimum_msat: 0,
3664 htlc_maximum_msat: OptionalField::Present(100_000),
3666 fee_proportional_millionths: 0,
3667 excess_data: Vec::new()
3670 // Capacity of 200 sats because this channel will be used by 3rd path as well.
3671 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(5)), 5);
3672 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3673 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3674 short_channel_id: 5,
3677 cltv_expiry_delta: 0,
3678 htlc_minimum_msat: 0,
3679 htlc_maximum_msat: OptionalField::Present(200_000),
3681 fee_proportional_millionths: 0,
3682 excess_data: Vec::new()
3685 // Path via {node7, node2, node4} is channels {12, 13, 6, 11}.
3686 // Add 100 sats to the capacities of {12, 13}, because these channels
3687 // are also used for 3rd path. 100 sats for the rest. Total capacity: 100 sats.
3688 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3689 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3690 short_channel_id: 12,
3693 cltv_expiry_delta: 0,
3694 htlc_minimum_msat: 0,
3695 htlc_maximum_msat: OptionalField::Present(200_000),
3697 fee_proportional_millionths: 0,
3698 excess_data: Vec::new()
3700 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
3701 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3702 short_channel_id: 13,
3705 cltv_expiry_delta: 0,
3706 htlc_minimum_msat: 0,
3707 htlc_maximum_msat: OptionalField::Present(200_000),
3709 fee_proportional_millionths: 0,
3710 excess_data: Vec::new()
3713 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3714 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3715 short_channel_id: 6,
3718 cltv_expiry_delta: 0,
3719 htlc_minimum_msat: 0,
3720 htlc_maximum_msat: OptionalField::Present(100_000),
3722 fee_proportional_millionths: 0,
3723 excess_data: Vec::new()
3725 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
3726 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3727 short_channel_id: 11,
3730 cltv_expiry_delta: 0,
3731 htlc_minimum_msat: 0,
3732 htlc_maximum_msat: OptionalField::Present(100_000),
3734 fee_proportional_millionths: 0,
3735 excess_data: Vec::new()
3738 // Path via {node7, node2} is channels {12, 13, 5}.
3739 // We already limited them to 200 sats (they are used twice for 100 sats).
3740 // Nothing to do here.
3743 // Attempt to route more than available results in a failure.
3744 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
3745 &our_id, &payee, &network_graph, None, 350_000, 42, Arc::clone(&logger), &scorer) {
3746 assert_eq!(err, "Failed to find a sufficient route to the given destination");
3747 } else { panic!(); }
3751 // Now, attempt to route 300 sats (exact amount we can route).
3752 // Our algorithm should provide us with these 3 paths, 100 sats each.
3753 let route = get_route(&our_id, &payee, &network_graph, None, 300_000, 42, Arc::clone(&logger), &scorer).unwrap();
3754 assert_eq!(route.paths.len(), 3);
3756 let mut total_amount_paid_msat = 0;
3757 for path in &route.paths {
3758 assert_eq!(path.last().unwrap().pubkey, nodes[3]);
3759 total_amount_paid_msat += path.last().unwrap().fee_msat;
3761 assert_eq!(total_amount_paid_msat, 300_000);
3767 fn mpp_cheaper_route_test() {
3768 let (secp_ctx, network_graph, net_graph_msg_handler, _, logger) = build_graph();
3769 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3770 let scorer = test_utils::TestScorer::with_fixed_penalty(0);
3771 let payee = Payee::from_node_id(nodes[3]).with_features(InvoiceFeatures::known());
3773 // This test checks that if we have two cheaper paths and one more expensive path,
3774 // so that liquidity-wise any 2 of 3 combination is sufficient,
3775 // two cheaper paths will be taken.
3776 // These paths have equal available liquidity.
3778 // We need a combination of 3 paths:
3779 // From our node to node3 via {node0, node2}, {node7, node2, node4} and {node7, node2}.
3780 // Note that these paths overlap (channels 5, 12, 13).
3781 // Each path will have 100 sats capacity, those channels which
3782 // are used twice will have 200 sats capacity.
3784 // Disable other potential paths.
3785 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3786 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3787 short_channel_id: 2,
3790 cltv_expiry_delta: 0,
3791 htlc_minimum_msat: 0,
3792 htlc_maximum_msat: OptionalField::Present(100_000),
3794 fee_proportional_millionths: 0,
3795 excess_data: Vec::new()
3797 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3798 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3799 short_channel_id: 7,
3802 cltv_expiry_delta: 0,
3803 htlc_minimum_msat: 0,
3804 htlc_maximum_msat: OptionalField::Present(100_000),
3806 fee_proportional_millionths: 0,
3807 excess_data: Vec::new()
3810 // Path via {node0, node2} is channels {1, 3, 5}.
3811 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3812 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3813 short_channel_id: 1,
3816 cltv_expiry_delta: 0,
3817 htlc_minimum_msat: 0,
3818 htlc_maximum_msat: OptionalField::Present(100_000),
3820 fee_proportional_millionths: 0,
3821 excess_data: Vec::new()
3823 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3824 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3825 short_channel_id: 3,
3828 cltv_expiry_delta: 0,
3829 htlc_minimum_msat: 0,
3830 htlc_maximum_msat: OptionalField::Present(100_000),
3832 fee_proportional_millionths: 0,
3833 excess_data: Vec::new()
3836 // Capacity of 200 sats because this channel will be used by 3rd path as well.
3837 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(5)), 5);
3838 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3839 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3840 short_channel_id: 5,
3843 cltv_expiry_delta: 0,
3844 htlc_minimum_msat: 0,
3845 htlc_maximum_msat: OptionalField::Present(200_000),
3847 fee_proportional_millionths: 0,
3848 excess_data: Vec::new()
3851 // Path via {node7, node2, node4} is channels {12, 13, 6, 11}.
3852 // Add 100 sats to the capacities of {12, 13}, because these channels
3853 // are also used for 3rd path. 100 sats for the rest. Total capacity: 100 sats.
3854 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3855 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3856 short_channel_id: 12,
3859 cltv_expiry_delta: 0,
3860 htlc_minimum_msat: 0,
3861 htlc_maximum_msat: OptionalField::Present(200_000),
3863 fee_proportional_millionths: 0,
3864 excess_data: Vec::new()
3866 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
3867 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3868 short_channel_id: 13,
3871 cltv_expiry_delta: 0,
3872 htlc_minimum_msat: 0,
3873 htlc_maximum_msat: OptionalField::Present(200_000),
3875 fee_proportional_millionths: 0,
3876 excess_data: Vec::new()
3879 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3880 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3881 short_channel_id: 6,
3884 cltv_expiry_delta: 0,
3885 htlc_minimum_msat: 0,
3886 htlc_maximum_msat: OptionalField::Present(100_000),
3887 fee_base_msat: 1_000,
3888 fee_proportional_millionths: 0,
3889 excess_data: Vec::new()
3891 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
3892 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3893 short_channel_id: 11,
3896 cltv_expiry_delta: 0,
3897 htlc_minimum_msat: 0,
3898 htlc_maximum_msat: OptionalField::Present(100_000),
3900 fee_proportional_millionths: 0,
3901 excess_data: Vec::new()
3904 // Path via {node7, node2} is channels {12, 13, 5}.
3905 // We already limited them to 200 sats (they are used twice for 100 sats).
3906 // Nothing to do here.
3909 // Now, attempt to route 180 sats.
3910 // Our algorithm should provide us with these 2 paths.
3911 let route = get_route(&our_id, &payee, &network_graph, None, 180_000, 42, Arc::clone(&logger), &scorer).unwrap();
3912 assert_eq!(route.paths.len(), 2);
3914 let mut total_value_transferred_msat = 0;
3915 let mut total_paid_msat = 0;
3916 for path in &route.paths {
3917 assert_eq!(path.last().unwrap().pubkey, nodes[3]);
3918 total_value_transferred_msat += path.last().unwrap().fee_msat;
3920 total_paid_msat += hop.fee_msat;
3923 // If we paid fee, this would be higher.
3924 assert_eq!(total_value_transferred_msat, 180_000);
3925 let total_fees_paid = total_paid_msat - total_value_transferred_msat;
3926 assert_eq!(total_fees_paid, 0);
3931 fn fees_on_mpp_route_test() {
3932 // This test makes sure that MPP algorithm properly takes into account
3933 // fees charged on the channels, by making the fees impactful:
3934 // if the fee is not properly accounted for, the behavior is different.
3935 let (secp_ctx, network_graph, net_graph_msg_handler, _, logger) = build_graph();
3936 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3937 let scorer = test_utils::TestScorer::with_fixed_penalty(0);
3938 let payee = Payee::from_node_id(nodes[3]).with_features(InvoiceFeatures::known());
3940 // We need a route consisting of 2 paths:
3941 // From our node to node3 via {node0, node2} and {node7, node2, node4}.
3942 // We will route 200 sats, Each path will have 100 sats capacity.
3944 // This test is not particularly stable: e.g.,
3945 // there's a way to route via {node0, node2, node4}.
3946 // It works while pathfinding is deterministic, but can be broken otherwise.
3947 // It's fine to ignore this concern for now.
3949 // Disable other potential paths.
3950 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3951 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3952 short_channel_id: 2,
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 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3964 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3965 short_channel_id: 7,
3968 cltv_expiry_delta: 0,
3969 htlc_minimum_msat: 0,
3970 htlc_maximum_msat: OptionalField::Present(100_000),
3972 fee_proportional_millionths: 0,
3973 excess_data: Vec::new()
3976 // Path via {node0, node2} is channels {1, 3, 5}.
3977 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3978 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3979 short_channel_id: 1,
3982 cltv_expiry_delta: 0,
3983 htlc_minimum_msat: 0,
3984 htlc_maximum_msat: OptionalField::Present(100_000),
3986 fee_proportional_millionths: 0,
3987 excess_data: Vec::new()
3989 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3990 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3991 short_channel_id: 3,
3994 cltv_expiry_delta: 0,
3995 htlc_minimum_msat: 0,
3996 htlc_maximum_msat: OptionalField::Present(100_000),
3998 fee_proportional_millionths: 0,
3999 excess_data: Vec::new()
4002 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(5)), 5);
4003 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4004 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4005 short_channel_id: 5,
4008 cltv_expiry_delta: 0,
4009 htlc_minimum_msat: 0,
4010 htlc_maximum_msat: OptionalField::Present(100_000),
4012 fee_proportional_millionths: 0,
4013 excess_data: Vec::new()
4016 // Path via {node7, node2, node4} is channels {12, 13, 6, 11}.
4017 // All channels should be 100 sats capacity. But for the fee experiment,
4018 // we'll add absolute fee of 150 sats paid for the use channel 6 (paid to node2 on channel 13).
4019 // Since channel 12 allows to deliver only 250 sats to channel 13, channel 13 can transfer only
4020 // 100 sats (and pay 150 sats in fees for the use of channel 6),
4021 // so no matter how large are other channels,
4022 // the whole path will be limited by 100 sats with just these 2 conditions:
4023 // - channel 12 capacity is 250 sats
4024 // - fee for channel 6 is 150 sats
4025 // Let's test this by enforcing these 2 conditions and removing other limits.
4026 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4027 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4028 short_channel_id: 12,
4031 cltv_expiry_delta: 0,
4032 htlc_minimum_msat: 0,
4033 htlc_maximum_msat: OptionalField::Present(250_000),
4035 fee_proportional_millionths: 0,
4036 excess_data: Vec::new()
4038 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
4039 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4040 short_channel_id: 13,
4043 cltv_expiry_delta: 0,
4044 htlc_minimum_msat: 0,
4045 htlc_maximum_msat: OptionalField::Absent,
4047 fee_proportional_millionths: 0,
4048 excess_data: Vec::new()
4051 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4052 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4053 short_channel_id: 6,
4056 cltv_expiry_delta: 0,
4057 htlc_minimum_msat: 0,
4058 htlc_maximum_msat: OptionalField::Absent,
4059 fee_base_msat: 150_000,
4060 fee_proportional_millionths: 0,
4061 excess_data: Vec::new()
4063 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
4064 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4065 short_channel_id: 11,
4068 cltv_expiry_delta: 0,
4069 htlc_minimum_msat: 0,
4070 htlc_maximum_msat: OptionalField::Absent,
4072 fee_proportional_millionths: 0,
4073 excess_data: Vec::new()
4077 // Attempt to route more than available results in a failure.
4078 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
4079 &our_id, &payee, &network_graph, None, 210_000, 42, Arc::clone(&logger), &scorer) {
4080 assert_eq!(err, "Failed to find a sufficient route to the given destination");
4081 } else { panic!(); }
4085 // Now, attempt to route 200 sats (exact amount we can route).
4086 let route = get_route(&our_id, &payee, &network_graph, None, 200_000, 42, Arc::clone(&logger), &scorer).unwrap();
4087 assert_eq!(route.paths.len(), 2);
4089 let mut total_amount_paid_msat = 0;
4090 for path in &route.paths {
4091 assert_eq!(path.last().unwrap().pubkey, nodes[3]);
4092 total_amount_paid_msat += path.last().unwrap().fee_msat;
4094 assert_eq!(total_amount_paid_msat, 200_000);
4095 assert_eq!(route.get_total_fees(), 150_000);
4100 fn mpp_with_last_hops() {
4101 // Previously, if we tried to send an MPP payment to a destination which was only reachable
4102 // via a single last-hop route hint, we'd fail to route if we first collected routes
4103 // totaling close but not quite enough to fund the full payment.
4105 // This was because we considered last-hop hints to have exactly the sought payment amount
4106 // instead of the amount we were trying to collect, needlessly limiting our path searching
4107 // at the very first hop.
4109 // Specifically, this interacted with our "all paths must fund at least 5% of total target"
4110 // criterion to cause us to refuse all routes at the last hop hint which would be considered
4111 // to only have the remaining to-collect amount in available liquidity.
4113 // This bug appeared in production in some specific channel configurations.
4114 let (secp_ctx, network_graph, net_graph_msg_handler, _, logger) = build_graph();
4115 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
4116 let scorer = test_utils::TestScorer::with_fixed_penalty(0);
4117 let payee = Payee::from_node_id(PublicKey::from_slice(&[02; 33]).unwrap()).with_features(InvoiceFeatures::known())
4118 .with_route_hints(vec![RouteHint(vec![RouteHintHop {
4119 src_node_id: nodes[2],
4120 short_channel_id: 42,
4121 fees: RoutingFees { base_msat: 0, proportional_millionths: 0 },
4122 cltv_expiry_delta: 42,
4123 htlc_minimum_msat: None,
4124 htlc_maximum_msat: None,
4127 // Keep only two paths from us to nodes[2], both with a 99sat HTLC maximum, with one with
4128 // no fee and one with a 1msat fee. Previously, trying to route 100 sats to nodes[2] here
4129 // would first use the no-fee route and then fail to find a path along the second route as
4130 // we think we can only send up to 1 additional sat over the last-hop but refuse to as its
4131 // under 5% of our payment amount.
4132 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4133 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4134 short_channel_id: 1,
4137 cltv_expiry_delta: (5 << 4) | 5,
4138 htlc_minimum_msat: 0,
4139 htlc_maximum_msat: OptionalField::Present(99_000),
4140 fee_base_msat: u32::max_value(),
4141 fee_proportional_millionths: u32::max_value(),
4142 excess_data: Vec::new()
4144 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4145 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4146 short_channel_id: 2,
4149 cltv_expiry_delta: (5 << 4) | 3,
4150 htlc_minimum_msat: 0,
4151 htlc_maximum_msat: OptionalField::Present(99_000),
4152 fee_base_msat: u32::max_value(),
4153 fee_proportional_millionths: u32::max_value(),
4154 excess_data: Vec::new()
4156 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
4157 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4158 short_channel_id: 4,
4161 cltv_expiry_delta: (4 << 4) | 1,
4162 htlc_minimum_msat: 0,
4163 htlc_maximum_msat: OptionalField::Absent,
4165 fee_proportional_millionths: 0,
4166 excess_data: Vec::new()
4168 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
4169 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4170 short_channel_id: 13,
4172 flags: 0|2, // Channel disabled
4173 cltv_expiry_delta: (13 << 4) | 1,
4174 htlc_minimum_msat: 0,
4175 htlc_maximum_msat: OptionalField::Absent,
4177 fee_proportional_millionths: 2000000,
4178 excess_data: Vec::new()
4181 // Get a route for 100 sats and check that we found the MPP route no problem and didn't
4183 let route = get_route(&our_id, &payee, &network_graph, None, 100_000, 42, Arc::clone(&logger), &scorer).unwrap();
4184 assert_eq!(route.paths.len(), 2);
4185 // Paths are somewhat randomly ordered, but:
4186 // * the first is channel 2 (1 msat fee) -> channel 4 -> channel 42
4187 // * the second is channel 1 (0 fee, but 99 sat maximum) -> channel 3 -> channel 42
4188 assert_eq!(route.paths[0][0].short_channel_id, 2);
4189 assert_eq!(route.paths[0][0].fee_msat, 1);
4190 assert_eq!(route.paths[0][2].fee_msat, 1_000);
4191 assert_eq!(route.paths[1][0].short_channel_id, 1);
4192 assert_eq!(route.paths[1][0].fee_msat, 0);
4193 assert_eq!(route.paths[1][2].fee_msat, 99_000);
4194 assert_eq!(route.get_total_fees(), 1);
4195 assert_eq!(route.get_total_amount(), 100_000);
4199 fn drop_lowest_channel_mpp_route_test() {
4200 // This test checks that low-capacity channel is dropped when after
4201 // path finding we realize that we found more capacity than we need.
4202 let (secp_ctx, network_graph, net_graph_msg_handler, _, logger) = build_graph();
4203 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
4204 let scorer = test_utils::TestScorer::with_fixed_penalty(0);
4205 let payee = Payee::from_node_id(nodes[2]).with_features(InvoiceFeatures::known());
4207 // We need a route consisting of 3 paths:
4208 // From our node to node2 via node0, node7, node1 (three paths one hop each).
4210 // The first and the second paths should be sufficient, but the third should be
4211 // cheaper, so that we select it but drop later.
4213 // First, we set limits on these (previously unlimited) channels.
4214 // Their aggregate capacity will be 50 + 60 + 20 = 130 sats.
4216 // Path via node0 is channels {1, 3}. Limit them to 100 and 50 sats (total limit 50);
4217 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4218 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4219 short_channel_id: 1,
4222 cltv_expiry_delta: 0,
4223 htlc_minimum_msat: 0,
4224 htlc_maximum_msat: OptionalField::Present(100_000),
4226 fee_proportional_millionths: 0,
4227 excess_data: Vec::new()
4229 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
4230 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4231 short_channel_id: 3,
4234 cltv_expiry_delta: 0,
4235 htlc_minimum_msat: 0,
4236 htlc_maximum_msat: OptionalField::Present(50_000),
4238 fee_proportional_millionths: 0,
4239 excess_data: Vec::new()
4242 // Path via node7 is channels {12, 13}. Limit them to 60 and 60 sats (total limit 60);
4243 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4244 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4245 short_channel_id: 12,
4248 cltv_expiry_delta: 0,
4249 htlc_minimum_msat: 0,
4250 htlc_maximum_msat: OptionalField::Present(60_000),
4252 fee_proportional_millionths: 0,
4253 excess_data: Vec::new()
4255 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
4256 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4257 short_channel_id: 13,
4260 cltv_expiry_delta: 0,
4261 htlc_minimum_msat: 0,
4262 htlc_maximum_msat: OptionalField::Present(60_000),
4264 fee_proportional_millionths: 0,
4265 excess_data: Vec::new()
4268 // Path via node1 is channels {2, 4}. Limit them to 20 and 20 sats (total capacity 20 sats).
4269 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4270 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4271 short_channel_id: 2,
4274 cltv_expiry_delta: 0,
4275 htlc_minimum_msat: 0,
4276 htlc_maximum_msat: OptionalField::Present(20_000),
4278 fee_proportional_millionths: 0,
4279 excess_data: Vec::new()
4281 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
4282 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4283 short_channel_id: 4,
4286 cltv_expiry_delta: 0,
4287 htlc_minimum_msat: 0,
4288 htlc_maximum_msat: OptionalField::Present(20_000),
4290 fee_proportional_millionths: 0,
4291 excess_data: Vec::new()
4295 // Attempt to route more than available results in a failure.
4296 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
4297 &our_id, &payee, &network_graph, None, 150_000, 42, Arc::clone(&logger), &scorer) {
4298 assert_eq!(err, "Failed to find a sufficient route to the given destination");
4299 } else { panic!(); }
4303 // Now, attempt to route 125 sats (just a bit below the capacity of 3 channels).
4304 // Our algorithm should provide us with these 3 paths.
4305 let route = get_route(&our_id, &payee, &network_graph, None, 125_000, 42, Arc::clone(&logger), &scorer).unwrap();
4306 assert_eq!(route.paths.len(), 3);
4307 let mut total_amount_paid_msat = 0;
4308 for path in &route.paths {
4309 assert_eq!(path.len(), 2);
4310 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
4311 total_amount_paid_msat += path.last().unwrap().fee_msat;
4313 assert_eq!(total_amount_paid_msat, 125_000);
4317 // Attempt to route without the last small cheap channel
4318 let route = get_route(&our_id, &payee, &network_graph, None, 90_000, 42, Arc::clone(&logger), &scorer).unwrap();
4319 assert_eq!(route.paths.len(), 2);
4320 let mut total_amount_paid_msat = 0;
4321 for path in &route.paths {
4322 assert_eq!(path.len(), 2);
4323 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
4324 total_amount_paid_msat += path.last().unwrap().fee_msat;
4326 assert_eq!(total_amount_paid_msat, 90_000);
4331 fn min_criteria_consistency() {
4332 // Test that we don't use an inconsistent metric between updating and walking nodes during
4333 // our Dijkstra's pass. In the initial version of MPP, the "best source" for a given node
4334 // was updated with a different criterion from the heap sorting, resulting in loops in
4335 // calculated paths. We test for that specific case here.
4337 // We construct a network that looks like this:
4339 // node2 -1(3)2- node3
4343 // node1 -1(5)2- node4 -1(1)2- node6
4349 // We create a loop on the side of our real path - our destination is node 6, with a
4350 // previous hop of node 4. From 4, the cheapest previous path is channel 2 from node 2,
4351 // followed by node 3 over channel 3. Thereafter, the cheapest next-hop is back to node 4
4352 // (this time over channel 4). Channel 4 has 0 htlc_minimum_msat whereas channel 1 (the
4353 // other channel with a previous-hop of node 4) has a high (but irrelevant to the overall
4354 // payment) htlc_minimum_msat. In the original algorithm, this resulted in node4's
4355 // "previous hop" being set to node 3, creating a loop in the path.
4356 let secp_ctx = Secp256k1::new();
4357 let logger = Arc::new(test_utils::TestLogger::new());
4358 let network_graph = Arc::new(NetworkGraph::new(genesis_block(Network::Testnet).header.block_hash()));
4359 let net_graph_msg_handler = NetGraphMsgHandler::new(Arc::clone(&network_graph), None, Arc::clone(&logger));
4360 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
4361 let scorer = test_utils::TestScorer::with_fixed_penalty(0);
4362 let payee = Payee::from_node_id(nodes[6]);
4364 add_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, &privkeys[1], ChannelFeatures::from_le_bytes(id_to_feature_flags(6)), 6);
4365 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4366 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4367 short_channel_id: 6,
4370 cltv_expiry_delta: (6 << 4) | 0,
4371 htlc_minimum_msat: 0,
4372 htlc_maximum_msat: OptionalField::Absent,
4374 fee_proportional_millionths: 0,
4375 excess_data: Vec::new()
4377 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[1], NodeFeatures::from_le_bytes(id_to_feature_flags(1)), 0);
4379 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], &privkeys[4], ChannelFeatures::from_le_bytes(id_to_feature_flags(5)), 5);
4380 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
4381 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4382 short_channel_id: 5,
4385 cltv_expiry_delta: (5 << 4) | 0,
4386 htlc_minimum_msat: 0,
4387 htlc_maximum_msat: OptionalField::Absent,
4389 fee_proportional_millionths: 0,
4390 excess_data: Vec::new()
4392 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[4], NodeFeatures::from_le_bytes(id_to_feature_flags(4)), 0);
4394 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(4)), 4);
4395 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
4396 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4397 short_channel_id: 4,
4400 cltv_expiry_delta: (4 << 4) | 0,
4401 htlc_minimum_msat: 0,
4402 htlc_maximum_msat: OptionalField::Absent,
4404 fee_proportional_millionths: 0,
4405 excess_data: Vec::new()
4407 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[3], NodeFeatures::from_le_bytes(id_to_feature_flags(3)), 0);
4409 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[3], &privkeys[2], ChannelFeatures::from_le_bytes(id_to_feature_flags(3)), 3);
4410 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[3], UnsignedChannelUpdate {
4411 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4412 short_channel_id: 3,
4415 cltv_expiry_delta: (3 << 4) | 0,
4416 htlc_minimum_msat: 0,
4417 htlc_maximum_msat: OptionalField::Absent,
4419 fee_proportional_millionths: 0,
4420 excess_data: Vec::new()
4422 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[2], NodeFeatures::from_le_bytes(id_to_feature_flags(2)), 0);
4424 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], &privkeys[4], ChannelFeatures::from_le_bytes(id_to_feature_flags(2)), 2);
4425 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4426 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4427 short_channel_id: 2,
4430 cltv_expiry_delta: (2 << 4) | 0,
4431 htlc_minimum_msat: 0,
4432 htlc_maximum_msat: OptionalField::Absent,
4434 fee_proportional_millionths: 0,
4435 excess_data: Vec::new()
4438 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], &privkeys[6], ChannelFeatures::from_le_bytes(id_to_feature_flags(1)), 1);
4439 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
4440 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4441 short_channel_id: 1,
4444 cltv_expiry_delta: (1 << 4) | 0,
4445 htlc_minimum_msat: 100,
4446 htlc_maximum_msat: OptionalField::Absent,
4448 fee_proportional_millionths: 0,
4449 excess_data: Vec::new()
4451 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[6], NodeFeatures::from_le_bytes(id_to_feature_flags(6)), 0);
4454 // Now ensure the route flows simply over nodes 1 and 4 to 6.
4455 let route = get_route(&our_id, &payee, &network_graph, None, 10_000, 42, Arc::clone(&logger), &scorer).unwrap();
4456 assert_eq!(route.paths.len(), 1);
4457 assert_eq!(route.paths[0].len(), 3);
4459 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
4460 assert_eq!(route.paths[0][0].short_channel_id, 6);
4461 assert_eq!(route.paths[0][0].fee_msat, 100);
4462 assert_eq!(route.paths[0][0].cltv_expiry_delta, (5 << 4) | 0);
4463 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(1));
4464 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(6));
4466 assert_eq!(route.paths[0][1].pubkey, nodes[4]);
4467 assert_eq!(route.paths[0][1].short_channel_id, 5);
4468 assert_eq!(route.paths[0][1].fee_msat, 0);
4469 assert_eq!(route.paths[0][1].cltv_expiry_delta, (1 << 4) | 0);
4470 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(4));
4471 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(5));
4473 assert_eq!(route.paths[0][2].pubkey, nodes[6]);
4474 assert_eq!(route.paths[0][2].short_channel_id, 1);
4475 assert_eq!(route.paths[0][2].fee_msat, 10_000);
4476 assert_eq!(route.paths[0][2].cltv_expiry_delta, 42);
4477 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(6));
4478 assert_eq!(route.paths[0][2].channel_features.le_flags(), &id_to_feature_flags(1));
4484 fn exact_fee_liquidity_limit() {
4485 // Test that if, while walking the graph, we find a hop that has exactly enough liquidity
4486 // for us, including later hop fees, we take it. In the first version of our MPP algorithm
4487 // we calculated fees on a higher value, resulting in us ignoring such paths.
4488 let (secp_ctx, network_graph, net_graph_msg_handler, _, logger) = build_graph();
4489 let (our_privkey, our_id, _, nodes) = get_nodes(&secp_ctx);
4490 let scorer = test_utils::TestScorer::with_fixed_penalty(0);
4491 let payee = Payee::from_node_id(nodes[2]);
4493 // We modify the graph to set the htlc_maximum of channel 2 to below the value we wish to
4495 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4496 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4497 short_channel_id: 2,
4500 cltv_expiry_delta: 0,
4501 htlc_minimum_msat: 0,
4502 htlc_maximum_msat: OptionalField::Present(85_000),
4504 fee_proportional_millionths: 0,
4505 excess_data: Vec::new()
4508 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4509 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4510 short_channel_id: 12,
4513 cltv_expiry_delta: (4 << 4) | 1,
4514 htlc_minimum_msat: 0,
4515 htlc_maximum_msat: OptionalField::Present(270_000),
4517 fee_proportional_millionths: 1000000,
4518 excess_data: Vec::new()
4522 // Now, attempt to route 90 sats, which is exactly 90 sats at the last hop, plus the
4523 // 200% fee charged channel 13 in the 1-to-2 direction.
4524 let route = get_route(&our_id, &payee, &network_graph, None, 90_000, 42, Arc::clone(&logger), &scorer).unwrap();
4525 assert_eq!(route.paths.len(), 1);
4526 assert_eq!(route.paths[0].len(), 2);
4528 assert_eq!(route.paths[0][0].pubkey, nodes[7]);
4529 assert_eq!(route.paths[0][0].short_channel_id, 12);
4530 assert_eq!(route.paths[0][0].fee_msat, 90_000*2);
4531 assert_eq!(route.paths[0][0].cltv_expiry_delta, (13 << 4) | 1);
4532 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(8));
4533 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(12));
4535 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
4536 assert_eq!(route.paths[0][1].short_channel_id, 13);
4537 assert_eq!(route.paths[0][1].fee_msat, 90_000);
4538 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
4539 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
4540 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(13));
4545 fn htlc_max_reduction_below_min() {
4546 // Test that if, while walking the graph, we reduce the value being sent to meet an
4547 // htlc_maximum_msat, we don't end up undershooting a later htlc_minimum_msat. In the
4548 // initial version of MPP we'd accept such routes but reject them while recalculating fees,
4549 // resulting in us thinking there is no possible path, even if other paths exist.
4550 let (secp_ctx, network_graph, net_graph_msg_handler, _, logger) = build_graph();
4551 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
4552 let scorer = test_utils::TestScorer::with_fixed_penalty(0);
4553 let payee = Payee::from_node_id(nodes[2]).with_features(InvoiceFeatures::known());
4555 // We modify the graph to set the htlc_minimum of channel 2 and 4 as needed - channel 2
4556 // gets an htlc_maximum_msat of 80_000 and channel 4 an htlc_minimum_msat of 90_000. We
4557 // then try to send 90_000.
4558 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4559 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4560 short_channel_id: 2,
4563 cltv_expiry_delta: 0,
4564 htlc_minimum_msat: 0,
4565 htlc_maximum_msat: OptionalField::Present(80_000),
4567 fee_proportional_millionths: 0,
4568 excess_data: Vec::new()
4570 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
4571 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4572 short_channel_id: 4,
4575 cltv_expiry_delta: (4 << 4) | 1,
4576 htlc_minimum_msat: 90_000,
4577 htlc_maximum_msat: OptionalField::Absent,
4579 fee_proportional_millionths: 0,
4580 excess_data: Vec::new()
4584 // Now, attempt to route 90 sats, hitting the htlc_minimum on channel 4, but
4585 // overshooting the htlc_maximum on channel 2. Thus, we should pick the (absurdly
4586 // expensive) channels 12-13 path.
4587 let route = get_route(&our_id, &payee, &network_graph, None, 90_000, 42, Arc::clone(&logger), &scorer).unwrap();
4588 assert_eq!(route.paths.len(), 1);
4589 assert_eq!(route.paths[0].len(), 2);
4591 assert_eq!(route.paths[0][0].pubkey, nodes[7]);
4592 assert_eq!(route.paths[0][0].short_channel_id, 12);
4593 assert_eq!(route.paths[0][0].fee_msat, 90_000*2);
4594 assert_eq!(route.paths[0][0].cltv_expiry_delta, (13 << 4) | 1);
4595 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(8));
4596 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(12));
4598 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
4599 assert_eq!(route.paths[0][1].short_channel_id, 13);
4600 assert_eq!(route.paths[0][1].fee_msat, 90_000);
4601 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
4602 assert_eq!(route.paths[0][1].node_features.le_flags(), InvoiceFeatures::known().le_flags());
4603 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(13));
4608 fn multiple_direct_first_hops() {
4609 // Previously we'd only ever considered one first hop path per counterparty.
4610 // However, as we don't restrict users to one channel per peer, we really need to support
4611 // looking at all first hop paths.
4612 // Here we test that we do not ignore all-but-the-last first hop paths per counterparty (as
4613 // we used to do by overwriting the `first_hop_targets` hashmap entry) and that we can MPP
4614 // route over multiple channels with the same first hop.
4615 let secp_ctx = Secp256k1::new();
4616 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
4617 let logger = Arc::new(test_utils::TestLogger::new());
4618 let network_graph = NetworkGraph::new(genesis_block(Network::Testnet).header.block_hash());
4619 let scorer = test_utils::TestScorer::with_fixed_penalty(0);
4620 let payee = Payee::from_node_id(nodes[0]).with_features(InvoiceFeatures::known());
4623 let route = get_route(&our_id, &payee, &network_graph, Some(&[
4624 &get_channel_details(Some(3), nodes[0], InitFeatures::known(), 200_000),
4625 &get_channel_details(Some(2), nodes[0], InitFeatures::known(), 10_000),
4626 ]), 100_000, 42, Arc::clone(&logger), &scorer).unwrap();
4627 assert_eq!(route.paths.len(), 1);
4628 assert_eq!(route.paths[0].len(), 1);
4630 assert_eq!(route.paths[0][0].pubkey, nodes[0]);
4631 assert_eq!(route.paths[0][0].short_channel_id, 3);
4632 assert_eq!(route.paths[0][0].fee_msat, 100_000);
4635 let route = get_route(&our_id, &payee, &network_graph, Some(&[
4636 &get_channel_details(Some(3), nodes[0], InitFeatures::known(), 50_000),
4637 &get_channel_details(Some(2), nodes[0], InitFeatures::known(), 50_000),
4638 ]), 100_000, 42, Arc::clone(&logger), &scorer).unwrap();
4639 assert_eq!(route.paths.len(), 2);
4640 assert_eq!(route.paths[0].len(), 1);
4641 assert_eq!(route.paths[1].len(), 1);
4643 assert_eq!(route.paths[0][0].pubkey, nodes[0]);
4644 assert_eq!(route.paths[0][0].short_channel_id, 3);
4645 assert_eq!(route.paths[0][0].fee_msat, 50_000);
4647 assert_eq!(route.paths[1][0].pubkey, nodes[0]);
4648 assert_eq!(route.paths[1][0].short_channel_id, 2);
4649 assert_eq!(route.paths[1][0].fee_msat, 50_000);
4654 fn prefers_shorter_route_with_higher_fees() {
4655 let (secp_ctx, network_graph, _, _, logger) = build_graph();
4656 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
4657 let payee = Payee::from_node_id(nodes[6]).with_route_hints(last_hops(&nodes));
4659 // Without penalizing each hop 100 msats, a longer path with lower fees is chosen.
4660 let scorer = test_utils::TestScorer::with_fixed_penalty(0);
4661 let route = get_route(
4662 &our_id, &payee, &network_graph, None, 100, 42,
4663 Arc::clone(&logger), &scorer
4665 let path = route.paths[0].iter().map(|hop| hop.short_channel_id).collect::<Vec<_>>();
4667 assert_eq!(route.get_total_fees(), 100);
4668 assert_eq!(route.get_total_amount(), 100);
4669 assert_eq!(path, vec![2, 4, 6, 11, 8]);
4671 // Applying a 100 msat penalty to each hop results in taking channels 7 and 10 to nodes[6]
4672 // from nodes[2] rather than channel 6, 11, and 8, even though the longer path is cheaper.
4673 let scorer = test_utils::TestScorer::with_fixed_penalty(100);
4674 let route = get_route(
4675 &our_id, &payee, &network_graph, None, 100, 42,
4676 Arc::clone(&logger), &scorer
4678 let path = route.paths[0].iter().map(|hop| hop.short_channel_id).collect::<Vec<_>>();
4680 assert_eq!(route.get_total_fees(), 300);
4681 assert_eq!(route.get_total_amount(), 100);
4682 assert_eq!(path, vec![2, 4, 7, 10]);
4685 struct BadChannelScorer {
4686 short_channel_id: u64,
4690 impl Writeable for BadChannelScorer {
4691 fn write<W: Writer>(&self, _w: &mut W) -> Result<(), ::io::Error> { unimplemented!() }
4693 impl Score for BadChannelScorer {
4694 fn channel_penalty_msat(&self, short_channel_id: u64, _send_amt: u64, _chan_amt: Option<u64>, _source: &NodeId, _target: &NodeId) -> u64 {
4695 if short_channel_id == self.short_channel_id { u64::max_value() } else { 0 }
4698 fn payment_path_failed(&mut self, _path: &[&RouteHop], _short_channel_id: u64) {}
4699 fn payment_path_successful(&mut self, _path: &[&RouteHop]) {}
4702 struct BadNodeScorer {
4707 impl Writeable for BadNodeScorer {
4708 fn write<W: Writer>(&self, _w: &mut W) -> Result<(), ::io::Error> { unimplemented!() }
4711 impl Score for BadNodeScorer {
4712 fn channel_penalty_msat(&self, _short_channel_id: u64, _send_amt: u64, _chan_amt: Option<u64>, _source: &NodeId, target: &NodeId) -> u64 {
4713 if *target == self.node_id { u64::max_value() } else { 0 }
4716 fn payment_path_failed(&mut self, _path: &[&RouteHop], _short_channel_id: u64) {}
4717 fn payment_path_successful(&mut self, _path: &[&RouteHop]) {}
4721 fn avoids_routing_through_bad_channels_and_nodes() {
4722 let (secp_ctx, network_graph, _, _, logger) = build_graph();
4723 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
4724 let payee = Payee::from_node_id(nodes[6]).with_route_hints(last_hops(&nodes));
4726 // A path to nodes[6] exists when no penalties are applied to any channel.
4727 let scorer = test_utils::TestScorer::with_fixed_penalty(0);
4728 let route = get_route(
4729 &our_id, &payee, &network_graph, None, 100, 42,
4730 Arc::clone(&logger), &scorer
4732 let path = route.paths[0].iter().map(|hop| hop.short_channel_id).collect::<Vec<_>>();
4734 assert_eq!(route.get_total_fees(), 100);
4735 assert_eq!(route.get_total_amount(), 100);
4736 assert_eq!(path, vec![2, 4, 6, 11, 8]);
4738 // A different path to nodes[6] exists if channel 6 cannot be routed over.
4739 let scorer = BadChannelScorer { short_channel_id: 6 };
4740 let route = get_route(
4741 &our_id, &payee, &network_graph, None, 100, 42,
4742 Arc::clone(&logger), &scorer
4744 let path = route.paths[0].iter().map(|hop| hop.short_channel_id).collect::<Vec<_>>();
4746 assert_eq!(route.get_total_fees(), 300);
4747 assert_eq!(route.get_total_amount(), 100);
4748 assert_eq!(path, vec![2, 4, 7, 10]);
4750 // A path to nodes[6] does not exist if nodes[2] cannot be routed through.
4751 let scorer = BadNodeScorer { node_id: NodeId::from_pubkey(&nodes[2]) };
4753 &our_id, &payee, &network_graph, None, 100, 42,
4754 Arc::clone(&logger), &scorer
4756 Err(LightningError { err, .. } ) => {
4757 assert_eq!(err, "Failed to find a path to the given destination");
4759 Ok(_) => panic!("Expected error"),
4764 fn total_fees_single_path() {
4768 pubkey: PublicKey::from_slice(&hex::decode("02eec7245d6b7d2ccb30380bfbe2a3648cd7a942653f5aa340edcea1f283686619").unwrap()[..]).unwrap(),
4769 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
4770 short_channel_id: 0, fee_msat: 100, cltv_expiry_delta: 0
4773 pubkey: PublicKey::from_slice(&hex::decode("0324653eac434488002cc06bbfb7f10fe18991e35f9fe4302dbea6d2353dc0ab1c").unwrap()[..]).unwrap(),
4774 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
4775 short_channel_id: 0, fee_msat: 150, cltv_expiry_delta: 0
4778 pubkey: PublicKey::from_slice(&hex::decode("027f31ebc5462c1fdce1b737ecff52d37d75dea43ce11c74d25aa297165faa2007").unwrap()[..]).unwrap(),
4779 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
4780 short_channel_id: 0, fee_msat: 225, cltv_expiry_delta: 0
4786 assert_eq!(route.get_total_fees(), 250);
4787 assert_eq!(route.get_total_amount(), 225);
4791 fn total_fees_multi_path() {
4795 pubkey: PublicKey::from_slice(&hex::decode("02eec7245d6b7d2ccb30380bfbe2a3648cd7a942653f5aa340edcea1f283686619").unwrap()[..]).unwrap(),
4796 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
4797 short_channel_id: 0, fee_msat: 100, cltv_expiry_delta: 0
4800 pubkey: PublicKey::from_slice(&hex::decode("0324653eac434488002cc06bbfb7f10fe18991e35f9fe4302dbea6d2353dc0ab1c").unwrap()[..]).unwrap(),
4801 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
4802 short_channel_id: 0, fee_msat: 150, cltv_expiry_delta: 0
4806 pubkey: PublicKey::from_slice(&hex::decode("02eec7245d6b7d2ccb30380bfbe2a3648cd7a942653f5aa340edcea1f283686619").unwrap()[..]).unwrap(),
4807 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
4808 short_channel_id: 0, fee_msat: 100, cltv_expiry_delta: 0
4811 pubkey: PublicKey::from_slice(&hex::decode("0324653eac434488002cc06bbfb7f10fe18991e35f9fe4302dbea6d2353dc0ab1c").unwrap()[..]).unwrap(),
4812 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
4813 short_channel_id: 0, fee_msat: 150, cltv_expiry_delta: 0
4819 assert_eq!(route.get_total_fees(), 200);
4820 assert_eq!(route.get_total_amount(), 300);
4824 fn total_empty_route_no_panic() {
4825 // In an earlier version of `Route::get_total_fees` and `Route::get_total_amount`, they
4826 // would both panic if the route was completely empty. We test to ensure they return 0
4827 // here, even though its somewhat nonsensical as a route.
4828 let route = Route { paths: Vec::new(), payee: None };
4830 assert_eq!(route.get_total_fees(), 0);
4831 assert_eq!(route.get_total_amount(), 0);
4835 fn limits_total_cltv_delta() {
4836 let (secp_ctx, network_graph, _, _, logger) = build_graph();
4837 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
4839 let scorer = test_utils::TestScorer::with_fixed_penalty(0);
4841 // Make sure that generally there is at least one route available
4842 let feasible_max_total_cltv_delta = 1008;
4843 let feasible_payee = Payee::from_node_id(nodes[6]).with_route_hints(last_hops(&nodes))
4844 .with_max_total_cltv_expiry_delta(feasible_max_total_cltv_delta);
4845 let route = get_route(&our_id, &feasible_payee, &network_graph, None, 100, 42, Arc::clone(&logger), &scorer).unwrap();
4846 let path = route.paths[0].iter().map(|hop| hop.short_channel_id).collect::<Vec<_>>();
4847 assert_ne!(path.len(), 0);
4849 // But not if we exclude all paths on the basis of their accumulated CLTV delta
4850 let fail_max_total_cltv_delta = 23;
4851 let fail_payee = Payee::from_node_id(nodes[6]).with_route_hints(last_hops(&nodes))
4852 .with_max_total_cltv_expiry_delta(fail_max_total_cltv_delta);
4853 match get_route(&our_id, &fail_payee, &network_graph, None, 100, 42, Arc::clone(&logger), &scorer)
4855 Err(LightningError { err, .. } ) => {
4856 assert_eq!(err, "Failed to find a path to the given destination");
4858 Ok(_) => panic!("Expected error"),
4862 #[cfg(not(feature = "no-std"))]
4863 pub(super) fn random_init_seed() -> u64 {
4864 // Because the default HashMap in std pulls OS randomness, we can use it as a (bad) RNG.
4865 use core::hash::{BuildHasher, Hasher};
4866 let seed = std::collections::hash_map::RandomState::new().build_hasher().finish();
4867 println!("Using seed of {}", seed);
4870 #[cfg(not(feature = "no-std"))]
4871 use util::ser::Readable;
4874 #[cfg(not(feature = "no-std"))]
4875 fn generate_routes() {
4876 let mut d = match super::test_utils::get_route_file() {
4883 let graph = NetworkGraph::read(&mut d).unwrap();
4884 let scorer = test_utils::TestScorer::with_fixed_penalty(0);
4886 // First, get 100 (source, destination) pairs for which route-getting actually succeeds...
4887 let mut seed = random_init_seed() as usize;
4888 let nodes = graph.read_only().nodes().clone();
4889 'load_endpoints: for _ in 0..10 {
4891 seed = seed.overflowing_mul(0xdeadbeef).0;
4892 let src = &PublicKey::from_slice(nodes.keys().skip(seed % nodes.len()).next().unwrap().as_slice()).unwrap();
4893 seed = seed.overflowing_mul(0xdeadbeef).0;
4894 let dst = PublicKey::from_slice(nodes.keys().skip(seed % nodes.len()).next().unwrap().as_slice()).unwrap();
4895 let payee = Payee::from_node_id(dst);
4896 let amt = seed as u64 % 200_000_000;
4897 if get_route(src, &payee, &graph, None, amt, 42, &test_utils::TestLogger::new(), &scorer).is_ok() {
4898 continue 'load_endpoints;
4905 #[cfg(not(feature = "no-std"))]
4906 fn generate_routes_mpp() {
4907 let mut d = match super::test_utils::get_route_file() {
4914 let graph = NetworkGraph::read(&mut d).unwrap();
4915 let scorer = test_utils::TestScorer::with_fixed_penalty(0);
4917 // First, get 100 (source, destination) pairs for which route-getting actually succeeds...
4918 let mut seed = random_init_seed() as usize;
4919 let nodes = graph.read_only().nodes().clone();
4920 'load_endpoints: for _ in 0..10 {
4922 seed = seed.overflowing_mul(0xdeadbeef).0;
4923 let src = &PublicKey::from_slice(nodes.keys().skip(seed % nodes.len()).next().unwrap().as_slice()).unwrap();
4924 seed = seed.overflowing_mul(0xdeadbeef).0;
4925 let dst = PublicKey::from_slice(nodes.keys().skip(seed % nodes.len()).next().unwrap().as_slice()).unwrap();
4926 let payee = Payee::from_node_id(dst).with_features(InvoiceFeatures::known());
4927 let amt = seed as u64 % 200_000_000;
4928 if get_route(src, &payee, &graph, None, amt, 42, &test_utils::TestLogger::new(), &scorer).is_ok() {
4929 continue 'load_endpoints;
4936 #[cfg(all(test, not(feature = "no-std")))]
4937 pub(crate) mod test_utils {
4939 /// Tries to open a network graph file, or panics with a URL to fetch it.
4940 pub(crate) fn get_route_file() -> Result<std::fs::File, &'static str> {
4941 let res = File::open("net_graph-2021-05-31.bin") // By default we're run in RL/lightning
4942 .or_else(|_| File::open("lightning/net_graph-2021-05-31.bin")) // We may be run manually in RL/
4943 .or_else(|_| { // Fall back to guessing based on the binary location
4944 // path is likely something like .../rust-lightning/target/debug/deps/lightning-...
4945 let mut path = std::env::current_exe().unwrap();
4946 path.pop(); // lightning-...
4948 path.pop(); // debug
4949 path.pop(); // target
4950 path.push("lightning");
4951 path.push("net_graph-2021-05-31.bin");
4952 eprintln!("{}", path.to_str().unwrap());
4955 .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");
4956 #[cfg(require_route_graph_test)]
4957 return Ok(res.unwrap());
4958 #[cfg(not(require_route_graph_test))]
4963 #[cfg(all(test, feature = "unstable", not(feature = "no-std")))]
4966 use bitcoin::hashes::Hash;
4967 use bitcoin::secp256k1::{PublicKey, Secp256k1, SecretKey};
4968 use chain::transaction::OutPoint;
4969 use ln::channelmanager::{ChannelCounterparty, ChannelDetails};
4970 use ln::features::{InitFeatures, InvoiceFeatures};
4971 use routing::scoring::Scorer;
4972 use util::logger::{Logger, Record};
4976 struct DummyLogger {}
4977 impl Logger for DummyLogger {
4978 fn log(&self, _record: &Record) {}
4981 struct ZeroPenaltyScorer;
4982 impl Score for ZeroPenaltyScorer {
4983 fn channel_penalty_msat(
4984 &self, _short_channel_id: u64, _send_amt: u64, _capacity_msat: Option<u64>, _source: &NodeId, _target: &NodeId
4986 fn payment_path_failed(&mut self, _path: &[&RouteHop], _short_channel_id: u64) {}
4987 fn payment_path_successful(&mut self, _path: &[&RouteHop]) {}
4990 fn read_network_graph() -> NetworkGraph {
4991 let mut d = test_utils::get_route_file().unwrap();
4992 NetworkGraph::read(&mut d).unwrap()
4995 fn payer_pubkey() -> PublicKey {
4996 let secp_ctx = Secp256k1::new();
4997 PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[42; 32]).unwrap())
5001 fn first_hop(node_id: PublicKey) -> ChannelDetails {
5003 channel_id: [0; 32],
5004 counterparty: ChannelCounterparty {
5005 features: InitFeatures::known(),
5007 unspendable_punishment_reserve: 0,
5008 forwarding_info: None,
5010 funding_txo: Some(OutPoint {
5011 txid: bitcoin::Txid::from_slice(&[0; 32]).unwrap(), index: 0
5013 short_channel_id: Some(1),
5014 channel_value_satoshis: 10_000_000,
5016 balance_msat: 10_000_000,
5017 outbound_capacity_msat: 10_000_000,
5018 inbound_capacity_msat: 0,
5019 unspendable_punishment_reserve: None,
5020 confirmations_required: None,
5021 force_close_spend_delay: None,
5023 is_funding_locked: true,
5030 fn generate_routes_with_zero_penalty_scorer(bench: &mut Bencher) {
5031 let network_graph = read_network_graph();
5032 let scorer = ZeroPenaltyScorer;
5033 generate_routes(bench, &network_graph, scorer, InvoiceFeatures::empty());
5037 fn generate_mpp_routes_with_zero_penalty_scorer(bench: &mut Bencher) {
5038 let network_graph = read_network_graph();
5039 let scorer = ZeroPenaltyScorer;
5040 generate_routes(bench, &network_graph, scorer, InvoiceFeatures::known());
5044 fn generate_routes_with_default_scorer(bench: &mut Bencher) {
5045 let network_graph = read_network_graph();
5046 let scorer = Scorer::default();
5047 generate_routes(bench, &network_graph, scorer, InvoiceFeatures::empty());
5051 fn generate_mpp_routes_with_default_scorer(bench: &mut Bencher) {
5052 let network_graph = read_network_graph();
5053 let scorer = Scorer::default();
5054 generate_routes(bench, &network_graph, scorer, InvoiceFeatures::known());
5057 fn generate_routes<S: Score>(
5058 bench: &mut Bencher, graph: &NetworkGraph, mut scorer: S, features: InvoiceFeatures
5060 let nodes = graph.read_only().nodes().clone();
5061 let payer = payer_pubkey();
5063 // First, get 100 (source, destination) pairs for which route-getting actually succeeds...
5064 let mut routes = Vec::new();
5065 let mut route_endpoints = Vec::new();
5066 let mut seed: usize = 0xdeadbeef;
5067 'load_endpoints: for _ in 0..100 {
5070 let src = PublicKey::from_slice(nodes.keys().skip(seed % nodes.len()).next().unwrap().as_slice()).unwrap();
5072 let dst = PublicKey::from_slice(nodes.keys().skip(seed % nodes.len()).next().unwrap().as_slice()).unwrap();
5073 let payee = Payee::from_node_id(dst).with_features(features.clone());
5074 let first_hop = first_hop(src);
5075 let amt = seed as u64 % 1_000_000;
5076 if let Ok(route) = get_route(&payer, &payee, &graph, Some(&[&first_hop]), amt, 42, &DummyLogger{}, &scorer) {
5078 route_endpoints.push((first_hop, payee, amt));
5079 continue 'load_endpoints;
5084 // ...and seed the scorer with success and failure data...
5085 for route in routes {
5086 let amount = route.get_total_amount();
5087 if amount < 250_000 {
5088 for path in route.paths {
5089 scorer.payment_path_successful(&path.iter().collect::<Vec<_>>());
5091 } else if amount > 750_000 {
5092 for path in route.paths {
5093 let short_channel_id = path[path.len() / 2].short_channel_id;
5094 scorer.payment_path_failed(&path.iter().collect::<Vec<_>>(), short_channel_id);
5099 // ...then benchmark finding paths between the nodes we learned.
5102 let (first_hop, payee, amt) = &route_endpoints[idx % route_endpoints.len()];
5103 assert!(get_route(&payer, payee, &graph, Some(&[first_hop]), *amt, 42, &DummyLogger{}, &scorer).is_ok());