1 // This file is Copyright its original authors, visible in version control
4 // This file is licensed under the Apache License, Version 2.0 <LICENSE-APACHE
5 // or http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
6 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your option.
7 // You may not use this file except in accordance with one or both of these
10 //! The top-level routing/network map tracking logic lives here.
12 //! You probably want to create a NetGraphMsgHandler and use that as your RoutingMessageHandler and then
13 //! interrogate it to get routes for your own payments.
15 use bitcoin::secp256k1::key::PublicKey;
17 use ln::channelmanager::ChannelDetails;
18 use ln::features::{ChannelFeatures, InvoiceFeatures, NodeFeatures};
19 use ln::msgs::{DecodeError, ErrorAction, LightningError, MAX_VALUE_MSAT};
20 use routing::network_graph::{NetworkGraph, RoutingFees};
21 use util::ser::{Writeable, Readable};
22 use util::logger::Logger;
25 use std::collections::{HashMap, BinaryHeap};
29 #[derive(Clone, PartialEq)]
31 /// The node_id of the node at this hop.
32 pub pubkey: PublicKey,
33 /// The node_announcement features of the node at this hop. For the last hop, these may be
34 /// amended to match the features present in the invoice this node generated.
35 pub node_features: NodeFeatures,
36 /// The channel that should be used from the previous hop to reach this node.
37 pub short_channel_id: u64,
38 /// The channel_announcement features of the channel that should be used from the previous hop
39 /// to reach this node.
40 pub channel_features: ChannelFeatures,
41 /// The fee taken on this hop (for paying for the use of the *next* channel in the path).
42 /// For the last hop, this should be the full value of the payment (might be more than
43 /// requested if we had to match htlc_minimum_msat).
45 /// The CLTV delta added for this hop. For the last hop, this should be the full CLTV value
46 /// expected at the destination, in excess of the current block height.
47 pub cltv_expiry_delta: u32,
51 impl Writeable for Vec<RouteHop> {
52 fn write<W: ::util::ser::Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
53 (self.len() as u8).write(writer)?;
54 for hop in self.iter() {
55 hop.pubkey.write(writer)?;
56 hop.node_features.write(writer)?;
57 hop.short_channel_id.write(writer)?;
58 hop.channel_features.write(writer)?;
59 hop.fee_msat.write(writer)?;
60 hop.cltv_expiry_delta.write(writer)?;
67 impl Readable for Vec<RouteHop> {
68 fn read<R: ::std::io::Read>(reader: &mut R) -> Result<Vec<RouteHop>, DecodeError> {
69 let hops_count: u8 = Readable::read(reader)?;
70 let mut hops = Vec::with_capacity(hops_count as usize);
71 for _ in 0..hops_count {
73 pubkey: Readable::read(reader)?,
74 node_features: Readable::read(reader)?,
75 short_channel_id: Readable::read(reader)?,
76 channel_features: Readable::read(reader)?,
77 fee_msat: Readable::read(reader)?,
78 cltv_expiry_delta: Readable::read(reader)?,
85 /// A route directs a payment from the sender (us) to the recipient. If the recipient supports MPP,
86 /// it can take multiple paths. Each path is composed of one or more hops through the network.
87 #[derive(Clone, PartialEq)]
89 /// The list of routes taken for a single (potentially-)multi-part payment. The pubkey of the
90 /// last RouteHop in each path must be the same.
91 /// Each entry represents a list of hops, NOT INCLUDING our own, where the last hop is the
92 /// destination. Thus, this must always be at least length one. While the maximum length of any
93 /// given path is variable, keeping the length of any path to less than 20 should currently
94 /// ensure it is viable.
95 pub paths: Vec<Vec<RouteHop>>,
98 impl Writeable for Route {
99 fn write<W: ::util::ser::Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
100 (self.paths.len() as u64).write(writer)?;
101 for hops in self.paths.iter() {
108 impl Readable for Route {
109 fn read<R: ::std::io::Read>(reader: &mut R) -> Result<Route, DecodeError> {
110 let path_count: u64 = Readable::read(reader)?;
111 let mut paths = Vec::with_capacity(cmp::min(path_count, 128) as usize);
112 for _ in 0..path_count {
113 paths.push(Readable::read(reader)?);
119 /// A channel descriptor which provides a last-hop route to get_route
121 pub struct RouteHint {
122 /// The node_id of the non-target end of the route
123 pub src_node_id: PublicKey,
124 /// The short_channel_id of this channel
125 pub short_channel_id: u64,
126 /// The fees which must be paid to use this channel
127 pub fees: RoutingFees,
128 /// The difference in CLTV values between this node and the next node.
129 pub cltv_expiry_delta: u16,
130 /// The minimum value, in msat, which must be relayed to the next hop.
131 pub htlc_minimum_msat: Option<u64>,
132 /// The maximum value in msat available for routing with a single HTLC.
133 pub htlc_maximum_msat: Option<u64>,
136 #[derive(Eq, PartialEq)]
137 struct RouteGraphNode {
139 lowest_fee_to_peer_through_node: u64,
140 lowest_fee_to_node: u64,
141 // The maximum value a yet-to-be-constructed payment path might flow through this node.
142 // This value is upper-bounded by us by:
143 // - how much is needed for a path being constructed
144 // - how much value can channels following this node (up to the destination) can contribute,
145 // considering their capacity and fees
146 value_contribution_msat: u64,
147 /// The maximum htlc_minimum_msat along the path, taking into consideration the fees required
148 /// to meet the minimum over the hops required to get there.
149 path_htlc_minimum_msat: u64,
152 impl cmp::Ord for RouteGraphNode {
153 fn cmp(&self, other: &RouteGraphNode) -> cmp::Ordering {
154 cmp::max(other.lowest_fee_to_peer_through_node, other.path_htlc_minimum_msat)
155 .cmp(&cmp::max(self.lowest_fee_to_peer_through_node, self.path_htlc_minimum_msat))
156 .then_with(|| other.pubkey.serialize().cmp(&self.pubkey.serialize()))
160 impl cmp::PartialOrd for RouteGraphNode {
161 fn partial_cmp(&self, other: &RouteGraphNode) -> Option<cmp::Ordering> {
162 Some(self.cmp(other))
166 struct DummyDirectionalChannelInfo {
167 cltv_expiry_delta: u32,
168 htlc_minimum_msat: u64,
169 htlc_maximum_msat: Option<u64>,
173 /// It's useful to keep track of the hops associated with the fees required to use them,
174 /// so that we can choose cheaper paths (as per Dijkstra's algorithm).
175 /// Fee values should be updated only in the context of the whole path, see update_value_and_recompute_fees.
176 /// These fee values are useful to choose hops as we traverse the graph "payee-to-payer".
178 struct PathBuildingHop {
179 /// Hop-specific details unrelated to the path during the routing phase,
180 /// but rather relevant to the LN graph.
182 /// Minimal fees required to route to the source node of the current hop via any of its inbound channels.
183 src_lowest_inbound_fees: RoutingFees,
184 /// Fees of the channel used in this hop.
185 channel_fees: RoutingFees,
186 /// All the fees paid *after* this channel on the way to the destination
187 next_hops_fee_msat: u64,
188 /// Fee paid for the use of the current channel (see channel_fees).
189 /// The value will be actually deducted from the counterparty balance on the previous link.
190 hop_use_fee_msat: u64,
191 /// Used to compare channels when choosing the for routing.
192 /// Includes paying for the use of a hop and the following hops, as well as
193 /// an estimated cost of reaching this hop.
194 /// Might get stale when fees are recomputed. Primarily for internal use.
196 /// This is useful for update_value_and_recompute_fees to make sure
197 /// we don't fall below the minimum. Should not be updated manually and
198 /// generally should not be accessed.
199 htlc_minimum_msat: u64,
200 /// A mirror of the same field in RouteGraphNode. Note that this is only used during the graph
201 /// walk and may be invalid thereafter.
202 path_htlc_minimum_msat: u64,
205 // Instantiated with a list of hops with correct data in them collected during path finding,
206 // an instance of this struct should be further modified only via given methods.
209 hops: Vec<PathBuildingHop>,
214 // TODO: Add a value_msat field to PaymentPath and use it instead of this function.
215 fn get_value_msat(&self) -> u64 {
216 self.hops.last().unwrap().route_hop.fee_msat
219 fn get_total_fee_paid_msat(&self) -> u64 {
220 if self.hops.len() < 1 {
224 // Can't use next_hops_fee_msat because it gets outdated.
225 for (i, hop) in self.hops.iter().enumerate() {
226 if i != self.hops.len() - 1 {
227 result += hop.route_hop.fee_msat;
233 // If the amount transferred by the path is updated, the fees should be adjusted. Any other way
234 // to change fees may result in an inconsistency.
236 // Sometimes we call this function right after constructing a path which has inconsistent
237 // (in terms of reaching htlc_minimum_msat), so that this function puts the fees in order.
238 // In that case we call it on the "same" amount we initially allocated for this path, and which
239 // could have been reduced on the way. In that case, there is also a risk of exceeding
240 // available_liquidity inside this function, because the function is unaware of this bound.
241 // In our specific recomputation cases where we never increase the value the risk is pretty low.
242 // This function, however, does not support arbitrarily increasing the value being transferred,
243 // and the exception will be triggered.
244 fn update_value_and_recompute_fees(&mut self, value_msat: u64) {
245 assert!(value_msat <= self.hops.last().unwrap().route_hop.fee_msat);
247 let mut total_fee_paid_msat = 0 as u64;
248 for i in (0..self.hops.len()).rev() {
249 let last_hop = i == self.hops.len() - 1;
251 // For non-last-hop, this value will represent the fees paid on the current hop. It
252 // will consist of the fees for the use of the next hop, and extra fees to match
253 // htlc_minimum_msat of the current channel. Last hop is handled separately.
254 let mut cur_hop_fees_msat = 0;
256 cur_hop_fees_msat = self.hops.get(i + 1).unwrap().hop_use_fee_msat;
259 let mut cur_hop = self.hops.get_mut(i).unwrap();
260 cur_hop.next_hops_fee_msat = total_fee_paid_msat;
261 // Overpay in fees if we can't save these funds due to htlc_minimum_msat.
262 // We try to account for htlc_minimum_msat in scoring (add_entry!), so that nodes don't
263 // set it too high just to maliciously take more fees by exploiting this
264 // match htlc_minimum_msat logic.
265 let mut cur_hop_transferred_amount_msat = total_fee_paid_msat + value_msat;
266 if let Some(extra_fees_msat) = cur_hop.htlc_minimum_msat.checked_sub(cur_hop_transferred_amount_msat) {
267 // Note that there is a risk that *previous hops* (those closer to us, as we go
268 // payee->our_node here) would exceed their htlc_maximum_msat or available balance.
270 // This might make us end up with a broken route, although this should be super-rare
271 // in practice, both because of how healthy channels look like, and how we pick
272 // channels in add_entry.
273 // Also, this can't be exploited more heavily than *announce a free path and fail
275 cur_hop_transferred_amount_msat += extra_fees_msat;
276 total_fee_paid_msat += extra_fees_msat;
277 cur_hop_fees_msat += extra_fees_msat;
281 // Final hop is a special case: it usually has just value_msat (by design), but also
282 // it still could overpay for the htlc_minimum_msat.
283 cur_hop.route_hop.fee_msat = cur_hop_transferred_amount_msat;
285 // Propagate updated fees for the use of the channels to one hop back, where they
286 // will be actually paid (fee_msat). The last hop is handled above separately.
287 cur_hop.route_hop.fee_msat = cur_hop_fees_msat;
290 // Fee for the use of the current hop which will be deducted on the previous hop.
291 // Irrelevant for the first hop, as it doesn't have the previous hop, and the use of
292 // this channel is free for us.
294 if let Some(new_fee) = compute_fees(cur_hop_transferred_amount_msat, cur_hop.channel_fees) {
295 cur_hop.hop_use_fee_msat = new_fee;
296 total_fee_paid_msat += new_fee;
298 // It should not be possible because this function is called only to reduce the
299 // value. In that case, compute_fee was already called with the same fees for
300 // larger amount and there was no overflow.
308 fn compute_fees(amount_msat: u64, channel_fees: RoutingFees) -> Option<u64> {
309 let proportional_fee_millions =
310 amount_msat.checked_mul(channel_fees.proportional_millionths as u64);
311 if let Some(new_fee) = proportional_fee_millions.and_then(|part| {
312 (channel_fees.base_msat as u64).checked_add(part / 1_000_000) }) {
316 // This function may be (indirectly) called without any verification,
317 // with channel_fees provided by a caller. We should handle it gracefully.
322 /// Gets a route from us (payer) to the given target node (payee).
324 /// If the payee provided features in their invoice, they should be provided via payee_features.
325 /// Without this, MPP will only be used if the payee's features are available in the network graph.
327 /// Extra routing hops between known nodes and the target will be used if they are included in
330 /// If some channels aren't announced, it may be useful to fill in a first_hops with the
331 /// results from a local ChannelManager::list_usable_channels() call. If it is filled in, our
332 /// view of our local channels (from net_graph_msg_handler) will be ignored, and only those
333 /// in first_hops will be used.
335 /// Panics if first_hops contains channels without short_channel_ids
336 /// (ChannelManager::list_usable_channels will never include such channels).
338 /// The fees on channels from us to next-hops are ignored (as they are assumed to all be
339 /// equal), however the enabled/disabled bit on such channels as well as the
340 /// htlc_minimum_msat/htlc_maximum_msat *are* checked as they may change based on the receiving node.
341 pub fn get_route<L: Deref>(our_node_id: &PublicKey, network: &NetworkGraph, payee: &PublicKey, payee_features: Option<InvoiceFeatures>, first_hops: Option<&[&ChannelDetails]>,
342 last_hops: &[&RouteHint], final_value_msat: u64, final_cltv: u32, logger: L) -> Result<Route, LightningError> where L::Target: Logger {
343 // TODO: Obviously *only* using total fee cost sucks. We should consider weighting by
344 // uptime/success in using a node in the past.
345 if *payee == *our_node_id {
346 return Err(LightningError{err: "Cannot generate a route to ourselves".to_owned(), action: ErrorAction::IgnoreError});
349 if final_value_msat > MAX_VALUE_MSAT {
350 return Err(LightningError{err: "Cannot generate a route of more value than all existing satoshis".to_owned(), action: ErrorAction::IgnoreError});
353 if final_value_msat == 0 {
354 return Err(LightningError{err: "Cannot send a payment of 0 msat".to_owned(), action: ErrorAction::IgnoreError});
357 for last_hop in last_hops {
358 if last_hop.src_node_id == *payee {
359 return Err(LightningError{err: "Last hop cannot have a payee as a source.".to_owned(), action: ErrorAction::IgnoreError});
363 // The general routing idea is the following:
364 // 1. Fill first/last hops communicated by the caller.
365 // 2. Attempt to construct a path from payer to payee for transferring
366 // any ~sufficient (described later) value.
367 // If succeed, remember which channels were used and how much liquidity they have available,
368 // so that future paths don't rely on the same liquidity.
369 // 3. Prooceed to the next step if:
370 // - we hit the recommended target value;
371 // - OR if we could not construct a new path. Any next attempt will fail too.
372 // Otherwise, repeat step 2.
373 // 4. See if we managed to collect paths which aggregately are able to transfer target value
374 // (not recommended value). If yes, proceed. If not, fail routing.
375 // 5. Randomly combine paths into routes having enough to fulfill the payment. (TODO: knapsack)
376 // 6. Of all the found paths, select only those with the lowest total fee.
377 // 7. The last path in every selected route is likely to be more than we need.
378 // Reduce its value-to-transfer and recompute fees.
379 // 8. Choose the best route by the lowest total fee.
381 // As for the actual search algorithm,
382 // we do a payee-to-payer pseudo-Dijkstra's sorting by each node's distance from the payee
383 // plus the minimum per-HTLC fee to get from it to another node (aka "shitty pseudo-A*").
385 // We are not a faithful Dijkstra's implementation because we can change values which impact
386 // earlier nodes while processing later nodes. Specifically, if we reach a channel with a lower
387 // liquidity limit (via htlc_maximum_msat, on-chain capacity or assumed liquidity limits) then
388 // the value we are currently attempting to send over a path, we simply reduce the value being
389 // sent along the path for any hops after that channel. This may imply that later fees (which
390 // we've already tabulated) are lower because a smaller value is passing through the channels
391 // (and the proportional fee is thus lower). There isn't a trivial way to recalculate the
392 // channels which were selected earlier (and which may still be used for other paths without a
393 // lower liquidity limit), so we simply accept that some liquidity-limited paths may be
396 // One potentially problematic case for this algorithm would be if there are many
397 // liquidity-limited paths which are liquidity-limited near the destination (ie early in our
398 // graph walking), we may never find a liquidity-unlimited path which has lower proportional
399 // fee (and only lower absolute fee when considering the ultimate value sent). Because we only
400 // consider paths with at least 5% of the total value being sent, the damage from such a case
401 // should be limited, however this could be further reduced in the future by calculating fees
402 // on the amount we wish to route over a path, not the amount we are routing over a path.
404 // Alternatively, we could store more detailed path information in the heap (targets, below)
405 // and index the best-path map (dist, below) by node *and* HTLC limits, however that would blow
406 // up the runtime significantly both algorithmically (as we'd traverse nodes multiple times)
407 // and practically (as we would need to store dynamically-allocated path information in heap
408 // objects, increasing malloc traffic and indirect memory access significantly). Further, the
409 // results of such an algorithm would likely be biased towards lower-value paths.
411 // Further, we could return to a faithful Dijkstra's algorithm by rejecting paths with limits
412 // outside of our current search value, running a path search more times to gather candidate
413 // paths at different values. While this may be acceptable, further path searches may increase
414 // runtime for little gain. Specifically, the current algorithm rather efficiently explores the
415 // graph for candidate paths, calculating the maximum value which can realistically be sent at
416 // the same time, remaining generic across different payment values.
418 // TODO: There are a few tweaks we could do, including possibly pre-calculating more stuff
419 // to use as the A* heuristic beyond just the cost to get one node further than the current
422 let dummy_directional_info = DummyDirectionalChannelInfo { // used for first_hops routes
423 cltv_expiry_delta: 0,
424 htlc_minimum_msat: 0,
425 htlc_maximum_msat: None,
428 proportional_millionths: 0,
432 let mut targets = BinaryHeap::new(); //TODO: Do we care about switching to eg Fibbonaci heap?
433 let mut dist = HashMap::with_capacity(network.get_nodes().len());
435 // During routing, if we ignore a path due to an htlc_minimum_msat limit, we set this,
436 // indicating that we may wish to try again with a higher value, potentially paying to meet an
437 // htlc_minimum with extra fees while still finding a cheaper path.
438 let mut hit_minimum_limit;
440 // When arranging a route, we select multiple paths so that we can make a multi-path payment.
441 // We start with a path_value of the exact amount we want, and if that generates a route we may
442 // return it immediately. Otherwise, we don't stop searching for paths until we have 3x the
443 // amount we want in total across paths, selecting the best subset at the end.
444 const ROUTE_CAPACITY_PROVISION_FACTOR: u64 = 3;
445 let recommended_value_msat = final_value_msat * ROUTE_CAPACITY_PROVISION_FACTOR as u64;
446 let mut path_value_msat = final_value_msat;
448 // Allow MPP only if we have a features set from somewhere that indicates the payee supports
449 // it. If the payee supports it they're supposed to include it in the invoice, so that should
451 let allow_mpp = if let Some(features) = &payee_features {
452 features.supports_basic_mpp()
453 } else if let Some(node) = network.get_nodes().get(&payee) {
454 if let Some(node_info) = node.announcement_info.as_ref() {
455 node_info.features.supports_basic_mpp()
460 // Prepare the data we'll use for payee-to-payer search by
461 // inserting first hops suggested by the caller as targets.
462 // Our search will then attempt to reach them while traversing from the payee node.
463 let mut first_hop_targets = HashMap::with_capacity(if first_hops.is_some() { first_hops.as_ref().unwrap().len() } else { 0 });
464 if let Some(hops) = first_hops {
466 let short_channel_id = chan.short_channel_id.expect("first_hops should be filled in with usable channels, not pending ones");
467 if chan.remote_network_id == *our_node_id {
468 return Err(LightningError{err: "First hop cannot have our_node_id as a destination.".to_owned(), action: ErrorAction::IgnoreError});
470 first_hop_targets.insert(chan.remote_network_id, (short_channel_id, chan.counterparty_features.clone(), chan.outbound_capacity_msat));
472 if first_hop_targets.is_empty() {
473 return Err(LightningError{err: "Cannot route when there are no outbound routes away from us".to_owned(), action: ErrorAction::IgnoreError});
477 // We don't want multiple paths (as per MPP) share liquidity of the same channels.
478 // This map allows paths to be aware of the channel use by other paths in the same call.
479 // This would help to make a better path finding decisions and not "overbook" channels.
480 // It is unaware of the directions (except for `outbound_capacity_msat` in `first_hops`).
481 let mut bookkeeped_channels_liquidity_available_msat = HashMap::new();
483 // Keeping track of how much value we already collected across other paths. Helps to decide:
484 // - how much a new path should be transferring (upper bound);
485 // - whether a channel should be disregarded because
486 // it's available liquidity is too small comparing to how much more we need to collect;
487 // - when we want to stop looking for new paths.
488 let mut already_collected_value_msat = 0;
490 macro_rules! add_entry {
491 // Adds entry which goes from $src_node_id to $dest_node_id
492 // over the channel with id $chan_id with fees described in
493 // $directional_info.
494 // $next_hops_fee_msat represents the fees paid for using all the channel *after* this one,
495 // since that value has to be transferred over this channel.
496 ( $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,
497 $next_hops_value_contribution: expr, $incl_fee_next_hops_htlc_minimum_msat: expr ) => {
498 // Channels to self should not be used. This is more of belt-and-suspenders, because in
499 // practice these cases should be caught earlier:
500 // - for regular channels at channel announcement (TODO)
501 // - for first and last hops early in get_route
502 if $src_node_id != $dest_node_id.clone() {
503 let available_liquidity_msat = bookkeeped_channels_liquidity_available_msat.entry($chan_id.clone()).or_insert_with(|| {
504 let mut initial_liquidity_available_msat = None;
505 if let Some(capacity_sats) = $capacity_sats {
506 initial_liquidity_available_msat = Some(capacity_sats * 1000);
509 if let Some(htlc_maximum_msat) = $directional_info.htlc_maximum_msat {
510 if let Some(available_msat) = initial_liquidity_available_msat {
511 initial_liquidity_available_msat = Some(cmp::min(available_msat, htlc_maximum_msat));
513 initial_liquidity_available_msat = Some(htlc_maximum_msat);
517 match initial_liquidity_available_msat {
518 Some(available_msat) => available_msat,
519 // We assume channels with unknown balance have
520 // a capacity of 0.0025 BTC (or 250_000 sats).
521 None => 250_000 * 1000
525 // It is tricky to substract $next_hops_fee_msat from available liquidity here.
526 // It may be misleading because we might later choose to reduce the value transferred
527 // over these channels, and the channel which was insufficient might become sufficient.
528 // Worst case: we drop a good channel here because it can't cover the high following
529 // fees caused by one expensive channel, but then this channel could have been used
530 // if the amount being transferred over this path is lower.
531 // We do this for now, but this is a subject for removal.
532 if let Some(available_value_contribution_msat) = available_liquidity_msat.checked_sub($next_hops_fee_msat) {
534 // Routing Fragmentation Mitigation heuristic:
536 // Routing fragmentation across many payment paths increases the overall routing
537 // fees as you have irreducible routing fees per-link used (`fee_base_msat`).
538 // Taking too many smaller paths also increases the chance of payment failure.
539 // Thus to avoid this effect, we require from our collected links to provide
540 // at least a minimal contribution to the recommended value yet-to-be-fulfilled.
542 // This requirement is currently 5% of the remaining-to-be-collected value.
543 // This means as we successfully advance in our collection,
544 // the absolute liquidity contribution is lowered,
545 // thus increasing the number of potential channels to be selected.
547 // Derive the minimal liquidity contribution with a ratio of 20 (5%, rounded up)
548 // or 100% if we're not allowed to do multipath payments.
549 let minimal_value_contribution_msat: u64 = if allow_mpp {
550 (recommended_value_msat - already_collected_value_msat + 19) / 20
554 // Verify the liquidity offered by this channel complies to the minimal contribution.
555 let contributes_sufficient_value = available_value_contribution_msat >= minimal_value_contribution_msat;
557 let value_contribution_msat = cmp::min(available_value_contribution_msat, $next_hops_value_contribution);
558 // Includes paying fees for the use of the following channels.
559 let amount_to_transfer_over_msat: u64 = match value_contribution_msat.checked_add($next_hops_fee_msat) {
560 Some(result) => result,
561 // Can't overflow due to how the values were computed right above.
562 None => unreachable!(),
564 #[allow(unused_comparisons)] // $incl_fee_next_hops_htlc_minimum_msat is 0 in some calls so rustc complains
565 let over_path_minimum_msat = amount_to_transfer_over_msat >= $directional_info.htlc_minimum_msat &&
566 amount_to_transfer_over_msat >= $incl_fee_next_hops_htlc_minimum_msat;
568 // If HTLC minimum is larger than the amount we're going to transfer, we shouldn't
569 // bother considering this channel.
570 // Since we're choosing amount_to_transfer_over_msat as maximum possible, it can
571 // be only reduced later (not increased), so this channel should just be skipped
572 // as not sufficient.
573 if !over_path_minimum_msat {
574 hit_minimum_limit = true;
575 } else if contributes_sufficient_value {
576 // Note that low contribution here (limited by available_liquidity_msat)
577 // might violate htlc_minimum_msat on the hops which are next along the
578 // payment path (upstream to the payee). To avoid that, we recompute path
579 // path fees knowing the final path contribution after constructing it.
580 let path_htlc_minimum_msat = match compute_fees($incl_fee_next_hops_htlc_minimum_msat, $directional_info.fees)
581 .map(|fee_msat| fee_msat.checked_add($incl_fee_next_hops_htlc_minimum_msat)) {
582 Some(Some(value_msat)) => cmp::max(value_msat, $directional_info.htlc_minimum_msat),
583 _ => u64::max_value()
585 let hm_entry = dist.entry(&$src_node_id);
586 let old_entry = hm_entry.or_insert_with(|| {
587 // If there was previously no known way to access
588 // the source node (recall it goes payee-to-payer) of $chan_id, first add
589 // a semi-dummy record just to compute the fees to reach the source node.
590 // This will affect our decision on selecting $chan_id
591 // as a way to reach the $dest_node_id.
592 let mut fee_base_msat = u32::max_value();
593 let mut fee_proportional_millionths = u32::max_value();
594 if let Some(Some(fees)) = network.get_nodes().get(&$src_node_id).map(|node| node.lowest_inbound_channel_fees) {
595 fee_base_msat = fees.base_msat;
596 fee_proportional_millionths = fees.proportional_millionths;
599 route_hop: RouteHop {
600 pubkey: $dest_node_id.clone(),
601 node_features: NodeFeatures::empty(),
603 channel_features: $chan_features.clone(),
605 cltv_expiry_delta: 0,
607 src_lowest_inbound_fees: RoutingFees {
608 base_msat: fee_base_msat,
609 proportional_millionths: fee_proportional_millionths,
611 channel_fees: $directional_info.fees,
612 next_hops_fee_msat: u64::max_value(),
613 hop_use_fee_msat: u64::max_value(),
614 total_fee_msat: u64::max_value(),
615 htlc_minimum_msat: $directional_info.htlc_minimum_msat,
616 path_htlc_minimum_msat,
620 let mut hop_use_fee_msat = 0;
621 let mut total_fee_msat = $next_hops_fee_msat;
623 // Ignore hop_use_fee_msat for channel-from-us as we assume all channels-from-us
624 // will have the same effective-fee
625 if $src_node_id != *our_node_id {
626 match compute_fees(amount_to_transfer_over_msat, $directional_info.fees) {
627 // max_value means we'll always fail
628 // the old_entry.total_fee_msat > total_fee_msat check
629 None => total_fee_msat = u64::max_value(),
631 hop_use_fee_msat = fee_msat;
632 total_fee_msat += hop_use_fee_msat;
633 if let Some(prev_hop_fee_msat) = compute_fees(total_fee_msat + amount_to_transfer_over_msat,
634 old_entry.src_lowest_inbound_fees) {
635 if let Some(incremented_total_fee_msat) = total_fee_msat.checked_add(prev_hop_fee_msat) {
636 total_fee_msat = incremented_total_fee_msat;
639 // max_value means we'll always fail
640 // the old_entry.total_fee_msat > total_fee_msat check
641 total_fee_msat = u64::max_value();
644 // max_value means we'll always fail
645 // the old_entry.total_fee_msat > total_fee_msat check
646 total_fee_msat = u64::max_value();
652 let new_graph_node = RouteGraphNode {
653 pubkey: $src_node_id,
654 lowest_fee_to_peer_through_node: total_fee_msat,
655 lowest_fee_to_node: $next_hops_fee_msat as u64 + hop_use_fee_msat,
656 value_contribution_msat: value_contribution_msat,
657 path_htlc_minimum_msat,
660 // Update the way of reaching $src_node_id with the given $chan_id (from $dest_node_id),
661 // if this way is cheaper than the already known
662 // (considering the cost to "reach" this channel from the route destination,
663 // the cost of using this channel,
664 // and the cost of routing to the source node of this channel).
665 // Also, consider that htlc_minimum_msat_difference, because we might end up
666 // paying it. Consider the following exploit:
667 // we use 2 paths to transfer 1.5 BTC. One of them is 0-fee normal 1 BTC path,
668 // and for the other one we picked a 1sat-fee path with htlc_minimum_msat of
669 // 1 BTC. Now, since the latter is more expensive, we gonna try to cut it
670 // by 0.5 BTC, but then match htlc_minimum_msat by paying a fee of 0.5 BTC
672 // Ideally the scoring could be smarter (e.g. 0.5*htlc_minimum_msat here),
673 // but it may require additional tracking - we don't want to double-count
674 // the fees included in $incl_fee_next_hops_htlc_minimum_msat, but also
675 // can't use something that may decrease on future hops.
676 let old_cost = cmp::max(old_entry.total_fee_msat, old_entry.path_htlc_minimum_msat);
677 let new_cost = cmp::max(total_fee_msat, path_htlc_minimum_msat);
679 if new_cost < old_cost {
680 targets.push(new_graph_node);
681 old_entry.next_hops_fee_msat = $next_hops_fee_msat;
682 old_entry.hop_use_fee_msat = hop_use_fee_msat;
683 old_entry.total_fee_msat = total_fee_msat;
684 old_entry.route_hop = RouteHop {
685 pubkey: $dest_node_id.clone(),
686 node_features: NodeFeatures::empty(),
687 short_channel_id: $chan_id.clone(),
688 channel_features: $chan_features.clone(),
689 fee_msat: 0, // This value will be later filled with hop_use_fee_msat of the following channel
690 cltv_expiry_delta: $directional_info.cltv_expiry_delta as u32,
692 old_entry.channel_fees = $directional_info.fees;
693 old_entry.htlc_minimum_msat = $directional_info.htlc_minimum_msat;
694 old_entry.path_htlc_minimum_msat = path_htlc_minimum_msat;
702 // Find ways (channels with destination) to reach a given node and store them
703 // in the corresponding data structures (routing graph etc).
704 // $fee_to_target_msat represents how much it costs to reach to this node from the payee,
705 // meaning how much will be paid in fees after this node (to the best of our knowledge).
706 // This data can later be helpful to optimize routing (pay lower fees).
707 macro_rules! add_entries_to_cheapest_to_target_node {
708 ( $node: expr, $node_id: expr, $fee_to_target_msat: expr, $next_hops_value_contribution: expr, $incl_fee_next_hops_htlc_minimum_msat: expr ) => {
709 if first_hops.is_some() {
710 if let Some(&(ref first_hop, ref features, ref outbound_capacity_msat)) = first_hop_targets.get(&$node_id) {
711 add_entry!(first_hop, *our_node_id, $node_id, dummy_directional_info, Some(outbound_capacity_msat / 1000), features.to_context(), $fee_to_target_msat, $next_hops_value_contribution, $incl_fee_next_hops_htlc_minimum_msat);
716 if let Some(node_info) = $node.announcement_info.as_ref() {
717 features = node_info.features.clone();
719 features = NodeFeatures::empty();
722 if !features.requires_unknown_bits() {
723 for chan_id in $node.channels.iter() {
724 let chan = network.get_channels().get(chan_id).unwrap();
725 if !chan.features.requires_unknown_bits() {
726 if chan.node_one == *$node_id {
727 // ie $node is one, ie next hop in A* is two, via the two_to_one channel
728 if first_hops.is_none() || chan.node_two != *our_node_id {
729 if let Some(two_to_one) = chan.two_to_one.as_ref() {
730 if two_to_one.enabled {
731 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, $incl_fee_next_hops_htlc_minimum_msat);
736 if first_hops.is_none() || chan.node_one != *our_node_id {
737 if let Some(one_to_two) = chan.one_to_two.as_ref() {
738 if one_to_two.enabled {
739 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, $incl_fee_next_hops_htlc_minimum_msat);
751 let mut payment_paths = Vec::<PaymentPath>::new();
753 // TODO: diversify by nodes (so that all paths aren't doomed if one node is offline).
754 'paths_collection: loop {
755 // For every new path, start from scratch, except
756 // bookkeeped_channels_liquidity_available_msat, which will improve
757 // the further iterations of path finding. Also don't erase first_hop_targets.
760 hit_minimum_limit = false;
762 // If first hop is a private channel and the only way to reach the payee, this is the only
763 // place where it could be added.
764 if first_hops.is_some() {
765 if let Some(&(ref first_hop, ref features, ref outbound_capacity_msat)) = first_hop_targets.get(&payee) {
766 add_entry!(first_hop, *our_node_id, payee, dummy_directional_info, Some(outbound_capacity_msat / 1000), features.to_context(), 0, path_value_msat, 0);
770 // Add the payee as a target, so that the payee-to-payer
771 // search algorithm knows what to start with.
772 match network.get_nodes().get(payee) {
773 // The payee is not in our network graph, so nothing to add here.
774 // There is still a chance of reaching them via last_hops though,
775 // so don't yet fail the payment here.
776 // If not, targets.pop() will not even let us enter the loop in step 2.
779 add_entries_to_cheapest_to_target_node!(node, payee, 0, path_value_msat, 0);
784 // If a caller provided us with last hops, add them to routing targets. Since this happens
785 // earlier than general path finding, they will be somewhat prioritized, although currently
786 // it matters only if the fees are exactly the same.
787 for hop in last_hops.iter() {
788 let have_hop_src_in_graph =
789 if let Some(&(ref first_hop, ref features, ref outbound_capacity_msat)) = first_hop_targets.get(&hop.src_node_id) {
790 // If this hop connects to a node with which we have a direct channel, ignore
791 // the network graph and add both the hop and our direct channel to
792 // the candidate set.
794 // Currently there are no channel-context features defined, so we are a
795 // bit lazy here. In the future, we should pull them out via our
796 // ChannelManager, but there's no reason to waste the space until we
798 add_entry!(first_hop, *our_node_id , hop.src_node_id, dummy_directional_info, Some(outbound_capacity_msat / 1000), features.to_context(), 0, path_value_msat, 0);
801 // In any other case, only add the hop if the source is in the regular network
803 network.get_nodes().get(&hop.src_node_id).is_some()
805 if have_hop_src_in_graph {
806 // BOLT 11 doesn't allow inclusion of features for the last hop hints, which
807 // really sucks, cause we're gonna need that eventually.
808 let last_path_htlc_minimum_msat: u64 = match hop.htlc_minimum_msat {
809 Some(htlc_minimum_msat) => htlc_minimum_msat,
812 let directional_info = DummyDirectionalChannelInfo {
813 cltv_expiry_delta: hop.cltv_expiry_delta as u32,
814 htlc_minimum_msat: last_path_htlc_minimum_msat,
815 htlc_maximum_msat: hop.htlc_maximum_msat,
818 add_entry!(hop.short_channel_id, hop.src_node_id, payee, directional_info, None::<u64>, ChannelFeatures::empty(), 0, path_value_msat, 0);
822 // At this point, targets are filled with the data from first and
823 // last hops communicated by the caller, and the payment receiver.
824 let mut found_new_path = false;
827 // If this loop terminates due the exhaustion of targets, two situations are possible:
828 // - not enough outgoing liquidity:
829 // 0 < already_collected_value_msat < final_value_msat
830 // - enough outgoing liquidity:
831 // final_value_msat <= already_collected_value_msat < recommended_value_msat
832 // Both these cases (and other cases except reaching recommended_value_msat) mean that
833 // paths_collection will be stopped because found_new_path==false.
834 // This is not necessarily a routing failure.
835 'path_construction: while let Some(RouteGraphNode { pubkey, lowest_fee_to_node, value_contribution_msat, path_htlc_minimum_msat, .. }) = targets.pop() {
837 // Since we're going payee-to-payer, hitting our node as a target means we should stop
838 // traversing the graph and arrange the path out of what we found.
839 if pubkey == *our_node_id {
840 let mut new_entry = dist.remove(&our_node_id).unwrap();
841 let mut ordered_hops = vec!(new_entry.clone());
844 if let Some(&(_, ref features, _)) = first_hop_targets.get(&ordered_hops.last().unwrap().route_hop.pubkey) {
845 ordered_hops.last_mut().unwrap().route_hop.node_features = features.to_context();
846 } else if let Some(node) = network.get_nodes().get(&ordered_hops.last().unwrap().route_hop.pubkey) {
847 if let Some(node_info) = node.announcement_info.as_ref() {
848 ordered_hops.last_mut().unwrap().route_hop.node_features = node_info.features.clone();
850 ordered_hops.last_mut().unwrap().route_hop.node_features = NodeFeatures::empty();
853 // We should be able to fill in features for everything except the last
854 // hop, if the last hop was provided via a BOLT 11 invoice (though we
855 // should be able to extend it further as BOLT 11 does have feature
856 // flags for the last hop node itself).
857 assert!(ordered_hops.last().unwrap().route_hop.pubkey == *payee);
860 // Means we succesfully traversed from the payer to the payee, now
861 // save this path for the payment route. Also, update the liquidity
862 // remaining on the used hops, so that we take them into account
863 // while looking for more paths.
864 if ordered_hops.last().unwrap().route_hop.pubkey == *payee {
868 new_entry = match dist.remove(&ordered_hops.last().unwrap().route_hop.pubkey) {
869 Some(payment_hop) => payment_hop,
870 // We can't arrive at None because, if we ever add an entry to targets,
871 // we also fill in the entry in dist (see add_entry!).
872 None => unreachable!(),
874 // We "propagate" the fees one hop backward (topologically) here,
875 // so that fees paid for a HTLC forwarding on the current channel are
876 // associated with the previous channel (where they will be subtracted).
877 ordered_hops.last_mut().unwrap().route_hop.fee_msat = new_entry.hop_use_fee_msat;
878 ordered_hops.last_mut().unwrap().route_hop.cltv_expiry_delta = new_entry.route_hop.cltv_expiry_delta;
879 ordered_hops.push(new_entry.clone());
881 ordered_hops.last_mut().unwrap().route_hop.fee_msat = value_contribution_msat;
882 ordered_hops.last_mut().unwrap().hop_use_fee_msat = 0;
883 ordered_hops.last_mut().unwrap().route_hop.cltv_expiry_delta = final_cltv;
885 let mut payment_path = PaymentPath {hops: ordered_hops};
887 // We could have possibly constructed a slightly inconsistent path: since we reduce
888 // value being transferred along the way, we could have violated htlc_minimum_msat
889 // on some channels we already passed (assuming dest->source direction). Here, we
890 // recompute the fees again, so that if that's the case, we match the currently
891 // underpaid htlc_minimum_msat with fees.
892 payment_path.update_value_and_recompute_fees(value_contribution_msat);
894 // Since a path allows to transfer as much value as
895 // the smallest channel it has ("bottleneck"), we should recompute
896 // the fees so sender HTLC don't overpay fees when traversing
897 // larger channels than the bottleneck. This may happen because
898 // when we were selecting those channels we were not aware how much value
899 // this path will transfer, and the relative fee for them
900 // might have been computed considering a larger value.
901 // Remember that we used these channels so that we don't rely
902 // on the same liquidity in future paths.
903 for payment_hop in payment_path.hops.iter() {
904 let channel_liquidity_available_msat = bookkeeped_channels_liquidity_available_msat.get_mut(&payment_hop.route_hop.short_channel_id).unwrap();
905 let mut spent_on_hop_msat = value_contribution_msat;
906 let next_hops_fee_msat = payment_hop.next_hops_fee_msat;
907 spent_on_hop_msat += next_hops_fee_msat;
908 if *channel_liquidity_available_msat < spent_on_hop_msat {
909 // This should not happen because we do recompute fees right before,
910 // trying to avoid cases when a hop is not usable due to the fee situation.
911 break 'path_construction;
913 *channel_liquidity_available_msat -= spent_on_hop_msat;
915 // Track the total amount all our collected paths allow to send so that we:
916 // - know when to stop looking for more paths
917 // - know which of the hops are useless considering how much more sats we need
918 // (contributes_sufficient_value)
919 already_collected_value_msat += value_contribution_msat;
921 payment_paths.push(payment_path);
922 found_new_path = true;
923 break 'path_construction;
926 // Otherwise, since the current target node is not us,
927 // keep "unrolling" the payment graph from payee to payer by
928 // finding a way to reach the current target from the payer side.
929 match network.get_nodes().get(&pubkey) {
932 add_entries_to_cheapest_to_target_node!(node, &pubkey, lowest_fee_to_node, value_contribution_msat, path_htlc_minimum_msat);
938 // If we don't support MPP, no use trying to gather more value ever.
939 break 'paths_collection;
943 // Stop either when the recommended value is reached or if no new path was found in this
945 // In the latter case, making another path finding attempt won't help,
946 // because we deterministically terminated the search due to low liquidity.
947 if already_collected_value_msat >= recommended_value_msat || !found_new_path {
948 break 'paths_collection;
950 // Further, if this was our first walk of the graph, and we weren't limited by an
951 // htlc_minim_msat, return immediately because this path should suffice. If we were limited
952 // by an htlc_minimum_msat value, find another path with a higher value, potentially
953 // allowing us to pay fees to meet the htlc_minimum while still keeping a lower total fee.
954 if already_collected_value_msat == final_value_msat && payment_paths.len() == 1 {
955 if !hit_minimum_limit {
956 break 'paths_collection;
958 path_value_msat = recommended_value_msat;
963 if payment_paths.len() == 0 {
964 return Err(LightningError{err: "Failed to find a path to the given destination".to_owned(), action: ErrorAction::IgnoreError});
967 if already_collected_value_msat < final_value_msat {
968 return Err(LightningError{err: "Failed to find a sufficient route to the given destination".to_owned(), action: ErrorAction::IgnoreError});
971 // Sort by total fees and take the best paths.
972 payment_paths.sort_by_key(|path| path.get_total_fee_paid_msat());
973 if payment_paths.len() > 50 {
974 payment_paths.truncate(50);
977 // Draw multiple sufficient routes by randomly combining the selected paths.
978 let mut drawn_routes = Vec::new();
979 for i in 0..payment_paths.len() {
980 let mut cur_route = Vec::<PaymentPath>::new();
981 let mut aggregate_route_value_msat = 0;
984 // TODO: real random shuffle
985 // Currently just starts with i_th and goes up to i-1_th in a looped way.
986 let cur_payment_paths = [&payment_paths[i..], &payment_paths[..i]].concat();
989 for payment_path in cur_payment_paths {
990 cur_route.push(payment_path.clone());
991 aggregate_route_value_msat += payment_path.get_value_msat();
992 if aggregate_route_value_msat > final_value_msat {
993 // Last path likely overpaid. Substract it from the most expensive
994 // (in terms of proportional fee) path in this route and recompute fees.
995 // This might be not the most economically efficient way, but fewer paths
996 // also makes routing more reliable.
997 let mut overpaid_value_msat = aggregate_route_value_msat - final_value_msat;
999 // First, drop some expensive low-value paths entirely if possible.
1000 // Sort by value so that we drop many really-low values first, since
1001 // fewer paths is better: the payment is less likely to fail.
1002 // TODO: this could also be optimized by also sorting by feerate_per_sat_routed,
1003 // so that the sender pays less fees overall. And also htlc_minimum_msat.
1004 cur_route.sort_by_key(|path| path.get_value_msat());
1005 // We should make sure that at least 1 path left.
1006 let mut paths_left = cur_route.len();
1007 cur_route.retain(|path| {
1008 if paths_left == 1 {
1011 let mut keep = true;
1012 let path_value_msat = path.get_value_msat();
1013 if path_value_msat <= overpaid_value_msat {
1015 overpaid_value_msat -= path_value_msat;
1021 if overpaid_value_msat == 0 {
1025 assert!(cur_route.len() > 0);
1028 // Now, substract the overpaid value from the most-expensive path.
1029 // TODO: this could also be optimized by also sorting by feerate_per_sat_routed,
1030 // so that the sender pays less fees overall. And also htlc_minimum_msat.
1031 cur_route.sort_by_key(|path| { path.hops.iter().map(|hop| hop.channel_fees.proportional_millionths as u64).sum::<u64>() });
1032 let expensive_payment_path = cur_route.first_mut().unwrap();
1033 // We already dropped all the small channels above, meaning all the
1034 // remaining channels are larger than remaining overpaid_value_msat.
1035 // Thus, this can't be negative.
1036 let expensive_path_new_value_msat = expensive_payment_path.get_value_msat() - overpaid_value_msat;
1037 expensive_payment_path.update_value_and_recompute_fees(expensive_path_new_value_msat);
1041 drawn_routes.push(cur_route);
1045 // Select the best route by lowest total fee.
1046 drawn_routes.sort_by_key(|paths| paths.iter().map(|path| path.get_total_fee_paid_msat()).sum::<u64>());
1047 let mut selected_paths = Vec::<Vec<RouteHop>>::new();
1048 for payment_path in drawn_routes.first().unwrap() {
1049 selected_paths.push(payment_path.hops.iter().map(|payment_hop| payment_hop.route_hop.clone()).collect());
1052 if let Some(features) = &payee_features {
1053 for path in selected_paths.iter_mut() {
1054 path.last_mut().unwrap().node_features = features.to_context();
1058 let route = Route { paths: selected_paths };
1059 log_trace!(logger, "Got route: {}", log_route!(route));
1065 use routing::router::{get_route, RouteHint, RoutingFees};
1066 use routing::network_graph::{NetworkGraph, NetGraphMsgHandler};
1067 use ln::features::{ChannelFeatures, InitFeatures, InvoiceFeatures, NodeFeatures};
1068 use ln::msgs::{ErrorAction, LightningError, OptionalField, UnsignedChannelAnnouncement, ChannelAnnouncement, RoutingMessageHandler,
1069 NodeAnnouncement, UnsignedNodeAnnouncement, ChannelUpdate, UnsignedChannelUpdate};
1070 use ln::channelmanager;
1071 use util::test_utils;
1072 use util::ser::Writeable;
1074 use bitcoin::hashes::sha256d::Hash as Sha256dHash;
1075 use bitcoin::hashes::Hash;
1076 use bitcoin::network::constants::Network;
1077 use bitcoin::blockdata::constants::genesis_block;
1078 use bitcoin::blockdata::script::Builder;
1079 use bitcoin::blockdata::opcodes;
1080 use bitcoin::blockdata::transaction::TxOut;
1084 use bitcoin::secp256k1::key::{PublicKey,SecretKey};
1085 use bitcoin::secp256k1::{Secp256k1, All};
1089 // Using the same keys for LN and BTC ids
1090 fn add_channel(net_graph_msg_handler: &NetGraphMsgHandler<Arc<test_utils::TestChainSource>, Arc<test_utils::TestLogger>>, secp_ctx: &Secp256k1<All>, node_1_privkey: &SecretKey,
1091 node_2_privkey: &SecretKey, features: ChannelFeatures, short_channel_id: u64) {
1092 let node_id_1 = PublicKey::from_secret_key(&secp_ctx, node_1_privkey);
1093 let node_id_2 = PublicKey::from_secret_key(&secp_ctx, node_2_privkey);
1095 let unsigned_announcement = UnsignedChannelAnnouncement {
1097 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1101 bitcoin_key_1: node_id_1,
1102 bitcoin_key_2: node_id_2,
1103 excess_data: Vec::new(),
1106 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1107 let valid_announcement = ChannelAnnouncement {
1108 node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
1109 node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
1110 bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
1111 bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
1112 contents: unsigned_announcement.clone(),
1114 match net_graph_msg_handler.handle_channel_announcement(&valid_announcement) {
1115 Ok(res) => assert!(res),
1120 fn update_channel(net_graph_msg_handler: &NetGraphMsgHandler<Arc<test_utils::TestChainSource>, Arc<test_utils::TestLogger>>, secp_ctx: &Secp256k1<All>, node_privkey: &SecretKey, update: UnsignedChannelUpdate) {
1121 let msghash = hash_to_message!(&Sha256dHash::hash(&update.encode()[..])[..]);
1122 let valid_channel_update = ChannelUpdate {
1123 signature: secp_ctx.sign(&msghash, node_privkey),
1124 contents: update.clone()
1127 match net_graph_msg_handler.handle_channel_update(&valid_channel_update) {
1128 Ok(res) => assert!(res),
1133 fn add_or_update_node(net_graph_msg_handler: &NetGraphMsgHandler<Arc<test_utils::TestChainSource>, Arc<test_utils::TestLogger>>, secp_ctx: &Secp256k1<All>, node_privkey: &SecretKey,
1134 features: NodeFeatures, timestamp: u32) {
1135 let node_id = PublicKey::from_secret_key(&secp_ctx, node_privkey);
1136 let unsigned_announcement = UnsignedNodeAnnouncement {
1142 addresses: Vec::new(),
1143 excess_address_data: Vec::new(),
1144 excess_data: Vec::new(),
1146 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1147 let valid_announcement = NodeAnnouncement {
1148 signature: secp_ctx.sign(&msghash, node_privkey),
1149 contents: unsigned_announcement.clone()
1152 match net_graph_msg_handler.handle_node_announcement(&valid_announcement) {
1158 fn get_nodes(secp_ctx: &Secp256k1<All>) -> (SecretKey, PublicKey, Vec<SecretKey>, Vec<PublicKey>) {
1159 let privkeys: Vec<SecretKey> = (2..10).map(|i| {
1160 SecretKey::from_slice(&hex::decode(format!("{:02}", i).repeat(32)).unwrap()[..]).unwrap()
1163 let pubkeys = privkeys.iter().map(|secret| PublicKey::from_secret_key(&secp_ctx, secret)).collect();
1165 let our_privkey = SecretKey::from_slice(&hex::decode("01".repeat(32)).unwrap()[..]).unwrap();
1166 let our_id = PublicKey::from_secret_key(&secp_ctx, &our_privkey);
1168 (our_privkey, our_id, privkeys, pubkeys)
1171 fn id_to_feature_flags(id: u8) -> Vec<u8> {
1172 // Set the feature flags to the id'th odd (ie non-required) feature bit so that we can
1173 // test for it later.
1174 let idx = (id - 1) * 2 + 1;
1176 vec![1 << (idx - 8*3), 0, 0, 0]
1177 } else if idx > 8*2 {
1178 vec![1 << (idx - 8*2), 0, 0]
1179 } else if idx > 8*1 {
1180 vec![1 << (idx - 8*1), 0]
1186 fn build_graph() -> (Secp256k1<All>, NetGraphMsgHandler<std::sync::Arc<test_utils::TestChainSource>, std::sync::Arc<crate::util::test_utils::TestLogger>>, std::sync::Arc<test_utils::TestChainSource>, std::sync::Arc<test_utils::TestLogger>) {
1187 let secp_ctx = Secp256k1::new();
1188 let logger = Arc::new(test_utils::TestLogger::new());
1189 let chain_monitor = Arc::new(test_utils::TestChainSource::new(Network::Testnet));
1190 let net_graph_msg_handler = NetGraphMsgHandler::new(genesis_block(Network::Testnet).header.block_hash(), None, Arc::clone(&logger));
1191 // Build network from our_id to node7:
1193 // -1(1)2- node0 -1(3)2-
1195 // our_id -1(12)2- node7 -1(13)2--- node2
1197 // -1(2)2- node1 -1(4)2-
1200 // chan1 1-to-2: disabled
1201 // chan1 2-to-1: enabled, 0 fee
1203 // chan2 1-to-2: enabled, ignored fee
1204 // chan2 2-to-1: enabled, 0 fee
1206 // chan3 1-to-2: enabled, 0 fee
1207 // chan3 2-to-1: enabled, 100 msat fee
1209 // chan4 1-to-2: enabled, 100% fee
1210 // chan4 2-to-1: enabled, 0 fee
1212 // chan12 1-to-2: enabled, ignored fee
1213 // chan12 2-to-1: enabled, 0 fee
1215 // chan13 1-to-2: enabled, 200% fee
1216 // chan13 2-to-1: enabled, 0 fee
1219 // -1(5)2- node3 -1(8)2--
1223 // node2--1(6)2- node4 -1(9)2--- node6 (not in global route map)
1225 // -1(7)2- node5 -1(10)2-
1227 // chan5 1-to-2: enabled, 100 msat fee
1228 // chan5 2-to-1: enabled, 0 fee
1230 // chan6 1-to-2: enabled, 0 fee
1231 // chan6 2-to-1: enabled, 0 fee
1233 // chan7 1-to-2: enabled, 100% fee
1234 // chan7 2-to-1: enabled, 0 fee
1236 // chan8 1-to-2: enabled, variable fee (0 then 1000 msat)
1237 // chan8 2-to-1: enabled, 0 fee
1239 // chan9 1-to-2: enabled, 1001 msat fee
1240 // chan9 2-to-1: enabled, 0 fee
1242 // chan10 1-to-2: enabled, 0 fee
1243 // chan10 2-to-1: enabled, 0 fee
1245 // chan11 1-to-2: enabled, 0 fee
1246 // chan11 2-to-1: enabled, 0 fee
1248 let (our_privkey, _, privkeys, _) = get_nodes(&secp_ctx);
1250 add_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, &privkeys[0], ChannelFeatures::from_le_bytes(id_to_feature_flags(1)), 1);
1251 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
1252 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1253 short_channel_id: 1,
1256 cltv_expiry_delta: 0,
1257 htlc_minimum_msat: 0,
1258 htlc_maximum_msat: OptionalField::Absent,
1260 fee_proportional_millionths: 0,
1261 excess_data: Vec::new()
1264 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[0], NodeFeatures::from_le_bytes(id_to_feature_flags(1)), 0);
1266 add_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, &privkeys[1], ChannelFeatures::from_le_bytes(id_to_feature_flags(2)), 2);
1267 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
1268 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1269 short_channel_id: 2,
1272 cltv_expiry_delta: u16::max_value(),
1273 htlc_minimum_msat: 0,
1274 htlc_maximum_msat: OptionalField::Absent,
1275 fee_base_msat: u32::max_value(),
1276 fee_proportional_millionths: u32::max_value(),
1277 excess_data: Vec::new()
1279 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
1280 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1281 short_channel_id: 2,
1284 cltv_expiry_delta: 0,
1285 htlc_minimum_msat: 0,
1286 htlc_maximum_msat: OptionalField::Absent,
1288 fee_proportional_millionths: 0,
1289 excess_data: Vec::new()
1292 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[1], NodeFeatures::from_le_bytes(id_to_feature_flags(2)), 0);
1294 add_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, &privkeys[7], ChannelFeatures::from_le_bytes(id_to_feature_flags(12)), 12);
1295 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
1296 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1297 short_channel_id: 12,
1300 cltv_expiry_delta: u16::max_value(),
1301 htlc_minimum_msat: 0,
1302 htlc_maximum_msat: OptionalField::Absent,
1303 fee_base_msat: u32::max_value(),
1304 fee_proportional_millionths: u32::max_value(),
1305 excess_data: Vec::new()
1307 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
1308 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1309 short_channel_id: 12,
1312 cltv_expiry_delta: 0,
1313 htlc_minimum_msat: 0,
1314 htlc_maximum_msat: OptionalField::Absent,
1316 fee_proportional_millionths: 0,
1317 excess_data: Vec::new()
1320 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[7], NodeFeatures::from_le_bytes(id_to_feature_flags(8)), 0);
1322 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], &privkeys[2], ChannelFeatures::from_le_bytes(id_to_feature_flags(3)), 3);
1323 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
1324 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1325 short_channel_id: 3,
1328 cltv_expiry_delta: (3 << 8) | 1,
1329 htlc_minimum_msat: 0,
1330 htlc_maximum_msat: OptionalField::Absent,
1332 fee_proportional_millionths: 0,
1333 excess_data: Vec::new()
1335 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
1336 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1337 short_channel_id: 3,
1340 cltv_expiry_delta: (3 << 8) | 2,
1341 htlc_minimum_msat: 0,
1342 htlc_maximum_msat: OptionalField::Absent,
1344 fee_proportional_millionths: 0,
1345 excess_data: Vec::new()
1348 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], &privkeys[2], ChannelFeatures::from_le_bytes(id_to_feature_flags(4)), 4);
1349 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
1350 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1351 short_channel_id: 4,
1354 cltv_expiry_delta: (4 << 8) | 1,
1355 htlc_minimum_msat: 0,
1356 htlc_maximum_msat: OptionalField::Absent,
1358 fee_proportional_millionths: 1000000,
1359 excess_data: Vec::new()
1361 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
1362 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1363 short_channel_id: 4,
1366 cltv_expiry_delta: (4 << 8) | 2,
1367 htlc_minimum_msat: 0,
1368 htlc_maximum_msat: OptionalField::Absent,
1370 fee_proportional_millionths: 0,
1371 excess_data: Vec::new()
1374 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], &privkeys[2], ChannelFeatures::from_le_bytes(id_to_feature_flags(13)), 13);
1375 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
1376 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1377 short_channel_id: 13,
1380 cltv_expiry_delta: (13 << 8) | 1,
1381 htlc_minimum_msat: 0,
1382 htlc_maximum_msat: OptionalField::Absent,
1384 fee_proportional_millionths: 2000000,
1385 excess_data: Vec::new()
1387 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
1388 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1389 short_channel_id: 13,
1392 cltv_expiry_delta: (13 << 8) | 2,
1393 htlc_minimum_msat: 0,
1394 htlc_maximum_msat: OptionalField::Absent,
1396 fee_proportional_millionths: 0,
1397 excess_data: Vec::new()
1400 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[2], NodeFeatures::from_le_bytes(id_to_feature_flags(3)), 0);
1402 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], &privkeys[4], ChannelFeatures::from_le_bytes(id_to_feature_flags(6)), 6);
1403 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
1404 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1405 short_channel_id: 6,
1408 cltv_expiry_delta: (6 << 8) | 1,
1409 htlc_minimum_msat: 0,
1410 htlc_maximum_msat: OptionalField::Absent,
1412 fee_proportional_millionths: 0,
1413 excess_data: Vec::new()
1415 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
1416 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1417 short_channel_id: 6,
1420 cltv_expiry_delta: (6 << 8) | 2,
1421 htlc_minimum_msat: 0,
1422 htlc_maximum_msat: OptionalField::Absent,
1424 fee_proportional_millionths: 0,
1425 excess_data: Vec::new(),
1428 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(11)), 11);
1429 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
1430 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1431 short_channel_id: 11,
1434 cltv_expiry_delta: (11 << 8) | 1,
1435 htlc_minimum_msat: 0,
1436 htlc_maximum_msat: OptionalField::Absent,
1438 fee_proportional_millionths: 0,
1439 excess_data: Vec::new()
1441 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[3], UnsignedChannelUpdate {
1442 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1443 short_channel_id: 11,
1446 cltv_expiry_delta: (11 << 8) | 2,
1447 htlc_minimum_msat: 0,
1448 htlc_maximum_msat: OptionalField::Absent,
1450 fee_proportional_millionths: 0,
1451 excess_data: Vec::new()
1454 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[4], NodeFeatures::from_le_bytes(id_to_feature_flags(5)), 0);
1456 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[3], NodeFeatures::from_le_bytes(id_to_feature_flags(4)), 0);
1458 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], &privkeys[5], ChannelFeatures::from_le_bytes(id_to_feature_flags(7)), 7);
1459 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
1460 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1461 short_channel_id: 7,
1464 cltv_expiry_delta: (7 << 8) | 1,
1465 htlc_minimum_msat: 0,
1466 htlc_maximum_msat: OptionalField::Absent,
1468 fee_proportional_millionths: 1000000,
1469 excess_data: Vec::new()
1471 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[5], UnsignedChannelUpdate {
1472 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1473 short_channel_id: 7,
1476 cltv_expiry_delta: (7 << 8) | 2,
1477 htlc_minimum_msat: 0,
1478 htlc_maximum_msat: OptionalField::Absent,
1480 fee_proportional_millionths: 0,
1481 excess_data: Vec::new()
1484 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[5], NodeFeatures::from_le_bytes(id_to_feature_flags(6)), 0);
1486 (secp_ctx, net_graph_msg_handler, chain_monitor, logger)
1490 fn simple_route_test() {
1491 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
1492 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
1494 // Simple route to 2 via 1
1496 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2], None, None, &Vec::new(), 0, 42, Arc::clone(&logger)) {
1497 assert_eq!(err, "Cannot send a payment of 0 msat");
1498 } else { panic!(); }
1500 let route = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2], None, None, &Vec::new(), 100, 42, Arc::clone(&logger)).unwrap();
1501 assert_eq!(route.paths[0].len(), 2);
1503 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
1504 assert_eq!(route.paths[0][0].short_channel_id, 2);
1505 assert_eq!(route.paths[0][0].fee_msat, 100);
1506 assert_eq!(route.paths[0][0].cltv_expiry_delta, (4 << 8) | 1);
1507 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
1508 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
1510 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
1511 assert_eq!(route.paths[0][1].short_channel_id, 4);
1512 assert_eq!(route.paths[0][1].fee_msat, 100);
1513 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
1514 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
1515 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
1519 fn invalid_first_hop_test() {
1520 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
1521 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
1523 // Simple route to 2 via 1
1525 let our_chans = vec![channelmanager::ChannelDetails {
1526 channel_id: [0; 32],
1527 short_channel_id: Some(2),
1528 remote_network_id: our_id,
1529 counterparty_features: InitFeatures::from_le_bytes(vec![0b11]),
1530 channel_value_satoshis: 100000,
1532 outbound_capacity_msat: 100000,
1533 inbound_capacity_msat: 100000,
1535 counterparty_forwarding_info: None,
1538 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2], None, Some(&our_chans.iter().collect::<Vec<_>>()), &Vec::new(), 100, 42, Arc::clone(&logger)) {
1539 assert_eq!(err, "First hop cannot have our_node_id as a destination.");
1540 } else { panic!(); }
1542 let route = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2], None, None, &Vec::new(), 100, 42, Arc::clone(&logger)).unwrap();
1543 assert_eq!(route.paths[0].len(), 2);
1547 fn htlc_minimum_test() {
1548 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
1549 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
1551 // Simple route to 2 via 1
1553 // Disable other paths
1554 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
1555 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1556 short_channel_id: 12,
1558 flags: 2, // to disable
1559 cltv_expiry_delta: 0,
1560 htlc_minimum_msat: 0,
1561 htlc_maximum_msat: OptionalField::Absent,
1563 fee_proportional_millionths: 0,
1564 excess_data: Vec::new()
1566 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
1567 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1568 short_channel_id: 3,
1570 flags: 2, // to disable
1571 cltv_expiry_delta: 0,
1572 htlc_minimum_msat: 0,
1573 htlc_maximum_msat: OptionalField::Absent,
1575 fee_proportional_millionths: 0,
1576 excess_data: Vec::new()
1578 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
1579 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1580 short_channel_id: 13,
1582 flags: 2, // to disable
1583 cltv_expiry_delta: 0,
1584 htlc_minimum_msat: 0,
1585 htlc_maximum_msat: OptionalField::Absent,
1587 fee_proportional_millionths: 0,
1588 excess_data: Vec::new()
1590 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
1591 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1592 short_channel_id: 6,
1594 flags: 2, // to disable
1595 cltv_expiry_delta: 0,
1596 htlc_minimum_msat: 0,
1597 htlc_maximum_msat: OptionalField::Absent,
1599 fee_proportional_millionths: 0,
1600 excess_data: Vec::new()
1602 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
1603 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1604 short_channel_id: 7,
1606 flags: 2, // to disable
1607 cltv_expiry_delta: 0,
1608 htlc_minimum_msat: 0,
1609 htlc_maximum_msat: OptionalField::Absent,
1611 fee_proportional_millionths: 0,
1612 excess_data: Vec::new()
1615 // Check against amount_to_transfer_over_msat.
1616 // Set minimal HTLC of 200_000_000 msat.
1617 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
1618 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1619 short_channel_id: 2,
1622 cltv_expiry_delta: 0,
1623 htlc_minimum_msat: 200_000_000,
1624 htlc_maximum_msat: OptionalField::Absent,
1626 fee_proportional_millionths: 0,
1627 excess_data: Vec::new()
1630 // Second hop only allows to forward 199_999_999 at most, thus not allowing the first hop to
1632 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
1633 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1634 short_channel_id: 4,
1637 cltv_expiry_delta: 0,
1638 htlc_minimum_msat: 0,
1639 htlc_maximum_msat: OptionalField::Present(199_999_999),
1641 fee_proportional_millionths: 0,
1642 excess_data: Vec::new()
1645 // Not possible to send 199_999_999, because the minimum on channel=2 is 200_000_000.
1646 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2], None, None, &Vec::new(), 199_999_999, 42, Arc::clone(&logger)) {
1647 assert_eq!(err, "Failed to find a path to the given destination");
1648 } else { panic!(); }
1650 // Lift the restriction on the first hop.
1651 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
1652 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1653 short_channel_id: 2,
1656 cltv_expiry_delta: 0,
1657 htlc_minimum_msat: 0,
1658 htlc_maximum_msat: OptionalField::Absent,
1660 fee_proportional_millionths: 0,
1661 excess_data: Vec::new()
1664 // A payment above the minimum should pass
1665 let route = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2], None, None, &Vec::new(), 199_999_999, 42, Arc::clone(&logger)).unwrap();
1666 assert_eq!(route.paths[0].len(), 2);
1670 fn htlc_minimum_overpay_test() {
1671 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
1672 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
1674 // A route to node#2 via two paths.
1675 // One path allows transferring 35-40 sats, another one also allows 35-40 sats.
1676 // Thus, they can't send 60 without overpaying.
1677 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
1678 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1679 short_channel_id: 2,
1682 cltv_expiry_delta: 0,
1683 htlc_minimum_msat: 35_000,
1684 htlc_maximum_msat: OptionalField::Present(40_000),
1686 fee_proportional_millionths: 0,
1687 excess_data: Vec::new()
1689 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
1690 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1691 short_channel_id: 12,
1694 cltv_expiry_delta: 0,
1695 htlc_minimum_msat: 35_000,
1696 htlc_maximum_msat: OptionalField::Present(40_000),
1698 fee_proportional_millionths: 0,
1699 excess_data: Vec::new()
1703 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
1704 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1705 short_channel_id: 13,
1708 cltv_expiry_delta: 0,
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[1], UnsignedChannelUpdate {
1716 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1717 short_channel_id: 4,
1720 cltv_expiry_delta: 0,
1721 htlc_minimum_msat: 0,
1722 htlc_maximum_msat: OptionalField::Absent,
1724 fee_proportional_millionths: 0,
1725 excess_data: Vec::new()
1728 // Disable other paths
1729 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
1730 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1731 short_channel_id: 1,
1733 flags: 2, // to disable
1734 cltv_expiry_delta: 0,
1735 htlc_minimum_msat: 0,
1736 htlc_maximum_msat: OptionalField::Absent,
1738 fee_proportional_millionths: 0,
1739 excess_data: Vec::new()
1742 let route = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2],
1743 Some(InvoiceFeatures::known()), None, &Vec::new(), 60_000, 42, Arc::clone(&logger)).unwrap();
1744 // Overpay fees to hit htlc_minimum_msat.
1745 let overpaid_fees = route.paths[0][0].fee_msat + route.paths[1][0].fee_msat;
1746 // TODO: this could be better balanced to overpay 10k and not 15k.
1747 assert_eq!(overpaid_fees, 15_000);
1749 // Now, test that if there are 2 paths, a "cheaper" by fee path wouldn't be prioritized
1750 // while taking even more fee to match htlc_minimum_msat.
1751 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
1752 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1753 short_channel_id: 12,
1756 cltv_expiry_delta: 0,
1757 htlc_minimum_msat: 65_000,
1758 htlc_maximum_msat: OptionalField::Present(80_000),
1760 fee_proportional_millionths: 0,
1761 excess_data: Vec::new()
1763 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
1764 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1765 short_channel_id: 2,
1768 cltv_expiry_delta: 0,
1769 htlc_minimum_msat: 0,
1770 htlc_maximum_msat: OptionalField::Absent,
1772 fee_proportional_millionths: 0,
1773 excess_data: Vec::new()
1775 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
1776 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1777 short_channel_id: 4,
1780 cltv_expiry_delta: 0,
1781 htlc_minimum_msat: 0,
1782 htlc_maximum_msat: OptionalField::Absent,
1784 fee_proportional_millionths: 100_000,
1785 excess_data: Vec::new()
1788 let route = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2],
1789 Some(InvoiceFeatures::known()), None, &Vec::new(), 60_000, 42, Arc::clone(&logger)).unwrap();
1790 // Fine to overpay for htlc_minimum_msat if it allows us to save fee.
1791 assert_eq!(route.paths.len(), 1);
1792 assert_eq!(route.paths[0][0].short_channel_id, 12);
1793 let fees = route.paths[0][0].fee_msat;
1794 assert_eq!(fees, 5_000);
1796 let route = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2],
1797 Some(InvoiceFeatures::known()), None, &Vec::new(), 50_000, 42, Arc::clone(&logger)).unwrap();
1798 // Not fine to overpay for htlc_minimum_msat if it requires paying more than fee on
1799 // the other channel.
1800 assert_eq!(route.paths.len(), 1);
1801 assert_eq!(route.paths[0][0].short_channel_id, 2);
1802 let fees = route.paths[0][0].fee_msat;
1803 assert_eq!(fees, 5_000);
1807 fn disable_channels_test() {
1808 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
1809 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
1811 // // Disable channels 4 and 12 by flags=2
1812 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
1813 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1814 short_channel_id: 4,
1816 flags: 2, // to disable
1817 cltv_expiry_delta: 0,
1818 htlc_minimum_msat: 0,
1819 htlc_maximum_msat: OptionalField::Absent,
1821 fee_proportional_millionths: 0,
1822 excess_data: Vec::new()
1824 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
1825 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1826 short_channel_id: 12,
1828 flags: 2, // to disable
1829 cltv_expiry_delta: 0,
1830 htlc_minimum_msat: 0,
1831 htlc_maximum_msat: OptionalField::Absent,
1833 fee_proportional_millionths: 0,
1834 excess_data: Vec::new()
1837 // If all the channels require some features we don't understand, route should fail
1838 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2], None, None, &Vec::new(), 100, 42, Arc::clone(&logger)) {
1839 assert_eq!(err, "Failed to find a path to the given destination");
1840 } else { panic!(); }
1842 // If we specify a channel to node7, that overrides our local channel view and that gets used
1843 let our_chans = vec![channelmanager::ChannelDetails {
1844 channel_id: [0; 32],
1845 short_channel_id: Some(42),
1846 remote_network_id: nodes[7].clone(),
1847 counterparty_features: InitFeatures::from_le_bytes(vec![0b11]),
1848 channel_value_satoshis: 0,
1850 outbound_capacity_msat: 250_000_000,
1851 inbound_capacity_msat: 0,
1853 counterparty_forwarding_info: None,
1855 let route = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2], None, Some(&our_chans.iter().collect::<Vec<_>>()), &Vec::new(), 100, 42, Arc::clone(&logger)).unwrap();
1856 assert_eq!(route.paths[0].len(), 2);
1858 assert_eq!(route.paths[0][0].pubkey, nodes[7]);
1859 assert_eq!(route.paths[0][0].short_channel_id, 42);
1860 assert_eq!(route.paths[0][0].fee_msat, 200);
1861 assert_eq!(route.paths[0][0].cltv_expiry_delta, (13 << 8) | 1);
1862 assert_eq!(route.paths[0][0].node_features.le_flags(), &vec![0b11]); // it should also override our view of their features
1863 assert_eq!(route.paths[0][0].channel_features.le_flags(), &Vec::<u8>::new()); // No feature flags will meet the relevant-to-channel conversion
1865 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
1866 assert_eq!(route.paths[0][1].short_channel_id, 13);
1867 assert_eq!(route.paths[0][1].fee_msat, 100);
1868 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
1869 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
1870 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(13));
1874 fn disable_node_test() {
1875 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
1876 let (_, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
1878 // Disable nodes 1, 2, and 8 by requiring unknown feature bits
1879 let mut unknown_features = NodeFeatures::known();
1880 unknown_features.set_required_unknown_bits();
1881 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[0], unknown_features.clone(), 1);
1882 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[1], unknown_features.clone(), 1);
1883 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[7], unknown_features.clone(), 1);
1885 // If all nodes require some features we don't understand, route should fail
1886 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2], None, None, &Vec::new(), 100, 42, Arc::clone(&logger)) {
1887 assert_eq!(err, "Failed to find a path to the given destination");
1888 } else { panic!(); }
1890 // If we specify a channel to node7, that overrides our local channel view and that gets used
1891 let our_chans = vec![channelmanager::ChannelDetails {
1892 channel_id: [0; 32],
1893 short_channel_id: Some(42),
1894 remote_network_id: nodes[7].clone(),
1895 counterparty_features: InitFeatures::from_le_bytes(vec![0b11]),
1896 channel_value_satoshis: 0,
1898 outbound_capacity_msat: 250_000_000,
1899 inbound_capacity_msat: 0,
1901 counterparty_forwarding_info: None,
1903 let route = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2], None, Some(&our_chans.iter().collect::<Vec<_>>()), &Vec::new(), 100, 42, Arc::clone(&logger)).unwrap();
1904 assert_eq!(route.paths[0].len(), 2);
1906 assert_eq!(route.paths[0][0].pubkey, nodes[7]);
1907 assert_eq!(route.paths[0][0].short_channel_id, 42);
1908 assert_eq!(route.paths[0][0].fee_msat, 200);
1909 assert_eq!(route.paths[0][0].cltv_expiry_delta, (13 << 8) | 1);
1910 assert_eq!(route.paths[0][0].node_features.le_flags(), &vec![0b11]); // it should also override our view of their features
1911 assert_eq!(route.paths[0][0].channel_features.le_flags(), &Vec::<u8>::new()); // No feature flags will meet the relevant-to-channel conversion
1913 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
1914 assert_eq!(route.paths[0][1].short_channel_id, 13);
1915 assert_eq!(route.paths[0][1].fee_msat, 100);
1916 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
1917 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
1918 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(13));
1920 // Note that we don't test disabling node 3 and failing to route to it, as we (somewhat
1921 // naively) assume that the user checked the feature bits on the invoice, which override
1922 // the node_announcement.
1926 fn our_chans_test() {
1927 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
1928 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
1930 // Route to 1 via 2 and 3 because our channel to 1 is disabled
1931 let route = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[0], None, None, &Vec::new(), 100, 42, Arc::clone(&logger)).unwrap();
1932 assert_eq!(route.paths[0].len(), 3);
1934 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
1935 assert_eq!(route.paths[0][0].short_channel_id, 2);
1936 assert_eq!(route.paths[0][0].fee_msat, 200);
1937 assert_eq!(route.paths[0][0].cltv_expiry_delta, (4 << 8) | 1);
1938 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
1939 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
1941 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
1942 assert_eq!(route.paths[0][1].short_channel_id, 4);
1943 assert_eq!(route.paths[0][1].fee_msat, 100);
1944 assert_eq!(route.paths[0][1].cltv_expiry_delta, (3 << 8) | 2);
1945 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
1946 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
1948 assert_eq!(route.paths[0][2].pubkey, nodes[0]);
1949 assert_eq!(route.paths[0][2].short_channel_id, 3);
1950 assert_eq!(route.paths[0][2].fee_msat, 100);
1951 assert_eq!(route.paths[0][2].cltv_expiry_delta, 42);
1952 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(1));
1953 assert_eq!(route.paths[0][2].channel_features.le_flags(), &id_to_feature_flags(3));
1955 // If we specify a channel to node7, that overrides our local channel view and that gets used
1956 let our_chans = vec![channelmanager::ChannelDetails {
1957 channel_id: [0; 32],
1958 short_channel_id: Some(42),
1959 remote_network_id: nodes[7].clone(),
1960 counterparty_features: InitFeatures::from_le_bytes(vec![0b11]),
1961 channel_value_satoshis: 0,
1963 outbound_capacity_msat: 250_000_000,
1964 inbound_capacity_msat: 0,
1966 counterparty_forwarding_info: None,
1968 let route = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2], None, Some(&our_chans.iter().collect::<Vec<_>>()), &Vec::new(), 100, 42, Arc::clone(&logger)).unwrap();
1969 assert_eq!(route.paths[0].len(), 2);
1971 assert_eq!(route.paths[0][0].pubkey, nodes[7]);
1972 assert_eq!(route.paths[0][0].short_channel_id, 42);
1973 assert_eq!(route.paths[0][0].fee_msat, 200);
1974 assert_eq!(route.paths[0][0].cltv_expiry_delta, (13 << 8) | 1);
1975 assert_eq!(route.paths[0][0].node_features.le_flags(), &vec![0b11]);
1976 assert_eq!(route.paths[0][0].channel_features.le_flags(), &Vec::<u8>::new()); // No feature flags will meet the relevant-to-channel conversion
1978 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
1979 assert_eq!(route.paths[0][1].short_channel_id, 13);
1980 assert_eq!(route.paths[0][1].fee_msat, 100);
1981 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
1982 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
1983 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(13));
1986 fn last_hops(nodes: &Vec<PublicKey>) -> Vec<RouteHint> {
1987 let zero_fees = RoutingFees {
1989 proportional_millionths: 0,
1992 src_node_id: nodes[3].clone(),
1993 short_channel_id: 8,
1995 cltv_expiry_delta: (8 << 8) | 1,
1996 htlc_minimum_msat: None,
1997 htlc_maximum_msat: None,
1999 src_node_id: nodes[4].clone(),
2000 short_channel_id: 9,
2003 proportional_millionths: 0,
2005 cltv_expiry_delta: (9 << 8) | 1,
2006 htlc_minimum_msat: None,
2007 htlc_maximum_msat: None,
2009 src_node_id: nodes[5].clone(),
2010 short_channel_id: 10,
2012 cltv_expiry_delta: (10 << 8) | 1,
2013 htlc_minimum_msat: None,
2014 htlc_maximum_msat: None,
2019 fn last_hops_test() {
2020 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
2021 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
2023 // Simple test across 2, 3, 5, and 4 via a last_hop channel
2025 // First check that lst hop can't have its source as the payee.
2026 let invalid_last_hop = RouteHint {
2027 src_node_id: nodes[6],
2028 short_channel_id: 8,
2031 proportional_millionths: 0,
2033 cltv_expiry_delta: (8 << 8) | 1,
2034 htlc_minimum_msat: None,
2035 htlc_maximum_msat: None,
2038 let mut invalid_last_hops = last_hops(&nodes);
2039 invalid_last_hops.push(invalid_last_hop);
2041 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[6], None, None, &invalid_last_hops.iter().collect::<Vec<_>>(), 100, 42, Arc::clone(&logger)) {
2042 assert_eq!(err, "Last hop cannot have a payee as a source.");
2043 } else { panic!(); }
2046 let route = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[6], None, None, &last_hops(&nodes).iter().collect::<Vec<_>>(), 100, 42, Arc::clone(&logger)).unwrap();
2047 assert_eq!(route.paths[0].len(), 5);
2049 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
2050 assert_eq!(route.paths[0][0].short_channel_id, 2);
2051 assert_eq!(route.paths[0][0].fee_msat, 100);
2052 assert_eq!(route.paths[0][0].cltv_expiry_delta, (4 << 8) | 1);
2053 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
2054 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
2056 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2057 assert_eq!(route.paths[0][1].short_channel_id, 4);
2058 assert_eq!(route.paths[0][1].fee_msat, 0);
2059 assert_eq!(route.paths[0][1].cltv_expiry_delta, (6 << 8) | 1);
2060 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2061 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
2063 assert_eq!(route.paths[0][2].pubkey, nodes[4]);
2064 assert_eq!(route.paths[0][2].short_channel_id, 6);
2065 assert_eq!(route.paths[0][2].fee_msat, 0);
2066 assert_eq!(route.paths[0][2].cltv_expiry_delta, (11 << 8) | 1);
2067 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(5));
2068 assert_eq!(route.paths[0][2].channel_features.le_flags(), &id_to_feature_flags(6));
2070 assert_eq!(route.paths[0][3].pubkey, nodes[3]);
2071 assert_eq!(route.paths[0][3].short_channel_id, 11);
2072 assert_eq!(route.paths[0][3].fee_msat, 0);
2073 assert_eq!(route.paths[0][3].cltv_expiry_delta, (8 << 8) | 1);
2074 // If we have a peer in the node map, we'll use their features here since we don't have
2075 // a way of figuring out their features from the invoice:
2076 assert_eq!(route.paths[0][3].node_features.le_flags(), &id_to_feature_flags(4));
2077 assert_eq!(route.paths[0][3].channel_features.le_flags(), &id_to_feature_flags(11));
2079 assert_eq!(route.paths[0][4].pubkey, nodes[6]);
2080 assert_eq!(route.paths[0][4].short_channel_id, 8);
2081 assert_eq!(route.paths[0][4].fee_msat, 100);
2082 assert_eq!(route.paths[0][4].cltv_expiry_delta, 42);
2083 assert_eq!(route.paths[0][4].node_features.le_flags(), &Vec::<u8>::new()); // We dont pass flags in from invoices yet
2084 assert_eq!(route.paths[0][4].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
2088 fn our_chans_last_hop_connect_test() {
2089 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
2090 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
2092 // Simple test with outbound channel to 4 to test that last_hops and first_hops connect
2093 let our_chans = vec![channelmanager::ChannelDetails {
2094 channel_id: [0; 32],
2095 short_channel_id: Some(42),
2096 remote_network_id: nodes[3].clone(),
2097 counterparty_features: InitFeatures::from_le_bytes(vec![0b11]),
2098 channel_value_satoshis: 0,
2100 outbound_capacity_msat: 250_000_000,
2101 inbound_capacity_msat: 0,
2103 counterparty_forwarding_info: None,
2105 let mut last_hops = last_hops(&nodes);
2106 let route = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[6], None, Some(&our_chans.iter().collect::<Vec<_>>()), &last_hops.iter().collect::<Vec<_>>(), 100, 42, Arc::clone(&logger)).unwrap();
2107 assert_eq!(route.paths[0].len(), 2);
2109 assert_eq!(route.paths[0][0].pubkey, nodes[3]);
2110 assert_eq!(route.paths[0][0].short_channel_id, 42);
2111 assert_eq!(route.paths[0][0].fee_msat, 0);
2112 assert_eq!(route.paths[0][0].cltv_expiry_delta, (8 << 8) | 1);
2113 assert_eq!(route.paths[0][0].node_features.le_flags(), &vec![0b11]);
2114 assert_eq!(route.paths[0][0].channel_features.le_flags(), &Vec::<u8>::new()); // No feature flags will meet the relevant-to-channel conversion
2116 assert_eq!(route.paths[0][1].pubkey, nodes[6]);
2117 assert_eq!(route.paths[0][1].short_channel_id, 8);
2118 assert_eq!(route.paths[0][1].fee_msat, 100);
2119 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
2120 assert_eq!(route.paths[0][1].node_features.le_flags(), &Vec::<u8>::new()); // We dont pass flags in from invoices yet
2121 assert_eq!(route.paths[0][1].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
2123 last_hops[0].fees.base_msat = 1000;
2125 // Revert to via 6 as the fee on 8 goes up
2126 let route = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[6], None, None, &last_hops.iter().collect::<Vec<_>>(), 100, 42, Arc::clone(&logger)).unwrap();
2127 assert_eq!(route.paths[0].len(), 4);
2129 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
2130 assert_eq!(route.paths[0][0].short_channel_id, 2);
2131 assert_eq!(route.paths[0][0].fee_msat, 200); // fee increased as its % of value transferred across node
2132 assert_eq!(route.paths[0][0].cltv_expiry_delta, (4 << 8) | 1);
2133 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
2134 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
2136 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2137 assert_eq!(route.paths[0][1].short_channel_id, 4);
2138 assert_eq!(route.paths[0][1].fee_msat, 100);
2139 assert_eq!(route.paths[0][1].cltv_expiry_delta, (7 << 8) | 1);
2140 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2141 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
2143 assert_eq!(route.paths[0][2].pubkey, nodes[5]);
2144 assert_eq!(route.paths[0][2].short_channel_id, 7);
2145 assert_eq!(route.paths[0][2].fee_msat, 0);
2146 assert_eq!(route.paths[0][2].cltv_expiry_delta, (10 << 8) | 1);
2147 // If we have a peer in the node map, we'll use their features here since we don't have
2148 // a way of figuring out their features from the invoice:
2149 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(6));
2150 assert_eq!(route.paths[0][2].channel_features.le_flags(), &id_to_feature_flags(7));
2152 assert_eq!(route.paths[0][3].pubkey, nodes[6]);
2153 assert_eq!(route.paths[0][3].short_channel_id, 10);
2154 assert_eq!(route.paths[0][3].fee_msat, 100);
2155 assert_eq!(route.paths[0][3].cltv_expiry_delta, 42);
2156 assert_eq!(route.paths[0][3].node_features.le_flags(), &Vec::<u8>::new()); // We dont pass flags in from invoices yet
2157 assert_eq!(route.paths[0][3].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
2159 // ...but still use 8 for larger payments as 6 has a variable feerate
2160 let route = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[6], None, None, &last_hops.iter().collect::<Vec<_>>(), 2000, 42, Arc::clone(&logger)).unwrap();
2161 assert_eq!(route.paths[0].len(), 5);
2163 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
2164 assert_eq!(route.paths[0][0].short_channel_id, 2);
2165 assert_eq!(route.paths[0][0].fee_msat, 3000);
2166 assert_eq!(route.paths[0][0].cltv_expiry_delta, (4 << 8) | 1);
2167 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
2168 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
2170 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2171 assert_eq!(route.paths[0][1].short_channel_id, 4);
2172 assert_eq!(route.paths[0][1].fee_msat, 0);
2173 assert_eq!(route.paths[0][1].cltv_expiry_delta, (6 << 8) | 1);
2174 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2175 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
2177 assert_eq!(route.paths[0][2].pubkey, nodes[4]);
2178 assert_eq!(route.paths[0][2].short_channel_id, 6);
2179 assert_eq!(route.paths[0][2].fee_msat, 0);
2180 assert_eq!(route.paths[0][2].cltv_expiry_delta, (11 << 8) | 1);
2181 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(5));
2182 assert_eq!(route.paths[0][2].channel_features.le_flags(), &id_to_feature_flags(6));
2184 assert_eq!(route.paths[0][3].pubkey, nodes[3]);
2185 assert_eq!(route.paths[0][3].short_channel_id, 11);
2186 assert_eq!(route.paths[0][3].fee_msat, 1000);
2187 assert_eq!(route.paths[0][3].cltv_expiry_delta, (8 << 8) | 1);
2188 // If we have a peer in the node map, we'll use their features here since we don't have
2189 // a way of figuring out their features from the invoice:
2190 assert_eq!(route.paths[0][3].node_features.le_flags(), &id_to_feature_flags(4));
2191 assert_eq!(route.paths[0][3].channel_features.le_flags(), &id_to_feature_flags(11));
2193 assert_eq!(route.paths[0][4].pubkey, nodes[6]);
2194 assert_eq!(route.paths[0][4].short_channel_id, 8);
2195 assert_eq!(route.paths[0][4].fee_msat, 2000);
2196 assert_eq!(route.paths[0][4].cltv_expiry_delta, 42);
2197 assert_eq!(route.paths[0][4].node_features.le_flags(), &Vec::<u8>::new()); // We dont pass flags in from invoices yet
2198 assert_eq!(route.paths[0][4].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
2202 fn unannounced_path_test() {
2203 // We should be able to send a payment to a destination without any help of a routing graph
2204 // if we have a channel with a common counterparty that appears in the first and last hop
2206 let source_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&hex::decode(format!("{:02}", 41).repeat(32)).unwrap()[..]).unwrap());
2207 let middle_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&hex::decode(format!("{:02}", 42).repeat(32)).unwrap()[..]).unwrap());
2208 let target_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&hex::decode(format!("{:02}", 43).repeat(32)).unwrap()[..]).unwrap());
2210 // If we specify a channel to a middle hop, that overrides our local channel view and that gets used
2211 let last_hops = vec![RouteHint {
2212 src_node_id: middle_node_id,
2213 short_channel_id: 8,
2216 proportional_millionths: 0,
2218 cltv_expiry_delta: (8 << 8) | 1,
2219 htlc_minimum_msat: None,
2220 htlc_maximum_msat: None,
2222 let our_chans = vec![channelmanager::ChannelDetails {
2223 channel_id: [0; 32],
2224 short_channel_id: Some(42),
2225 remote_network_id: middle_node_id,
2226 counterparty_features: InitFeatures::from_le_bytes(vec![0b11]),
2227 channel_value_satoshis: 100000,
2229 outbound_capacity_msat: 100000,
2230 inbound_capacity_msat: 100000,
2232 counterparty_forwarding_info: None,
2234 let route = get_route(&source_node_id, &NetworkGraph::new(genesis_block(Network::Testnet).header.block_hash()), &target_node_id, None, Some(&our_chans.iter().collect::<Vec<_>>()), &last_hops.iter().collect::<Vec<_>>(), 100, 42, Arc::new(test_utils::TestLogger::new())).unwrap();
2236 assert_eq!(route.paths[0].len(), 2);
2238 assert_eq!(route.paths[0][0].pubkey, middle_node_id);
2239 assert_eq!(route.paths[0][0].short_channel_id, 42);
2240 assert_eq!(route.paths[0][0].fee_msat, 1000);
2241 assert_eq!(route.paths[0][0].cltv_expiry_delta, (8 << 8) | 1);
2242 assert_eq!(route.paths[0][0].node_features.le_flags(), &[0b11]);
2243 assert_eq!(route.paths[0][0].channel_features.le_flags(), &[0; 0]); // We can't learn any flags from invoices, sadly
2245 assert_eq!(route.paths[0][1].pubkey, target_node_id);
2246 assert_eq!(route.paths[0][1].short_channel_id, 8);
2247 assert_eq!(route.paths[0][1].fee_msat, 100);
2248 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
2249 assert_eq!(route.paths[0][1].node_features.le_flags(), &[0; 0]); // We dont pass flags in from invoices yet
2250 assert_eq!(route.paths[0][1].channel_features.le_flags(), &[0; 0]); // We can't learn any flags from invoices, sadly
2254 fn available_amount_while_routing_test() {
2255 // Tests whether we choose the correct available channel amount while routing.
2257 let (secp_ctx, mut net_graph_msg_handler, chain_monitor, logger) = build_graph();
2258 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
2260 // We will use a simple single-path route from
2261 // our node to node2 via node0: channels {1, 3}.
2263 // First disable all other paths.
2264 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2265 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2266 short_channel_id: 2,
2269 cltv_expiry_delta: 0,
2270 htlc_minimum_msat: 0,
2271 htlc_maximum_msat: OptionalField::Present(100_000),
2273 fee_proportional_millionths: 0,
2274 excess_data: Vec::new()
2276 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2277 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2278 short_channel_id: 12,
2281 cltv_expiry_delta: 0,
2282 htlc_minimum_msat: 0,
2283 htlc_maximum_msat: OptionalField::Present(100_000),
2285 fee_proportional_millionths: 0,
2286 excess_data: Vec::new()
2289 // Make the first channel (#1) very permissive,
2290 // and we will be testing all limits on the second channel.
2291 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2292 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2293 short_channel_id: 1,
2296 cltv_expiry_delta: 0,
2297 htlc_minimum_msat: 0,
2298 htlc_maximum_msat: OptionalField::Present(1_000_000_000),
2300 fee_proportional_millionths: 0,
2301 excess_data: Vec::new()
2304 // First, let's see if routing works if we have absolutely no idea about the available amount.
2305 // In this case, it should be set to 250_000 sats.
2306 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
2307 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2308 short_channel_id: 3,
2311 cltv_expiry_delta: 0,
2312 htlc_minimum_msat: 0,
2313 htlc_maximum_msat: OptionalField::Absent,
2315 fee_proportional_millionths: 0,
2316 excess_data: Vec::new()
2320 // Attempt to route more than available results in a failure.
2321 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2],
2322 Some(InvoiceFeatures::known()), None, &Vec::new(), 250_000_001, 42, Arc::clone(&logger)) {
2323 assert_eq!(err, "Failed to find a sufficient route to the given destination");
2324 } else { panic!(); }
2328 // Now, attempt to route an exact amount we have should be fine.
2329 let route = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2],
2330 Some(InvoiceFeatures::known()), None, &Vec::new(), 250_000_000, 42, Arc::clone(&logger)).unwrap();
2331 assert_eq!(route.paths.len(), 1);
2332 let path = route.paths.last().unwrap();
2333 assert_eq!(path.len(), 2);
2334 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
2335 assert_eq!(path.last().unwrap().fee_msat, 250_000_000);
2338 // Check that setting outbound_capacity_msat in first_hops limits the channels.
2339 // Disable channel #1 and use another first hop.
2340 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2341 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2342 short_channel_id: 1,
2345 cltv_expiry_delta: 0,
2346 htlc_minimum_msat: 0,
2347 htlc_maximum_msat: OptionalField::Present(1_000_000_000),
2349 fee_proportional_millionths: 0,
2350 excess_data: Vec::new()
2353 // Now, limit the first_hop by the outbound_capacity_msat of 200_000 sats.
2354 let our_chans = vec![channelmanager::ChannelDetails {
2355 channel_id: [0; 32],
2356 short_channel_id: Some(42),
2357 remote_network_id: nodes[0].clone(),
2358 counterparty_features: InitFeatures::from_le_bytes(vec![0b11]),
2359 channel_value_satoshis: 0,
2361 outbound_capacity_msat: 200_000_000,
2362 inbound_capacity_msat: 0,
2364 counterparty_forwarding_info: None,
2368 // Attempt to route more than available results in a failure.
2369 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2],
2370 Some(InvoiceFeatures::known()), Some(&our_chans.iter().collect::<Vec<_>>()), &Vec::new(), 200_000_001, 42, Arc::clone(&logger)) {
2371 assert_eq!(err, "Failed to find a sufficient route to the given destination");
2372 } else { panic!(); }
2376 // Now, attempt to route an exact amount we have should be fine.
2377 let route = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2],
2378 Some(InvoiceFeatures::known()), Some(&our_chans.iter().collect::<Vec<_>>()), &Vec::new(), 200_000_000, 42, Arc::clone(&logger)).unwrap();
2379 assert_eq!(route.paths.len(), 1);
2380 let path = route.paths.last().unwrap();
2381 assert_eq!(path.len(), 2);
2382 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
2383 assert_eq!(path.last().unwrap().fee_msat, 200_000_000);
2386 // Enable channel #1 back.
2387 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2388 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2389 short_channel_id: 1,
2392 cltv_expiry_delta: 0,
2393 htlc_minimum_msat: 0,
2394 htlc_maximum_msat: OptionalField::Present(1_000_000_000),
2396 fee_proportional_millionths: 0,
2397 excess_data: Vec::new()
2401 // Now let's see if routing works if we know only htlc_maximum_msat.
2402 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
2403 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2404 short_channel_id: 3,
2407 cltv_expiry_delta: 0,
2408 htlc_minimum_msat: 0,
2409 htlc_maximum_msat: OptionalField::Present(15_000),
2411 fee_proportional_millionths: 0,
2412 excess_data: Vec::new()
2416 // Attempt to route more than available results in a failure.
2417 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2],
2418 Some(InvoiceFeatures::known()), None, &Vec::new(), 15_001, 42, Arc::clone(&logger)) {
2419 assert_eq!(err, "Failed to find a sufficient route to the given destination");
2420 } else { panic!(); }
2424 // Now, attempt to route an exact amount we have should be fine.
2425 let route = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2],
2426 Some(InvoiceFeatures::known()), None, &Vec::new(), 15_000, 42, Arc::clone(&logger)).unwrap();
2427 assert_eq!(route.paths.len(), 1);
2428 let path = route.paths.last().unwrap();
2429 assert_eq!(path.len(), 2);
2430 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
2431 assert_eq!(path.last().unwrap().fee_msat, 15_000);
2434 // Now let's see if routing works if we know only capacity from the UTXO.
2436 // We can't change UTXO capacity on the fly, so we'll disable
2437 // the existing channel and add another one with the capacity we need.
2438 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
2439 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2440 short_channel_id: 3,
2443 cltv_expiry_delta: 0,
2444 htlc_minimum_msat: 0,
2445 htlc_maximum_msat: OptionalField::Absent,
2447 fee_proportional_millionths: 0,
2448 excess_data: Vec::new()
2451 let good_script = Builder::new().push_opcode(opcodes::all::OP_PUSHNUM_2)
2452 .push_slice(&PublicKey::from_secret_key(&secp_ctx, &privkeys[0]).serialize())
2453 .push_slice(&PublicKey::from_secret_key(&secp_ctx, &privkeys[2]).serialize())
2454 .push_opcode(opcodes::all::OP_PUSHNUM_2)
2455 .push_opcode(opcodes::all::OP_CHECKMULTISIG).into_script().to_v0_p2wsh();
2457 *chain_monitor.utxo_ret.lock().unwrap() = Ok(TxOut { value: 15, script_pubkey: good_script.clone() });
2458 net_graph_msg_handler.add_chain_access(Some(chain_monitor));
2460 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], &privkeys[2], ChannelFeatures::from_le_bytes(id_to_feature_flags(3)), 333);
2461 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
2462 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2463 short_channel_id: 333,
2466 cltv_expiry_delta: (3 << 8) | 1,
2467 htlc_minimum_msat: 0,
2468 htlc_maximum_msat: OptionalField::Absent,
2470 fee_proportional_millionths: 0,
2471 excess_data: Vec::new()
2473 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
2474 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2475 short_channel_id: 333,
2478 cltv_expiry_delta: (3 << 8) | 2,
2479 htlc_minimum_msat: 0,
2480 htlc_maximum_msat: OptionalField::Absent,
2482 fee_proportional_millionths: 0,
2483 excess_data: Vec::new()
2487 // Attempt to route more than available results in a failure.
2488 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2],
2489 Some(InvoiceFeatures::known()), None, &Vec::new(), 15_001, 42, Arc::clone(&logger)) {
2490 assert_eq!(err, "Failed to find a sufficient route to the given destination");
2491 } else { panic!(); }
2495 // Now, attempt to route an exact amount we have should be fine.
2496 let route = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2],
2497 Some(InvoiceFeatures::known()), None, &Vec::new(), 15_000, 42, Arc::clone(&logger)).unwrap();
2498 assert_eq!(route.paths.len(), 1);
2499 let path = route.paths.last().unwrap();
2500 assert_eq!(path.len(), 2);
2501 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
2502 assert_eq!(path.last().unwrap().fee_msat, 15_000);
2505 // Now let's see if routing chooses htlc_maximum_msat over UTXO capacity.
2506 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
2507 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2508 short_channel_id: 333,
2511 cltv_expiry_delta: 0,
2512 htlc_minimum_msat: 0,
2513 htlc_maximum_msat: OptionalField::Present(10_000),
2515 fee_proportional_millionths: 0,
2516 excess_data: Vec::new()
2520 // Attempt to route more than available results in a failure.
2521 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2],
2522 Some(InvoiceFeatures::known()), None, &Vec::new(), 10_001, 42, Arc::clone(&logger)) {
2523 assert_eq!(err, "Failed to find a sufficient route to the given destination");
2524 } else { panic!(); }
2528 // Now, attempt to route an exact amount we have should be fine.
2529 let route = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2],
2530 Some(InvoiceFeatures::known()), None, &Vec::new(), 10_000, 42, Arc::clone(&logger)).unwrap();
2531 assert_eq!(route.paths.len(), 1);
2532 let path = route.paths.last().unwrap();
2533 assert_eq!(path.len(), 2);
2534 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
2535 assert_eq!(path.last().unwrap().fee_msat, 10_000);
2540 fn available_liquidity_last_hop_test() {
2541 // Check that available liquidity properly limits the path even when only
2542 // one of the latter hops is limited.
2543 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
2544 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
2546 // Path via {node7, node2, node4} is channels {12, 13, 6, 11}.
2547 // {12, 13, 11} have the capacities of 100, {6} has a capacity of 50.
2548 // Total capacity: 50 sats.
2550 // Disable other potential paths.
2551 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2552 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2553 short_channel_id: 2,
2556 cltv_expiry_delta: 0,
2557 htlc_minimum_msat: 0,
2558 htlc_maximum_msat: OptionalField::Present(100_000),
2560 fee_proportional_millionths: 0,
2561 excess_data: Vec::new()
2563 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
2564 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2565 short_channel_id: 7,
2568 cltv_expiry_delta: 0,
2569 htlc_minimum_msat: 0,
2570 htlc_maximum_msat: OptionalField::Present(100_000),
2572 fee_proportional_millionths: 0,
2573 excess_data: Vec::new()
2578 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2579 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2580 short_channel_id: 12,
2583 cltv_expiry_delta: 0,
2584 htlc_minimum_msat: 0,
2585 htlc_maximum_msat: OptionalField::Present(100_000),
2587 fee_proportional_millionths: 0,
2588 excess_data: Vec::new()
2590 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
2591 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2592 short_channel_id: 13,
2595 cltv_expiry_delta: 0,
2596 htlc_minimum_msat: 0,
2597 htlc_maximum_msat: OptionalField::Present(100_000),
2599 fee_proportional_millionths: 0,
2600 excess_data: Vec::new()
2603 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
2604 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2605 short_channel_id: 6,
2608 cltv_expiry_delta: 0,
2609 htlc_minimum_msat: 0,
2610 htlc_maximum_msat: OptionalField::Present(50_000),
2612 fee_proportional_millionths: 0,
2613 excess_data: Vec::new()
2615 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
2616 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2617 short_channel_id: 11,
2620 cltv_expiry_delta: 0,
2621 htlc_minimum_msat: 0,
2622 htlc_maximum_msat: OptionalField::Present(100_000),
2624 fee_proportional_millionths: 0,
2625 excess_data: Vec::new()
2628 // Attempt to route more than available results in a failure.
2629 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[3],
2630 Some(InvoiceFeatures::known()), None, &Vec::new(), 60_000, 42, Arc::clone(&logger)) {
2631 assert_eq!(err, "Failed to find a sufficient route to the given destination");
2632 } else { panic!(); }
2636 // Now, attempt to route 49 sats (just a bit below the capacity).
2637 let route = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[3],
2638 Some(InvoiceFeatures::known()), None, &Vec::new(), 49_000, 42, Arc::clone(&logger)).unwrap();
2639 assert_eq!(route.paths.len(), 1);
2640 let mut total_amount_paid_msat = 0;
2641 for path in &route.paths {
2642 assert_eq!(path.len(), 4);
2643 assert_eq!(path.last().unwrap().pubkey, nodes[3]);
2644 total_amount_paid_msat += path.last().unwrap().fee_msat;
2646 assert_eq!(total_amount_paid_msat, 49_000);
2650 // Attempt to route an exact amount is also fine
2651 let route = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[3],
2652 Some(InvoiceFeatures::known()), None, &Vec::new(), 50_000, 42, Arc::clone(&logger)).unwrap();
2653 assert_eq!(route.paths.len(), 1);
2654 let mut total_amount_paid_msat = 0;
2655 for path in &route.paths {
2656 assert_eq!(path.len(), 4);
2657 assert_eq!(path.last().unwrap().pubkey, nodes[3]);
2658 total_amount_paid_msat += path.last().unwrap().fee_msat;
2660 assert_eq!(total_amount_paid_msat, 50_000);
2665 fn ignore_fee_first_hop_test() {
2666 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
2667 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
2669 // Path via node0 is channels {1, 3}. Limit them to 100 and 50 sats (total limit 50).
2670 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2671 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2672 short_channel_id: 1,
2675 cltv_expiry_delta: 0,
2676 htlc_minimum_msat: 0,
2677 htlc_maximum_msat: OptionalField::Present(100_000),
2678 fee_base_msat: 1_000_000,
2679 fee_proportional_millionths: 0,
2680 excess_data: Vec::new()
2682 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
2683 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2684 short_channel_id: 3,
2687 cltv_expiry_delta: 0,
2688 htlc_minimum_msat: 0,
2689 htlc_maximum_msat: OptionalField::Present(50_000),
2691 fee_proportional_millionths: 0,
2692 excess_data: Vec::new()
2696 let route = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2], None, None, &Vec::new(), 50_000, 42, Arc::clone(&logger)).unwrap();
2697 assert_eq!(route.paths.len(), 1);
2698 let mut total_amount_paid_msat = 0;
2699 for path in &route.paths {
2700 assert_eq!(path.len(), 2);
2701 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
2702 total_amount_paid_msat += path.last().unwrap().fee_msat;
2704 assert_eq!(total_amount_paid_msat, 50_000);
2709 fn simple_mpp_route_test() {
2710 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
2711 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
2713 // We need a route consisting of 3 paths:
2714 // From our node to node2 via node0, node7, node1 (three paths one hop each).
2715 // To achieve this, the amount being transferred should be around
2716 // the total capacity of these 3 paths.
2718 // First, we set limits on these (previously unlimited) channels.
2719 // Their aggregate capacity will be 50 + 60 + 180 = 290 sats.
2721 // Path via node0 is channels {1, 3}. Limit them to 100 and 50 sats (total limit 50).
2722 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2723 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2724 short_channel_id: 1,
2727 cltv_expiry_delta: 0,
2728 htlc_minimum_msat: 0,
2729 htlc_maximum_msat: OptionalField::Present(100_000),
2731 fee_proportional_millionths: 0,
2732 excess_data: Vec::new()
2734 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
2735 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2736 short_channel_id: 3,
2739 cltv_expiry_delta: 0,
2740 htlc_minimum_msat: 0,
2741 htlc_maximum_msat: OptionalField::Present(50_000),
2743 fee_proportional_millionths: 0,
2744 excess_data: Vec::new()
2747 // Path via node7 is channels {12, 13}. Limit them to 60 and 60 sats
2748 // (total limit 60).
2749 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2750 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2751 short_channel_id: 12,
2754 cltv_expiry_delta: 0,
2755 htlc_minimum_msat: 0,
2756 htlc_maximum_msat: OptionalField::Present(60_000),
2758 fee_proportional_millionths: 0,
2759 excess_data: Vec::new()
2761 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
2762 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2763 short_channel_id: 13,
2766 cltv_expiry_delta: 0,
2767 htlc_minimum_msat: 0,
2768 htlc_maximum_msat: OptionalField::Present(60_000),
2770 fee_proportional_millionths: 0,
2771 excess_data: Vec::new()
2774 // Path via node1 is channels {2, 4}. Limit them to 200 and 180 sats
2775 // (total capacity 180 sats).
2776 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2777 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2778 short_channel_id: 2,
2781 cltv_expiry_delta: 0,
2782 htlc_minimum_msat: 0,
2783 htlc_maximum_msat: OptionalField::Present(200_000),
2785 fee_proportional_millionths: 0,
2786 excess_data: Vec::new()
2788 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
2789 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2790 short_channel_id: 4,
2793 cltv_expiry_delta: 0,
2794 htlc_minimum_msat: 0,
2795 htlc_maximum_msat: OptionalField::Present(180_000),
2797 fee_proportional_millionths: 0,
2798 excess_data: Vec::new()
2802 // Attempt to route more than available results in a failure.
2803 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(),
2804 &nodes[2], Some(InvoiceFeatures::known()), None, &Vec::new(), 300_000, 42, Arc::clone(&logger)) {
2805 assert_eq!(err, "Failed to find a sufficient route to the given destination");
2806 } else { panic!(); }
2810 // Now, attempt to route 250 sats (just a bit below the capacity).
2811 // Our algorithm should provide us with these 3 paths.
2812 let route = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2],
2813 Some(InvoiceFeatures::known()), None, &Vec::new(), 250_000, 42, Arc::clone(&logger)).unwrap();
2814 assert_eq!(route.paths.len(), 3);
2815 let mut total_amount_paid_msat = 0;
2816 for path in &route.paths {
2817 assert_eq!(path.len(), 2);
2818 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
2819 total_amount_paid_msat += path.last().unwrap().fee_msat;
2821 assert_eq!(total_amount_paid_msat, 250_000);
2825 // Attempt to route an exact amount is also fine
2826 let route = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2],
2827 Some(InvoiceFeatures::known()), None, &Vec::new(), 290_000, 42, Arc::clone(&logger)).unwrap();
2828 assert_eq!(route.paths.len(), 3);
2829 let mut total_amount_paid_msat = 0;
2830 for path in &route.paths {
2831 assert_eq!(path.len(), 2);
2832 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
2833 total_amount_paid_msat += path.last().unwrap().fee_msat;
2835 assert_eq!(total_amount_paid_msat, 290_000);
2840 fn long_mpp_route_test() {
2841 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
2842 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
2844 // We need a route consisting of 3 paths:
2845 // From our node to node3 via {node0, node2}, {node7, node2, node4} and {node7, node2}.
2846 // Note that these paths overlap (channels 5, 12, 13).
2847 // We will route 300 sats.
2848 // Each path will have 100 sats capacity, those channels which
2849 // are used twice will have 200 sats capacity.
2851 // Disable other potential paths.
2852 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2853 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2854 short_channel_id: 2,
2857 cltv_expiry_delta: 0,
2858 htlc_minimum_msat: 0,
2859 htlc_maximum_msat: OptionalField::Present(100_000),
2861 fee_proportional_millionths: 0,
2862 excess_data: Vec::new()
2864 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
2865 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2866 short_channel_id: 7,
2869 cltv_expiry_delta: 0,
2870 htlc_minimum_msat: 0,
2871 htlc_maximum_msat: OptionalField::Present(100_000),
2873 fee_proportional_millionths: 0,
2874 excess_data: Vec::new()
2877 // Path via {node0, node2} is channels {1, 3, 5}.
2878 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2879 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2880 short_channel_id: 1,
2883 cltv_expiry_delta: 0,
2884 htlc_minimum_msat: 0,
2885 htlc_maximum_msat: OptionalField::Present(100_000),
2887 fee_proportional_millionths: 0,
2888 excess_data: Vec::new()
2890 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
2891 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2892 short_channel_id: 3,
2895 cltv_expiry_delta: 0,
2896 htlc_minimum_msat: 0,
2897 htlc_maximum_msat: OptionalField::Present(100_000),
2899 fee_proportional_millionths: 0,
2900 excess_data: Vec::new()
2903 // Capacity of 200 sats because this channel will be used by 3rd path as well.
2904 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(5)), 5);
2905 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
2906 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2907 short_channel_id: 5,
2910 cltv_expiry_delta: 0,
2911 htlc_minimum_msat: 0,
2912 htlc_maximum_msat: OptionalField::Present(200_000),
2914 fee_proportional_millionths: 0,
2915 excess_data: Vec::new()
2918 // Path via {node7, node2, node4} is channels {12, 13, 6, 11}.
2919 // Add 100 sats to the capacities of {12, 13}, because these channels
2920 // are also used for 3rd path. 100 sats for the rest. Total capacity: 100 sats.
2921 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2922 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2923 short_channel_id: 12,
2926 cltv_expiry_delta: 0,
2927 htlc_minimum_msat: 0,
2928 htlc_maximum_msat: OptionalField::Present(200_000),
2930 fee_proportional_millionths: 0,
2931 excess_data: Vec::new()
2933 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
2934 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2935 short_channel_id: 13,
2938 cltv_expiry_delta: 0,
2939 htlc_minimum_msat: 0,
2940 htlc_maximum_msat: OptionalField::Present(200_000),
2942 fee_proportional_millionths: 0,
2943 excess_data: Vec::new()
2946 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
2947 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2948 short_channel_id: 6,
2951 cltv_expiry_delta: 0,
2952 htlc_minimum_msat: 0,
2953 htlc_maximum_msat: OptionalField::Present(100_000),
2955 fee_proportional_millionths: 0,
2956 excess_data: Vec::new()
2958 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
2959 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2960 short_channel_id: 11,
2963 cltv_expiry_delta: 0,
2964 htlc_minimum_msat: 0,
2965 htlc_maximum_msat: OptionalField::Present(100_000),
2967 fee_proportional_millionths: 0,
2968 excess_data: Vec::new()
2971 // Path via {node7, node2} is channels {12, 13, 5}.
2972 // We already limited them to 200 sats (they are used twice for 100 sats).
2973 // Nothing to do here.
2976 // Attempt to route more than available results in a failure.
2977 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[3],
2978 Some(InvoiceFeatures::known()), None, &Vec::new(), 350_000, 42, Arc::clone(&logger)) {
2979 assert_eq!(err, "Failed to find a sufficient route to the given destination");
2980 } else { panic!(); }
2984 // Now, attempt to route 300 sats (exact amount we can route).
2985 // Our algorithm should provide us with these 3 paths, 100 sats each.
2986 let route = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[3],
2987 Some(InvoiceFeatures::known()), None, &Vec::new(), 300_000, 42, Arc::clone(&logger)).unwrap();
2988 assert_eq!(route.paths.len(), 3);
2990 let mut total_amount_paid_msat = 0;
2991 for path in &route.paths {
2992 assert_eq!(path.last().unwrap().pubkey, nodes[3]);
2993 total_amount_paid_msat += path.last().unwrap().fee_msat;
2995 assert_eq!(total_amount_paid_msat, 300_000);
3001 fn mpp_cheaper_route_test() {
3002 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
3003 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3005 // This test checks that if we have two cheaper paths and one more expensive path,
3006 // so that liquidity-wise any 2 of 3 combination is sufficient,
3007 // two cheaper paths will be taken.
3008 // These paths have equal available liquidity.
3010 // We need a combination of 3 paths:
3011 // From our node to node3 via {node0, node2}, {node7, node2, node4} and {node7, node2}.
3012 // Note that these paths overlap (channels 5, 12, 13).
3013 // Each path will have 100 sats capacity, those channels which
3014 // are used twice will have 200 sats capacity.
3016 // Disable other potential paths.
3017 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3018 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3019 short_channel_id: 2,
3022 cltv_expiry_delta: 0,
3023 htlc_minimum_msat: 0,
3024 htlc_maximum_msat: OptionalField::Present(100_000),
3026 fee_proportional_millionths: 0,
3027 excess_data: Vec::new()
3029 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3030 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3031 short_channel_id: 7,
3034 cltv_expiry_delta: 0,
3035 htlc_minimum_msat: 0,
3036 htlc_maximum_msat: OptionalField::Present(100_000),
3038 fee_proportional_millionths: 0,
3039 excess_data: Vec::new()
3042 // Path via {node0, node2} is channels {1, 3, 5}.
3043 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3044 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3045 short_channel_id: 1,
3048 cltv_expiry_delta: 0,
3049 htlc_minimum_msat: 0,
3050 htlc_maximum_msat: OptionalField::Present(100_000),
3052 fee_proportional_millionths: 0,
3053 excess_data: Vec::new()
3055 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3056 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3057 short_channel_id: 3,
3060 cltv_expiry_delta: 0,
3061 htlc_minimum_msat: 0,
3062 htlc_maximum_msat: OptionalField::Present(100_000),
3064 fee_proportional_millionths: 0,
3065 excess_data: Vec::new()
3068 // Capacity of 200 sats because this channel will be used by 3rd path as well.
3069 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(5)), 5);
3070 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3071 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3072 short_channel_id: 5,
3075 cltv_expiry_delta: 0,
3076 htlc_minimum_msat: 0,
3077 htlc_maximum_msat: OptionalField::Present(200_000),
3079 fee_proportional_millionths: 0,
3080 excess_data: Vec::new()
3083 // Path via {node7, node2, node4} is channels {12, 13, 6, 11}.
3084 // Add 100 sats to the capacities of {12, 13}, because these channels
3085 // are also used for 3rd path. 100 sats for the rest. Total capacity: 100 sats.
3086 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3087 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3088 short_channel_id: 12,
3091 cltv_expiry_delta: 0,
3092 htlc_minimum_msat: 0,
3093 htlc_maximum_msat: OptionalField::Present(200_000),
3095 fee_proportional_millionths: 0,
3096 excess_data: Vec::new()
3098 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
3099 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3100 short_channel_id: 13,
3103 cltv_expiry_delta: 0,
3104 htlc_minimum_msat: 0,
3105 htlc_maximum_msat: OptionalField::Present(200_000),
3107 fee_proportional_millionths: 0,
3108 excess_data: Vec::new()
3111 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3112 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3113 short_channel_id: 6,
3116 cltv_expiry_delta: 0,
3117 htlc_minimum_msat: 0,
3118 htlc_maximum_msat: OptionalField::Present(100_000),
3119 fee_base_msat: 1_000,
3120 fee_proportional_millionths: 0,
3121 excess_data: Vec::new()
3123 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
3124 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3125 short_channel_id: 11,
3128 cltv_expiry_delta: 0,
3129 htlc_minimum_msat: 0,
3130 htlc_maximum_msat: OptionalField::Present(100_000),
3132 fee_proportional_millionths: 0,
3133 excess_data: Vec::new()
3136 // Path via {node7, node2} is channels {12, 13, 5}.
3137 // We already limited them to 200 sats (they are used twice for 100 sats).
3138 // Nothing to do here.
3141 // Now, attempt to route 180 sats.
3142 // Our algorithm should provide us with these 2 paths.
3143 let route = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[3],
3144 Some(InvoiceFeatures::known()), None, &Vec::new(), 180_000, 42, Arc::clone(&logger)).unwrap();
3145 assert_eq!(route.paths.len(), 2);
3147 let mut total_value_transferred_msat = 0;
3148 let mut total_paid_msat = 0;
3149 for path in &route.paths {
3150 assert_eq!(path.last().unwrap().pubkey, nodes[3]);
3151 total_value_transferred_msat += path.last().unwrap().fee_msat;
3153 total_paid_msat += hop.fee_msat;
3156 // If we paid fee, this would be higher.
3157 assert_eq!(total_value_transferred_msat, 180_000);
3158 let total_fees_paid = total_paid_msat - total_value_transferred_msat;
3159 assert_eq!(total_fees_paid, 0);
3164 fn fees_on_mpp_route_test() {
3165 // This test makes sure that MPP algorithm properly takes into account
3166 // fees charged on the channels, by making the fees impactful:
3167 // if the fee is not properly accounted for, the behavior is different.
3168 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
3169 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3171 // We need a route consisting of 2 paths:
3172 // From our node to node3 via {node0, node2} and {node7, node2, node4}.
3173 // We will route 200 sats, Each path will have 100 sats capacity.
3175 // This test is not particularly stable: e.g.,
3176 // there's a way to route via {node0, node2, node4}.
3177 // It works while pathfinding is deterministic, but can be broken otherwise.
3178 // It's fine to ignore this concern for now.
3180 // Disable other potential paths.
3181 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3182 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3183 short_channel_id: 2,
3186 cltv_expiry_delta: 0,
3187 htlc_minimum_msat: 0,
3188 htlc_maximum_msat: OptionalField::Present(100_000),
3190 fee_proportional_millionths: 0,
3191 excess_data: Vec::new()
3194 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3195 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3196 short_channel_id: 7,
3199 cltv_expiry_delta: 0,
3200 htlc_minimum_msat: 0,
3201 htlc_maximum_msat: OptionalField::Present(100_000),
3203 fee_proportional_millionths: 0,
3204 excess_data: Vec::new()
3207 // Path via {node0, node2} is channels {1, 3, 5}.
3208 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3209 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3210 short_channel_id: 1,
3213 cltv_expiry_delta: 0,
3214 htlc_minimum_msat: 0,
3215 htlc_maximum_msat: OptionalField::Present(100_000),
3217 fee_proportional_millionths: 0,
3218 excess_data: Vec::new()
3220 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3221 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3222 short_channel_id: 3,
3225 cltv_expiry_delta: 0,
3226 htlc_minimum_msat: 0,
3227 htlc_maximum_msat: OptionalField::Present(100_000),
3229 fee_proportional_millionths: 0,
3230 excess_data: Vec::new()
3233 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(5)), 5);
3234 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3235 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3236 short_channel_id: 5,
3239 cltv_expiry_delta: 0,
3240 htlc_minimum_msat: 0,
3241 htlc_maximum_msat: OptionalField::Present(100_000),
3243 fee_proportional_millionths: 0,
3244 excess_data: Vec::new()
3247 // Path via {node7, node2, node4} is channels {12, 13, 6, 11}.
3248 // All channels should be 100 sats capacity. But for the fee experiment,
3249 // we'll add absolute fee of 150 sats paid for the use channel 6 (paid to node2 on channel 13).
3250 // Since channel 12 allows to deliver only 250 sats to channel 13, channel 13 can transfer only
3251 // 100 sats (and pay 150 sats in fees for the use of channel 6),
3252 // so no matter how large are other channels,
3253 // the whole path will be limited by 100 sats with just these 2 conditions:
3254 // - channel 12 capacity is 250 sats
3255 // - fee for channel 6 is 150 sats
3256 // Let's test this by enforcing these 2 conditions and removing other limits.
3257 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3258 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3259 short_channel_id: 12,
3262 cltv_expiry_delta: 0,
3263 htlc_minimum_msat: 0,
3264 htlc_maximum_msat: OptionalField::Present(250_000),
3266 fee_proportional_millionths: 0,
3267 excess_data: Vec::new()
3269 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
3270 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3271 short_channel_id: 13,
3274 cltv_expiry_delta: 0,
3275 htlc_minimum_msat: 0,
3276 htlc_maximum_msat: OptionalField::Absent,
3278 fee_proportional_millionths: 0,
3279 excess_data: Vec::new()
3282 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3283 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3284 short_channel_id: 6,
3287 cltv_expiry_delta: 0,
3288 htlc_minimum_msat: 0,
3289 htlc_maximum_msat: OptionalField::Absent,
3290 fee_base_msat: 150_000,
3291 fee_proportional_millionths: 0,
3292 excess_data: Vec::new()
3294 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
3295 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3296 short_channel_id: 11,
3299 cltv_expiry_delta: 0,
3300 htlc_minimum_msat: 0,
3301 htlc_maximum_msat: OptionalField::Absent,
3303 fee_proportional_millionths: 0,
3304 excess_data: Vec::new()
3308 // Attempt to route more than available results in a failure.
3309 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[3],
3310 Some(InvoiceFeatures::known()), None, &Vec::new(), 210_000, 42, Arc::clone(&logger)) {
3311 assert_eq!(err, "Failed to find a sufficient route to the given destination");
3312 } else { panic!(); }
3316 // Now, attempt to route 200 sats (exact amount we can route).
3317 let route = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[3],
3318 Some(InvoiceFeatures::known()), None, &Vec::new(), 200_000, 42, Arc::clone(&logger)).unwrap();
3319 assert_eq!(route.paths.len(), 2);
3321 let mut total_amount_paid_msat = 0;
3322 for path in &route.paths {
3323 assert_eq!(path.last().unwrap().pubkey, nodes[3]);
3324 total_amount_paid_msat += path.last().unwrap().fee_msat;
3326 assert_eq!(total_amount_paid_msat, 200_000);
3332 fn drop_lowest_channel_mpp_route_test() {
3333 // This test checks that low-capacity channel is dropped when after
3334 // path finding we realize that we found more capacity than we need.
3335 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
3336 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3338 // We need a route consisting of 3 paths:
3339 // From our node to node2 via node0, node7, node1 (three paths one hop each).
3341 // The first and the second paths should be sufficient, but the third should be
3342 // cheaper, so that we select it but drop later.
3344 // First, we set limits on these (previously unlimited) channels.
3345 // Their aggregate capacity will be 50 + 60 + 20 = 130 sats.
3347 // Path via node0 is channels {1, 3}. Limit them to 100 and 50 sats (total limit 50);
3348 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3349 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3350 short_channel_id: 1,
3353 cltv_expiry_delta: 0,
3354 htlc_minimum_msat: 0,
3355 htlc_maximum_msat: OptionalField::Present(100_000),
3357 fee_proportional_millionths: 0,
3358 excess_data: Vec::new()
3360 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3361 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3362 short_channel_id: 3,
3365 cltv_expiry_delta: 0,
3366 htlc_minimum_msat: 0,
3367 htlc_maximum_msat: OptionalField::Present(50_000),
3369 fee_proportional_millionths: 0,
3370 excess_data: Vec::new()
3373 // Path via node7 is channels {12, 13}. Limit them to 60 and 60 sats (total limit 60);
3374 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3375 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3376 short_channel_id: 12,
3379 cltv_expiry_delta: 0,
3380 htlc_minimum_msat: 0,
3381 htlc_maximum_msat: OptionalField::Present(60_000),
3383 fee_proportional_millionths: 0,
3384 excess_data: Vec::new()
3386 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
3387 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3388 short_channel_id: 13,
3391 cltv_expiry_delta: 0,
3392 htlc_minimum_msat: 0,
3393 htlc_maximum_msat: OptionalField::Present(60_000),
3395 fee_proportional_millionths: 0,
3396 excess_data: Vec::new()
3399 // Path via node1 is channels {2, 4}. Limit them to 20 and 20 sats (total capacity 20 sats).
3400 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3401 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3402 short_channel_id: 2,
3405 cltv_expiry_delta: 0,
3406 htlc_minimum_msat: 0,
3407 htlc_maximum_msat: OptionalField::Present(20_000),
3409 fee_proportional_millionths: 0,
3410 excess_data: Vec::new()
3412 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
3413 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3414 short_channel_id: 4,
3417 cltv_expiry_delta: 0,
3418 htlc_minimum_msat: 0,
3419 htlc_maximum_msat: OptionalField::Present(20_000),
3421 fee_proportional_millionths: 0,
3422 excess_data: Vec::new()
3426 // Attempt to route more than available results in a failure.
3427 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2],
3428 Some(InvoiceFeatures::known()), None, &Vec::new(), 150_000, 42, Arc::clone(&logger)) {
3429 assert_eq!(err, "Failed to find a sufficient route to the given destination");
3430 } else { panic!(); }
3434 // Now, attempt to route 125 sats (just a bit below the capacity of 3 channels).
3435 // Our algorithm should provide us with these 3 paths.
3436 let route = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2],
3437 Some(InvoiceFeatures::known()), None, &Vec::new(), 125_000, 42, Arc::clone(&logger)).unwrap();
3438 assert_eq!(route.paths.len(), 3);
3439 let mut total_amount_paid_msat = 0;
3440 for path in &route.paths {
3441 assert_eq!(path.len(), 2);
3442 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
3443 total_amount_paid_msat += path.last().unwrap().fee_msat;
3445 assert_eq!(total_amount_paid_msat, 125_000);
3449 // Attempt to route without the last small cheap channel
3450 let route = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2],
3451 Some(InvoiceFeatures::known()), None, &Vec::new(), 90_000, 42, Arc::clone(&logger)).unwrap();
3452 assert_eq!(route.paths.len(), 2);
3453 let mut total_amount_paid_msat = 0;
3454 for path in &route.paths {
3455 assert_eq!(path.len(), 2);
3456 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
3457 total_amount_paid_msat += path.last().unwrap().fee_msat;
3459 assert_eq!(total_amount_paid_msat, 90_000);
3464 fn min_criteria_consistency() {
3465 // Test that we don't use an inconsistent metric between updating and walking nodes during
3466 // our Dijkstra's pass. In the initial version of MPP, the "best source" for a given node
3467 // was updated with a different critera from the heap sorting, resulting in loops in
3468 // calculated paths. We test for that specific case here.
3470 // We construct a network that looks like this:
3472 // node2 -1(3)2- node3
3476 // node1 -1(5)2- node4 -1(1)2- node6
3482 // We create a loop on the side of our real path - our destination is node 6, with a
3483 // previous hop of node 4. From 4, the cheapest previous path is channel 2 from node 2,
3484 // followed by node 3 over channel 3. Thereafter, the cheapest next-hop is back to node 4
3485 // (this time over channel 4). Channel 4 has 0 htlc_minimum_msat whereas channel 1 (the
3486 // other channel with a previous-hop of node 4) has a high (but irrelevant to the overall
3487 // payment) htlc_minimum_msat. In the original algorithm, this resulted in node4's
3488 // "previous hop" being set to node 3, creating a loop in the path.
3489 let secp_ctx = Secp256k1::new();
3490 let logger = Arc::new(test_utils::TestLogger::new());
3491 let net_graph_msg_handler = NetGraphMsgHandler::new(genesis_block(Network::Testnet).header.block_hash(), None, Arc::clone(&logger));
3492 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3494 add_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, &privkeys[1], ChannelFeatures::from_le_bytes(id_to_feature_flags(6)), 6);
3495 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3496 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3497 short_channel_id: 6,
3500 cltv_expiry_delta: (6 << 8) | 0,
3501 htlc_minimum_msat: 0,
3502 htlc_maximum_msat: OptionalField::Absent,
3504 fee_proportional_millionths: 0,
3505 excess_data: Vec::new()
3507 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[1], NodeFeatures::from_le_bytes(id_to_feature_flags(1)), 0);
3509 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], &privkeys[4], ChannelFeatures::from_le_bytes(id_to_feature_flags(5)), 5);
3510 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
3511 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3512 short_channel_id: 5,
3515 cltv_expiry_delta: (5 << 8) | 0,
3516 htlc_minimum_msat: 0,
3517 htlc_maximum_msat: OptionalField::Absent,
3519 fee_proportional_millionths: 0,
3520 excess_data: Vec::new()
3522 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[4], NodeFeatures::from_le_bytes(id_to_feature_flags(4)), 0);
3524 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(4)), 4);
3525 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
3526 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3527 short_channel_id: 4,
3530 cltv_expiry_delta: (4 << 8) | 0,
3531 htlc_minimum_msat: 0,
3532 htlc_maximum_msat: OptionalField::Absent,
3534 fee_proportional_millionths: 0,
3535 excess_data: Vec::new()
3537 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[3], NodeFeatures::from_le_bytes(id_to_feature_flags(3)), 0);
3539 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[3], &privkeys[2], ChannelFeatures::from_le_bytes(id_to_feature_flags(3)), 3);
3540 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[3], UnsignedChannelUpdate {
3541 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3542 short_channel_id: 3,
3545 cltv_expiry_delta: (3 << 8) | 0,
3546 htlc_minimum_msat: 0,
3547 htlc_maximum_msat: OptionalField::Absent,
3549 fee_proportional_millionths: 0,
3550 excess_data: Vec::new()
3552 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[2], NodeFeatures::from_le_bytes(id_to_feature_flags(2)), 0);
3554 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], &privkeys[4], ChannelFeatures::from_le_bytes(id_to_feature_flags(2)), 2);
3555 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3556 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3557 short_channel_id: 2,
3560 cltv_expiry_delta: (2 << 8) | 0,
3561 htlc_minimum_msat: 0,
3562 htlc_maximum_msat: OptionalField::Absent,
3564 fee_proportional_millionths: 0,
3565 excess_data: Vec::new()
3568 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], &privkeys[6], ChannelFeatures::from_le_bytes(id_to_feature_flags(1)), 1);
3569 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
3570 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3571 short_channel_id: 1,
3574 cltv_expiry_delta: (1 << 8) | 0,
3575 htlc_minimum_msat: 100,
3576 htlc_maximum_msat: OptionalField::Absent,
3578 fee_proportional_millionths: 0,
3579 excess_data: Vec::new()
3581 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[6], NodeFeatures::from_le_bytes(id_to_feature_flags(6)), 0);
3584 // Now ensure the route flows simply over nodes 1 and 4 to 6.
3585 let route = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[6], None, None, &Vec::new(), 10_000, 42, Arc::clone(&logger)).unwrap();
3586 assert_eq!(route.paths.len(), 1);
3587 assert_eq!(route.paths[0].len(), 3);
3589 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
3590 assert_eq!(route.paths[0][0].short_channel_id, 6);
3591 assert_eq!(route.paths[0][0].fee_msat, 100);
3592 assert_eq!(route.paths[0][0].cltv_expiry_delta, (5 << 8) | 0);
3593 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(1));
3594 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(6));
3596 assert_eq!(route.paths[0][1].pubkey, nodes[4]);
3597 assert_eq!(route.paths[0][1].short_channel_id, 5);
3598 assert_eq!(route.paths[0][1].fee_msat, 0);
3599 assert_eq!(route.paths[0][1].cltv_expiry_delta, (1 << 8) | 0);
3600 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(4));
3601 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(5));
3603 assert_eq!(route.paths[0][2].pubkey, nodes[6]);
3604 assert_eq!(route.paths[0][2].short_channel_id, 1);
3605 assert_eq!(route.paths[0][2].fee_msat, 10_000);
3606 assert_eq!(route.paths[0][2].cltv_expiry_delta, 42);
3607 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(6));
3608 assert_eq!(route.paths[0][2].channel_features.le_flags(), &id_to_feature_flags(1));
3614 fn exact_fee_liquidity_limit() {
3615 // Test that if, while walking the graph, we find a hop that has exactly enough liquidity
3616 // for us, including later hop fees, we take it. In the first version of our MPP algorithm
3617 // we calculated fees on a higher value, resulting in us ignoring such paths.
3618 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
3619 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3621 // We modify the graph to set the htlc_maximum of channel 2 to below the value we wish to
3623 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3624 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3625 short_channel_id: 2,
3628 cltv_expiry_delta: 0,
3629 htlc_minimum_msat: 0,
3630 htlc_maximum_msat: OptionalField::Present(85_000),
3632 fee_proportional_millionths: 0,
3633 excess_data: Vec::new()
3636 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3637 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3638 short_channel_id: 12,
3641 cltv_expiry_delta: (4 << 8) | 1,
3642 htlc_minimum_msat: 0,
3643 htlc_maximum_msat: OptionalField::Present(270_000),
3645 fee_proportional_millionths: 1000000,
3646 excess_data: Vec::new()
3649 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3650 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3651 short_channel_id: 13,
3654 cltv_expiry_delta: (13 << 8) | 2,
3655 htlc_minimum_msat: 0,
3656 htlc_maximum_msat: OptionalField::Absent,
3658 fee_proportional_millionths: 0,
3659 excess_data: Vec::new()
3663 // Now, attempt to route 125 sats (just a bit below the capacity of 3 channels).
3664 // Our algorithm should provide us with these 3 paths.
3665 let route = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2], None, None, &Vec::new(), 90_000, 42, Arc::clone(&logger)).unwrap();
3666 assert_eq!(route.paths.len(), 1);
3667 assert_eq!(route.paths[0].len(), 2);
3669 assert_eq!(route.paths[0][0].pubkey, nodes[7]);
3670 assert_eq!(route.paths[0][0].short_channel_id, 12);
3671 assert_eq!(route.paths[0][0].fee_msat, 90_000*2);
3672 assert_eq!(route.paths[0][0].cltv_expiry_delta, (13 << 8) | 1);
3673 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(8));
3674 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(12));
3676 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
3677 assert_eq!(route.paths[0][1].short_channel_id, 13);
3678 assert_eq!(route.paths[0][1].fee_msat, 90_000);
3679 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
3680 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
3681 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(13));
3686 fn htlc_max_reduction_below_min() {
3687 // Test that if, while walking the graph, we reduce the value being sent to meet an
3688 // htlc_maximum_msat, we don't end up undershooting a later htlc_minimum_msat. In the
3689 // initial version of MPP we'd accept such routes but reject them while recalculating fees,
3690 // resulting in us thinking there is no possible path, even if other paths exist.
3691 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
3692 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3694 // We modify the graph to set the htlc_minimum of channel 2 and 4 as needed - channel 2
3695 // gets an htlc_minimum_msat of 80_000 and channel 4 an htlc_maximum_msat of 90_000. We
3696 // then try to send 90_000.
3697 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3698 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3699 short_channel_id: 2,
3702 cltv_expiry_delta: 0,
3703 htlc_minimum_msat: 0,
3704 htlc_maximum_msat: OptionalField::Present(80_000),
3706 fee_proportional_millionths: 0,
3707 excess_data: Vec::new()
3709 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
3710 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3711 short_channel_id: 4,
3714 cltv_expiry_delta: (4 << 8) | 1,
3715 htlc_minimum_msat: 90_000,
3716 htlc_maximum_msat: OptionalField::Absent,
3718 fee_proportional_millionths: 0,
3719 excess_data: Vec::new()
3723 // Now, attempt to route 125 sats (just a bit below the capacity of 3 channels).
3724 // Our algorithm should provide us with these 3 paths.
3725 let route = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2], Some(InvoiceFeatures::known()), None, &Vec::new(), 90_000, 42, Arc::clone(&logger)).unwrap();
3726 assert_eq!(route.paths.len(), 1);
3727 assert_eq!(route.paths[0].len(), 2);
3729 assert_eq!(route.paths[0][0].pubkey, nodes[7]);
3730 assert_eq!(route.paths[0][0].short_channel_id, 12);
3731 assert_eq!(route.paths[0][0].fee_msat, 90_000*2);
3732 assert_eq!(route.paths[0][0].cltv_expiry_delta, (13 << 8) | 1);
3733 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(8));
3734 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(12));
3736 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
3737 assert_eq!(route.paths[0][1].short_channel_id, 13);
3738 assert_eq!(route.paths[0][1].fee_msat, 90_000);
3739 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
3740 assert_eq!(route.paths[0][1].node_features.le_flags(), InvoiceFeatures::known().le_flags());
3741 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(13));
3745 /// Tries to open a network graph file, or panics with a URL to fetch it.
3746 pub(super) fn get_route_file() -> std::fs::File {
3747 File::open("net_graph-2021-02-12.bin") // By default we're run in RL/lightning
3748 .or_else(|_| File::open("lightning/net_graph-2021-02-12.bin")) // We may be run manually in RL/
3749 .or_else(|_| { // Fall back to guessing based on the binary location
3750 // path is likely something like .../rust-lightning/target/debug/deps/lightning-...
3751 let mut path = std::env::current_exe().unwrap();
3752 path.pop(); // lightning-...
3754 path.pop(); // debug
3755 path.pop(); // target
3756 path.push("lightning");
3757 path.push("net_graph-2021-02-12.bin");
3758 eprintln!("{}", path.to_str().unwrap());
3761 .expect("Please fetch https://bitcoin.ninja/ldk-net_graph-879e309c128-2020-02-12.bin and place it at lightning/net_graph-2021-02-12.bin")
3764 pub(super) fn random_init_seed() -> u64 {
3765 // Because the default HashMap in std pulls OS randomness, we can use it as a (bad) RNG.
3766 use std::hash::{BuildHasher, Hasher};
3767 let seed = std::collections::hash_map::RandomState::new().build_hasher().finish();
3768 println!("Using seed of {}", seed);
3773 use util::ser::Readable;
3775 fn generate_routes() {
3776 let mut d = get_route_file();
3777 let graph = NetworkGraph::read(&mut d).unwrap();
3779 // First, get 100 (source, destination) pairs for which route-getting actually succeeds...
3780 let mut seed = random_init_seed() as usize;
3781 'load_endpoints: for _ in 0..10 {
3783 seed = seed.overflowing_mul(0xdeadbeef).0;
3784 let src = graph.get_nodes().keys().skip(seed % graph.get_nodes().len()).next().unwrap();
3785 seed = seed.overflowing_mul(0xdeadbeef).0;
3786 let dst = graph.get_nodes().keys().skip(seed % graph.get_nodes().len()).next().unwrap();
3787 let amt = seed as u64 % 200_000_000;
3788 if get_route(src, &graph, dst, None, None, &[], amt, 42, &test_utils::TestLogger::new()).is_ok() {
3789 continue 'load_endpoints;
3796 fn generate_routes_mpp() {
3797 let mut d = get_route_file();
3798 let graph = NetworkGraph::read(&mut d).unwrap();
3800 // First, get 100 (source, destination) pairs for which route-getting actually succeeds...
3801 let mut seed = random_init_seed() as usize;
3802 'load_endpoints: for _ in 0..10 {
3804 seed = seed.overflowing_mul(0xdeadbeef).0;
3805 let src = graph.get_nodes().keys().skip(seed % graph.get_nodes().len()).next().unwrap();
3806 seed = seed.overflowing_mul(0xdeadbeef).0;
3807 let dst = graph.get_nodes().keys().skip(seed % graph.get_nodes().len()).next().unwrap();
3808 let amt = seed as u64 % 200_000_000;
3809 if get_route(src, &graph, dst, Some(InvoiceFeatures::known()), None, &[], amt, 42, &test_utils::TestLogger::new()).is_ok() {
3810 continue 'load_endpoints;
3817 #[cfg(all(test, feature = "unstable"))]
3820 use util::logger::{Logger, Record};
3825 struct DummyLogger {}
3826 impl Logger for DummyLogger {
3827 fn log(&self, _record: &Record) {}
3831 fn generate_routes(bench: &mut Bencher) {
3832 let mut d = tests::get_route_file();
3833 let graph = NetworkGraph::read(&mut d).unwrap();
3835 // First, get 100 (source, destination) pairs for which route-getting actually succeeds...
3836 let mut path_endpoints = Vec::new();
3837 let mut seed: usize = 0xdeadbeef;
3838 'load_endpoints: for _ in 0..100 {
3841 let src = graph.get_nodes().keys().skip(seed % graph.get_nodes().len()).next().unwrap();
3843 let dst = graph.get_nodes().keys().skip(seed % graph.get_nodes().len()).next().unwrap();
3844 let amt = seed as u64 % 1_000_000;
3845 if get_route(src, &graph, dst, None, None, &[], amt, 42, &DummyLogger{}).is_ok() {
3846 path_endpoints.push((src, dst, amt));
3847 continue 'load_endpoints;
3852 // ...then benchmark finding paths between the nodes we learned.
3855 let (src, dst, amt) = path_endpoints[idx % path_endpoints.len()];
3856 assert!(get_route(src, &graph, dst, None, None, &[], amt, 42, &DummyLogger{}).is_ok());
3862 fn generate_mpp_routes(bench: &mut Bencher) {
3863 let mut d = tests::get_route_file();
3864 let graph = NetworkGraph::read(&mut d).unwrap();
3866 // First, get 100 (source, destination) pairs for which route-getting actually succeeds...
3867 let mut path_endpoints = Vec::new();
3868 let mut seed: usize = 0xdeadbeef;
3869 'load_endpoints: for _ in 0..100 {
3872 let src = graph.get_nodes().keys().skip(seed % graph.get_nodes().len()).next().unwrap();
3874 let dst = graph.get_nodes().keys().skip(seed % graph.get_nodes().len()).next().unwrap();
3875 let amt = seed as u64 % 1_000_000;
3876 if get_route(src, &graph, dst, Some(InvoiceFeatures::known()), None, &[], amt, 42, &DummyLogger{}).is_ok() {
3877 path_endpoints.push((src, dst, amt));
3878 continue 'load_endpoints;
3883 // ...then benchmark finding paths between the nodes we learned.
3886 let (src, dst, amt) = path_endpoints[idx % path_endpoints.len()];
3887 assert!(get_route(src, &graph, dst, Some(InvoiceFeatures::known()), None, &[], amt, 42, &DummyLogger{}).is_ok());