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
149 impl cmp::Ord for RouteGraphNode {
150 fn cmp(&self, other: &RouteGraphNode) -> cmp::Ordering {
151 other.lowest_fee_to_peer_through_node.cmp(&self.lowest_fee_to_peer_through_node)
152 .then_with(|| other.pubkey.serialize().cmp(&self.pubkey.serialize()))
156 impl cmp::PartialOrd for RouteGraphNode {
157 fn partial_cmp(&self, other: &RouteGraphNode) -> Option<cmp::Ordering> {
158 Some(self.cmp(other))
162 struct DummyDirectionalChannelInfo {
163 cltv_expiry_delta: u32,
164 htlc_minimum_msat: u64,
165 htlc_maximum_msat: Option<u64>,
169 /// It's useful to keep track of the hops associated with the fees required to use them,
170 /// so that we can choose cheaper paths (as per Dijkstra's algorithm).
171 /// Fee values should be updated only in the context of the whole path, see update_value_and_recompute_fees.
172 /// These fee values are useful to choose hops as we traverse the graph "payee-to-payer".
174 struct PathBuildingHop {
175 /// Hop-specific details unrelated to the path during the routing phase,
176 /// but rather relevant to the LN graph.
178 /// Minimal fees required to route to the source node of the current hop via any of its inbound channels.
179 src_lowest_inbound_fees: RoutingFees,
180 /// Fees of the channel used in this hop.
181 channel_fees: RoutingFees,
182 /// All the fees paid *after* this channel on the way to the destination
183 next_hops_fee_msat: u64,
184 /// Fee paid for the use of the current channel (see channel_fees).
185 /// The value will be actually deducted from the counterparty balance on the previous link.
186 hop_use_fee_msat: u64,
187 /// Used to compare channels when choosing the for routing.
188 /// Includes paying for the use of a hop and the following hops, as well as
189 /// an estimated cost of reaching this hop.
190 /// Might get stale when fees are recomputed. Primarily for internal use.
192 /// This is useful for update_value_and_recompute_fees to make sure
193 /// we don't fall below the minimum. Should not be updated manually and
194 /// generally should not be accessed.
195 htlc_minimum_msat: u64,
198 // Instantiated with a list of hops with correct data in them collected during path finding,
199 // an instance of this struct should be further modified only via given methods.
202 hops: Vec<PathBuildingHop>,
207 // TODO: Add a value_msat field to PaymentPath and use it instead of this function.
208 fn get_value_msat(&self) -> u64 {
209 self.hops.last().unwrap().route_hop.fee_msat
212 fn get_total_fee_paid_msat(&self) -> u64 {
213 if self.hops.len() < 1 {
217 // Can't use next_hops_fee_msat because it gets outdated.
218 for (i, hop) in self.hops.iter().enumerate() {
219 if i != self.hops.len() - 1 {
220 result += hop.route_hop.fee_msat;
226 // If the amount transferred by the path is updated, the fees should be adjusted. Any other way
227 // to change fees may result in an inconsistency.
229 // Sometimes we call this function right after constructing a path which has inconsistent
230 // (in terms of reaching htlc_minimum_msat), so that this function puts the fees in order.
231 // In that case we call it on the "same" amount we initially allocated for this path, and which
232 // could have been reduced on the way. In that case, there is also a risk of exceeding
233 // available_liquidity inside this function, because the function is unaware of this bound.
234 // In our specific recomputation cases where we never increase the value the risk is pretty low.
235 // This function, however, does not support arbitrarily increasing the value being transferred,
236 // and the exception will be triggered.
237 fn update_value_and_recompute_fees(&mut self, value_msat: u64) {
238 assert!(value_msat <= self.hops.last().unwrap().route_hop.fee_msat);
240 let mut total_fee_paid_msat = 0 as u64;
241 for i in (0..self.hops.len()).rev() {
242 let last_hop = i == self.hops.len() - 1;
244 // For non-last-hop, this value will represent the fees paid on the current hop. It
245 // will consist of the fees for the use of the next hop, and extra fees to match
246 // htlc_minimum_msat of the current channel. Last hop is handled separately.
247 let mut cur_hop_fees_msat = 0;
249 cur_hop_fees_msat = self.hops.get(i + 1).unwrap().hop_use_fee_msat;
252 let mut cur_hop = self.hops.get_mut(i).unwrap();
253 cur_hop.next_hops_fee_msat = total_fee_paid_msat;
254 // Overpay in fees if we can't save these funds due to htlc_minimum_msat.
255 // We try to account for htlc_minimum_msat in scoring (add_entry!), so that nodes don't
256 // set it too high just to maliciously take more fees by exploiting this
257 // match htlc_minimum_msat logic.
258 let mut cur_hop_transferred_amount_msat = total_fee_paid_msat + value_msat;
259 if let Some(extra_fees_msat) = cur_hop.htlc_minimum_msat.checked_sub(cur_hop_transferred_amount_msat) {
260 // Note that there is a risk that *previous hops* (those closer to us, as we go
261 // payee->our_node here) would exceed their htlc_maximum_msat or available balance.
263 // This might make us end up with a broken route, although this should be super-rare
264 // in practice, both because of how healthy channels look like, and how we pick
265 // channels in add_entry.
266 // Also, this can't be exploited more heavily than *announce a free path and fail
268 cur_hop_transferred_amount_msat += extra_fees_msat;
269 total_fee_paid_msat += extra_fees_msat;
270 cur_hop_fees_msat += extra_fees_msat;
274 // Final hop is a special case: it usually has just value_msat (by design), but also
275 // it still could overpay for the htlc_minimum_msat.
276 cur_hop.route_hop.fee_msat = cur_hop_transferred_amount_msat;
278 // Propagate updated fees for the use of the channels to one hop back, where they
279 // will be actually paid (fee_msat). The last hop is handled above separately.
280 cur_hop.route_hop.fee_msat = cur_hop_fees_msat;
283 // Fee for the use of the current hop which will be deducted on the previous hop.
284 // Irrelevant for the first hop, as it doesn't have the previous hop, and the use of
285 // this channel is free for us.
287 if let Some(new_fee) = compute_fees(cur_hop_transferred_amount_msat, cur_hop.channel_fees) {
288 cur_hop.hop_use_fee_msat = new_fee;
289 total_fee_paid_msat += new_fee;
291 // It should not be possible because this function is called only to reduce the
292 // value. In that case, compute_fee was already called with the same fees for
293 // larger amount and there was no overflow.
301 fn compute_fees(amount_msat: u64, channel_fees: RoutingFees) -> Option<u64> {
302 let proportional_fee_millions =
303 amount_msat.checked_mul(channel_fees.proportional_millionths as u64);
304 if let Some(new_fee) = proportional_fee_millions.and_then(|part| {
305 (channel_fees.base_msat as u64).checked_add(part / 1_000_000) }) {
309 // This function may be (indirectly) called without any verification,
310 // with channel_fees provided by a caller. We should handle it gracefully.
315 /// Gets a route from us (payer) to the given target node (payee).
317 /// If the payee provided features in their invoice, they should be provided via payee_features.
318 /// Without this, MPP will only be used if the payee's features are available in the network graph.
320 /// Extra routing hops between known nodes and the target will be used if they are included in
323 /// If some channels aren't announced, it may be useful to fill in a first_hops with the
324 /// results from a local ChannelManager::list_usable_channels() call. If it is filled in, our
325 /// view of our local channels (from net_graph_msg_handler) will be ignored, and only those
326 /// in first_hops will be used.
328 /// Panics if first_hops contains channels without short_channel_ids
329 /// (ChannelManager::list_usable_channels will never include such channels).
331 /// The fees on channels from us to next-hops are ignored (as they are assumed to all be
332 /// equal), however the enabled/disabled bit on such channels as well as the
333 /// htlc_minimum_msat/htlc_maximum_msat *are* checked as they may change based on the receiving node.
334 pub fn get_route<L: Deref>(our_node_id: &PublicKey, network: &NetworkGraph, payee: &PublicKey, payee_features: Option<InvoiceFeatures>, first_hops: Option<&[&ChannelDetails]>,
335 last_hops: &[&RouteHint], final_value_msat: u64, final_cltv: u32, logger: L) -> Result<Route, LightningError> where L::Target: Logger {
336 // TODO: Obviously *only* using total fee cost sucks. We should consider weighting by
337 // uptime/success in using a node in the past.
338 if *payee == *our_node_id {
339 return Err(LightningError{err: "Cannot generate a route to ourselves".to_owned(), action: ErrorAction::IgnoreError});
342 if final_value_msat > MAX_VALUE_MSAT {
343 return Err(LightningError{err: "Cannot generate a route of more value than all existing satoshis".to_owned(), action: ErrorAction::IgnoreError});
346 if final_value_msat == 0 {
347 return Err(LightningError{err: "Cannot send a payment of 0 msat".to_owned(), action: ErrorAction::IgnoreError});
350 for last_hop in last_hops {
351 if last_hop.src_node_id == *payee {
352 return Err(LightningError{err: "Last hop cannot have a payee as a source.".to_owned(), action: ErrorAction::IgnoreError});
356 // The general routing idea is the following:
357 // 1. Fill first/last hops communicated by the caller.
358 // 2. Attempt to construct a path from payer to payee for transferring
359 // any ~sufficient (described later) value.
360 // If succeed, remember which channels were used and how much liquidity they have available,
361 // so that future paths don't rely on the same liquidity.
362 // 3. Prooceed to the next step if:
363 // - we hit the recommended target value;
364 // - OR if we could not construct a new path. Any next attempt will fail too.
365 // Otherwise, repeat step 2.
366 // 4. See if we managed to collect paths which aggregately are able to transfer target value
367 // (not recommended value). If yes, proceed. If not, fail routing.
368 // 5. Randomly combine paths into routes having enough to fulfill the payment. (TODO: knapsack)
369 // 6. Of all the found paths, select only those with the lowest total fee.
370 // 7. The last path in every selected route is likely to be more than we need.
371 // Reduce its value-to-transfer and recompute fees.
372 // 8. Choose the best route by the lowest total fee.
374 // As for the actual search algorithm,
375 // we do a payee-to-payer pseudo-Dijkstra's sorting by each node's distance from the payee
376 // plus the minimum per-HTLC fee to get from it to another node (aka "shitty pseudo-A*").
378 // We are not a faithful Dijkstra's implementation because we can change values which impact
379 // earlier nodes while processing later nodes. Specifically, if we reach a channel with a lower
380 // liquidity limit (via htlc_maximum_msat, on-chain capacity or assumed liquidity limits) then
381 // the value we are currently attempting to send over a path, we simply reduce the value being
382 // sent along the path for any hops after that channel. This may imply that later fees (which
383 // we've already tabulated) are lower because a smaller value is passing through the channels
384 // (and the proportional fee is thus lower). There isn't a trivial way to recalculate the
385 // channels which were selected earlier (and which may still be used for other paths without a
386 // lower liquidity limit), so we simply accept that some liquidity-limited paths may be
389 // One potentially problematic case for this algorithm would be if there are many
390 // liquidity-limited paths which are liquidity-limited near the destination (ie early in our
391 // graph walking), we may never find a path which is not liquidity-limited and has lower
392 // proportional fee (and only lower absolute fee when considering the ultimate value sent).
393 // Because we only consider paths with at least 5% of the total value being sent, the damage
394 // from such a case should be limited, however this could be further reduced in the future by
395 // calculating fees on the amount we wish to route over a path, ie ignoring the liquidity
396 // limits for the purposes of fee calculation.
398 // Alternatively, we could store more detailed path information in the heap (targets, below)
399 // and index the best-path map (dist, below) by node *and* HTLC limits, however that would blow
400 // up the runtime significantly both algorithmically (as we'd traverse nodes multiple times)
401 // and practically (as we would need to store dynamically-allocated path information in heap
402 // objects, increasing malloc traffic and indirect memory access significantly). Further, the
403 // results of such an algorithm would likely be biased towards lower-value paths.
405 // Further, we could return to a faithful Dijkstra's algorithm by rejecting paths with limits
406 // outside of our current search value, running a path search more times to gather candidate
407 // paths at different values. While this may be acceptable, further path searches may increase
408 // runtime for little gain. Specifically, the current algorithm rather efficiently explores the
409 // graph for candidate paths, calculating the maximum value which can realistically be sent at
410 // the same time, remaining generic across different payment values.
412 // TODO: There are a few tweaks we could do, including possibly pre-calculating more stuff
413 // to use as the A* heuristic beyond just the cost to get one node further than the current
416 let dummy_directional_info = DummyDirectionalChannelInfo { // used for first_hops routes
417 cltv_expiry_delta: 0,
418 htlc_minimum_msat: 0,
419 htlc_maximum_msat: None,
422 proportional_millionths: 0,
426 let mut targets = BinaryHeap::new(); //TODO: Do we care about switching to eg Fibbonaci heap?
427 let mut dist = HashMap::with_capacity(network.get_nodes().len());
429 // When arranging a route, we select multiple paths so that we can make a multi-path payment.
430 // Don't stop searching for paths when we think they're
431 // sufficient to transfer a given value aggregately.
432 // Search for higher value, so that we collect many more paths,
433 // and then select the best combination among them.
434 const ROUTE_CAPACITY_PROVISION_FACTOR: u64 = 3;
435 let recommended_value_msat = final_value_msat * ROUTE_CAPACITY_PROVISION_FACTOR as u64;
437 // Allow MPP only if we have a features set from somewhere that indicates the payee supports
438 // it. If the payee supports it they're supposed to include it in the invoice, so that should
440 let allow_mpp = if let Some(features) = &payee_features {
441 features.supports_basic_mpp()
442 } else if let Some(node) = network.get_nodes().get(&payee) {
443 if let Some(node_info) = node.announcement_info.as_ref() {
444 node_info.features.supports_basic_mpp()
449 // Prepare the data we'll use for payee-to-payer search by
450 // inserting first hops suggested by the caller as targets.
451 // Our search will then attempt to reach them while traversing from the payee node.
452 let mut first_hop_targets = HashMap::with_capacity(if first_hops.is_some() { first_hops.as_ref().unwrap().len() } else { 0 });
453 if let Some(hops) = first_hops {
455 let short_channel_id = chan.short_channel_id.expect("first_hops should be filled in with usable channels, not pending ones");
456 if chan.remote_network_id == *our_node_id {
457 return Err(LightningError{err: "First hop cannot have our_node_id as a destination.".to_owned(), action: ErrorAction::IgnoreError});
459 first_hop_targets.insert(chan.remote_network_id, (short_channel_id, chan.counterparty_features.clone(), chan.outbound_capacity_msat));
461 if first_hop_targets.is_empty() {
462 return Err(LightningError{err: "Cannot route when there are no outbound routes away from us".to_owned(), action: ErrorAction::IgnoreError});
466 // We don't want multiple paths (as per MPP) share liquidity of the same channels.
467 // This map allows paths to be aware of the channel use by other paths in the same call.
468 // This would help to make a better path finding decisions and not "overbook" channels.
469 // It is unaware of the directions (except for `outbound_capacity_msat` in `first_hops`).
470 let mut bookkeeped_channels_liquidity_available_msat = HashMap::new();
472 // Keeping track of how much value we already collected across other paths. Helps to decide:
473 // - how much a new path should be transferring (upper bound);
474 // - whether a channel should be disregarded because
475 // it's available liquidity is too small comparing to how much more we need to collect;
476 // - when we want to stop looking for new paths.
477 let mut already_collected_value_msat = 0;
479 macro_rules! add_entry {
480 // Adds entry which goes from $src_node_id to $dest_node_id
481 // over the channel with id $chan_id with fees described in
482 // $directional_info.
483 // $next_hops_fee_msat represents the fees paid for using all the channel *after* this one,
484 // since that value has to be transferred over this channel.
485 ( $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,
486 $next_hops_value_contribution: expr ) => {
487 // Channels to self should not be used. This is more of belt-and-suspenders, because in
488 // practice these cases should be caught earlier:
489 // - for regular channels at channel announcement (TODO)
490 // - for first and last hops early in get_route
491 if $src_node_id != $dest_node_id.clone() {
492 let available_liquidity_msat = bookkeeped_channels_liquidity_available_msat.entry($chan_id.clone()).or_insert_with(|| {
493 let mut initial_liquidity_available_msat = None;
494 if let Some(capacity_sats) = $capacity_sats {
495 initial_liquidity_available_msat = Some(capacity_sats * 1000);
498 if let Some(htlc_maximum_msat) = $directional_info.htlc_maximum_msat {
499 if let Some(available_msat) = initial_liquidity_available_msat {
500 initial_liquidity_available_msat = Some(cmp::min(available_msat, htlc_maximum_msat));
502 initial_liquidity_available_msat = Some(htlc_maximum_msat);
506 match initial_liquidity_available_msat {
507 Some(available_msat) => available_msat,
508 // We assume channels with unknown balance have
509 // a capacity of 0.0025 BTC (or 250_000 sats).
510 None => 250_000 * 1000
514 // It is tricky to substract $next_hops_fee_msat from available liquidity here.
515 // It may be misleading because we might later choose to reduce the value transferred
516 // over these channels, and the channel which was insufficient might become sufficient.
517 // Worst case: we drop a good channel here because it can't cover the high following
518 // fees caused by one expensive channel, but then this channel could have been used
519 // if the amount being transferred over this path is lower.
520 // We do this for now, but this is a subject for removal.
521 if let Some(available_value_contribution_msat) = available_liquidity_msat.checked_sub($next_hops_fee_msat) {
523 // Routing Fragmentation Mitigation heuristic:
525 // Routing fragmentation across many payment paths increases the overall routing
526 // fees as you have irreducible routing fees per-link used (`fee_base_msat`).
527 // Taking too many smaller paths also increases the chance of payment failure.
528 // Thus to avoid this effect, we require from our collected links to provide
529 // at least a minimal contribution to the recommended value yet-to-be-fulfilled.
531 // This requirement is currently 5% of the remaining-to-be-collected value.
532 // This means as we successfully advance in our collection,
533 // the absolute liquidity contribution is lowered,
534 // thus increasing the number of potential channels to be selected.
536 // Derive the minimal liquidity contribution with a ratio of 20 (5%, rounded up)
537 // or 100% if we're not allowed to do multipath payments.
538 let minimal_value_contribution_msat: u64 = if allow_mpp {
539 (recommended_value_msat - already_collected_value_msat + 19) / 20
543 // Verify the liquidity offered by this channel complies to the minimal contribution.
544 let contributes_sufficient_value = available_value_contribution_msat >= minimal_value_contribution_msat;
546 let value_contribution_msat = cmp::min(available_value_contribution_msat, $next_hops_value_contribution);
547 // Includes paying fees for the use of the following channels.
548 let amount_to_transfer_over_msat: u64 = match value_contribution_msat.checked_add($next_hops_fee_msat) {
549 Some(result) => result,
550 // Can't overflow due to how the values were computed right above.
551 None => unreachable!(),
554 // If HTLC minimum is larger than the amount we're going to transfer, we shouldn't
555 // bother considering this channel.
556 // Since we're choosing amount_to_transfer_over_msat as maximum possible, it can
557 // be only reduced later (not increased), so this channel should just be skipped
558 // as not sufficient.
559 // TODO: Explore simply adding fee to hit htlc_minimum_msat
560 if contributes_sufficient_value && amount_to_transfer_over_msat >= $directional_info.htlc_minimum_msat {
561 // Note that low contribution here (limited by available_liquidity_msat)
562 // might violate htlc_minimum_msat on the hops which are next along the
563 // payment path (upstream to the payee). To avoid that, we recompute path
564 // path fees knowing the final path contribution after constructing it.
565 let hm_entry = dist.entry(&$src_node_id);
566 let old_entry = hm_entry.or_insert_with(|| {
567 // If there was previously no known way to access
568 // the source node (recall it goes payee-to-payer) of $chan_id, first add
569 // a semi-dummy record just to compute the fees to reach the source node.
570 // This will affect our decision on selecting $chan_id
571 // as a way to reach the $dest_node_id.
572 let mut fee_base_msat = u32::max_value();
573 let mut fee_proportional_millionths = u32::max_value();
574 if let Some(Some(fees)) = network.get_nodes().get(&$src_node_id).map(|node| node.lowest_inbound_channel_fees) {
575 fee_base_msat = fees.base_msat;
576 fee_proportional_millionths = fees.proportional_millionths;
579 route_hop: RouteHop {
580 pubkey: $dest_node_id.clone(),
581 node_features: NodeFeatures::empty(),
583 channel_features: $chan_features.clone(),
585 cltv_expiry_delta: 0,
587 src_lowest_inbound_fees: RoutingFees {
588 base_msat: fee_base_msat,
589 proportional_millionths: fee_proportional_millionths,
591 channel_fees: $directional_info.fees,
592 next_hops_fee_msat: u64::max_value(),
593 hop_use_fee_msat: u64::max_value(),
594 total_fee_msat: u64::max_value(),
595 htlc_minimum_msat: $directional_info.htlc_minimum_msat,
599 let mut hop_use_fee_msat = 0;
600 let mut total_fee_msat = $next_hops_fee_msat;
602 // Ignore hop_use_fee_msat for channel-from-us as we assume all channels-from-us
603 // will have the same effective-fee
604 if $src_node_id != *our_node_id {
605 match compute_fees(amount_to_transfer_over_msat, $directional_info.fees) {
606 // max_value means we'll always fail
607 // the old_entry.total_fee_msat > total_fee_msat check
608 None => total_fee_msat = u64::max_value(),
610 hop_use_fee_msat = fee_msat;
611 total_fee_msat += hop_use_fee_msat;
612 if let Some(prev_hop_fee_msat) = compute_fees(total_fee_msat + amount_to_transfer_over_msat,
613 old_entry.src_lowest_inbound_fees) {
614 if let Some(incremented_total_fee_msat) = total_fee_msat.checked_add(prev_hop_fee_msat) {
615 total_fee_msat = incremented_total_fee_msat;
618 // max_value means we'll always fail
619 // the old_entry.total_fee_msat > total_fee_msat check
620 total_fee_msat = u64::max_value();
623 // max_value means we'll always fail
624 // the old_entry.total_fee_msat > total_fee_msat check
625 total_fee_msat = u64::max_value();
631 let new_graph_node = RouteGraphNode {
632 pubkey: $src_node_id,
633 lowest_fee_to_peer_through_node: total_fee_msat,
634 lowest_fee_to_node: $next_hops_fee_msat as u64 + hop_use_fee_msat,
635 value_contribution_msat: value_contribution_msat,
638 // Update the way of reaching $src_node_id with the given $chan_id (from $dest_node_id),
639 // if this way is cheaper than the already known
640 // (considering the cost to "reach" this channel from the route destination,
641 // the cost of using this channel,
642 // and the cost of routing to the source node of this channel).
643 // Also, consider that htlc_minimum_msat_difference, because we might end up
644 // paying it. Consider the following exploit:
645 // we use 2 paths to transfer 1.5 BTC. One of them is 0-fee normal 1 BTC path,
646 // and for the other one we picked a 1sat-fee path with htlc_minimum_msat of
647 // 1 BTC. Now, since the latter is more expensive, we gonna try to cut it
648 // by 0.5 BTC, but then match htlc_minimum_msat by paying a fee of 0.5 BTC
650 // TODO: this scoring could be smarter (e.g. 0.5*htlc_minimum_msat here).
651 let mut old_cost = old_entry.total_fee_msat;
652 if let Some(increased_old_cost) = old_cost.checked_add(old_entry.htlc_minimum_msat) {
653 old_cost = increased_old_cost;
655 old_cost = u64::max_value();
658 let mut new_cost = total_fee_msat;
659 if let Some(increased_new_cost) = new_cost.checked_add($directional_info.htlc_minimum_msat) {
660 new_cost = increased_new_cost;
662 new_cost = u64::max_value();
665 if new_cost < old_cost {
666 targets.push(new_graph_node);
667 old_entry.next_hops_fee_msat = $next_hops_fee_msat;
668 old_entry.hop_use_fee_msat = hop_use_fee_msat;
669 old_entry.total_fee_msat = total_fee_msat;
670 old_entry.route_hop = RouteHop {
671 pubkey: $dest_node_id.clone(),
672 node_features: NodeFeatures::empty(),
673 short_channel_id: $chan_id.clone(),
674 channel_features: $chan_features.clone(),
675 fee_msat: 0, // This value will be later filled with hop_use_fee_msat of the following channel
676 cltv_expiry_delta: $directional_info.cltv_expiry_delta as u32,
678 old_entry.channel_fees = $directional_info.fees;
679 // It's probably fine to replace the old entry, because the new one
680 // passed the htlc_minimum-related checks above.
681 old_entry.htlc_minimum_msat = $directional_info.htlc_minimum_msat;
689 // Find ways (channels with destination) to reach a given node and store them
690 // in the corresponding data structures (routing graph etc).
691 // $fee_to_target_msat represents how much it costs to reach to this node from the payee,
692 // meaning how much will be paid in fees after this node (to the best of our knowledge).
693 // This data can later be helpful to optimize routing (pay lower fees).
694 macro_rules! add_entries_to_cheapest_to_target_node {
695 ( $node: expr, $node_id: expr, $fee_to_target_msat: expr, $next_hops_value_contribution: expr ) => {
696 if first_hops.is_some() {
697 if let Some(&(ref first_hop, ref features, ref outbound_capacity_msat)) = first_hop_targets.get(&$node_id) {
698 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);
703 if let Some(node_info) = $node.announcement_info.as_ref() {
704 features = node_info.features.clone();
706 features = NodeFeatures::empty();
709 if !features.requires_unknown_bits() {
710 for chan_id in $node.channels.iter() {
711 let chan = network.get_channels().get(chan_id).unwrap();
712 if !chan.features.requires_unknown_bits() {
713 if chan.node_one == *$node_id {
714 // ie $node is one, ie next hop in A* is two, via the two_to_one channel
715 if first_hops.is_none() || chan.node_two != *our_node_id {
716 if let Some(two_to_one) = chan.two_to_one.as_ref() {
717 if two_to_one.enabled {
718 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);
723 if first_hops.is_none() || chan.node_one != *our_node_id {
724 if let Some(one_to_two) = chan.one_to_two.as_ref() {
725 if one_to_two.enabled {
726 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);
738 let mut payment_paths = Vec::<PaymentPath>::new();
740 // TODO: diversify by nodes (so that all paths aren't doomed if one node is offline).
741 'paths_collection: loop {
742 // For every new path, start from scratch, except
743 // bookkeeped_channels_liquidity_available_msat, which will improve
744 // the further iterations of path finding. Also don't erase first_hop_targets.
748 // If first hop is a private channel and the only way to reach the payee, this is the only
749 // place where it could be added.
750 if first_hops.is_some() {
751 if let Some(&(ref first_hop, ref features, ref outbound_capacity_msat)) = first_hop_targets.get(&payee) {
752 add_entry!(first_hop, *our_node_id, payee, dummy_directional_info, Some(outbound_capacity_msat / 1000), features.to_context(), 0, recommended_value_msat);
756 // Add the payee as a target, so that the payee-to-payer
757 // search algorithm knows what to start with.
758 match network.get_nodes().get(payee) {
759 // The payee is not in our network graph, so nothing to add here.
760 // There is still a chance of reaching them via last_hops though,
761 // so don't yet fail the payment here.
762 // If not, targets.pop() will not even let us enter the loop in step 2.
765 add_entries_to_cheapest_to_target_node!(node, payee, 0, recommended_value_msat);
770 // If a caller provided us with last hops, add them to routing targets. Since this happens
771 // earlier than general path finding, they will be somewhat prioritized, although currently
772 // it matters only if the fees are exactly the same.
773 for hop in last_hops.iter() {
774 let have_hop_src_in_graph =
775 if let Some(&(ref first_hop, ref features, ref outbound_capacity_msat)) = first_hop_targets.get(&hop.src_node_id) {
776 // If this hop connects to a node with which we have a direct channel, ignore
777 // the network graph and add both the hop and our direct channel to
778 // the candidate set.
780 // Currently there are no channel-context features defined, so we are a
781 // bit lazy here. In the future, we should pull them out via our
782 // ChannelManager, but there's no reason to waste the space until we
784 add_entry!(first_hop, *our_node_id , hop.src_node_id, dummy_directional_info, Some(outbound_capacity_msat / 1000), features.to_context(), 0, recommended_value_msat);
787 // In any other case, only add the hop if the source is in the regular network
789 network.get_nodes().get(&hop.src_node_id).is_some()
791 if have_hop_src_in_graph {
792 // BOLT 11 doesn't allow inclusion of features for the last hop hints, which
793 // really sucks, cause we're gonna need that eventually.
794 let last_hop_htlc_minimum_msat: u64 = match hop.htlc_minimum_msat {
795 Some(htlc_minimum_msat) => htlc_minimum_msat,
798 let directional_info = DummyDirectionalChannelInfo {
799 cltv_expiry_delta: hop.cltv_expiry_delta as u32,
800 htlc_minimum_msat: last_hop_htlc_minimum_msat,
801 htlc_maximum_msat: hop.htlc_maximum_msat,
804 add_entry!(hop.short_channel_id, hop.src_node_id, payee, directional_info, None::<u64>, ChannelFeatures::empty(), 0, recommended_value_msat);
808 // At this point, targets are filled with the data from first and
809 // last hops communicated by the caller, and the payment receiver.
810 let mut found_new_path = false;
813 // If this loop terminates due the exhaustion of targets, two situations are possible:
814 // - not enough outgoing liquidity:
815 // 0 < already_collected_value_msat < final_value_msat
816 // - enough outgoing liquidity:
817 // final_value_msat <= already_collected_value_msat < recommended_value_msat
818 // Both these cases (and other cases except reaching recommended_value_msat) mean that
819 // paths_collection will be stopped because found_new_path==false.
820 // This is not necessarily a routing failure.
821 'path_construction: while let Some(RouteGraphNode { pubkey, lowest_fee_to_node, value_contribution_msat, .. }) = targets.pop() {
823 // Since we're going payee-to-payer, hitting our node as a target means we should stop
824 // traversing the graph and arrange the path out of what we found.
825 if pubkey == *our_node_id {
826 let mut new_entry = dist.remove(&our_node_id).unwrap();
827 let mut ordered_hops = vec!(new_entry.clone());
830 if let Some(&(_, ref features, _)) = first_hop_targets.get(&ordered_hops.last().unwrap().route_hop.pubkey) {
831 ordered_hops.last_mut().unwrap().route_hop.node_features = features.to_context();
832 } else if let Some(node) = network.get_nodes().get(&ordered_hops.last().unwrap().route_hop.pubkey) {
833 if let Some(node_info) = node.announcement_info.as_ref() {
834 ordered_hops.last_mut().unwrap().route_hop.node_features = node_info.features.clone();
836 ordered_hops.last_mut().unwrap().route_hop.node_features = NodeFeatures::empty();
839 // We should be able to fill in features for everything except the last
840 // hop, if the last hop was provided via a BOLT 11 invoice (though we
841 // should be able to extend it further as BOLT 11 does have feature
842 // flags for the last hop node itself).
843 assert!(ordered_hops.last().unwrap().route_hop.pubkey == *payee);
846 // Means we succesfully traversed from the payer to the payee, now
847 // save this path for the payment route. Also, update the liquidity
848 // remaining on the used hops, so that we take them into account
849 // while looking for more paths.
850 if ordered_hops.last().unwrap().route_hop.pubkey == *payee {
854 new_entry = match dist.remove(&ordered_hops.last().unwrap().route_hop.pubkey) {
855 Some(payment_hop) => payment_hop,
856 // We can't arrive at None because, if we ever add an entry to targets,
857 // we also fill in the entry in dist (see add_entry!).
858 None => unreachable!(),
860 // We "propagate" the fees one hop backward (topologically) here,
861 // so that fees paid for a HTLC forwarding on the current channel are
862 // associated with the previous channel (where they will be subtracted).
863 ordered_hops.last_mut().unwrap().route_hop.fee_msat = new_entry.hop_use_fee_msat;
864 ordered_hops.last_mut().unwrap().route_hop.cltv_expiry_delta = new_entry.route_hop.cltv_expiry_delta;
865 ordered_hops.push(new_entry.clone());
867 ordered_hops.last_mut().unwrap().route_hop.fee_msat = value_contribution_msat;
868 ordered_hops.last_mut().unwrap().hop_use_fee_msat = 0;
869 ordered_hops.last_mut().unwrap().route_hop.cltv_expiry_delta = final_cltv;
871 let mut payment_path = PaymentPath {hops: ordered_hops};
873 // We could have possibly constructed a slightly inconsistent path: since we reduce
874 // value being transferred along the way, we could have violated htlc_minimum_msat
875 // on some channels we already passed (assuming dest->source direction). Here, we
876 // recompute the fees again, so that if that's the case, we match the currently
877 // underpaid htlc_minimum_msat with fees.
878 payment_path.update_value_and_recompute_fees(value_contribution_msat);
880 // Since a path allows to transfer as much value as
881 // the smallest channel it has ("bottleneck"), we should recompute
882 // the fees so sender HTLC don't overpay fees when traversing
883 // larger channels than the bottleneck. This may happen because
884 // when we were selecting those channels we were not aware how much value
885 // this path will transfer, and the relative fee for them
886 // might have been computed considering a larger value.
887 // Remember that we used these channels so that we don't rely
888 // on the same liquidity in future paths.
889 for payment_hop in payment_path.hops.iter() {
890 let channel_liquidity_available_msat = bookkeeped_channels_liquidity_available_msat.get_mut(&payment_hop.route_hop.short_channel_id).unwrap();
891 let mut spent_on_hop_msat = value_contribution_msat;
892 let next_hops_fee_msat = payment_hop.next_hops_fee_msat;
893 spent_on_hop_msat += next_hops_fee_msat;
894 if *channel_liquidity_available_msat < spent_on_hop_msat {
895 // This should not happen because we do recompute fees right before,
896 // trying to avoid cases when a hop is not usable due to the fee situation.
897 break 'path_construction;
899 *channel_liquidity_available_msat -= spent_on_hop_msat;
901 // Track the total amount all our collected paths allow to send so that we:
902 // - know when to stop looking for more paths
903 // - know which of the hops are useless considering how much more sats we need
904 // (contributes_sufficient_value)
905 already_collected_value_msat += value_contribution_msat;
907 payment_paths.push(payment_path);
908 found_new_path = true;
909 break 'path_construction;
912 // Otherwise, since the current target node is not us,
913 // keep "unrolling" the payment graph from payee to payer by
914 // finding a way to reach the current target from the payer side.
915 match network.get_nodes().get(&pubkey) {
918 add_entries_to_cheapest_to_target_node!(node, &pubkey, lowest_fee_to_node, value_contribution_msat);
924 // If we don't support MPP, no use trying to gather more value ever.
925 break 'paths_collection;
929 // Stop either when recommended value is reached,
930 // or if during last iteration no new path was found.
931 // In the latter case, making another path finding attempt could not help,
932 // because we deterministically terminate the search due to low liquidity.
933 if already_collected_value_msat >= recommended_value_msat || !found_new_path {
934 break 'paths_collection;
939 if payment_paths.len() == 0 {
940 return Err(LightningError{err: "Failed to find a path to the given destination".to_owned(), action: ErrorAction::IgnoreError});
943 if already_collected_value_msat < final_value_msat {
944 return Err(LightningError{err: "Failed to find a sufficient route to the given destination".to_owned(), action: ErrorAction::IgnoreError});
947 // Sort by total fees and take the best paths.
948 payment_paths.sort_by_key(|path| path.get_total_fee_paid_msat());
949 if payment_paths.len() > 50 {
950 payment_paths.truncate(50);
953 // Draw multiple sufficient routes by randomly combining the selected paths.
954 let mut drawn_routes = Vec::new();
955 for i in 0..payment_paths.len() {
956 let mut cur_route = Vec::<PaymentPath>::new();
957 let mut aggregate_route_value_msat = 0;
960 // TODO: real random shuffle
961 // Currently just starts with i_th and goes up to i-1_th in a looped way.
962 let cur_payment_paths = [&payment_paths[i..], &payment_paths[..i]].concat();
965 for payment_path in cur_payment_paths {
966 cur_route.push(payment_path.clone());
967 aggregate_route_value_msat += payment_path.get_value_msat();
968 if aggregate_route_value_msat > final_value_msat {
969 // Last path likely overpaid. Substract it from the most expensive
970 // (in terms of proportional fee) path in this route and recompute fees.
971 // This might be not the most economically efficient way, but fewer paths
972 // also makes routing more reliable.
973 let mut overpaid_value_msat = aggregate_route_value_msat - final_value_msat;
975 // First, drop some expensive low-value paths entirely if possible.
976 // Sort by value so that we drop many really-low values first, since
977 // fewer paths is better: the payment is less likely to fail.
978 // TODO: this could also be optimized by also sorting by feerate_per_sat_routed,
979 // so that the sender pays less fees overall. And also htlc_minimum_msat.
980 cur_route.sort_by_key(|path| path.get_value_msat());
981 // We should make sure that at least 1 path left.
982 let mut paths_left = cur_route.len();
983 cur_route.retain(|path| {
988 let path_value_msat = path.get_value_msat();
989 if path_value_msat <= overpaid_value_msat {
991 overpaid_value_msat -= path_value_msat;
997 if overpaid_value_msat == 0 {
1001 assert!(cur_route.len() > 0);
1004 // Now, substract the overpaid value from the most-expensive path.
1005 // TODO: this could also be optimized by also sorting by feerate_per_sat_routed,
1006 // so that the sender pays less fees overall. And also htlc_minimum_msat.
1007 cur_route.sort_by_key(|path| { path.hops.iter().map(|hop| hop.channel_fees.proportional_millionths as u64).sum::<u64>() });
1008 let expensive_payment_path = cur_route.first_mut().unwrap();
1009 // We already dropped all the small channels above, meaning all the
1010 // remaining channels are larger than remaining overpaid_value_msat.
1011 // Thus, this can't be negative.
1012 let expensive_path_new_value_msat = expensive_payment_path.get_value_msat() - overpaid_value_msat;
1013 expensive_payment_path.update_value_and_recompute_fees(expensive_path_new_value_msat);
1017 drawn_routes.push(cur_route);
1021 // Select the best route by lowest total fee.
1022 drawn_routes.sort_by_key(|paths| paths.iter().map(|path| path.get_total_fee_paid_msat()).sum::<u64>());
1023 let mut selected_paths = Vec::<Vec<RouteHop>>::new();
1024 for payment_path in drawn_routes.first().unwrap() {
1025 selected_paths.push(payment_path.hops.iter().map(|payment_hop| payment_hop.route_hop.clone()).collect());
1028 if let Some(features) = &payee_features {
1029 for path in selected_paths.iter_mut() {
1030 path.last_mut().unwrap().node_features = features.to_context();
1034 let route = Route { paths: selected_paths };
1035 log_trace!(logger, "Got route: {}", log_route!(route));
1041 use routing::router::{get_route, RouteHint, RoutingFees};
1042 use routing::network_graph::{NetworkGraph, NetGraphMsgHandler};
1043 use ln::features::{ChannelFeatures, InitFeatures, InvoiceFeatures, NodeFeatures};
1044 use ln::msgs::{ErrorAction, LightningError, OptionalField, UnsignedChannelAnnouncement, ChannelAnnouncement, RoutingMessageHandler,
1045 NodeAnnouncement, UnsignedNodeAnnouncement, ChannelUpdate, UnsignedChannelUpdate};
1046 use ln::channelmanager;
1047 use util::test_utils;
1048 use util::ser::Writeable;
1050 use bitcoin::hashes::sha256d::Hash as Sha256dHash;
1051 use bitcoin::hashes::Hash;
1052 use bitcoin::network::constants::Network;
1053 use bitcoin::blockdata::constants::genesis_block;
1054 use bitcoin::blockdata::script::Builder;
1055 use bitcoin::blockdata::opcodes;
1056 use bitcoin::blockdata::transaction::TxOut;
1060 use bitcoin::secp256k1::key::{PublicKey,SecretKey};
1061 use bitcoin::secp256k1::{Secp256k1, All};
1065 // Using the same keys for LN and BTC ids
1066 fn add_channel(net_graph_msg_handler: &NetGraphMsgHandler<Arc<test_utils::TestChainSource>, Arc<test_utils::TestLogger>>, secp_ctx: &Secp256k1<All>, node_1_privkey: &SecretKey,
1067 node_2_privkey: &SecretKey, features: ChannelFeatures, short_channel_id: u64) {
1068 let node_id_1 = PublicKey::from_secret_key(&secp_ctx, node_1_privkey);
1069 let node_id_2 = PublicKey::from_secret_key(&secp_ctx, node_2_privkey);
1071 let unsigned_announcement = UnsignedChannelAnnouncement {
1073 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1077 bitcoin_key_1: node_id_1,
1078 bitcoin_key_2: node_id_2,
1079 excess_data: Vec::new(),
1082 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1083 let valid_announcement = ChannelAnnouncement {
1084 node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
1085 node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
1086 bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
1087 bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
1088 contents: unsigned_announcement.clone(),
1090 match net_graph_msg_handler.handle_channel_announcement(&valid_announcement) {
1091 Ok(res) => assert!(res),
1096 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) {
1097 let msghash = hash_to_message!(&Sha256dHash::hash(&update.encode()[..])[..]);
1098 let valid_channel_update = ChannelUpdate {
1099 signature: secp_ctx.sign(&msghash, node_privkey),
1100 contents: update.clone()
1103 match net_graph_msg_handler.handle_channel_update(&valid_channel_update) {
1104 Ok(res) => assert!(res),
1109 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,
1110 features: NodeFeatures, timestamp: u32) {
1111 let node_id = PublicKey::from_secret_key(&secp_ctx, node_privkey);
1112 let unsigned_announcement = UnsignedNodeAnnouncement {
1118 addresses: Vec::new(),
1119 excess_address_data: Vec::new(),
1120 excess_data: Vec::new(),
1122 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1123 let valid_announcement = NodeAnnouncement {
1124 signature: secp_ctx.sign(&msghash, node_privkey),
1125 contents: unsigned_announcement.clone()
1128 match net_graph_msg_handler.handle_node_announcement(&valid_announcement) {
1134 fn get_nodes(secp_ctx: &Secp256k1<All>) -> (SecretKey, PublicKey, Vec<SecretKey>, Vec<PublicKey>) {
1135 let privkeys: Vec<SecretKey> = (2..10).map(|i| {
1136 SecretKey::from_slice(&hex::decode(format!("{:02}", i).repeat(32)).unwrap()[..]).unwrap()
1139 let pubkeys = privkeys.iter().map(|secret| PublicKey::from_secret_key(&secp_ctx, secret)).collect();
1141 let our_privkey = SecretKey::from_slice(&hex::decode("01".repeat(32)).unwrap()[..]).unwrap();
1142 let our_id = PublicKey::from_secret_key(&secp_ctx, &our_privkey);
1144 (our_privkey, our_id, privkeys, pubkeys)
1147 fn id_to_feature_flags(id: u8) -> Vec<u8> {
1148 // Set the feature flags to the id'th odd (ie non-required) feature bit so that we can
1149 // test for it later.
1150 let idx = (id - 1) * 2 + 1;
1152 vec![1 << (idx - 8*3), 0, 0, 0]
1153 } else if idx > 8*2 {
1154 vec![1 << (idx - 8*2), 0, 0]
1155 } else if idx > 8*1 {
1156 vec![1 << (idx - 8*1), 0]
1162 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>) {
1163 let secp_ctx = Secp256k1::new();
1164 let logger = Arc::new(test_utils::TestLogger::new());
1165 let chain_monitor = Arc::new(test_utils::TestChainSource::new(Network::Testnet));
1166 let net_graph_msg_handler = NetGraphMsgHandler::new(genesis_block(Network::Testnet).header.block_hash(), None, Arc::clone(&logger));
1167 // Build network from our_id to node7:
1169 // -1(1)2- node0 -1(3)2-
1171 // our_id -1(12)2- node7 -1(13)2--- node2
1173 // -1(2)2- node1 -1(4)2-
1176 // chan1 1-to-2: disabled
1177 // chan1 2-to-1: enabled, 0 fee
1179 // chan2 1-to-2: enabled, ignored fee
1180 // chan2 2-to-1: enabled, 0 fee
1182 // chan3 1-to-2: enabled, 0 fee
1183 // chan3 2-to-1: enabled, 100 msat fee
1185 // chan4 1-to-2: enabled, 100% fee
1186 // chan4 2-to-1: enabled, 0 fee
1188 // chan12 1-to-2: enabled, ignored fee
1189 // chan12 2-to-1: enabled, 0 fee
1191 // chan13 1-to-2: enabled, 200% fee
1192 // chan13 2-to-1: enabled, 0 fee
1195 // -1(5)2- node3 -1(8)2--
1199 // node2--1(6)2- node4 -1(9)2--- node6 (not in global route map)
1201 // -1(7)2- node5 -1(10)2-
1203 // chan5 1-to-2: enabled, 100 msat fee
1204 // chan5 2-to-1: enabled, 0 fee
1206 // chan6 1-to-2: enabled, 0 fee
1207 // chan6 2-to-1: enabled, 0 fee
1209 // chan7 1-to-2: enabled, 100% fee
1210 // chan7 2-to-1: enabled, 0 fee
1212 // chan8 1-to-2: enabled, variable fee (0 then 1000 msat)
1213 // chan8 2-to-1: enabled, 0 fee
1215 // chan9 1-to-2: enabled, 1001 msat fee
1216 // chan9 2-to-1: enabled, 0 fee
1218 // chan10 1-to-2: enabled, 0 fee
1219 // chan10 2-to-1: enabled, 0 fee
1221 // chan11 1-to-2: enabled, 0 fee
1222 // chan11 2-to-1: enabled, 0 fee
1224 let (our_privkey, _, privkeys, _) = get_nodes(&secp_ctx);
1226 add_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, &privkeys[0], ChannelFeatures::from_le_bytes(id_to_feature_flags(1)), 1);
1227 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
1228 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1229 short_channel_id: 1,
1232 cltv_expiry_delta: 0,
1233 htlc_minimum_msat: 0,
1234 htlc_maximum_msat: OptionalField::Absent,
1236 fee_proportional_millionths: 0,
1237 excess_data: Vec::new()
1240 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[0], NodeFeatures::from_le_bytes(id_to_feature_flags(1)), 0);
1242 add_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, &privkeys[1], ChannelFeatures::from_le_bytes(id_to_feature_flags(2)), 2);
1243 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
1244 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1245 short_channel_id: 2,
1248 cltv_expiry_delta: u16::max_value(),
1249 htlc_minimum_msat: 0,
1250 htlc_maximum_msat: OptionalField::Absent,
1251 fee_base_msat: u32::max_value(),
1252 fee_proportional_millionths: u32::max_value(),
1253 excess_data: Vec::new()
1255 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
1256 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1257 short_channel_id: 2,
1260 cltv_expiry_delta: 0,
1261 htlc_minimum_msat: 0,
1262 htlc_maximum_msat: OptionalField::Absent,
1264 fee_proportional_millionths: 0,
1265 excess_data: Vec::new()
1268 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[1], NodeFeatures::from_le_bytes(id_to_feature_flags(2)), 0);
1270 add_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, &privkeys[7], ChannelFeatures::from_le_bytes(id_to_feature_flags(12)), 12);
1271 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
1272 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1273 short_channel_id: 12,
1276 cltv_expiry_delta: u16::max_value(),
1277 htlc_minimum_msat: 0,
1278 htlc_maximum_msat: OptionalField::Absent,
1279 fee_base_msat: u32::max_value(),
1280 fee_proportional_millionths: u32::max_value(),
1281 excess_data: Vec::new()
1283 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
1284 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1285 short_channel_id: 12,
1288 cltv_expiry_delta: 0,
1289 htlc_minimum_msat: 0,
1290 htlc_maximum_msat: OptionalField::Absent,
1292 fee_proportional_millionths: 0,
1293 excess_data: Vec::new()
1296 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[7], NodeFeatures::from_le_bytes(id_to_feature_flags(8)), 0);
1298 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], &privkeys[2], ChannelFeatures::from_le_bytes(id_to_feature_flags(3)), 3);
1299 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
1300 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1301 short_channel_id: 3,
1304 cltv_expiry_delta: (3 << 8) | 1,
1305 htlc_minimum_msat: 0,
1306 htlc_maximum_msat: OptionalField::Absent,
1308 fee_proportional_millionths: 0,
1309 excess_data: Vec::new()
1311 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
1312 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1313 short_channel_id: 3,
1316 cltv_expiry_delta: (3 << 8) | 2,
1317 htlc_minimum_msat: 0,
1318 htlc_maximum_msat: OptionalField::Absent,
1320 fee_proportional_millionths: 0,
1321 excess_data: Vec::new()
1324 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], &privkeys[2], ChannelFeatures::from_le_bytes(id_to_feature_flags(4)), 4);
1325 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
1326 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1327 short_channel_id: 4,
1330 cltv_expiry_delta: (4 << 8) | 1,
1331 htlc_minimum_msat: 0,
1332 htlc_maximum_msat: OptionalField::Absent,
1334 fee_proportional_millionths: 1000000,
1335 excess_data: Vec::new()
1337 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
1338 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1339 short_channel_id: 4,
1342 cltv_expiry_delta: (4 << 8) | 2,
1343 htlc_minimum_msat: 0,
1344 htlc_maximum_msat: OptionalField::Absent,
1346 fee_proportional_millionths: 0,
1347 excess_data: Vec::new()
1350 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], &privkeys[2], ChannelFeatures::from_le_bytes(id_to_feature_flags(13)), 13);
1351 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
1352 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1353 short_channel_id: 13,
1356 cltv_expiry_delta: (13 << 8) | 1,
1357 htlc_minimum_msat: 0,
1358 htlc_maximum_msat: OptionalField::Absent,
1360 fee_proportional_millionths: 2000000,
1361 excess_data: Vec::new()
1363 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
1364 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1365 short_channel_id: 13,
1368 cltv_expiry_delta: (13 << 8) | 2,
1369 htlc_minimum_msat: 0,
1370 htlc_maximum_msat: OptionalField::Absent,
1372 fee_proportional_millionths: 0,
1373 excess_data: Vec::new()
1376 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[2], NodeFeatures::from_le_bytes(id_to_feature_flags(3)), 0);
1378 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], &privkeys[4], ChannelFeatures::from_le_bytes(id_to_feature_flags(6)), 6);
1379 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
1380 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1381 short_channel_id: 6,
1384 cltv_expiry_delta: (6 << 8) | 1,
1385 htlc_minimum_msat: 0,
1386 htlc_maximum_msat: OptionalField::Absent,
1388 fee_proportional_millionths: 0,
1389 excess_data: Vec::new()
1391 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
1392 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1393 short_channel_id: 6,
1396 cltv_expiry_delta: (6 << 8) | 2,
1397 htlc_minimum_msat: 0,
1398 htlc_maximum_msat: OptionalField::Absent,
1400 fee_proportional_millionths: 0,
1401 excess_data: Vec::new(),
1404 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(11)), 11);
1405 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
1406 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1407 short_channel_id: 11,
1410 cltv_expiry_delta: (11 << 8) | 1,
1411 htlc_minimum_msat: 0,
1412 htlc_maximum_msat: OptionalField::Absent,
1414 fee_proportional_millionths: 0,
1415 excess_data: Vec::new()
1417 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[3], UnsignedChannelUpdate {
1418 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1419 short_channel_id: 11,
1422 cltv_expiry_delta: (11 << 8) | 2,
1423 htlc_minimum_msat: 0,
1424 htlc_maximum_msat: OptionalField::Absent,
1426 fee_proportional_millionths: 0,
1427 excess_data: Vec::new()
1430 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[4], NodeFeatures::from_le_bytes(id_to_feature_flags(5)), 0);
1432 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[3], NodeFeatures::from_le_bytes(id_to_feature_flags(4)), 0);
1434 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], &privkeys[5], ChannelFeatures::from_le_bytes(id_to_feature_flags(7)), 7);
1435 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
1436 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1437 short_channel_id: 7,
1440 cltv_expiry_delta: (7 << 8) | 1,
1441 htlc_minimum_msat: 0,
1442 htlc_maximum_msat: OptionalField::Absent,
1444 fee_proportional_millionths: 1000000,
1445 excess_data: Vec::new()
1447 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[5], UnsignedChannelUpdate {
1448 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1449 short_channel_id: 7,
1452 cltv_expiry_delta: (7 << 8) | 2,
1453 htlc_minimum_msat: 0,
1454 htlc_maximum_msat: OptionalField::Absent,
1456 fee_proportional_millionths: 0,
1457 excess_data: Vec::new()
1460 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[5], NodeFeatures::from_le_bytes(id_to_feature_flags(6)), 0);
1462 (secp_ctx, net_graph_msg_handler, chain_monitor, logger)
1466 fn simple_route_test() {
1467 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
1468 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
1470 // Simple route to 2 via 1
1472 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)) {
1473 assert_eq!(err, "Cannot send a payment of 0 msat");
1474 } else { panic!(); }
1476 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();
1477 assert_eq!(route.paths[0].len(), 2);
1479 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
1480 assert_eq!(route.paths[0][0].short_channel_id, 2);
1481 assert_eq!(route.paths[0][0].fee_msat, 100);
1482 assert_eq!(route.paths[0][0].cltv_expiry_delta, (4 << 8) | 1);
1483 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
1484 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
1486 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
1487 assert_eq!(route.paths[0][1].short_channel_id, 4);
1488 assert_eq!(route.paths[0][1].fee_msat, 100);
1489 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
1490 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
1491 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
1495 fn invalid_first_hop_test() {
1496 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
1497 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
1499 // Simple route to 2 via 1
1501 let our_chans = vec![channelmanager::ChannelDetails {
1502 channel_id: [0; 32],
1503 short_channel_id: Some(2),
1504 remote_network_id: our_id,
1505 counterparty_features: InitFeatures::from_le_bytes(vec![0b11]),
1506 channel_value_satoshis: 100000,
1508 outbound_capacity_msat: 100000,
1509 inbound_capacity_msat: 100000,
1511 counterparty_forwarding_info: None,
1514 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)) {
1515 assert_eq!(err, "First hop cannot have our_node_id as a destination.");
1516 } else { panic!(); }
1518 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();
1519 assert_eq!(route.paths[0].len(), 2);
1523 fn htlc_minimum_test() {
1524 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
1525 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
1527 // Simple route to 2 via 1
1529 // Disable other paths
1530 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
1531 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1532 short_channel_id: 12,
1534 flags: 2, // to disable
1535 cltv_expiry_delta: 0,
1536 htlc_minimum_msat: 0,
1537 htlc_maximum_msat: OptionalField::Absent,
1539 fee_proportional_millionths: 0,
1540 excess_data: Vec::new()
1542 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
1543 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1544 short_channel_id: 3,
1546 flags: 2, // to disable
1547 cltv_expiry_delta: 0,
1548 htlc_minimum_msat: 0,
1549 htlc_maximum_msat: OptionalField::Absent,
1551 fee_proportional_millionths: 0,
1552 excess_data: Vec::new()
1554 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
1555 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1556 short_channel_id: 13,
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[2], UnsignedChannelUpdate {
1567 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1568 short_channel_id: 6,
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[2], UnsignedChannelUpdate {
1579 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1580 short_channel_id: 7,
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()
1591 // Check against amount_to_transfer_over_msat.
1592 // Set minimal HTLC of 200_000_000 msat.
1593 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
1594 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1595 short_channel_id: 2,
1598 cltv_expiry_delta: 0,
1599 htlc_minimum_msat: 200_000_000,
1600 htlc_maximum_msat: OptionalField::Absent,
1602 fee_proportional_millionths: 0,
1603 excess_data: Vec::new()
1606 // Second hop only allows to forward 199_999_999 at most, thus not allowing the first hop to
1608 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
1609 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1610 short_channel_id: 4,
1613 cltv_expiry_delta: 0,
1614 htlc_minimum_msat: 0,
1615 htlc_maximum_msat: OptionalField::Present(199_999_999),
1617 fee_proportional_millionths: 0,
1618 excess_data: Vec::new()
1621 // Not possible to send 199_999_999, because the minimum on channel=2 is 200_000_000.
1622 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)) {
1623 assert_eq!(err, "Failed to find a path to the given destination");
1624 } else { panic!(); }
1626 // Lift the restriction on the first hop.
1627 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
1628 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1629 short_channel_id: 2,
1632 cltv_expiry_delta: 0,
1633 htlc_minimum_msat: 0,
1634 htlc_maximum_msat: OptionalField::Absent,
1636 fee_proportional_millionths: 0,
1637 excess_data: Vec::new()
1640 // A payment above the minimum should pass
1641 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();
1642 assert_eq!(route.paths[0].len(), 2);
1646 fn htlc_minimum_overpay_test() {
1647 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
1648 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
1650 // A route to node#2 via two paths.
1651 // One path allows transferring 35-40 sats, another one also allows 35-40 sats.
1652 // Thus, they can't send 60 without overpaying.
1653 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
1654 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1655 short_channel_id: 2,
1658 cltv_expiry_delta: 0,
1659 htlc_minimum_msat: 35_000,
1660 htlc_maximum_msat: OptionalField::Present(40_000),
1662 fee_proportional_millionths: 0,
1663 excess_data: Vec::new()
1665 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
1666 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1667 short_channel_id: 12,
1670 cltv_expiry_delta: 0,
1671 htlc_minimum_msat: 35_000,
1672 htlc_maximum_msat: OptionalField::Present(40_000),
1674 fee_proportional_millionths: 0,
1675 excess_data: Vec::new()
1679 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
1680 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1681 short_channel_id: 13,
1684 cltv_expiry_delta: 0,
1685 htlc_minimum_msat: 0,
1686 htlc_maximum_msat: OptionalField::Absent,
1688 fee_proportional_millionths: 0,
1689 excess_data: Vec::new()
1691 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
1692 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1693 short_channel_id: 4,
1696 cltv_expiry_delta: 0,
1697 htlc_minimum_msat: 0,
1698 htlc_maximum_msat: OptionalField::Absent,
1700 fee_proportional_millionths: 0,
1701 excess_data: Vec::new()
1704 // Disable other paths
1705 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
1706 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1707 short_channel_id: 1,
1709 flags: 2, // to disable
1710 cltv_expiry_delta: 0,
1711 htlc_minimum_msat: 0,
1712 htlc_maximum_msat: OptionalField::Absent,
1714 fee_proportional_millionths: 0,
1715 excess_data: Vec::new()
1718 let route = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2],
1719 Some(InvoiceFeatures::known()), None, &Vec::new(), 60_000, 42, Arc::clone(&logger)).unwrap();
1720 // Overpay fees to hit htlc_minimum_msat.
1721 let overpaid_fees = route.paths[0][0].fee_msat + route.paths[1][0].fee_msat;
1722 // TODO: this could be better balanced to overpay 10k and not 15k.
1723 assert_eq!(overpaid_fees, 15_000);
1725 // Now, test that if there are 2 paths, a "cheaper" by fee path wouldn't be prioritized
1726 // while taking even more fee to match htlc_minimum_msat.
1727 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
1728 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1729 short_channel_id: 12,
1732 cltv_expiry_delta: 0,
1733 htlc_minimum_msat: 65_000,
1734 htlc_maximum_msat: OptionalField::Present(80_000),
1736 fee_proportional_millionths: 0,
1737 excess_data: Vec::new()
1739 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
1740 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1741 short_channel_id: 2,
1744 cltv_expiry_delta: 0,
1745 htlc_minimum_msat: 0,
1746 htlc_maximum_msat: OptionalField::Absent,
1748 fee_proportional_millionths: 0,
1749 excess_data: Vec::new()
1751 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
1752 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1753 short_channel_id: 4,
1756 cltv_expiry_delta: 0,
1757 htlc_minimum_msat: 0,
1758 htlc_maximum_msat: OptionalField::Absent,
1760 fee_proportional_millionths: 100_000,
1761 excess_data: Vec::new()
1764 let route = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2],
1765 Some(InvoiceFeatures::known()), None, &Vec::new(), 60_000, 42, Arc::clone(&logger)).unwrap();
1766 // Fine to overpay for htlc_minimum_msat if it allows us to save fee.
1767 assert_eq!(route.paths.len(), 1);
1768 assert_eq!(route.paths[0][0].short_channel_id, 12);
1769 let fees = route.paths[0][0].fee_msat;
1770 assert_eq!(fees, 5_000);
1772 let route = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2],
1773 Some(InvoiceFeatures::known()), None, &Vec::new(), 50_000, 42, Arc::clone(&logger)).unwrap();
1774 // Not fine to overpay for htlc_minimum_msat if it requires paying more than fee on
1775 // the other channel.
1776 assert_eq!(route.paths.len(), 1);
1777 assert_eq!(route.paths[0][0].short_channel_id, 2);
1778 let fees = route.paths[0][0].fee_msat;
1779 assert_eq!(fees, 5_000);
1783 fn disable_channels_test() {
1784 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
1785 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
1787 // // Disable channels 4 and 12 by flags=2
1788 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
1789 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1790 short_channel_id: 4,
1792 flags: 2, // to disable
1793 cltv_expiry_delta: 0,
1794 htlc_minimum_msat: 0,
1795 htlc_maximum_msat: OptionalField::Absent,
1797 fee_proportional_millionths: 0,
1798 excess_data: Vec::new()
1800 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
1801 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1802 short_channel_id: 12,
1804 flags: 2, // to disable
1805 cltv_expiry_delta: 0,
1806 htlc_minimum_msat: 0,
1807 htlc_maximum_msat: OptionalField::Absent,
1809 fee_proportional_millionths: 0,
1810 excess_data: Vec::new()
1813 // If all the channels require some features we don't understand, route should fail
1814 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)) {
1815 assert_eq!(err, "Failed to find a path to the given destination");
1816 } else { panic!(); }
1818 // If we specify a channel to node7, that overrides our local channel view and that gets used
1819 let our_chans = vec![channelmanager::ChannelDetails {
1820 channel_id: [0; 32],
1821 short_channel_id: Some(42),
1822 remote_network_id: nodes[7].clone(),
1823 counterparty_features: InitFeatures::from_le_bytes(vec![0b11]),
1824 channel_value_satoshis: 0,
1826 outbound_capacity_msat: 250_000_000,
1827 inbound_capacity_msat: 0,
1829 counterparty_forwarding_info: None,
1831 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();
1832 assert_eq!(route.paths[0].len(), 2);
1834 assert_eq!(route.paths[0][0].pubkey, nodes[7]);
1835 assert_eq!(route.paths[0][0].short_channel_id, 42);
1836 assert_eq!(route.paths[0][0].fee_msat, 200);
1837 assert_eq!(route.paths[0][0].cltv_expiry_delta, (13 << 8) | 1);
1838 assert_eq!(route.paths[0][0].node_features.le_flags(), &vec![0b11]); // it should also override our view of their features
1839 assert_eq!(route.paths[0][0].channel_features.le_flags(), &Vec::<u8>::new()); // No feature flags will meet the relevant-to-channel conversion
1841 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
1842 assert_eq!(route.paths[0][1].short_channel_id, 13);
1843 assert_eq!(route.paths[0][1].fee_msat, 100);
1844 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
1845 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
1846 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(13));
1850 fn disable_node_test() {
1851 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
1852 let (_, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
1854 // Disable nodes 1, 2, and 8 by requiring unknown feature bits
1855 let mut unknown_features = NodeFeatures::known();
1856 unknown_features.set_required_unknown_bits();
1857 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[0], unknown_features.clone(), 1);
1858 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[1], unknown_features.clone(), 1);
1859 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[7], unknown_features.clone(), 1);
1861 // If all nodes require some features we don't understand, route should fail
1862 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)) {
1863 assert_eq!(err, "Failed to find a path to the given destination");
1864 } else { panic!(); }
1866 // If we specify a channel to node7, that overrides our local channel view and that gets used
1867 let our_chans = vec![channelmanager::ChannelDetails {
1868 channel_id: [0; 32],
1869 short_channel_id: Some(42),
1870 remote_network_id: nodes[7].clone(),
1871 counterparty_features: InitFeatures::from_le_bytes(vec![0b11]),
1872 channel_value_satoshis: 0,
1874 outbound_capacity_msat: 250_000_000,
1875 inbound_capacity_msat: 0,
1877 counterparty_forwarding_info: None,
1879 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();
1880 assert_eq!(route.paths[0].len(), 2);
1882 assert_eq!(route.paths[0][0].pubkey, nodes[7]);
1883 assert_eq!(route.paths[0][0].short_channel_id, 42);
1884 assert_eq!(route.paths[0][0].fee_msat, 200);
1885 assert_eq!(route.paths[0][0].cltv_expiry_delta, (13 << 8) | 1);
1886 assert_eq!(route.paths[0][0].node_features.le_flags(), &vec![0b11]); // it should also override our view of their features
1887 assert_eq!(route.paths[0][0].channel_features.le_flags(), &Vec::<u8>::new()); // No feature flags will meet the relevant-to-channel conversion
1889 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
1890 assert_eq!(route.paths[0][1].short_channel_id, 13);
1891 assert_eq!(route.paths[0][1].fee_msat, 100);
1892 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
1893 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
1894 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(13));
1896 // Note that we don't test disabling node 3 and failing to route to it, as we (somewhat
1897 // naively) assume that the user checked the feature bits on the invoice, which override
1898 // the node_announcement.
1902 fn our_chans_test() {
1903 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
1904 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
1906 // Route to 1 via 2 and 3 because our channel to 1 is disabled
1907 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();
1908 assert_eq!(route.paths[0].len(), 3);
1910 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
1911 assert_eq!(route.paths[0][0].short_channel_id, 2);
1912 assert_eq!(route.paths[0][0].fee_msat, 200);
1913 assert_eq!(route.paths[0][0].cltv_expiry_delta, (4 << 8) | 1);
1914 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
1915 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
1917 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
1918 assert_eq!(route.paths[0][1].short_channel_id, 4);
1919 assert_eq!(route.paths[0][1].fee_msat, 100);
1920 assert_eq!(route.paths[0][1].cltv_expiry_delta, (3 << 8) | 2);
1921 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
1922 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
1924 assert_eq!(route.paths[0][2].pubkey, nodes[0]);
1925 assert_eq!(route.paths[0][2].short_channel_id, 3);
1926 assert_eq!(route.paths[0][2].fee_msat, 100);
1927 assert_eq!(route.paths[0][2].cltv_expiry_delta, 42);
1928 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(1));
1929 assert_eq!(route.paths[0][2].channel_features.le_flags(), &id_to_feature_flags(3));
1931 // If we specify a channel to node7, that overrides our local channel view and that gets used
1932 let our_chans = vec![channelmanager::ChannelDetails {
1933 channel_id: [0; 32],
1934 short_channel_id: Some(42),
1935 remote_network_id: nodes[7].clone(),
1936 counterparty_features: InitFeatures::from_le_bytes(vec![0b11]),
1937 channel_value_satoshis: 0,
1939 outbound_capacity_msat: 250_000_000,
1940 inbound_capacity_msat: 0,
1942 counterparty_forwarding_info: None,
1944 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();
1945 assert_eq!(route.paths[0].len(), 2);
1947 assert_eq!(route.paths[0][0].pubkey, nodes[7]);
1948 assert_eq!(route.paths[0][0].short_channel_id, 42);
1949 assert_eq!(route.paths[0][0].fee_msat, 200);
1950 assert_eq!(route.paths[0][0].cltv_expiry_delta, (13 << 8) | 1);
1951 assert_eq!(route.paths[0][0].node_features.le_flags(), &vec![0b11]);
1952 assert_eq!(route.paths[0][0].channel_features.le_flags(), &Vec::<u8>::new()); // No feature flags will meet the relevant-to-channel conversion
1954 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
1955 assert_eq!(route.paths[0][1].short_channel_id, 13);
1956 assert_eq!(route.paths[0][1].fee_msat, 100);
1957 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
1958 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
1959 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(13));
1962 fn last_hops(nodes: &Vec<PublicKey>) -> Vec<RouteHint> {
1963 let zero_fees = RoutingFees {
1965 proportional_millionths: 0,
1968 src_node_id: nodes[3].clone(),
1969 short_channel_id: 8,
1971 cltv_expiry_delta: (8 << 8) | 1,
1972 htlc_minimum_msat: None,
1973 htlc_maximum_msat: None,
1975 src_node_id: nodes[4].clone(),
1976 short_channel_id: 9,
1979 proportional_millionths: 0,
1981 cltv_expiry_delta: (9 << 8) | 1,
1982 htlc_minimum_msat: None,
1983 htlc_maximum_msat: None,
1985 src_node_id: nodes[5].clone(),
1986 short_channel_id: 10,
1988 cltv_expiry_delta: (10 << 8) | 1,
1989 htlc_minimum_msat: None,
1990 htlc_maximum_msat: None,
1995 fn last_hops_test() {
1996 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
1997 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
1999 // Simple test across 2, 3, 5, and 4 via a last_hop channel
2001 // First check that lst hop can't have its source as the payee.
2002 let invalid_last_hop = RouteHint {
2003 src_node_id: nodes[6],
2004 short_channel_id: 8,
2007 proportional_millionths: 0,
2009 cltv_expiry_delta: (8 << 8) | 1,
2010 htlc_minimum_msat: None,
2011 htlc_maximum_msat: None,
2014 let mut invalid_last_hops = last_hops(&nodes);
2015 invalid_last_hops.push(invalid_last_hop);
2017 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)) {
2018 assert_eq!(err, "Last hop cannot have a payee as a source.");
2019 } else { panic!(); }
2022 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();
2023 assert_eq!(route.paths[0].len(), 5);
2025 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
2026 assert_eq!(route.paths[0][0].short_channel_id, 2);
2027 assert_eq!(route.paths[0][0].fee_msat, 100);
2028 assert_eq!(route.paths[0][0].cltv_expiry_delta, (4 << 8) | 1);
2029 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
2030 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
2032 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2033 assert_eq!(route.paths[0][1].short_channel_id, 4);
2034 assert_eq!(route.paths[0][1].fee_msat, 0);
2035 assert_eq!(route.paths[0][1].cltv_expiry_delta, (6 << 8) | 1);
2036 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2037 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
2039 assert_eq!(route.paths[0][2].pubkey, nodes[4]);
2040 assert_eq!(route.paths[0][2].short_channel_id, 6);
2041 assert_eq!(route.paths[0][2].fee_msat, 0);
2042 assert_eq!(route.paths[0][2].cltv_expiry_delta, (11 << 8) | 1);
2043 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(5));
2044 assert_eq!(route.paths[0][2].channel_features.le_flags(), &id_to_feature_flags(6));
2046 assert_eq!(route.paths[0][3].pubkey, nodes[3]);
2047 assert_eq!(route.paths[0][3].short_channel_id, 11);
2048 assert_eq!(route.paths[0][3].fee_msat, 0);
2049 assert_eq!(route.paths[0][3].cltv_expiry_delta, (8 << 8) | 1);
2050 // If we have a peer in the node map, we'll use their features here since we don't have
2051 // a way of figuring out their features from the invoice:
2052 assert_eq!(route.paths[0][3].node_features.le_flags(), &id_to_feature_flags(4));
2053 assert_eq!(route.paths[0][3].channel_features.le_flags(), &id_to_feature_flags(11));
2055 assert_eq!(route.paths[0][4].pubkey, nodes[6]);
2056 assert_eq!(route.paths[0][4].short_channel_id, 8);
2057 assert_eq!(route.paths[0][4].fee_msat, 100);
2058 assert_eq!(route.paths[0][4].cltv_expiry_delta, 42);
2059 assert_eq!(route.paths[0][4].node_features.le_flags(), &Vec::<u8>::new()); // We dont pass flags in from invoices yet
2060 assert_eq!(route.paths[0][4].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
2064 fn our_chans_last_hop_connect_test() {
2065 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
2066 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
2068 // Simple test with outbound channel to 4 to test that last_hops and first_hops connect
2069 let our_chans = vec![channelmanager::ChannelDetails {
2070 channel_id: [0; 32],
2071 short_channel_id: Some(42),
2072 remote_network_id: nodes[3].clone(),
2073 counterparty_features: InitFeatures::from_le_bytes(vec![0b11]),
2074 channel_value_satoshis: 0,
2076 outbound_capacity_msat: 250_000_000,
2077 inbound_capacity_msat: 0,
2079 counterparty_forwarding_info: None,
2081 let mut last_hops = last_hops(&nodes);
2082 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();
2083 assert_eq!(route.paths[0].len(), 2);
2085 assert_eq!(route.paths[0][0].pubkey, nodes[3]);
2086 assert_eq!(route.paths[0][0].short_channel_id, 42);
2087 assert_eq!(route.paths[0][0].fee_msat, 0);
2088 assert_eq!(route.paths[0][0].cltv_expiry_delta, (8 << 8) | 1);
2089 assert_eq!(route.paths[0][0].node_features.le_flags(), &vec![0b11]);
2090 assert_eq!(route.paths[0][0].channel_features.le_flags(), &Vec::<u8>::new()); // No feature flags will meet the relevant-to-channel conversion
2092 assert_eq!(route.paths[0][1].pubkey, nodes[6]);
2093 assert_eq!(route.paths[0][1].short_channel_id, 8);
2094 assert_eq!(route.paths[0][1].fee_msat, 100);
2095 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
2096 assert_eq!(route.paths[0][1].node_features.le_flags(), &Vec::<u8>::new()); // We dont pass flags in from invoices yet
2097 assert_eq!(route.paths[0][1].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
2099 last_hops[0].fees.base_msat = 1000;
2101 // Revert to via 6 as the fee on 8 goes up
2102 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();
2103 assert_eq!(route.paths[0].len(), 4);
2105 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
2106 assert_eq!(route.paths[0][0].short_channel_id, 2);
2107 assert_eq!(route.paths[0][0].fee_msat, 200); // fee increased as its % of value transferred across node
2108 assert_eq!(route.paths[0][0].cltv_expiry_delta, (4 << 8) | 1);
2109 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
2110 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
2112 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2113 assert_eq!(route.paths[0][1].short_channel_id, 4);
2114 assert_eq!(route.paths[0][1].fee_msat, 100);
2115 assert_eq!(route.paths[0][1].cltv_expiry_delta, (7 << 8) | 1);
2116 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2117 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
2119 assert_eq!(route.paths[0][2].pubkey, nodes[5]);
2120 assert_eq!(route.paths[0][2].short_channel_id, 7);
2121 assert_eq!(route.paths[0][2].fee_msat, 0);
2122 assert_eq!(route.paths[0][2].cltv_expiry_delta, (10 << 8) | 1);
2123 // If we have a peer in the node map, we'll use their features here since we don't have
2124 // a way of figuring out their features from the invoice:
2125 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(6));
2126 assert_eq!(route.paths[0][2].channel_features.le_flags(), &id_to_feature_flags(7));
2128 assert_eq!(route.paths[0][3].pubkey, nodes[6]);
2129 assert_eq!(route.paths[0][3].short_channel_id, 10);
2130 assert_eq!(route.paths[0][3].fee_msat, 100);
2131 assert_eq!(route.paths[0][3].cltv_expiry_delta, 42);
2132 assert_eq!(route.paths[0][3].node_features.le_flags(), &Vec::<u8>::new()); // We dont pass flags in from invoices yet
2133 assert_eq!(route.paths[0][3].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
2135 // ...but still use 8 for larger payments as 6 has a variable feerate
2136 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();
2137 assert_eq!(route.paths[0].len(), 5);
2139 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
2140 assert_eq!(route.paths[0][0].short_channel_id, 2);
2141 assert_eq!(route.paths[0][0].fee_msat, 3000);
2142 assert_eq!(route.paths[0][0].cltv_expiry_delta, (4 << 8) | 1);
2143 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
2144 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
2146 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2147 assert_eq!(route.paths[0][1].short_channel_id, 4);
2148 assert_eq!(route.paths[0][1].fee_msat, 0);
2149 assert_eq!(route.paths[0][1].cltv_expiry_delta, (6 << 8) | 1);
2150 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2151 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
2153 assert_eq!(route.paths[0][2].pubkey, nodes[4]);
2154 assert_eq!(route.paths[0][2].short_channel_id, 6);
2155 assert_eq!(route.paths[0][2].fee_msat, 0);
2156 assert_eq!(route.paths[0][2].cltv_expiry_delta, (11 << 8) | 1);
2157 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(5));
2158 assert_eq!(route.paths[0][2].channel_features.le_flags(), &id_to_feature_flags(6));
2160 assert_eq!(route.paths[0][3].pubkey, nodes[3]);
2161 assert_eq!(route.paths[0][3].short_channel_id, 11);
2162 assert_eq!(route.paths[0][3].fee_msat, 1000);
2163 assert_eq!(route.paths[0][3].cltv_expiry_delta, (8 << 8) | 1);
2164 // If we have a peer in the node map, we'll use their features here since we don't have
2165 // a way of figuring out their features from the invoice:
2166 assert_eq!(route.paths[0][3].node_features.le_flags(), &id_to_feature_flags(4));
2167 assert_eq!(route.paths[0][3].channel_features.le_flags(), &id_to_feature_flags(11));
2169 assert_eq!(route.paths[0][4].pubkey, nodes[6]);
2170 assert_eq!(route.paths[0][4].short_channel_id, 8);
2171 assert_eq!(route.paths[0][4].fee_msat, 2000);
2172 assert_eq!(route.paths[0][4].cltv_expiry_delta, 42);
2173 assert_eq!(route.paths[0][4].node_features.le_flags(), &Vec::<u8>::new()); // We dont pass flags in from invoices yet
2174 assert_eq!(route.paths[0][4].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
2178 fn unannounced_path_test() {
2179 // We should be able to send a payment to a destination without any help of a routing graph
2180 // if we have a channel with a common counterparty that appears in the first and last hop
2182 let source_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&hex::decode(format!("{:02}", 41).repeat(32)).unwrap()[..]).unwrap());
2183 let middle_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&hex::decode(format!("{:02}", 42).repeat(32)).unwrap()[..]).unwrap());
2184 let target_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&hex::decode(format!("{:02}", 43).repeat(32)).unwrap()[..]).unwrap());
2186 // If we specify a channel to a middle hop, that overrides our local channel view and that gets used
2187 let last_hops = vec![RouteHint {
2188 src_node_id: middle_node_id,
2189 short_channel_id: 8,
2192 proportional_millionths: 0,
2194 cltv_expiry_delta: (8 << 8) | 1,
2195 htlc_minimum_msat: None,
2196 htlc_maximum_msat: None,
2198 let our_chans = vec![channelmanager::ChannelDetails {
2199 channel_id: [0; 32],
2200 short_channel_id: Some(42),
2201 remote_network_id: middle_node_id,
2202 counterparty_features: InitFeatures::from_le_bytes(vec![0b11]),
2203 channel_value_satoshis: 100000,
2205 outbound_capacity_msat: 100000,
2206 inbound_capacity_msat: 100000,
2208 counterparty_forwarding_info: None,
2210 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();
2212 assert_eq!(route.paths[0].len(), 2);
2214 assert_eq!(route.paths[0][0].pubkey, middle_node_id);
2215 assert_eq!(route.paths[0][0].short_channel_id, 42);
2216 assert_eq!(route.paths[0][0].fee_msat, 1000);
2217 assert_eq!(route.paths[0][0].cltv_expiry_delta, (8 << 8) | 1);
2218 assert_eq!(route.paths[0][0].node_features.le_flags(), &[0b11]);
2219 assert_eq!(route.paths[0][0].channel_features.le_flags(), &[0; 0]); // We can't learn any flags from invoices, sadly
2221 assert_eq!(route.paths[0][1].pubkey, target_node_id);
2222 assert_eq!(route.paths[0][1].short_channel_id, 8);
2223 assert_eq!(route.paths[0][1].fee_msat, 100);
2224 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
2225 assert_eq!(route.paths[0][1].node_features.le_flags(), &[0; 0]); // We dont pass flags in from invoices yet
2226 assert_eq!(route.paths[0][1].channel_features.le_flags(), &[0; 0]); // We can't learn any flags from invoices, sadly
2230 fn available_amount_while_routing_test() {
2231 // Tests whether we choose the correct available channel amount while routing.
2233 let (secp_ctx, mut net_graph_msg_handler, chain_monitor, logger) = build_graph();
2234 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
2236 // We will use a simple single-path route from
2237 // our node to node2 via node0: channels {1, 3}.
2239 // First disable all other paths.
2240 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2241 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2242 short_channel_id: 2,
2245 cltv_expiry_delta: 0,
2246 htlc_minimum_msat: 0,
2247 htlc_maximum_msat: OptionalField::Present(100_000),
2249 fee_proportional_millionths: 0,
2250 excess_data: Vec::new()
2252 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2253 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2254 short_channel_id: 12,
2257 cltv_expiry_delta: 0,
2258 htlc_minimum_msat: 0,
2259 htlc_maximum_msat: OptionalField::Present(100_000),
2261 fee_proportional_millionths: 0,
2262 excess_data: Vec::new()
2265 // Make the first channel (#1) very permissive,
2266 // and we will be testing all limits on the second channel.
2267 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2268 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2269 short_channel_id: 1,
2272 cltv_expiry_delta: 0,
2273 htlc_minimum_msat: 0,
2274 htlc_maximum_msat: OptionalField::Present(1_000_000_000),
2276 fee_proportional_millionths: 0,
2277 excess_data: Vec::new()
2280 // First, let's see if routing works if we have absolutely no idea about the available amount.
2281 // In this case, it should be set to 250_000 sats.
2282 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
2283 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2284 short_channel_id: 3,
2287 cltv_expiry_delta: 0,
2288 htlc_minimum_msat: 0,
2289 htlc_maximum_msat: OptionalField::Absent,
2291 fee_proportional_millionths: 0,
2292 excess_data: Vec::new()
2296 // Attempt to route more than available results in a failure.
2297 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2],
2298 Some(InvoiceFeatures::known()), None, &Vec::new(), 250_000_001, 42, Arc::clone(&logger)) {
2299 assert_eq!(err, "Failed to find a sufficient route to the given destination");
2300 } else { panic!(); }
2304 // Now, attempt to route an exact amount we have should be fine.
2305 let route = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2],
2306 Some(InvoiceFeatures::known()), None, &Vec::new(), 250_000_000, 42, Arc::clone(&logger)).unwrap();
2307 assert_eq!(route.paths.len(), 1);
2308 let path = route.paths.last().unwrap();
2309 assert_eq!(path.len(), 2);
2310 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
2311 assert_eq!(path.last().unwrap().fee_msat, 250_000_000);
2314 // Check that setting outbound_capacity_msat in first_hops limits the channels.
2315 // Disable channel #1 and use another first hop.
2316 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2317 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2318 short_channel_id: 1,
2321 cltv_expiry_delta: 0,
2322 htlc_minimum_msat: 0,
2323 htlc_maximum_msat: OptionalField::Present(1_000_000_000),
2325 fee_proportional_millionths: 0,
2326 excess_data: Vec::new()
2329 // Now, limit the first_hop by the outbound_capacity_msat of 200_000 sats.
2330 let our_chans = vec![channelmanager::ChannelDetails {
2331 channel_id: [0; 32],
2332 short_channel_id: Some(42),
2333 remote_network_id: nodes[0].clone(),
2334 counterparty_features: InitFeatures::from_le_bytes(vec![0b11]),
2335 channel_value_satoshis: 0,
2337 outbound_capacity_msat: 200_000_000,
2338 inbound_capacity_msat: 0,
2340 counterparty_forwarding_info: None,
2344 // Attempt to route more than available results in a failure.
2345 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2],
2346 Some(InvoiceFeatures::known()), Some(&our_chans.iter().collect::<Vec<_>>()), &Vec::new(), 200_000_001, 42, Arc::clone(&logger)) {
2347 assert_eq!(err, "Failed to find a sufficient route to the given destination");
2348 } else { panic!(); }
2352 // Now, attempt to route an exact amount we have should be fine.
2353 let route = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2],
2354 Some(InvoiceFeatures::known()), Some(&our_chans.iter().collect::<Vec<_>>()), &Vec::new(), 200_000_000, 42, Arc::clone(&logger)).unwrap();
2355 assert_eq!(route.paths.len(), 1);
2356 let path = route.paths.last().unwrap();
2357 assert_eq!(path.len(), 2);
2358 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
2359 assert_eq!(path.last().unwrap().fee_msat, 200_000_000);
2362 // Enable channel #1 back.
2363 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2364 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2365 short_channel_id: 1,
2368 cltv_expiry_delta: 0,
2369 htlc_minimum_msat: 0,
2370 htlc_maximum_msat: OptionalField::Present(1_000_000_000),
2372 fee_proportional_millionths: 0,
2373 excess_data: Vec::new()
2377 // Now let's see if routing works if we know only htlc_maximum_msat.
2378 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
2379 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2380 short_channel_id: 3,
2383 cltv_expiry_delta: 0,
2384 htlc_minimum_msat: 0,
2385 htlc_maximum_msat: OptionalField::Present(15_000),
2387 fee_proportional_millionths: 0,
2388 excess_data: Vec::new()
2392 // Attempt to route more than available results in a failure.
2393 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2],
2394 Some(InvoiceFeatures::known()), None, &Vec::new(), 15_001, 42, Arc::clone(&logger)) {
2395 assert_eq!(err, "Failed to find a sufficient route to the given destination");
2396 } else { panic!(); }
2400 // Now, attempt to route an exact amount we have should be fine.
2401 let route = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2],
2402 Some(InvoiceFeatures::known()), None, &Vec::new(), 15_000, 42, Arc::clone(&logger)).unwrap();
2403 assert_eq!(route.paths.len(), 1);
2404 let path = route.paths.last().unwrap();
2405 assert_eq!(path.len(), 2);
2406 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
2407 assert_eq!(path.last().unwrap().fee_msat, 15_000);
2410 // Now let's see if routing works if we know only capacity from the UTXO.
2412 // We can't change UTXO capacity on the fly, so we'll disable
2413 // the existing channel and add another one with the capacity we need.
2414 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
2415 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2416 short_channel_id: 3,
2419 cltv_expiry_delta: 0,
2420 htlc_minimum_msat: 0,
2421 htlc_maximum_msat: OptionalField::Absent,
2423 fee_proportional_millionths: 0,
2424 excess_data: Vec::new()
2427 let good_script = Builder::new().push_opcode(opcodes::all::OP_PUSHNUM_2)
2428 .push_slice(&PublicKey::from_secret_key(&secp_ctx, &privkeys[0]).serialize())
2429 .push_slice(&PublicKey::from_secret_key(&secp_ctx, &privkeys[2]).serialize())
2430 .push_opcode(opcodes::all::OP_PUSHNUM_2)
2431 .push_opcode(opcodes::all::OP_CHECKMULTISIG).into_script().to_v0_p2wsh();
2433 *chain_monitor.utxo_ret.lock().unwrap() = Ok(TxOut { value: 15, script_pubkey: good_script.clone() });
2434 net_graph_msg_handler.add_chain_access(Some(chain_monitor));
2436 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], &privkeys[2], ChannelFeatures::from_le_bytes(id_to_feature_flags(3)), 333);
2437 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
2438 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2439 short_channel_id: 333,
2442 cltv_expiry_delta: (3 << 8) | 1,
2443 htlc_minimum_msat: 0,
2444 htlc_maximum_msat: OptionalField::Absent,
2446 fee_proportional_millionths: 0,
2447 excess_data: Vec::new()
2449 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
2450 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2451 short_channel_id: 333,
2454 cltv_expiry_delta: (3 << 8) | 2,
2455 htlc_minimum_msat: 0,
2456 htlc_maximum_msat: OptionalField::Absent,
2458 fee_proportional_millionths: 0,
2459 excess_data: Vec::new()
2463 // Attempt to route more than available results in a failure.
2464 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2],
2465 Some(InvoiceFeatures::known()), None, &Vec::new(), 15_001, 42, Arc::clone(&logger)) {
2466 assert_eq!(err, "Failed to find a sufficient route to the given destination");
2467 } else { panic!(); }
2471 // Now, attempt to route an exact amount we have should be fine.
2472 let route = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2],
2473 Some(InvoiceFeatures::known()), None, &Vec::new(), 15_000, 42, Arc::clone(&logger)).unwrap();
2474 assert_eq!(route.paths.len(), 1);
2475 let path = route.paths.last().unwrap();
2476 assert_eq!(path.len(), 2);
2477 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
2478 assert_eq!(path.last().unwrap().fee_msat, 15_000);
2481 // Now let's see if routing chooses htlc_maximum_msat over UTXO capacity.
2482 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
2483 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2484 short_channel_id: 333,
2487 cltv_expiry_delta: 0,
2488 htlc_minimum_msat: 0,
2489 htlc_maximum_msat: OptionalField::Present(10_000),
2491 fee_proportional_millionths: 0,
2492 excess_data: Vec::new()
2496 // Attempt to route more than available results in a failure.
2497 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2],
2498 Some(InvoiceFeatures::known()), None, &Vec::new(), 10_001, 42, Arc::clone(&logger)) {
2499 assert_eq!(err, "Failed to find a sufficient route to the given destination");
2500 } else { panic!(); }
2504 // Now, attempt to route an exact amount we have should be fine.
2505 let route = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2],
2506 Some(InvoiceFeatures::known()), None, &Vec::new(), 10_000, 42, Arc::clone(&logger)).unwrap();
2507 assert_eq!(route.paths.len(), 1);
2508 let path = route.paths.last().unwrap();
2509 assert_eq!(path.len(), 2);
2510 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
2511 assert_eq!(path.last().unwrap().fee_msat, 10_000);
2516 fn available_liquidity_last_hop_test() {
2517 // Check that available liquidity properly limits the path even when only
2518 // one of the latter hops is limited.
2519 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
2520 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
2522 // Path via {node7, node2, node4} is channels {12, 13, 6, 11}.
2523 // {12, 13, 11} have the capacities of 100, {6} has a capacity of 50.
2524 // Total capacity: 50 sats.
2526 // Disable other potential paths.
2527 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2528 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2529 short_channel_id: 2,
2532 cltv_expiry_delta: 0,
2533 htlc_minimum_msat: 0,
2534 htlc_maximum_msat: OptionalField::Present(100_000),
2536 fee_proportional_millionths: 0,
2537 excess_data: Vec::new()
2539 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
2540 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2541 short_channel_id: 7,
2544 cltv_expiry_delta: 0,
2545 htlc_minimum_msat: 0,
2546 htlc_maximum_msat: OptionalField::Present(100_000),
2548 fee_proportional_millionths: 0,
2549 excess_data: Vec::new()
2554 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2555 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2556 short_channel_id: 12,
2559 cltv_expiry_delta: 0,
2560 htlc_minimum_msat: 0,
2561 htlc_maximum_msat: OptionalField::Present(100_000),
2563 fee_proportional_millionths: 0,
2564 excess_data: Vec::new()
2566 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
2567 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2568 short_channel_id: 13,
2571 cltv_expiry_delta: 0,
2572 htlc_minimum_msat: 0,
2573 htlc_maximum_msat: OptionalField::Present(100_000),
2575 fee_proportional_millionths: 0,
2576 excess_data: Vec::new()
2579 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
2580 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2581 short_channel_id: 6,
2584 cltv_expiry_delta: 0,
2585 htlc_minimum_msat: 0,
2586 htlc_maximum_msat: OptionalField::Present(50_000),
2588 fee_proportional_millionths: 0,
2589 excess_data: Vec::new()
2591 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
2592 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2593 short_channel_id: 11,
2596 cltv_expiry_delta: 0,
2597 htlc_minimum_msat: 0,
2598 htlc_maximum_msat: OptionalField::Present(100_000),
2600 fee_proportional_millionths: 0,
2601 excess_data: Vec::new()
2604 // Attempt to route more than available results in a failure.
2605 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[3],
2606 Some(InvoiceFeatures::known()), None, &Vec::new(), 60_000, 42, Arc::clone(&logger)) {
2607 assert_eq!(err, "Failed to find a sufficient route to the given destination");
2608 } else { panic!(); }
2612 // Now, attempt to route 49 sats (just a bit below the capacity).
2613 let route = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[3],
2614 Some(InvoiceFeatures::known()), None, &Vec::new(), 49_000, 42, Arc::clone(&logger)).unwrap();
2615 assert_eq!(route.paths.len(), 1);
2616 let mut total_amount_paid_msat = 0;
2617 for path in &route.paths {
2618 assert_eq!(path.len(), 4);
2619 assert_eq!(path.last().unwrap().pubkey, nodes[3]);
2620 total_amount_paid_msat += path.last().unwrap().fee_msat;
2622 assert_eq!(total_amount_paid_msat, 49_000);
2626 // Attempt to route an exact amount is also fine
2627 let route = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[3],
2628 Some(InvoiceFeatures::known()), None, &Vec::new(), 50_000, 42, Arc::clone(&logger)).unwrap();
2629 assert_eq!(route.paths.len(), 1);
2630 let mut total_amount_paid_msat = 0;
2631 for path in &route.paths {
2632 assert_eq!(path.len(), 4);
2633 assert_eq!(path.last().unwrap().pubkey, nodes[3]);
2634 total_amount_paid_msat += path.last().unwrap().fee_msat;
2636 assert_eq!(total_amount_paid_msat, 50_000);
2641 fn ignore_fee_first_hop_test() {
2642 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
2643 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
2645 // Path via node0 is channels {1, 3}. Limit them to 100 and 50 sats (total limit 50).
2646 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2647 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2648 short_channel_id: 1,
2651 cltv_expiry_delta: 0,
2652 htlc_minimum_msat: 0,
2653 htlc_maximum_msat: OptionalField::Present(100_000),
2654 fee_base_msat: 1_000_000,
2655 fee_proportional_millionths: 0,
2656 excess_data: Vec::new()
2658 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
2659 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2660 short_channel_id: 3,
2663 cltv_expiry_delta: 0,
2664 htlc_minimum_msat: 0,
2665 htlc_maximum_msat: OptionalField::Present(50_000),
2667 fee_proportional_millionths: 0,
2668 excess_data: Vec::new()
2672 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();
2673 assert_eq!(route.paths.len(), 1);
2674 let mut total_amount_paid_msat = 0;
2675 for path in &route.paths {
2676 assert_eq!(path.len(), 2);
2677 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
2678 total_amount_paid_msat += path.last().unwrap().fee_msat;
2680 assert_eq!(total_amount_paid_msat, 50_000);
2685 fn simple_mpp_route_test() {
2686 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
2687 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
2689 // We need a route consisting of 3 paths:
2690 // From our node to node2 via node0, node7, node1 (three paths one hop each).
2691 // To achieve this, the amount being transferred should be around
2692 // the total capacity of these 3 paths.
2694 // First, we set limits on these (previously unlimited) channels.
2695 // Their aggregate capacity will be 50 + 60 + 180 = 290 sats.
2697 // Path via node0 is channels {1, 3}. Limit them to 100 and 50 sats (total limit 50).
2698 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2699 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2700 short_channel_id: 1,
2703 cltv_expiry_delta: 0,
2704 htlc_minimum_msat: 0,
2705 htlc_maximum_msat: OptionalField::Present(100_000),
2707 fee_proportional_millionths: 0,
2708 excess_data: Vec::new()
2710 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
2711 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2712 short_channel_id: 3,
2715 cltv_expiry_delta: 0,
2716 htlc_minimum_msat: 0,
2717 htlc_maximum_msat: OptionalField::Present(50_000),
2719 fee_proportional_millionths: 0,
2720 excess_data: Vec::new()
2723 // Path via node7 is channels {12, 13}. Limit them to 60 and 60 sats
2724 // (total limit 60).
2725 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2726 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2727 short_channel_id: 12,
2730 cltv_expiry_delta: 0,
2731 htlc_minimum_msat: 0,
2732 htlc_maximum_msat: OptionalField::Present(60_000),
2734 fee_proportional_millionths: 0,
2735 excess_data: Vec::new()
2737 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
2738 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2739 short_channel_id: 13,
2742 cltv_expiry_delta: 0,
2743 htlc_minimum_msat: 0,
2744 htlc_maximum_msat: OptionalField::Present(60_000),
2746 fee_proportional_millionths: 0,
2747 excess_data: Vec::new()
2750 // Path via node1 is channels {2, 4}. Limit them to 200 and 180 sats
2751 // (total capacity 180 sats).
2752 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2753 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2754 short_channel_id: 2,
2757 cltv_expiry_delta: 0,
2758 htlc_minimum_msat: 0,
2759 htlc_maximum_msat: OptionalField::Present(200_000),
2761 fee_proportional_millionths: 0,
2762 excess_data: Vec::new()
2764 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
2765 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2766 short_channel_id: 4,
2769 cltv_expiry_delta: 0,
2770 htlc_minimum_msat: 0,
2771 htlc_maximum_msat: OptionalField::Present(180_000),
2773 fee_proportional_millionths: 0,
2774 excess_data: Vec::new()
2778 // Attempt to route more than available results in a failure.
2779 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(),
2780 &nodes[2], Some(InvoiceFeatures::known()), None, &Vec::new(), 300_000, 42, Arc::clone(&logger)) {
2781 assert_eq!(err, "Failed to find a sufficient route to the given destination");
2782 } else { panic!(); }
2786 // Now, attempt to route 250 sats (just a bit below the capacity).
2787 // Our algorithm should provide us with these 3 paths.
2788 let route = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2],
2789 Some(InvoiceFeatures::known()), None, &Vec::new(), 250_000, 42, Arc::clone(&logger)).unwrap();
2790 assert_eq!(route.paths.len(), 3);
2791 let mut total_amount_paid_msat = 0;
2792 for path in &route.paths {
2793 assert_eq!(path.len(), 2);
2794 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
2795 total_amount_paid_msat += path.last().unwrap().fee_msat;
2797 assert_eq!(total_amount_paid_msat, 250_000);
2801 // Attempt to route an exact amount is also fine
2802 let route = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2],
2803 Some(InvoiceFeatures::known()), None, &Vec::new(), 290_000, 42, Arc::clone(&logger)).unwrap();
2804 assert_eq!(route.paths.len(), 3);
2805 let mut total_amount_paid_msat = 0;
2806 for path in &route.paths {
2807 assert_eq!(path.len(), 2);
2808 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
2809 total_amount_paid_msat += path.last().unwrap().fee_msat;
2811 assert_eq!(total_amount_paid_msat, 290_000);
2816 fn long_mpp_route_test() {
2817 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
2818 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
2820 // We need a route consisting of 3 paths:
2821 // From our node to node3 via {node0, node2}, {node7, node2, node4} and {node7, node2}.
2822 // Note that these paths overlap (channels 5, 12, 13).
2823 // We will route 300 sats.
2824 // Each path will have 100 sats capacity, those channels which
2825 // are used twice will have 200 sats capacity.
2827 // Disable other potential paths.
2828 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2829 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2830 short_channel_id: 2,
2833 cltv_expiry_delta: 0,
2834 htlc_minimum_msat: 0,
2835 htlc_maximum_msat: OptionalField::Present(100_000),
2837 fee_proportional_millionths: 0,
2838 excess_data: Vec::new()
2840 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
2841 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2842 short_channel_id: 7,
2845 cltv_expiry_delta: 0,
2846 htlc_minimum_msat: 0,
2847 htlc_maximum_msat: OptionalField::Present(100_000),
2849 fee_proportional_millionths: 0,
2850 excess_data: Vec::new()
2853 // Path via {node0, node2} is channels {1, 3, 5}.
2854 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2855 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2856 short_channel_id: 1,
2859 cltv_expiry_delta: 0,
2860 htlc_minimum_msat: 0,
2861 htlc_maximum_msat: OptionalField::Present(100_000),
2863 fee_proportional_millionths: 0,
2864 excess_data: Vec::new()
2866 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
2867 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2868 short_channel_id: 3,
2871 cltv_expiry_delta: 0,
2872 htlc_minimum_msat: 0,
2873 htlc_maximum_msat: OptionalField::Present(100_000),
2875 fee_proportional_millionths: 0,
2876 excess_data: Vec::new()
2879 // Capacity of 200 sats because this channel will be used by 3rd path as well.
2880 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(5)), 5);
2881 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
2882 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2883 short_channel_id: 5,
2886 cltv_expiry_delta: 0,
2887 htlc_minimum_msat: 0,
2888 htlc_maximum_msat: OptionalField::Present(200_000),
2890 fee_proportional_millionths: 0,
2891 excess_data: Vec::new()
2894 // Path via {node7, node2, node4} is channels {12, 13, 6, 11}.
2895 // Add 100 sats to the capacities of {12, 13}, because these channels
2896 // are also used for 3rd path. 100 sats for the rest. Total capacity: 100 sats.
2897 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2898 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2899 short_channel_id: 12,
2902 cltv_expiry_delta: 0,
2903 htlc_minimum_msat: 0,
2904 htlc_maximum_msat: OptionalField::Present(200_000),
2906 fee_proportional_millionths: 0,
2907 excess_data: Vec::new()
2909 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
2910 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2911 short_channel_id: 13,
2914 cltv_expiry_delta: 0,
2915 htlc_minimum_msat: 0,
2916 htlc_maximum_msat: OptionalField::Present(200_000),
2918 fee_proportional_millionths: 0,
2919 excess_data: Vec::new()
2922 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
2923 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2924 short_channel_id: 6,
2927 cltv_expiry_delta: 0,
2928 htlc_minimum_msat: 0,
2929 htlc_maximum_msat: OptionalField::Present(100_000),
2931 fee_proportional_millionths: 0,
2932 excess_data: Vec::new()
2934 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
2935 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2936 short_channel_id: 11,
2939 cltv_expiry_delta: 0,
2940 htlc_minimum_msat: 0,
2941 htlc_maximum_msat: OptionalField::Present(100_000),
2943 fee_proportional_millionths: 0,
2944 excess_data: Vec::new()
2947 // Path via {node7, node2} is channels {12, 13, 5}.
2948 // We already limited them to 200 sats (they are used twice for 100 sats).
2949 // Nothing to do here.
2952 // Attempt to route more than available results in a failure.
2953 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[3],
2954 Some(InvoiceFeatures::known()), None, &Vec::new(), 350_000, 42, Arc::clone(&logger)) {
2955 assert_eq!(err, "Failed to find a sufficient route to the given destination");
2956 } else { panic!(); }
2960 // Now, attempt to route 300 sats (exact amount we can route).
2961 // Our algorithm should provide us with these 3 paths, 100 sats each.
2962 let route = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[3],
2963 Some(InvoiceFeatures::known()), None, &Vec::new(), 300_000, 42, Arc::clone(&logger)).unwrap();
2964 assert_eq!(route.paths.len(), 3);
2966 let mut total_amount_paid_msat = 0;
2967 for path in &route.paths {
2968 assert_eq!(path.last().unwrap().pubkey, nodes[3]);
2969 total_amount_paid_msat += path.last().unwrap().fee_msat;
2971 assert_eq!(total_amount_paid_msat, 300_000);
2977 fn mpp_cheaper_route_test() {
2978 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
2979 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
2981 // This test checks that if we have two cheaper paths and one more expensive path,
2982 // so that liquidity-wise any 2 of 3 combination is sufficient,
2983 // two cheaper paths will be taken.
2984 // These paths have equal available liquidity.
2986 // We need a combination of 3 paths:
2987 // From our node to node3 via {node0, node2}, {node7, node2, node4} and {node7, node2}.
2988 // Note that these paths overlap (channels 5, 12, 13).
2989 // Each path will have 100 sats capacity, those channels which
2990 // are used twice will have 200 sats capacity.
2992 // Disable other potential paths.
2993 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2994 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2995 short_channel_id: 2,
2998 cltv_expiry_delta: 0,
2999 htlc_minimum_msat: 0,
3000 htlc_maximum_msat: OptionalField::Present(100_000),
3002 fee_proportional_millionths: 0,
3003 excess_data: Vec::new()
3005 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3006 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3007 short_channel_id: 7,
3010 cltv_expiry_delta: 0,
3011 htlc_minimum_msat: 0,
3012 htlc_maximum_msat: OptionalField::Present(100_000),
3014 fee_proportional_millionths: 0,
3015 excess_data: Vec::new()
3018 // Path via {node0, node2} is channels {1, 3, 5}.
3019 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3020 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3021 short_channel_id: 1,
3024 cltv_expiry_delta: 0,
3025 htlc_minimum_msat: 0,
3026 htlc_maximum_msat: OptionalField::Present(100_000),
3028 fee_proportional_millionths: 0,
3029 excess_data: Vec::new()
3031 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3032 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3033 short_channel_id: 3,
3036 cltv_expiry_delta: 0,
3037 htlc_minimum_msat: 0,
3038 htlc_maximum_msat: OptionalField::Present(100_000),
3040 fee_proportional_millionths: 0,
3041 excess_data: Vec::new()
3044 // Capacity of 200 sats because this channel will be used by 3rd path as well.
3045 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(5)), 5);
3046 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3047 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3048 short_channel_id: 5,
3051 cltv_expiry_delta: 0,
3052 htlc_minimum_msat: 0,
3053 htlc_maximum_msat: OptionalField::Present(200_000),
3055 fee_proportional_millionths: 0,
3056 excess_data: Vec::new()
3059 // Path via {node7, node2, node4} is channels {12, 13, 6, 11}.
3060 // Add 100 sats to the capacities of {12, 13}, because these channels
3061 // are also used for 3rd path. 100 sats for the rest. Total capacity: 100 sats.
3062 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3063 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3064 short_channel_id: 12,
3067 cltv_expiry_delta: 0,
3068 htlc_minimum_msat: 0,
3069 htlc_maximum_msat: OptionalField::Present(200_000),
3071 fee_proportional_millionths: 0,
3072 excess_data: Vec::new()
3074 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
3075 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3076 short_channel_id: 13,
3079 cltv_expiry_delta: 0,
3080 htlc_minimum_msat: 0,
3081 htlc_maximum_msat: OptionalField::Present(200_000),
3083 fee_proportional_millionths: 0,
3084 excess_data: Vec::new()
3087 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3088 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3089 short_channel_id: 6,
3092 cltv_expiry_delta: 0,
3093 htlc_minimum_msat: 0,
3094 htlc_maximum_msat: OptionalField::Present(100_000),
3095 fee_base_msat: 1_000,
3096 fee_proportional_millionths: 0,
3097 excess_data: Vec::new()
3099 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
3100 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3101 short_channel_id: 11,
3104 cltv_expiry_delta: 0,
3105 htlc_minimum_msat: 0,
3106 htlc_maximum_msat: OptionalField::Present(100_000),
3108 fee_proportional_millionths: 0,
3109 excess_data: Vec::new()
3112 // Path via {node7, node2} is channels {12, 13, 5}.
3113 // We already limited them to 200 sats (they are used twice for 100 sats).
3114 // Nothing to do here.
3117 // Now, attempt to route 180 sats.
3118 // Our algorithm should provide us with these 2 paths.
3119 let route = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[3],
3120 Some(InvoiceFeatures::known()), None, &Vec::new(), 180_000, 42, Arc::clone(&logger)).unwrap();
3121 assert_eq!(route.paths.len(), 2);
3123 let mut total_value_transferred_msat = 0;
3124 let mut total_paid_msat = 0;
3125 for path in &route.paths {
3126 assert_eq!(path.last().unwrap().pubkey, nodes[3]);
3127 total_value_transferred_msat += path.last().unwrap().fee_msat;
3129 total_paid_msat += hop.fee_msat;
3132 // If we paid fee, this would be higher.
3133 assert_eq!(total_value_transferred_msat, 180_000);
3134 let total_fees_paid = total_paid_msat - total_value_transferred_msat;
3135 assert_eq!(total_fees_paid, 0);
3140 fn fees_on_mpp_route_test() {
3141 // This test makes sure that MPP algorithm properly takes into account
3142 // fees charged on the channels, by making the fees impactful:
3143 // if the fee is not properly accounted for, the behavior is different.
3144 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
3145 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3147 // We need a route consisting of 2 paths:
3148 // From our node to node3 via {node0, node2} and {node7, node2, node4}.
3149 // We will route 200 sats, Each path will have 100 sats capacity.
3151 // This test is not particularly stable: e.g.,
3152 // there's a way to route via {node0, node2, node4}.
3153 // It works while pathfinding is deterministic, but can be broken otherwise.
3154 // It's fine to ignore this concern for now.
3156 // Disable other potential paths.
3157 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3158 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3159 short_channel_id: 2,
3162 cltv_expiry_delta: 0,
3163 htlc_minimum_msat: 0,
3164 htlc_maximum_msat: OptionalField::Present(100_000),
3166 fee_proportional_millionths: 0,
3167 excess_data: Vec::new()
3170 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3171 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3172 short_channel_id: 7,
3175 cltv_expiry_delta: 0,
3176 htlc_minimum_msat: 0,
3177 htlc_maximum_msat: OptionalField::Present(100_000),
3179 fee_proportional_millionths: 0,
3180 excess_data: Vec::new()
3183 // Path via {node0, node2} is channels {1, 3, 5}.
3184 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3185 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3186 short_channel_id: 1,
3189 cltv_expiry_delta: 0,
3190 htlc_minimum_msat: 0,
3191 htlc_maximum_msat: OptionalField::Present(100_000),
3193 fee_proportional_millionths: 0,
3194 excess_data: Vec::new()
3196 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3197 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3198 short_channel_id: 3,
3201 cltv_expiry_delta: 0,
3202 htlc_minimum_msat: 0,
3203 htlc_maximum_msat: OptionalField::Present(100_000),
3205 fee_proportional_millionths: 0,
3206 excess_data: Vec::new()
3209 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(5)), 5);
3210 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3211 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3212 short_channel_id: 5,
3215 cltv_expiry_delta: 0,
3216 htlc_minimum_msat: 0,
3217 htlc_maximum_msat: OptionalField::Present(100_000),
3219 fee_proportional_millionths: 0,
3220 excess_data: Vec::new()
3223 // Path via {node7, node2, node4} is channels {12, 13, 6, 11}.
3224 // All channels should be 100 sats capacity. But for the fee experiment,
3225 // we'll add absolute fee of 150 sats paid for the use channel 6 (paid to node2 on channel 13).
3226 // Since channel 12 allows to deliver only 250 sats to channel 13, channel 13 can transfer only
3227 // 100 sats (and pay 150 sats in fees for the use of channel 6),
3228 // so no matter how large are other channels,
3229 // the whole path will be limited by 100 sats with just these 2 conditions:
3230 // - channel 12 capacity is 250 sats
3231 // - fee for channel 6 is 150 sats
3232 // Let's test this by enforcing these 2 conditions and removing other limits.
3233 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3234 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3235 short_channel_id: 12,
3238 cltv_expiry_delta: 0,
3239 htlc_minimum_msat: 0,
3240 htlc_maximum_msat: OptionalField::Present(250_000),
3242 fee_proportional_millionths: 0,
3243 excess_data: Vec::new()
3245 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
3246 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3247 short_channel_id: 13,
3250 cltv_expiry_delta: 0,
3251 htlc_minimum_msat: 0,
3252 htlc_maximum_msat: OptionalField::Absent,
3254 fee_proportional_millionths: 0,
3255 excess_data: Vec::new()
3258 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3259 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3260 short_channel_id: 6,
3263 cltv_expiry_delta: 0,
3264 htlc_minimum_msat: 0,
3265 htlc_maximum_msat: OptionalField::Absent,
3266 fee_base_msat: 150_000,
3267 fee_proportional_millionths: 0,
3268 excess_data: Vec::new()
3270 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
3271 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3272 short_channel_id: 11,
3275 cltv_expiry_delta: 0,
3276 htlc_minimum_msat: 0,
3277 htlc_maximum_msat: OptionalField::Absent,
3279 fee_proportional_millionths: 0,
3280 excess_data: Vec::new()
3284 // Attempt to route more than available results in a failure.
3285 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[3],
3286 Some(InvoiceFeatures::known()), None, &Vec::new(), 210_000, 42, Arc::clone(&logger)) {
3287 assert_eq!(err, "Failed to find a sufficient route to the given destination");
3288 } else { panic!(); }
3292 // Now, attempt to route 200 sats (exact amount we can route).
3293 let route = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[3],
3294 Some(InvoiceFeatures::known()), None, &Vec::new(), 200_000, 42, Arc::clone(&logger)).unwrap();
3295 assert_eq!(route.paths.len(), 2);
3297 let mut total_amount_paid_msat = 0;
3298 for path in &route.paths {
3299 assert_eq!(path.last().unwrap().pubkey, nodes[3]);
3300 total_amount_paid_msat += path.last().unwrap().fee_msat;
3302 assert_eq!(total_amount_paid_msat, 200_000);
3308 fn drop_lowest_channel_mpp_route_test() {
3309 // This test checks that low-capacity channel is dropped when after
3310 // path finding we realize that we found more capacity than we need.
3311 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
3312 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3314 // We need a route consisting of 3 paths:
3315 // From our node to node2 via node0, node7, node1 (three paths one hop each).
3317 // The first and the second paths should be sufficient, but the third should be
3318 // cheaper, so that we select it but drop later.
3320 // First, we set limits on these (previously unlimited) channels.
3321 // Their aggregate capacity will be 50 + 60 + 20 = 130 sats.
3323 // Path via node0 is channels {1, 3}. Limit them to 100 and 50 sats (total limit 50);
3324 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3325 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3326 short_channel_id: 1,
3329 cltv_expiry_delta: 0,
3330 htlc_minimum_msat: 0,
3331 htlc_maximum_msat: OptionalField::Present(100_000),
3333 fee_proportional_millionths: 0,
3334 excess_data: Vec::new()
3336 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3337 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3338 short_channel_id: 3,
3341 cltv_expiry_delta: 0,
3342 htlc_minimum_msat: 0,
3343 htlc_maximum_msat: OptionalField::Present(50_000),
3345 fee_proportional_millionths: 0,
3346 excess_data: Vec::new()
3349 // Path via node7 is channels {12, 13}. Limit them to 60 and 60 sats (total limit 60);
3350 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3351 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3352 short_channel_id: 12,
3355 cltv_expiry_delta: 0,
3356 htlc_minimum_msat: 0,
3357 htlc_maximum_msat: OptionalField::Present(60_000),
3359 fee_proportional_millionths: 0,
3360 excess_data: Vec::new()
3362 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
3363 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3364 short_channel_id: 13,
3367 cltv_expiry_delta: 0,
3368 htlc_minimum_msat: 0,
3369 htlc_maximum_msat: OptionalField::Present(60_000),
3371 fee_proportional_millionths: 0,
3372 excess_data: Vec::new()
3375 // Path via node1 is channels {2, 4}. Limit them to 20 and 20 sats (total capacity 20 sats).
3376 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3377 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3378 short_channel_id: 2,
3381 cltv_expiry_delta: 0,
3382 htlc_minimum_msat: 0,
3383 htlc_maximum_msat: OptionalField::Present(20_000),
3385 fee_proportional_millionths: 0,
3386 excess_data: Vec::new()
3388 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
3389 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3390 short_channel_id: 4,
3393 cltv_expiry_delta: 0,
3394 htlc_minimum_msat: 0,
3395 htlc_maximum_msat: OptionalField::Present(20_000),
3397 fee_proportional_millionths: 0,
3398 excess_data: Vec::new()
3402 // Attempt to route more than available results in a failure.
3403 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2],
3404 Some(InvoiceFeatures::known()), None, &Vec::new(), 150_000, 42, Arc::clone(&logger)) {
3405 assert_eq!(err, "Failed to find a sufficient route to the given destination");
3406 } else { panic!(); }
3410 // Now, attempt to route 125 sats (just a bit below the capacity of 3 channels).
3411 // Our algorithm should provide us with these 3 paths.
3412 let route = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2],
3413 Some(InvoiceFeatures::known()), None, &Vec::new(), 125_000, 42, Arc::clone(&logger)).unwrap();
3414 assert_eq!(route.paths.len(), 3);
3415 let mut total_amount_paid_msat = 0;
3416 for path in &route.paths {
3417 assert_eq!(path.len(), 2);
3418 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
3419 total_amount_paid_msat += path.last().unwrap().fee_msat;
3421 assert_eq!(total_amount_paid_msat, 125_000);
3425 // Attempt to route without the last small cheap channel
3426 let route = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2],
3427 Some(InvoiceFeatures::known()), None, &Vec::new(), 90_000, 42, Arc::clone(&logger)).unwrap();
3428 assert_eq!(route.paths.len(), 2);
3429 let mut total_amount_paid_msat = 0;
3430 for path in &route.paths {
3431 assert_eq!(path.len(), 2);
3432 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
3433 total_amount_paid_msat += path.last().unwrap().fee_msat;
3435 assert_eq!(total_amount_paid_msat, 90_000);
3440 #[cfg(all(test, feature = "unstable"))]
3443 use util::logger::{Logger, Record};
3448 struct DummyLogger {}
3449 impl Logger for DummyLogger {
3450 fn log(&self, _record: &Record) {}
3454 fn generate_routes(bench: &mut Bencher) {
3455 let mut d = File::open("net_graph-2021-02-12.bin").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");
3456 let graph = NetworkGraph::read(&mut d).unwrap();
3458 // First, get 100 (source, destination) pairs for which route-getting actually succeeds...
3459 let mut path_endpoints = Vec::new();
3460 let mut seed: usize = 0xdeadbeef;
3461 'load_endpoints: for _ in 0..100 {
3464 let src = graph.get_nodes().keys().skip(seed % graph.get_nodes().len()).next().unwrap();
3466 let dst = graph.get_nodes().keys().skip(seed % graph.get_nodes().len()).next().unwrap();
3467 let amt = seed as u64 % 1_000_000;
3468 if get_route(src, &graph, dst, None, None, &[], amt, 42, &DummyLogger{}).is_ok() {
3469 path_endpoints.push((src, dst, amt));
3470 continue 'load_endpoints;
3475 // ...then benchmark finding paths between the nodes we learned.
3478 let (src, dst, amt) = path_endpoints[idx % path_endpoints.len()];
3479 assert!(get_route(src, &graph, dst, None, None, &[], amt, 42, &DummyLogger{}).is_ok());
3485 fn generate_mpp_routes(bench: &mut Bencher) {
3486 let mut d = File::open("net_graph-2021-02-12.bin").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");
3487 let graph = NetworkGraph::read(&mut d).unwrap();
3489 // First, get 100 (source, destination) pairs for which route-getting actually succeeds...
3490 let mut path_endpoints = Vec::new();
3491 let mut seed: usize = 0xdeadbeef;
3492 'load_endpoints: for _ in 0..100 {
3495 let src = graph.get_nodes().keys().skip(seed % graph.get_nodes().len()).next().unwrap();
3497 let dst = graph.get_nodes().keys().skip(seed % graph.get_nodes().len()).next().unwrap();
3498 let amt = seed as u64 % 1_000_000;
3499 if get_route(src, &graph, dst, Some(InvoiceFeatures::known()), None, &[], amt, 42, &DummyLogger{}).is_ok() {
3500 path_endpoints.push((src, dst, amt));
3501 continue 'load_endpoints;
3506 // ...then benchmark finding paths between the nodes we learned.
3509 let (src, dst, amt) = path_endpoints[idx % path_endpoints.len()];
3510 assert!(get_route(src, &graph, dst, Some(InvoiceFeatures::known()), None, &[], amt, 42, &DummyLogger{}).is_ok());