1 // This file is Copyright its original authors, visible in version control
4 // This file is licensed under the Apache License, Version 2.0 <LICENSE-APACHE
5 // or http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
6 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your option.
7 // You may not use this file except in accordance with one or both of these
10 //! The top-level routing/network map tracking logic lives here.
12 //! You probably want to create a NetGraphMsgHandler and use that as your RoutingMessageHandler and then
13 //! interrogate it to get routes for your own payments.
15 use bitcoin::secp256k1::key::PublicKey;
17 use ln::channelmanager::ChannelDetails;
18 use ln::features::{ChannelFeatures, InvoiceFeatures, NodeFeatures};
19 use ln::msgs::{DecodeError, ErrorAction, LightningError, MAX_VALUE_MSAT};
21 use routing::network_graph::{NetworkGraph, NodeId, RoutingFees};
22 use util::ser::{Writeable, Readable};
23 use util::logger::{Level, Logger};
27 use alloc::collections::BinaryHeap;
32 #[derive(Clone, Debug, Hash, PartialEq, Eq)]
34 /// The node_id of the node at this hop.
35 pub pubkey: PublicKey,
36 /// The node_announcement features of the node at this hop. For the last hop, these may be
37 /// amended to match the features present in the invoice this node generated.
38 pub node_features: NodeFeatures,
39 /// The channel that should be used from the previous hop to reach this node.
40 pub short_channel_id: u64,
41 /// The channel_announcement features of the channel that should be used from the previous hop
42 /// to reach this node.
43 pub channel_features: ChannelFeatures,
44 /// The fee taken on this hop (for paying for the use of the *next* channel in the path).
45 /// For the last hop, this should be the full value of the payment (might be more than
46 /// requested if we had to match htlc_minimum_msat).
48 /// The CLTV delta added for this hop. For the last hop, this should be the full CLTV value
49 /// expected at the destination, in excess of the current block height.
50 pub cltv_expiry_delta: u32,
53 impl_writeable_tlv_based!(RouteHop, {
54 (0, pubkey, required),
55 (2, node_features, required),
56 (4, short_channel_id, required),
57 (6, channel_features, required),
58 (8, fee_msat, required),
59 (10, cltv_expiry_delta, required),
62 /// A route directs a payment from the sender (us) to the recipient. If the recipient supports MPP,
63 /// it can take multiple paths. Each path is composed of one or more hops through the network.
64 #[derive(Clone, Hash, PartialEq, Eq)]
66 /// The list of routes taken for a single (potentially-)multi-part payment. The pubkey of the
67 /// last RouteHop in each path must be the same.
68 /// Each entry represents a list of hops, NOT INCLUDING our own, where the last hop is the
69 /// destination. Thus, this must always be at least length one. While the maximum length of any
70 /// given path is variable, keeping the length of any path to less than 20 should currently
71 /// ensure it is viable.
72 pub paths: Vec<Vec<RouteHop>>,
73 /// The `payee` parameter passed to [`find_route`].
74 /// This is used by `ChannelManager` to track information which may be required for retries,
75 /// provided back to you via [`Event::PaymentPathFailed`].
77 /// [`Event::PaymentPathFailed`]: crate::util::events::Event::PaymentPathFailed
78 pub payee: Option<Payee>,
82 /// Returns the total amount of fees paid on this [`Route`].
84 /// This doesn't include any extra payment made to the recipient, which can happen in excess of
85 /// the amount passed to [`find_route`]'s `params.final_value_msat`.
86 pub fn get_total_fees(&self) -> u64 {
87 // Do not count last hop of each path since that's the full value of the payment
88 return self.paths.iter()
89 .flat_map(|path| path.split_last().map(|(_, path_prefix)| path_prefix).unwrap_or(&[]))
90 .map(|hop| &hop.fee_msat)
94 /// Returns the total amount paid on this [`Route`], excluding the fees.
95 pub fn get_total_amount(&self) -> u64 {
96 return self.paths.iter()
97 .map(|path| path.split_last().map(|(hop, _)| hop.fee_msat).unwrap_or(0))
102 const SERIALIZATION_VERSION: u8 = 1;
103 const MIN_SERIALIZATION_VERSION: u8 = 1;
105 impl Writeable for Route {
106 fn write<W: ::util::ser::Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
107 write_ver_prefix!(writer, SERIALIZATION_VERSION, MIN_SERIALIZATION_VERSION);
108 (self.paths.len() as u64).write(writer)?;
109 for hops in self.paths.iter() {
110 (hops.len() as u8).write(writer)?;
111 for hop in hops.iter() {
115 write_tlv_fields!(writer, {
116 (1, self.payee, option),
122 impl Readable for Route {
123 fn read<R: io::Read>(reader: &mut R) -> Result<Route, DecodeError> {
124 let _ver = read_ver_prefix!(reader, SERIALIZATION_VERSION);
125 let path_count: u64 = Readable::read(reader)?;
126 let mut paths = Vec::with_capacity(cmp::min(path_count, 128) as usize);
127 for _ in 0..path_count {
128 let hop_count: u8 = Readable::read(reader)?;
129 let mut hops = Vec::with_capacity(hop_count as usize);
130 for _ in 0..hop_count {
131 hops.push(Readable::read(reader)?);
135 let mut payee = None;
136 read_tlv_fields!(reader, {
139 Ok(Route { paths, payee })
143 /// Parameters needed to find a [`Route`] for paying a [`Payee`].
145 /// Passed to [`find_route`] and also provided in [`Event::PaymentPathFailed`] for retrying a failed
148 /// [`Event::PaymentPathFailed`]: crate::util::events::Event::PaymentPathFailed
149 #[derive(Clone, Debug)]
150 pub struct RouteParameters {
151 /// The recipient of the failed payment path.
154 /// The amount in msats sent on the failed payment path.
155 pub final_value_msat: u64,
157 /// The CLTV on the final hop of the failed payment path.
158 pub final_cltv_expiry_delta: u32,
161 impl_writeable_tlv_based!(RouteParameters, {
162 (0, payee, required),
163 (2, final_value_msat, required),
164 (4, final_cltv_expiry_delta, required),
167 /// The recipient of a payment.
168 #[derive(Clone, Debug, Hash, PartialEq, Eq)]
170 /// The node id of the payee.
171 pub pubkey: PublicKey,
173 /// Features supported by the payee.
175 /// May be set from the payee's invoice or via [`for_keysend`]. May be `None` if the invoice
176 /// does not contain any features.
178 /// [`for_keysend`]: Self::for_keysend
179 pub features: Option<InvoiceFeatures>,
181 /// Hints for routing to the payee, containing channels connecting the payee to public nodes.
182 pub route_hints: Vec<RouteHint>,
185 impl_writeable_tlv_based!(Payee, {
186 (0, pubkey, required),
187 (2, features, option),
188 (4, route_hints, vec_type),
192 /// Creates a payee with the node id of the given `pubkey`.
193 pub fn new(pubkey: PublicKey) -> Self {
201 /// Creates a payee with the node id of the given `pubkey` to use for keysend payments.
202 pub fn for_keysend(pubkey: PublicKey) -> Self {
203 Self::new(pubkey).with_features(InvoiceFeatures::for_keysend())
206 /// Includes the payee's features.
208 /// (C-not exported) since bindings don't support move semantics
209 pub fn with_features(self, features: InvoiceFeatures) -> Self {
210 Self { features: Some(features), ..self }
213 /// Includes hints for routing to the payee.
215 /// (C-not exported) since bindings don't support move semantics
216 pub fn with_route_hints(self, route_hints: Vec<RouteHint>) -> Self {
217 Self { route_hints, ..self }
221 /// A list of hops along a payment path terminating with a channel to the recipient.
222 #[derive(Clone, Debug, Hash, Eq, PartialEq)]
223 pub struct RouteHint(pub Vec<RouteHintHop>);
226 impl Writeable for RouteHint {
227 fn write<W: ::util::ser::Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
228 (self.0.len() as u64).write(writer)?;
229 for hop in self.0.iter() {
236 impl Readable for RouteHint {
237 fn read<R: io::Read>(reader: &mut R) -> Result<Self, DecodeError> {
238 let hop_count: u64 = Readable::read(reader)?;
239 let mut hops = Vec::with_capacity(cmp::min(hop_count, 16) as usize);
240 for _ in 0..hop_count {
241 hops.push(Readable::read(reader)?);
247 /// A channel descriptor for a hop along a payment path.
248 #[derive(Clone, Debug, Hash, Eq, PartialEq)]
249 pub struct RouteHintHop {
250 /// The node_id of the non-target end of the route
251 pub src_node_id: PublicKey,
252 /// The short_channel_id of this channel
253 pub short_channel_id: u64,
254 /// The fees which must be paid to use this channel
255 pub fees: RoutingFees,
256 /// The difference in CLTV values between this node and the next node.
257 pub cltv_expiry_delta: u16,
258 /// The minimum value, in msat, which must be relayed to the next hop.
259 pub htlc_minimum_msat: Option<u64>,
260 /// The maximum value in msat available for routing with a single HTLC.
261 pub htlc_maximum_msat: Option<u64>,
264 impl_writeable_tlv_based!(RouteHintHop, {
265 (0, src_node_id, required),
266 (1, htlc_minimum_msat, option),
267 (2, short_channel_id, required),
268 (3, htlc_maximum_msat, option),
270 (6, cltv_expiry_delta, required),
273 #[derive(Eq, PartialEq)]
274 struct RouteGraphNode {
276 lowest_fee_to_peer_through_node: u64,
277 lowest_fee_to_node: u64,
278 // The maximum value a yet-to-be-constructed payment path might flow through this node.
279 // This value is upper-bounded by us by:
280 // - how much is needed for a path being constructed
281 // - how much value can channels following this node (up to the destination) can contribute,
282 // considering their capacity and fees
283 value_contribution_msat: u64,
284 /// The effective htlc_minimum_msat at this hop. If a later hop on the path had a higher HTLC
285 /// minimum, we use it, plus the fees required at each earlier hop to meet it.
286 path_htlc_minimum_msat: u64,
287 /// All penalties incurred from this hop on the way to the destination, as calculated using
289 path_penalty_msat: u64,
292 impl cmp::Ord for RouteGraphNode {
293 fn cmp(&self, other: &RouteGraphNode) -> cmp::Ordering {
294 let other_score = cmp::max(other.lowest_fee_to_peer_through_node, other.path_htlc_minimum_msat)
295 .checked_add(other.path_penalty_msat)
296 .unwrap_or_else(|| u64::max_value());
297 let self_score = cmp::max(self.lowest_fee_to_peer_through_node, self.path_htlc_minimum_msat)
298 .checked_add(self.path_penalty_msat)
299 .unwrap_or_else(|| u64::max_value());
300 other_score.cmp(&self_score).then_with(|| other.node_id.cmp(&self.node_id))
304 impl cmp::PartialOrd for RouteGraphNode {
305 fn partial_cmp(&self, other: &RouteGraphNode) -> Option<cmp::Ordering> {
306 Some(self.cmp(other))
310 struct DummyDirectionalChannelInfo {
311 cltv_expiry_delta: u32,
312 htlc_minimum_msat: u64,
313 htlc_maximum_msat: Option<u64>,
317 /// It's useful to keep track of the hops associated with the fees required to use them,
318 /// so that we can choose cheaper paths (as per Dijkstra's algorithm).
319 /// Fee values should be updated only in the context of the whole path, see update_value_and_recompute_fees.
320 /// These fee values are useful to choose hops as we traverse the graph "payee-to-payer".
321 #[derive(Clone, Debug)]
322 struct PathBuildingHop<'a> {
323 // The RouteHintHop fields which will eventually be used if this hop is used in a final Route.
324 // Note that node_features is calculated separately after our initial graph walk.
326 short_channel_id: u64,
327 channel_features: &'a ChannelFeatures,
329 cltv_expiry_delta: u32,
331 /// Minimal fees required to route to the source node of the current hop via any of its inbound channels.
332 src_lowest_inbound_fees: RoutingFees,
333 /// Fees of the channel used in this hop.
334 channel_fees: RoutingFees,
335 /// All the fees paid *after* this channel on the way to the destination
336 next_hops_fee_msat: u64,
337 /// Fee paid for the use of the current channel (see channel_fees).
338 /// The value will be actually deducted from the counterparty balance on the previous link.
339 hop_use_fee_msat: u64,
340 /// Used to compare channels when choosing the for routing.
341 /// Includes paying for the use of a hop and the following hops, as well as
342 /// an estimated cost of reaching this hop.
343 /// Might get stale when fees are recomputed. Primarily for internal use.
345 /// This is useful for update_value_and_recompute_fees to make sure
346 /// we don't fall below the minimum. Should not be updated manually and
347 /// generally should not be accessed.
348 htlc_minimum_msat: u64,
349 /// A mirror of the same field in RouteGraphNode. Note that this is only used during the graph
350 /// walk and may be invalid thereafter.
351 path_htlc_minimum_msat: u64,
352 /// All penalties incurred from this channel on the way to the destination, as calculated using
354 path_penalty_msat: u64,
355 /// If we've already processed a node as the best node, we shouldn't process it again. Normally
356 /// we'd just ignore it if we did as all channels would have a higher new fee, but because we
357 /// may decrease the amounts in use as we walk the graph, the actual calculated fee may
358 /// decrease as well. Thus, we have to explicitly track which nodes have been processed and
359 /// avoid processing them again.
361 #[cfg(any(test, feature = "fuzztarget"))]
362 // In tests, we apply further sanity checks on cases where we skip nodes we already processed
363 // to ensure it is specifically in cases where the fee has gone down because of a decrease in
364 // value_contribution_msat, which requires tracking it here. See comments below where it is
365 // used for more info.
366 value_contribution_msat: u64,
369 // Instantiated with a list of hops with correct data in them collected during path finding,
370 // an instance of this struct should be further modified only via given methods.
372 struct PaymentPath<'a> {
373 hops: Vec<(PathBuildingHop<'a>, NodeFeatures)>,
376 impl<'a> PaymentPath<'a> {
377 // TODO: Add a value_msat field to PaymentPath and use it instead of this function.
378 fn get_value_msat(&self) -> u64 {
379 self.hops.last().unwrap().0.fee_msat
382 fn get_total_fee_paid_msat(&self) -> u64 {
383 if self.hops.len() < 1 {
387 // Can't use next_hops_fee_msat because it gets outdated.
388 for (i, (hop, _)) in self.hops.iter().enumerate() {
389 if i != self.hops.len() - 1 {
390 result += hop.fee_msat;
396 // If the amount transferred by the path is updated, the fees should be adjusted. Any other way
397 // to change fees may result in an inconsistency.
399 // Sometimes we call this function right after constructing a path which is inconsistent in
400 // that it the value being transferred has decreased while we were doing path finding, leading
401 // to the fees being paid not lining up with the actual limits.
403 // Note that this function is not aware of the available_liquidity limit, and thus does not
404 // support increasing the value being transferred.
405 fn update_value_and_recompute_fees(&mut self, value_msat: u64) {
406 assert!(value_msat <= self.hops.last().unwrap().0.fee_msat);
408 let mut total_fee_paid_msat = 0 as u64;
409 for i in (0..self.hops.len()).rev() {
410 let last_hop = i == self.hops.len() - 1;
412 // For non-last-hop, this value will represent the fees paid on the current hop. It
413 // will consist of the fees for the use of the next hop, and extra fees to match
414 // htlc_minimum_msat of the current channel. Last hop is handled separately.
415 let mut cur_hop_fees_msat = 0;
417 cur_hop_fees_msat = self.hops.get(i + 1).unwrap().0.hop_use_fee_msat;
420 let mut cur_hop = &mut self.hops.get_mut(i).unwrap().0;
421 cur_hop.next_hops_fee_msat = total_fee_paid_msat;
422 // Overpay in fees if we can't save these funds due to htlc_minimum_msat.
423 // We try to account for htlc_minimum_msat in scoring (add_entry!), so that nodes don't
424 // set it too high just to maliciously take more fees by exploiting this
425 // match htlc_minimum_msat logic.
426 let mut cur_hop_transferred_amount_msat = total_fee_paid_msat + value_msat;
427 if let Some(extra_fees_msat) = cur_hop.htlc_minimum_msat.checked_sub(cur_hop_transferred_amount_msat) {
428 // Note that there is a risk that *previous hops* (those closer to us, as we go
429 // payee->our_node here) would exceed their htlc_maximum_msat or available balance.
431 // This might make us end up with a broken route, although this should be super-rare
432 // in practice, both because of how healthy channels look like, and how we pick
433 // channels in add_entry.
434 // Also, this can't be exploited more heavily than *announce a free path and fail
436 cur_hop_transferred_amount_msat += extra_fees_msat;
437 total_fee_paid_msat += extra_fees_msat;
438 cur_hop_fees_msat += extra_fees_msat;
442 // Final hop is a special case: it usually has just value_msat (by design), but also
443 // it still could overpay for the htlc_minimum_msat.
444 cur_hop.fee_msat = cur_hop_transferred_amount_msat;
446 // Propagate updated fees for the use of the channels to one hop back, where they
447 // will be actually paid (fee_msat). The last hop is handled above separately.
448 cur_hop.fee_msat = cur_hop_fees_msat;
451 // Fee for the use of the current hop which will be deducted on the previous hop.
452 // Irrelevant for the first hop, as it doesn't have the previous hop, and the use of
453 // this channel is free for us.
455 if let Some(new_fee) = compute_fees(cur_hop_transferred_amount_msat, cur_hop.channel_fees) {
456 cur_hop.hop_use_fee_msat = new_fee;
457 total_fee_paid_msat += new_fee;
459 // It should not be possible because this function is called only to reduce the
460 // value. In that case, compute_fee was already called with the same fees for
461 // larger amount and there was no overflow.
469 fn compute_fees(amount_msat: u64, channel_fees: RoutingFees) -> Option<u64> {
470 let proportional_fee_millions =
471 amount_msat.checked_mul(channel_fees.proportional_millionths as u64);
472 if let Some(new_fee) = proportional_fee_millions.and_then(|part| {
473 (channel_fees.base_msat as u64).checked_add(part / 1_000_000) }) {
477 // This function may be (indirectly) called without any verification,
478 // with channel_fees provided by a caller. We should handle it gracefully.
483 /// Finds a route from us (payer) to the given target node (payee).
485 /// If the payee provided features in their invoice, they should be provided via `params.payee`.
486 /// Without this, MPP will only be used if the payee's features are available in the network graph.
488 /// Private routing paths between a public node and the target may be included in `params.payee`.
490 /// If some channels aren't announced, it may be useful to fill in `first_hops` with the results
491 /// from [`ChannelManager::list_usable_channels`]. If it is filled in, the view of our local
492 /// channels from [`NetworkGraph`] will be ignored, and only those in `first_hops` will be used.
494 /// The fees on channels from us to the next hop are ignored as they are assumed to all be equal.
495 /// However, the enabled/disabled bit on such channels as well as the `htlc_minimum_msat` /
496 /// `htlc_maximum_msat` *are* checked as they may change based on the receiving node.
500 /// May be used to re-compute a [`Route`] when handling a [`Event::PaymentPathFailed`]. Any
501 /// adjustments to the [`NetworkGraph`] and channel scores should be made prior to calling this
506 /// Panics if first_hops contains channels without short_channel_ids;
507 /// [`ChannelManager::list_usable_channels`] will never include such channels.
509 /// [`ChannelManager::list_usable_channels`]: crate::ln::channelmanager::ChannelManager::list_usable_channels
510 /// [`Event::PaymentPathFailed`]: crate::util::events::Event::PaymentPathFailed
511 pub fn find_route<L: Deref, S: routing::Score>(
512 our_node_pubkey: &PublicKey, params: &RouteParameters, network: &NetworkGraph,
513 first_hops: Option<&[&ChannelDetails]>, logger: L, scorer: &S
514 ) -> Result<Route, LightningError>
515 where L::Target: Logger {
517 our_node_pubkey, ¶ms.payee, network, first_hops, params.final_value_msat,
518 params.final_cltv_expiry_delta, logger, scorer
522 pub(crate) fn get_route<L: Deref, S: routing::Score>(
523 our_node_pubkey: &PublicKey, payee: &Payee, network: &NetworkGraph,
524 first_hops: Option<&[&ChannelDetails]>, final_value_msat: u64, final_cltv_expiry_delta: u32,
525 logger: L, scorer: &S
526 ) -> Result<Route, LightningError>
527 where L::Target: Logger {
528 let payee_node_id = NodeId::from_pubkey(&payee.pubkey);
529 let our_node_id = NodeId::from_pubkey(&our_node_pubkey);
531 if payee_node_id == our_node_id {
532 return Err(LightningError{err: "Cannot generate a route to ourselves".to_owned(), action: ErrorAction::IgnoreError});
535 if final_value_msat > MAX_VALUE_MSAT {
536 return Err(LightningError{err: "Cannot generate a route of more value than all existing satoshis".to_owned(), action: ErrorAction::IgnoreError});
539 if final_value_msat == 0 {
540 return Err(LightningError{err: "Cannot send a payment of 0 msat".to_owned(), action: ErrorAction::IgnoreError});
543 for route in payee.route_hints.iter() {
544 for hop in &route.0 {
545 if hop.src_node_id == payee.pubkey {
546 return Err(LightningError{err: "Route hint cannot have the payee as the source.".to_owned(), action: ErrorAction::IgnoreError});
551 // The general routing idea is the following:
552 // 1. Fill first/last hops communicated by the caller.
553 // 2. Attempt to construct a path from payer to payee for transferring
554 // any ~sufficient (described later) value.
555 // If succeed, remember which channels were used and how much liquidity they have available,
556 // so that future paths don't rely on the same liquidity.
557 // 3. Prooceed to the next step if:
558 // - we hit the recommended target value;
559 // - OR if we could not construct a new path. Any next attempt will fail too.
560 // Otherwise, repeat step 2.
561 // 4. See if we managed to collect paths which aggregately are able to transfer target value
562 // (not recommended value). If yes, proceed. If not, fail routing.
563 // 5. Randomly combine paths into routes having enough to fulfill the payment. (TODO: knapsack)
564 // 6. Of all the found paths, select only those with the lowest total fee.
565 // 7. The last path in every selected route is likely to be more than we need.
566 // Reduce its value-to-transfer and recompute fees.
567 // 8. Choose the best route by the lowest total fee.
569 // As for the actual search algorithm,
570 // we do a payee-to-payer pseudo-Dijkstra's sorting by each node's distance from the payee
571 // plus the minimum per-HTLC fee to get from it to another node (aka "shitty pseudo-A*").
573 // We are not a faithful Dijkstra's implementation because we can change values which impact
574 // earlier nodes while processing later nodes. Specifically, if we reach a channel with a lower
575 // liquidity limit (via htlc_maximum_msat, on-chain capacity or assumed liquidity limits) then
576 // the value we are currently attempting to send over a path, we simply reduce the value being
577 // sent along the path for any hops after that channel. This may imply that later fees (which
578 // we've already tabulated) are lower because a smaller value is passing through the channels
579 // (and the proportional fee is thus lower). There isn't a trivial way to recalculate the
580 // channels which were selected earlier (and which may still be used for other paths without a
581 // lower liquidity limit), so we simply accept that some liquidity-limited paths may be
584 // One potentially problematic case for this algorithm would be if there are many
585 // liquidity-limited paths which are liquidity-limited near the destination (ie early in our
586 // graph walking), we may never find a path which is not liquidity-limited and has lower
587 // proportional fee (and only lower absolute fee when considering the ultimate value sent).
588 // Because we only consider paths with at least 5% of the total value being sent, the damage
589 // from such a case should be limited, however this could be further reduced in the future by
590 // calculating fees on the amount we wish to route over a path, ie ignoring the liquidity
591 // limits for the purposes of fee calculation.
593 // Alternatively, we could store more detailed path information in the heap (targets, below)
594 // and index the best-path map (dist, below) by node *and* HTLC limits, however that would blow
595 // up the runtime significantly both algorithmically (as we'd traverse nodes multiple times)
596 // and practically (as we would need to store dynamically-allocated path information in heap
597 // objects, increasing malloc traffic and indirect memory access significantly). Further, the
598 // results of such an algorithm would likely be biased towards lower-value paths.
600 // Further, we could return to a faithful Dijkstra's algorithm by rejecting paths with limits
601 // outside of our current search value, running a path search more times to gather candidate
602 // paths at different values. While this may be acceptable, further path searches may increase
603 // runtime for little gain. Specifically, the current algorithm rather efficiently explores the
604 // graph for candidate paths, calculating the maximum value which can realistically be sent at
605 // the same time, remaining generic across different payment values.
607 // TODO: There are a few tweaks we could do, including possibly pre-calculating more stuff
608 // to use as the A* heuristic beyond just the cost to get one node further than the current
611 let network_graph = network.read_only();
612 let network_channels = network_graph.channels();
613 let network_nodes = network_graph.nodes();
614 let dummy_directional_info = DummyDirectionalChannelInfo { // used for first_hops routes
615 cltv_expiry_delta: 0,
616 htlc_minimum_msat: 0,
617 htlc_maximum_msat: None,
620 proportional_millionths: 0,
624 // Allow MPP only if we have a features set from somewhere that indicates the payee supports
625 // it. If the payee supports it they're supposed to include it in the invoice, so that should
627 let allow_mpp = if let Some(features) = &payee.features {
628 features.supports_basic_mpp()
629 } else if let Some(node) = network_nodes.get(&payee_node_id) {
630 if let Some(node_info) = node.announcement_info.as_ref() {
631 node_info.features.supports_basic_mpp()
634 log_trace!(logger, "Searching for a route from payer {} to payee {} {} MPP", our_node_pubkey,
635 payee.pubkey, if allow_mpp { "with" } else { "without" });
638 // Prepare the data we'll use for payee-to-payer search by
639 // inserting first hops suggested by the caller as targets.
640 // Our search will then attempt to reach them while traversing from the payee node.
641 let mut first_hop_targets: HashMap<_, Vec<(_, ChannelFeatures, _, NodeFeatures)>> =
642 HashMap::with_capacity(if first_hops.is_some() { first_hops.as_ref().unwrap().len() } else { 0 });
643 if let Some(hops) = first_hops {
645 let short_channel_id = chan.short_channel_id.expect("first_hops should be filled in with usable channels, not pending ones");
646 if chan.counterparty.node_id == *our_node_pubkey {
647 return Err(LightningError{err: "First hop cannot have our_node_pubkey as a destination.".to_owned(), action: ErrorAction::IgnoreError});
649 first_hop_targets.entry(NodeId::from_pubkey(&chan.counterparty.node_id)).or_insert(Vec::new())
650 .push((short_channel_id, chan.counterparty.features.to_context(), chan.outbound_capacity_msat, chan.counterparty.features.to_context()));
652 if first_hop_targets.is_empty() {
653 return Err(LightningError{err: "Cannot route when there are no outbound routes away from us".to_owned(), action: ErrorAction::IgnoreError});
657 let empty_channel_features = ChannelFeatures::empty();
659 // The main heap containing all candidate next-hops sorted by their score (max(A* fee,
660 // htlc_minimum)). Ideally this would be a heap which allowed cheap score reduction instead of
661 // adding duplicate entries when we find a better path to a given node.
662 let mut targets = BinaryHeap::new();
664 // Map from node_id to information about the best current path to that node, including feerate
666 let mut dist = HashMap::with_capacity(network_nodes.len());
668 // During routing, if we ignore a path due to an htlc_minimum_msat limit, we set this,
669 // indicating that we may wish to try again with a higher value, potentially paying to meet an
670 // htlc_minimum with extra fees while still finding a cheaper path.
671 let mut hit_minimum_limit;
673 // When arranging a route, we select multiple paths so that we can make a multi-path payment.
674 // We start with a path_value of the exact amount we want, and if that generates a route we may
675 // return it immediately. Otherwise, we don't stop searching for paths until we have 3x the
676 // amount we want in total across paths, selecting the best subset at the end.
677 const ROUTE_CAPACITY_PROVISION_FACTOR: u64 = 3;
678 let recommended_value_msat = final_value_msat * ROUTE_CAPACITY_PROVISION_FACTOR as u64;
679 let mut path_value_msat = final_value_msat;
681 // We don't want multiple paths (as per MPP) share liquidity of the same channels.
682 // This map allows paths to be aware of the channel use by other paths in the same call.
683 // This would help to make a better path finding decisions and not "overbook" channels.
684 // It is unaware of the directions (except for `outbound_capacity_msat` in `first_hops`).
685 let mut bookkeeped_channels_liquidity_available_msat = HashMap::with_capacity(network_nodes.len());
687 // Keeping track of how much value we already collected across other paths. Helps to decide:
688 // - how much a new path should be transferring (upper bound);
689 // - whether a channel should be disregarded because
690 // it's available liquidity is too small comparing to how much more we need to collect;
691 // - when we want to stop looking for new paths.
692 let mut already_collected_value_msat = 0;
694 log_trace!(logger, "Building path from {} (payee) to {} (us/payer) for value {} msat.", payee.pubkey, our_node_pubkey, final_value_msat);
696 macro_rules! add_entry {
697 // Adds entry which goes from $src_node_id to $dest_node_id
698 // over the channel with id $chan_id with fees described in
699 // $directional_info.
700 // $next_hops_fee_msat represents the fees paid for using all the channel *after* this one,
701 // since that value has to be transferred over this channel.
702 // Returns whether this channel caused an update to `targets`.
703 ( $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,
704 $next_hops_value_contribution: expr, $next_hops_path_htlc_minimum_msat: expr, $next_hops_path_penalty_msat: expr ) => { {
705 // We "return" whether we updated the path at the end, via this:
706 let mut did_add_update_path_to_src_node = false;
707 // Channels to self should not be used. This is more of belt-and-suspenders, because in
708 // practice these cases should be caught earlier:
709 // - for regular channels at channel announcement (TODO)
710 // - for first and last hops early in get_route
711 if $src_node_id != $dest_node_id.clone() {
712 let available_liquidity_msat = bookkeeped_channels_liquidity_available_msat.entry($chan_id.clone()).or_insert_with(|| {
713 let mut initial_liquidity_available_msat = None;
714 if let Some(capacity_sats) = $capacity_sats {
715 initial_liquidity_available_msat = Some(capacity_sats * 1000);
718 if let Some(htlc_maximum_msat) = $directional_info.htlc_maximum_msat {
719 if let Some(available_msat) = initial_liquidity_available_msat {
720 initial_liquidity_available_msat = Some(cmp::min(available_msat, htlc_maximum_msat));
722 initial_liquidity_available_msat = Some(htlc_maximum_msat);
726 match initial_liquidity_available_msat {
727 Some(available_msat) => available_msat,
728 // We assume channels with unknown balance have
729 // a capacity of 0.0025 BTC (or 250_000 sats).
730 None => 250_000 * 1000
734 // It is tricky to substract $next_hops_fee_msat from available liquidity here.
735 // It may be misleading because we might later choose to reduce the value transferred
736 // over these channels, and the channel which was insufficient might become sufficient.
737 // Worst case: we drop a good channel here because it can't cover the high following
738 // fees caused by one expensive channel, but then this channel could have been used
739 // if the amount being transferred over this path is lower.
740 // We do this for now, but this is a subject for removal.
741 if let Some(available_value_contribution_msat) = available_liquidity_msat.checked_sub($next_hops_fee_msat) {
743 // Routing Fragmentation Mitigation heuristic:
745 // Routing fragmentation across many payment paths increases the overall routing
746 // fees as you have irreducible routing fees per-link used (`fee_base_msat`).
747 // Taking too many smaller paths also increases the chance of payment failure.
748 // Thus to avoid this effect, we require from our collected links to provide
749 // at least a minimal contribution to the recommended value yet-to-be-fulfilled.
751 // This requirement is currently 5% of the remaining-to-be-collected value.
752 // This means as we successfully advance in our collection,
753 // the absolute liquidity contribution is lowered,
754 // thus increasing the number of potential channels to be selected.
756 // Derive the minimal liquidity contribution with a ratio of 20 (5%, rounded up)
757 // or 100% if we're not allowed to do multipath payments.
758 let minimal_value_contribution_msat: u64 = if allow_mpp {
759 (recommended_value_msat - already_collected_value_msat + 19) / 20
763 // Verify the liquidity offered by this channel complies to the minimal contribution.
764 let contributes_sufficient_value = available_value_contribution_msat >= minimal_value_contribution_msat;
766 let value_contribution_msat = cmp::min(available_value_contribution_msat, $next_hops_value_contribution);
767 // Includes paying fees for the use of the following channels.
768 let amount_to_transfer_over_msat: u64 = match value_contribution_msat.checked_add($next_hops_fee_msat) {
769 Some(result) => result,
770 // Can't overflow due to how the values were computed right above.
771 None => unreachable!(),
773 #[allow(unused_comparisons)] // $next_hops_path_htlc_minimum_msat is 0 in some calls so rustc complains
774 let over_path_minimum_msat = amount_to_transfer_over_msat >= $directional_info.htlc_minimum_msat &&
775 amount_to_transfer_over_msat >= $next_hops_path_htlc_minimum_msat;
777 // If HTLC minimum is larger than the amount we're going to transfer, we shouldn't
778 // bother considering this channel.
779 // Since we're choosing amount_to_transfer_over_msat as maximum possible, it can
780 // be only reduced later (not increased), so this channel should just be skipped
781 // as not sufficient.
782 if !over_path_minimum_msat {
783 hit_minimum_limit = true;
784 } else if contributes_sufficient_value {
785 // Note that low contribution here (limited by available_liquidity_msat)
786 // might violate htlc_minimum_msat on the hops which are next along the
787 // payment path (upstream to the payee). To avoid that, we recompute path
788 // path fees knowing the final path contribution after constructing it.
789 let path_htlc_minimum_msat = compute_fees($next_hops_path_htlc_minimum_msat, $directional_info.fees)
790 .and_then(|fee_msat| fee_msat.checked_add($next_hops_path_htlc_minimum_msat))
791 .map(|fee_msat| cmp::max(fee_msat, $directional_info.htlc_minimum_msat))
792 .unwrap_or_else(|| u64::max_value());
793 let hm_entry = dist.entry($src_node_id);
794 let old_entry = hm_entry.or_insert_with(|| {
795 // If there was previously no known way to access
796 // the source node (recall it goes payee-to-payer) of $chan_id, first add
797 // a semi-dummy record just to compute the fees to reach the source node.
798 // This will affect our decision on selecting $chan_id
799 // as a way to reach the $dest_node_id.
800 let mut fee_base_msat = u32::max_value();
801 let mut fee_proportional_millionths = u32::max_value();
802 if let Some(Some(fees)) = network_nodes.get(&$src_node_id).map(|node| node.lowest_inbound_channel_fees) {
803 fee_base_msat = fees.base_msat;
804 fee_proportional_millionths = fees.proportional_millionths;
807 node_id: $dest_node_id.clone(),
809 channel_features: $chan_features,
811 cltv_expiry_delta: 0,
812 src_lowest_inbound_fees: RoutingFees {
813 base_msat: fee_base_msat,
814 proportional_millionths: fee_proportional_millionths,
816 channel_fees: $directional_info.fees,
817 next_hops_fee_msat: u64::max_value(),
818 hop_use_fee_msat: u64::max_value(),
819 total_fee_msat: u64::max_value(),
820 htlc_minimum_msat: $directional_info.htlc_minimum_msat,
821 path_htlc_minimum_msat,
822 path_penalty_msat: u64::max_value(),
823 was_processed: false,
824 #[cfg(any(test, feature = "fuzztarget"))]
825 value_contribution_msat,
829 #[allow(unused_mut)] // We only use the mut in cfg(test)
830 let mut should_process = !old_entry.was_processed;
831 #[cfg(any(test, feature = "fuzztarget"))]
833 // In test/fuzzing builds, we do extra checks to make sure the skipping
834 // of already-seen nodes only happens in cases we expect (see below).
835 if !should_process { should_process = true; }
839 let mut hop_use_fee_msat = 0;
840 let mut total_fee_msat = $next_hops_fee_msat;
842 // Ignore hop_use_fee_msat for channel-from-us as we assume all channels-from-us
843 // will have the same effective-fee
844 if $src_node_id != our_node_id {
845 match compute_fees(amount_to_transfer_over_msat, $directional_info.fees) {
846 // max_value means we'll always fail
847 // the old_entry.total_fee_msat > total_fee_msat check
848 None => total_fee_msat = u64::max_value(),
850 hop_use_fee_msat = fee_msat;
851 total_fee_msat += hop_use_fee_msat;
852 // When calculating the lowest inbound fees to a node, we
853 // calculate fees here not based on the actual value we think
854 // will flow over this channel, but on the minimum value that
855 // we'll accept flowing over it. The minimum accepted value
856 // is a constant through each path collection run, ensuring
857 // consistent basis. Otherwise we may later find a
858 // different path to the source node that is more expensive,
859 // but which we consider to be cheaper because we are capacity
860 // constrained and the relative fee becomes lower.
861 match compute_fees(minimal_value_contribution_msat, old_entry.src_lowest_inbound_fees)
862 .map(|a| a.checked_add(total_fee_msat)) {
867 total_fee_msat = u64::max_value();
874 let path_penalty_msat = $next_hops_path_penalty_msat
875 .checked_add(scorer.channel_penalty_msat($chan_id.clone(), &$src_node_id, &$dest_node_id))
876 .unwrap_or_else(|| u64::max_value());
877 let new_graph_node = RouteGraphNode {
878 node_id: $src_node_id,
879 lowest_fee_to_peer_through_node: total_fee_msat,
880 lowest_fee_to_node: $next_hops_fee_msat as u64 + hop_use_fee_msat,
881 value_contribution_msat: value_contribution_msat,
882 path_htlc_minimum_msat,
886 // Update the way of reaching $src_node_id with the given $chan_id (from $dest_node_id),
887 // if this way is cheaper than the already known
888 // (considering the cost to "reach" this channel from the route destination,
889 // the cost of using this channel,
890 // and the cost of routing to the source node of this channel).
891 // Also, consider that htlc_minimum_msat_difference, because we might end up
892 // paying it. Consider the following exploit:
893 // we use 2 paths to transfer 1.5 BTC. One of them is 0-fee normal 1 BTC path,
894 // and for the other one we picked a 1sat-fee path with htlc_minimum_msat of
895 // 1 BTC. Now, since the latter is more expensive, we gonna try to cut it
896 // by 0.5 BTC, but then match htlc_minimum_msat by paying a fee of 0.5 BTC
898 // Ideally the scoring could be smarter (e.g. 0.5*htlc_minimum_msat here),
899 // but it may require additional tracking - we don't want to double-count
900 // the fees included in $next_hops_path_htlc_minimum_msat, but also
901 // can't use something that may decrease on future hops.
902 let old_cost = cmp::max(old_entry.total_fee_msat, old_entry.path_htlc_minimum_msat)
903 .checked_add(old_entry.path_penalty_msat)
904 .unwrap_or_else(|| u64::max_value());
905 let new_cost = cmp::max(total_fee_msat, path_htlc_minimum_msat)
906 .checked_add(path_penalty_msat)
907 .unwrap_or_else(|| u64::max_value());
909 if !old_entry.was_processed && new_cost < old_cost {
910 targets.push(new_graph_node);
911 old_entry.next_hops_fee_msat = $next_hops_fee_msat;
912 old_entry.hop_use_fee_msat = hop_use_fee_msat;
913 old_entry.total_fee_msat = total_fee_msat;
914 old_entry.node_id = $dest_node_id.clone();
915 old_entry.short_channel_id = $chan_id.clone();
916 old_entry.channel_features = $chan_features;
917 old_entry.fee_msat = 0; // This value will be later filled with hop_use_fee_msat of the following channel
918 old_entry.cltv_expiry_delta = $directional_info.cltv_expiry_delta as u32;
919 old_entry.channel_fees = $directional_info.fees;
920 old_entry.htlc_minimum_msat = $directional_info.htlc_minimum_msat;
921 old_entry.path_htlc_minimum_msat = path_htlc_minimum_msat;
922 old_entry.path_penalty_msat = path_penalty_msat;
923 #[cfg(any(test, feature = "fuzztarget"))]
925 old_entry.value_contribution_msat = value_contribution_msat;
927 did_add_update_path_to_src_node = true;
928 } else if old_entry.was_processed && new_cost < old_cost {
929 #[cfg(any(test, feature = "fuzztarget"))]
931 // If we're skipping processing a node which was previously
932 // processed even though we found another path to it with a
933 // cheaper fee, check that it was because the second path we
934 // found (which we are processing now) has a lower value
935 // contribution due to an HTLC minimum limit.
937 // e.g. take a graph with two paths from node 1 to node 2, one
938 // through channel A, and one through channel B. Channel A and
939 // B are both in the to-process heap, with their scores set by
940 // a higher htlc_minimum than fee.
941 // Channel A is processed first, and the channels onwards from
942 // node 1 are added to the to-process heap. Thereafter, we pop
943 // Channel B off of the heap, note that it has a much more
944 // restrictive htlc_maximum_msat, and recalculate the fees for
945 // all of node 1's channels using the new, reduced, amount.
947 // This would be bogus - we'd be selecting a higher-fee path
948 // with a lower htlc_maximum_msat instead of the one we'd
949 // already decided to use.
950 debug_assert!(path_htlc_minimum_msat < old_entry.path_htlc_minimum_msat);
952 value_contribution_msat + path_penalty_msat <
953 old_entry.value_contribution_msat + old_entry.path_penalty_msat
961 did_add_update_path_to_src_node
965 let empty_node_features = NodeFeatures::empty();
966 // Find ways (channels with destination) to reach a given node and store them
967 // in the corresponding data structures (routing graph etc).
968 // $fee_to_target_msat represents how much it costs to reach to this node from the payee,
969 // meaning how much will be paid in fees after this node (to the best of our knowledge).
970 // This data can later be helpful to optimize routing (pay lower fees).
971 macro_rules! add_entries_to_cheapest_to_target_node {
972 ( $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 ) => {
973 let skip_node = if let Some(elem) = dist.get_mut(&$node_id) {
974 let was_processed = elem.was_processed;
975 elem.was_processed = true;
978 // Entries are added to dist in add_entry!() when there is a channel from a node.
979 // Because there are no channels from payee, it will not have a dist entry at this point.
980 // If we're processing any other node, it is always be the result of a channel from it.
981 assert_eq!($node_id, payee_node_id);
986 if let Some(first_channels) = first_hop_targets.get(&$node_id) {
987 for (ref first_hop, ref features, ref outbound_capacity_msat, _) in first_channels {
988 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);
992 let features = if let Some(node_info) = $node.announcement_info.as_ref() {
998 if !features.requires_unknown_bits() {
999 for chan_id in $node.channels.iter() {
1000 let chan = network_channels.get(chan_id).unwrap();
1001 if !chan.features.requires_unknown_bits() {
1002 if chan.node_one == $node_id {
1003 // ie $node is one, ie next hop in A* is two, via the two_to_one channel
1004 if first_hops.is_none() || chan.node_two != our_node_id {
1005 if let Some(two_to_one) = chan.two_to_one.as_ref() {
1006 if two_to_one.enabled {
1007 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);
1012 if first_hops.is_none() || chan.node_one != our_node_id{
1013 if let Some(one_to_two) = chan.one_to_two.as_ref() {
1014 if one_to_two.enabled {
1015 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);
1027 let mut payment_paths = Vec::<PaymentPath>::new();
1029 // TODO: diversify by nodes (so that all paths aren't doomed if one node is offline).
1030 'paths_collection: loop {
1031 // For every new path, start from scratch, except
1032 // bookkeeped_channels_liquidity_available_msat, which will improve
1033 // the further iterations of path finding. Also don't erase first_hop_targets.
1036 hit_minimum_limit = false;
1038 // If first hop is a private channel and the only way to reach the payee, this is the only
1039 // place where it could be added.
1040 if let Some(first_channels) = first_hop_targets.get(&payee_node_id) {
1041 for (ref first_hop, ref features, ref outbound_capacity_msat, _) in first_channels {
1042 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);
1043 log_trace!(logger, "{} direct route to payee via SCID {}", if added { "Added" } else { "Skipped" }, first_hop);
1047 // Add the payee as a target, so that the payee-to-payer
1048 // search algorithm knows what to start with.
1049 match network_nodes.get(&payee_node_id) {
1050 // The payee is not in our network graph, so nothing to add here.
1051 // There is still a chance of reaching them via last_hops though,
1052 // so don't yet fail the payment here.
1053 // If not, targets.pop() will not even let us enter the loop in step 2.
1056 add_entries_to_cheapest_to_target_node!(node, payee_node_id, 0, path_value_msat, 0, 0u64);
1061 // If a caller provided us with last hops, add them to routing targets. Since this happens
1062 // earlier than general path finding, they will be somewhat prioritized, although currently
1063 // it matters only if the fees are exactly the same.
1064 for route in payee.route_hints.iter().filter(|route| !route.0.is_empty()) {
1065 let first_hop_in_route = &(route.0)[0];
1066 let have_hop_src_in_graph =
1067 // Only add the hops in this route to our candidate set if either
1068 // we have a direct channel to the first hop or the first hop is
1069 // in the regular network graph.
1070 first_hop_targets.get(&NodeId::from_pubkey(&first_hop_in_route.src_node_id)).is_some() ||
1071 network_nodes.get(&NodeId::from_pubkey(&first_hop_in_route.src_node_id)).is_some();
1072 if have_hop_src_in_graph {
1073 // We start building the path from reverse, i.e., from payee
1074 // to the first RouteHintHop in the path.
1075 let hop_iter = route.0.iter().rev();
1076 let prev_hop_iter = core::iter::once(&payee.pubkey).chain(
1077 route.0.iter().skip(1).rev().map(|hop| &hop.src_node_id));
1078 let mut hop_used = true;
1079 let mut aggregate_next_hops_fee_msat: u64 = 0;
1080 let mut aggregate_next_hops_path_htlc_minimum_msat: u64 = 0;
1081 let mut aggregate_next_hops_path_penalty_msat: u64 = 0;
1083 for (idx, (hop, prev_hop_id)) in hop_iter.zip(prev_hop_iter).enumerate() {
1084 // BOLT 11 doesn't allow inclusion of features for the last hop hints, which
1085 // really sucks, cause we're gonna need that eventually.
1086 let hop_htlc_minimum_msat: u64 = hop.htlc_minimum_msat.unwrap_or(0);
1088 let directional_info = DummyDirectionalChannelInfo {
1089 cltv_expiry_delta: hop.cltv_expiry_delta as u32,
1090 htlc_minimum_msat: hop_htlc_minimum_msat,
1091 htlc_maximum_msat: hop.htlc_maximum_msat,
1095 let reqd_channel_cap = if let Some (val) = final_value_msat.checked_add(match idx {
1097 _ => aggregate_next_hops_fee_msat.checked_add(999).unwrap_or(u64::max_value())
1098 }) { Some( val / 1000 ) } else { break; }; // converting from msat or breaking if max ~ infinity
1100 let src_node_id = NodeId::from_pubkey(&hop.src_node_id);
1101 let dest_node_id = NodeId::from_pubkey(&prev_hop_id);
1102 aggregate_next_hops_path_penalty_msat = aggregate_next_hops_path_penalty_msat
1103 .checked_add(scorer.channel_penalty_msat(hop.short_channel_id, &src_node_id, &dest_node_id))
1104 .unwrap_or_else(|| u64::max_value());
1106 // We assume that the recipient only included route hints for routes which had
1107 // sufficient value to route `final_value_msat`. Note that in the case of "0-value"
1108 // invoices where the invoice does not specify value this may not be the case, but
1109 // better to include the hints than not.
1110 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) {
1111 // If this hop was not used then there is no use checking the preceding hops
1112 // in the RouteHint. We can break by just searching for a direct channel between
1113 // last checked hop and first_hop_targets
1117 // Searching for a direct channel between last checked hop and first_hop_targets
1118 if let Some(first_channels) = first_hop_targets.get(&NodeId::from_pubkey(&prev_hop_id)) {
1119 for (ref first_hop, ref features, ref outbound_capacity_msat, _) in first_channels {
1120 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);
1128 // In the next values of the iterator, the aggregate fees already reflects
1129 // the sum of value sent from payer (final_value_msat) and routing fees
1130 // for the last node in the RouteHint. We need to just add the fees to
1131 // route through the current node so that the preceeding node (next iteration)
1133 let hops_fee = compute_fees(aggregate_next_hops_fee_msat + final_value_msat, hop.fees)
1134 .map_or(None, |inc| inc.checked_add(aggregate_next_hops_fee_msat));
1135 aggregate_next_hops_fee_msat = if let Some(val) = hops_fee { val } else { break; };
1137 let hop_htlc_minimum_msat_inc = if let Some(val) = compute_fees(aggregate_next_hops_path_htlc_minimum_msat, hop.fees) { val } else { break; };
1138 let hops_path_htlc_minimum = aggregate_next_hops_path_htlc_minimum_msat
1139 .checked_add(hop_htlc_minimum_msat_inc);
1140 aggregate_next_hops_path_htlc_minimum_msat = if let Some(val) = hops_path_htlc_minimum { cmp::max(hop_htlc_minimum_msat, val) } else { break; };
1142 if idx == route.0.len() - 1 {
1143 // The last hop in this iterator is the first hop in
1144 // overall RouteHint.
1145 // If this hop connects to a node with which we have a direct channel,
1146 // ignore the network graph and, if the last hop was added, add our
1147 // direct channel to the candidate set.
1149 // Note that we *must* check if the last hop was added as `add_entry`
1150 // always assumes that the third argument is a node to which we have a
1152 if let Some(first_channels) = first_hop_targets.get(&NodeId::from_pubkey(&hop.src_node_id)) {
1153 for (ref first_hop, ref features, ref outbound_capacity_msat, _) in first_channels {
1154 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);
1162 log_trace!(logger, "Starting main path collection loop with {} nodes pre-filled from first/last hops.", targets.len());
1164 // At this point, targets are filled with the data from first and
1165 // last hops communicated by the caller, and the payment receiver.
1166 let mut found_new_path = false;
1169 // If this loop terminates due the exhaustion of targets, two situations are possible:
1170 // - not enough outgoing liquidity:
1171 // 0 < already_collected_value_msat < final_value_msat
1172 // - enough outgoing liquidity:
1173 // final_value_msat <= already_collected_value_msat < recommended_value_msat
1174 // Both these cases (and other cases except reaching recommended_value_msat) mean that
1175 // paths_collection will be stopped because found_new_path==false.
1176 // This is not necessarily a routing failure.
1177 'path_construction: while let Some(RouteGraphNode { node_id, lowest_fee_to_node, value_contribution_msat, path_htlc_minimum_msat, path_penalty_msat, .. }) = targets.pop() {
1179 // Since we're going payee-to-payer, hitting our node as a target means we should stop
1180 // traversing the graph and arrange the path out of what we found.
1181 if node_id == our_node_id {
1182 let mut new_entry = dist.remove(&our_node_id).unwrap();
1183 let mut ordered_hops = vec!((new_entry.clone(), NodeFeatures::empty()));
1186 let mut features_set = false;
1187 if let Some(first_channels) = first_hop_targets.get(&ordered_hops.last().unwrap().0.node_id) {
1188 for (scid, _, _, ref features) in first_channels {
1189 if *scid == ordered_hops.last().unwrap().0.short_channel_id {
1190 ordered_hops.last_mut().unwrap().1 = features.clone();
1191 features_set = true;
1197 if let Some(node) = network_nodes.get(&ordered_hops.last().unwrap().0.node_id) {
1198 if let Some(node_info) = node.announcement_info.as_ref() {
1199 ordered_hops.last_mut().unwrap().1 = node_info.features.clone();
1201 ordered_hops.last_mut().unwrap().1 = NodeFeatures::empty();
1204 // We should be able to fill in features for everything except the last
1205 // hop, if the last hop was provided via a BOLT 11 invoice (though we
1206 // should be able to extend it further as BOLT 11 does have feature
1207 // flags for the last hop node itself).
1208 assert!(ordered_hops.last().unwrap().0.node_id == payee_node_id);
1212 // Means we succesfully traversed from the payer to the payee, now
1213 // save this path for the payment route. Also, update the liquidity
1214 // remaining on the used hops, so that we take them into account
1215 // while looking for more paths.
1216 if ordered_hops.last().unwrap().0.node_id == payee_node_id {
1220 new_entry = match dist.remove(&ordered_hops.last().unwrap().0.node_id) {
1221 Some(payment_hop) => payment_hop,
1222 // We can't arrive at None because, if we ever add an entry to targets,
1223 // we also fill in the entry in dist (see add_entry!).
1224 None => unreachable!(),
1226 // We "propagate" the fees one hop backward (topologically) here,
1227 // so that fees paid for a HTLC forwarding on the current channel are
1228 // associated with the previous channel (where they will be subtracted).
1229 ordered_hops.last_mut().unwrap().0.fee_msat = new_entry.hop_use_fee_msat;
1230 ordered_hops.last_mut().unwrap().0.cltv_expiry_delta = new_entry.cltv_expiry_delta;
1231 ordered_hops.push((new_entry.clone(), NodeFeatures::empty()));
1233 ordered_hops.last_mut().unwrap().0.fee_msat = value_contribution_msat;
1234 ordered_hops.last_mut().unwrap().0.hop_use_fee_msat = 0;
1235 ordered_hops.last_mut().unwrap().0.cltv_expiry_delta = final_cltv_expiry_delta;
1237 log_trace!(logger, "Found a path back to us from the target with {} hops contributing up to {} msat: {:?}",
1238 ordered_hops.len(), value_contribution_msat, ordered_hops);
1240 let mut payment_path = PaymentPath {hops: ordered_hops};
1242 // We could have possibly constructed a slightly inconsistent path: since we reduce
1243 // value being transferred along the way, we could have violated htlc_minimum_msat
1244 // on some channels we already passed (assuming dest->source direction). Here, we
1245 // recompute the fees again, so that if that's the case, we match the currently
1246 // underpaid htlc_minimum_msat with fees.
1247 payment_path.update_value_and_recompute_fees(cmp::min(value_contribution_msat, final_value_msat));
1249 // Since a path allows to transfer as much value as
1250 // the smallest channel it has ("bottleneck"), we should recompute
1251 // the fees so sender HTLC don't overpay fees when traversing
1252 // larger channels than the bottleneck. This may happen because
1253 // when we were selecting those channels we were not aware how much value
1254 // this path will transfer, and the relative fee for them
1255 // might have been computed considering a larger value.
1256 // Remember that we used these channels so that we don't rely
1257 // on the same liquidity in future paths.
1258 let mut prevented_redundant_path_selection = false;
1259 for (payment_hop, _) in payment_path.hops.iter() {
1260 let channel_liquidity_available_msat = bookkeeped_channels_liquidity_available_msat.get_mut(&payment_hop.short_channel_id).unwrap();
1261 let mut spent_on_hop_msat = value_contribution_msat;
1262 let next_hops_fee_msat = payment_hop.next_hops_fee_msat;
1263 spent_on_hop_msat += next_hops_fee_msat;
1264 if spent_on_hop_msat == *channel_liquidity_available_msat {
1265 // If this path used all of this channel's available liquidity, we know
1266 // this path will not be selected again in the next loop iteration.
1267 prevented_redundant_path_selection = true;
1269 *channel_liquidity_available_msat -= spent_on_hop_msat;
1271 if !prevented_redundant_path_selection {
1272 // If we weren't capped by hitting a liquidity limit on a channel in the path,
1273 // we'll probably end up picking the same path again on the next iteration.
1274 // Decrease the available liquidity of a hop in the middle of the path.
1275 let victim_scid = payment_path.hops[(payment_path.hops.len() - 1) / 2].0.short_channel_id;
1276 log_trace!(logger, "Disabling channel {} for future path building iterations to avoid duplicates.", victim_scid);
1277 let victim_liquidity = bookkeeped_channels_liquidity_available_msat.get_mut(&victim_scid).unwrap();
1278 *victim_liquidity = 0;
1281 // Track the total amount all our collected paths allow to send so that we:
1282 // - know when to stop looking for more paths
1283 // - know which of the hops are useless considering how much more sats we need
1284 // (contributes_sufficient_value)
1285 already_collected_value_msat += value_contribution_msat;
1287 payment_paths.push(payment_path);
1288 found_new_path = true;
1289 break 'path_construction;
1292 // If we found a path back to the payee, we shouldn't try to process it again. This is
1293 // the equivalent of the `elem.was_processed` check in
1294 // add_entries_to_cheapest_to_target_node!() (see comment there for more info).
1295 if node_id == payee_node_id { continue 'path_construction; }
1297 // Otherwise, since the current target node is not us,
1298 // keep "unrolling" the payment graph from payee to payer by
1299 // finding a way to reach the current target from the payer side.
1300 match network_nodes.get(&node_id) {
1303 add_entries_to_cheapest_to_target_node!(node, node_id, lowest_fee_to_node, value_contribution_msat, path_htlc_minimum_msat, path_penalty_msat);
1309 // If we don't support MPP, no use trying to gather more value ever.
1310 break 'paths_collection;
1314 // Stop either when the recommended value is reached or if no new path was found in this
1316 // In the latter case, making another path finding attempt won't help,
1317 // because we deterministically terminated the search due to low liquidity.
1318 if already_collected_value_msat >= recommended_value_msat || !found_new_path {
1319 log_trace!(logger, "Have now collected {} msat (seeking {} msat) in paths. Last path loop {} a new path.",
1320 already_collected_value_msat, recommended_value_msat, if found_new_path { "found" } else { "did not find" });
1321 break 'paths_collection;
1322 } else if found_new_path && already_collected_value_msat == final_value_msat && payment_paths.len() == 1 {
1323 // Further, if this was our first walk of the graph, and we weren't limited by an
1324 // htlc_minimum_msat, return immediately because this path should suffice. If we were
1325 // limited by an htlc_minimum_msat value, find another path with a higher value,
1326 // potentially allowing us to pay fees to meet the htlc_minimum on the new path while
1327 // still keeping a lower total fee than this path.
1328 if !hit_minimum_limit {
1329 log_trace!(logger, "Collected exactly our payment amount on the first pass, without hitting an htlc_minimum_msat limit, exiting.");
1330 break 'paths_collection;
1332 log_trace!(logger, "Collected our payment amount on the first pass, but running again to collect extra paths with a potentially higher limit.");
1333 path_value_msat = recommended_value_msat;
1338 if payment_paths.len() == 0 {
1339 return Err(LightningError{err: "Failed to find a path to the given destination".to_owned(), action: ErrorAction::IgnoreError});
1342 if already_collected_value_msat < final_value_msat {
1343 return Err(LightningError{err: "Failed to find a sufficient route to the given destination".to_owned(), action: ErrorAction::IgnoreError});
1346 // Sort by total fees and take the best paths.
1347 payment_paths.sort_by_key(|path| path.get_total_fee_paid_msat());
1348 if payment_paths.len() > 50 {
1349 payment_paths.truncate(50);
1352 // Draw multiple sufficient routes by randomly combining the selected paths.
1353 let mut drawn_routes = Vec::new();
1354 for i in 0..payment_paths.len() {
1355 let mut cur_route = Vec::<PaymentPath>::new();
1356 let mut aggregate_route_value_msat = 0;
1359 // TODO: real random shuffle
1360 // Currently just starts with i_th and goes up to i-1_th in a looped way.
1361 let cur_payment_paths = [&payment_paths[i..], &payment_paths[..i]].concat();
1364 for payment_path in cur_payment_paths {
1365 cur_route.push(payment_path.clone());
1366 aggregate_route_value_msat += payment_path.get_value_msat();
1367 if aggregate_route_value_msat > final_value_msat {
1368 // Last path likely overpaid. Substract it from the most expensive
1369 // (in terms of proportional fee) path in this route and recompute fees.
1370 // This might be not the most economically efficient way, but fewer paths
1371 // also makes routing more reliable.
1372 let mut overpaid_value_msat = aggregate_route_value_msat - final_value_msat;
1374 // First, drop some expensive low-value paths entirely if possible.
1375 // Sort by value so that we drop many really-low values first, since
1376 // fewer paths is better: the payment is less likely to fail.
1377 // TODO: this could also be optimized by also sorting by feerate_per_sat_routed,
1378 // so that the sender pays less fees overall. And also htlc_minimum_msat.
1379 cur_route.sort_by_key(|path| path.get_value_msat());
1380 // We should make sure that at least 1 path left.
1381 let mut paths_left = cur_route.len();
1382 cur_route.retain(|path| {
1383 if paths_left == 1 {
1386 let mut keep = true;
1387 let path_value_msat = path.get_value_msat();
1388 if path_value_msat <= overpaid_value_msat {
1390 overpaid_value_msat -= path_value_msat;
1396 if overpaid_value_msat == 0 {
1400 assert!(cur_route.len() > 0);
1403 // Now, substract the overpaid value from the most-expensive path.
1404 // TODO: this could also be optimized by also sorting by feerate_per_sat_routed,
1405 // so that the sender pays less fees overall. And also htlc_minimum_msat.
1406 cur_route.sort_by_key(|path| { path.hops.iter().map(|hop| hop.0.channel_fees.proportional_millionths as u64).sum::<u64>() });
1407 let expensive_payment_path = cur_route.first_mut().unwrap();
1408 // We already dropped all the small channels above, meaning all the
1409 // remaining channels are larger than remaining overpaid_value_msat.
1410 // Thus, this can't be negative.
1411 let expensive_path_new_value_msat = expensive_payment_path.get_value_msat() - overpaid_value_msat;
1412 expensive_payment_path.update_value_and_recompute_fees(expensive_path_new_value_msat);
1416 drawn_routes.push(cur_route);
1420 // Select the best route by lowest total fee.
1421 drawn_routes.sort_by_key(|paths| paths.iter().map(|path| path.get_total_fee_paid_msat()).sum::<u64>());
1422 let mut selected_paths = Vec::<Vec<Result<RouteHop, LightningError>>>::new();
1423 for payment_path in drawn_routes.first().unwrap() {
1424 selected_paths.push(payment_path.hops.iter().map(|(payment_hop, node_features)| {
1426 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)})?,
1427 node_features: node_features.clone(),
1428 short_channel_id: payment_hop.short_channel_id,
1429 channel_features: payment_hop.channel_features.clone(),
1430 fee_msat: payment_hop.fee_msat,
1431 cltv_expiry_delta: payment_hop.cltv_expiry_delta,
1436 if let Some(features) = &payee.features {
1437 for path in selected_paths.iter_mut() {
1438 if let Ok(route_hop) = path.last_mut().unwrap() {
1439 route_hop.node_features = features.to_context();
1445 paths: selected_paths.into_iter().map(|path| path.into_iter().collect()).collect::<Result<Vec<_>, _>>()?,
1446 payee: Some(payee.clone()),
1448 log_info!(logger, "Got route to {}: {}", payee.pubkey, log_route!(route));
1455 use routing::network_graph::{NetworkGraph, NetGraphMsgHandler, NodeId};
1456 use routing::router::{get_route, Payee, Route, RouteHint, RouteHintHop, RouteHop, RoutingFees};
1457 use routing::scorer::Scorer;
1458 use chain::transaction::OutPoint;
1459 use ln::features::{ChannelFeatures, InitFeatures, InvoiceFeatures, NodeFeatures};
1460 use ln::msgs::{ErrorAction, LightningError, OptionalField, UnsignedChannelAnnouncement, ChannelAnnouncement, RoutingMessageHandler,
1461 NodeAnnouncement, UnsignedNodeAnnouncement, ChannelUpdate, UnsignedChannelUpdate};
1462 use ln::channelmanager;
1463 use util::test_utils;
1464 use util::ser::Writeable;
1466 use bitcoin::hashes::sha256d::Hash as Sha256dHash;
1467 use bitcoin::hashes::Hash;
1468 use bitcoin::network::constants::Network;
1469 use bitcoin::blockdata::constants::genesis_block;
1470 use bitcoin::blockdata::script::Builder;
1471 use bitcoin::blockdata::opcodes;
1472 use bitcoin::blockdata::transaction::TxOut;
1476 use bitcoin::secp256k1::key::{PublicKey,SecretKey};
1477 use bitcoin::secp256k1::{Secp256k1, All};
1480 use sync::{self, Arc};
1482 fn get_channel_details(short_channel_id: Option<u64>, node_id: PublicKey,
1483 features: InitFeatures, outbound_capacity_msat: u64) -> channelmanager::ChannelDetails {
1484 channelmanager::ChannelDetails {
1485 channel_id: [0; 32],
1486 counterparty: channelmanager::ChannelCounterparty {
1489 unspendable_punishment_reserve: 0,
1490 forwarding_info: None,
1492 funding_txo: Some(OutPoint { txid: bitcoin::Txid::from_slice(&[0; 32]).unwrap(), index: 0 }),
1494 channel_value_satoshis: 0,
1496 outbound_capacity_msat,
1497 inbound_capacity_msat: 42,
1498 unspendable_punishment_reserve: None,
1499 confirmations_required: None,
1500 force_close_spend_delay: None,
1501 is_outbound: true, is_funding_locked: true,
1502 is_usable: true, is_public: true,
1506 // Using the same keys for LN and BTC ids
1508 net_graph_msg_handler: &NetGraphMsgHandler<Arc<test_utils::TestChainSource>, Arc<test_utils::TestLogger>>,
1509 secp_ctx: &Secp256k1<All>, node_1_privkey: &SecretKey, node_2_privkey: &SecretKey, features: ChannelFeatures, short_channel_id: u64
1511 let node_id_1 = PublicKey::from_secret_key(&secp_ctx, node_1_privkey);
1512 let node_id_2 = PublicKey::from_secret_key(&secp_ctx, node_2_privkey);
1514 let unsigned_announcement = UnsignedChannelAnnouncement {
1516 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1520 bitcoin_key_1: node_id_1,
1521 bitcoin_key_2: node_id_2,
1522 excess_data: Vec::new(),
1525 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1526 let valid_announcement = ChannelAnnouncement {
1527 node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
1528 node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
1529 bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
1530 bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
1531 contents: unsigned_announcement.clone(),
1533 match net_graph_msg_handler.handle_channel_announcement(&valid_announcement) {
1534 Ok(res) => assert!(res),
1540 net_graph_msg_handler: &NetGraphMsgHandler<Arc<test_utils::TestChainSource>, Arc<test_utils::TestLogger>>,
1541 secp_ctx: &Secp256k1<All>, node_privkey: &SecretKey, update: UnsignedChannelUpdate
1543 let msghash = hash_to_message!(&Sha256dHash::hash(&update.encode()[..])[..]);
1544 let valid_channel_update = ChannelUpdate {
1545 signature: secp_ctx.sign(&msghash, node_privkey),
1546 contents: update.clone()
1549 match net_graph_msg_handler.handle_channel_update(&valid_channel_update) {
1550 Ok(res) => assert!(res),
1555 fn add_or_update_node(
1556 net_graph_msg_handler: &NetGraphMsgHandler<Arc<test_utils::TestChainSource>, Arc<test_utils::TestLogger>>,
1557 secp_ctx: &Secp256k1<All>, node_privkey: &SecretKey, features: NodeFeatures, timestamp: u32
1559 let node_id = PublicKey::from_secret_key(&secp_ctx, node_privkey);
1560 let unsigned_announcement = UnsignedNodeAnnouncement {
1566 addresses: Vec::new(),
1567 excess_address_data: Vec::new(),
1568 excess_data: Vec::new(),
1570 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1571 let valid_announcement = NodeAnnouncement {
1572 signature: secp_ctx.sign(&msghash, node_privkey),
1573 contents: unsigned_announcement.clone()
1576 match net_graph_msg_handler.handle_node_announcement(&valid_announcement) {
1582 fn get_nodes(secp_ctx: &Secp256k1<All>) -> (SecretKey, PublicKey, Vec<SecretKey>, Vec<PublicKey>) {
1583 let privkeys: Vec<SecretKey> = (2..10).map(|i| {
1584 SecretKey::from_slice(&hex::decode(format!("{:02}", i).repeat(32)).unwrap()[..]).unwrap()
1587 let pubkeys = privkeys.iter().map(|secret| PublicKey::from_secret_key(&secp_ctx, secret)).collect();
1589 let our_privkey = SecretKey::from_slice(&hex::decode("01".repeat(32)).unwrap()[..]).unwrap();
1590 let our_id = PublicKey::from_secret_key(&secp_ctx, &our_privkey);
1592 (our_privkey, our_id, privkeys, pubkeys)
1595 fn id_to_feature_flags(id: u8) -> Vec<u8> {
1596 // Set the feature flags to the id'th odd (ie non-required) feature bit so that we can
1597 // test for it later.
1598 let idx = (id - 1) * 2 + 1;
1600 vec![1 << (idx - 8*3), 0, 0, 0]
1601 } else if idx > 8*2 {
1602 vec![1 << (idx - 8*2), 0, 0]
1603 } else if idx > 8*1 {
1604 vec![1 << (idx - 8*1), 0]
1610 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>) {
1611 let secp_ctx = Secp256k1::new();
1612 let logger = Arc::new(test_utils::TestLogger::new());
1613 let chain_monitor = Arc::new(test_utils::TestChainSource::new(Network::Testnet));
1614 let network_graph = NetworkGraph::new(genesis_block(Network::Testnet).header.block_hash());
1615 let net_graph_msg_handler = NetGraphMsgHandler::new(network_graph, None, Arc::clone(&logger));
1616 // Build network from our_id to node6:
1618 // -1(1)2- node0 -1(3)2-
1620 // our_id -1(12)2- node7 -1(13)2--- node2
1622 // -1(2)2- node1 -1(4)2-
1625 // chan1 1-to-2: disabled
1626 // chan1 2-to-1: enabled, 0 fee
1628 // chan2 1-to-2: enabled, ignored fee
1629 // chan2 2-to-1: enabled, 0 fee
1631 // chan3 1-to-2: enabled, 0 fee
1632 // chan3 2-to-1: enabled, 100 msat fee
1634 // chan4 1-to-2: enabled, 100% fee
1635 // chan4 2-to-1: enabled, 0 fee
1637 // chan12 1-to-2: enabled, ignored fee
1638 // chan12 2-to-1: enabled, 0 fee
1640 // chan13 1-to-2: enabled, 200% fee
1641 // chan13 2-to-1: enabled, 0 fee
1644 // -1(5)2- node3 -1(8)2--
1648 // node2--1(6)2- node4 -1(9)2--- node6 (not in global route map)
1650 // -1(7)2- node5 -1(10)2-
1652 // Channels 5, 8, 9 and 10 are private channels.
1654 // chan5 1-to-2: enabled, 100 msat fee
1655 // chan5 2-to-1: enabled, 0 fee
1657 // chan6 1-to-2: enabled, 0 fee
1658 // chan6 2-to-1: enabled, 0 fee
1660 // chan7 1-to-2: enabled, 100% fee
1661 // chan7 2-to-1: enabled, 0 fee
1663 // chan8 1-to-2: enabled, variable fee (0 then 1000 msat)
1664 // chan8 2-to-1: enabled, 0 fee
1666 // chan9 1-to-2: enabled, 1001 msat fee
1667 // chan9 2-to-1: enabled, 0 fee
1669 // chan10 1-to-2: enabled, 0 fee
1670 // chan10 2-to-1: enabled, 0 fee
1672 // chan11 1-to-2: enabled, 0 fee
1673 // chan11 2-to-1: enabled, 0 fee
1675 let (our_privkey, _, privkeys, _) = get_nodes(&secp_ctx);
1677 add_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, &privkeys[0], ChannelFeatures::from_le_bytes(id_to_feature_flags(1)), 1);
1678 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
1679 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1680 short_channel_id: 1,
1683 cltv_expiry_delta: 0,
1684 htlc_minimum_msat: 0,
1685 htlc_maximum_msat: OptionalField::Absent,
1687 fee_proportional_millionths: 0,
1688 excess_data: Vec::new()
1691 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[0], NodeFeatures::from_le_bytes(id_to_feature_flags(1)), 0);
1693 add_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, &privkeys[1], ChannelFeatures::from_le_bytes(id_to_feature_flags(2)), 2);
1694 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
1695 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1696 short_channel_id: 2,
1699 cltv_expiry_delta: u16::max_value(),
1700 htlc_minimum_msat: 0,
1701 htlc_maximum_msat: OptionalField::Absent,
1702 fee_base_msat: u32::max_value(),
1703 fee_proportional_millionths: u32::max_value(),
1704 excess_data: Vec::new()
1706 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
1707 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1708 short_channel_id: 2,
1711 cltv_expiry_delta: 0,
1712 htlc_minimum_msat: 0,
1713 htlc_maximum_msat: OptionalField::Absent,
1715 fee_proportional_millionths: 0,
1716 excess_data: Vec::new()
1719 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[1], NodeFeatures::from_le_bytes(id_to_feature_flags(2)), 0);
1721 add_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, &privkeys[7], ChannelFeatures::from_le_bytes(id_to_feature_flags(12)), 12);
1722 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
1723 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1724 short_channel_id: 12,
1727 cltv_expiry_delta: u16::max_value(),
1728 htlc_minimum_msat: 0,
1729 htlc_maximum_msat: OptionalField::Absent,
1730 fee_base_msat: u32::max_value(),
1731 fee_proportional_millionths: u32::max_value(),
1732 excess_data: Vec::new()
1734 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
1735 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1736 short_channel_id: 12,
1739 cltv_expiry_delta: 0,
1740 htlc_minimum_msat: 0,
1741 htlc_maximum_msat: OptionalField::Absent,
1743 fee_proportional_millionths: 0,
1744 excess_data: Vec::new()
1747 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[7], NodeFeatures::from_le_bytes(id_to_feature_flags(8)), 0);
1749 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], &privkeys[2], ChannelFeatures::from_le_bytes(id_to_feature_flags(3)), 3);
1750 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
1751 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1752 short_channel_id: 3,
1755 cltv_expiry_delta: (3 << 8) | 1,
1756 htlc_minimum_msat: 0,
1757 htlc_maximum_msat: OptionalField::Absent,
1759 fee_proportional_millionths: 0,
1760 excess_data: Vec::new()
1762 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
1763 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1764 short_channel_id: 3,
1767 cltv_expiry_delta: (3 << 8) | 2,
1768 htlc_minimum_msat: 0,
1769 htlc_maximum_msat: OptionalField::Absent,
1771 fee_proportional_millionths: 0,
1772 excess_data: Vec::new()
1775 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], &privkeys[2], ChannelFeatures::from_le_bytes(id_to_feature_flags(4)), 4);
1776 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
1777 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1778 short_channel_id: 4,
1781 cltv_expiry_delta: (4 << 8) | 1,
1782 htlc_minimum_msat: 0,
1783 htlc_maximum_msat: OptionalField::Absent,
1785 fee_proportional_millionths: 1000000,
1786 excess_data: Vec::new()
1788 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
1789 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1790 short_channel_id: 4,
1793 cltv_expiry_delta: (4 << 8) | 2,
1794 htlc_minimum_msat: 0,
1795 htlc_maximum_msat: OptionalField::Absent,
1797 fee_proportional_millionths: 0,
1798 excess_data: Vec::new()
1801 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], &privkeys[2], ChannelFeatures::from_le_bytes(id_to_feature_flags(13)), 13);
1802 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
1803 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1804 short_channel_id: 13,
1807 cltv_expiry_delta: (13 << 8) | 1,
1808 htlc_minimum_msat: 0,
1809 htlc_maximum_msat: OptionalField::Absent,
1811 fee_proportional_millionths: 2000000,
1812 excess_data: Vec::new()
1814 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
1815 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1816 short_channel_id: 13,
1819 cltv_expiry_delta: (13 << 8) | 2,
1820 htlc_minimum_msat: 0,
1821 htlc_maximum_msat: OptionalField::Absent,
1823 fee_proportional_millionths: 0,
1824 excess_data: Vec::new()
1827 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[2], NodeFeatures::from_le_bytes(id_to_feature_flags(3)), 0);
1829 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], &privkeys[4], ChannelFeatures::from_le_bytes(id_to_feature_flags(6)), 6);
1830 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
1831 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1832 short_channel_id: 6,
1835 cltv_expiry_delta: (6 << 8) | 1,
1836 htlc_minimum_msat: 0,
1837 htlc_maximum_msat: OptionalField::Absent,
1839 fee_proportional_millionths: 0,
1840 excess_data: Vec::new()
1842 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
1843 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1844 short_channel_id: 6,
1847 cltv_expiry_delta: (6 << 8) | 2,
1848 htlc_minimum_msat: 0,
1849 htlc_maximum_msat: OptionalField::Absent,
1851 fee_proportional_millionths: 0,
1852 excess_data: Vec::new(),
1855 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(11)), 11);
1856 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
1857 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1858 short_channel_id: 11,
1861 cltv_expiry_delta: (11 << 8) | 1,
1862 htlc_minimum_msat: 0,
1863 htlc_maximum_msat: OptionalField::Absent,
1865 fee_proportional_millionths: 0,
1866 excess_data: Vec::new()
1868 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[3], UnsignedChannelUpdate {
1869 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1870 short_channel_id: 11,
1873 cltv_expiry_delta: (11 << 8) | 2,
1874 htlc_minimum_msat: 0,
1875 htlc_maximum_msat: OptionalField::Absent,
1877 fee_proportional_millionths: 0,
1878 excess_data: Vec::new()
1881 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[4], NodeFeatures::from_le_bytes(id_to_feature_flags(5)), 0);
1883 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[3], NodeFeatures::from_le_bytes(id_to_feature_flags(4)), 0);
1885 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], &privkeys[5], ChannelFeatures::from_le_bytes(id_to_feature_flags(7)), 7);
1886 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
1887 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1888 short_channel_id: 7,
1891 cltv_expiry_delta: (7 << 8) | 1,
1892 htlc_minimum_msat: 0,
1893 htlc_maximum_msat: OptionalField::Absent,
1895 fee_proportional_millionths: 1000000,
1896 excess_data: Vec::new()
1898 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[5], UnsignedChannelUpdate {
1899 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1900 short_channel_id: 7,
1903 cltv_expiry_delta: (7 << 8) | 2,
1904 htlc_minimum_msat: 0,
1905 htlc_maximum_msat: OptionalField::Absent,
1907 fee_proportional_millionths: 0,
1908 excess_data: Vec::new()
1911 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[5], NodeFeatures::from_le_bytes(id_to_feature_flags(6)), 0);
1913 (secp_ctx, net_graph_msg_handler, chain_monitor, logger)
1917 fn simple_route_test() {
1918 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
1919 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
1920 let payee = Payee::new(nodes[2]);
1921 let scorer = Scorer::new(0);
1923 // Simple route to 2 via 1
1925 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) {
1926 assert_eq!(err, "Cannot send a payment of 0 msat");
1927 } else { panic!(); }
1929 let route = get_route(&our_id, &payee, &net_graph_msg_handler.network_graph, None, 100, 42, Arc::clone(&logger), &scorer).unwrap();
1930 assert_eq!(route.paths[0].len(), 2);
1932 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
1933 assert_eq!(route.paths[0][0].short_channel_id, 2);
1934 assert_eq!(route.paths[0][0].fee_msat, 100);
1935 assert_eq!(route.paths[0][0].cltv_expiry_delta, (4 << 8) | 1);
1936 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
1937 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
1939 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
1940 assert_eq!(route.paths[0][1].short_channel_id, 4);
1941 assert_eq!(route.paths[0][1].fee_msat, 100);
1942 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
1943 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
1944 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
1948 fn invalid_first_hop_test() {
1949 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
1950 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
1951 let payee = Payee::new(nodes[2]);
1952 let scorer = Scorer::new(0);
1954 // Simple route to 2 via 1
1956 let our_chans = vec![get_channel_details(Some(2), our_id, InitFeatures::from_le_bytes(vec![0b11]), 100000)];
1958 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) {
1959 assert_eq!(err, "First hop cannot have our_node_pubkey as a destination.");
1960 } else { panic!(); }
1962 let route = get_route(&our_id, &payee, &net_graph_msg_handler.network_graph, None, 100, 42, Arc::clone(&logger), &scorer).unwrap();
1963 assert_eq!(route.paths[0].len(), 2);
1967 fn htlc_minimum_test() {
1968 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
1969 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
1970 let payee = Payee::new(nodes[2]);
1971 let scorer = Scorer::new(0);
1973 // Simple route to 2 via 1
1975 // Disable other paths
1976 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
1977 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1978 short_channel_id: 12,
1980 flags: 2, // to disable
1981 cltv_expiry_delta: 0,
1982 htlc_minimum_msat: 0,
1983 htlc_maximum_msat: OptionalField::Absent,
1985 fee_proportional_millionths: 0,
1986 excess_data: Vec::new()
1988 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
1989 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1990 short_channel_id: 3,
1992 flags: 2, // to disable
1993 cltv_expiry_delta: 0,
1994 htlc_minimum_msat: 0,
1995 htlc_maximum_msat: OptionalField::Absent,
1997 fee_proportional_millionths: 0,
1998 excess_data: Vec::new()
2000 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
2001 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2002 short_channel_id: 13,
2004 flags: 2, // to disable
2005 cltv_expiry_delta: 0,
2006 htlc_minimum_msat: 0,
2007 htlc_maximum_msat: OptionalField::Absent,
2009 fee_proportional_millionths: 0,
2010 excess_data: Vec::new()
2012 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
2013 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2014 short_channel_id: 6,
2016 flags: 2, // to disable
2017 cltv_expiry_delta: 0,
2018 htlc_minimum_msat: 0,
2019 htlc_maximum_msat: OptionalField::Absent,
2021 fee_proportional_millionths: 0,
2022 excess_data: Vec::new()
2024 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
2025 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2026 short_channel_id: 7,
2028 flags: 2, // to disable
2029 cltv_expiry_delta: 0,
2030 htlc_minimum_msat: 0,
2031 htlc_maximum_msat: OptionalField::Absent,
2033 fee_proportional_millionths: 0,
2034 excess_data: Vec::new()
2037 // Check against amount_to_transfer_over_msat.
2038 // Set minimal HTLC of 200_000_000 msat.
2039 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2040 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2041 short_channel_id: 2,
2044 cltv_expiry_delta: 0,
2045 htlc_minimum_msat: 200_000_000,
2046 htlc_maximum_msat: OptionalField::Absent,
2048 fee_proportional_millionths: 0,
2049 excess_data: Vec::new()
2052 // Second hop only allows to forward 199_999_999 at most, thus not allowing the first hop to
2054 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
2055 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2056 short_channel_id: 4,
2059 cltv_expiry_delta: 0,
2060 htlc_minimum_msat: 0,
2061 htlc_maximum_msat: OptionalField::Present(199_999_999),
2063 fee_proportional_millionths: 0,
2064 excess_data: Vec::new()
2067 // Not possible to send 199_999_999, because the minimum on channel=2 is 200_000_000.
2068 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) {
2069 assert_eq!(err, "Failed to find a path to the given destination");
2070 } else { panic!(); }
2072 // Lift the restriction on the first hop.
2073 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2074 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2075 short_channel_id: 2,
2078 cltv_expiry_delta: 0,
2079 htlc_minimum_msat: 0,
2080 htlc_maximum_msat: OptionalField::Absent,
2082 fee_proportional_millionths: 0,
2083 excess_data: Vec::new()
2086 // A payment above the minimum should pass
2087 let route = get_route(&our_id, &payee, &net_graph_msg_handler.network_graph, None, 199_999_999, 42, Arc::clone(&logger), &scorer).unwrap();
2088 assert_eq!(route.paths[0].len(), 2);
2092 fn htlc_minimum_overpay_test() {
2093 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
2094 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
2095 let payee = Payee::new(nodes[2]).with_features(InvoiceFeatures::known());
2096 let scorer = Scorer::new(0);
2098 // A route to node#2 via two paths.
2099 // One path allows transferring 35-40 sats, another one also allows 35-40 sats.
2100 // Thus, they can't send 60 without overpaying.
2101 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2102 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2103 short_channel_id: 2,
2106 cltv_expiry_delta: 0,
2107 htlc_minimum_msat: 35_000,
2108 htlc_maximum_msat: OptionalField::Present(40_000),
2110 fee_proportional_millionths: 0,
2111 excess_data: Vec::new()
2113 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2114 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2115 short_channel_id: 12,
2118 cltv_expiry_delta: 0,
2119 htlc_minimum_msat: 35_000,
2120 htlc_maximum_msat: OptionalField::Present(40_000),
2122 fee_proportional_millionths: 0,
2123 excess_data: Vec::new()
2127 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
2128 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2129 short_channel_id: 13,
2132 cltv_expiry_delta: 0,
2133 htlc_minimum_msat: 0,
2134 htlc_maximum_msat: OptionalField::Absent,
2136 fee_proportional_millionths: 0,
2137 excess_data: Vec::new()
2139 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
2140 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2141 short_channel_id: 4,
2144 cltv_expiry_delta: 0,
2145 htlc_minimum_msat: 0,
2146 htlc_maximum_msat: OptionalField::Absent,
2148 fee_proportional_millionths: 0,
2149 excess_data: Vec::new()
2152 // Disable other paths
2153 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2154 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2155 short_channel_id: 1,
2157 flags: 2, // to disable
2158 cltv_expiry_delta: 0,
2159 htlc_minimum_msat: 0,
2160 htlc_maximum_msat: OptionalField::Absent,
2162 fee_proportional_millionths: 0,
2163 excess_data: Vec::new()
2166 let route = get_route(&our_id, &payee, &net_graph_msg_handler.network_graph, None, 60_000, 42, Arc::clone(&logger), &scorer).unwrap();
2167 // Overpay fees to hit htlc_minimum_msat.
2168 let overpaid_fees = route.paths[0][0].fee_msat + route.paths[1][0].fee_msat;
2169 // TODO: this could be better balanced to overpay 10k and not 15k.
2170 assert_eq!(overpaid_fees, 15_000);
2172 // Now, test that if there are 2 paths, a "cheaper" by fee path wouldn't be prioritized
2173 // while taking even more fee to match htlc_minimum_msat.
2174 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2175 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2176 short_channel_id: 12,
2179 cltv_expiry_delta: 0,
2180 htlc_minimum_msat: 65_000,
2181 htlc_maximum_msat: OptionalField::Present(80_000),
2183 fee_proportional_millionths: 0,
2184 excess_data: Vec::new()
2186 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2187 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2188 short_channel_id: 2,
2191 cltv_expiry_delta: 0,
2192 htlc_minimum_msat: 0,
2193 htlc_maximum_msat: OptionalField::Absent,
2195 fee_proportional_millionths: 0,
2196 excess_data: Vec::new()
2198 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
2199 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2200 short_channel_id: 4,
2203 cltv_expiry_delta: 0,
2204 htlc_minimum_msat: 0,
2205 htlc_maximum_msat: OptionalField::Absent,
2207 fee_proportional_millionths: 100_000,
2208 excess_data: Vec::new()
2211 let route = get_route(&our_id, &payee, &net_graph_msg_handler.network_graph, None, 60_000, 42, Arc::clone(&logger), &scorer).unwrap();
2212 // Fine to overpay for htlc_minimum_msat if it allows us to save fee.
2213 assert_eq!(route.paths.len(), 1);
2214 assert_eq!(route.paths[0][0].short_channel_id, 12);
2215 let fees = route.paths[0][0].fee_msat;
2216 assert_eq!(fees, 5_000);
2218 let route = get_route(&our_id, &payee, &net_graph_msg_handler.network_graph, None, 50_000, 42, Arc::clone(&logger), &scorer).unwrap();
2219 // Not fine to overpay for htlc_minimum_msat if it requires paying more than fee on
2220 // the other channel.
2221 assert_eq!(route.paths.len(), 1);
2222 assert_eq!(route.paths[0][0].short_channel_id, 2);
2223 let fees = route.paths[0][0].fee_msat;
2224 assert_eq!(fees, 5_000);
2228 fn disable_channels_test() {
2229 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
2230 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
2231 let payee = Payee::new(nodes[2]);
2232 let scorer = Scorer::new(0);
2234 // // Disable channels 4 and 12 by flags=2
2235 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
2236 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2237 short_channel_id: 4,
2239 flags: 2, // to disable
2240 cltv_expiry_delta: 0,
2241 htlc_minimum_msat: 0,
2242 htlc_maximum_msat: OptionalField::Absent,
2244 fee_proportional_millionths: 0,
2245 excess_data: Vec::new()
2247 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2248 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2249 short_channel_id: 12,
2251 flags: 2, // to disable
2252 cltv_expiry_delta: 0,
2253 htlc_minimum_msat: 0,
2254 htlc_maximum_msat: OptionalField::Absent,
2256 fee_proportional_millionths: 0,
2257 excess_data: Vec::new()
2260 // If all the channels require some features we don't understand, route should fail
2261 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) {
2262 assert_eq!(err, "Failed to find a path to the given destination");
2263 } else { panic!(); }
2265 // If we specify a channel to node7, that overrides our local channel view and that gets used
2266 let our_chans = vec![get_channel_details(Some(42), nodes[7].clone(), InitFeatures::from_le_bytes(vec![0b11]), 250_000_000)];
2267 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();
2268 assert_eq!(route.paths[0].len(), 2);
2270 assert_eq!(route.paths[0][0].pubkey, nodes[7]);
2271 assert_eq!(route.paths[0][0].short_channel_id, 42);
2272 assert_eq!(route.paths[0][0].fee_msat, 200);
2273 assert_eq!(route.paths[0][0].cltv_expiry_delta, (13 << 8) | 1);
2274 assert_eq!(route.paths[0][0].node_features.le_flags(), &vec![0b11]); // it should also override our view of their features
2275 assert_eq!(route.paths[0][0].channel_features.le_flags(), &Vec::<u8>::new()); // No feature flags will meet the relevant-to-channel conversion
2277 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2278 assert_eq!(route.paths[0][1].short_channel_id, 13);
2279 assert_eq!(route.paths[0][1].fee_msat, 100);
2280 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
2281 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2282 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(13));
2286 fn disable_node_test() {
2287 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
2288 let (_, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
2289 let payee = Payee::new(nodes[2]);
2290 let scorer = Scorer::new(0);
2292 // Disable nodes 1, 2, and 8 by requiring unknown feature bits
2293 let unknown_features = NodeFeatures::known().set_unknown_feature_required();
2294 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[0], unknown_features.clone(), 1);
2295 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[1], unknown_features.clone(), 1);
2296 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[7], unknown_features.clone(), 1);
2298 // If all nodes require some features we don't understand, route should fail
2299 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) {
2300 assert_eq!(err, "Failed to find a path to the given destination");
2301 } else { panic!(); }
2303 // If we specify a channel to node7, that overrides our local channel view and that gets used
2304 let our_chans = vec![get_channel_details(Some(42), nodes[7].clone(), InitFeatures::from_le_bytes(vec![0b11]), 250_000_000)];
2305 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();
2306 assert_eq!(route.paths[0].len(), 2);
2308 assert_eq!(route.paths[0][0].pubkey, nodes[7]);
2309 assert_eq!(route.paths[0][0].short_channel_id, 42);
2310 assert_eq!(route.paths[0][0].fee_msat, 200);
2311 assert_eq!(route.paths[0][0].cltv_expiry_delta, (13 << 8) | 1);
2312 assert_eq!(route.paths[0][0].node_features.le_flags(), &vec![0b11]); // it should also override our view of their features
2313 assert_eq!(route.paths[0][0].channel_features.le_flags(), &Vec::<u8>::new()); // No feature flags will meet the relevant-to-channel conversion
2315 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2316 assert_eq!(route.paths[0][1].short_channel_id, 13);
2317 assert_eq!(route.paths[0][1].fee_msat, 100);
2318 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
2319 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2320 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(13));
2322 // Note that we don't test disabling node 3 and failing to route to it, as we (somewhat
2323 // naively) assume that the user checked the feature bits on the invoice, which override
2324 // the node_announcement.
2328 fn our_chans_test() {
2329 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
2330 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
2331 let scorer = Scorer::new(0);
2333 // Route to 1 via 2 and 3 because our channel to 1 is disabled
2334 let payee = Payee::new(nodes[0]);
2335 let route = get_route(&our_id, &payee, &net_graph_msg_handler.network_graph, None, 100, 42, Arc::clone(&logger), &scorer).unwrap();
2336 assert_eq!(route.paths[0].len(), 3);
2338 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
2339 assert_eq!(route.paths[0][0].short_channel_id, 2);
2340 assert_eq!(route.paths[0][0].fee_msat, 200);
2341 assert_eq!(route.paths[0][0].cltv_expiry_delta, (4 << 8) | 1);
2342 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
2343 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
2345 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2346 assert_eq!(route.paths[0][1].short_channel_id, 4);
2347 assert_eq!(route.paths[0][1].fee_msat, 100);
2348 assert_eq!(route.paths[0][1].cltv_expiry_delta, (3 << 8) | 2);
2349 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2350 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
2352 assert_eq!(route.paths[0][2].pubkey, nodes[0]);
2353 assert_eq!(route.paths[0][2].short_channel_id, 3);
2354 assert_eq!(route.paths[0][2].fee_msat, 100);
2355 assert_eq!(route.paths[0][2].cltv_expiry_delta, 42);
2356 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(1));
2357 assert_eq!(route.paths[0][2].channel_features.le_flags(), &id_to_feature_flags(3));
2359 // If we specify a channel to node7, that overrides our local channel view and that gets used
2360 let payee = Payee::new(nodes[2]);
2361 let our_chans = vec![get_channel_details(Some(42), nodes[7].clone(), InitFeatures::from_le_bytes(vec![0b11]), 250_000_000)];
2362 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();
2363 assert_eq!(route.paths[0].len(), 2);
2365 assert_eq!(route.paths[0][0].pubkey, nodes[7]);
2366 assert_eq!(route.paths[0][0].short_channel_id, 42);
2367 assert_eq!(route.paths[0][0].fee_msat, 200);
2368 assert_eq!(route.paths[0][0].cltv_expiry_delta, (13 << 8) | 1);
2369 assert_eq!(route.paths[0][0].node_features.le_flags(), &vec![0b11]);
2370 assert_eq!(route.paths[0][0].channel_features.le_flags(), &Vec::<u8>::new()); // No feature flags will meet the relevant-to-channel conversion
2372 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2373 assert_eq!(route.paths[0][1].short_channel_id, 13);
2374 assert_eq!(route.paths[0][1].fee_msat, 100);
2375 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
2376 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2377 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(13));
2380 fn last_hops(nodes: &Vec<PublicKey>) -> Vec<RouteHint> {
2381 let zero_fees = RoutingFees {
2383 proportional_millionths: 0,
2385 vec![RouteHint(vec![RouteHintHop {
2386 src_node_id: nodes[3],
2387 short_channel_id: 8,
2389 cltv_expiry_delta: (8 << 8) | 1,
2390 htlc_minimum_msat: None,
2391 htlc_maximum_msat: None,
2393 ]), RouteHint(vec![RouteHintHop {
2394 src_node_id: nodes[4],
2395 short_channel_id: 9,
2398 proportional_millionths: 0,
2400 cltv_expiry_delta: (9 << 8) | 1,
2401 htlc_minimum_msat: None,
2402 htlc_maximum_msat: None,
2403 }]), RouteHint(vec![RouteHintHop {
2404 src_node_id: nodes[5],
2405 short_channel_id: 10,
2407 cltv_expiry_delta: (10 << 8) | 1,
2408 htlc_minimum_msat: None,
2409 htlc_maximum_msat: None,
2413 fn last_hops_multi_private_channels(nodes: &Vec<PublicKey>) -> Vec<RouteHint> {
2414 let zero_fees = RoutingFees {
2416 proportional_millionths: 0,
2418 vec![RouteHint(vec![RouteHintHop {
2419 src_node_id: nodes[2],
2420 short_channel_id: 5,
2423 proportional_millionths: 0,
2425 cltv_expiry_delta: (5 << 8) | 1,
2426 htlc_minimum_msat: None,
2427 htlc_maximum_msat: None,
2429 src_node_id: nodes[3],
2430 short_channel_id: 8,
2432 cltv_expiry_delta: (8 << 8) | 1,
2433 htlc_minimum_msat: None,
2434 htlc_maximum_msat: None,
2436 ]), RouteHint(vec![RouteHintHop {
2437 src_node_id: nodes[4],
2438 short_channel_id: 9,
2441 proportional_millionths: 0,
2443 cltv_expiry_delta: (9 << 8) | 1,
2444 htlc_minimum_msat: None,
2445 htlc_maximum_msat: None,
2446 }]), RouteHint(vec![RouteHintHop {
2447 src_node_id: nodes[5],
2448 short_channel_id: 10,
2450 cltv_expiry_delta: (10 << 8) | 1,
2451 htlc_minimum_msat: None,
2452 htlc_maximum_msat: None,
2457 fn partial_route_hint_test() {
2458 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
2459 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
2460 let scorer = Scorer::new(0);
2462 // Simple test across 2, 3, 5, and 4 via a last_hop channel
2463 // Tests the behaviour when the RouteHint contains a suboptimal hop.
2464 // RouteHint may be partially used by the algo to build the best path.
2466 // First check that last hop can't have its source as the payee.
2467 let invalid_last_hop = RouteHint(vec![RouteHintHop {
2468 src_node_id: nodes[6],
2469 short_channel_id: 8,
2472 proportional_millionths: 0,
2474 cltv_expiry_delta: (8 << 8) | 1,
2475 htlc_minimum_msat: None,
2476 htlc_maximum_msat: None,
2479 let mut invalid_last_hops = last_hops_multi_private_channels(&nodes);
2480 invalid_last_hops.push(invalid_last_hop);
2482 let payee = Payee::new(nodes[6]).with_route_hints(invalid_last_hops);
2483 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) {
2484 assert_eq!(err, "Route hint cannot have the payee as the source.");
2485 } else { panic!(); }
2488 let payee = Payee::new(nodes[6]).with_route_hints(last_hops_multi_private_channels(&nodes));
2489 let route = get_route(&our_id, &payee, &net_graph_msg_handler.network_graph, None, 100, 42, Arc::clone(&logger), &scorer).unwrap();
2490 assert_eq!(route.paths[0].len(), 5);
2492 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
2493 assert_eq!(route.paths[0][0].short_channel_id, 2);
2494 assert_eq!(route.paths[0][0].fee_msat, 100);
2495 assert_eq!(route.paths[0][0].cltv_expiry_delta, (4 << 8) | 1);
2496 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
2497 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
2499 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2500 assert_eq!(route.paths[0][1].short_channel_id, 4);
2501 assert_eq!(route.paths[0][1].fee_msat, 0);
2502 assert_eq!(route.paths[0][1].cltv_expiry_delta, (6 << 8) | 1);
2503 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2504 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
2506 assert_eq!(route.paths[0][2].pubkey, nodes[4]);
2507 assert_eq!(route.paths[0][2].short_channel_id, 6);
2508 assert_eq!(route.paths[0][2].fee_msat, 0);
2509 assert_eq!(route.paths[0][2].cltv_expiry_delta, (11 << 8) | 1);
2510 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(5));
2511 assert_eq!(route.paths[0][2].channel_features.le_flags(), &id_to_feature_flags(6));
2513 assert_eq!(route.paths[0][3].pubkey, nodes[3]);
2514 assert_eq!(route.paths[0][3].short_channel_id, 11);
2515 assert_eq!(route.paths[0][3].fee_msat, 0);
2516 assert_eq!(route.paths[0][3].cltv_expiry_delta, (8 << 8) | 1);
2517 // If we have a peer in the node map, we'll use their features here since we don't have
2518 // a way of figuring out their features from the invoice:
2519 assert_eq!(route.paths[0][3].node_features.le_flags(), &id_to_feature_flags(4));
2520 assert_eq!(route.paths[0][3].channel_features.le_flags(), &id_to_feature_flags(11));
2522 assert_eq!(route.paths[0][4].pubkey, nodes[6]);
2523 assert_eq!(route.paths[0][4].short_channel_id, 8);
2524 assert_eq!(route.paths[0][4].fee_msat, 100);
2525 assert_eq!(route.paths[0][4].cltv_expiry_delta, 42);
2526 assert_eq!(route.paths[0][4].node_features.le_flags(), &Vec::<u8>::new()); // We dont pass flags in from invoices yet
2527 assert_eq!(route.paths[0][4].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
2530 fn empty_last_hop(nodes: &Vec<PublicKey>) -> Vec<RouteHint> {
2531 let zero_fees = RoutingFees {
2533 proportional_millionths: 0,
2535 vec![RouteHint(vec![RouteHintHop {
2536 src_node_id: nodes[3],
2537 short_channel_id: 8,
2539 cltv_expiry_delta: (8 << 8) | 1,
2540 htlc_minimum_msat: None,
2541 htlc_maximum_msat: None,
2542 }]), RouteHint(vec![
2544 ]), RouteHint(vec![RouteHintHop {
2545 src_node_id: nodes[5],
2546 short_channel_id: 10,
2548 cltv_expiry_delta: (10 << 8) | 1,
2549 htlc_minimum_msat: None,
2550 htlc_maximum_msat: None,
2555 fn ignores_empty_last_hops_test() {
2556 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
2557 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
2558 let payee = Payee::new(nodes[6]).with_route_hints(empty_last_hop(&nodes));
2559 let scorer = Scorer::new(0);
2561 // Test handling of an empty RouteHint passed in Invoice.
2563 let route = get_route(&our_id, &payee, &net_graph_msg_handler.network_graph, None, 100, 42, Arc::clone(&logger), &scorer).unwrap();
2564 assert_eq!(route.paths[0].len(), 5);
2566 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
2567 assert_eq!(route.paths[0][0].short_channel_id, 2);
2568 assert_eq!(route.paths[0][0].fee_msat, 100);
2569 assert_eq!(route.paths[0][0].cltv_expiry_delta, (4 << 8) | 1);
2570 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
2571 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
2573 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2574 assert_eq!(route.paths[0][1].short_channel_id, 4);
2575 assert_eq!(route.paths[0][1].fee_msat, 0);
2576 assert_eq!(route.paths[0][1].cltv_expiry_delta, (6 << 8) | 1);
2577 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2578 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
2580 assert_eq!(route.paths[0][2].pubkey, nodes[4]);
2581 assert_eq!(route.paths[0][2].short_channel_id, 6);
2582 assert_eq!(route.paths[0][2].fee_msat, 0);
2583 assert_eq!(route.paths[0][2].cltv_expiry_delta, (11 << 8) | 1);
2584 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(5));
2585 assert_eq!(route.paths[0][2].channel_features.le_flags(), &id_to_feature_flags(6));
2587 assert_eq!(route.paths[0][3].pubkey, nodes[3]);
2588 assert_eq!(route.paths[0][3].short_channel_id, 11);
2589 assert_eq!(route.paths[0][3].fee_msat, 0);
2590 assert_eq!(route.paths[0][3].cltv_expiry_delta, (8 << 8) | 1);
2591 // If we have a peer in the node map, we'll use their features here since we don't have
2592 // a way of figuring out their features from the invoice:
2593 assert_eq!(route.paths[0][3].node_features.le_flags(), &id_to_feature_flags(4));
2594 assert_eq!(route.paths[0][3].channel_features.le_flags(), &id_to_feature_flags(11));
2596 assert_eq!(route.paths[0][4].pubkey, nodes[6]);
2597 assert_eq!(route.paths[0][4].short_channel_id, 8);
2598 assert_eq!(route.paths[0][4].fee_msat, 100);
2599 assert_eq!(route.paths[0][4].cltv_expiry_delta, 42);
2600 assert_eq!(route.paths[0][4].node_features.le_flags(), &Vec::<u8>::new()); // We dont pass flags in from invoices yet
2601 assert_eq!(route.paths[0][4].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
2604 fn multi_hint_last_hops(nodes: &Vec<PublicKey>) -> Vec<RouteHint> {
2605 let zero_fees = RoutingFees {
2607 proportional_millionths: 0,
2609 vec![RouteHint(vec![RouteHintHop {
2610 src_node_id: nodes[2],
2611 short_channel_id: 5,
2614 proportional_millionths: 0,
2616 cltv_expiry_delta: (5 << 8) | 1,
2617 htlc_minimum_msat: None,
2618 htlc_maximum_msat: None,
2620 src_node_id: nodes[3],
2621 short_channel_id: 8,
2623 cltv_expiry_delta: (8 << 8) | 1,
2624 htlc_minimum_msat: None,
2625 htlc_maximum_msat: None,
2626 }]), RouteHint(vec![RouteHintHop {
2627 src_node_id: nodes[5],
2628 short_channel_id: 10,
2630 cltv_expiry_delta: (10 << 8) | 1,
2631 htlc_minimum_msat: None,
2632 htlc_maximum_msat: None,
2637 fn multi_hint_last_hops_test() {
2638 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
2639 let (_, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
2640 let payee = Payee::new(nodes[6]).with_route_hints(multi_hint_last_hops(&nodes));
2641 let scorer = Scorer::new(0);
2642 // Test through channels 2, 3, 5, 8.
2643 // Test shows that multiple hop hints are considered.
2645 // Disabling channels 6 & 7 by flags=2
2646 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
2647 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2648 short_channel_id: 6,
2650 flags: 2, // to disable
2651 cltv_expiry_delta: 0,
2652 htlc_minimum_msat: 0,
2653 htlc_maximum_msat: OptionalField::Absent,
2655 fee_proportional_millionths: 0,
2656 excess_data: Vec::new()
2658 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
2659 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2660 short_channel_id: 7,
2662 flags: 2, // to disable
2663 cltv_expiry_delta: 0,
2664 htlc_minimum_msat: 0,
2665 htlc_maximum_msat: OptionalField::Absent,
2667 fee_proportional_millionths: 0,
2668 excess_data: Vec::new()
2671 let route = get_route(&our_id, &payee, &net_graph_msg_handler.network_graph, None, 100, 42, Arc::clone(&logger), &scorer).unwrap();
2672 assert_eq!(route.paths[0].len(), 4);
2674 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
2675 assert_eq!(route.paths[0][0].short_channel_id, 2);
2676 assert_eq!(route.paths[0][0].fee_msat, 200);
2677 assert_eq!(route.paths[0][0].cltv_expiry_delta, 1025);
2678 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
2679 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
2681 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2682 assert_eq!(route.paths[0][1].short_channel_id, 4);
2683 assert_eq!(route.paths[0][1].fee_msat, 100);
2684 assert_eq!(route.paths[0][1].cltv_expiry_delta, 1281);
2685 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2686 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
2688 assert_eq!(route.paths[0][2].pubkey, nodes[3]);
2689 assert_eq!(route.paths[0][2].short_channel_id, 5);
2690 assert_eq!(route.paths[0][2].fee_msat, 0);
2691 assert_eq!(route.paths[0][2].cltv_expiry_delta, 2049);
2692 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(4));
2693 assert_eq!(route.paths[0][2].channel_features.le_flags(), &Vec::<u8>::new());
2695 assert_eq!(route.paths[0][3].pubkey, nodes[6]);
2696 assert_eq!(route.paths[0][3].short_channel_id, 8);
2697 assert_eq!(route.paths[0][3].fee_msat, 100);
2698 assert_eq!(route.paths[0][3].cltv_expiry_delta, 42);
2699 assert_eq!(route.paths[0][3].node_features.le_flags(), &Vec::<u8>::new()); // We dont pass flags in from invoices yet
2700 assert_eq!(route.paths[0][3].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
2703 fn last_hops_with_public_channel(nodes: &Vec<PublicKey>) -> Vec<RouteHint> {
2704 let zero_fees = RoutingFees {
2706 proportional_millionths: 0,
2708 vec![RouteHint(vec![RouteHintHop {
2709 src_node_id: nodes[4],
2710 short_channel_id: 11,
2712 cltv_expiry_delta: (11 << 8) | 1,
2713 htlc_minimum_msat: None,
2714 htlc_maximum_msat: None,
2716 src_node_id: nodes[3],
2717 short_channel_id: 8,
2719 cltv_expiry_delta: (8 << 8) | 1,
2720 htlc_minimum_msat: None,
2721 htlc_maximum_msat: None,
2722 }]), RouteHint(vec![RouteHintHop {
2723 src_node_id: nodes[4],
2724 short_channel_id: 9,
2727 proportional_millionths: 0,
2729 cltv_expiry_delta: (9 << 8) | 1,
2730 htlc_minimum_msat: None,
2731 htlc_maximum_msat: None,
2732 }]), RouteHint(vec![RouteHintHop {
2733 src_node_id: nodes[5],
2734 short_channel_id: 10,
2736 cltv_expiry_delta: (10 << 8) | 1,
2737 htlc_minimum_msat: None,
2738 htlc_maximum_msat: None,
2743 fn last_hops_with_public_channel_test() {
2744 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
2745 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
2746 let payee = Payee::new(nodes[6]).with_route_hints(last_hops_with_public_channel(&nodes));
2747 let scorer = Scorer::new(0);
2748 // This test shows that public routes can be present in the invoice
2749 // which would be handled in the same manner.
2751 let route = get_route(&our_id, &payee, &net_graph_msg_handler.network_graph, None, 100, 42, Arc::clone(&logger), &scorer).unwrap();
2752 assert_eq!(route.paths[0].len(), 5);
2754 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
2755 assert_eq!(route.paths[0][0].short_channel_id, 2);
2756 assert_eq!(route.paths[0][0].fee_msat, 100);
2757 assert_eq!(route.paths[0][0].cltv_expiry_delta, (4 << 8) | 1);
2758 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
2759 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
2761 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2762 assert_eq!(route.paths[0][1].short_channel_id, 4);
2763 assert_eq!(route.paths[0][1].fee_msat, 0);
2764 assert_eq!(route.paths[0][1].cltv_expiry_delta, (6 << 8) | 1);
2765 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2766 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
2768 assert_eq!(route.paths[0][2].pubkey, nodes[4]);
2769 assert_eq!(route.paths[0][2].short_channel_id, 6);
2770 assert_eq!(route.paths[0][2].fee_msat, 0);
2771 assert_eq!(route.paths[0][2].cltv_expiry_delta, (11 << 8) | 1);
2772 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(5));
2773 assert_eq!(route.paths[0][2].channel_features.le_flags(), &id_to_feature_flags(6));
2775 assert_eq!(route.paths[0][3].pubkey, nodes[3]);
2776 assert_eq!(route.paths[0][3].short_channel_id, 11);
2777 assert_eq!(route.paths[0][3].fee_msat, 0);
2778 assert_eq!(route.paths[0][3].cltv_expiry_delta, (8 << 8) | 1);
2779 // If we have a peer in the node map, we'll use their features here since we don't have
2780 // a way of figuring out their features from the invoice:
2781 assert_eq!(route.paths[0][3].node_features.le_flags(), &id_to_feature_flags(4));
2782 assert_eq!(route.paths[0][3].channel_features.le_flags(), &Vec::<u8>::new());
2784 assert_eq!(route.paths[0][4].pubkey, nodes[6]);
2785 assert_eq!(route.paths[0][4].short_channel_id, 8);
2786 assert_eq!(route.paths[0][4].fee_msat, 100);
2787 assert_eq!(route.paths[0][4].cltv_expiry_delta, 42);
2788 assert_eq!(route.paths[0][4].node_features.le_flags(), &Vec::<u8>::new()); // We dont pass flags in from invoices yet
2789 assert_eq!(route.paths[0][4].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
2793 fn our_chans_last_hop_connect_test() {
2794 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
2795 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
2796 let scorer = Scorer::new(0);
2798 // Simple test with outbound channel to 4 to test that last_hops and first_hops connect
2799 let our_chans = vec![get_channel_details(Some(42), nodes[3].clone(), InitFeatures::from_le_bytes(vec![0b11]), 250_000_000)];
2800 let mut last_hops = last_hops(&nodes);
2801 let payee = Payee::new(nodes[6]).with_route_hints(last_hops.clone());
2802 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();
2803 assert_eq!(route.paths[0].len(), 2);
2805 assert_eq!(route.paths[0][0].pubkey, nodes[3]);
2806 assert_eq!(route.paths[0][0].short_channel_id, 42);
2807 assert_eq!(route.paths[0][0].fee_msat, 0);
2808 assert_eq!(route.paths[0][0].cltv_expiry_delta, (8 << 8) | 1);
2809 assert_eq!(route.paths[0][0].node_features.le_flags(), &vec![0b11]);
2810 assert_eq!(route.paths[0][0].channel_features.le_flags(), &Vec::<u8>::new()); // No feature flags will meet the relevant-to-channel conversion
2812 assert_eq!(route.paths[0][1].pubkey, nodes[6]);
2813 assert_eq!(route.paths[0][1].short_channel_id, 8);
2814 assert_eq!(route.paths[0][1].fee_msat, 100);
2815 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
2816 assert_eq!(route.paths[0][1].node_features.le_flags(), &Vec::<u8>::new()); // We dont pass flags in from invoices yet
2817 assert_eq!(route.paths[0][1].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
2819 last_hops[0].0[0].fees.base_msat = 1000;
2821 // Revert to via 6 as the fee on 8 goes up
2822 let payee = Payee::new(nodes[6]).with_route_hints(last_hops);
2823 let route = get_route(&our_id, &payee, &net_graph_msg_handler.network_graph, None, 100, 42, Arc::clone(&logger), &scorer).unwrap();
2824 assert_eq!(route.paths[0].len(), 4);
2826 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
2827 assert_eq!(route.paths[0][0].short_channel_id, 2);
2828 assert_eq!(route.paths[0][0].fee_msat, 200); // fee increased as its % of value transferred across node
2829 assert_eq!(route.paths[0][0].cltv_expiry_delta, (4 << 8) | 1);
2830 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
2831 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
2833 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2834 assert_eq!(route.paths[0][1].short_channel_id, 4);
2835 assert_eq!(route.paths[0][1].fee_msat, 100);
2836 assert_eq!(route.paths[0][1].cltv_expiry_delta, (7 << 8) | 1);
2837 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2838 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
2840 assert_eq!(route.paths[0][2].pubkey, nodes[5]);
2841 assert_eq!(route.paths[0][2].short_channel_id, 7);
2842 assert_eq!(route.paths[0][2].fee_msat, 0);
2843 assert_eq!(route.paths[0][2].cltv_expiry_delta, (10 << 8) | 1);
2844 // If we have a peer in the node map, we'll use their features here since we don't have
2845 // a way of figuring out their features from the invoice:
2846 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(6));
2847 assert_eq!(route.paths[0][2].channel_features.le_flags(), &id_to_feature_flags(7));
2849 assert_eq!(route.paths[0][3].pubkey, nodes[6]);
2850 assert_eq!(route.paths[0][3].short_channel_id, 10);
2851 assert_eq!(route.paths[0][3].fee_msat, 100);
2852 assert_eq!(route.paths[0][3].cltv_expiry_delta, 42);
2853 assert_eq!(route.paths[0][3].node_features.le_flags(), &Vec::<u8>::new()); // We dont pass flags in from invoices yet
2854 assert_eq!(route.paths[0][3].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
2856 // ...but still use 8 for larger payments as 6 has a variable feerate
2857 let route = get_route(&our_id, &payee, &net_graph_msg_handler.network_graph, None, 2000, 42, Arc::clone(&logger), &scorer).unwrap();
2858 assert_eq!(route.paths[0].len(), 5);
2860 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
2861 assert_eq!(route.paths[0][0].short_channel_id, 2);
2862 assert_eq!(route.paths[0][0].fee_msat, 3000);
2863 assert_eq!(route.paths[0][0].cltv_expiry_delta, (4 << 8) | 1);
2864 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
2865 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
2867 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2868 assert_eq!(route.paths[0][1].short_channel_id, 4);
2869 assert_eq!(route.paths[0][1].fee_msat, 0);
2870 assert_eq!(route.paths[0][1].cltv_expiry_delta, (6 << 8) | 1);
2871 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2872 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
2874 assert_eq!(route.paths[0][2].pubkey, nodes[4]);
2875 assert_eq!(route.paths[0][2].short_channel_id, 6);
2876 assert_eq!(route.paths[0][2].fee_msat, 0);
2877 assert_eq!(route.paths[0][2].cltv_expiry_delta, (11 << 8) | 1);
2878 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(5));
2879 assert_eq!(route.paths[0][2].channel_features.le_flags(), &id_to_feature_flags(6));
2881 assert_eq!(route.paths[0][3].pubkey, nodes[3]);
2882 assert_eq!(route.paths[0][3].short_channel_id, 11);
2883 assert_eq!(route.paths[0][3].fee_msat, 1000);
2884 assert_eq!(route.paths[0][3].cltv_expiry_delta, (8 << 8) | 1);
2885 // If we have a peer in the node map, we'll use their features here since we don't have
2886 // a way of figuring out their features from the invoice:
2887 assert_eq!(route.paths[0][3].node_features.le_flags(), &id_to_feature_flags(4));
2888 assert_eq!(route.paths[0][3].channel_features.le_flags(), &id_to_feature_flags(11));
2890 assert_eq!(route.paths[0][4].pubkey, nodes[6]);
2891 assert_eq!(route.paths[0][4].short_channel_id, 8);
2892 assert_eq!(route.paths[0][4].fee_msat, 2000);
2893 assert_eq!(route.paths[0][4].cltv_expiry_delta, 42);
2894 assert_eq!(route.paths[0][4].node_features.le_flags(), &Vec::<u8>::new()); // We dont pass flags in from invoices yet
2895 assert_eq!(route.paths[0][4].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
2898 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> {
2899 let source_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&hex::decode(format!("{:02}", 41).repeat(32)).unwrap()[..]).unwrap());
2900 let middle_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&hex::decode(format!("{:02}", 42).repeat(32)).unwrap()[..]).unwrap());
2901 let target_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&hex::decode(format!("{:02}", 43).repeat(32)).unwrap()[..]).unwrap());
2903 // If we specify a channel to a middle hop, that overrides our local channel view and that gets used
2904 let last_hops = RouteHint(vec![RouteHintHop {
2905 src_node_id: middle_node_id,
2906 short_channel_id: 8,
2909 proportional_millionths: last_hop_fee_prop,
2911 cltv_expiry_delta: (8 << 8) | 1,
2912 htlc_minimum_msat: None,
2913 htlc_maximum_msat: last_hop_htlc_max,
2915 let payee = Payee::new(target_node_id).with_route_hints(vec![last_hops]);
2916 let our_chans = vec![get_channel_details(Some(42), middle_node_id, InitFeatures::from_le_bytes(vec![0b11]), outbound_capacity_msat)];
2917 let scorer = Scorer::new(0);
2918 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)
2922 fn unannounced_path_test() {
2923 // We should be able to send a payment to a destination without any help of a routing graph
2924 // if we have a channel with a common counterparty that appears in the first and last hop
2926 let route = do_unannounced_path_test(None, 1, 2000000, 1000000).unwrap();
2928 let middle_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&hex::decode(format!("{:02}", 42).repeat(32)).unwrap()[..]).unwrap());
2929 let target_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&hex::decode(format!("{:02}", 43).repeat(32)).unwrap()[..]).unwrap());
2930 assert_eq!(route.paths[0].len(), 2);
2932 assert_eq!(route.paths[0][0].pubkey, middle_node_id);
2933 assert_eq!(route.paths[0][0].short_channel_id, 42);
2934 assert_eq!(route.paths[0][0].fee_msat, 1001);
2935 assert_eq!(route.paths[0][0].cltv_expiry_delta, (8 << 8) | 1);
2936 assert_eq!(route.paths[0][0].node_features.le_flags(), &[0b11]);
2937 assert_eq!(route.paths[0][0].channel_features.le_flags(), &[0; 0]); // We can't learn any flags from invoices, sadly
2939 assert_eq!(route.paths[0][1].pubkey, target_node_id);
2940 assert_eq!(route.paths[0][1].short_channel_id, 8);
2941 assert_eq!(route.paths[0][1].fee_msat, 1000000);
2942 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
2943 assert_eq!(route.paths[0][1].node_features.le_flags(), &[0; 0]); // We dont pass flags in from invoices yet
2944 assert_eq!(route.paths[0][1].channel_features.le_flags(), &[0; 0]); // We can't learn any flags from invoices, sadly
2948 fn overflow_unannounced_path_test_liquidity_underflow() {
2949 // Previously, when we had a last-hop hint connected directly to a first-hop channel, where
2950 // the last-hop had a fee which overflowed a u64, we'd panic.
2951 // This was due to us adding the first-hop from us unconditionally, causing us to think
2952 // we'd built a path (as our node is in the "best candidate" set), when we had not.
2953 // In this test, we previously hit a subtraction underflow due to having less available
2954 // liquidity at the last hop than 0.
2955 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());
2959 fn overflow_unannounced_path_test_feerate_overflow() {
2960 // This tests for the same case as above, except instead of hitting a subtraction
2961 // underflow, we hit a case where the fee charged at a hop overflowed.
2962 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());
2966 fn available_amount_while_routing_test() {
2967 // Tests whether we choose the correct available channel amount while routing.
2969 let (secp_ctx, mut net_graph_msg_handler, chain_monitor, logger) = build_graph();
2970 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
2971 let scorer = Scorer::new(0);
2972 let payee = Payee::new(nodes[2]).with_features(InvoiceFeatures::known());
2974 // We will use a simple single-path route from
2975 // our node to node2 via node0: channels {1, 3}.
2977 // First disable all other paths.
2978 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2979 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2980 short_channel_id: 2,
2983 cltv_expiry_delta: 0,
2984 htlc_minimum_msat: 0,
2985 htlc_maximum_msat: OptionalField::Present(100_000),
2987 fee_proportional_millionths: 0,
2988 excess_data: Vec::new()
2990 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2991 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2992 short_channel_id: 12,
2995 cltv_expiry_delta: 0,
2996 htlc_minimum_msat: 0,
2997 htlc_maximum_msat: OptionalField::Present(100_000),
2999 fee_proportional_millionths: 0,
3000 excess_data: Vec::new()
3003 // Make the first channel (#1) very permissive,
3004 // and we will be testing all limits on the second channel.
3005 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3006 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3007 short_channel_id: 1,
3010 cltv_expiry_delta: 0,
3011 htlc_minimum_msat: 0,
3012 htlc_maximum_msat: OptionalField::Present(1_000_000_000),
3014 fee_proportional_millionths: 0,
3015 excess_data: Vec::new()
3018 // First, let's see if routing works if we have absolutely no idea about the available amount.
3019 // In this case, it should be set to 250_000 sats.
3020 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3021 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3022 short_channel_id: 3,
3025 cltv_expiry_delta: 0,
3026 htlc_minimum_msat: 0,
3027 htlc_maximum_msat: OptionalField::Absent,
3029 fee_proportional_millionths: 0,
3030 excess_data: Vec::new()
3034 // Attempt to route more than available results in a failure.
3035 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
3036 &our_id, &payee, &net_graph_msg_handler.network_graph, None, 250_000_001, 42, Arc::clone(&logger), &scorer) {
3037 assert_eq!(err, "Failed to find a sufficient route to the given destination");
3038 } else { panic!(); }
3042 // Now, attempt to route an exact amount we have should be fine.
3043 let route = get_route(&our_id, &payee, &net_graph_msg_handler.network_graph, None, 250_000_000, 42, Arc::clone(&logger), &scorer).unwrap();
3044 assert_eq!(route.paths.len(), 1);
3045 let path = route.paths.last().unwrap();
3046 assert_eq!(path.len(), 2);
3047 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
3048 assert_eq!(path.last().unwrap().fee_msat, 250_000_000);
3051 // Check that setting outbound_capacity_msat in first_hops limits the channels.
3052 // Disable channel #1 and use another first hop.
3053 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3054 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3055 short_channel_id: 1,
3058 cltv_expiry_delta: 0,
3059 htlc_minimum_msat: 0,
3060 htlc_maximum_msat: OptionalField::Present(1_000_000_000),
3062 fee_proportional_millionths: 0,
3063 excess_data: Vec::new()
3066 // Now, limit the first_hop by the outbound_capacity_msat of 200_000 sats.
3067 let our_chans = vec![get_channel_details(Some(42), nodes[0].clone(), InitFeatures::from_le_bytes(vec![0b11]), 200_000_000)];
3070 // Attempt to route more than available results in a failure.
3071 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
3072 &our_id, &payee, &net_graph_msg_handler.network_graph, Some(&our_chans.iter().collect::<Vec<_>>()), 200_000_001, 42, Arc::clone(&logger), &scorer) {
3073 assert_eq!(err, "Failed to find a sufficient route to the given destination");
3074 } else { panic!(); }
3078 // Now, attempt to route an exact amount we have should be fine.
3079 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();
3080 assert_eq!(route.paths.len(), 1);
3081 let path = route.paths.last().unwrap();
3082 assert_eq!(path.len(), 2);
3083 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
3084 assert_eq!(path.last().unwrap().fee_msat, 200_000_000);
3087 // Enable channel #1 back.
3088 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3089 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3090 short_channel_id: 1,
3093 cltv_expiry_delta: 0,
3094 htlc_minimum_msat: 0,
3095 htlc_maximum_msat: OptionalField::Present(1_000_000_000),
3097 fee_proportional_millionths: 0,
3098 excess_data: Vec::new()
3102 // Now let's see if routing works if we know only htlc_maximum_msat.
3103 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3104 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3105 short_channel_id: 3,
3108 cltv_expiry_delta: 0,
3109 htlc_minimum_msat: 0,
3110 htlc_maximum_msat: OptionalField::Present(15_000),
3112 fee_proportional_millionths: 0,
3113 excess_data: Vec::new()
3117 // Attempt to route more than available results in a failure.
3118 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
3119 &our_id, &payee, &net_graph_msg_handler.network_graph, None, 15_001, 42, Arc::clone(&logger), &scorer) {
3120 assert_eq!(err, "Failed to find a sufficient route to the given destination");
3121 } else { panic!(); }
3125 // Now, attempt to route an exact amount we have should be fine.
3126 let route = get_route(&our_id, &payee, &net_graph_msg_handler.network_graph, None, 15_000, 42, Arc::clone(&logger), &scorer).unwrap();
3127 assert_eq!(route.paths.len(), 1);
3128 let path = route.paths.last().unwrap();
3129 assert_eq!(path.len(), 2);
3130 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
3131 assert_eq!(path.last().unwrap().fee_msat, 15_000);
3134 // Now let's see if routing works if we know only capacity from the UTXO.
3136 // We can't change UTXO capacity on the fly, so we'll disable
3137 // the existing channel and add another one with the capacity we need.
3138 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3139 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3140 short_channel_id: 3,
3143 cltv_expiry_delta: 0,
3144 htlc_minimum_msat: 0,
3145 htlc_maximum_msat: OptionalField::Absent,
3147 fee_proportional_millionths: 0,
3148 excess_data: Vec::new()
3151 let good_script = Builder::new().push_opcode(opcodes::all::OP_PUSHNUM_2)
3152 .push_slice(&PublicKey::from_secret_key(&secp_ctx, &privkeys[0]).serialize())
3153 .push_slice(&PublicKey::from_secret_key(&secp_ctx, &privkeys[2]).serialize())
3154 .push_opcode(opcodes::all::OP_PUSHNUM_2)
3155 .push_opcode(opcodes::all::OP_CHECKMULTISIG).into_script().to_v0_p2wsh();
3157 *chain_monitor.utxo_ret.lock().unwrap() = Ok(TxOut { value: 15, script_pubkey: good_script.clone() });
3158 net_graph_msg_handler.add_chain_access(Some(chain_monitor));
3160 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], &privkeys[2], ChannelFeatures::from_le_bytes(id_to_feature_flags(3)), 333);
3161 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3162 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3163 short_channel_id: 333,
3166 cltv_expiry_delta: (3 << 8) | 1,
3167 htlc_minimum_msat: 0,
3168 htlc_maximum_msat: OptionalField::Absent,
3170 fee_proportional_millionths: 0,
3171 excess_data: Vec::new()
3173 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3174 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3175 short_channel_id: 333,
3178 cltv_expiry_delta: (3 << 8) | 2,
3179 htlc_minimum_msat: 0,
3180 htlc_maximum_msat: OptionalField::Absent,
3182 fee_proportional_millionths: 0,
3183 excess_data: Vec::new()
3187 // Attempt to route more than available results in a failure.
3188 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
3189 &our_id, &payee, &net_graph_msg_handler.network_graph, None, 15_001, 42, Arc::clone(&logger), &scorer) {
3190 assert_eq!(err, "Failed to find a sufficient route to the given destination");
3191 } else { panic!(); }
3195 // Now, attempt to route an exact amount we have should be fine.
3196 let route = get_route(&our_id, &payee, &net_graph_msg_handler.network_graph, None, 15_000, 42, Arc::clone(&logger), &scorer).unwrap();
3197 assert_eq!(route.paths.len(), 1);
3198 let path = route.paths.last().unwrap();
3199 assert_eq!(path.len(), 2);
3200 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
3201 assert_eq!(path.last().unwrap().fee_msat, 15_000);
3204 // Now let's see if routing chooses htlc_maximum_msat over UTXO capacity.
3205 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3206 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3207 short_channel_id: 333,
3210 cltv_expiry_delta: 0,
3211 htlc_minimum_msat: 0,
3212 htlc_maximum_msat: OptionalField::Present(10_000),
3214 fee_proportional_millionths: 0,
3215 excess_data: Vec::new()
3219 // Attempt to route more than available results in a failure.
3220 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
3221 &our_id, &payee, &net_graph_msg_handler.network_graph, None, 10_001, 42, Arc::clone(&logger), &scorer) {
3222 assert_eq!(err, "Failed to find a sufficient route to the given destination");
3223 } else { panic!(); }
3227 // Now, attempt to route an exact amount we have should be fine.
3228 let route = get_route(&our_id, &payee, &net_graph_msg_handler.network_graph, None, 10_000, 42, Arc::clone(&logger), &scorer).unwrap();
3229 assert_eq!(route.paths.len(), 1);
3230 let path = route.paths.last().unwrap();
3231 assert_eq!(path.len(), 2);
3232 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
3233 assert_eq!(path.last().unwrap().fee_msat, 10_000);
3238 fn available_liquidity_last_hop_test() {
3239 // Check that available liquidity properly limits the path even when only
3240 // one of the latter hops is limited.
3241 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
3242 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3243 let scorer = Scorer::new(0);
3244 let payee = Payee::new(nodes[3]).with_features(InvoiceFeatures::known());
3246 // Path via {node7, node2, node4} is channels {12, 13, 6, 11}.
3247 // {12, 13, 11} have the capacities of 100, {6} has a capacity of 50.
3248 // Total capacity: 50 sats.
3250 // Disable other potential paths.
3251 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3252 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3253 short_channel_id: 2,
3256 cltv_expiry_delta: 0,
3257 htlc_minimum_msat: 0,
3258 htlc_maximum_msat: OptionalField::Present(100_000),
3260 fee_proportional_millionths: 0,
3261 excess_data: Vec::new()
3263 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3264 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3265 short_channel_id: 7,
3268 cltv_expiry_delta: 0,
3269 htlc_minimum_msat: 0,
3270 htlc_maximum_msat: OptionalField::Present(100_000),
3272 fee_proportional_millionths: 0,
3273 excess_data: Vec::new()
3278 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3279 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3280 short_channel_id: 12,
3283 cltv_expiry_delta: 0,
3284 htlc_minimum_msat: 0,
3285 htlc_maximum_msat: OptionalField::Present(100_000),
3287 fee_proportional_millionths: 0,
3288 excess_data: Vec::new()
3290 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
3291 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3292 short_channel_id: 13,
3295 cltv_expiry_delta: 0,
3296 htlc_minimum_msat: 0,
3297 htlc_maximum_msat: OptionalField::Present(100_000),
3299 fee_proportional_millionths: 0,
3300 excess_data: Vec::new()
3303 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3304 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3305 short_channel_id: 6,
3308 cltv_expiry_delta: 0,
3309 htlc_minimum_msat: 0,
3310 htlc_maximum_msat: OptionalField::Present(50_000),
3312 fee_proportional_millionths: 0,
3313 excess_data: Vec::new()
3315 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
3316 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3317 short_channel_id: 11,
3320 cltv_expiry_delta: 0,
3321 htlc_minimum_msat: 0,
3322 htlc_maximum_msat: OptionalField::Present(100_000),
3324 fee_proportional_millionths: 0,
3325 excess_data: Vec::new()
3328 // Attempt to route more than available results in a failure.
3329 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
3330 &our_id, &payee, &net_graph_msg_handler.network_graph, None, 60_000, 42, Arc::clone(&logger), &scorer) {
3331 assert_eq!(err, "Failed to find a sufficient route to the given destination");
3332 } else { panic!(); }
3336 // Now, attempt to route 49 sats (just a bit below the capacity).
3337 let route = get_route(&our_id, &payee, &net_graph_msg_handler.network_graph, None, 49_000, 42, Arc::clone(&logger), &scorer).unwrap();
3338 assert_eq!(route.paths.len(), 1);
3339 let mut total_amount_paid_msat = 0;
3340 for path in &route.paths {
3341 assert_eq!(path.len(), 4);
3342 assert_eq!(path.last().unwrap().pubkey, nodes[3]);
3343 total_amount_paid_msat += path.last().unwrap().fee_msat;
3345 assert_eq!(total_amount_paid_msat, 49_000);
3349 // Attempt to route an exact amount is also fine
3350 let route = get_route(&our_id, &payee, &net_graph_msg_handler.network_graph, None, 50_000, 42, Arc::clone(&logger), &scorer).unwrap();
3351 assert_eq!(route.paths.len(), 1);
3352 let mut total_amount_paid_msat = 0;
3353 for path in &route.paths {
3354 assert_eq!(path.len(), 4);
3355 assert_eq!(path.last().unwrap().pubkey, nodes[3]);
3356 total_amount_paid_msat += path.last().unwrap().fee_msat;
3358 assert_eq!(total_amount_paid_msat, 50_000);
3363 fn ignore_fee_first_hop_test() {
3364 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
3365 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3366 let scorer = Scorer::new(0);
3367 let payee = Payee::new(nodes[2]);
3369 // Path via node0 is channels {1, 3}. Limit them to 100 and 50 sats (total limit 50).
3370 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3371 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3372 short_channel_id: 1,
3375 cltv_expiry_delta: 0,
3376 htlc_minimum_msat: 0,
3377 htlc_maximum_msat: OptionalField::Present(100_000),
3378 fee_base_msat: 1_000_000,
3379 fee_proportional_millionths: 0,
3380 excess_data: Vec::new()
3382 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3383 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3384 short_channel_id: 3,
3387 cltv_expiry_delta: 0,
3388 htlc_minimum_msat: 0,
3389 htlc_maximum_msat: OptionalField::Present(50_000),
3391 fee_proportional_millionths: 0,
3392 excess_data: Vec::new()
3396 let route = get_route(&our_id, &payee, &net_graph_msg_handler.network_graph, None, 50_000, 42, Arc::clone(&logger), &scorer).unwrap();
3397 assert_eq!(route.paths.len(), 1);
3398 let mut total_amount_paid_msat = 0;
3399 for path in &route.paths {
3400 assert_eq!(path.len(), 2);
3401 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
3402 total_amount_paid_msat += path.last().unwrap().fee_msat;
3404 assert_eq!(total_amount_paid_msat, 50_000);
3409 fn simple_mpp_route_test() {
3410 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
3411 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3412 let scorer = Scorer::new(0);
3413 let payee = Payee::new(nodes[2]).with_features(InvoiceFeatures::known());
3415 // We need a route consisting of 3 paths:
3416 // From our node to node2 via node0, node7, node1 (three paths one hop each).
3417 // To achieve this, the amount being transferred should be around
3418 // the total capacity of these 3 paths.
3420 // First, we set limits on these (previously unlimited) channels.
3421 // Their aggregate capacity will be 50 + 60 + 180 = 290 sats.
3423 // Path via node0 is channels {1, 3}. Limit them to 100 and 50 sats (total limit 50).
3424 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3425 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3426 short_channel_id: 1,
3429 cltv_expiry_delta: 0,
3430 htlc_minimum_msat: 0,
3431 htlc_maximum_msat: OptionalField::Present(100_000),
3433 fee_proportional_millionths: 0,
3434 excess_data: Vec::new()
3436 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3437 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3438 short_channel_id: 3,
3441 cltv_expiry_delta: 0,
3442 htlc_minimum_msat: 0,
3443 htlc_maximum_msat: OptionalField::Present(50_000),
3445 fee_proportional_millionths: 0,
3446 excess_data: Vec::new()
3449 // Path via node7 is channels {12, 13}. Limit them to 60 and 60 sats
3450 // (total limit 60).
3451 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3452 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3453 short_channel_id: 12,
3456 cltv_expiry_delta: 0,
3457 htlc_minimum_msat: 0,
3458 htlc_maximum_msat: OptionalField::Present(60_000),
3460 fee_proportional_millionths: 0,
3461 excess_data: Vec::new()
3463 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
3464 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3465 short_channel_id: 13,
3468 cltv_expiry_delta: 0,
3469 htlc_minimum_msat: 0,
3470 htlc_maximum_msat: OptionalField::Present(60_000),
3472 fee_proportional_millionths: 0,
3473 excess_data: Vec::new()
3476 // Path via node1 is channels {2, 4}. Limit them to 200 and 180 sats
3477 // (total capacity 180 sats).
3478 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3479 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3480 short_channel_id: 2,
3483 cltv_expiry_delta: 0,
3484 htlc_minimum_msat: 0,
3485 htlc_maximum_msat: OptionalField::Present(200_000),
3487 fee_proportional_millionths: 0,
3488 excess_data: Vec::new()
3490 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
3491 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3492 short_channel_id: 4,
3495 cltv_expiry_delta: 0,
3496 htlc_minimum_msat: 0,
3497 htlc_maximum_msat: OptionalField::Present(180_000),
3499 fee_proportional_millionths: 0,
3500 excess_data: Vec::new()
3504 // Attempt to route more than available results in a failure.
3505 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
3506 &our_id, &payee, &net_graph_msg_handler.network_graph, None, 300_000, 42, Arc::clone(&logger), &scorer) {
3507 assert_eq!(err, "Failed to find a sufficient route to the given destination");
3508 } else { panic!(); }
3512 // Now, attempt to route 250 sats (just a bit below the capacity).
3513 // Our algorithm should provide us with these 3 paths.
3514 let route = get_route(&our_id, &payee, &net_graph_msg_handler.network_graph, None, 250_000, 42, Arc::clone(&logger), &scorer).unwrap();
3515 assert_eq!(route.paths.len(), 3);
3516 let mut total_amount_paid_msat = 0;
3517 for path in &route.paths {
3518 assert_eq!(path.len(), 2);
3519 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
3520 total_amount_paid_msat += path.last().unwrap().fee_msat;
3522 assert_eq!(total_amount_paid_msat, 250_000);
3526 // Attempt to route an exact amount is also fine
3527 let route = get_route(&our_id, &payee, &net_graph_msg_handler.network_graph, None, 290_000, 42, Arc::clone(&logger), &scorer).unwrap();
3528 assert_eq!(route.paths.len(), 3);
3529 let mut total_amount_paid_msat = 0;
3530 for path in &route.paths {
3531 assert_eq!(path.len(), 2);
3532 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
3533 total_amount_paid_msat += path.last().unwrap().fee_msat;
3535 assert_eq!(total_amount_paid_msat, 290_000);
3540 fn long_mpp_route_test() {
3541 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
3542 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3543 let scorer = Scorer::new(0);
3544 let payee = Payee::new(nodes[3]).with_features(InvoiceFeatures::known());
3546 // We need a route consisting of 3 paths:
3547 // From our node to node3 via {node0, node2}, {node7, node2, node4} and {node7, node2}.
3548 // Note that these paths overlap (channels 5, 12, 13).
3549 // We will route 300 sats.
3550 // Each path will have 100 sats capacity, those channels which
3551 // are used twice will have 200 sats capacity.
3553 // Disable other potential paths.
3554 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3555 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3556 short_channel_id: 2,
3559 cltv_expiry_delta: 0,
3560 htlc_minimum_msat: 0,
3561 htlc_maximum_msat: OptionalField::Present(100_000),
3563 fee_proportional_millionths: 0,
3564 excess_data: Vec::new()
3566 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3567 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3568 short_channel_id: 7,
3571 cltv_expiry_delta: 0,
3572 htlc_minimum_msat: 0,
3573 htlc_maximum_msat: OptionalField::Present(100_000),
3575 fee_proportional_millionths: 0,
3576 excess_data: Vec::new()
3579 // Path via {node0, node2} is channels {1, 3, 5}.
3580 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3581 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3582 short_channel_id: 1,
3585 cltv_expiry_delta: 0,
3586 htlc_minimum_msat: 0,
3587 htlc_maximum_msat: OptionalField::Present(100_000),
3589 fee_proportional_millionths: 0,
3590 excess_data: Vec::new()
3592 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3593 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3594 short_channel_id: 3,
3597 cltv_expiry_delta: 0,
3598 htlc_minimum_msat: 0,
3599 htlc_maximum_msat: OptionalField::Present(100_000),
3601 fee_proportional_millionths: 0,
3602 excess_data: Vec::new()
3605 // Capacity of 200 sats because this channel will be used by 3rd path as well.
3606 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(5)), 5);
3607 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3608 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3609 short_channel_id: 5,
3612 cltv_expiry_delta: 0,
3613 htlc_minimum_msat: 0,
3614 htlc_maximum_msat: OptionalField::Present(200_000),
3616 fee_proportional_millionths: 0,
3617 excess_data: Vec::new()
3620 // Path via {node7, node2, node4} is channels {12, 13, 6, 11}.
3621 // Add 100 sats to the capacities of {12, 13}, because these channels
3622 // are also used for 3rd path. 100 sats for the rest. Total capacity: 100 sats.
3623 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3624 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3625 short_channel_id: 12,
3628 cltv_expiry_delta: 0,
3629 htlc_minimum_msat: 0,
3630 htlc_maximum_msat: OptionalField::Present(200_000),
3632 fee_proportional_millionths: 0,
3633 excess_data: Vec::new()
3635 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
3636 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3637 short_channel_id: 13,
3640 cltv_expiry_delta: 0,
3641 htlc_minimum_msat: 0,
3642 htlc_maximum_msat: OptionalField::Present(200_000),
3644 fee_proportional_millionths: 0,
3645 excess_data: Vec::new()
3648 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3649 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3650 short_channel_id: 6,
3653 cltv_expiry_delta: 0,
3654 htlc_minimum_msat: 0,
3655 htlc_maximum_msat: OptionalField::Present(100_000),
3657 fee_proportional_millionths: 0,
3658 excess_data: Vec::new()
3660 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
3661 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3662 short_channel_id: 11,
3665 cltv_expiry_delta: 0,
3666 htlc_minimum_msat: 0,
3667 htlc_maximum_msat: OptionalField::Present(100_000),
3669 fee_proportional_millionths: 0,
3670 excess_data: Vec::new()
3673 // Path via {node7, node2} is channels {12, 13, 5}.
3674 // We already limited them to 200 sats (they are used twice for 100 sats).
3675 // Nothing to do here.
3678 // Attempt to route more than available results in a failure.
3679 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
3680 &our_id, &payee, &net_graph_msg_handler.network_graph, None, 350_000, 42, Arc::clone(&logger), &scorer) {
3681 assert_eq!(err, "Failed to find a sufficient route to the given destination");
3682 } else { panic!(); }
3686 // Now, attempt to route 300 sats (exact amount we can route).
3687 // Our algorithm should provide us with these 3 paths, 100 sats each.
3688 let route = get_route(&our_id, &payee, &net_graph_msg_handler.network_graph, None, 300_000, 42, Arc::clone(&logger), &scorer).unwrap();
3689 assert_eq!(route.paths.len(), 3);
3691 let mut total_amount_paid_msat = 0;
3692 for path in &route.paths {
3693 assert_eq!(path.last().unwrap().pubkey, nodes[3]);
3694 total_amount_paid_msat += path.last().unwrap().fee_msat;
3696 assert_eq!(total_amount_paid_msat, 300_000);
3702 fn mpp_cheaper_route_test() {
3703 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
3704 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3705 let scorer = Scorer::new(0);
3706 let payee = Payee::new(nodes[3]).with_features(InvoiceFeatures::known());
3708 // This test checks that if we have two cheaper paths and one more expensive path,
3709 // so that liquidity-wise any 2 of 3 combination is sufficient,
3710 // two cheaper paths will be taken.
3711 // These paths have equal available liquidity.
3713 // We need a combination of 3 paths:
3714 // From our node to node3 via {node0, node2}, {node7, node2, node4} and {node7, node2}.
3715 // Note that these paths overlap (channels 5, 12, 13).
3716 // Each path will have 100 sats capacity, those channels which
3717 // are used twice will have 200 sats capacity.
3719 // Disable other potential paths.
3720 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3721 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3722 short_channel_id: 2,
3725 cltv_expiry_delta: 0,
3726 htlc_minimum_msat: 0,
3727 htlc_maximum_msat: OptionalField::Present(100_000),
3729 fee_proportional_millionths: 0,
3730 excess_data: Vec::new()
3732 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3733 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3734 short_channel_id: 7,
3737 cltv_expiry_delta: 0,
3738 htlc_minimum_msat: 0,
3739 htlc_maximum_msat: OptionalField::Present(100_000),
3741 fee_proportional_millionths: 0,
3742 excess_data: Vec::new()
3745 // Path via {node0, node2} is channels {1, 3, 5}.
3746 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3747 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3748 short_channel_id: 1,
3751 cltv_expiry_delta: 0,
3752 htlc_minimum_msat: 0,
3753 htlc_maximum_msat: OptionalField::Present(100_000),
3755 fee_proportional_millionths: 0,
3756 excess_data: Vec::new()
3758 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3759 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3760 short_channel_id: 3,
3763 cltv_expiry_delta: 0,
3764 htlc_minimum_msat: 0,
3765 htlc_maximum_msat: OptionalField::Present(100_000),
3767 fee_proportional_millionths: 0,
3768 excess_data: Vec::new()
3771 // Capacity of 200 sats because this channel will be used by 3rd path as well.
3772 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(5)), 5);
3773 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3774 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3775 short_channel_id: 5,
3778 cltv_expiry_delta: 0,
3779 htlc_minimum_msat: 0,
3780 htlc_maximum_msat: OptionalField::Present(200_000),
3782 fee_proportional_millionths: 0,
3783 excess_data: Vec::new()
3786 // Path via {node7, node2, node4} is channels {12, 13, 6, 11}.
3787 // Add 100 sats to the capacities of {12, 13}, because these channels
3788 // are also used for 3rd path. 100 sats for the rest. Total capacity: 100 sats.
3789 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3790 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3791 short_channel_id: 12,
3794 cltv_expiry_delta: 0,
3795 htlc_minimum_msat: 0,
3796 htlc_maximum_msat: OptionalField::Present(200_000),
3798 fee_proportional_millionths: 0,
3799 excess_data: Vec::new()
3801 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
3802 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3803 short_channel_id: 13,
3806 cltv_expiry_delta: 0,
3807 htlc_minimum_msat: 0,
3808 htlc_maximum_msat: OptionalField::Present(200_000),
3810 fee_proportional_millionths: 0,
3811 excess_data: Vec::new()
3814 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3815 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3816 short_channel_id: 6,
3819 cltv_expiry_delta: 0,
3820 htlc_minimum_msat: 0,
3821 htlc_maximum_msat: OptionalField::Present(100_000),
3822 fee_base_msat: 1_000,
3823 fee_proportional_millionths: 0,
3824 excess_data: Vec::new()
3826 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
3827 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3828 short_channel_id: 11,
3831 cltv_expiry_delta: 0,
3832 htlc_minimum_msat: 0,
3833 htlc_maximum_msat: OptionalField::Present(100_000),
3835 fee_proportional_millionths: 0,
3836 excess_data: Vec::new()
3839 // Path via {node7, node2} is channels {12, 13, 5}.
3840 // We already limited them to 200 sats (they are used twice for 100 sats).
3841 // Nothing to do here.
3844 // Now, attempt to route 180 sats.
3845 // Our algorithm should provide us with these 2 paths.
3846 let route = get_route(&our_id, &payee, &net_graph_msg_handler.network_graph, None, 180_000, 42, Arc::clone(&logger), &scorer).unwrap();
3847 assert_eq!(route.paths.len(), 2);
3849 let mut total_value_transferred_msat = 0;
3850 let mut total_paid_msat = 0;
3851 for path in &route.paths {
3852 assert_eq!(path.last().unwrap().pubkey, nodes[3]);
3853 total_value_transferred_msat += path.last().unwrap().fee_msat;
3855 total_paid_msat += hop.fee_msat;
3858 // If we paid fee, this would be higher.
3859 assert_eq!(total_value_transferred_msat, 180_000);
3860 let total_fees_paid = total_paid_msat - total_value_transferred_msat;
3861 assert_eq!(total_fees_paid, 0);
3866 fn fees_on_mpp_route_test() {
3867 // This test makes sure that MPP algorithm properly takes into account
3868 // fees charged on the channels, by making the fees impactful:
3869 // if the fee is not properly accounted for, the behavior is different.
3870 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
3871 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3872 let scorer = Scorer::new(0);
3873 let payee = Payee::new(nodes[3]).with_features(InvoiceFeatures::known());
3875 // We need a route consisting of 2 paths:
3876 // From our node to node3 via {node0, node2} and {node7, node2, node4}.
3877 // We will route 200 sats, Each path will have 100 sats capacity.
3879 // This test is not particularly stable: e.g.,
3880 // there's a way to route via {node0, node2, node4}.
3881 // It works while pathfinding is deterministic, but can be broken otherwise.
3882 // It's fine to ignore this concern for now.
3884 // Disable other potential paths.
3885 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3886 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3887 short_channel_id: 2,
3890 cltv_expiry_delta: 0,
3891 htlc_minimum_msat: 0,
3892 htlc_maximum_msat: OptionalField::Present(100_000),
3894 fee_proportional_millionths: 0,
3895 excess_data: Vec::new()
3898 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3899 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3900 short_channel_id: 7,
3903 cltv_expiry_delta: 0,
3904 htlc_minimum_msat: 0,
3905 htlc_maximum_msat: OptionalField::Present(100_000),
3907 fee_proportional_millionths: 0,
3908 excess_data: Vec::new()
3911 // Path via {node0, node2} is channels {1, 3, 5}.
3912 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3913 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3914 short_channel_id: 1,
3917 cltv_expiry_delta: 0,
3918 htlc_minimum_msat: 0,
3919 htlc_maximum_msat: OptionalField::Present(100_000),
3921 fee_proportional_millionths: 0,
3922 excess_data: Vec::new()
3924 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3925 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3926 short_channel_id: 3,
3929 cltv_expiry_delta: 0,
3930 htlc_minimum_msat: 0,
3931 htlc_maximum_msat: OptionalField::Present(100_000),
3933 fee_proportional_millionths: 0,
3934 excess_data: Vec::new()
3937 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(5)), 5);
3938 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3939 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3940 short_channel_id: 5,
3943 cltv_expiry_delta: 0,
3944 htlc_minimum_msat: 0,
3945 htlc_maximum_msat: OptionalField::Present(100_000),
3947 fee_proportional_millionths: 0,
3948 excess_data: Vec::new()
3951 // Path via {node7, node2, node4} is channels {12, 13, 6, 11}.
3952 // All channels should be 100 sats capacity. But for the fee experiment,
3953 // we'll add absolute fee of 150 sats paid for the use channel 6 (paid to node2 on channel 13).
3954 // Since channel 12 allows to deliver only 250 sats to channel 13, channel 13 can transfer only
3955 // 100 sats (and pay 150 sats in fees for the use of channel 6),
3956 // so no matter how large are other channels,
3957 // the whole path will be limited by 100 sats with just these 2 conditions:
3958 // - channel 12 capacity is 250 sats
3959 // - fee for channel 6 is 150 sats
3960 // Let's test this by enforcing these 2 conditions and removing other limits.
3961 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3962 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3963 short_channel_id: 12,
3966 cltv_expiry_delta: 0,
3967 htlc_minimum_msat: 0,
3968 htlc_maximum_msat: OptionalField::Present(250_000),
3970 fee_proportional_millionths: 0,
3971 excess_data: Vec::new()
3973 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
3974 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3975 short_channel_id: 13,
3978 cltv_expiry_delta: 0,
3979 htlc_minimum_msat: 0,
3980 htlc_maximum_msat: OptionalField::Absent,
3982 fee_proportional_millionths: 0,
3983 excess_data: Vec::new()
3986 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3987 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3988 short_channel_id: 6,
3991 cltv_expiry_delta: 0,
3992 htlc_minimum_msat: 0,
3993 htlc_maximum_msat: OptionalField::Absent,
3994 fee_base_msat: 150_000,
3995 fee_proportional_millionths: 0,
3996 excess_data: Vec::new()
3998 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
3999 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4000 short_channel_id: 11,
4003 cltv_expiry_delta: 0,
4004 htlc_minimum_msat: 0,
4005 htlc_maximum_msat: OptionalField::Absent,
4007 fee_proportional_millionths: 0,
4008 excess_data: Vec::new()
4012 // Attempt to route more than available results in a failure.
4013 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
4014 &our_id, &payee, &net_graph_msg_handler.network_graph, None, 210_000, 42, Arc::clone(&logger), &scorer) {
4015 assert_eq!(err, "Failed to find a sufficient route to the given destination");
4016 } else { panic!(); }
4020 // Now, attempt to route 200 sats (exact amount we can route).
4021 let route = get_route(&our_id, &payee, &net_graph_msg_handler.network_graph, None, 200_000, 42, Arc::clone(&logger), &scorer).unwrap();
4022 assert_eq!(route.paths.len(), 2);
4024 let mut total_amount_paid_msat = 0;
4025 for path in &route.paths {
4026 assert_eq!(path.last().unwrap().pubkey, nodes[3]);
4027 total_amount_paid_msat += path.last().unwrap().fee_msat;
4029 assert_eq!(total_amount_paid_msat, 200_000);
4030 assert_eq!(route.get_total_fees(), 150_000);
4036 fn drop_lowest_channel_mpp_route_test() {
4037 // This test checks that low-capacity channel is dropped when after
4038 // path finding we realize that we found more capacity than we need.
4039 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
4040 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
4041 let scorer = Scorer::new(0);
4042 let payee = Payee::new(nodes[2]).with_features(InvoiceFeatures::known());
4044 // We need a route consisting of 3 paths:
4045 // From our node to node2 via node0, node7, node1 (three paths one hop each).
4047 // The first and the second paths should be sufficient, but the third should be
4048 // cheaper, so that we select it but drop later.
4050 // First, we set limits on these (previously unlimited) channels.
4051 // Their aggregate capacity will be 50 + 60 + 20 = 130 sats.
4053 // Path via node0 is channels {1, 3}. Limit them to 100 and 50 sats (total limit 50);
4054 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4055 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4056 short_channel_id: 1,
4059 cltv_expiry_delta: 0,
4060 htlc_minimum_msat: 0,
4061 htlc_maximum_msat: OptionalField::Present(100_000),
4063 fee_proportional_millionths: 0,
4064 excess_data: Vec::new()
4066 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
4067 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4068 short_channel_id: 3,
4071 cltv_expiry_delta: 0,
4072 htlc_minimum_msat: 0,
4073 htlc_maximum_msat: OptionalField::Present(50_000),
4075 fee_proportional_millionths: 0,
4076 excess_data: Vec::new()
4079 // Path via node7 is channels {12, 13}. Limit them to 60 and 60 sats (total limit 60);
4080 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4081 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4082 short_channel_id: 12,
4085 cltv_expiry_delta: 0,
4086 htlc_minimum_msat: 0,
4087 htlc_maximum_msat: OptionalField::Present(60_000),
4089 fee_proportional_millionths: 0,
4090 excess_data: Vec::new()
4092 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
4093 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4094 short_channel_id: 13,
4097 cltv_expiry_delta: 0,
4098 htlc_minimum_msat: 0,
4099 htlc_maximum_msat: OptionalField::Present(60_000),
4101 fee_proportional_millionths: 0,
4102 excess_data: Vec::new()
4105 // Path via node1 is channels {2, 4}. Limit them to 20 and 20 sats (total capacity 20 sats).
4106 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4107 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4108 short_channel_id: 2,
4111 cltv_expiry_delta: 0,
4112 htlc_minimum_msat: 0,
4113 htlc_maximum_msat: OptionalField::Present(20_000),
4115 fee_proportional_millionths: 0,
4116 excess_data: Vec::new()
4118 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
4119 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4120 short_channel_id: 4,
4123 cltv_expiry_delta: 0,
4124 htlc_minimum_msat: 0,
4125 htlc_maximum_msat: OptionalField::Present(20_000),
4127 fee_proportional_millionths: 0,
4128 excess_data: Vec::new()
4132 // Attempt to route more than available results in a failure.
4133 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
4134 &our_id, &payee, &net_graph_msg_handler.network_graph, None, 150_000, 42, Arc::clone(&logger), &scorer) {
4135 assert_eq!(err, "Failed to find a sufficient route to the given destination");
4136 } else { panic!(); }
4140 // Now, attempt to route 125 sats (just a bit below the capacity of 3 channels).
4141 // Our algorithm should provide us with these 3 paths.
4142 let route = get_route(&our_id, &payee, &net_graph_msg_handler.network_graph, None, 125_000, 42, Arc::clone(&logger), &scorer).unwrap();
4143 assert_eq!(route.paths.len(), 3);
4144 let mut total_amount_paid_msat = 0;
4145 for path in &route.paths {
4146 assert_eq!(path.len(), 2);
4147 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
4148 total_amount_paid_msat += path.last().unwrap().fee_msat;
4150 assert_eq!(total_amount_paid_msat, 125_000);
4154 // Attempt to route without the last small cheap channel
4155 let route = get_route(&our_id, &payee, &net_graph_msg_handler.network_graph, None, 90_000, 42, Arc::clone(&logger), &scorer).unwrap();
4156 assert_eq!(route.paths.len(), 2);
4157 let mut total_amount_paid_msat = 0;
4158 for path in &route.paths {
4159 assert_eq!(path.len(), 2);
4160 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
4161 total_amount_paid_msat += path.last().unwrap().fee_msat;
4163 assert_eq!(total_amount_paid_msat, 90_000);
4168 fn min_criteria_consistency() {
4169 // Test that we don't use an inconsistent metric between updating and walking nodes during
4170 // our Dijkstra's pass. In the initial version of MPP, the "best source" for a given node
4171 // was updated with a different criterion from the heap sorting, resulting in loops in
4172 // calculated paths. We test for that specific case here.
4174 // We construct a network that looks like this:
4176 // node2 -1(3)2- node3
4180 // node1 -1(5)2- node4 -1(1)2- node6
4186 // We create a loop on the side of our real path - our destination is node 6, with a
4187 // previous hop of node 4. From 4, the cheapest previous path is channel 2 from node 2,
4188 // followed by node 3 over channel 3. Thereafter, the cheapest next-hop is back to node 4
4189 // (this time over channel 4). Channel 4 has 0 htlc_minimum_msat whereas channel 1 (the
4190 // other channel with a previous-hop of node 4) has a high (but irrelevant to the overall
4191 // payment) htlc_minimum_msat. In the original algorithm, this resulted in node4's
4192 // "previous hop" being set to node 3, creating a loop in the path.
4193 let secp_ctx = Secp256k1::new();
4194 let logger = Arc::new(test_utils::TestLogger::new());
4195 let network_graph = NetworkGraph::new(genesis_block(Network::Testnet).header.block_hash());
4196 let net_graph_msg_handler = NetGraphMsgHandler::new(network_graph, None, Arc::clone(&logger));
4197 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
4198 let scorer = Scorer::new(0);
4199 let payee = Payee::new(nodes[6]);
4201 add_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, &privkeys[1], ChannelFeatures::from_le_bytes(id_to_feature_flags(6)), 6);
4202 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4203 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4204 short_channel_id: 6,
4207 cltv_expiry_delta: (6 << 8) | 0,
4208 htlc_minimum_msat: 0,
4209 htlc_maximum_msat: OptionalField::Absent,
4211 fee_proportional_millionths: 0,
4212 excess_data: Vec::new()
4214 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[1], NodeFeatures::from_le_bytes(id_to_feature_flags(1)), 0);
4216 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], &privkeys[4], ChannelFeatures::from_le_bytes(id_to_feature_flags(5)), 5);
4217 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
4218 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4219 short_channel_id: 5,
4222 cltv_expiry_delta: (5 << 8) | 0,
4223 htlc_minimum_msat: 0,
4224 htlc_maximum_msat: OptionalField::Absent,
4226 fee_proportional_millionths: 0,
4227 excess_data: Vec::new()
4229 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[4], NodeFeatures::from_le_bytes(id_to_feature_flags(4)), 0);
4231 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(4)), 4);
4232 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
4233 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4234 short_channel_id: 4,
4237 cltv_expiry_delta: (4 << 8) | 0,
4238 htlc_minimum_msat: 0,
4239 htlc_maximum_msat: OptionalField::Absent,
4241 fee_proportional_millionths: 0,
4242 excess_data: Vec::new()
4244 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[3], NodeFeatures::from_le_bytes(id_to_feature_flags(3)), 0);
4246 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[3], &privkeys[2], ChannelFeatures::from_le_bytes(id_to_feature_flags(3)), 3);
4247 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[3], UnsignedChannelUpdate {
4248 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4249 short_channel_id: 3,
4252 cltv_expiry_delta: (3 << 8) | 0,
4253 htlc_minimum_msat: 0,
4254 htlc_maximum_msat: OptionalField::Absent,
4256 fee_proportional_millionths: 0,
4257 excess_data: Vec::new()
4259 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[2], NodeFeatures::from_le_bytes(id_to_feature_flags(2)), 0);
4261 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], &privkeys[4], ChannelFeatures::from_le_bytes(id_to_feature_flags(2)), 2);
4262 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4263 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4264 short_channel_id: 2,
4267 cltv_expiry_delta: (2 << 8) | 0,
4268 htlc_minimum_msat: 0,
4269 htlc_maximum_msat: OptionalField::Absent,
4271 fee_proportional_millionths: 0,
4272 excess_data: Vec::new()
4275 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], &privkeys[6], ChannelFeatures::from_le_bytes(id_to_feature_flags(1)), 1);
4276 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
4277 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4278 short_channel_id: 1,
4281 cltv_expiry_delta: (1 << 8) | 0,
4282 htlc_minimum_msat: 100,
4283 htlc_maximum_msat: OptionalField::Absent,
4285 fee_proportional_millionths: 0,
4286 excess_data: Vec::new()
4288 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[6], NodeFeatures::from_le_bytes(id_to_feature_flags(6)), 0);
4291 // Now ensure the route flows simply over nodes 1 and 4 to 6.
4292 let route = get_route(&our_id, &payee, &net_graph_msg_handler.network_graph, None, 10_000, 42, Arc::clone(&logger), &scorer).unwrap();
4293 assert_eq!(route.paths.len(), 1);
4294 assert_eq!(route.paths[0].len(), 3);
4296 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
4297 assert_eq!(route.paths[0][0].short_channel_id, 6);
4298 assert_eq!(route.paths[0][0].fee_msat, 100);
4299 assert_eq!(route.paths[0][0].cltv_expiry_delta, (5 << 8) | 0);
4300 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(1));
4301 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(6));
4303 assert_eq!(route.paths[0][1].pubkey, nodes[4]);
4304 assert_eq!(route.paths[0][1].short_channel_id, 5);
4305 assert_eq!(route.paths[0][1].fee_msat, 0);
4306 assert_eq!(route.paths[0][1].cltv_expiry_delta, (1 << 8) | 0);
4307 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(4));
4308 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(5));
4310 assert_eq!(route.paths[0][2].pubkey, nodes[6]);
4311 assert_eq!(route.paths[0][2].short_channel_id, 1);
4312 assert_eq!(route.paths[0][2].fee_msat, 10_000);
4313 assert_eq!(route.paths[0][2].cltv_expiry_delta, 42);
4314 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(6));
4315 assert_eq!(route.paths[0][2].channel_features.le_flags(), &id_to_feature_flags(1));
4321 fn exact_fee_liquidity_limit() {
4322 // Test that if, while walking the graph, we find a hop that has exactly enough liquidity
4323 // for us, including later hop fees, we take it. In the first version of our MPP algorithm
4324 // we calculated fees on a higher value, resulting in us ignoring such paths.
4325 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
4326 let (our_privkey, our_id, _, nodes) = get_nodes(&secp_ctx);
4327 let scorer = Scorer::new(0);
4328 let payee = Payee::new(nodes[2]);
4330 // We modify the graph to set the htlc_maximum of channel 2 to below the value we wish to
4332 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4333 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4334 short_channel_id: 2,
4337 cltv_expiry_delta: 0,
4338 htlc_minimum_msat: 0,
4339 htlc_maximum_msat: OptionalField::Present(85_000),
4341 fee_proportional_millionths: 0,
4342 excess_data: Vec::new()
4345 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4346 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4347 short_channel_id: 12,
4350 cltv_expiry_delta: (4 << 8) | 1,
4351 htlc_minimum_msat: 0,
4352 htlc_maximum_msat: OptionalField::Present(270_000),
4354 fee_proportional_millionths: 1000000,
4355 excess_data: Vec::new()
4359 // Now, attempt to route 90 sats, which is exactly 90 sats at the last hop, plus the
4360 // 200% fee charged channel 13 in the 1-to-2 direction.
4361 let route = get_route(&our_id, &payee, &net_graph_msg_handler.network_graph, None, 90_000, 42, Arc::clone(&logger), &scorer).unwrap();
4362 assert_eq!(route.paths.len(), 1);
4363 assert_eq!(route.paths[0].len(), 2);
4365 assert_eq!(route.paths[0][0].pubkey, nodes[7]);
4366 assert_eq!(route.paths[0][0].short_channel_id, 12);
4367 assert_eq!(route.paths[0][0].fee_msat, 90_000*2);
4368 assert_eq!(route.paths[0][0].cltv_expiry_delta, (13 << 8) | 1);
4369 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(8));
4370 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(12));
4372 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
4373 assert_eq!(route.paths[0][1].short_channel_id, 13);
4374 assert_eq!(route.paths[0][1].fee_msat, 90_000);
4375 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
4376 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
4377 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(13));
4382 fn htlc_max_reduction_below_min() {
4383 // Test that if, while walking the graph, we reduce the value being sent to meet an
4384 // htlc_maximum_msat, we don't end up undershooting a later htlc_minimum_msat. In the
4385 // initial version of MPP we'd accept such routes but reject them while recalculating fees,
4386 // resulting in us thinking there is no possible path, even if other paths exist.
4387 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
4388 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
4389 let scorer = Scorer::new(0);
4390 let payee = Payee::new(nodes[2]).with_features(InvoiceFeatures::known());
4392 // We modify the graph to set the htlc_minimum of channel 2 and 4 as needed - channel 2
4393 // gets an htlc_maximum_msat of 80_000 and channel 4 an htlc_minimum_msat of 90_000. We
4394 // then try to send 90_000.
4395 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4396 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4397 short_channel_id: 2,
4400 cltv_expiry_delta: 0,
4401 htlc_minimum_msat: 0,
4402 htlc_maximum_msat: OptionalField::Present(80_000),
4404 fee_proportional_millionths: 0,
4405 excess_data: Vec::new()
4407 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
4408 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4409 short_channel_id: 4,
4412 cltv_expiry_delta: (4 << 8) | 1,
4413 htlc_minimum_msat: 90_000,
4414 htlc_maximum_msat: OptionalField::Absent,
4416 fee_proportional_millionths: 0,
4417 excess_data: Vec::new()
4421 // Now, attempt to route 90 sats, hitting the htlc_minimum on channel 4, but
4422 // overshooting the htlc_maximum on channel 2. Thus, we should pick the (absurdly
4423 // expensive) channels 12-13 path.
4424 let route = get_route(&our_id, &payee, &net_graph_msg_handler.network_graph, None, 90_000, 42, Arc::clone(&logger), &scorer).unwrap();
4425 assert_eq!(route.paths.len(), 1);
4426 assert_eq!(route.paths[0].len(), 2);
4428 assert_eq!(route.paths[0][0].pubkey, nodes[7]);
4429 assert_eq!(route.paths[0][0].short_channel_id, 12);
4430 assert_eq!(route.paths[0][0].fee_msat, 90_000*2);
4431 assert_eq!(route.paths[0][0].cltv_expiry_delta, (13 << 8) | 1);
4432 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(8));
4433 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(12));
4435 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
4436 assert_eq!(route.paths[0][1].short_channel_id, 13);
4437 assert_eq!(route.paths[0][1].fee_msat, 90_000);
4438 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
4439 assert_eq!(route.paths[0][1].node_features.le_flags(), InvoiceFeatures::known().le_flags());
4440 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(13));
4445 fn multiple_direct_first_hops() {
4446 // Previously we'd only ever considered one first hop path per counterparty.
4447 // However, as we don't restrict users to one channel per peer, we really need to support
4448 // looking at all first hop paths.
4449 // Here we test that we do not ignore all-but-the-last first hop paths per counterparty (as
4450 // we used to do by overwriting the `first_hop_targets` hashmap entry) and that we can MPP
4451 // route over multiple channels with the same first hop.
4452 let secp_ctx = Secp256k1::new();
4453 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
4454 let logger = Arc::new(test_utils::TestLogger::new());
4455 let network_graph = NetworkGraph::new(genesis_block(Network::Testnet).header.block_hash());
4456 let scorer = Scorer::new(0);
4457 let payee = Payee::new(nodes[0]).with_features(InvoiceFeatures::known());
4460 let route = get_route(&our_id, &payee, &network_graph, Some(&[
4461 &get_channel_details(Some(3), nodes[0], InitFeatures::known(), 200_000),
4462 &get_channel_details(Some(2), nodes[0], InitFeatures::known(), 10_000),
4463 ]), 100_000, 42, Arc::clone(&logger), &scorer).unwrap();
4464 assert_eq!(route.paths.len(), 1);
4465 assert_eq!(route.paths[0].len(), 1);
4467 assert_eq!(route.paths[0][0].pubkey, nodes[0]);
4468 assert_eq!(route.paths[0][0].short_channel_id, 3);
4469 assert_eq!(route.paths[0][0].fee_msat, 100_000);
4472 let route = get_route(&our_id, &payee, &network_graph, Some(&[
4473 &get_channel_details(Some(3), nodes[0], InitFeatures::known(), 50_000),
4474 &get_channel_details(Some(2), nodes[0], InitFeatures::known(), 50_000),
4475 ]), 100_000, 42, Arc::clone(&logger), &scorer).unwrap();
4476 assert_eq!(route.paths.len(), 2);
4477 assert_eq!(route.paths[0].len(), 1);
4478 assert_eq!(route.paths[1].len(), 1);
4480 assert_eq!(route.paths[0][0].pubkey, nodes[0]);
4481 assert_eq!(route.paths[0][0].short_channel_id, 3);
4482 assert_eq!(route.paths[0][0].fee_msat, 50_000);
4484 assert_eq!(route.paths[1][0].pubkey, nodes[0]);
4485 assert_eq!(route.paths[1][0].short_channel_id, 2);
4486 assert_eq!(route.paths[1][0].fee_msat, 50_000);
4491 fn prefers_shorter_route_with_higher_fees() {
4492 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
4493 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
4494 let payee = Payee::new(nodes[6]).with_route_hints(last_hops(&nodes));
4496 // Without penalizing each hop 100 msats, a longer path with lower fees is chosen.
4497 let scorer = Scorer::new(0);
4498 let route = get_route(
4499 &our_id, &payee, &net_graph_msg_handler.network_graph, None, 100, 42,
4500 Arc::clone(&logger), &scorer
4502 let path = route.paths[0].iter().map(|hop| hop.short_channel_id).collect::<Vec<_>>();
4504 assert_eq!(route.get_total_fees(), 100);
4505 assert_eq!(route.get_total_amount(), 100);
4506 assert_eq!(path, vec![2, 4, 6, 11, 8]);
4508 // Applying a 100 msat penalty to each hop results in taking channels 7 and 10 to nodes[6]
4509 // from nodes[2] rather than channel 6, 11, and 8, even though the longer path is cheaper.
4510 let scorer = Scorer::new(100);
4511 let route = get_route(
4512 &our_id, &payee, &net_graph_msg_handler.network_graph, None, 100, 42,
4513 Arc::clone(&logger), &scorer
4515 let path = route.paths[0].iter().map(|hop| hop.short_channel_id).collect::<Vec<_>>();
4517 assert_eq!(route.get_total_fees(), 300);
4518 assert_eq!(route.get_total_amount(), 100);
4519 assert_eq!(path, vec![2, 4, 7, 10]);
4522 struct BadChannelScorer {
4523 short_channel_id: u64,
4526 impl routing::Score for BadChannelScorer {
4527 fn channel_penalty_msat(&self, short_channel_id: u64, _source: &NodeId, _target: &NodeId) -> u64 {
4528 if short_channel_id == self.short_channel_id { u64::max_value() } else { 0 }
4532 struct BadNodeScorer {
4536 impl routing::Score for BadNodeScorer {
4537 fn channel_penalty_msat(&self, _short_channel_id: u64, _source: &NodeId, target: &NodeId) -> u64 {
4538 if *target == self.node_id { u64::max_value() } else { 0 }
4543 fn avoids_routing_through_bad_channels_and_nodes() {
4544 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
4545 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
4546 let payee = Payee::new(nodes[6]).with_route_hints(last_hops(&nodes));
4548 // A path to nodes[6] exists when no penalties are applied to any channel.
4549 let scorer = Scorer::new(0);
4550 let route = get_route(
4551 &our_id, &payee, &net_graph_msg_handler.network_graph, None, 100, 42,
4552 Arc::clone(&logger), &scorer
4554 let path = route.paths[0].iter().map(|hop| hop.short_channel_id).collect::<Vec<_>>();
4556 assert_eq!(route.get_total_fees(), 100);
4557 assert_eq!(route.get_total_amount(), 100);
4558 assert_eq!(path, vec![2, 4, 6, 11, 8]);
4560 // A different path to nodes[6] exists if channel 6 cannot be routed over.
4561 let scorer = BadChannelScorer { short_channel_id: 6 };
4562 let route = get_route(
4563 &our_id, &payee, &net_graph_msg_handler.network_graph, None, 100, 42,
4564 Arc::clone(&logger), &scorer
4566 let path = route.paths[0].iter().map(|hop| hop.short_channel_id).collect::<Vec<_>>();
4568 assert_eq!(route.get_total_fees(), 300);
4569 assert_eq!(route.get_total_amount(), 100);
4570 assert_eq!(path, vec![2, 4, 7, 10]);
4572 // A path to nodes[6] does not exist if nodes[2] cannot be routed through.
4573 let scorer = BadNodeScorer { node_id: NodeId::from_pubkey(&nodes[2]) };
4575 &our_id, &payee, &net_graph_msg_handler.network_graph, None, 100, 42,
4576 Arc::clone(&logger), &scorer
4578 Err(LightningError { err, .. } ) => {
4579 assert_eq!(err, "Failed to find a path to the given destination");
4581 Ok(_) => panic!("Expected error"),
4586 fn total_fees_single_path() {
4590 pubkey: PublicKey::from_slice(&hex::decode("02eec7245d6b7d2ccb30380bfbe2a3648cd7a942653f5aa340edcea1f283686619").unwrap()[..]).unwrap(),
4591 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
4592 short_channel_id: 0, fee_msat: 100, cltv_expiry_delta: 0
4595 pubkey: PublicKey::from_slice(&hex::decode("0324653eac434488002cc06bbfb7f10fe18991e35f9fe4302dbea6d2353dc0ab1c").unwrap()[..]).unwrap(),
4596 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
4597 short_channel_id: 0, fee_msat: 150, cltv_expiry_delta: 0
4600 pubkey: PublicKey::from_slice(&hex::decode("027f31ebc5462c1fdce1b737ecff52d37d75dea43ce11c74d25aa297165faa2007").unwrap()[..]).unwrap(),
4601 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
4602 short_channel_id: 0, fee_msat: 225, cltv_expiry_delta: 0
4608 assert_eq!(route.get_total_fees(), 250);
4609 assert_eq!(route.get_total_amount(), 225);
4613 fn total_fees_multi_path() {
4617 pubkey: PublicKey::from_slice(&hex::decode("02eec7245d6b7d2ccb30380bfbe2a3648cd7a942653f5aa340edcea1f283686619").unwrap()[..]).unwrap(),
4618 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
4619 short_channel_id: 0, fee_msat: 100, cltv_expiry_delta: 0
4622 pubkey: PublicKey::from_slice(&hex::decode("0324653eac434488002cc06bbfb7f10fe18991e35f9fe4302dbea6d2353dc0ab1c").unwrap()[..]).unwrap(),
4623 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
4624 short_channel_id: 0, fee_msat: 150, cltv_expiry_delta: 0
4628 pubkey: PublicKey::from_slice(&hex::decode("02eec7245d6b7d2ccb30380bfbe2a3648cd7a942653f5aa340edcea1f283686619").unwrap()[..]).unwrap(),
4629 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
4630 short_channel_id: 0, fee_msat: 100, cltv_expiry_delta: 0
4633 pubkey: PublicKey::from_slice(&hex::decode("0324653eac434488002cc06bbfb7f10fe18991e35f9fe4302dbea6d2353dc0ab1c").unwrap()[..]).unwrap(),
4634 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
4635 short_channel_id: 0, fee_msat: 150, cltv_expiry_delta: 0
4641 assert_eq!(route.get_total_fees(), 200);
4642 assert_eq!(route.get_total_amount(), 300);
4646 fn total_empty_route_no_panic() {
4647 // In an earlier version of `Route::get_total_fees` and `Route::get_total_amount`, they
4648 // would both panic if the route was completely empty. We test to ensure they return 0
4649 // here, even though its somewhat nonsensical as a route.
4650 let route = Route { paths: Vec::new(), payee: None };
4652 assert_eq!(route.get_total_fees(), 0);
4653 assert_eq!(route.get_total_amount(), 0);
4656 #[cfg(not(feature = "no-std"))]
4657 pub(super) fn random_init_seed() -> u64 {
4658 // Because the default HashMap in std pulls OS randomness, we can use it as a (bad) RNG.
4659 use core::hash::{BuildHasher, Hasher};
4660 let seed = std::collections::hash_map::RandomState::new().build_hasher().finish();
4661 println!("Using seed of {}", seed);
4664 #[cfg(not(feature = "no-std"))]
4665 use util::ser::Readable;
4668 #[cfg(not(feature = "no-std"))]
4669 fn generate_routes() {
4670 let mut d = match super::test_utils::get_route_file() {
4677 let graph = NetworkGraph::read(&mut d).unwrap();
4678 let scorer = Scorer::new(0);
4680 // First, get 100 (source, destination) pairs for which route-getting actually succeeds...
4681 let mut seed = random_init_seed() as usize;
4682 let nodes = graph.read_only().nodes().clone();
4683 'load_endpoints: for _ in 0..10 {
4685 seed = seed.overflowing_mul(0xdeadbeef).0;
4686 let src = &PublicKey::from_slice(nodes.keys().skip(seed % nodes.len()).next().unwrap().as_slice()).unwrap();
4687 seed = seed.overflowing_mul(0xdeadbeef).0;
4688 let dst = PublicKey::from_slice(nodes.keys().skip(seed % nodes.len()).next().unwrap().as_slice()).unwrap();
4689 let payee = Payee::new(dst);
4690 let amt = seed as u64 % 200_000_000;
4691 if get_route(src, &payee, &graph, None, amt, 42, &test_utils::TestLogger::new(), &scorer).is_ok() {
4692 continue 'load_endpoints;
4699 #[cfg(not(feature = "no-std"))]
4700 fn generate_routes_mpp() {
4701 let mut d = match super::test_utils::get_route_file() {
4708 let graph = NetworkGraph::read(&mut d).unwrap();
4709 let scorer = Scorer::new(0);
4711 // First, get 100 (source, destination) pairs for which route-getting actually succeeds...
4712 let mut seed = random_init_seed() as usize;
4713 let nodes = graph.read_only().nodes().clone();
4714 'load_endpoints: for _ in 0..10 {
4716 seed = seed.overflowing_mul(0xdeadbeef).0;
4717 let src = &PublicKey::from_slice(nodes.keys().skip(seed % nodes.len()).next().unwrap().as_slice()).unwrap();
4718 seed = seed.overflowing_mul(0xdeadbeef).0;
4719 let dst = PublicKey::from_slice(nodes.keys().skip(seed % nodes.len()).next().unwrap().as_slice()).unwrap();
4720 let payee = Payee::new(dst).with_features(InvoiceFeatures::known());
4721 let amt = seed as u64 % 200_000_000;
4722 if get_route(src, &payee, &graph, None, amt, 42, &test_utils::TestLogger::new(), &scorer).is_ok() {
4723 continue 'load_endpoints;
4730 #[cfg(all(test, not(feature = "no-std")))]
4731 pub(crate) mod test_utils {
4733 /// Tries to open a network graph file, or panics with a URL to fetch it.
4734 pub(crate) fn get_route_file() -> Result<std::fs::File, &'static str> {
4735 let res = File::open("net_graph-2021-05-31.bin") // By default we're run in RL/lightning
4736 .or_else(|_| File::open("lightning/net_graph-2021-05-31.bin")) // We may be run manually in RL/
4737 .or_else(|_| { // Fall back to guessing based on the binary location
4738 // path is likely something like .../rust-lightning/target/debug/deps/lightning-...
4739 let mut path = std::env::current_exe().unwrap();
4740 path.pop(); // lightning-...
4742 path.pop(); // debug
4743 path.pop(); // target
4744 path.push("lightning");
4745 path.push("net_graph-2021-05-31.bin");
4746 eprintln!("{}", path.to_str().unwrap());
4749 .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");
4750 #[cfg(require_route_graph_test)]
4751 return Ok(res.unwrap());
4752 #[cfg(not(require_route_graph_test))]
4757 #[cfg(all(test, feature = "unstable", not(feature = "no-std")))]
4760 use routing::scorer::Scorer;
4761 use util::logger::{Logger, Record};
4765 struct DummyLogger {}
4766 impl Logger for DummyLogger {
4767 fn log(&self, _record: &Record) {}
4771 fn generate_routes(bench: &mut Bencher) {
4772 let mut d = test_utils::get_route_file().unwrap();
4773 let graph = NetworkGraph::read(&mut d).unwrap();
4774 let nodes = graph.read_only().nodes().clone();
4775 let scorer = Scorer::new(0);
4777 // First, get 100 (source, destination) pairs for which route-getting actually succeeds...
4778 let mut path_endpoints = Vec::new();
4779 let mut seed: usize = 0xdeadbeef;
4780 'load_endpoints: for _ in 0..100 {
4783 let src = PublicKey::from_slice(nodes.keys().skip(seed % nodes.len()).next().unwrap().as_slice()).unwrap();
4785 let dst = PublicKey::from_slice(nodes.keys().skip(seed % nodes.len()).next().unwrap().as_slice()).unwrap();
4786 let payee = Payee::new(dst);
4787 let amt = seed as u64 % 1_000_000;
4788 if get_route(&src, &payee, &graph, None, amt, 42, &DummyLogger{}, &scorer).is_ok() {
4789 path_endpoints.push((src, dst, amt));
4790 continue 'load_endpoints;
4795 // ...then benchmark finding paths between the nodes we learned.
4798 let (src, dst, amt) = path_endpoints[idx % path_endpoints.len()];
4799 let payee = Payee::new(dst);
4800 assert!(get_route(&src, &payee, &graph, None, amt, 42, &DummyLogger{}, &scorer).is_ok());
4806 fn generate_mpp_routes(bench: &mut Bencher) {
4807 let mut d = test_utils::get_route_file().unwrap();
4808 let graph = NetworkGraph::read(&mut d).unwrap();
4809 let nodes = graph.read_only().nodes().clone();
4810 let scorer = Scorer::new(0);
4812 // First, get 100 (source, destination) pairs for which route-getting actually succeeds...
4813 let mut path_endpoints = Vec::new();
4814 let mut seed: usize = 0xdeadbeef;
4815 'load_endpoints: for _ in 0..100 {
4818 let src = PublicKey::from_slice(nodes.keys().skip(seed % nodes.len()).next().unwrap().as_slice()).unwrap();
4820 let dst = PublicKey::from_slice(nodes.keys().skip(seed % nodes.len()).next().unwrap().as_slice()).unwrap();
4821 let payee = Payee::new(dst).with_features(InvoiceFeatures::known());
4822 let amt = seed as u64 % 1_000_000;
4823 if get_route(&src, &payee, &graph, None, amt, 42, &DummyLogger{}, &scorer).is_ok() {
4824 path_endpoints.push((src, dst, amt));
4825 continue 'load_endpoints;
4830 // ...then benchmark finding paths between the nodes we learned.
4833 let (src, dst, amt) = path_endpoints[idx % path_endpoints.len()];
4834 let payee = Payee::new(dst).with_features(InvoiceFeatures::known());
4835 assert!(get_route(&src, &payee, &graph, None, amt, 42, &DummyLogger{}, &scorer).is_ok());