1 // This file is Copyright its original authors, visible in version control
4 // This file is licensed under the Apache License, Version 2.0 <LICENSE-APACHE
5 // or http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
6 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your option.
7 // You may not use this file except in accordance with one or both of these
10 //! The top-level routing/network map tracking logic lives here.
12 //! You probably want to create a NetGraphMsgHandler and use that as your RoutingMessageHandler and then
13 //! interrogate it to get routes for your own payments.
15 use bitcoin::secp256k1::key::PublicKey;
17 use ln::channelmanager::ChannelDetails;
18 use ln::features::{ChannelFeatures, InvoiceFeatures, NodeFeatures};
19 use ln::msgs::{DecodeError, ErrorAction, LightningError, MAX_VALUE_MSAT};
20 use routing::network_graph::{NetworkGraph, RoutingFees};
21 use util::ser::{Writeable, Readable};
22 use util::logger::Logger;
25 use std::collections::{HashMap, BinaryHeap};
29 #[derive(Clone, PartialEq)]
31 /// The node_id of the node at this hop.
32 pub pubkey: PublicKey,
33 /// The node_announcement features of the node at this hop. For the last hop, these may be
34 /// amended to match the features present in the invoice this node generated.
35 pub node_features: NodeFeatures,
36 /// The channel that should be used from the previous hop to reach this node.
37 pub short_channel_id: u64,
38 /// The channel_announcement features of the channel that should be used from the previous hop
39 /// to reach this node.
40 pub channel_features: ChannelFeatures,
41 /// The fee taken on this hop (for paying for the use of the *next* channel in the path).
42 /// For the last hop, this should be the full value of the payment (might be more than
43 /// requested if we had to match htlc_minimum_msat).
45 /// The CLTV delta added for this hop. For the last hop, this should be the full CLTV value
46 /// expected at the destination, in excess of the current block height.
47 pub cltv_expiry_delta: u32,
51 impl Writeable for Vec<RouteHop> {
52 fn write<W: ::util::ser::Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
53 (self.len() as u8).write(writer)?;
54 for hop in self.iter() {
55 hop.pubkey.write(writer)?;
56 hop.node_features.write(writer)?;
57 hop.short_channel_id.write(writer)?;
58 hop.channel_features.write(writer)?;
59 hop.fee_msat.write(writer)?;
60 hop.cltv_expiry_delta.write(writer)?;
67 impl Readable for Vec<RouteHop> {
68 fn read<R: ::std::io::Read>(reader: &mut R) -> Result<Vec<RouteHop>, DecodeError> {
69 let hops_count: u8 = Readable::read(reader)?;
70 let mut hops = Vec::with_capacity(hops_count as usize);
71 for _ in 0..hops_count {
73 pubkey: Readable::read(reader)?,
74 node_features: Readable::read(reader)?,
75 short_channel_id: Readable::read(reader)?,
76 channel_features: Readable::read(reader)?,
77 fee_msat: Readable::read(reader)?,
78 cltv_expiry_delta: Readable::read(reader)?,
85 /// A route directs a payment from the sender (us) to the recipient. If the recipient supports MPP,
86 /// it can take multiple paths. Each path is composed of one or more hops through the network.
87 #[derive(Clone, PartialEq)]
89 /// The list of routes taken for a single (potentially-)multi-part payment. The pubkey of the
90 /// last RouteHop in each path must be the same.
91 /// Each entry represents a list of hops, NOT INCLUDING our own, where the last hop is the
92 /// destination. Thus, this must always be at least length one. While the maximum length of any
93 /// given path is variable, keeping the length of any path to less than 20 should currently
94 /// ensure it is viable.
95 pub paths: Vec<Vec<RouteHop>>,
98 impl Writeable for Route {
99 fn write<W: ::util::ser::Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
100 (self.paths.len() as u64).write(writer)?;
101 for hops in self.paths.iter() {
108 impl Readable for Route {
109 fn read<R: ::std::io::Read>(reader: &mut R) -> Result<Route, DecodeError> {
110 let path_count: u64 = Readable::read(reader)?;
111 let mut paths = Vec::with_capacity(cmp::min(path_count, 128) as usize);
112 for _ in 0..path_count {
113 paths.push(Readable::read(reader)?);
119 /// A channel descriptor which provides a last-hop route to get_route
121 pub struct RouteHint {
122 /// The node_id of the non-target end of the route
123 pub src_node_id: PublicKey,
124 /// The short_channel_id of this channel
125 pub short_channel_id: u64,
126 /// The fees which must be paid to use this channel
127 pub fees: RoutingFees,
128 /// The difference in CLTV values between this node and the next node.
129 pub cltv_expiry_delta: u16,
130 /// The minimum value, in msat, which must be relayed to the next hop.
131 pub htlc_minimum_msat: Option<u64>,
132 /// The maximum value in msat available for routing with a single HTLC.
133 pub htlc_maximum_msat: Option<u64>,
136 #[derive(Eq, PartialEq)]
137 struct RouteGraphNode {
139 lowest_fee_to_peer_through_node: u64,
140 lowest_fee_to_node: u64,
141 // The maximum value a yet-to-be-constructed payment path might flow through this node.
142 // This value is upper-bounded by us by:
143 // - how much is needed for a path being constructed
144 // - how much value can channels following this node (up to the destination) can contribute,
145 // considering their capacity and fees
146 value_contribution_msat: u64,
147 /// The effective htlc_minimum_msat at this hop. If a later hop on the path had a higher HTLC
148 /// minimum, we use it, plus the fees required at each earlier hop to meet it.
149 path_htlc_minimum_msat: u64,
152 impl cmp::Ord for RouteGraphNode {
153 fn cmp(&self, other: &RouteGraphNode) -> cmp::Ordering {
154 let other_score = cmp::max(other.lowest_fee_to_peer_through_node, other.path_htlc_minimum_msat);
155 let self_score = cmp::max(self.lowest_fee_to_peer_through_node, self.path_htlc_minimum_msat);
156 other_score.cmp(&self_score).then_with(|| other.pubkey.serialize().cmp(&self.pubkey.serialize()))
160 impl cmp::PartialOrd for RouteGraphNode {
161 fn partial_cmp(&self, other: &RouteGraphNode) -> Option<cmp::Ordering> {
162 Some(self.cmp(other))
166 struct DummyDirectionalChannelInfo {
167 cltv_expiry_delta: u32,
168 htlc_minimum_msat: u64,
169 htlc_maximum_msat: Option<u64>,
173 /// It's useful to keep track of the hops associated with the fees required to use them,
174 /// so that we can choose cheaper paths (as per Dijkstra's algorithm).
175 /// Fee values should be updated only in the context of the whole path, see update_value_and_recompute_fees.
176 /// These fee values are useful to choose hops as we traverse the graph "payee-to-payer".
178 struct PathBuildingHop<'a> {
179 // The RouteHint fields which will eventually be used if this hop is used in a final Route.
180 // Note that node_features is calculated separately after our initial graph walk.
182 short_channel_id: u64,
183 channel_features: &'a ChannelFeatures,
185 cltv_expiry_delta: u32,
187 /// Minimal fees required to route to the source node of the current hop via any of its inbound channels.
188 src_lowest_inbound_fees: RoutingFees,
189 /// Fees of the channel used in this hop.
190 channel_fees: RoutingFees,
191 /// All the fees paid *after* this channel on the way to the destination
192 next_hops_fee_msat: u64,
193 /// Fee paid for the use of the current channel (see channel_fees).
194 /// The value will be actually deducted from the counterparty balance on the previous link.
195 hop_use_fee_msat: u64,
196 /// Used to compare channels when choosing the for routing.
197 /// Includes paying for the use of a hop and the following hops, as well as
198 /// an estimated cost of reaching this hop.
199 /// Might get stale when fees are recomputed. Primarily for internal use.
201 /// This is useful for update_value_and_recompute_fees to make sure
202 /// we don't fall below the minimum. Should not be updated manually and
203 /// generally should not be accessed.
204 htlc_minimum_msat: u64,
205 /// A mirror of the same field in RouteGraphNode. Note that this is only used during the graph
206 /// walk and may be invalid thereafter.
207 path_htlc_minimum_msat: u64,
208 /// If we've already processed a node as the best node, we shouldn't process it again. Normally
209 /// we'd just ignore it if we did as all channels would have a higher new fee, but because we
210 /// may decrease the amounts in use as we walk the graph, the actual calculated fee may
211 /// decrease as well. Thus, we have to explicitly track which nodes have been processed and
212 /// avoid processing them again.
214 #[cfg(any(test, feature = "fuzztarget"))]
215 // In tests, we apply further sanity checks on cases where we skip nodes we already processed
216 // to ensure it is specifically in cases where the fee has gone down because of a decrease in
217 // value_contribution_msat, which requires tracking it here. See comments below where it is
218 // used for more info.
219 value_contribution_msat: u64,
222 // Instantiated with a list of hops with correct data in them collected during path finding,
223 // an instance of this struct should be further modified only via given methods.
225 struct PaymentPath<'a> {
226 hops: Vec<(PathBuildingHop<'a>, NodeFeatures)>,
229 impl<'a> PaymentPath<'a> {
230 // TODO: Add a value_msat field to PaymentPath and use it instead of this function.
231 fn get_value_msat(&self) -> u64 {
232 self.hops.last().unwrap().0.fee_msat
235 fn get_total_fee_paid_msat(&self) -> u64 {
236 if self.hops.len() < 1 {
240 // Can't use next_hops_fee_msat because it gets outdated.
241 for (i, (hop, _)) in self.hops.iter().enumerate() {
242 if i != self.hops.len() - 1 {
243 result += hop.fee_msat;
249 // If the amount transferred by the path is updated, the fees should be adjusted. Any other way
250 // to change fees may result in an inconsistency.
252 // Sometimes we call this function right after constructing a path which has inconsistent
253 // (in terms of reaching htlc_minimum_msat), so that this function puts the fees in order.
254 // In that case we call it on the "same" amount we initially allocated for this path, and which
255 // could have been reduced on the way. In that case, there is also a risk of exceeding
256 // available_liquidity inside this function, because the function is unaware of this bound.
257 // In our specific recomputation cases where we never increase the value the risk is pretty low.
258 // This function, however, does not support arbitrarily increasing the value being transferred,
259 // and the exception will be triggered.
260 fn update_value_and_recompute_fees(&mut self, value_msat: u64) {
261 assert!(value_msat <= self.hops.last().unwrap().0.fee_msat);
263 let mut total_fee_paid_msat = 0 as u64;
264 for i in (0..self.hops.len()).rev() {
265 let last_hop = i == self.hops.len() - 1;
267 // For non-last-hop, this value will represent the fees paid on the current hop. It
268 // will consist of the fees for the use of the next hop, and extra fees to match
269 // htlc_minimum_msat of the current channel. Last hop is handled separately.
270 let mut cur_hop_fees_msat = 0;
272 cur_hop_fees_msat = self.hops.get(i + 1).unwrap().0.hop_use_fee_msat;
275 let mut cur_hop = &mut self.hops.get_mut(i).unwrap().0;
276 cur_hop.next_hops_fee_msat = total_fee_paid_msat;
277 // Overpay in fees if we can't save these funds due to htlc_minimum_msat.
278 // We try to account for htlc_minimum_msat in scoring (add_entry!), so that nodes don't
279 // set it too high just to maliciously take more fees by exploiting this
280 // match htlc_minimum_msat logic.
281 let mut cur_hop_transferred_amount_msat = total_fee_paid_msat + value_msat;
282 if let Some(extra_fees_msat) = cur_hop.htlc_minimum_msat.checked_sub(cur_hop_transferred_amount_msat) {
283 // Note that there is a risk that *previous hops* (those closer to us, as we go
284 // payee->our_node here) would exceed their htlc_maximum_msat or available balance.
286 // This might make us end up with a broken route, although this should be super-rare
287 // in practice, both because of how healthy channels look like, and how we pick
288 // channels in add_entry.
289 // Also, this can't be exploited more heavily than *announce a free path and fail
291 cur_hop_transferred_amount_msat += extra_fees_msat;
292 total_fee_paid_msat += extra_fees_msat;
293 cur_hop_fees_msat += extra_fees_msat;
297 // Final hop is a special case: it usually has just value_msat (by design), but also
298 // it still could overpay for the htlc_minimum_msat.
299 cur_hop.fee_msat = cur_hop_transferred_amount_msat;
301 // Propagate updated fees for the use of the channels to one hop back, where they
302 // will be actually paid (fee_msat). The last hop is handled above separately.
303 cur_hop.fee_msat = cur_hop_fees_msat;
306 // Fee for the use of the current hop which will be deducted on the previous hop.
307 // Irrelevant for the first hop, as it doesn't have the previous hop, and the use of
308 // this channel is free for us.
310 if let Some(new_fee) = compute_fees(cur_hop_transferred_amount_msat, cur_hop.channel_fees) {
311 cur_hop.hop_use_fee_msat = new_fee;
312 total_fee_paid_msat += new_fee;
314 // It should not be possible because this function is called only to reduce the
315 // value. In that case, compute_fee was already called with the same fees for
316 // larger amount and there was no overflow.
324 fn compute_fees(amount_msat: u64, channel_fees: RoutingFees) -> Option<u64> {
325 let proportional_fee_millions =
326 amount_msat.checked_mul(channel_fees.proportional_millionths as u64);
327 if let Some(new_fee) = proportional_fee_millions.and_then(|part| {
328 (channel_fees.base_msat as u64).checked_add(part / 1_000_000) }) {
332 // This function may be (indirectly) called without any verification,
333 // with channel_fees provided by a caller. We should handle it gracefully.
338 /// Gets a route from us (payer) to the given target node (payee).
340 /// If the payee provided features in their invoice, they should be provided via payee_features.
341 /// Without this, MPP will only be used if the payee's features are available in the network graph.
343 /// Extra routing hops between known nodes and the target will be used if they are included in
346 /// If some channels aren't announced, it may be useful to fill in a first_hops with the
347 /// results from a local ChannelManager::list_usable_channels() call. If it is filled in, our
348 /// view of our local channels (from net_graph_msg_handler) will be ignored, and only those
349 /// in first_hops will be used.
351 /// Panics if first_hops contains channels without short_channel_ids
352 /// (ChannelManager::list_usable_channels will never include such channels).
354 /// The fees on channels from us to next-hops are ignored (as they are assumed to all be
355 /// equal), however the enabled/disabled bit on such channels as well as the
356 /// htlc_minimum_msat/htlc_maximum_msat *are* checked as they may change based on the receiving node.
357 pub fn get_route<L: Deref>(our_node_id: &PublicKey, network: &NetworkGraph, payee: &PublicKey, payee_features: Option<InvoiceFeatures>, first_hops: Option<&[&ChannelDetails]>,
358 last_hops: &[&RouteHint], final_value_msat: u64, final_cltv: u32, logger: L) -> Result<Route, LightningError> where L::Target: Logger {
359 // TODO: Obviously *only* using total fee cost sucks. We should consider weighting by
360 // uptime/success in using a node in the past.
361 if *payee == *our_node_id {
362 return Err(LightningError{err: "Cannot generate a route to ourselves".to_owned(), action: ErrorAction::IgnoreError});
365 if final_value_msat > MAX_VALUE_MSAT {
366 return Err(LightningError{err: "Cannot generate a route of more value than all existing satoshis".to_owned(), action: ErrorAction::IgnoreError});
369 if final_value_msat == 0 {
370 return Err(LightningError{err: "Cannot send a payment of 0 msat".to_owned(), action: ErrorAction::IgnoreError});
373 for last_hop in last_hops {
374 if last_hop.src_node_id == *payee {
375 return Err(LightningError{err: "Last hop cannot have a payee as a source.".to_owned(), action: ErrorAction::IgnoreError});
379 // The general routing idea is the following:
380 // 1. Fill first/last hops communicated by the caller.
381 // 2. Attempt to construct a path from payer to payee for transferring
382 // any ~sufficient (described later) value.
383 // If succeed, remember which channels were used and how much liquidity they have available,
384 // so that future paths don't rely on the same liquidity.
385 // 3. Prooceed to the next step if:
386 // - we hit the recommended target value;
387 // - OR if we could not construct a new path. Any next attempt will fail too.
388 // Otherwise, repeat step 2.
389 // 4. See if we managed to collect paths which aggregately are able to transfer target value
390 // (not recommended value). If yes, proceed. If not, fail routing.
391 // 5. Randomly combine paths into routes having enough to fulfill the payment. (TODO: knapsack)
392 // 6. Of all the found paths, select only those with the lowest total fee.
393 // 7. The last path in every selected route is likely to be more than we need.
394 // Reduce its value-to-transfer and recompute fees.
395 // 8. Choose the best route by the lowest total fee.
397 // As for the actual search algorithm,
398 // we do a payee-to-payer pseudo-Dijkstra's sorting by each node's distance from the payee
399 // plus the minimum per-HTLC fee to get from it to another node (aka "shitty pseudo-A*").
401 // We are not a faithful Dijkstra's implementation because we can change values which impact
402 // earlier nodes while processing later nodes. Specifically, if we reach a channel with a lower
403 // liquidity limit (via htlc_maximum_msat, on-chain capacity or assumed liquidity limits) then
404 // the value we are currently attempting to send over a path, we simply reduce the value being
405 // sent along the path for any hops after that channel. This may imply that later fees (which
406 // we've already tabulated) are lower because a smaller value is passing through the channels
407 // (and the proportional fee is thus lower). There isn't a trivial way to recalculate the
408 // channels which were selected earlier (and which may still be used for other paths without a
409 // lower liquidity limit), so we simply accept that some liquidity-limited paths may be
412 // One potentially problematic case for this algorithm would be if there are many
413 // liquidity-limited paths which are liquidity-limited near the destination (ie early in our
414 // graph walking), we may never find a path which is not liquidity-limited and has lower
415 // proportional fee (and only lower absolute fee when considering the ultimate value sent).
416 // Because we only consider paths with at least 5% of the total value being sent, the damage
417 // from such a case should be limited, however this could be further reduced in the future by
418 // calculating fees on the amount we wish to route over a path, ie ignoring the liquidity
419 // limits for the purposes of fee calculation.
421 // Alternatively, we could store more detailed path information in the heap (targets, below)
422 // and index the best-path map (dist, below) by node *and* HTLC limits, however that would blow
423 // up the runtime significantly both algorithmically (as we'd traverse nodes multiple times)
424 // and practically (as we would need to store dynamically-allocated path information in heap
425 // objects, increasing malloc traffic and indirect memory access significantly). Further, the
426 // results of such an algorithm would likely be biased towards lower-value paths.
428 // Further, we could return to a faithful Dijkstra's algorithm by rejecting paths with limits
429 // outside of our current search value, running a path search more times to gather candidate
430 // paths at different values. While this may be acceptable, further path searches may increase
431 // runtime for little gain. Specifically, the current algorithm rather efficiently explores the
432 // graph for candidate paths, calculating the maximum value which can realistically be sent at
433 // the same time, remaining generic across different payment values.
435 // TODO: There are a few tweaks we could do, including possibly pre-calculating more stuff
436 // to use as the A* heuristic beyond just the cost to get one node further than the current
439 let dummy_directional_info = DummyDirectionalChannelInfo { // used for first_hops routes
440 cltv_expiry_delta: 0,
441 htlc_minimum_msat: 0,
442 htlc_maximum_msat: None,
445 proportional_millionths: 0,
449 // Allow MPP only if we have a features set from somewhere that indicates the payee supports
450 // it. If the payee supports it they're supposed to include it in the invoice, so that should
452 let allow_mpp = if let Some(features) = &payee_features {
453 features.supports_basic_mpp()
454 } else if let Some(node) = network.get_nodes().get(&payee) {
455 if let Some(node_info) = node.announcement_info.as_ref() {
456 node_info.features.supports_basic_mpp()
461 // Prepare the data we'll use for payee-to-payer search by
462 // inserting first hops suggested by the caller as targets.
463 // Our search will then attempt to reach them while traversing from the payee node.
464 let mut first_hop_targets: HashMap<_, (_, ChannelFeatures, _, NodeFeatures)> =
465 HashMap::with_capacity(if first_hops.is_some() { first_hops.as_ref().unwrap().len() } else { 0 });
466 if let Some(hops) = first_hops {
468 let short_channel_id = chan.short_channel_id.expect("first_hops should be filled in with usable channels, not pending ones");
469 if chan.remote_network_id == *our_node_id {
470 return Err(LightningError{err: "First hop cannot have our_node_id as a destination.".to_owned(), action: ErrorAction::IgnoreError});
472 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()));
474 if first_hop_targets.is_empty() {
475 return Err(LightningError{err: "Cannot route when there are no outbound routes away from us".to_owned(), action: ErrorAction::IgnoreError});
479 let empty_channel_features = ChannelFeatures::empty();
481 let mut targets = BinaryHeap::new(); //TODO: Do we care about switching to eg Fibbonaci heap?
482 let mut dist = HashMap::with_capacity(network.get_nodes().len());
484 // During routing, if we ignore a path due to an htlc_minimum_msat limit, we set this,
485 // indicating that we may wish to try again with a higher value, potentially paying to meet an
486 // htlc_minimum with extra fees while still finding a cheaper path.
487 let mut hit_minimum_limit;
489 // When arranging a route, we select multiple paths so that we can make a multi-path payment.
490 // We start with a path_value of the exact amount we want, and if that generates a route we may
491 // return it immediately. Otherwise, we don't stop searching for paths until we have 3x the
492 // amount we want in total across paths, selecting the best subset at the end.
493 const ROUTE_CAPACITY_PROVISION_FACTOR: u64 = 3;
494 let recommended_value_msat = final_value_msat * ROUTE_CAPACITY_PROVISION_FACTOR as u64;
495 let mut path_value_msat = final_value_msat;
497 // We don't want multiple paths (as per MPP) share liquidity of the same channels.
498 // This map allows paths to be aware of the channel use by other paths in the same call.
499 // This would help to make a better path finding decisions and not "overbook" channels.
500 // It is unaware of the directions (except for `outbound_capacity_msat` in `first_hops`).
501 let mut bookkeeped_channels_liquidity_available_msat = HashMap::with_capacity(network.get_nodes().len());
503 // Keeping track of how much value we already collected across other paths. Helps to decide:
504 // - how much a new path should be transferring (upper bound);
505 // - whether a channel should be disregarded because
506 // it's available liquidity is too small comparing to how much more we need to collect;
507 // - when we want to stop looking for new paths.
508 let mut already_collected_value_msat = 0;
510 macro_rules! add_entry {
511 // Adds entry which goes from $src_node_id to $dest_node_id
512 // over the channel with id $chan_id with fees described in
513 // $directional_info.
514 // $next_hops_fee_msat represents the fees paid for using all the channel *after* this one,
515 // since that value has to be transferred over this channel.
516 ( $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,
517 $next_hops_value_contribution: expr, $next_hops_path_htlc_minimum_msat: expr ) => {
518 // Channels to self should not be used. This is more of belt-and-suspenders, because in
519 // practice these cases should be caught earlier:
520 // - for regular channels at channel announcement (TODO)
521 // - for first and last hops early in get_route
522 if $src_node_id != $dest_node_id.clone() {
523 let available_liquidity_msat = bookkeeped_channels_liquidity_available_msat.entry($chan_id.clone()).or_insert_with(|| {
524 let mut initial_liquidity_available_msat = None;
525 if let Some(capacity_sats) = $capacity_sats {
526 initial_liquidity_available_msat = Some(capacity_sats * 1000);
529 if let Some(htlc_maximum_msat) = $directional_info.htlc_maximum_msat {
530 if let Some(available_msat) = initial_liquidity_available_msat {
531 initial_liquidity_available_msat = Some(cmp::min(available_msat, htlc_maximum_msat));
533 initial_liquidity_available_msat = Some(htlc_maximum_msat);
537 match initial_liquidity_available_msat {
538 Some(available_msat) => available_msat,
539 // We assume channels with unknown balance have
540 // a capacity of 0.0025 BTC (or 250_000 sats).
541 None => 250_000 * 1000
545 // It is tricky to substract $next_hops_fee_msat from available liquidity here.
546 // It may be misleading because we might later choose to reduce the value transferred
547 // over these channels, and the channel which was insufficient might become sufficient.
548 // Worst case: we drop a good channel here because it can't cover the high following
549 // fees caused by one expensive channel, but then this channel could have been used
550 // if the amount being transferred over this path is lower.
551 // We do this for now, but this is a subject for removal.
552 if let Some(available_value_contribution_msat) = available_liquidity_msat.checked_sub($next_hops_fee_msat) {
554 // Routing Fragmentation Mitigation heuristic:
556 // Routing fragmentation across many payment paths increases the overall routing
557 // fees as you have irreducible routing fees per-link used (`fee_base_msat`).
558 // Taking too many smaller paths also increases the chance of payment failure.
559 // Thus to avoid this effect, we require from our collected links to provide
560 // at least a minimal contribution to the recommended value yet-to-be-fulfilled.
562 // This requirement is currently 5% of the remaining-to-be-collected value.
563 // This means as we successfully advance in our collection,
564 // the absolute liquidity contribution is lowered,
565 // thus increasing the number of potential channels to be selected.
567 // Derive the minimal liquidity contribution with a ratio of 20 (5%, rounded up)
568 // or 100% if we're not allowed to do multipath payments.
569 let minimal_value_contribution_msat: u64 = if allow_mpp {
570 (recommended_value_msat - already_collected_value_msat + 19) / 20
574 // Verify the liquidity offered by this channel complies to the minimal contribution.
575 let contributes_sufficient_value = available_value_contribution_msat >= minimal_value_contribution_msat;
577 let value_contribution_msat = cmp::min(available_value_contribution_msat, $next_hops_value_contribution);
578 // Includes paying fees for the use of the following channels.
579 let amount_to_transfer_over_msat: u64 = match value_contribution_msat.checked_add($next_hops_fee_msat) {
580 Some(result) => result,
581 // Can't overflow due to how the values were computed right above.
582 None => unreachable!(),
584 #[allow(unused_comparisons)] // $next_hops_path_htlc_minimum_msat is 0 in some calls so rustc complains
585 let over_path_minimum_msat = amount_to_transfer_over_msat >= $directional_info.htlc_minimum_msat &&
586 amount_to_transfer_over_msat >= $next_hops_path_htlc_minimum_msat;
588 // If HTLC minimum is larger than the amount we're going to transfer, we shouldn't
589 // bother considering this channel.
590 // Since we're choosing amount_to_transfer_over_msat as maximum possible, it can
591 // be only reduced later (not increased), so this channel should just be skipped
592 // as not sufficient.
593 if !over_path_minimum_msat {
594 hit_minimum_limit = true;
595 } else if contributes_sufficient_value {
596 // Note that low contribution here (limited by available_liquidity_msat)
597 // might violate htlc_minimum_msat on the hops which are next along the
598 // payment path (upstream to the payee). To avoid that, we recompute path
599 // path fees knowing the final path contribution after constructing it.
600 let path_htlc_minimum_msat = match compute_fees($next_hops_path_htlc_minimum_msat, $directional_info.fees)
601 .map(|fee_msat| fee_msat.checked_add($next_hops_path_htlc_minimum_msat)) {
602 Some(Some(value_msat)) => cmp::max(value_msat, $directional_info.htlc_minimum_msat),
603 _ => u64::max_value()
605 let hm_entry = dist.entry(&$src_node_id);
606 let old_entry = hm_entry.or_insert_with(|| {
607 // If there was previously no known way to access
608 // the source node (recall it goes payee-to-payer) of $chan_id, first add
609 // a semi-dummy record just to compute the fees to reach the source node.
610 // This will affect our decision on selecting $chan_id
611 // as a way to reach the $dest_node_id.
612 let mut fee_base_msat = u32::max_value();
613 let mut fee_proportional_millionths = u32::max_value();
614 if let Some(Some(fees)) = network.get_nodes().get(&$src_node_id).map(|node| node.lowest_inbound_channel_fees) {
615 fee_base_msat = fees.base_msat;
616 fee_proportional_millionths = fees.proportional_millionths;
619 pubkey: $dest_node_id.clone(),
621 channel_features: $chan_features,
623 cltv_expiry_delta: 0,
624 src_lowest_inbound_fees: RoutingFees {
625 base_msat: fee_base_msat,
626 proportional_millionths: fee_proportional_millionths,
628 channel_fees: $directional_info.fees,
629 next_hops_fee_msat: u64::max_value(),
630 hop_use_fee_msat: u64::max_value(),
631 total_fee_msat: u64::max_value(),
632 htlc_minimum_msat: $directional_info.htlc_minimum_msat,
633 path_htlc_minimum_msat,
634 was_processed: false,
635 #[cfg(any(test, feature = "fuzztarget"))]
636 value_contribution_msat,
640 #[allow(unused_mut)] // We only use the mut in cfg(test)
641 let mut should_process = !old_entry.was_processed;
642 #[cfg(any(test, feature = "fuzztarget"))]
644 // In test/fuzzing builds, we do extra checks to make sure the skipping
645 // of already-seen nodes only happens in cases we expect (see below).
646 if !should_process { should_process = true; }
650 let mut hop_use_fee_msat = 0;
651 let mut total_fee_msat = $next_hops_fee_msat;
653 // Ignore hop_use_fee_msat for channel-from-us as we assume all channels-from-us
654 // will have the same effective-fee
655 if $src_node_id != *our_node_id {
656 match compute_fees(amount_to_transfer_over_msat, $directional_info.fees) {
657 // max_value means we'll always fail
658 // the old_entry.total_fee_msat > total_fee_msat check
659 None => total_fee_msat = u64::max_value(),
661 hop_use_fee_msat = fee_msat;
662 total_fee_msat += hop_use_fee_msat;
663 // When calculating the lowest inbound fees to a node, we
664 // calculate fees here not based on the actual value we think
665 // will flow over this channel, but on the minimum value that
666 // we'll accept flowing over it. The minimum accepted value
667 // is a constant through each path collection run, ensuring
668 // consistent basis. Otherwise we may later find a
669 // different path to the source node that is more expensive,
670 // but which we consider to be cheaper because we are capacity
671 // constrained and the relative fee becomes lower.
672 match compute_fees(minimal_value_contribution_msat, old_entry.src_lowest_inbound_fees)
673 .map(|a| a.checked_add(total_fee_msat)) {
678 total_fee_msat = u64::max_value();
685 let new_graph_node = RouteGraphNode {
686 pubkey: $src_node_id,
687 lowest_fee_to_peer_through_node: total_fee_msat,
688 lowest_fee_to_node: $next_hops_fee_msat as u64 + hop_use_fee_msat,
689 value_contribution_msat: value_contribution_msat,
690 path_htlc_minimum_msat,
693 // Update the way of reaching $src_node_id with the given $chan_id (from $dest_node_id),
694 // if this way is cheaper than the already known
695 // (considering the cost to "reach" this channel from the route destination,
696 // the cost of using this channel,
697 // and the cost of routing to the source node of this channel).
698 // Also, consider that htlc_minimum_msat_difference, because we might end up
699 // paying it. Consider the following exploit:
700 // we use 2 paths to transfer 1.5 BTC. One of them is 0-fee normal 1 BTC path,
701 // and for the other one we picked a 1sat-fee path with htlc_minimum_msat of
702 // 1 BTC. Now, since the latter is more expensive, we gonna try to cut it
703 // by 0.5 BTC, but then match htlc_minimum_msat by paying a fee of 0.5 BTC
705 // Ideally the scoring could be smarter (e.g. 0.5*htlc_minimum_msat here),
706 // but it may require additional tracking - we don't want to double-count
707 // the fees included in $next_hops_path_htlc_minimum_msat, but also
708 // can't use something that may decrease on future hops.
709 let old_cost = cmp::max(old_entry.total_fee_msat, old_entry.path_htlc_minimum_msat);
710 let new_cost = cmp::max(total_fee_msat, path_htlc_minimum_msat);
712 if !old_entry.was_processed && new_cost < old_cost {
713 targets.push(new_graph_node);
714 old_entry.next_hops_fee_msat = $next_hops_fee_msat;
715 old_entry.hop_use_fee_msat = hop_use_fee_msat;
716 old_entry.total_fee_msat = total_fee_msat;
717 old_entry.pubkey = $dest_node_id.clone();
718 old_entry.short_channel_id = $chan_id.clone();
719 old_entry.channel_features = $chan_features;
720 old_entry.fee_msat = 0; // This value will be later filled with hop_use_fee_msat of the following channel
721 old_entry.cltv_expiry_delta = $directional_info.cltv_expiry_delta as u32;
722 old_entry.channel_fees = $directional_info.fees;
723 old_entry.htlc_minimum_msat = $directional_info.htlc_minimum_msat;
724 old_entry.path_htlc_minimum_msat = path_htlc_minimum_msat;
725 #[cfg(any(test, feature = "fuzztarget"))]
727 old_entry.value_contribution_msat = value_contribution_msat;
729 } else if old_entry.was_processed && new_cost < old_cost {
730 #[cfg(any(test, feature = "fuzztarget"))]
732 // If we're skipping processing a node which was previously
733 // processed even though we found another path to it with a
734 // cheaper fee, check that it was because the second path we
735 // found (which we are processing now) has a lower value
736 // contribution due to an HTLC minimum limit.
738 // e.g. take a graph with two paths from node 1 to node 2, one
739 // through channel A, and one through channel B. Channel A and
740 // B are both in the to-process heap, with their scores set by
741 // a higher htlc_minimum than fee.
742 // Channel A is processed first, and the channels onwards from
743 // node 1 are added to the to-process heap. Thereafter, we pop
744 // Channel B off of the heap, note that it has a much more
745 // restrictive htlc_maximum_msat, and recalculate the fees for
746 // all of node 1's channels using the new, reduced, amount.
748 // This would be bogus - we'd be selecting a higher-fee path
749 // with a lower htlc_maximum_msat instead of the one we'd
750 // already decided to use.
751 debug_assert!(path_htlc_minimum_msat < old_entry.path_htlc_minimum_msat);
752 debug_assert!(value_contribution_msat < old_entry.value_contribution_msat);
762 let empty_node_features = NodeFeatures::empty();
763 // Find ways (channels with destination) to reach a given node and store them
764 // in the corresponding data structures (routing graph etc).
765 // $fee_to_target_msat represents how much it costs to reach to this node from the payee,
766 // meaning how much will be paid in fees after this node (to the best of our knowledge).
767 // This data can later be helpful to optimize routing (pay lower fees).
768 macro_rules! add_entries_to_cheapest_to_target_node {
769 ( $node: expr, $node_id: expr, $fee_to_target_msat: expr, $next_hops_value_contribution: expr, $next_hops_path_htlc_minimum_msat: expr ) => {
770 let skip_node = if let Some(elem) = dist.get_mut($node_id) {
771 let was_processed = elem.was_processed;
772 elem.was_processed = true;
775 // Entries are added to dist in add_entry!() when there is a channel from a node.
776 // Because there are no channels from payee, it will not have a dist entry at this point.
777 // If we're processing any other node, it is always be the result of a channel from it.
778 assert_eq!($node_id, payee);
783 if first_hops.is_some() {
784 if let Some(&(ref first_hop, ref features, ref outbound_capacity_msat, _)) = first_hop_targets.get(&$node_id) {
785 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);
789 let features = if let Some(node_info) = $node.announcement_info.as_ref() {
795 if !features.requires_unknown_bits() {
796 for chan_id in $node.channels.iter() {
797 let chan = network.get_channels().get(chan_id).unwrap();
798 if !chan.features.requires_unknown_bits() {
799 if chan.node_one == *$node_id {
800 // ie $node is one, ie next hop in A* is two, via the two_to_one channel
801 if first_hops.is_none() || chan.node_two != *our_node_id {
802 if let Some(two_to_one) = chan.two_to_one.as_ref() {
803 if two_to_one.enabled {
804 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);
809 if first_hops.is_none() || chan.node_one != *our_node_id {
810 if let Some(one_to_two) = chan.one_to_two.as_ref() {
811 if one_to_two.enabled {
812 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);
824 let mut payment_paths = Vec::<PaymentPath>::new();
826 // TODO: diversify by nodes (so that all paths aren't doomed if one node is offline).
827 'paths_collection: loop {
828 // For every new path, start from scratch, except
829 // bookkeeped_channels_liquidity_available_msat, which will improve
830 // the further iterations of path finding. Also don't erase first_hop_targets.
833 hit_minimum_limit = false;
835 // If first hop is a private channel and the only way to reach the payee, this is the only
836 // place where it could be added.
837 if first_hops.is_some() {
838 if let Some(&(ref first_hop, ref features, ref outbound_capacity_msat, _)) = first_hop_targets.get(&payee) {
839 add_entry!(first_hop, *our_node_id, payee, dummy_directional_info, Some(outbound_capacity_msat / 1000), features, 0, path_value_msat, 0);
843 // Add the payee as a target, so that the payee-to-payer
844 // search algorithm knows what to start with.
845 match network.get_nodes().get(payee) {
846 // The payee is not in our network graph, so nothing to add here.
847 // There is still a chance of reaching them via last_hops though,
848 // so don't yet fail the payment here.
849 // If not, targets.pop() will not even let us enter the loop in step 2.
852 add_entries_to_cheapest_to_target_node!(node, payee, 0, path_value_msat, 0);
857 // If a caller provided us with last hops, add them to routing targets. Since this happens
858 // earlier than general path finding, they will be somewhat prioritized, although currently
859 // it matters only if the fees are exactly the same.
860 for hop in last_hops.iter() {
861 let have_hop_src_in_graph =
862 if let Some(&(ref first_hop, ref features, ref outbound_capacity_msat, _)) = first_hop_targets.get(&hop.src_node_id) {
863 // If this hop connects to a node with which we have a direct channel, ignore
864 // the network graph and add both the hop and our direct channel to
865 // the candidate set.
867 // Currently there are no channel-context features defined, so we are a
868 // bit lazy here. In the future, we should pull them out via our
869 // ChannelManager, but there's no reason to waste the space until we
871 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);
874 // In any other case, only add the hop if the source is in the regular network
876 network.get_nodes().get(&hop.src_node_id).is_some()
878 if have_hop_src_in_graph {
879 // BOLT 11 doesn't allow inclusion of features for the last hop hints, which
880 // really sucks, cause we're gonna need that eventually.
881 let last_hop_htlc_minimum_msat: u64 = match hop.htlc_minimum_msat {
882 Some(htlc_minimum_msat) => htlc_minimum_msat,
885 let directional_info = DummyDirectionalChannelInfo {
886 cltv_expiry_delta: hop.cltv_expiry_delta as u32,
887 htlc_minimum_msat: last_hop_htlc_minimum_msat,
888 htlc_maximum_msat: hop.htlc_maximum_msat,
891 add_entry!(hop.short_channel_id, hop.src_node_id, payee, directional_info, None::<u64>, &empty_channel_features, 0, path_value_msat, 0);
895 // At this point, targets are filled with the data from first and
896 // last hops communicated by the caller, and the payment receiver.
897 let mut found_new_path = false;
900 // If this loop terminates due the exhaustion of targets, two situations are possible:
901 // - not enough outgoing liquidity:
902 // 0 < already_collected_value_msat < final_value_msat
903 // - enough outgoing liquidity:
904 // final_value_msat <= already_collected_value_msat < recommended_value_msat
905 // Both these cases (and other cases except reaching recommended_value_msat) mean that
906 // paths_collection will be stopped because found_new_path==false.
907 // This is not necessarily a routing failure.
908 'path_construction: while let Some(RouteGraphNode { pubkey, lowest_fee_to_node, value_contribution_msat, path_htlc_minimum_msat, .. }) = targets.pop() {
910 // Since we're going payee-to-payer, hitting our node as a target means we should stop
911 // traversing the graph and arrange the path out of what we found.
912 if pubkey == *our_node_id {
913 let mut new_entry = dist.remove(&our_node_id).unwrap();
914 let mut ordered_hops = vec!((new_entry.clone(), NodeFeatures::empty()));
917 if let Some(&(_, _, _, ref features)) = first_hop_targets.get(&ordered_hops.last().unwrap().0.pubkey) {
918 ordered_hops.last_mut().unwrap().1 = features.clone();
919 } else if let Some(node) = network.get_nodes().get(&ordered_hops.last().unwrap().0.pubkey) {
920 if let Some(node_info) = node.announcement_info.as_ref() {
921 ordered_hops.last_mut().unwrap().1 = node_info.features.clone();
923 ordered_hops.last_mut().unwrap().1 = NodeFeatures::empty();
926 // We should be able to fill in features for everything except the last
927 // hop, if the last hop was provided via a BOLT 11 invoice (though we
928 // should be able to extend it further as BOLT 11 does have feature
929 // flags for the last hop node itself).
930 assert!(ordered_hops.last().unwrap().0.pubkey == *payee);
933 // Means we succesfully traversed from the payer to the payee, now
934 // save this path for the payment route. Also, update the liquidity
935 // remaining on the used hops, so that we take them into account
936 // while looking for more paths.
937 if ordered_hops.last().unwrap().0.pubkey == *payee {
941 new_entry = match dist.remove(&ordered_hops.last().unwrap().0.pubkey) {
942 Some(payment_hop) => payment_hop,
943 // We can't arrive at None because, if we ever add an entry to targets,
944 // we also fill in the entry in dist (see add_entry!).
945 None => unreachable!(),
947 // We "propagate" the fees one hop backward (topologically) here,
948 // so that fees paid for a HTLC forwarding on the current channel are
949 // associated with the previous channel (where they will be subtracted).
950 ordered_hops.last_mut().unwrap().0.fee_msat = new_entry.hop_use_fee_msat;
951 ordered_hops.last_mut().unwrap().0.cltv_expiry_delta = new_entry.cltv_expiry_delta;
952 ordered_hops.push((new_entry.clone(), NodeFeatures::empty()));
954 ordered_hops.last_mut().unwrap().0.fee_msat = value_contribution_msat;
955 ordered_hops.last_mut().unwrap().0.hop_use_fee_msat = 0;
956 ordered_hops.last_mut().unwrap().0.cltv_expiry_delta = final_cltv;
958 let mut payment_path = PaymentPath {hops: ordered_hops};
960 // We could have possibly constructed a slightly inconsistent path: since we reduce
961 // value being transferred along the way, we could have violated htlc_minimum_msat
962 // on some channels we already passed (assuming dest->source direction). Here, we
963 // recompute the fees again, so that if that's the case, we match the currently
964 // underpaid htlc_minimum_msat with fees.
965 payment_path.update_value_and_recompute_fees(cmp::min(value_contribution_msat, final_value_msat));
967 // Since a path allows to transfer as much value as
968 // the smallest channel it has ("bottleneck"), we should recompute
969 // the fees so sender HTLC don't overpay fees when traversing
970 // larger channels than the bottleneck. This may happen because
971 // when we were selecting those channels we were not aware how much value
972 // this path will transfer, and the relative fee for them
973 // might have been computed considering a larger value.
974 // Remember that we used these channels so that we don't rely
975 // on the same liquidity in future paths.
976 let mut prevented_redundant_path_selection = false;
977 for (payment_hop, _) in payment_path.hops.iter() {
978 let channel_liquidity_available_msat = bookkeeped_channels_liquidity_available_msat.get_mut(&payment_hop.short_channel_id).unwrap();
979 let mut spent_on_hop_msat = value_contribution_msat;
980 let next_hops_fee_msat = payment_hop.next_hops_fee_msat;
981 spent_on_hop_msat += next_hops_fee_msat;
982 if spent_on_hop_msat == *channel_liquidity_available_msat {
983 // If this path used all of this channel's available liquidity, we know
984 // this path will not be selected again in the next loop iteration.
985 prevented_redundant_path_selection = true;
987 *channel_liquidity_available_msat -= spent_on_hop_msat;
989 if !prevented_redundant_path_selection {
990 // If we weren't capped by hitting a liquidity limit on a channel in the path,
991 // we'll probably end up picking the same path again on the next iteration.
992 // Decrease the available liquidity of a hop in the middle of the path.
993 let victim_liquidity = bookkeeped_channels_liquidity_available_msat.get_mut(
994 &payment_path.hops[(payment_path.hops.len() - 1) / 2].0.short_channel_id).unwrap();
995 *victim_liquidity = 0;
998 // Track the total amount all our collected paths allow to send so that we:
999 // - know when to stop looking for more paths
1000 // - know which of the hops are useless considering how much more sats we need
1001 // (contributes_sufficient_value)
1002 already_collected_value_msat += value_contribution_msat;
1004 payment_paths.push(payment_path);
1005 found_new_path = true;
1006 break 'path_construction;
1009 // If we found a path back to the payee, we shouldn't try to process it again. This is
1010 // the equivalent of the `elem.was_processed` check in
1011 // add_entries_to_cheapest_to_target_node!() (see comment there for more info).
1012 if pubkey == *payee { continue 'path_construction; }
1014 // Otherwise, since the current target node is not us,
1015 // keep "unrolling" the payment graph from payee to payer by
1016 // finding a way to reach the current target from the payer side.
1017 match network.get_nodes().get(&pubkey) {
1020 add_entries_to_cheapest_to_target_node!(node, &pubkey, lowest_fee_to_node, value_contribution_msat, path_htlc_minimum_msat);
1026 // If we don't support MPP, no use trying to gather more value ever.
1027 break 'paths_collection;
1031 // Stop either when the recommended value is reached or if no new path was found in this
1033 // In the latter case, making another path finding attempt won't help,
1034 // because we deterministically terminated the search due to low liquidity.
1035 if already_collected_value_msat >= recommended_value_msat || !found_new_path {
1036 break 'paths_collection;
1037 } else if found_new_path && already_collected_value_msat == final_value_msat && payment_paths.len() == 1 {
1038 // Further, if this was our first walk of the graph, and we weren't limited by an
1039 // htlc_minimum_msat, return immediately because this path should suffice. If we were
1040 // limited by an htlc_minimum_msat value, find another path with a higher value,
1041 // potentially allowing us to pay fees to meet the htlc_minimum on the new path while
1042 // still keeping a lower total fee than this path.
1043 if !hit_minimum_limit {
1044 break 'paths_collection;
1046 path_value_msat = recommended_value_msat;
1051 if payment_paths.len() == 0 {
1052 return Err(LightningError{err: "Failed to find a path to the given destination".to_owned(), action: ErrorAction::IgnoreError});
1055 if already_collected_value_msat < final_value_msat {
1056 return Err(LightningError{err: "Failed to find a sufficient route to the given destination".to_owned(), action: ErrorAction::IgnoreError});
1059 // Sort by total fees and take the best paths.
1060 payment_paths.sort_by_key(|path| path.get_total_fee_paid_msat());
1061 if payment_paths.len() > 50 {
1062 payment_paths.truncate(50);
1065 // Draw multiple sufficient routes by randomly combining the selected paths.
1066 let mut drawn_routes = Vec::new();
1067 for i in 0..payment_paths.len() {
1068 let mut cur_route = Vec::<PaymentPath>::new();
1069 let mut aggregate_route_value_msat = 0;
1072 // TODO: real random shuffle
1073 // Currently just starts with i_th and goes up to i-1_th in a looped way.
1074 let cur_payment_paths = [&payment_paths[i..], &payment_paths[..i]].concat();
1077 for payment_path in cur_payment_paths {
1078 cur_route.push(payment_path.clone());
1079 aggregate_route_value_msat += payment_path.get_value_msat();
1080 if aggregate_route_value_msat > final_value_msat {
1081 // Last path likely overpaid. Substract it from the most expensive
1082 // (in terms of proportional fee) path in this route and recompute fees.
1083 // This might be not the most economically efficient way, but fewer paths
1084 // also makes routing more reliable.
1085 let mut overpaid_value_msat = aggregate_route_value_msat - final_value_msat;
1087 // First, drop some expensive low-value paths entirely if possible.
1088 // Sort by value so that we drop many really-low values first, since
1089 // fewer paths is better: the payment is less likely to fail.
1090 // TODO: this could also be optimized by also sorting by feerate_per_sat_routed,
1091 // so that the sender pays less fees overall. And also htlc_minimum_msat.
1092 cur_route.sort_by_key(|path| path.get_value_msat());
1093 // We should make sure that at least 1 path left.
1094 let mut paths_left = cur_route.len();
1095 cur_route.retain(|path| {
1096 if paths_left == 1 {
1099 let mut keep = true;
1100 let path_value_msat = path.get_value_msat();
1101 if path_value_msat <= overpaid_value_msat {
1103 overpaid_value_msat -= path_value_msat;
1109 if overpaid_value_msat == 0 {
1113 assert!(cur_route.len() > 0);
1116 // Now, substract the overpaid value from the most-expensive path.
1117 // TODO: this could also be optimized by also sorting by feerate_per_sat_routed,
1118 // so that the sender pays less fees overall. And also htlc_minimum_msat.
1119 cur_route.sort_by_key(|path| { path.hops.iter().map(|hop| hop.0.channel_fees.proportional_millionths as u64).sum::<u64>() });
1120 let expensive_payment_path = cur_route.first_mut().unwrap();
1121 // We already dropped all the small channels above, meaning all the
1122 // remaining channels are larger than remaining overpaid_value_msat.
1123 // Thus, this can't be negative.
1124 let expensive_path_new_value_msat = expensive_payment_path.get_value_msat() - overpaid_value_msat;
1125 expensive_payment_path.update_value_and_recompute_fees(expensive_path_new_value_msat);
1129 drawn_routes.push(cur_route);
1133 // Select the best route by lowest total fee.
1134 drawn_routes.sort_by_key(|paths| paths.iter().map(|path| path.get_total_fee_paid_msat()).sum::<u64>());
1135 let mut selected_paths = Vec::<Vec<RouteHop>>::new();
1136 for payment_path in drawn_routes.first().unwrap() {
1137 selected_paths.push(payment_path.hops.iter().map(|(payment_hop, node_features)| {
1139 pubkey: payment_hop.pubkey,
1140 node_features: node_features.clone(),
1141 short_channel_id: payment_hop.short_channel_id,
1142 channel_features: payment_hop.channel_features.clone(),
1143 fee_msat: payment_hop.fee_msat,
1144 cltv_expiry_delta: payment_hop.cltv_expiry_delta,
1149 if let Some(features) = &payee_features {
1150 for path in selected_paths.iter_mut() {
1151 path.last_mut().unwrap().node_features = features.to_context();
1155 let route = Route { paths: selected_paths };
1156 log_trace!(logger, "Got route: {}", log_route!(route));
1162 use routing::router::{get_route, RouteHint, RoutingFees};
1163 use routing::network_graph::{NetworkGraph, NetGraphMsgHandler};
1164 use ln::features::{ChannelFeatures, InitFeatures, InvoiceFeatures, NodeFeatures};
1165 use ln::msgs::{ErrorAction, LightningError, OptionalField, UnsignedChannelAnnouncement, ChannelAnnouncement, RoutingMessageHandler,
1166 NodeAnnouncement, UnsignedNodeAnnouncement, ChannelUpdate, UnsignedChannelUpdate};
1167 use ln::channelmanager;
1168 use util::test_utils;
1169 use util::ser::Writeable;
1171 use bitcoin::hashes::sha256d::Hash as Sha256dHash;
1172 use bitcoin::hashes::Hash;
1173 use bitcoin::network::constants::Network;
1174 use bitcoin::blockdata::constants::genesis_block;
1175 use bitcoin::blockdata::script::Builder;
1176 use bitcoin::blockdata::opcodes;
1177 use bitcoin::blockdata::transaction::TxOut;
1181 use bitcoin::secp256k1::key::{PublicKey,SecretKey};
1182 use bitcoin::secp256k1::{Secp256k1, All};
1186 // Using the same keys for LN and BTC ids
1187 fn add_channel(net_graph_msg_handler: &NetGraphMsgHandler<Arc<test_utils::TestChainSource>, Arc<test_utils::TestLogger>>, secp_ctx: &Secp256k1<All>, node_1_privkey: &SecretKey,
1188 node_2_privkey: &SecretKey, features: ChannelFeatures, short_channel_id: u64) {
1189 let node_id_1 = PublicKey::from_secret_key(&secp_ctx, node_1_privkey);
1190 let node_id_2 = PublicKey::from_secret_key(&secp_ctx, node_2_privkey);
1192 let unsigned_announcement = UnsignedChannelAnnouncement {
1194 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1198 bitcoin_key_1: node_id_1,
1199 bitcoin_key_2: node_id_2,
1200 excess_data: Vec::new(),
1203 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1204 let valid_announcement = ChannelAnnouncement {
1205 node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
1206 node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
1207 bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
1208 bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
1209 contents: unsigned_announcement.clone(),
1211 match net_graph_msg_handler.handle_channel_announcement(&valid_announcement) {
1212 Ok(res) => assert!(res),
1217 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) {
1218 let msghash = hash_to_message!(&Sha256dHash::hash(&update.encode()[..])[..]);
1219 let valid_channel_update = ChannelUpdate {
1220 signature: secp_ctx.sign(&msghash, node_privkey),
1221 contents: update.clone()
1224 match net_graph_msg_handler.handle_channel_update(&valid_channel_update) {
1225 Ok(res) => assert!(res),
1230 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,
1231 features: NodeFeatures, timestamp: u32) {
1232 let node_id = PublicKey::from_secret_key(&secp_ctx, node_privkey);
1233 let unsigned_announcement = UnsignedNodeAnnouncement {
1239 addresses: Vec::new(),
1240 excess_address_data: Vec::new(),
1241 excess_data: Vec::new(),
1243 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1244 let valid_announcement = NodeAnnouncement {
1245 signature: secp_ctx.sign(&msghash, node_privkey),
1246 contents: unsigned_announcement.clone()
1249 match net_graph_msg_handler.handle_node_announcement(&valid_announcement) {
1255 fn get_nodes(secp_ctx: &Secp256k1<All>) -> (SecretKey, PublicKey, Vec<SecretKey>, Vec<PublicKey>) {
1256 let privkeys: Vec<SecretKey> = (2..10).map(|i| {
1257 SecretKey::from_slice(&hex::decode(format!("{:02}", i).repeat(32)).unwrap()[..]).unwrap()
1260 let pubkeys = privkeys.iter().map(|secret| PublicKey::from_secret_key(&secp_ctx, secret)).collect();
1262 let our_privkey = SecretKey::from_slice(&hex::decode("01".repeat(32)).unwrap()[..]).unwrap();
1263 let our_id = PublicKey::from_secret_key(&secp_ctx, &our_privkey);
1265 (our_privkey, our_id, privkeys, pubkeys)
1268 fn id_to_feature_flags(id: u8) -> Vec<u8> {
1269 // Set the feature flags to the id'th odd (ie non-required) feature bit so that we can
1270 // test for it later.
1271 let idx = (id - 1) * 2 + 1;
1273 vec![1 << (idx - 8*3), 0, 0, 0]
1274 } else if idx > 8*2 {
1275 vec![1 << (idx - 8*2), 0, 0]
1276 } else if idx > 8*1 {
1277 vec![1 << (idx - 8*1), 0]
1283 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>) {
1284 let secp_ctx = Secp256k1::new();
1285 let logger = Arc::new(test_utils::TestLogger::new());
1286 let chain_monitor = Arc::new(test_utils::TestChainSource::new(Network::Testnet));
1287 let net_graph_msg_handler = NetGraphMsgHandler::new(genesis_block(Network::Testnet).header.block_hash(), None, Arc::clone(&logger));
1288 // Build network from our_id to node7:
1290 // -1(1)2- node0 -1(3)2-
1292 // our_id -1(12)2- node7 -1(13)2--- node2
1294 // -1(2)2- node1 -1(4)2-
1297 // chan1 1-to-2: disabled
1298 // chan1 2-to-1: enabled, 0 fee
1300 // chan2 1-to-2: enabled, ignored fee
1301 // chan2 2-to-1: enabled, 0 fee
1303 // chan3 1-to-2: enabled, 0 fee
1304 // chan3 2-to-1: enabled, 100 msat fee
1306 // chan4 1-to-2: enabled, 100% fee
1307 // chan4 2-to-1: enabled, 0 fee
1309 // chan12 1-to-2: enabled, ignored fee
1310 // chan12 2-to-1: enabled, 0 fee
1312 // chan13 1-to-2: enabled, 200% fee
1313 // chan13 2-to-1: enabled, 0 fee
1316 // -1(5)2- node3 -1(8)2--
1320 // node2--1(6)2- node4 -1(9)2--- node6 (not in global route map)
1322 // -1(7)2- node5 -1(10)2-
1324 // chan5 1-to-2: enabled, 100 msat fee
1325 // chan5 2-to-1: enabled, 0 fee
1327 // chan6 1-to-2: enabled, 0 fee
1328 // chan6 2-to-1: enabled, 0 fee
1330 // chan7 1-to-2: enabled, 100% fee
1331 // chan7 2-to-1: enabled, 0 fee
1333 // chan8 1-to-2: enabled, variable fee (0 then 1000 msat)
1334 // chan8 2-to-1: enabled, 0 fee
1336 // chan9 1-to-2: enabled, 1001 msat fee
1337 // chan9 2-to-1: enabled, 0 fee
1339 // chan10 1-to-2: enabled, 0 fee
1340 // chan10 2-to-1: enabled, 0 fee
1342 // chan11 1-to-2: enabled, 0 fee
1343 // chan11 2-to-1: enabled, 0 fee
1345 let (our_privkey, _, privkeys, _) = get_nodes(&secp_ctx);
1347 add_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, &privkeys[0], ChannelFeatures::from_le_bytes(id_to_feature_flags(1)), 1);
1348 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
1349 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1350 short_channel_id: 1,
1353 cltv_expiry_delta: 0,
1354 htlc_minimum_msat: 0,
1355 htlc_maximum_msat: OptionalField::Absent,
1357 fee_proportional_millionths: 0,
1358 excess_data: Vec::new()
1361 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[0], NodeFeatures::from_le_bytes(id_to_feature_flags(1)), 0);
1363 add_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, &privkeys[1], ChannelFeatures::from_le_bytes(id_to_feature_flags(2)), 2);
1364 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
1365 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1366 short_channel_id: 2,
1369 cltv_expiry_delta: u16::max_value(),
1370 htlc_minimum_msat: 0,
1371 htlc_maximum_msat: OptionalField::Absent,
1372 fee_base_msat: u32::max_value(),
1373 fee_proportional_millionths: u32::max_value(),
1374 excess_data: Vec::new()
1376 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
1377 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1378 short_channel_id: 2,
1381 cltv_expiry_delta: 0,
1382 htlc_minimum_msat: 0,
1383 htlc_maximum_msat: OptionalField::Absent,
1385 fee_proportional_millionths: 0,
1386 excess_data: Vec::new()
1389 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[1], NodeFeatures::from_le_bytes(id_to_feature_flags(2)), 0);
1391 add_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, &privkeys[7], ChannelFeatures::from_le_bytes(id_to_feature_flags(12)), 12);
1392 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
1393 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1394 short_channel_id: 12,
1397 cltv_expiry_delta: u16::max_value(),
1398 htlc_minimum_msat: 0,
1399 htlc_maximum_msat: OptionalField::Absent,
1400 fee_base_msat: u32::max_value(),
1401 fee_proportional_millionths: u32::max_value(),
1402 excess_data: Vec::new()
1404 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
1405 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1406 short_channel_id: 12,
1409 cltv_expiry_delta: 0,
1410 htlc_minimum_msat: 0,
1411 htlc_maximum_msat: OptionalField::Absent,
1413 fee_proportional_millionths: 0,
1414 excess_data: Vec::new()
1417 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[7], NodeFeatures::from_le_bytes(id_to_feature_flags(8)), 0);
1419 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], &privkeys[2], ChannelFeatures::from_le_bytes(id_to_feature_flags(3)), 3);
1420 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
1421 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1422 short_channel_id: 3,
1425 cltv_expiry_delta: (3 << 8) | 1,
1426 htlc_minimum_msat: 0,
1427 htlc_maximum_msat: OptionalField::Absent,
1429 fee_proportional_millionths: 0,
1430 excess_data: Vec::new()
1432 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
1433 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1434 short_channel_id: 3,
1437 cltv_expiry_delta: (3 << 8) | 2,
1438 htlc_minimum_msat: 0,
1439 htlc_maximum_msat: OptionalField::Absent,
1441 fee_proportional_millionths: 0,
1442 excess_data: Vec::new()
1445 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], &privkeys[2], ChannelFeatures::from_le_bytes(id_to_feature_flags(4)), 4);
1446 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
1447 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1448 short_channel_id: 4,
1451 cltv_expiry_delta: (4 << 8) | 1,
1452 htlc_minimum_msat: 0,
1453 htlc_maximum_msat: OptionalField::Absent,
1455 fee_proportional_millionths: 1000000,
1456 excess_data: Vec::new()
1458 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
1459 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1460 short_channel_id: 4,
1463 cltv_expiry_delta: (4 << 8) | 2,
1464 htlc_minimum_msat: 0,
1465 htlc_maximum_msat: OptionalField::Absent,
1467 fee_proportional_millionths: 0,
1468 excess_data: Vec::new()
1471 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], &privkeys[2], ChannelFeatures::from_le_bytes(id_to_feature_flags(13)), 13);
1472 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
1473 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1474 short_channel_id: 13,
1477 cltv_expiry_delta: (13 << 8) | 1,
1478 htlc_minimum_msat: 0,
1479 htlc_maximum_msat: OptionalField::Absent,
1481 fee_proportional_millionths: 2000000,
1482 excess_data: Vec::new()
1484 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
1485 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1486 short_channel_id: 13,
1489 cltv_expiry_delta: (13 << 8) | 2,
1490 htlc_minimum_msat: 0,
1491 htlc_maximum_msat: OptionalField::Absent,
1493 fee_proportional_millionths: 0,
1494 excess_data: Vec::new()
1497 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[2], NodeFeatures::from_le_bytes(id_to_feature_flags(3)), 0);
1499 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], &privkeys[4], ChannelFeatures::from_le_bytes(id_to_feature_flags(6)), 6);
1500 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
1501 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1502 short_channel_id: 6,
1505 cltv_expiry_delta: (6 << 8) | 1,
1506 htlc_minimum_msat: 0,
1507 htlc_maximum_msat: OptionalField::Absent,
1509 fee_proportional_millionths: 0,
1510 excess_data: Vec::new()
1512 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
1513 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1514 short_channel_id: 6,
1517 cltv_expiry_delta: (6 << 8) | 2,
1518 htlc_minimum_msat: 0,
1519 htlc_maximum_msat: OptionalField::Absent,
1521 fee_proportional_millionths: 0,
1522 excess_data: Vec::new(),
1525 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(11)), 11);
1526 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
1527 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1528 short_channel_id: 11,
1531 cltv_expiry_delta: (11 << 8) | 1,
1532 htlc_minimum_msat: 0,
1533 htlc_maximum_msat: OptionalField::Absent,
1535 fee_proportional_millionths: 0,
1536 excess_data: Vec::new()
1538 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[3], UnsignedChannelUpdate {
1539 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1540 short_channel_id: 11,
1543 cltv_expiry_delta: (11 << 8) | 2,
1544 htlc_minimum_msat: 0,
1545 htlc_maximum_msat: OptionalField::Absent,
1547 fee_proportional_millionths: 0,
1548 excess_data: Vec::new()
1551 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[4], NodeFeatures::from_le_bytes(id_to_feature_flags(5)), 0);
1553 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[3], NodeFeatures::from_le_bytes(id_to_feature_flags(4)), 0);
1555 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], &privkeys[5], ChannelFeatures::from_le_bytes(id_to_feature_flags(7)), 7);
1556 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
1557 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1558 short_channel_id: 7,
1561 cltv_expiry_delta: (7 << 8) | 1,
1562 htlc_minimum_msat: 0,
1563 htlc_maximum_msat: OptionalField::Absent,
1565 fee_proportional_millionths: 1000000,
1566 excess_data: Vec::new()
1568 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[5], UnsignedChannelUpdate {
1569 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1570 short_channel_id: 7,
1573 cltv_expiry_delta: (7 << 8) | 2,
1574 htlc_minimum_msat: 0,
1575 htlc_maximum_msat: OptionalField::Absent,
1577 fee_proportional_millionths: 0,
1578 excess_data: Vec::new()
1581 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[5], NodeFeatures::from_le_bytes(id_to_feature_flags(6)), 0);
1583 (secp_ctx, net_graph_msg_handler, chain_monitor, logger)
1587 fn simple_route_test() {
1588 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
1589 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
1591 // Simple route to 2 via 1
1593 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)) {
1594 assert_eq!(err, "Cannot send a payment of 0 msat");
1595 } else { panic!(); }
1597 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();
1598 assert_eq!(route.paths[0].len(), 2);
1600 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
1601 assert_eq!(route.paths[0][0].short_channel_id, 2);
1602 assert_eq!(route.paths[0][0].fee_msat, 100);
1603 assert_eq!(route.paths[0][0].cltv_expiry_delta, (4 << 8) | 1);
1604 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
1605 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
1607 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
1608 assert_eq!(route.paths[0][1].short_channel_id, 4);
1609 assert_eq!(route.paths[0][1].fee_msat, 100);
1610 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
1611 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
1612 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
1616 fn invalid_first_hop_test() {
1617 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
1618 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
1620 // Simple route to 2 via 1
1622 let our_chans = vec![channelmanager::ChannelDetails {
1623 channel_id: [0; 32],
1624 short_channel_id: Some(2),
1625 remote_network_id: our_id,
1626 counterparty_features: InitFeatures::from_le_bytes(vec![0b11]),
1627 channel_value_satoshis: 100000,
1629 outbound_capacity_msat: 100000,
1630 inbound_capacity_msat: 100000,
1632 counterparty_forwarding_info: None,
1635 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)) {
1636 assert_eq!(err, "First hop cannot have our_node_id as a destination.");
1637 } else { panic!(); }
1639 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();
1640 assert_eq!(route.paths[0].len(), 2);
1644 fn htlc_minimum_test() {
1645 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
1646 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
1648 // Simple route to 2 via 1
1650 // Disable other paths
1651 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
1652 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1653 short_channel_id: 12,
1655 flags: 2, // to disable
1656 cltv_expiry_delta: 0,
1657 htlc_minimum_msat: 0,
1658 htlc_maximum_msat: OptionalField::Absent,
1660 fee_proportional_millionths: 0,
1661 excess_data: Vec::new()
1663 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
1664 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1665 short_channel_id: 3,
1667 flags: 2, // to disable
1668 cltv_expiry_delta: 0,
1669 htlc_minimum_msat: 0,
1670 htlc_maximum_msat: OptionalField::Absent,
1672 fee_proportional_millionths: 0,
1673 excess_data: Vec::new()
1675 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
1676 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1677 short_channel_id: 13,
1679 flags: 2, // to disable
1680 cltv_expiry_delta: 0,
1681 htlc_minimum_msat: 0,
1682 htlc_maximum_msat: OptionalField::Absent,
1684 fee_proportional_millionths: 0,
1685 excess_data: Vec::new()
1687 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
1688 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1689 short_channel_id: 6,
1691 flags: 2, // to disable
1692 cltv_expiry_delta: 0,
1693 htlc_minimum_msat: 0,
1694 htlc_maximum_msat: OptionalField::Absent,
1696 fee_proportional_millionths: 0,
1697 excess_data: Vec::new()
1699 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
1700 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1701 short_channel_id: 7,
1703 flags: 2, // to disable
1704 cltv_expiry_delta: 0,
1705 htlc_minimum_msat: 0,
1706 htlc_maximum_msat: OptionalField::Absent,
1708 fee_proportional_millionths: 0,
1709 excess_data: Vec::new()
1712 // Check against amount_to_transfer_over_msat.
1713 // Set minimal HTLC of 200_000_000 msat.
1714 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
1715 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1716 short_channel_id: 2,
1719 cltv_expiry_delta: 0,
1720 htlc_minimum_msat: 200_000_000,
1721 htlc_maximum_msat: OptionalField::Absent,
1723 fee_proportional_millionths: 0,
1724 excess_data: Vec::new()
1727 // Second hop only allows to forward 199_999_999 at most, thus not allowing the first hop to
1729 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
1730 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1731 short_channel_id: 4,
1734 cltv_expiry_delta: 0,
1735 htlc_minimum_msat: 0,
1736 htlc_maximum_msat: OptionalField::Present(199_999_999),
1738 fee_proportional_millionths: 0,
1739 excess_data: Vec::new()
1742 // Not possible to send 199_999_999, because the minimum on channel=2 is 200_000_000.
1743 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)) {
1744 assert_eq!(err, "Failed to find a path to the given destination");
1745 } else { panic!(); }
1747 // Lift the restriction on the first hop.
1748 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
1749 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1750 short_channel_id: 2,
1753 cltv_expiry_delta: 0,
1754 htlc_minimum_msat: 0,
1755 htlc_maximum_msat: OptionalField::Absent,
1757 fee_proportional_millionths: 0,
1758 excess_data: Vec::new()
1761 // A payment above the minimum should pass
1762 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();
1763 assert_eq!(route.paths[0].len(), 2);
1767 fn htlc_minimum_overpay_test() {
1768 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
1769 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
1771 // A route to node#2 via two paths.
1772 // One path allows transferring 35-40 sats, another one also allows 35-40 sats.
1773 // Thus, they can't send 60 without overpaying.
1774 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
1775 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1776 short_channel_id: 2,
1779 cltv_expiry_delta: 0,
1780 htlc_minimum_msat: 35_000,
1781 htlc_maximum_msat: OptionalField::Present(40_000),
1783 fee_proportional_millionths: 0,
1784 excess_data: Vec::new()
1786 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
1787 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1788 short_channel_id: 12,
1791 cltv_expiry_delta: 0,
1792 htlc_minimum_msat: 35_000,
1793 htlc_maximum_msat: OptionalField::Present(40_000),
1795 fee_proportional_millionths: 0,
1796 excess_data: Vec::new()
1800 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
1801 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1802 short_channel_id: 13,
1805 cltv_expiry_delta: 0,
1806 htlc_minimum_msat: 0,
1807 htlc_maximum_msat: OptionalField::Absent,
1809 fee_proportional_millionths: 0,
1810 excess_data: Vec::new()
1812 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
1813 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1814 short_channel_id: 4,
1817 cltv_expiry_delta: 0,
1818 htlc_minimum_msat: 0,
1819 htlc_maximum_msat: OptionalField::Absent,
1821 fee_proportional_millionths: 0,
1822 excess_data: Vec::new()
1825 // Disable other paths
1826 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
1827 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1828 short_channel_id: 1,
1830 flags: 2, // to disable
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 let route = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2],
1840 Some(InvoiceFeatures::known()), None, &Vec::new(), 60_000, 42, Arc::clone(&logger)).unwrap();
1841 // Overpay fees to hit htlc_minimum_msat.
1842 let overpaid_fees = route.paths[0][0].fee_msat + route.paths[1][0].fee_msat;
1843 // TODO: this could be better balanced to overpay 10k and not 15k.
1844 assert_eq!(overpaid_fees, 15_000);
1846 // Now, test that if there are 2 paths, a "cheaper" by fee path wouldn't be prioritized
1847 // while taking even more fee to match htlc_minimum_msat.
1848 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
1849 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1850 short_channel_id: 12,
1853 cltv_expiry_delta: 0,
1854 htlc_minimum_msat: 65_000,
1855 htlc_maximum_msat: OptionalField::Present(80_000),
1857 fee_proportional_millionths: 0,
1858 excess_data: Vec::new()
1860 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
1861 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1862 short_channel_id: 2,
1865 cltv_expiry_delta: 0,
1866 htlc_minimum_msat: 0,
1867 htlc_maximum_msat: OptionalField::Absent,
1869 fee_proportional_millionths: 0,
1870 excess_data: Vec::new()
1872 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
1873 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1874 short_channel_id: 4,
1877 cltv_expiry_delta: 0,
1878 htlc_minimum_msat: 0,
1879 htlc_maximum_msat: OptionalField::Absent,
1881 fee_proportional_millionths: 100_000,
1882 excess_data: Vec::new()
1885 let route = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2],
1886 Some(InvoiceFeatures::known()), None, &Vec::new(), 60_000, 42, Arc::clone(&logger)).unwrap();
1887 // Fine to overpay for htlc_minimum_msat if it allows us to save fee.
1888 assert_eq!(route.paths.len(), 1);
1889 assert_eq!(route.paths[0][0].short_channel_id, 12);
1890 let fees = route.paths[0][0].fee_msat;
1891 assert_eq!(fees, 5_000);
1893 let route = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2],
1894 Some(InvoiceFeatures::known()), None, &Vec::new(), 50_000, 42, Arc::clone(&logger)).unwrap();
1895 // Not fine to overpay for htlc_minimum_msat if it requires paying more than fee on
1896 // the other channel.
1897 assert_eq!(route.paths.len(), 1);
1898 assert_eq!(route.paths[0][0].short_channel_id, 2);
1899 let fees = route.paths[0][0].fee_msat;
1900 assert_eq!(fees, 5_000);
1904 fn disable_channels_test() {
1905 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
1906 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
1908 // // Disable channels 4 and 12 by flags=2
1909 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
1910 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1911 short_channel_id: 4,
1913 flags: 2, // to disable
1914 cltv_expiry_delta: 0,
1915 htlc_minimum_msat: 0,
1916 htlc_maximum_msat: OptionalField::Absent,
1918 fee_proportional_millionths: 0,
1919 excess_data: Vec::new()
1921 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
1922 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1923 short_channel_id: 12,
1925 flags: 2, // to disable
1926 cltv_expiry_delta: 0,
1927 htlc_minimum_msat: 0,
1928 htlc_maximum_msat: OptionalField::Absent,
1930 fee_proportional_millionths: 0,
1931 excess_data: Vec::new()
1934 // If all the channels require some features we don't understand, route should fail
1935 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)) {
1936 assert_eq!(err, "Failed to find a path to the given destination");
1937 } else { panic!(); }
1939 // If we specify a channel to node7, that overrides our local channel view and that gets used
1940 let our_chans = vec![channelmanager::ChannelDetails {
1941 channel_id: [0; 32],
1942 short_channel_id: Some(42),
1943 remote_network_id: nodes[7].clone(),
1944 counterparty_features: InitFeatures::from_le_bytes(vec![0b11]),
1945 channel_value_satoshis: 0,
1947 outbound_capacity_msat: 250_000_000,
1948 inbound_capacity_msat: 0,
1950 counterparty_forwarding_info: None,
1952 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();
1953 assert_eq!(route.paths[0].len(), 2);
1955 assert_eq!(route.paths[0][0].pubkey, nodes[7]);
1956 assert_eq!(route.paths[0][0].short_channel_id, 42);
1957 assert_eq!(route.paths[0][0].fee_msat, 200);
1958 assert_eq!(route.paths[0][0].cltv_expiry_delta, (13 << 8) | 1);
1959 assert_eq!(route.paths[0][0].node_features.le_flags(), &vec![0b11]); // it should also override our view of their features
1960 assert_eq!(route.paths[0][0].channel_features.le_flags(), &Vec::<u8>::new()); // No feature flags will meet the relevant-to-channel conversion
1962 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
1963 assert_eq!(route.paths[0][1].short_channel_id, 13);
1964 assert_eq!(route.paths[0][1].fee_msat, 100);
1965 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
1966 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
1967 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(13));
1971 fn disable_node_test() {
1972 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
1973 let (_, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
1975 // Disable nodes 1, 2, and 8 by requiring unknown feature bits
1976 let mut unknown_features = NodeFeatures::known();
1977 unknown_features.set_required_unknown_bits();
1978 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[0], unknown_features.clone(), 1);
1979 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[1], unknown_features.clone(), 1);
1980 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[7], unknown_features.clone(), 1);
1982 // If all nodes require some features we don't understand, route should fail
1983 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)) {
1984 assert_eq!(err, "Failed to find a path to the given destination");
1985 } else { panic!(); }
1987 // If we specify a channel to node7, that overrides our local channel view and that gets used
1988 let our_chans = vec![channelmanager::ChannelDetails {
1989 channel_id: [0; 32],
1990 short_channel_id: Some(42),
1991 remote_network_id: nodes[7].clone(),
1992 counterparty_features: InitFeatures::from_le_bytes(vec![0b11]),
1993 channel_value_satoshis: 0,
1995 outbound_capacity_msat: 250_000_000,
1996 inbound_capacity_msat: 0,
1998 counterparty_forwarding_info: None,
2000 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();
2001 assert_eq!(route.paths[0].len(), 2);
2003 assert_eq!(route.paths[0][0].pubkey, nodes[7]);
2004 assert_eq!(route.paths[0][0].short_channel_id, 42);
2005 assert_eq!(route.paths[0][0].fee_msat, 200);
2006 assert_eq!(route.paths[0][0].cltv_expiry_delta, (13 << 8) | 1);
2007 assert_eq!(route.paths[0][0].node_features.le_flags(), &vec![0b11]); // it should also override our view of their features
2008 assert_eq!(route.paths[0][0].channel_features.le_flags(), &Vec::<u8>::new()); // No feature flags will meet the relevant-to-channel conversion
2010 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2011 assert_eq!(route.paths[0][1].short_channel_id, 13);
2012 assert_eq!(route.paths[0][1].fee_msat, 100);
2013 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
2014 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2015 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(13));
2017 // Note that we don't test disabling node 3 and failing to route to it, as we (somewhat
2018 // naively) assume that the user checked the feature bits on the invoice, which override
2019 // the node_announcement.
2023 fn our_chans_test() {
2024 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
2025 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
2027 // Route to 1 via 2 and 3 because our channel to 1 is disabled
2028 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();
2029 assert_eq!(route.paths[0].len(), 3);
2031 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
2032 assert_eq!(route.paths[0][0].short_channel_id, 2);
2033 assert_eq!(route.paths[0][0].fee_msat, 200);
2034 assert_eq!(route.paths[0][0].cltv_expiry_delta, (4 << 8) | 1);
2035 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
2036 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
2038 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2039 assert_eq!(route.paths[0][1].short_channel_id, 4);
2040 assert_eq!(route.paths[0][1].fee_msat, 100);
2041 assert_eq!(route.paths[0][1].cltv_expiry_delta, (3 << 8) | 2);
2042 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2043 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
2045 assert_eq!(route.paths[0][2].pubkey, nodes[0]);
2046 assert_eq!(route.paths[0][2].short_channel_id, 3);
2047 assert_eq!(route.paths[0][2].fee_msat, 100);
2048 assert_eq!(route.paths[0][2].cltv_expiry_delta, 42);
2049 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(1));
2050 assert_eq!(route.paths[0][2].channel_features.le_flags(), &id_to_feature_flags(3));
2052 // If we specify a channel to node7, that overrides our local channel view and that gets used
2053 let our_chans = vec![channelmanager::ChannelDetails {
2054 channel_id: [0; 32],
2055 short_channel_id: Some(42),
2056 remote_network_id: nodes[7].clone(),
2057 counterparty_features: InitFeatures::from_le_bytes(vec![0b11]),
2058 channel_value_satoshis: 0,
2060 outbound_capacity_msat: 250_000_000,
2061 inbound_capacity_msat: 0,
2063 counterparty_forwarding_info: None,
2065 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();
2066 assert_eq!(route.paths[0].len(), 2);
2068 assert_eq!(route.paths[0][0].pubkey, nodes[7]);
2069 assert_eq!(route.paths[0][0].short_channel_id, 42);
2070 assert_eq!(route.paths[0][0].fee_msat, 200);
2071 assert_eq!(route.paths[0][0].cltv_expiry_delta, (13 << 8) | 1);
2072 assert_eq!(route.paths[0][0].node_features.le_flags(), &vec![0b11]);
2073 assert_eq!(route.paths[0][0].channel_features.le_flags(), &Vec::<u8>::new()); // No feature flags will meet the relevant-to-channel conversion
2075 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2076 assert_eq!(route.paths[0][1].short_channel_id, 13);
2077 assert_eq!(route.paths[0][1].fee_msat, 100);
2078 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
2079 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2080 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(13));
2083 fn last_hops(nodes: &Vec<PublicKey>) -> Vec<RouteHint> {
2084 let zero_fees = RoutingFees {
2086 proportional_millionths: 0,
2089 src_node_id: nodes[3].clone(),
2090 short_channel_id: 8,
2092 cltv_expiry_delta: (8 << 8) | 1,
2093 htlc_minimum_msat: None,
2094 htlc_maximum_msat: None,
2096 src_node_id: nodes[4].clone(),
2097 short_channel_id: 9,
2100 proportional_millionths: 0,
2102 cltv_expiry_delta: (9 << 8) | 1,
2103 htlc_minimum_msat: None,
2104 htlc_maximum_msat: None,
2106 src_node_id: nodes[5].clone(),
2107 short_channel_id: 10,
2109 cltv_expiry_delta: (10 << 8) | 1,
2110 htlc_minimum_msat: None,
2111 htlc_maximum_msat: None,
2116 fn last_hops_test() {
2117 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
2118 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
2120 // Simple test across 2, 3, 5, and 4 via a last_hop channel
2122 // First check that lst hop can't have its source as the payee.
2123 let invalid_last_hop = RouteHint {
2124 src_node_id: nodes[6],
2125 short_channel_id: 8,
2128 proportional_millionths: 0,
2130 cltv_expiry_delta: (8 << 8) | 1,
2131 htlc_minimum_msat: None,
2132 htlc_maximum_msat: None,
2135 let mut invalid_last_hops = last_hops(&nodes);
2136 invalid_last_hops.push(invalid_last_hop);
2138 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)) {
2139 assert_eq!(err, "Last hop cannot have a payee as a source.");
2140 } else { panic!(); }
2143 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();
2144 assert_eq!(route.paths[0].len(), 5);
2146 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
2147 assert_eq!(route.paths[0][0].short_channel_id, 2);
2148 assert_eq!(route.paths[0][0].fee_msat, 100);
2149 assert_eq!(route.paths[0][0].cltv_expiry_delta, (4 << 8) | 1);
2150 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
2151 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
2153 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2154 assert_eq!(route.paths[0][1].short_channel_id, 4);
2155 assert_eq!(route.paths[0][1].fee_msat, 0);
2156 assert_eq!(route.paths[0][1].cltv_expiry_delta, (6 << 8) | 1);
2157 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2158 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
2160 assert_eq!(route.paths[0][2].pubkey, nodes[4]);
2161 assert_eq!(route.paths[0][2].short_channel_id, 6);
2162 assert_eq!(route.paths[0][2].fee_msat, 0);
2163 assert_eq!(route.paths[0][2].cltv_expiry_delta, (11 << 8) | 1);
2164 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(5));
2165 assert_eq!(route.paths[0][2].channel_features.le_flags(), &id_to_feature_flags(6));
2167 assert_eq!(route.paths[0][3].pubkey, nodes[3]);
2168 assert_eq!(route.paths[0][3].short_channel_id, 11);
2169 assert_eq!(route.paths[0][3].fee_msat, 0);
2170 assert_eq!(route.paths[0][3].cltv_expiry_delta, (8 << 8) | 1);
2171 // If we have a peer in the node map, we'll use their features here since we don't have
2172 // a way of figuring out their features from the invoice:
2173 assert_eq!(route.paths[0][3].node_features.le_flags(), &id_to_feature_flags(4));
2174 assert_eq!(route.paths[0][3].channel_features.le_flags(), &id_to_feature_flags(11));
2176 assert_eq!(route.paths[0][4].pubkey, nodes[6]);
2177 assert_eq!(route.paths[0][4].short_channel_id, 8);
2178 assert_eq!(route.paths[0][4].fee_msat, 100);
2179 assert_eq!(route.paths[0][4].cltv_expiry_delta, 42);
2180 assert_eq!(route.paths[0][4].node_features.le_flags(), &Vec::<u8>::new()); // We dont pass flags in from invoices yet
2181 assert_eq!(route.paths[0][4].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
2185 fn our_chans_last_hop_connect_test() {
2186 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
2187 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
2189 // Simple test with outbound channel to 4 to test that last_hops and first_hops connect
2190 let our_chans = vec![channelmanager::ChannelDetails {
2191 channel_id: [0; 32],
2192 short_channel_id: Some(42),
2193 remote_network_id: nodes[3].clone(),
2194 counterparty_features: InitFeatures::from_le_bytes(vec![0b11]),
2195 channel_value_satoshis: 0,
2197 outbound_capacity_msat: 250_000_000,
2198 inbound_capacity_msat: 0,
2200 counterparty_forwarding_info: None,
2202 let mut last_hops = last_hops(&nodes);
2203 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();
2204 assert_eq!(route.paths[0].len(), 2);
2206 assert_eq!(route.paths[0][0].pubkey, nodes[3]);
2207 assert_eq!(route.paths[0][0].short_channel_id, 42);
2208 assert_eq!(route.paths[0][0].fee_msat, 0);
2209 assert_eq!(route.paths[0][0].cltv_expiry_delta, (8 << 8) | 1);
2210 assert_eq!(route.paths[0][0].node_features.le_flags(), &vec![0b11]);
2211 assert_eq!(route.paths[0][0].channel_features.le_flags(), &Vec::<u8>::new()); // No feature flags will meet the relevant-to-channel conversion
2213 assert_eq!(route.paths[0][1].pubkey, nodes[6]);
2214 assert_eq!(route.paths[0][1].short_channel_id, 8);
2215 assert_eq!(route.paths[0][1].fee_msat, 100);
2216 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
2217 assert_eq!(route.paths[0][1].node_features.le_flags(), &Vec::<u8>::new()); // We dont pass flags in from invoices yet
2218 assert_eq!(route.paths[0][1].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
2220 last_hops[0].fees.base_msat = 1000;
2222 // Revert to via 6 as the fee on 8 goes up
2223 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();
2224 assert_eq!(route.paths[0].len(), 4);
2226 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
2227 assert_eq!(route.paths[0][0].short_channel_id, 2);
2228 assert_eq!(route.paths[0][0].fee_msat, 200); // fee increased as its % of value transferred across node
2229 assert_eq!(route.paths[0][0].cltv_expiry_delta, (4 << 8) | 1);
2230 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
2231 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
2233 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2234 assert_eq!(route.paths[0][1].short_channel_id, 4);
2235 assert_eq!(route.paths[0][1].fee_msat, 100);
2236 assert_eq!(route.paths[0][1].cltv_expiry_delta, (7 << 8) | 1);
2237 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2238 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
2240 assert_eq!(route.paths[0][2].pubkey, nodes[5]);
2241 assert_eq!(route.paths[0][2].short_channel_id, 7);
2242 assert_eq!(route.paths[0][2].fee_msat, 0);
2243 assert_eq!(route.paths[0][2].cltv_expiry_delta, (10 << 8) | 1);
2244 // If we have a peer in the node map, we'll use their features here since we don't have
2245 // a way of figuring out their features from the invoice:
2246 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(6));
2247 assert_eq!(route.paths[0][2].channel_features.le_flags(), &id_to_feature_flags(7));
2249 assert_eq!(route.paths[0][3].pubkey, nodes[6]);
2250 assert_eq!(route.paths[0][3].short_channel_id, 10);
2251 assert_eq!(route.paths[0][3].fee_msat, 100);
2252 assert_eq!(route.paths[0][3].cltv_expiry_delta, 42);
2253 assert_eq!(route.paths[0][3].node_features.le_flags(), &Vec::<u8>::new()); // We dont pass flags in from invoices yet
2254 assert_eq!(route.paths[0][3].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
2256 // ...but still use 8 for larger payments as 6 has a variable feerate
2257 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();
2258 assert_eq!(route.paths[0].len(), 5);
2260 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
2261 assert_eq!(route.paths[0][0].short_channel_id, 2);
2262 assert_eq!(route.paths[0][0].fee_msat, 3000);
2263 assert_eq!(route.paths[0][0].cltv_expiry_delta, (4 << 8) | 1);
2264 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
2265 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
2267 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2268 assert_eq!(route.paths[0][1].short_channel_id, 4);
2269 assert_eq!(route.paths[0][1].fee_msat, 0);
2270 assert_eq!(route.paths[0][1].cltv_expiry_delta, (6 << 8) | 1);
2271 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2272 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
2274 assert_eq!(route.paths[0][2].pubkey, nodes[4]);
2275 assert_eq!(route.paths[0][2].short_channel_id, 6);
2276 assert_eq!(route.paths[0][2].fee_msat, 0);
2277 assert_eq!(route.paths[0][2].cltv_expiry_delta, (11 << 8) | 1);
2278 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(5));
2279 assert_eq!(route.paths[0][2].channel_features.le_flags(), &id_to_feature_flags(6));
2281 assert_eq!(route.paths[0][3].pubkey, nodes[3]);
2282 assert_eq!(route.paths[0][3].short_channel_id, 11);
2283 assert_eq!(route.paths[0][3].fee_msat, 1000);
2284 assert_eq!(route.paths[0][3].cltv_expiry_delta, (8 << 8) | 1);
2285 // If we have a peer in the node map, we'll use their features here since we don't have
2286 // a way of figuring out their features from the invoice:
2287 assert_eq!(route.paths[0][3].node_features.le_flags(), &id_to_feature_flags(4));
2288 assert_eq!(route.paths[0][3].channel_features.le_flags(), &id_to_feature_flags(11));
2290 assert_eq!(route.paths[0][4].pubkey, nodes[6]);
2291 assert_eq!(route.paths[0][4].short_channel_id, 8);
2292 assert_eq!(route.paths[0][4].fee_msat, 2000);
2293 assert_eq!(route.paths[0][4].cltv_expiry_delta, 42);
2294 assert_eq!(route.paths[0][4].node_features.le_flags(), &Vec::<u8>::new()); // We dont pass flags in from invoices yet
2295 assert_eq!(route.paths[0][4].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
2299 fn unannounced_path_test() {
2300 // We should be able to send a payment to a destination without any help of a routing graph
2301 // if we have a channel with a common counterparty that appears in the first and last hop
2303 let source_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&hex::decode(format!("{:02}", 41).repeat(32)).unwrap()[..]).unwrap());
2304 let middle_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&hex::decode(format!("{:02}", 42).repeat(32)).unwrap()[..]).unwrap());
2305 let target_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&hex::decode(format!("{:02}", 43).repeat(32)).unwrap()[..]).unwrap());
2307 // If we specify a channel to a middle hop, that overrides our local channel view and that gets used
2308 let last_hops = vec![RouteHint {
2309 src_node_id: middle_node_id,
2310 short_channel_id: 8,
2313 proportional_millionths: 0,
2315 cltv_expiry_delta: (8 << 8) | 1,
2316 htlc_minimum_msat: None,
2317 htlc_maximum_msat: None,
2319 let our_chans = vec![channelmanager::ChannelDetails {
2320 channel_id: [0; 32],
2321 short_channel_id: Some(42),
2322 remote_network_id: middle_node_id,
2323 counterparty_features: InitFeatures::from_le_bytes(vec![0b11]),
2324 channel_value_satoshis: 100000,
2326 outbound_capacity_msat: 100000,
2327 inbound_capacity_msat: 100000,
2329 counterparty_forwarding_info: None,
2331 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();
2333 assert_eq!(route.paths[0].len(), 2);
2335 assert_eq!(route.paths[0][0].pubkey, middle_node_id);
2336 assert_eq!(route.paths[0][0].short_channel_id, 42);
2337 assert_eq!(route.paths[0][0].fee_msat, 1000);
2338 assert_eq!(route.paths[0][0].cltv_expiry_delta, (8 << 8) | 1);
2339 assert_eq!(route.paths[0][0].node_features.le_flags(), &[0b11]);
2340 assert_eq!(route.paths[0][0].channel_features.le_flags(), &[0; 0]); // We can't learn any flags from invoices, sadly
2342 assert_eq!(route.paths[0][1].pubkey, target_node_id);
2343 assert_eq!(route.paths[0][1].short_channel_id, 8);
2344 assert_eq!(route.paths[0][1].fee_msat, 100);
2345 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
2346 assert_eq!(route.paths[0][1].node_features.le_flags(), &[0; 0]); // We dont pass flags in from invoices yet
2347 assert_eq!(route.paths[0][1].channel_features.le_flags(), &[0; 0]); // We can't learn any flags from invoices, sadly
2351 fn available_amount_while_routing_test() {
2352 // Tests whether we choose the correct available channel amount while routing.
2354 let (secp_ctx, mut net_graph_msg_handler, chain_monitor, logger) = build_graph();
2355 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
2357 // We will use a simple single-path route from
2358 // our node to node2 via node0: channels {1, 3}.
2360 // First disable all other paths.
2361 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2362 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2363 short_channel_id: 2,
2366 cltv_expiry_delta: 0,
2367 htlc_minimum_msat: 0,
2368 htlc_maximum_msat: OptionalField::Present(100_000),
2370 fee_proportional_millionths: 0,
2371 excess_data: Vec::new()
2373 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2374 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2375 short_channel_id: 12,
2378 cltv_expiry_delta: 0,
2379 htlc_minimum_msat: 0,
2380 htlc_maximum_msat: OptionalField::Present(100_000),
2382 fee_proportional_millionths: 0,
2383 excess_data: Vec::new()
2386 // Make the first channel (#1) very permissive,
2387 // and we will be testing all limits on the second channel.
2388 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2389 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2390 short_channel_id: 1,
2393 cltv_expiry_delta: 0,
2394 htlc_minimum_msat: 0,
2395 htlc_maximum_msat: OptionalField::Present(1_000_000_000),
2397 fee_proportional_millionths: 0,
2398 excess_data: Vec::new()
2401 // First, let's see if routing works if we have absolutely no idea about the available amount.
2402 // In this case, it should be set to 250_000 sats.
2403 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
2404 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2405 short_channel_id: 3,
2408 cltv_expiry_delta: 0,
2409 htlc_minimum_msat: 0,
2410 htlc_maximum_msat: OptionalField::Absent,
2412 fee_proportional_millionths: 0,
2413 excess_data: Vec::new()
2417 // Attempt to route more than available results in a failure.
2418 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2],
2419 Some(InvoiceFeatures::known()), None, &Vec::new(), 250_000_001, 42, Arc::clone(&logger)) {
2420 assert_eq!(err, "Failed to find a sufficient route to the given destination");
2421 } else { panic!(); }
2425 // Now, attempt to route an exact amount we have should be fine.
2426 let route = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2],
2427 Some(InvoiceFeatures::known()), None, &Vec::new(), 250_000_000, 42, Arc::clone(&logger)).unwrap();
2428 assert_eq!(route.paths.len(), 1);
2429 let path = route.paths.last().unwrap();
2430 assert_eq!(path.len(), 2);
2431 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
2432 assert_eq!(path.last().unwrap().fee_msat, 250_000_000);
2435 // Check that setting outbound_capacity_msat in first_hops limits the channels.
2436 // Disable channel #1 and use another first hop.
2437 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2438 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2439 short_channel_id: 1,
2442 cltv_expiry_delta: 0,
2443 htlc_minimum_msat: 0,
2444 htlc_maximum_msat: OptionalField::Present(1_000_000_000),
2446 fee_proportional_millionths: 0,
2447 excess_data: Vec::new()
2450 // Now, limit the first_hop by the outbound_capacity_msat of 200_000 sats.
2451 let our_chans = vec![channelmanager::ChannelDetails {
2452 channel_id: [0; 32],
2453 short_channel_id: Some(42),
2454 remote_network_id: nodes[0].clone(),
2455 counterparty_features: InitFeatures::from_le_bytes(vec![0b11]),
2456 channel_value_satoshis: 0,
2458 outbound_capacity_msat: 200_000_000,
2459 inbound_capacity_msat: 0,
2461 counterparty_forwarding_info: None,
2465 // Attempt to route more than available results in a failure.
2466 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2],
2467 Some(InvoiceFeatures::known()), Some(&our_chans.iter().collect::<Vec<_>>()), &Vec::new(), 200_000_001, 42, Arc::clone(&logger)) {
2468 assert_eq!(err, "Failed to find a sufficient route to the given destination");
2469 } else { panic!(); }
2473 // Now, attempt to route an exact amount we have should be fine.
2474 let route = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2],
2475 Some(InvoiceFeatures::known()), Some(&our_chans.iter().collect::<Vec<_>>()), &Vec::new(), 200_000_000, 42, Arc::clone(&logger)).unwrap();
2476 assert_eq!(route.paths.len(), 1);
2477 let path = route.paths.last().unwrap();
2478 assert_eq!(path.len(), 2);
2479 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
2480 assert_eq!(path.last().unwrap().fee_msat, 200_000_000);
2483 // Enable channel #1 back.
2484 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2485 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2486 short_channel_id: 1,
2489 cltv_expiry_delta: 0,
2490 htlc_minimum_msat: 0,
2491 htlc_maximum_msat: OptionalField::Present(1_000_000_000),
2493 fee_proportional_millionths: 0,
2494 excess_data: Vec::new()
2498 // Now let's see if routing works if we know only htlc_maximum_msat.
2499 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
2500 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2501 short_channel_id: 3,
2504 cltv_expiry_delta: 0,
2505 htlc_minimum_msat: 0,
2506 htlc_maximum_msat: OptionalField::Present(15_000),
2508 fee_proportional_millionths: 0,
2509 excess_data: Vec::new()
2513 // Attempt to route more than available results in a failure.
2514 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2],
2515 Some(InvoiceFeatures::known()), None, &Vec::new(), 15_001, 42, Arc::clone(&logger)) {
2516 assert_eq!(err, "Failed to find a sufficient route to the given destination");
2517 } else { panic!(); }
2521 // Now, attempt to route an exact amount we have should be fine.
2522 let route = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2],
2523 Some(InvoiceFeatures::known()), None, &Vec::new(), 15_000, 42, Arc::clone(&logger)).unwrap();
2524 assert_eq!(route.paths.len(), 1);
2525 let path = route.paths.last().unwrap();
2526 assert_eq!(path.len(), 2);
2527 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
2528 assert_eq!(path.last().unwrap().fee_msat, 15_000);
2531 // Now let's see if routing works if we know only capacity from the UTXO.
2533 // We can't change UTXO capacity on the fly, so we'll disable
2534 // the existing channel and add another one with the capacity we need.
2535 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
2536 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2537 short_channel_id: 3,
2540 cltv_expiry_delta: 0,
2541 htlc_minimum_msat: 0,
2542 htlc_maximum_msat: OptionalField::Absent,
2544 fee_proportional_millionths: 0,
2545 excess_data: Vec::new()
2548 let good_script = Builder::new().push_opcode(opcodes::all::OP_PUSHNUM_2)
2549 .push_slice(&PublicKey::from_secret_key(&secp_ctx, &privkeys[0]).serialize())
2550 .push_slice(&PublicKey::from_secret_key(&secp_ctx, &privkeys[2]).serialize())
2551 .push_opcode(opcodes::all::OP_PUSHNUM_2)
2552 .push_opcode(opcodes::all::OP_CHECKMULTISIG).into_script().to_v0_p2wsh();
2554 *chain_monitor.utxo_ret.lock().unwrap() = Ok(TxOut { value: 15, script_pubkey: good_script.clone() });
2555 net_graph_msg_handler.add_chain_access(Some(chain_monitor));
2557 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], &privkeys[2], ChannelFeatures::from_le_bytes(id_to_feature_flags(3)), 333);
2558 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
2559 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2560 short_channel_id: 333,
2563 cltv_expiry_delta: (3 << 8) | 1,
2564 htlc_minimum_msat: 0,
2565 htlc_maximum_msat: OptionalField::Absent,
2567 fee_proportional_millionths: 0,
2568 excess_data: Vec::new()
2570 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
2571 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2572 short_channel_id: 333,
2575 cltv_expiry_delta: (3 << 8) | 2,
2576 htlc_minimum_msat: 0,
2577 htlc_maximum_msat: OptionalField::Absent,
2579 fee_proportional_millionths: 0,
2580 excess_data: Vec::new()
2584 // Attempt to route more than available results in a failure.
2585 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2],
2586 Some(InvoiceFeatures::known()), None, &Vec::new(), 15_001, 42, Arc::clone(&logger)) {
2587 assert_eq!(err, "Failed to find a sufficient route to the given destination");
2588 } else { panic!(); }
2592 // Now, attempt to route an exact amount we have should be fine.
2593 let route = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2],
2594 Some(InvoiceFeatures::known()), None, &Vec::new(), 15_000, 42, Arc::clone(&logger)).unwrap();
2595 assert_eq!(route.paths.len(), 1);
2596 let path = route.paths.last().unwrap();
2597 assert_eq!(path.len(), 2);
2598 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
2599 assert_eq!(path.last().unwrap().fee_msat, 15_000);
2602 // Now let's see if routing chooses htlc_maximum_msat over UTXO capacity.
2603 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
2604 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2605 short_channel_id: 333,
2608 cltv_expiry_delta: 0,
2609 htlc_minimum_msat: 0,
2610 htlc_maximum_msat: OptionalField::Present(10_000),
2612 fee_proportional_millionths: 0,
2613 excess_data: Vec::new()
2617 // Attempt to route more than available results in a failure.
2618 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2],
2619 Some(InvoiceFeatures::known()), None, &Vec::new(), 10_001, 42, Arc::clone(&logger)) {
2620 assert_eq!(err, "Failed to find a sufficient route to the given destination");
2621 } else { panic!(); }
2625 // Now, attempt to route an exact amount we have should be fine.
2626 let route = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2],
2627 Some(InvoiceFeatures::known()), None, &Vec::new(), 10_000, 42, Arc::clone(&logger)).unwrap();
2628 assert_eq!(route.paths.len(), 1);
2629 let path = route.paths.last().unwrap();
2630 assert_eq!(path.len(), 2);
2631 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
2632 assert_eq!(path.last().unwrap().fee_msat, 10_000);
2637 fn available_liquidity_last_hop_test() {
2638 // Check that available liquidity properly limits the path even when only
2639 // one of the latter hops is limited.
2640 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
2641 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
2643 // Path via {node7, node2, node4} is channels {12, 13, 6, 11}.
2644 // {12, 13, 11} have the capacities of 100, {6} has a capacity of 50.
2645 // Total capacity: 50 sats.
2647 // Disable other potential paths.
2648 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2649 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2650 short_channel_id: 2,
2653 cltv_expiry_delta: 0,
2654 htlc_minimum_msat: 0,
2655 htlc_maximum_msat: OptionalField::Present(100_000),
2657 fee_proportional_millionths: 0,
2658 excess_data: Vec::new()
2660 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
2661 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2662 short_channel_id: 7,
2665 cltv_expiry_delta: 0,
2666 htlc_minimum_msat: 0,
2667 htlc_maximum_msat: OptionalField::Present(100_000),
2669 fee_proportional_millionths: 0,
2670 excess_data: Vec::new()
2675 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2676 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2677 short_channel_id: 12,
2680 cltv_expiry_delta: 0,
2681 htlc_minimum_msat: 0,
2682 htlc_maximum_msat: OptionalField::Present(100_000),
2684 fee_proportional_millionths: 0,
2685 excess_data: Vec::new()
2687 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
2688 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2689 short_channel_id: 13,
2692 cltv_expiry_delta: 0,
2693 htlc_minimum_msat: 0,
2694 htlc_maximum_msat: OptionalField::Present(100_000),
2696 fee_proportional_millionths: 0,
2697 excess_data: Vec::new()
2700 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
2701 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2702 short_channel_id: 6,
2705 cltv_expiry_delta: 0,
2706 htlc_minimum_msat: 0,
2707 htlc_maximum_msat: OptionalField::Present(50_000),
2709 fee_proportional_millionths: 0,
2710 excess_data: Vec::new()
2712 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
2713 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2714 short_channel_id: 11,
2717 cltv_expiry_delta: 0,
2718 htlc_minimum_msat: 0,
2719 htlc_maximum_msat: OptionalField::Present(100_000),
2721 fee_proportional_millionths: 0,
2722 excess_data: Vec::new()
2725 // Attempt to route more than available results in a failure.
2726 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[3],
2727 Some(InvoiceFeatures::known()), None, &Vec::new(), 60_000, 42, Arc::clone(&logger)) {
2728 assert_eq!(err, "Failed to find a sufficient route to the given destination");
2729 } else { panic!(); }
2733 // Now, attempt to route 49 sats (just a bit below the capacity).
2734 let route = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[3],
2735 Some(InvoiceFeatures::known()), None, &Vec::new(), 49_000, 42, Arc::clone(&logger)).unwrap();
2736 assert_eq!(route.paths.len(), 1);
2737 let mut total_amount_paid_msat = 0;
2738 for path in &route.paths {
2739 assert_eq!(path.len(), 4);
2740 assert_eq!(path.last().unwrap().pubkey, nodes[3]);
2741 total_amount_paid_msat += path.last().unwrap().fee_msat;
2743 assert_eq!(total_amount_paid_msat, 49_000);
2747 // Attempt to route an exact amount is also fine
2748 let route = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[3],
2749 Some(InvoiceFeatures::known()), None, &Vec::new(), 50_000, 42, Arc::clone(&logger)).unwrap();
2750 assert_eq!(route.paths.len(), 1);
2751 let mut total_amount_paid_msat = 0;
2752 for path in &route.paths {
2753 assert_eq!(path.len(), 4);
2754 assert_eq!(path.last().unwrap().pubkey, nodes[3]);
2755 total_amount_paid_msat += path.last().unwrap().fee_msat;
2757 assert_eq!(total_amount_paid_msat, 50_000);
2762 fn ignore_fee_first_hop_test() {
2763 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
2764 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
2766 // Path via node0 is channels {1, 3}. Limit them to 100 and 50 sats (total limit 50).
2767 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2768 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2769 short_channel_id: 1,
2772 cltv_expiry_delta: 0,
2773 htlc_minimum_msat: 0,
2774 htlc_maximum_msat: OptionalField::Present(100_000),
2775 fee_base_msat: 1_000_000,
2776 fee_proportional_millionths: 0,
2777 excess_data: Vec::new()
2779 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
2780 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2781 short_channel_id: 3,
2784 cltv_expiry_delta: 0,
2785 htlc_minimum_msat: 0,
2786 htlc_maximum_msat: OptionalField::Present(50_000),
2788 fee_proportional_millionths: 0,
2789 excess_data: Vec::new()
2793 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();
2794 assert_eq!(route.paths.len(), 1);
2795 let mut total_amount_paid_msat = 0;
2796 for path in &route.paths {
2797 assert_eq!(path.len(), 2);
2798 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
2799 total_amount_paid_msat += path.last().unwrap().fee_msat;
2801 assert_eq!(total_amount_paid_msat, 50_000);
2806 fn simple_mpp_route_test() {
2807 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
2808 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
2810 // We need a route consisting of 3 paths:
2811 // From our node to node2 via node0, node7, node1 (three paths one hop each).
2812 // To achieve this, the amount being transferred should be around
2813 // the total capacity of these 3 paths.
2815 // First, we set limits on these (previously unlimited) channels.
2816 // Their aggregate capacity will be 50 + 60 + 180 = 290 sats.
2818 // Path via node0 is channels {1, 3}. Limit them to 100 and 50 sats (total limit 50).
2819 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2820 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2821 short_channel_id: 1,
2824 cltv_expiry_delta: 0,
2825 htlc_minimum_msat: 0,
2826 htlc_maximum_msat: OptionalField::Present(100_000),
2828 fee_proportional_millionths: 0,
2829 excess_data: Vec::new()
2831 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
2832 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2833 short_channel_id: 3,
2836 cltv_expiry_delta: 0,
2837 htlc_minimum_msat: 0,
2838 htlc_maximum_msat: OptionalField::Present(50_000),
2840 fee_proportional_millionths: 0,
2841 excess_data: Vec::new()
2844 // Path via node7 is channels {12, 13}. Limit them to 60 and 60 sats
2845 // (total limit 60).
2846 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2847 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2848 short_channel_id: 12,
2851 cltv_expiry_delta: 0,
2852 htlc_minimum_msat: 0,
2853 htlc_maximum_msat: OptionalField::Present(60_000),
2855 fee_proportional_millionths: 0,
2856 excess_data: Vec::new()
2858 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
2859 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2860 short_channel_id: 13,
2863 cltv_expiry_delta: 0,
2864 htlc_minimum_msat: 0,
2865 htlc_maximum_msat: OptionalField::Present(60_000),
2867 fee_proportional_millionths: 0,
2868 excess_data: Vec::new()
2871 // Path via node1 is channels {2, 4}. Limit them to 200 and 180 sats
2872 // (total capacity 180 sats).
2873 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2874 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2875 short_channel_id: 2,
2878 cltv_expiry_delta: 0,
2879 htlc_minimum_msat: 0,
2880 htlc_maximum_msat: OptionalField::Present(200_000),
2882 fee_proportional_millionths: 0,
2883 excess_data: Vec::new()
2885 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
2886 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2887 short_channel_id: 4,
2890 cltv_expiry_delta: 0,
2891 htlc_minimum_msat: 0,
2892 htlc_maximum_msat: OptionalField::Present(180_000),
2894 fee_proportional_millionths: 0,
2895 excess_data: Vec::new()
2899 // Attempt to route more than available results in a failure.
2900 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(),
2901 &nodes[2], Some(InvoiceFeatures::known()), None, &Vec::new(), 300_000, 42, Arc::clone(&logger)) {
2902 assert_eq!(err, "Failed to find a sufficient route to the given destination");
2903 } else { panic!(); }
2907 // Now, attempt to route 250 sats (just a bit below the capacity).
2908 // Our algorithm should provide us with these 3 paths.
2909 let route = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2],
2910 Some(InvoiceFeatures::known()), None, &Vec::new(), 250_000, 42, Arc::clone(&logger)).unwrap();
2911 assert_eq!(route.paths.len(), 3);
2912 let mut total_amount_paid_msat = 0;
2913 for path in &route.paths {
2914 assert_eq!(path.len(), 2);
2915 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
2916 total_amount_paid_msat += path.last().unwrap().fee_msat;
2918 assert_eq!(total_amount_paid_msat, 250_000);
2922 // Attempt to route an exact amount is also fine
2923 let route = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2],
2924 Some(InvoiceFeatures::known()), None, &Vec::new(), 290_000, 42, Arc::clone(&logger)).unwrap();
2925 assert_eq!(route.paths.len(), 3);
2926 let mut total_amount_paid_msat = 0;
2927 for path in &route.paths {
2928 assert_eq!(path.len(), 2);
2929 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
2930 total_amount_paid_msat += path.last().unwrap().fee_msat;
2932 assert_eq!(total_amount_paid_msat, 290_000);
2937 fn long_mpp_route_test() {
2938 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
2939 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
2941 // We need a route consisting of 3 paths:
2942 // From our node to node3 via {node0, node2}, {node7, node2, node4} and {node7, node2}.
2943 // Note that these paths overlap (channels 5, 12, 13).
2944 // We will route 300 sats.
2945 // Each path will have 100 sats capacity, those channels which
2946 // are used twice will have 200 sats capacity.
2948 // Disable other potential paths.
2949 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2950 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2951 short_channel_id: 2,
2954 cltv_expiry_delta: 0,
2955 htlc_minimum_msat: 0,
2956 htlc_maximum_msat: OptionalField::Present(100_000),
2958 fee_proportional_millionths: 0,
2959 excess_data: Vec::new()
2961 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
2962 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2963 short_channel_id: 7,
2966 cltv_expiry_delta: 0,
2967 htlc_minimum_msat: 0,
2968 htlc_maximum_msat: OptionalField::Present(100_000),
2970 fee_proportional_millionths: 0,
2971 excess_data: Vec::new()
2974 // Path via {node0, node2} is channels {1, 3, 5}.
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: 1,
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[0], UnsignedChannelUpdate {
2988 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2989 short_channel_id: 3,
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 // Capacity of 200 sats because this channel will be used by 3rd path as well.
3001 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(5)), 5);
3002 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3003 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3004 short_channel_id: 5,
3007 cltv_expiry_delta: 0,
3008 htlc_minimum_msat: 0,
3009 htlc_maximum_msat: OptionalField::Present(200_000),
3011 fee_proportional_millionths: 0,
3012 excess_data: Vec::new()
3015 // Path via {node7, node2, node4} is channels {12, 13, 6, 11}.
3016 // Add 100 sats to the capacities of {12, 13}, because these channels
3017 // are also used for 3rd path. 100 sats for the rest. Total capacity: 100 sats.
3018 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3019 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3020 short_channel_id: 12,
3023 cltv_expiry_delta: 0,
3024 htlc_minimum_msat: 0,
3025 htlc_maximum_msat: OptionalField::Present(200_000),
3027 fee_proportional_millionths: 0,
3028 excess_data: Vec::new()
3030 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
3031 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3032 short_channel_id: 13,
3035 cltv_expiry_delta: 0,
3036 htlc_minimum_msat: 0,
3037 htlc_maximum_msat: OptionalField::Present(200_000),
3039 fee_proportional_millionths: 0,
3040 excess_data: Vec::new()
3043 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3044 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3045 short_channel_id: 6,
3048 cltv_expiry_delta: 0,
3049 htlc_minimum_msat: 0,
3050 htlc_maximum_msat: OptionalField::Present(100_000),
3052 fee_proportional_millionths: 0,
3053 excess_data: Vec::new()
3055 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
3056 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3057 short_channel_id: 11,
3060 cltv_expiry_delta: 0,
3061 htlc_minimum_msat: 0,
3062 htlc_maximum_msat: OptionalField::Present(100_000),
3064 fee_proportional_millionths: 0,
3065 excess_data: Vec::new()
3068 // Path via {node7, node2} is channels {12, 13, 5}.
3069 // We already limited them to 200 sats (they are used twice for 100 sats).
3070 // Nothing to do here.
3073 // Attempt to route more than available results in a failure.
3074 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[3],
3075 Some(InvoiceFeatures::known()), None, &Vec::new(), 350_000, 42, Arc::clone(&logger)) {
3076 assert_eq!(err, "Failed to find a sufficient route to the given destination");
3077 } else { panic!(); }
3081 // Now, attempt to route 300 sats (exact amount we can route).
3082 // Our algorithm should provide us with these 3 paths, 100 sats each.
3083 let route = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[3],
3084 Some(InvoiceFeatures::known()), None, &Vec::new(), 300_000, 42, Arc::clone(&logger)).unwrap();
3085 assert_eq!(route.paths.len(), 3);
3087 let mut total_amount_paid_msat = 0;
3088 for path in &route.paths {
3089 assert_eq!(path.last().unwrap().pubkey, nodes[3]);
3090 total_amount_paid_msat += path.last().unwrap().fee_msat;
3092 assert_eq!(total_amount_paid_msat, 300_000);
3098 fn mpp_cheaper_route_test() {
3099 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
3100 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3102 // This test checks that if we have two cheaper paths and one more expensive path,
3103 // so that liquidity-wise any 2 of 3 combination is sufficient,
3104 // two cheaper paths will be taken.
3105 // These paths have equal available liquidity.
3107 // We need a combination of 3 paths:
3108 // From our node to node3 via {node0, node2}, {node7, node2, node4} and {node7, node2}.
3109 // Note that these paths overlap (channels 5, 12, 13).
3110 // Each path will have 100 sats capacity, those channels which
3111 // are used twice will have 200 sats capacity.
3113 // Disable other potential paths.
3114 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3115 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3116 short_channel_id: 2,
3119 cltv_expiry_delta: 0,
3120 htlc_minimum_msat: 0,
3121 htlc_maximum_msat: OptionalField::Present(100_000),
3123 fee_proportional_millionths: 0,
3124 excess_data: Vec::new()
3126 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3127 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3128 short_channel_id: 7,
3131 cltv_expiry_delta: 0,
3132 htlc_minimum_msat: 0,
3133 htlc_maximum_msat: OptionalField::Present(100_000),
3135 fee_proportional_millionths: 0,
3136 excess_data: Vec::new()
3139 // Path via {node0, node2} is channels {1, 3, 5}.
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: 1,
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[0], UnsignedChannelUpdate {
3153 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3154 short_channel_id: 3,
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 // Capacity of 200 sats because this channel will be used by 3rd path as well.
3166 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(5)), 5);
3167 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3168 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3169 short_channel_id: 5,
3172 cltv_expiry_delta: 0,
3173 htlc_minimum_msat: 0,
3174 htlc_maximum_msat: OptionalField::Present(200_000),
3176 fee_proportional_millionths: 0,
3177 excess_data: Vec::new()
3180 // Path via {node7, node2, node4} is channels {12, 13, 6, 11}.
3181 // Add 100 sats to the capacities of {12, 13}, because these channels
3182 // are also used for 3rd path. 100 sats for the rest. Total capacity: 100 sats.
3183 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3184 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3185 short_channel_id: 12,
3188 cltv_expiry_delta: 0,
3189 htlc_minimum_msat: 0,
3190 htlc_maximum_msat: OptionalField::Present(200_000),
3192 fee_proportional_millionths: 0,
3193 excess_data: Vec::new()
3195 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
3196 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3197 short_channel_id: 13,
3200 cltv_expiry_delta: 0,
3201 htlc_minimum_msat: 0,
3202 htlc_maximum_msat: OptionalField::Present(200_000),
3204 fee_proportional_millionths: 0,
3205 excess_data: Vec::new()
3208 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3209 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3210 short_channel_id: 6,
3213 cltv_expiry_delta: 0,
3214 htlc_minimum_msat: 0,
3215 htlc_maximum_msat: OptionalField::Present(100_000),
3216 fee_base_msat: 1_000,
3217 fee_proportional_millionths: 0,
3218 excess_data: Vec::new()
3220 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
3221 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3222 short_channel_id: 11,
3225 cltv_expiry_delta: 0,
3226 htlc_minimum_msat: 0,
3227 htlc_maximum_msat: OptionalField::Present(100_000),
3229 fee_proportional_millionths: 0,
3230 excess_data: Vec::new()
3233 // Path via {node7, node2} is channels {12, 13, 5}.
3234 // We already limited them to 200 sats (they are used twice for 100 sats).
3235 // Nothing to do here.
3238 // Now, attempt to route 180 sats.
3239 // Our algorithm should provide us with these 2 paths.
3240 let route = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[3],
3241 Some(InvoiceFeatures::known()), None, &Vec::new(), 180_000, 42, Arc::clone(&logger)).unwrap();
3242 assert_eq!(route.paths.len(), 2);
3244 let mut total_value_transferred_msat = 0;
3245 let mut total_paid_msat = 0;
3246 for path in &route.paths {
3247 assert_eq!(path.last().unwrap().pubkey, nodes[3]);
3248 total_value_transferred_msat += path.last().unwrap().fee_msat;
3250 total_paid_msat += hop.fee_msat;
3253 // If we paid fee, this would be higher.
3254 assert_eq!(total_value_transferred_msat, 180_000);
3255 let total_fees_paid = total_paid_msat - total_value_transferred_msat;
3256 assert_eq!(total_fees_paid, 0);
3261 fn fees_on_mpp_route_test() {
3262 // This test makes sure that MPP algorithm properly takes into account
3263 // fees charged on the channels, by making the fees impactful:
3264 // if the fee is not properly accounted for, the behavior is different.
3265 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
3266 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3268 // We need a route consisting of 2 paths:
3269 // From our node to node3 via {node0, node2} and {node7, node2, node4}.
3270 // We will route 200 sats, Each path will have 100 sats capacity.
3272 // This test is not particularly stable: e.g.,
3273 // there's a way to route via {node0, node2, node4}.
3274 // It works while pathfinding is deterministic, but can be broken otherwise.
3275 // It's fine to ignore this concern for now.
3277 // Disable other potential paths.
3278 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3279 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3280 short_channel_id: 2,
3283 cltv_expiry_delta: 0,
3284 htlc_minimum_msat: 0,
3285 htlc_maximum_msat: OptionalField::Present(100_000),
3287 fee_proportional_millionths: 0,
3288 excess_data: Vec::new()
3291 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3292 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3293 short_channel_id: 7,
3296 cltv_expiry_delta: 0,
3297 htlc_minimum_msat: 0,
3298 htlc_maximum_msat: OptionalField::Present(100_000),
3300 fee_proportional_millionths: 0,
3301 excess_data: Vec::new()
3304 // Path via {node0, node2} is channels {1, 3, 5}.
3305 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3306 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3307 short_channel_id: 1,
3310 cltv_expiry_delta: 0,
3311 htlc_minimum_msat: 0,
3312 htlc_maximum_msat: OptionalField::Present(100_000),
3314 fee_proportional_millionths: 0,
3315 excess_data: Vec::new()
3317 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3318 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3319 short_channel_id: 3,
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 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(5)), 5);
3331 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3332 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3333 short_channel_id: 5,
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()
3344 // Path via {node7, node2, node4} is channels {12, 13, 6, 11}.
3345 // All channels should be 100 sats capacity. But for the fee experiment,
3346 // we'll add absolute fee of 150 sats paid for the use channel 6 (paid to node2 on channel 13).
3347 // Since channel 12 allows to deliver only 250 sats to channel 13, channel 13 can transfer only
3348 // 100 sats (and pay 150 sats in fees for the use of channel 6),
3349 // so no matter how large are other channels,
3350 // the whole path will be limited by 100 sats with just these 2 conditions:
3351 // - channel 12 capacity is 250 sats
3352 // - fee for channel 6 is 150 sats
3353 // Let's test this by enforcing these 2 conditions and removing other limits.
3354 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3355 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3356 short_channel_id: 12,
3359 cltv_expiry_delta: 0,
3360 htlc_minimum_msat: 0,
3361 htlc_maximum_msat: OptionalField::Present(250_000),
3363 fee_proportional_millionths: 0,
3364 excess_data: Vec::new()
3366 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
3367 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3368 short_channel_id: 13,
3371 cltv_expiry_delta: 0,
3372 htlc_minimum_msat: 0,
3373 htlc_maximum_msat: OptionalField::Absent,
3375 fee_proportional_millionths: 0,
3376 excess_data: Vec::new()
3379 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3380 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3381 short_channel_id: 6,
3384 cltv_expiry_delta: 0,
3385 htlc_minimum_msat: 0,
3386 htlc_maximum_msat: OptionalField::Absent,
3387 fee_base_msat: 150_000,
3388 fee_proportional_millionths: 0,
3389 excess_data: Vec::new()
3391 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
3392 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3393 short_channel_id: 11,
3396 cltv_expiry_delta: 0,
3397 htlc_minimum_msat: 0,
3398 htlc_maximum_msat: OptionalField::Absent,
3400 fee_proportional_millionths: 0,
3401 excess_data: Vec::new()
3405 // Attempt to route more than available results in a failure.
3406 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[3],
3407 Some(InvoiceFeatures::known()), None, &Vec::new(), 210_000, 42, Arc::clone(&logger)) {
3408 assert_eq!(err, "Failed to find a sufficient route to the given destination");
3409 } else { panic!(); }
3413 // Now, attempt to route 200 sats (exact amount we can route).
3414 let route = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[3],
3415 Some(InvoiceFeatures::known()), None, &Vec::new(), 200_000, 42, Arc::clone(&logger)).unwrap();
3416 assert_eq!(route.paths.len(), 2);
3418 let mut total_amount_paid_msat = 0;
3419 for path in &route.paths {
3420 assert_eq!(path.last().unwrap().pubkey, nodes[3]);
3421 total_amount_paid_msat += path.last().unwrap().fee_msat;
3423 assert_eq!(total_amount_paid_msat, 200_000);
3429 fn drop_lowest_channel_mpp_route_test() {
3430 // This test checks that low-capacity channel is dropped when after
3431 // path finding we realize that we found more capacity than we need.
3432 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
3433 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3435 // We need a route consisting of 3 paths:
3436 // From our node to node2 via node0, node7, node1 (three paths one hop each).
3438 // The first and the second paths should be sufficient, but the third should be
3439 // cheaper, so that we select it but drop later.
3441 // First, we set limits on these (previously unlimited) channels.
3442 // Their aggregate capacity will be 50 + 60 + 20 = 130 sats.
3444 // Path via node0 is channels {1, 3}. Limit them to 100 and 50 sats (total limit 50);
3445 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3446 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3447 short_channel_id: 1,
3450 cltv_expiry_delta: 0,
3451 htlc_minimum_msat: 0,
3452 htlc_maximum_msat: OptionalField::Present(100_000),
3454 fee_proportional_millionths: 0,
3455 excess_data: Vec::new()
3457 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3458 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3459 short_channel_id: 3,
3462 cltv_expiry_delta: 0,
3463 htlc_minimum_msat: 0,
3464 htlc_maximum_msat: OptionalField::Present(50_000),
3466 fee_proportional_millionths: 0,
3467 excess_data: Vec::new()
3470 // Path via node7 is channels {12, 13}. Limit them to 60 and 60 sats (total limit 60);
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: 12,
3476 cltv_expiry_delta: 0,
3477 htlc_minimum_msat: 0,
3478 htlc_maximum_msat: OptionalField::Present(60_000),
3480 fee_proportional_millionths: 0,
3481 excess_data: Vec::new()
3483 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
3484 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3485 short_channel_id: 13,
3488 cltv_expiry_delta: 0,
3489 htlc_minimum_msat: 0,
3490 htlc_maximum_msat: OptionalField::Present(60_000),
3492 fee_proportional_millionths: 0,
3493 excess_data: Vec::new()
3496 // Path via node1 is channels {2, 4}. Limit them to 20 and 20 sats (total capacity 20 sats).
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: 2,
3502 cltv_expiry_delta: 0,
3503 htlc_minimum_msat: 0,
3504 htlc_maximum_msat: OptionalField::Present(20_000),
3506 fee_proportional_millionths: 0,
3507 excess_data: Vec::new()
3509 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
3510 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3511 short_channel_id: 4,
3514 cltv_expiry_delta: 0,
3515 htlc_minimum_msat: 0,
3516 htlc_maximum_msat: OptionalField::Present(20_000),
3518 fee_proportional_millionths: 0,
3519 excess_data: Vec::new()
3523 // Attempt to route more than available results in a failure.
3524 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2],
3525 Some(InvoiceFeatures::known()), None, &Vec::new(), 150_000, 42, Arc::clone(&logger)) {
3526 assert_eq!(err, "Failed to find a sufficient route to the given destination");
3527 } else { panic!(); }
3531 // Now, attempt to route 125 sats (just a bit below the capacity of 3 channels).
3532 // Our algorithm should provide us with these 3 paths.
3533 let route = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2],
3534 Some(InvoiceFeatures::known()), None, &Vec::new(), 125_000, 42, Arc::clone(&logger)).unwrap();
3535 assert_eq!(route.paths.len(), 3);
3536 let mut total_amount_paid_msat = 0;
3537 for path in &route.paths {
3538 assert_eq!(path.len(), 2);
3539 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
3540 total_amount_paid_msat += path.last().unwrap().fee_msat;
3542 assert_eq!(total_amount_paid_msat, 125_000);
3546 // Attempt to route without the last small cheap channel
3547 let route = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2],
3548 Some(InvoiceFeatures::known()), None, &Vec::new(), 90_000, 42, Arc::clone(&logger)).unwrap();
3549 assert_eq!(route.paths.len(), 2);
3550 let mut total_amount_paid_msat = 0;
3551 for path in &route.paths {
3552 assert_eq!(path.len(), 2);
3553 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
3554 total_amount_paid_msat += path.last().unwrap().fee_msat;
3556 assert_eq!(total_amount_paid_msat, 90_000);
3561 fn min_criteria_consistency() {
3562 // Test that we don't use an inconsistent metric between updating and walking nodes during
3563 // our Dijkstra's pass. In the initial version of MPP, the "best source" for a given node
3564 // was updated with a different criterion from the heap sorting, resulting in loops in
3565 // calculated paths. We test for that specific case here.
3567 // We construct a network that looks like this:
3569 // node2 -1(3)2- node3
3573 // node1 -1(5)2- node4 -1(1)2- node6
3579 // We create a loop on the side of our real path - our destination is node 6, with a
3580 // previous hop of node 4. From 4, the cheapest previous path is channel 2 from node 2,
3581 // followed by node 3 over channel 3. Thereafter, the cheapest next-hop is back to node 4
3582 // (this time over channel 4). Channel 4 has 0 htlc_minimum_msat whereas channel 1 (the
3583 // other channel with a previous-hop of node 4) has a high (but irrelevant to the overall
3584 // payment) htlc_minimum_msat. In the original algorithm, this resulted in node4's
3585 // "previous hop" being set to node 3, creating a loop in the path.
3586 let secp_ctx = Secp256k1::new();
3587 let logger = Arc::new(test_utils::TestLogger::new());
3588 let net_graph_msg_handler = NetGraphMsgHandler::new(genesis_block(Network::Testnet).header.block_hash(), None, Arc::clone(&logger));
3589 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3591 add_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, &privkeys[1], ChannelFeatures::from_le_bytes(id_to_feature_flags(6)), 6);
3592 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3593 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3594 short_channel_id: 6,
3597 cltv_expiry_delta: (6 << 8) | 0,
3598 htlc_minimum_msat: 0,
3599 htlc_maximum_msat: OptionalField::Absent,
3601 fee_proportional_millionths: 0,
3602 excess_data: Vec::new()
3604 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[1], NodeFeatures::from_le_bytes(id_to_feature_flags(1)), 0);
3606 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], &privkeys[4], ChannelFeatures::from_le_bytes(id_to_feature_flags(5)), 5);
3607 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
3608 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3609 short_channel_id: 5,
3612 cltv_expiry_delta: (5 << 8) | 0,
3613 htlc_minimum_msat: 0,
3614 htlc_maximum_msat: OptionalField::Absent,
3616 fee_proportional_millionths: 0,
3617 excess_data: Vec::new()
3619 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[4], NodeFeatures::from_le_bytes(id_to_feature_flags(4)), 0);
3621 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(4)), 4);
3622 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
3623 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3624 short_channel_id: 4,
3627 cltv_expiry_delta: (4 << 8) | 0,
3628 htlc_minimum_msat: 0,
3629 htlc_maximum_msat: OptionalField::Absent,
3631 fee_proportional_millionths: 0,
3632 excess_data: Vec::new()
3634 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[3], NodeFeatures::from_le_bytes(id_to_feature_flags(3)), 0);
3636 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[3], &privkeys[2], ChannelFeatures::from_le_bytes(id_to_feature_flags(3)), 3);
3637 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[3], UnsignedChannelUpdate {
3638 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3639 short_channel_id: 3,
3642 cltv_expiry_delta: (3 << 8) | 0,
3643 htlc_minimum_msat: 0,
3644 htlc_maximum_msat: OptionalField::Absent,
3646 fee_proportional_millionths: 0,
3647 excess_data: Vec::new()
3649 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[2], NodeFeatures::from_le_bytes(id_to_feature_flags(2)), 0);
3651 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], &privkeys[4], ChannelFeatures::from_le_bytes(id_to_feature_flags(2)), 2);
3652 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3653 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3654 short_channel_id: 2,
3657 cltv_expiry_delta: (2 << 8) | 0,
3658 htlc_minimum_msat: 0,
3659 htlc_maximum_msat: OptionalField::Absent,
3661 fee_proportional_millionths: 0,
3662 excess_data: Vec::new()
3665 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], &privkeys[6], ChannelFeatures::from_le_bytes(id_to_feature_flags(1)), 1);
3666 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
3667 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3668 short_channel_id: 1,
3671 cltv_expiry_delta: (1 << 8) | 0,
3672 htlc_minimum_msat: 100,
3673 htlc_maximum_msat: OptionalField::Absent,
3675 fee_proportional_millionths: 0,
3676 excess_data: Vec::new()
3678 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[6], NodeFeatures::from_le_bytes(id_to_feature_flags(6)), 0);
3681 // Now ensure the route flows simply over nodes 1 and 4 to 6.
3682 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();
3683 assert_eq!(route.paths.len(), 1);
3684 assert_eq!(route.paths[0].len(), 3);
3686 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
3687 assert_eq!(route.paths[0][0].short_channel_id, 6);
3688 assert_eq!(route.paths[0][0].fee_msat, 100);
3689 assert_eq!(route.paths[0][0].cltv_expiry_delta, (5 << 8) | 0);
3690 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(1));
3691 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(6));
3693 assert_eq!(route.paths[0][1].pubkey, nodes[4]);
3694 assert_eq!(route.paths[0][1].short_channel_id, 5);
3695 assert_eq!(route.paths[0][1].fee_msat, 0);
3696 assert_eq!(route.paths[0][1].cltv_expiry_delta, (1 << 8) | 0);
3697 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(4));
3698 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(5));
3700 assert_eq!(route.paths[0][2].pubkey, nodes[6]);
3701 assert_eq!(route.paths[0][2].short_channel_id, 1);
3702 assert_eq!(route.paths[0][2].fee_msat, 10_000);
3703 assert_eq!(route.paths[0][2].cltv_expiry_delta, 42);
3704 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(6));
3705 assert_eq!(route.paths[0][2].channel_features.le_flags(), &id_to_feature_flags(1));
3711 fn exact_fee_liquidity_limit() {
3712 // Test that if, while walking the graph, we find a hop that has exactly enough liquidity
3713 // for us, including later hop fees, we take it. In the first version of our MPP algorithm
3714 // we calculated fees on a higher value, resulting in us ignoring such paths.
3715 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
3716 let (our_privkey, our_id, _, nodes) = get_nodes(&secp_ctx);
3718 // We modify the graph to set the htlc_maximum of channel 2 to below the value we wish to
3720 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3721 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3722 short_channel_id: 2,
3725 cltv_expiry_delta: 0,
3726 htlc_minimum_msat: 0,
3727 htlc_maximum_msat: OptionalField::Present(85_000),
3729 fee_proportional_millionths: 0,
3730 excess_data: Vec::new()
3733 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3734 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3735 short_channel_id: 12,
3738 cltv_expiry_delta: (4 << 8) | 1,
3739 htlc_minimum_msat: 0,
3740 htlc_maximum_msat: OptionalField::Present(270_000),
3742 fee_proportional_millionths: 1000000,
3743 excess_data: Vec::new()
3747 // Now, attempt to route 90 sats, which is exactly 90 sats at the last hop, plus the
3748 // 200% fee charged channel 13 in the 1-to-2 direction.
3749 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();
3750 assert_eq!(route.paths.len(), 1);
3751 assert_eq!(route.paths[0].len(), 2);
3753 assert_eq!(route.paths[0][0].pubkey, nodes[7]);
3754 assert_eq!(route.paths[0][0].short_channel_id, 12);
3755 assert_eq!(route.paths[0][0].fee_msat, 90_000*2);
3756 assert_eq!(route.paths[0][0].cltv_expiry_delta, (13 << 8) | 1);
3757 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(8));
3758 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(12));
3760 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
3761 assert_eq!(route.paths[0][1].short_channel_id, 13);
3762 assert_eq!(route.paths[0][1].fee_msat, 90_000);
3763 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
3764 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
3765 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(13));
3770 fn htlc_max_reduction_below_min() {
3771 // Test that if, while walking the graph, we reduce the value being sent to meet an
3772 // htlc_maximum_msat, we don't end up undershooting a later htlc_minimum_msat. In the
3773 // initial version of MPP we'd accept such routes but reject them while recalculating fees,
3774 // resulting in us thinking there is no possible path, even if other paths exist.
3775 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
3776 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3778 // We modify the graph to set the htlc_minimum of channel 2 and 4 as needed - channel 2
3779 // gets an htlc_maximum_msat of 80_000 and channel 4 an htlc_minimum_msat of 90_000. We
3780 // then try to send 90_000.
3781 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3782 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3783 short_channel_id: 2,
3786 cltv_expiry_delta: 0,
3787 htlc_minimum_msat: 0,
3788 htlc_maximum_msat: OptionalField::Present(80_000),
3790 fee_proportional_millionths: 0,
3791 excess_data: Vec::new()
3793 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
3794 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3795 short_channel_id: 4,
3798 cltv_expiry_delta: (4 << 8) | 1,
3799 htlc_minimum_msat: 90_000,
3800 htlc_maximum_msat: OptionalField::Absent,
3802 fee_proportional_millionths: 0,
3803 excess_data: Vec::new()
3807 // Now, attempt to route 90 sats, hitting the htlc_minimum on channel 4, but
3808 // overshooting the htlc_maximum on channel 2. Thus, we should pick the (absurdly
3809 // expensive) channels 12-13 path.
3810 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();
3811 assert_eq!(route.paths.len(), 1);
3812 assert_eq!(route.paths[0].len(), 2);
3814 assert_eq!(route.paths[0][0].pubkey, nodes[7]);
3815 assert_eq!(route.paths[0][0].short_channel_id, 12);
3816 assert_eq!(route.paths[0][0].fee_msat, 90_000*2);
3817 assert_eq!(route.paths[0][0].cltv_expiry_delta, (13 << 8) | 1);
3818 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(8));
3819 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(12));
3821 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
3822 assert_eq!(route.paths[0][1].short_channel_id, 13);
3823 assert_eq!(route.paths[0][1].fee_msat, 90_000);
3824 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
3825 assert_eq!(route.paths[0][1].node_features.le_flags(), InvoiceFeatures::known().le_flags());
3826 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(13));
3831 use util::ser::Readable;
3832 /// Tries to open a network graph file, or panics with a URL to fetch it.
3833 pub(super) fn get_route_file() -> Result<std::fs::File, std::io::Error> {
3834 let res = File::open("net_graph-2021-02-12.bin") // By default we're run in RL/lightning
3835 .or_else(|_| File::open("lightning/net_graph-2021-02-12.bin")) // We may be run manually in RL/
3836 .or_else(|_| { // Fall back to guessing based on the binary location
3837 // path is likely something like .../rust-lightning/target/debug/deps/lightning-...
3838 let mut path = std::env::current_exe().unwrap();
3839 path.pop(); // lightning-...
3841 path.pop(); // debug
3842 path.pop(); // target
3843 path.push("lightning");
3844 path.push("net_graph-2021-02-12.bin");
3845 eprintln!("{}", path.to_str().unwrap());
3848 #[cfg(require_route_graph_test)]
3849 return Ok(res.expect("Didn't have route graph and was configured to require it"));
3853 pub(super) fn random_init_seed() -> u64 {
3854 // Because the default HashMap in std pulls OS randomness, we can use it as a (bad) RNG.
3855 use std::hash::{BuildHasher, Hasher};
3856 let seed = std::collections::hash_map::RandomState::new().build_hasher().finish();
3857 println!("Using seed of {}", seed);
3862 fn generate_routes() {
3863 let mut d = match get_route_file() {
3866 eprintln!("Please fetch https://bitcoin.ninja/ldk-net_graph-879e309c128-2020-02-12.bin and place it at lightning/net_graph-2021-02-12.bin");
3870 let graph = NetworkGraph::read(&mut d).unwrap();
3872 // First, get 100 (source, destination) pairs for which route-getting actually succeeds...
3873 let mut seed = random_init_seed() as usize;
3874 'load_endpoints: for _ in 0..10 {
3876 seed = seed.overflowing_mul(0xdeadbeef).0;
3877 let src = graph.get_nodes().keys().skip(seed % graph.get_nodes().len()).next().unwrap();
3878 seed = seed.overflowing_mul(0xdeadbeef).0;
3879 let dst = graph.get_nodes().keys().skip(seed % graph.get_nodes().len()).next().unwrap();
3880 let amt = seed as u64 % 200_000_000;
3881 if get_route(src, &graph, dst, None, None, &[], amt, 42, &test_utils::TestLogger::new()).is_ok() {
3882 continue 'load_endpoints;
3889 fn generate_routes_mpp() {
3890 let mut d = match get_route_file() {
3893 eprintln!("Please fetch https://bitcoin.ninja/ldk-net_graph-879e309c128-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, Some(InvoiceFeatures::known()), None, &[], amt, 42, &test_utils::TestLogger::new()).is_ok() {
3909 continue 'load_endpoints;
3916 #[cfg(all(test, feature = "unstable"))]
3919 use util::logger::{Logger, Record};
3924 struct DummyLogger {}
3925 impl Logger for DummyLogger {
3926 fn log(&self, _record: &Record) {}
3930 fn generate_routes(bench: &mut Bencher) {
3931 let mut d = tests::get_route_file()
3932 .expect("Please fetch https://bitcoin.ninja/ldk-net_graph-879e309c128-2020-02-12.bin and place it at lightning/net_graph-2021-02-12.bin");
3933 let graph = NetworkGraph::read(&mut d).unwrap();
3935 // First, get 100 (source, destination) pairs for which route-getting actually succeeds...
3936 let mut path_endpoints = Vec::new();
3937 let mut seed: usize = 0xdeadbeef;
3938 'load_endpoints: for _ in 0..100 {
3941 let src = graph.get_nodes().keys().skip(seed % graph.get_nodes().len()).next().unwrap();
3943 let dst = graph.get_nodes().keys().skip(seed % graph.get_nodes().len()).next().unwrap();
3944 let amt = seed as u64 % 1_000_000;
3945 if get_route(src, &graph, dst, None, None, &[], amt, 42, &DummyLogger{}).is_ok() {
3946 path_endpoints.push((src, dst, amt));
3947 continue 'load_endpoints;
3952 // ...then benchmark finding paths between the nodes we learned.
3955 let (src, dst, amt) = path_endpoints[idx % path_endpoints.len()];
3956 assert!(get_route(src, &graph, dst, None, None, &[], amt, 42, &DummyLogger{}).is_ok());
3962 fn generate_mpp_routes(bench: &mut Bencher) {
3963 let mut d = tests::get_route_file()
3964 .expect("Please fetch https://bitcoin.ninja/ldk-net_graph-879e309c128-2020-02-12.bin and place it at lightning/net_graph-2021-02-12.bin");
3965 let graph = NetworkGraph::read(&mut d).unwrap();
3967 // First, get 100 (source, destination) pairs for which route-getting actually succeeds...
3968 let mut path_endpoints = Vec::new();
3969 let mut seed: usize = 0xdeadbeef;
3970 'load_endpoints: for _ in 0..100 {
3973 let src = graph.get_nodes().keys().skip(seed % graph.get_nodes().len()).next().unwrap();
3975 let dst = graph.get_nodes().keys().skip(seed % graph.get_nodes().len()).next().unwrap();
3976 let amt = seed as u64 % 1_000_000;
3977 if get_route(src, &graph, dst, Some(InvoiceFeatures::known()), None, &[], amt, 42, &DummyLogger{}).is_ok() {
3978 path_endpoints.push((src, dst, amt));
3979 continue 'load_endpoints;
3984 // ...then benchmark finding paths between the nodes we learned.
3987 let (src, dst, amt) = path_endpoints[idx % path_endpoints.len()];
3988 assert!(get_route(src, &graph, dst, Some(InvoiceFeatures::known()), None, &[], amt, 42, &DummyLogger{}).is_ok());