1 // This file is Copyright its original authors, visible in version control
4 // This file is licensed under the Apache License, Version 2.0 <LICENSE-APACHE
5 // or http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
6 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your option.
7 // You may not use this file except in accordance with one or both of these
10 //! The top-level routing/network map tracking logic lives here.
12 //! You probably want to create a NetGraphMsgHandler and use that as your RoutingMessageHandler and then
13 //! interrogate it to get routes for your own payments.
15 use bitcoin::secp256k1::key::PublicKey;
17 use ln::channelmanager::ChannelDetails;
18 use ln::features::{ChannelFeatures, InvoiceFeatures, NodeFeatures};
19 use ln::msgs::{DecodeError, ErrorAction, LightningError, MAX_VALUE_MSAT};
21 use routing::network_graph::{NetworkGraph, NodeId, RoutingFees};
22 use util::ser::{Writeable, Readable};
23 use util::logger::{Level, Logger};
27 use alloc::collections::BinaryHeap;
32 #[derive(Clone, Debug, Hash, PartialEq, Eq)]
34 /// The node_id of the node at this hop.
35 pub pubkey: PublicKey,
36 /// The node_announcement features of the node at this hop. For the last hop, these may be
37 /// amended to match the features present in the invoice this node generated.
38 pub node_features: NodeFeatures,
39 /// The channel that should be used from the previous hop to reach this node.
40 pub short_channel_id: u64,
41 /// The channel_announcement features of the channel that should be used from the previous hop
42 /// to reach this node.
43 pub channel_features: ChannelFeatures,
44 /// The fee taken on this hop (for paying for the use of the *next* channel in the path).
45 /// For the last hop, this should be the full value of the payment (might be more than
46 /// requested if we had to match htlc_minimum_msat).
48 /// The CLTV delta added for this hop. For the last hop, this should be the full CLTV value
49 /// expected at the destination, in excess of the current block height.
50 pub cltv_expiry_delta: u32,
53 impl_writeable_tlv_based!(RouteHop, {
54 (0, pubkey, required),
55 (2, node_features, required),
56 (4, short_channel_id, required),
57 (6, channel_features, required),
58 (8, fee_msat, required),
59 (10, cltv_expiry_delta, required),
62 /// A route directs a payment from the sender (us) to the recipient. If the recipient supports MPP,
63 /// it can take multiple paths. Each path is composed of one or more hops through the network.
64 #[derive(Clone, Hash, PartialEq, Eq)]
66 /// The list of routes taken for a single (potentially-)multi-part payment. The pubkey of the
67 /// last RouteHop in each path must be the same.
68 /// Each entry represents a list of hops, NOT INCLUDING our own, where the last hop is the
69 /// destination. Thus, this must always be at least length one. While the maximum length of any
70 /// given path is variable, keeping the length of any path to less than 20 should currently
71 /// ensure it is viable.
72 pub paths: Vec<Vec<RouteHop>>,
76 /// Returns the total amount of fees paid on this [`Route`].
78 /// This doesn't include any extra payment made to the recipient, which can happen in excess of
79 /// the amount passed to [`get_route`]'s `final_value_msat`.
80 pub fn get_total_fees(&self) -> u64 {
81 // Do not count last hop of each path since that's the full value of the payment
82 return self.paths.iter()
83 .flat_map(|path| path.split_last().map(|(_, path_prefix)| path_prefix).unwrap_or(&[]))
84 .map(|hop| &hop.fee_msat)
88 /// Returns the total amount paid on this [`Route`], excluding the fees.
89 pub fn get_total_amount(&self) -> u64 {
90 return self.paths.iter()
91 .map(|path| path.split_last().map(|(hop, _)| hop.fee_msat).unwrap_or(0))
96 const SERIALIZATION_VERSION: u8 = 1;
97 const MIN_SERIALIZATION_VERSION: u8 = 1;
99 impl Writeable for Route {
100 fn write<W: ::util::ser::Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
101 write_ver_prefix!(writer, SERIALIZATION_VERSION, MIN_SERIALIZATION_VERSION);
102 (self.paths.len() as u64).write(writer)?;
103 for hops in self.paths.iter() {
104 (hops.len() as u8).write(writer)?;
105 for hop in hops.iter() {
109 write_tlv_fields!(writer, {});
114 impl Readable for Route {
115 fn read<R: io::Read>(reader: &mut R) -> Result<Route, DecodeError> {
116 let _ver = read_ver_prefix!(reader, SERIALIZATION_VERSION);
117 let path_count: u64 = Readable::read(reader)?;
118 let mut paths = Vec::with_capacity(cmp::min(path_count, 128) as usize);
119 for _ in 0..path_count {
120 let hop_count: u8 = Readable::read(reader)?;
121 let mut hops = Vec::with_capacity(hop_count as usize);
122 for _ in 0..hop_count {
123 hops.push(Readable::read(reader)?);
127 read_tlv_fields!(reader, {});
132 /// A list of hops along a payment path terminating with a channel to the recipient.
133 #[derive(Clone, Debug, Hash, Eq, PartialEq)]
134 pub struct RouteHint(pub Vec<RouteHintHop>);
136 /// A channel descriptor for a hop along a payment path.
137 #[derive(Clone, Debug, Hash, Eq, PartialEq)]
138 pub struct RouteHintHop {
139 /// The node_id of the non-target end of the route
140 pub src_node_id: PublicKey,
141 /// The short_channel_id of this channel
142 pub short_channel_id: u64,
143 /// The fees which must be paid to use this channel
144 pub fees: RoutingFees,
145 /// The difference in CLTV values between this node and the next node.
146 pub cltv_expiry_delta: u16,
147 /// The minimum value, in msat, which must be relayed to the next hop.
148 pub htlc_minimum_msat: Option<u64>,
149 /// The maximum value in msat available for routing with a single HTLC.
150 pub htlc_maximum_msat: Option<u64>,
153 #[derive(Eq, PartialEq)]
154 struct RouteGraphNode {
156 lowest_fee_to_peer_through_node: u64,
157 lowest_fee_to_node: u64,
158 // The maximum value a yet-to-be-constructed payment path might flow through this node.
159 // This value is upper-bounded by us by:
160 // - how much is needed for a path being constructed
161 // - how much value can channels following this node (up to the destination) can contribute,
162 // considering their capacity and fees
163 value_contribution_msat: u64,
164 /// The effective htlc_minimum_msat at this hop. If a later hop on the path had a higher HTLC
165 /// minimum, we use it, plus the fees required at each earlier hop to meet it.
166 path_htlc_minimum_msat: u64,
167 /// All penalties incurred from this hop on the way to the destination, as calculated using
169 path_penalty_msat: u64,
172 impl cmp::Ord for RouteGraphNode {
173 fn cmp(&self, other: &RouteGraphNode) -> cmp::Ordering {
174 let other_score = cmp::max(other.lowest_fee_to_peer_through_node, other.path_htlc_minimum_msat)
175 .checked_add(other.path_penalty_msat)
176 .unwrap_or_else(|| u64::max_value());
177 let self_score = cmp::max(self.lowest_fee_to_peer_through_node, self.path_htlc_minimum_msat)
178 .checked_add(self.path_penalty_msat)
179 .unwrap_or_else(|| u64::max_value());
180 other_score.cmp(&self_score).then_with(|| other.node_id.cmp(&self.node_id))
184 impl cmp::PartialOrd for RouteGraphNode {
185 fn partial_cmp(&self, other: &RouteGraphNode) -> Option<cmp::Ordering> {
186 Some(self.cmp(other))
190 struct DummyDirectionalChannelInfo {
191 cltv_expiry_delta: u32,
192 htlc_minimum_msat: u64,
193 htlc_maximum_msat: Option<u64>,
197 /// It's useful to keep track of the hops associated with the fees required to use them,
198 /// so that we can choose cheaper paths (as per Dijkstra's algorithm).
199 /// Fee values should be updated only in the context of the whole path, see update_value_and_recompute_fees.
200 /// These fee values are useful to choose hops as we traverse the graph "payee-to-payer".
201 #[derive(Clone, Debug)]
202 struct PathBuildingHop<'a> {
203 // The RouteHintHop fields which will eventually be used if this hop is used in a final Route.
204 // Note that node_features is calculated separately after our initial graph walk.
206 short_channel_id: u64,
207 channel_features: &'a ChannelFeatures,
209 cltv_expiry_delta: u32,
211 /// Minimal fees required to route to the source node of the current hop via any of its inbound channels.
212 src_lowest_inbound_fees: RoutingFees,
213 /// Fees of the channel used in this hop.
214 channel_fees: RoutingFees,
215 /// All the fees paid *after* this channel on the way to the destination
216 next_hops_fee_msat: u64,
217 /// Fee paid for the use of the current channel (see channel_fees).
218 /// The value will be actually deducted from the counterparty balance on the previous link.
219 hop_use_fee_msat: u64,
220 /// Used to compare channels when choosing the for routing.
221 /// Includes paying for the use of a hop and the following hops, as well as
222 /// an estimated cost of reaching this hop.
223 /// Might get stale when fees are recomputed. Primarily for internal use.
225 /// This is useful for update_value_and_recompute_fees to make sure
226 /// we don't fall below the minimum. Should not be updated manually and
227 /// generally should not be accessed.
228 htlc_minimum_msat: u64,
229 /// A mirror of the same field in RouteGraphNode. Note that this is only used during the graph
230 /// walk and may be invalid thereafter.
231 path_htlc_minimum_msat: u64,
232 /// All penalties incurred from this channel on the way to the destination, as calculated using
234 path_penalty_msat: u64,
235 /// If we've already processed a node as the best node, we shouldn't process it again. Normally
236 /// we'd just ignore it if we did as all channels would have a higher new fee, but because we
237 /// may decrease the amounts in use as we walk the graph, the actual calculated fee may
238 /// decrease as well. Thus, we have to explicitly track which nodes have been processed and
239 /// avoid processing them again.
241 #[cfg(any(test, feature = "fuzztarget"))]
242 // In tests, we apply further sanity checks on cases where we skip nodes we already processed
243 // to ensure it is specifically in cases where the fee has gone down because of a decrease in
244 // value_contribution_msat, which requires tracking it here. See comments below where it is
245 // used for more info.
246 value_contribution_msat: u64,
249 // Instantiated with a list of hops with correct data in them collected during path finding,
250 // an instance of this struct should be further modified only via given methods.
252 struct PaymentPath<'a> {
253 hops: Vec<(PathBuildingHop<'a>, NodeFeatures)>,
256 impl<'a> PaymentPath<'a> {
257 // TODO: Add a value_msat field to PaymentPath and use it instead of this function.
258 fn get_value_msat(&self) -> u64 {
259 self.hops.last().unwrap().0.fee_msat
262 fn get_total_fee_paid_msat(&self) -> u64 {
263 if self.hops.len() < 1 {
267 // Can't use next_hops_fee_msat because it gets outdated.
268 for (i, (hop, _)) in self.hops.iter().enumerate() {
269 if i != self.hops.len() - 1 {
270 result += hop.fee_msat;
276 // If the amount transferred by the path is updated, the fees should be adjusted. Any other way
277 // to change fees may result in an inconsistency.
279 // Sometimes we call this function right after constructing a path which is inconsistent in
280 // that it the value being transferred has decreased while we were doing path finding, leading
281 // to the fees being paid not lining up with the actual limits.
283 // Note that this function is not aware of the available_liquidity limit, and thus does not
284 // support increasing the value being transferred.
285 fn update_value_and_recompute_fees(&mut self, value_msat: u64) {
286 assert!(value_msat <= self.hops.last().unwrap().0.fee_msat);
288 let mut total_fee_paid_msat = 0 as u64;
289 for i in (0..self.hops.len()).rev() {
290 let last_hop = i == self.hops.len() - 1;
292 // For non-last-hop, this value will represent the fees paid on the current hop. It
293 // will consist of the fees for the use of the next hop, and extra fees to match
294 // htlc_minimum_msat of the current channel. Last hop is handled separately.
295 let mut cur_hop_fees_msat = 0;
297 cur_hop_fees_msat = self.hops.get(i + 1).unwrap().0.hop_use_fee_msat;
300 let mut cur_hop = &mut self.hops.get_mut(i).unwrap().0;
301 cur_hop.next_hops_fee_msat = total_fee_paid_msat;
302 // Overpay in fees if we can't save these funds due to htlc_minimum_msat.
303 // We try to account for htlc_minimum_msat in scoring (add_entry!), so that nodes don't
304 // set it too high just to maliciously take more fees by exploiting this
305 // match htlc_minimum_msat logic.
306 let mut cur_hop_transferred_amount_msat = total_fee_paid_msat + value_msat;
307 if let Some(extra_fees_msat) = cur_hop.htlc_minimum_msat.checked_sub(cur_hop_transferred_amount_msat) {
308 // Note that there is a risk that *previous hops* (those closer to us, as we go
309 // payee->our_node here) would exceed their htlc_maximum_msat or available balance.
311 // This might make us end up with a broken route, although this should be super-rare
312 // in practice, both because of how healthy channels look like, and how we pick
313 // channels in add_entry.
314 // Also, this can't be exploited more heavily than *announce a free path and fail
316 cur_hop_transferred_amount_msat += extra_fees_msat;
317 total_fee_paid_msat += extra_fees_msat;
318 cur_hop_fees_msat += extra_fees_msat;
322 // Final hop is a special case: it usually has just value_msat (by design), but also
323 // it still could overpay for the htlc_minimum_msat.
324 cur_hop.fee_msat = cur_hop_transferred_amount_msat;
326 // Propagate updated fees for the use of the channels to one hop back, where they
327 // will be actually paid (fee_msat). The last hop is handled above separately.
328 cur_hop.fee_msat = cur_hop_fees_msat;
331 // Fee for the use of the current hop which will be deducted on the previous hop.
332 // Irrelevant for the first hop, as it doesn't have the previous hop, and the use of
333 // this channel is free for us.
335 if let Some(new_fee) = compute_fees(cur_hop_transferred_amount_msat, cur_hop.channel_fees) {
336 cur_hop.hop_use_fee_msat = new_fee;
337 total_fee_paid_msat += new_fee;
339 // It should not be possible because this function is called only to reduce the
340 // value. In that case, compute_fee was already called with the same fees for
341 // larger amount and there was no overflow.
349 fn compute_fees(amount_msat: u64, channel_fees: RoutingFees) -> Option<u64> {
350 let proportional_fee_millions =
351 amount_msat.checked_mul(channel_fees.proportional_millionths as u64);
352 if let Some(new_fee) = proportional_fee_millions.and_then(|part| {
353 (channel_fees.base_msat as u64).checked_add(part / 1_000_000) }) {
357 // This function may be (indirectly) called without any verification,
358 // with channel_fees provided by a caller. We should handle it gracefully.
363 /// Gets a keysend route from us (payer) to the given target node (payee). This is needed because
364 /// keysend payments do not have an invoice from which to pull the payee's supported features, which
365 /// makes it tricky to otherwise supply the `payee_features` parameter of `get_route`.
366 pub fn get_keysend_route<L: Deref, S: routing::Score>(
367 our_node_pubkey: &PublicKey, network: &NetworkGraph, payee: &PublicKey,
368 first_hops: Option<&[&ChannelDetails]>, last_hops: &[&RouteHint], final_value_msat: u64,
369 final_cltv: u32, logger: L, scorer: &S
370 ) -> Result<Route, LightningError>
371 where L::Target: Logger {
372 let invoice_features = InvoiceFeatures::for_keysend();
374 our_node_pubkey, network, payee, Some(invoice_features), first_hops, last_hops,
375 final_value_msat, final_cltv, logger, scorer
379 /// Gets a route from us (payer) to the given target node (payee).
381 /// If the payee provided features in their invoice, they should be provided via payee_features.
382 /// Without this, MPP will only be used if the payee's features are available in the network graph.
384 /// Private routing paths between a public node and the target may be included in `last_hops`.
385 /// Currently, only the last hop in each path is considered.
387 /// If some channels aren't announced, it may be useful to fill in a first_hops with the
388 /// results from a local ChannelManager::list_usable_channels() call. If it is filled in, our
389 /// view of our local channels (from net_graph_msg_handler) will be ignored, and only those
390 /// in first_hops will be used.
392 /// Panics if first_hops contains channels without short_channel_ids
393 /// (ChannelManager::list_usable_channels will never include such channels).
395 /// The fees on channels from us to next-hops are ignored (as they are assumed to all be
396 /// equal), however the enabled/disabled bit on such channels as well as the
397 /// htlc_minimum_msat/htlc_maximum_msat *are* checked as they may change based on the receiving node.
398 pub fn get_route<L: Deref, S: routing::Score>(
399 our_node_pubkey: &PublicKey, network: &NetworkGraph, payee: &PublicKey,
400 payee_features: Option<InvoiceFeatures>, first_hops: Option<&[&ChannelDetails]>,
401 last_hops: &[&RouteHint], final_value_msat: u64, final_cltv: u32, logger: L, scorer: &S
402 ) -> Result<Route, LightningError>
403 where L::Target: Logger {
404 let payee_node_id = NodeId::from_pubkey(&payee);
405 let our_node_id = NodeId::from_pubkey(&our_node_pubkey);
407 if payee_node_id == our_node_id {
408 return Err(LightningError{err: "Cannot generate a route to ourselves".to_owned(), action: ErrorAction::IgnoreError});
411 if final_value_msat > MAX_VALUE_MSAT {
412 return Err(LightningError{err: "Cannot generate a route of more value than all existing satoshis".to_owned(), action: ErrorAction::IgnoreError});
415 if final_value_msat == 0 {
416 return Err(LightningError{err: "Cannot send a payment of 0 msat".to_owned(), action: ErrorAction::IgnoreError});
419 for route in last_hops.iter() {
420 for hop in &route.0 {
421 if hop.src_node_id == *payee {
422 return Err(LightningError{err: "Last hop cannot have a payee as a source.".to_owned(), action: ErrorAction::IgnoreError});
427 // The general routing idea is the following:
428 // 1. Fill first/last hops communicated by the caller.
429 // 2. Attempt to construct a path from payer to payee for transferring
430 // any ~sufficient (described later) value.
431 // If succeed, remember which channels were used and how much liquidity they have available,
432 // so that future paths don't rely on the same liquidity.
433 // 3. Prooceed to the next step if:
434 // - we hit the recommended target value;
435 // - OR if we could not construct a new path. Any next attempt will fail too.
436 // Otherwise, repeat step 2.
437 // 4. See if we managed to collect paths which aggregately are able to transfer target value
438 // (not recommended value). If yes, proceed. If not, fail routing.
439 // 5. Randomly combine paths into routes having enough to fulfill the payment. (TODO: knapsack)
440 // 6. Of all the found paths, select only those with the lowest total fee.
441 // 7. The last path in every selected route is likely to be more than we need.
442 // Reduce its value-to-transfer and recompute fees.
443 // 8. Choose the best route by the lowest total fee.
445 // As for the actual search algorithm,
446 // we do a payee-to-payer pseudo-Dijkstra's sorting by each node's distance from the payee
447 // plus the minimum per-HTLC fee to get from it to another node (aka "shitty pseudo-A*").
449 // We are not a faithful Dijkstra's implementation because we can change values which impact
450 // earlier nodes while processing later nodes. Specifically, if we reach a channel with a lower
451 // liquidity limit (via htlc_maximum_msat, on-chain capacity or assumed liquidity limits) then
452 // the value we are currently attempting to send over a path, we simply reduce the value being
453 // sent along the path for any hops after that channel. This may imply that later fees (which
454 // we've already tabulated) are lower because a smaller value is passing through the channels
455 // (and the proportional fee is thus lower). There isn't a trivial way to recalculate the
456 // channels which were selected earlier (and which may still be used for other paths without a
457 // lower liquidity limit), so we simply accept that some liquidity-limited paths may be
460 // One potentially problematic case for this algorithm would be if there are many
461 // liquidity-limited paths which are liquidity-limited near the destination (ie early in our
462 // graph walking), we may never find a path which is not liquidity-limited and has lower
463 // proportional fee (and only lower absolute fee when considering the ultimate value sent).
464 // Because we only consider paths with at least 5% of the total value being sent, the damage
465 // from such a case should be limited, however this could be further reduced in the future by
466 // calculating fees on the amount we wish to route over a path, ie ignoring the liquidity
467 // limits for the purposes of fee calculation.
469 // Alternatively, we could store more detailed path information in the heap (targets, below)
470 // and index the best-path map (dist, below) by node *and* HTLC limits, however that would blow
471 // up the runtime significantly both algorithmically (as we'd traverse nodes multiple times)
472 // and practically (as we would need to store dynamically-allocated path information in heap
473 // objects, increasing malloc traffic and indirect memory access significantly). Further, the
474 // results of such an algorithm would likely be biased towards lower-value paths.
476 // Further, we could return to a faithful Dijkstra's algorithm by rejecting paths with limits
477 // outside of our current search value, running a path search more times to gather candidate
478 // paths at different values. While this may be acceptable, further path searches may increase
479 // runtime for little gain. Specifically, the current algorithm rather efficiently explores the
480 // graph for candidate paths, calculating the maximum value which can realistically be sent at
481 // the same time, remaining generic across different payment values.
483 // TODO: There are a few tweaks we could do, including possibly pre-calculating more stuff
484 // to use as the A* heuristic beyond just the cost to get one node further than the current
487 let network_graph = network.read_only();
488 let network_channels = network_graph.channels();
489 let network_nodes = network_graph.nodes();
490 let dummy_directional_info = DummyDirectionalChannelInfo { // used for first_hops routes
491 cltv_expiry_delta: 0,
492 htlc_minimum_msat: 0,
493 htlc_maximum_msat: None,
496 proportional_millionths: 0,
500 // Allow MPP only if we have a features set from somewhere that indicates the payee supports
501 // it. If the payee supports it they're supposed to include it in the invoice, so that should
503 let allow_mpp = if let Some(features) = &payee_features {
504 features.supports_basic_mpp()
505 } else if let Some(node) = network_nodes.get(&payee_node_id) {
506 if let Some(node_info) = node.announcement_info.as_ref() {
507 node_info.features.supports_basic_mpp()
510 log_trace!(logger, "Searching for a route from payer {} to payee {} {} MPP", our_node_pubkey, payee,
511 if allow_mpp { "with" } else { "without" });
514 // Prepare the data we'll use for payee-to-payer search by
515 // inserting first hops suggested by the caller as targets.
516 // Our search will then attempt to reach them while traversing from the payee node.
517 let mut first_hop_targets: HashMap<_, Vec<(_, ChannelFeatures, _, NodeFeatures)>> =
518 HashMap::with_capacity(if first_hops.is_some() { first_hops.as_ref().unwrap().len() } else { 0 });
519 if let Some(hops) = first_hops {
521 let short_channel_id = chan.short_channel_id.expect("first_hops should be filled in with usable channels, not pending ones");
522 if chan.counterparty.node_id == *our_node_pubkey {
523 return Err(LightningError{err: "First hop cannot have our_node_pubkey as a destination.".to_owned(), action: ErrorAction::IgnoreError});
525 first_hop_targets.entry(NodeId::from_pubkey(&chan.counterparty.node_id)).or_insert(Vec::new())
526 .push((short_channel_id, chan.counterparty.features.to_context(), chan.outbound_capacity_msat, chan.counterparty.features.to_context()));
528 if first_hop_targets.is_empty() {
529 return Err(LightningError{err: "Cannot route when there are no outbound routes away from us".to_owned(), action: ErrorAction::IgnoreError});
533 let empty_channel_features = ChannelFeatures::empty();
535 // The main heap containing all candidate next-hops sorted by their score (max(A* fee,
536 // htlc_minimum)). Ideally this would be a heap which allowed cheap score reduction instead of
537 // adding duplicate entries when we find a better path to a given node.
538 let mut targets = BinaryHeap::new();
540 // Map from node_id to information about the best current path to that node, including feerate
542 let mut dist = HashMap::with_capacity(network_nodes.len());
544 // During routing, if we ignore a path due to an htlc_minimum_msat limit, we set this,
545 // indicating that we may wish to try again with a higher value, potentially paying to meet an
546 // htlc_minimum with extra fees while still finding a cheaper path.
547 let mut hit_minimum_limit;
549 // When arranging a route, we select multiple paths so that we can make a multi-path payment.
550 // We start with a path_value of the exact amount we want, and if that generates a route we may
551 // return it immediately. Otherwise, we don't stop searching for paths until we have 3x the
552 // amount we want in total across paths, selecting the best subset at the end.
553 const ROUTE_CAPACITY_PROVISION_FACTOR: u64 = 3;
554 let recommended_value_msat = final_value_msat * ROUTE_CAPACITY_PROVISION_FACTOR as u64;
555 let mut path_value_msat = final_value_msat;
557 // We don't want multiple paths (as per MPP) share liquidity of the same channels.
558 // This map allows paths to be aware of the channel use by other paths in the same call.
559 // This would help to make a better path finding decisions and not "overbook" channels.
560 // It is unaware of the directions (except for `outbound_capacity_msat` in `first_hops`).
561 let mut bookkeeped_channels_liquidity_available_msat = HashMap::with_capacity(network_nodes.len());
563 // Keeping track of how much value we already collected across other paths. Helps to decide:
564 // - how much a new path should be transferring (upper bound);
565 // - whether a channel should be disregarded because
566 // it's available liquidity is too small comparing to how much more we need to collect;
567 // - when we want to stop looking for new paths.
568 let mut already_collected_value_msat = 0;
570 log_trace!(logger, "Building path from {} (payee) to {} (us/payer) for value {} msat.", payee, our_node_pubkey, final_value_msat);
572 macro_rules! add_entry {
573 // Adds entry which goes from $src_node_id to $dest_node_id
574 // over the channel with id $chan_id with fees described in
575 // $directional_info.
576 // $next_hops_fee_msat represents the fees paid for using all the channel *after* this one,
577 // since that value has to be transferred over this channel.
578 // Returns whether this channel caused an update to `targets`.
579 ( $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,
580 $next_hops_value_contribution: expr, $next_hops_path_htlc_minimum_msat: expr, $next_hops_path_penalty_msat: expr ) => { {
581 // We "return" whether we updated the path at the end, via this:
582 let mut did_add_update_path_to_src_node = false;
583 // Channels to self should not be used. This is more of belt-and-suspenders, because in
584 // practice these cases should be caught earlier:
585 // - for regular channels at channel announcement (TODO)
586 // - for first and last hops early in get_route
587 if $src_node_id != $dest_node_id.clone() {
588 let available_liquidity_msat = bookkeeped_channels_liquidity_available_msat.entry($chan_id.clone()).or_insert_with(|| {
589 let mut initial_liquidity_available_msat = None;
590 if let Some(capacity_sats) = $capacity_sats {
591 initial_liquidity_available_msat = Some(capacity_sats * 1000);
594 if let Some(htlc_maximum_msat) = $directional_info.htlc_maximum_msat {
595 if let Some(available_msat) = initial_liquidity_available_msat {
596 initial_liquidity_available_msat = Some(cmp::min(available_msat, htlc_maximum_msat));
598 initial_liquidity_available_msat = Some(htlc_maximum_msat);
602 match initial_liquidity_available_msat {
603 Some(available_msat) => available_msat,
604 // We assume channels with unknown balance have
605 // a capacity of 0.0025 BTC (or 250_000 sats).
606 None => 250_000 * 1000
610 // It is tricky to substract $next_hops_fee_msat from available liquidity here.
611 // It may be misleading because we might later choose to reduce the value transferred
612 // over these channels, and the channel which was insufficient might become sufficient.
613 // Worst case: we drop a good channel here because it can't cover the high following
614 // fees caused by one expensive channel, but then this channel could have been used
615 // if the amount being transferred over this path is lower.
616 // We do this for now, but this is a subject for removal.
617 if let Some(available_value_contribution_msat) = available_liquidity_msat.checked_sub($next_hops_fee_msat) {
619 // Routing Fragmentation Mitigation heuristic:
621 // Routing fragmentation across many payment paths increases the overall routing
622 // fees as you have irreducible routing fees per-link used (`fee_base_msat`).
623 // Taking too many smaller paths also increases the chance of payment failure.
624 // Thus to avoid this effect, we require from our collected links to provide
625 // at least a minimal contribution to the recommended value yet-to-be-fulfilled.
627 // This requirement is currently 5% of the remaining-to-be-collected value.
628 // This means as we successfully advance in our collection,
629 // the absolute liquidity contribution is lowered,
630 // thus increasing the number of potential channels to be selected.
632 // Derive the minimal liquidity contribution with a ratio of 20 (5%, rounded up)
633 // or 100% if we're not allowed to do multipath payments.
634 let minimal_value_contribution_msat: u64 = if allow_mpp {
635 (recommended_value_msat - already_collected_value_msat + 19) / 20
639 // Verify the liquidity offered by this channel complies to the minimal contribution.
640 let contributes_sufficient_value = available_value_contribution_msat >= minimal_value_contribution_msat;
642 let value_contribution_msat = cmp::min(available_value_contribution_msat, $next_hops_value_contribution);
643 // Includes paying fees for the use of the following channels.
644 let amount_to_transfer_over_msat: u64 = match value_contribution_msat.checked_add($next_hops_fee_msat) {
645 Some(result) => result,
646 // Can't overflow due to how the values were computed right above.
647 None => unreachable!(),
649 #[allow(unused_comparisons)] // $next_hops_path_htlc_minimum_msat is 0 in some calls so rustc complains
650 let over_path_minimum_msat = amount_to_transfer_over_msat >= $directional_info.htlc_minimum_msat &&
651 amount_to_transfer_over_msat >= $next_hops_path_htlc_minimum_msat;
653 // If HTLC minimum is larger than the amount we're going to transfer, we shouldn't
654 // bother considering this channel.
655 // Since we're choosing amount_to_transfer_over_msat as maximum possible, it can
656 // be only reduced later (not increased), so this channel should just be skipped
657 // as not sufficient.
658 if !over_path_minimum_msat {
659 hit_minimum_limit = true;
660 } else if contributes_sufficient_value {
661 // Note that low contribution here (limited by available_liquidity_msat)
662 // might violate htlc_minimum_msat on the hops which are next along the
663 // payment path (upstream to the payee). To avoid that, we recompute path
664 // path fees knowing the final path contribution after constructing it.
665 let path_htlc_minimum_msat = compute_fees($next_hops_path_htlc_minimum_msat, $directional_info.fees)
666 .and_then(|fee_msat| fee_msat.checked_add($next_hops_path_htlc_minimum_msat))
667 .map(|fee_msat| cmp::max(fee_msat, $directional_info.htlc_minimum_msat))
668 .unwrap_or_else(|| u64::max_value());
669 let hm_entry = dist.entry($src_node_id);
670 let old_entry = hm_entry.or_insert_with(|| {
671 // If there was previously no known way to access
672 // the source node (recall it goes payee-to-payer) of $chan_id, first add
673 // a semi-dummy record just to compute the fees to reach the source node.
674 // This will affect our decision on selecting $chan_id
675 // as a way to reach the $dest_node_id.
676 let mut fee_base_msat = u32::max_value();
677 let mut fee_proportional_millionths = u32::max_value();
678 if let Some(Some(fees)) = network_nodes.get(&$src_node_id).map(|node| node.lowest_inbound_channel_fees) {
679 fee_base_msat = fees.base_msat;
680 fee_proportional_millionths = fees.proportional_millionths;
683 node_id: $dest_node_id.clone(),
685 channel_features: $chan_features,
687 cltv_expiry_delta: 0,
688 src_lowest_inbound_fees: RoutingFees {
689 base_msat: fee_base_msat,
690 proportional_millionths: fee_proportional_millionths,
692 channel_fees: $directional_info.fees,
693 next_hops_fee_msat: u64::max_value(),
694 hop_use_fee_msat: u64::max_value(),
695 total_fee_msat: u64::max_value(),
696 htlc_minimum_msat: $directional_info.htlc_minimum_msat,
697 path_htlc_minimum_msat,
698 path_penalty_msat: u64::max_value(),
699 was_processed: false,
700 #[cfg(any(test, feature = "fuzztarget"))]
701 value_contribution_msat,
705 #[allow(unused_mut)] // We only use the mut in cfg(test)
706 let mut should_process = !old_entry.was_processed;
707 #[cfg(any(test, feature = "fuzztarget"))]
709 // In test/fuzzing builds, we do extra checks to make sure the skipping
710 // of already-seen nodes only happens in cases we expect (see below).
711 if !should_process { should_process = true; }
715 let mut hop_use_fee_msat = 0;
716 let mut total_fee_msat = $next_hops_fee_msat;
718 // Ignore hop_use_fee_msat for channel-from-us as we assume all channels-from-us
719 // will have the same effective-fee
720 if $src_node_id != our_node_id {
721 match compute_fees(amount_to_transfer_over_msat, $directional_info.fees) {
722 // max_value means we'll always fail
723 // the old_entry.total_fee_msat > total_fee_msat check
724 None => total_fee_msat = u64::max_value(),
726 hop_use_fee_msat = fee_msat;
727 total_fee_msat += hop_use_fee_msat;
728 // When calculating the lowest inbound fees to a node, we
729 // calculate fees here not based on the actual value we think
730 // will flow over this channel, but on the minimum value that
731 // we'll accept flowing over it. The minimum accepted value
732 // is a constant through each path collection run, ensuring
733 // consistent basis. Otherwise we may later find a
734 // different path to the source node that is more expensive,
735 // but which we consider to be cheaper because we are capacity
736 // constrained and the relative fee becomes lower.
737 match compute_fees(minimal_value_contribution_msat, old_entry.src_lowest_inbound_fees)
738 .map(|a| a.checked_add(total_fee_msat)) {
743 total_fee_msat = u64::max_value();
750 let path_penalty_msat = $next_hops_path_penalty_msat
751 .checked_add(scorer.channel_penalty_msat($chan_id.clone(), &$src_node_id, &$dest_node_id))
752 .unwrap_or_else(|| u64::max_value());
753 let new_graph_node = RouteGraphNode {
754 node_id: $src_node_id,
755 lowest_fee_to_peer_through_node: total_fee_msat,
756 lowest_fee_to_node: $next_hops_fee_msat as u64 + hop_use_fee_msat,
757 value_contribution_msat: value_contribution_msat,
758 path_htlc_minimum_msat,
762 // Update the way of reaching $src_node_id with the given $chan_id (from $dest_node_id),
763 // if this way is cheaper than the already known
764 // (considering the cost to "reach" this channel from the route destination,
765 // the cost of using this channel,
766 // and the cost of routing to the source node of this channel).
767 // Also, consider that htlc_minimum_msat_difference, because we might end up
768 // paying it. Consider the following exploit:
769 // we use 2 paths to transfer 1.5 BTC. One of them is 0-fee normal 1 BTC path,
770 // and for the other one we picked a 1sat-fee path with htlc_minimum_msat of
771 // 1 BTC. Now, since the latter is more expensive, we gonna try to cut it
772 // by 0.5 BTC, but then match htlc_minimum_msat by paying a fee of 0.5 BTC
774 // Ideally the scoring could be smarter (e.g. 0.5*htlc_minimum_msat here),
775 // but it may require additional tracking - we don't want to double-count
776 // the fees included in $next_hops_path_htlc_minimum_msat, but also
777 // can't use something that may decrease on future hops.
778 let old_cost = cmp::max(old_entry.total_fee_msat, old_entry.path_htlc_minimum_msat)
779 .checked_add(old_entry.path_penalty_msat)
780 .unwrap_or_else(|| u64::max_value());
781 let new_cost = cmp::max(total_fee_msat, path_htlc_minimum_msat)
782 .checked_add(path_penalty_msat)
783 .unwrap_or_else(|| u64::max_value());
785 if !old_entry.was_processed && new_cost < old_cost {
786 targets.push(new_graph_node);
787 old_entry.next_hops_fee_msat = $next_hops_fee_msat;
788 old_entry.hop_use_fee_msat = hop_use_fee_msat;
789 old_entry.total_fee_msat = total_fee_msat;
790 old_entry.node_id = $dest_node_id.clone();
791 old_entry.short_channel_id = $chan_id.clone();
792 old_entry.channel_features = $chan_features;
793 old_entry.fee_msat = 0; // This value will be later filled with hop_use_fee_msat of the following channel
794 old_entry.cltv_expiry_delta = $directional_info.cltv_expiry_delta as u32;
795 old_entry.channel_fees = $directional_info.fees;
796 old_entry.htlc_minimum_msat = $directional_info.htlc_minimum_msat;
797 old_entry.path_htlc_minimum_msat = path_htlc_minimum_msat;
798 old_entry.path_penalty_msat = path_penalty_msat;
799 #[cfg(any(test, feature = "fuzztarget"))]
801 old_entry.value_contribution_msat = value_contribution_msat;
803 did_add_update_path_to_src_node = true;
804 } else if old_entry.was_processed && new_cost < old_cost {
805 #[cfg(any(test, feature = "fuzztarget"))]
807 // If we're skipping processing a node which was previously
808 // processed even though we found another path to it with a
809 // cheaper fee, check that it was because the second path we
810 // found (which we are processing now) has a lower value
811 // contribution due to an HTLC minimum limit.
813 // e.g. take a graph with two paths from node 1 to node 2, one
814 // through channel A, and one through channel B. Channel A and
815 // B are both in the to-process heap, with their scores set by
816 // a higher htlc_minimum than fee.
817 // Channel A is processed first, and the channels onwards from
818 // node 1 are added to the to-process heap. Thereafter, we pop
819 // Channel B off of the heap, note that it has a much more
820 // restrictive htlc_maximum_msat, and recalculate the fees for
821 // all of node 1's channels using the new, reduced, amount.
823 // This would be bogus - we'd be selecting a higher-fee path
824 // with a lower htlc_maximum_msat instead of the one we'd
825 // already decided to use.
826 debug_assert!(path_htlc_minimum_msat < old_entry.path_htlc_minimum_msat);
828 value_contribution_msat + path_penalty_msat <
829 old_entry.value_contribution_msat + old_entry.path_penalty_msat
837 did_add_update_path_to_src_node
841 let empty_node_features = NodeFeatures::empty();
842 // Find ways (channels with destination) to reach a given node and store them
843 // in the corresponding data structures (routing graph etc).
844 // $fee_to_target_msat represents how much it costs to reach to this node from the payee,
845 // meaning how much will be paid in fees after this node (to the best of our knowledge).
846 // This data can later be helpful to optimize routing (pay lower fees).
847 macro_rules! add_entries_to_cheapest_to_target_node {
848 ( $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 ) => {
849 let skip_node = if let Some(elem) = dist.get_mut(&$node_id) {
850 let was_processed = elem.was_processed;
851 elem.was_processed = true;
854 // Entries are added to dist in add_entry!() when there is a channel from a node.
855 // Because there are no channels from payee, it will not have a dist entry at this point.
856 // If we're processing any other node, it is always be the result of a channel from it.
857 assert_eq!($node_id, payee_node_id);
862 if let Some(first_channels) = first_hop_targets.get(&$node_id) {
863 for (ref first_hop, ref features, ref outbound_capacity_msat, _) in first_channels {
864 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);
868 let features = if let Some(node_info) = $node.announcement_info.as_ref() {
874 if !features.requires_unknown_bits() {
875 for chan_id in $node.channels.iter() {
876 let chan = network_channels.get(chan_id).unwrap();
877 if !chan.features.requires_unknown_bits() {
878 if chan.node_one == $node_id {
879 // ie $node is one, ie next hop in A* is two, via the two_to_one channel
880 if first_hops.is_none() || chan.node_two != our_node_id {
881 if let Some(two_to_one) = chan.two_to_one.as_ref() {
882 if two_to_one.enabled {
883 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);
888 if first_hops.is_none() || chan.node_one != our_node_id{
889 if let Some(one_to_two) = chan.one_to_two.as_ref() {
890 if one_to_two.enabled {
891 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);
903 let mut payment_paths = Vec::<PaymentPath>::new();
905 // TODO: diversify by nodes (so that all paths aren't doomed if one node is offline).
906 'paths_collection: loop {
907 // For every new path, start from scratch, except
908 // bookkeeped_channels_liquidity_available_msat, which will improve
909 // the further iterations of path finding. Also don't erase first_hop_targets.
912 hit_minimum_limit = false;
914 // If first hop is a private channel and the only way to reach the payee, this is the only
915 // place where it could be added.
916 if let Some(first_channels) = first_hop_targets.get(&payee_node_id) {
917 for (ref first_hop, ref features, ref outbound_capacity_msat, _) in first_channels {
918 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);
919 log_trace!(logger, "{} direct route to payee via SCID {}", if added { "Added" } else { "Skipped" }, first_hop);
923 // Add the payee as a target, so that the payee-to-payer
924 // search algorithm knows what to start with.
925 match network_nodes.get(&payee_node_id) {
926 // The payee is not in our network graph, so nothing to add here.
927 // There is still a chance of reaching them via last_hops though,
928 // so don't yet fail the payment here.
929 // If not, targets.pop() will not even let us enter the loop in step 2.
932 add_entries_to_cheapest_to_target_node!(node, payee_node_id, 0, path_value_msat, 0, 0u64);
937 // If a caller provided us with last hops, add them to routing targets. Since this happens
938 // earlier than general path finding, they will be somewhat prioritized, although currently
939 // it matters only if the fees are exactly the same.
940 for route in last_hops.iter().filter(|route| !route.0.is_empty()) {
941 let first_hop_in_route = &(route.0)[0];
942 let have_hop_src_in_graph =
943 // Only add the hops in this route to our candidate set if either
944 // we have a direct channel to the first hop or the first hop is
945 // in the regular network graph.
946 first_hop_targets.get(&NodeId::from_pubkey(&first_hop_in_route.src_node_id)).is_some() ||
947 network_nodes.get(&NodeId::from_pubkey(&first_hop_in_route.src_node_id)).is_some();
948 if have_hop_src_in_graph {
949 // We start building the path from reverse, i.e., from payee
950 // to the first RouteHintHop in the path.
951 let hop_iter = route.0.iter().rev();
952 let prev_hop_iter = core::iter::once(payee).chain(
953 route.0.iter().skip(1).rev().map(|hop| &hop.src_node_id));
954 let mut hop_used = true;
955 let mut aggregate_next_hops_fee_msat: u64 = 0;
956 let mut aggregate_next_hops_path_htlc_minimum_msat: u64 = 0;
957 let mut aggregate_next_hops_path_penalty_msat: u64 = 0;
959 for (idx, (hop, prev_hop_id)) in hop_iter.zip(prev_hop_iter).enumerate() {
960 // BOLT 11 doesn't allow inclusion of features for the last hop hints, which
961 // really sucks, cause we're gonna need that eventually.
962 let hop_htlc_minimum_msat: u64 = hop.htlc_minimum_msat.unwrap_or(0);
964 let directional_info = DummyDirectionalChannelInfo {
965 cltv_expiry_delta: hop.cltv_expiry_delta as u32,
966 htlc_minimum_msat: hop_htlc_minimum_msat,
967 htlc_maximum_msat: hop.htlc_maximum_msat,
971 let reqd_channel_cap = if let Some (val) = final_value_msat.checked_add(match idx {
973 _ => aggregate_next_hops_fee_msat.checked_add(999).unwrap_or(u64::max_value())
974 }) { Some( val / 1000 ) } else { break; }; // converting from msat or breaking if max ~ infinity
976 let src_node_id = NodeId::from_pubkey(&hop.src_node_id);
977 let dest_node_id = NodeId::from_pubkey(&prev_hop_id);
978 aggregate_next_hops_path_penalty_msat = aggregate_next_hops_path_penalty_msat
979 .checked_add(scorer.channel_penalty_msat(hop.short_channel_id, &src_node_id, &dest_node_id))
980 .unwrap_or_else(|| u64::max_value());
982 // We assume that the recipient only included route hints for routes which had
983 // sufficient value to route `final_value_msat`. Note that in the case of "0-value"
984 // invoices where the invoice does not specify value this may not be the case, but
985 // better to include the hints than not.
986 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) {
987 // If this hop was not used then there is no use checking the preceding hops
988 // in the RouteHint. We can break by just searching for a direct channel between
989 // last checked hop and first_hop_targets
993 // Searching for a direct channel between last checked hop and first_hop_targets
994 if let Some(first_channels) = first_hop_targets.get(&NodeId::from_pubkey(&prev_hop_id)) {
995 for (ref first_hop, ref features, ref outbound_capacity_msat, _) in first_channels {
996 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);
1004 // In the next values of the iterator, the aggregate fees already reflects
1005 // the sum of value sent from payer (final_value_msat) and routing fees
1006 // for the last node in the RouteHint. We need to just add the fees to
1007 // route through the current node so that the preceeding node (next iteration)
1009 let hops_fee = compute_fees(aggregate_next_hops_fee_msat + final_value_msat, hop.fees)
1010 .map_or(None, |inc| inc.checked_add(aggregate_next_hops_fee_msat));
1011 aggregate_next_hops_fee_msat = if let Some(val) = hops_fee { val } else { break; };
1013 let hop_htlc_minimum_msat_inc = if let Some(val) = compute_fees(aggregate_next_hops_path_htlc_minimum_msat, hop.fees) { val } else { break; };
1014 let hops_path_htlc_minimum = aggregate_next_hops_path_htlc_minimum_msat
1015 .checked_add(hop_htlc_minimum_msat_inc);
1016 aggregate_next_hops_path_htlc_minimum_msat = if let Some(val) = hops_path_htlc_minimum { cmp::max(hop_htlc_minimum_msat, val) } else { break; };
1018 if idx == route.0.len() - 1 {
1019 // The last hop in this iterator is the first hop in
1020 // overall RouteHint.
1021 // If this hop connects to a node with which we have a direct channel,
1022 // ignore the network graph and, if the last hop was added, add our
1023 // direct channel to the candidate set.
1025 // Note that we *must* check if the last hop was added as `add_entry`
1026 // always assumes that the third argument is a node to which we have a
1028 if let Some(first_channels) = first_hop_targets.get(&NodeId::from_pubkey(&hop.src_node_id)) {
1029 for (ref first_hop, ref features, ref outbound_capacity_msat, _) in first_channels {
1030 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);
1038 log_trace!(logger, "Starting main path collection loop with {} nodes pre-filled from first/last hops.", targets.len());
1040 // At this point, targets are filled with the data from first and
1041 // last hops communicated by the caller, and the payment receiver.
1042 let mut found_new_path = false;
1045 // If this loop terminates due the exhaustion of targets, two situations are possible:
1046 // - not enough outgoing liquidity:
1047 // 0 < already_collected_value_msat < final_value_msat
1048 // - enough outgoing liquidity:
1049 // final_value_msat <= already_collected_value_msat < recommended_value_msat
1050 // Both these cases (and other cases except reaching recommended_value_msat) mean that
1051 // paths_collection will be stopped because found_new_path==false.
1052 // This is not necessarily a routing failure.
1053 'path_construction: while let Some(RouteGraphNode { node_id, lowest_fee_to_node, value_contribution_msat, path_htlc_minimum_msat, path_penalty_msat, .. }) = targets.pop() {
1055 // Since we're going payee-to-payer, hitting our node as a target means we should stop
1056 // traversing the graph and arrange the path out of what we found.
1057 if node_id == our_node_id {
1058 let mut new_entry = dist.remove(&our_node_id).unwrap();
1059 let mut ordered_hops = vec!((new_entry.clone(), NodeFeatures::empty()));
1062 let mut features_set = false;
1063 if let Some(first_channels) = first_hop_targets.get(&ordered_hops.last().unwrap().0.node_id) {
1064 for (scid, _, _, ref features) in first_channels {
1065 if *scid == ordered_hops.last().unwrap().0.short_channel_id {
1066 ordered_hops.last_mut().unwrap().1 = features.clone();
1067 features_set = true;
1073 if let Some(node) = network_nodes.get(&ordered_hops.last().unwrap().0.node_id) {
1074 if let Some(node_info) = node.announcement_info.as_ref() {
1075 ordered_hops.last_mut().unwrap().1 = node_info.features.clone();
1077 ordered_hops.last_mut().unwrap().1 = NodeFeatures::empty();
1080 // We should be able to fill in features for everything except the last
1081 // hop, if the last hop was provided via a BOLT 11 invoice (though we
1082 // should be able to extend it further as BOLT 11 does have feature
1083 // flags for the last hop node itself).
1084 assert!(ordered_hops.last().unwrap().0.node_id == payee_node_id);
1088 // Means we succesfully traversed from the payer to the payee, now
1089 // save this path for the payment route. Also, update the liquidity
1090 // remaining on the used hops, so that we take them into account
1091 // while looking for more paths.
1092 if ordered_hops.last().unwrap().0.node_id == payee_node_id {
1096 new_entry = match dist.remove(&ordered_hops.last().unwrap().0.node_id) {
1097 Some(payment_hop) => payment_hop,
1098 // We can't arrive at None because, if we ever add an entry to targets,
1099 // we also fill in the entry in dist (see add_entry!).
1100 None => unreachable!(),
1102 // We "propagate" the fees one hop backward (topologically) here,
1103 // so that fees paid for a HTLC forwarding on the current channel are
1104 // associated with the previous channel (where they will be subtracted).
1105 ordered_hops.last_mut().unwrap().0.fee_msat = new_entry.hop_use_fee_msat;
1106 ordered_hops.last_mut().unwrap().0.cltv_expiry_delta = new_entry.cltv_expiry_delta;
1107 ordered_hops.push((new_entry.clone(), NodeFeatures::empty()));
1109 ordered_hops.last_mut().unwrap().0.fee_msat = value_contribution_msat;
1110 ordered_hops.last_mut().unwrap().0.hop_use_fee_msat = 0;
1111 ordered_hops.last_mut().unwrap().0.cltv_expiry_delta = final_cltv;
1113 log_trace!(logger, "Found a path back to us from the target with {} hops contributing up to {} msat: {:?}",
1114 ordered_hops.len(), value_contribution_msat, ordered_hops);
1116 let mut payment_path = PaymentPath {hops: ordered_hops};
1118 // We could have possibly constructed a slightly inconsistent path: since we reduce
1119 // value being transferred along the way, we could have violated htlc_minimum_msat
1120 // on some channels we already passed (assuming dest->source direction). Here, we
1121 // recompute the fees again, so that if that's the case, we match the currently
1122 // underpaid htlc_minimum_msat with fees.
1123 payment_path.update_value_and_recompute_fees(cmp::min(value_contribution_msat, final_value_msat));
1125 // Since a path allows to transfer as much value as
1126 // the smallest channel it has ("bottleneck"), we should recompute
1127 // the fees so sender HTLC don't overpay fees when traversing
1128 // larger channels than the bottleneck. This may happen because
1129 // when we were selecting those channels we were not aware how much value
1130 // this path will transfer, and the relative fee for them
1131 // might have been computed considering a larger value.
1132 // Remember that we used these channels so that we don't rely
1133 // on the same liquidity in future paths.
1134 let mut prevented_redundant_path_selection = false;
1135 for (payment_hop, _) in payment_path.hops.iter() {
1136 let channel_liquidity_available_msat = bookkeeped_channels_liquidity_available_msat.get_mut(&payment_hop.short_channel_id).unwrap();
1137 let mut spent_on_hop_msat = value_contribution_msat;
1138 let next_hops_fee_msat = payment_hop.next_hops_fee_msat;
1139 spent_on_hop_msat += next_hops_fee_msat;
1140 if spent_on_hop_msat == *channel_liquidity_available_msat {
1141 // If this path used all of this channel's available liquidity, we know
1142 // this path will not be selected again in the next loop iteration.
1143 prevented_redundant_path_selection = true;
1145 *channel_liquidity_available_msat -= spent_on_hop_msat;
1147 if !prevented_redundant_path_selection {
1148 // If we weren't capped by hitting a liquidity limit on a channel in the path,
1149 // we'll probably end up picking the same path again on the next iteration.
1150 // Decrease the available liquidity of a hop in the middle of the path.
1151 let victim_scid = payment_path.hops[(payment_path.hops.len() - 1) / 2].0.short_channel_id;
1152 log_trace!(logger, "Disabling channel {} for future path building iterations to avoid duplicates.", victim_scid);
1153 let victim_liquidity = bookkeeped_channels_liquidity_available_msat.get_mut(&victim_scid).unwrap();
1154 *victim_liquidity = 0;
1157 // Track the total amount all our collected paths allow to send so that we:
1158 // - know when to stop looking for more paths
1159 // - know which of the hops are useless considering how much more sats we need
1160 // (contributes_sufficient_value)
1161 already_collected_value_msat += value_contribution_msat;
1163 payment_paths.push(payment_path);
1164 found_new_path = true;
1165 break 'path_construction;
1168 // If we found a path back to the payee, we shouldn't try to process it again. This is
1169 // the equivalent of the `elem.was_processed` check in
1170 // add_entries_to_cheapest_to_target_node!() (see comment there for more info).
1171 if node_id == payee_node_id { continue 'path_construction; }
1173 // Otherwise, since the current target node is not us,
1174 // keep "unrolling" the payment graph from payee to payer by
1175 // finding a way to reach the current target from the payer side.
1176 match network_nodes.get(&node_id) {
1179 add_entries_to_cheapest_to_target_node!(node, node_id, lowest_fee_to_node, value_contribution_msat, path_htlc_minimum_msat, path_penalty_msat);
1185 // If we don't support MPP, no use trying to gather more value ever.
1186 break 'paths_collection;
1190 // Stop either when the recommended value is reached or if no new path was found in this
1192 // In the latter case, making another path finding attempt won't help,
1193 // because we deterministically terminated the search due to low liquidity.
1194 if already_collected_value_msat >= recommended_value_msat || !found_new_path {
1195 log_trace!(logger, "Have now collected {} msat (seeking {} msat) in paths. Last path loop {} a new path.",
1196 already_collected_value_msat, recommended_value_msat, if found_new_path { "found" } else { "did not find" });
1197 break 'paths_collection;
1198 } else if found_new_path && already_collected_value_msat == final_value_msat && payment_paths.len() == 1 {
1199 // Further, if this was our first walk of the graph, and we weren't limited by an
1200 // htlc_minimum_msat, return immediately because this path should suffice. If we were
1201 // limited by an htlc_minimum_msat value, find another path with a higher value,
1202 // potentially allowing us to pay fees to meet the htlc_minimum on the new path while
1203 // still keeping a lower total fee than this path.
1204 if !hit_minimum_limit {
1205 log_trace!(logger, "Collected exactly our payment amount on the first pass, without hitting an htlc_minimum_msat limit, exiting.");
1206 break 'paths_collection;
1208 log_trace!(logger, "Collected our payment amount on the first pass, but running again to collect extra paths with a potentially higher limit.");
1209 path_value_msat = recommended_value_msat;
1214 if payment_paths.len() == 0 {
1215 return Err(LightningError{err: "Failed to find a path to the given destination".to_owned(), action: ErrorAction::IgnoreError});
1218 if already_collected_value_msat < final_value_msat {
1219 return Err(LightningError{err: "Failed to find a sufficient route to the given destination".to_owned(), action: ErrorAction::IgnoreError});
1222 // Sort by total fees and take the best paths.
1223 payment_paths.sort_by_key(|path| path.get_total_fee_paid_msat());
1224 if payment_paths.len() > 50 {
1225 payment_paths.truncate(50);
1228 // Draw multiple sufficient routes by randomly combining the selected paths.
1229 let mut drawn_routes = Vec::new();
1230 for i in 0..payment_paths.len() {
1231 let mut cur_route = Vec::<PaymentPath>::new();
1232 let mut aggregate_route_value_msat = 0;
1235 // TODO: real random shuffle
1236 // Currently just starts with i_th and goes up to i-1_th in a looped way.
1237 let cur_payment_paths = [&payment_paths[i..], &payment_paths[..i]].concat();
1240 for payment_path in cur_payment_paths {
1241 cur_route.push(payment_path.clone());
1242 aggregate_route_value_msat += payment_path.get_value_msat();
1243 if aggregate_route_value_msat > final_value_msat {
1244 // Last path likely overpaid. Substract it from the most expensive
1245 // (in terms of proportional fee) path in this route and recompute fees.
1246 // This might be not the most economically efficient way, but fewer paths
1247 // also makes routing more reliable.
1248 let mut overpaid_value_msat = aggregate_route_value_msat - final_value_msat;
1250 // First, drop some expensive low-value paths entirely if possible.
1251 // Sort by value so that we drop many really-low values first, since
1252 // fewer paths is better: the payment is less likely to fail.
1253 // TODO: this could also be optimized by also sorting by feerate_per_sat_routed,
1254 // so that the sender pays less fees overall. And also htlc_minimum_msat.
1255 cur_route.sort_by_key(|path| path.get_value_msat());
1256 // We should make sure that at least 1 path left.
1257 let mut paths_left = cur_route.len();
1258 cur_route.retain(|path| {
1259 if paths_left == 1 {
1262 let mut keep = true;
1263 let path_value_msat = path.get_value_msat();
1264 if path_value_msat <= overpaid_value_msat {
1266 overpaid_value_msat -= path_value_msat;
1272 if overpaid_value_msat == 0 {
1276 assert!(cur_route.len() > 0);
1279 // Now, substract the overpaid value from the most-expensive path.
1280 // TODO: this could also be optimized by also sorting by feerate_per_sat_routed,
1281 // so that the sender pays less fees overall. And also htlc_minimum_msat.
1282 cur_route.sort_by_key(|path| { path.hops.iter().map(|hop| hop.0.channel_fees.proportional_millionths as u64).sum::<u64>() });
1283 let expensive_payment_path = cur_route.first_mut().unwrap();
1284 // We already dropped all the small channels above, meaning all the
1285 // remaining channels are larger than remaining overpaid_value_msat.
1286 // Thus, this can't be negative.
1287 let expensive_path_new_value_msat = expensive_payment_path.get_value_msat() - overpaid_value_msat;
1288 expensive_payment_path.update_value_and_recompute_fees(expensive_path_new_value_msat);
1292 drawn_routes.push(cur_route);
1296 // Select the best route by lowest total fee.
1297 drawn_routes.sort_by_key(|paths| paths.iter().map(|path| path.get_total_fee_paid_msat()).sum::<u64>());
1298 let mut selected_paths = Vec::<Vec<Result<RouteHop, LightningError>>>::new();
1299 for payment_path in drawn_routes.first().unwrap() {
1300 selected_paths.push(payment_path.hops.iter().map(|(payment_hop, node_features)| {
1302 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)})?,
1303 node_features: node_features.clone(),
1304 short_channel_id: payment_hop.short_channel_id,
1305 channel_features: payment_hop.channel_features.clone(),
1306 fee_msat: payment_hop.fee_msat,
1307 cltv_expiry_delta: payment_hop.cltv_expiry_delta,
1312 if let Some(features) = &payee_features {
1313 for path in selected_paths.iter_mut() {
1314 if let Ok(route_hop) = path.last_mut().unwrap() {
1315 route_hop.node_features = features.to_context();
1320 let route = Route { paths: selected_paths.into_iter().map(|path| path.into_iter().collect()).collect::<Result<Vec<_>, _>>()? };
1321 log_info!(logger, "Got route to {}: {}", payee, log_route!(route));
1328 use routing::network_graph::{NetworkGraph, NetGraphMsgHandler, NodeId};
1329 use routing::router::{get_route, Route, RouteHint, RouteHintHop, RouteHop, RoutingFees};
1330 use routing::scorer::Scorer;
1331 use chain::transaction::OutPoint;
1332 use ln::features::{ChannelFeatures, InitFeatures, InvoiceFeatures, NodeFeatures};
1333 use ln::msgs::{ErrorAction, LightningError, OptionalField, UnsignedChannelAnnouncement, ChannelAnnouncement, RoutingMessageHandler,
1334 NodeAnnouncement, UnsignedNodeAnnouncement, ChannelUpdate, UnsignedChannelUpdate};
1335 use ln::channelmanager;
1336 use util::test_utils;
1337 use util::ser::Writeable;
1339 use bitcoin::hashes::sha256d::Hash as Sha256dHash;
1340 use bitcoin::hashes::Hash;
1341 use bitcoin::network::constants::Network;
1342 use bitcoin::blockdata::constants::genesis_block;
1343 use bitcoin::blockdata::script::Builder;
1344 use bitcoin::blockdata::opcodes;
1345 use bitcoin::blockdata::transaction::TxOut;
1349 use bitcoin::secp256k1::key::{PublicKey,SecretKey};
1350 use bitcoin::secp256k1::{Secp256k1, All};
1353 use sync::{self, Arc};
1355 fn get_channel_details(short_channel_id: Option<u64>, node_id: PublicKey,
1356 features: InitFeatures, outbound_capacity_msat: u64) -> channelmanager::ChannelDetails {
1357 channelmanager::ChannelDetails {
1358 channel_id: [0; 32],
1359 counterparty: channelmanager::ChannelCounterparty {
1362 unspendable_punishment_reserve: 0,
1363 forwarding_info: None,
1365 funding_txo: Some(OutPoint { txid: bitcoin::Txid::from_slice(&[0; 32]).unwrap(), index: 0 }),
1367 channel_value_satoshis: 0,
1369 outbound_capacity_msat,
1370 inbound_capacity_msat: 42,
1371 unspendable_punishment_reserve: None,
1372 confirmations_required: None,
1373 force_close_spend_delay: None,
1374 is_outbound: true, is_funding_locked: true,
1375 is_usable: true, is_public: true,
1379 // Using the same keys for LN and BTC ids
1381 net_graph_msg_handler: &NetGraphMsgHandler<Arc<test_utils::TestChainSource>, Arc<test_utils::TestLogger>>,
1382 secp_ctx: &Secp256k1<All>, node_1_privkey: &SecretKey, node_2_privkey: &SecretKey, features: ChannelFeatures, short_channel_id: u64
1384 let node_id_1 = PublicKey::from_secret_key(&secp_ctx, node_1_privkey);
1385 let node_id_2 = PublicKey::from_secret_key(&secp_ctx, node_2_privkey);
1387 let unsigned_announcement = UnsignedChannelAnnouncement {
1389 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1393 bitcoin_key_1: node_id_1,
1394 bitcoin_key_2: node_id_2,
1395 excess_data: Vec::new(),
1398 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1399 let valid_announcement = ChannelAnnouncement {
1400 node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
1401 node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
1402 bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
1403 bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
1404 contents: unsigned_announcement.clone(),
1406 match net_graph_msg_handler.handle_channel_announcement(&valid_announcement) {
1407 Ok(res) => assert!(res),
1413 net_graph_msg_handler: &NetGraphMsgHandler<Arc<test_utils::TestChainSource>, Arc<test_utils::TestLogger>>,
1414 secp_ctx: &Secp256k1<All>, node_privkey: &SecretKey, update: UnsignedChannelUpdate
1416 let msghash = hash_to_message!(&Sha256dHash::hash(&update.encode()[..])[..]);
1417 let valid_channel_update = ChannelUpdate {
1418 signature: secp_ctx.sign(&msghash, node_privkey),
1419 contents: update.clone()
1422 match net_graph_msg_handler.handle_channel_update(&valid_channel_update) {
1423 Ok(res) => assert!(res),
1428 fn add_or_update_node(
1429 net_graph_msg_handler: &NetGraphMsgHandler<Arc<test_utils::TestChainSource>, Arc<test_utils::TestLogger>>,
1430 secp_ctx: &Secp256k1<All>, node_privkey: &SecretKey, features: NodeFeatures, timestamp: u32
1432 let node_id = PublicKey::from_secret_key(&secp_ctx, node_privkey);
1433 let unsigned_announcement = UnsignedNodeAnnouncement {
1439 addresses: Vec::new(),
1440 excess_address_data: Vec::new(),
1441 excess_data: Vec::new(),
1443 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1444 let valid_announcement = NodeAnnouncement {
1445 signature: secp_ctx.sign(&msghash, node_privkey),
1446 contents: unsigned_announcement.clone()
1449 match net_graph_msg_handler.handle_node_announcement(&valid_announcement) {
1455 fn get_nodes(secp_ctx: &Secp256k1<All>) -> (SecretKey, PublicKey, Vec<SecretKey>, Vec<PublicKey>) {
1456 let privkeys: Vec<SecretKey> = (2..10).map(|i| {
1457 SecretKey::from_slice(&hex::decode(format!("{:02}", i).repeat(32)).unwrap()[..]).unwrap()
1460 let pubkeys = privkeys.iter().map(|secret| PublicKey::from_secret_key(&secp_ctx, secret)).collect();
1462 let our_privkey = SecretKey::from_slice(&hex::decode("01".repeat(32)).unwrap()[..]).unwrap();
1463 let our_id = PublicKey::from_secret_key(&secp_ctx, &our_privkey);
1465 (our_privkey, our_id, privkeys, pubkeys)
1468 fn id_to_feature_flags(id: u8) -> Vec<u8> {
1469 // Set the feature flags to the id'th odd (ie non-required) feature bit so that we can
1470 // test for it later.
1471 let idx = (id - 1) * 2 + 1;
1473 vec![1 << (idx - 8*3), 0, 0, 0]
1474 } else if idx > 8*2 {
1475 vec![1 << (idx - 8*2), 0, 0]
1476 } else if idx > 8*1 {
1477 vec![1 << (idx - 8*1), 0]
1483 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>) {
1484 let secp_ctx = Secp256k1::new();
1485 let logger = Arc::new(test_utils::TestLogger::new());
1486 let chain_monitor = Arc::new(test_utils::TestChainSource::new(Network::Testnet));
1487 let network_graph = NetworkGraph::new(genesis_block(Network::Testnet).header.block_hash());
1488 let net_graph_msg_handler = NetGraphMsgHandler::new(network_graph, None, Arc::clone(&logger));
1489 // Build network from our_id to node6:
1491 // -1(1)2- node0 -1(3)2-
1493 // our_id -1(12)2- node7 -1(13)2--- node2
1495 // -1(2)2- node1 -1(4)2-
1498 // chan1 1-to-2: disabled
1499 // chan1 2-to-1: enabled, 0 fee
1501 // chan2 1-to-2: enabled, ignored fee
1502 // chan2 2-to-1: enabled, 0 fee
1504 // chan3 1-to-2: enabled, 0 fee
1505 // chan3 2-to-1: enabled, 100 msat fee
1507 // chan4 1-to-2: enabled, 100% fee
1508 // chan4 2-to-1: enabled, 0 fee
1510 // chan12 1-to-2: enabled, ignored fee
1511 // chan12 2-to-1: enabled, 0 fee
1513 // chan13 1-to-2: enabled, 200% fee
1514 // chan13 2-to-1: enabled, 0 fee
1517 // -1(5)2- node3 -1(8)2--
1521 // node2--1(6)2- node4 -1(9)2--- node6 (not in global route map)
1523 // -1(7)2- node5 -1(10)2-
1525 // Channels 5, 8, 9 and 10 are private channels.
1527 // chan5 1-to-2: enabled, 100 msat fee
1528 // chan5 2-to-1: enabled, 0 fee
1530 // chan6 1-to-2: enabled, 0 fee
1531 // chan6 2-to-1: enabled, 0 fee
1533 // chan7 1-to-2: enabled, 100% fee
1534 // chan7 2-to-1: enabled, 0 fee
1536 // chan8 1-to-2: enabled, variable fee (0 then 1000 msat)
1537 // chan8 2-to-1: enabled, 0 fee
1539 // chan9 1-to-2: enabled, 1001 msat fee
1540 // chan9 2-to-1: enabled, 0 fee
1542 // chan10 1-to-2: enabled, 0 fee
1543 // chan10 2-to-1: enabled, 0 fee
1545 // chan11 1-to-2: enabled, 0 fee
1546 // chan11 2-to-1: enabled, 0 fee
1548 let (our_privkey, _, privkeys, _) = get_nodes(&secp_ctx);
1550 add_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, &privkeys[0], ChannelFeatures::from_le_bytes(id_to_feature_flags(1)), 1);
1551 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
1552 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1553 short_channel_id: 1,
1556 cltv_expiry_delta: 0,
1557 htlc_minimum_msat: 0,
1558 htlc_maximum_msat: OptionalField::Absent,
1560 fee_proportional_millionths: 0,
1561 excess_data: Vec::new()
1564 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[0], NodeFeatures::from_le_bytes(id_to_feature_flags(1)), 0);
1566 add_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, &privkeys[1], ChannelFeatures::from_le_bytes(id_to_feature_flags(2)), 2);
1567 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
1568 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1569 short_channel_id: 2,
1572 cltv_expiry_delta: u16::max_value(),
1573 htlc_minimum_msat: 0,
1574 htlc_maximum_msat: OptionalField::Absent,
1575 fee_base_msat: u32::max_value(),
1576 fee_proportional_millionths: u32::max_value(),
1577 excess_data: Vec::new()
1579 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
1580 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1581 short_channel_id: 2,
1584 cltv_expiry_delta: 0,
1585 htlc_minimum_msat: 0,
1586 htlc_maximum_msat: OptionalField::Absent,
1588 fee_proportional_millionths: 0,
1589 excess_data: Vec::new()
1592 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[1], NodeFeatures::from_le_bytes(id_to_feature_flags(2)), 0);
1594 add_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, &privkeys[7], ChannelFeatures::from_le_bytes(id_to_feature_flags(12)), 12);
1595 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
1596 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1597 short_channel_id: 12,
1600 cltv_expiry_delta: u16::max_value(),
1601 htlc_minimum_msat: 0,
1602 htlc_maximum_msat: OptionalField::Absent,
1603 fee_base_msat: u32::max_value(),
1604 fee_proportional_millionths: u32::max_value(),
1605 excess_data: Vec::new()
1607 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
1608 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1609 short_channel_id: 12,
1612 cltv_expiry_delta: 0,
1613 htlc_minimum_msat: 0,
1614 htlc_maximum_msat: OptionalField::Absent,
1616 fee_proportional_millionths: 0,
1617 excess_data: Vec::new()
1620 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[7], NodeFeatures::from_le_bytes(id_to_feature_flags(8)), 0);
1622 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], &privkeys[2], ChannelFeatures::from_le_bytes(id_to_feature_flags(3)), 3);
1623 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
1624 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1625 short_channel_id: 3,
1628 cltv_expiry_delta: (3 << 8) | 1,
1629 htlc_minimum_msat: 0,
1630 htlc_maximum_msat: OptionalField::Absent,
1632 fee_proportional_millionths: 0,
1633 excess_data: Vec::new()
1635 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
1636 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1637 short_channel_id: 3,
1640 cltv_expiry_delta: (3 << 8) | 2,
1641 htlc_minimum_msat: 0,
1642 htlc_maximum_msat: OptionalField::Absent,
1644 fee_proportional_millionths: 0,
1645 excess_data: Vec::new()
1648 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], &privkeys[2], ChannelFeatures::from_le_bytes(id_to_feature_flags(4)), 4);
1649 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
1650 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1651 short_channel_id: 4,
1654 cltv_expiry_delta: (4 << 8) | 1,
1655 htlc_minimum_msat: 0,
1656 htlc_maximum_msat: OptionalField::Absent,
1658 fee_proportional_millionths: 1000000,
1659 excess_data: Vec::new()
1661 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
1662 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1663 short_channel_id: 4,
1666 cltv_expiry_delta: (4 << 8) | 2,
1667 htlc_minimum_msat: 0,
1668 htlc_maximum_msat: OptionalField::Absent,
1670 fee_proportional_millionths: 0,
1671 excess_data: Vec::new()
1674 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], &privkeys[2], ChannelFeatures::from_le_bytes(id_to_feature_flags(13)), 13);
1675 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
1676 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1677 short_channel_id: 13,
1680 cltv_expiry_delta: (13 << 8) | 1,
1681 htlc_minimum_msat: 0,
1682 htlc_maximum_msat: OptionalField::Absent,
1684 fee_proportional_millionths: 2000000,
1685 excess_data: Vec::new()
1687 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
1688 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1689 short_channel_id: 13,
1692 cltv_expiry_delta: (13 << 8) | 2,
1693 htlc_minimum_msat: 0,
1694 htlc_maximum_msat: OptionalField::Absent,
1696 fee_proportional_millionths: 0,
1697 excess_data: Vec::new()
1700 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[2], NodeFeatures::from_le_bytes(id_to_feature_flags(3)), 0);
1702 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], &privkeys[4], ChannelFeatures::from_le_bytes(id_to_feature_flags(6)), 6);
1703 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
1704 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1705 short_channel_id: 6,
1708 cltv_expiry_delta: (6 << 8) | 1,
1709 htlc_minimum_msat: 0,
1710 htlc_maximum_msat: OptionalField::Absent,
1712 fee_proportional_millionths: 0,
1713 excess_data: Vec::new()
1715 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
1716 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1717 short_channel_id: 6,
1720 cltv_expiry_delta: (6 << 8) | 2,
1721 htlc_minimum_msat: 0,
1722 htlc_maximum_msat: OptionalField::Absent,
1724 fee_proportional_millionths: 0,
1725 excess_data: Vec::new(),
1728 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(11)), 11);
1729 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
1730 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1731 short_channel_id: 11,
1734 cltv_expiry_delta: (11 << 8) | 1,
1735 htlc_minimum_msat: 0,
1736 htlc_maximum_msat: OptionalField::Absent,
1738 fee_proportional_millionths: 0,
1739 excess_data: Vec::new()
1741 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[3], UnsignedChannelUpdate {
1742 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1743 short_channel_id: 11,
1746 cltv_expiry_delta: (11 << 8) | 2,
1747 htlc_minimum_msat: 0,
1748 htlc_maximum_msat: OptionalField::Absent,
1750 fee_proportional_millionths: 0,
1751 excess_data: Vec::new()
1754 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[4], NodeFeatures::from_le_bytes(id_to_feature_flags(5)), 0);
1756 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[3], NodeFeatures::from_le_bytes(id_to_feature_flags(4)), 0);
1758 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], &privkeys[5], ChannelFeatures::from_le_bytes(id_to_feature_flags(7)), 7);
1759 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
1760 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1761 short_channel_id: 7,
1764 cltv_expiry_delta: (7 << 8) | 1,
1765 htlc_minimum_msat: 0,
1766 htlc_maximum_msat: OptionalField::Absent,
1768 fee_proportional_millionths: 1000000,
1769 excess_data: Vec::new()
1771 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[5], UnsignedChannelUpdate {
1772 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1773 short_channel_id: 7,
1776 cltv_expiry_delta: (7 << 8) | 2,
1777 htlc_minimum_msat: 0,
1778 htlc_maximum_msat: OptionalField::Absent,
1780 fee_proportional_millionths: 0,
1781 excess_data: Vec::new()
1784 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[5], NodeFeatures::from_le_bytes(id_to_feature_flags(6)), 0);
1786 (secp_ctx, net_graph_msg_handler, chain_monitor, logger)
1790 fn simple_route_test() {
1791 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
1792 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
1793 let scorer = Scorer::new(0);
1795 // Simple route to 2 via 1
1797 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id, &net_graph_msg_handler.network_graph, &nodes[2], None, None, &Vec::new(), 0, 42, Arc::clone(&logger), &scorer) {
1798 assert_eq!(err, "Cannot send a payment of 0 msat");
1799 } else { panic!(); }
1801 let route = get_route(&our_id, &net_graph_msg_handler.network_graph, &nodes[2], None, None, &Vec::new(), 100, 42, Arc::clone(&logger), &scorer).unwrap();
1802 assert_eq!(route.paths[0].len(), 2);
1804 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
1805 assert_eq!(route.paths[0][0].short_channel_id, 2);
1806 assert_eq!(route.paths[0][0].fee_msat, 100);
1807 assert_eq!(route.paths[0][0].cltv_expiry_delta, (4 << 8) | 1);
1808 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
1809 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
1811 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
1812 assert_eq!(route.paths[0][1].short_channel_id, 4);
1813 assert_eq!(route.paths[0][1].fee_msat, 100);
1814 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
1815 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
1816 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
1820 fn invalid_first_hop_test() {
1821 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
1822 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
1823 let scorer = Scorer::new(0);
1825 // Simple route to 2 via 1
1827 let our_chans = vec![get_channel_details(Some(2), our_id, InitFeatures::from_le_bytes(vec![0b11]), 100000)];
1829 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id, &net_graph_msg_handler.network_graph, &nodes[2], None, Some(&our_chans.iter().collect::<Vec<_>>()), &Vec::new(), 100, 42, Arc::clone(&logger), &scorer) {
1830 assert_eq!(err, "First hop cannot have our_node_pubkey as a destination.");
1831 } else { panic!(); }
1833 let route = get_route(&our_id, &net_graph_msg_handler.network_graph, &nodes[2], None, None, &Vec::new(), 100, 42, Arc::clone(&logger), &scorer).unwrap();
1834 assert_eq!(route.paths[0].len(), 2);
1838 fn htlc_minimum_test() {
1839 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
1840 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
1841 let scorer = Scorer::new(0);
1843 // Simple route to 2 via 1
1845 // Disable other paths
1846 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
1847 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1848 short_channel_id: 12,
1850 flags: 2, // to disable
1851 cltv_expiry_delta: 0,
1852 htlc_minimum_msat: 0,
1853 htlc_maximum_msat: OptionalField::Absent,
1855 fee_proportional_millionths: 0,
1856 excess_data: Vec::new()
1858 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
1859 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1860 short_channel_id: 3,
1862 flags: 2, // to disable
1863 cltv_expiry_delta: 0,
1864 htlc_minimum_msat: 0,
1865 htlc_maximum_msat: OptionalField::Absent,
1867 fee_proportional_millionths: 0,
1868 excess_data: Vec::new()
1870 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
1871 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1872 short_channel_id: 13,
1874 flags: 2, // to disable
1875 cltv_expiry_delta: 0,
1876 htlc_minimum_msat: 0,
1877 htlc_maximum_msat: OptionalField::Absent,
1879 fee_proportional_millionths: 0,
1880 excess_data: Vec::new()
1882 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
1883 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1884 short_channel_id: 6,
1886 flags: 2, // to disable
1887 cltv_expiry_delta: 0,
1888 htlc_minimum_msat: 0,
1889 htlc_maximum_msat: OptionalField::Absent,
1891 fee_proportional_millionths: 0,
1892 excess_data: Vec::new()
1894 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
1895 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1896 short_channel_id: 7,
1898 flags: 2, // to disable
1899 cltv_expiry_delta: 0,
1900 htlc_minimum_msat: 0,
1901 htlc_maximum_msat: OptionalField::Absent,
1903 fee_proportional_millionths: 0,
1904 excess_data: Vec::new()
1907 // Check against amount_to_transfer_over_msat.
1908 // Set minimal HTLC of 200_000_000 msat.
1909 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
1910 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1911 short_channel_id: 2,
1914 cltv_expiry_delta: 0,
1915 htlc_minimum_msat: 200_000_000,
1916 htlc_maximum_msat: OptionalField::Absent,
1918 fee_proportional_millionths: 0,
1919 excess_data: Vec::new()
1922 // Second hop only allows to forward 199_999_999 at most, thus not allowing the first hop to
1924 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
1925 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1926 short_channel_id: 4,
1929 cltv_expiry_delta: 0,
1930 htlc_minimum_msat: 0,
1931 htlc_maximum_msat: OptionalField::Present(199_999_999),
1933 fee_proportional_millionths: 0,
1934 excess_data: Vec::new()
1937 // Not possible to send 199_999_999, because the minimum on channel=2 is 200_000_000.
1938 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id, &net_graph_msg_handler.network_graph, &nodes[2], None, None, &Vec::new(), 199_999_999, 42, Arc::clone(&logger), &scorer) {
1939 assert_eq!(err, "Failed to find a path to the given destination");
1940 } else { panic!(); }
1942 // Lift the restriction on the first hop.
1943 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
1944 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1945 short_channel_id: 2,
1948 cltv_expiry_delta: 0,
1949 htlc_minimum_msat: 0,
1950 htlc_maximum_msat: OptionalField::Absent,
1952 fee_proportional_millionths: 0,
1953 excess_data: Vec::new()
1956 // A payment above the minimum should pass
1957 let route = get_route(&our_id, &net_graph_msg_handler.network_graph, &nodes[2], None, None, &Vec::new(), 199_999_999, 42, Arc::clone(&logger), &scorer).unwrap();
1958 assert_eq!(route.paths[0].len(), 2);
1962 fn htlc_minimum_overpay_test() {
1963 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
1964 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
1965 let scorer = Scorer::new(0);
1967 // A route to node#2 via two paths.
1968 // One path allows transferring 35-40 sats, another one also allows 35-40 sats.
1969 // Thus, they can't send 60 without overpaying.
1970 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
1971 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1972 short_channel_id: 2,
1975 cltv_expiry_delta: 0,
1976 htlc_minimum_msat: 35_000,
1977 htlc_maximum_msat: OptionalField::Present(40_000),
1979 fee_proportional_millionths: 0,
1980 excess_data: Vec::new()
1982 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
1983 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1984 short_channel_id: 12,
1987 cltv_expiry_delta: 0,
1988 htlc_minimum_msat: 35_000,
1989 htlc_maximum_msat: OptionalField::Present(40_000),
1991 fee_proportional_millionths: 0,
1992 excess_data: Vec::new()
1996 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
1997 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1998 short_channel_id: 13,
2001 cltv_expiry_delta: 0,
2002 htlc_minimum_msat: 0,
2003 htlc_maximum_msat: OptionalField::Absent,
2005 fee_proportional_millionths: 0,
2006 excess_data: Vec::new()
2008 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
2009 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2010 short_channel_id: 4,
2013 cltv_expiry_delta: 0,
2014 htlc_minimum_msat: 0,
2015 htlc_maximum_msat: OptionalField::Absent,
2017 fee_proportional_millionths: 0,
2018 excess_data: Vec::new()
2021 // Disable other paths
2022 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2023 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2024 short_channel_id: 1,
2026 flags: 2, // to disable
2027 cltv_expiry_delta: 0,
2028 htlc_minimum_msat: 0,
2029 htlc_maximum_msat: OptionalField::Absent,
2031 fee_proportional_millionths: 0,
2032 excess_data: Vec::new()
2035 let route = get_route(&our_id, &net_graph_msg_handler.network_graph, &nodes[2],
2036 Some(InvoiceFeatures::known()), None, &Vec::new(), 60_000, 42, Arc::clone(&logger), &scorer).unwrap();
2037 // Overpay fees to hit htlc_minimum_msat.
2038 let overpaid_fees = route.paths[0][0].fee_msat + route.paths[1][0].fee_msat;
2039 // TODO: this could be better balanced to overpay 10k and not 15k.
2040 assert_eq!(overpaid_fees, 15_000);
2042 // Now, test that if there are 2 paths, a "cheaper" by fee path wouldn't be prioritized
2043 // while taking even more fee to match htlc_minimum_msat.
2044 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2045 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2046 short_channel_id: 12,
2049 cltv_expiry_delta: 0,
2050 htlc_minimum_msat: 65_000,
2051 htlc_maximum_msat: OptionalField::Present(80_000),
2053 fee_proportional_millionths: 0,
2054 excess_data: Vec::new()
2056 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2057 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2058 short_channel_id: 2,
2061 cltv_expiry_delta: 0,
2062 htlc_minimum_msat: 0,
2063 htlc_maximum_msat: OptionalField::Absent,
2065 fee_proportional_millionths: 0,
2066 excess_data: Vec::new()
2068 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
2069 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2070 short_channel_id: 4,
2073 cltv_expiry_delta: 0,
2074 htlc_minimum_msat: 0,
2075 htlc_maximum_msat: OptionalField::Absent,
2077 fee_proportional_millionths: 100_000,
2078 excess_data: Vec::new()
2081 let route = get_route(&our_id, &net_graph_msg_handler.network_graph, &nodes[2],
2082 Some(InvoiceFeatures::known()), None, &Vec::new(), 60_000, 42, Arc::clone(&logger), &scorer).unwrap();
2083 // Fine to overpay for htlc_minimum_msat if it allows us to save fee.
2084 assert_eq!(route.paths.len(), 1);
2085 assert_eq!(route.paths[0][0].short_channel_id, 12);
2086 let fees = route.paths[0][0].fee_msat;
2087 assert_eq!(fees, 5_000);
2089 let route = get_route(&our_id, &net_graph_msg_handler.network_graph, &nodes[2],
2090 Some(InvoiceFeatures::known()), None, &Vec::new(), 50_000, 42, Arc::clone(&logger), &scorer).unwrap();
2091 // Not fine to overpay for htlc_minimum_msat if it requires paying more than fee on
2092 // the other channel.
2093 assert_eq!(route.paths.len(), 1);
2094 assert_eq!(route.paths[0][0].short_channel_id, 2);
2095 let fees = route.paths[0][0].fee_msat;
2096 assert_eq!(fees, 5_000);
2100 fn disable_channels_test() {
2101 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
2102 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
2103 let scorer = Scorer::new(0);
2105 // // Disable channels 4 and 12 by flags=2
2106 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
2107 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2108 short_channel_id: 4,
2110 flags: 2, // to disable
2111 cltv_expiry_delta: 0,
2112 htlc_minimum_msat: 0,
2113 htlc_maximum_msat: OptionalField::Absent,
2115 fee_proportional_millionths: 0,
2116 excess_data: Vec::new()
2118 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2119 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2120 short_channel_id: 12,
2122 flags: 2, // to disable
2123 cltv_expiry_delta: 0,
2124 htlc_minimum_msat: 0,
2125 htlc_maximum_msat: OptionalField::Absent,
2127 fee_proportional_millionths: 0,
2128 excess_data: Vec::new()
2131 // If all the channels require some features we don't understand, route should fail
2132 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id, &net_graph_msg_handler.network_graph, &nodes[2], None, None, &Vec::new(), 100, 42, Arc::clone(&logger), &scorer) {
2133 assert_eq!(err, "Failed to find a path to the given destination");
2134 } else { panic!(); }
2136 // If we specify a channel to node7, that overrides our local channel view and that gets used
2137 let our_chans = vec![get_channel_details(Some(42), nodes[7].clone(), InitFeatures::from_le_bytes(vec![0b11]), 250_000_000)];
2138 let route = get_route(&our_id, &net_graph_msg_handler.network_graph, &nodes[2], None, Some(&our_chans.iter().collect::<Vec<_>>()), &Vec::new(), 100, 42, Arc::clone(&logger), &scorer).unwrap();
2139 assert_eq!(route.paths[0].len(), 2);
2141 assert_eq!(route.paths[0][0].pubkey, nodes[7]);
2142 assert_eq!(route.paths[0][0].short_channel_id, 42);
2143 assert_eq!(route.paths[0][0].fee_msat, 200);
2144 assert_eq!(route.paths[0][0].cltv_expiry_delta, (13 << 8) | 1);
2145 assert_eq!(route.paths[0][0].node_features.le_flags(), &vec![0b11]); // it should also override our view of their features
2146 assert_eq!(route.paths[0][0].channel_features.le_flags(), &Vec::<u8>::new()); // No feature flags will meet the relevant-to-channel conversion
2148 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2149 assert_eq!(route.paths[0][1].short_channel_id, 13);
2150 assert_eq!(route.paths[0][1].fee_msat, 100);
2151 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
2152 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2153 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(13));
2157 fn disable_node_test() {
2158 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
2159 let (_, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
2160 let scorer = Scorer::new(0);
2162 // Disable nodes 1, 2, and 8 by requiring unknown feature bits
2163 let unknown_features = NodeFeatures::known().set_unknown_feature_required();
2164 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[0], unknown_features.clone(), 1);
2165 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[1], unknown_features.clone(), 1);
2166 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[7], unknown_features.clone(), 1);
2168 // If all nodes require some features we don't understand, route should fail
2169 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id, &net_graph_msg_handler.network_graph, &nodes[2], None, None, &Vec::new(), 100, 42, Arc::clone(&logger), &scorer) {
2170 assert_eq!(err, "Failed to find a path to the given destination");
2171 } else { panic!(); }
2173 // If we specify a channel to node7, that overrides our local channel view and that gets used
2174 let our_chans = vec![get_channel_details(Some(42), nodes[7].clone(), InitFeatures::from_le_bytes(vec![0b11]), 250_000_000)];
2175 let route = get_route(&our_id, &net_graph_msg_handler.network_graph, &nodes[2], None, Some(&our_chans.iter().collect::<Vec<_>>()), &Vec::new(), 100, 42, Arc::clone(&logger), &scorer).unwrap();
2176 assert_eq!(route.paths[0].len(), 2);
2178 assert_eq!(route.paths[0][0].pubkey, nodes[7]);
2179 assert_eq!(route.paths[0][0].short_channel_id, 42);
2180 assert_eq!(route.paths[0][0].fee_msat, 200);
2181 assert_eq!(route.paths[0][0].cltv_expiry_delta, (13 << 8) | 1);
2182 assert_eq!(route.paths[0][0].node_features.le_flags(), &vec![0b11]); // it should also override our view of their features
2183 assert_eq!(route.paths[0][0].channel_features.le_flags(), &Vec::<u8>::new()); // No feature flags will meet the relevant-to-channel conversion
2185 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2186 assert_eq!(route.paths[0][1].short_channel_id, 13);
2187 assert_eq!(route.paths[0][1].fee_msat, 100);
2188 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
2189 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2190 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(13));
2192 // Note that we don't test disabling node 3 and failing to route to it, as we (somewhat
2193 // naively) assume that the user checked the feature bits on the invoice, which override
2194 // the node_announcement.
2198 fn our_chans_test() {
2199 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
2200 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
2201 let scorer = Scorer::new(0);
2203 // Route to 1 via 2 and 3 because our channel to 1 is disabled
2204 let route = get_route(&our_id, &net_graph_msg_handler.network_graph, &nodes[0], None, None, &Vec::new(), 100, 42, Arc::clone(&logger), &scorer).unwrap();
2205 assert_eq!(route.paths[0].len(), 3);
2207 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
2208 assert_eq!(route.paths[0][0].short_channel_id, 2);
2209 assert_eq!(route.paths[0][0].fee_msat, 200);
2210 assert_eq!(route.paths[0][0].cltv_expiry_delta, (4 << 8) | 1);
2211 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
2212 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
2214 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2215 assert_eq!(route.paths[0][1].short_channel_id, 4);
2216 assert_eq!(route.paths[0][1].fee_msat, 100);
2217 assert_eq!(route.paths[0][1].cltv_expiry_delta, (3 << 8) | 2);
2218 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2219 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
2221 assert_eq!(route.paths[0][2].pubkey, nodes[0]);
2222 assert_eq!(route.paths[0][2].short_channel_id, 3);
2223 assert_eq!(route.paths[0][2].fee_msat, 100);
2224 assert_eq!(route.paths[0][2].cltv_expiry_delta, 42);
2225 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(1));
2226 assert_eq!(route.paths[0][2].channel_features.le_flags(), &id_to_feature_flags(3));
2228 // If we specify a channel to node7, that overrides our local channel view and that gets used
2229 let our_chans = vec![get_channel_details(Some(42), nodes[7].clone(), InitFeatures::from_le_bytes(vec![0b11]), 250_000_000)];
2230 let route = get_route(&our_id, &net_graph_msg_handler.network_graph, &nodes[2], None, Some(&our_chans.iter().collect::<Vec<_>>()), &Vec::new(), 100, 42, Arc::clone(&logger), &scorer).unwrap();
2231 assert_eq!(route.paths[0].len(), 2);
2233 assert_eq!(route.paths[0][0].pubkey, nodes[7]);
2234 assert_eq!(route.paths[0][0].short_channel_id, 42);
2235 assert_eq!(route.paths[0][0].fee_msat, 200);
2236 assert_eq!(route.paths[0][0].cltv_expiry_delta, (13 << 8) | 1);
2237 assert_eq!(route.paths[0][0].node_features.le_flags(), &vec![0b11]);
2238 assert_eq!(route.paths[0][0].channel_features.le_flags(), &Vec::<u8>::new()); // No feature flags will meet the relevant-to-channel conversion
2240 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2241 assert_eq!(route.paths[0][1].short_channel_id, 13);
2242 assert_eq!(route.paths[0][1].fee_msat, 100);
2243 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
2244 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2245 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(13));
2248 fn last_hops(nodes: &Vec<PublicKey>) -> Vec<RouteHint> {
2249 let zero_fees = RoutingFees {
2251 proportional_millionths: 0,
2253 vec![RouteHint(vec![RouteHintHop {
2254 src_node_id: nodes[3],
2255 short_channel_id: 8,
2257 cltv_expiry_delta: (8 << 8) | 1,
2258 htlc_minimum_msat: None,
2259 htlc_maximum_msat: None,
2261 ]), RouteHint(vec![RouteHintHop {
2262 src_node_id: nodes[4],
2263 short_channel_id: 9,
2266 proportional_millionths: 0,
2268 cltv_expiry_delta: (9 << 8) | 1,
2269 htlc_minimum_msat: None,
2270 htlc_maximum_msat: None,
2271 }]), RouteHint(vec![RouteHintHop {
2272 src_node_id: nodes[5],
2273 short_channel_id: 10,
2275 cltv_expiry_delta: (10 << 8) | 1,
2276 htlc_minimum_msat: None,
2277 htlc_maximum_msat: None,
2281 fn last_hops_multi_private_channels(nodes: &Vec<PublicKey>) -> Vec<RouteHint> {
2282 let zero_fees = RoutingFees {
2284 proportional_millionths: 0,
2286 vec![RouteHint(vec![RouteHintHop {
2287 src_node_id: nodes[2],
2288 short_channel_id: 5,
2291 proportional_millionths: 0,
2293 cltv_expiry_delta: (5 << 8) | 1,
2294 htlc_minimum_msat: None,
2295 htlc_maximum_msat: None,
2297 src_node_id: nodes[3],
2298 short_channel_id: 8,
2300 cltv_expiry_delta: (8 << 8) | 1,
2301 htlc_minimum_msat: None,
2302 htlc_maximum_msat: None,
2304 ]), RouteHint(vec![RouteHintHop {
2305 src_node_id: nodes[4],
2306 short_channel_id: 9,
2309 proportional_millionths: 0,
2311 cltv_expiry_delta: (9 << 8) | 1,
2312 htlc_minimum_msat: None,
2313 htlc_maximum_msat: None,
2314 }]), RouteHint(vec![RouteHintHop {
2315 src_node_id: nodes[5],
2316 short_channel_id: 10,
2318 cltv_expiry_delta: (10 << 8) | 1,
2319 htlc_minimum_msat: None,
2320 htlc_maximum_msat: None,
2325 fn partial_route_hint_test() {
2326 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
2327 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
2328 let scorer = Scorer::new(0);
2330 // Simple test across 2, 3, 5, and 4 via a last_hop channel
2331 // Tests the behaviour when the RouteHint contains a suboptimal hop.
2332 // RouteHint may be partially used by the algo to build the best path.
2334 // First check that last hop can't have its source as the payee.
2335 let invalid_last_hop = RouteHint(vec![RouteHintHop {
2336 src_node_id: nodes[6],
2337 short_channel_id: 8,
2340 proportional_millionths: 0,
2342 cltv_expiry_delta: (8 << 8) | 1,
2343 htlc_minimum_msat: None,
2344 htlc_maximum_msat: None,
2347 let mut invalid_last_hops = last_hops_multi_private_channels(&nodes);
2348 invalid_last_hops.push(invalid_last_hop);
2350 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id, &net_graph_msg_handler.network_graph, &nodes[6], None, None, &invalid_last_hops.iter().collect::<Vec<_>>(), 100, 42, Arc::clone(&logger), &scorer) {
2351 assert_eq!(err, "Last hop cannot have a payee as a source.");
2352 } else { panic!(); }
2355 let route = get_route(&our_id, &net_graph_msg_handler.network_graph, &nodes[6], None, None, &last_hops_multi_private_channels(&nodes).iter().collect::<Vec<_>>(), 100, 42, Arc::clone(&logger), &scorer).unwrap();
2356 assert_eq!(route.paths[0].len(), 5);
2358 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
2359 assert_eq!(route.paths[0][0].short_channel_id, 2);
2360 assert_eq!(route.paths[0][0].fee_msat, 100);
2361 assert_eq!(route.paths[0][0].cltv_expiry_delta, (4 << 8) | 1);
2362 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
2363 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
2365 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2366 assert_eq!(route.paths[0][1].short_channel_id, 4);
2367 assert_eq!(route.paths[0][1].fee_msat, 0);
2368 assert_eq!(route.paths[0][1].cltv_expiry_delta, (6 << 8) | 1);
2369 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2370 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
2372 assert_eq!(route.paths[0][2].pubkey, nodes[4]);
2373 assert_eq!(route.paths[0][2].short_channel_id, 6);
2374 assert_eq!(route.paths[0][2].fee_msat, 0);
2375 assert_eq!(route.paths[0][2].cltv_expiry_delta, (11 << 8) | 1);
2376 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(5));
2377 assert_eq!(route.paths[0][2].channel_features.le_flags(), &id_to_feature_flags(6));
2379 assert_eq!(route.paths[0][3].pubkey, nodes[3]);
2380 assert_eq!(route.paths[0][3].short_channel_id, 11);
2381 assert_eq!(route.paths[0][3].fee_msat, 0);
2382 assert_eq!(route.paths[0][3].cltv_expiry_delta, (8 << 8) | 1);
2383 // If we have a peer in the node map, we'll use their features here since we don't have
2384 // a way of figuring out their features from the invoice:
2385 assert_eq!(route.paths[0][3].node_features.le_flags(), &id_to_feature_flags(4));
2386 assert_eq!(route.paths[0][3].channel_features.le_flags(), &id_to_feature_flags(11));
2388 assert_eq!(route.paths[0][4].pubkey, nodes[6]);
2389 assert_eq!(route.paths[0][4].short_channel_id, 8);
2390 assert_eq!(route.paths[0][4].fee_msat, 100);
2391 assert_eq!(route.paths[0][4].cltv_expiry_delta, 42);
2392 assert_eq!(route.paths[0][4].node_features.le_flags(), &Vec::<u8>::new()); // We dont pass flags in from invoices yet
2393 assert_eq!(route.paths[0][4].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
2396 fn empty_last_hop(nodes: &Vec<PublicKey>) -> Vec<RouteHint> {
2397 let zero_fees = RoutingFees {
2399 proportional_millionths: 0,
2401 vec![RouteHint(vec![RouteHintHop {
2402 src_node_id: nodes[3],
2403 short_channel_id: 8,
2405 cltv_expiry_delta: (8 << 8) | 1,
2406 htlc_minimum_msat: None,
2407 htlc_maximum_msat: None,
2408 }]), RouteHint(vec![
2410 ]), RouteHint(vec![RouteHintHop {
2411 src_node_id: nodes[5],
2412 short_channel_id: 10,
2414 cltv_expiry_delta: (10 << 8) | 1,
2415 htlc_minimum_msat: None,
2416 htlc_maximum_msat: None,
2421 fn ignores_empty_last_hops_test() {
2422 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
2423 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
2424 let scorer = Scorer::new(0);
2426 // Test handling of an empty RouteHint passed in Invoice.
2428 let route = get_route(&our_id, &net_graph_msg_handler.network_graph, &nodes[6], None, None, &empty_last_hop(&nodes).iter().collect::<Vec<_>>(), 100, 42, Arc::clone(&logger), &scorer).unwrap();
2429 assert_eq!(route.paths[0].len(), 5);
2431 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
2432 assert_eq!(route.paths[0][0].short_channel_id, 2);
2433 assert_eq!(route.paths[0][0].fee_msat, 100);
2434 assert_eq!(route.paths[0][0].cltv_expiry_delta, (4 << 8) | 1);
2435 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
2436 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
2438 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2439 assert_eq!(route.paths[0][1].short_channel_id, 4);
2440 assert_eq!(route.paths[0][1].fee_msat, 0);
2441 assert_eq!(route.paths[0][1].cltv_expiry_delta, (6 << 8) | 1);
2442 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2443 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
2445 assert_eq!(route.paths[0][2].pubkey, nodes[4]);
2446 assert_eq!(route.paths[0][2].short_channel_id, 6);
2447 assert_eq!(route.paths[0][2].fee_msat, 0);
2448 assert_eq!(route.paths[0][2].cltv_expiry_delta, (11 << 8) | 1);
2449 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(5));
2450 assert_eq!(route.paths[0][2].channel_features.le_flags(), &id_to_feature_flags(6));
2452 assert_eq!(route.paths[0][3].pubkey, nodes[3]);
2453 assert_eq!(route.paths[0][3].short_channel_id, 11);
2454 assert_eq!(route.paths[0][3].fee_msat, 0);
2455 assert_eq!(route.paths[0][3].cltv_expiry_delta, (8 << 8) | 1);
2456 // If we have a peer in the node map, we'll use their features here since we don't have
2457 // a way of figuring out their features from the invoice:
2458 assert_eq!(route.paths[0][3].node_features.le_flags(), &id_to_feature_flags(4));
2459 assert_eq!(route.paths[0][3].channel_features.le_flags(), &id_to_feature_flags(11));
2461 assert_eq!(route.paths[0][4].pubkey, nodes[6]);
2462 assert_eq!(route.paths[0][4].short_channel_id, 8);
2463 assert_eq!(route.paths[0][4].fee_msat, 100);
2464 assert_eq!(route.paths[0][4].cltv_expiry_delta, 42);
2465 assert_eq!(route.paths[0][4].node_features.le_flags(), &Vec::<u8>::new()); // We dont pass flags in from invoices yet
2466 assert_eq!(route.paths[0][4].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
2469 fn multi_hint_last_hops(nodes: &Vec<PublicKey>) -> Vec<RouteHint> {
2470 let zero_fees = RoutingFees {
2472 proportional_millionths: 0,
2474 vec![RouteHint(vec![RouteHintHop {
2475 src_node_id: nodes[2],
2476 short_channel_id: 5,
2479 proportional_millionths: 0,
2481 cltv_expiry_delta: (5 << 8) | 1,
2482 htlc_minimum_msat: None,
2483 htlc_maximum_msat: None,
2485 src_node_id: nodes[3],
2486 short_channel_id: 8,
2488 cltv_expiry_delta: (8 << 8) | 1,
2489 htlc_minimum_msat: None,
2490 htlc_maximum_msat: None,
2491 }]), RouteHint(vec![RouteHintHop {
2492 src_node_id: nodes[5],
2493 short_channel_id: 10,
2495 cltv_expiry_delta: (10 << 8) | 1,
2496 htlc_minimum_msat: None,
2497 htlc_maximum_msat: None,
2502 fn multi_hint_last_hops_test() {
2503 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
2504 let (_, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
2505 let scorer = Scorer::new(0);
2506 // Test through channels 2, 3, 5, 8.
2507 // Test shows that multiple hop hints are considered.
2509 // Disabling channels 6 & 7 by flags=2
2510 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
2511 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2512 short_channel_id: 6,
2514 flags: 2, // to disable
2515 cltv_expiry_delta: 0,
2516 htlc_minimum_msat: 0,
2517 htlc_maximum_msat: OptionalField::Absent,
2519 fee_proportional_millionths: 0,
2520 excess_data: Vec::new()
2522 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
2523 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2524 short_channel_id: 7,
2526 flags: 2, // to disable
2527 cltv_expiry_delta: 0,
2528 htlc_minimum_msat: 0,
2529 htlc_maximum_msat: OptionalField::Absent,
2531 fee_proportional_millionths: 0,
2532 excess_data: Vec::new()
2535 let route = get_route(&our_id, &net_graph_msg_handler.network_graph, &nodes[6], None, None, &multi_hint_last_hops(&nodes).iter().collect::<Vec<_>>(), 100, 42, Arc::clone(&logger), &scorer).unwrap();
2536 assert_eq!(route.paths[0].len(), 4);
2538 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
2539 assert_eq!(route.paths[0][0].short_channel_id, 2);
2540 assert_eq!(route.paths[0][0].fee_msat, 200);
2541 assert_eq!(route.paths[0][0].cltv_expiry_delta, 1025);
2542 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
2543 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
2545 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2546 assert_eq!(route.paths[0][1].short_channel_id, 4);
2547 assert_eq!(route.paths[0][1].fee_msat, 100);
2548 assert_eq!(route.paths[0][1].cltv_expiry_delta, 1281);
2549 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2550 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
2552 assert_eq!(route.paths[0][2].pubkey, nodes[3]);
2553 assert_eq!(route.paths[0][2].short_channel_id, 5);
2554 assert_eq!(route.paths[0][2].fee_msat, 0);
2555 assert_eq!(route.paths[0][2].cltv_expiry_delta, 2049);
2556 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(4));
2557 assert_eq!(route.paths[0][2].channel_features.le_flags(), &Vec::<u8>::new());
2559 assert_eq!(route.paths[0][3].pubkey, nodes[6]);
2560 assert_eq!(route.paths[0][3].short_channel_id, 8);
2561 assert_eq!(route.paths[0][3].fee_msat, 100);
2562 assert_eq!(route.paths[0][3].cltv_expiry_delta, 42);
2563 assert_eq!(route.paths[0][3].node_features.le_flags(), &Vec::<u8>::new()); // We dont pass flags in from invoices yet
2564 assert_eq!(route.paths[0][3].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
2567 fn last_hops_with_public_channel(nodes: &Vec<PublicKey>) -> Vec<RouteHint> {
2568 let zero_fees = RoutingFees {
2570 proportional_millionths: 0,
2572 vec![RouteHint(vec![RouteHintHop {
2573 src_node_id: nodes[4],
2574 short_channel_id: 11,
2576 cltv_expiry_delta: (11 << 8) | 1,
2577 htlc_minimum_msat: None,
2578 htlc_maximum_msat: None,
2580 src_node_id: nodes[3],
2581 short_channel_id: 8,
2583 cltv_expiry_delta: (8 << 8) | 1,
2584 htlc_minimum_msat: None,
2585 htlc_maximum_msat: None,
2586 }]), RouteHint(vec![RouteHintHop {
2587 src_node_id: nodes[4],
2588 short_channel_id: 9,
2591 proportional_millionths: 0,
2593 cltv_expiry_delta: (9 << 8) | 1,
2594 htlc_minimum_msat: None,
2595 htlc_maximum_msat: None,
2596 }]), RouteHint(vec![RouteHintHop {
2597 src_node_id: nodes[5],
2598 short_channel_id: 10,
2600 cltv_expiry_delta: (10 << 8) | 1,
2601 htlc_minimum_msat: None,
2602 htlc_maximum_msat: None,
2607 fn last_hops_with_public_channel_test() {
2608 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
2609 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
2610 let scorer = Scorer::new(0);
2611 // This test shows that public routes can be present in the invoice
2612 // which would be handled in the same manner.
2614 let route = get_route(&our_id, &net_graph_msg_handler.network_graph, &nodes[6], None, None, &last_hops_with_public_channel(&nodes).iter().collect::<Vec<_>>(), 100, 42, Arc::clone(&logger), &scorer).unwrap();
2615 assert_eq!(route.paths[0].len(), 5);
2617 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
2618 assert_eq!(route.paths[0][0].short_channel_id, 2);
2619 assert_eq!(route.paths[0][0].fee_msat, 100);
2620 assert_eq!(route.paths[0][0].cltv_expiry_delta, (4 << 8) | 1);
2621 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
2622 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
2624 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2625 assert_eq!(route.paths[0][1].short_channel_id, 4);
2626 assert_eq!(route.paths[0][1].fee_msat, 0);
2627 assert_eq!(route.paths[0][1].cltv_expiry_delta, (6 << 8) | 1);
2628 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2629 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
2631 assert_eq!(route.paths[0][2].pubkey, nodes[4]);
2632 assert_eq!(route.paths[0][2].short_channel_id, 6);
2633 assert_eq!(route.paths[0][2].fee_msat, 0);
2634 assert_eq!(route.paths[0][2].cltv_expiry_delta, (11 << 8) | 1);
2635 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(5));
2636 assert_eq!(route.paths[0][2].channel_features.le_flags(), &id_to_feature_flags(6));
2638 assert_eq!(route.paths[0][3].pubkey, nodes[3]);
2639 assert_eq!(route.paths[0][3].short_channel_id, 11);
2640 assert_eq!(route.paths[0][3].fee_msat, 0);
2641 assert_eq!(route.paths[0][3].cltv_expiry_delta, (8 << 8) | 1);
2642 // If we have a peer in the node map, we'll use their features here since we don't have
2643 // a way of figuring out their features from the invoice:
2644 assert_eq!(route.paths[0][3].node_features.le_flags(), &id_to_feature_flags(4));
2645 assert_eq!(route.paths[0][3].channel_features.le_flags(), &Vec::<u8>::new());
2647 assert_eq!(route.paths[0][4].pubkey, nodes[6]);
2648 assert_eq!(route.paths[0][4].short_channel_id, 8);
2649 assert_eq!(route.paths[0][4].fee_msat, 100);
2650 assert_eq!(route.paths[0][4].cltv_expiry_delta, 42);
2651 assert_eq!(route.paths[0][4].node_features.le_flags(), &Vec::<u8>::new()); // We dont pass flags in from invoices yet
2652 assert_eq!(route.paths[0][4].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
2656 fn our_chans_last_hop_connect_test() {
2657 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
2658 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
2659 let scorer = Scorer::new(0);
2661 // Simple test with outbound channel to 4 to test that last_hops and first_hops connect
2662 let our_chans = vec![get_channel_details(Some(42), nodes[3].clone(), InitFeatures::from_le_bytes(vec![0b11]), 250_000_000)];
2663 let mut last_hops = last_hops(&nodes);
2664 let route = get_route(&our_id, &net_graph_msg_handler.network_graph, &nodes[6], None, Some(&our_chans.iter().collect::<Vec<_>>()), &last_hops.iter().collect::<Vec<_>>(), 100, 42, Arc::clone(&logger), &scorer).unwrap();
2665 assert_eq!(route.paths[0].len(), 2);
2667 assert_eq!(route.paths[0][0].pubkey, nodes[3]);
2668 assert_eq!(route.paths[0][0].short_channel_id, 42);
2669 assert_eq!(route.paths[0][0].fee_msat, 0);
2670 assert_eq!(route.paths[0][0].cltv_expiry_delta, (8 << 8) | 1);
2671 assert_eq!(route.paths[0][0].node_features.le_flags(), &vec![0b11]);
2672 assert_eq!(route.paths[0][0].channel_features.le_flags(), &Vec::<u8>::new()); // No feature flags will meet the relevant-to-channel conversion
2674 assert_eq!(route.paths[0][1].pubkey, nodes[6]);
2675 assert_eq!(route.paths[0][1].short_channel_id, 8);
2676 assert_eq!(route.paths[0][1].fee_msat, 100);
2677 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
2678 assert_eq!(route.paths[0][1].node_features.le_flags(), &Vec::<u8>::new()); // We dont pass flags in from invoices yet
2679 assert_eq!(route.paths[0][1].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
2681 last_hops[0].0[0].fees.base_msat = 1000;
2683 // Revert to via 6 as the fee on 8 goes up
2684 let route = get_route(&our_id, &net_graph_msg_handler.network_graph, &nodes[6], None, None, &last_hops.iter().collect::<Vec<_>>(), 100, 42, Arc::clone(&logger), &scorer).unwrap();
2685 assert_eq!(route.paths[0].len(), 4);
2687 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
2688 assert_eq!(route.paths[0][0].short_channel_id, 2);
2689 assert_eq!(route.paths[0][0].fee_msat, 200); // fee increased as its % of value transferred across node
2690 assert_eq!(route.paths[0][0].cltv_expiry_delta, (4 << 8) | 1);
2691 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
2692 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
2694 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2695 assert_eq!(route.paths[0][1].short_channel_id, 4);
2696 assert_eq!(route.paths[0][1].fee_msat, 100);
2697 assert_eq!(route.paths[0][1].cltv_expiry_delta, (7 << 8) | 1);
2698 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2699 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
2701 assert_eq!(route.paths[0][2].pubkey, nodes[5]);
2702 assert_eq!(route.paths[0][2].short_channel_id, 7);
2703 assert_eq!(route.paths[0][2].fee_msat, 0);
2704 assert_eq!(route.paths[0][2].cltv_expiry_delta, (10 << 8) | 1);
2705 // If we have a peer in the node map, we'll use their features here since we don't have
2706 // a way of figuring out their features from the invoice:
2707 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(6));
2708 assert_eq!(route.paths[0][2].channel_features.le_flags(), &id_to_feature_flags(7));
2710 assert_eq!(route.paths[0][3].pubkey, nodes[6]);
2711 assert_eq!(route.paths[0][3].short_channel_id, 10);
2712 assert_eq!(route.paths[0][3].fee_msat, 100);
2713 assert_eq!(route.paths[0][3].cltv_expiry_delta, 42);
2714 assert_eq!(route.paths[0][3].node_features.le_flags(), &Vec::<u8>::new()); // We dont pass flags in from invoices yet
2715 assert_eq!(route.paths[0][3].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
2717 // ...but still use 8 for larger payments as 6 has a variable feerate
2718 let route = get_route(&our_id, &net_graph_msg_handler.network_graph, &nodes[6], None, None, &last_hops.iter().collect::<Vec<_>>(), 2000, 42, Arc::clone(&logger), &scorer).unwrap();
2719 assert_eq!(route.paths[0].len(), 5);
2721 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
2722 assert_eq!(route.paths[0][0].short_channel_id, 2);
2723 assert_eq!(route.paths[0][0].fee_msat, 3000);
2724 assert_eq!(route.paths[0][0].cltv_expiry_delta, (4 << 8) | 1);
2725 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
2726 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
2728 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2729 assert_eq!(route.paths[0][1].short_channel_id, 4);
2730 assert_eq!(route.paths[0][1].fee_msat, 0);
2731 assert_eq!(route.paths[0][1].cltv_expiry_delta, (6 << 8) | 1);
2732 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2733 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
2735 assert_eq!(route.paths[0][2].pubkey, nodes[4]);
2736 assert_eq!(route.paths[0][2].short_channel_id, 6);
2737 assert_eq!(route.paths[0][2].fee_msat, 0);
2738 assert_eq!(route.paths[0][2].cltv_expiry_delta, (11 << 8) | 1);
2739 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(5));
2740 assert_eq!(route.paths[0][2].channel_features.le_flags(), &id_to_feature_flags(6));
2742 assert_eq!(route.paths[0][3].pubkey, nodes[3]);
2743 assert_eq!(route.paths[0][3].short_channel_id, 11);
2744 assert_eq!(route.paths[0][3].fee_msat, 1000);
2745 assert_eq!(route.paths[0][3].cltv_expiry_delta, (8 << 8) | 1);
2746 // If we have a peer in the node map, we'll use their features here since we don't have
2747 // a way of figuring out their features from the invoice:
2748 assert_eq!(route.paths[0][3].node_features.le_flags(), &id_to_feature_flags(4));
2749 assert_eq!(route.paths[0][3].channel_features.le_flags(), &id_to_feature_flags(11));
2751 assert_eq!(route.paths[0][4].pubkey, nodes[6]);
2752 assert_eq!(route.paths[0][4].short_channel_id, 8);
2753 assert_eq!(route.paths[0][4].fee_msat, 2000);
2754 assert_eq!(route.paths[0][4].cltv_expiry_delta, 42);
2755 assert_eq!(route.paths[0][4].node_features.le_flags(), &Vec::<u8>::new()); // We dont pass flags in from invoices yet
2756 assert_eq!(route.paths[0][4].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
2759 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> {
2760 let source_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&hex::decode(format!("{:02}", 41).repeat(32)).unwrap()[..]).unwrap());
2761 let middle_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&hex::decode(format!("{:02}", 42).repeat(32)).unwrap()[..]).unwrap());
2762 let target_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&hex::decode(format!("{:02}", 43).repeat(32)).unwrap()[..]).unwrap());
2764 // If we specify a channel to a middle hop, that overrides our local channel view and that gets used
2765 let last_hops = RouteHint(vec![RouteHintHop {
2766 src_node_id: middle_node_id,
2767 short_channel_id: 8,
2770 proportional_millionths: last_hop_fee_prop,
2772 cltv_expiry_delta: (8 << 8) | 1,
2773 htlc_minimum_msat: None,
2774 htlc_maximum_msat: last_hop_htlc_max,
2776 let our_chans = vec![get_channel_details(Some(42), middle_node_id, InitFeatures::from_le_bytes(vec![0b11]), outbound_capacity_msat)];
2777 let scorer = Scorer::new(0);
2778 get_route(&source_node_id, &NetworkGraph::new(genesis_block(Network::Testnet).header.block_hash()), &target_node_id, None, Some(&our_chans.iter().collect::<Vec<_>>()), &vec![&last_hops], route_val, 42, &test_utils::TestLogger::new(), &scorer)
2782 fn unannounced_path_test() {
2783 // We should be able to send a payment to a destination without any help of a routing graph
2784 // if we have a channel with a common counterparty that appears in the first and last hop
2786 let route = do_unannounced_path_test(None, 1, 2000000, 1000000).unwrap();
2788 let middle_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&hex::decode(format!("{:02}", 42).repeat(32)).unwrap()[..]).unwrap());
2789 let target_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&hex::decode(format!("{:02}", 43).repeat(32)).unwrap()[..]).unwrap());
2790 assert_eq!(route.paths[0].len(), 2);
2792 assert_eq!(route.paths[0][0].pubkey, middle_node_id);
2793 assert_eq!(route.paths[0][0].short_channel_id, 42);
2794 assert_eq!(route.paths[0][0].fee_msat, 1001);
2795 assert_eq!(route.paths[0][0].cltv_expiry_delta, (8 << 8) | 1);
2796 assert_eq!(route.paths[0][0].node_features.le_flags(), &[0b11]);
2797 assert_eq!(route.paths[0][0].channel_features.le_flags(), &[0; 0]); // We can't learn any flags from invoices, sadly
2799 assert_eq!(route.paths[0][1].pubkey, target_node_id);
2800 assert_eq!(route.paths[0][1].short_channel_id, 8);
2801 assert_eq!(route.paths[0][1].fee_msat, 1000000);
2802 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
2803 assert_eq!(route.paths[0][1].node_features.le_flags(), &[0; 0]); // We dont pass flags in from invoices yet
2804 assert_eq!(route.paths[0][1].channel_features.le_flags(), &[0; 0]); // We can't learn any flags from invoices, sadly
2808 fn overflow_unannounced_path_test_liquidity_underflow() {
2809 // Previously, when we had a last-hop hint connected directly to a first-hop channel, where
2810 // the last-hop had a fee which overflowed a u64, we'd panic.
2811 // This was due to us adding the first-hop from us unconditionally, causing us to think
2812 // we'd built a path (as our node is in the "best candidate" set), when we had not.
2813 // In this test, we previously hit a subtraction underflow due to having less available
2814 // liquidity at the last hop than 0.
2815 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());
2819 fn overflow_unannounced_path_test_feerate_overflow() {
2820 // This tests for the same case as above, except instead of hitting a subtraction
2821 // underflow, we hit a case where the fee charged at a hop overflowed.
2822 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());
2826 fn available_amount_while_routing_test() {
2827 // Tests whether we choose the correct available channel amount while routing.
2829 let (secp_ctx, mut net_graph_msg_handler, chain_monitor, logger) = build_graph();
2830 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
2831 let scorer = Scorer::new(0);
2833 // We will use a simple single-path route from
2834 // our node to node2 via node0: channels {1, 3}.
2836 // First disable all other paths.
2837 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2838 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2839 short_channel_id: 2,
2842 cltv_expiry_delta: 0,
2843 htlc_minimum_msat: 0,
2844 htlc_maximum_msat: OptionalField::Present(100_000),
2846 fee_proportional_millionths: 0,
2847 excess_data: Vec::new()
2849 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2850 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2851 short_channel_id: 12,
2854 cltv_expiry_delta: 0,
2855 htlc_minimum_msat: 0,
2856 htlc_maximum_msat: OptionalField::Present(100_000),
2858 fee_proportional_millionths: 0,
2859 excess_data: Vec::new()
2862 // Make the first channel (#1) very permissive,
2863 // and we will be testing all limits on the second channel.
2864 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2865 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2866 short_channel_id: 1,
2869 cltv_expiry_delta: 0,
2870 htlc_minimum_msat: 0,
2871 htlc_maximum_msat: OptionalField::Present(1_000_000_000),
2873 fee_proportional_millionths: 0,
2874 excess_data: Vec::new()
2877 // First, let's see if routing works if we have absolutely no idea about the available amount.
2878 // In this case, it should be set to 250_000 sats.
2879 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
2880 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2881 short_channel_id: 3,
2884 cltv_expiry_delta: 0,
2885 htlc_minimum_msat: 0,
2886 htlc_maximum_msat: OptionalField::Absent,
2888 fee_proportional_millionths: 0,
2889 excess_data: Vec::new()
2893 // Attempt to route more than available results in a failure.
2894 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id, &net_graph_msg_handler.network_graph, &nodes[2],
2895 Some(InvoiceFeatures::known()), None, &Vec::new(), 250_000_001, 42, Arc::clone(&logger), &scorer) {
2896 assert_eq!(err, "Failed to find a sufficient route to the given destination");
2897 } else { panic!(); }
2901 // Now, attempt to route an exact amount we have should be fine.
2902 let route = get_route(&our_id, &net_graph_msg_handler.network_graph, &nodes[2],
2903 Some(InvoiceFeatures::known()), None, &Vec::new(), 250_000_000, 42, Arc::clone(&logger), &scorer).unwrap();
2904 assert_eq!(route.paths.len(), 1);
2905 let path = route.paths.last().unwrap();
2906 assert_eq!(path.len(), 2);
2907 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
2908 assert_eq!(path.last().unwrap().fee_msat, 250_000_000);
2911 // Check that setting outbound_capacity_msat in first_hops limits the channels.
2912 // Disable channel #1 and use another first hop.
2913 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2914 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2915 short_channel_id: 1,
2918 cltv_expiry_delta: 0,
2919 htlc_minimum_msat: 0,
2920 htlc_maximum_msat: OptionalField::Present(1_000_000_000),
2922 fee_proportional_millionths: 0,
2923 excess_data: Vec::new()
2926 // Now, limit the first_hop by the outbound_capacity_msat of 200_000 sats.
2927 let our_chans = vec![get_channel_details(Some(42), nodes[0].clone(), InitFeatures::from_le_bytes(vec![0b11]), 200_000_000)];
2930 // Attempt to route more than available results in a failure.
2931 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id, &net_graph_msg_handler.network_graph, &nodes[2],
2932 Some(InvoiceFeatures::known()), Some(&our_chans.iter().collect::<Vec<_>>()), &Vec::new(), 200_000_001, 42, Arc::clone(&logger), &scorer) {
2933 assert_eq!(err, "Failed to find a sufficient route to the given destination");
2934 } else { panic!(); }
2938 // Now, attempt to route an exact amount we have should be fine.
2939 let route = get_route(&our_id, &net_graph_msg_handler.network_graph, &nodes[2],
2940 Some(InvoiceFeatures::known()), Some(&our_chans.iter().collect::<Vec<_>>()), &Vec::new(), 200_000_000, 42, Arc::clone(&logger), &scorer).unwrap();
2941 assert_eq!(route.paths.len(), 1);
2942 let path = route.paths.last().unwrap();
2943 assert_eq!(path.len(), 2);
2944 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
2945 assert_eq!(path.last().unwrap().fee_msat, 200_000_000);
2948 // Enable channel #1 back.
2949 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2950 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2951 short_channel_id: 1,
2954 cltv_expiry_delta: 0,
2955 htlc_minimum_msat: 0,
2956 htlc_maximum_msat: OptionalField::Present(1_000_000_000),
2958 fee_proportional_millionths: 0,
2959 excess_data: Vec::new()
2963 // Now let's see if routing works if we know only htlc_maximum_msat.
2964 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
2965 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2966 short_channel_id: 3,
2969 cltv_expiry_delta: 0,
2970 htlc_minimum_msat: 0,
2971 htlc_maximum_msat: OptionalField::Present(15_000),
2973 fee_proportional_millionths: 0,
2974 excess_data: Vec::new()
2978 // Attempt to route more than available results in a failure.
2979 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id, &net_graph_msg_handler.network_graph, &nodes[2],
2980 Some(InvoiceFeatures::known()), None, &Vec::new(), 15_001, 42, Arc::clone(&logger), &scorer) {
2981 assert_eq!(err, "Failed to find a sufficient route to the given destination");
2982 } else { panic!(); }
2986 // Now, attempt to route an exact amount we have should be fine.
2987 let route = get_route(&our_id, &net_graph_msg_handler.network_graph, &nodes[2],
2988 Some(InvoiceFeatures::known()), None, &Vec::new(), 15_000, 42, Arc::clone(&logger), &scorer).unwrap();
2989 assert_eq!(route.paths.len(), 1);
2990 let path = route.paths.last().unwrap();
2991 assert_eq!(path.len(), 2);
2992 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
2993 assert_eq!(path.last().unwrap().fee_msat, 15_000);
2996 // Now let's see if routing works if we know only capacity from the UTXO.
2998 // We can't change UTXO capacity on the fly, so we'll disable
2999 // the existing channel and add another one with the capacity we need.
3000 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3001 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3002 short_channel_id: 3,
3005 cltv_expiry_delta: 0,
3006 htlc_minimum_msat: 0,
3007 htlc_maximum_msat: OptionalField::Absent,
3009 fee_proportional_millionths: 0,
3010 excess_data: Vec::new()
3013 let good_script = Builder::new().push_opcode(opcodes::all::OP_PUSHNUM_2)
3014 .push_slice(&PublicKey::from_secret_key(&secp_ctx, &privkeys[0]).serialize())
3015 .push_slice(&PublicKey::from_secret_key(&secp_ctx, &privkeys[2]).serialize())
3016 .push_opcode(opcodes::all::OP_PUSHNUM_2)
3017 .push_opcode(opcodes::all::OP_CHECKMULTISIG).into_script().to_v0_p2wsh();
3019 *chain_monitor.utxo_ret.lock().unwrap() = Ok(TxOut { value: 15, script_pubkey: good_script.clone() });
3020 net_graph_msg_handler.add_chain_access(Some(chain_monitor));
3022 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], &privkeys[2], ChannelFeatures::from_le_bytes(id_to_feature_flags(3)), 333);
3023 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3024 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3025 short_channel_id: 333,
3028 cltv_expiry_delta: (3 << 8) | 1,
3029 htlc_minimum_msat: 0,
3030 htlc_maximum_msat: OptionalField::Absent,
3032 fee_proportional_millionths: 0,
3033 excess_data: Vec::new()
3035 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3036 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3037 short_channel_id: 333,
3040 cltv_expiry_delta: (3 << 8) | 2,
3041 htlc_minimum_msat: 0,
3042 htlc_maximum_msat: OptionalField::Absent,
3044 fee_proportional_millionths: 0,
3045 excess_data: Vec::new()
3049 // Attempt to route more than available results in a failure.
3050 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id, &net_graph_msg_handler.network_graph, &nodes[2],
3051 Some(InvoiceFeatures::known()), None, &Vec::new(), 15_001, 42, Arc::clone(&logger), &scorer) {
3052 assert_eq!(err, "Failed to find a sufficient route to the given destination");
3053 } else { panic!(); }
3057 // Now, attempt to route an exact amount we have should be fine.
3058 let route = get_route(&our_id, &net_graph_msg_handler.network_graph, &nodes[2],
3059 Some(InvoiceFeatures::known()), None, &Vec::new(), 15_000, 42, Arc::clone(&logger), &scorer).unwrap();
3060 assert_eq!(route.paths.len(), 1);
3061 let path = route.paths.last().unwrap();
3062 assert_eq!(path.len(), 2);
3063 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
3064 assert_eq!(path.last().unwrap().fee_msat, 15_000);
3067 // Now let's see if routing chooses htlc_maximum_msat over UTXO capacity.
3068 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3069 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3070 short_channel_id: 333,
3073 cltv_expiry_delta: 0,
3074 htlc_minimum_msat: 0,
3075 htlc_maximum_msat: OptionalField::Present(10_000),
3077 fee_proportional_millionths: 0,
3078 excess_data: Vec::new()
3082 // Attempt to route more than available results in a failure.
3083 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id, &net_graph_msg_handler.network_graph, &nodes[2],
3084 Some(InvoiceFeatures::known()), None, &Vec::new(), 10_001, 42, Arc::clone(&logger), &scorer) {
3085 assert_eq!(err, "Failed to find a sufficient route to the given destination");
3086 } else { panic!(); }
3090 // Now, attempt to route an exact amount we have should be fine.
3091 let route = get_route(&our_id, &net_graph_msg_handler.network_graph, &nodes[2],
3092 Some(InvoiceFeatures::known()), None, &Vec::new(), 10_000, 42, Arc::clone(&logger), &scorer).unwrap();
3093 assert_eq!(route.paths.len(), 1);
3094 let path = route.paths.last().unwrap();
3095 assert_eq!(path.len(), 2);
3096 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
3097 assert_eq!(path.last().unwrap().fee_msat, 10_000);
3102 fn available_liquidity_last_hop_test() {
3103 // Check that available liquidity properly limits the path even when only
3104 // one of the latter hops is limited.
3105 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
3106 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3107 let scorer = Scorer::new(0);
3109 // Path via {node7, node2, node4} is channels {12, 13, 6, 11}.
3110 // {12, 13, 11} have the capacities of 100, {6} has a capacity of 50.
3111 // Total capacity: 50 sats.
3113 // Disable other potential paths.
3114 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3115 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3116 short_channel_id: 2,
3119 cltv_expiry_delta: 0,
3120 htlc_minimum_msat: 0,
3121 htlc_maximum_msat: OptionalField::Present(100_000),
3123 fee_proportional_millionths: 0,
3124 excess_data: Vec::new()
3126 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3127 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3128 short_channel_id: 7,
3131 cltv_expiry_delta: 0,
3132 htlc_minimum_msat: 0,
3133 htlc_maximum_msat: OptionalField::Present(100_000),
3135 fee_proportional_millionths: 0,
3136 excess_data: Vec::new()
3141 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3142 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3143 short_channel_id: 12,
3146 cltv_expiry_delta: 0,
3147 htlc_minimum_msat: 0,
3148 htlc_maximum_msat: OptionalField::Present(100_000),
3150 fee_proportional_millionths: 0,
3151 excess_data: Vec::new()
3153 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
3154 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3155 short_channel_id: 13,
3158 cltv_expiry_delta: 0,
3159 htlc_minimum_msat: 0,
3160 htlc_maximum_msat: OptionalField::Present(100_000),
3162 fee_proportional_millionths: 0,
3163 excess_data: Vec::new()
3166 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3167 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3168 short_channel_id: 6,
3171 cltv_expiry_delta: 0,
3172 htlc_minimum_msat: 0,
3173 htlc_maximum_msat: OptionalField::Present(50_000),
3175 fee_proportional_millionths: 0,
3176 excess_data: Vec::new()
3178 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
3179 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3180 short_channel_id: 11,
3183 cltv_expiry_delta: 0,
3184 htlc_minimum_msat: 0,
3185 htlc_maximum_msat: OptionalField::Present(100_000),
3187 fee_proportional_millionths: 0,
3188 excess_data: Vec::new()
3191 // Attempt to route more than available results in a failure.
3192 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id, &net_graph_msg_handler.network_graph, &nodes[3],
3193 Some(InvoiceFeatures::known()), None, &Vec::new(), 60_000, 42, Arc::clone(&logger), &scorer) {
3194 assert_eq!(err, "Failed to find a sufficient route to the given destination");
3195 } else { panic!(); }
3199 // Now, attempt to route 49 sats (just a bit below the capacity).
3200 let route = get_route(&our_id, &net_graph_msg_handler.network_graph, &nodes[3],
3201 Some(InvoiceFeatures::known()), None, &Vec::new(), 49_000, 42, Arc::clone(&logger), &scorer).unwrap();
3202 assert_eq!(route.paths.len(), 1);
3203 let mut total_amount_paid_msat = 0;
3204 for path in &route.paths {
3205 assert_eq!(path.len(), 4);
3206 assert_eq!(path.last().unwrap().pubkey, nodes[3]);
3207 total_amount_paid_msat += path.last().unwrap().fee_msat;
3209 assert_eq!(total_amount_paid_msat, 49_000);
3213 // Attempt to route an exact amount is also fine
3214 let route = get_route(&our_id, &net_graph_msg_handler.network_graph, &nodes[3],
3215 Some(InvoiceFeatures::known()), None, &Vec::new(), 50_000, 42, Arc::clone(&logger), &scorer).unwrap();
3216 assert_eq!(route.paths.len(), 1);
3217 let mut total_amount_paid_msat = 0;
3218 for path in &route.paths {
3219 assert_eq!(path.len(), 4);
3220 assert_eq!(path.last().unwrap().pubkey, nodes[3]);
3221 total_amount_paid_msat += path.last().unwrap().fee_msat;
3223 assert_eq!(total_amount_paid_msat, 50_000);
3228 fn ignore_fee_first_hop_test() {
3229 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
3230 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3231 let scorer = Scorer::new(0);
3233 // Path via node0 is channels {1, 3}. Limit them to 100 and 50 sats (total limit 50).
3234 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3235 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3236 short_channel_id: 1,
3239 cltv_expiry_delta: 0,
3240 htlc_minimum_msat: 0,
3241 htlc_maximum_msat: OptionalField::Present(100_000),
3242 fee_base_msat: 1_000_000,
3243 fee_proportional_millionths: 0,
3244 excess_data: Vec::new()
3246 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3247 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3248 short_channel_id: 3,
3251 cltv_expiry_delta: 0,
3252 htlc_minimum_msat: 0,
3253 htlc_maximum_msat: OptionalField::Present(50_000),
3255 fee_proportional_millionths: 0,
3256 excess_data: Vec::new()
3260 let route = get_route(&our_id, &net_graph_msg_handler.network_graph, &nodes[2], None, None, &Vec::new(), 50_000, 42, Arc::clone(&logger), &scorer).unwrap();
3261 assert_eq!(route.paths.len(), 1);
3262 let mut total_amount_paid_msat = 0;
3263 for path in &route.paths {
3264 assert_eq!(path.len(), 2);
3265 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
3266 total_amount_paid_msat += path.last().unwrap().fee_msat;
3268 assert_eq!(total_amount_paid_msat, 50_000);
3273 fn simple_mpp_route_test() {
3274 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
3275 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3276 let scorer = Scorer::new(0);
3278 // We need a route consisting of 3 paths:
3279 // From our node to node2 via node0, node7, node1 (three paths one hop each).
3280 // To achieve this, the amount being transferred should be around
3281 // the total capacity of these 3 paths.
3283 // First, we set limits on these (previously unlimited) channels.
3284 // Their aggregate capacity will be 50 + 60 + 180 = 290 sats.
3286 // Path via node0 is channels {1, 3}. Limit them to 100 and 50 sats (total limit 50).
3287 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3288 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3289 short_channel_id: 1,
3292 cltv_expiry_delta: 0,
3293 htlc_minimum_msat: 0,
3294 htlc_maximum_msat: OptionalField::Present(100_000),
3296 fee_proportional_millionths: 0,
3297 excess_data: Vec::new()
3299 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3300 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3301 short_channel_id: 3,
3304 cltv_expiry_delta: 0,
3305 htlc_minimum_msat: 0,
3306 htlc_maximum_msat: OptionalField::Present(50_000),
3308 fee_proportional_millionths: 0,
3309 excess_data: Vec::new()
3312 // Path via node7 is channels {12, 13}. Limit them to 60 and 60 sats
3313 // (total limit 60).
3314 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3315 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3316 short_channel_id: 12,
3319 cltv_expiry_delta: 0,
3320 htlc_minimum_msat: 0,
3321 htlc_maximum_msat: OptionalField::Present(60_000),
3323 fee_proportional_millionths: 0,
3324 excess_data: Vec::new()
3326 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
3327 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3328 short_channel_id: 13,
3331 cltv_expiry_delta: 0,
3332 htlc_minimum_msat: 0,
3333 htlc_maximum_msat: OptionalField::Present(60_000),
3335 fee_proportional_millionths: 0,
3336 excess_data: Vec::new()
3339 // Path via node1 is channels {2, 4}. Limit them to 200 and 180 sats
3340 // (total capacity 180 sats).
3341 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3342 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3343 short_channel_id: 2,
3346 cltv_expiry_delta: 0,
3347 htlc_minimum_msat: 0,
3348 htlc_maximum_msat: OptionalField::Present(200_000),
3350 fee_proportional_millionths: 0,
3351 excess_data: Vec::new()
3353 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
3354 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3355 short_channel_id: 4,
3358 cltv_expiry_delta: 0,
3359 htlc_minimum_msat: 0,
3360 htlc_maximum_msat: OptionalField::Present(180_000),
3362 fee_proportional_millionths: 0,
3363 excess_data: Vec::new()
3367 // Attempt to route more than available results in a failure.
3368 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id, &net_graph_msg_handler.network_graph,
3369 &nodes[2], Some(InvoiceFeatures::known()), None, &Vec::new(), 300_000, 42, Arc::clone(&logger), &scorer) {
3370 assert_eq!(err, "Failed to find a sufficient route to the given destination");
3371 } else { panic!(); }
3375 // Now, attempt to route 250 sats (just a bit below the capacity).
3376 // Our algorithm should provide us with these 3 paths.
3377 let route = get_route(&our_id, &net_graph_msg_handler.network_graph, &nodes[2],
3378 Some(InvoiceFeatures::known()), None, &Vec::new(), 250_000, 42, Arc::clone(&logger), &scorer).unwrap();
3379 assert_eq!(route.paths.len(), 3);
3380 let mut total_amount_paid_msat = 0;
3381 for path in &route.paths {
3382 assert_eq!(path.len(), 2);
3383 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
3384 total_amount_paid_msat += path.last().unwrap().fee_msat;
3386 assert_eq!(total_amount_paid_msat, 250_000);
3390 // Attempt to route an exact amount is also fine
3391 let route = get_route(&our_id, &net_graph_msg_handler.network_graph, &nodes[2],
3392 Some(InvoiceFeatures::known()), None, &Vec::new(), 290_000, 42, Arc::clone(&logger), &scorer).unwrap();
3393 assert_eq!(route.paths.len(), 3);
3394 let mut total_amount_paid_msat = 0;
3395 for path in &route.paths {
3396 assert_eq!(path.len(), 2);
3397 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
3398 total_amount_paid_msat += path.last().unwrap().fee_msat;
3400 assert_eq!(total_amount_paid_msat, 290_000);
3405 fn long_mpp_route_test() {
3406 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
3407 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3408 let scorer = Scorer::new(0);
3410 // We need a route consisting of 3 paths:
3411 // From our node to node3 via {node0, node2}, {node7, node2, node4} and {node7, node2}.
3412 // Note that these paths overlap (channels 5, 12, 13).
3413 // We will route 300 sats.
3414 // Each path will have 100 sats capacity, those channels which
3415 // are used twice will have 200 sats capacity.
3417 // Disable other potential paths.
3418 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3419 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3420 short_channel_id: 2,
3423 cltv_expiry_delta: 0,
3424 htlc_minimum_msat: 0,
3425 htlc_maximum_msat: OptionalField::Present(100_000),
3427 fee_proportional_millionths: 0,
3428 excess_data: Vec::new()
3430 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3431 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3432 short_channel_id: 7,
3435 cltv_expiry_delta: 0,
3436 htlc_minimum_msat: 0,
3437 htlc_maximum_msat: OptionalField::Present(100_000),
3439 fee_proportional_millionths: 0,
3440 excess_data: Vec::new()
3443 // Path via {node0, node2} is channels {1, 3, 5}.
3444 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3445 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3446 short_channel_id: 1,
3449 cltv_expiry_delta: 0,
3450 htlc_minimum_msat: 0,
3451 htlc_maximum_msat: OptionalField::Present(100_000),
3453 fee_proportional_millionths: 0,
3454 excess_data: Vec::new()
3456 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3457 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3458 short_channel_id: 3,
3461 cltv_expiry_delta: 0,
3462 htlc_minimum_msat: 0,
3463 htlc_maximum_msat: OptionalField::Present(100_000),
3465 fee_proportional_millionths: 0,
3466 excess_data: Vec::new()
3469 // Capacity of 200 sats because this channel will be used by 3rd path as well.
3470 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(5)), 5);
3471 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3472 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3473 short_channel_id: 5,
3476 cltv_expiry_delta: 0,
3477 htlc_minimum_msat: 0,
3478 htlc_maximum_msat: OptionalField::Present(200_000),
3480 fee_proportional_millionths: 0,
3481 excess_data: Vec::new()
3484 // Path via {node7, node2, node4} is channels {12, 13, 6, 11}.
3485 // Add 100 sats to the capacities of {12, 13}, because these channels
3486 // are also used for 3rd path. 100 sats for the rest. Total capacity: 100 sats.
3487 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3488 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3489 short_channel_id: 12,
3492 cltv_expiry_delta: 0,
3493 htlc_minimum_msat: 0,
3494 htlc_maximum_msat: OptionalField::Present(200_000),
3496 fee_proportional_millionths: 0,
3497 excess_data: Vec::new()
3499 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
3500 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3501 short_channel_id: 13,
3504 cltv_expiry_delta: 0,
3505 htlc_minimum_msat: 0,
3506 htlc_maximum_msat: OptionalField::Present(200_000),
3508 fee_proportional_millionths: 0,
3509 excess_data: Vec::new()
3512 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3513 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3514 short_channel_id: 6,
3517 cltv_expiry_delta: 0,
3518 htlc_minimum_msat: 0,
3519 htlc_maximum_msat: OptionalField::Present(100_000),
3521 fee_proportional_millionths: 0,
3522 excess_data: Vec::new()
3524 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
3525 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3526 short_channel_id: 11,
3529 cltv_expiry_delta: 0,
3530 htlc_minimum_msat: 0,
3531 htlc_maximum_msat: OptionalField::Present(100_000),
3533 fee_proportional_millionths: 0,
3534 excess_data: Vec::new()
3537 // Path via {node7, node2} is channels {12, 13, 5}.
3538 // We already limited them to 200 sats (they are used twice for 100 sats).
3539 // Nothing to do here.
3542 // Attempt to route more than available results in a failure.
3543 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id, &net_graph_msg_handler.network_graph, &nodes[3],
3544 Some(InvoiceFeatures::known()), None, &Vec::new(), 350_000, 42, Arc::clone(&logger), &scorer) {
3545 assert_eq!(err, "Failed to find a sufficient route to the given destination");
3546 } else { panic!(); }
3550 // Now, attempt to route 300 sats (exact amount we can route).
3551 // Our algorithm should provide us with these 3 paths, 100 sats each.
3552 let route = get_route(&our_id, &net_graph_msg_handler.network_graph, &nodes[3],
3553 Some(InvoiceFeatures::known()), None, &Vec::new(), 300_000, 42, Arc::clone(&logger), &scorer).unwrap();
3554 assert_eq!(route.paths.len(), 3);
3556 let mut total_amount_paid_msat = 0;
3557 for path in &route.paths {
3558 assert_eq!(path.last().unwrap().pubkey, nodes[3]);
3559 total_amount_paid_msat += path.last().unwrap().fee_msat;
3561 assert_eq!(total_amount_paid_msat, 300_000);
3567 fn mpp_cheaper_route_test() {
3568 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
3569 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3570 let scorer = Scorer::new(0);
3572 // This test checks that if we have two cheaper paths and one more expensive path,
3573 // so that liquidity-wise any 2 of 3 combination is sufficient,
3574 // two cheaper paths will be taken.
3575 // These paths have equal available liquidity.
3577 // We need a combination of 3 paths:
3578 // From our node to node3 via {node0, node2}, {node7, node2, node4} and {node7, node2}.
3579 // Note that these paths overlap (channels 5, 12, 13).
3580 // Each path will have 100 sats capacity, those channels which
3581 // are used twice will have 200 sats capacity.
3583 // Disable other potential paths.
3584 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3585 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3586 short_channel_id: 2,
3589 cltv_expiry_delta: 0,
3590 htlc_minimum_msat: 0,
3591 htlc_maximum_msat: OptionalField::Present(100_000),
3593 fee_proportional_millionths: 0,
3594 excess_data: Vec::new()
3596 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3597 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3598 short_channel_id: 7,
3601 cltv_expiry_delta: 0,
3602 htlc_minimum_msat: 0,
3603 htlc_maximum_msat: OptionalField::Present(100_000),
3605 fee_proportional_millionths: 0,
3606 excess_data: Vec::new()
3609 // Path via {node0, node2} is channels {1, 3, 5}.
3610 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3611 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3612 short_channel_id: 1,
3615 cltv_expiry_delta: 0,
3616 htlc_minimum_msat: 0,
3617 htlc_maximum_msat: OptionalField::Present(100_000),
3619 fee_proportional_millionths: 0,
3620 excess_data: Vec::new()
3622 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3623 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3624 short_channel_id: 3,
3627 cltv_expiry_delta: 0,
3628 htlc_minimum_msat: 0,
3629 htlc_maximum_msat: OptionalField::Present(100_000),
3631 fee_proportional_millionths: 0,
3632 excess_data: Vec::new()
3635 // Capacity of 200 sats because this channel will be used by 3rd path as well.
3636 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(5)), 5);
3637 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3638 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3639 short_channel_id: 5,
3642 cltv_expiry_delta: 0,
3643 htlc_minimum_msat: 0,
3644 htlc_maximum_msat: OptionalField::Present(200_000),
3646 fee_proportional_millionths: 0,
3647 excess_data: Vec::new()
3650 // Path via {node7, node2, node4} is channels {12, 13, 6, 11}.
3651 // Add 100 sats to the capacities of {12, 13}, because these channels
3652 // are also used for 3rd path. 100 sats for the rest. Total capacity: 100 sats.
3653 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3654 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3655 short_channel_id: 12,
3658 cltv_expiry_delta: 0,
3659 htlc_minimum_msat: 0,
3660 htlc_maximum_msat: OptionalField::Present(200_000),
3662 fee_proportional_millionths: 0,
3663 excess_data: Vec::new()
3665 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
3666 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3667 short_channel_id: 13,
3670 cltv_expiry_delta: 0,
3671 htlc_minimum_msat: 0,
3672 htlc_maximum_msat: OptionalField::Present(200_000),
3674 fee_proportional_millionths: 0,
3675 excess_data: Vec::new()
3678 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3679 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3680 short_channel_id: 6,
3683 cltv_expiry_delta: 0,
3684 htlc_minimum_msat: 0,
3685 htlc_maximum_msat: OptionalField::Present(100_000),
3686 fee_base_msat: 1_000,
3687 fee_proportional_millionths: 0,
3688 excess_data: Vec::new()
3690 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
3691 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3692 short_channel_id: 11,
3695 cltv_expiry_delta: 0,
3696 htlc_minimum_msat: 0,
3697 htlc_maximum_msat: OptionalField::Present(100_000),
3699 fee_proportional_millionths: 0,
3700 excess_data: Vec::new()
3703 // Path via {node7, node2} is channels {12, 13, 5}.
3704 // We already limited them to 200 sats (they are used twice for 100 sats).
3705 // Nothing to do here.
3708 // Now, attempt to route 180 sats.
3709 // Our algorithm should provide us with these 2 paths.
3710 let route = get_route(&our_id, &net_graph_msg_handler.network_graph, &nodes[3],
3711 Some(InvoiceFeatures::known()), None, &Vec::new(), 180_000, 42, Arc::clone(&logger), &scorer).unwrap();
3712 assert_eq!(route.paths.len(), 2);
3714 let mut total_value_transferred_msat = 0;
3715 let mut total_paid_msat = 0;
3716 for path in &route.paths {
3717 assert_eq!(path.last().unwrap().pubkey, nodes[3]);
3718 total_value_transferred_msat += path.last().unwrap().fee_msat;
3720 total_paid_msat += hop.fee_msat;
3723 // If we paid fee, this would be higher.
3724 assert_eq!(total_value_transferred_msat, 180_000);
3725 let total_fees_paid = total_paid_msat - total_value_transferred_msat;
3726 assert_eq!(total_fees_paid, 0);
3731 fn fees_on_mpp_route_test() {
3732 // This test makes sure that MPP algorithm properly takes into account
3733 // fees charged on the channels, by making the fees impactful:
3734 // if the fee is not properly accounted for, the behavior is different.
3735 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
3736 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3737 let scorer = Scorer::new(0);
3739 // We need a route consisting of 2 paths:
3740 // From our node to node3 via {node0, node2} and {node7, node2, node4}.
3741 // We will route 200 sats, Each path will have 100 sats capacity.
3743 // This test is not particularly stable: e.g.,
3744 // there's a way to route via {node0, node2, node4}.
3745 // It works while pathfinding is deterministic, but can be broken otherwise.
3746 // It's fine to ignore this concern for now.
3748 // Disable other potential paths.
3749 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3750 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3751 short_channel_id: 2,
3754 cltv_expiry_delta: 0,
3755 htlc_minimum_msat: 0,
3756 htlc_maximum_msat: OptionalField::Present(100_000),
3758 fee_proportional_millionths: 0,
3759 excess_data: Vec::new()
3762 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3763 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3764 short_channel_id: 7,
3767 cltv_expiry_delta: 0,
3768 htlc_minimum_msat: 0,
3769 htlc_maximum_msat: OptionalField::Present(100_000),
3771 fee_proportional_millionths: 0,
3772 excess_data: Vec::new()
3775 // Path via {node0, node2} is channels {1, 3, 5}.
3776 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3777 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3778 short_channel_id: 1,
3781 cltv_expiry_delta: 0,
3782 htlc_minimum_msat: 0,
3783 htlc_maximum_msat: OptionalField::Present(100_000),
3785 fee_proportional_millionths: 0,
3786 excess_data: Vec::new()
3788 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3789 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3790 short_channel_id: 3,
3793 cltv_expiry_delta: 0,
3794 htlc_minimum_msat: 0,
3795 htlc_maximum_msat: OptionalField::Present(100_000),
3797 fee_proportional_millionths: 0,
3798 excess_data: Vec::new()
3801 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(5)), 5);
3802 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3803 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3804 short_channel_id: 5,
3807 cltv_expiry_delta: 0,
3808 htlc_minimum_msat: 0,
3809 htlc_maximum_msat: OptionalField::Present(100_000),
3811 fee_proportional_millionths: 0,
3812 excess_data: Vec::new()
3815 // Path via {node7, node2, node4} is channels {12, 13, 6, 11}.
3816 // All channels should be 100 sats capacity. But for the fee experiment,
3817 // we'll add absolute fee of 150 sats paid for the use channel 6 (paid to node2 on channel 13).
3818 // Since channel 12 allows to deliver only 250 sats to channel 13, channel 13 can transfer only
3819 // 100 sats (and pay 150 sats in fees for the use of channel 6),
3820 // so no matter how large are other channels,
3821 // the whole path will be limited by 100 sats with just these 2 conditions:
3822 // - channel 12 capacity is 250 sats
3823 // - fee for channel 6 is 150 sats
3824 // Let's test this by enforcing these 2 conditions and removing other limits.
3825 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3826 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3827 short_channel_id: 12,
3830 cltv_expiry_delta: 0,
3831 htlc_minimum_msat: 0,
3832 htlc_maximum_msat: OptionalField::Present(250_000),
3834 fee_proportional_millionths: 0,
3835 excess_data: Vec::new()
3837 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
3838 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3839 short_channel_id: 13,
3842 cltv_expiry_delta: 0,
3843 htlc_minimum_msat: 0,
3844 htlc_maximum_msat: OptionalField::Absent,
3846 fee_proportional_millionths: 0,
3847 excess_data: Vec::new()
3850 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3851 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3852 short_channel_id: 6,
3855 cltv_expiry_delta: 0,
3856 htlc_minimum_msat: 0,
3857 htlc_maximum_msat: OptionalField::Absent,
3858 fee_base_msat: 150_000,
3859 fee_proportional_millionths: 0,
3860 excess_data: Vec::new()
3862 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
3863 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3864 short_channel_id: 11,
3867 cltv_expiry_delta: 0,
3868 htlc_minimum_msat: 0,
3869 htlc_maximum_msat: OptionalField::Absent,
3871 fee_proportional_millionths: 0,
3872 excess_data: Vec::new()
3876 // Attempt to route more than available results in a failure.
3877 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id, &net_graph_msg_handler.network_graph, &nodes[3],
3878 Some(InvoiceFeatures::known()), None, &Vec::new(), 210_000, 42, Arc::clone(&logger), &scorer) {
3879 assert_eq!(err, "Failed to find a sufficient route to the given destination");
3880 } else { panic!(); }
3884 // Now, attempt to route 200 sats (exact amount we can route).
3885 let route = get_route(&our_id, &net_graph_msg_handler.network_graph, &nodes[3],
3886 Some(InvoiceFeatures::known()), None, &Vec::new(), 200_000, 42, Arc::clone(&logger), &scorer).unwrap();
3887 assert_eq!(route.paths.len(), 2);
3889 let mut total_amount_paid_msat = 0;
3890 for path in &route.paths {
3891 assert_eq!(path.last().unwrap().pubkey, nodes[3]);
3892 total_amount_paid_msat += path.last().unwrap().fee_msat;
3894 assert_eq!(total_amount_paid_msat, 200_000);
3895 assert_eq!(route.get_total_fees(), 150_000);
3901 fn drop_lowest_channel_mpp_route_test() {
3902 // This test checks that low-capacity channel is dropped when after
3903 // path finding we realize that we found more capacity than we need.
3904 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
3905 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3906 let scorer = Scorer::new(0);
3908 // We need a route consisting of 3 paths:
3909 // From our node to node2 via node0, node7, node1 (three paths one hop each).
3911 // The first and the second paths should be sufficient, but the third should be
3912 // cheaper, so that we select it but drop later.
3914 // First, we set limits on these (previously unlimited) channels.
3915 // Their aggregate capacity will be 50 + 60 + 20 = 130 sats.
3917 // Path via node0 is channels {1, 3}. Limit them to 100 and 50 sats (total limit 50);
3918 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3919 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3920 short_channel_id: 1,
3923 cltv_expiry_delta: 0,
3924 htlc_minimum_msat: 0,
3925 htlc_maximum_msat: OptionalField::Present(100_000),
3927 fee_proportional_millionths: 0,
3928 excess_data: Vec::new()
3930 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3931 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3932 short_channel_id: 3,
3935 cltv_expiry_delta: 0,
3936 htlc_minimum_msat: 0,
3937 htlc_maximum_msat: OptionalField::Present(50_000),
3939 fee_proportional_millionths: 0,
3940 excess_data: Vec::new()
3943 // Path via node7 is channels {12, 13}. Limit them to 60 and 60 sats (total limit 60);
3944 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3945 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3946 short_channel_id: 12,
3949 cltv_expiry_delta: 0,
3950 htlc_minimum_msat: 0,
3951 htlc_maximum_msat: OptionalField::Present(60_000),
3953 fee_proportional_millionths: 0,
3954 excess_data: Vec::new()
3956 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
3957 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3958 short_channel_id: 13,
3961 cltv_expiry_delta: 0,
3962 htlc_minimum_msat: 0,
3963 htlc_maximum_msat: OptionalField::Present(60_000),
3965 fee_proportional_millionths: 0,
3966 excess_data: Vec::new()
3969 // Path via node1 is channels {2, 4}. Limit them to 20 and 20 sats (total capacity 20 sats).
3970 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3971 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3972 short_channel_id: 2,
3975 cltv_expiry_delta: 0,
3976 htlc_minimum_msat: 0,
3977 htlc_maximum_msat: OptionalField::Present(20_000),
3979 fee_proportional_millionths: 0,
3980 excess_data: Vec::new()
3982 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
3983 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3984 short_channel_id: 4,
3987 cltv_expiry_delta: 0,
3988 htlc_minimum_msat: 0,
3989 htlc_maximum_msat: OptionalField::Present(20_000),
3991 fee_proportional_millionths: 0,
3992 excess_data: Vec::new()
3996 // Attempt to route more than available results in a failure.
3997 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id, &net_graph_msg_handler.network_graph, &nodes[2],
3998 Some(InvoiceFeatures::known()), None, &Vec::new(), 150_000, 42, Arc::clone(&logger), &scorer) {
3999 assert_eq!(err, "Failed to find a sufficient route to the given destination");
4000 } else { panic!(); }
4004 // Now, attempt to route 125 sats (just a bit below the capacity of 3 channels).
4005 // Our algorithm should provide us with these 3 paths.
4006 let route = get_route(&our_id, &net_graph_msg_handler.network_graph, &nodes[2],
4007 Some(InvoiceFeatures::known()), None, &Vec::new(), 125_000, 42, Arc::clone(&logger), &scorer).unwrap();
4008 assert_eq!(route.paths.len(), 3);
4009 let mut total_amount_paid_msat = 0;
4010 for path in &route.paths {
4011 assert_eq!(path.len(), 2);
4012 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
4013 total_amount_paid_msat += path.last().unwrap().fee_msat;
4015 assert_eq!(total_amount_paid_msat, 125_000);
4019 // Attempt to route without the last small cheap channel
4020 let route = get_route(&our_id, &net_graph_msg_handler.network_graph, &nodes[2],
4021 Some(InvoiceFeatures::known()), None, &Vec::new(), 90_000, 42, Arc::clone(&logger), &scorer).unwrap();
4022 assert_eq!(route.paths.len(), 2);
4023 let mut total_amount_paid_msat = 0;
4024 for path in &route.paths {
4025 assert_eq!(path.len(), 2);
4026 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
4027 total_amount_paid_msat += path.last().unwrap().fee_msat;
4029 assert_eq!(total_amount_paid_msat, 90_000);
4034 fn min_criteria_consistency() {
4035 // Test that we don't use an inconsistent metric between updating and walking nodes during
4036 // our Dijkstra's pass. In the initial version of MPP, the "best source" for a given node
4037 // was updated with a different criterion from the heap sorting, resulting in loops in
4038 // calculated paths. We test for that specific case here.
4040 // We construct a network that looks like this:
4042 // node2 -1(3)2- node3
4046 // node1 -1(5)2- node4 -1(1)2- node6
4052 // We create a loop on the side of our real path - our destination is node 6, with a
4053 // previous hop of node 4. From 4, the cheapest previous path is channel 2 from node 2,
4054 // followed by node 3 over channel 3. Thereafter, the cheapest next-hop is back to node 4
4055 // (this time over channel 4). Channel 4 has 0 htlc_minimum_msat whereas channel 1 (the
4056 // other channel with a previous-hop of node 4) has a high (but irrelevant to the overall
4057 // payment) htlc_minimum_msat. In the original algorithm, this resulted in node4's
4058 // "previous hop" being set to node 3, creating a loop in the path.
4059 let secp_ctx = Secp256k1::new();
4060 let logger = Arc::new(test_utils::TestLogger::new());
4061 let network_graph = NetworkGraph::new(genesis_block(Network::Testnet).header.block_hash());
4062 let net_graph_msg_handler = NetGraphMsgHandler::new(network_graph, None, Arc::clone(&logger));
4063 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
4064 let scorer = Scorer::new(0);
4066 add_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, &privkeys[1], ChannelFeatures::from_le_bytes(id_to_feature_flags(6)), 6);
4067 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4068 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4069 short_channel_id: 6,
4072 cltv_expiry_delta: (6 << 8) | 0,
4073 htlc_minimum_msat: 0,
4074 htlc_maximum_msat: OptionalField::Absent,
4076 fee_proportional_millionths: 0,
4077 excess_data: Vec::new()
4079 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[1], NodeFeatures::from_le_bytes(id_to_feature_flags(1)), 0);
4081 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], &privkeys[4], ChannelFeatures::from_le_bytes(id_to_feature_flags(5)), 5);
4082 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
4083 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4084 short_channel_id: 5,
4087 cltv_expiry_delta: (5 << 8) | 0,
4088 htlc_minimum_msat: 0,
4089 htlc_maximum_msat: OptionalField::Absent,
4091 fee_proportional_millionths: 0,
4092 excess_data: Vec::new()
4094 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[4], NodeFeatures::from_le_bytes(id_to_feature_flags(4)), 0);
4096 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(4)), 4);
4097 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
4098 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4099 short_channel_id: 4,
4102 cltv_expiry_delta: (4 << 8) | 0,
4103 htlc_minimum_msat: 0,
4104 htlc_maximum_msat: OptionalField::Absent,
4106 fee_proportional_millionths: 0,
4107 excess_data: Vec::new()
4109 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[3], NodeFeatures::from_le_bytes(id_to_feature_flags(3)), 0);
4111 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[3], &privkeys[2], ChannelFeatures::from_le_bytes(id_to_feature_flags(3)), 3);
4112 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[3], UnsignedChannelUpdate {
4113 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4114 short_channel_id: 3,
4117 cltv_expiry_delta: (3 << 8) | 0,
4118 htlc_minimum_msat: 0,
4119 htlc_maximum_msat: OptionalField::Absent,
4121 fee_proportional_millionths: 0,
4122 excess_data: Vec::new()
4124 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[2], NodeFeatures::from_le_bytes(id_to_feature_flags(2)), 0);
4126 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], &privkeys[4], ChannelFeatures::from_le_bytes(id_to_feature_flags(2)), 2);
4127 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4128 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4129 short_channel_id: 2,
4132 cltv_expiry_delta: (2 << 8) | 0,
4133 htlc_minimum_msat: 0,
4134 htlc_maximum_msat: OptionalField::Absent,
4136 fee_proportional_millionths: 0,
4137 excess_data: Vec::new()
4140 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], &privkeys[6], ChannelFeatures::from_le_bytes(id_to_feature_flags(1)), 1);
4141 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
4142 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4143 short_channel_id: 1,
4146 cltv_expiry_delta: (1 << 8) | 0,
4147 htlc_minimum_msat: 100,
4148 htlc_maximum_msat: OptionalField::Absent,
4150 fee_proportional_millionths: 0,
4151 excess_data: Vec::new()
4153 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[6], NodeFeatures::from_le_bytes(id_to_feature_flags(6)), 0);
4156 // Now ensure the route flows simply over nodes 1 and 4 to 6.
4157 let route = get_route(&our_id, &net_graph_msg_handler.network_graph, &nodes[6], None, None, &Vec::new(), 10_000, 42, Arc::clone(&logger), &scorer).unwrap();
4158 assert_eq!(route.paths.len(), 1);
4159 assert_eq!(route.paths[0].len(), 3);
4161 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
4162 assert_eq!(route.paths[0][0].short_channel_id, 6);
4163 assert_eq!(route.paths[0][0].fee_msat, 100);
4164 assert_eq!(route.paths[0][0].cltv_expiry_delta, (5 << 8) | 0);
4165 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(1));
4166 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(6));
4168 assert_eq!(route.paths[0][1].pubkey, nodes[4]);
4169 assert_eq!(route.paths[0][1].short_channel_id, 5);
4170 assert_eq!(route.paths[0][1].fee_msat, 0);
4171 assert_eq!(route.paths[0][1].cltv_expiry_delta, (1 << 8) | 0);
4172 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(4));
4173 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(5));
4175 assert_eq!(route.paths[0][2].pubkey, nodes[6]);
4176 assert_eq!(route.paths[0][2].short_channel_id, 1);
4177 assert_eq!(route.paths[0][2].fee_msat, 10_000);
4178 assert_eq!(route.paths[0][2].cltv_expiry_delta, 42);
4179 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(6));
4180 assert_eq!(route.paths[0][2].channel_features.le_flags(), &id_to_feature_flags(1));
4186 fn exact_fee_liquidity_limit() {
4187 // Test that if, while walking the graph, we find a hop that has exactly enough liquidity
4188 // for us, including later hop fees, we take it. In the first version of our MPP algorithm
4189 // we calculated fees on a higher value, resulting in us ignoring such paths.
4190 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
4191 let (our_privkey, our_id, _, nodes) = get_nodes(&secp_ctx);
4192 let scorer = Scorer::new(0);
4194 // We modify the graph to set the htlc_maximum of channel 2 to below the value we wish to
4196 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4197 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4198 short_channel_id: 2,
4201 cltv_expiry_delta: 0,
4202 htlc_minimum_msat: 0,
4203 htlc_maximum_msat: OptionalField::Present(85_000),
4205 fee_proportional_millionths: 0,
4206 excess_data: Vec::new()
4209 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4210 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4211 short_channel_id: 12,
4214 cltv_expiry_delta: (4 << 8) | 1,
4215 htlc_minimum_msat: 0,
4216 htlc_maximum_msat: OptionalField::Present(270_000),
4218 fee_proportional_millionths: 1000000,
4219 excess_data: Vec::new()
4223 // Now, attempt to route 90 sats, which is exactly 90 sats at the last hop, plus the
4224 // 200% fee charged channel 13 in the 1-to-2 direction.
4225 let route = get_route(&our_id, &net_graph_msg_handler.network_graph, &nodes[2], None, None, &Vec::new(), 90_000, 42, Arc::clone(&logger), &scorer).unwrap();
4226 assert_eq!(route.paths.len(), 1);
4227 assert_eq!(route.paths[0].len(), 2);
4229 assert_eq!(route.paths[0][0].pubkey, nodes[7]);
4230 assert_eq!(route.paths[0][0].short_channel_id, 12);
4231 assert_eq!(route.paths[0][0].fee_msat, 90_000*2);
4232 assert_eq!(route.paths[0][0].cltv_expiry_delta, (13 << 8) | 1);
4233 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(8));
4234 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(12));
4236 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
4237 assert_eq!(route.paths[0][1].short_channel_id, 13);
4238 assert_eq!(route.paths[0][1].fee_msat, 90_000);
4239 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
4240 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
4241 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(13));
4246 fn htlc_max_reduction_below_min() {
4247 // Test that if, while walking the graph, we reduce the value being sent to meet an
4248 // htlc_maximum_msat, we don't end up undershooting a later htlc_minimum_msat. In the
4249 // initial version of MPP we'd accept such routes but reject them while recalculating fees,
4250 // resulting in us thinking there is no possible path, even if other paths exist.
4251 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
4252 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
4253 let scorer = Scorer::new(0);
4255 // We modify the graph to set the htlc_minimum of channel 2 and 4 as needed - channel 2
4256 // gets an htlc_maximum_msat of 80_000 and channel 4 an htlc_minimum_msat of 90_000. We
4257 // then try to send 90_000.
4258 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4259 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4260 short_channel_id: 2,
4263 cltv_expiry_delta: 0,
4264 htlc_minimum_msat: 0,
4265 htlc_maximum_msat: OptionalField::Present(80_000),
4267 fee_proportional_millionths: 0,
4268 excess_data: Vec::new()
4270 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
4271 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4272 short_channel_id: 4,
4275 cltv_expiry_delta: (4 << 8) | 1,
4276 htlc_minimum_msat: 90_000,
4277 htlc_maximum_msat: OptionalField::Absent,
4279 fee_proportional_millionths: 0,
4280 excess_data: Vec::new()
4284 // Now, attempt to route 90 sats, hitting the htlc_minimum on channel 4, but
4285 // overshooting the htlc_maximum on channel 2. Thus, we should pick the (absurdly
4286 // expensive) channels 12-13 path.
4287 let route = get_route(&our_id, &net_graph_msg_handler.network_graph, &nodes[2], Some(InvoiceFeatures::known()), None, &Vec::new(), 90_000, 42, Arc::clone(&logger), &scorer).unwrap();
4288 assert_eq!(route.paths.len(), 1);
4289 assert_eq!(route.paths[0].len(), 2);
4291 assert_eq!(route.paths[0][0].pubkey, nodes[7]);
4292 assert_eq!(route.paths[0][0].short_channel_id, 12);
4293 assert_eq!(route.paths[0][0].fee_msat, 90_000*2);
4294 assert_eq!(route.paths[0][0].cltv_expiry_delta, (13 << 8) | 1);
4295 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(8));
4296 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(12));
4298 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
4299 assert_eq!(route.paths[0][1].short_channel_id, 13);
4300 assert_eq!(route.paths[0][1].fee_msat, 90_000);
4301 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
4302 assert_eq!(route.paths[0][1].node_features.le_flags(), InvoiceFeatures::known().le_flags());
4303 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(13));
4308 fn multiple_direct_first_hops() {
4309 // Previously we'd only ever considered one first hop path per counterparty.
4310 // However, as we don't restrict users to one channel per peer, we really need to support
4311 // looking at all first hop paths.
4312 // Here we test that we do not ignore all-but-the-last first hop paths per counterparty (as
4313 // we used to do by overwriting the `first_hop_targets` hashmap entry) and that we can MPP
4314 // route over multiple channels with the same first hop.
4315 let secp_ctx = Secp256k1::new();
4316 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
4317 let logger = Arc::new(test_utils::TestLogger::new());
4318 let network_graph = NetworkGraph::new(genesis_block(Network::Testnet).header.block_hash());
4319 let scorer = Scorer::new(0);
4322 let route = get_route(&our_id, &network_graph, &nodes[0], Some(InvoiceFeatures::known()), Some(&[
4323 &get_channel_details(Some(3), nodes[0], InitFeatures::known(), 200_000),
4324 &get_channel_details(Some(2), nodes[0], InitFeatures::known(), 10_000),
4325 ]), &[], 100_000, 42, Arc::clone(&logger), &scorer).unwrap();
4326 assert_eq!(route.paths.len(), 1);
4327 assert_eq!(route.paths[0].len(), 1);
4329 assert_eq!(route.paths[0][0].pubkey, nodes[0]);
4330 assert_eq!(route.paths[0][0].short_channel_id, 3);
4331 assert_eq!(route.paths[0][0].fee_msat, 100_000);
4334 let route = get_route(&our_id, &network_graph, &nodes[0], Some(InvoiceFeatures::known()), Some(&[
4335 &get_channel_details(Some(3), nodes[0], InitFeatures::known(), 50_000),
4336 &get_channel_details(Some(2), nodes[0], InitFeatures::known(), 50_000),
4337 ]), &[], 100_000, 42, Arc::clone(&logger), &scorer).unwrap();
4338 assert_eq!(route.paths.len(), 2);
4339 assert_eq!(route.paths[0].len(), 1);
4340 assert_eq!(route.paths[1].len(), 1);
4342 assert_eq!(route.paths[0][0].pubkey, nodes[0]);
4343 assert_eq!(route.paths[0][0].short_channel_id, 3);
4344 assert_eq!(route.paths[0][0].fee_msat, 50_000);
4346 assert_eq!(route.paths[1][0].pubkey, nodes[0]);
4347 assert_eq!(route.paths[1][0].short_channel_id, 2);
4348 assert_eq!(route.paths[1][0].fee_msat, 50_000);
4353 fn prefers_shorter_route_with_higher_fees() {
4354 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
4355 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
4357 // Without penalizing each hop 100 msats, a longer path with lower fees is chosen.
4358 let scorer = Scorer::new(0);
4359 let route = get_route(
4360 &our_id, &net_graph_msg_handler.network_graph, &nodes[6], None, None,
4361 &last_hops(&nodes).iter().collect::<Vec<_>>(), 100, 42, Arc::clone(&logger), &scorer
4363 let path = route.paths[0].iter().map(|hop| hop.short_channel_id).collect::<Vec<_>>();
4365 assert_eq!(route.get_total_fees(), 100);
4366 assert_eq!(route.get_total_amount(), 100);
4367 assert_eq!(path, vec![2, 4, 6, 11, 8]);
4369 // Applying a 100 msat penalty to each hop results in taking channels 7 and 10 to nodes[6]
4370 // from nodes[2] rather than channel 6, 11, and 8, even though the longer path is cheaper.
4371 let scorer = Scorer::new(100);
4372 let route = get_route(
4373 &our_id, &net_graph_msg_handler.network_graph, &nodes[6], None, None,
4374 &last_hops(&nodes).iter().collect::<Vec<_>>(), 100, 42, Arc::clone(&logger), &scorer
4376 let path = route.paths[0].iter().map(|hop| hop.short_channel_id).collect::<Vec<_>>();
4378 assert_eq!(route.get_total_fees(), 300);
4379 assert_eq!(route.get_total_amount(), 100);
4380 assert_eq!(path, vec![2, 4, 7, 10]);
4383 struct BadChannelScorer {
4384 short_channel_id: u64,
4387 impl routing::Score for BadChannelScorer {
4388 fn channel_penalty_msat(&self, short_channel_id: u64, _source: &NodeId, _target: &NodeId) -> u64 {
4389 if short_channel_id == self.short_channel_id { u64::max_value() } else { 0 }
4393 struct BadNodeScorer {
4397 impl routing::Score for BadNodeScorer {
4398 fn channel_penalty_msat(&self, _short_channel_id: u64, _source: &NodeId, target: &NodeId) -> u64 {
4399 if *target == self.node_id { u64::max_value() } else { 0 }
4404 fn avoids_routing_through_bad_channels_and_nodes() {
4405 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
4406 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
4408 // A path to nodes[6] exists when no penalties are applied to any channel.
4409 let scorer = Scorer::new(0);
4410 let route = get_route(
4411 &our_id, &net_graph_msg_handler.network_graph, &nodes[6], None, None,
4412 &last_hops(&nodes).iter().collect::<Vec<_>>(), 100, 42, Arc::clone(&logger), &scorer
4414 let path = route.paths[0].iter().map(|hop| hop.short_channel_id).collect::<Vec<_>>();
4416 assert_eq!(route.get_total_fees(), 100);
4417 assert_eq!(route.get_total_amount(), 100);
4418 assert_eq!(path, vec![2, 4, 6, 11, 8]);
4420 // A different path to nodes[6] exists if channel 6 cannot be routed over.
4421 let scorer = BadChannelScorer { short_channel_id: 6 };
4422 let route = get_route(
4423 &our_id, &net_graph_msg_handler.network_graph, &nodes[6], None, None,
4424 &last_hops(&nodes).iter().collect::<Vec<_>>(), 100, 42, Arc::clone(&logger), &scorer
4426 let path = route.paths[0].iter().map(|hop| hop.short_channel_id).collect::<Vec<_>>();
4428 assert_eq!(route.get_total_fees(), 300);
4429 assert_eq!(route.get_total_amount(), 100);
4430 assert_eq!(path, vec![2, 4, 7, 10]);
4432 // A path to nodes[6] does not exist if nodes[2] cannot be routed through.
4433 let scorer = BadNodeScorer { node_id: NodeId::from_pubkey(&nodes[2]) };
4435 &our_id, &net_graph_msg_handler.network_graph, &nodes[6], None, None,
4436 &last_hops(&nodes).iter().collect::<Vec<_>>(), 100, 42, Arc::clone(&logger), &scorer
4438 Err(LightningError { err, .. } ) => {
4439 assert_eq!(err, "Failed to find a path to the given destination");
4441 Ok(_) => panic!("Expected error"),
4446 fn total_fees_single_path() {
4450 pubkey: PublicKey::from_slice(&hex::decode("02eec7245d6b7d2ccb30380bfbe2a3648cd7a942653f5aa340edcea1f283686619").unwrap()[..]).unwrap(),
4451 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
4452 short_channel_id: 0, fee_msat: 100, cltv_expiry_delta: 0
4455 pubkey: PublicKey::from_slice(&hex::decode("0324653eac434488002cc06bbfb7f10fe18991e35f9fe4302dbea6d2353dc0ab1c").unwrap()[..]).unwrap(),
4456 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
4457 short_channel_id: 0, fee_msat: 150, cltv_expiry_delta: 0
4460 pubkey: PublicKey::from_slice(&hex::decode("027f31ebc5462c1fdce1b737ecff52d37d75dea43ce11c74d25aa297165faa2007").unwrap()[..]).unwrap(),
4461 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
4462 short_channel_id: 0, fee_msat: 225, cltv_expiry_delta: 0
4467 assert_eq!(route.get_total_fees(), 250);
4468 assert_eq!(route.get_total_amount(), 225);
4472 fn total_fees_multi_path() {
4476 pubkey: PublicKey::from_slice(&hex::decode("02eec7245d6b7d2ccb30380bfbe2a3648cd7a942653f5aa340edcea1f283686619").unwrap()[..]).unwrap(),
4477 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
4478 short_channel_id: 0, fee_msat: 100, cltv_expiry_delta: 0
4481 pubkey: PublicKey::from_slice(&hex::decode("0324653eac434488002cc06bbfb7f10fe18991e35f9fe4302dbea6d2353dc0ab1c").unwrap()[..]).unwrap(),
4482 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
4483 short_channel_id: 0, fee_msat: 150, cltv_expiry_delta: 0
4487 pubkey: PublicKey::from_slice(&hex::decode("02eec7245d6b7d2ccb30380bfbe2a3648cd7a942653f5aa340edcea1f283686619").unwrap()[..]).unwrap(),
4488 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
4489 short_channel_id: 0, fee_msat: 100, cltv_expiry_delta: 0
4492 pubkey: PublicKey::from_slice(&hex::decode("0324653eac434488002cc06bbfb7f10fe18991e35f9fe4302dbea6d2353dc0ab1c").unwrap()[..]).unwrap(),
4493 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
4494 short_channel_id: 0, fee_msat: 150, cltv_expiry_delta: 0
4499 assert_eq!(route.get_total_fees(), 200);
4500 assert_eq!(route.get_total_amount(), 300);
4504 fn total_empty_route_no_panic() {
4505 // In an earlier version of `Route::get_total_fees` and `Route::get_total_amount`, they
4506 // would both panic if the route was completely empty. We test to ensure they return 0
4507 // here, even though its somewhat nonsensical as a route.
4508 let route = Route { paths: Vec::new() };
4510 assert_eq!(route.get_total_fees(), 0);
4511 assert_eq!(route.get_total_amount(), 0);
4514 #[cfg(not(feature = "no-std"))]
4515 pub(super) fn random_init_seed() -> u64 {
4516 // Because the default HashMap in std pulls OS randomness, we can use it as a (bad) RNG.
4517 use core::hash::{BuildHasher, Hasher};
4518 let seed = std::collections::hash_map::RandomState::new().build_hasher().finish();
4519 println!("Using seed of {}", seed);
4522 #[cfg(not(feature = "no-std"))]
4523 use util::ser::Readable;
4526 #[cfg(not(feature = "no-std"))]
4527 fn generate_routes() {
4528 let mut d = match super::test_utils::get_route_file() {
4535 let graph = NetworkGraph::read(&mut d).unwrap();
4536 let scorer = Scorer::new(0);
4538 // First, get 100 (source, destination) pairs for which route-getting actually succeeds...
4539 let mut seed = random_init_seed() as usize;
4540 let nodes = graph.read_only().nodes().clone();
4541 'load_endpoints: for _ in 0..10 {
4543 seed = seed.overflowing_mul(0xdeadbeef).0;
4544 let src = &PublicKey::from_slice(nodes.keys().skip(seed % nodes.len()).next().unwrap().as_slice()).unwrap();
4545 seed = seed.overflowing_mul(0xdeadbeef).0;
4546 let dst = &PublicKey::from_slice(nodes.keys().skip(seed % nodes.len()).next().unwrap().as_slice()).unwrap();
4547 let amt = seed as u64 % 200_000_000;
4548 if get_route(src, &graph, dst, None, None, &[], amt, 42, &test_utils::TestLogger::new(), &scorer).is_ok() {
4549 continue 'load_endpoints;
4556 #[cfg(not(feature = "no-std"))]
4557 fn generate_routes_mpp() {
4558 let mut d = match super::test_utils::get_route_file() {
4565 let graph = NetworkGraph::read(&mut d).unwrap();
4566 let scorer = Scorer::new(0);
4568 // First, get 100 (source, destination) pairs for which route-getting actually succeeds...
4569 let mut seed = random_init_seed() as usize;
4570 let nodes = graph.read_only().nodes().clone();
4571 'load_endpoints: for _ in 0..10 {
4573 seed = seed.overflowing_mul(0xdeadbeef).0;
4574 let src = &PublicKey::from_slice(nodes.keys().skip(seed % nodes.len()).next().unwrap().as_slice()).unwrap();
4575 seed = seed.overflowing_mul(0xdeadbeef).0;
4576 let dst = &PublicKey::from_slice(nodes.keys().skip(seed % nodes.len()).next().unwrap().as_slice()).unwrap();
4577 let amt = seed as u64 % 200_000_000;
4578 if get_route(src, &graph, dst, Some(InvoiceFeatures::known()), None, &[], amt, 42, &test_utils::TestLogger::new(), &scorer).is_ok() {
4579 continue 'load_endpoints;
4586 #[cfg(all(test, not(feature = "no-std")))]
4587 pub(crate) mod test_utils {
4589 /// Tries to open a network graph file, or panics with a URL to fetch it.
4590 pub(crate) fn get_route_file() -> Result<std::fs::File, &'static str> {
4591 let res = File::open("net_graph-2021-05-31.bin") // By default we're run in RL/lightning
4592 .or_else(|_| File::open("lightning/net_graph-2021-05-31.bin")) // We may be run manually in RL/
4593 .or_else(|_| { // Fall back to guessing based on the binary location
4594 // path is likely something like .../rust-lightning/target/debug/deps/lightning-...
4595 let mut path = std::env::current_exe().unwrap();
4596 path.pop(); // lightning-...
4598 path.pop(); // debug
4599 path.pop(); // target
4600 path.push("lightning");
4601 path.push("net_graph-2021-05-31.bin");
4602 eprintln!("{}", path.to_str().unwrap());
4605 .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");
4606 #[cfg(require_route_graph_test)]
4607 return Ok(res.unwrap());
4608 #[cfg(not(require_route_graph_test))]
4613 #[cfg(all(test, feature = "unstable", not(feature = "no-std")))]
4616 use routing::scorer::Scorer;
4617 use util::logger::{Logger, Record};
4621 struct DummyLogger {}
4622 impl Logger for DummyLogger {
4623 fn log(&self, _record: &Record) {}
4627 fn generate_routes(bench: &mut Bencher) {
4628 let mut d = test_utils::get_route_file().unwrap();
4629 let graph = NetworkGraph::read(&mut d).unwrap();
4630 let nodes = graph.read_only().nodes().clone();
4631 let scorer = Scorer::new(0);
4633 // First, get 100 (source, destination) pairs for which route-getting actually succeeds...
4634 let mut path_endpoints = Vec::new();
4635 let mut seed: usize = 0xdeadbeef;
4636 'load_endpoints: for _ in 0..100 {
4639 let src = PublicKey::from_slice(nodes.keys().skip(seed % nodes.len()).next().unwrap().as_slice()).unwrap();
4641 let dst = PublicKey::from_slice(nodes.keys().skip(seed % nodes.len()).next().unwrap().as_slice()).unwrap();
4642 let amt = seed as u64 % 1_000_000;
4643 if get_route(&src, &graph, &dst, None, None, &[], amt, 42, &DummyLogger{}, &scorer).is_ok() {
4644 path_endpoints.push((src, dst, amt));
4645 continue 'load_endpoints;
4650 // ...then benchmark finding paths between the nodes we learned.
4653 let (src, dst, amt) = path_endpoints[idx % path_endpoints.len()];
4654 assert!(get_route(&src, &graph, &dst, None, None, &[], amt, 42, &DummyLogger{}, &scorer).is_ok());
4660 fn generate_mpp_routes(bench: &mut Bencher) {
4661 let mut d = test_utils::get_route_file().unwrap();
4662 let graph = NetworkGraph::read(&mut d).unwrap();
4663 let nodes = graph.read_only().nodes().clone();
4664 let scorer = Scorer::new(0);
4666 // First, get 100 (source, destination) pairs for which route-getting actually succeeds...
4667 let mut path_endpoints = Vec::new();
4668 let mut seed: usize = 0xdeadbeef;
4669 'load_endpoints: for _ in 0..100 {
4672 let src = PublicKey::from_slice(nodes.keys().skip(seed % nodes.len()).next().unwrap().as_slice()).unwrap();
4674 let dst = PublicKey::from_slice(nodes.keys().skip(seed % nodes.len()).next().unwrap().as_slice()).unwrap();
4675 let amt = seed as u64 % 1_000_000;
4676 if get_route(&src, &graph, &dst, Some(InvoiceFeatures::known()), None, &[], amt, 42, &DummyLogger{}, &scorer).is_ok() {
4677 path_endpoints.push((src, dst, amt));
4678 continue 'load_endpoints;
4683 // ...then benchmark finding paths between the nodes we learned.
4686 let (src, dst, amt) = path_endpoints[idx % path_endpoints.len()];
4687 assert!(get_route(&src, &graph, &dst, Some(InvoiceFeatures::known()), None, &[], amt, 42, &DummyLogger{}, &scorer).is_ok());