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 const SERIALIZATION_VERSION: u8 = 1;
99 const MIN_SERIALIZATION_VERSION: u8 = 1;
101 impl Writeable for Route {
102 fn write<W: ::util::ser::Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
103 write_ver_prefix!(writer, SERIALIZATION_VERSION, MIN_SERIALIZATION_VERSION);
104 (self.paths.len() as u64).write(writer)?;
105 for hops in self.paths.iter() {
108 write_tlv_fields!(writer, {}, {});
113 impl Readable for Route {
114 fn read<R: ::std::io::Read>(reader: &mut R) -> Result<Route, DecodeError> {
115 let _ver = read_ver_prefix!(reader, SERIALIZATION_VERSION);
116 let path_count: u64 = Readable::read(reader)?;
117 let mut paths = Vec::with_capacity(cmp::min(path_count, 128) as usize);
118 for _ in 0..path_count {
119 paths.push(Readable::read(reader)?);
121 read_tlv_fields!(reader, {}, {});
126 /// A channel descriptor which provides a last-hop route to get_route
127 #[derive(Eq, PartialEq, Debug, Clone)]
128 pub struct RouteHintHop {
129 /// The node_id of the non-target end of the route
130 pub src_node_id: PublicKey,
131 /// The short_channel_id of this channel
132 pub short_channel_id: u64,
133 /// The fees which must be paid to use this channel
134 pub fees: RoutingFees,
135 /// The difference in CLTV values between this node and the next node.
136 pub cltv_expiry_delta: u16,
137 /// The minimum value, in msat, which must be relayed to the next hop.
138 pub htlc_minimum_msat: Option<u64>,
139 /// The maximum value in msat available for routing with a single HTLC.
140 pub htlc_maximum_msat: Option<u64>,
143 #[derive(Eq, PartialEq)]
144 struct RouteGraphNode {
146 lowest_fee_to_peer_through_node: u64,
147 lowest_fee_to_node: u64,
148 // The maximum value a yet-to-be-constructed payment path might flow through this node.
149 // This value is upper-bounded by us by:
150 // - how much is needed for a path being constructed
151 // - how much value can channels following this node (up to the destination) can contribute,
152 // considering their capacity and fees
153 value_contribution_msat: u64,
154 /// The effective htlc_minimum_msat at this hop. If a later hop on the path had a higher HTLC
155 /// minimum, we use it, plus the fees required at each earlier hop to meet it.
156 path_htlc_minimum_msat: u64,
159 impl cmp::Ord for RouteGraphNode {
160 fn cmp(&self, other: &RouteGraphNode) -> cmp::Ordering {
161 let other_score = cmp::max(other.lowest_fee_to_peer_through_node, other.path_htlc_minimum_msat);
162 let self_score = cmp::max(self.lowest_fee_to_peer_through_node, self.path_htlc_minimum_msat);
163 other_score.cmp(&self_score).then_with(|| other.pubkey.serialize().cmp(&self.pubkey.serialize()))
167 impl cmp::PartialOrd for RouteGraphNode {
168 fn partial_cmp(&self, other: &RouteGraphNode) -> Option<cmp::Ordering> {
169 Some(self.cmp(other))
173 struct DummyDirectionalChannelInfo {
174 cltv_expiry_delta: u32,
175 htlc_minimum_msat: u64,
176 htlc_maximum_msat: Option<u64>,
180 /// It's useful to keep track of the hops associated with the fees required to use them,
181 /// so that we can choose cheaper paths (as per Dijkstra's algorithm).
182 /// Fee values should be updated only in the context of the whole path, see update_value_and_recompute_fees.
183 /// These fee values are useful to choose hops as we traverse the graph "payee-to-payer".
185 struct PathBuildingHop<'a> {
186 // The RouteHintHop fields which will eventually be used if this hop is used in a final Route.
187 // Note that node_features is calculated separately after our initial graph walk.
189 short_channel_id: u64,
190 channel_features: &'a ChannelFeatures,
192 cltv_expiry_delta: u32,
194 /// Minimal fees required to route to the source node of the current hop via any of its inbound channels.
195 src_lowest_inbound_fees: RoutingFees,
196 /// Fees of the channel used in this hop.
197 channel_fees: RoutingFees,
198 /// All the fees paid *after* this channel on the way to the destination
199 next_hops_fee_msat: u64,
200 /// Fee paid for the use of the current channel (see channel_fees).
201 /// The value will be actually deducted from the counterparty balance on the previous link.
202 hop_use_fee_msat: u64,
203 /// Used to compare channels when choosing the for routing.
204 /// Includes paying for the use of a hop and the following hops, as well as
205 /// an estimated cost of reaching this hop.
206 /// Might get stale when fees are recomputed. Primarily for internal use.
208 /// This is useful for update_value_and_recompute_fees to make sure
209 /// we don't fall below the minimum. Should not be updated manually and
210 /// generally should not be accessed.
211 htlc_minimum_msat: u64,
212 /// A mirror of the same field in RouteGraphNode. Note that this is only used during the graph
213 /// walk and may be invalid thereafter.
214 path_htlc_minimum_msat: u64,
215 /// If we've already processed a node as the best node, we shouldn't process it again. Normally
216 /// we'd just ignore it if we did as all channels would have a higher new fee, but because we
217 /// may decrease the amounts in use as we walk the graph, the actual calculated fee may
218 /// decrease as well. Thus, we have to explicitly track which nodes have been processed and
219 /// avoid processing them again.
221 #[cfg(any(test, feature = "fuzztarget"))]
222 // In tests, we apply further sanity checks on cases where we skip nodes we already processed
223 // to ensure it is specifically in cases where the fee has gone down because of a decrease in
224 // value_contribution_msat, which requires tracking it here. See comments below where it is
225 // used for more info.
226 value_contribution_msat: u64,
229 // Instantiated with a list of hops with correct data in them collected during path finding,
230 // an instance of this struct should be further modified only via given methods.
232 struct PaymentPath<'a> {
233 hops: Vec<(PathBuildingHop<'a>, NodeFeatures)>,
236 impl<'a> PaymentPath<'a> {
237 // TODO: Add a value_msat field to PaymentPath and use it instead of this function.
238 fn get_value_msat(&self) -> u64 {
239 self.hops.last().unwrap().0.fee_msat
242 fn get_total_fee_paid_msat(&self) -> u64 {
243 if self.hops.len() < 1 {
247 // Can't use next_hops_fee_msat because it gets outdated.
248 for (i, (hop, _)) in self.hops.iter().enumerate() {
249 if i != self.hops.len() - 1 {
250 result += hop.fee_msat;
256 // If the amount transferred by the path is updated, the fees should be adjusted. Any other way
257 // to change fees may result in an inconsistency.
259 // Sometimes we call this function right after constructing a path which is inconsistent in
260 // that it the value being transferred has decreased while we were doing path finding, leading
261 // to the fees being paid not lining up with the actual limits.
263 // Note that this function is not aware of the available_liquidity limit, and thus does not
264 // support increasing the value being transferred.
265 fn update_value_and_recompute_fees(&mut self, value_msat: u64) {
266 assert!(value_msat <= self.hops.last().unwrap().0.fee_msat);
268 let mut total_fee_paid_msat = 0 as u64;
269 for i in (0..self.hops.len()).rev() {
270 let last_hop = i == self.hops.len() - 1;
272 // For non-last-hop, this value will represent the fees paid on the current hop. It
273 // will consist of the fees for the use of the next hop, and extra fees to match
274 // htlc_minimum_msat of the current channel. Last hop is handled separately.
275 let mut cur_hop_fees_msat = 0;
277 cur_hop_fees_msat = self.hops.get(i + 1).unwrap().0.hop_use_fee_msat;
280 let mut cur_hop = &mut self.hops.get_mut(i).unwrap().0;
281 cur_hop.next_hops_fee_msat = total_fee_paid_msat;
282 // Overpay in fees if we can't save these funds due to htlc_minimum_msat.
283 // We try to account for htlc_minimum_msat in scoring (add_entry!), so that nodes don't
284 // set it too high just to maliciously take more fees by exploiting this
285 // match htlc_minimum_msat logic.
286 let mut cur_hop_transferred_amount_msat = total_fee_paid_msat + value_msat;
287 if let Some(extra_fees_msat) = cur_hop.htlc_minimum_msat.checked_sub(cur_hop_transferred_amount_msat) {
288 // Note that there is a risk that *previous hops* (those closer to us, as we go
289 // payee->our_node here) would exceed their htlc_maximum_msat or available balance.
291 // This might make us end up with a broken route, although this should be super-rare
292 // in practice, both because of how healthy channels look like, and how we pick
293 // channels in add_entry.
294 // Also, this can't be exploited more heavily than *announce a free path and fail
296 cur_hop_transferred_amount_msat += extra_fees_msat;
297 total_fee_paid_msat += extra_fees_msat;
298 cur_hop_fees_msat += extra_fees_msat;
302 // Final hop is a special case: it usually has just value_msat (by design), but also
303 // it still could overpay for the htlc_minimum_msat.
304 cur_hop.fee_msat = cur_hop_transferred_amount_msat;
306 // Propagate updated fees for the use of the channels to one hop back, where they
307 // will be actually paid (fee_msat). The last hop is handled above separately.
308 cur_hop.fee_msat = cur_hop_fees_msat;
311 // Fee for the use of the current hop which will be deducted on the previous hop.
312 // Irrelevant for the first hop, as it doesn't have the previous hop, and the use of
313 // this channel is free for us.
315 if let Some(new_fee) = compute_fees(cur_hop_transferred_amount_msat, cur_hop.channel_fees) {
316 cur_hop.hop_use_fee_msat = new_fee;
317 total_fee_paid_msat += new_fee;
319 // It should not be possible because this function is called only to reduce the
320 // value. In that case, compute_fee was already called with the same fees for
321 // larger amount and there was no overflow.
329 fn compute_fees(amount_msat: u64, channel_fees: RoutingFees) -> Option<u64> {
330 let proportional_fee_millions =
331 amount_msat.checked_mul(channel_fees.proportional_millionths as u64);
332 if let Some(new_fee) = proportional_fee_millions.and_then(|part| {
333 (channel_fees.base_msat as u64).checked_add(part / 1_000_000) }) {
337 // This function may be (indirectly) called without any verification,
338 // with channel_fees provided by a caller. We should handle it gracefully.
343 /// Gets a route from us (payer) to the given target node (payee).
345 /// If the payee provided features in their invoice, they should be provided via payee_features.
346 /// Without this, MPP will only be used if the payee's features are available in the network graph.
348 /// Extra routing hops between known nodes and the target will be used if they are included in
351 /// If some channels aren't announced, it may be useful to fill in a first_hops with the
352 /// results from a local ChannelManager::list_usable_channels() call. If it is filled in, our
353 /// view of our local channels (from net_graph_msg_handler) will be ignored, and only those
354 /// in first_hops will be used.
356 /// Panics if first_hops contains channels without short_channel_ids
357 /// (ChannelManager::list_usable_channels will never include such channels).
359 /// The fees on channels from us to next-hops are ignored (as they are assumed to all be
360 /// equal), however the enabled/disabled bit on such channels as well as the
361 /// htlc_minimum_msat/htlc_maximum_msat *are* checked as they may change based on the receiving node.
362 pub fn get_route<L: Deref>(our_node_id: &PublicKey, network: &NetworkGraph, payee: &PublicKey, payee_features: Option<InvoiceFeatures>, first_hops: Option<&[&ChannelDetails]>,
363 last_hops: &[&RouteHintHop], final_value_msat: u64, final_cltv: u32, logger: L) -> Result<Route, LightningError> where L::Target: Logger {
364 // TODO: Obviously *only* using total fee cost sucks. We should consider weighting by
365 // uptime/success in using a node in the past.
366 if *payee == *our_node_id {
367 return Err(LightningError{err: "Cannot generate a route to ourselves".to_owned(), action: ErrorAction::IgnoreError});
370 if final_value_msat > MAX_VALUE_MSAT {
371 return Err(LightningError{err: "Cannot generate a route of more value than all existing satoshis".to_owned(), action: ErrorAction::IgnoreError});
374 if final_value_msat == 0 {
375 return Err(LightningError{err: "Cannot send a payment of 0 msat".to_owned(), action: ErrorAction::IgnoreError});
378 for last_hop in last_hops {
379 if last_hop.src_node_id == *payee {
380 return Err(LightningError{err: "Last hop cannot have a payee as a source.".to_owned(), action: ErrorAction::IgnoreError});
384 // The general routing idea is the following:
385 // 1. Fill first/last hops communicated by the caller.
386 // 2. Attempt to construct a path from payer to payee for transferring
387 // any ~sufficient (described later) value.
388 // If succeed, remember which channels were used and how much liquidity they have available,
389 // so that future paths don't rely on the same liquidity.
390 // 3. Prooceed to the next step if:
391 // - we hit the recommended target value;
392 // - OR if we could not construct a new path. Any next attempt will fail too.
393 // Otherwise, repeat step 2.
394 // 4. See if we managed to collect paths which aggregately are able to transfer target value
395 // (not recommended value). If yes, proceed. If not, fail routing.
396 // 5. Randomly combine paths into routes having enough to fulfill the payment. (TODO: knapsack)
397 // 6. Of all the found paths, select only those with the lowest total fee.
398 // 7. The last path in every selected route is likely to be more than we need.
399 // Reduce its value-to-transfer and recompute fees.
400 // 8. Choose the best route by the lowest total fee.
402 // As for the actual search algorithm,
403 // we do a payee-to-payer pseudo-Dijkstra's sorting by each node's distance from the payee
404 // plus the minimum per-HTLC fee to get from it to another node (aka "shitty pseudo-A*").
406 // We are not a faithful Dijkstra's implementation because we can change values which impact
407 // earlier nodes while processing later nodes. Specifically, if we reach a channel with a lower
408 // liquidity limit (via htlc_maximum_msat, on-chain capacity or assumed liquidity limits) then
409 // the value we are currently attempting to send over a path, we simply reduce the value being
410 // sent along the path for any hops after that channel. This may imply that later fees (which
411 // we've already tabulated) are lower because a smaller value is passing through the channels
412 // (and the proportional fee is thus lower). There isn't a trivial way to recalculate the
413 // channels which were selected earlier (and which may still be used for other paths without a
414 // lower liquidity limit), so we simply accept that some liquidity-limited paths may be
417 // One potentially problematic case for this algorithm would be if there are many
418 // liquidity-limited paths which are liquidity-limited near the destination (ie early in our
419 // graph walking), we may never find a path which is not liquidity-limited and has lower
420 // proportional fee (and only lower absolute fee when considering the ultimate value sent).
421 // Because we only consider paths with at least 5% of the total value being sent, the damage
422 // from such a case should be limited, however this could be further reduced in the future by
423 // calculating fees on the amount we wish to route over a path, ie ignoring the liquidity
424 // limits for the purposes of fee calculation.
426 // Alternatively, we could store more detailed path information in the heap (targets, below)
427 // and index the best-path map (dist, below) by node *and* HTLC limits, however that would blow
428 // up the runtime significantly both algorithmically (as we'd traverse nodes multiple times)
429 // and practically (as we would need to store dynamically-allocated path information in heap
430 // objects, increasing malloc traffic and indirect memory access significantly). Further, the
431 // results of such an algorithm would likely be biased towards lower-value paths.
433 // Further, we could return to a faithful Dijkstra's algorithm by rejecting paths with limits
434 // outside of our current search value, running a path search more times to gather candidate
435 // paths at different values. While this may be acceptable, further path searches may increase
436 // runtime for little gain. Specifically, the current algorithm rather efficiently explores the
437 // graph for candidate paths, calculating the maximum value which can realistically be sent at
438 // the same time, remaining generic across different payment values.
440 // TODO: There are a few tweaks we could do, including possibly pre-calculating more stuff
441 // to use as the A* heuristic beyond just the cost to get one node further than the current
444 let dummy_directional_info = DummyDirectionalChannelInfo { // used for first_hops routes
445 cltv_expiry_delta: 0,
446 htlc_minimum_msat: 0,
447 htlc_maximum_msat: None,
450 proportional_millionths: 0,
454 // Allow MPP only if we have a features set from somewhere that indicates the payee supports
455 // it. If the payee supports it they're supposed to include it in the invoice, so that should
457 let allow_mpp = if let Some(features) = &payee_features {
458 features.supports_basic_mpp()
459 } else if let Some(node) = network.get_nodes().get(&payee) {
460 if let Some(node_info) = node.announcement_info.as_ref() {
461 node_info.features.supports_basic_mpp()
466 // Prepare the data we'll use for payee-to-payer search by
467 // inserting first hops suggested by the caller as targets.
468 // Our search will then attempt to reach them while traversing from the payee node.
469 let mut first_hop_targets: HashMap<_, (_, ChannelFeatures, _, NodeFeatures)> =
470 HashMap::with_capacity(if first_hops.is_some() { first_hops.as_ref().unwrap().len() } else { 0 });
471 if let Some(hops) = first_hops {
473 let short_channel_id = chan.short_channel_id.expect("first_hops should be filled in with usable channels, not pending ones");
474 if chan.remote_network_id == *our_node_id {
475 return Err(LightningError{err: "First hop cannot have our_node_id as a destination.".to_owned(), action: ErrorAction::IgnoreError});
477 first_hop_targets.insert(chan.remote_network_id, (short_channel_id, chan.counterparty_features.to_context(), chan.outbound_capacity_msat, chan.counterparty_features.to_context()));
479 if first_hop_targets.is_empty() {
480 return Err(LightningError{err: "Cannot route when there are no outbound routes away from us".to_owned(), action: ErrorAction::IgnoreError});
484 let empty_channel_features = ChannelFeatures::empty();
486 // The main heap containing all candidate next-hops sorted by their score (max(A* fee,
487 // htlc_minimum)). Ideally this would be a heap which allowed cheap score reduction instead of
488 // adding duplicate entries when we find a better path to a given node.
489 let mut targets = BinaryHeap::new();
491 // Map from node_id to information about the best current path to that node, including feerate
493 let mut dist = HashMap::with_capacity(network.get_nodes().len());
495 // During routing, if we ignore a path due to an htlc_minimum_msat limit, we set this,
496 // indicating that we may wish to try again with a higher value, potentially paying to meet an
497 // htlc_minimum with extra fees while still finding a cheaper path.
498 let mut hit_minimum_limit;
500 // When arranging a route, we select multiple paths so that we can make a multi-path payment.
501 // We start with a path_value of the exact amount we want, and if that generates a route we may
502 // return it immediately. Otherwise, we don't stop searching for paths until we have 3x the
503 // amount we want in total across paths, selecting the best subset at the end.
504 const ROUTE_CAPACITY_PROVISION_FACTOR: u64 = 3;
505 let recommended_value_msat = final_value_msat * ROUTE_CAPACITY_PROVISION_FACTOR as u64;
506 let mut path_value_msat = final_value_msat;
508 // We don't want multiple paths (as per MPP) share liquidity of the same channels.
509 // This map allows paths to be aware of the channel use by other paths in the same call.
510 // This would help to make a better path finding decisions and not "overbook" channels.
511 // It is unaware of the directions (except for `outbound_capacity_msat` in `first_hops`).
512 let mut bookkeeped_channels_liquidity_available_msat = HashMap::with_capacity(network.get_nodes().len());
514 // Keeping track of how much value we already collected across other paths. Helps to decide:
515 // - how much a new path should be transferring (upper bound);
516 // - whether a channel should be disregarded because
517 // it's available liquidity is too small comparing to how much more we need to collect;
518 // - when we want to stop looking for new paths.
519 let mut already_collected_value_msat = 0;
521 macro_rules! add_entry {
522 // Adds entry which goes from $src_node_id to $dest_node_id
523 // over the channel with id $chan_id with fees described in
524 // $directional_info.
525 // $next_hops_fee_msat represents the fees paid for using all the channel *after* this one,
526 // since that value has to be transferred over this channel.
527 ( $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,
528 $next_hops_value_contribution: expr, $next_hops_path_htlc_minimum_msat: expr ) => {
529 // Channels to self should not be used. This is more of belt-and-suspenders, because in
530 // practice these cases should be caught earlier:
531 // - for regular channels at channel announcement (TODO)
532 // - for first and last hops early in get_route
533 if $src_node_id != $dest_node_id.clone() {
534 let available_liquidity_msat = bookkeeped_channels_liquidity_available_msat.entry($chan_id.clone()).or_insert_with(|| {
535 let mut initial_liquidity_available_msat = None;
536 if let Some(capacity_sats) = $capacity_sats {
537 initial_liquidity_available_msat = Some(capacity_sats * 1000);
540 if let Some(htlc_maximum_msat) = $directional_info.htlc_maximum_msat {
541 if let Some(available_msat) = initial_liquidity_available_msat {
542 initial_liquidity_available_msat = Some(cmp::min(available_msat, htlc_maximum_msat));
544 initial_liquidity_available_msat = Some(htlc_maximum_msat);
548 match initial_liquidity_available_msat {
549 Some(available_msat) => available_msat,
550 // We assume channels with unknown balance have
551 // a capacity of 0.0025 BTC (or 250_000 sats).
552 None => 250_000 * 1000
556 // It is tricky to substract $next_hops_fee_msat from available liquidity here.
557 // It may be misleading because we might later choose to reduce the value transferred
558 // over these channels, and the channel which was insufficient might become sufficient.
559 // Worst case: we drop a good channel here because it can't cover the high following
560 // fees caused by one expensive channel, but then this channel could have been used
561 // if the amount being transferred over this path is lower.
562 // We do this for now, but this is a subject for removal.
563 if let Some(available_value_contribution_msat) = available_liquidity_msat.checked_sub($next_hops_fee_msat) {
565 // Routing Fragmentation Mitigation heuristic:
567 // Routing fragmentation across many payment paths increases the overall routing
568 // fees as you have irreducible routing fees per-link used (`fee_base_msat`).
569 // Taking too many smaller paths also increases the chance of payment failure.
570 // Thus to avoid this effect, we require from our collected links to provide
571 // at least a minimal contribution to the recommended value yet-to-be-fulfilled.
573 // This requirement is currently 5% of the remaining-to-be-collected value.
574 // This means as we successfully advance in our collection,
575 // the absolute liquidity contribution is lowered,
576 // thus increasing the number of potential channels to be selected.
578 // Derive the minimal liquidity contribution with a ratio of 20 (5%, rounded up)
579 // or 100% if we're not allowed to do multipath payments.
580 let minimal_value_contribution_msat: u64 = if allow_mpp {
581 (recommended_value_msat - already_collected_value_msat + 19) / 20
585 // Verify the liquidity offered by this channel complies to the minimal contribution.
586 let contributes_sufficient_value = available_value_contribution_msat >= minimal_value_contribution_msat;
588 let value_contribution_msat = cmp::min(available_value_contribution_msat, $next_hops_value_contribution);
589 // Includes paying fees for the use of the following channels.
590 let amount_to_transfer_over_msat: u64 = match value_contribution_msat.checked_add($next_hops_fee_msat) {
591 Some(result) => result,
592 // Can't overflow due to how the values were computed right above.
593 None => unreachable!(),
595 #[allow(unused_comparisons)] // $next_hops_path_htlc_minimum_msat is 0 in some calls so rustc complains
596 let over_path_minimum_msat = amount_to_transfer_over_msat >= $directional_info.htlc_minimum_msat &&
597 amount_to_transfer_over_msat >= $next_hops_path_htlc_minimum_msat;
599 // If HTLC minimum is larger than the amount we're going to transfer, we shouldn't
600 // bother considering this channel.
601 // Since we're choosing amount_to_transfer_over_msat as maximum possible, it can
602 // be only reduced later (not increased), so this channel should just be skipped
603 // as not sufficient.
604 if !over_path_minimum_msat {
605 hit_minimum_limit = true;
606 } else if contributes_sufficient_value {
607 // Note that low contribution here (limited by available_liquidity_msat)
608 // might violate htlc_minimum_msat on the hops which are next along the
609 // payment path (upstream to the payee). To avoid that, we recompute path
610 // path fees knowing the final path contribution after constructing it.
611 let path_htlc_minimum_msat = match compute_fees($next_hops_path_htlc_minimum_msat, $directional_info.fees)
612 .map(|fee_msat| fee_msat.checked_add($next_hops_path_htlc_minimum_msat)) {
613 Some(Some(value_msat)) => cmp::max(value_msat, $directional_info.htlc_minimum_msat),
614 _ => u64::max_value()
616 let hm_entry = dist.entry(&$src_node_id);
617 let old_entry = hm_entry.or_insert_with(|| {
618 // If there was previously no known way to access
619 // the source node (recall it goes payee-to-payer) of $chan_id, first add
620 // a semi-dummy record just to compute the fees to reach the source node.
621 // This will affect our decision on selecting $chan_id
622 // as a way to reach the $dest_node_id.
623 let mut fee_base_msat = u32::max_value();
624 let mut fee_proportional_millionths = u32::max_value();
625 if let Some(Some(fees)) = network.get_nodes().get(&$src_node_id).map(|node| node.lowest_inbound_channel_fees) {
626 fee_base_msat = fees.base_msat;
627 fee_proportional_millionths = fees.proportional_millionths;
630 pubkey: $dest_node_id.clone(),
632 channel_features: $chan_features,
634 cltv_expiry_delta: 0,
635 src_lowest_inbound_fees: RoutingFees {
636 base_msat: fee_base_msat,
637 proportional_millionths: fee_proportional_millionths,
639 channel_fees: $directional_info.fees,
640 next_hops_fee_msat: u64::max_value(),
641 hop_use_fee_msat: u64::max_value(),
642 total_fee_msat: u64::max_value(),
643 htlc_minimum_msat: $directional_info.htlc_minimum_msat,
644 path_htlc_minimum_msat,
645 was_processed: false,
646 #[cfg(any(test, feature = "fuzztarget"))]
647 value_contribution_msat,
651 #[allow(unused_mut)] // We only use the mut in cfg(test)
652 let mut should_process = !old_entry.was_processed;
653 #[cfg(any(test, feature = "fuzztarget"))]
655 // In test/fuzzing builds, we do extra checks to make sure the skipping
656 // of already-seen nodes only happens in cases we expect (see below).
657 if !should_process { should_process = true; }
661 let mut hop_use_fee_msat = 0;
662 let mut total_fee_msat = $next_hops_fee_msat;
664 // Ignore hop_use_fee_msat for channel-from-us as we assume all channels-from-us
665 // will have the same effective-fee
666 if $src_node_id != *our_node_id {
667 match compute_fees(amount_to_transfer_over_msat, $directional_info.fees) {
668 // max_value means we'll always fail
669 // the old_entry.total_fee_msat > total_fee_msat check
670 None => total_fee_msat = u64::max_value(),
672 hop_use_fee_msat = fee_msat;
673 total_fee_msat += hop_use_fee_msat;
674 // When calculating the lowest inbound fees to a node, we
675 // calculate fees here not based on the actual value we think
676 // will flow over this channel, but on the minimum value that
677 // we'll accept flowing over it. The minimum accepted value
678 // is a constant through each path collection run, ensuring
679 // consistent basis. Otherwise we may later find a
680 // different path to the source node that is more expensive,
681 // but which we consider to be cheaper because we are capacity
682 // constrained and the relative fee becomes lower.
683 match compute_fees(minimal_value_contribution_msat, old_entry.src_lowest_inbound_fees)
684 .map(|a| a.checked_add(total_fee_msat)) {
689 total_fee_msat = u64::max_value();
696 let new_graph_node = RouteGraphNode {
697 pubkey: $src_node_id,
698 lowest_fee_to_peer_through_node: total_fee_msat,
699 lowest_fee_to_node: $next_hops_fee_msat as u64 + hop_use_fee_msat,
700 value_contribution_msat: value_contribution_msat,
701 path_htlc_minimum_msat,
704 // Update the way of reaching $src_node_id with the given $chan_id (from $dest_node_id),
705 // if this way is cheaper than the already known
706 // (considering the cost to "reach" this channel from the route destination,
707 // the cost of using this channel,
708 // and the cost of routing to the source node of this channel).
709 // Also, consider that htlc_minimum_msat_difference, because we might end up
710 // paying it. Consider the following exploit:
711 // we use 2 paths to transfer 1.5 BTC. One of them is 0-fee normal 1 BTC path,
712 // and for the other one we picked a 1sat-fee path with htlc_minimum_msat of
713 // 1 BTC. Now, since the latter is more expensive, we gonna try to cut it
714 // by 0.5 BTC, but then match htlc_minimum_msat by paying a fee of 0.5 BTC
716 // Ideally the scoring could be smarter (e.g. 0.5*htlc_minimum_msat here),
717 // but it may require additional tracking - we don't want to double-count
718 // the fees included in $next_hops_path_htlc_minimum_msat, but also
719 // can't use something that may decrease on future hops.
720 let old_cost = cmp::max(old_entry.total_fee_msat, old_entry.path_htlc_minimum_msat);
721 let new_cost = cmp::max(total_fee_msat, path_htlc_minimum_msat);
723 if !old_entry.was_processed && new_cost < old_cost {
724 targets.push(new_graph_node);
725 old_entry.next_hops_fee_msat = $next_hops_fee_msat;
726 old_entry.hop_use_fee_msat = hop_use_fee_msat;
727 old_entry.total_fee_msat = total_fee_msat;
728 old_entry.pubkey = $dest_node_id.clone();
729 old_entry.short_channel_id = $chan_id.clone();
730 old_entry.channel_features = $chan_features;
731 old_entry.fee_msat = 0; // This value will be later filled with hop_use_fee_msat of the following channel
732 old_entry.cltv_expiry_delta = $directional_info.cltv_expiry_delta as u32;
733 old_entry.channel_fees = $directional_info.fees;
734 old_entry.htlc_minimum_msat = $directional_info.htlc_minimum_msat;
735 old_entry.path_htlc_minimum_msat = path_htlc_minimum_msat;
736 #[cfg(any(test, feature = "fuzztarget"))]
738 old_entry.value_contribution_msat = value_contribution_msat;
740 } else if old_entry.was_processed && new_cost < old_cost {
741 #[cfg(any(test, feature = "fuzztarget"))]
743 // If we're skipping processing a node which was previously
744 // processed even though we found another path to it with a
745 // cheaper fee, check that it was because the second path we
746 // found (which we are processing now) has a lower value
747 // contribution due to an HTLC minimum limit.
749 // e.g. take a graph with two paths from node 1 to node 2, one
750 // through channel A, and one through channel B. Channel A and
751 // B are both in the to-process heap, with their scores set by
752 // a higher htlc_minimum than fee.
753 // Channel A is processed first, and the channels onwards from
754 // node 1 are added to the to-process heap. Thereafter, we pop
755 // Channel B off of the heap, note that it has a much more
756 // restrictive htlc_maximum_msat, and recalculate the fees for
757 // all of node 1's channels using the new, reduced, amount.
759 // This would be bogus - we'd be selecting a higher-fee path
760 // with a lower htlc_maximum_msat instead of the one we'd
761 // already decided to use.
762 debug_assert!(path_htlc_minimum_msat < old_entry.path_htlc_minimum_msat);
763 debug_assert!(value_contribution_msat < old_entry.value_contribution_msat);
773 let empty_node_features = NodeFeatures::empty();
774 // Find ways (channels with destination) to reach a given node and store them
775 // in the corresponding data structures (routing graph etc).
776 // $fee_to_target_msat represents how much it costs to reach to this node from the payee,
777 // meaning how much will be paid in fees after this node (to the best of our knowledge).
778 // This data can later be helpful to optimize routing (pay lower fees).
779 macro_rules! add_entries_to_cheapest_to_target_node {
780 ( $node: expr, $node_id: expr, $fee_to_target_msat: expr, $next_hops_value_contribution: expr, $next_hops_path_htlc_minimum_msat: expr ) => {
781 let skip_node = if let Some(elem) = dist.get_mut($node_id) {
782 let was_processed = elem.was_processed;
783 elem.was_processed = true;
786 // Entries are added to dist in add_entry!() when there is a channel from a node.
787 // Because there are no channels from payee, it will not have a dist entry at this point.
788 // If we're processing any other node, it is always be the result of a channel from it.
789 assert_eq!($node_id, payee);
794 if first_hops.is_some() {
795 if let Some(&(ref first_hop, ref features, ref outbound_capacity_msat, _)) = first_hop_targets.get(&$node_id) {
796 add_entry!(first_hop, *our_node_id, $node_id, dummy_directional_info, Some(outbound_capacity_msat / 1000), features, $fee_to_target_msat, $next_hops_value_contribution, $next_hops_path_htlc_minimum_msat);
800 let features = if let Some(node_info) = $node.announcement_info.as_ref() {
806 if !features.requires_unknown_bits() {
807 for chan_id in $node.channels.iter() {
808 let chan = network.get_channels().get(chan_id).unwrap();
809 if !chan.features.requires_unknown_bits() {
810 if chan.node_one == *$node_id {
811 // ie $node is one, ie next hop in A* is two, via the two_to_one channel
812 if first_hops.is_none() || chan.node_two != *our_node_id {
813 if let Some(two_to_one) = chan.two_to_one.as_ref() {
814 if two_to_one.enabled {
815 add_entry!(chan_id, chan.node_two, chan.node_one, two_to_one, chan.capacity_sats, &chan.features, $fee_to_target_msat, $next_hops_value_contribution, $next_hops_path_htlc_minimum_msat);
820 if first_hops.is_none() || chan.node_one != *our_node_id {
821 if let Some(one_to_two) = chan.one_to_two.as_ref() {
822 if one_to_two.enabled {
823 add_entry!(chan_id, chan.node_one, chan.node_two, one_to_two, chan.capacity_sats, &chan.features, $fee_to_target_msat, $next_hops_value_contribution, $next_hops_path_htlc_minimum_msat);
835 let mut payment_paths = Vec::<PaymentPath>::new();
837 // TODO: diversify by nodes (so that all paths aren't doomed if one node is offline).
838 'paths_collection: loop {
839 // For every new path, start from scratch, except
840 // bookkeeped_channels_liquidity_available_msat, which will improve
841 // the further iterations of path finding. Also don't erase first_hop_targets.
844 hit_minimum_limit = false;
846 // If first hop is a private channel and the only way to reach the payee, this is the only
847 // place where it could be added.
848 if first_hops.is_some() {
849 if let Some(&(ref first_hop, ref features, ref outbound_capacity_msat, _)) = first_hop_targets.get(&payee) {
850 add_entry!(first_hop, *our_node_id, payee, dummy_directional_info, Some(outbound_capacity_msat / 1000), features, 0, path_value_msat, 0);
854 // Add the payee as a target, so that the payee-to-payer
855 // search algorithm knows what to start with.
856 match network.get_nodes().get(payee) {
857 // The payee is not in our network graph, so nothing to add here.
858 // There is still a chance of reaching them via last_hops though,
859 // so don't yet fail the payment here.
860 // If not, targets.pop() will not even let us enter the loop in step 2.
863 add_entries_to_cheapest_to_target_node!(node, payee, 0, path_value_msat, 0);
868 // If a caller provided us with last hops, add them to routing targets. Since this happens
869 // earlier than general path finding, they will be somewhat prioritized, although currently
870 // it matters only if the fees are exactly the same.
871 for hop in last_hops.iter() {
872 let have_hop_src_in_graph =
873 if let Some(&(ref first_hop, ref features, ref outbound_capacity_msat, _)) = first_hop_targets.get(&hop.src_node_id) {
874 // If this hop connects to a node with which we have a direct channel, ignore
875 // the network graph and add both the hop and our direct channel to
876 // the candidate set.
878 // Currently there are no channel-context features defined, so we are a
879 // bit lazy here. In the future, we should pull them out via our
880 // ChannelManager, but there's no reason to waste the space until we
882 add_entry!(first_hop, *our_node_id , hop.src_node_id, dummy_directional_info, Some(outbound_capacity_msat / 1000), features, 0, path_value_msat, 0);
885 // In any other case, only add the hop if the source is in the regular network
887 network.get_nodes().get(&hop.src_node_id).is_some()
889 if have_hop_src_in_graph {
890 // BOLT 11 doesn't allow inclusion of features for the last hop hints, which
891 // really sucks, cause we're gonna need that eventually.
892 let last_hop_htlc_minimum_msat: u64 = match hop.htlc_minimum_msat {
893 Some(htlc_minimum_msat) => htlc_minimum_msat,
896 let directional_info = DummyDirectionalChannelInfo {
897 cltv_expiry_delta: hop.cltv_expiry_delta as u32,
898 htlc_minimum_msat: last_hop_htlc_minimum_msat,
899 htlc_maximum_msat: hop.htlc_maximum_msat,
902 add_entry!(hop.short_channel_id, hop.src_node_id, payee, directional_info, None::<u64>, &empty_channel_features, 0, path_value_msat, 0);
906 // At this point, targets are filled with the data from first and
907 // last hops communicated by the caller, and the payment receiver.
908 let mut found_new_path = false;
911 // If this loop terminates due the exhaustion of targets, two situations are possible:
912 // - not enough outgoing liquidity:
913 // 0 < already_collected_value_msat < final_value_msat
914 // - enough outgoing liquidity:
915 // final_value_msat <= already_collected_value_msat < recommended_value_msat
916 // Both these cases (and other cases except reaching recommended_value_msat) mean that
917 // paths_collection will be stopped because found_new_path==false.
918 // This is not necessarily a routing failure.
919 'path_construction: while let Some(RouteGraphNode { pubkey, lowest_fee_to_node, value_contribution_msat, path_htlc_minimum_msat, .. }) = targets.pop() {
921 // Since we're going payee-to-payer, hitting our node as a target means we should stop
922 // traversing the graph and arrange the path out of what we found.
923 if pubkey == *our_node_id {
924 let mut new_entry = dist.remove(&our_node_id).unwrap();
925 let mut ordered_hops = vec!((new_entry.clone(), NodeFeatures::empty()));
928 if let Some(&(_, _, _, ref features)) = first_hop_targets.get(&ordered_hops.last().unwrap().0.pubkey) {
929 ordered_hops.last_mut().unwrap().1 = features.clone();
930 } else if let Some(node) = network.get_nodes().get(&ordered_hops.last().unwrap().0.pubkey) {
931 if let Some(node_info) = node.announcement_info.as_ref() {
932 ordered_hops.last_mut().unwrap().1 = node_info.features.clone();
934 ordered_hops.last_mut().unwrap().1 = NodeFeatures::empty();
937 // We should be able to fill in features for everything except the last
938 // hop, if the last hop was provided via a BOLT 11 invoice (though we
939 // should be able to extend it further as BOLT 11 does have feature
940 // flags for the last hop node itself).
941 assert!(ordered_hops.last().unwrap().0.pubkey == *payee);
944 // Means we succesfully traversed from the payer to the payee, now
945 // save this path for the payment route. Also, update the liquidity
946 // remaining on the used hops, so that we take them into account
947 // while looking for more paths.
948 if ordered_hops.last().unwrap().0.pubkey == *payee {
952 new_entry = match dist.remove(&ordered_hops.last().unwrap().0.pubkey) {
953 Some(payment_hop) => payment_hop,
954 // We can't arrive at None because, if we ever add an entry to targets,
955 // we also fill in the entry in dist (see add_entry!).
956 None => unreachable!(),
958 // We "propagate" the fees one hop backward (topologically) here,
959 // so that fees paid for a HTLC forwarding on the current channel are
960 // associated with the previous channel (where they will be subtracted).
961 ordered_hops.last_mut().unwrap().0.fee_msat = new_entry.hop_use_fee_msat;
962 ordered_hops.last_mut().unwrap().0.cltv_expiry_delta = new_entry.cltv_expiry_delta;
963 ordered_hops.push((new_entry.clone(), NodeFeatures::empty()));
965 ordered_hops.last_mut().unwrap().0.fee_msat = value_contribution_msat;
966 ordered_hops.last_mut().unwrap().0.hop_use_fee_msat = 0;
967 ordered_hops.last_mut().unwrap().0.cltv_expiry_delta = final_cltv;
969 let mut payment_path = PaymentPath {hops: ordered_hops};
971 // We could have possibly constructed a slightly inconsistent path: since we reduce
972 // value being transferred along the way, we could have violated htlc_minimum_msat
973 // on some channels we already passed (assuming dest->source direction). Here, we
974 // recompute the fees again, so that if that's the case, we match the currently
975 // underpaid htlc_minimum_msat with fees.
976 payment_path.update_value_and_recompute_fees(cmp::min(value_contribution_msat, final_value_msat));
978 // Since a path allows to transfer as much value as
979 // the smallest channel it has ("bottleneck"), we should recompute
980 // the fees so sender HTLC don't overpay fees when traversing
981 // larger channels than the bottleneck. This may happen because
982 // when we were selecting those channels we were not aware how much value
983 // this path will transfer, and the relative fee for them
984 // might have been computed considering a larger value.
985 // Remember that we used these channels so that we don't rely
986 // on the same liquidity in future paths.
987 let mut prevented_redundant_path_selection = false;
988 for (payment_hop, _) in payment_path.hops.iter() {
989 let channel_liquidity_available_msat = bookkeeped_channels_liquidity_available_msat.get_mut(&payment_hop.short_channel_id).unwrap();
990 let mut spent_on_hop_msat = value_contribution_msat;
991 let next_hops_fee_msat = payment_hop.next_hops_fee_msat;
992 spent_on_hop_msat += next_hops_fee_msat;
993 if spent_on_hop_msat == *channel_liquidity_available_msat {
994 // If this path used all of this channel's available liquidity, we know
995 // this path will not be selected again in the next loop iteration.
996 prevented_redundant_path_selection = true;
998 *channel_liquidity_available_msat -= spent_on_hop_msat;
1000 if !prevented_redundant_path_selection {
1001 // If we weren't capped by hitting a liquidity limit on a channel in the path,
1002 // we'll probably end up picking the same path again on the next iteration.
1003 // Decrease the available liquidity of a hop in the middle of the path.
1004 let victim_liquidity = bookkeeped_channels_liquidity_available_msat.get_mut(
1005 &payment_path.hops[(payment_path.hops.len() - 1) / 2].0.short_channel_id).unwrap();
1006 *victim_liquidity = 0;
1009 // Track the total amount all our collected paths allow to send so that we:
1010 // - know when to stop looking for more paths
1011 // - know which of the hops are useless considering how much more sats we need
1012 // (contributes_sufficient_value)
1013 already_collected_value_msat += value_contribution_msat;
1015 payment_paths.push(payment_path);
1016 found_new_path = true;
1017 break 'path_construction;
1020 // If we found a path back to the payee, we shouldn't try to process it again. This is
1021 // the equivalent of the `elem.was_processed` check in
1022 // add_entries_to_cheapest_to_target_node!() (see comment there for more info).
1023 if pubkey == *payee { continue 'path_construction; }
1025 // Otherwise, since the current target node is not us,
1026 // keep "unrolling" the payment graph from payee to payer by
1027 // finding a way to reach the current target from the payer side.
1028 match network.get_nodes().get(&pubkey) {
1031 add_entries_to_cheapest_to_target_node!(node, &pubkey, lowest_fee_to_node, value_contribution_msat, path_htlc_minimum_msat);
1037 // If we don't support MPP, no use trying to gather more value ever.
1038 break 'paths_collection;
1042 // Stop either when the recommended value is reached or if no new path was found in this
1044 // In the latter case, making another path finding attempt won't help,
1045 // because we deterministically terminated the search due to low liquidity.
1046 if already_collected_value_msat >= recommended_value_msat || !found_new_path {
1047 break 'paths_collection;
1048 } else if found_new_path && already_collected_value_msat == final_value_msat && payment_paths.len() == 1 {
1049 // Further, if this was our first walk of the graph, and we weren't limited by an
1050 // htlc_minimum_msat, return immediately because this path should suffice. If we were
1051 // limited by an htlc_minimum_msat value, find another path with a higher value,
1052 // potentially allowing us to pay fees to meet the htlc_minimum on the new path while
1053 // still keeping a lower total fee than this path.
1054 if !hit_minimum_limit {
1055 break 'paths_collection;
1057 path_value_msat = recommended_value_msat;
1062 if payment_paths.len() == 0 {
1063 return Err(LightningError{err: "Failed to find a path to the given destination".to_owned(), action: ErrorAction::IgnoreError});
1066 if already_collected_value_msat < final_value_msat {
1067 return Err(LightningError{err: "Failed to find a sufficient route to the given destination".to_owned(), action: ErrorAction::IgnoreError});
1070 // Sort by total fees and take the best paths.
1071 payment_paths.sort_by_key(|path| path.get_total_fee_paid_msat());
1072 if payment_paths.len() > 50 {
1073 payment_paths.truncate(50);
1076 // Draw multiple sufficient routes by randomly combining the selected paths.
1077 let mut drawn_routes = Vec::new();
1078 for i in 0..payment_paths.len() {
1079 let mut cur_route = Vec::<PaymentPath>::new();
1080 let mut aggregate_route_value_msat = 0;
1083 // TODO: real random shuffle
1084 // Currently just starts with i_th and goes up to i-1_th in a looped way.
1085 let cur_payment_paths = [&payment_paths[i..], &payment_paths[..i]].concat();
1088 for payment_path in cur_payment_paths {
1089 cur_route.push(payment_path.clone());
1090 aggregate_route_value_msat += payment_path.get_value_msat();
1091 if aggregate_route_value_msat > final_value_msat {
1092 // Last path likely overpaid. Substract it from the most expensive
1093 // (in terms of proportional fee) path in this route and recompute fees.
1094 // This might be not the most economically efficient way, but fewer paths
1095 // also makes routing more reliable.
1096 let mut overpaid_value_msat = aggregate_route_value_msat - final_value_msat;
1098 // First, drop some expensive low-value paths entirely if possible.
1099 // Sort by value so that we drop many really-low values first, since
1100 // fewer paths is better: the payment is less likely to fail.
1101 // TODO: this could also be optimized by also sorting by feerate_per_sat_routed,
1102 // so that the sender pays less fees overall. And also htlc_minimum_msat.
1103 cur_route.sort_by_key(|path| path.get_value_msat());
1104 // We should make sure that at least 1 path left.
1105 let mut paths_left = cur_route.len();
1106 cur_route.retain(|path| {
1107 if paths_left == 1 {
1110 let mut keep = true;
1111 let path_value_msat = path.get_value_msat();
1112 if path_value_msat <= overpaid_value_msat {
1114 overpaid_value_msat -= path_value_msat;
1120 if overpaid_value_msat == 0 {
1124 assert!(cur_route.len() > 0);
1127 // Now, substract the overpaid value from the most-expensive path.
1128 // TODO: this could also be optimized by also sorting by feerate_per_sat_routed,
1129 // so that the sender pays less fees overall. And also htlc_minimum_msat.
1130 cur_route.sort_by_key(|path| { path.hops.iter().map(|hop| hop.0.channel_fees.proportional_millionths as u64).sum::<u64>() });
1131 let expensive_payment_path = cur_route.first_mut().unwrap();
1132 // We already dropped all the small channels above, meaning all the
1133 // remaining channels are larger than remaining overpaid_value_msat.
1134 // Thus, this can't be negative.
1135 let expensive_path_new_value_msat = expensive_payment_path.get_value_msat() - overpaid_value_msat;
1136 expensive_payment_path.update_value_and_recompute_fees(expensive_path_new_value_msat);
1140 drawn_routes.push(cur_route);
1144 // Select the best route by lowest total fee.
1145 drawn_routes.sort_by_key(|paths| paths.iter().map(|path| path.get_total_fee_paid_msat()).sum::<u64>());
1146 let mut selected_paths = Vec::<Vec<RouteHop>>::new();
1147 for payment_path in drawn_routes.first().unwrap() {
1148 selected_paths.push(payment_path.hops.iter().map(|(payment_hop, node_features)| {
1150 pubkey: payment_hop.pubkey,
1151 node_features: node_features.clone(),
1152 short_channel_id: payment_hop.short_channel_id,
1153 channel_features: payment_hop.channel_features.clone(),
1154 fee_msat: payment_hop.fee_msat,
1155 cltv_expiry_delta: payment_hop.cltv_expiry_delta,
1160 if let Some(features) = &payee_features {
1161 for path in selected_paths.iter_mut() {
1162 path.last_mut().unwrap().node_features = features.to_context();
1166 let route = Route { paths: selected_paths };
1167 log_trace!(logger, "Got route: {}", log_route!(route));
1173 use routing::router::{get_route, RouteHintHop, RoutingFees};
1174 use routing::network_graph::{NetworkGraph, NetGraphMsgHandler};
1175 use chain::transaction::OutPoint;
1176 use ln::features::{ChannelFeatures, InitFeatures, InvoiceFeatures, NodeFeatures};
1177 use ln::msgs::{ErrorAction, LightningError, OptionalField, UnsignedChannelAnnouncement, ChannelAnnouncement, RoutingMessageHandler,
1178 NodeAnnouncement, UnsignedNodeAnnouncement, ChannelUpdate, UnsignedChannelUpdate};
1179 use ln::channelmanager;
1180 use util::test_utils;
1181 use util::ser::Writeable;
1183 use bitcoin::hashes::sha256d::Hash as Sha256dHash;
1184 use bitcoin::hashes::Hash;
1185 use bitcoin::network::constants::Network;
1186 use bitcoin::blockdata::constants::genesis_block;
1187 use bitcoin::blockdata::script::Builder;
1188 use bitcoin::blockdata::opcodes;
1189 use bitcoin::blockdata::transaction::TxOut;
1193 use bitcoin::secp256k1::key::{PublicKey,SecretKey};
1194 use bitcoin::secp256k1::{Secp256k1, All};
1198 // Using the same keys for LN and BTC ids
1199 fn add_channel(net_graph_msg_handler: &NetGraphMsgHandler<Arc<test_utils::TestChainSource>, Arc<test_utils::TestLogger>>, secp_ctx: &Secp256k1<All>, node_1_privkey: &SecretKey,
1200 node_2_privkey: &SecretKey, features: ChannelFeatures, short_channel_id: u64) {
1201 let node_id_1 = PublicKey::from_secret_key(&secp_ctx, node_1_privkey);
1202 let node_id_2 = PublicKey::from_secret_key(&secp_ctx, node_2_privkey);
1204 let unsigned_announcement = UnsignedChannelAnnouncement {
1206 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1210 bitcoin_key_1: node_id_1,
1211 bitcoin_key_2: node_id_2,
1212 excess_data: Vec::new(),
1215 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1216 let valid_announcement = ChannelAnnouncement {
1217 node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
1218 node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
1219 bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
1220 bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
1221 contents: unsigned_announcement.clone(),
1223 match net_graph_msg_handler.handle_channel_announcement(&valid_announcement) {
1224 Ok(res) => assert!(res),
1229 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) {
1230 let msghash = hash_to_message!(&Sha256dHash::hash(&update.encode()[..])[..]);
1231 let valid_channel_update = ChannelUpdate {
1232 signature: secp_ctx.sign(&msghash, node_privkey),
1233 contents: update.clone()
1236 match net_graph_msg_handler.handle_channel_update(&valid_channel_update) {
1237 Ok(res) => assert!(res),
1242 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,
1243 features: NodeFeatures, timestamp: u32) {
1244 let node_id = PublicKey::from_secret_key(&secp_ctx, node_privkey);
1245 let unsigned_announcement = UnsignedNodeAnnouncement {
1251 addresses: Vec::new(),
1252 excess_address_data: Vec::new(),
1253 excess_data: Vec::new(),
1255 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1256 let valid_announcement = NodeAnnouncement {
1257 signature: secp_ctx.sign(&msghash, node_privkey),
1258 contents: unsigned_announcement.clone()
1261 match net_graph_msg_handler.handle_node_announcement(&valid_announcement) {
1267 fn get_nodes(secp_ctx: &Secp256k1<All>) -> (SecretKey, PublicKey, Vec<SecretKey>, Vec<PublicKey>) {
1268 let privkeys: Vec<SecretKey> = (2..10).map(|i| {
1269 SecretKey::from_slice(&hex::decode(format!("{:02}", i).repeat(32)).unwrap()[..]).unwrap()
1272 let pubkeys = privkeys.iter().map(|secret| PublicKey::from_secret_key(&secp_ctx, secret)).collect();
1274 let our_privkey = SecretKey::from_slice(&hex::decode("01".repeat(32)).unwrap()[..]).unwrap();
1275 let our_id = PublicKey::from_secret_key(&secp_ctx, &our_privkey);
1277 (our_privkey, our_id, privkeys, pubkeys)
1280 fn id_to_feature_flags(id: u8) -> Vec<u8> {
1281 // Set the feature flags to the id'th odd (ie non-required) feature bit so that we can
1282 // test for it later.
1283 let idx = (id - 1) * 2 + 1;
1285 vec![1 << (idx - 8*3), 0, 0, 0]
1286 } else if idx > 8*2 {
1287 vec![1 << (idx - 8*2), 0, 0]
1288 } else if idx > 8*1 {
1289 vec![1 << (idx - 8*1), 0]
1295 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>) {
1296 let secp_ctx = Secp256k1::new();
1297 let logger = Arc::new(test_utils::TestLogger::new());
1298 let chain_monitor = Arc::new(test_utils::TestChainSource::new(Network::Testnet));
1299 let net_graph_msg_handler = NetGraphMsgHandler::new(genesis_block(Network::Testnet).header.block_hash(), None, Arc::clone(&logger));
1300 // Build network from our_id to node7:
1302 // -1(1)2- node0 -1(3)2-
1304 // our_id -1(12)2- node7 -1(13)2--- node2
1306 // -1(2)2- node1 -1(4)2-
1309 // chan1 1-to-2: disabled
1310 // chan1 2-to-1: enabled, 0 fee
1312 // chan2 1-to-2: enabled, ignored fee
1313 // chan2 2-to-1: enabled, 0 fee
1315 // chan3 1-to-2: enabled, 0 fee
1316 // chan3 2-to-1: enabled, 100 msat fee
1318 // chan4 1-to-2: enabled, 100% fee
1319 // chan4 2-to-1: enabled, 0 fee
1321 // chan12 1-to-2: enabled, ignored fee
1322 // chan12 2-to-1: enabled, 0 fee
1324 // chan13 1-to-2: enabled, 200% fee
1325 // chan13 2-to-1: enabled, 0 fee
1328 // -1(5)2- node3 -1(8)2--
1332 // node2--1(6)2- node4 -1(9)2--- node6 (not in global route map)
1334 // -1(7)2- node5 -1(10)2-
1336 // chan5 1-to-2: enabled, 100 msat fee
1337 // chan5 2-to-1: enabled, 0 fee
1339 // chan6 1-to-2: enabled, 0 fee
1340 // chan6 2-to-1: enabled, 0 fee
1342 // chan7 1-to-2: enabled, 100% fee
1343 // chan7 2-to-1: enabled, 0 fee
1345 // chan8 1-to-2: enabled, variable fee (0 then 1000 msat)
1346 // chan8 2-to-1: enabled, 0 fee
1348 // chan9 1-to-2: enabled, 1001 msat fee
1349 // chan9 2-to-1: enabled, 0 fee
1351 // chan10 1-to-2: enabled, 0 fee
1352 // chan10 2-to-1: enabled, 0 fee
1354 // chan11 1-to-2: enabled, 0 fee
1355 // chan11 2-to-1: enabled, 0 fee
1357 let (our_privkey, _, privkeys, _) = get_nodes(&secp_ctx);
1359 add_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, &privkeys[0], ChannelFeatures::from_le_bytes(id_to_feature_flags(1)), 1);
1360 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
1361 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1362 short_channel_id: 1,
1365 cltv_expiry_delta: 0,
1366 htlc_minimum_msat: 0,
1367 htlc_maximum_msat: OptionalField::Absent,
1369 fee_proportional_millionths: 0,
1370 excess_data: Vec::new()
1373 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[0], NodeFeatures::from_le_bytes(id_to_feature_flags(1)), 0);
1375 add_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, &privkeys[1], ChannelFeatures::from_le_bytes(id_to_feature_flags(2)), 2);
1376 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
1377 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1378 short_channel_id: 2,
1381 cltv_expiry_delta: u16::max_value(),
1382 htlc_minimum_msat: 0,
1383 htlc_maximum_msat: OptionalField::Absent,
1384 fee_base_msat: u32::max_value(),
1385 fee_proportional_millionths: u32::max_value(),
1386 excess_data: Vec::new()
1388 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
1389 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1390 short_channel_id: 2,
1393 cltv_expiry_delta: 0,
1394 htlc_minimum_msat: 0,
1395 htlc_maximum_msat: OptionalField::Absent,
1397 fee_proportional_millionths: 0,
1398 excess_data: Vec::new()
1401 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[1], NodeFeatures::from_le_bytes(id_to_feature_flags(2)), 0);
1403 add_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, &privkeys[7], ChannelFeatures::from_le_bytes(id_to_feature_flags(12)), 12);
1404 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
1405 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1406 short_channel_id: 12,
1409 cltv_expiry_delta: u16::max_value(),
1410 htlc_minimum_msat: 0,
1411 htlc_maximum_msat: OptionalField::Absent,
1412 fee_base_msat: u32::max_value(),
1413 fee_proportional_millionths: u32::max_value(),
1414 excess_data: Vec::new()
1416 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
1417 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1418 short_channel_id: 12,
1421 cltv_expiry_delta: 0,
1422 htlc_minimum_msat: 0,
1423 htlc_maximum_msat: OptionalField::Absent,
1425 fee_proportional_millionths: 0,
1426 excess_data: Vec::new()
1429 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[7], NodeFeatures::from_le_bytes(id_to_feature_flags(8)), 0);
1431 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], &privkeys[2], ChannelFeatures::from_le_bytes(id_to_feature_flags(3)), 3);
1432 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
1433 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1434 short_channel_id: 3,
1437 cltv_expiry_delta: (3 << 8) | 1,
1438 htlc_minimum_msat: 0,
1439 htlc_maximum_msat: OptionalField::Absent,
1441 fee_proportional_millionths: 0,
1442 excess_data: Vec::new()
1444 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
1445 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1446 short_channel_id: 3,
1449 cltv_expiry_delta: (3 << 8) | 2,
1450 htlc_minimum_msat: 0,
1451 htlc_maximum_msat: OptionalField::Absent,
1453 fee_proportional_millionths: 0,
1454 excess_data: Vec::new()
1457 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], &privkeys[2], ChannelFeatures::from_le_bytes(id_to_feature_flags(4)), 4);
1458 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
1459 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1460 short_channel_id: 4,
1463 cltv_expiry_delta: (4 << 8) | 1,
1464 htlc_minimum_msat: 0,
1465 htlc_maximum_msat: OptionalField::Absent,
1467 fee_proportional_millionths: 1000000,
1468 excess_data: Vec::new()
1470 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
1471 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1472 short_channel_id: 4,
1475 cltv_expiry_delta: (4 << 8) | 2,
1476 htlc_minimum_msat: 0,
1477 htlc_maximum_msat: OptionalField::Absent,
1479 fee_proportional_millionths: 0,
1480 excess_data: Vec::new()
1483 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], &privkeys[2], ChannelFeatures::from_le_bytes(id_to_feature_flags(13)), 13);
1484 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
1485 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1486 short_channel_id: 13,
1489 cltv_expiry_delta: (13 << 8) | 1,
1490 htlc_minimum_msat: 0,
1491 htlc_maximum_msat: OptionalField::Absent,
1493 fee_proportional_millionths: 2000000,
1494 excess_data: Vec::new()
1496 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
1497 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1498 short_channel_id: 13,
1501 cltv_expiry_delta: (13 << 8) | 2,
1502 htlc_minimum_msat: 0,
1503 htlc_maximum_msat: OptionalField::Absent,
1505 fee_proportional_millionths: 0,
1506 excess_data: Vec::new()
1509 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[2], NodeFeatures::from_le_bytes(id_to_feature_flags(3)), 0);
1511 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], &privkeys[4], ChannelFeatures::from_le_bytes(id_to_feature_flags(6)), 6);
1512 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
1513 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1514 short_channel_id: 6,
1517 cltv_expiry_delta: (6 << 8) | 1,
1518 htlc_minimum_msat: 0,
1519 htlc_maximum_msat: OptionalField::Absent,
1521 fee_proportional_millionths: 0,
1522 excess_data: Vec::new()
1524 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
1525 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1526 short_channel_id: 6,
1529 cltv_expiry_delta: (6 << 8) | 2,
1530 htlc_minimum_msat: 0,
1531 htlc_maximum_msat: OptionalField::Absent,
1533 fee_proportional_millionths: 0,
1534 excess_data: Vec::new(),
1537 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(11)), 11);
1538 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
1539 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1540 short_channel_id: 11,
1543 cltv_expiry_delta: (11 << 8) | 1,
1544 htlc_minimum_msat: 0,
1545 htlc_maximum_msat: OptionalField::Absent,
1547 fee_proportional_millionths: 0,
1548 excess_data: Vec::new()
1550 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[3], UnsignedChannelUpdate {
1551 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1552 short_channel_id: 11,
1555 cltv_expiry_delta: (11 << 8) | 2,
1556 htlc_minimum_msat: 0,
1557 htlc_maximum_msat: OptionalField::Absent,
1559 fee_proportional_millionths: 0,
1560 excess_data: Vec::new()
1563 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[4], NodeFeatures::from_le_bytes(id_to_feature_flags(5)), 0);
1565 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[3], NodeFeatures::from_le_bytes(id_to_feature_flags(4)), 0);
1567 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], &privkeys[5], ChannelFeatures::from_le_bytes(id_to_feature_flags(7)), 7);
1568 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
1569 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1570 short_channel_id: 7,
1573 cltv_expiry_delta: (7 << 8) | 1,
1574 htlc_minimum_msat: 0,
1575 htlc_maximum_msat: OptionalField::Absent,
1577 fee_proportional_millionths: 1000000,
1578 excess_data: Vec::new()
1580 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[5], UnsignedChannelUpdate {
1581 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1582 short_channel_id: 7,
1585 cltv_expiry_delta: (7 << 8) | 2,
1586 htlc_minimum_msat: 0,
1587 htlc_maximum_msat: OptionalField::Absent,
1589 fee_proportional_millionths: 0,
1590 excess_data: Vec::new()
1593 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[5], NodeFeatures::from_le_bytes(id_to_feature_flags(6)), 0);
1595 (secp_ctx, net_graph_msg_handler, chain_monitor, logger)
1599 fn simple_route_test() {
1600 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
1601 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
1603 // Simple route to 2 via 1
1605 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)) {
1606 assert_eq!(err, "Cannot send a payment of 0 msat");
1607 } else { panic!(); }
1609 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();
1610 assert_eq!(route.paths[0].len(), 2);
1612 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
1613 assert_eq!(route.paths[0][0].short_channel_id, 2);
1614 assert_eq!(route.paths[0][0].fee_msat, 100);
1615 assert_eq!(route.paths[0][0].cltv_expiry_delta, (4 << 8) | 1);
1616 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
1617 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
1619 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
1620 assert_eq!(route.paths[0][1].short_channel_id, 4);
1621 assert_eq!(route.paths[0][1].fee_msat, 100);
1622 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
1623 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
1624 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
1628 fn invalid_first_hop_test() {
1629 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
1630 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
1632 // Simple route to 2 via 1
1634 let our_chans = vec![channelmanager::ChannelDetails {
1635 channel_id: [0; 32],
1636 funding_txo: Some(OutPoint { txid: bitcoin::Txid::from_slice(&[0; 32]).unwrap(), index: 0 }),
1637 short_channel_id: Some(2),
1638 remote_network_id: our_id,
1639 counterparty_features: InitFeatures::from_le_bytes(vec![0b11]),
1640 channel_value_satoshis: 100000,
1642 outbound_capacity_msat: 100000,
1643 inbound_capacity_msat: 100000,
1644 is_outbound: true, is_funding_locked: true,
1645 is_usable: true, is_public: true,
1646 counterparty_forwarding_info: None,
1649 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)) {
1650 assert_eq!(err, "First hop cannot have our_node_id as a destination.");
1651 } else { panic!(); }
1653 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();
1654 assert_eq!(route.paths[0].len(), 2);
1658 fn htlc_minimum_test() {
1659 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
1660 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
1662 // Simple route to 2 via 1
1664 // Disable other paths
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,
1669 flags: 2, // to disable
1670 cltv_expiry_delta: 0,
1671 htlc_minimum_msat: 0,
1672 htlc_maximum_msat: OptionalField::Absent,
1674 fee_proportional_millionths: 0,
1675 excess_data: Vec::new()
1677 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
1678 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1679 short_channel_id: 3,
1681 flags: 2, // to disable
1682 cltv_expiry_delta: 0,
1683 htlc_minimum_msat: 0,
1684 htlc_maximum_msat: OptionalField::Absent,
1686 fee_proportional_millionths: 0,
1687 excess_data: Vec::new()
1689 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
1690 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1691 short_channel_id: 13,
1693 flags: 2, // to disable
1694 cltv_expiry_delta: 0,
1695 htlc_minimum_msat: 0,
1696 htlc_maximum_msat: OptionalField::Absent,
1698 fee_proportional_millionths: 0,
1699 excess_data: Vec::new()
1701 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
1702 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1703 short_channel_id: 6,
1705 flags: 2, // to disable
1706 cltv_expiry_delta: 0,
1707 htlc_minimum_msat: 0,
1708 htlc_maximum_msat: OptionalField::Absent,
1710 fee_proportional_millionths: 0,
1711 excess_data: Vec::new()
1713 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
1714 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1715 short_channel_id: 7,
1717 flags: 2, // to disable
1718 cltv_expiry_delta: 0,
1719 htlc_minimum_msat: 0,
1720 htlc_maximum_msat: OptionalField::Absent,
1722 fee_proportional_millionths: 0,
1723 excess_data: Vec::new()
1726 // Check against amount_to_transfer_over_msat.
1727 // Set minimal HTLC of 200_000_000 msat.
1728 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
1729 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1730 short_channel_id: 2,
1733 cltv_expiry_delta: 0,
1734 htlc_minimum_msat: 200_000_000,
1735 htlc_maximum_msat: OptionalField::Absent,
1737 fee_proportional_millionths: 0,
1738 excess_data: Vec::new()
1741 // Second hop only allows to forward 199_999_999 at most, thus not allowing the first hop to
1743 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
1744 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1745 short_channel_id: 4,
1748 cltv_expiry_delta: 0,
1749 htlc_minimum_msat: 0,
1750 htlc_maximum_msat: OptionalField::Present(199_999_999),
1752 fee_proportional_millionths: 0,
1753 excess_data: Vec::new()
1756 // Not possible to send 199_999_999, because the minimum on channel=2 is 200_000_000.
1757 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)) {
1758 assert_eq!(err, "Failed to find a path to the given destination");
1759 } else { panic!(); }
1761 // Lift the restriction on the first hop.
1762 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
1763 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1764 short_channel_id: 2,
1767 cltv_expiry_delta: 0,
1768 htlc_minimum_msat: 0,
1769 htlc_maximum_msat: OptionalField::Absent,
1771 fee_proportional_millionths: 0,
1772 excess_data: Vec::new()
1775 // A payment above the minimum should pass
1776 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();
1777 assert_eq!(route.paths[0].len(), 2);
1781 fn htlc_minimum_overpay_test() {
1782 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
1783 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
1785 // A route to node#2 via two paths.
1786 // One path allows transferring 35-40 sats, another one also allows 35-40 sats.
1787 // Thus, they can't send 60 without overpaying.
1788 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
1789 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1790 short_channel_id: 2,
1793 cltv_expiry_delta: 0,
1794 htlc_minimum_msat: 35_000,
1795 htlc_maximum_msat: OptionalField::Present(40_000),
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,
1805 cltv_expiry_delta: 0,
1806 htlc_minimum_msat: 35_000,
1807 htlc_maximum_msat: OptionalField::Present(40_000),
1809 fee_proportional_millionths: 0,
1810 excess_data: Vec::new()
1814 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
1815 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1816 short_channel_id: 13,
1819 cltv_expiry_delta: 0,
1820 htlc_minimum_msat: 0,
1821 htlc_maximum_msat: OptionalField::Absent,
1823 fee_proportional_millionths: 0,
1824 excess_data: Vec::new()
1826 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
1827 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1828 short_channel_id: 4,
1831 cltv_expiry_delta: 0,
1832 htlc_minimum_msat: 0,
1833 htlc_maximum_msat: OptionalField::Absent,
1835 fee_proportional_millionths: 0,
1836 excess_data: Vec::new()
1839 // Disable other paths
1840 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
1841 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1842 short_channel_id: 1,
1844 flags: 2, // to disable
1845 cltv_expiry_delta: 0,
1846 htlc_minimum_msat: 0,
1847 htlc_maximum_msat: OptionalField::Absent,
1849 fee_proportional_millionths: 0,
1850 excess_data: Vec::new()
1853 let route = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2],
1854 Some(InvoiceFeatures::known()), None, &Vec::new(), 60_000, 42, Arc::clone(&logger)).unwrap();
1855 // Overpay fees to hit htlc_minimum_msat.
1856 let overpaid_fees = route.paths[0][0].fee_msat + route.paths[1][0].fee_msat;
1857 // TODO: this could be better balanced to overpay 10k and not 15k.
1858 assert_eq!(overpaid_fees, 15_000);
1860 // Now, test that if there are 2 paths, a "cheaper" by fee path wouldn't be prioritized
1861 // while taking even more fee to match htlc_minimum_msat.
1862 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
1863 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1864 short_channel_id: 12,
1867 cltv_expiry_delta: 0,
1868 htlc_minimum_msat: 65_000,
1869 htlc_maximum_msat: OptionalField::Present(80_000),
1871 fee_proportional_millionths: 0,
1872 excess_data: Vec::new()
1874 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
1875 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1876 short_channel_id: 2,
1879 cltv_expiry_delta: 0,
1880 htlc_minimum_msat: 0,
1881 htlc_maximum_msat: OptionalField::Absent,
1883 fee_proportional_millionths: 0,
1884 excess_data: Vec::new()
1886 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
1887 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1888 short_channel_id: 4,
1891 cltv_expiry_delta: 0,
1892 htlc_minimum_msat: 0,
1893 htlc_maximum_msat: OptionalField::Absent,
1895 fee_proportional_millionths: 100_000,
1896 excess_data: Vec::new()
1899 let route = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2],
1900 Some(InvoiceFeatures::known()), None, &Vec::new(), 60_000, 42, Arc::clone(&logger)).unwrap();
1901 // Fine to overpay for htlc_minimum_msat if it allows us to save fee.
1902 assert_eq!(route.paths.len(), 1);
1903 assert_eq!(route.paths[0][0].short_channel_id, 12);
1904 let fees = route.paths[0][0].fee_msat;
1905 assert_eq!(fees, 5_000);
1907 let route = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2],
1908 Some(InvoiceFeatures::known()), None, &Vec::new(), 50_000, 42, Arc::clone(&logger)).unwrap();
1909 // Not fine to overpay for htlc_minimum_msat if it requires paying more than fee on
1910 // the other channel.
1911 assert_eq!(route.paths.len(), 1);
1912 assert_eq!(route.paths[0][0].short_channel_id, 2);
1913 let fees = route.paths[0][0].fee_msat;
1914 assert_eq!(fees, 5_000);
1918 fn disable_channels_test() {
1919 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
1920 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
1922 // // Disable channels 4 and 12 by flags=2
1923 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
1924 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1925 short_channel_id: 4,
1927 flags: 2, // to disable
1928 cltv_expiry_delta: 0,
1929 htlc_minimum_msat: 0,
1930 htlc_maximum_msat: OptionalField::Absent,
1932 fee_proportional_millionths: 0,
1933 excess_data: Vec::new()
1935 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
1936 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1937 short_channel_id: 12,
1939 flags: 2, // to disable
1940 cltv_expiry_delta: 0,
1941 htlc_minimum_msat: 0,
1942 htlc_maximum_msat: OptionalField::Absent,
1944 fee_proportional_millionths: 0,
1945 excess_data: Vec::new()
1948 // If all the channels require some features we don't understand, route should fail
1949 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)) {
1950 assert_eq!(err, "Failed to find a path to the given destination");
1951 } else { panic!(); }
1953 // If we specify a channel to node7, that overrides our local channel view and that gets used
1954 let our_chans = vec![channelmanager::ChannelDetails {
1955 channel_id: [0; 32],
1956 funding_txo: Some(OutPoint { txid: bitcoin::Txid::from_slice(&[0; 32]).unwrap(), index: 0 }),
1957 short_channel_id: Some(42),
1958 remote_network_id: nodes[7].clone(),
1959 counterparty_features: InitFeatures::from_le_bytes(vec![0b11]),
1960 channel_value_satoshis: 0,
1962 outbound_capacity_msat: 250_000_000,
1963 inbound_capacity_msat: 0,
1964 is_outbound: true, is_funding_locked: true,
1965 is_usable: true, is_public: true,
1966 counterparty_forwarding_info: None,
1968 let route = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2], None, Some(&our_chans.iter().collect::<Vec<_>>()), &Vec::new(), 100, 42, Arc::clone(&logger)).unwrap();
1969 assert_eq!(route.paths[0].len(), 2);
1971 assert_eq!(route.paths[0][0].pubkey, nodes[7]);
1972 assert_eq!(route.paths[0][0].short_channel_id, 42);
1973 assert_eq!(route.paths[0][0].fee_msat, 200);
1974 assert_eq!(route.paths[0][0].cltv_expiry_delta, (13 << 8) | 1);
1975 assert_eq!(route.paths[0][0].node_features.le_flags(), &vec![0b11]); // it should also override our view of their features
1976 assert_eq!(route.paths[0][0].channel_features.le_flags(), &Vec::<u8>::new()); // No feature flags will meet the relevant-to-channel conversion
1978 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
1979 assert_eq!(route.paths[0][1].short_channel_id, 13);
1980 assert_eq!(route.paths[0][1].fee_msat, 100);
1981 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
1982 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
1983 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(13));
1987 fn disable_node_test() {
1988 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
1989 let (_, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
1991 // Disable nodes 1, 2, and 8 by requiring unknown feature bits
1992 let mut unknown_features = NodeFeatures::known();
1993 unknown_features.set_required_unknown_bits();
1994 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[0], unknown_features.clone(), 1);
1995 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[1], unknown_features.clone(), 1);
1996 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[7], unknown_features.clone(), 1);
1998 // If all nodes require some features we don't understand, route should fail
1999 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)) {
2000 assert_eq!(err, "Failed to find a path to the given destination");
2001 } else { panic!(); }
2003 // If we specify a channel to node7, that overrides our local channel view and that gets used
2004 let our_chans = vec![channelmanager::ChannelDetails {
2005 channel_id: [0; 32],
2006 funding_txo: Some(OutPoint { txid: bitcoin::Txid::from_slice(&[0; 32]).unwrap(), index: 0 }),
2007 short_channel_id: Some(42),
2008 remote_network_id: nodes[7].clone(),
2009 counterparty_features: InitFeatures::from_le_bytes(vec![0b11]),
2010 channel_value_satoshis: 0,
2012 outbound_capacity_msat: 250_000_000,
2013 inbound_capacity_msat: 0,
2014 is_outbound: true, is_funding_locked: true,
2015 is_usable: true, is_public: true,
2016 counterparty_forwarding_info: None,
2018 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();
2019 assert_eq!(route.paths[0].len(), 2);
2021 assert_eq!(route.paths[0][0].pubkey, nodes[7]);
2022 assert_eq!(route.paths[0][0].short_channel_id, 42);
2023 assert_eq!(route.paths[0][0].fee_msat, 200);
2024 assert_eq!(route.paths[0][0].cltv_expiry_delta, (13 << 8) | 1);
2025 assert_eq!(route.paths[0][0].node_features.le_flags(), &vec![0b11]); // it should also override our view of their features
2026 assert_eq!(route.paths[0][0].channel_features.le_flags(), &Vec::<u8>::new()); // No feature flags will meet the relevant-to-channel conversion
2028 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2029 assert_eq!(route.paths[0][1].short_channel_id, 13);
2030 assert_eq!(route.paths[0][1].fee_msat, 100);
2031 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
2032 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2033 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(13));
2035 // Note that we don't test disabling node 3 and failing to route to it, as we (somewhat
2036 // naively) assume that the user checked the feature bits on the invoice, which override
2037 // the node_announcement.
2041 fn our_chans_test() {
2042 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
2043 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
2045 // Route to 1 via 2 and 3 because our channel to 1 is disabled
2046 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();
2047 assert_eq!(route.paths[0].len(), 3);
2049 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
2050 assert_eq!(route.paths[0][0].short_channel_id, 2);
2051 assert_eq!(route.paths[0][0].fee_msat, 200);
2052 assert_eq!(route.paths[0][0].cltv_expiry_delta, (4 << 8) | 1);
2053 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
2054 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
2056 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2057 assert_eq!(route.paths[0][1].short_channel_id, 4);
2058 assert_eq!(route.paths[0][1].fee_msat, 100);
2059 assert_eq!(route.paths[0][1].cltv_expiry_delta, (3 << 8) | 2);
2060 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2061 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
2063 assert_eq!(route.paths[0][2].pubkey, nodes[0]);
2064 assert_eq!(route.paths[0][2].short_channel_id, 3);
2065 assert_eq!(route.paths[0][2].fee_msat, 100);
2066 assert_eq!(route.paths[0][2].cltv_expiry_delta, 42);
2067 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(1));
2068 assert_eq!(route.paths[0][2].channel_features.le_flags(), &id_to_feature_flags(3));
2070 // If we specify a channel to node7, that overrides our local channel view and that gets used
2071 let our_chans = vec![channelmanager::ChannelDetails {
2072 channel_id: [0; 32],
2073 funding_txo: Some(OutPoint { txid: bitcoin::Txid::from_slice(&[0; 32]).unwrap(), index: 0 }),
2074 short_channel_id: Some(42),
2075 remote_network_id: nodes[7].clone(),
2076 counterparty_features: InitFeatures::from_le_bytes(vec![0b11]),
2077 channel_value_satoshis: 0,
2079 outbound_capacity_msat: 250_000_000,
2080 inbound_capacity_msat: 0,
2081 is_outbound: true, is_funding_locked: true,
2082 is_usable: true, is_public: true,
2083 counterparty_forwarding_info: None,
2085 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();
2086 assert_eq!(route.paths[0].len(), 2);
2088 assert_eq!(route.paths[0][0].pubkey, nodes[7]);
2089 assert_eq!(route.paths[0][0].short_channel_id, 42);
2090 assert_eq!(route.paths[0][0].fee_msat, 200);
2091 assert_eq!(route.paths[0][0].cltv_expiry_delta, (13 << 8) | 1);
2092 assert_eq!(route.paths[0][0].node_features.le_flags(), &vec![0b11]);
2093 assert_eq!(route.paths[0][0].channel_features.le_flags(), &Vec::<u8>::new()); // No feature flags will meet the relevant-to-channel conversion
2095 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2096 assert_eq!(route.paths[0][1].short_channel_id, 13);
2097 assert_eq!(route.paths[0][1].fee_msat, 100);
2098 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
2099 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2100 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(13));
2103 fn last_hops(nodes: &Vec<PublicKey>) -> Vec<RouteHintHop> {
2104 let zero_fees = RoutingFees {
2106 proportional_millionths: 0,
2109 src_node_id: nodes[3].clone(),
2110 short_channel_id: 8,
2112 cltv_expiry_delta: (8 << 8) | 1,
2113 htlc_minimum_msat: None,
2114 htlc_maximum_msat: None,
2116 src_node_id: nodes[4].clone(),
2117 short_channel_id: 9,
2120 proportional_millionths: 0,
2122 cltv_expiry_delta: (9 << 8) | 1,
2123 htlc_minimum_msat: None,
2124 htlc_maximum_msat: None,
2126 src_node_id: nodes[5].clone(),
2127 short_channel_id: 10,
2129 cltv_expiry_delta: (10 << 8) | 1,
2130 htlc_minimum_msat: None,
2131 htlc_maximum_msat: None,
2136 fn last_hops_test() {
2137 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
2138 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
2140 // Simple test across 2, 3, 5, and 4 via a last_hop channel
2142 // First check that lst hop can't have its source as the payee.
2143 let invalid_last_hop = RouteHintHop {
2144 src_node_id: nodes[6],
2145 short_channel_id: 8,
2148 proportional_millionths: 0,
2150 cltv_expiry_delta: (8 << 8) | 1,
2151 htlc_minimum_msat: None,
2152 htlc_maximum_msat: None,
2155 let mut invalid_last_hops = last_hops(&nodes);
2156 invalid_last_hops.push(invalid_last_hop);
2158 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)) {
2159 assert_eq!(err, "Last hop cannot have a payee as a source.");
2160 } else { panic!(); }
2163 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();
2164 assert_eq!(route.paths[0].len(), 5);
2166 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
2167 assert_eq!(route.paths[0][0].short_channel_id, 2);
2168 assert_eq!(route.paths[0][0].fee_msat, 100);
2169 assert_eq!(route.paths[0][0].cltv_expiry_delta, (4 << 8) | 1);
2170 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
2171 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
2173 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2174 assert_eq!(route.paths[0][1].short_channel_id, 4);
2175 assert_eq!(route.paths[0][1].fee_msat, 0);
2176 assert_eq!(route.paths[0][1].cltv_expiry_delta, (6 << 8) | 1);
2177 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2178 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
2180 assert_eq!(route.paths[0][2].pubkey, nodes[4]);
2181 assert_eq!(route.paths[0][2].short_channel_id, 6);
2182 assert_eq!(route.paths[0][2].fee_msat, 0);
2183 assert_eq!(route.paths[0][2].cltv_expiry_delta, (11 << 8) | 1);
2184 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(5));
2185 assert_eq!(route.paths[0][2].channel_features.le_flags(), &id_to_feature_flags(6));
2187 assert_eq!(route.paths[0][3].pubkey, nodes[3]);
2188 assert_eq!(route.paths[0][3].short_channel_id, 11);
2189 assert_eq!(route.paths[0][3].fee_msat, 0);
2190 assert_eq!(route.paths[0][3].cltv_expiry_delta, (8 << 8) | 1);
2191 // If we have a peer in the node map, we'll use their features here since we don't have
2192 // a way of figuring out their features from the invoice:
2193 assert_eq!(route.paths[0][3].node_features.le_flags(), &id_to_feature_flags(4));
2194 assert_eq!(route.paths[0][3].channel_features.le_flags(), &id_to_feature_flags(11));
2196 assert_eq!(route.paths[0][4].pubkey, nodes[6]);
2197 assert_eq!(route.paths[0][4].short_channel_id, 8);
2198 assert_eq!(route.paths[0][4].fee_msat, 100);
2199 assert_eq!(route.paths[0][4].cltv_expiry_delta, 42);
2200 assert_eq!(route.paths[0][4].node_features.le_flags(), &Vec::<u8>::new()); // We dont pass flags in from invoices yet
2201 assert_eq!(route.paths[0][4].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
2205 fn our_chans_last_hop_connect_test() {
2206 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
2207 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
2209 // Simple test with outbound channel to 4 to test that last_hops and first_hops connect
2210 let our_chans = vec![channelmanager::ChannelDetails {
2211 channel_id: [0; 32],
2212 funding_txo: Some(OutPoint { txid: bitcoin::Txid::from_slice(&[0; 32]).unwrap(), index: 0 }),
2213 short_channel_id: Some(42),
2214 remote_network_id: nodes[3].clone(),
2215 counterparty_features: InitFeatures::from_le_bytes(vec![0b11]),
2216 channel_value_satoshis: 0,
2218 outbound_capacity_msat: 250_000_000,
2219 inbound_capacity_msat: 0,
2220 is_outbound: true, is_funding_locked: true,
2221 is_usable: true, is_public: true,
2222 counterparty_forwarding_info: None,
2224 let mut last_hops = last_hops(&nodes);
2225 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();
2226 assert_eq!(route.paths[0].len(), 2);
2228 assert_eq!(route.paths[0][0].pubkey, nodes[3]);
2229 assert_eq!(route.paths[0][0].short_channel_id, 42);
2230 assert_eq!(route.paths[0][0].fee_msat, 0);
2231 assert_eq!(route.paths[0][0].cltv_expiry_delta, (8 << 8) | 1);
2232 assert_eq!(route.paths[0][0].node_features.le_flags(), &vec![0b11]);
2233 assert_eq!(route.paths[0][0].channel_features.le_flags(), &Vec::<u8>::new()); // No feature flags will meet the relevant-to-channel conversion
2235 assert_eq!(route.paths[0][1].pubkey, nodes[6]);
2236 assert_eq!(route.paths[0][1].short_channel_id, 8);
2237 assert_eq!(route.paths[0][1].fee_msat, 100);
2238 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
2239 assert_eq!(route.paths[0][1].node_features.le_flags(), &Vec::<u8>::new()); // We dont pass flags in from invoices yet
2240 assert_eq!(route.paths[0][1].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
2242 last_hops[0].fees.base_msat = 1000;
2244 // Revert to via 6 as the fee on 8 goes up
2245 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();
2246 assert_eq!(route.paths[0].len(), 4);
2248 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
2249 assert_eq!(route.paths[0][0].short_channel_id, 2);
2250 assert_eq!(route.paths[0][0].fee_msat, 200); // fee increased as its % of value transferred across node
2251 assert_eq!(route.paths[0][0].cltv_expiry_delta, (4 << 8) | 1);
2252 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
2253 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
2255 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2256 assert_eq!(route.paths[0][1].short_channel_id, 4);
2257 assert_eq!(route.paths[0][1].fee_msat, 100);
2258 assert_eq!(route.paths[0][1].cltv_expiry_delta, (7 << 8) | 1);
2259 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2260 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
2262 assert_eq!(route.paths[0][2].pubkey, nodes[5]);
2263 assert_eq!(route.paths[0][2].short_channel_id, 7);
2264 assert_eq!(route.paths[0][2].fee_msat, 0);
2265 assert_eq!(route.paths[0][2].cltv_expiry_delta, (10 << 8) | 1);
2266 // If we have a peer in the node map, we'll use their features here since we don't have
2267 // a way of figuring out their features from the invoice:
2268 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(6));
2269 assert_eq!(route.paths[0][2].channel_features.le_flags(), &id_to_feature_flags(7));
2271 assert_eq!(route.paths[0][3].pubkey, nodes[6]);
2272 assert_eq!(route.paths[0][3].short_channel_id, 10);
2273 assert_eq!(route.paths[0][3].fee_msat, 100);
2274 assert_eq!(route.paths[0][3].cltv_expiry_delta, 42);
2275 assert_eq!(route.paths[0][3].node_features.le_flags(), &Vec::<u8>::new()); // We dont pass flags in from invoices yet
2276 assert_eq!(route.paths[0][3].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
2278 // ...but still use 8 for larger payments as 6 has a variable feerate
2279 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();
2280 assert_eq!(route.paths[0].len(), 5);
2282 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
2283 assert_eq!(route.paths[0][0].short_channel_id, 2);
2284 assert_eq!(route.paths[0][0].fee_msat, 3000);
2285 assert_eq!(route.paths[0][0].cltv_expiry_delta, (4 << 8) | 1);
2286 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
2287 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
2289 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2290 assert_eq!(route.paths[0][1].short_channel_id, 4);
2291 assert_eq!(route.paths[0][1].fee_msat, 0);
2292 assert_eq!(route.paths[0][1].cltv_expiry_delta, (6 << 8) | 1);
2293 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2294 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
2296 assert_eq!(route.paths[0][2].pubkey, nodes[4]);
2297 assert_eq!(route.paths[0][2].short_channel_id, 6);
2298 assert_eq!(route.paths[0][2].fee_msat, 0);
2299 assert_eq!(route.paths[0][2].cltv_expiry_delta, (11 << 8) | 1);
2300 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(5));
2301 assert_eq!(route.paths[0][2].channel_features.le_flags(), &id_to_feature_flags(6));
2303 assert_eq!(route.paths[0][3].pubkey, nodes[3]);
2304 assert_eq!(route.paths[0][3].short_channel_id, 11);
2305 assert_eq!(route.paths[0][3].fee_msat, 1000);
2306 assert_eq!(route.paths[0][3].cltv_expiry_delta, (8 << 8) | 1);
2307 // If we have a peer in the node map, we'll use their features here since we don't have
2308 // a way of figuring out their features from the invoice:
2309 assert_eq!(route.paths[0][3].node_features.le_flags(), &id_to_feature_flags(4));
2310 assert_eq!(route.paths[0][3].channel_features.le_flags(), &id_to_feature_flags(11));
2312 assert_eq!(route.paths[0][4].pubkey, nodes[6]);
2313 assert_eq!(route.paths[0][4].short_channel_id, 8);
2314 assert_eq!(route.paths[0][4].fee_msat, 2000);
2315 assert_eq!(route.paths[0][4].cltv_expiry_delta, 42);
2316 assert_eq!(route.paths[0][4].node_features.le_flags(), &Vec::<u8>::new()); // We dont pass flags in from invoices yet
2317 assert_eq!(route.paths[0][4].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
2321 fn unannounced_path_test() {
2322 // We should be able to send a payment to a destination without any help of a routing graph
2323 // if we have a channel with a common counterparty that appears in the first and last hop
2325 let source_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&hex::decode(format!("{:02}", 41).repeat(32)).unwrap()[..]).unwrap());
2326 let middle_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&hex::decode(format!("{:02}", 42).repeat(32)).unwrap()[..]).unwrap());
2327 let target_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&hex::decode(format!("{:02}", 43).repeat(32)).unwrap()[..]).unwrap());
2329 // If we specify a channel to a middle hop, that overrides our local channel view and that gets used
2330 let last_hops = vec![RouteHintHop {
2331 src_node_id: middle_node_id,
2332 short_channel_id: 8,
2335 proportional_millionths: 0,
2337 cltv_expiry_delta: (8 << 8) | 1,
2338 htlc_minimum_msat: None,
2339 htlc_maximum_msat: None,
2341 let our_chans = vec![channelmanager::ChannelDetails {
2342 channel_id: [0; 32],
2343 funding_txo: Some(OutPoint { txid: bitcoin::Txid::from_slice(&[0; 32]).unwrap(), index: 0 }),
2344 short_channel_id: Some(42),
2345 remote_network_id: middle_node_id,
2346 counterparty_features: InitFeatures::from_le_bytes(vec![0b11]),
2347 channel_value_satoshis: 100000,
2349 outbound_capacity_msat: 100000,
2350 inbound_capacity_msat: 100000,
2351 is_outbound: true, is_funding_locked: true,
2352 is_usable: true, is_public: true,
2353 counterparty_forwarding_info: None,
2355 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();
2357 assert_eq!(route.paths[0].len(), 2);
2359 assert_eq!(route.paths[0][0].pubkey, middle_node_id);
2360 assert_eq!(route.paths[0][0].short_channel_id, 42);
2361 assert_eq!(route.paths[0][0].fee_msat, 1000);
2362 assert_eq!(route.paths[0][0].cltv_expiry_delta, (8 << 8) | 1);
2363 assert_eq!(route.paths[0][0].node_features.le_flags(), &[0b11]);
2364 assert_eq!(route.paths[0][0].channel_features.le_flags(), &[0; 0]); // We can't learn any flags from invoices, sadly
2366 assert_eq!(route.paths[0][1].pubkey, target_node_id);
2367 assert_eq!(route.paths[0][1].short_channel_id, 8);
2368 assert_eq!(route.paths[0][1].fee_msat, 100);
2369 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
2370 assert_eq!(route.paths[0][1].node_features.le_flags(), &[0; 0]); // We dont pass flags in from invoices yet
2371 assert_eq!(route.paths[0][1].channel_features.le_flags(), &[0; 0]); // We can't learn any flags from invoices, sadly
2375 fn available_amount_while_routing_test() {
2376 // Tests whether we choose the correct available channel amount while routing.
2378 let (secp_ctx, mut net_graph_msg_handler, chain_monitor, logger) = build_graph();
2379 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
2381 // We will use a simple single-path route from
2382 // our node to node2 via node0: channels {1, 3}.
2384 // First disable all other paths.
2385 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2386 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2387 short_channel_id: 2,
2390 cltv_expiry_delta: 0,
2391 htlc_minimum_msat: 0,
2392 htlc_maximum_msat: OptionalField::Present(100_000),
2394 fee_proportional_millionths: 0,
2395 excess_data: Vec::new()
2397 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2398 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2399 short_channel_id: 12,
2402 cltv_expiry_delta: 0,
2403 htlc_minimum_msat: 0,
2404 htlc_maximum_msat: OptionalField::Present(100_000),
2406 fee_proportional_millionths: 0,
2407 excess_data: Vec::new()
2410 // Make the first channel (#1) very permissive,
2411 // and we will be testing all limits on the second channel.
2412 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2413 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2414 short_channel_id: 1,
2417 cltv_expiry_delta: 0,
2418 htlc_minimum_msat: 0,
2419 htlc_maximum_msat: OptionalField::Present(1_000_000_000),
2421 fee_proportional_millionths: 0,
2422 excess_data: Vec::new()
2425 // First, let's see if routing works if we have absolutely no idea about the available amount.
2426 // In this case, it should be set to 250_000 sats.
2427 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
2428 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2429 short_channel_id: 3,
2432 cltv_expiry_delta: 0,
2433 htlc_minimum_msat: 0,
2434 htlc_maximum_msat: OptionalField::Absent,
2436 fee_proportional_millionths: 0,
2437 excess_data: Vec::new()
2441 // Attempt to route more than available results in a failure.
2442 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2],
2443 Some(InvoiceFeatures::known()), None, &Vec::new(), 250_000_001, 42, Arc::clone(&logger)) {
2444 assert_eq!(err, "Failed to find a sufficient route to the given destination");
2445 } else { panic!(); }
2449 // Now, attempt to route an exact amount we have should be fine.
2450 let route = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2],
2451 Some(InvoiceFeatures::known()), None, &Vec::new(), 250_000_000, 42, Arc::clone(&logger)).unwrap();
2452 assert_eq!(route.paths.len(), 1);
2453 let path = route.paths.last().unwrap();
2454 assert_eq!(path.len(), 2);
2455 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
2456 assert_eq!(path.last().unwrap().fee_msat, 250_000_000);
2459 // Check that setting outbound_capacity_msat in first_hops limits the channels.
2460 // Disable channel #1 and use another first hop.
2461 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2462 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2463 short_channel_id: 1,
2466 cltv_expiry_delta: 0,
2467 htlc_minimum_msat: 0,
2468 htlc_maximum_msat: OptionalField::Present(1_000_000_000),
2470 fee_proportional_millionths: 0,
2471 excess_data: Vec::new()
2474 // Now, limit the first_hop by the outbound_capacity_msat of 200_000 sats.
2475 let our_chans = vec![channelmanager::ChannelDetails {
2476 channel_id: [0; 32],
2477 funding_txo: Some(OutPoint { txid: bitcoin::Txid::from_slice(&[0; 32]).unwrap(), index: 0 }),
2478 short_channel_id: Some(42),
2479 remote_network_id: nodes[0].clone(),
2480 counterparty_features: InitFeatures::from_le_bytes(vec![0b11]),
2481 channel_value_satoshis: 0,
2483 outbound_capacity_msat: 200_000_000,
2484 inbound_capacity_msat: 0,
2485 is_outbound: true, is_funding_locked: true,
2486 is_usable: true, is_public: true,
2487 counterparty_forwarding_info: None,
2491 // Attempt to route more than available results in a failure.
2492 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2],
2493 Some(InvoiceFeatures::known()), Some(&our_chans.iter().collect::<Vec<_>>()), &Vec::new(), 200_000_001, 42, Arc::clone(&logger)) {
2494 assert_eq!(err, "Failed to find a sufficient route to the given destination");
2495 } else { panic!(); }
2499 // Now, attempt to route an exact amount we have should be fine.
2500 let route = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2],
2501 Some(InvoiceFeatures::known()), Some(&our_chans.iter().collect::<Vec<_>>()), &Vec::new(), 200_000_000, 42, Arc::clone(&logger)).unwrap();
2502 assert_eq!(route.paths.len(), 1);
2503 let path = route.paths.last().unwrap();
2504 assert_eq!(path.len(), 2);
2505 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
2506 assert_eq!(path.last().unwrap().fee_msat, 200_000_000);
2509 // Enable channel #1 back.
2510 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2511 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2512 short_channel_id: 1,
2515 cltv_expiry_delta: 0,
2516 htlc_minimum_msat: 0,
2517 htlc_maximum_msat: OptionalField::Present(1_000_000_000),
2519 fee_proportional_millionths: 0,
2520 excess_data: Vec::new()
2524 // Now let's see if routing works if we know only htlc_maximum_msat.
2525 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
2526 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2527 short_channel_id: 3,
2530 cltv_expiry_delta: 0,
2531 htlc_minimum_msat: 0,
2532 htlc_maximum_msat: OptionalField::Present(15_000),
2534 fee_proportional_millionths: 0,
2535 excess_data: Vec::new()
2539 // Attempt to route more than available results in a failure.
2540 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2],
2541 Some(InvoiceFeatures::known()), None, &Vec::new(), 15_001, 42, Arc::clone(&logger)) {
2542 assert_eq!(err, "Failed to find a sufficient route to the given destination");
2543 } else { panic!(); }
2547 // Now, attempt to route an exact amount we have should be fine.
2548 let route = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2],
2549 Some(InvoiceFeatures::known()), None, &Vec::new(), 15_000, 42, Arc::clone(&logger)).unwrap();
2550 assert_eq!(route.paths.len(), 1);
2551 let path = route.paths.last().unwrap();
2552 assert_eq!(path.len(), 2);
2553 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
2554 assert_eq!(path.last().unwrap().fee_msat, 15_000);
2557 // Now let's see if routing works if we know only capacity from the UTXO.
2559 // We can't change UTXO capacity on the fly, so we'll disable
2560 // the existing channel and add another one with the capacity we need.
2561 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
2562 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2563 short_channel_id: 3,
2566 cltv_expiry_delta: 0,
2567 htlc_minimum_msat: 0,
2568 htlc_maximum_msat: OptionalField::Absent,
2570 fee_proportional_millionths: 0,
2571 excess_data: Vec::new()
2574 let good_script = Builder::new().push_opcode(opcodes::all::OP_PUSHNUM_2)
2575 .push_slice(&PublicKey::from_secret_key(&secp_ctx, &privkeys[0]).serialize())
2576 .push_slice(&PublicKey::from_secret_key(&secp_ctx, &privkeys[2]).serialize())
2577 .push_opcode(opcodes::all::OP_PUSHNUM_2)
2578 .push_opcode(opcodes::all::OP_CHECKMULTISIG).into_script().to_v0_p2wsh();
2580 *chain_monitor.utxo_ret.lock().unwrap() = Ok(TxOut { value: 15, script_pubkey: good_script.clone() });
2581 net_graph_msg_handler.add_chain_access(Some(chain_monitor));
2583 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], &privkeys[2], ChannelFeatures::from_le_bytes(id_to_feature_flags(3)), 333);
2584 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
2585 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2586 short_channel_id: 333,
2589 cltv_expiry_delta: (3 << 8) | 1,
2590 htlc_minimum_msat: 0,
2591 htlc_maximum_msat: OptionalField::Absent,
2593 fee_proportional_millionths: 0,
2594 excess_data: Vec::new()
2596 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
2597 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2598 short_channel_id: 333,
2601 cltv_expiry_delta: (3 << 8) | 2,
2602 htlc_minimum_msat: 0,
2603 htlc_maximum_msat: OptionalField::Absent,
2605 fee_proportional_millionths: 0,
2606 excess_data: Vec::new()
2610 // Attempt to route more than available results in a failure.
2611 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2],
2612 Some(InvoiceFeatures::known()), None, &Vec::new(), 15_001, 42, Arc::clone(&logger)) {
2613 assert_eq!(err, "Failed to find a sufficient route to the given destination");
2614 } else { panic!(); }
2618 // Now, attempt to route an exact amount we have should be fine.
2619 let route = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2],
2620 Some(InvoiceFeatures::known()), None, &Vec::new(), 15_000, 42, Arc::clone(&logger)).unwrap();
2621 assert_eq!(route.paths.len(), 1);
2622 let path = route.paths.last().unwrap();
2623 assert_eq!(path.len(), 2);
2624 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
2625 assert_eq!(path.last().unwrap().fee_msat, 15_000);
2628 // Now let's see if routing chooses htlc_maximum_msat over UTXO capacity.
2629 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
2630 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2631 short_channel_id: 333,
2634 cltv_expiry_delta: 0,
2635 htlc_minimum_msat: 0,
2636 htlc_maximum_msat: OptionalField::Present(10_000),
2638 fee_proportional_millionths: 0,
2639 excess_data: Vec::new()
2643 // Attempt to route more than available results in a failure.
2644 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2],
2645 Some(InvoiceFeatures::known()), None, &Vec::new(), 10_001, 42, Arc::clone(&logger)) {
2646 assert_eq!(err, "Failed to find a sufficient route to the given destination");
2647 } else { panic!(); }
2651 // Now, attempt to route an exact amount we have should be fine.
2652 let route = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2],
2653 Some(InvoiceFeatures::known()), None, &Vec::new(), 10_000, 42, Arc::clone(&logger)).unwrap();
2654 assert_eq!(route.paths.len(), 1);
2655 let path = route.paths.last().unwrap();
2656 assert_eq!(path.len(), 2);
2657 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
2658 assert_eq!(path.last().unwrap().fee_msat, 10_000);
2663 fn available_liquidity_last_hop_test() {
2664 // Check that available liquidity properly limits the path even when only
2665 // one of the latter hops is limited.
2666 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
2667 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
2669 // Path via {node7, node2, node4} is channels {12, 13, 6, 11}.
2670 // {12, 13, 11} have the capacities of 100, {6} has a capacity of 50.
2671 // Total capacity: 50 sats.
2673 // Disable other potential paths.
2674 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2675 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2676 short_channel_id: 2,
2679 cltv_expiry_delta: 0,
2680 htlc_minimum_msat: 0,
2681 htlc_maximum_msat: OptionalField::Present(100_000),
2683 fee_proportional_millionths: 0,
2684 excess_data: Vec::new()
2686 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
2687 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2688 short_channel_id: 7,
2691 cltv_expiry_delta: 0,
2692 htlc_minimum_msat: 0,
2693 htlc_maximum_msat: OptionalField::Present(100_000),
2695 fee_proportional_millionths: 0,
2696 excess_data: Vec::new()
2701 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2702 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2703 short_channel_id: 12,
2706 cltv_expiry_delta: 0,
2707 htlc_minimum_msat: 0,
2708 htlc_maximum_msat: OptionalField::Present(100_000),
2710 fee_proportional_millionths: 0,
2711 excess_data: Vec::new()
2713 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
2714 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2715 short_channel_id: 13,
2718 cltv_expiry_delta: 0,
2719 htlc_minimum_msat: 0,
2720 htlc_maximum_msat: OptionalField::Present(100_000),
2722 fee_proportional_millionths: 0,
2723 excess_data: Vec::new()
2726 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
2727 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2728 short_channel_id: 6,
2731 cltv_expiry_delta: 0,
2732 htlc_minimum_msat: 0,
2733 htlc_maximum_msat: OptionalField::Present(50_000),
2735 fee_proportional_millionths: 0,
2736 excess_data: Vec::new()
2738 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
2739 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2740 short_channel_id: 11,
2743 cltv_expiry_delta: 0,
2744 htlc_minimum_msat: 0,
2745 htlc_maximum_msat: OptionalField::Present(100_000),
2747 fee_proportional_millionths: 0,
2748 excess_data: Vec::new()
2751 // Attempt to route more than available results in a failure.
2752 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[3],
2753 Some(InvoiceFeatures::known()), None, &Vec::new(), 60_000, 42, Arc::clone(&logger)) {
2754 assert_eq!(err, "Failed to find a sufficient route to the given destination");
2755 } else { panic!(); }
2759 // Now, attempt to route 49 sats (just a bit below the capacity).
2760 let route = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[3],
2761 Some(InvoiceFeatures::known()), None, &Vec::new(), 49_000, 42, Arc::clone(&logger)).unwrap();
2762 assert_eq!(route.paths.len(), 1);
2763 let mut total_amount_paid_msat = 0;
2764 for path in &route.paths {
2765 assert_eq!(path.len(), 4);
2766 assert_eq!(path.last().unwrap().pubkey, nodes[3]);
2767 total_amount_paid_msat += path.last().unwrap().fee_msat;
2769 assert_eq!(total_amount_paid_msat, 49_000);
2773 // Attempt to route an exact amount is also fine
2774 let route = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[3],
2775 Some(InvoiceFeatures::known()), None, &Vec::new(), 50_000, 42, Arc::clone(&logger)).unwrap();
2776 assert_eq!(route.paths.len(), 1);
2777 let mut total_amount_paid_msat = 0;
2778 for path in &route.paths {
2779 assert_eq!(path.len(), 4);
2780 assert_eq!(path.last().unwrap().pubkey, nodes[3]);
2781 total_amount_paid_msat += path.last().unwrap().fee_msat;
2783 assert_eq!(total_amount_paid_msat, 50_000);
2788 fn ignore_fee_first_hop_test() {
2789 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
2790 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
2792 // Path via node0 is channels {1, 3}. Limit them to 100 and 50 sats (total limit 50).
2793 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2794 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2795 short_channel_id: 1,
2798 cltv_expiry_delta: 0,
2799 htlc_minimum_msat: 0,
2800 htlc_maximum_msat: OptionalField::Present(100_000),
2801 fee_base_msat: 1_000_000,
2802 fee_proportional_millionths: 0,
2803 excess_data: Vec::new()
2805 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
2806 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2807 short_channel_id: 3,
2810 cltv_expiry_delta: 0,
2811 htlc_minimum_msat: 0,
2812 htlc_maximum_msat: OptionalField::Present(50_000),
2814 fee_proportional_millionths: 0,
2815 excess_data: Vec::new()
2819 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();
2820 assert_eq!(route.paths.len(), 1);
2821 let mut total_amount_paid_msat = 0;
2822 for path in &route.paths {
2823 assert_eq!(path.len(), 2);
2824 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
2825 total_amount_paid_msat += path.last().unwrap().fee_msat;
2827 assert_eq!(total_amount_paid_msat, 50_000);
2832 fn simple_mpp_route_test() {
2833 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
2834 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
2836 // We need a route consisting of 3 paths:
2837 // From our node to node2 via node0, node7, node1 (three paths one hop each).
2838 // To achieve this, the amount being transferred should be around
2839 // the total capacity of these 3 paths.
2841 // First, we set limits on these (previously unlimited) channels.
2842 // Their aggregate capacity will be 50 + 60 + 180 = 290 sats.
2844 // Path via node0 is channels {1, 3}. Limit them to 100 and 50 sats (total limit 50).
2845 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2846 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2847 short_channel_id: 1,
2850 cltv_expiry_delta: 0,
2851 htlc_minimum_msat: 0,
2852 htlc_maximum_msat: OptionalField::Present(100_000),
2854 fee_proportional_millionths: 0,
2855 excess_data: Vec::new()
2857 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
2858 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2859 short_channel_id: 3,
2862 cltv_expiry_delta: 0,
2863 htlc_minimum_msat: 0,
2864 htlc_maximum_msat: OptionalField::Present(50_000),
2866 fee_proportional_millionths: 0,
2867 excess_data: Vec::new()
2870 // Path via node7 is channels {12, 13}. Limit them to 60 and 60 sats
2871 // (total limit 60).
2872 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2873 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2874 short_channel_id: 12,
2877 cltv_expiry_delta: 0,
2878 htlc_minimum_msat: 0,
2879 htlc_maximum_msat: OptionalField::Present(60_000),
2881 fee_proportional_millionths: 0,
2882 excess_data: Vec::new()
2884 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
2885 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2886 short_channel_id: 13,
2889 cltv_expiry_delta: 0,
2890 htlc_minimum_msat: 0,
2891 htlc_maximum_msat: OptionalField::Present(60_000),
2893 fee_proportional_millionths: 0,
2894 excess_data: Vec::new()
2897 // Path via node1 is channels {2, 4}. Limit them to 200 and 180 sats
2898 // (total capacity 180 sats).
2899 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2900 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2901 short_channel_id: 2,
2904 cltv_expiry_delta: 0,
2905 htlc_minimum_msat: 0,
2906 htlc_maximum_msat: OptionalField::Present(200_000),
2908 fee_proportional_millionths: 0,
2909 excess_data: Vec::new()
2911 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
2912 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2913 short_channel_id: 4,
2916 cltv_expiry_delta: 0,
2917 htlc_minimum_msat: 0,
2918 htlc_maximum_msat: OptionalField::Present(180_000),
2920 fee_proportional_millionths: 0,
2921 excess_data: Vec::new()
2925 // Attempt to route more than available results in a failure.
2926 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(),
2927 &nodes[2], Some(InvoiceFeatures::known()), None, &Vec::new(), 300_000, 42, Arc::clone(&logger)) {
2928 assert_eq!(err, "Failed to find a sufficient route to the given destination");
2929 } else { panic!(); }
2933 // Now, attempt to route 250 sats (just a bit below the capacity).
2934 // Our algorithm should provide us with these 3 paths.
2935 let route = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2],
2936 Some(InvoiceFeatures::known()), None, &Vec::new(), 250_000, 42, Arc::clone(&logger)).unwrap();
2937 assert_eq!(route.paths.len(), 3);
2938 let mut total_amount_paid_msat = 0;
2939 for path in &route.paths {
2940 assert_eq!(path.len(), 2);
2941 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
2942 total_amount_paid_msat += path.last().unwrap().fee_msat;
2944 assert_eq!(total_amount_paid_msat, 250_000);
2948 // Attempt to route an exact amount is also fine
2949 let route = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2],
2950 Some(InvoiceFeatures::known()), None, &Vec::new(), 290_000, 42, Arc::clone(&logger)).unwrap();
2951 assert_eq!(route.paths.len(), 3);
2952 let mut total_amount_paid_msat = 0;
2953 for path in &route.paths {
2954 assert_eq!(path.len(), 2);
2955 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
2956 total_amount_paid_msat += path.last().unwrap().fee_msat;
2958 assert_eq!(total_amount_paid_msat, 290_000);
2963 fn long_mpp_route_test() {
2964 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
2965 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
2967 // We need a route consisting of 3 paths:
2968 // From our node to node3 via {node0, node2}, {node7, node2, node4} and {node7, node2}.
2969 // Note that these paths overlap (channels 5, 12, 13).
2970 // We will route 300 sats.
2971 // Each path will have 100 sats capacity, those channels which
2972 // are used twice will have 200 sats capacity.
2974 // Disable other potential paths.
2975 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2976 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2977 short_channel_id: 2,
2980 cltv_expiry_delta: 0,
2981 htlc_minimum_msat: 0,
2982 htlc_maximum_msat: OptionalField::Present(100_000),
2984 fee_proportional_millionths: 0,
2985 excess_data: Vec::new()
2987 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
2988 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2989 short_channel_id: 7,
2992 cltv_expiry_delta: 0,
2993 htlc_minimum_msat: 0,
2994 htlc_maximum_msat: OptionalField::Present(100_000),
2996 fee_proportional_millionths: 0,
2997 excess_data: Vec::new()
3000 // Path via {node0, node2} is channels {1, 3, 5}.
3001 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3002 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3003 short_channel_id: 1,
3006 cltv_expiry_delta: 0,
3007 htlc_minimum_msat: 0,
3008 htlc_maximum_msat: OptionalField::Present(100_000),
3010 fee_proportional_millionths: 0,
3011 excess_data: Vec::new()
3013 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3014 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3015 short_channel_id: 3,
3018 cltv_expiry_delta: 0,
3019 htlc_minimum_msat: 0,
3020 htlc_maximum_msat: OptionalField::Present(100_000),
3022 fee_proportional_millionths: 0,
3023 excess_data: Vec::new()
3026 // Capacity of 200 sats because this channel will be used by 3rd path as well.
3027 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(5)), 5);
3028 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3029 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3030 short_channel_id: 5,
3033 cltv_expiry_delta: 0,
3034 htlc_minimum_msat: 0,
3035 htlc_maximum_msat: OptionalField::Present(200_000),
3037 fee_proportional_millionths: 0,
3038 excess_data: Vec::new()
3041 // Path via {node7, node2, node4} is channels {12, 13, 6, 11}.
3042 // Add 100 sats to the capacities of {12, 13}, because these channels
3043 // are also used for 3rd path. 100 sats for the rest. Total capacity: 100 sats.
3044 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3045 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3046 short_channel_id: 12,
3049 cltv_expiry_delta: 0,
3050 htlc_minimum_msat: 0,
3051 htlc_maximum_msat: OptionalField::Present(200_000),
3053 fee_proportional_millionths: 0,
3054 excess_data: Vec::new()
3056 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
3057 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3058 short_channel_id: 13,
3061 cltv_expiry_delta: 0,
3062 htlc_minimum_msat: 0,
3063 htlc_maximum_msat: OptionalField::Present(200_000),
3065 fee_proportional_millionths: 0,
3066 excess_data: Vec::new()
3069 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3070 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3071 short_channel_id: 6,
3074 cltv_expiry_delta: 0,
3075 htlc_minimum_msat: 0,
3076 htlc_maximum_msat: OptionalField::Present(100_000),
3078 fee_proportional_millionths: 0,
3079 excess_data: Vec::new()
3081 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
3082 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3083 short_channel_id: 11,
3086 cltv_expiry_delta: 0,
3087 htlc_minimum_msat: 0,
3088 htlc_maximum_msat: OptionalField::Present(100_000),
3090 fee_proportional_millionths: 0,
3091 excess_data: Vec::new()
3094 // Path via {node7, node2} is channels {12, 13, 5}.
3095 // We already limited them to 200 sats (they are used twice for 100 sats).
3096 // Nothing to do here.
3099 // Attempt to route more than available results in a failure.
3100 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[3],
3101 Some(InvoiceFeatures::known()), None, &Vec::new(), 350_000, 42, Arc::clone(&logger)) {
3102 assert_eq!(err, "Failed to find a sufficient route to the given destination");
3103 } else { panic!(); }
3107 // Now, attempt to route 300 sats (exact amount we can route).
3108 // Our algorithm should provide us with these 3 paths, 100 sats each.
3109 let route = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[3],
3110 Some(InvoiceFeatures::known()), None, &Vec::new(), 300_000, 42, Arc::clone(&logger)).unwrap();
3111 assert_eq!(route.paths.len(), 3);
3113 let mut total_amount_paid_msat = 0;
3114 for path in &route.paths {
3115 assert_eq!(path.last().unwrap().pubkey, nodes[3]);
3116 total_amount_paid_msat += path.last().unwrap().fee_msat;
3118 assert_eq!(total_amount_paid_msat, 300_000);
3124 fn mpp_cheaper_route_test() {
3125 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
3126 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3128 // This test checks that if we have two cheaper paths and one more expensive path,
3129 // so that liquidity-wise any 2 of 3 combination is sufficient,
3130 // two cheaper paths will be taken.
3131 // These paths have equal available liquidity.
3133 // We need a combination of 3 paths:
3134 // From our node to node3 via {node0, node2}, {node7, node2, node4} and {node7, node2}.
3135 // Note that these paths overlap (channels 5, 12, 13).
3136 // Each path will have 100 sats capacity, those channels which
3137 // are used twice will have 200 sats capacity.
3139 // Disable other potential paths.
3140 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3141 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3142 short_channel_id: 2,
3145 cltv_expiry_delta: 0,
3146 htlc_minimum_msat: 0,
3147 htlc_maximum_msat: OptionalField::Present(100_000),
3149 fee_proportional_millionths: 0,
3150 excess_data: Vec::new()
3152 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3153 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3154 short_channel_id: 7,
3157 cltv_expiry_delta: 0,
3158 htlc_minimum_msat: 0,
3159 htlc_maximum_msat: OptionalField::Present(100_000),
3161 fee_proportional_millionths: 0,
3162 excess_data: Vec::new()
3165 // Path via {node0, node2} is channels {1, 3, 5}.
3166 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3167 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3168 short_channel_id: 1,
3171 cltv_expiry_delta: 0,
3172 htlc_minimum_msat: 0,
3173 htlc_maximum_msat: OptionalField::Present(100_000),
3175 fee_proportional_millionths: 0,
3176 excess_data: Vec::new()
3178 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3179 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3180 short_channel_id: 3,
3183 cltv_expiry_delta: 0,
3184 htlc_minimum_msat: 0,
3185 htlc_maximum_msat: OptionalField::Present(100_000),
3187 fee_proportional_millionths: 0,
3188 excess_data: Vec::new()
3191 // Capacity of 200 sats because this channel will be used by 3rd path as well.
3192 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(5)), 5);
3193 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3194 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3195 short_channel_id: 5,
3198 cltv_expiry_delta: 0,
3199 htlc_minimum_msat: 0,
3200 htlc_maximum_msat: OptionalField::Present(200_000),
3202 fee_proportional_millionths: 0,
3203 excess_data: Vec::new()
3206 // Path via {node7, node2, node4} is channels {12, 13, 6, 11}.
3207 // Add 100 sats to the capacities of {12, 13}, because these channels
3208 // are also used for 3rd path. 100 sats for the rest. Total capacity: 100 sats.
3209 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3210 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3211 short_channel_id: 12,
3214 cltv_expiry_delta: 0,
3215 htlc_minimum_msat: 0,
3216 htlc_maximum_msat: OptionalField::Present(200_000),
3218 fee_proportional_millionths: 0,
3219 excess_data: Vec::new()
3221 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
3222 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3223 short_channel_id: 13,
3226 cltv_expiry_delta: 0,
3227 htlc_minimum_msat: 0,
3228 htlc_maximum_msat: OptionalField::Present(200_000),
3230 fee_proportional_millionths: 0,
3231 excess_data: Vec::new()
3234 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3235 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3236 short_channel_id: 6,
3239 cltv_expiry_delta: 0,
3240 htlc_minimum_msat: 0,
3241 htlc_maximum_msat: OptionalField::Present(100_000),
3242 fee_base_msat: 1_000,
3243 fee_proportional_millionths: 0,
3244 excess_data: Vec::new()
3246 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
3247 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3248 short_channel_id: 11,
3251 cltv_expiry_delta: 0,
3252 htlc_minimum_msat: 0,
3253 htlc_maximum_msat: OptionalField::Present(100_000),
3255 fee_proportional_millionths: 0,
3256 excess_data: Vec::new()
3259 // Path via {node7, node2} is channels {12, 13, 5}.
3260 // We already limited them to 200 sats (they are used twice for 100 sats).
3261 // Nothing to do here.
3264 // Now, attempt to route 180 sats.
3265 // Our algorithm should provide us with these 2 paths.
3266 let route = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[3],
3267 Some(InvoiceFeatures::known()), None, &Vec::new(), 180_000, 42, Arc::clone(&logger)).unwrap();
3268 assert_eq!(route.paths.len(), 2);
3270 let mut total_value_transferred_msat = 0;
3271 let mut total_paid_msat = 0;
3272 for path in &route.paths {
3273 assert_eq!(path.last().unwrap().pubkey, nodes[3]);
3274 total_value_transferred_msat += path.last().unwrap().fee_msat;
3276 total_paid_msat += hop.fee_msat;
3279 // If we paid fee, this would be higher.
3280 assert_eq!(total_value_transferred_msat, 180_000);
3281 let total_fees_paid = total_paid_msat - total_value_transferred_msat;
3282 assert_eq!(total_fees_paid, 0);
3287 fn fees_on_mpp_route_test() {
3288 // This test makes sure that MPP algorithm properly takes into account
3289 // fees charged on the channels, by making the fees impactful:
3290 // if the fee is not properly accounted for, the behavior is different.
3291 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
3292 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3294 // We need a route consisting of 2 paths:
3295 // From our node to node3 via {node0, node2} and {node7, node2, node4}.
3296 // We will route 200 sats, Each path will have 100 sats capacity.
3298 // This test is not particularly stable: e.g.,
3299 // there's a way to route via {node0, node2, node4}.
3300 // It works while pathfinding is deterministic, but can be broken otherwise.
3301 // It's fine to ignore this concern for now.
3303 // Disable other potential paths.
3304 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3305 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3306 short_channel_id: 2,
3309 cltv_expiry_delta: 0,
3310 htlc_minimum_msat: 0,
3311 htlc_maximum_msat: OptionalField::Present(100_000),
3313 fee_proportional_millionths: 0,
3314 excess_data: Vec::new()
3317 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3318 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3319 short_channel_id: 7,
3322 cltv_expiry_delta: 0,
3323 htlc_minimum_msat: 0,
3324 htlc_maximum_msat: OptionalField::Present(100_000),
3326 fee_proportional_millionths: 0,
3327 excess_data: Vec::new()
3330 // Path via {node0, node2} is channels {1, 3, 5}.
3331 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3332 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3333 short_channel_id: 1,
3336 cltv_expiry_delta: 0,
3337 htlc_minimum_msat: 0,
3338 htlc_maximum_msat: OptionalField::Present(100_000),
3340 fee_proportional_millionths: 0,
3341 excess_data: Vec::new()
3343 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3344 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3345 short_channel_id: 3,
3348 cltv_expiry_delta: 0,
3349 htlc_minimum_msat: 0,
3350 htlc_maximum_msat: OptionalField::Present(100_000),
3352 fee_proportional_millionths: 0,
3353 excess_data: Vec::new()
3356 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(5)), 5);
3357 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3358 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3359 short_channel_id: 5,
3362 cltv_expiry_delta: 0,
3363 htlc_minimum_msat: 0,
3364 htlc_maximum_msat: OptionalField::Present(100_000),
3366 fee_proportional_millionths: 0,
3367 excess_data: Vec::new()
3370 // Path via {node7, node2, node4} is channels {12, 13, 6, 11}.
3371 // All channels should be 100 sats capacity. But for the fee experiment,
3372 // we'll add absolute fee of 150 sats paid for the use channel 6 (paid to node2 on channel 13).
3373 // Since channel 12 allows to deliver only 250 sats to channel 13, channel 13 can transfer only
3374 // 100 sats (and pay 150 sats in fees for the use of channel 6),
3375 // so no matter how large are other channels,
3376 // the whole path will be limited by 100 sats with just these 2 conditions:
3377 // - channel 12 capacity is 250 sats
3378 // - fee for channel 6 is 150 sats
3379 // Let's test this by enforcing these 2 conditions and removing other limits.
3380 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3381 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3382 short_channel_id: 12,
3385 cltv_expiry_delta: 0,
3386 htlc_minimum_msat: 0,
3387 htlc_maximum_msat: OptionalField::Present(250_000),
3389 fee_proportional_millionths: 0,
3390 excess_data: Vec::new()
3392 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
3393 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3394 short_channel_id: 13,
3397 cltv_expiry_delta: 0,
3398 htlc_minimum_msat: 0,
3399 htlc_maximum_msat: OptionalField::Absent,
3401 fee_proportional_millionths: 0,
3402 excess_data: Vec::new()
3405 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3406 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3407 short_channel_id: 6,
3410 cltv_expiry_delta: 0,
3411 htlc_minimum_msat: 0,
3412 htlc_maximum_msat: OptionalField::Absent,
3413 fee_base_msat: 150_000,
3414 fee_proportional_millionths: 0,
3415 excess_data: Vec::new()
3417 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
3418 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3419 short_channel_id: 11,
3422 cltv_expiry_delta: 0,
3423 htlc_minimum_msat: 0,
3424 htlc_maximum_msat: OptionalField::Absent,
3426 fee_proportional_millionths: 0,
3427 excess_data: Vec::new()
3431 // Attempt to route more than available results in a failure.
3432 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[3],
3433 Some(InvoiceFeatures::known()), None, &Vec::new(), 210_000, 42, Arc::clone(&logger)) {
3434 assert_eq!(err, "Failed to find a sufficient route to the given destination");
3435 } else { panic!(); }
3439 // Now, attempt to route 200 sats (exact amount we can route).
3440 let route = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[3],
3441 Some(InvoiceFeatures::known()), None, &Vec::new(), 200_000, 42, Arc::clone(&logger)).unwrap();
3442 assert_eq!(route.paths.len(), 2);
3444 let mut total_amount_paid_msat = 0;
3445 for path in &route.paths {
3446 assert_eq!(path.last().unwrap().pubkey, nodes[3]);
3447 total_amount_paid_msat += path.last().unwrap().fee_msat;
3449 assert_eq!(total_amount_paid_msat, 200_000);
3455 fn drop_lowest_channel_mpp_route_test() {
3456 // This test checks that low-capacity channel is dropped when after
3457 // path finding we realize that we found more capacity than we need.
3458 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
3459 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3461 // We need a route consisting of 3 paths:
3462 // From our node to node2 via node0, node7, node1 (three paths one hop each).
3464 // The first and the second paths should be sufficient, but the third should be
3465 // cheaper, so that we select it but drop later.
3467 // First, we set limits on these (previously unlimited) channels.
3468 // Their aggregate capacity will be 50 + 60 + 20 = 130 sats.
3470 // Path via node0 is channels {1, 3}. Limit them to 100 and 50 sats (total limit 50);
3471 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3472 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3473 short_channel_id: 1,
3476 cltv_expiry_delta: 0,
3477 htlc_minimum_msat: 0,
3478 htlc_maximum_msat: OptionalField::Present(100_000),
3480 fee_proportional_millionths: 0,
3481 excess_data: Vec::new()
3483 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3484 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3485 short_channel_id: 3,
3488 cltv_expiry_delta: 0,
3489 htlc_minimum_msat: 0,
3490 htlc_maximum_msat: OptionalField::Present(50_000),
3492 fee_proportional_millionths: 0,
3493 excess_data: Vec::new()
3496 // Path via node7 is channels {12, 13}. Limit them to 60 and 60 sats (total limit 60);
3497 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3498 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3499 short_channel_id: 12,
3502 cltv_expiry_delta: 0,
3503 htlc_minimum_msat: 0,
3504 htlc_maximum_msat: OptionalField::Present(60_000),
3506 fee_proportional_millionths: 0,
3507 excess_data: Vec::new()
3509 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
3510 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3511 short_channel_id: 13,
3514 cltv_expiry_delta: 0,
3515 htlc_minimum_msat: 0,
3516 htlc_maximum_msat: OptionalField::Present(60_000),
3518 fee_proportional_millionths: 0,
3519 excess_data: Vec::new()
3522 // Path via node1 is channels {2, 4}. Limit them to 20 and 20 sats (total capacity 20 sats).
3523 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3524 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3525 short_channel_id: 2,
3528 cltv_expiry_delta: 0,
3529 htlc_minimum_msat: 0,
3530 htlc_maximum_msat: OptionalField::Present(20_000),
3532 fee_proportional_millionths: 0,
3533 excess_data: Vec::new()
3535 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
3536 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3537 short_channel_id: 4,
3540 cltv_expiry_delta: 0,
3541 htlc_minimum_msat: 0,
3542 htlc_maximum_msat: OptionalField::Present(20_000),
3544 fee_proportional_millionths: 0,
3545 excess_data: Vec::new()
3549 // Attempt to route more than available results in a failure.
3550 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2],
3551 Some(InvoiceFeatures::known()), None, &Vec::new(), 150_000, 42, Arc::clone(&logger)) {
3552 assert_eq!(err, "Failed to find a sufficient route to the given destination");
3553 } else { panic!(); }
3557 // Now, attempt to route 125 sats (just a bit below the capacity of 3 channels).
3558 // Our algorithm should provide us with these 3 paths.
3559 let route = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2],
3560 Some(InvoiceFeatures::known()), None, &Vec::new(), 125_000, 42, Arc::clone(&logger)).unwrap();
3561 assert_eq!(route.paths.len(), 3);
3562 let mut total_amount_paid_msat = 0;
3563 for path in &route.paths {
3564 assert_eq!(path.len(), 2);
3565 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
3566 total_amount_paid_msat += path.last().unwrap().fee_msat;
3568 assert_eq!(total_amount_paid_msat, 125_000);
3572 // Attempt to route without the last small cheap channel
3573 let route = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2],
3574 Some(InvoiceFeatures::known()), None, &Vec::new(), 90_000, 42, Arc::clone(&logger)).unwrap();
3575 assert_eq!(route.paths.len(), 2);
3576 let mut total_amount_paid_msat = 0;
3577 for path in &route.paths {
3578 assert_eq!(path.len(), 2);
3579 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
3580 total_amount_paid_msat += path.last().unwrap().fee_msat;
3582 assert_eq!(total_amount_paid_msat, 90_000);
3587 fn min_criteria_consistency() {
3588 // Test that we don't use an inconsistent metric between updating and walking nodes during
3589 // our Dijkstra's pass. In the initial version of MPP, the "best source" for a given node
3590 // was updated with a different criterion from the heap sorting, resulting in loops in
3591 // calculated paths. We test for that specific case here.
3593 // We construct a network that looks like this:
3595 // node2 -1(3)2- node3
3599 // node1 -1(5)2- node4 -1(1)2- node6
3605 // We create a loop on the side of our real path - our destination is node 6, with a
3606 // previous hop of node 4. From 4, the cheapest previous path is channel 2 from node 2,
3607 // followed by node 3 over channel 3. Thereafter, the cheapest next-hop is back to node 4
3608 // (this time over channel 4). Channel 4 has 0 htlc_minimum_msat whereas channel 1 (the
3609 // other channel with a previous-hop of node 4) has a high (but irrelevant to the overall
3610 // payment) htlc_minimum_msat. In the original algorithm, this resulted in node4's
3611 // "previous hop" being set to node 3, creating a loop in the path.
3612 let secp_ctx = Secp256k1::new();
3613 let logger = Arc::new(test_utils::TestLogger::new());
3614 let net_graph_msg_handler = NetGraphMsgHandler::new(genesis_block(Network::Testnet).header.block_hash(), None, Arc::clone(&logger));
3615 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3617 add_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, &privkeys[1], ChannelFeatures::from_le_bytes(id_to_feature_flags(6)), 6);
3618 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3619 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3620 short_channel_id: 6,
3623 cltv_expiry_delta: (6 << 8) | 0,
3624 htlc_minimum_msat: 0,
3625 htlc_maximum_msat: OptionalField::Absent,
3627 fee_proportional_millionths: 0,
3628 excess_data: Vec::new()
3630 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[1], NodeFeatures::from_le_bytes(id_to_feature_flags(1)), 0);
3632 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], &privkeys[4], ChannelFeatures::from_le_bytes(id_to_feature_flags(5)), 5);
3633 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
3634 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3635 short_channel_id: 5,
3638 cltv_expiry_delta: (5 << 8) | 0,
3639 htlc_minimum_msat: 0,
3640 htlc_maximum_msat: OptionalField::Absent,
3642 fee_proportional_millionths: 0,
3643 excess_data: Vec::new()
3645 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[4], NodeFeatures::from_le_bytes(id_to_feature_flags(4)), 0);
3647 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(4)), 4);
3648 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
3649 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3650 short_channel_id: 4,
3653 cltv_expiry_delta: (4 << 8) | 0,
3654 htlc_minimum_msat: 0,
3655 htlc_maximum_msat: OptionalField::Absent,
3657 fee_proportional_millionths: 0,
3658 excess_data: Vec::new()
3660 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[3], NodeFeatures::from_le_bytes(id_to_feature_flags(3)), 0);
3662 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[3], &privkeys[2], ChannelFeatures::from_le_bytes(id_to_feature_flags(3)), 3);
3663 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[3], UnsignedChannelUpdate {
3664 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3665 short_channel_id: 3,
3668 cltv_expiry_delta: (3 << 8) | 0,
3669 htlc_minimum_msat: 0,
3670 htlc_maximum_msat: OptionalField::Absent,
3672 fee_proportional_millionths: 0,
3673 excess_data: Vec::new()
3675 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[2], NodeFeatures::from_le_bytes(id_to_feature_flags(2)), 0);
3677 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], &privkeys[4], ChannelFeatures::from_le_bytes(id_to_feature_flags(2)), 2);
3678 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3679 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3680 short_channel_id: 2,
3683 cltv_expiry_delta: (2 << 8) | 0,
3684 htlc_minimum_msat: 0,
3685 htlc_maximum_msat: OptionalField::Absent,
3687 fee_proportional_millionths: 0,
3688 excess_data: Vec::new()
3691 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], &privkeys[6], ChannelFeatures::from_le_bytes(id_to_feature_flags(1)), 1);
3692 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
3693 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3694 short_channel_id: 1,
3697 cltv_expiry_delta: (1 << 8) | 0,
3698 htlc_minimum_msat: 100,
3699 htlc_maximum_msat: OptionalField::Absent,
3701 fee_proportional_millionths: 0,
3702 excess_data: Vec::new()
3704 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[6], NodeFeatures::from_le_bytes(id_to_feature_flags(6)), 0);
3707 // Now ensure the route flows simply over nodes 1 and 4 to 6.
3708 let route = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[6], None, None, &Vec::new(), 10_000, 42, Arc::clone(&logger)).unwrap();
3709 assert_eq!(route.paths.len(), 1);
3710 assert_eq!(route.paths[0].len(), 3);
3712 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
3713 assert_eq!(route.paths[0][0].short_channel_id, 6);
3714 assert_eq!(route.paths[0][0].fee_msat, 100);
3715 assert_eq!(route.paths[0][0].cltv_expiry_delta, (5 << 8) | 0);
3716 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(1));
3717 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(6));
3719 assert_eq!(route.paths[0][1].pubkey, nodes[4]);
3720 assert_eq!(route.paths[0][1].short_channel_id, 5);
3721 assert_eq!(route.paths[0][1].fee_msat, 0);
3722 assert_eq!(route.paths[0][1].cltv_expiry_delta, (1 << 8) | 0);
3723 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(4));
3724 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(5));
3726 assert_eq!(route.paths[0][2].pubkey, nodes[6]);
3727 assert_eq!(route.paths[0][2].short_channel_id, 1);
3728 assert_eq!(route.paths[0][2].fee_msat, 10_000);
3729 assert_eq!(route.paths[0][2].cltv_expiry_delta, 42);
3730 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(6));
3731 assert_eq!(route.paths[0][2].channel_features.le_flags(), &id_to_feature_flags(1));
3737 fn exact_fee_liquidity_limit() {
3738 // Test that if, while walking the graph, we find a hop that has exactly enough liquidity
3739 // for us, including later hop fees, we take it. In the first version of our MPP algorithm
3740 // we calculated fees on a higher value, resulting in us ignoring such paths.
3741 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
3742 let (our_privkey, our_id, _, nodes) = get_nodes(&secp_ctx);
3744 // We modify the graph to set the htlc_maximum of channel 2 to below the value we wish to
3746 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3747 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3748 short_channel_id: 2,
3751 cltv_expiry_delta: 0,
3752 htlc_minimum_msat: 0,
3753 htlc_maximum_msat: OptionalField::Present(85_000),
3755 fee_proportional_millionths: 0,
3756 excess_data: Vec::new()
3759 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3760 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3761 short_channel_id: 12,
3764 cltv_expiry_delta: (4 << 8) | 1,
3765 htlc_minimum_msat: 0,
3766 htlc_maximum_msat: OptionalField::Present(270_000),
3768 fee_proportional_millionths: 1000000,
3769 excess_data: Vec::new()
3773 // Now, attempt to route 90 sats, which is exactly 90 sats at the last hop, plus the
3774 // 200% fee charged channel 13 in the 1-to-2 direction.
3775 let route = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2], None, None, &Vec::new(), 90_000, 42, Arc::clone(&logger)).unwrap();
3776 assert_eq!(route.paths.len(), 1);
3777 assert_eq!(route.paths[0].len(), 2);
3779 assert_eq!(route.paths[0][0].pubkey, nodes[7]);
3780 assert_eq!(route.paths[0][0].short_channel_id, 12);
3781 assert_eq!(route.paths[0][0].fee_msat, 90_000*2);
3782 assert_eq!(route.paths[0][0].cltv_expiry_delta, (13 << 8) | 1);
3783 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(8));
3784 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(12));
3786 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
3787 assert_eq!(route.paths[0][1].short_channel_id, 13);
3788 assert_eq!(route.paths[0][1].fee_msat, 90_000);
3789 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
3790 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
3791 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(13));
3796 fn htlc_max_reduction_below_min() {
3797 // Test that if, while walking the graph, we reduce the value being sent to meet an
3798 // htlc_maximum_msat, we don't end up undershooting a later htlc_minimum_msat. In the
3799 // initial version of MPP we'd accept such routes but reject them while recalculating fees,
3800 // resulting in us thinking there is no possible path, even if other paths exist.
3801 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
3802 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3804 // We modify the graph to set the htlc_minimum of channel 2 and 4 as needed - channel 2
3805 // gets an htlc_maximum_msat of 80_000 and channel 4 an htlc_minimum_msat of 90_000. We
3806 // then try to send 90_000.
3807 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3808 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3809 short_channel_id: 2,
3812 cltv_expiry_delta: 0,
3813 htlc_minimum_msat: 0,
3814 htlc_maximum_msat: OptionalField::Present(80_000),
3816 fee_proportional_millionths: 0,
3817 excess_data: Vec::new()
3819 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
3820 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3821 short_channel_id: 4,
3824 cltv_expiry_delta: (4 << 8) | 1,
3825 htlc_minimum_msat: 90_000,
3826 htlc_maximum_msat: OptionalField::Absent,
3828 fee_proportional_millionths: 0,
3829 excess_data: Vec::new()
3833 // Now, attempt to route 90 sats, hitting the htlc_minimum on channel 4, but
3834 // overshooting the htlc_maximum on channel 2. Thus, we should pick the (absurdly
3835 // expensive) channels 12-13 path.
3836 let route = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2], Some(InvoiceFeatures::known()), None, &Vec::new(), 90_000, 42, Arc::clone(&logger)).unwrap();
3837 assert_eq!(route.paths.len(), 1);
3838 assert_eq!(route.paths[0].len(), 2);
3840 assert_eq!(route.paths[0][0].pubkey, nodes[7]);
3841 assert_eq!(route.paths[0][0].short_channel_id, 12);
3842 assert_eq!(route.paths[0][0].fee_msat, 90_000*2);
3843 assert_eq!(route.paths[0][0].cltv_expiry_delta, (13 << 8) | 1);
3844 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(8));
3845 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(12));
3847 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
3848 assert_eq!(route.paths[0][1].short_channel_id, 13);
3849 assert_eq!(route.paths[0][1].fee_msat, 90_000);
3850 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
3851 assert_eq!(route.paths[0][1].node_features.le_flags(), InvoiceFeatures::known().le_flags());
3852 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(13));
3857 use util::ser::Readable;
3858 /// Tries to open a network graph file, or panics with a URL to fetch it.
3859 pub(super) fn get_route_file() -> Result<std::fs::File, std::io::Error> {
3860 let res = File::open("net_graph-2021-02-12.bin") // By default we're run in RL/lightning
3861 .or_else(|_| File::open("lightning/net_graph-2021-02-12.bin")) // We may be run manually in RL/
3862 .or_else(|_| { // Fall back to guessing based on the binary location
3863 // path is likely something like .../rust-lightning/target/debug/deps/lightning-...
3864 let mut path = std::env::current_exe().unwrap();
3865 path.pop(); // lightning-...
3867 path.pop(); // debug
3868 path.pop(); // target
3869 path.push("lightning");
3870 path.push("net_graph-2021-02-12.bin");
3871 eprintln!("{}", path.to_str().unwrap());
3874 #[cfg(require_route_graph_test)]
3875 return Ok(res.expect("Didn't have route graph and was configured to require it"));
3876 #[cfg(not(require_route_graph_test))]
3880 pub(super) fn random_init_seed() -> u64 {
3881 // Because the default HashMap in std pulls OS randomness, we can use it as a (bad) RNG.
3882 use core::hash::{BuildHasher, Hasher};
3883 let seed = std::collections::hash_map::RandomState::new().build_hasher().finish();
3884 println!("Using seed of {}", seed);
3889 fn generate_routes() {
3890 let mut d = match get_route_file() {
3893 eprintln!("Please fetch https://bitcoin.ninja/ldk-net_graph-05f0c5a0d772-2020-02-12.bin and place it at lightning/net_graph-2021-02-12.bin");
3897 let graph = NetworkGraph::read(&mut d).unwrap();
3899 // First, get 100 (source, destination) pairs for which route-getting actually succeeds...
3900 let mut seed = random_init_seed() as usize;
3901 'load_endpoints: for _ in 0..10 {
3903 seed = seed.overflowing_mul(0xdeadbeef).0;
3904 let src = graph.get_nodes().keys().skip(seed % graph.get_nodes().len()).next().unwrap();
3905 seed = seed.overflowing_mul(0xdeadbeef).0;
3906 let dst = graph.get_nodes().keys().skip(seed % graph.get_nodes().len()).next().unwrap();
3907 let amt = seed as u64 % 200_000_000;
3908 if get_route(src, &graph, dst, None, None, &[], amt, 42, &test_utils::TestLogger::new()).is_ok() {
3909 continue 'load_endpoints;
3916 fn generate_routes_mpp() {
3917 let mut d = match get_route_file() {
3920 eprintln!("Please fetch https://bitcoin.ninja/ldk-net_graph-05f0c5a0d772-2020-02-12.bin and place it at lightning/net_graph-2021-02-12.bin");
3924 let graph = NetworkGraph::read(&mut d).unwrap();
3926 // First, get 100 (source, destination) pairs for which route-getting actually succeeds...
3927 let mut seed = random_init_seed() as usize;
3928 'load_endpoints: for _ in 0..10 {
3930 seed = seed.overflowing_mul(0xdeadbeef).0;
3931 let src = graph.get_nodes().keys().skip(seed % graph.get_nodes().len()).next().unwrap();
3932 seed = seed.overflowing_mul(0xdeadbeef).0;
3933 let dst = graph.get_nodes().keys().skip(seed % graph.get_nodes().len()).next().unwrap();
3934 let amt = seed as u64 % 200_000_000;
3935 if get_route(src, &graph, dst, Some(InvoiceFeatures::known()), None, &[], amt, 42, &test_utils::TestLogger::new()).is_ok() {
3936 continue 'load_endpoints;
3943 #[cfg(all(test, feature = "unstable"))]
3946 use util::logger::{Logger, Record};
3950 struct DummyLogger {}
3951 impl Logger for DummyLogger {
3952 fn log(&self, _record: &Record) {}
3956 fn generate_routes(bench: &mut Bencher) {
3957 let mut d = tests::get_route_file()
3958 .expect("Please fetch https://bitcoin.ninja/ldk-net_graph-05f0c5a0d772-2020-02-12.bin and place it at lightning/net_graph-2021-02-12.bin");
3959 let graph = NetworkGraph::read(&mut d).unwrap();
3961 // First, get 100 (source, destination) pairs for which route-getting actually succeeds...
3962 let mut path_endpoints = Vec::new();
3963 let mut seed: usize = 0xdeadbeef;
3964 'load_endpoints: for _ in 0..100 {
3967 let src = graph.get_nodes().keys().skip(seed % graph.get_nodes().len()).next().unwrap();
3969 let dst = graph.get_nodes().keys().skip(seed % graph.get_nodes().len()).next().unwrap();
3970 let amt = seed as u64 % 1_000_000;
3971 if get_route(src, &graph, dst, None, None, &[], amt, 42, &DummyLogger{}).is_ok() {
3972 path_endpoints.push((src, dst, amt));
3973 continue 'load_endpoints;
3978 // ...then benchmark finding paths between the nodes we learned.
3981 let (src, dst, amt) = path_endpoints[idx % path_endpoints.len()];
3982 assert!(get_route(src, &graph, dst, None, None, &[], amt, 42, &DummyLogger{}).is_ok());
3988 fn generate_mpp_routes(bench: &mut Bencher) {
3989 let mut d = tests::get_route_file()
3990 .expect("Please fetch https://bitcoin.ninja/ldk-net_graph-05f0c5a0d772-2020-02-12.bin and place it at lightning/net_graph-2021-02-12.bin");
3991 let graph = NetworkGraph::read(&mut d).unwrap();
3993 // First, get 100 (source, destination) pairs for which route-getting actually succeeds...
3994 let mut path_endpoints = Vec::new();
3995 let mut seed: usize = 0xdeadbeef;
3996 'load_endpoints: for _ in 0..100 {
3999 let src = graph.get_nodes().keys().skip(seed % graph.get_nodes().len()).next().unwrap();
4001 let dst = graph.get_nodes().keys().skip(seed % graph.get_nodes().len()).next().unwrap();
4002 let amt = seed as u64 % 1_000_000;
4003 if get_route(src, &graph, dst, Some(InvoiceFeatures::known()), None, &[], amt, 42, &DummyLogger{}).is_ok() {
4004 path_endpoints.push((src, dst, amt));
4005 continue 'load_endpoints;
4010 // ...then benchmark finding paths between the nodes we learned.
4013 let (src, dst, amt) = path_endpoints[idx % path_endpoints.len()];
4014 assert!(get_route(src, &graph, dst, Some(InvoiceFeatures::known()), None, &[], amt, 42, &DummyLogger{}).is_ok());