1 // This file is Copyright its original authors, visible in version control
4 // This file is licensed under the Apache License, Version 2.0 <LICENSE-APACHE
5 // or http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
6 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your option.
7 // You may not use this file except in accordance with one or both of these
10 //! The top-level routing/network map tracking logic lives here.
12 //! You probably want to create a NetGraphMsgHandler and use that as your RoutingMessageHandler and then
13 //! interrogate it to get routes for your own payments.
15 use bitcoin::secp256k1::key::PublicKey;
17 use ln::channelmanager::ChannelDetails;
18 use ln::features::{ChannelFeatures, InvoiceFeatures, NodeFeatures};
19 use ln::msgs::{DecodeError, ErrorAction, LightningError, MAX_VALUE_MSAT};
21 use routing::network_graph::{NetworkGraph, NodeId, RoutingFees};
22 use util::ser::{Writeable, Readable};
23 use util::logger::{Level, Logger};
27 use alloc::collections::BinaryHeap;
32 #[derive(Clone, Debug, Hash, PartialEq, Eq)]
34 /// The node_id of the node at this hop.
35 pub pubkey: PublicKey,
36 /// The node_announcement features of the node at this hop. For the last hop, these may be
37 /// amended to match the features present in the invoice this node generated.
38 pub node_features: NodeFeatures,
39 /// The channel that should be used from the previous hop to reach this node.
40 pub short_channel_id: u64,
41 /// The channel_announcement features of the channel that should be used from the previous hop
42 /// to reach this node.
43 pub channel_features: ChannelFeatures,
44 /// The fee taken on this hop (for paying for the use of the *next* channel in the path).
45 /// For the last hop, this should be the full value of the payment (might be more than
46 /// requested if we had to match htlc_minimum_msat).
48 /// The CLTV delta added for this hop. For the last hop, this should be the full CLTV value
49 /// expected at the destination, in excess of the current block height.
50 pub cltv_expiry_delta: u32,
53 impl_writeable_tlv_based!(RouteHop, {
54 (0, pubkey, required),
55 (2, node_features, required),
56 (4, short_channel_id, required),
57 (6, channel_features, required),
58 (8, fee_msat, required),
59 (10, cltv_expiry_delta, required),
62 /// A route directs a payment from the sender (us) to the recipient. If the recipient supports MPP,
63 /// it can take multiple paths. Each path is composed of one or more hops through the network.
64 #[derive(Clone, Hash, PartialEq, Eq)]
66 /// The list of routes taken for a single (potentially-)multi-part payment. The pubkey of the
67 /// last RouteHop in each path must be the same.
68 /// Each entry represents a list of hops, NOT INCLUDING our own, where the last hop is the
69 /// destination. Thus, this must always be at least length one. While the maximum length of any
70 /// given path is variable, keeping the length of any path to less than 20 should currently
71 /// ensure it is viable.
72 pub paths: Vec<Vec<RouteHop>>,
76 /// Returns the total amount of fees paid on this [`Route`].
78 /// This doesn't include any extra payment made to the recipient, which can happen in excess of
79 /// the amount passed to [`get_route`]'s `final_value_msat`.
80 pub fn get_total_fees(&self) -> u64 {
81 // Do not count last hop of each path since that's the full value of the payment
82 return self.paths.iter()
83 .flat_map(|path| path.split_last().map(|(_, path_prefix)| path_prefix).unwrap_or(&[]))
84 .map(|hop| &hop.fee_msat)
88 /// Returns the total amount paid on this [`Route`], excluding the fees.
89 pub fn get_total_amount(&self) -> u64 {
90 return self.paths.iter()
91 .map(|path| path.split_last().map(|(hop, _)| hop.fee_msat).unwrap_or(0))
96 const SERIALIZATION_VERSION: u8 = 1;
97 const MIN_SERIALIZATION_VERSION: u8 = 1;
99 impl Writeable for Route {
100 fn write<W: ::util::ser::Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
101 write_ver_prefix!(writer, SERIALIZATION_VERSION, MIN_SERIALIZATION_VERSION);
102 (self.paths.len() as u64).write(writer)?;
103 for hops in self.paths.iter() {
104 (hops.len() as u8).write(writer)?;
105 for hop in hops.iter() {
109 write_tlv_fields!(writer, {});
114 impl Readable for Route {
115 fn read<R: io::Read>(reader: &mut R) -> Result<Route, DecodeError> {
116 let _ver = read_ver_prefix!(reader, SERIALIZATION_VERSION);
117 let path_count: u64 = Readable::read(reader)?;
118 let mut paths = Vec::with_capacity(cmp::min(path_count, 128) as usize);
119 for _ in 0..path_count {
120 let hop_count: u8 = Readable::read(reader)?;
121 let mut hops = Vec::with_capacity(hop_count as usize);
122 for _ in 0..hop_count {
123 hops.push(Readable::read(reader)?);
127 read_tlv_fields!(reader, {});
132 /// Parameters needed to re-compute a [`Route`] for retrying a failed payment path.
134 /// Provided in [`Event::PaymentPathFailed`] and passed to [`get_retry_route`].
136 /// [`Event::PaymentPathFailed`]: crate::util::events::Event::PaymentPathFailed
137 #[derive(Clone, Debug)]
138 pub struct PaymentPathRetry {
139 /// The recipient of the failed payment path.
142 /// The amount in msats sent on the failed payment path.
143 pub final_value_msat: u64,
145 /// The CLTV on the final hop of the failed payment path.
146 pub final_cltv_expiry_delta: u32,
149 impl_writeable_tlv_based!(PaymentPathRetry, {
150 (0, payee, required),
151 (2, final_value_msat, required),
152 (4, final_cltv_expiry_delta, required),
155 /// The recipient of a payment.
156 #[derive(Clone, Debug)]
158 /// The node id of the payee.
161 /// Features supported by the payee.
163 /// May be set from the payee's invoice or via [`for_keysend`]. May be `None` if the invoice
164 /// does not contain any features.
166 /// [`for_keysend`]: Self::for_keysend
167 pub features: Option<InvoiceFeatures>,
169 /// Hints for routing to the payee, containing channels connecting the payee to public nodes.
170 pub route_hints: Vec<RouteHint>,
173 impl_writeable_tlv_based!(Payee, {
174 (0, pubkey, required),
175 (2, features, option),
176 (4, route_hints, vec_type),
180 /// Creates a payee with the node id of the given `pubkey`.
181 pub fn new(pubkey: PublicKey) -> Self {
189 /// Creates a payee with the node id of the given `pubkey` to use for keysend payments.
190 pub fn for_keysend(pubkey: PublicKey) -> Self {
191 Self::new(pubkey).with_features(InvoiceFeatures::for_keysend())
194 /// Includes the payee's features.
196 /// (C-not exported) since bindings don't support move semantics
197 pub fn with_features(self, features: InvoiceFeatures) -> Self {
198 Self { features: Some(features), ..self }
201 /// Includes hints for routing to the payee.
203 /// (C-not exported) since bindings don't support move semantics
204 pub fn with_route_hints(self, route_hints: Vec<RouteHint>) -> Self {
205 Self { route_hints, ..self }
209 /// A list of hops along a payment path terminating with a channel to the recipient.
210 #[derive(Clone, Debug, Hash, Eq, PartialEq)]
211 pub struct RouteHint(pub Vec<RouteHintHop>);
214 impl Writeable for RouteHint {
215 fn write<W: ::util::ser::Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
216 (self.0.len() as u64).write(writer)?;
217 for hop in self.0.iter() {
224 impl Readable for RouteHint {
225 fn read<R: io::Read>(reader: &mut R) -> Result<Self, DecodeError> {
226 let hop_count: u64 = Readable::read(reader)?;
227 let mut hops = Vec::with_capacity(cmp::min(hop_count, 16) as usize);
228 for _ in 0..hop_count {
229 hops.push(Readable::read(reader)?);
235 /// A channel descriptor for a hop along a payment path.
236 #[derive(Clone, Debug, Hash, Eq, PartialEq)]
237 pub struct RouteHintHop {
238 /// The node_id of the non-target end of the route
239 pub src_node_id: PublicKey,
240 /// The short_channel_id of this channel
241 pub short_channel_id: u64,
242 /// The fees which must be paid to use this channel
243 pub fees: RoutingFees,
244 /// The difference in CLTV values between this node and the next node.
245 pub cltv_expiry_delta: u16,
246 /// The minimum value, in msat, which must be relayed to the next hop.
247 pub htlc_minimum_msat: Option<u64>,
248 /// The maximum value in msat available for routing with a single HTLC.
249 pub htlc_maximum_msat: Option<u64>,
252 impl_writeable_tlv_based!(RouteHintHop, {
253 (0, src_node_id, required),
254 (1, htlc_minimum_msat, option),
255 (2, short_channel_id, required),
256 (3, htlc_maximum_msat, option),
258 (6, cltv_expiry_delta, required),
261 #[derive(Eq, PartialEq)]
262 struct RouteGraphNode {
264 lowest_fee_to_peer_through_node: u64,
265 lowest_fee_to_node: u64,
266 // The maximum value a yet-to-be-constructed payment path might flow through this node.
267 // This value is upper-bounded by us by:
268 // - how much is needed for a path being constructed
269 // - how much value can channels following this node (up to the destination) can contribute,
270 // considering their capacity and fees
271 value_contribution_msat: u64,
272 /// The effective htlc_minimum_msat at this hop. If a later hop on the path had a higher HTLC
273 /// minimum, we use it, plus the fees required at each earlier hop to meet it.
274 path_htlc_minimum_msat: u64,
275 /// All penalties incurred from this hop on the way to the destination, as calculated using
277 path_penalty_msat: u64,
280 impl cmp::Ord for RouteGraphNode {
281 fn cmp(&self, other: &RouteGraphNode) -> cmp::Ordering {
282 let other_score = cmp::max(other.lowest_fee_to_peer_through_node, other.path_htlc_minimum_msat)
283 .checked_add(other.path_penalty_msat)
284 .unwrap_or_else(|| u64::max_value());
285 let self_score = cmp::max(self.lowest_fee_to_peer_through_node, self.path_htlc_minimum_msat)
286 .checked_add(self.path_penalty_msat)
287 .unwrap_or_else(|| u64::max_value());
288 other_score.cmp(&self_score).then_with(|| other.node_id.cmp(&self.node_id))
292 impl cmp::PartialOrd for RouteGraphNode {
293 fn partial_cmp(&self, other: &RouteGraphNode) -> Option<cmp::Ordering> {
294 Some(self.cmp(other))
298 struct DummyDirectionalChannelInfo {
299 cltv_expiry_delta: u32,
300 htlc_minimum_msat: u64,
301 htlc_maximum_msat: Option<u64>,
305 /// It's useful to keep track of the hops associated with the fees required to use them,
306 /// so that we can choose cheaper paths (as per Dijkstra's algorithm).
307 /// Fee values should be updated only in the context of the whole path, see update_value_and_recompute_fees.
308 /// These fee values are useful to choose hops as we traverse the graph "payee-to-payer".
309 #[derive(Clone, Debug)]
310 struct PathBuildingHop<'a> {
311 // The RouteHintHop fields which will eventually be used if this hop is used in a final Route.
312 // Note that node_features is calculated separately after our initial graph walk.
314 short_channel_id: u64,
315 channel_features: &'a ChannelFeatures,
317 cltv_expiry_delta: u32,
319 /// Minimal fees required to route to the source node of the current hop via any of its inbound channels.
320 src_lowest_inbound_fees: RoutingFees,
321 /// Fees of the channel used in this hop.
322 channel_fees: RoutingFees,
323 /// All the fees paid *after* this channel on the way to the destination
324 next_hops_fee_msat: u64,
325 /// Fee paid for the use of the current channel (see channel_fees).
326 /// The value will be actually deducted from the counterparty balance on the previous link.
327 hop_use_fee_msat: u64,
328 /// Used to compare channels when choosing the for routing.
329 /// Includes paying for the use of a hop and the following hops, as well as
330 /// an estimated cost of reaching this hop.
331 /// Might get stale when fees are recomputed. Primarily for internal use.
333 /// This is useful for update_value_and_recompute_fees to make sure
334 /// we don't fall below the minimum. Should not be updated manually and
335 /// generally should not be accessed.
336 htlc_minimum_msat: u64,
337 /// A mirror of the same field in RouteGraphNode. Note that this is only used during the graph
338 /// walk and may be invalid thereafter.
339 path_htlc_minimum_msat: u64,
340 /// All penalties incurred from this channel on the way to the destination, as calculated using
342 path_penalty_msat: u64,
343 /// If we've already processed a node as the best node, we shouldn't process it again. Normally
344 /// we'd just ignore it if we did as all channels would have a higher new fee, but because we
345 /// may decrease the amounts in use as we walk the graph, the actual calculated fee may
346 /// decrease as well. Thus, we have to explicitly track which nodes have been processed and
347 /// avoid processing them again.
349 #[cfg(any(test, feature = "fuzztarget"))]
350 // In tests, we apply further sanity checks on cases where we skip nodes we already processed
351 // to ensure it is specifically in cases where the fee has gone down because of a decrease in
352 // value_contribution_msat, which requires tracking it here. See comments below where it is
353 // used for more info.
354 value_contribution_msat: u64,
357 // Instantiated with a list of hops with correct data in them collected during path finding,
358 // an instance of this struct should be further modified only via given methods.
360 struct PaymentPath<'a> {
361 hops: Vec<(PathBuildingHop<'a>, NodeFeatures)>,
364 impl<'a> PaymentPath<'a> {
365 // TODO: Add a value_msat field to PaymentPath and use it instead of this function.
366 fn get_value_msat(&self) -> u64 {
367 self.hops.last().unwrap().0.fee_msat
370 fn get_total_fee_paid_msat(&self) -> u64 {
371 if self.hops.len() < 1 {
375 // Can't use next_hops_fee_msat because it gets outdated.
376 for (i, (hop, _)) in self.hops.iter().enumerate() {
377 if i != self.hops.len() - 1 {
378 result += hop.fee_msat;
384 // If the amount transferred by the path is updated, the fees should be adjusted. Any other way
385 // to change fees may result in an inconsistency.
387 // Sometimes we call this function right after constructing a path which is inconsistent in
388 // that it the value being transferred has decreased while we were doing path finding, leading
389 // to the fees being paid not lining up with the actual limits.
391 // Note that this function is not aware of the available_liquidity limit, and thus does not
392 // support increasing the value being transferred.
393 fn update_value_and_recompute_fees(&mut self, value_msat: u64) {
394 assert!(value_msat <= self.hops.last().unwrap().0.fee_msat);
396 let mut total_fee_paid_msat = 0 as u64;
397 for i in (0..self.hops.len()).rev() {
398 let last_hop = i == self.hops.len() - 1;
400 // For non-last-hop, this value will represent the fees paid on the current hop. It
401 // will consist of the fees for the use of the next hop, and extra fees to match
402 // htlc_minimum_msat of the current channel. Last hop is handled separately.
403 let mut cur_hop_fees_msat = 0;
405 cur_hop_fees_msat = self.hops.get(i + 1).unwrap().0.hop_use_fee_msat;
408 let mut cur_hop = &mut self.hops.get_mut(i).unwrap().0;
409 cur_hop.next_hops_fee_msat = total_fee_paid_msat;
410 // Overpay in fees if we can't save these funds due to htlc_minimum_msat.
411 // We try to account for htlc_minimum_msat in scoring (add_entry!), so that nodes don't
412 // set it too high just to maliciously take more fees by exploiting this
413 // match htlc_minimum_msat logic.
414 let mut cur_hop_transferred_amount_msat = total_fee_paid_msat + value_msat;
415 if let Some(extra_fees_msat) = cur_hop.htlc_minimum_msat.checked_sub(cur_hop_transferred_amount_msat) {
416 // Note that there is a risk that *previous hops* (those closer to us, as we go
417 // payee->our_node here) would exceed their htlc_maximum_msat or available balance.
419 // This might make us end up with a broken route, although this should be super-rare
420 // in practice, both because of how healthy channels look like, and how we pick
421 // channels in add_entry.
422 // Also, this can't be exploited more heavily than *announce a free path and fail
424 cur_hop_transferred_amount_msat += extra_fees_msat;
425 total_fee_paid_msat += extra_fees_msat;
426 cur_hop_fees_msat += extra_fees_msat;
430 // Final hop is a special case: it usually has just value_msat (by design), but also
431 // it still could overpay for the htlc_minimum_msat.
432 cur_hop.fee_msat = cur_hop_transferred_amount_msat;
434 // Propagate updated fees for the use of the channels to one hop back, where they
435 // will be actually paid (fee_msat). The last hop is handled above separately.
436 cur_hop.fee_msat = cur_hop_fees_msat;
439 // Fee for the use of the current hop which will be deducted on the previous hop.
440 // Irrelevant for the first hop, as it doesn't have the previous hop, and the use of
441 // this channel is free for us.
443 if let Some(new_fee) = compute_fees(cur_hop_transferred_amount_msat, cur_hop.channel_fees) {
444 cur_hop.hop_use_fee_msat = new_fee;
445 total_fee_paid_msat += new_fee;
447 // It should not be possible because this function is called only to reduce the
448 // value. In that case, compute_fee was already called with the same fees for
449 // larger amount and there was no overflow.
457 fn compute_fees(amount_msat: u64, channel_fees: RoutingFees) -> Option<u64> {
458 let proportional_fee_millions =
459 amount_msat.checked_mul(channel_fees.proportional_millionths as u64);
460 if let Some(new_fee) = proportional_fee_millions.and_then(|part| {
461 (channel_fees.base_msat as u64).checked_add(part / 1_000_000) }) {
465 // This function may be (indirectly) called without any verification,
466 // with channel_fees provided by a caller. We should handle it gracefully.
471 /// Gets a keysend route from us (payer) to the given target node (payee). This is needed because
472 /// keysend payments do not have an invoice from which to pull the payee's supported features, which
473 /// makes it tricky to otherwise supply the `payee` parameter of `get_route`.
474 pub fn get_keysend_route<L: Deref, S: routing::Score>(
475 our_node_pubkey: &PublicKey, network: &NetworkGraph, payee: &PublicKey,
476 first_hops: Option<&[&ChannelDetails]>, last_hops: &[&RouteHint], final_value_msat: u64,
477 final_cltv_expiry_delta: u32, logger: L, scorer: &S
478 ) -> Result<Route, LightningError>
479 where L::Target: Logger {
480 let route_hints = last_hops.iter().map(|hint| (*hint).clone()).collect();
481 let payee = Payee::for_keysend(*payee).with_route_hints(route_hints);
483 our_node_pubkey, &payee, network, first_hops, final_value_msat, final_cltv_expiry_delta,
488 /// Gets a route suitable for retrying a failed payment path.
490 /// Used to re-compute a [`Route`] when handling a [`Event::PaymentPathFailed`]. Any adjustments to
491 /// the [`NetworkGraph`] and channel scores should be made prior to calling this function.
493 /// [`Event::PaymentPathFailed`]: crate::util::events::Event::PaymentPathFailed
494 pub fn get_retry_route<L: Deref, S: routing::Score>(
495 our_node_pubkey: &PublicKey, retry: &PaymentPathRetry, network: &NetworkGraph,
496 first_hops: Option<&[&ChannelDetails]>, logger: L, scorer: &S
497 ) -> Result<Route, LightningError>
498 where L::Target: Logger {
500 our_node_pubkey, &retry.payee, network, first_hops, retry.final_value_msat,
501 retry.final_cltv_expiry_delta, logger, scorer
505 /// Gets a route from us (payer) to the given target node (payee).
507 /// If the payee provided features in their invoice, they should be provided via `payee`. Without
508 /// this, MPP will only be used if the payee's features are available in the network graph.
510 /// Private routing paths between a public node and the target may be included in `payee`.
512 /// If some channels aren't announced, it may be useful to fill in a first_hops with the
513 /// results from a local ChannelManager::list_usable_channels() call. If it is filled in, our
514 /// view of our local channels (from net_graph_msg_handler) will be ignored, and only those
515 /// in first_hops will be used.
517 /// Panics if first_hops contains channels without short_channel_ids
518 /// (ChannelManager::list_usable_channels will never include such channels).
520 /// The fees on channels from us to next-hops are ignored (as they are assumed to all be
521 /// equal), however the enabled/disabled bit on such channels as well as the
522 /// htlc_minimum_msat/htlc_maximum_msat *are* checked as they may change based on the receiving node.
523 pub fn get_route<L: Deref, S: routing::Score>(
524 our_node_pubkey: &PublicKey, payee: &Payee, network: &NetworkGraph,
525 first_hops: Option<&[&ChannelDetails]>, final_value_msat: u64, final_cltv_expiry_delta: u32,
526 logger: L, scorer: &S
527 ) -> Result<Route, LightningError>
528 where L::Target: Logger {
529 let payee_node_id = NodeId::from_pubkey(&payee.pubkey);
530 let our_node_id = NodeId::from_pubkey(&our_node_pubkey);
532 if payee_node_id == our_node_id {
533 return Err(LightningError{err: "Cannot generate a route to ourselves".to_owned(), action: ErrorAction::IgnoreError});
536 if final_value_msat > MAX_VALUE_MSAT {
537 return Err(LightningError{err: "Cannot generate a route of more value than all existing satoshis".to_owned(), action: ErrorAction::IgnoreError});
540 if final_value_msat == 0 {
541 return Err(LightningError{err: "Cannot send a payment of 0 msat".to_owned(), action: ErrorAction::IgnoreError});
544 for route in payee.route_hints.iter() {
545 for hop in &route.0 {
546 if hop.src_node_id == payee.pubkey {
547 return Err(LightningError{err: "Route hint cannot have the payee as the source.".to_owned(), action: ErrorAction::IgnoreError});
552 // The general routing idea is the following:
553 // 1. Fill first/last hops communicated by the caller.
554 // 2. Attempt to construct a path from payer to payee for transferring
555 // any ~sufficient (described later) value.
556 // If succeed, remember which channels were used and how much liquidity they have available,
557 // so that future paths don't rely on the same liquidity.
558 // 3. Prooceed to the next step if:
559 // - we hit the recommended target value;
560 // - OR if we could not construct a new path. Any next attempt will fail too.
561 // Otherwise, repeat step 2.
562 // 4. See if we managed to collect paths which aggregately are able to transfer target value
563 // (not recommended value). If yes, proceed. If not, fail routing.
564 // 5. Randomly combine paths into routes having enough to fulfill the payment. (TODO: knapsack)
565 // 6. Of all the found paths, select only those with the lowest total fee.
566 // 7. The last path in every selected route is likely to be more than we need.
567 // Reduce its value-to-transfer and recompute fees.
568 // 8. Choose the best route by the lowest total fee.
570 // As for the actual search algorithm,
571 // we do a payee-to-payer pseudo-Dijkstra's sorting by each node's distance from the payee
572 // plus the minimum per-HTLC fee to get from it to another node (aka "shitty pseudo-A*").
574 // We are not a faithful Dijkstra's implementation because we can change values which impact
575 // earlier nodes while processing later nodes. Specifically, if we reach a channel with a lower
576 // liquidity limit (via htlc_maximum_msat, on-chain capacity or assumed liquidity limits) then
577 // the value we are currently attempting to send over a path, we simply reduce the value being
578 // sent along the path for any hops after that channel. This may imply that later fees (which
579 // we've already tabulated) are lower because a smaller value is passing through the channels
580 // (and the proportional fee is thus lower). There isn't a trivial way to recalculate the
581 // channels which were selected earlier (and which may still be used for other paths without a
582 // lower liquidity limit), so we simply accept that some liquidity-limited paths may be
585 // One potentially problematic case for this algorithm would be if there are many
586 // liquidity-limited paths which are liquidity-limited near the destination (ie early in our
587 // graph walking), we may never find a path which is not liquidity-limited and has lower
588 // proportional fee (and only lower absolute fee when considering the ultimate value sent).
589 // Because we only consider paths with at least 5% of the total value being sent, the damage
590 // from such a case should be limited, however this could be further reduced in the future by
591 // calculating fees on the amount we wish to route over a path, ie ignoring the liquidity
592 // limits for the purposes of fee calculation.
594 // Alternatively, we could store more detailed path information in the heap (targets, below)
595 // and index the best-path map (dist, below) by node *and* HTLC limits, however that would blow
596 // up the runtime significantly both algorithmically (as we'd traverse nodes multiple times)
597 // and practically (as we would need to store dynamically-allocated path information in heap
598 // objects, increasing malloc traffic and indirect memory access significantly). Further, the
599 // results of such an algorithm would likely be biased towards lower-value paths.
601 // Further, we could return to a faithful Dijkstra's algorithm by rejecting paths with limits
602 // outside of our current search value, running a path search more times to gather candidate
603 // paths at different values. While this may be acceptable, further path searches may increase
604 // runtime for little gain. Specifically, the current algorithm rather efficiently explores the
605 // graph for candidate paths, calculating the maximum value which can realistically be sent at
606 // the same time, remaining generic across different payment values.
608 // TODO: There are a few tweaks we could do, including possibly pre-calculating more stuff
609 // to use as the A* heuristic beyond just the cost to get one node further than the current
612 let network_graph = network.read_only();
613 let network_channels = network_graph.channels();
614 let network_nodes = network_graph.nodes();
615 let dummy_directional_info = DummyDirectionalChannelInfo { // used for first_hops routes
616 cltv_expiry_delta: 0,
617 htlc_minimum_msat: 0,
618 htlc_maximum_msat: None,
621 proportional_millionths: 0,
625 // Allow MPP only if we have a features set from somewhere that indicates the payee supports
626 // it. If the payee supports it they're supposed to include it in the invoice, so that should
628 let allow_mpp = if let Some(features) = &payee.features {
629 features.supports_basic_mpp()
630 } else if let Some(node) = network_nodes.get(&payee_node_id) {
631 if let Some(node_info) = node.announcement_info.as_ref() {
632 node_info.features.supports_basic_mpp()
635 log_trace!(logger, "Searching for a route from payer {} to payee {} {} MPP", our_node_pubkey,
636 payee.pubkey, if allow_mpp { "with" } else { "without" });
639 // Prepare the data we'll use for payee-to-payer search by
640 // inserting first hops suggested by the caller as targets.
641 // Our search will then attempt to reach them while traversing from the payee node.
642 let mut first_hop_targets: HashMap<_, Vec<(_, ChannelFeatures, _, NodeFeatures)>> =
643 HashMap::with_capacity(if first_hops.is_some() { first_hops.as_ref().unwrap().len() } else { 0 });
644 if let Some(hops) = first_hops {
646 let short_channel_id = chan.short_channel_id.expect("first_hops should be filled in with usable channels, not pending ones");
647 if chan.counterparty.node_id == *our_node_pubkey {
648 return Err(LightningError{err: "First hop cannot have our_node_pubkey as a destination.".to_owned(), action: ErrorAction::IgnoreError});
650 first_hop_targets.entry(NodeId::from_pubkey(&chan.counterparty.node_id)).or_insert(Vec::new())
651 .push((short_channel_id, chan.counterparty.features.to_context(), chan.outbound_capacity_msat, chan.counterparty.features.to_context()));
653 if first_hop_targets.is_empty() {
654 return Err(LightningError{err: "Cannot route when there are no outbound routes away from us".to_owned(), action: ErrorAction::IgnoreError});
658 let empty_channel_features = ChannelFeatures::empty();
660 // The main heap containing all candidate next-hops sorted by their score (max(A* fee,
661 // htlc_minimum)). Ideally this would be a heap which allowed cheap score reduction instead of
662 // adding duplicate entries when we find a better path to a given node.
663 let mut targets = BinaryHeap::new();
665 // Map from node_id to information about the best current path to that node, including feerate
667 let mut dist = HashMap::with_capacity(network_nodes.len());
669 // During routing, if we ignore a path due to an htlc_minimum_msat limit, we set this,
670 // indicating that we may wish to try again with a higher value, potentially paying to meet an
671 // htlc_minimum with extra fees while still finding a cheaper path.
672 let mut hit_minimum_limit;
674 // When arranging a route, we select multiple paths so that we can make a multi-path payment.
675 // We start with a path_value of the exact amount we want, and if that generates a route we may
676 // return it immediately. Otherwise, we don't stop searching for paths until we have 3x the
677 // amount we want in total across paths, selecting the best subset at the end.
678 const ROUTE_CAPACITY_PROVISION_FACTOR: u64 = 3;
679 let recommended_value_msat = final_value_msat * ROUTE_CAPACITY_PROVISION_FACTOR as u64;
680 let mut path_value_msat = final_value_msat;
682 // We don't want multiple paths (as per MPP) share liquidity of the same channels.
683 // This map allows paths to be aware of the channel use by other paths in the same call.
684 // This would help to make a better path finding decisions and not "overbook" channels.
685 // It is unaware of the directions (except for `outbound_capacity_msat` in `first_hops`).
686 let mut bookkeeped_channels_liquidity_available_msat = HashMap::with_capacity(network_nodes.len());
688 // Keeping track of how much value we already collected across other paths. Helps to decide:
689 // - how much a new path should be transferring (upper bound);
690 // - whether a channel should be disregarded because
691 // it's available liquidity is too small comparing to how much more we need to collect;
692 // - when we want to stop looking for new paths.
693 let mut already_collected_value_msat = 0;
695 log_trace!(logger, "Building path from {} (payee) to {} (us/payer) for value {} msat.", payee.pubkey, our_node_pubkey, final_value_msat);
697 macro_rules! add_entry {
698 // Adds entry which goes from $src_node_id to $dest_node_id
699 // over the channel with id $chan_id with fees described in
700 // $directional_info.
701 // $next_hops_fee_msat represents the fees paid for using all the channel *after* this one,
702 // since that value has to be transferred over this channel.
703 // Returns whether this channel caused an update to `targets`.
704 ( $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,
705 $next_hops_value_contribution: expr, $next_hops_path_htlc_minimum_msat: expr, $next_hops_path_penalty_msat: expr ) => { {
706 // We "return" whether we updated the path at the end, via this:
707 let mut did_add_update_path_to_src_node = false;
708 // Channels to self should not be used. This is more of belt-and-suspenders, because in
709 // practice these cases should be caught earlier:
710 // - for regular channels at channel announcement (TODO)
711 // - for first and last hops early in get_route
712 if $src_node_id != $dest_node_id.clone() {
713 let available_liquidity_msat = bookkeeped_channels_liquidity_available_msat.entry($chan_id.clone()).or_insert_with(|| {
714 let mut initial_liquidity_available_msat = None;
715 if let Some(capacity_sats) = $capacity_sats {
716 initial_liquidity_available_msat = Some(capacity_sats * 1000);
719 if let Some(htlc_maximum_msat) = $directional_info.htlc_maximum_msat {
720 if let Some(available_msat) = initial_liquidity_available_msat {
721 initial_liquidity_available_msat = Some(cmp::min(available_msat, htlc_maximum_msat));
723 initial_liquidity_available_msat = Some(htlc_maximum_msat);
727 match initial_liquidity_available_msat {
728 Some(available_msat) => available_msat,
729 // We assume channels with unknown balance have
730 // a capacity of 0.0025 BTC (or 250_000 sats).
731 None => 250_000 * 1000
735 // It is tricky to substract $next_hops_fee_msat from available liquidity here.
736 // It may be misleading because we might later choose to reduce the value transferred
737 // over these channels, and the channel which was insufficient might become sufficient.
738 // Worst case: we drop a good channel here because it can't cover the high following
739 // fees caused by one expensive channel, but then this channel could have been used
740 // if the amount being transferred over this path is lower.
741 // We do this for now, but this is a subject for removal.
742 if let Some(available_value_contribution_msat) = available_liquidity_msat.checked_sub($next_hops_fee_msat) {
744 // Routing Fragmentation Mitigation heuristic:
746 // Routing fragmentation across many payment paths increases the overall routing
747 // fees as you have irreducible routing fees per-link used (`fee_base_msat`).
748 // Taking too many smaller paths also increases the chance of payment failure.
749 // Thus to avoid this effect, we require from our collected links to provide
750 // at least a minimal contribution to the recommended value yet-to-be-fulfilled.
752 // This requirement is currently 5% of the remaining-to-be-collected value.
753 // This means as we successfully advance in our collection,
754 // the absolute liquidity contribution is lowered,
755 // thus increasing the number of potential channels to be selected.
757 // Derive the minimal liquidity contribution with a ratio of 20 (5%, rounded up)
758 // or 100% if we're not allowed to do multipath payments.
759 let minimal_value_contribution_msat: u64 = if allow_mpp {
760 (recommended_value_msat - already_collected_value_msat + 19) / 20
764 // Verify the liquidity offered by this channel complies to the minimal contribution.
765 let contributes_sufficient_value = available_value_contribution_msat >= minimal_value_contribution_msat;
767 let value_contribution_msat = cmp::min(available_value_contribution_msat, $next_hops_value_contribution);
768 // Includes paying fees for the use of the following channels.
769 let amount_to_transfer_over_msat: u64 = match value_contribution_msat.checked_add($next_hops_fee_msat) {
770 Some(result) => result,
771 // Can't overflow due to how the values were computed right above.
772 None => unreachable!(),
774 #[allow(unused_comparisons)] // $next_hops_path_htlc_minimum_msat is 0 in some calls so rustc complains
775 let over_path_minimum_msat = amount_to_transfer_over_msat >= $directional_info.htlc_minimum_msat &&
776 amount_to_transfer_over_msat >= $next_hops_path_htlc_minimum_msat;
778 // If HTLC minimum is larger than the amount we're going to transfer, we shouldn't
779 // bother considering this channel.
780 // Since we're choosing amount_to_transfer_over_msat as maximum possible, it can
781 // be only reduced later (not increased), so this channel should just be skipped
782 // as not sufficient.
783 if !over_path_minimum_msat {
784 hit_minimum_limit = true;
785 } else if contributes_sufficient_value {
786 // Note that low contribution here (limited by available_liquidity_msat)
787 // might violate htlc_minimum_msat on the hops which are next along the
788 // payment path (upstream to the payee). To avoid that, we recompute path
789 // path fees knowing the final path contribution after constructing it.
790 let path_htlc_minimum_msat = compute_fees($next_hops_path_htlc_minimum_msat, $directional_info.fees)
791 .and_then(|fee_msat| fee_msat.checked_add($next_hops_path_htlc_minimum_msat))
792 .map(|fee_msat| cmp::max(fee_msat, $directional_info.htlc_minimum_msat))
793 .unwrap_or_else(|| u64::max_value());
794 let hm_entry = dist.entry($src_node_id);
795 let old_entry = hm_entry.or_insert_with(|| {
796 // If there was previously no known way to access
797 // the source node (recall it goes payee-to-payer) of $chan_id, first add
798 // a semi-dummy record just to compute the fees to reach the source node.
799 // This will affect our decision on selecting $chan_id
800 // as a way to reach the $dest_node_id.
801 let mut fee_base_msat = u32::max_value();
802 let mut fee_proportional_millionths = u32::max_value();
803 if let Some(Some(fees)) = network_nodes.get(&$src_node_id).map(|node| node.lowest_inbound_channel_fees) {
804 fee_base_msat = fees.base_msat;
805 fee_proportional_millionths = fees.proportional_millionths;
808 node_id: $dest_node_id.clone(),
810 channel_features: $chan_features,
812 cltv_expiry_delta: 0,
813 src_lowest_inbound_fees: RoutingFees {
814 base_msat: fee_base_msat,
815 proportional_millionths: fee_proportional_millionths,
817 channel_fees: $directional_info.fees,
818 next_hops_fee_msat: u64::max_value(),
819 hop_use_fee_msat: u64::max_value(),
820 total_fee_msat: u64::max_value(),
821 htlc_minimum_msat: $directional_info.htlc_minimum_msat,
822 path_htlc_minimum_msat,
823 path_penalty_msat: u64::max_value(),
824 was_processed: false,
825 #[cfg(any(test, feature = "fuzztarget"))]
826 value_contribution_msat,
830 #[allow(unused_mut)] // We only use the mut in cfg(test)
831 let mut should_process = !old_entry.was_processed;
832 #[cfg(any(test, feature = "fuzztarget"))]
834 // In test/fuzzing builds, we do extra checks to make sure the skipping
835 // of already-seen nodes only happens in cases we expect (see below).
836 if !should_process { should_process = true; }
840 let mut hop_use_fee_msat = 0;
841 let mut total_fee_msat = $next_hops_fee_msat;
843 // Ignore hop_use_fee_msat for channel-from-us as we assume all channels-from-us
844 // will have the same effective-fee
845 if $src_node_id != our_node_id {
846 match compute_fees(amount_to_transfer_over_msat, $directional_info.fees) {
847 // max_value means we'll always fail
848 // the old_entry.total_fee_msat > total_fee_msat check
849 None => total_fee_msat = u64::max_value(),
851 hop_use_fee_msat = fee_msat;
852 total_fee_msat += hop_use_fee_msat;
853 // When calculating the lowest inbound fees to a node, we
854 // calculate fees here not based on the actual value we think
855 // will flow over this channel, but on the minimum value that
856 // we'll accept flowing over it. The minimum accepted value
857 // is a constant through each path collection run, ensuring
858 // consistent basis. Otherwise we may later find a
859 // different path to the source node that is more expensive,
860 // but which we consider to be cheaper because we are capacity
861 // constrained and the relative fee becomes lower.
862 match compute_fees(minimal_value_contribution_msat, old_entry.src_lowest_inbound_fees)
863 .map(|a| a.checked_add(total_fee_msat)) {
868 total_fee_msat = u64::max_value();
875 let path_penalty_msat = $next_hops_path_penalty_msat
876 .checked_add(scorer.channel_penalty_msat($chan_id.clone(), &$src_node_id, &$dest_node_id))
877 .unwrap_or_else(|| u64::max_value());
878 let new_graph_node = RouteGraphNode {
879 node_id: $src_node_id,
880 lowest_fee_to_peer_through_node: total_fee_msat,
881 lowest_fee_to_node: $next_hops_fee_msat as u64 + hop_use_fee_msat,
882 value_contribution_msat: value_contribution_msat,
883 path_htlc_minimum_msat,
887 // Update the way of reaching $src_node_id with the given $chan_id (from $dest_node_id),
888 // if this way is cheaper than the already known
889 // (considering the cost to "reach" this channel from the route destination,
890 // the cost of using this channel,
891 // and the cost of routing to the source node of this channel).
892 // Also, consider that htlc_minimum_msat_difference, because we might end up
893 // paying it. Consider the following exploit:
894 // we use 2 paths to transfer 1.5 BTC. One of them is 0-fee normal 1 BTC path,
895 // and for the other one we picked a 1sat-fee path with htlc_minimum_msat of
896 // 1 BTC. Now, since the latter is more expensive, we gonna try to cut it
897 // by 0.5 BTC, but then match htlc_minimum_msat by paying a fee of 0.5 BTC
899 // Ideally the scoring could be smarter (e.g. 0.5*htlc_minimum_msat here),
900 // but it may require additional tracking - we don't want to double-count
901 // the fees included in $next_hops_path_htlc_minimum_msat, but also
902 // can't use something that may decrease on future hops.
903 let old_cost = cmp::max(old_entry.total_fee_msat, old_entry.path_htlc_minimum_msat)
904 .checked_add(old_entry.path_penalty_msat)
905 .unwrap_or_else(|| u64::max_value());
906 let new_cost = cmp::max(total_fee_msat, path_htlc_minimum_msat)
907 .checked_add(path_penalty_msat)
908 .unwrap_or_else(|| u64::max_value());
910 if !old_entry.was_processed && new_cost < old_cost {
911 targets.push(new_graph_node);
912 old_entry.next_hops_fee_msat = $next_hops_fee_msat;
913 old_entry.hop_use_fee_msat = hop_use_fee_msat;
914 old_entry.total_fee_msat = total_fee_msat;
915 old_entry.node_id = $dest_node_id.clone();
916 old_entry.short_channel_id = $chan_id.clone();
917 old_entry.channel_features = $chan_features;
918 old_entry.fee_msat = 0; // This value will be later filled with hop_use_fee_msat of the following channel
919 old_entry.cltv_expiry_delta = $directional_info.cltv_expiry_delta as u32;
920 old_entry.channel_fees = $directional_info.fees;
921 old_entry.htlc_minimum_msat = $directional_info.htlc_minimum_msat;
922 old_entry.path_htlc_minimum_msat = path_htlc_minimum_msat;
923 old_entry.path_penalty_msat = path_penalty_msat;
924 #[cfg(any(test, feature = "fuzztarget"))]
926 old_entry.value_contribution_msat = value_contribution_msat;
928 did_add_update_path_to_src_node = true;
929 } else if old_entry.was_processed && new_cost < old_cost {
930 #[cfg(any(test, feature = "fuzztarget"))]
932 // If we're skipping processing a node which was previously
933 // processed even though we found another path to it with a
934 // cheaper fee, check that it was because the second path we
935 // found (which we are processing now) has a lower value
936 // contribution due to an HTLC minimum limit.
938 // e.g. take a graph with two paths from node 1 to node 2, one
939 // through channel A, and one through channel B. Channel A and
940 // B are both in the to-process heap, with their scores set by
941 // a higher htlc_minimum than fee.
942 // Channel A is processed first, and the channels onwards from
943 // node 1 are added to the to-process heap. Thereafter, we pop
944 // Channel B off of the heap, note that it has a much more
945 // restrictive htlc_maximum_msat, and recalculate the fees for
946 // all of node 1's channels using the new, reduced, amount.
948 // This would be bogus - we'd be selecting a higher-fee path
949 // with a lower htlc_maximum_msat instead of the one we'd
950 // already decided to use.
951 debug_assert!(path_htlc_minimum_msat < old_entry.path_htlc_minimum_msat);
953 value_contribution_msat + path_penalty_msat <
954 old_entry.value_contribution_msat + old_entry.path_penalty_msat
962 did_add_update_path_to_src_node
966 let empty_node_features = NodeFeatures::empty();
967 // Find ways (channels with destination) to reach a given node and store them
968 // in the corresponding data structures (routing graph etc).
969 // $fee_to_target_msat represents how much it costs to reach to this node from the payee,
970 // meaning how much will be paid in fees after this node (to the best of our knowledge).
971 // This data can later be helpful to optimize routing (pay lower fees).
972 macro_rules! add_entries_to_cheapest_to_target_node {
973 ( $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 ) => {
974 let skip_node = if let Some(elem) = dist.get_mut(&$node_id) {
975 let was_processed = elem.was_processed;
976 elem.was_processed = true;
979 // Entries are added to dist in add_entry!() when there is a channel from a node.
980 // Because there are no channels from payee, it will not have a dist entry at this point.
981 // If we're processing any other node, it is always be the result of a channel from it.
982 assert_eq!($node_id, payee_node_id);
987 if let Some(first_channels) = first_hop_targets.get(&$node_id) {
988 for (ref first_hop, ref features, ref outbound_capacity_msat, _) in first_channels {
989 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);
993 let features = if let Some(node_info) = $node.announcement_info.as_ref() {
999 if !features.requires_unknown_bits() {
1000 for chan_id in $node.channels.iter() {
1001 let chan = network_channels.get(chan_id).unwrap();
1002 if !chan.features.requires_unknown_bits() {
1003 if chan.node_one == $node_id {
1004 // ie $node is one, ie next hop in A* is two, via the two_to_one channel
1005 if first_hops.is_none() || chan.node_two != our_node_id {
1006 if let Some(two_to_one) = chan.two_to_one.as_ref() {
1007 if two_to_one.enabled {
1008 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);
1013 if first_hops.is_none() || chan.node_one != our_node_id{
1014 if let Some(one_to_two) = chan.one_to_two.as_ref() {
1015 if one_to_two.enabled {
1016 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);
1028 let mut payment_paths = Vec::<PaymentPath>::new();
1030 // TODO: diversify by nodes (so that all paths aren't doomed if one node is offline).
1031 'paths_collection: loop {
1032 // For every new path, start from scratch, except
1033 // bookkeeped_channels_liquidity_available_msat, which will improve
1034 // the further iterations of path finding. Also don't erase first_hop_targets.
1037 hit_minimum_limit = false;
1039 // If first hop is a private channel and the only way to reach the payee, this is the only
1040 // place where it could be added.
1041 if let Some(first_channels) = first_hop_targets.get(&payee_node_id) {
1042 for (ref first_hop, ref features, ref outbound_capacity_msat, _) in first_channels {
1043 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);
1044 log_trace!(logger, "{} direct route to payee via SCID {}", if added { "Added" } else { "Skipped" }, first_hop);
1048 // Add the payee as a target, so that the payee-to-payer
1049 // search algorithm knows what to start with.
1050 match network_nodes.get(&payee_node_id) {
1051 // The payee is not in our network graph, so nothing to add here.
1052 // There is still a chance of reaching them via last_hops though,
1053 // so don't yet fail the payment here.
1054 // If not, targets.pop() will not even let us enter the loop in step 2.
1057 add_entries_to_cheapest_to_target_node!(node, payee_node_id, 0, path_value_msat, 0, 0u64);
1062 // If a caller provided us with last hops, add them to routing targets. Since this happens
1063 // earlier than general path finding, they will be somewhat prioritized, although currently
1064 // it matters only if the fees are exactly the same.
1065 for route in payee.route_hints.iter().filter(|route| !route.0.is_empty()) {
1066 let first_hop_in_route = &(route.0)[0];
1067 let have_hop_src_in_graph =
1068 // Only add the hops in this route to our candidate set if either
1069 // we have a direct channel to the first hop or the first hop is
1070 // in the regular network graph.
1071 first_hop_targets.get(&NodeId::from_pubkey(&first_hop_in_route.src_node_id)).is_some() ||
1072 network_nodes.get(&NodeId::from_pubkey(&first_hop_in_route.src_node_id)).is_some();
1073 if have_hop_src_in_graph {
1074 // We start building the path from reverse, i.e., from payee
1075 // to the first RouteHintHop in the path.
1076 let hop_iter = route.0.iter().rev();
1077 let prev_hop_iter = core::iter::once(&payee.pubkey).chain(
1078 route.0.iter().skip(1).rev().map(|hop| &hop.src_node_id));
1079 let mut hop_used = true;
1080 let mut aggregate_next_hops_fee_msat: u64 = 0;
1081 let mut aggregate_next_hops_path_htlc_minimum_msat: u64 = 0;
1082 let mut aggregate_next_hops_path_penalty_msat: u64 = 0;
1084 for (idx, (hop, prev_hop_id)) in hop_iter.zip(prev_hop_iter).enumerate() {
1085 // BOLT 11 doesn't allow inclusion of features for the last hop hints, which
1086 // really sucks, cause we're gonna need that eventually.
1087 let hop_htlc_minimum_msat: u64 = hop.htlc_minimum_msat.unwrap_or(0);
1089 let directional_info = DummyDirectionalChannelInfo {
1090 cltv_expiry_delta: hop.cltv_expiry_delta as u32,
1091 htlc_minimum_msat: hop_htlc_minimum_msat,
1092 htlc_maximum_msat: hop.htlc_maximum_msat,
1096 let reqd_channel_cap = if let Some (val) = final_value_msat.checked_add(match idx {
1098 _ => aggregate_next_hops_fee_msat.checked_add(999).unwrap_or(u64::max_value())
1099 }) { Some( val / 1000 ) } else { break; }; // converting from msat or breaking if max ~ infinity
1101 let src_node_id = NodeId::from_pubkey(&hop.src_node_id);
1102 let dest_node_id = NodeId::from_pubkey(&prev_hop_id);
1103 aggregate_next_hops_path_penalty_msat = aggregate_next_hops_path_penalty_msat
1104 .checked_add(scorer.channel_penalty_msat(hop.short_channel_id, &src_node_id, &dest_node_id))
1105 .unwrap_or_else(|| u64::max_value());
1107 // We assume that the recipient only included route hints for routes which had
1108 // sufficient value to route `final_value_msat`. Note that in the case of "0-value"
1109 // invoices where the invoice does not specify value this may not be the case, but
1110 // better to include the hints than not.
1111 if !add_entry!(hop.short_channel_id, src_node_id, dest_node_id, directional_info, reqd_channel_cap, &empty_channel_features, aggregate_next_hops_fee_msat, path_value_msat, aggregate_next_hops_path_htlc_minimum_msat, aggregate_next_hops_path_penalty_msat) {
1112 // If this hop was not used then there is no use checking the preceding hops
1113 // in the RouteHint. We can break by just searching for a direct channel between
1114 // last checked hop and first_hop_targets
1118 // Searching for a direct channel between last checked hop and first_hop_targets
1119 if let Some(first_channels) = first_hop_targets.get(&NodeId::from_pubkey(&prev_hop_id)) {
1120 for (ref first_hop, ref features, ref outbound_capacity_msat, _) in first_channels {
1121 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);
1129 // In the next values of the iterator, the aggregate fees already reflects
1130 // the sum of value sent from payer (final_value_msat) and routing fees
1131 // for the last node in the RouteHint. We need to just add the fees to
1132 // route through the current node so that the preceeding node (next iteration)
1134 let hops_fee = compute_fees(aggregate_next_hops_fee_msat + final_value_msat, hop.fees)
1135 .map_or(None, |inc| inc.checked_add(aggregate_next_hops_fee_msat));
1136 aggregate_next_hops_fee_msat = if let Some(val) = hops_fee { val } else { break; };
1138 let hop_htlc_minimum_msat_inc = if let Some(val) = compute_fees(aggregate_next_hops_path_htlc_minimum_msat, hop.fees) { val } else { break; };
1139 let hops_path_htlc_minimum = aggregate_next_hops_path_htlc_minimum_msat
1140 .checked_add(hop_htlc_minimum_msat_inc);
1141 aggregate_next_hops_path_htlc_minimum_msat = if let Some(val) = hops_path_htlc_minimum { cmp::max(hop_htlc_minimum_msat, val) } else { break; };
1143 if idx == route.0.len() - 1 {
1144 // The last hop in this iterator is the first hop in
1145 // overall RouteHint.
1146 // If this hop connects to a node with which we have a direct channel,
1147 // ignore the network graph and, if the last hop was added, add our
1148 // direct channel to the candidate set.
1150 // Note that we *must* check if the last hop was added as `add_entry`
1151 // always assumes that the third argument is a node to which we have a
1153 if let Some(first_channels) = first_hop_targets.get(&NodeId::from_pubkey(&hop.src_node_id)) {
1154 for (ref first_hop, ref features, ref outbound_capacity_msat, _) in first_channels {
1155 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);
1163 log_trace!(logger, "Starting main path collection loop with {} nodes pre-filled from first/last hops.", targets.len());
1165 // At this point, targets are filled with the data from first and
1166 // last hops communicated by the caller, and the payment receiver.
1167 let mut found_new_path = false;
1170 // If this loop terminates due the exhaustion of targets, two situations are possible:
1171 // - not enough outgoing liquidity:
1172 // 0 < already_collected_value_msat < final_value_msat
1173 // - enough outgoing liquidity:
1174 // final_value_msat <= already_collected_value_msat < recommended_value_msat
1175 // Both these cases (and other cases except reaching recommended_value_msat) mean that
1176 // paths_collection will be stopped because found_new_path==false.
1177 // This is not necessarily a routing failure.
1178 'path_construction: while let Some(RouteGraphNode { node_id, lowest_fee_to_node, value_contribution_msat, path_htlc_minimum_msat, path_penalty_msat, .. }) = targets.pop() {
1180 // Since we're going payee-to-payer, hitting our node as a target means we should stop
1181 // traversing the graph and arrange the path out of what we found.
1182 if node_id == our_node_id {
1183 let mut new_entry = dist.remove(&our_node_id).unwrap();
1184 let mut ordered_hops = vec!((new_entry.clone(), NodeFeatures::empty()));
1187 let mut features_set = false;
1188 if let Some(first_channels) = first_hop_targets.get(&ordered_hops.last().unwrap().0.node_id) {
1189 for (scid, _, _, ref features) in first_channels {
1190 if *scid == ordered_hops.last().unwrap().0.short_channel_id {
1191 ordered_hops.last_mut().unwrap().1 = features.clone();
1192 features_set = true;
1198 if let Some(node) = network_nodes.get(&ordered_hops.last().unwrap().0.node_id) {
1199 if let Some(node_info) = node.announcement_info.as_ref() {
1200 ordered_hops.last_mut().unwrap().1 = node_info.features.clone();
1202 ordered_hops.last_mut().unwrap().1 = NodeFeatures::empty();
1205 // We should be able to fill in features for everything except the last
1206 // hop, if the last hop was provided via a BOLT 11 invoice (though we
1207 // should be able to extend it further as BOLT 11 does have feature
1208 // flags for the last hop node itself).
1209 assert!(ordered_hops.last().unwrap().0.node_id == payee_node_id);
1213 // Means we succesfully traversed from the payer to the payee, now
1214 // save this path for the payment route. Also, update the liquidity
1215 // remaining on the used hops, so that we take them into account
1216 // while looking for more paths.
1217 if ordered_hops.last().unwrap().0.node_id == payee_node_id {
1221 new_entry = match dist.remove(&ordered_hops.last().unwrap().0.node_id) {
1222 Some(payment_hop) => payment_hop,
1223 // We can't arrive at None because, if we ever add an entry to targets,
1224 // we also fill in the entry in dist (see add_entry!).
1225 None => unreachable!(),
1227 // We "propagate" the fees one hop backward (topologically) here,
1228 // so that fees paid for a HTLC forwarding on the current channel are
1229 // associated with the previous channel (where they will be subtracted).
1230 ordered_hops.last_mut().unwrap().0.fee_msat = new_entry.hop_use_fee_msat;
1231 ordered_hops.last_mut().unwrap().0.cltv_expiry_delta = new_entry.cltv_expiry_delta;
1232 ordered_hops.push((new_entry.clone(), NodeFeatures::empty()));
1234 ordered_hops.last_mut().unwrap().0.fee_msat = value_contribution_msat;
1235 ordered_hops.last_mut().unwrap().0.hop_use_fee_msat = 0;
1236 ordered_hops.last_mut().unwrap().0.cltv_expiry_delta = final_cltv_expiry_delta;
1238 log_trace!(logger, "Found a path back to us from the target with {} hops contributing up to {} msat: {:?}",
1239 ordered_hops.len(), value_contribution_msat, ordered_hops);
1241 let mut payment_path = PaymentPath {hops: ordered_hops};
1243 // We could have possibly constructed a slightly inconsistent path: since we reduce
1244 // value being transferred along the way, we could have violated htlc_minimum_msat
1245 // on some channels we already passed (assuming dest->source direction). Here, we
1246 // recompute the fees again, so that if that's the case, we match the currently
1247 // underpaid htlc_minimum_msat with fees.
1248 payment_path.update_value_and_recompute_fees(cmp::min(value_contribution_msat, final_value_msat));
1250 // Since a path allows to transfer as much value as
1251 // the smallest channel it has ("bottleneck"), we should recompute
1252 // the fees so sender HTLC don't overpay fees when traversing
1253 // larger channels than the bottleneck. This may happen because
1254 // when we were selecting those channels we were not aware how much value
1255 // this path will transfer, and the relative fee for them
1256 // might have been computed considering a larger value.
1257 // Remember that we used these channels so that we don't rely
1258 // on the same liquidity in future paths.
1259 let mut prevented_redundant_path_selection = false;
1260 for (payment_hop, _) in payment_path.hops.iter() {
1261 let channel_liquidity_available_msat = bookkeeped_channels_liquidity_available_msat.get_mut(&payment_hop.short_channel_id).unwrap();
1262 let mut spent_on_hop_msat = value_contribution_msat;
1263 let next_hops_fee_msat = payment_hop.next_hops_fee_msat;
1264 spent_on_hop_msat += next_hops_fee_msat;
1265 if spent_on_hop_msat == *channel_liquidity_available_msat {
1266 // If this path used all of this channel's available liquidity, we know
1267 // this path will not be selected again in the next loop iteration.
1268 prevented_redundant_path_selection = true;
1270 *channel_liquidity_available_msat -= spent_on_hop_msat;
1272 if !prevented_redundant_path_selection {
1273 // If we weren't capped by hitting a liquidity limit on a channel in the path,
1274 // we'll probably end up picking the same path again on the next iteration.
1275 // Decrease the available liquidity of a hop in the middle of the path.
1276 let victim_scid = payment_path.hops[(payment_path.hops.len() - 1) / 2].0.short_channel_id;
1277 log_trace!(logger, "Disabling channel {} for future path building iterations to avoid duplicates.", victim_scid);
1278 let victim_liquidity = bookkeeped_channels_liquidity_available_msat.get_mut(&victim_scid).unwrap();
1279 *victim_liquidity = 0;
1282 // Track the total amount all our collected paths allow to send so that we:
1283 // - know when to stop looking for more paths
1284 // - know which of the hops are useless considering how much more sats we need
1285 // (contributes_sufficient_value)
1286 already_collected_value_msat += value_contribution_msat;
1288 payment_paths.push(payment_path);
1289 found_new_path = true;
1290 break 'path_construction;
1293 // If we found a path back to the payee, we shouldn't try to process it again. This is
1294 // the equivalent of the `elem.was_processed` check in
1295 // add_entries_to_cheapest_to_target_node!() (see comment there for more info).
1296 if node_id == payee_node_id { continue 'path_construction; }
1298 // Otherwise, since the current target node is not us,
1299 // keep "unrolling" the payment graph from payee to payer by
1300 // finding a way to reach the current target from the payer side.
1301 match network_nodes.get(&node_id) {
1304 add_entries_to_cheapest_to_target_node!(node, node_id, lowest_fee_to_node, value_contribution_msat, path_htlc_minimum_msat, path_penalty_msat);
1310 // If we don't support MPP, no use trying to gather more value ever.
1311 break 'paths_collection;
1315 // Stop either when the recommended value is reached or if no new path was found in this
1317 // In the latter case, making another path finding attempt won't help,
1318 // because we deterministically terminated the search due to low liquidity.
1319 if already_collected_value_msat >= recommended_value_msat || !found_new_path {
1320 log_trace!(logger, "Have now collected {} msat (seeking {} msat) in paths. Last path loop {} a new path.",
1321 already_collected_value_msat, recommended_value_msat, if found_new_path { "found" } else { "did not find" });
1322 break 'paths_collection;
1323 } else if found_new_path && already_collected_value_msat == final_value_msat && payment_paths.len() == 1 {
1324 // Further, if this was our first walk of the graph, and we weren't limited by an
1325 // htlc_minimum_msat, return immediately because this path should suffice. If we were
1326 // limited by an htlc_minimum_msat value, find another path with a higher value,
1327 // potentially allowing us to pay fees to meet the htlc_minimum on the new path while
1328 // still keeping a lower total fee than this path.
1329 if !hit_minimum_limit {
1330 log_trace!(logger, "Collected exactly our payment amount on the first pass, without hitting an htlc_minimum_msat limit, exiting.");
1331 break 'paths_collection;
1333 log_trace!(logger, "Collected our payment amount on the first pass, but running again to collect extra paths with a potentially higher limit.");
1334 path_value_msat = recommended_value_msat;
1339 if payment_paths.len() == 0 {
1340 return Err(LightningError{err: "Failed to find a path to the given destination".to_owned(), action: ErrorAction::IgnoreError});
1343 if already_collected_value_msat < final_value_msat {
1344 return Err(LightningError{err: "Failed to find a sufficient route to the given destination".to_owned(), action: ErrorAction::IgnoreError});
1347 // Sort by total fees and take the best paths.
1348 payment_paths.sort_by_key(|path| path.get_total_fee_paid_msat());
1349 if payment_paths.len() > 50 {
1350 payment_paths.truncate(50);
1353 // Draw multiple sufficient routes by randomly combining the selected paths.
1354 let mut drawn_routes = Vec::new();
1355 for i in 0..payment_paths.len() {
1356 let mut cur_route = Vec::<PaymentPath>::new();
1357 let mut aggregate_route_value_msat = 0;
1360 // TODO: real random shuffle
1361 // Currently just starts with i_th and goes up to i-1_th in a looped way.
1362 let cur_payment_paths = [&payment_paths[i..], &payment_paths[..i]].concat();
1365 for payment_path in cur_payment_paths {
1366 cur_route.push(payment_path.clone());
1367 aggregate_route_value_msat += payment_path.get_value_msat();
1368 if aggregate_route_value_msat > final_value_msat {
1369 // Last path likely overpaid. Substract it from the most expensive
1370 // (in terms of proportional fee) path in this route and recompute fees.
1371 // This might be not the most economically efficient way, but fewer paths
1372 // also makes routing more reliable.
1373 let mut overpaid_value_msat = aggregate_route_value_msat - final_value_msat;
1375 // First, drop some expensive low-value paths entirely if possible.
1376 // Sort by value so that we drop many really-low values first, since
1377 // fewer paths is better: the payment is less likely to fail.
1378 // TODO: this could also be optimized by also sorting by feerate_per_sat_routed,
1379 // so that the sender pays less fees overall. And also htlc_minimum_msat.
1380 cur_route.sort_by_key(|path| path.get_value_msat());
1381 // We should make sure that at least 1 path left.
1382 let mut paths_left = cur_route.len();
1383 cur_route.retain(|path| {
1384 if paths_left == 1 {
1387 let mut keep = true;
1388 let path_value_msat = path.get_value_msat();
1389 if path_value_msat <= overpaid_value_msat {
1391 overpaid_value_msat -= path_value_msat;
1397 if overpaid_value_msat == 0 {
1401 assert!(cur_route.len() > 0);
1404 // Now, substract the overpaid value from the most-expensive path.
1405 // TODO: this could also be optimized by also sorting by feerate_per_sat_routed,
1406 // so that the sender pays less fees overall. And also htlc_minimum_msat.
1407 cur_route.sort_by_key(|path| { path.hops.iter().map(|hop| hop.0.channel_fees.proportional_millionths as u64).sum::<u64>() });
1408 let expensive_payment_path = cur_route.first_mut().unwrap();
1409 // We already dropped all the small channels above, meaning all the
1410 // remaining channels are larger than remaining overpaid_value_msat.
1411 // Thus, this can't be negative.
1412 let expensive_path_new_value_msat = expensive_payment_path.get_value_msat() - overpaid_value_msat;
1413 expensive_payment_path.update_value_and_recompute_fees(expensive_path_new_value_msat);
1417 drawn_routes.push(cur_route);
1421 // Select the best route by lowest total fee.
1422 drawn_routes.sort_by_key(|paths| paths.iter().map(|path| path.get_total_fee_paid_msat()).sum::<u64>());
1423 let mut selected_paths = Vec::<Vec<Result<RouteHop, LightningError>>>::new();
1424 for payment_path in drawn_routes.first().unwrap() {
1425 selected_paths.push(payment_path.hops.iter().map(|(payment_hop, node_features)| {
1427 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)})?,
1428 node_features: node_features.clone(),
1429 short_channel_id: payment_hop.short_channel_id,
1430 channel_features: payment_hop.channel_features.clone(),
1431 fee_msat: payment_hop.fee_msat,
1432 cltv_expiry_delta: payment_hop.cltv_expiry_delta,
1437 if let Some(features) = &payee.features {
1438 for path in selected_paths.iter_mut() {
1439 if let Ok(route_hop) = path.last_mut().unwrap() {
1440 route_hop.node_features = features.to_context();
1445 let route = Route { paths: selected_paths.into_iter().map(|path| path.into_iter().collect()).collect::<Result<Vec<_>, _>>()? };
1446 log_info!(logger, "Got route to {}: {}", payee.pubkey, log_route!(route));
1453 use routing::network_graph::{NetworkGraph, NetGraphMsgHandler, NodeId};
1454 use routing::router::{get_route, Payee, Route, RouteHint, RouteHintHop, RouteHop, RoutingFees};
1455 use routing::scorer::Scorer;
1456 use chain::transaction::OutPoint;
1457 use ln::features::{ChannelFeatures, InitFeatures, InvoiceFeatures, NodeFeatures};
1458 use ln::msgs::{ErrorAction, LightningError, OptionalField, UnsignedChannelAnnouncement, ChannelAnnouncement, RoutingMessageHandler,
1459 NodeAnnouncement, UnsignedNodeAnnouncement, ChannelUpdate, UnsignedChannelUpdate};
1460 use ln::channelmanager;
1461 use util::test_utils;
1462 use util::ser::Writeable;
1464 use bitcoin::hashes::sha256d::Hash as Sha256dHash;
1465 use bitcoin::hashes::Hash;
1466 use bitcoin::network::constants::Network;
1467 use bitcoin::blockdata::constants::genesis_block;
1468 use bitcoin::blockdata::script::Builder;
1469 use bitcoin::blockdata::opcodes;
1470 use bitcoin::blockdata::transaction::TxOut;
1474 use bitcoin::secp256k1::key::{PublicKey,SecretKey};
1475 use bitcoin::secp256k1::{Secp256k1, All};
1478 use sync::{self, Arc};
1480 fn get_channel_details(short_channel_id: Option<u64>, node_id: PublicKey,
1481 features: InitFeatures, outbound_capacity_msat: u64) -> channelmanager::ChannelDetails {
1482 channelmanager::ChannelDetails {
1483 channel_id: [0; 32],
1484 counterparty: channelmanager::ChannelCounterparty {
1487 unspendable_punishment_reserve: 0,
1488 forwarding_info: None,
1490 funding_txo: Some(OutPoint { txid: bitcoin::Txid::from_slice(&[0; 32]).unwrap(), index: 0 }),
1492 channel_value_satoshis: 0,
1494 outbound_capacity_msat,
1495 inbound_capacity_msat: 42,
1496 unspendable_punishment_reserve: None,
1497 confirmations_required: None,
1498 force_close_spend_delay: None,
1499 is_outbound: true, is_funding_locked: true,
1500 is_usable: true, is_public: true,
1504 // Using the same keys for LN and BTC ids
1506 net_graph_msg_handler: &NetGraphMsgHandler<Arc<test_utils::TestChainSource>, Arc<test_utils::TestLogger>>,
1507 secp_ctx: &Secp256k1<All>, node_1_privkey: &SecretKey, node_2_privkey: &SecretKey, features: ChannelFeatures, short_channel_id: u64
1509 let node_id_1 = PublicKey::from_secret_key(&secp_ctx, node_1_privkey);
1510 let node_id_2 = PublicKey::from_secret_key(&secp_ctx, node_2_privkey);
1512 let unsigned_announcement = UnsignedChannelAnnouncement {
1514 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1518 bitcoin_key_1: node_id_1,
1519 bitcoin_key_2: node_id_2,
1520 excess_data: Vec::new(),
1523 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1524 let valid_announcement = ChannelAnnouncement {
1525 node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
1526 node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
1527 bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
1528 bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
1529 contents: unsigned_announcement.clone(),
1531 match net_graph_msg_handler.handle_channel_announcement(&valid_announcement) {
1532 Ok(res) => assert!(res),
1538 net_graph_msg_handler: &NetGraphMsgHandler<Arc<test_utils::TestChainSource>, Arc<test_utils::TestLogger>>,
1539 secp_ctx: &Secp256k1<All>, node_privkey: &SecretKey, update: UnsignedChannelUpdate
1541 let msghash = hash_to_message!(&Sha256dHash::hash(&update.encode()[..])[..]);
1542 let valid_channel_update = ChannelUpdate {
1543 signature: secp_ctx.sign(&msghash, node_privkey),
1544 contents: update.clone()
1547 match net_graph_msg_handler.handle_channel_update(&valid_channel_update) {
1548 Ok(res) => assert!(res),
1553 fn add_or_update_node(
1554 net_graph_msg_handler: &NetGraphMsgHandler<Arc<test_utils::TestChainSource>, Arc<test_utils::TestLogger>>,
1555 secp_ctx: &Secp256k1<All>, node_privkey: &SecretKey, features: NodeFeatures, timestamp: u32
1557 let node_id = PublicKey::from_secret_key(&secp_ctx, node_privkey);
1558 let unsigned_announcement = UnsignedNodeAnnouncement {
1564 addresses: Vec::new(),
1565 excess_address_data: Vec::new(),
1566 excess_data: Vec::new(),
1568 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1569 let valid_announcement = NodeAnnouncement {
1570 signature: secp_ctx.sign(&msghash, node_privkey),
1571 contents: unsigned_announcement.clone()
1574 match net_graph_msg_handler.handle_node_announcement(&valid_announcement) {
1580 fn get_nodes(secp_ctx: &Secp256k1<All>) -> (SecretKey, PublicKey, Vec<SecretKey>, Vec<PublicKey>) {
1581 let privkeys: Vec<SecretKey> = (2..10).map(|i| {
1582 SecretKey::from_slice(&hex::decode(format!("{:02}", i).repeat(32)).unwrap()[..]).unwrap()
1585 let pubkeys = privkeys.iter().map(|secret| PublicKey::from_secret_key(&secp_ctx, secret)).collect();
1587 let our_privkey = SecretKey::from_slice(&hex::decode("01".repeat(32)).unwrap()[..]).unwrap();
1588 let our_id = PublicKey::from_secret_key(&secp_ctx, &our_privkey);
1590 (our_privkey, our_id, privkeys, pubkeys)
1593 fn id_to_feature_flags(id: u8) -> Vec<u8> {
1594 // Set the feature flags to the id'th odd (ie non-required) feature bit so that we can
1595 // test for it later.
1596 let idx = (id - 1) * 2 + 1;
1598 vec![1 << (idx - 8*3), 0, 0, 0]
1599 } else if idx > 8*2 {
1600 vec![1 << (idx - 8*2), 0, 0]
1601 } else if idx > 8*1 {
1602 vec![1 << (idx - 8*1), 0]
1608 fn build_graph() -> (Secp256k1<All>, NetGraphMsgHandler<sync::Arc<test_utils::TestChainSource>, sync::Arc<crate::util::test_utils::TestLogger>>, sync::Arc<test_utils::TestChainSource>, sync::Arc<test_utils::TestLogger>) {
1609 let secp_ctx = Secp256k1::new();
1610 let logger = Arc::new(test_utils::TestLogger::new());
1611 let chain_monitor = Arc::new(test_utils::TestChainSource::new(Network::Testnet));
1612 let network_graph = NetworkGraph::new(genesis_block(Network::Testnet).header.block_hash());
1613 let net_graph_msg_handler = NetGraphMsgHandler::new(network_graph, None, Arc::clone(&logger));
1614 // Build network from our_id to node6:
1616 // -1(1)2- node0 -1(3)2-
1618 // our_id -1(12)2- node7 -1(13)2--- node2
1620 // -1(2)2- node1 -1(4)2-
1623 // chan1 1-to-2: disabled
1624 // chan1 2-to-1: enabled, 0 fee
1626 // chan2 1-to-2: enabled, ignored fee
1627 // chan2 2-to-1: enabled, 0 fee
1629 // chan3 1-to-2: enabled, 0 fee
1630 // chan3 2-to-1: enabled, 100 msat fee
1632 // chan4 1-to-2: enabled, 100% fee
1633 // chan4 2-to-1: enabled, 0 fee
1635 // chan12 1-to-2: enabled, ignored fee
1636 // chan12 2-to-1: enabled, 0 fee
1638 // chan13 1-to-2: enabled, 200% fee
1639 // chan13 2-to-1: enabled, 0 fee
1642 // -1(5)2- node3 -1(8)2--
1646 // node2--1(6)2- node4 -1(9)2--- node6 (not in global route map)
1648 // -1(7)2- node5 -1(10)2-
1650 // Channels 5, 8, 9 and 10 are private channels.
1652 // chan5 1-to-2: enabled, 100 msat fee
1653 // chan5 2-to-1: enabled, 0 fee
1655 // chan6 1-to-2: enabled, 0 fee
1656 // chan6 2-to-1: enabled, 0 fee
1658 // chan7 1-to-2: enabled, 100% fee
1659 // chan7 2-to-1: enabled, 0 fee
1661 // chan8 1-to-2: enabled, variable fee (0 then 1000 msat)
1662 // chan8 2-to-1: enabled, 0 fee
1664 // chan9 1-to-2: enabled, 1001 msat fee
1665 // chan9 2-to-1: enabled, 0 fee
1667 // chan10 1-to-2: enabled, 0 fee
1668 // chan10 2-to-1: enabled, 0 fee
1670 // chan11 1-to-2: enabled, 0 fee
1671 // chan11 2-to-1: enabled, 0 fee
1673 let (our_privkey, _, privkeys, _) = get_nodes(&secp_ctx);
1675 add_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, &privkeys[0], ChannelFeatures::from_le_bytes(id_to_feature_flags(1)), 1);
1676 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
1677 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1678 short_channel_id: 1,
1681 cltv_expiry_delta: 0,
1682 htlc_minimum_msat: 0,
1683 htlc_maximum_msat: OptionalField::Absent,
1685 fee_proportional_millionths: 0,
1686 excess_data: Vec::new()
1689 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[0], NodeFeatures::from_le_bytes(id_to_feature_flags(1)), 0);
1691 add_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, &privkeys[1], ChannelFeatures::from_le_bytes(id_to_feature_flags(2)), 2);
1692 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
1693 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1694 short_channel_id: 2,
1697 cltv_expiry_delta: u16::max_value(),
1698 htlc_minimum_msat: 0,
1699 htlc_maximum_msat: OptionalField::Absent,
1700 fee_base_msat: u32::max_value(),
1701 fee_proportional_millionths: u32::max_value(),
1702 excess_data: Vec::new()
1704 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
1705 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1706 short_channel_id: 2,
1709 cltv_expiry_delta: 0,
1710 htlc_minimum_msat: 0,
1711 htlc_maximum_msat: OptionalField::Absent,
1713 fee_proportional_millionths: 0,
1714 excess_data: Vec::new()
1717 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[1], NodeFeatures::from_le_bytes(id_to_feature_flags(2)), 0);
1719 add_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, &privkeys[7], ChannelFeatures::from_le_bytes(id_to_feature_flags(12)), 12);
1720 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
1721 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1722 short_channel_id: 12,
1725 cltv_expiry_delta: u16::max_value(),
1726 htlc_minimum_msat: 0,
1727 htlc_maximum_msat: OptionalField::Absent,
1728 fee_base_msat: u32::max_value(),
1729 fee_proportional_millionths: u32::max_value(),
1730 excess_data: Vec::new()
1732 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
1733 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1734 short_channel_id: 12,
1737 cltv_expiry_delta: 0,
1738 htlc_minimum_msat: 0,
1739 htlc_maximum_msat: OptionalField::Absent,
1741 fee_proportional_millionths: 0,
1742 excess_data: Vec::new()
1745 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[7], NodeFeatures::from_le_bytes(id_to_feature_flags(8)), 0);
1747 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], &privkeys[2], ChannelFeatures::from_le_bytes(id_to_feature_flags(3)), 3);
1748 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
1749 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1750 short_channel_id: 3,
1753 cltv_expiry_delta: (3 << 8) | 1,
1754 htlc_minimum_msat: 0,
1755 htlc_maximum_msat: OptionalField::Absent,
1757 fee_proportional_millionths: 0,
1758 excess_data: Vec::new()
1760 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
1761 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1762 short_channel_id: 3,
1765 cltv_expiry_delta: (3 << 8) | 2,
1766 htlc_minimum_msat: 0,
1767 htlc_maximum_msat: OptionalField::Absent,
1769 fee_proportional_millionths: 0,
1770 excess_data: Vec::new()
1773 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], &privkeys[2], ChannelFeatures::from_le_bytes(id_to_feature_flags(4)), 4);
1774 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
1775 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1776 short_channel_id: 4,
1779 cltv_expiry_delta: (4 << 8) | 1,
1780 htlc_minimum_msat: 0,
1781 htlc_maximum_msat: OptionalField::Absent,
1783 fee_proportional_millionths: 1000000,
1784 excess_data: Vec::new()
1786 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
1787 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1788 short_channel_id: 4,
1791 cltv_expiry_delta: (4 << 8) | 2,
1792 htlc_minimum_msat: 0,
1793 htlc_maximum_msat: OptionalField::Absent,
1795 fee_proportional_millionths: 0,
1796 excess_data: Vec::new()
1799 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], &privkeys[2], ChannelFeatures::from_le_bytes(id_to_feature_flags(13)), 13);
1800 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
1801 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1802 short_channel_id: 13,
1805 cltv_expiry_delta: (13 << 8) | 1,
1806 htlc_minimum_msat: 0,
1807 htlc_maximum_msat: OptionalField::Absent,
1809 fee_proportional_millionths: 2000000,
1810 excess_data: Vec::new()
1812 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
1813 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1814 short_channel_id: 13,
1817 cltv_expiry_delta: (13 << 8) | 2,
1818 htlc_minimum_msat: 0,
1819 htlc_maximum_msat: OptionalField::Absent,
1821 fee_proportional_millionths: 0,
1822 excess_data: Vec::new()
1825 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[2], NodeFeatures::from_le_bytes(id_to_feature_flags(3)), 0);
1827 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], &privkeys[4], ChannelFeatures::from_le_bytes(id_to_feature_flags(6)), 6);
1828 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
1829 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1830 short_channel_id: 6,
1833 cltv_expiry_delta: (6 << 8) | 1,
1834 htlc_minimum_msat: 0,
1835 htlc_maximum_msat: OptionalField::Absent,
1837 fee_proportional_millionths: 0,
1838 excess_data: Vec::new()
1840 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
1841 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1842 short_channel_id: 6,
1845 cltv_expiry_delta: (6 << 8) | 2,
1846 htlc_minimum_msat: 0,
1847 htlc_maximum_msat: OptionalField::Absent,
1849 fee_proportional_millionths: 0,
1850 excess_data: Vec::new(),
1853 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(11)), 11);
1854 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
1855 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1856 short_channel_id: 11,
1859 cltv_expiry_delta: (11 << 8) | 1,
1860 htlc_minimum_msat: 0,
1861 htlc_maximum_msat: OptionalField::Absent,
1863 fee_proportional_millionths: 0,
1864 excess_data: Vec::new()
1866 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[3], UnsignedChannelUpdate {
1867 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1868 short_channel_id: 11,
1871 cltv_expiry_delta: (11 << 8) | 2,
1872 htlc_minimum_msat: 0,
1873 htlc_maximum_msat: OptionalField::Absent,
1875 fee_proportional_millionths: 0,
1876 excess_data: Vec::new()
1879 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[4], NodeFeatures::from_le_bytes(id_to_feature_flags(5)), 0);
1881 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[3], NodeFeatures::from_le_bytes(id_to_feature_flags(4)), 0);
1883 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], &privkeys[5], ChannelFeatures::from_le_bytes(id_to_feature_flags(7)), 7);
1884 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
1885 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1886 short_channel_id: 7,
1889 cltv_expiry_delta: (7 << 8) | 1,
1890 htlc_minimum_msat: 0,
1891 htlc_maximum_msat: OptionalField::Absent,
1893 fee_proportional_millionths: 1000000,
1894 excess_data: Vec::new()
1896 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[5], UnsignedChannelUpdate {
1897 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1898 short_channel_id: 7,
1901 cltv_expiry_delta: (7 << 8) | 2,
1902 htlc_minimum_msat: 0,
1903 htlc_maximum_msat: OptionalField::Absent,
1905 fee_proportional_millionths: 0,
1906 excess_data: Vec::new()
1909 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[5], NodeFeatures::from_le_bytes(id_to_feature_flags(6)), 0);
1911 (secp_ctx, net_graph_msg_handler, chain_monitor, logger)
1915 fn simple_route_test() {
1916 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
1917 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
1918 let payee = Payee::new(nodes[2]);
1919 let scorer = Scorer::new(0);
1921 // Simple route to 2 via 1
1923 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id, &payee, &net_graph_msg_handler.network_graph, None, 0, 42, Arc::clone(&logger), &scorer) {
1924 assert_eq!(err, "Cannot send a payment of 0 msat");
1925 } else { panic!(); }
1927 let route = get_route(&our_id, &payee, &net_graph_msg_handler.network_graph, None, 100, 42, Arc::clone(&logger), &scorer).unwrap();
1928 assert_eq!(route.paths[0].len(), 2);
1930 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
1931 assert_eq!(route.paths[0][0].short_channel_id, 2);
1932 assert_eq!(route.paths[0][0].fee_msat, 100);
1933 assert_eq!(route.paths[0][0].cltv_expiry_delta, (4 << 8) | 1);
1934 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
1935 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
1937 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
1938 assert_eq!(route.paths[0][1].short_channel_id, 4);
1939 assert_eq!(route.paths[0][1].fee_msat, 100);
1940 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
1941 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
1942 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
1946 fn invalid_first_hop_test() {
1947 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
1948 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
1949 let payee = Payee::new(nodes[2]);
1950 let scorer = Scorer::new(0);
1952 // Simple route to 2 via 1
1954 let our_chans = vec![get_channel_details(Some(2), our_id, InitFeatures::from_le_bytes(vec![0b11]), 100000)];
1956 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id, &payee, &net_graph_msg_handler.network_graph, Some(&our_chans.iter().collect::<Vec<_>>()), 100, 42, Arc::clone(&logger), &scorer) {
1957 assert_eq!(err, "First hop cannot have our_node_pubkey as a destination.");
1958 } else { panic!(); }
1960 let route = get_route(&our_id, &payee, &net_graph_msg_handler.network_graph, None, 100, 42, Arc::clone(&logger), &scorer).unwrap();
1961 assert_eq!(route.paths[0].len(), 2);
1965 fn htlc_minimum_test() {
1966 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
1967 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
1968 let payee = Payee::new(nodes[2]);
1969 let scorer = Scorer::new(0);
1971 // Simple route to 2 via 1
1973 // Disable other paths
1974 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
1975 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1976 short_channel_id: 12,
1978 flags: 2, // to disable
1979 cltv_expiry_delta: 0,
1980 htlc_minimum_msat: 0,
1981 htlc_maximum_msat: OptionalField::Absent,
1983 fee_proportional_millionths: 0,
1984 excess_data: Vec::new()
1986 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
1987 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1988 short_channel_id: 3,
1990 flags: 2, // to disable
1991 cltv_expiry_delta: 0,
1992 htlc_minimum_msat: 0,
1993 htlc_maximum_msat: OptionalField::Absent,
1995 fee_proportional_millionths: 0,
1996 excess_data: Vec::new()
1998 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
1999 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2000 short_channel_id: 13,
2002 flags: 2, // to disable
2003 cltv_expiry_delta: 0,
2004 htlc_minimum_msat: 0,
2005 htlc_maximum_msat: OptionalField::Absent,
2007 fee_proportional_millionths: 0,
2008 excess_data: Vec::new()
2010 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
2011 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2012 short_channel_id: 6,
2014 flags: 2, // to disable
2015 cltv_expiry_delta: 0,
2016 htlc_minimum_msat: 0,
2017 htlc_maximum_msat: OptionalField::Absent,
2019 fee_proportional_millionths: 0,
2020 excess_data: Vec::new()
2022 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
2023 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2024 short_channel_id: 7,
2026 flags: 2, // to disable
2027 cltv_expiry_delta: 0,
2028 htlc_minimum_msat: 0,
2029 htlc_maximum_msat: OptionalField::Absent,
2031 fee_proportional_millionths: 0,
2032 excess_data: Vec::new()
2035 // Check against amount_to_transfer_over_msat.
2036 // Set minimal HTLC of 200_000_000 msat.
2037 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2038 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2039 short_channel_id: 2,
2042 cltv_expiry_delta: 0,
2043 htlc_minimum_msat: 200_000_000,
2044 htlc_maximum_msat: OptionalField::Absent,
2046 fee_proportional_millionths: 0,
2047 excess_data: Vec::new()
2050 // Second hop only allows to forward 199_999_999 at most, thus not allowing the first hop to
2052 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
2053 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2054 short_channel_id: 4,
2057 cltv_expiry_delta: 0,
2058 htlc_minimum_msat: 0,
2059 htlc_maximum_msat: OptionalField::Present(199_999_999),
2061 fee_proportional_millionths: 0,
2062 excess_data: Vec::new()
2065 // Not possible to send 199_999_999, because the minimum on channel=2 is 200_000_000.
2066 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id, &payee, &net_graph_msg_handler.network_graph, None, 199_999_999, 42, Arc::clone(&logger), &scorer) {
2067 assert_eq!(err, "Failed to find a path to the given destination");
2068 } else { panic!(); }
2070 // Lift the restriction on the first hop.
2071 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2072 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2073 short_channel_id: 2,
2076 cltv_expiry_delta: 0,
2077 htlc_minimum_msat: 0,
2078 htlc_maximum_msat: OptionalField::Absent,
2080 fee_proportional_millionths: 0,
2081 excess_data: Vec::new()
2084 // A payment above the minimum should pass
2085 let route = get_route(&our_id, &payee, &net_graph_msg_handler.network_graph, None, 199_999_999, 42, Arc::clone(&logger), &scorer).unwrap();
2086 assert_eq!(route.paths[0].len(), 2);
2090 fn htlc_minimum_overpay_test() {
2091 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
2092 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
2093 let payee = Payee::new(nodes[2]).with_features(InvoiceFeatures::known());
2094 let scorer = Scorer::new(0);
2096 // A route to node#2 via two paths.
2097 // One path allows transferring 35-40 sats, another one also allows 35-40 sats.
2098 // Thus, they can't send 60 without overpaying.
2099 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2100 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2101 short_channel_id: 2,
2104 cltv_expiry_delta: 0,
2105 htlc_minimum_msat: 35_000,
2106 htlc_maximum_msat: OptionalField::Present(40_000),
2108 fee_proportional_millionths: 0,
2109 excess_data: Vec::new()
2111 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2112 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2113 short_channel_id: 12,
2116 cltv_expiry_delta: 0,
2117 htlc_minimum_msat: 35_000,
2118 htlc_maximum_msat: OptionalField::Present(40_000),
2120 fee_proportional_millionths: 0,
2121 excess_data: Vec::new()
2125 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
2126 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2127 short_channel_id: 13,
2130 cltv_expiry_delta: 0,
2131 htlc_minimum_msat: 0,
2132 htlc_maximum_msat: OptionalField::Absent,
2134 fee_proportional_millionths: 0,
2135 excess_data: Vec::new()
2137 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
2138 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2139 short_channel_id: 4,
2142 cltv_expiry_delta: 0,
2143 htlc_minimum_msat: 0,
2144 htlc_maximum_msat: OptionalField::Absent,
2146 fee_proportional_millionths: 0,
2147 excess_data: Vec::new()
2150 // Disable other paths
2151 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2152 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2153 short_channel_id: 1,
2155 flags: 2, // to disable
2156 cltv_expiry_delta: 0,
2157 htlc_minimum_msat: 0,
2158 htlc_maximum_msat: OptionalField::Absent,
2160 fee_proportional_millionths: 0,
2161 excess_data: Vec::new()
2164 let route = get_route(&our_id, &payee, &net_graph_msg_handler.network_graph, None, 60_000, 42, Arc::clone(&logger), &scorer).unwrap();
2165 // Overpay fees to hit htlc_minimum_msat.
2166 let overpaid_fees = route.paths[0][0].fee_msat + route.paths[1][0].fee_msat;
2167 // TODO: this could be better balanced to overpay 10k and not 15k.
2168 assert_eq!(overpaid_fees, 15_000);
2170 // Now, test that if there are 2 paths, a "cheaper" by fee path wouldn't be prioritized
2171 // while taking even more fee to match htlc_minimum_msat.
2172 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2173 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2174 short_channel_id: 12,
2177 cltv_expiry_delta: 0,
2178 htlc_minimum_msat: 65_000,
2179 htlc_maximum_msat: OptionalField::Present(80_000),
2181 fee_proportional_millionths: 0,
2182 excess_data: Vec::new()
2184 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2185 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2186 short_channel_id: 2,
2189 cltv_expiry_delta: 0,
2190 htlc_minimum_msat: 0,
2191 htlc_maximum_msat: OptionalField::Absent,
2193 fee_proportional_millionths: 0,
2194 excess_data: Vec::new()
2196 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
2197 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2198 short_channel_id: 4,
2201 cltv_expiry_delta: 0,
2202 htlc_minimum_msat: 0,
2203 htlc_maximum_msat: OptionalField::Absent,
2205 fee_proportional_millionths: 100_000,
2206 excess_data: Vec::new()
2209 let route = get_route(&our_id, &payee, &net_graph_msg_handler.network_graph, None, 60_000, 42, Arc::clone(&logger), &scorer).unwrap();
2210 // Fine to overpay for htlc_minimum_msat if it allows us to save fee.
2211 assert_eq!(route.paths.len(), 1);
2212 assert_eq!(route.paths[0][0].short_channel_id, 12);
2213 let fees = route.paths[0][0].fee_msat;
2214 assert_eq!(fees, 5_000);
2216 let route = get_route(&our_id, &payee, &net_graph_msg_handler.network_graph, None, 50_000, 42, Arc::clone(&logger), &scorer).unwrap();
2217 // Not fine to overpay for htlc_minimum_msat if it requires paying more than fee on
2218 // the other channel.
2219 assert_eq!(route.paths.len(), 1);
2220 assert_eq!(route.paths[0][0].short_channel_id, 2);
2221 let fees = route.paths[0][0].fee_msat;
2222 assert_eq!(fees, 5_000);
2226 fn disable_channels_test() {
2227 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
2228 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
2229 let payee = Payee::new(nodes[2]);
2230 let scorer = Scorer::new(0);
2232 // // Disable channels 4 and 12 by flags=2
2233 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
2234 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2235 short_channel_id: 4,
2237 flags: 2, // to disable
2238 cltv_expiry_delta: 0,
2239 htlc_minimum_msat: 0,
2240 htlc_maximum_msat: OptionalField::Absent,
2242 fee_proportional_millionths: 0,
2243 excess_data: Vec::new()
2245 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2246 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2247 short_channel_id: 12,
2249 flags: 2, // to disable
2250 cltv_expiry_delta: 0,
2251 htlc_minimum_msat: 0,
2252 htlc_maximum_msat: OptionalField::Absent,
2254 fee_proportional_millionths: 0,
2255 excess_data: Vec::new()
2258 // If all the channels require some features we don't understand, route should fail
2259 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id, &payee, &net_graph_msg_handler.network_graph, None, 100, 42, Arc::clone(&logger), &scorer) {
2260 assert_eq!(err, "Failed to find a path to the given destination");
2261 } else { panic!(); }
2263 // If we specify a channel to node7, that overrides our local channel view and that gets used
2264 let our_chans = vec![get_channel_details(Some(42), nodes[7].clone(), InitFeatures::from_le_bytes(vec![0b11]), 250_000_000)];
2265 let route = get_route(&our_id, &payee, &net_graph_msg_handler.network_graph, Some(&our_chans.iter().collect::<Vec<_>>()), 100, 42, Arc::clone(&logger), &scorer).unwrap();
2266 assert_eq!(route.paths[0].len(), 2);
2268 assert_eq!(route.paths[0][0].pubkey, nodes[7]);
2269 assert_eq!(route.paths[0][0].short_channel_id, 42);
2270 assert_eq!(route.paths[0][0].fee_msat, 200);
2271 assert_eq!(route.paths[0][0].cltv_expiry_delta, (13 << 8) | 1);
2272 assert_eq!(route.paths[0][0].node_features.le_flags(), &vec![0b11]); // it should also override our view of their features
2273 assert_eq!(route.paths[0][0].channel_features.le_flags(), &Vec::<u8>::new()); // No feature flags will meet the relevant-to-channel conversion
2275 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2276 assert_eq!(route.paths[0][1].short_channel_id, 13);
2277 assert_eq!(route.paths[0][1].fee_msat, 100);
2278 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
2279 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2280 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(13));
2284 fn disable_node_test() {
2285 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
2286 let (_, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
2287 let payee = Payee::new(nodes[2]);
2288 let scorer = Scorer::new(0);
2290 // Disable nodes 1, 2, and 8 by requiring unknown feature bits
2291 let unknown_features = NodeFeatures::known().set_unknown_feature_required();
2292 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[0], unknown_features.clone(), 1);
2293 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[1], unknown_features.clone(), 1);
2294 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[7], unknown_features.clone(), 1);
2296 // If all nodes require some features we don't understand, route should fail
2297 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id, &payee, &net_graph_msg_handler.network_graph, None, 100, 42, Arc::clone(&logger), &scorer) {
2298 assert_eq!(err, "Failed to find a path to the given destination");
2299 } else { panic!(); }
2301 // If we specify a channel to node7, that overrides our local channel view and that gets used
2302 let our_chans = vec![get_channel_details(Some(42), nodes[7].clone(), InitFeatures::from_le_bytes(vec![0b11]), 250_000_000)];
2303 let route = get_route(&our_id, &payee, &net_graph_msg_handler.network_graph, Some(&our_chans.iter().collect::<Vec<_>>()), 100, 42, Arc::clone(&logger), &scorer).unwrap();
2304 assert_eq!(route.paths[0].len(), 2);
2306 assert_eq!(route.paths[0][0].pubkey, nodes[7]);
2307 assert_eq!(route.paths[0][0].short_channel_id, 42);
2308 assert_eq!(route.paths[0][0].fee_msat, 200);
2309 assert_eq!(route.paths[0][0].cltv_expiry_delta, (13 << 8) | 1);
2310 assert_eq!(route.paths[0][0].node_features.le_flags(), &vec![0b11]); // it should also override our view of their features
2311 assert_eq!(route.paths[0][0].channel_features.le_flags(), &Vec::<u8>::new()); // No feature flags will meet the relevant-to-channel conversion
2313 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2314 assert_eq!(route.paths[0][1].short_channel_id, 13);
2315 assert_eq!(route.paths[0][1].fee_msat, 100);
2316 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
2317 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2318 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(13));
2320 // Note that we don't test disabling node 3 and failing to route to it, as we (somewhat
2321 // naively) assume that the user checked the feature bits on the invoice, which override
2322 // the node_announcement.
2326 fn our_chans_test() {
2327 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
2328 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
2329 let scorer = Scorer::new(0);
2331 // Route to 1 via 2 and 3 because our channel to 1 is disabled
2332 let payee = Payee::new(nodes[0]);
2333 let route = get_route(&our_id, &payee, &net_graph_msg_handler.network_graph, None, 100, 42, Arc::clone(&logger), &scorer).unwrap();
2334 assert_eq!(route.paths[0].len(), 3);
2336 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
2337 assert_eq!(route.paths[0][0].short_channel_id, 2);
2338 assert_eq!(route.paths[0][0].fee_msat, 200);
2339 assert_eq!(route.paths[0][0].cltv_expiry_delta, (4 << 8) | 1);
2340 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
2341 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
2343 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2344 assert_eq!(route.paths[0][1].short_channel_id, 4);
2345 assert_eq!(route.paths[0][1].fee_msat, 100);
2346 assert_eq!(route.paths[0][1].cltv_expiry_delta, (3 << 8) | 2);
2347 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2348 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
2350 assert_eq!(route.paths[0][2].pubkey, nodes[0]);
2351 assert_eq!(route.paths[0][2].short_channel_id, 3);
2352 assert_eq!(route.paths[0][2].fee_msat, 100);
2353 assert_eq!(route.paths[0][2].cltv_expiry_delta, 42);
2354 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(1));
2355 assert_eq!(route.paths[0][2].channel_features.le_flags(), &id_to_feature_flags(3));
2357 // If we specify a channel to node7, that overrides our local channel view and that gets used
2358 let payee = Payee::new(nodes[2]);
2359 let our_chans = vec![get_channel_details(Some(42), nodes[7].clone(), InitFeatures::from_le_bytes(vec![0b11]), 250_000_000)];
2360 let route = get_route(&our_id, &payee, &net_graph_msg_handler.network_graph, Some(&our_chans.iter().collect::<Vec<_>>()), 100, 42, Arc::clone(&logger), &scorer).unwrap();
2361 assert_eq!(route.paths[0].len(), 2);
2363 assert_eq!(route.paths[0][0].pubkey, nodes[7]);
2364 assert_eq!(route.paths[0][0].short_channel_id, 42);
2365 assert_eq!(route.paths[0][0].fee_msat, 200);
2366 assert_eq!(route.paths[0][0].cltv_expiry_delta, (13 << 8) | 1);
2367 assert_eq!(route.paths[0][0].node_features.le_flags(), &vec![0b11]);
2368 assert_eq!(route.paths[0][0].channel_features.le_flags(), &Vec::<u8>::new()); // No feature flags will meet the relevant-to-channel conversion
2370 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2371 assert_eq!(route.paths[0][1].short_channel_id, 13);
2372 assert_eq!(route.paths[0][1].fee_msat, 100);
2373 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
2374 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2375 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(13));
2378 fn last_hops(nodes: &Vec<PublicKey>) -> Vec<RouteHint> {
2379 let zero_fees = RoutingFees {
2381 proportional_millionths: 0,
2383 vec![RouteHint(vec![RouteHintHop {
2384 src_node_id: nodes[3],
2385 short_channel_id: 8,
2387 cltv_expiry_delta: (8 << 8) | 1,
2388 htlc_minimum_msat: None,
2389 htlc_maximum_msat: None,
2391 ]), RouteHint(vec![RouteHintHop {
2392 src_node_id: nodes[4],
2393 short_channel_id: 9,
2396 proportional_millionths: 0,
2398 cltv_expiry_delta: (9 << 8) | 1,
2399 htlc_minimum_msat: None,
2400 htlc_maximum_msat: None,
2401 }]), RouteHint(vec![RouteHintHop {
2402 src_node_id: nodes[5],
2403 short_channel_id: 10,
2405 cltv_expiry_delta: (10 << 8) | 1,
2406 htlc_minimum_msat: None,
2407 htlc_maximum_msat: None,
2411 fn last_hops_multi_private_channels(nodes: &Vec<PublicKey>) -> Vec<RouteHint> {
2412 let zero_fees = RoutingFees {
2414 proportional_millionths: 0,
2416 vec![RouteHint(vec![RouteHintHop {
2417 src_node_id: nodes[2],
2418 short_channel_id: 5,
2421 proportional_millionths: 0,
2423 cltv_expiry_delta: (5 << 8) | 1,
2424 htlc_minimum_msat: None,
2425 htlc_maximum_msat: None,
2427 src_node_id: nodes[3],
2428 short_channel_id: 8,
2430 cltv_expiry_delta: (8 << 8) | 1,
2431 htlc_minimum_msat: None,
2432 htlc_maximum_msat: None,
2434 ]), RouteHint(vec![RouteHintHop {
2435 src_node_id: nodes[4],
2436 short_channel_id: 9,
2439 proportional_millionths: 0,
2441 cltv_expiry_delta: (9 << 8) | 1,
2442 htlc_minimum_msat: None,
2443 htlc_maximum_msat: None,
2444 }]), RouteHint(vec![RouteHintHop {
2445 src_node_id: nodes[5],
2446 short_channel_id: 10,
2448 cltv_expiry_delta: (10 << 8) | 1,
2449 htlc_minimum_msat: None,
2450 htlc_maximum_msat: None,
2455 fn partial_route_hint_test() {
2456 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
2457 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
2458 let scorer = Scorer::new(0);
2460 // Simple test across 2, 3, 5, and 4 via a last_hop channel
2461 // Tests the behaviour when the RouteHint contains a suboptimal hop.
2462 // RouteHint may be partially used by the algo to build the best path.
2464 // First check that last hop can't have its source as the payee.
2465 let invalid_last_hop = RouteHint(vec![RouteHintHop {
2466 src_node_id: nodes[6],
2467 short_channel_id: 8,
2470 proportional_millionths: 0,
2472 cltv_expiry_delta: (8 << 8) | 1,
2473 htlc_minimum_msat: None,
2474 htlc_maximum_msat: None,
2477 let mut invalid_last_hops = last_hops_multi_private_channels(&nodes);
2478 invalid_last_hops.push(invalid_last_hop);
2480 let payee = Payee::new(nodes[6]).with_route_hints(invalid_last_hops);
2481 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id, &payee, &net_graph_msg_handler.network_graph, None, 100, 42, Arc::clone(&logger), &scorer) {
2482 assert_eq!(err, "Route hint cannot have the payee as the source.");
2483 } else { panic!(); }
2486 let payee = Payee::new(nodes[6]).with_route_hints(last_hops_multi_private_channels(&nodes));
2487 let route = get_route(&our_id, &payee, &net_graph_msg_handler.network_graph, None, 100, 42, Arc::clone(&logger), &scorer).unwrap();
2488 assert_eq!(route.paths[0].len(), 5);
2490 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
2491 assert_eq!(route.paths[0][0].short_channel_id, 2);
2492 assert_eq!(route.paths[0][0].fee_msat, 100);
2493 assert_eq!(route.paths[0][0].cltv_expiry_delta, (4 << 8) | 1);
2494 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
2495 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
2497 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2498 assert_eq!(route.paths[0][1].short_channel_id, 4);
2499 assert_eq!(route.paths[0][1].fee_msat, 0);
2500 assert_eq!(route.paths[0][1].cltv_expiry_delta, (6 << 8) | 1);
2501 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2502 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
2504 assert_eq!(route.paths[0][2].pubkey, nodes[4]);
2505 assert_eq!(route.paths[0][2].short_channel_id, 6);
2506 assert_eq!(route.paths[0][2].fee_msat, 0);
2507 assert_eq!(route.paths[0][2].cltv_expiry_delta, (11 << 8) | 1);
2508 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(5));
2509 assert_eq!(route.paths[0][2].channel_features.le_flags(), &id_to_feature_flags(6));
2511 assert_eq!(route.paths[0][3].pubkey, nodes[3]);
2512 assert_eq!(route.paths[0][3].short_channel_id, 11);
2513 assert_eq!(route.paths[0][3].fee_msat, 0);
2514 assert_eq!(route.paths[0][3].cltv_expiry_delta, (8 << 8) | 1);
2515 // If we have a peer in the node map, we'll use their features here since we don't have
2516 // a way of figuring out their features from the invoice:
2517 assert_eq!(route.paths[0][3].node_features.le_flags(), &id_to_feature_flags(4));
2518 assert_eq!(route.paths[0][3].channel_features.le_flags(), &id_to_feature_flags(11));
2520 assert_eq!(route.paths[0][4].pubkey, nodes[6]);
2521 assert_eq!(route.paths[0][4].short_channel_id, 8);
2522 assert_eq!(route.paths[0][4].fee_msat, 100);
2523 assert_eq!(route.paths[0][4].cltv_expiry_delta, 42);
2524 assert_eq!(route.paths[0][4].node_features.le_flags(), &Vec::<u8>::new()); // We dont pass flags in from invoices yet
2525 assert_eq!(route.paths[0][4].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
2528 fn empty_last_hop(nodes: &Vec<PublicKey>) -> Vec<RouteHint> {
2529 let zero_fees = RoutingFees {
2531 proportional_millionths: 0,
2533 vec![RouteHint(vec![RouteHintHop {
2534 src_node_id: nodes[3],
2535 short_channel_id: 8,
2537 cltv_expiry_delta: (8 << 8) | 1,
2538 htlc_minimum_msat: None,
2539 htlc_maximum_msat: None,
2540 }]), RouteHint(vec![
2542 ]), RouteHint(vec![RouteHintHop {
2543 src_node_id: nodes[5],
2544 short_channel_id: 10,
2546 cltv_expiry_delta: (10 << 8) | 1,
2547 htlc_minimum_msat: None,
2548 htlc_maximum_msat: None,
2553 fn ignores_empty_last_hops_test() {
2554 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
2555 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
2556 let payee = Payee::new(nodes[6]).with_route_hints(empty_last_hop(&nodes));
2557 let scorer = Scorer::new(0);
2559 // Test handling of an empty RouteHint passed in Invoice.
2561 let route = get_route(&our_id, &payee, &net_graph_msg_handler.network_graph, None, 100, 42, Arc::clone(&logger), &scorer).unwrap();
2562 assert_eq!(route.paths[0].len(), 5);
2564 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
2565 assert_eq!(route.paths[0][0].short_channel_id, 2);
2566 assert_eq!(route.paths[0][0].fee_msat, 100);
2567 assert_eq!(route.paths[0][0].cltv_expiry_delta, (4 << 8) | 1);
2568 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
2569 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
2571 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2572 assert_eq!(route.paths[0][1].short_channel_id, 4);
2573 assert_eq!(route.paths[0][1].fee_msat, 0);
2574 assert_eq!(route.paths[0][1].cltv_expiry_delta, (6 << 8) | 1);
2575 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2576 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
2578 assert_eq!(route.paths[0][2].pubkey, nodes[4]);
2579 assert_eq!(route.paths[0][2].short_channel_id, 6);
2580 assert_eq!(route.paths[0][2].fee_msat, 0);
2581 assert_eq!(route.paths[0][2].cltv_expiry_delta, (11 << 8) | 1);
2582 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(5));
2583 assert_eq!(route.paths[0][2].channel_features.le_flags(), &id_to_feature_flags(6));
2585 assert_eq!(route.paths[0][3].pubkey, nodes[3]);
2586 assert_eq!(route.paths[0][3].short_channel_id, 11);
2587 assert_eq!(route.paths[0][3].fee_msat, 0);
2588 assert_eq!(route.paths[0][3].cltv_expiry_delta, (8 << 8) | 1);
2589 // If we have a peer in the node map, we'll use their features here since we don't have
2590 // a way of figuring out their features from the invoice:
2591 assert_eq!(route.paths[0][3].node_features.le_flags(), &id_to_feature_flags(4));
2592 assert_eq!(route.paths[0][3].channel_features.le_flags(), &id_to_feature_flags(11));
2594 assert_eq!(route.paths[0][4].pubkey, nodes[6]);
2595 assert_eq!(route.paths[0][4].short_channel_id, 8);
2596 assert_eq!(route.paths[0][4].fee_msat, 100);
2597 assert_eq!(route.paths[0][4].cltv_expiry_delta, 42);
2598 assert_eq!(route.paths[0][4].node_features.le_flags(), &Vec::<u8>::new()); // We dont pass flags in from invoices yet
2599 assert_eq!(route.paths[0][4].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
2602 fn multi_hint_last_hops(nodes: &Vec<PublicKey>) -> Vec<RouteHint> {
2603 let zero_fees = RoutingFees {
2605 proportional_millionths: 0,
2607 vec![RouteHint(vec![RouteHintHop {
2608 src_node_id: nodes[2],
2609 short_channel_id: 5,
2612 proportional_millionths: 0,
2614 cltv_expiry_delta: (5 << 8) | 1,
2615 htlc_minimum_msat: None,
2616 htlc_maximum_msat: None,
2618 src_node_id: nodes[3],
2619 short_channel_id: 8,
2621 cltv_expiry_delta: (8 << 8) | 1,
2622 htlc_minimum_msat: None,
2623 htlc_maximum_msat: None,
2624 }]), RouteHint(vec![RouteHintHop {
2625 src_node_id: nodes[5],
2626 short_channel_id: 10,
2628 cltv_expiry_delta: (10 << 8) | 1,
2629 htlc_minimum_msat: None,
2630 htlc_maximum_msat: None,
2635 fn multi_hint_last_hops_test() {
2636 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
2637 let (_, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
2638 let payee = Payee::new(nodes[6]).with_route_hints(multi_hint_last_hops(&nodes));
2639 let scorer = Scorer::new(0);
2640 // Test through channels 2, 3, 5, 8.
2641 // Test shows that multiple hop hints are considered.
2643 // Disabling channels 6 & 7 by flags=2
2644 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
2645 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2646 short_channel_id: 6,
2648 flags: 2, // to disable
2649 cltv_expiry_delta: 0,
2650 htlc_minimum_msat: 0,
2651 htlc_maximum_msat: OptionalField::Absent,
2653 fee_proportional_millionths: 0,
2654 excess_data: Vec::new()
2656 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
2657 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2658 short_channel_id: 7,
2660 flags: 2, // to disable
2661 cltv_expiry_delta: 0,
2662 htlc_minimum_msat: 0,
2663 htlc_maximum_msat: OptionalField::Absent,
2665 fee_proportional_millionths: 0,
2666 excess_data: Vec::new()
2669 let route = get_route(&our_id, &payee, &net_graph_msg_handler.network_graph, None, 100, 42, Arc::clone(&logger), &scorer).unwrap();
2670 assert_eq!(route.paths[0].len(), 4);
2672 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
2673 assert_eq!(route.paths[0][0].short_channel_id, 2);
2674 assert_eq!(route.paths[0][0].fee_msat, 200);
2675 assert_eq!(route.paths[0][0].cltv_expiry_delta, 1025);
2676 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
2677 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
2679 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2680 assert_eq!(route.paths[0][1].short_channel_id, 4);
2681 assert_eq!(route.paths[0][1].fee_msat, 100);
2682 assert_eq!(route.paths[0][1].cltv_expiry_delta, 1281);
2683 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2684 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
2686 assert_eq!(route.paths[0][2].pubkey, nodes[3]);
2687 assert_eq!(route.paths[0][2].short_channel_id, 5);
2688 assert_eq!(route.paths[0][2].fee_msat, 0);
2689 assert_eq!(route.paths[0][2].cltv_expiry_delta, 2049);
2690 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(4));
2691 assert_eq!(route.paths[0][2].channel_features.le_flags(), &Vec::<u8>::new());
2693 assert_eq!(route.paths[0][3].pubkey, nodes[6]);
2694 assert_eq!(route.paths[0][3].short_channel_id, 8);
2695 assert_eq!(route.paths[0][3].fee_msat, 100);
2696 assert_eq!(route.paths[0][3].cltv_expiry_delta, 42);
2697 assert_eq!(route.paths[0][3].node_features.le_flags(), &Vec::<u8>::new()); // We dont pass flags in from invoices yet
2698 assert_eq!(route.paths[0][3].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
2701 fn last_hops_with_public_channel(nodes: &Vec<PublicKey>) -> Vec<RouteHint> {
2702 let zero_fees = RoutingFees {
2704 proportional_millionths: 0,
2706 vec![RouteHint(vec![RouteHintHop {
2707 src_node_id: nodes[4],
2708 short_channel_id: 11,
2710 cltv_expiry_delta: (11 << 8) | 1,
2711 htlc_minimum_msat: None,
2712 htlc_maximum_msat: None,
2714 src_node_id: nodes[3],
2715 short_channel_id: 8,
2717 cltv_expiry_delta: (8 << 8) | 1,
2718 htlc_minimum_msat: None,
2719 htlc_maximum_msat: None,
2720 }]), RouteHint(vec![RouteHintHop {
2721 src_node_id: nodes[4],
2722 short_channel_id: 9,
2725 proportional_millionths: 0,
2727 cltv_expiry_delta: (9 << 8) | 1,
2728 htlc_minimum_msat: None,
2729 htlc_maximum_msat: None,
2730 }]), RouteHint(vec![RouteHintHop {
2731 src_node_id: nodes[5],
2732 short_channel_id: 10,
2734 cltv_expiry_delta: (10 << 8) | 1,
2735 htlc_minimum_msat: None,
2736 htlc_maximum_msat: None,
2741 fn last_hops_with_public_channel_test() {
2742 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
2743 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
2744 let payee = Payee::new(nodes[6]).with_route_hints(last_hops_with_public_channel(&nodes));
2745 let scorer = Scorer::new(0);
2746 // This test shows that public routes can be present in the invoice
2747 // which would be handled in the same manner.
2749 let route = get_route(&our_id, &payee, &net_graph_msg_handler.network_graph, None, 100, 42, Arc::clone(&logger), &scorer).unwrap();
2750 assert_eq!(route.paths[0].len(), 5);
2752 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
2753 assert_eq!(route.paths[0][0].short_channel_id, 2);
2754 assert_eq!(route.paths[0][0].fee_msat, 100);
2755 assert_eq!(route.paths[0][0].cltv_expiry_delta, (4 << 8) | 1);
2756 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
2757 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
2759 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2760 assert_eq!(route.paths[0][1].short_channel_id, 4);
2761 assert_eq!(route.paths[0][1].fee_msat, 0);
2762 assert_eq!(route.paths[0][1].cltv_expiry_delta, (6 << 8) | 1);
2763 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2764 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
2766 assert_eq!(route.paths[0][2].pubkey, nodes[4]);
2767 assert_eq!(route.paths[0][2].short_channel_id, 6);
2768 assert_eq!(route.paths[0][2].fee_msat, 0);
2769 assert_eq!(route.paths[0][2].cltv_expiry_delta, (11 << 8) | 1);
2770 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(5));
2771 assert_eq!(route.paths[0][2].channel_features.le_flags(), &id_to_feature_flags(6));
2773 assert_eq!(route.paths[0][3].pubkey, nodes[3]);
2774 assert_eq!(route.paths[0][3].short_channel_id, 11);
2775 assert_eq!(route.paths[0][3].fee_msat, 0);
2776 assert_eq!(route.paths[0][3].cltv_expiry_delta, (8 << 8) | 1);
2777 // If we have a peer in the node map, we'll use their features here since we don't have
2778 // a way of figuring out their features from the invoice:
2779 assert_eq!(route.paths[0][3].node_features.le_flags(), &id_to_feature_flags(4));
2780 assert_eq!(route.paths[0][3].channel_features.le_flags(), &Vec::<u8>::new());
2782 assert_eq!(route.paths[0][4].pubkey, nodes[6]);
2783 assert_eq!(route.paths[0][4].short_channel_id, 8);
2784 assert_eq!(route.paths[0][4].fee_msat, 100);
2785 assert_eq!(route.paths[0][4].cltv_expiry_delta, 42);
2786 assert_eq!(route.paths[0][4].node_features.le_flags(), &Vec::<u8>::new()); // We dont pass flags in from invoices yet
2787 assert_eq!(route.paths[0][4].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
2791 fn our_chans_last_hop_connect_test() {
2792 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
2793 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
2794 let scorer = Scorer::new(0);
2796 // Simple test with outbound channel to 4 to test that last_hops and first_hops connect
2797 let our_chans = vec![get_channel_details(Some(42), nodes[3].clone(), InitFeatures::from_le_bytes(vec![0b11]), 250_000_000)];
2798 let mut last_hops = last_hops(&nodes);
2799 let payee = Payee::new(nodes[6]).with_route_hints(last_hops.clone());
2800 let route = get_route(&our_id, &payee, &net_graph_msg_handler.network_graph, Some(&our_chans.iter().collect::<Vec<_>>()), 100, 42, Arc::clone(&logger), &scorer).unwrap();
2801 assert_eq!(route.paths[0].len(), 2);
2803 assert_eq!(route.paths[0][0].pubkey, nodes[3]);
2804 assert_eq!(route.paths[0][0].short_channel_id, 42);
2805 assert_eq!(route.paths[0][0].fee_msat, 0);
2806 assert_eq!(route.paths[0][0].cltv_expiry_delta, (8 << 8) | 1);
2807 assert_eq!(route.paths[0][0].node_features.le_flags(), &vec![0b11]);
2808 assert_eq!(route.paths[0][0].channel_features.le_flags(), &Vec::<u8>::new()); // No feature flags will meet the relevant-to-channel conversion
2810 assert_eq!(route.paths[0][1].pubkey, nodes[6]);
2811 assert_eq!(route.paths[0][1].short_channel_id, 8);
2812 assert_eq!(route.paths[0][1].fee_msat, 100);
2813 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
2814 assert_eq!(route.paths[0][1].node_features.le_flags(), &Vec::<u8>::new()); // We dont pass flags in from invoices yet
2815 assert_eq!(route.paths[0][1].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
2817 last_hops[0].0[0].fees.base_msat = 1000;
2819 // Revert to via 6 as the fee on 8 goes up
2820 let payee = Payee::new(nodes[6]).with_route_hints(last_hops);
2821 let route = get_route(&our_id, &payee, &net_graph_msg_handler.network_graph, None, 100, 42, Arc::clone(&logger), &scorer).unwrap();
2822 assert_eq!(route.paths[0].len(), 4);
2824 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
2825 assert_eq!(route.paths[0][0].short_channel_id, 2);
2826 assert_eq!(route.paths[0][0].fee_msat, 200); // fee increased as its % of value transferred across node
2827 assert_eq!(route.paths[0][0].cltv_expiry_delta, (4 << 8) | 1);
2828 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
2829 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
2831 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2832 assert_eq!(route.paths[0][1].short_channel_id, 4);
2833 assert_eq!(route.paths[0][1].fee_msat, 100);
2834 assert_eq!(route.paths[0][1].cltv_expiry_delta, (7 << 8) | 1);
2835 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2836 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
2838 assert_eq!(route.paths[0][2].pubkey, nodes[5]);
2839 assert_eq!(route.paths[0][2].short_channel_id, 7);
2840 assert_eq!(route.paths[0][2].fee_msat, 0);
2841 assert_eq!(route.paths[0][2].cltv_expiry_delta, (10 << 8) | 1);
2842 // If we have a peer in the node map, we'll use their features here since we don't have
2843 // a way of figuring out their features from the invoice:
2844 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(6));
2845 assert_eq!(route.paths[0][2].channel_features.le_flags(), &id_to_feature_flags(7));
2847 assert_eq!(route.paths[0][3].pubkey, nodes[6]);
2848 assert_eq!(route.paths[0][3].short_channel_id, 10);
2849 assert_eq!(route.paths[0][3].fee_msat, 100);
2850 assert_eq!(route.paths[0][3].cltv_expiry_delta, 42);
2851 assert_eq!(route.paths[0][3].node_features.le_flags(), &Vec::<u8>::new()); // We dont pass flags in from invoices yet
2852 assert_eq!(route.paths[0][3].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
2854 // ...but still use 8 for larger payments as 6 has a variable feerate
2855 let route = get_route(&our_id, &payee, &net_graph_msg_handler.network_graph, None, 2000, 42, Arc::clone(&logger), &scorer).unwrap();
2856 assert_eq!(route.paths[0].len(), 5);
2858 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
2859 assert_eq!(route.paths[0][0].short_channel_id, 2);
2860 assert_eq!(route.paths[0][0].fee_msat, 3000);
2861 assert_eq!(route.paths[0][0].cltv_expiry_delta, (4 << 8) | 1);
2862 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
2863 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
2865 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2866 assert_eq!(route.paths[0][1].short_channel_id, 4);
2867 assert_eq!(route.paths[0][1].fee_msat, 0);
2868 assert_eq!(route.paths[0][1].cltv_expiry_delta, (6 << 8) | 1);
2869 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2870 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
2872 assert_eq!(route.paths[0][2].pubkey, nodes[4]);
2873 assert_eq!(route.paths[0][2].short_channel_id, 6);
2874 assert_eq!(route.paths[0][2].fee_msat, 0);
2875 assert_eq!(route.paths[0][2].cltv_expiry_delta, (11 << 8) | 1);
2876 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(5));
2877 assert_eq!(route.paths[0][2].channel_features.le_flags(), &id_to_feature_flags(6));
2879 assert_eq!(route.paths[0][3].pubkey, nodes[3]);
2880 assert_eq!(route.paths[0][3].short_channel_id, 11);
2881 assert_eq!(route.paths[0][3].fee_msat, 1000);
2882 assert_eq!(route.paths[0][3].cltv_expiry_delta, (8 << 8) | 1);
2883 // If we have a peer in the node map, we'll use their features here since we don't have
2884 // a way of figuring out their features from the invoice:
2885 assert_eq!(route.paths[0][3].node_features.le_flags(), &id_to_feature_flags(4));
2886 assert_eq!(route.paths[0][3].channel_features.le_flags(), &id_to_feature_flags(11));
2888 assert_eq!(route.paths[0][4].pubkey, nodes[6]);
2889 assert_eq!(route.paths[0][4].short_channel_id, 8);
2890 assert_eq!(route.paths[0][4].fee_msat, 2000);
2891 assert_eq!(route.paths[0][4].cltv_expiry_delta, 42);
2892 assert_eq!(route.paths[0][4].node_features.le_flags(), &Vec::<u8>::new()); // We dont pass flags in from invoices yet
2893 assert_eq!(route.paths[0][4].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
2896 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> {
2897 let source_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&hex::decode(format!("{:02}", 41).repeat(32)).unwrap()[..]).unwrap());
2898 let middle_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&hex::decode(format!("{:02}", 42).repeat(32)).unwrap()[..]).unwrap());
2899 let target_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&hex::decode(format!("{:02}", 43).repeat(32)).unwrap()[..]).unwrap());
2901 // If we specify a channel to a middle hop, that overrides our local channel view and that gets used
2902 let last_hops = RouteHint(vec![RouteHintHop {
2903 src_node_id: middle_node_id,
2904 short_channel_id: 8,
2907 proportional_millionths: last_hop_fee_prop,
2909 cltv_expiry_delta: (8 << 8) | 1,
2910 htlc_minimum_msat: None,
2911 htlc_maximum_msat: last_hop_htlc_max,
2913 let payee = Payee::new(target_node_id).with_route_hints(vec![last_hops]);
2914 let our_chans = vec![get_channel_details(Some(42), middle_node_id, InitFeatures::from_le_bytes(vec![0b11]), outbound_capacity_msat)];
2915 let scorer = Scorer::new(0);
2916 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)
2920 fn unannounced_path_test() {
2921 // We should be able to send a payment to a destination without any help of a routing graph
2922 // if we have a channel with a common counterparty that appears in the first and last hop
2924 let route = do_unannounced_path_test(None, 1, 2000000, 1000000).unwrap();
2926 let middle_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&hex::decode(format!("{:02}", 42).repeat(32)).unwrap()[..]).unwrap());
2927 let target_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&hex::decode(format!("{:02}", 43).repeat(32)).unwrap()[..]).unwrap());
2928 assert_eq!(route.paths[0].len(), 2);
2930 assert_eq!(route.paths[0][0].pubkey, middle_node_id);
2931 assert_eq!(route.paths[0][0].short_channel_id, 42);
2932 assert_eq!(route.paths[0][0].fee_msat, 1001);
2933 assert_eq!(route.paths[0][0].cltv_expiry_delta, (8 << 8) | 1);
2934 assert_eq!(route.paths[0][0].node_features.le_flags(), &[0b11]);
2935 assert_eq!(route.paths[0][0].channel_features.le_flags(), &[0; 0]); // We can't learn any flags from invoices, sadly
2937 assert_eq!(route.paths[0][1].pubkey, target_node_id);
2938 assert_eq!(route.paths[0][1].short_channel_id, 8);
2939 assert_eq!(route.paths[0][1].fee_msat, 1000000);
2940 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
2941 assert_eq!(route.paths[0][1].node_features.le_flags(), &[0; 0]); // We dont pass flags in from invoices yet
2942 assert_eq!(route.paths[0][1].channel_features.le_flags(), &[0; 0]); // We can't learn any flags from invoices, sadly
2946 fn overflow_unannounced_path_test_liquidity_underflow() {
2947 // Previously, when we had a last-hop hint connected directly to a first-hop channel, where
2948 // the last-hop had a fee which overflowed a u64, we'd panic.
2949 // This was due to us adding the first-hop from us unconditionally, causing us to think
2950 // we'd built a path (as our node is in the "best candidate" set), when we had not.
2951 // In this test, we previously hit a subtraction underflow due to having less available
2952 // liquidity at the last hop than 0.
2953 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());
2957 fn overflow_unannounced_path_test_feerate_overflow() {
2958 // This tests for the same case as above, except instead of hitting a subtraction
2959 // underflow, we hit a case where the fee charged at a hop overflowed.
2960 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());
2964 fn available_amount_while_routing_test() {
2965 // Tests whether we choose the correct available channel amount while routing.
2967 let (secp_ctx, mut net_graph_msg_handler, chain_monitor, logger) = build_graph();
2968 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
2969 let scorer = Scorer::new(0);
2970 let payee = Payee::new(nodes[2]).with_features(InvoiceFeatures::known());
2972 // We will use a simple single-path route from
2973 // our node to node2 via node0: channels {1, 3}.
2975 // First disable all other paths.
2976 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2977 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2978 short_channel_id: 2,
2981 cltv_expiry_delta: 0,
2982 htlc_minimum_msat: 0,
2983 htlc_maximum_msat: OptionalField::Present(100_000),
2985 fee_proportional_millionths: 0,
2986 excess_data: Vec::new()
2988 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2989 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2990 short_channel_id: 12,
2993 cltv_expiry_delta: 0,
2994 htlc_minimum_msat: 0,
2995 htlc_maximum_msat: OptionalField::Present(100_000),
2997 fee_proportional_millionths: 0,
2998 excess_data: Vec::new()
3001 // Make the first channel (#1) very permissive,
3002 // and we will be testing all limits on the second channel.
3003 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3004 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3005 short_channel_id: 1,
3008 cltv_expiry_delta: 0,
3009 htlc_minimum_msat: 0,
3010 htlc_maximum_msat: OptionalField::Present(1_000_000_000),
3012 fee_proportional_millionths: 0,
3013 excess_data: Vec::new()
3016 // First, let's see if routing works if we have absolutely no idea about the available amount.
3017 // In this case, it should be set to 250_000 sats.
3018 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3019 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3020 short_channel_id: 3,
3023 cltv_expiry_delta: 0,
3024 htlc_minimum_msat: 0,
3025 htlc_maximum_msat: OptionalField::Absent,
3027 fee_proportional_millionths: 0,
3028 excess_data: Vec::new()
3032 // Attempt to route more than available results in a failure.
3033 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
3034 &our_id, &payee, &net_graph_msg_handler.network_graph, None, 250_000_001, 42, Arc::clone(&logger), &scorer) {
3035 assert_eq!(err, "Failed to find a sufficient route to the given destination");
3036 } else { panic!(); }
3040 // Now, attempt to route an exact amount we have should be fine.
3041 let route = get_route(&our_id, &payee, &net_graph_msg_handler.network_graph, None, 250_000_000, 42, Arc::clone(&logger), &scorer).unwrap();
3042 assert_eq!(route.paths.len(), 1);
3043 let path = route.paths.last().unwrap();
3044 assert_eq!(path.len(), 2);
3045 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
3046 assert_eq!(path.last().unwrap().fee_msat, 250_000_000);
3049 // Check that setting outbound_capacity_msat in first_hops limits the channels.
3050 // Disable channel #1 and use another first hop.
3051 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3052 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3053 short_channel_id: 1,
3056 cltv_expiry_delta: 0,
3057 htlc_minimum_msat: 0,
3058 htlc_maximum_msat: OptionalField::Present(1_000_000_000),
3060 fee_proportional_millionths: 0,
3061 excess_data: Vec::new()
3064 // Now, limit the first_hop by the outbound_capacity_msat of 200_000 sats.
3065 let our_chans = vec![get_channel_details(Some(42), nodes[0].clone(), InitFeatures::from_le_bytes(vec![0b11]), 200_000_000)];
3068 // Attempt to route more than available results in a failure.
3069 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
3070 &our_id, &payee, &net_graph_msg_handler.network_graph, Some(&our_chans.iter().collect::<Vec<_>>()), 200_000_001, 42, Arc::clone(&logger), &scorer) {
3071 assert_eq!(err, "Failed to find a sufficient route to the given destination");
3072 } else { panic!(); }
3076 // Now, attempt to route an exact amount we have should be fine.
3077 let route = get_route(&our_id, &payee, &net_graph_msg_handler.network_graph, Some(&our_chans.iter().collect::<Vec<_>>()), 200_000_000, 42, Arc::clone(&logger), &scorer).unwrap();
3078 assert_eq!(route.paths.len(), 1);
3079 let path = route.paths.last().unwrap();
3080 assert_eq!(path.len(), 2);
3081 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
3082 assert_eq!(path.last().unwrap().fee_msat, 200_000_000);
3085 // Enable channel #1 back.
3086 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3087 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3088 short_channel_id: 1,
3091 cltv_expiry_delta: 0,
3092 htlc_minimum_msat: 0,
3093 htlc_maximum_msat: OptionalField::Present(1_000_000_000),
3095 fee_proportional_millionths: 0,
3096 excess_data: Vec::new()
3100 // Now let's see if routing works if we know only htlc_maximum_msat.
3101 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3102 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3103 short_channel_id: 3,
3106 cltv_expiry_delta: 0,
3107 htlc_minimum_msat: 0,
3108 htlc_maximum_msat: OptionalField::Present(15_000),
3110 fee_proportional_millionths: 0,
3111 excess_data: Vec::new()
3115 // Attempt to route more than available results in a failure.
3116 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
3117 &our_id, &payee, &net_graph_msg_handler.network_graph, None, 15_001, 42, Arc::clone(&logger), &scorer) {
3118 assert_eq!(err, "Failed to find a sufficient route to the given destination");
3119 } else { panic!(); }
3123 // Now, attempt to route an exact amount we have should be fine.
3124 let route = get_route(&our_id, &payee, &net_graph_msg_handler.network_graph, None, 15_000, 42, Arc::clone(&logger), &scorer).unwrap();
3125 assert_eq!(route.paths.len(), 1);
3126 let path = route.paths.last().unwrap();
3127 assert_eq!(path.len(), 2);
3128 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
3129 assert_eq!(path.last().unwrap().fee_msat, 15_000);
3132 // Now let's see if routing works if we know only capacity from the UTXO.
3134 // We can't change UTXO capacity on the fly, so we'll disable
3135 // the existing channel and add another one with the capacity we need.
3136 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3137 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3138 short_channel_id: 3,
3141 cltv_expiry_delta: 0,
3142 htlc_minimum_msat: 0,
3143 htlc_maximum_msat: OptionalField::Absent,
3145 fee_proportional_millionths: 0,
3146 excess_data: Vec::new()
3149 let good_script = Builder::new().push_opcode(opcodes::all::OP_PUSHNUM_2)
3150 .push_slice(&PublicKey::from_secret_key(&secp_ctx, &privkeys[0]).serialize())
3151 .push_slice(&PublicKey::from_secret_key(&secp_ctx, &privkeys[2]).serialize())
3152 .push_opcode(opcodes::all::OP_PUSHNUM_2)
3153 .push_opcode(opcodes::all::OP_CHECKMULTISIG).into_script().to_v0_p2wsh();
3155 *chain_monitor.utxo_ret.lock().unwrap() = Ok(TxOut { value: 15, script_pubkey: good_script.clone() });
3156 net_graph_msg_handler.add_chain_access(Some(chain_monitor));
3158 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], &privkeys[2], ChannelFeatures::from_le_bytes(id_to_feature_flags(3)), 333);
3159 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3160 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3161 short_channel_id: 333,
3164 cltv_expiry_delta: (3 << 8) | 1,
3165 htlc_minimum_msat: 0,
3166 htlc_maximum_msat: OptionalField::Absent,
3168 fee_proportional_millionths: 0,
3169 excess_data: Vec::new()
3171 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3172 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3173 short_channel_id: 333,
3176 cltv_expiry_delta: (3 << 8) | 2,
3177 htlc_minimum_msat: 0,
3178 htlc_maximum_msat: OptionalField::Absent,
3180 fee_proportional_millionths: 0,
3181 excess_data: Vec::new()
3185 // Attempt to route more than available results in a failure.
3186 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
3187 &our_id, &payee, &net_graph_msg_handler.network_graph, None, 15_001, 42, Arc::clone(&logger), &scorer) {
3188 assert_eq!(err, "Failed to find a sufficient route to the given destination");
3189 } else { panic!(); }
3193 // Now, attempt to route an exact amount we have should be fine.
3194 let route = get_route(&our_id, &payee, &net_graph_msg_handler.network_graph, None, 15_000, 42, Arc::clone(&logger), &scorer).unwrap();
3195 assert_eq!(route.paths.len(), 1);
3196 let path = route.paths.last().unwrap();
3197 assert_eq!(path.len(), 2);
3198 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
3199 assert_eq!(path.last().unwrap().fee_msat, 15_000);
3202 // Now let's see if routing chooses htlc_maximum_msat over UTXO capacity.
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: 333,
3208 cltv_expiry_delta: 0,
3209 htlc_minimum_msat: 0,
3210 htlc_maximum_msat: OptionalField::Present(10_000),
3212 fee_proportional_millionths: 0,
3213 excess_data: Vec::new()
3217 // Attempt to route more than available results in a failure.
3218 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
3219 &our_id, &payee, &net_graph_msg_handler.network_graph, None, 10_001, 42, Arc::clone(&logger), &scorer) {
3220 assert_eq!(err, "Failed to find a sufficient route to the given destination");
3221 } else { panic!(); }
3225 // Now, attempt to route an exact amount we have should be fine.
3226 let route = get_route(&our_id, &payee, &net_graph_msg_handler.network_graph, None, 10_000, 42, Arc::clone(&logger), &scorer).unwrap();
3227 assert_eq!(route.paths.len(), 1);
3228 let path = route.paths.last().unwrap();
3229 assert_eq!(path.len(), 2);
3230 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
3231 assert_eq!(path.last().unwrap().fee_msat, 10_000);
3236 fn available_liquidity_last_hop_test() {
3237 // Check that available liquidity properly limits the path even when only
3238 // one of the latter hops is limited.
3239 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
3240 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3241 let scorer = Scorer::new(0);
3242 let payee = Payee::new(nodes[3]).with_features(InvoiceFeatures::known());
3244 // Path via {node7, node2, node4} is channels {12, 13, 6, 11}.
3245 // {12, 13, 11} have the capacities of 100, {6} has a capacity of 50.
3246 // Total capacity: 50 sats.
3248 // Disable other potential paths.
3249 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3250 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3251 short_channel_id: 2,
3254 cltv_expiry_delta: 0,
3255 htlc_minimum_msat: 0,
3256 htlc_maximum_msat: OptionalField::Present(100_000),
3258 fee_proportional_millionths: 0,
3259 excess_data: Vec::new()
3261 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3262 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3263 short_channel_id: 7,
3266 cltv_expiry_delta: 0,
3267 htlc_minimum_msat: 0,
3268 htlc_maximum_msat: OptionalField::Present(100_000),
3270 fee_proportional_millionths: 0,
3271 excess_data: Vec::new()
3276 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3277 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3278 short_channel_id: 12,
3281 cltv_expiry_delta: 0,
3282 htlc_minimum_msat: 0,
3283 htlc_maximum_msat: OptionalField::Present(100_000),
3285 fee_proportional_millionths: 0,
3286 excess_data: Vec::new()
3288 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
3289 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3290 short_channel_id: 13,
3293 cltv_expiry_delta: 0,
3294 htlc_minimum_msat: 0,
3295 htlc_maximum_msat: OptionalField::Present(100_000),
3297 fee_proportional_millionths: 0,
3298 excess_data: Vec::new()
3301 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3302 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3303 short_channel_id: 6,
3306 cltv_expiry_delta: 0,
3307 htlc_minimum_msat: 0,
3308 htlc_maximum_msat: OptionalField::Present(50_000),
3310 fee_proportional_millionths: 0,
3311 excess_data: Vec::new()
3313 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
3314 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3315 short_channel_id: 11,
3318 cltv_expiry_delta: 0,
3319 htlc_minimum_msat: 0,
3320 htlc_maximum_msat: OptionalField::Present(100_000),
3322 fee_proportional_millionths: 0,
3323 excess_data: Vec::new()
3326 // Attempt to route more than available results in a failure.
3327 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
3328 &our_id, &payee, &net_graph_msg_handler.network_graph, None, 60_000, 42, Arc::clone(&logger), &scorer) {
3329 assert_eq!(err, "Failed to find a sufficient route to the given destination");
3330 } else { panic!(); }
3334 // Now, attempt to route 49 sats (just a bit below the capacity).
3335 let route = get_route(&our_id, &payee, &net_graph_msg_handler.network_graph, None, 49_000, 42, Arc::clone(&logger), &scorer).unwrap();
3336 assert_eq!(route.paths.len(), 1);
3337 let mut total_amount_paid_msat = 0;
3338 for path in &route.paths {
3339 assert_eq!(path.len(), 4);
3340 assert_eq!(path.last().unwrap().pubkey, nodes[3]);
3341 total_amount_paid_msat += path.last().unwrap().fee_msat;
3343 assert_eq!(total_amount_paid_msat, 49_000);
3347 // Attempt to route an exact amount is also fine
3348 let route = get_route(&our_id, &payee, &net_graph_msg_handler.network_graph, None, 50_000, 42, Arc::clone(&logger), &scorer).unwrap();
3349 assert_eq!(route.paths.len(), 1);
3350 let mut total_amount_paid_msat = 0;
3351 for path in &route.paths {
3352 assert_eq!(path.len(), 4);
3353 assert_eq!(path.last().unwrap().pubkey, nodes[3]);
3354 total_amount_paid_msat += path.last().unwrap().fee_msat;
3356 assert_eq!(total_amount_paid_msat, 50_000);
3361 fn ignore_fee_first_hop_test() {
3362 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
3363 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3364 let scorer = Scorer::new(0);
3365 let payee = Payee::new(nodes[2]);
3367 // Path via node0 is channels {1, 3}. Limit them to 100 and 50 sats (total limit 50).
3368 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3369 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3370 short_channel_id: 1,
3373 cltv_expiry_delta: 0,
3374 htlc_minimum_msat: 0,
3375 htlc_maximum_msat: OptionalField::Present(100_000),
3376 fee_base_msat: 1_000_000,
3377 fee_proportional_millionths: 0,
3378 excess_data: Vec::new()
3380 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3381 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3382 short_channel_id: 3,
3385 cltv_expiry_delta: 0,
3386 htlc_minimum_msat: 0,
3387 htlc_maximum_msat: OptionalField::Present(50_000),
3389 fee_proportional_millionths: 0,
3390 excess_data: Vec::new()
3394 let route = get_route(&our_id, &payee, &net_graph_msg_handler.network_graph, None, 50_000, 42, Arc::clone(&logger), &scorer).unwrap();
3395 assert_eq!(route.paths.len(), 1);
3396 let mut total_amount_paid_msat = 0;
3397 for path in &route.paths {
3398 assert_eq!(path.len(), 2);
3399 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
3400 total_amount_paid_msat += path.last().unwrap().fee_msat;
3402 assert_eq!(total_amount_paid_msat, 50_000);
3407 fn simple_mpp_route_test() {
3408 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
3409 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3410 let scorer = Scorer::new(0);
3411 let payee = Payee::new(nodes[2]).with_features(InvoiceFeatures::known());
3413 // We need a route consisting of 3 paths:
3414 // From our node to node2 via node0, node7, node1 (three paths one hop each).
3415 // To achieve this, the amount being transferred should be around
3416 // the total capacity of these 3 paths.
3418 // First, we set limits on these (previously unlimited) channels.
3419 // Their aggregate capacity will be 50 + 60 + 180 = 290 sats.
3421 // Path via node0 is channels {1, 3}. Limit them to 100 and 50 sats (total limit 50).
3422 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3423 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3424 short_channel_id: 1,
3427 cltv_expiry_delta: 0,
3428 htlc_minimum_msat: 0,
3429 htlc_maximum_msat: OptionalField::Present(100_000),
3431 fee_proportional_millionths: 0,
3432 excess_data: Vec::new()
3434 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3435 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3436 short_channel_id: 3,
3439 cltv_expiry_delta: 0,
3440 htlc_minimum_msat: 0,
3441 htlc_maximum_msat: OptionalField::Present(50_000),
3443 fee_proportional_millionths: 0,
3444 excess_data: Vec::new()
3447 // Path via node7 is channels {12, 13}. Limit them to 60 and 60 sats
3448 // (total limit 60).
3449 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3450 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3451 short_channel_id: 12,
3454 cltv_expiry_delta: 0,
3455 htlc_minimum_msat: 0,
3456 htlc_maximum_msat: OptionalField::Present(60_000),
3458 fee_proportional_millionths: 0,
3459 excess_data: Vec::new()
3461 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
3462 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3463 short_channel_id: 13,
3466 cltv_expiry_delta: 0,
3467 htlc_minimum_msat: 0,
3468 htlc_maximum_msat: OptionalField::Present(60_000),
3470 fee_proportional_millionths: 0,
3471 excess_data: Vec::new()
3474 // Path via node1 is channels {2, 4}. Limit them to 200 and 180 sats
3475 // (total capacity 180 sats).
3476 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3477 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3478 short_channel_id: 2,
3481 cltv_expiry_delta: 0,
3482 htlc_minimum_msat: 0,
3483 htlc_maximum_msat: OptionalField::Present(200_000),
3485 fee_proportional_millionths: 0,
3486 excess_data: Vec::new()
3488 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
3489 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3490 short_channel_id: 4,
3493 cltv_expiry_delta: 0,
3494 htlc_minimum_msat: 0,
3495 htlc_maximum_msat: OptionalField::Present(180_000),
3497 fee_proportional_millionths: 0,
3498 excess_data: Vec::new()
3502 // Attempt to route more than available results in a failure.
3503 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
3504 &our_id, &payee, &net_graph_msg_handler.network_graph, None, 300_000, 42, Arc::clone(&logger), &scorer) {
3505 assert_eq!(err, "Failed to find a sufficient route to the given destination");
3506 } else { panic!(); }
3510 // Now, attempt to route 250 sats (just a bit below the capacity).
3511 // Our algorithm should provide us with these 3 paths.
3512 let route = get_route(&our_id, &payee, &net_graph_msg_handler.network_graph, None, 250_000, 42, Arc::clone(&logger), &scorer).unwrap();
3513 assert_eq!(route.paths.len(), 3);
3514 let mut total_amount_paid_msat = 0;
3515 for path in &route.paths {
3516 assert_eq!(path.len(), 2);
3517 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
3518 total_amount_paid_msat += path.last().unwrap().fee_msat;
3520 assert_eq!(total_amount_paid_msat, 250_000);
3524 // Attempt to route an exact amount is also fine
3525 let route = get_route(&our_id, &payee, &net_graph_msg_handler.network_graph, None, 290_000, 42, Arc::clone(&logger), &scorer).unwrap();
3526 assert_eq!(route.paths.len(), 3);
3527 let mut total_amount_paid_msat = 0;
3528 for path in &route.paths {
3529 assert_eq!(path.len(), 2);
3530 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
3531 total_amount_paid_msat += path.last().unwrap().fee_msat;
3533 assert_eq!(total_amount_paid_msat, 290_000);
3538 fn long_mpp_route_test() {
3539 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
3540 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3541 let scorer = Scorer::new(0);
3542 let payee = Payee::new(nodes[3]).with_features(InvoiceFeatures::known());
3544 // We need a route consisting of 3 paths:
3545 // From our node to node3 via {node0, node2}, {node7, node2, node4} and {node7, node2}.
3546 // Note that these paths overlap (channels 5, 12, 13).
3547 // We will route 300 sats.
3548 // Each path will have 100 sats capacity, those channels which
3549 // are used twice will have 200 sats capacity.
3551 // Disable other potential paths.
3552 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3553 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3554 short_channel_id: 2,
3557 cltv_expiry_delta: 0,
3558 htlc_minimum_msat: 0,
3559 htlc_maximum_msat: OptionalField::Present(100_000),
3561 fee_proportional_millionths: 0,
3562 excess_data: Vec::new()
3564 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3565 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3566 short_channel_id: 7,
3569 cltv_expiry_delta: 0,
3570 htlc_minimum_msat: 0,
3571 htlc_maximum_msat: OptionalField::Present(100_000),
3573 fee_proportional_millionths: 0,
3574 excess_data: Vec::new()
3577 // Path via {node0, node2} is channels {1, 3, 5}.
3578 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3579 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3580 short_channel_id: 1,
3583 cltv_expiry_delta: 0,
3584 htlc_minimum_msat: 0,
3585 htlc_maximum_msat: OptionalField::Present(100_000),
3587 fee_proportional_millionths: 0,
3588 excess_data: Vec::new()
3590 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3591 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3592 short_channel_id: 3,
3595 cltv_expiry_delta: 0,
3596 htlc_minimum_msat: 0,
3597 htlc_maximum_msat: OptionalField::Present(100_000),
3599 fee_proportional_millionths: 0,
3600 excess_data: Vec::new()
3603 // Capacity of 200 sats because this channel will be used by 3rd path as well.
3604 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(5)), 5);
3605 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3606 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3607 short_channel_id: 5,
3610 cltv_expiry_delta: 0,
3611 htlc_minimum_msat: 0,
3612 htlc_maximum_msat: OptionalField::Present(200_000),
3614 fee_proportional_millionths: 0,
3615 excess_data: Vec::new()
3618 // Path via {node7, node2, node4} is channels {12, 13, 6, 11}.
3619 // Add 100 sats to the capacities of {12, 13}, because these channels
3620 // are also used for 3rd path. 100 sats for the rest. Total capacity: 100 sats.
3621 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3622 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3623 short_channel_id: 12,
3626 cltv_expiry_delta: 0,
3627 htlc_minimum_msat: 0,
3628 htlc_maximum_msat: OptionalField::Present(200_000),
3630 fee_proportional_millionths: 0,
3631 excess_data: Vec::new()
3633 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
3634 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3635 short_channel_id: 13,
3638 cltv_expiry_delta: 0,
3639 htlc_minimum_msat: 0,
3640 htlc_maximum_msat: OptionalField::Present(200_000),
3642 fee_proportional_millionths: 0,
3643 excess_data: Vec::new()
3646 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3647 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3648 short_channel_id: 6,
3651 cltv_expiry_delta: 0,
3652 htlc_minimum_msat: 0,
3653 htlc_maximum_msat: OptionalField::Present(100_000),
3655 fee_proportional_millionths: 0,
3656 excess_data: Vec::new()
3658 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
3659 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3660 short_channel_id: 11,
3663 cltv_expiry_delta: 0,
3664 htlc_minimum_msat: 0,
3665 htlc_maximum_msat: OptionalField::Present(100_000),
3667 fee_proportional_millionths: 0,
3668 excess_data: Vec::new()
3671 // Path via {node7, node2} is channels {12, 13, 5}.
3672 // We already limited them to 200 sats (they are used twice for 100 sats).
3673 // Nothing to do here.
3676 // Attempt to route more than available results in a failure.
3677 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
3678 &our_id, &payee, &net_graph_msg_handler.network_graph, None, 350_000, 42, Arc::clone(&logger), &scorer) {
3679 assert_eq!(err, "Failed to find a sufficient route to the given destination");
3680 } else { panic!(); }
3684 // Now, attempt to route 300 sats (exact amount we can route).
3685 // Our algorithm should provide us with these 3 paths, 100 sats each.
3686 let route = get_route(&our_id, &payee, &net_graph_msg_handler.network_graph, None, 300_000, 42, Arc::clone(&logger), &scorer).unwrap();
3687 assert_eq!(route.paths.len(), 3);
3689 let mut total_amount_paid_msat = 0;
3690 for path in &route.paths {
3691 assert_eq!(path.last().unwrap().pubkey, nodes[3]);
3692 total_amount_paid_msat += path.last().unwrap().fee_msat;
3694 assert_eq!(total_amount_paid_msat, 300_000);
3700 fn mpp_cheaper_route_test() {
3701 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
3702 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3703 let scorer = Scorer::new(0);
3704 let payee = Payee::new(nodes[3]).with_features(InvoiceFeatures::known());
3706 // This test checks that if we have two cheaper paths and one more expensive path,
3707 // so that liquidity-wise any 2 of 3 combination is sufficient,
3708 // two cheaper paths will be taken.
3709 // These paths have equal available liquidity.
3711 // We need a combination of 3 paths:
3712 // From our node to node3 via {node0, node2}, {node7, node2, node4} and {node7, node2}.
3713 // Note that these paths overlap (channels 5, 12, 13).
3714 // Each path will have 100 sats capacity, those channels which
3715 // are used twice will have 200 sats capacity.
3717 // Disable other potential paths.
3718 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3719 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3720 short_channel_id: 2,
3723 cltv_expiry_delta: 0,
3724 htlc_minimum_msat: 0,
3725 htlc_maximum_msat: OptionalField::Present(100_000),
3727 fee_proportional_millionths: 0,
3728 excess_data: Vec::new()
3730 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3731 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3732 short_channel_id: 7,
3735 cltv_expiry_delta: 0,
3736 htlc_minimum_msat: 0,
3737 htlc_maximum_msat: OptionalField::Present(100_000),
3739 fee_proportional_millionths: 0,
3740 excess_data: Vec::new()
3743 // Path via {node0, node2} is channels {1, 3, 5}.
3744 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3745 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3746 short_channel_id: 1,
3749 cltv_expiry_delta: 0,
3750 htlc_minimum_msat: 0,
3751 htlc_maximum_msat: OptionalField::Present(100_000),
3753 fee_proportional_millionths: 0,
3754 excess_data: Vec::new()
3756 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3757 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3758 short_channel_id: 3,
3761 cltv_expiry_delta: 0,
3762 htlc_minimum_msat: 0,
3763 htlc_maximum_msat: OptionalField::Present(100_000),
3765 fee_proportional_millionths: 0,
3766 excess_data: Vec::new()
3769 // Capacity of 200 sats because this channel will be used by 3rd path as well.
3770 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(5)), 5);
3771 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3772 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3773 short_channel_id: 5,
3776 cltv_expiry_delta: 0,
3777 htlc_minimum_msat: 0,
3778 htlc_maximum_msat: OptionalField::Present(200_000),
3780 fee_proportional_millionths: 0,
3781 excess_data: Vec::new()
3784 // Path via {node7, node2, node4} is channels {12, 13, 6, 11}.
3785 // Add 100 sats to the capacities of {12, 13}, because these channels
3786 // are also used for 3rd path. 100 sats for the rest. Total capacity: 100 sats.
3787 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3788 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3789 short_channel_id: 12,
3792 cltv_expiry_delta: 0,
3793 htlc_minimum_msat: 0,
3794 htlc_maximum_msat: OptionalField::Present(200_000),
3796 fee_proportional_millionths: 0,
3797 excess_data: Vec::new()
3799 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
3800 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3801 short_channel_id: 13,
3804 cltv_expiry_delta: 0,
3805 htlc_minimum_msat: 0,
3806 htlc_maximum_msat: OptionalField::Present(200_000),
3808 fee_proportional_millionths: 0,
3809 excess_data: Vec::new()
3812 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3813 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3814 short_channel_id: 6,
3817 cltv_expiry_delta: 0,
3818 htlc_minimum_msat: 0,
3819 htlc_maximum_msat: OptionalField::Present(100_000),
3820 fee_base_msat: 1_000,
3821 fee_proportional_millionths: 0,
3822 excess_data: Vec::new()
3824 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
3825 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3826 short_channel_id: 11,
3829 cltv_expiry_delta: 0,
3830 htlc_minimum_msat: 0,
3831 htlc_maximum_msat: OptionalField::Present(100_000),
3833 fee_proportional_millionths: 0,
3834 excess_data: Vec::new()
3837 // Path via {node7, node2} is channels {12, 13, 5}.
3838 // We already limited them to 200 sats (they are used twice for 100 sats).
3839 // Nothing to do here.
3842 // Now, attempt to route 180 sats.
3843 // Our algorithm should provide us with these 2 paths.
3844 let route = get_route(&our_id, &payee, &net_graph_msg_handler.network_graph, None, 180_000, 42, Arc::clone(&logger), &scorer).unwrap();
3845 assert_eq!(route.paths.len(), 2);
3847 let mut total_value_transferred_msat = 0;
3848 let mut total_paid_msat = 0;
3849 for path in &route.paths {
3850 assert_eq!(path.last().unwrap().pubkey, nodes[3]);
3851 total_value_transferred_msat += path.last().unwrap().fee_msat;
3853 total_paid_msat += hop.fee_msat;
3856 // If we paid fee, this would be higher.
3857 assert_eq!(total_value_transferred_msat, 180_000);
3858 let total_fees_paid = total_paid_msat - total_value_transferred_msat;
3859 assert_eq!(total_fees_paid, 0);
3864 fn fees_on_mpp_route_test() {
3865 // This test makes sure that MPP algorithm properly takes into account
3866 // fees charged on the channels, by making the fees impactful:
3867 // if the fee is not properly accounted for, the behavior is different.
3868 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
3869 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3870 let scorer = Scorer::new(0);
3871 let payee = Payee::new(nodes[3]).with_features(InvoiceFeatures::known());
3873 // We need a route consisting of 2 paths:
3874 // From our node to node3 via {node0, node2} and {node7, node2, node4}.
3875 // We will route 200 sats, Each path will have 100 sats capacity.
3877 // This test is not particularly stable: e.g.,
3878 // there's a way to route via {node0, node2, node4}.
3879 // It works while pathfinding is deterministic, but can be broken otherwise.
3880 // It's fine to ignore this concern for now.
3882 // Disable other potential paths.
3883 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3884 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3885 short_channel_id: 2,
3888 cltv_expiry_delta: 0,
3889 htlc_minimum_msat: 0,
3890 htlc_maximum_msat: OptionalField::Present(100_000),
3892 fee_proportional_millionths: 0,
3893 excess_data: Vec::new()
3896 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3897 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3898 short_channel_id: 7,
3901 cltv_expiry_delta: 0,
3902 htlc_minimum_msat: 0,
3903 htlc_maximum_msat: OptionalField::Present(100_000),
3905 fee_proportional_millionths: 0,
3906 excess_data: Vec::new()
3909 // Path via {node0, node2} is channels {1, 3, 5}.
3910 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3911 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3912 short_channel_id: 1,
3915 cltv_expiry_delta: 0,
3916 htlc_minimum_msat: 0,
3917 htlc_maximum_msat: OptionalField::Present(100_000),
3919 fee_proportional_millionths: 0,
3920 excess_data: Vec::new()
3922 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3923 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3924 short_channel_id: 3,
3927 cltv_expiry_delta: 0,
3928 htlc_minimum_msat: 0,
3929 htlc_maximum_msat: OptionalField::Present(100_000),
3931 fee_proportional_millionths: 0,
3932 excess_data: Vec::new()
3935 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(5)), 5);
3936 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3937 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3938 short_channel_id: 5,
3941 cltv_expiry_delta: 0,
3942 htlc_minimum_msat: 0,
3943 htlc_maximum_msat: OptionalField::Present(100_000),
3945 fee_proportional_millionths: 0,
3946 excess_data: Vec::new()
3949 // Path via {node7, node2, node4} is channels {12, 13, 6, 11}.
3950 // All channels should be 100 sats capacity. But for the fee experiment,
3951 // we'll add absolute fee of 150 sats paid for the use channel 6 (paid to node2 on channel 13).
3952 // Since channel 12 allows to deliver only 250 sats to channel 13, channel 13 can transfer only
3953 // 100 sats (and pay 150 sats in fees for the use of channel 6),
3954 // so no matter how large are other channels,
3955 // the whole path will be limited by 100 sats with just these 2 conditions:
3956 // - channel 12 capacity is 250 sats
3957 // - fee for channel 6 is 150 sats
3958 // Let's test this by enforcing these 2 conditions and removing other limits.
3959 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3960 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3961 short_channel_id: 12,
3964 cltv_expiry_delta: 0,
3965 htlc_minimum_msat: 0,
3966 htlc_maximum_msat: OptionalField::Present(250_000),
3968 fee_proportional_millionths: 0,
3969 excess_data: Vec::new()
3971 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
3972 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3973 short_channel_id: 13,
3976 cltv_expiry_delta: 0,
3977 htlc_minimum_msat: 0,
3978 htlc_maximum_msat: OptionalField::Absent,
3980 fee_proportional_millionths: 0,
3981 excess_data: Vec::new()
3984 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3985 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3986 short_channel_id: 6,
3989 cltv_expiry_delta: 0,
3990 htlc_minimum_msat: 0,
3991 htlc_maximum_msat: OptionalField::Absent,
3992 fee_base_msat: 150_000,
3993 fee_proportional_millionths: 0,
3994 excess_data: Vec::new()
3996 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
3997 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3998 short_channel_id: 11,
4001 cltv_expiry_delta: 0,
4002 htlc_minimum_msat: 0,
4003 htlc_maximum_msat: OptionalField::Absent,
4005 fee_proportional_millionths: 0,
4006 excess_data: Vec::new()
4010 // Attempt to route more than available results in a failure.
4011 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
4012 &our_id, &payee, &net_graph_msg_handler.network_graph, None, 210_000, 42, Arc::clone(&logger), &scorer) {
4013 assert_eq!(err, "Failed to find a sufficient route to the given destination");
4014 } else { panic!(); }
4018 // Now, attempt to route 200 sats (exact amount we can route).
4019 let route = get_route(&our_id, &payee, &net_graph_msg_handler.network_graph, None, 200_000, 42, Arc::clone(&logger), &scorer).unwrap();
4020 assert_eq!(route.paths.len(), 2);
4022 let mut total_amount_paid_msat = 0;
4023 for path in &route.paths {
4024 assert_eq!(path.last().unwrap().pubkey, nodes[3]);
4025 total_amount_paid_msat += path.last().unwrap().fee_msat;
4027 assert_eq!(total_amount_paid_msat, 200_000);
4028 assert_eq!(route.get_total_fees(), 150_000);
4034 fn drop_lowest_channel_mpp_route_test() {
4035 // This test checks that low-capacity channel is dropped when after
4036 // path finding we realize that we found more capacity than we need.
4037 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
4038 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
4039 let scorer = Scorer::new(0);
4040 let payee = Payee::new(nodes[2]).with_features(InvoiceFeatures::known());
4042 // We need a route consisting of 3 paths:
4043 // From our node to node2 via node0, node7, node1 (three paths one hop each).
4045 // The first and the second paths should be sufficient, but the third should be
4046 // cheaper, so that we select it but drop later.
4048 // First, we set limits on these (previously unlimited) channels.
4049 // Their aggregate capacity will be 50 + 60 + 20 = 130 sats.
4051 // Path via node0 is channels {1, 3}. Limit them to 100 and 50 sats (total limit 50);
4052 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4053 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4054 short_channel_id: 1,
4057 cltv_expiry_delta: 0,
4058 htlc_minimum_msat: 0,
4059 htlc_maximum_msat: OptionalField::Present(100_000),
4061 fee_proportional_millionths: 0,
4062 excess_data: Vec::new()
4064 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
4065 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4066 short_channel_id: 3,
4069 cltv_expiry_delta: 0,
4070 htlc_minimum_msat: 0,
4071 htlc_maximum_msat: OptionalField::Present(50_000),
4073 fee_proportional_millionths: 0,
4074 excess_data: Vec::new()
4077 // Path via node7 is channels {12, 13}. Limit them to 60 and 60 sats (total limit 60);
4078 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4079 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4080 short_channel_id: 12,
4083 cltv_expiry_delta: 0,
4084 htlc_minimum_msat: 0,
4085 htlc_maximum_msat: OptionalField::Present(60_000),
4087 fee_proportional_millionths: 0,
4088 excess_data: Vec::new()
4090 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
4091 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4092 short_channel_id: 13,
4095 cltv_expiry_delta: 0,
4096 htlc_minimum_msat: 0,
4097 htlc_maximum_msat: OptionalField::Present(60_000),
4099 fee_proportional_millionths: 0,
4100 excess_data: Vec::new()
4103 // Path via node1 is channels {2, 4}. Limit them to 20 and 20 sats (total capacity 20 sats).
4104 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4105 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4106 short_channel_id: 2,
4109 cltv_expiry_delta: 0,
4110 htlc_minimum_msat: 0,
4111 htlc_maximum_msat: OptionalField::Present(20_000),
4113 fee_proportional_millionths: 0,
4114 excess_data: Vec::new()
4116 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
4117 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4118 short_channel_id: 4,
4121 cltv_expiry_delta: 0,
4122 htlc_minimum_msat: 0,
4123 htlc_maximum_msat: OptionalField::Present(20_000),
4125 fee_proportional_millionths: 0,
4126 excess_data: Vec::new()
4130 // Attempt to route more than available results in a failure.
4131 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
4132 &our_id, &payee, &net_graph_msg_handler.network_graph, None, 150_000, 42, Arc::clone(&logger), &scorer) {
4133 assert_eq!(err, "Failed to find a sufficient route to the given destination");
4134 } else { panic!(); }
4138 // Now, attempt to route 125 sats (just a bit below the capacity of 3 channels).
4139 // Our algorithm should provide us with these 3 paths.
4140 let route = get_route(&our_id, &payee, &net_graph_msg_handler.network_graph, None, 125_000, 42, Arc::clone(&logger), &scorer).unwrap();
4141 assert_eq!(route.paths.len(), 3);
4142 let mut total_amount_paid_msat = 0;
4143 for path in &route.paths {
4144 assert_eq!(path.len(), 2);
4145 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
4146 total_amount_paid_msat += path.last().unwrap().fee_msat;
4148 assert_eq!(total_amount_paid_msat, 125_000);
4152 // Attempt to route without the last small cheap channel
4153 let route = get_route(&our_id, &payee, &net_graph_msg_handler.network_graph, None, 90_000, 42, Arc::clone(&logger), &scorer).unwrap();
4154 assert_eq!(route.paths.len(), 2);
4155 let mut total_amount_paid_msat = 0;
4156 for path in &route.paths {
4157 assert_eq!(path.len(), 2);
4158 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
4159 total_amount_paid_msat += path.last().unwrap().fee_msat;
4161 assert_eq!(total_amount_paid_msat, 90_000);
4166 fn min_criteria_consistency() {
4167 // Test that we don't use an inconsistent metric between updating and walking nodes during
4168 // our Dijkstra's pass. In the initial version of MPP, the "best source" for a given node
4169 // was updated with a different criterion from the heap sorting, resulting in loops in
4170 // calculated paths. We test for that specific case here.
4172 // We construct a network that looks like this:
4174 // node2 -1(3)2- node3
4178 // node1 -1(5)2- node4 -1(1)2- node6
4184 // We create a loop on the side of our real path - our destination is node 6, with a
4185 // previous hop of node 4. From 4, the cheapest previous path is channel 2 from node 2,
4186 // followed by node 3 over channel 3. Thereafter, the cheapest next-hop is back to node 4
4187 // (this time over channel 4). Channel 4 has 0 htlc_minimum_msat whereas channel 1 (the
4188 // other channel with a previous-hop of node 4) has a high (but irrelevant to the overall
4189 // payment) htlc_minimum_msat. In the original algorithm, this resulted in node4's
4190 // "previous hop" being set to node 3, creating a loop in the path.
4191 let secp_ctx = Secp256k1::new();
4192 let logger = Arc::new(test_utils::TestLogger::new());
4193 let network_graph = NetworkGraph::new(genesis_block(Network::Testnet).header.block_hash());
4194 let net_graph_msg_handler = NetGraphMsgHandler::new(network_graph, None, Arc::clone(&logger));
4195 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
4196 let scorer = Scorer::new(0);
4197 let payee = Payee::new(nodes[6]);
4199 add_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, &privkeys[1], ChannelFeatures::from_le_bytes(id_to_feature_flags(6)), 6);
4200 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4201 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4202 short_channel_id: 6,
4205 cltv_expiry_delta: (6 << 8) | 0,
4206 htlc_minimum_msat: 0,
4207 htlc_maximum_msat: OptionalField::Absent,
4209 fee_proportional_millionths: 0,
4210 excess_data: Vec::new()
4212 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[1], NodeFeatures::from_le_bytes(id_to_feature_flags(1)), 0);
4214 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], &privkeys[4], ChannelFeatures::from_le_bytes(id_to_feature_flags(5)), 5);
4215 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
4216 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4217 short_channel_id: 5,
4220 cltv_expiry_delta: (5 << 8) | 0,
4221 htlc_minimum_msat: 0,
4222 htlc_maximum_msat: OptionalField::Absent,
4224 fee_proportional_millionths: 0,
4225 excess_data: Vec::new()
4227 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[4], NodeFeatures::from_le_bytes(id_to_feature_flags(4)), 0);
4229 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(4)), 4);
4230 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
4231 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4232 short_channel_id: 4,
4235 cltv_expiry_delta: (4 << 8) | 0,
4236 htlc_minimum_msat: 0,
4237 htlc_maximum_msat: OptionalField::Absent,
4239 fee_proportional_millionths: 0,
4240 excess_data: Vec::new()
4242 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[3], NodeFeatures::from_le_bytes(id_to_feature_flags(3)), 0);
4244 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[3], &privkeys[2], ChannelFeatures::from_le_bytes(id_to_feature_flags(3)), 3);
4245 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[3], UnsignedChannelUpdate {
4246 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4247 short_channel_id: 3,
4250 cltv_expiry_delta: (3 << 8) | 0,
4251 htlc_minimum_msat: 0,
4252 htlc_maximum_msat: OptionalField::Absent,
4254 fee_proportional_millionths: 0,
4255 excess_data: Vec::new()
4257 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[2], NodeFeatures::from_le_bytes(id_to_feature_flags(2)), 0);
4259 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], &privkeys[4], ChannelFeatures::from_le_bytes(id_to_feature_flags(2)), 2);
4260 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4261 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4262 short_channel_id: 2,
4265 cltv_expiry_delta: (2 << 8) | 0,
4266 htlc_minimum_msat: 0,
4267 htlc_maximum_msat: OptionalField::Absent,
4269 fee_proportional_millionths: 0,
4270 excess_data: Vec::new()
4273 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], &privkeys[6], ChannelFeatures::from_le_bytes(id_to_feature_flags(1)), 1);
4274 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
4275 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4276 short_channel_id: 1,
4279 cltv_expiry_delta: (1 << 8) | 0,
4280 htlc_minimum_msat: 100,
4281 htlc_maximum_msat: OptionalField::Absent,
4283 fee_proportional_millionths: 0,
4284 excess_data: Vec::new()
4286 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[6], NodeFeatures::from_le_bytes(id_to_feature_flags(6)), 0);
4289 // Now ensure the route flows simply over nodes 1 and 4 to 6.
4290 let route = get_route(&our_id, &payee, &net_graph_msg_handler.network_graph, None, 10_000, 42, Arc::clone(&logger), &scorer).unwrap();
4291 assert_eq!(route.paths.len(), 1);
4292 assert_eq!(route.paths[0].len(), 3);
4294 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
4295 assert_eq!(route.paths[0][0].short_channel_id, 6);
4296 assert_eq!(route.paths[0][0].fee_msat, 100);
4297 assert_eq!(route.paths[0][0].cltv_expiry_delta, (5 << 8) | 0);
4298 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(1));
4299 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(6));
4301 assert_eq!(route.paths[0][1].pubkey, nodes[4]);
4302 assert_eq!(route.paths[0][1].short_channel_id, 5);
4303 assert_eq!(route.paths[0][1].fee_msat, 0);
4304 assert_eq!(route.paths[0][1].cltv_expiry_delta, (1 << 8) | 0);
4305 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(4));
4306 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(5));
4308 assert_eq!(route.paths[0][2].pubkey, nodes[6]);
4309 assert_eq!(route.paths[0][2].short_channel_id, 1);
4310 assert_eq!(route.paths[0][2].fee_msat, 10_000);
4311 assert_eq!(route.paths[0][2].cltv_expiry_delta, 42);
4312 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(6));
4313 assert_eq!(route.paths[0][2].channel_features.le_flags(), &id_to_feature_flags(1));
4319 fn exact_fee_liquidity_limit() {
4320 // Test that if, while walking the graph, we find a hop that has exactly enough liquidity
4321 // for us, including later hop fees, we take it. In the first version of our MPP algorithm
4322 // we calculated fees on a higher value, resulting in us ignoring such paths.
4323 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
4324 let (our_privkey, our_id, _, nodes) = get_nodes(&secp_ctx);
4325 let scorer = Scorer::new(0);
4326 let payee = Payee::new(nodes[2]);
4328 // We modify the graph to set the htlc_maximum of channel 2 to below the value we wish to
4330 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4331 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4332 short_channel_id: 2,
4335 cltv_expiry_delta: 0,
4336 htlc_minimum_msat: 0,
4337 htlc_maximum_msat: OptionalField::Present(85_000),
4339 fee_proportional_millionths: 0,
4340 excess_data: Vec::new()
4343 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4344 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4345 short_channel_id: 12,
4348 cltv_expiry_delta: (4 << 8) | 1,
4349 htlc_minimum_msat: 0,
4350 htlc_maximum_msat: OptionalField::Present(270_000),
4352 fee_proportional_millionths: 1000000,
4353 excess_data: Vec::new()
4357 // Now, attempt to route 90 sats, which is exactly 90 sats at the last hop, plus the
4358 // 200% fee charged channel 13 in the 1-to-2 direction.
4359 let route = get_route(&our_id, &payee, &net_graph_msg_handler.network_graph, None, 90_000, 42, Arc::clone(&logger), &scorer).unwrap();
4360 assert_eq!(route.paths.len(), 1);
4361 assert_eq!(route.paths[0].len(), 2);
4363 assert_eq!(route.paths[0][0].pubkey, nodes[7]);
4364 assert_eq!(route.paths[0][0].short_channel_id, 12);
4365 assert_eq!(route.paths[0][0].fee_msat, 90_000*2);
4366 assert_eq!(route.paths[0][0].cltv_expiry_delta, (13 << 8) | 1);
4367 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(8));
4368 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(12));
4370 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
4371 assert_eq!(route.paths[0][1].short_channel_id, 13);
4372 assert_eq!(route.paths[0][1].fee_msat, 90_000);
4373 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
4374 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
4375 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(13));
4380 fn htlc_max_reduction_below_min() {
4381 // Test that if, while walking the graph, we reduce the value being sent to meet an
4382 // htlc_maximum_msat, we don't end up undershooting a later htlc_minimum_msat. In the
4383 // initial version of MPP we'd accept such routes but reject them while recalculating fees,
4384 // resulting in us thinking there is no possible path, even if other paths exist.
4385 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
4386 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
4387 let scorer = Scorer::new(0);
4388 let payee = Payee::new(nodes[2]).with_features(InvoiceFeatures::known());
4390 // We modify the graph to set the htlc_minimum of channel 2 and 4 as needed - channel 2
4391 // gets an htlc_maximum_msat of 80_000 and channel 4 an htlc_minimum_msat of 90_000. We
4392 // then try to send 90_000.
4393 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4394 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4395 short_channel_id: 2,
4398 cltv_expiry_delta: 0,
4399 htlc_minimum_msat: 0,
4400 htlc_maximum_msat: OptionalField::Present(80_000),
4402 fee_proportional_millionths: 0,
4403 excess_data: Vec::new()
4405 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
4406 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4407 short_channel_id: 4,
4410 cltv_expiry_delta: (4 << 8) | 1,
4411 htlc_minimum_msat: 90_000,
4412 htlc_maximum_msat: OptionalField::Absent,
4414 fee_proportional_millionths: 0,
4415 excess_data: Vec::new()
4419 // Now, attempt to route 90 sats, hitting the htlc_minimum on channel 4, but
4420 // overshooting the htlc_maximum on channel 2. Thus, we should pick the (absurdly
4421 // expensive) channels 12-13 path.
4422 let route = get_route(&our_id, &payee, &net_graph_msg_handler.network_graph, None, 90_000, 42, Arc::clone(&logger), &scorer).unwrap();
4423 assert_eq!(route.paths.len(), 1);
4424 assert_eq!(route.paths[0].len(), 2);
4426 assert_eq!(route.paths[0][0].pubkey, nodes[7]);
4427 assert_eq!(route.paths[0][0].short_channel_id, 12);
4428 assert_eq!(route.paths[0][0].fee_msat, 90_000*2);
4429 assert_eq!(route.paths[0][0].cltv_expiry_delta, (13 << 8) | 1);
4430 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(8));
4431 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(12));
4433 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
4434 assert_eq!(route.paths[0][1].short_channel_id, 13);
4435 assert_eq!(route.paths[0][1].fee_msat, 90_000);
4436 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
4437 assert_eq!(route.paths[0][1].node_features.le_flags(), InvoiceFeatures::known().le_flags());
4438 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(13));
4443 fn multiple_direct_first_hops() {
4444 // Previously we'd only ever considered one first hop path per counterparty.
4445 // However, as we don't restrict users to one channel per peer, we really need to support
4446 // looking at all first hop paths.
4447 // Here we test that we do not ignore all-but-the-last first hop paths per counterparty (as
4448 // we used to do by overwriting the `first_hop_targets` hashmap entry) and that we can MPP
4449 // route over multiple channels with the same first hop.
4450 let secp_ctx = Secp256k1::new();
4451 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
4452 let logger = Arc::new(test_utils::TestLogger::new());
4453 let network_graph = NetworkGraph::new(genesis_block(Network::Testnet).header.block_hash());
4454 let scorer = Scorer::new(0);
4455 let payee = Payee::new(nodes[0]).with_features(InvoiceFeatures::known());
4458 let route = get_route(&our_id, &payee, &network_graph, Some(&[
4459 &get_channel_details(Some(3), nodes[0], InitFeatures::known(), 200_000),
4460 &get_channel_details(Some(2), nodes[0], InitFeatures::known(), 10_000),
4461 ]), 100_000, 42, Arc::clone(&logger), &scorer).unwrap();
4462 assert_eq!(route.paths.len(), 1);
4463 assert_eq!(route.paths[0].len(), 1);
4465 assert_eq!(route.paths[0][0].pubkey, nodes[0]);
4466 assert_eq!(route.paths[0][0].short_channel_id, 3);
4467 assert_eq!(route.paths[0][0].fee_msat, 100_000);
4470 let route = get_route(&our_id, &payee, &network_graph, Some(&[
4471 &get_channel_details(Some(3), nodes[0], InitFeatures::known(), 50_000),
4472 &get_channel_details(Some(2), nodes[0], InitFeatures::known(), 50_000),
4473 ]), 100_000, 42, Arc::clone(&logger), &scorer).unwrap();
4474 assert_eq!(route.paths.len(), 2);
4475 assert_eq!(route.paths[0].len(), 1);
4476 assert_eq!(route.paths[1].len(), 1);
4478 assert_eq!(route.paths[0][0].pubkey, nodes[0]);
4479 assert_eq!(route.paths[0][0].short_channel_id, 3);
4480 assert_eq!(route.paths[0][0].fee_msat, 50_000);
4482 assert_eq!(route.paths[1][0].pubkey, nodes[0]);
4483 assert_eq!(route.paths[1][0].short_channel_id, 2);
4484 assert_eq!(route.paths[1][0].fee_msat, 50_000);
4489 fn prefers_shorter_route_with_higher_fees() {
4490 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
4491 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
4492 let payee = Payee::new(nodes[6]).with_route_hints(last_hops(&nodes));
4494 // Without penalizing each hop 100 msats, a longer path with lower fees is chosen.
4495 let scorer = Scorer::new(0);
4496 let route = get_route(
4497 &our_id, &payee, &net_graph_msg_handler.network_graph, None, 100, 42,
4498 Arc::clone(&logger), &scorer
4500 let path = route.paths[0].iter().map(|hop| hop.short_channel_id).collect::<Vec<_>>();
4502 assert_eq!(route.get_total_fees(), 100);
4503 assert_eq!(route.get_total_amount(), 100);
4504 assert_eq!(path, vec![2, 4, 6, 11, 8]);
4506 // Applying a 100 msat penalty to each hop results in taking channels 7 and 10 to nodes[6]
4507 // from nodes[2] rather than channel 6, 11, and 8, even though the longer path is cheaper.
4508 let scorer = Scorer::new(100);
4509 let route = get_route(
4510 &our_id, &payee, &net_graph_msg_handler.network_graph, None, 100, 42,
4511 Arc::clone(&logger), &scorer
4513 let path = route.paths[0].iter().map(|hop| hop.short_channel_id).collect::<Vec<_>>();
4515 assert_eq!(route.get_total_fees(), 300);
4516 assert_eq!(route.get_total_amount(), 100);
4517 assert_eq!(path, vec![2, 4, 7, 10]);
4520 struct BadChannelScorer {
4521 short_channel_id: u64,
4524 impl routing::Score for BadChannelScorer {
4525 fn channel_penalty_msat(&self, short_channel_id: u64, _source: &NodeId, _target: &NodeId) -> u64 {
4526 if short_channel_id == self.short_channel_id { u64::max_value() } else { 0 }
4530 struct BadNodeScorer {
4534 impl routing::Score for BadNodeScorer {
4535 fn channel_penalty_msat(&self, _short_channel_id: u64, _source: &NodeId, target: &NodeId) -> u64 {
4536 if *target == self.node_id { u64::max_value() } else { 0 }
4541 fn avoids_routing_through_bad_channels_and_nodes() {
4542 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
4543 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
4544 let payee = Payee::new(nodes[6]).with_route_hints(last_hops(&nodes));
4546 // A path to nodes[6] exists when no penalties are applied to any channel.
4547 let scorer = Scorer::new(0);
4548 let route = get_route(
4549 &our_id, &payee, &net_graph_msg_handler.network_graph, None, 100, 42,
4550 Arc::clone(&logger), &scorer
4552 let path = route.paths[0].iter().map(|hop| hop.short_channel_id).collect::<Vec<_>>();
4554 assert_eq!(route.get_total_fees(), 100);
4555 assert_eq!(route.get_total_amount(), 100);
4556 assert_eq!(path, vec![2, 4, 6, 11, 8]);
4558 // A different path to nodes[6] exists if channel 6 cannot be routed over.
4559 let scorer = BadChannelScorer { short_channel_id: 6 };
4560 let route = get_route(
4561 &our_id, &payee, &net_graph_msg_handler.network_graph, None, 100, 42,
4562 Arc::clone(&logger), &scorer
4564 let path = route.paths[0].iter().map(|hop| hop.short_channel_id).collect::<Vec<_>>();
4566 assert_eq!(route.get_total_fees(), 300);
4567 assert_eq!(route.get_total_amount(), 100);
4568 assert_eq!(path, vec![2, 4, 7, 10]);
4570 // A path to nodes[6] does not exist if nodes[2] cannot be routed through.
4571 let scorer = BadNodeScorer { node_id: NodeId::from_pubkey(&nodes[2]) };
4573 &our_id, &payee, &net_graph_msg_handler.network_graph, None, 100, 42,
4574 Arc::clone(&logger), &scorer
4576 Err(LightningError { err, .. } ) => {
4577 assert_eq!(err, "Failed to find a path to the given destination");
4579 Ok(_) => panic!("Expected error"),
4584 fn total_fees_single_path() {
4588 pubkey: PublicKey::from_slice(&hex::decode("02eec7245d6b7d2ccb30380bfbe2a3648cd7a942653f5aa340edcea1f283686619").unwrap()[..]).unwrap(),
4589 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
4590 short_channel_id: 0, fee_msat: 100, cltv_expiry_delta: 0
4593 pubkey: PublicKey::from_slice(&hex::decode("0324653eac434488002cc06bbfb7f10fe18991e35f9fe4302dbea6d2353dc0ab1c").unwrap()[..]).unwrap(),
4594 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
4595 short_channel_id: 0, fee_msat: 150, cltv_expiry_delta: 0
4598 pubkey: PublicKey::from_slice(&hex::decode("027f31ebc5462c1fdce1b737ecff52d37d75dea43ce11c74d25aa297165faa2007").unwrap()[..]).unwrap(),
4599 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
4600 short_channel_id: 0, fee_msat: 225, cltv_expiry_delta: 0
4605 assert_eq!(route.get_total_fees(), 250);
4606 assert_eq!(route.get_total_amount(), 225);
4610 fn total_fees_multi_path() {
4614 pubkey: PublicKey::from_slice(&hex::decode("02eec7245d6b7d2ccb30380bfbe2a3648cd7a942653f5aa340edcea1f283686619").unwrap()[..]).unwrap(),
4615 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
4616 short_channel_id: 0, fee_msat: 100, cltv_expiry_delta: 0
4619 pubkey: PublicKey::from_slice(&hex::decode("0324653eac434488002cc06bbfb7f10fe18991e35f9fe4302dbea6d2353dc0ab1c").unwrap()[..]).unwrap(),
4620 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
4621 short_channel_id: 0, fee_msat: 150, cltv_expiry_delta: 0
4625 pubkey: PublicKey::from_slice(&hex::decode("02eec7245d6b7d2ccb30380bfbe2a3648cd7a942653f5aa340edcea1f283686619").unwrap()[..]).unwrap(),
4626 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
4627 short_channel_id: 0, fee_msat: 100, cltv_expiry_delta: 0
4630 pubkey: PublicKey::from_slice(&hex::decode("0324653eac434488002cc06bbfb7f10fe18991e35f9fe4302dbea6d2353dc0ab1c").unwrap()[..]).unwrap(),
4631 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
4632 short_channel_id: 0, fee_msat: 150, cltv_expiry_delta: 0
4637 assert_eq!(route.get_total_fees(), 200);
4638 assert_eq!(route.get_total_amount(), 300);
4642 fn total_empty_route_no_panic() {
4643 // In an earlier version of `Route::get_total_fees` and `Route::get_total_amount`, they
4644 // would both panic if the route was completely empty. We test to ensure they return 0
4645 // here, even though its somewhat nonsensical as a route.
4646 let route = Route { paths: Vec::new() };
4648 assert_eq!(route.get_total_fees(), 0);
4649 assert_eq!(route.get_total_amount(), 0);
4652 #[cfg(not(feature = "no-std"))]
4653 pub(super) fn random_init_seed() -> u64 {
4654 // Because the default HashMap in std pulls OS randomness, we can use it as a (bad) RNG.
4655 use core::hash::{BuildHasher, Hasher};
4656 let seed = std::collections::hash_map::RandomState::new().build_hasher().finish();
4657 println!("Using seed of {}", seed);
4660 #[cfg(not(feature = "no-std"))]
4661 use util::ser::Readable;
4664 #[cfg(not(feature = "no-std"))]
4665 fn generate_routes() {
4666 let mut d = match super::test_utils::get_route_file() {
4673 let graph = NetworkGraph::read(&mut d).unwrap();
4674 let scorer = Scorer::new(0);
4676 // First, get 100 (source, destination) pairs for which route-getting actually succeeds...
4677 let mut seed = random_init_seed() as usize;
4678 let nodes = graph.read_only().nodes().clone();
4679 'load_endpoints: for _ in 0..10 {
4681 seed = seed.overflowing_mul(0xdeadbeef).0;
4682 let src = &PublicKey::from_slice(nodes.keys().skip(seed % nodes.len()).next().unwrap().as_slice()).unwrap();
4683 seed = seed.overflowing_mul(0xdeadbeef).0;
4684 let dst = PublicKey::from_slice(nodes.keys().skip(seed % nodes.len()).next().unwrap().as_slice()).unwrap();
4685 let payee = Payee::new(dst);
4686 let amt = seed as u64 % 200_000_000;
4687 if get_route(src, &payee, &graph, None, amt, 42, &test_utils::TestLogger::new(), &scorer).is_ok() {
4688 continue 'load_endpoints;
4695 #[cfg(not(feature = "no-std"))]
4696 fn generate_routes_mpp() {
4697 let mut d = match super::test_utils::get_route_file() {
4704 let graph = NetworkGraph::read(&mut d).unwrap();
4705 let scorer = Scorer::new(0);
4707 // First, get 100 (source, destination) pairs for which route-getting actually succeeds...
4708 let mut seed = random_init_seed() as usize;
4709 let nodes = graph.read_only().nodes().clone();
4710 'load_endpoints: for _ in 0..10 {
4712 seed = seed.overflowing_mul(0xdeadbeef).0;
4713 let src = &PublicKey::from_slice(nodes.keys().skip(seed % nodes.len()).next().unwrap().as_slice()).unwrap();
4714 seed = seed.overflowing_mul(0xdeadbeef).0;
4715 let dst = PublicKey::from_slice(nodes.keys().skip(seed % nodes.len()).next().unwrap().as_slice()).unwrap();
4716 let payee = Payee::new(dst).with_features(InvoiceFeatures::known());
4717 let amt = seed as u64 % 200_000_000;
4718 if get_route(src, &payee, &graph, None, amt, 42, &test_utils::TestLogger::new(), &scorer).is_ok() {
4719 continue 'load_endpoints;
4726 #[cfg(all(test, not(feature = "no-std")))]
4727 pub(crate) mod test_utils {
4729 /// Tries to open a network graph file, or panics with a URL to fetch it.
4730 pub(crate) fn get_route_file() -> Result<std::fs::File, &'static str> {
4731 let res = File::open("net_graph-2021-05-31.bin") // By default we're run in RL/lightning
4732 .or_else(|_| File::open("lightning/net_graph-2021-05-31.bin")) // We may be run manually in RL/
4733 .or_else(|_| { // Fall back to guessing based on the binary location
4734 // path is likely something like .../rust-lightning/target/debug/deps/lightning-...
4735 let mut path = std::env::current_exe().unwrap();
4736 path.pop(); // lightning-...
4738 path.pop(); // debug
4739 path.pop(); // target
4740 path.push("lightning");
4741 path.push("net_graph-2021-05-31.bin");
4742 eprintln!("{}", path.to_str().unwrap());
4745 .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");
4746 #[cfg(require_route_graph_test)]
4747 return Ok(res.unwrap());
4748 #[cfg(not(require_route_graph_test))]
4753 #[cfg(all(test, feature = "unstable", not(feature = "no-std")))]
4756 use routing::scorer::Scorer;
4757 use util::logger::{Logger, Record};
4761 struct DummyLogger {}
4762 impl Logger for DummyLogger {
4763 fn log(&self, _record: &Record) {}
4767 fn generate_routes(bench: &mut Bencher) {
4768 let mut d = test_utils::get_route_file().unwrap();
4769 let graph = NetworkGraph::read(&mut d).unwrap();
4770 let nodes = graph.read_only().nodes().clone();
4771 let scorer = Scorer::new(0);
4773 // First, get 100 (source, destination) pairs for which route-getting actually succeeds...
4774 let mut path_endpoints = Vec::new();
4775 let mut seed: usize = 0xdeadbeef;
4776 'load_endpoints: for _ in 0..100 {
4779 let src = PublicKey::from_slice(nodes.keys().skip(seed % nodes.len()).next().unwrap().as_slice()).unwrap();
4781 let dst = PublicKey::from_slice(nodes.keys().skip(seed % nodes.len()).next().unwrap().as_slice()).unwrap();
4782 let payee = Payee::new(dst);
4783 let amt = seed as u64 % 1_000_000;
4784 if get_route(&src, &payee, &graph, None, amt, 42, &DummyLogger{}, &scorer).is_ok() {
4785 path_endpoints.push((src, dst, amt));
4786 continue 'load_endpoints;
4791 // ...then benchmark finding paths between the nodes we learned.
4794 let (src, dst, amt) = path_endpoints[idx % path_endpoints.len()];
4795 let payee = Payee::new(dst);
4796 assert!(get_route(&src, &payee, &graph, None, amt, 42, &DummyLogger{}, &scorer).is_ok());
4802 fn generate_mpp_routes(bench: &mut Bencher) {
4803 let mut d = test_utils::get_route_file().unwrap();
4804 let graph = NetworkGraph::read(&mut d).unwrap();
4805 let nodes = graph.read_only().nodes().clone();
4806 let scorer = Scorer::new(0);
4808 // First, get 100 (source, destination) pairs for which route-getting actually succeeds...
4809 let mut path_endpoints = Vec::new();
4810 let mut seed: usize = 0xdeadbeef;
4811 'load_endpoints: for _ in 0..100 {
4814 let src = PublicKey::from_slice(nodes.keys().skip(seed % nodes.len()).next().unwrap().as_slice()).unwrap();
4816 let dst = PublicKey::from_slice(nodes.keys().skip(seed % nodes.len()).next().unwrap().as_slice()).unwrap();
4817 let payee = Payee::new(dst).with_features(InvoiceFeatures::known());
4818 let amt = seed as u64 % 1_000_000;
4819 if get_route(&src, &payee, &graph, None, amt, 42, &DummyLogger{}, &scorer).is_ok() {
4820 path_endpoints.push((src, dst, amt));
4821 continue 'load_endpoints;
4826 // ...then benchmark finding paths between the nodes we learned.
4829 let (src, dst, amt) = path_endpoints[idx % path_endpoints.len()];
4830 let payee = Payee::new(dst).with_features(InvoiceFeatures::known());
4831 assert!(get_route(&src, &payee, &graph, None, amt, 42, &DummyLogger{}, &scorer).is_ok());