1 // This file is Copyright its original authors, visible in version control
4 // This file is licensed under the Apache License, Version 2.0 <LICENSE-APACHE
5 // or http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
6 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your option.
7 // You may not use this file except in accordance with one or both of these
10 //! The top-level routing/network map tracking logic lives here.
12 //! You probably want to create a NetGraphMsgHandler and use that as your RoutingMessageHandler and then
13 //! interrogate it to get routes for your own payments.
15 use bitcoin::secp256k1::key::PublicKey;
17 use ln::channelmanager::ChannelDetails;
18 use ln::features::{ChannelFeatures, InvoiceFeatures, NodeFeatures};
19 use ln::msgs::{DecodeError, ErrorAction, LightningError, MAX_VALUE_MSAT};
20 use routing::network_graph::{NetworkGraph, RoutingFees};
21 use util::ser::{Writeable, Readable};
22 use util::logger::Logger;
25 use std::collections::{HashMap, BinaryHeap};
29 #[derive(Clone, PartialEq)]
31 /// The node_id of the node at this hop.
32 pub pubkey: PublicKey,
33 /// The node_announcement features of the node at this hop. For the last hop, these may be
34 /// amended to match the features present in the invoice this node generated.
35 pub node_features: NodeFeatures,
36 /// The channel that should be used from the previous hop to reach this node.
37 pub short_channel_id: u64,
38 /// The channel_announcement features of the channel that should be used from the previous hop
39 /// to reach this node.
40 pub channel_features: ChannelFeatures,
41 /// The fee taken on this hop (for paying for the use of the *next* channel in the path).
42 /// For the last hop, this should be the full value of the payment (might be more than
43 /// requested if we had to match htlc_minimum_msat).
45 /// The CLTV delta added for this hop. For the last hop, this should be the full CLTV value
46 /// expected at the destination, in excess of the current block height.
47 pub cltv_expiry_delta: u32,
51 impl Writeable for Vec<RouteHop> {
52 fn write<W: ::util::ser::Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
53 (self.len() as u8).write(writer)?;
54 for hop in self.iter() {
55 hop.pubkey.write(writer)?;
56 hop.node_features.write(writer)?;
57 hop.short_channel_id.write(writer)?;
58 hop.channel_features.write(writer)?;
59 hop.fee_msat.write(writer)?;
60 hop.cltv_expiry_delta.write(writer)?;
67 impl Readable for Vec<RouteHop> {
68 fn read<R: ::std::io::Read>(reader: &mut R) -> Result<Vec<RouteHop>, DecodeError> {
69 let hops_count: u8 = Readable::read(reader)?;
70 let mut hops = Vec::with_capacity(hops_count as usize);
71 for _ in 0..hops_count {
73 pubkey: Readable::read(reader)?,
74 node_features: Readable::read(reader)?,
75 short_channel_id: Readable::read(reader)?,
76 channel_features: Readable::read(reader)?,
77 fee_msat: Readable::read(reader)?,
78 cltv_expiry_delta: Readable::read(reader)?,
85 /// A route directs a payment from the sender (us) to the recipient. If the recipient supports MPP,
86 /// it can take multiple paths. Each path is composed of one or more hops through the network.
87 #[derive(Clone, PartialEq)]
89 /// The list of routes taken for a single (potentially-)multi-part payment. The pubkey of the
90 /// last RouteHop in each path must be the same.
91 /// Each entry represents a list of hops, NOT INCLUDING our own, where the last hop is the
92 /// destination. Thus, this must always be at least length one. While the maximum length of any
93 /// given path is variable, keeping the length of any path to less than 20 should currently
94 /// ensure it is viable.
95 pub paths: Vec<Vec<RouteHop>>,
98 impl Writeable for Route {
99 fn write<W: ::util::ser::Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
100 (self.paths.len() as u64).write(writer)?;
101 for hops in self.paths.iter() {
108 impl Readable for Route {
109 fn read<R: ::std::io::Read>(reader: &mut R) -> Result<Route, DecodeError> {
110 let path_count: u64 = Readable::read(reader)?;
111 let mut paths = Vec::with_capacity(cmp::min(path_count, 128) as usize);
112 for _ in 0..path_count {
113 paths.push(Readable::read(reader)?);
119 /// A channel descriptor which provides a last-hop route to get_route
121 pub struct RouteHint {
122 /// The node_id of the non-target end of the route
123 pub src_node_id: PublicKey,
124 /// The short_channel_id of this channel
125 pub short_channel_id: u64,
126 /// The fees which must be paid to use this channel
127 pub fees: RoutingFees,
128 /// The difference in CLTV values between this node and the next node.
129 pub cltv_expiry_delta: u16,
130 /// The minimum value, in msat, which must be relayed to the next hop.
131 pub htlc_minimum_msat: Option<u64>,
132 /// The maximum value in msat available for routing with a single HTLC.
133 pub htlc_maximum_msat: Option<u64>,
136 #[derive(Eq, PartialEq)]
137 struct RouteGraphNode {
139 lowest_fee_to_peer_through_node: u64,
140 lowest_fee_to_node: u64,
141 // The maximum value a yet-to-be-constructed payment path might flow through this node.
142 // This value is upper-bounded by us by:
143 // - how much is needed for a path being constructed
144 // - how much value can channels following this node (up to the destination) can contribute,
145 // considering their capacity and fees
146 value_contribution_msat: u64
149 impl cmp::Ord for RouteGraphNode {
150 fn cmp(&self, other: &RouteGraphNode) -> cmp::Ordering {
151 other.lowest_fee_to_peer_through_node.cmp(&self.lowest_fee_to_peer_through_node)
152 .then_with(|| other.pubkey.serialize().cmp(&self.pubkey.serialize()))
156 impl cmp::PartialOrd for RouteGraphNode {
157 fn partial_cmp(&self, other: &RouteGraphNode) -> Option<cmp::Ordering> {
158 Some(self.cmp(other))
162 struct DummyDirectionalChannelInfo {
163 cltv_expiry_delta: u32,
164 htlc_minimum_msat: u64,
165 htlc_maximum_msat: Option<u64>,
169 /// It's useful to keep track of the hops associated with the fees required to use them,
170 /// so that we can choose cheaper paths (as per Dijkstra's algorithm).
171 /// Fee values should be updated only in the context of the whole path, see update_value_and_recompute_fees.
172 /// These fee values are useful to choose hops as we traverse the graph "payee-to-payer".
174 struct PathBuildingHop {
175 /// Hop-specific details unrelated to the path during the routing phase,
176 /// but rather relevant to the LN graph.
178 /// Minimal fees required to route to the source node of the current hop via any of its inbound channels.
179 src_lowest_inbound_fees: RoutingFees,
180 /// Fees of the channel used in this hop.
181 channel_fees: RoutingFees,
182 /// All the fees paid *after* this channel on the way to the destination
183 next_hops_fee_msat: u64,
184 /// Fee paid for the use of the current channel (see channel_fees).
185 /// The value will be actually deducted from the counterparty balance on the previous link.
186 hop_use_fee_msat: u64,
187 /// Used to compare channels when choosing the for routing.
188 /// Includes paying for the use of a hop and the following hops, as well as
189 /// an estimated cost of reaching this hop.
190 /// Might get stale when fees are recomputed. Primarily for internal use.
192 /// This is useful for update_value_and_recompute_fees to make sure
193 /// we don't fall below the minimum. Should not be updated manually and
194 /// generally should not be accessed.
195 htlc_minimum_msat: u64,
198 // Instantiated with a list of hops with correct data in them collected during path finding,
199 // an instance of this struct should be further modified only via given methods.
202 hops: Vec<PathBuildingHop>,
207 // TODO: Add a value_msat field to PaymentPath and use it instead of this function.
208 fn get_value_msat(&self) -> u64 {
209 self.hops.last().unwrap().route_hop.fee_msat
212 fn get_total_fee_paid_msat(&self) -> u64 {
213 if self.hops.len() < 1 {
217 // Can't use next_hops_fee_msat because it gets outdated.
218 for (i, hop) in self.hops.iter().enumerate() {
219 if i != self.hops.len() - 1 {
220 result += hop.route_hop.fee_msat;
226 // If the amount transferred by the path is updated, the fees should be adjusted. Any other way
227 // to change fees may result in an inconsistency.
229 // Sometimes we call this function right after constructing a path which has inconsistent
230 // (in terms of reaching htlc_minimum_msat), so that this function puts the fees in order.
231 // In that case we call it on the "same" amount we initially allocated for this path, and which
232 // could have been reduced on the way. In that case, there is also a risk of exceeding
233 // available_liquidity inside this function, because the function is unaware of this bound.
234 // In our specific recomputation cases where we never increase the value the risk is pretty low.
235 // This function, however, does not support arbitrarily increasing the value being transferred,
236 // and the exception will be triggered.
237 fn update_value_and_recompute_fees(&mut self, value_msat: u64) {
238 assert!(value_msat <= self.hops.last().unwrap().route_hop.fee_msat);
240 let mut total_fee_paid_msat = 0 as u64;
241 for i in (0..self.hops.len()).rev() {
242 let last_hop = i == self.hops.len() - 1;
244 // For non-last-hop, this value will represent the fees paid on the current hop. It
245 // will consist of the fees for the use of the next hop, and extra fees to match
246 // htlc_minimum_msat of the current channel. Last hop is handled separately.
247 let mut cur_hop_fees_msat = 0;
249 cur_hop_fees_msat = self.hops.get(i + 1).unwrap().hop_use_fee_msat;
252 let mut cur_hop = self.hops.get_mut(i).unwrap();
253 cur_hop.next_hops_fee_msat = total_fee_paid_msat;
254 // Overpay in fees if we can't save these funds due to htlc_minimum_msat.
255 // We try to account for htlc_minimum_msat in scoring (add_entry!), so that nodes don't
256 // set it too high just to maliciously take more fees by exploiting this
257 // match htlc_minimum_msat logic.
258 let mut cur_hop_transferred_amount_msat = total_fee_paid_msat + value_msat;
259 if let Some(extra_fees_msat) = cur_hop.htlc_minimum_msat.checked_sub(cur_hop_transferred_amount_msat) {
260 // Note that there is a risk that *previous hops* (those closer to us, as we go
261 // payee->our_node here) would exceed their htlc_maximum_msat or available balance.
263 // This might make us end up with a broken route, although this should be super-rare
264 // in practice, both because of how healthy channels look like, and how we pick
265 // channels in add_entry.
266 // Also, this can't be exploited more heavily than *announce a free path and fail
268 cur_hop_transferred_amount_msat += extra_fees_msat;
269 total_fee_paid_msat += extra_fees_msat;
270 cur_hop_fees_msat += extra_fees_msat;
274 // Final hop is a special case: it usually has just value_msat (by design), but also
275 // it still could overpay for the htlc_minimum_msat.
276 cur_hop.route_hop.fee_msat = cur_hop_transferred_amount_msat;
278 // Propagate updated fees for the use of the channels to one hop back, where they
279 // will be actually paid (fee_msat). The last hop is handled above separately.
280 cur_hop.route_hop.fee_msat = cur_hop_fees_msat;
283 // Fee for the use of the current hop which will be deducted on the previous hop.
284 // Irrelevant for the first hop, as it doesn't have the previous hop, and the use of
285 // this channel is free for us.
287 if let Some(new_fee) = compute_fees(cur_hop_transferred_amount_msat, cur_hop.channel_fees) {
288 cur_hop.hop_use_fee_msat = new_fee;
289 total_fee_paid_msat += new_fee;
291 // It should not be possible because this function is called only to reduce the
292 // value. In that case, compute_fee was already called with the same fees for
293 // larger amount and there was no overflow.
301 fn compute_fees(amount_msat: u64, channel_fees: RoutingFees) -> Option<u64> {
302 let proportional_fee_millions =
303 amount_msat.checked_mul(channel_fees.proportional_millionths as u64);
304 if let Some(new_fee) = proportional_fee_millions.and_then(|part| {
305 (channel_fees.base_msat as u64).checked_add(part / 1_000_000) }) {
309 // This function may be (indirectly) called without any verification,
310 // with channel_fees provided by a caller. We should handle it gracefully.
315 /// Gets a route from us (payer) to the given target node (payee).
317 /// If the payee provided features in their invoice, they should be provided via payee_features.
318 /// Without this, MPP will only be used if the payee's features are available in the network graph.
320 /// Extra routing hops between known nodes and the target will be used if they are included in
323 /// If some channels aren't announced, it may be useful to fill in a first_hops with the
324 /// results from a local ChannelManager::list_usable_channels() call. If it is filled in, our
325 /// view of our local channels (from net_graph_msg_handler) will be ignored, and only those
326 /// in first_hops will be used.
328 /// Panics if first_hops contains channels without short_channel_ids
329 /// (ChannelManager::list_usable_channels will never include such channels).
331 /// The fees on channels from us to next-hops are ignored (as they are assumed to all be
332 /// equal), however the enabled/disabled bit on such channels as well as the
333 /// htlc_minimum_msat/htlc_maximum_msat *are* checked as they may change based on the receiving node.
334 pub fn get_route<L: Deref>(our_node_id: &PublicKey, network: &NetworkGraph, payee: &PublicKey, payee_features: Option<InvoiceFeatures>, first_hops: Option<&[&ChannelDetails]>,
335 last_hops: &[&RouteHint], final_value_msat: u64, final_cltv: u32, logger: L) -> Result<Route, LightningError> where L::Target: Logger {
336 // TODO: Obviously *only* using total fee cost sucks. We should consider weighting by
337 // uptime/success in using a node in the past.
338 if *payee == *our_node_id {
339 return Err(LightningError{err: "Cannot generate a route to ourselves".to_owned(), action: ErrorAction::IgnoreError});
342 if final_value_msat > MAX_VALUE_MSAT {
343 return Err(LightningError{err: "Cannot generate a route of more value than all existing satoshis".to_owned(), action: ErrorAction::IgnoreError});
346 if final_value_msat == 0 {
347 return Err(LightningError{err: "Cannot send a payment of 0 msat".to_owned(), action: ErrorAction::IgnoreError});
350 for last_hop in last_hops {
351 if last_hop.src_node_id == *payee {
352 return Err(LightningError{err: "Last hop cannot have a payee as a source.".to_owned(), action: ErrorAction::IgnoreError});
356 // The general routing idea is the following:
357 // 1. Fill first/last hops communicated by the caller.
358 // 2. Attempt to construct a path from payer to payee for transferring
359 // any ~sufficient (described later) value.
360 // If succeed, remember which channels were used and how much liquidity they have available,
361 // so that future paths don't rely on the same liquidity.
362 // 3. Prooceed to the next step if:
363 // - we hit the recommended target value;
364 // - OR if we could not construct a new path. Any next attempt will fail too.
365 // Otherwise, repeat step 2.
366 // 4. See if we managed to collect paths which aggregately are able to transfer target value
367 // (not recommended value). If yes, proceed. If not, fail routing.
368 // 5. Randomly combine paths into routes having enough to fulfill the payment. (TODO: knapsack)
369 // 6. Of all the found paths, select only those with the lowest total fee.
370 // 7. The last path in every selected route is likely to be more than we need.
371 // Reduce its value-to-transfer and recompute fees.
372 // 8. Choose the best route by the lowest total fee.
374 // As for the actual search algorithm,
375 // we do a payee-to-payer pseudo-Dijkstra's sorting by each node's distance from the payee
376 // plus the minimum per-HTLC fee to get from it to another node (aka "shitty pseudo-A*").
378 // We are not a faithful Dijkstra's implementation because we can change values which impact
379 // earlier nodes while processing later nodes. Specifically, if we reach a channel with a lower
380 // liquidity limit (via htlc_maximum_msat, on-chain capacity or assumed liquidity limits) then
381 // the value we are currently attempting to send over a path, we simply reduce the value being
382 // sent along the path for any hops after that channel. This may imply that later fees (which
383 // we've already tabulated) are lower because a smaller value is passing through the channels
384 // (and the proportional fee is thus lower). There isn't a trivial way to recalculate the
385 // channels which were selected earlier (and which may still be used for other paths without a
386 // lower liquidity limit), so we simply accept that some liquidity-limited paths may be
389 // One potentially problematic case for this algorithm would be if there are many
390 // liquidity-limited paths which are liquidity-limited near the destination (ie early in our
391 // graph walking), we may never find a liquidity-unlimited path which has lower proportional
392 // fee (and only lower absolute fee when considering the ultimate value sent). Because we only
393 // consider paths with at least 5% of the total value being sent, the damage from such a case
394 // should be limited, however this could be further reduced in the future by calculating fees
395 // on the amount we wish to route over a path, not the amount we are routing over a path.
397 // Alternatively, we could store more detailed path information in the heap (targets, below)
398 // and index the best-path map (dist, below) by node *and* HTLC limits, however that would blow
399 // up the runtime significantly both algorithmically (as we'd traverse nodes multiple times)
400 // and practically (as we would need to store dynamically-allocated path information in heap
401 // objects, increasing malloc traffic and indirect memory access significantly). Further, the
402 // results of such an algorithm would likely be biased towards lower-value paths.
404 // Further, we could return to a faithful Dijkstra's algorithm by rejecting paths with limits
405 // outside of our current search value, running a path search more times to gather candidate
406 // paths at different values. While this may be acceptable, further path searches may increase
407 // runtime for little gain. Specifically, the current algorithm rather efficiently explores the
408 // graph for candidate paths, calculating the maximum value which can realistically be sent at
409 // the same time, remaining generic across different payment values.
411 // TODO: There are a few tweaks we could do, including possibly pre-calculating more stuff
412 // to use as the A* heuristic beyond just the cost to get one node further than the current
415 let dummy_directional_info = DummyDirectionalChannelInfo { // used for first_hops routes
416 cltv_expiry_delta: 0,
417 htlc_minimum_msat: 0,
418 htlc_maximum_msat: None,
421 proportional_millionths: 0,
425 let mut targets = BinaryHeap::new(); //TODO: Do we care about switching to eg Fibbonaci heap?
426 let mut dist = HashMap::with_capacity(network.get_nodes().len());
428 // During routing, if we ignore a path due to an htlc_minimum_msat limit, we set this,
429 // indicating that we may wish to try again with a higher value, potentially paying to meet an
430 // htlc_minimum with extra fees while still finding a cheaper path.
431 let mut hit_minimum_limit;
433 // When arranging a route, we select multiple paths so that we can make a multi-path payment.
434 // We start with a path_value of the exact amount we want, and if that generates a route we may
435 // return it immediately. Otherwise, we don't stop searching for paths until we have 3x the
436 // amount we want in total across paths, selecting the best subset at the end.
437 const ROUTE_CAPACITY_PROVISION_FACTOR: u64 = 3;
438 let recommended_value_msat = final_value_msat * ROUTE_CAPACITY_PROVISION_FACTOR as u64;
439 let mut path_value_msat = final_value_msat;
441 // Allow MPP only if we have a features set from somewhere that indicates the payee supports
442 // it. If the payee supports it they're supposed to include it in the invoice, so that should
444 let allow_mpp = if let Some(features) = &payee_features {
445 features.supports_basic_mpp()
446 } else if let Some(node) = network.get_nodes().get(&payee) {
447 if let Some(node_info) = node.announcement_info.as_ref() {
448 node_info.features.supports_basic_mpp()
453 // Prepare the data we'll use for payee-to-payer search by
454 // inserting first hops suggested by the caller as targets.
455 // Our search will then attempt to reach them while traversing from the payee node.
456 let mut first_hop_targets = HashMap::with_capacity(if first_hops.is_some() { first_hops.as_ref().unwrap().len() } else { 0 });
457 if let Some(hops) = first_hops {
459 let short_channel_id = chan.short_channel_id.expect("first_hops should be filled in with usable channels, not pending ones");
460 if chan.remote_network_id == *our_node_id {
461 return Err(LightningError{err: "First hop cannot have our_node_id as a destination.".to_owned(), action: ErrorAction::IgnoreError});
463 first_hop_targets.insert(chan.remote_network_id, (short_channel_id, chan.counterparty_features.clone(), chan.outbound_capacity_msat));
465 if first_hop_targets.is_empty() {
466 return Err(LightningError{err: "Cannot route when there are no outbound routes away from us".to_owned(), action: ErrorAction::IgnoreError});
470 // We don't want multiple paths (as per MPP) share liquidity of the same channels.
471 // This map allows paths to be aware of the channel use by other paths in the same call.
472 // This would help to make a better path finding decisions and not "overbook" channels.
473 // It is unaware of the directions (except for `outbound_capacity_msat` in `first_hops`).
474 let mut bookkeeped_channels_liquidity_available_msat = HashMap::new();
476 // Keeping track of how much value we already collected across other paths. Helps to decide:
477 // - how much a new path should be transferring (upper bound);
478 // - whether a channel should be disregarded because
479 // it's available liquidity is too small comparing to how much more we need to collect;
480 // - when we want to stop looking for new paths.
481 let mut already_collected_value_msat = 0;
483 macro_rules! add_entry {
484 // Adds entry which goes from $src_node_id to $dest_node_id
485 // over the channel with id $chan_id with fees described in
486 // $directional_info.
487 // $next_hops_fee_msat represents the fees paid for using all the channel *after* this one,
488 // since that value has to be transferred over this channel.
489 ( $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,
490 $next_hops_value_contribution: expr ) => {
491 // Channels to self should not be used. This is more of belt-and-suspenders, because in
492 // practice these cases should be caught earlier:
493 // - for regular channels at channel announcement (TODO)
494 // - for first and last hops early in get_route
495 if $src_node_id != $dest_node_id.clone() {
496 let available_liquidity_msat = bookkeeped_channels_liquidity_available_msat.entry($chan_id.clone()).or_insert_with(|| {
497 let mut initial_liquidity_available_msat = None;
498 if let Some(capacity_sats) = $capacity_sats {
499 initial_liquidity_available_msat = Some(capacity_sats * 1000);
502 if let Some(htlc_maximum_msat) = $directional_info.htlc_maximum_msat {
503 if let Some(available_msat) = initial_liquidity_available_msat {
504 initial_liquidity_available_msat = Some(cmp::min(available_msat, htlc_maximum_msat));
506 initial_liquidity_available_msat = Some(htlc_maximum_msat);
510 match initial_liquidity_available_msat {
511 Some(available_msat) => available_msat,
512 // We assume channels with unknown balance have
513 // a capacity of 0.0025 BTC (or 250_000 sats).
514 None => 250_000 * 1000
518 // It is tricky to substract $next_hops_fee_msat from available liquidity here.
519 // It may be misleading because we might later choose to reduce the value transferred
520 // over these channels, and the channel which was insufficient might become sufficient.
521 // Worst case: we drop a good channel here because it can't cover the high following
522 // fees caused by one expensive channel, but then this channel could have been used
523 // if the amount being transferred over this path is lower.
524 // We do this for now, but this is a subject for removal.
525 if let Some(available_value_contribution_msat) = available_liquidity_msat.checked_sub($next_hops_fee_msat) {
527 // Routing Fragmentation Mitigation heuristic:
529 // Routing fragmentation across many payment paths increases the overall routing
530 // fees as you have irreducible routing fees per-link used (`fee_base_msat`).
531 // Taking too many smaller paths also increases the chance of payment failure.
532 // Thus to avoid this effect, we require from our collected links to provide
533 // at least a minimal contribution to the recommended value yet-to-be-fulfilled.
535 // This requirement is currently 5% of the remaining-to-be-collected value.
536 // This means as we successfully advance in our collection,
537 // the absolute liquidity contribution is lowered,
538 // thus increasing the number of potential channels to be selected.
540 // Derive the minimal liquidity contribution with a ratio of 20 (5%, rounded up)
541 // or 100% if we're not allowed to do multipath payments.
542 let minimal_value_contribution_msat: u64 = if allow_mpp {
543 (recommended_value_msat - already_collected_value_msat + 19) / 20
547 // Verify the liquidity offered by this channel complies to the minimal contribution.
548 let contributes_sufficient_value = available_value_contribution_msat >= minimal_value_contribution_msat;
550 let value_contribution_msat = cmp::min(available_value_contribution_msat, $next_hops_value_contribution);
551 // Includes paying fees for the use of the following channels.
552 let amount_to_transfer_over_msat: u64 = match value_contribution_msat.checked_add($next_hops_fee_msat) {
553 Some(result) => result,
554 // Can't overflow due to how the values were computed right above.
555 None => unreachable!(),
558 // If HTLC minimum is larger than the amount we're going to transfer, we shouldn't
559 // bother considering this channel.
560 // Since we're choosing amount_to_transfer_over_msat as maximum possible, it can
561 // be only reduced later (not increased), so this channel should just be skipped
562 // as not sufficient.
563 if amount_to_transfer_over_msat < $directional_info.htlc_minimum_msat {
564 hit_minimum_limit = true;
565 } else if contributes_sufficient_value {
566 // Note that low contribution here (limited by available_liquidity_msat)
567 // might violate htlc_minimum_msat on the hops which are next along the
568 // payment path (upstream to the payee). To avoid that, we recompute path
569 // path fees knowing the final path contribution after constructing it.
570 let hm_entry = dist.entry(&$src_node_id);
571 let old_entry = hm_entry.or_insert_with(|| {
572 // If there was previously no known way to access
573 // the source node (recall it goes payee-to-payer) of $chan_id, first add
574 // a semi-dummy record just to compute the fees to reach the source node.
575 // This will affect our decision on selecting $chan_id
576 // as a way to reach the $dest_node_id.
577 let mut fee_base_msat = u32::max_value();
578 let mut fee_proportional_millionths = u32::max_value();
579 if let Some(Some(fees)) = network.get_nodes().get(&$src_node_id).map(|node| node.lowest_inbound_channel_fees) {
580 fee_base_msat = fees.base_msat;
581 fee_proportional_millionths = fees.proportional_millionths;
584 route_hop: RouteHop {
585 pubkey: $dest_node_id.clone(),
586 node_features: NodeFeatures::empty(),
588 channel_features: $chan_features.clone(),
590 cltv_expiry_delta: 0,
592 src_lowest_inbound_fees: RoutingFees {
593 base_msat: fee_base_msat,
594 proportional_millionths: fee_proportional_millionths,
596 channel_fees: $directional_info.fees,
597 next_hops_fee_msat: u64::max_value(),
598 hop_use_fee_msat: u64::max_value(),
599 total_fee_msat: u64::max_value(),
600 htlc_minimum_msat: $directional_info.htlc_minimum_msat,
604 let mut hop_use_fee_msat = 0;
605 let mut total_fee_msat = $next_hops_fee_msat;
607 // Ignore hop_use_fee_msat for channel-from-us as we assume all channels-from-us
608 // will have the same effective-fee
609 if $src_node_id != *our_node_id {
610 match compute_fees(amount_to_transfer_over_msat, $directional_info.fees) {
611 // max_value means we'll always fail
612 // the old_entry.total_fee_msat > total_fee_msat check
613 None => total_fee_msat = u64::max_value(),
615 hop_use_fee_msat = fee_msat;
616 total_fee_msat += hop_use_fee_msat;
617 if let Some(prev_hop_fee_msat) = compute_fees(total_fee_msat + amount_to_transfer_over_msat,
618 old_entry.src_lowest_inbound_fees) {
619 if let Some(incremented_total_fee_msat) = total_fee_msat.checked_add(prev_hop_fee_msat) {
620 total_fee_msat = incremented_total_fee_msat;
623 // max_value means we'll always fail
624 // the old_entry.total_fee_msat > total_fee_msat check
625 total_fee_msat = u64::max_value();
628 // max_value means we'll always fail
629 // the old_entry.total_fee_msat > total_fee_msat check
630 total_fee_msat = u64::max_value();
636 let new_graph_node = RouteGraphNode {
637 pubkey: $src_node_id,
638 lowest_fee_to_peer_through_node: total_fee_msat,
639 lowest_fee_to_node: $next_hops_fee_msat as u64 + hop_use_fee_msat,
640 value_contribution_msat: value_contribution_msat,
643 // Update the way of reaching $src_node_id with the given $chan_id (from $dest_node_id),
644 // if this way is cheaper than the already known
645 // (considering the cost to "reach" this channel from the route destination,
646 // the cost of using this channel,
647 // and the cost of routing to the source node of this channel).
648 // Also, consider that htlc_minimum_msat_difference, because we might end up
649 // paying it. Consider the following exploit:
650 // we use 2 paths to transfer 1.5 BTC. One of them is 0-fee normal 1 BTC path,
651 // and for the other one we picked a 1sat-fee path with htlc_minimum_msat of
652 // 1 BTC. Now, since the latter is more expensive, we gonna try to cut it
653 // by 0.5 BTC, but then match htlc_minimum_msat by paying a fee of 0.5 BTC
655 // TODO: this scoring could be smarter (e.g. 0.5*htlc_minimum_msat here).
656 let mut old_cost = old_entry.total_fee_msat;
657 if let Some(increased_old_cost) = old_cost.checked_add(old_entry.htlc_minimum_msat) {
658 old_cost = increased_old_cost;
660 old_cost = u64::max_value();
663 let mut new_cost = total_fee_msat;
664 if let Some(increased_new_cost) = new_cost.checked_add($directional_info.htlc_minimum_msat) {
665 new_cost = increased_new_cost;
667 new_cost = u64::max_value();
670 if new_cost < old_cost {
671 targets.push(new_graph_node);
672 old_entry.next_hops_fee_msat = $next_hops_fee_msat;
673 old_entry.hop_use_fee_msat = hop_use_fee_msat;
674 old_entry.total_fee_msat = total_fee_msat;
675 old_entry.route_hop = RouteHop {
676 pubkey: $dest_node_id.clone(),
677 node_features: NodeFeatures::empty(),
678 short_channel_id: $chan_id.clone(),
679 channel_features: $chan_features.clone(),
680 fee_msat: 0, // This value will be later filled with hop_use_fee_msat of the following channel
681 cltv_expiry_delta: $directional_info.cltv_expiry_delta as u32,
683 old_entry.channel_fees = $directional_info.fees;
684 // It's probably fine to replace the old entry, because the new one
685 // passed the htlc_minimum-related checks above.
686 old_entry.htlc_minimum_msat = $directional_info.htlc_minimum_msat;
694 // Find ways (channels with destination) to reach a given node and store them
695 // in the corresponding data structures (routing graph etc).
696 // $fee_to_target_msat represents how much it costs to reach to this node from the payee,
697 // meaning how much will be paid in fees after this node (to the best of our knowledge).
698 // This data can later be helpful to optimize routing (pay lower fees).
699 macro_rules! add_entries_to_cheapest_to_target_node {
700 ( $node: expr, $node_id: expr, $fee_to_target_msat: expr, $next_hops_value_contribution: expr ) => {
701 if first_hops.is_some() {
702 if let Some(&(ref first_hop, ref features, ref outbound_capacity_msat)) = first_hop_targets.get(&$node_id) {
703 add_entry!(first_hop, *our_node_id, $node_id, dummy_directional_info, Some(outbound_capacity_msat / 1000), features.to_context(), $fee_to_target_msat, $next_hops_value_contribution);
708 if let Some(node_info) = $node.announcement_info.as_ref() {
709 features = node_info.features.clone();
711 features = NodeFeatures::empty();
714 if !features.requires_unknown_bits() {
715 for chan_id in $node.channels.iter() {
716 let chan = network.get_channels().get(chan_id).unwrap();
717 if !chan.features.requires_unknown_bits() {
718 if chan.node_one == *$node_id {
719 // ie $node is one, ie next hop in A* is two, via the two_to_one channel
720 if first_hops.is_none() || chan.node_two != *our_node_id {
721 if let Some(two_to_one) = chan.two_to_one.as_ref() {
722 if two_to_one.enabled {
723 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);
728 if first_hops.is_none() || chan.node_one != *our_node_id {
729 if let Some(one_to_two) = chan.one_to_two.as_ref() {
730 if one_to_two.enabled {
731 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);
743 let mut payment_paths = Vec::<PaymentPath>::new();
745 // TODO: diversify by nodes (so that all paths aren't doomed if one node is offline).
746 'paths_collection: loop {
747 // For every new path, start from scratch, except
748 // bookkeeped_channels_liquidity_available_msat, which will improve
749 // the further iterations of path finding. Also don't erase first_hop_targets.
752 hit_minimum_limit = false;
754 // If first hop is a private channel and the only way to reach the payee, this is the only
755 // place where it could be added.
756 if first_hops.is_some() {
757 if let Some(&(ref first_hop, ref features, ref outbound_capacity_msat)) = first_hop_targets.get(&payee) {
758 add_entry!(first_hop, *our_node_id, payee, dummy_directional_info, Some(outbound_capacity_msat / 1000), features.to_context(), 0, path_value_msat);
762 // Add the payee as a target, so that the payee-to-payer
763 // search algorithm knows what to start with.
764 match network.get_nodes().get(payee) {
765 // The payee is not in our network graph, so nothing to add here.
766 // There is still a chance of reaching them via last_hops though,
767 // so don't yet fail the payment here.
768 // If not, targets.pop() will not even let us enter the loop in step 2.
771 add_entries_to_cheapest_to_target_node!(node, payee, 0, path_value_msat);
776 // If a caller provided us with last hops, add them to routing targets. Since this happens
777 // earlier than general path finding, they will be somewhat prioritized, although currently
778 // it matters only if the fees are exactly the same.
779 for hop in last_hops.iter() {
780 let have_hop_src_in_graph =
781 if let Some(&(ref first_hop, ref features, ref outbound_capacity_msat)) = first_hop_targets.get(&hop.src_node_id) {
782 // If this hop connects to a node with which we have a direct channel, ignore
783 // the network graph and add both the hop and our direct channel to
784 // the candidate set.
786 // Currently there are no channel-context features defined, so we are a
787 // bit lazy here. In the future, we should pull them out via our
788 // ChannelManager, but there's no reason to waste the space until we
790 add_entry!(first_hop, *our_node_id , hop.src_node_id, dummy_directional_info, Some(outbound_capacity_msat / 1000), features.to_context(), 0, path_value_msat);
793 // In any other case, only add the hop if the source is in the regular network
795 network.get_nodes().get(&hop.src_node_id).is_some()
797 if have_hop_src_in_graph {
798 // BOLT 11 doesn't allow inclusion of features for the last hop hints, which
799 // really sucks, cause we're gonna need that eventually.
800 let last_hop_htlc_minimum_msat: u64 = match hop.htlc_minimum_msat {
801 Some(htlc_minimum_msat) => htlc_minimum_msat,
804 let directional_info = DummyDirectionalChannelInfo {
805 cltv_expiry_delta: hop.cltv_expiry_delta as u32,
806 htlc_minimum_msat: last_hop_htlc_minimum_msat,
807 htlc_maximum_msat: hop.htlc_maximum_msat,
810 add_entry!(hop.short_channel_id, hop.src_node_id, payee, directional_info, None::<u64>, ChannelFeatures::empty(), 0, path_value_msat);
814 // At this point, targets are filled with the data from first and
815 // last hops communicated by the caller, and the payment receiver.
816 let mut found_new_path = false;
819 // If this loop terminates due the exhaustion of targets, two situations are possible:
820 // - not enough outgoing liquidity:
821 // 0 < already_collected_value_msat < final_value_msat
822 // - enough outgoing liquidity:
823 // final_value_msat <= already_collected_value_msat < recommended_value_msat
824 // Both these cases (and other cases except reaching recommended_value_msat) mean that
825 // paths_collection will be stopped because found_new_path==false.
826 // This is not necessarily a routing failure.
827 'path_construction: while let Some(RouteGraphNode { pubkey, lowest_fee_to_node, value_contribution_msat, .. }) = targets.pop() {
829 // Since we're going payee-to-payer, hitting our node as a target means we should stop
830 // traversing the graph and arrange the path out of what we found.
831 if pubkey == *our_node_id {
832 let mut new_entry = dist.remove(&our_node_id).unwrap();
833 let mut ordered_hops = vec!(new_entry.clone());
836 if let Some(&(_, ref features, _)) = first_hop_targets.get(&ordered_hops.last().unwrap().route_hop.pubkey) {
837 ordered_hops.last_mut().unwrap().route_hop.node_features = features.to_context();
838 } else if let Some(node) = network.get_nodes().get(&ordered_hops.last().unwrap().route_hop.pubkey) {
839 if let Some(node_info) = node.announcement_info.as_ref() {
840 ordered_hops.last_mut().unwrap().route_hop.node_features = node_info.features.clone();
842 ordered_hops.last_mut().unwrap().route_hop.node_features = NodeFeatures::empty();
845 // We should be able to fill in features for everything except the last
846 // hop, if the last hop was provided via a BOLT 11 invoice (though we
847 // should be able to extend it further as BOLT 11 does have feature
848 // flags for the last hop node itself).
849 assert!(ordered_hops.last().unwrap().route_hop.pubkey == *payee);
852 // Means we succesfully traversed from the payer to the payee, now
853 // save this path for the payment route. Also, update the liquidity
854 // remaining on the used hops, so that we take them into account
855 // while looking for more paths.
856 if ordered_hops.last().unwrap().route_hop.pubkey == *payee {
860 new_entry = match dist.remove(&ordered_hops.last().unwrap().route_hop.pubkey) {
861 Some(payment_hop) => payment_hop,
862 // We can't arrive at None because, if we ever add an entry to targets,
863 // we also fill in the entry in dist (see add_entry!).
864 None => unreachable!(),
866 // We "propagate" the fees one hop backward (topologically) here,
867 // so that fees paid for a HTLC forwarding on the current channel are
868 // associated with the previous channel (where they will be subtracted).
869 ordered_hops.last_mut().unwrap().route_hop.fee_msat = new_entry.hop_use_fee_msat;
870 ordered_hops.last_mut().unwrap().route_hop.cltv_expiry_delta = new_entry.route_hop.cltv_expiry_delta;
871 ordered_hops.push(new_entry.clone());
873 ordered_hops.last_mut().unwrap().route_hop.fee_msat = value_contribution_msat;
874 ordered_hops.last_mut().unwrap().hop_use_fee_msat = 0;
875 ordered_hops.last_mut().unwrap().route_hop.cltv_expiry_delta = final_cltv;
877 let mut payment_path = PaymentPath {hops: ordered_hops};
879 // We could have possibly constructed a slightly inconsistent path: since we reduce
880 // value being transferred along the way, we could have violated htlc_minimum_msat
881 // on some channels we already passed (assuming dest->source direction). Here, we
882 // recompute the fees again, so that if that's the case, we match the currently
883 // underpaid htlc_minimum_msat with fees.
884 payment_path.update_value_and_recompute_fees(value_contribution_msat);
886 // Since a path allows to transfer as much value as
887 // the smallest channel it has ("bottleneck"), we should recompute
888 // the fees so sender HTLC don't overpay fees when traversing
889 // larger channels than the bottleneck. This may happen because
890 // when we were selecting those channels we were not aware how much value
891 // this path will transfer, and the relative fee for them
892 // might have been computed considering a larger value.
893 // Remember that we used these channels so that we don't rely
894 // on the same liquidity in future paths.
895 for payment_hop in payment_path.hops.iter() {
896 let channel_liquidity_available_msat = bookkeeped_channels_liquidity_available_msat.get_mut(&payment_hop.route_hop.short_channel_id).unwrap();
897 let mut spent_on_hop_msat = value_contribution_msat;
898 let next_hops_fee_msat = payment_hop.next_hops_fee_msat;
899 spent_on_hop_msat += next_hops_fee_msat;
900 if *channel_liquidity_available_msat < spent_on_hop_msat {
901 // This should not happen because we do recompute fees right before,
902 // trying to avoid cases when a hop is not usable due to the fee situation.
903 break 'path_construction;
905 *channel_liquidity_available_msat -= spent_on_hop_msat;
907 // Track the total amount all our collected paths allow to send so that we:
908 // - know when to stop looking for more paths
909 // - know which of the hops are useless considering how much more sats we need
910 // (contributes_sufficient_value)
911 already_collected_value_msat += value_contribution_msat;
913 payment_paths.push(payment_path);
914 found_new_path = true;
915 break 'path_construction;
918 // Otherwise, since the current target node is not us,
919 // keep "unrolling" the payment graph from payee to payer by
920 // finding a way to reach the current target from the payer side.
921 match network.get_nodes().get(&pubkey) {
924 add_entries_to_cheapest_to_target_node!(node, &pubkey, lowest_fee_to_node, value_contribution_msat);
930 // If we don't support MPP, no use trying to gather more value ever.
931 break 'paths_collection;
935 // Stop either when the recommended value is reached or if no new path was found in this
937 // In the latter case, making another path finding attempt won't help,
938 // because we deterministically terminated the search due to low liquidity.
939 if already_collected_value_msat >= recommended_value_msat || !found_new_path {
940 break 'paths_collection;
942 // Further, if this was our first walk of the graph, and we weren't limited by an
943 // htlc_minim_msat, return immediately because this path should suffice. If we were limited
944 // by an htlc_minimum_msat value, find another path with a higher value, potentially
945 // allowing us to pay fees to meet the htlc_minimum while still keeping a lower total fee.
946 if already_collected_value_msat == final_value_msat && payment_paths.len() == 1 {
947 if !hit_minimum_limit {
948 break 'paths_collection;
950 path_value_msat = recommended_value_msat;
955 if payment_paths.len() == 0 {
956 return Err(LightningError{err: "Failed to find a path to the given destination".to_owned(), action: ErrorAction::IgnoreError});
959 if already_collected_value_msat < final_value_msat {
960 return Err(LightningError{err: "Failed to find a sufficient route to the given destination".to_owned(), action: ErrorAction::IgnoreError});
963 // Sort by total fees and take the best paths.
964 payment_paths.sort_by_key(|path| path.get_total_fee_paid_msat());
965 if payment_paths.len() > 50 {
966 payment_paths.truncate(50);
969 // Draw multiple sufficient routes by randomly combining the selected paths.
970 let mut drawn_routes = Vec::new();
971 for i in 0..payment_paths.len() {
972 let mut cur_route = Vec::<PaymentPath>::new();
973 let mut aggregate_route_value_msat = 0;
976 // TODO: real random shuffle
977 // Currently just starts with i_th and goes up to i-1_th in a looped way.
978 let cur_payment_paths = [&payment_paths[i..], &payment_paths[..i]].concat();
981 for payment_path in cur_payment_paths {
982 cur_route.push(payment_path.clone());
983 aggregate_route_value_msat += payment_path.get_value_msat();
984 if aggregate_route_value_msat > final_value_msat {
985 // Last path likely overpaid. Substract it from the most expensive
986 // (in terms of proportional fee) path in this route and recompute fees.
987 // This might be not the most economically efficient way, but fewer paths
988 // also makes routing more reliable.
989 let mut overpaid_value_msat = aggregate_route_value_msat - final_value_msat;
991 // First, drop some expensive low-value paths entirely if possible.
992 // Sort by value so that we drop many really-low values first, since
993 // fewer paths is better: the payment is less likely to fail.
994 // TODO: this could also be optimized by also sorting by feerate_per_sat_routed,
995 // so that the sender pays less fees overall. And also htlc_minimum_msat.
996 cur_route.sort_by_key(|path| path.get_value_msat());
997 // We should make sure that at least 1 path left.
998 let mut paths_left = cur_route.len();
999 cur_route.retain(|path| {
1000 if paths_left == 1 {
1003 let mut keep = true;
1004 let path_value_msat = path.get_value_msat();
1005 if path_value_msat <= overpaid_value_msat {
1007 overpaid_value_msat -= path_value_msat;
1013 if overpaid_value_msat == 0 {
1017 assert!(cur_route.len() > 0);
1020 // Now, substract the overpaid value from the most-expensive path.
1021 // TODO: this could also be optimized by also sorting by feerate_per_sat_routed,
1022 // so that the sender pays less fees overall. And also htlc_minimum_msat.
1023 cur_route.sort_by_key(|path| { path.hops.iter().map(|hop| hop.channel_fees.proportional_millionths as u64).sum::<u64>() });
1024 let expensive_payment_path = cur_route.first_mut().unwrap();
1025 // We already dropped all the small channels above, meaning all the
1026 // remaining channels are larger than remaining overpaid_value_msat.
1027 // Thus, this can't be negative.
1028 let expensive_path_new_value_msat = expensive_payment_path.get_value_msat() - overpaid_value_msat;
1029 expensive_payment_path.update_value_and_recompute_fees(expensive_path_new_value_msat);
1033 drawn_routes.push(cur_route);
1037 // Select the best route by lowest total fee.
1038 drawn_routes.sort_by_key(|paths| paths.iter().map(|path| path.get_total_fee_paid_msat()).sum::<u64>());
1039 let mut selected_paths = Vec::<Vec<RouteHop>>::new();
1040 for payment_path in drawn_routes.first().unwrap() {
1041 selected_paths.push(payment_path.hops.iter().map(|payment_hop| payment_hop.route_hop.clone()).collect());
1044 if let Some(features) = &payee_features {
1045 for path in selected_paths.iter_mut() {
1046 path.last_mut().unwrap().node_features = features.to_context();
1050 let route = Route { paths: selected_paths };
1051 log_trace!(logger, "Got route: {}", log_route!(route));
1057 use routing::router::{get_route, RouteHint, RoutingFees};
1058 use routing::network_graph::{NetworkGraph, NetGraphMsgHandler};
1059 use ln::features::{ChannelFeatures, InitFeatures, InvoiceFeatures, NodeFeatures};
1060 use ln::msgs::{ErrorAction, LightningError, OptionalField, UnsignedChannelAnnouncement, ChannelAnnouncement, RoutingMessageHandler,
1061 NodeAnnouncement, UnsignedNodeAnnouncement, ChannelUpdate, UnsignedChannelUpdate};
1062 use ln::channelmanager;
1063 use util::test_utils;
1064 use util::ser::Writeable;
1066 use bitcoin::hashes::sha256d::Hash as Sha256dHash;
1067 use bitcoin::hashes::Hash;
1068 use bitcoin::network::constants::Network;
1069 use bitcoin::blockdata::constants::genesis_block;
1070 use bitcoin::blockdata::script::Builder;
1071 use bitcoin::blockdata::opcodes;
1072 use bitcoin::blockdata::transaction::TxOut;
1076 use bitcoin::secp256k1::key::{PublicKey,SecretKey};
1077 use bitcoin::secp256k1::{Secp256k1, All};
1081 // Using the same keys for LN and BTC ids
1082 fn add_channel(net_graph_msg_handler: &NetGraphMsgHandler<Arc<test_utils::TestChainSource>, Arc<test_utils::TestLogger>>, secp_ctx: &Secp256k1<All>, node_1_privkey: &SecretKey,
1083 node_2_privkey: &SecretKey, features: ChannelFeatures, short_channel_id: u64) {
1084 let node_id_1 = PublicKey::from_secret_key(&secp_ctx, node_1_privkey);
1085 let node_id_2 = PublicKey::from_secret_key(&secp_ctx, node_2_privkey);
1087 let unsigned_announcement = UnsignedChannelAnnouncement {
1089 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1093 bitcoin_key_1: node_id_1,
1094 bitcoin_key_2: node_id_2,
1095 excess_data: Vec::new(),
1098 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1099 let valid_announcement = ChannelAnnouncement {
1100 node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
1101 node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
1102 bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
1103 bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
1104 contents: unsigned_announcement.clone(),
1106 match net_graph_msg_handler.handle_channel_announcement(&valid_announcement) {
1107 Ok(res) => assert!(res),
1112 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) {
1113 let msghash = hash_to_message!(&Sha256dHash::hash(&update.encode()[..])[..]);
1114 let valid_channel_update = ChannelUpdate {
1115 signature: secp_ctx.sign(&msghash, node_privkey),
1116 contents: update.clone()
1119 match net_graph_msg_handler.handle_channel_update(&valid_channel_update) {
1120 Ok(res) => assert!(res),
1125 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,
1126 features: NodeFeatures, timestamp: u32) {
1127 let node_id = PublicKey::from_secret_key(&secp_ctx, node_privkey);
1128 let unsigned_announcement = UnsignedNodeAnnouncement {
1134 addresses: Vec::new(),
1135 excess_address_data: Vec::new(),
1136 excess_data: Vec::new(),
1138 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1139 let valid_announcement = NodeAnnouncement {
1140 signature: secp_ctx.sign(&msghash, node_privkey),
1141 contents: unsigned_announcement.clone()
1144 match net_graph_msg_handler.handle_node_announcement(&valid_announcement) {
1150 fn get_nodes(secp_ctx: &Secp256k1<All>) -> (SecretKey, PublicKey, Vec<SecretKey>, Vec<PublicKey>) {
1151 let privkeys: Vec<SecretKey> = (2..10).map(|i| {
1152 SecretKey::from_slice(&hex::decode(format!("{:02}", i).repeat(32)).unwrap()[..]).unwrap()
1155 let pubkeys = privkeys.iter().map(|secret| PublicKey::from_secret_key(&secp_ctx, secret)).collect();
1157 let our_privkey = SecretKey::from_slice(&hex::decode("01".repeat(32)).unwrap()[..]).unwrap();
1158 let our_id = PublicKey::from_secret_key(&secp_ctx, &our_privkey);
1160 (our_privkey, our_id, privkeys, pubkeys)
1163 fn id_to_feature_flags(id: u8) -> Vec<u8> {
1164 // Set the feature flags to the id'th odd (ie non-required) feature bit so that we can
1165 // test for it later.
1166 let idx = (id - 1) * 2 + 1;
1168 vec![1 << (idx - 8*3), 0, 0, 0]
1169 } else if idx > 8*2 {
1170 vec![1 << (idx - 8*2), 0, 0]
1171 } else if idx > 8*1 {
1172 vec![1 << (idx - 8*1), 0]
1178 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>) {
1179 let secp_ctx = Secp256k1::new();
1180 let logger = Arc::new(test_utils::TestLogger::new());
1181 let chain_monitor = Arc::new(test_utils::TestChainSource::new(Network::Testnet));
1182 let net_graph_msg_handler = NetGraphMsgHandler::new(genesis_block(Network::Testnet).header.block_hash(), None, Arc::clone(&logger));
1183 // Build network from our_id to node7:
1185 // -1(1)2- node0 -1(3)2-
1187 // our_id -1(12)2- node7 -1(13)2--- node2
1189 // -1(2)2- node1 -1(4)2-
1192 // chan1 1-to-2: disabled
1193 // chan1 2-to-1: enabled, 0 fee
1195 // chan2 1-to-2: enabled, ignored fee
1196 // chan2 2-to-1: enabled, 0 fee
1198 // chan3 1-to-2: enabled, 0 fee
1199 // chan3 2-to-1: enabled, 100 msat fee
1201 // chan4 1-to-2: enabled, 100% fee
1202 // chan4 2-to-1: enabled, 0 fee
1204 // chan12 1-to-2: enabled, ignored fee
1205 // chan12 2-to-1: enabled, 0 fee
1207 // chan13 1-to-2: enabled, 200% fee
1208 // chan13 2-to-1: enabled, 0 fee
1211 // -1(5)2- node3 -1(8)2--
1215 // node2--1(6)2- node4 -1(9)2--- node6 (not in global route map)
1217 // -1(7)2- node5 -1(10)2-
1219 // chan5 1-to-2: enabled, 100 msat fee
1220 // chan5 2-to-1: enabled, 0 fee
1222 // chan6 1-to-2: enabled, 0 fee
1223 // chan6 2-to-1: enabled, 0 fee
1225 // chan7 1-to-2: enabled, 100% fee
1226 // chan7 2-to-1: enabled, 0 fee
1228 // chan8 1-to-2: enabled, variable fee (0 then 1000 msat)
1229 // chan8 2-to-1: enabled, 0 fee
1231 // chan9 1-to-2: enabled, 1001 msat fee
1232 // chan9 2-to-1: enabled, 0 fee
1234 // chan10 1-to-2: enabled, 0 fee
1235 // chan10 2-to-1: enabled, 0 fee
1237 // chan11 1-to-2: enabled, 0 fee
1238 // chan11 2-to-1: enabled, 0 fee
1240 let (our_privkey, _, privkeys, _) = get_nodes(&secp_ctx);
1242 add_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, &privkeys[0], ChannelFeatures::from_le_bytes(id_to_feature_flags(1)), 1);
1243 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
1244 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1245 short_channel_id: 1,
1248 cltv_expiry_delta: 0,
1249 htlc_minimum_msat: 0,
1250 htlc_maximum_msat: OptionalField::Absent,
1252 fee_proportional_millionths: 0,
1253 excess_data: Vec::new()
1256 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[0], NodeFeatures::from_le_bytes(id_to_feature_flags(1)), 0);
1258 add_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, &privkeys[1], ChannelFeatures::from_le_bytes(id_to_feature_flags(2)), 2);
1259 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
1260 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1261 short_channel_id: 2,
1264 cltv_expiry_delta: u16::max_value(),
1265 htlc_minimum_msat: 0,
1266 htlc_maximum_msat: OptionalField::Absent,
1267 fee_base_msat: u32::max_value(),
1268 fee_proportional_millionths: u32::max_value(),
1269 excess_data: Vec::new()
1271 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
1272 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1273 short_channel_id: 2,
1276 cltv_expiry_delta: 0,
1277 htlc_minimum_msat: 0,
1278 htlc_maximum_msat: OptionalField::Absent,
1280 fee_proportional_millionths: 0,
1281 excess_data: Vec::new()
1284 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[1], NodeFeatures::from_le_bytes(id_to_feature_flags(2)), 0);
1286 add_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, &privkeys[7], ChannelFeatures::from_le_bytes(id_to_feature_flags(12)), 12);
1287 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
1288 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1289 short_channel_id: 12,
1292 cltv_expiry_delta: u16::max_value(),
1293 htlc_minimum_msat: 0,
1294 htlc_maximum_msat: OptionalField::Absent,
1295 fee_base_msat: u32::max_value(),
1296 fee_proportional_millionths: u32::max_value(),
1297 excess_data: Vec::new()
1299 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
1300 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1301 short_channel_id: 12,
1304 cltv_expiry_delta: 0,
1305 htlc_minimum_msat: 0,
1306 htlc_maximum_msat: OptionalField::Absent,
1308 fee_proportional_millionths: 0,
1309 excess_data: Vec::new()
1312 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[7], NodeFeatures::from_le_bytes(id_to_feature_flags(8)), 0);
1314 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], &privkeys[2], ChannelFeatures::from_le_bytes(id_to_feature_flags(3)), 3);
1315 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
1316 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1317 short_channel_id: 3,
1320 cltv_expiry_delta: (3 << 8) | 1,
1321 htlc_minimum_msat: 0,
1322 htlc_maximum_msat: OptionalField::Absent,
1324 fee_proportional_millionths: 0,
1325 excess_data: Vec::new()
1327 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
1328 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1329 short_channel_id: 3,
1332 cltv_expiry_delta: (3 << 8) | 2,
1333 htlc_minimum_msat: 0,
1334 htlc_maximum_msat: OptionalField::Absent,
1336 fee_proportional_millionths: 0,
1337 excess_data: Vec::new()
1340 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], &privkeys[2], ChannelFeatures::from_le_bytes(id_to_feature_flags(4)), 4);
1341 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
1342 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1343 short_channel_id: 4,
1346 cltv_expiry_delta: (4 << 8) | 1,
1347 htlc_minimum_msat: 0,
1348 htlc_maximum_msat: OptionalField::Absent,
1350 fee_proportional_millionths: 1000000,
1351 excess_data: Vec::new()
1353 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
1354 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1355 short_channel_id: 4,
1358 cltv_expiry_delta: (4 << 8) | 2,
1359 htlc_minimum_msat: 0,
1360 htlc_maximum_msat: OptionalField::Absent,
1362 fee_proportional_millionths: 0,
1363 excess_data: Vec::new()
1366 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], &privkeys[2], ChannelFeatures::from_le_bytes(id_to_feature_flags(13)), 13);
1367 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
1368 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1369 short_channel_id: 13,
1372 cltv_expiry_delta: (13 << 8) | 1,
1373 htlc_minimum_msat: 0,
1374 htlc_maximum_msat: OptionalField::Absent,
1376 fee_proportional_millionths: 2000000,
1377 excess_data: Vec::new()
1379 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
1380 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1381 short_channel_id: 13,
1384 cltv_expiry_delta: (13 << 8) | 2,
1385 htlc_minimum_msat: 0,
1386 htlc_maximum_msat: OptionalField::Absent,
1388 fee_proportional_millionths: 0,
1389 excess_data: Vec::new()
1392 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[2], NodeFeatures::from_le_bytes(id_to_feature_flags(3)), 0);
1394 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], &privkeys[4], ChannelFeatures::from_le_bytes(id_to_feature_flags(6)), 6);
1395 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
1396 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1397 short_channel_id: 6,
1400 cltv_expiry_delta: (6 << 8) | 1,
1401 htlc_minimum_msat: 0,
1402 htlc_maximum_msat: OptionalField::Absent,
1404 fee_proportional_millionths: 0,
1405 excess_data: Vec::new()
1407 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
1408 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1409 short_channel_id: 6,
1412 cltv_expiry_delta: (6 << 8) | 2,
1413 htlc_minimum_msat: 0,
1414 htlc_maximum_msat: OptionalField::Absent,
1416 fee_proportional_millionths: 0,
1417 excess_data: Vec::new(),
1420 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(11)), 11);
1421 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
1422 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1423 short_channel_id: 11,
1426 cltv_expiry_delta: (11 << 8) | 1,
1427 htlc_minimum_msat: 0,
1428 htlc_maximum_msat: OptionalField::Absent,
1430 fee_proportional_millionths: 0,
1431 excess_data: Vec::new()
1433 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[3], UnsignedChannelUpdate {
1434 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1435 short_channel_id: 11,
1438 cltv_expiry_delta: (11 << 8) | 2,
1439 htlc_minimum_msat: 0,
1440 htlc_maximum_msat: OptionalField::Absent,
1442 fee_proportional_millionths: 0,
1443 excess_data: Vec::new()
1446 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[4], NodeFeatures::from_le_bytes(id_to_feature_flags(5)), 0);
1448 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[3], NodeFeatures::from_le_bytes(id_to_feature_flags(4)), 0);
1450 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], &privkeys[5], ChannelFeatures::from_le_bytes(id_to_feature_flags(7)), 7);
1451 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
1452 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1453 short_channel_id: 7,
1456 cltv_expiry_delta: (7 << 8) | 1,
1457 htlc_minimum_msat: 0,
1458 htlc_maximum_msat: OptionalField::Absent,
1460 fee_proportional_millionths: 1000000,
1461 excess_data: Vec::new()
1463 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[5], UnsignedChannelUpdate {
1464 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1465 short_channel_id: 7,
1468 cltv_expiry_delta: (7 << 8) | 2,
1469 htlc_minimum_msat: 0,
1470 htlc_maximum_msat: OptionalField::Absent,
1472 fee_proportional_millionths: 0,
1473 excess_data: Vec::new()
1476 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[5], NodeFeatures::from_le_bytes(id_to_feature_flags(6)), 0);
1478 (secp_ctx, net_graph_msg_handler, chain_monitor, logger)
1482 fn simple_route_test() {
1483 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
1484 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
1486 // Simple route to 2 via 1
1488 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)) {
1489 assert_eq!(err, "Cannot send a payment of 0 msat");
1490 } else { panic!(); }
1492 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();
1493 assert_eq!(route.paths[0].len(), 2);
1495 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
1496 assert_eq!(route.paths[0][0].short_channel_id, 2);
1497 assert_eq!(route.paths[0][0].fee_msat, 100);
1498 assert_eq!(route.paths[0][0].cltv_expiry_delta, (4 << 8) | 1);
1499 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
1500 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
1502 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
1503 assert_eq!(route.paths[0][1].short_channel_id, 4);
1504 assert_eq!(route.paths[0][1].fee_msat, 100);
1505 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
1506 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
1507 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
1511 fn invalid_first_hop_test() {
1512 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
1513 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
1515 // Simple route to 2 via 1
1517 let our_chans = vec![channelmanager::ChannelDetails {
1518 channel_id: [0; 32],
1519 short_channel_id: Some(2),
1520 remote_network_id: our_id,
1521 counterparty_features: InitFeatures::from_le_bytes(vec![0b11]),
1522 channel_value_satoshis: 100000,
1524 outbound_capacity_msat: 100000,
1525 inbound_capacity_msat: 100000,
1527 counterparty_forwarding_info: None,
1530 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)) {
1531 assert_eq!(err, "First hop cannot have our_node_id as a destination.");
1532 } else { panic!(); }
1534 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();
1535 assert_eq!(route.paths[0].len(), 2);
1539 fn htlc_minimum_test() {
1540 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
1541 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
1543 // Simple route to 2 via 1
1545 // Disable other paths
1546 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
1547 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1548 short_channel_id: 12,
1550 flags: 2, // to disable
1551 cltv_expiry_delta: 0,
1552 htlc_minimum_msat: 0,
1553 htlc_maximum_msat: OptionalField::Absent,
1555 fee_proportional_millionths: 0,
1556 excess_data: Vec::new()
1558 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
1559 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1560 short_channel_id: 3,
1562 flags: 2, // to disable
1563 cltv_expiry_delta: 0,
1564 htlc_minimum_msat: 0,
1565 htlc_maximum_msat: OptionalField::Absent,
1567 fee_proportional_millionths: 0,
1568 excess_data: Vec::new()
1570 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
1571 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1572 short_channel_id: 13,
1574 flags: 2, // to disable
1575 cltv_expiry_delta: 0,
1576 htlc_minimum_msat: 0,
1577 htlc_maximum_msat: OptionalField::Absent,
1579 fee_proportional_millionths: 0,
1580 excess_data: Vec::new()
1582 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
1583 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1584 short_channel_id: 6,
1586 flags: 2, // to disable
1587 cltv_expiry_delta: 0,
1588 htlc_minimum_msat: 0,
1589 htlc_maximum_msat: OptionalField::Absent,
1591 fee_proportional_millionths: 0,
1592 excess_data: Vec::new()
1594 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
1595 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1596 short_channel_id: 7,
1598 flags: 2, // to disable
1599 cltv_expiry_delta: 0,
1600 htlc_minimum_msat: 0,
1601 htlc_maximum_msat: OptionalField::Absent,
1603 fee_proportional_millionths: 0,
1604 excess_data: Vec::new()
1607 // Check against amount_to_transfer_over_msat.
1608 // Set minimal HTLC of 200_000_000 msat.
1609 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
1610 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1611 short_channel_id: 2,
1614 cltv_expiry_delta: 0,
1615 htlc_minimum_msat: 200_000_000,
1616 htlc_maximum_msat: OptionalField::Absent,
1618 fee_proportional_millionths: 0,
1619 excess_data: Vec::new()
1622 // Second hop only allows to forward 199_999_999 at most, thus not allowing the first hop to
1624 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
1625 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1626 short_channel_id: 4,
1629 cltv_expiry_delta: 0,
1630 htlc_minimum_msat: 0,
1631 htlc_maximum_msat: OptionalField::Present(199_999_999),
1633 fee_proportional_millionths: 0,
1634 excess_data: Vec::new()
1637 // Not possible to send 199_999_999, because the minimum on channel=2 is 200_000_000.
1638 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)) {
1639 assert_eq!(err, "Failed to find a path to the given destination");
1640 } else { panic!(); }
1642 // Lift the restriction on the first hop.
1643 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
1644 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1645 short_channel_id: 2,
1648 cltv_expiry_delta: 0,
1649 htlc_minimum_msat: 0,
1650 htlc_maximum_msat: OptionalField::Absent,
1652 fee_proportional_millionths: 0,
1653 excess_data: Vec::new()
1656 // A payment above the minimum should pass
1657 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();
1658 assert_eq!(route.paths[0].len(), 2);
1662 fn htlc_minimum_overpay_test() {
1663 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
1664 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
1666 // A route to node#2 via two paths.
1667 // One path allows transferring 35-40 sats, another one also allows 35-40 sats.
1668 // Thus, they can't send 60 without overpaying.
1669 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
1670 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1671 short_channel_id: 2,
1674 cltv_expiry_delta: 0,
1675 htlc_minimum_msat: 35_000,
1676 htlc_maximum_msat: OptionalField::Present(40_000),
1678 fee_proportional_millionths: 0,
1679 excess_data: Vec::new()
1681 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
1682 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1683 short_channel_id: 12,
1686 cltv_expiry_delta: 0,
1687 htlc_minimum_msat: 35_000,
1688 htlc_maximum_msat: OptionalField::Present(40_000),
1690 fee_proportional_millionths: 0,
1691 excess_data: Vec::new()
1695 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
1696 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1697 short_channel_id: 13,
1700 cltv_expiry_delta: 0,
1701 htlc_minimum_msat: 0,
1702 htlc_maximum_msat: OptionalField::Absent,
1704 fee_proportional_millionths: 0,
1705 excess_data: Vec::new()
1707 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
1708 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1709 short_channel_id: 4,
1712 cltv_expiry_delta: 0,
1713 htlc_minimum_msat: 0,
1714 htlc_maximum_msat: OptionalField::Absent,
1716 fee_proportional_millionths: 0,
1717 excess_data: Vec::new()
1720 // Disable other paths
1721 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
1722 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1723 short_channel_id: 1,
1725 flags: 2, // to disable
1726 cltv_expiry_delta: 0,
1727 htlc_minimum_msat: 0,
1728 htlc_maximum_msat: OptionalField::Absent,
1730 fee_proportional_millionths: 0,
1731 excess_data: Vec::new()
1734 let route = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2],
1735 Some(InvoiceFeatures::known()), None, &Vec::new(), 60_000, 42, Arc::clone(&logger)).unwrap();
1736 // Overpay fees to hit htlc_minimum_msat.
1737 let overpaid_fees = route.paths[0][0].fee_msat + route.paths[1][0].fee_msat;
1738 // TODO: this could be better balanced to overpay 10k and not 15k.
1739 assert_eq!(overpaid_fees, 15_000);
1741 // Now, test that if there are 2 paths, a "cheaper" by fee path wouldn't be prioritized
1742 // while taking even more fee to match htlc_minimum_msat.
1743 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
1744 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1745 short_channel_id: 12,
1748 cltv_expiry_delta: 0,
1749 htlc_minimum_msat: 65_000,
1750 htlc_maximum_msat: OptionalField::Present(80_000),
1752 fee_proportional_millionths: 0,
1753 excess_data: Vec::new()
1755 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
1756 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1757 short_channel_id: 2,
1760 cltv_expiry_delta: 0,
1761 htlc_minimum_msat: 0,
1762 htlc_maximum_msat: OptionalField::Absent,
1764 fee_proportional_millionths: 0,
1765 excess_data: Vec::new()
1767 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
1768 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1769 short_channel_id: 4,
1772 cltv_expiry_delta: 0,
1773 htlc_minimum_msat: 0,
1774 htlc_maximum_msat: OptionalField::Absent,
1776 fee_proportional_millionths: 100_000,
1777 excess_data: Vec::new()
1780 let route = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2],
1781 Some(InvoiceFeatures::known()), None, &Vec::new(), 60_000, 42, Arc::clone(&logger)).unwrap();
1782 // Fine to overpay for htlc_minimum_msat if it allows us to save fee.
1783 assert_eq!(route.paths.len(), 1);
1784 assert_eq!(route.paths[0][0].short_channel_id, 12);
1785 let fees = route.paths[0][0].fee_msat;
1786 assert_eq!(fees, 5_000);
1788 let route = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2],
1789 Some(InvoiceFeatures::known()), None, &Vec::new(), 50_000, 42, Arc::clone(&logger)).unwrap();
1790 // Not fine to overpay for htlc_minimum_msat if it requires paying more than fee on
1791 // the other channel.
1792 assert_eq!(route.paths.len(), 1);
1793 assert_eq!(route.paths[0][0].short_channel_id, 2);
1794 let fees = route.paths[0][0].fee_msat;
1795 assert_eq!(fees, 5_000);
1799 fn disable_channels_test() {
1800 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
1801 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
1803 // // Disable channels 4 and 12 by flags=2
1804 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
1805 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1806 short_channel_id: 4,
1808 flags: 2, // to disable
1809 cltv_expiry_delta: 0,
1810 htlc_minimum_msat: 0,
1811 htlc_maximum_msat: OptionalField::Absent,
1813 fee_proportional_millionths: 0,
1814 excess_data: Vec::new()
1816 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
1817 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1818 short_channel_id: 12,
1820 flags: 2, // to disable
1821 cltv_expiry_delta: 0,
1822 htlc_minimum_msat: 0,
1823 htlc_maximum_msat: OptionalField::Absent,
1825 fee_proportional_millionths: 0,
1826 excess_data: Vec::new()
1829 // If all the channels require some features we don't understand, route should fail
1830 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)) {
1831 assert_eq!(err, "Failed to find a path to the given destination");
1832 } else { panic!(); }
1834 // If we specify a channel to node7, that overrides our local channel view and that gets used
1835 let our_chans = vec![channelmanager::ChannelDetails {
1836 channel_id: [0; 32],
1837 short_channel_id: Some(42),
1838 remote_network_id: nodes[7].clone(),
1839 counterparty_features: InitFeatures::from_le_bytes(vec![0b11]),
1840 channel_value_satoshis: 0,
1842 outbound_capacity_msat: 250_000_000,
1843 inbound_capacity_msat: 0,
1845 counterparty_forwarding_info: None,
1847 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();
1848 assert_eq!(route.paths[0].len(), 2);
1850 assert_eq!(route.paths[0][0].pubkey, nodes[7]);
1851 assert_eq!(route.paths[0][0].short_channel_id, 42);
1852 assert_eq!(route.paths[0][0].fee_msat, 200);
1853 assert_eq!(route.paths[0][0].cltv_expiry_delta, (13 << 8) | 1);
1854 assert_eq!(route.paths[0][0].node_features.le_flags(), &vec![0b11]); // it should also override our view of their features
1855 assert_eq!(route.paths[0][0].channel_features.le_flags(), &Vec::<u8>::new()); // No feature flags will meet the relevant-to-channel conversion
1857 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
1858 assert_eq!(route.paths[0][1].short_channel_id, 13);
1859 assert_eq!(route.paths[0][1].fee_msat, 100);
1860 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
1861 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
1862 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(13));
1866 fn disable_node_test() {
1867 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
1868 let (_, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
1870 // Disable nodes 1, 2, and 8 by requiring unknown feature bits
1871 let mut unknown_features = NodeFeatures::known();
1872 unknown_features.set_required_unknown_bits();
1873 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[0], unknown_features.clone(), 1);
1874 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[1], unknown_features.clone(), 1);
1875 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[7], unknown_features.clone(), 1);
1877 // If all nodes require some features we don't understand, route should fail
1878 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)) {
1879 assert_eq!(err, "Failed to find a path to the given destination");
1880 } else { panic!(); }
1882 // If we specify a channel to node7, that overrides our local channel view and that gets used
1883 let our_chans = vec![channelmanager::ChannelDetails {
1884 channel_id: [0; 32],
1885 short_channel_id: Some(42),
1886 remote_network_id: nodes[7].clone(),
1887 counterparty_features: InitFeatures::from_le_bytes(vec![0b11]),
1888 channel_value_satoshis: 0,
1890 outbound_capacity_msat: 250_000_000,
1891 inbound_capacity_msat: 0,
1893 counterparty_forwarding_info: None,
1895 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();
1896 assert_eq!(route.paths[0].len(), 2);
1898 assert_eq!(route.paths[0][0].pubkey, nodes[7]);
1899 assert_eq!(route.paths[0][0].short_channel_id, 42);
1900 assert_eq!(route.paths[0][0].fee_msat, 200);
1901 assert_eq!(route.paths[0][0].cltv_expiry_delta, (13 << 8) | 1);
1902 assert_eq!(route.paths[0][0].node_features.le_flags(), &vec![0b11]); // it should also override our view of their features
1903 assert_eq!(route.paths[0][0].channel_features.le_flags(), &Vec::<u8>::new()); // No feature flags will meet the relevant-to-channel conversion
1905 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
1906 assert_eq!(route.paths[0][1].short_channel_id, 13);
1907 assert_eq!(route.paths[0][1].fee_msat, 100);
1908 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
1909 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
1910 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(13));
1912 // Note that we don't test disabling node 3 and failing to route to it, as we (somewhat
1913 // naively) assume that the user checked the feature bits on the invoice, which override
1914 // the node_announcement.
1918 fn our_chans_test() {
1919 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
1920 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
1922 // Route to 1 via 2 and 3 because our channel to 1 is disabled
1923 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();
1924 assert_eq!(route.paths[0].len(), 3);
1926 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
1927 assert_eq!(route.paths[0][0].short_channel_id, 2);
1928 assert_eq!(route.paths[0][0].fee_msat, 200);
1929 assert_eq!(route.paths[0][0].cltv_expiry_delta, (4 << 8) | 1);
1930 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
1931 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
1933 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
1934 assert_eq!(route.paths[0][1].short_channel_id, 4);
1935 assert_eq!(route.paths[0][1].fee_msat, 100);
1936 assert_eq!(route.paths[0][1].cltv_expiry_delta, (3 << 8) | 2);
1937 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
1938 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
1940 assert_eq!(route.paths[0][2].pubkey, nodes[0]);
1941 assert_eq!(route.paths[0][2].short_channel_id, 3);
1942 assert_eq!(route.paths[0][2].fee_msat, 100);
1943 assert_eq!(route.paths[0][2].cltv_expiry_delta, 42);
1944 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(1));
1945 assert_eq!(route.paths[0][2].channel_features.le_flags(), &id_to_feature_flags(3));
1947 // If we specify a channel to node7, that overrides our local channel view and that gets used
1948 let our_chans = vec![channelmanager::ChannelDetails {
1949 channel_id: [0; 32],
1950 short_channel_id: Some(42),
1951 remote_network_id: nodes[7].clone(),
1952 counterparty_features: InitFeatures::from_le_bytes(vec![0b11]),
1953 channel_value_satoshis: 0,
1955 outbound_capacity_msat: 250_000_000,
1956 inbound_capacity_msat: 0,
1958 counterparty_forwarding_info: None,
1960 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();
1961 assert_eq!(route.paths[0].len(), 2);
1963 assert_eq!(route.paths[0][0].pubkey, nodes[7]);
1964 assert_eq!(route.paths[0][0].short_channel_id, 42);
1965 assert_eq!(route.paths[0][0].fee_msat, 200);
1966 assert_eq!(route.paths[0][0].cltv_expiry_delta, (13 << 8) | 1);
1967 assert_eq!(route.paths[0][0].node_features.le_flags(), &vec![0b11]);
1968 assert_eq!(route.paths[0][0].channel_features.le_flags(), &Vec::<u8>::new()); // No feature flags will meet the relevant-to-channel conversion
1970 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
1971 assert_eq!(route.paths[0][1].short_channel_id, 13);
1972 assert_eq!(route.paths[0][1].fee_msat, 100);
1973 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
1974 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
1975 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(13));
1978 fn last_hops(nodes: &Vec<PublicKey>) -> Vec<RouteHint> {
1979 let zero_fees = RoutingFees {
1981 proportional_millionths: 0,
1984 src_node_id: nodes[3].clone(),
1985 short_channel_id: 8,
1987 cltv_expiry_delta: (8 << 8) | 1,
1988 htlc_minimum_msat: None,
1989 htlc_maximum_msat: None,
1991 src_node_id: nodes[4].clone(),
1992 short_channel_id: 9,
1995 proportional_millionths: 0,
1997 cltv_expiry_delta: (9 << 8) | 1,
1998 htlc_minimum_msat: None,
1999 htlc_maximum_msat: None,
2001 src_node_id: nodes[5].clone(),
2002 short_channel_id: 10,
2004 cltv_expiry_delta: (10 << 8) | 1,
2005 htlc_minimum_msat: None,
2006 htlc_maximum_msat: None,
2011 fn last_hops_test() {
2012 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
2013 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
2015 // Simple test across 2, 3, 5, and 4 via a last_hop channel
2017 // First check that lst hop can't have its source as the payee.
2018 let invalid_last_hop = RouteHint {
2019 src_node_id: nodes[6],
2020 short_channel_id: 8,
2023 proportional_millionths: 0,
2025 cltv_expiry_delta: (8 << 8) | 1,
2026 htlc_minimum_msat: None,
2027 htlc_maximum_msat: None,
2030 let mut invalid_last_hops = last_hops(&nodes);
2031 invalid_last_hops.push(invalid_last_hop);
2033 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)) {
2034 assert_eq!(err, "Last hop cannot have a payee as a source.");
2035 } else { panic!(); }
2038 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();
2039 assert_eq!(route.paths[0].len(), 5);
2041 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
2042 assert_eq!(route.paths[0][0].short_channel_id, 2);
2043 assert_eq!(route.paths[0][0].fee_msat, 100);
2044 assert_eq!(route.paths[0][0].cltv_expiry_delta, (4 << 8) | 1);
2045 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
2046 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
2048 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2049 assert_eq!(route.paths[0][1].short_channel_id, 4);
2050 assert_eq!(route.paths[0][1].fee_msat, 0);
2051 assert_eq!(route.paths[0][1].cltv_expiry_delta, (6 << 8) | 1);
2052 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2053 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
2055 assert_eq!(route.paths[0][2].pubkey, nodes[4]);
2056 assert_eq!(route.paths[0][2].short_channel_id, 6);
2057 assert_eq!(route.paths[0][2].fee_msat, 0);
2058 assert_eq!(route.paths[0][2].cltv_expiry_delta, (11 << 8) | 1);
2059 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(5));
2060 assert_eq!(route.paths[0][2].channel_features.le_flags(), &id_to_feature_flags(6));
2062 assert_eq!(route.paths[0][3].pubkey, nodes[3]);
2063 assert_eq!(route.paths[0][3].short_channel_id, 11);
2064 assert_eq!(route.paths[0][3].fee_msat, 0);
2065 assert_eq!(route.paths[0][3].cltv_expiry_delta, (8 << 8) | 1);
2066 // If we have a peer in the node map, we'll use their features here since we don't have
2067 // a way of figuring out their features from the invoice:
2068 assert_eq!(route.paths[0][3].node_features.le_flags(), &id_to_feature_flags(4));
2069 assert_eq!(route.paths[0][3].channel_features.le_flags(), &id_to_feature_flags(11));
2071 assert_eq!(route.paths[0][4].pubkey, nodes[6]);
2072 assert_eq!(route.paths[0][4].short_channel_id, 8);
2073 assert_eq!(route.paths[0][4].fee_msat, 100);
2074 assert_eq!(route.paths[0][4].cltv_expiry_delta, 42);
2075 assert_eq!(route.paths[0][4].node_features.le_flags(), &Vec::<u8>::new()); // We dont pass flags in from invoices yet
2076 assert_eq!(route.paths[0][4].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
2080 fn our_chans_last_hop_connect_test() {
2081 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
2082 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
2084 // Simple test with outbound channel to 4 to test that last_hops and first_hops connect
2085 let our_chans = vec![channelmanager::ChannelDetails {
2086 channel_id: [0; 32],
2087 short_channel_id: Some(42),
2088 remote_network_id: nodes[3].clone(),
2089 counterparty_features: InitFeatures::from_le_bytes(vec![0b11]),
2090 channel_value_satoshis: 0,
2092 outbound_capacity_msat: 250_000_000,
2093 inbound_capacity_msat: 0,
2095 counterparty_forwarding_info: None,
2097 let mut last_hops = last_hops(&nodes);
2098 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();
2099 assert_eq!(route.paths[0].len(), 2);
2101 assert_eq!(route.paths[0][0].pubkey, nodes[3]);
2102 assert_eq!(route.paths[0][0].short_channel_id, 42);
2103 assert_eq!(route.paths[0][0].fee_msat, 0);
2104 assert_eq!(route.paths[0][0].cltv_expiry_delta, (8 << 8) | 1);
2105 assert_eq!(route.paths[0][0].node_features.le_flags(), &vec![0b11]);
2106 assert_eq!(route.paths[0][0].channel_features.le_flags(), &Vec::<u8>::new()); // No feature flags will meet the relevant-to-channel conversion
2108 assert_eq!(route.paths[0][1].pubkey, nodes[6]);
2109 assert_eq!(route.paths[0][1].short_channel_id, 8);
2110 assert_eq!(route.paths[0][1].fee_msat, 100);
2111 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
2112 assert_eq!(route.paths[0][1].node_features.le_flags(), &Vec::<u8>::new()); // We dont pass flags in from invoices yet
2113 assert_eq!(route.paths[0][1].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
2115 last_hops[0].fees.base_msat = 1000;
2117 // Revert to via 6 as the fee on 8 goes up
2118 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();
2119 assert_eq!(route.paths[0].len(), 4);
2121 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
2122 assert_eq!(route.paths[0][0].short_channel_id, 2);
2123 assert_eq!(route.paths[0][0].fee_msat, 200); // fee increased as its % of value transferred across node
2124 assert_eq!(route.paths[0][0].cltv_expiry_delta, (4 << 8) | 1);
2125 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
2126 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
2128 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2129 assert_eq!(route.paths[0][1].short_channel_id, 4);
2130 assert_eq!(route.paths[0][1].fee_msat, 100);
2131 assert_eq!(route.paths[0][1].cltv_expiry_delta, (7 << 8) | 1);
2132 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2133 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
2135 assert_eq!(route.paths[0][2].pubkey, nodes[5]);
2136 assert_eq!(route.paths[0][2].short_channel_id, 7);
2137 assert_eq!(route.paths[0][2].fee_msat, 0);
2138 assert_eq!(route.paths[0][2].cltv_expiry_delta, (10 << 8) | 1);
2139 // If we have a peer in the node map, we'll use their features here since we don't have
2140 // a way of figuring out their features from the invoice:
2141 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(6));
2142 assert_eq!(route.paths[0][2].channel_features.le_flags(), &id_to_feature_flags(7));
2144 assert_eq!(route.paths[0][3].pubkey, nodes[6]);
2145 assert_eq!(route.paths[0][3].short_channel_id, 10);
2146 assert_eq!(route.paths[0][3].fee_msat, 100);
2147 assert_eq!(route.paths[0][3].cltv_expiry_delta, 42);
2148 assert_eq!(route.paths[0][3].node_features.le_flags(), &Vec::<u8>::new()); // We dont pass flags in from invoices yet
2149 assert_eq!(route.paths[0][3].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
2151 // ...but still use 8 for larger payments as 6 has a variable feerate
2152 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();
2153 assert_eq!(route.paths[0].len(), 5);
2155 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
2156 assert_eq!(route.paths[0][0].short_channel_id, 2);
2157 assert_eq!(route.paths[0][0].fee_msat, 3000);
2158 assert_eq!(route.paths[0][0].cltv_expiry_delta, (4 << 8) | 1);
2159 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
2160 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
2162 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2163 assert_eq!(route.paths[0][1].short_channel_id, 4);
2164 assert_eq!(route.paths[0][1].fee_msat, 0);
2165 assert_eq!(route.paths[0][1].cltv_expiry_delta, (6 << 8) | 1);
2166 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2167 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
2169 assert_eq!(route.paths[0][2].pubkey, nodes[4]);
2170 assert_eq!(route.paths[0][2].short_channel_id, 6);
2171 assert_eq!(route.paths[0][2].fee_msat, 0);
2172 assert_eq!(route.paths[0][2].cltv_expiry_delta, (11 << 8) | 1);
2173 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(5));
2174 assert_eq!(route.paths[0][2].channel_features.le_flags(), &id_to_feature_flags(6));
2176 assert_eq!(route.paths[0][3].pubkey, nodes[3]);
2177 assert_eq!(route.paths[0][3].short_channel_id, 11);
2178 assert_eq!(route.paths[0][3].fee_msat, 1000);
2179 assert_eq!(route.paths[0][3].cltv_expiry_delta, (8 << 8) | 1);
2180 // If we have a peer in the node map, we'll use their features here since we don't have
2181 // a way of figuring out their features from the invoice:
2182 assert_eq!(route.paths[0][3].node_features.le_flags(), &id_to_feature_flags(4));
2183 assert_eq!(route.paths[0][3].channel_features.le_flags(), &id_to_feature_flags(11));
2185 assert_eq!(route.paths[0][4].pubkey, nodes[6]);
2186 assert_eq!(route.paths[0][4].short_channel_id, 8);
2187 assert_eq!(route.paths[0][4].fee_msat, 2000);
2188 assert_eq!(route.paths[0][4].cltv_expiry_delta, 42);
2189 assert_eq!(route.paths[0][4].node_features.le_flags(), &Vec::<u8>::new()); // We dont pass flags in from invoices yet
2190 assert_eq!(route.paths[0][4].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
2194 fn unannounced_path_test() {
2195 // We should be able to send a payment to a destination without any help of a routing graph
2196 // if we have a channel with a common counterparty that appears in the first and last hop
2198 let source_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&hex::decode(format!("{:02}", 41).repeat(32)).unwrap()[..]).unwrap());
2199 let middle_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&hex::decode(format!("{:02}", 42).repeat(32)).unwrap()[..]).unwrap());
2200 let target_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&hex::decode(format!("{:02}", 43).repeat(32)).unwrap()[..]).unwrap());
2202 // If we specify a channel to a middle hop, that overrides our local channel view and that gets used
2203 let last_hops = vec![RouteHint {
2204 src_node_id: middle_node_id,
2205 short_channel_id: 8,
2208 proportional_millionths: 0,
2210 cltv_expiry_delta: (8 << 8) | 1,
2211 htlc_minimum_msat: None,
2212 htlc_maximum_msat: None,
2214 let our_chans = vec![channelmanager::ChannelDetails {
2215 channel_id: [0; 32],
2216 short_channel_id: Some(42),
2217 remote_network_id: middle_node_id,
2218 counterparty_features: InitFeatures::from_le_bytes(vec![0b11]),
2219 channel_value_satoshis: 100000,
2221 outbound_capacity_msat: 100000,
2222 inbound_capacity_msat: 100000,
2224 counterparty_forwarding_info: None,
2226 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();
2228 assert_eq!(route.paths[0].len(), 2);
2230 assert_eq!(route.paths[0][0].pubkey, middle_node_id);
2231 assert_eq!(route.paths[0][0].short_channel_id, 42);
2232 assert_eq!(route.paths[0][0].fee_msat, 1000);
2233 assert_eq!(route.paths[0][0].cltv_expiry_delta, (8 << 8) | 1);
2234 assert_eq!(route.paths[0][0].node_features.le_flags(), &[0b11]);
2235 assert_eq!(route.paths[0][0].channel_features.le_flags(), &[0; 0]); // We can't learn any flags from invoices, sadly
2237 assert_eq!(route.paths[0][1].pubkey, target_node_id);
2238 assert_eq!(route.paths[0][1].short_channel_id, 8);
2239 assert_eq!(route.paths[0][1].fee_msat, 100);
2240 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
2241 assert_eq!(route.paths[0][1].node_features.le_flags(), &[0; 0]); // We dont pass flags in from invoices yet
2242 assert_eq!(route.paths[0][1].channel_features.le_flags(), &[0; 0]); // We can't learn any flags from invoices, sadly
2246 fn available_amount_while_routing_test() {
2247 // Tests whether we choose the correct available channel amount while routing.
2249 let (secp_ctx, mut net_graph_msg_handler, chain_monitor, logger) = build_graph();
2250 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
2252 // We will use a simple single-path route from
2253 // our node to node2 via node0: channels {1, 3}.
2255 // First disable all other paths.
2256 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2257 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2258 short_channel_id: 2,
2261 cltv_expiry_delta: 0,
2262 htlc_minimum_msat: 0,
2263 htlc_maximum_msat: OptionalField::Present(100_000),
2265 fee_proportional_millionths: 0,
2266 excess_data: Vec::new()
2268 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2269 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2270 short_channel_id: 12,
2273 cltv_expiry_delta: 0,
2274 htlc_minimum_msat: 0,
2275 htlc_maximum_msat: OptionalField::Present(100_000),
2277 fee_proportional_millionths: 0,
2278 excess_data: Vec::new()
2281 // Make the first channel (#1) very permissive,
2282 // and we will be testing all limits on the second channel.
2283 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2284 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2285 short_channel_id: 1,
2288 cltv_expiry_delta: 0,
2289 htlc_minimum_msat: 0,
2290 htlc_maximum_msat: OptionalField::Present(1_000_000_000),
2292 fee_proportional_millionths: 0,
2293 excess_data: Vec::new()
2296 // First, let's see if routing works if we have absolutely no idea about the available amount.
2297 // In this case, it should be set to 250_000 sats.
2298 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
2299 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2300 short_channel_id: 3,
2303 cltv_expiry_delta: 0,
2304 htlc_minimum_msat: 0,
2305 htlc_maximum_msat: OptionalField::Absent,
2307 fee_proportional_millionths: 0,
2308 excess_data: Vec::new()
2312 // Attempt to route more than available results in a failure.
2313 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2],
2314 Some(InvoiceFeatures::known()), None, &Vec::new(), 250_000_001, 42, Arc::clone(&logger)) {
2315 assert_eq!(err, "Failed to find a sufficient route to the given destination");
2316 } else { panic!(); }
2320 // Now, attempt to route an exact amount we have should be fine.
2321 let route = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2],
2322 Some(InvoiceFeatures::known()), None, &Vec::new(), 250_000_000, 42, Arc::clone(&logger)).unwrap();
2323 assert_eq!(route.paths.len(), 1);
2324 let path = route.paths.last().unwrap();
2325 assert_eq!(path.len(), 2);
2326 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
2327 assert_eq!(path.last().unwrap().fee_msat, 250_000_000);
2330 // Check that setting outbound_capacity_msat in first_hops limits the channels.
2331 // Disable channel #1 and use another first hop.
2332 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2333 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2334 short_channel_id: 1,
2337 cltv_expiry_delta: 0,
2338 htlc_minimum_msat: 0,
2339 htlc_maximum_msat: OptionalField::Present(1_000_000_000),
2341 fee_proportional_millionths: 0,
2342 excess_data: Vec::new()
2345 // Now, limit the first_hop by the outbound_capacity_msat of 200_000 sats.
2346 let our_chans = vec![channelmanager::ChannelDetails {
2347 channel_id: [0; 32],
2348 short_channel_id: Some(42),
2349 remote_network_id: nodes[0].clone(),
2350 counterparty_features: InitFeatures::from_le_bytes(vec![0b11]),
2351 channel_value_satoshis: 0,
2353 outbound_capacity_msat: 200_000_000,
2354 inbound_capacity_msat: 0,
2356 counterparty_forwarding_info: None,
2360 // Attempt to route more than available results in a failure.
2361 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2],
2362 Some(InvoiceFeatures::known()), Some(&our_chans.iter().collect::<Vec<_>>()), &Vec::new(), 200_000_001, 42, Arc::clone(&logger)) {
2363 assert_eq!(err, "Failed to find a sufficient route to the given destination");
2364 } else { panic!(); }
2368 // Now, attempt to route an exact amount we have should be fine.
2369 let route = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2],
2370 Some(InvoiceFeatures::known()), Some(&our_chans.iter().collect::<Vec<_>>()), &Vec::new(), 200_000_000, 42, Arc::clone(&logger)).unwrap();
2371 assert_eq!(route.paths.len(), 1);
2372 let path = route.paths.last().unwrap();
2373 assert_eq!(path.len(), 2);
2374 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
2375 assert_eq!(path.last().unwrap().fee_msat, 200_000_000);
2378 // Enable channel #1 back.
2379 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2380 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2381 short_channel_id: 1,
2384 cltv_expiry_delta: 0,
2385 htlc_minimum_msat: 0,
2386 htlc_maximum_msat: OptionalField::Present(1_000_000_000),
2388 fee_proportional_millionths: 0,
2389 excess_data: Vec::new()
2393 // Now let's see if routing works if we know only htlc_maximum_msat.
2394 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
2395 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2396 short_channel_id: 3,
2399 cltv_expiry_delta: 0,
2400 htlc_minimum_msat: 0,
2401 htlc_maximum_msat: OptionalField::Present(15_000),
2403 fee_proportional_millionths: 0,
2404 excess_data: Vec::new()
2408 // Attempt to route more than available results in a failure.
2409 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2],
2410 Some(InvoiceFeatures::known()), None, &Vec::new(), 15_001, 42, Arc::clone(&logger)) {
2411 assert_eq!(err, "Failed to find a sufficient route to the given destination");
2412 } else { panic!(); }
2416 // Now, attempt to route an exact amount we have should be fine.
2417 let route = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2],
2418 Some(InvoiceFeatures::known()), None, &Vec::new(), 15_000, 42, Arc::clone(&logger)).unwrap();
2419 assert_eq!(route.paths.len(), 1);
2420 let path = route.paths.last().unwrap();
2421 assert_eq!(path.len(), 2);
2422 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
2423 assert_eq!(path.last().unwrap().fee_msat, 15_000);
2426 // Now let's see if routing works if we know only capacity from the UTXO.
2428 // We can't change UTXO capacity on the fly, so we'll disable
2429 // the existing channel and add another one with the capacity we need.
2430 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
2431 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2432 short_channel_id: 3,
2435 cltv_expiry_delta: 0,
2436 htlc_minimum_msat: 0,
2437 htlc_maximum_msat: OptionalField::Absent,
2439 fee_proportional_millionths: 0,
2440 excess_data: Vec::new()
2443 let good_script = Builder::new().push_opcode(opcodes::all::OP_PUSHNUM_2)
2444 .push_slice(&PublicKey::from_secret_key(&secp_ctx, &privkeys[0]).serialize())
2445 .push_slice(&PublicKey::from_secret_key(&secp_ctx, &privkeys[2]).serialize())
2446 .push_opcode(opcodes::all::OP_PUSHNUM_2)
2447 .push_opcode(opcodes::all::OP_CHECKMULTISIG).into_script().to_v0_p2wsh();
2449 *chain_monitor.utxo_ret.lock().unwrap() = Ok(TxOut { value: 15, script_pubkey: good_script.clone() });
2450 net_graph_msg_handler.add_chain_access(Some(chain_monitor));
2452 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], &privkeys[2], ChannelFeatures::from_le_bytes(id_to_feature_flags(3)), 333);
2453 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
2454 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2455 short_channel_id: 333,
2458 cltv_expiry_delta: (3 << 8) | 1,
2459 htlc_minimum_msat: 0,
2460 htlc_maximum_msat: OptionalField::Absent,
2462 fee_proportional_millionths: 0,
2463 excess_data: Vec::new()
2465 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
2466 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2467 short_channel_id: 333,
2470 cltv_expiry_delta: (3 << 8) | 2,
2471 htlc_minimum_msat: 0,
2472 htlc_maximum_msat: OptionalField::Absent,
2474 fee_proportional_millionths: 0,
2475 excess_data: Vec::new()
2479 // Attempt to route more than available results in a failure.
2480 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2],
2481 Some(InvoiceFeatures::known()), None, &Vec::new(), 15_001, 42, Arc::clone(&logger)) {
2482 assert_eq!(err, "Failed to find a sufficient route to the given destination");
2483 } else { panic!(); }
2487 // Now, attempt to route an exact amount we have should be fine.
2488 let route = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2],
2489 Some(InvoiceFeatures::known()), None, &Vec::new(), 15_000, 42, Arc::clone(&logger)).unwrap();
2490 assert_eq!(route.paths.len(), 1);
2491 let path = route.paths.last().unwrap();
2492 assert_eq!(path.len(), 2);
2493 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
2494 assert_eq!(path.last().unwrap().fee_msat, 15_000);
2497 // Now let's see if routing chooses htlc_maximum_msat over UTXO capacity.
2498 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
2499 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2500 short_channel_id: 333,
2503 cltv_expiry_delta: 0,
2504 htlc_minimum_msat: 0,
2505 htlc_maximum_msat: OptionalField::Present(10_000),
2507 fee_proportional_millionths: 0,
2508 excess_data: Vec::new()
2512 // Attempt to route more than available results in a failure.
2513 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2],
2514 Some(InvoiceFeatures::known()), None, &Vec::new(), 10_001, 42, Arc::clone(&logger)) {
2515 assert_eq!(err, "Failed to find a sufficient route to the given destination");
2516 } else { panic!(); }
2520 // Now, attempt to route an exact amount we have should be fine.
2521 let route = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2],
2522 Some(InvoiceFeatures::known()), None, &Vec::new(), 10_000, 42, Arc::clone(&logger)).unwrap();
2523 assert_eq!(route.paths.len(), 1);
2524 let path = route.paths.last().unwrap();
2525 assert_eq!(path.len(), 2);
2526 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
2527 assert_eq!(path.last().unwrap().fee_msat, 10_000);
2532 fn available_liquidity_last_hop_test() {
2533 // Check that available liquidity properly limits the path even when only
2534 // one of the latter hops is limited.
2535 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
2536 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
2538 // Path via {node7, node2, node4} is channels {12, 13, 6, 11}.
2539 // {12, 13, 11} have the capacities of 100, {6} has a capacity of 50.
2540 // Total capacity: 50 sats.
2542 // Disable other potential paths.
2543 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2544 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2545 short_channel_id: 2,
2548 cltv_expiry_delta: 0,
2549 htlc_minimum_msat: 0,
2550 htlc_maximum_msat: OptionalField::Present(100_000),
2552 fee_proportional_millionths: 0,
2553 excess_data: Vec::new()
2555 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
2556 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2557 short_channel_id: 7,
2560 cltv_expiry_delta: 0,
2561 htlc_minimum_msat: 0,
2562 htlc_maximum_msat: OptionalField::Present(100_000),
2564 fee_proportional_millionths: 0,
2565 excess_data: Vec::new()
2570 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2571 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2572 short_channel_id: 12,
2575 cltv_expiry_delta: 0,
2576 htlc_minimum_msat: 0,
2577 htlc_maximum_msat: OptionalField::Present(100_000),
2579 fee_proportional_millionths: 0,
2580 excess_data: Vec::new()
2582 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
2583 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2584 short_channel_id: 13,
2587 cltv_expiry_delta: 0,
2588 htlc_minimum_msat: 0,
2589 htlc_maximum_msat: OptionalField::Present(100_000),
2591 fee_proportional_millionths: 0,
2592 excess_data: Vec::new()
2595 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
2596 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2597 short_channel_id: 6,
2600 cltv_expiry_delta: 0,
2601 htlc_minimum_msat: 0,
2602 htlc_maximum_msat: OptionalField::Present(50_000),
2604 fee_proportional_millionths: 0,
2605 excess_data: Vec::new()
2607 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
2608 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2609 short_channel_id: 11,
2612 cltv_expiry_delta: 0,
2613 htlc_minimum_msat: 0,
2614 htlc_maximum_msat: OptionalField::Present(100_000),
2616 fee_proportional_millionths: 0,
2617 excess_data: Vec::new()
2620 // Attempt to route more than available results in a failure.
2621 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[3],
2622 Some(InvoiceFeatures::known()), None, &Vec::new(), 60_000, 42, Arc::clone(&logger)) {
2623 assert_eq!(err, "Failed to find a sufficient route to the given destination");
2624 } else { panic!(); }
2628 // Now, attempt to route 49 sats (just a bit below the capacity).
2629 let route = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[3],
2630 Some(InvoiceFeatures::known()), None, &Vec::new(), 49_000, 42, Arc::clone(&logger)).unwrap();
2631 assert_eq!(route.paths.len(), 1);
2632 let mut total_amount_paid_msat = 0;
2633 for path in &route.paths {
2634 assert_eq!(path.len(), 4);
2635 assert_eq!(path.last().unwrap().pubkey, nodes[3]);
2636 total_amount_paid_msat += path.last().unwrap().fee_msat;
2638 assert_eq!(total_amount_paid_msat, 49_000);
2642 // Attempt to route an exact amount is also fine
2643 let route = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[3],
2644 Some(InvoiceFeatures::known()), None, &Vec::new(), 50_000, 42, Arc::clone(&logger)).unwrap();
2645 assert_eq!(route.paths.len(), 1);
2646 let mut total_amount_paid_msat = 0;
2647 for path in &route.paths {
2648 assert_eq!(path.len(), 4);
2649 assert_eq!(path.last().unwrap().pubkey, nodes[3]);
2650 total_amount_paid_msat += path.last().unwrap().fee_msat;
2652 assert_eq!(total_amount_paid_msat, 50_000);
2657 fn ignore_fee_first_hop_test() {
2658 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
2659 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
2661 // Path via node0 is channels {1, 3}. Limit them to 100 and 50 sats (total limit 50).
2662 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2663 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2664 short_channel_id: 1,
2667 cltv_expiry_delta: 0,
2668 htlc_minimum_msat: 0,
2669 htlc_maximum_msat: OptionalField::Present(100_000),
2670 fee_base_msat: 1_000_000,
2671 fee_proportional_millionths: 0,
2672 excess_data: Vec::new()
2674 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
2675 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2676 short_channel_id: 3,
2679 cltv_expiry_delta: 0,
2680 htlc_minimum_msat: 0,
2681 htlc_maximum_msat: OptionalField::Present(50_000),
2683 fee_proportional_millionths: 0,
2684 excess_data: Vec::new()
2688 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();
2689 assert_eq!(route.paths.len(), 1);
2690 let mut total_amount_paid_msat = 0;
2691 for path in &route.paths {
2692 assert_eq!(path.len(), 2);
2693 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
2694 total_amount_paid_msat += path.last().unwrap().fee_msat;
2696 assert_eq!(total_amount_paid_msat, 50_000);
2701 fn simple_mpp_route_test() {
2702 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
2703 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
2705 // We need a route consisting of 3 paths:
2706 // From our node to node2 via node0, node7, node1 (three paths one hop each).
2707 // To achieve this, the amount being transferred should be around
2708 // the total capacity of these 3 paths.
2710 // First, we set limits on these (previously unlimited) channels.
2711 // Their aggregate capacity will be 50 + 60 + 180 = 290 sats.
2713 // Path via node0 is channels {1, 3}. Limit them to 100 and 50 sats (total limit 50).
2714 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2715 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2716 short_channel_id: 1,
2719 cltv_expiry_delta: 0,
2720 htlc_minimum_msat: 0,
2721 htlc_maximum_msat: OptionalField::Present(100_000),
2723 fee_proportional_millionths: 0,
2724 excess_data: Vec::new()
2726 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
2727 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2728 short_channel_id: 3,
2731 cltv_expiry_delta: 0,
2732 htlc_minimum_msat: 0,
2733 htlc_maximum_msat: OptionalField::Present(50_000),
2735 fee_proportional_millionths: 0,
2736 excess_data: Vec::new()
2739 // Path via node7 is channels {12, 13}. Limit them to 60 and 60 sats
2740 // (total limit 60).
2741 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2742 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2743 short_channel_id: 12,
2746 cltv_expiry_delta: 0,
2747 htlc_minimum_msat: 0,
2748 htlc_maximum_msat: OptionalField::Present(60_000),
2750 fee_proportional_millionths: 0,
2751 excess_data: Vec::new()
2753 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
2754 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2755 short_channel_id: 13,
2758 cltv_expiry_delta: 0,
2759 htlc_minimum_msat: 0,
2760 htlc_maximum_msat: OptionalField::Present(60_000),
2762 fee_proportional_millionths: 0,
2763 excess_data: Vec::new()
2766 // Path via node1 is channels {2, 4}. Limit them to 200 and 180 sats
2767 // (total capacity 180 sats).
2768 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2769 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2770 short_channel_id: 2,
2773 cltv_expiry_delta: 0,
2774 htlc_minimum_msat: 0,
2775 htlc_maximum_msat: OptionalField::Present(200_000),
2777 fee_proportional_millionths: 0,
2778 excess_data: Vec::new()
2780 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
2781 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2782 short_channel_id: 4,
2785 cltv_expiry_delta: 0,
2786 htlc_minimum_msat: 0,
2787 htlc_maximum_msat: OptionalField::Present(180_000),
2789 fee_proportional_millionths: 0,
2790 excess_data: Vec::new()
2794 // Attempt to route more than available results in a failure.
2795 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(),
2796 &nodes[2], Some(InvoiceFeatures::known()), None, &Vec::new(), 300_000, 42, Arc::clone(&logger)) {
2797 assert_eq!(err, "Failed to find a sufficient route to the given destination");
2798 } else { panic!(); }
2802 // Now, attempt to route 250 sats (just a bit below the capacity).
2803 // Our algorithm should provide us with these 3 paths.
2804 let route = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2],
2805 Some(InvoiceFeatures::known()), None, &Vec::new(), 250_000, 42, Arc::clone(&logger)).unwrap();
2806 assert_eq!(route.paths.len(), 3);
2807 let mut total_amount_paid_msat = 0;
2808 for path in &route.paths {
2809 assert_eq!(path.len(), 2);
2810 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
2811 total_amount_paid_msat += path.last().unwrap().fee_msat;
2813 assert_eq!(total_amount_paid_msat, 250_000);
2817 // Attempt to route an exact amount is also fine
2818 let route = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2],
2819 Some(InvoiceFeatures::known()), None, &Vec::new(), 290_000, 42, Arc::clone(&logger)).unwrap();
2820 assert_eq!(route.paths.len(), 3);
2821 let mut total_amount_paid_msat = 0;
2822 for path in &route.paths {
2823 assert_eq!(path.len(), 2);
2824 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
2825 total_amount_paid_msat += path.last().unwrap().fee_msat;
2827 assert_eq!(total_amount_paid_msat, 290_000);
2832 fn long_mpp_route_test() {
2833 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
2834 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
2836 // We need a route consisting of 3 paths:
2837 // From our node to node3 via {node0, node2}, {node7, node2, node4} and {node7, node2}.
2838 // Note that these paths overlap (channels 5, 12, 13).
2839 // We will route 300 sats.
2840 // Each path will have 100 sats capacity, those channels which
2841 // are used twice will have 200 sats capacity.
2843 // Disable other potential paths.
2844 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2845 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2846 short_channel_id: 2,
2849 cltv_expiry_delta: 0,
2850 htlc_minimum_msat: 0,
2851 htlc_maximum_msat: OptionalField::Present(100_000),
2853 fee_proportional_millionths: 0,
2854 excess_data: Vec::new()
2856 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
2857 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2858 short_channel_id: 7,
2861 cltv_expiry_delta: 0,
2862 htlc_minimum_msat: 0,
2863 htlc_maximum_msat: OptionalField::Present(100_000),
2865 fee_proportional_millionths: 0,
2866 excess_data: Vec::new()
2869 // Path via {node0, node2} is channels {1, 3, 5}.
2870 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2871 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2872 short_channel_id: 1,
2875 cltv_expiry_delta: 0,
2876 htlc_minimum_msat: 0,
2877 htlc_maximum_msat: OptionalField::Present(100_000),
2879 fee_proportional_millionths: 0,
2880 excess_data: Vec::new()
2882 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
2883 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2884 short_channel_id: 3,
2887 cltv_expiry_delta: 0,
2888 htlc_minimum_msat: 0,
2889 htlc_maximum_msat: OptionalField::Present(100_000),
2891 fee_proportional_millionths: 0,
2892 excess_data: Vec::new()
2895 // Capacity of 200 sats because this channel will be used by 3rd path as well.
2896 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(5)), 5);
2897 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
2898 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2899 short_channel_id: 5,
2902 cltv_expiry_delta: 0,
2903 htlc_minimum_msat: 0,
2904 htlc_maximum_msat: OptionalField::Present(200_000),
2906 fee_proportional_millionths: 0,
2907 excess_data: Vec::new()
2910 // Path via {node7, node2, node4} is channels {12, 13, 6, 11}.
2911 // Add 100 sats to the capacities of {12, 13}, because these channels
2912 // are also used for 3rd path. 100 sats for the rest. Total capacity: 100 sats.
2913 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2914 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2915 short_channel_id: 12,
2918 cltv_expiry_delta: 0,
2919 htlc_minimum_msat: 0,
2920 htlc_maximum_msat: OptionalField::Present(200_000),
2922 fee_proportional_millionths: 0,
2923 excess_data: Vec::new()
2925 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
2926 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2927 short_channel_id: 13,
2930 cltv_expiry_delta: 0,
2931 htlc_minimum_msat: 0,
2932 htlc_maximum_msat: OptionalField::Present(200_000),
2934 fee_proportional_millionths: 0,
2935 excess_data: Vec::new()
2938 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
2939 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2940 short_channel_id: 6,
2943 cltv_expiry_delta: 0,
2944 htlc_minimum_msat: 0,
2945 htlc_maximum_msat: OptionalField::Present(100_000),
2947 fee_proportional_millionths: 0,
2948 excess_data: Vec::new()
2950 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
2951 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2952 short_channel_id: 11,
2955 cltv_expiry_delta: 0,
2956 htlc_minimum_msat: 0,
2957 htlc_maximum_msat: OptionalField::Present(100_000),
2959 fee_proportional_millionths: 0,
2960 excess_data: Vec::new()
2963 // Path via {node7, node2} is channels {12, 13, 5}.
2964 // We already limited them to 200 sats (they are used twice for 100 sats).
2965 // Nothing to do here.
2968 // Attempt to route more than available results in a failure.
2969 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[3],
2970 Some(InvoiceFeatures::known()), None, &Vec::new(), 350_000, 42, Arc::clone(&logger)) {
2971 assert_eq!(err, "Failed to find a sufficient route to the given destination");
2972 } else { panic!(); }
2976 // Now, attempt to route 300 sats (exact amount we can route).
2977 // Our algorithm should provide us with these 3 paths, 100 sats each.
2978 let route = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[3],
2979 Some(InvoiceFeatures::known()), None, &Vec::new(), 300_000, 42, Arc::clone(&logger)).unwrap();
2980 assert_eq!(route.paths.len(), 3);
2982 let mut total_amount_paid_msat = 0;
2983 for path in &route.paths {
2984 assert_eq!(path.last().unwrap().pubkey, nodes[3]);
2985 total_amount_paid_msat += path.last().unwrap().fee_msat;
2987 assert_eq!(total_amount_paid_msat, 300_000);
2993 fn mpp_cheaper_route_test() {
2994 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
2995 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
2997 // This test checks that if we have two cheaper paths and one more expensive path,
2998 // so that liquidity-wise any 2 of 3 combination is sufficient,
2999 // two cheaper paths will be taken.
3000 // These paths have equal available liquidity.
3002 // We need a combination of 3 paths:
3003 // From our node to node3 via {node0, node2}, {node7, node2, node4} and {node7, node2}.
3004 // Note that these paths overlap (channels 5, 12, 13).
3005 // Each path will have 100 sats capacity, those channels which
3006 // are used twice will have 200 sats capacity.
3008 // Disable other potential paths.
3009 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3010 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3011 short_channel_id: 2,
3014 cltv_expiry_delta: 0,
3015 htlc_minimum_msat: 0,
3016 htlc_maximum_msat: OptionalField::Present(100_000),
3018 fee_proportional_millionths: 0,
3019 excess_data: Vec::new()
3021 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3022 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3023 short_channel_id: 7,
3026 cltv_expiry_delta: 0,
3027 htlc_minimum_msat: 0,
3028 htlc_maximum_msat: OptionalField::Present(100_000),
3030 fee_proportional_millionths: 0,
3031 excess_data: Vec::new()
3034 // Path via {node0, node2} is channels {1, 3, 5}.
3035 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3036 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3037 short_channel_id: 1,
3040 cltv_expiry_delta: 0,
3041 htlc_minimum_msat: 0,
3042 htlc_maximum_msat: OptionalField::Present(100_000),
3044 fee_proportional_millionths: 0,
3045 excess_data: Vec::new()
3047 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3048 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3049 short_channel_id: 3,
3052 cltv_expiry_delta: 0,
3053 htlc_minimum_msat: 0,
3054 htlc_maximum_msat: OptionalField::Present(100_000),
3056 fee_proportional_millionths: 0,
3057 excess_data: Vec::new()
3060 // Capacity of 200 sats because this channel will be used by 3rd path as well.
3061 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(5)), 5);
3062 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3063 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3064 short_channel_id: 5,
3067 cltv_expiry_delta: 0,
3068 htlc_minimum_msat: 0,
3069 htlc_maximum_msat: OptionalField::Present(200_000),
3071 fee_proportional_millionths: 0,
3072 excess_data: Vec::new()
3075 // Path via {node7, node2, node4} is channels {12, 13, 6, 11}.
3076 // Add 100 sats to the capacities of {12, 13}, because these channels
3077 // are also used for 3rd path. 100 sats for the rest. Total capacity: 100 sats.
3078 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3079 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3080 short_channel_id: 12,
3083 cltv_expiry_delta: 0,
3084 htlc_minimum_msat: 0,
3085 htlc_maximum_msat: OptionalField::Present(200_000),
3087 fee_proportional_millionths: 0,
3088 excess_data: Vec::new()
3090 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
3091 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3092 short_channel_id: 13,
3095 cltv_expiry_delta: 0,
3096 htlc_minimum_msat: 0,
3097 htlc_maximum_msat: OptionalField::Present(200_000),
3099 fee_proportional_millionths: 0,
3100 excess_data: Vec::new()
3103 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3104 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3105 short_channel_id: 6,
3108 cltv_expiry_delta: 0,
3109 htlc_minimum_msat: 0,
3110 htlc_maximum_msat: OptionalField::Present(100_000),
3111 fee_base_msat: 1_000,
3112 fee_proportional_millionths: 0,
3113 excess_data: Vec::new()
3115 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
3116 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3117 short_channel_id: 11,
3120 cltv_expiry_delta: 0,
3121 htlc_minimum_msat: 0,
3122 htlc_maximum_msat: OptionalField::Present(100_000),
3124 fee_proportional_millionths: 0,
3125 excess_data: Vec::new()
3128 // Path via {node7, node2} is channels {12, 13, 5}.
3129 // We already limited them to 200 sats (they are used twice for 100 sats).
3130 // Nothing to do here.
3133 // Now, attempt to route 180 sats.
3134 // Our algorithm should provide us with these 2 paths.
3135 let route = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[3],
3136 Some(InvoiceFeatures::known()), None, &Vec::new(), 180_000, 42, Arc::clone(&logger)).unwrap();
3137 assert_eq!(route.paths.len(), 2);
3139 let mut total_value_transferred_msat = 0;
3140 let mut total_paid_msat = 0;
3141 for path in &route.paths {
3142 assert_eq!(path.last().unwrap().pubkey, nodes[3]);
3143 total_value_transferred_msat += path.last().unwrap().fee_msat;
3145 total_paid_msat += hop.fee_msat;
3148 // If we paid fee, this would be higher.
3149 assert_eq!(total_value_transferred_msat, 180_000);
3150 let total_fees_paid = total_paid_msat - total_value_transferred_msat;
3151 assert_eq!(total_fees_paid, 0);
3156 fn fees_on_mpp_route_test() {
3157 // This test makes sure that MPP algorithm properly takes into account
3158 // fees charged on the channels, by making the fees impactful:
3159 // if the fee is not properly accounted for, the behavior is different.
3160 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
3161 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3163 // We need a route consisting of 2 paths:
3164 // From our node to node3 via {node0, node2} and {node7, node2, node4}.
3165 // We will route 200 sats, Each path will have 100 sats capacity.
3167 // This test is not particularly stable: e.g.,
3168 // there's a way to route via {node0, node2, node4}.
3169 // It works while pathfinding is deterministic, but can be broken otherwise.
3170 // It's fine to ignore this concern for now.
3172 // Disable other potential paths.
3173 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3174 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3175 short_channel_id: 2,
3178 cltv_expiry_delta: 0,
3179 htlc_minimum_msat: 0,
3180 htlc_maximum_msat: OptionalField::Present(100_000),
3182 fee_proportional_millionths: 0,
3183 excess_data: Vec::new()
3186 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3187 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3188 short_channel_id: 7,
3191 cltv_expiry_delta: 0,
3192 htlc_minimum_msat: 0,
3193 htlc_maximum_msat: OptionalField::Present(100_000),
3195 fee_proportional_millionths: 0,
3196 excess_data: Vec::new()
3199 // Path via {node0, node2} is channels {1, 3, 5}.
3200 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3201 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3202 short_channel_id: 1,
3205 cltv_expiry_delta: 0,
3206 htlc_minimum_msat: 0,
3207 htlc_maximum_msat: OptionalField::Present(100_000),
3209 fee_proportional_millionths: 0,
3210 excess_data: Vec::new()
3212 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3213 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3214 short_channel_id: 3,
3217 cltv_expiry_delta: 0,
3218 htlc_minimum_msat: 0,
3219 htlc_maximum_msat: OptionalField::Present(100_000),
3221 fee_proportional_millionths: 0,
3222 excess_data: Vec::new()
3225 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(5)), 5);
3226 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3227 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3228 short_channel_id: 5,
3231 cltv_expiry_delta: 0,
3232 htlc_minimum_msat: 0,
3233 htlc_maximum_msat: OptionalField::Present(100_000),
3235 fee_proportional_millionths: 0,
3236 excess_data: Vec::new()
3239 // Path via {node7, node2, node4} is channels {12, 13, 6, 11}.
3240 // All channels should be 100 sats capacity. But for the fee experiment,
3241 // we'll add absolute fee of 150 sats paid for the use channel 6 (paid to node2 on channel 13).
3242 // Since channel 12 allows to deliver only 250 sats to channel 13, channel 13 can transfer only
3243 // 100 sats (and pay 150 sats in fees for the use of channel 6),
3244 // so no matter how large are other channels,
3245 // the whole path will be limited by 100 sats with just these 2 conditions:
3246 // - channel 12 capacity is 250 sats
3247 // - fee for channel 6 is 150 sats
3248 // Let's test this by enforcing these 2 conditions and removing other limits.
3249 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3250 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3251 short_channel_id: 12,
3254 cltv_expiry_delta: 0,
3255 htlc_minimum_msat: 0,
3256 htlc_maximum_msat: OptionalField::Present(250_000),
3258 fee_proportional_millionths: 0,
3259 excess_data: Vec::new()
3261 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
3262 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3263 short_channel_id: 13,
3266 cltv_expiry_delta: 0,
3267 htlc_minimum_msat: 0,
3268 htlc_maximum_msat: OptionalField::Absent,
3270 fee_proportional_millionths: 0,
3271 excess_data: Vec::new()
3274 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3275 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3276 short_channel_id: 6,
3279 cltv_expiry_delta: 0,
3280 htlc_minimum_msat: 0,
3281 htlc_maximum_msat: OptionalField::Absent,
3282 fee_base_msat: 150_000,
3283 fee_proportional_millionths: 0,
3284 excess_data: Vec::new()
3286 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
3287 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3288 short_channel_id: 11,
3291 cltv_expiry_delta: 0,
3292 htlc_minimum_msat: 0,
3293 htlc_maximum_msat: OptionalField::Absent,
3295 fee_proportional_millionths: 0,
3296 excess_data: Vec::new()
3300 // Attempt to route more than available results in a failure.
3301 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[3],
3302 Some(InvoiceFeatures::known()), None, &Vec::new(), 210_000, 42, Arc::clone(&logger)) {
3303 assert_eq!(err, "Failed to find a sufficient route to the given destination");
3304 } else { panic!(); }
3308 // Now, attempt to route 200 sats (exact amount we can route).
3309 let route = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[3],
3310 Some(InvoiceFeatures::known()), None, &Vec::new(), 200_000, 42, Arc::clone(&logger)).unwrap();
3311 assert_eq!(route.paths.len(), 2);
3313 let mut total_amount_paid_msat = 0;
3314 for path in &route.paths {
3315 assert_eq!(path.last().unwrap().pubkey, nodes[3]);
3316 total_amount_paid_msat += path.last().unwrap().fee_msat;
3318 assert_eq!(total_amount_paid_msat, 200_000);
3324 fn drop_lowest_channel_mpp_route_test() {
3325 // This test checks that low-capacity channel is dropped when after
3326 // path finding we realize that we found more capacity than we need.
3327 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
3328 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3330 // We need a route consisting of 3 paths:
3331 // From our node to node2 via node0, node7, node1 (three paths one hop each).
3333 // The first and the second paths should be sufficient, but the third should be
3334 // cheaper, so that we select it but drop later.
3336 // First, we set limits on these (previously unlimited) channels.
3337 // Their aggregate capacity will be 50 + 60 + 20 = 130 sats.
3339 // Path via node0 is channels {1, 3}. Limit them to 100 and 50 sats (total limit 50);
3340 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3341 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3342 short_channel_id: 1,
3345 cltv_expiry_delta: 0,
3346 htlc_minimum_msat: 0,
3347 htlc_maximum_msat: OptionalField::Present(100_000),
3349 fee_proportional_millionths: 0,
3350 excess_data: Vec::new()
3352 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3353 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3354 short_channel_id: 3,
3357 cltv_expiry_delta: 0,
3358 htlc_minimum_msat: 0,
3359 htlc_maximum_msat: OptionalField::Present(50_000),
3361 fee_proportional_millionths: 0,
3362 excess_data: Vec::new()
3365 // Path via node7 is channels {12, 13}. Limit them to 60 and 60 sats (total limit 60);
3366 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3367 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3368 short_channel_id: 12,
3371 cltv_expiry_delta: 0,
3372 htlc_minimum_msat: 0,
3373 htlc_maximum_msat: OptionalField::Present(60_000),
3375 fee_proportional_millionths: 0,
3376 excess_data: Vec::new()
3378 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
3379 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3380 short_channel_id: 13,
3383 cltv_expiry_delta: 0,
3384 htlc_minimum_msat: 0,
3385 htlc_maximum_msat: OptionalField::Present(60_000),
3387 fee_proportional_millionths: 0,
3388 excess_data: Vec::new()
3391 // Path via node1 is channels {2, 4}. Limit them to 20 and 20 sats (total capacity 20 sats).
3392 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3393 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3394 short_channel_id: 2,
3397 cltv_expiry_delta: 0,
3398 htlc_minimum_msat: 0,
3399 htlc_maximum_msat: OptionalField::Present(20_000),
3401 fee_proportional_millionths: 0,
3402 excess_data: Vec::new()
3404 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
3405 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3406 short_channel_id: 4,
3409 cltv_expiry_delta: 0,
3410 htlc_minimum_msat: 0,
3411 htlc_maximum_msat: OptionalField::Present(20_000),
3413 fee_proportional_millionths: 0,
3414 excess_data: Vec::new()
3418 // Attempt to route more than available results in a failure.
3419 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2],
3420 Some(InvoiceFeatures::known()), None, &Vec::new(), 150_000, 42, Arc::clone(&logger)) {
3421 assert_eq!(err, "Failed to find a sufficient route to the given destination");
3422 } else { panic!(); }
3426 // Now, attempt to route 125 sats (just a bit below the capacity of 3 channels).
3427 // Our algorithm should provide us with these 3 paths.
3428 let route = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2],
3429 Some(InvoiceFeatures::known()), None, &Vec::new(), 125_000, 42, Arc::clone(&logger)).unwrap();
3430 assert_eq!(route.paths.len(), 3);
3431 let mut total_amount_paid_msat = 0;
3432 for path in &route.paths {
3433 assert_eq!(path.len(), 2);
3434 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
3435 total_amount_paid_msat += path.last().unwrap().fee_msat;
3437 assert_eq!(total_amount_paid_msat, 125_000);
3441 // Attempt to route without the last small cheap channel
3442 let route = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2],
3443 Some(InvoiceFeatures::known()), None, &Vec::new(), 90_000, 42, Arc::clone(&logger)).unwrap();
3444 assert_eq!(route.paths.len(), 2);
3445 let mut total_amount_paid_msat = 0;
3446 for path in &route.paths {
3447 assert_eq!(path.len(), 2);
3448 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
3449 total_amount_paid_msat += path.last().unwrap().fee_msat;
3451 assert_eq!(total_amount_paid_msat, 90_000);
3456 fn exact_fee_liquidity_limit() {
3457 // Test that if, while walking the graph, we find a hop that has exactly enough liquidity
3458 // for us, including later hop fees, we take it. In the first version of our MPP algorithm
3459 // we calculated fees on a higher value, resulting in us ignoring such paths.
3460 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
3461 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3463 // We modify the graph to set the htlc_maximum of channel 2 to below the value we wish to
3465 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3466 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3467 short_channel_id: 2,
3470 cltv_expiry_delta: 0,
3471 htlc_minimum_msat: 0,
3472 htlc_maximum_msat: OptionalField::Present(85_000),
3474 fee_proportional_millionths: 0,
3475 excess_data: Vec::new()
3478 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3479 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3480 short_channel_id: 12,
3483 cltv_expiry_delta: (4 << 8) | 1,
3484 htlc_minimum_msat: 0,
3485 htlc_maximum_msat: OptionalField::Present(270_000),
3487 fee_proportional_millionths: 1000000,
3488 excess_data: Vec::new()
3491 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3492 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3493 short_channel_id: 13,
3496 cltv_expiry_delta: (13 << 8) | 2,
3497 htlc_minimum_msat: 0,
3498 htlc_maximum_msat: OptionalField::Absent,
3500 fee_proportional_millionths: 0,
3501 excess_data: Vec::new()
3505 // Now, attempt to route 125 sats (just a bit below the capacity of 3 channels).
3506 // Our algorithm should provide us with these 3 paths.
3507 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();
3508 assert_eq!(route.paths.len(), 1);
3509 assert_eq!(route.paths[0].len(), 2);
3511 assert_eq!(route.paths[0][0].pubkey, nodes[7]);
3512 assert_eq!(route.paths[0][0].short_channel_id, 12);
3513 assert_eq!(route.paths[0][0].fee_msat, 90_000*2);
3514 assert_eq!(route.paths[0][0].cltv_expiry_delta, (13 << 8) | 1);
3515 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(8));
3516 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(12));
3518 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
3519 assert_eq!(route.paths[0][1].short_channel_id, 13);
3520 assert_eq!(route.paths[0][1].fee_msat, 90_000);
3521 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
3522 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
3523 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(13));
3528 #[cfg(all(test, feature = "unstable"))]
3531 use util::logger::{Logger, Record};
3536 struct DummyLogger {}
3537 impl Logger for DummyLogger {
3538 fn log(&self, _record: &Record) {}
3542 fn generate_routes(bench: &mut Bencher) {
3543 let mut d = File::open("net_graph-2021-02-12.bin").expect("Please fetch https://bitcoin.ninja/ldk-net_graph-879e309c128-2020-02-12.bin and place it at lightning/net_graph-2021-02-12.bin");
3544 let graph = NetworkGraph::read(&mut d).unwrap();
3546 // First, get 100 (source, destination) pairs for which route-getting actually succeeds...
3547 let mut path_endpoints = Vec::new();
3548 let mut seed: usize = 0xdeadbeef;
3549 'load_endpoints: for _ in 0..100 {
3552 let src = graph.get_nodes().keys().skip(seed % graph.get_nodes().len()).next().unwrap();
3554 let dst = graph.get_nodes().keys().skip(seed % graph.get_nodes().len()).next().unwrap();
3555 let amt = seed as u64 % 1_000_000;
3556 if get_route(src, &graph, dst, None, None, &[], amt, 42, &DummyLogger{}).is_ok() {
3557 path_endpoints.push((src, dst, amt));
3558 continue 'load_endpoints;
3563 // ...then benchmark finding paths between the nodes we learned.
3566 let (src, dst, amt) = path_endpoints[idx % path_endpoints.len()];
3567 assert!(get_route(src, &graph, dst, None, None, &[], amt, 42, &DummyLogger{}).is_ok());
3573 fn generate_mpp_routes(bench: &mut Bencher) {
3574 let mut d = File::open("net_graph-2021-02-12.bin").expect("Please fetch https://bitcoin.ninja/ldk-net_graph-879e309c128-2020-02-12.bin and place it at lightning/net_graph-2021-02-12.bin");
3575 let graph = NetworkGraph::read(&mut d).unwrap();
3577 // First, get 100 (source, destination) pairs for which route-getting actually succeeds...
3578 let mut path_endpoints = Vec::new();
3579 let mut seed: usize = 0xdeadbeef;
3580 'load_endpoints: for _ in 0..100 {
3583 let src = graph.get_nodes().keys().skip(seed % graph.get_nodes().len()).next().unwrap();
3585 let dst = graph.get_nodes().keys().skip(seed % graph.get_nodes().len()).next().unwrap();
3586 let amt = seed as u64 % 1_000_000;
3587 if get_route(src, &graph, dst, Some(InvoiceFeatures::known()), None, &[], amt, 42, &DummyLogger{}).is_ok() {
3588 path_endpoints.push((src, dst, amt));
3589 continue 'load_endpoints;
3594 // ...then benchmark finding paths between the nodes we learned.
3597 let (src, dst, amt) = path_endpoints[idx % path_endpoints.len()];
3598 assert!(get_route(src, &graph, dst, Some(InvoiceFeatures::known()), None, &[], amt, 42, &DummyLogger{}).is_ok());