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 alloc::collections::BinaryHeap;
30 #[derive(Clone, PartialEq)]
32 /// The node_id of the node at this hop.
33 pub pubkey: PublicKey,
34 /// The node_announcement features of the node at this hop. For the last hop, these may be
35 /// amended to match the features present in the invoice this node generated.
36 pub node_features: NodeFeatures,
37 /// The channel that should be used from the previous hop to reach this node.
38 pub short_channel_id: u64,
39 /// The channel_announcement features of the channel that should be used from the previous hop
40 /// to reach this node.
41 pub channel_features: ChannelFeatures,
42 /// The fee taken on this hop (for paying for the use of the *next* channel in the path).
43 /// For the last hop, this should be the full value of the payment (might be more than
44 /// requested if we had to match htlc_minimum_msat).
46 /// The CLTV delta added for this hop. For the last hop, this should be the full CLTV value
47 /// expected at the destination, in excess of the current block height.
48 pub cltv_expiry_delta: u32,
51 impl_writeable_tlv_based!(RouteHop, {
54 (4, short_channel_id),
55 (6, channel_features),
57 (10, cltv_expiry_delta),
60 /// A route directs a payment from the sender (us) to the recipient. If the recipient supports MPP,
61 /// it can take multiple paths. Each path is composed of one or more hops through the network.
62 #[derive(Clone, PartialEq)]
64 /// The list of routes taken for a single (potentially-)multi-part payment. The pubkey of the
65 /// last RouteHop in each path must be the same.
66 /// Each entry represents a list of hops, NOT INCLUDING our own, where the last hop is the
67 /// destination. Thus, this must always be at least length one. While the maximum length of any
68 /// given path is variable, keeping the length of any path to less than 20 should currently
69 /// ensure it is viable.
70 pub paths: Vec<Vec<RouteHop>>,
73 const SERIALIZATION_VERSION: u8 = 1;
74 const MIN_SERIALIZATION_VERSION: u8 = 1;
76 impl Writeable for Route {
77 fn write<W: ::util::ser::Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
78 write_ver_prefix!(writer, SERIALIZATION_VERSION, MIN_SERIALIZATION_VERSION);
79 (self.paths.len() as u64).write(writer)?;
80 for hops in self.paths.iter() {
81 (hops.len() as u8).write(writer)?;
82 for hop in hops.iter() {
86 write_tlv_fields!(writer, {}, {});
91 impl Readable for Route {
92 fn read<R: ::std::io::Read>(reader: &mut R) -> Result<Route, DecodeError> {
93 let _ver = read_ver_prefix!(reader, SERIALIZATION_VERSION);
94 let path_count: u64 = Readable::read(reader)?;
95 let mut paths = Vec::with_capacity(cmp::min(path_count, 128) as usize);
96 for _ in 0..path_count {
97 let hop_count: u8 = Readable::read(reader)?;
98 let mut hops = Vec::with_capacity(hop_count as usize);
99 for _ in 0..hop_count {
100 hops.push(Readable::read(reader)?);
104 read_tlv_fields!(reader, {}, {});
109 /// A list of hops along a payment path terminating with a channel to the recipient.
110 #[derive(Eq, PartialEq, Debug, Clone)]
111 pub struct RouteHint(pub Vec<RouteHintHop>);
113 /// A channel descriptor for a hop along a payment path.
114 #[derive(Eq, PartialEq, Debug, Clone)]
115 pub struct RouteHintHop {
116 /// The node_id of the non-target end of the route
117 pub src_node_id: PublicKey,
118 /// The short_channel_id of this channel
119 pub short_channel_id: u64,
120 /// The fees which must be paid to use this channel
121 pub fees: RoutingFees,
122 /// The difference in CLTV values between this node and the next node.
123 pub cltv_expiry_delta: u16,
124 /// The minimum value, in msat, which must be relayed to the next hop.
125 pub htlc_minimum_msat: Option<u64>,
126 /// The maximum value in msat available for routing with a single HTLC.
127 pub htlc_maximum_msat: Option<u64>,
130 #[derive(Eq, PartialEq)]
131 struct RouteGraphNode {
133 lowest_fee_to_peer_through_node: u64,
134 lowest_fee_to_node: u64,
135 // The maximum value a yet-to-be-constructed payment path might flow through this node.
136 // This value is upper-bounded by us by:
137 // - how much is needed for a path being constructed
138 // - how much value can channels following this node (up to the destination) can contribute,
139 // considering their capacity and fees
140 value_contribution_msat: u64,
141 /// The effective htlc_minimum_msat at this hop. If a later hop on the path had a higher HTLC
142 /// minimum, we use it, plus the fees required at each earlier hop to meet it.
143 path_htlc_minimum_msat: u64,
146 impl cmp::Ord for RouteGraphNode {
147 fn cmp(&self, other: &RouteGraphNode) -> cmp::Ordering {
148 let other_score = cmp::max(other.lowest_fee_to_peer_through_node, other.path_htlc_minimum_msat);
149 let self_score = cmp::max(self.lowest_fee_to_peer_through_node, self.path_htlc_minimum_msat);
150 other_score.cmp(&self_score).then_with(|| other.pubkey.serialize().cmp(&self.pubkey.serialize()))
154 impl cmp::PartialOrd for RouteGraphNode {
155 fn partial_cmp(&self, other: &RouteGraphNode) -> Option<cmp::Ordering> {
156 Some(self.cmp(other))
160 struct DummyDirectionalChannelInfo {
161 cltv_expiry_delta: u32,
162 htlc_minimum_msat: u64,
163 htlc_maximum_msat: Option<u64>,
167 /// It's useful to keep track of the hops associated with the fees required to use them,
168 /// so that we can choose cheaper paths (as per Dijkstra's algorithm).
169 /// Fee values should be updated only in the context of the whole path, see update_value_and_recompute_fees.
170 /// These fee values are useful to choose hops as we traverse the graph "payee-to-payer".
172 struct PathBuildingHop<'a> {
173 // The RouteHintHop fields which will eventually be used if this hop is used in a final Route.
174 // Note that node_features is calculated separately after our initial graph walk.
176 short_channel_id: u64,
177 channel_features: &'a ChannelFeatures,
179 cltv_expiry_delta: u32,
181 /// Minimal fees required to route to the source node of the current hop via any of its inbound channels.
182 src_lowest_inbound_fees: RoutingFees,
183 /// Fees of the channel used in this hop.
184 channel_fees: RoutingFees,
185 /// All the fees paid *after* this channel on the way to the destination
186 next_hops_fee_msat: u64,
187 /// Fee paid for the use of the current channel (see channel_fees).
188 /// The value will be actually deducted from the counterparty balance on the previous link.
189 hop_use_fee_msat: u64,
190 /// Used to compare channels when choosing the for routing.
191 /// Includes paying for the use of a hop and the following hops, as well as
192 /// an estimated cost of reaching this hop.
193 /// Might get stale when fees are recomputed. Primarily for internal use.
195 /// This is useful for update_value_and_recompute_fees to make sure
196 /// we don't fall below the minimum. Should not be updated manually and
197 /// generally should not be accessed.
198 htlc_minimum_msat: u64,
199 /// A mirror of the same field in RouteGraphNode. Note that this is only used during the graph
200 /// walk and may be invalid thereafter.
201 path_htlc_minimum_msat: u64,
202 /// If we've already processed a node as the best node, we shouldn't process it again. Normally
203 /// we'd just ignore it if we did as all channels would have a higher new fee, but because we
204 /// may decrease the amounts in use as we walk the graph, the actual calculated fee may
205 /// decrease as well. Thus, we have to explicitly track which nodes have been processed and
206 /// avoid processing them again.
208 #[cfg(any(test, feature = "fuzztarget"))]
209 // In tests, we apply further sanity checks on cases where we skip nodes we already processed
210 // to ensure it is specifically in cases where the fee has gone down because of a decrease in
211 // value_contribution_msat, which requires tracking it here. See comments below where it is
212 // used for more info.
213 value_contribution_msat: u64,
216 // Instantiated with a list of hops with correct data in them collected during path finding,
217 // an instance of this struct should be further modified only via given methods.
219 struct PaymentPath<'a> {
220 hops: Vec<(PathBuildingHop<'a>, NodeFeatures)>,
223 impl<'a> PaymentPath<'a> {
224 // TODO: Add a value_msat field to PaymentPath and use it instead of this function.
225 fn get_value_msat(&self) -> u64 {
226 self.hops.last().unwrap().0.fee_msat
229 fn get_total_fee_paid_msat(&self) -> u64 {
230 if self.hops.len() < 1 {
234 // Can't use next_hops_fee_msat because it gets outdated.
235 for (i, (hop, _)) in self.hops.iter().enumerate() {
236 if i != self.hops.len() - 1 {
237 result += hop.fee_msat;
243 // If the amount transferred by the path is updated, the fees should be adjusted. Any other way
244 // to change fees may result in an inconsistency.
246 // Sometimes we call this function right after constructing a path which is inconsistent in
247 // that it the value being transferred has decreased while we were doing path finding, leading
248 // to the fees being paid not lining up with the actual limits.
250 // Note that this function is not aware of the available_liquidity limit, and thus does not
251 // support increasing the value being transferred.
252 fn update_value_and_recompute_fees(&mut self, value_msat: u64) {
253 assert!(value_msat <= self.hops.last().unwrap().0.fee_msat);
255 let mut total_fee_paid_msat = 0 as u64;
256 for i in (0..self.hops.len()).rev() {
257 let last_hop = i == self.hops.len() - 1;
259 // For non-last-hop, this value will represent the fees paid on the current hop. It
260 // will consist of the fees for the use of the next hop, and extra fees to match
261 // htlc_minimum_msat of the current channel. Last hop is handled separately.
262 let mut cur_hop_fees_msat = 0;
264 cur_hop_fees_msat = self.hops.get(i + 1).unwrap().0.hop_use_fee_msat;
267 let mut cur_hop = &mut self.hops.get_mut(i).unwrap().0;
268 cur_hop.next_hops_fee_msat = total_fee_paid_msat;
269 // Overpay in fees if we can't save these funds due to htlc_minimum_msat.
270 // We try to account for htlc_minimum_msat in scoring (add_entry!), so that nodes don't
271 // set it too high just to maliciously take more fees by exploiting this
272 // match htlc_minimum_msat logic.
273 let mut cur_hop_transferred_amount_msat = total_fee_paid_msat + value_msat;
274 if let Some(extra_fees_msat) = cur_hop.htlc_minimum_msat.checked_sub(cur_hop_transferred_amount_msat) {
275 // Note that there is a risk that *previous hops* (those closer to us, as we go
276 // payee->our_node here) would exceed their htlc_maximum_msat or available balance.
278 // This might make us end up with a broken route, although this should be super-rare
279 // in practice, both because of how healthy channels look like, and how we pick
280 // channels in add_entry.
281 // Also, this can't be exploited more heavily than *announce a free path and fail
283 cur_hop_transferred_amount_msat += extra_fees_msat;
284 total_fee_paid_msat += extra_fees_msat;
285 cur_hop_fees_msat += extra_fees_msat;
289 // Final hop is a special case: it usually has just value_msat (by design), but also
290 // it still could overpay for the htlc_minimum_msat.
291 cur_hop.fee_msat = cur_hop_transferred_amount_msat;
293 // Propagate updated fees for the use of the channels to one hop back, where they
294 // will be actually paid (fee_msat). The last hop is handled above separately.
295 cur_hop.fee_msat = cur_hop_fees_msat;
298 // Fee for the use of the current hop which will be deducted on the previous hop.
299 // Irrelevant for the first hop, as it doesn't have the previous hop, and the use of
300 // this channel is free for us.
302 if let Some(new_fee) = compute_fees(cur_hop_transferred_amount_msat, cur_hop.channel_fees) {
303 cur_hop.hop_use_fee_msat = new_fee;
304 total_fee_paid_msat += new_fee;
306 // It should not be possible because this function is called only to reduce the
307 // value. In that case, compute_fee was already called with the same fees for
308 // larger amount and there was no overflow.
316 fn compute_fees(amount_msat: u64, channel_fees: RoutingFees) -> Option<u64> {
317 let proportional_fee_millions =
318 amount_msat.checked_mul(channel_fees.proportional_millionths as u64);
319 if let Some(new_fee) = proportional_fee_millions.and_then(|part| {
320 (channel_fees.base_msat as u64).checked_add(part / 1_000_000) }) {
324 // This function may be (indirectly) called without any verification,
325 // with channel_fees provided by a caller. We should handle it gracefully.
330 /// Gets a route from us (payer) to the given target node (payee).
332 /// If the payee provided features in their invoice, they should be provided via payee_features.
333 /// Without this, MPP will only be used if the payee's features are available in the network graph.
335 /// Private routing paths between a public node and the target may be included in `last_hops`.
336 /// Currently, only the last hop in each path is considered.
338 /// If some channels aren't announced, it may be useful to fill in a first_hops with the
339 /// results from a local ChannelManager::list_usable_channels() call. If it is filled in, our
340 /// view of our local channels (from net_graph_msg_handler) will be ignored, and only those
341 /// in first_hops will be used.
343 /// Panics if first_hops contains channels without short_channel_ids
344 /// (ChannelManager::list_usable_channels will never include such channels).
346 /// The fees on channels from us to next-hops are ignored (as they are assumed to all be
347 /// equal), however the enabled/disabled bit on such channels as well as the
348 /// htlc_minimum_msat/htlc_maximum_msat *are* checked as they may change based on the receiving node.
349 pub fn get_route<L: Deref>(our_node_id: &PublicKey, network: &NetworkGraph, payee: &PublicKey, payee_features: Option<InvoiceFeatures>, first_hops: Option<&[&ChannelDetails]>,
350 last_hops: &[&RouteHint], final_value_msat: u64, final_cltv: u32, logger: L) -> Result<Route, LightningError> where L::Target: Logger {
351 // TODO: Obviously *only* using total fee cost sucks. We should consider weighting by
352 // uptime/success in using a node in the past.
353 if *payee == *our_node_id {
354 return Err(LightningError{err: "Cannot generate a route to ourselves".to_owned(), action: ErrorAction::IgnoreError});
357 if final_value_msat > MAX_VALUE_MSAT {
358 return Err(LightningError{err: "Cannot generate a route of more value than all existing satoshis".to_owned(), action: ErrorAction::IgnoreError});
361 if final_value_msat == 0 {
362 return Err(LightningError{err: "Cannot send a payment of 0 msat".to_owned(), action: ErrorAction::IgnoreError});
365 let last_hops = last_hops.iter().filter_map(|hops| hops.0.last()).collect::<Vec<_>>();
366 for last_hop in last_hops.iter() {
367 if last_hop.src_node_id == *payee {
368 return Err(LightningError{err: "Last hop cannot have a payee as a source.".to_owned(), action: ErrorAction::IgnoreError});
372 // The general routing idea is the following:
373 // 1. Fill first/last hops communicated by the caller.
374 // 2. Attempt to construct a path from payer to payee for transferring
375 // any ~sufficient (described later) value.
376 // If succeed, remember which channels were used and how much liquidity they have available,
377 // so that future paths don't rely on the same liquidity.
378 // 3. Prooceed to the next step if:
379 // - we hit the recommended target value;
380 // - OR if we could not construct a new path. Any next attempt will fail too.
381 // Otherwise, repeat step 2.
382 // 4. See if we managed to collect paths which aggregately are able to transfer target value
383 // (not recommended value). If yes, proceed. If not, fail routing.
384 // 5. Randomly combine paths into routes having enough to fulfill the payment. (TODO: knapsack)
385 // 6. Of all the found paths, select only those with the lowest total fee.
386 // 7. The last path in every selected route is likely to be more than we need.
387 // Reduce its value-to-transfer and recompute fees.
388 // 8. Choose the best route by the lowest total fee.
390 // As for the actual search algorithm,
391 // we do a payee-to-payer pseudo-Dijkstra's sorting by each node's distance from the payee
392 // plus the minimum per-HTLC fee to get from it to another node (aka "shitty pseudo-A*").
394 // We are not a faithful Dijkstra's implementation because we can change values which impact
395 // earlier nodes while processing later nodes. Specifically, if we reach a channel with a lower
396 // liquidity limit (via htlc_maximum_msat, on-chain capacity or assumed liquidity limits) then
397 // the value we are currently attempting to send over a path, we simply reduce the value being
398 // sent along the path for any hops after that channel. This may imply that later fees (which
399 // we've already tabulated) are lower because a smaller value is passing through the channels
400 // (and the proportional fee is thus lower). There isn't a trivial way to recalculate the
401 // channels which were selected earlier (and which may still be used for other paths without a
402 // lower liquidity limit), so we simply accept that some liquidity-limited paths may be
405 // One potentially problematic case for this algorithm would be if there are many
406 // liquidity-limited paths which are liquidity-limited near the destination (ie early in our
407 // graph walking), we may never find a path which is not liquidity-limited and has lower
408 // proportional fee (and only lower absolute fee when considering the ultimate value sent).
409 // Because we only consider paths with at least 5% of the total value being sent, the damage
410 // from such a case should be limited, however this could be further reduced in the future by
411 // calculating fees on the amount we wish to route over a path, ie ignoring the liquidity
412 // limits for the purposes of fee calculation.
414 // Alternatively, we could store more detailed path information in the heap (targets, below)
415 // and index the best-path map (dist, below) by node *and* HTLC limits, however that would blow
416 // up the runtime significantly both algorithmically (as we'd traverse nodes multiple times)
417 // and practically (as we would need to store dynamically-allocated path information in heap
418 // objects, increasing malloc traffic and indirect memory access significantly). Further, the
419 // results of such an algorithm would likely be biased towards lower-value paths.
421 // Further, we could return to a faithful Dijkstra's algorithm by rejecting paths with limits
422 // outside of our current search value, running a path search more times to gather candidate
423 // paths at different values. While this may be acceptable, further path searches may increase
424 // runtime for little gain. Specifically, the current algorithm rather efficiently explores the
425 // graph for candidate paths, calculating the maximum value which can realistically be sent at
426 // the same time, remaining generic across different payment values.
428 // TODO: There are a few tweaks we could do, including possibly pre-calculating more stuff
429 // to use as the A* heuristic beyond just the cost to get one node further than the current
432 let dummy_directional_info = DummyDirectionalChannelInfo { // used for first_hops routes
433 cltv_expiry_delta: 0,
434 htlc_minimum_msat: 0,
435 htlc_maximum_msat: None,
438 proportional_millionths: 0,
442 // Allow MPP only if we have a features set from somewhere that indicates the payee supports
443 // it. If the payee supports it they're supposed to include it in the invoice, so that should
445 let allow_mpp = if let Some(features) = &payee_features {
446 features.supports_basic_mpp()
447 } else if let Some(node) = network.get_nodes().get(&payee) {
448 if let Some(node_info) = node.announcement_info.as_ref() {
449 node_info.features.supports_basic_mpp()
454 // Prepare the data we'll use for payee-to-payer search by
455 // inserting first hops suggested by the caller as targets.
456 // Our search will then attempt to reach them while traversing from the payee node.
457 let mut first_hop_targets: HashMap<_, (_, ChannelFeatures, _, NodeFeatures)> =
458 HashMap::with_capacity(if first_hops.is_some() { first_hops.as_ref().unwrap().len() } else { 0 });
459 if let Some(hops) = first_hops {
461 let short_channel_id = chan.short_channel_id.expect("first_hops should be filled in with usable channels, not pending ones");
462 if chan.remote_network_id == *our_node_id {
463 return Err(LightningError{err: "First hop cannot have our_node_id as a destination.".to_owned(), action: ErrorAction::IgnoreError});
465 first_hop_targets.insert(chan.remote_network_id, (short_channel_id, chan.counterparty_features.to_context(), chan.outbound_capacity_msat, chan.counterparty_features.to_context()));
467 if first_hop_targets.is_empty() {
468 return Err(LightningError{err: "Cannot route when there are no outbound routes away from us".to_owned(), action: ErrorAction::IgnoreError});
472 let empty_channel_features = ChannelFeatures::empty();
474 // The main heap containing all candidate next-hops sorted by their score (max(A* fee,
475 // htlc_minimum)). Ideally this would be a heap which allowed cheap score reduction instead of
476 // adding duplicate entries when we find a better path to a given node.
477 let mut targets = BinaryHeap::new();
479 // Map from node_id to information about the best current path to that node, including feerate
481 let mut dist = HashMap::with_capacity(network.get_nodes().len());
483 // During routing, if we ignore a path due to an htlc_minimum_msat limit, we set this,
484 // indicating that we may wish to try again with a higher value, potentially paying to meet an
485 // htlc_minimum with extra fees while still finding a cheaper path.
486 let mut hit_minimum_limit;
488 // When arranging a route, we select multiple paths so that we can make a multi-path payment.
489 // We start with a path_value of the exact amount we want, and if that generates a route we may
490 // return it immediately. Otherwise, we don't stop searching for paths until we have 3x the
491 // amount we want in total across paths, selecting the best subset at the end.
492 const ROUTE_CAPACITY_PROVISION_FACTOR: u64 = 3;
493 let recommended_value_msat = final_value_msat * ROUTE_CAPACITY_PROVISION_FACTOR as u64;
494 let mut path_value_msat = final_value_msat;
496 // We don't want multiple paths (as per MPP) share liquidity of the same channels.
497 // This map allows paths to be aware of the channel use by other paths in the same call.
498 // This would help to make a better path finding decisions and not "overbook" channels.
499 // It is unaware of the directions (except for `outbound_capacity_msat` in `first_hops`).
500 let mut bookkeeped_channels_liquidity_available_msat = HashMap::with_capacity(network.get_nodes().len());
502 // Keeping track of how much value we already collected across other paths. Helps to decide:
503 // - how much a new path should be transferring (upper bound);
504 // - whether a channel should be disregarded because
505 // it's available liquidity is too small comparing to how much more we need to collect;
506 // - when we want to stop looking for new paths.
507 let mut already_collected_value_msat = 0;
509 macro_rules! add_entry {
510 // Adds entry which goes from $src_node_id to $dest_node_id
511 // over the channel with id $chan_id with fees described in
512 // $directional_info.
513 // $next_hops_fee_msat represents the fees paid for using all the channel *after* this one,
514 // since that value has to be transferred over this channel.
515 ( $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,
516 $next_hops_value_contribution: expr, $next_hops_path_htlc_minimum_msat: expr ) => {
517 // Channels to self should not be used. This is more of belt-and-suspenders, because in
518 // practice these cases should be caught earlier:
519 // - for regular channels at channel announcement (TODO)
520 // - for first and last hops early in get_route
521 if $src_node_id != $dest_node_id.clone() {
522 let available_liquidity_msat = bookkeeped_channels_liquidity_available_msat.entry($chan_id.clone()).or_insert_with(|| {
523 let mut initial_liquidity_available_msat = None;
524 if let Some(capacity_sats) = $capacity_sats {
525 initial_liquidity_available_msat = Some(capacity_sats * 1000);
528 if let Some(htlc_maximum_msat) = $directional_info.htlc_maximum_msat {
529 if let Some(available_msat) = initial_liquidity_available_msat {
530 initial_liquidity_available_msat = Some(cmp::min(available_msat, htlc_maximum_msat));
532 initial_liquidity_available_msat = Some(htlc_maximum_msat);
536 match initial_liquidity_available_msat {
537 Some(available_msat) => available_msat,
538 // We assume channels with unknown balance have
539 // a capacity of 0.0025 BTC (or 250_000 sats).
540 None => 250_000 * 1000
544 // It is tricky to substract $next_hops_fee_msat from available liquidity here.
545 // It may be misleading because we might later choose to reduce the value transferred
546 // over these channels, and the channel which was insufficient might become sufficient.
547 // Worst case: we drop a good channel here because it can't cover the high following
548 // fees caused by one expensive channel, but then this channel could have been used
549 // if the amount being transferred over this path is lower.
550 // We do this for now, but this is a subject for removal.
551 if let Some(available_value_contribution_msat) = available_liquidity_msat.checked_sub($next_hops_fee_msat) {
553 // Routing Fragmentation Mitigation heuristic:
555 // Routing fragmentation across many payment paths increases the overall routing
556 // fees as you have irreducible routing fees per-link used (`fee_base_msat`).
557 // Taking too many smaller paths also increases the chance of payment failure.
558 // Thus to avoid this effect, we require from our collected links to provide
559 // at least a minimal contribution to the recommended value yet-to-be-fulfilled.
561 // This requirement is currently 5% of the remaining-to-be-collected value.
562 // This means as we successfully advance in our collection,
563 // the absolute liquidity contribution is lowered,
564 // thus increasing the number of potential channels to be selected.
566 // Derive the minimal liquidity contribution with a ratio of 20 (5%, rounded up)
567 // or 100% if we're not allowed to do multipath payments.
568 let minimal_value_contribution_msat: u64 = if allow_mpp {
569 (recommended_value_msat - already_collected_value_msat + 19) / 20
573 // Verify the liquidity offered by this channel complies to the minimal contribution.
574 let contributes_sufficient_value = available_value_contribution_msat >= minimal_value_contribution_msat;
576 let value_contribution_msat = cmp::min(available_value_contribution_msat, $next_hops_value_contribution);
577 // Includes paying fees for the use of the following channels.
578 let amount_to_transfer_over_msat: u64 = match value_contribution_msat.checked_add($next_hops_fee_msat) {
579 Some(result) => result,
580 // Can't overflow due to how the values were computed right above.
581 None => unreachable!(),
583 #[allow(unused_comparisons)] // $next_hops_path_htlc_minimum_msat is 0 in some calls so rustc complains
584 let over_path_minimum_msat = amount_to_transfer_over_msat >= $directional_info.htlc_minimum_msat &&
585 amount_to_transfer_over_msat >= $next_hops_path_htlc_minimum_msat;
587 // If HTLC minimum is larger than the amount we're going to transfer, we shouldn't
588 // bother considering this channel.
589 // Since we're choosing amount_to_transfer_over_msat as maximum possible, it can
590 // be only reduced later (not increased), so this channel should just be skipped
591 // as not sufficient.
592 if !over_path_minimum_msat {
593 hit_minimum_limit = true;
594 } else if contributes_sufficient_value {
595 // Note that low contribution here (limited by available_liquidity_msat)
596 // might violate htlc_minimum_msat on the hops which are next along the
597 // payment path (upstream to the payee). To avoid that, we recompute path
598 // path fees knowing the final path contribution after constructing it.
599 let path_htlc_minimum_msat = match compute_fees($next_hops_path_htlc_minimum_msat, $directional_info.fees)
600 .map(|fee_msat| fee_msat.checked_add($next_hops_path_htlc_minimum_msat)) {
601 Some(Some(value_msat)) => cmp::max(value_msat, $directional_info.htlc_minimum_msat),
602 _ => u64::max_value()
604 let hm_entry = dist.entry(&$src_node_id);
605 let old_entry = hm_entry.or_insert_with(|| {
606 // If there was previously no known way to access
607 // the source node (recall it goes payee-to-payer) of $chan_id, first add
608 // a semi-dummy record just to compute the fees to reach the source node.
609 // This will affect our decision on selecting $chan_id
610 // as a way to reach the $dest_node_id.
611 let mut fee_base_msat = u32::max_value();
612 let mut fee_proportional_millionths = u32::max_value();
613 if let Some(Some(fees)) = network.get_nodes().get(&$src_node_id).map(|node| node.lowest_inbound_channel_fees) {
614 fee_base_msat = fees.base_msat;
615 fee_proportional_millionths = fees.proportional_millionths;
618 pubkey: $dest_node_id.clone(),
620 channel_features: $chan_features,
622 cltv_expiry_delta: 0,
623 src_lowest_inbound_fees: RoutingFees {
624 base_msat: fee_base_msat,
625 proportional_millionths: fee_proportional_millionths,
627 channel_fees: $directional_info.fees,
628 next_hops_fee_msat: u64::max_value(),
629 hop_use_fee_msat: u64::max_value(),
630 total_fee_msat: u64::max_value(),
631 htlc_minimum_msat: $directional_info.htlc_minimum_msat,
632 path_htlc_minimum_msat,
633 was_processed: false,
634 #[cfg(any(test, feature = "fuzztarget"))]
635 value_contribution_msat,
639 #[allow(unused_mut)] // We only use the mut in cfg(test)
640 let mut should_process = !old_entry.was_processed;
641 #[cfg(any(test, feature = "fuzztarget"))]
643 // In test/fuzzing builds, we do extra checks to make sure the skipping
644 // of already-seen nodes only happens in cases we expect (see below).
645 if !should_process { should_process = true; }
649 let mut hop_use_fee_msat = 0;
650 let mut total_fee_msat = $next_hops_fee_msat;
652 // Ignore hop_use_fee_msat for channel-from-us as we assume all channels-from-us
653 // will have the same effective-fee
654 if $src_node_id != *our_node_id {
655 match compute_fees(amount_to_transfer_over_msat, $directional_info.fees) {
656 // max_value means we'll always fail
657 // the old_entry.total_fee_msat > total_fee_msat check
658 None => total_fee_msat = u64::max_value(),
660 hop_use_fee_msat = fee_msat;
661 total_fee_msat += hop_use_fee_msat;
662 // When calculating the lowest inbound fees to a node, we
663 // calculate fees here not based on the actual value we think
664 // will flow over this channel, but on the minimum value that
665 // we'll accept flowing over it. The minimum accepted value
666 // is a constant through each path collection run, ensuring
667 // consistent basis. Otherwise we may later find a
668 // different path to the source node that is more expensive,
669 // but which we consider to be cheaper because we are capacity
670 // constrained and the relative fee becomes lower.
671 match compute_fees(minimal_value_contribution_msat, old_entry.src_lowest_inbound_fees)
672 .map(|a| a.checked_add(total_fee_msat)) {
677 total_fee_msat = u64::max_value();
684 let new_graph_node = RouteGraphNode {
685 pubkey: $src_node_id,
686 lowest_fee_to_peer_through_node: total_fee_msat,
687 lowest_fee_to_node: $next_hops_fee_msat as u64 + hop_use_fee_msat,
688 value_contribution_msat: value_contribution_msat,
689 path_htlc_minimum_msat,
692 // Update the way of reaching $src_node_id with the given $chan_id (from $dest_node_id),
693 // if this way is cheaper than the already known
694 // (considering the cost to "reach" this channel from the route destination,
695 // the cost of using this channel,
696 // and the cost of routing to the source node of this channel).
697 // Also, consider that htlc_minimum_msat_difference, because we might end up
698 // paying it. Consider the following exploit:
699 // we use 2 paths to transfer 1.5 BTC. One of them is 0-fee normal 1 BTC path,
700 // and for the other one we picked a 1sat-fee path with htlc_minimum_msat of
701 // 1 BTC. Now, since the latter is more expensive, we gonna try to cut it
702 // by 0.5 BTC, but then match htlc_minimum_msat by paying a fee of 0.5 BTC
704 // Ideally the scoring could be smarter (e.g. 0.5*htlc_minimum_msat here),
705 // but it may require additional tracking - we don't want to double-count
706 // the fees included in $next_hops_path_htlc_minimum_msat, but also
707 // can't use something that may decrease on future hops.
708 let old_cost = cmp::max(old_entry.total_fee_msat, old_entry.path_htlc_minimum_msat);
709 let new_cost = cmp::max(total_fee_msat, path_htlc_minimum_msat);
711 if !old_entry.was_processed && new_cost < old_cost {
712 targets.push(new_graph_node);
713 old_entry.next_hops_fee_msat = $next_hops_fee_msat;
714 old_entry.hop_use_fee_msat = hop_use_fee_msat;
715 old_entry.total_fee_msat = total_fee_msat;
716 old_entry.pubkey = $dest_node_id.clone();
717 old_entry.short_channel_id = $chan_id.clone();
718 old_entry.channel_features = $chan_features;
719 old_entry.fee_msat = 0; // This value will be later filled with hop_use_fee_msat of the following channel
720 old_entry.cltv_expiry_delta = $directional_info.cltv_expiry_delta as u32;
721 old_entry.channel_fees = $directional_info.fees;
722 old_entry.htlc_minimum_msat = $directional_info.htlc_minimum_msat;
723 old_entry.path_htlc_minimum_msat = path_htlc_minimum_msat;
724 #[cfg(any(test, feature = "fuzztarget"))]
726 old_entry.value_contribution_msat = value_contribution_msat;
728 } else if old_entry.was_processed && new_cost < old_cost {
729 #[cfg(any(test, feature = "fuzztarget"))]
731 // If we're skipping processing a node which was previously
732 // processed even though we found another path to it with a
733 // cheaper fee, check that it was because the second path we
734 // found (which we are processing now) has a lower value
735 // contribution due to an HTLC minimum limit.
737 // e.g. take a graph with two paths from node 1 to node 2, one
738 // through channel A, and one through channel B. Channel A and
739 // B are both in the to-process heap, with their scores set by
740 // a higher htlc_minimum than fee.
741 // Channel A is processed first, and the channels onwards from
742 // node 1 are added to the to-process heap. Thereafter, we pop
743 // Channel B off of the heap, note that it has a much more
744 // restrictive htlc_maximum_msat, and recalculate the fees for
745 // all of node 1's channels using the new, reduced, amount.
747 // This would be bogus - we'd be selecting a higher-fee path
748 // with a lower htlc_maximum_msat instead of the one we'd
749 // already decided to use.
750 debug_assert!(path_htlc_minimum_msat < old_entry.path_htlc_minimum_msat);
751 debug_assert!(value_contribution_msat < old_entry.value_contribution_msat);
761 let empty_node_features = NodeFeatures::empty();
762 // Find ways (channels with destination) to reach a given node and store them
763 // in the corresponding data structures (routing graph etc).
764 // $fee_to_target_msat represents how much it costs to reach to this node from the payee,
765 // meaning how much will be paid in fees after this node (to the best of our knowledge).
766 // This data can later be helpful to optimize routing (pay lower fees).
767 macro_rules! add_entries_to_cheapest_to_target_node {
768 ( $node: expr, $node_id: expr, $fee_to_target_msat: expr, $next_hops_value_contribution: expr, $next_hops_path_htlc_minimum_msat: expr ) => {
769 let skip_node = if let Some(elem) = dist.get_mut($node_id) {
770 let was_processed = elem.was_processed;
771 elem.was_processed = true;
774 // Entries are added to dist in add_entry!() when there is a channel from a node.
775 // Because there are no channels from payee, it will not have a dist entry at this point.
776 // If we're processing any other node, it is always be the result of a channel from it.
777 assert_eq!($node_id, payee);
782 if first_hops.is_some() {
783 if let Some(&(ref first_hop, ref features, ref outbound_capacity_msat, _)) = first_hop_targets.get(&$node_id) {
784 add_entry!(first_hop, *our_node_id, $node_id, dummy_directional_info, Some(outbound_capacity_msat / 1000), features, $fee_to_target_msat, $next_hops_value_contribution, $next_hops_path_htlc_minimum_msat);
788 let features = if let Some(node_info) = $node.announcement_info.as_ref() {
794 if !features.requires_unknown_bits() {
795 for chan_id in $node.channels.iter() {
796 let chan = network.get_channels().get(chan_id).unwrap();
797 if !chan.features.requires_unknown_bits() {
798 if chan.node_one == *$node_id {
799 // ie $node is one, ie next hop in A* is two, via the two_to_one channel
800 if first_hops.is_none() || chan.node_two != *our_node_id {
801 if let Some(two_to_one) = chan.two_to_one.as_ref() {
802 if two_to_one.enabled {
803 add_entry!(chan_id, chan.node_two, chan.node_one, two_to_one, chan.capacity_sats, &chan.features, $fee_to_target_msat, $next_hops_value_contribution, $next_hops_path_htlc_minimum_msat);
808 if first_hops.is_none() || chan.node_one != *our_node_id {
809 if let Some(one_to_two) = chan.one_to_two.as_ref() {
810 if one_to_two.enabled {
811 add_entry!(chan_id, chan.node_one, chan.node_two, one_to_two, chan.capacity_sats, &chan.features, $fee_to_target_msat, $next_hops_value_contribution, $next_hops_path_htlc_minimum_msat);
823 let mut payment_paths = Vec::<PaymentPath>::new();
825 // TODO: diversify by nodes (so that all paths aren't doomed if one node is offline).
826 'paths_collection: loop {
827 // For every new path, start from scratch, except
828 // bookkeeped_channels_liquidity_available_msat, which will improve
829 // the further iterations of path finding. Also don't erase first_hop_targets.
832 hit_minimum_limit = false;
834 // If first hop is a private channel and the only way to reach the payee, this is the only
835 // place where it could be added.
836 if first_hops.is_some() {
837 if let Some(&(ref first_hop, ref features, ref outbound_capacity_msat, _)) = first_hop_targets.get(&payee) {
838 add_entry!(first_hop, *our_node_id, payee, dummy_directional_info, Some(outbound_capacity_msat / 1000), features, 0, path_value_msat, 0);
842 // Add the payee as a target, so that the payee-to-payer
843 // search algorithm knows what to start with.
844 match network.get_nodes().get(payee) {
845 // The payee is not in our network graph, so nothing to add here.
846 // There is still a chance of reaching them via last_hops though,
847 // so don't yet fail the payment here.
848 // If not, targets.pop() will not even let us enter the loop in step 2.
851 add_entries_to_cheapest_to_target_node!(node, payee, 0, path_value_msat, 0);
856 // If a caller provided us with last hops, add them to routing targets. Since this happens
857 // earlier than general path finding, they will be somewhat prioritized, although currently
858 // it matters only if the fees are exactly the same.
859 for hop in last_hops.iter() {
860 let have_hop_src_in_graph =
861 if let Some(&(ref first_hop, ref features, ref outbound_capacity_msat, _)) = first_hop_targets.get(&hop.src_node_id) {
862 // If this hop connects to a node with which we have a direct channel, ignore
863 // the network graph and add both the hop and our direct channel to
864 // the candidate set.
866 // Currently there are no channel-context features defined, so we are a
867 // bit lazy here. In the future, we should pull them out via our
868 // ChannelManager, but there's no reason to waste the space until we
870 add_entry!(first_hop, *our_node_id , hop.src_node_id, dummy_directional_info, Some(outbound_capacity_msat / 1000), features, 0, path_value_msat, 0);
873 // In any other case, only add the hop if the source is in the regular network
875 network.get_nodes().get(&hop.src_node_id).is_some()
877 if have_hop_src_in_graph {
878 // BOLT 11 doesn't allow inclusion of features for the last hop hints, which
879 // really sucks, cause we're gonna need that eventually.
880 let last_hop_htlc_minimum_msat: u64 = match hop.htlc_minimum_msat {
881 Some(htlc_minimum_msat) => htlc_minimum_msat,
884 let directional_info = DummyDirectionalChannelInfo {
885 cltv_expiry_delta: hop.cltv_expiry_delta as u32,
886 htlc_minimum_msat: last_hop_htlc_minimum_msat,
887 htlc_maximum_msat: hop.htlc_maximum_msat,
890 add_entry!(hop.short_channel_id, hop.src_node_id, payee, directional_info, None::<u64>, &empty_channel_features, 0, path_value_msat, 0);
894 // At this point, targets are filled with the data from first and
895 // last hops communicated by the caller, and the payment receiver.
896 let mut found_new_path = false;
899 // If this loop terminates due the exhaustion of targets, two situations are possible:
900 // - not enough outgoing liquidity:
901 // 0 < already_collected_value_msat < final_value_msat
902 // - enough outgoing liquidity:
903 // final_value_msat <= already_collected_value_msat < recommended_value_msat
904 // Both these cases (and other cases except reaching recommended_value_msat) mean that
905 // paths_collection will be stopped because found_new_path==false.
906 // This is not necessarily a routing failure.
907 'path_construction: while let Some(RouteGraphNode { pubkey, lowest_fee_to_node, value_contribution_msat, path_htlc_minimum_msat, .. }) = targets.pop() {
909 // Since we're going payee-to-payer, hitting our node as a target means we should stop
910 // traversing the graph and arrange the path out of what we found.
911 if pubkey == *our_node_id {
912 let mut new_entry = dist.remove(&our_node_id).unwrap();
913 let mut ordered_hops = vec!((new_entry.clone(), NodeFeatures::empty()));
916 if let Some(&(_, _, _, ref features)) = first_hop_targets.get(&ordered_hops.last().unwrap().0.pubkey) {
917 ordered_hops.last_mut().unwrap().1 = features.clone();
918 } else if let Some(node) = network.get_nodes().get(&ordered_hops.last().unwrap().0.pubkey) {
919 if let Some(node_info) = node.announcement_info.as_ref() {
920 ordered_hops.last_mut().unwrap().1 = node_info.features.clone();
922 ordered_hops.last_mut().unwrap().1 = NodeFeatures::empty();
925 // We should be able to fill in features for everything except the last
926 // hop, if the last hop was provided via a BOLT 11 invoice (though we
927 // should be able to extend it further as BOLT 11 does have feature
928 // flags for the last hop node itself).
929 assert!(ordered_hops.last().unwrap().0.pubkey == *payee);
932 // Means we succesfully traversed from the payer to the payee, now
933 // save this path for the payment route. Also, update the liquidity
934 // remaining on the used hops, so that we take them into account
935 // while looking for more paths.
936 if ordered_hops.last().unwrap().0.pubkey == *payee {
940 new_entry = match dist.remove(&ordered_hops.last().unwrap().0.pubkey) {
941 Some(payment_hop) => payment_hop,
942 // We can't arrive at None because, if we ever add an entry to targets,
943 // we also fill in the entry in dist (see add_entry!).
944 None => unreachable!(),
946 // We "propagate" the fees one hop backward (topologically) here,
947 // so that fees paid for a HTLC forwarding on the current channel are
948 // associated with the previous channel (where they will be subtracted).
949 ordered_hops.last_mut().unwrap().0.fee_msat = new_entry.hop_use_fee_msat;
950 ordered_hops.last_mut().unwrap().0.cltv_expiry_delta = new_entry.cltv_expiry_delta;
951 ordered_hops.push((new_entry.clone(), NodeFeatures::empty()));
953 ordered_hops.last_mut().unwrap().0.fee_msat = value_contribution_msat;
954 ordered_hops.last_mut().unwrap().0.hop_use_fee_msat = 0;
955 ordered_hops.last_mut().unwrap().0.cltv_expiry_delta = final_cltv;
957 let mut payment_path = PaymentPath {hops: ordered_hops};
959 // We could have possibly constructed a slightly inconsistent path: since we reduce
960 // value being transferred along the way, we could have violated htlc_minimum_msat
961 // on some channels we already passed (assuming dest->source direction). Here, we
962 // recompute the fees again, so that if that's the case, we match the currently
963 // underpaid htlc_minimum_msat with fees.
964 payment_path.update_value_and_recompute_fees(cmp::min(value_contribution_msat, final_value_msat));
966 // Since a path allows to transfer as much value as
967 // the smallest channel it has ("bottleneck"), we should recompute
968 // the fees so sender HTLC don't overpay fees when traversing
969 // larger channels than the bottleneck. This may happen because
970 // when we were selecting those channels we were not aware how much value
971 // this path will transfer, and the relative fee for them
972 // might have been computed considering a larger value.
973 // Remember that we used these channels so that we don't rely
974 // on the same liquidity in future paths.
975 let mut prevented_redundant_path_selection = false;
976 for (payment_hop, _) in payment_path.hops.iter() {
977 let channel_liquidity_available_msat = bookkeeped_channels_liquidity_available_msat.get_mut(&payment_hop.short_channel_id).unwrap();
978 let mut spent_on_hop_msat = value_contribution_msat;
979 let next_hops_fee_msat = payment_hop.next_hops_fee_msat;
980 spent_on_hop_msat += next_hops_fee_msat;
981 if spent_on_hop_msat == *channel_liquidity_available_msat {
982 // If this path used all of this channel's available liquidity, we know
983 // this path will not be selected again in the next loop iteration.
984 prevented_redundant_path_selection = true;
986 *channel_liquidity_available_msat -= spent_on_hop_msat;
988 if !prevented_redundant_path_selection {
989 // If we weren't capped by hitting a liquidity limit on a channel in the path,
990 // we'll probably end up picking the same path again on the next iteration.
991 // Decrease the available liquidity of a hop in the middle of the path.
992 let victim_liquidity = bookkeeped_channels_liquidity_available_msat.get_mut(
993 &payment_path.hops[(payment_path.hops.len() - 1) / 2].0.short_channel_id).unwrap();
994 *victim_liquidity = 0;
997 // Track the total amount all our collected paths allow to send so that we:
998 // - know when to stop looking for more paths
999 // - know which of the hops are useless considering how much more sats we need
1000 // (contributes_sufficient_value)
1001 already_collected_value_msat += value_contribution_msat;
1003 payment_paths.push(payment_path);
1004 found_new_path = true;
1005 break 'path_construction;
1008 // If we found a path back to the payee, we shouldn't try to process it again. This is
1009 // the equivalent of the `elem.was_processed` check in
1010 // add_entries_to_cheapest_to_target_node!() (see comment there for more info).
1011 if pubkey == *payee { continue 'path_construction; }
1013 // Otherwise, since the current target node is not us,
1014 // keep "unrolling" the payment graph from payee to payer by
1015 // finding a way to reach the current target from the payer side.
1016 match network.get_nodes().get(&pubkey) {
1019 add_entries_to_cheapest_to_target_node!(node, &pubkey, lowest_fee_to_node, value_contribution_msat, path_htlc_minimum_msat);
1025 // If we don't support MPP, no use trying to gather more value ever.
1026 break 'paths_collection;
1030 // Stop either when the recommended value is reached or if no new path was found in this
1032 // In the latter case, making another path finding attempt won't help,
1033 // because we deterministically terminated the search due to low liquidity.
1034 if already_collected_value_msat >= recommended_value_msat || !found_new_path {
1035 break 'paths_collection;
1036 } else if found_new_path && already_collected_value_msat == final_value_msat && payment_paths.len() == 1 {
1037 // Further, if this was our first walk of the graph, and we weren't limited by an
1038 // htlc_minimum_msat, return immediately because this path should suffice. If we were
1039 // limited by an htlc_minimum_msat value, find another path with a higher value,
1040 // potentially allowing us to pay fees to meet the htlc_minimum on the new path while
1041 // still keeping a lower total fee than this path.
1042 if !hit_minimum_limit {
1043 break 'paths_collection;
1045 path_value_msat = recommended_value_msat;
1050 if payment_paths.len() == 0 {
1051 return Err(LightningError{err: "Failed to find a path to the given destination".to_owned(), action: ErrorAction::IgnoreError});
1054 if already_collected_value_msat < final_value_msat {
1055 return Err(LightningError{err: "Failed to find a sufficient route to the given destination".to_owned(), action: ErrorAction::IgnoreError});
1058 // Sort by total fees and take the best paths.
1059 payment_paths.sort_by_key(|path| path.get_total_fee_paid_msat());
1060 if payment_paths.len() > 50 {
1061 payment_paths.truncate(50);
1064 // Draw multiple sufficient routes by randomly combining the selected paths.
1065 let mut drawn_routes = Vec::new();
1066 for i in 0..payment_paths.len() {
1067 let mut cur_route = Vec::<PaymentPath>::new();
1068 let mut aggregate_route_value_msat = 0;
1071 // TODO: real random shuffle
1072 // Currently just starts with i_th and goes up to i-1_th in a looped way.
1073 let cur_payment_paths = [&payment_paths[i..], &payment_paths[..i]].concat();
1076 for payment_path in cur_payment_paths {
1077 cur_route.push(payment_path.clone());
1078 aggregate_route_value_msat += payment_path.get_value_msat();
1079 if aggregate_route_value_msat > final_value_msat {
1080 // Last path likely overpaid. Substract it from the most expensive
1081 // (in terms of proportional fee) path in this route and recompute fees.
1082 // This might be not the most economically efficient way, but fewer paths
1083 // also makes routing more reliable.
1084 let mut overpaid_value_msat = aggregate_route_value_msat - final_value_msat;
1086 // First, drop some expensive low-value paths entirely if possible.
1087 // Sort by value so that we drop many really-low values first, since
1088 // fewer paths is better: the payment is less likely to fail.
1089 // TODO: this could also be optimized by also sorting by feerate_per_sat_routed,
1090 // so that the sender pays less fees overall. And also htlc_minimum_msat.
1091 cur_route.sort_by_key(|path| path.get_value_msat());
1092 // We should make sure that at least 1 path left.
1093 let mut paths_left = cur_route.len();
1094 cur_route.retain(|path| {
1095 if paths_left == 1 {
1098 let mut keep = true;
1099 let path_value_msat = path.get_value_msat();
1100 if path_value_msat <= overpaid_value_msat {
1102 overpaid_value_msat -= path_value_msat;
1108 if overpaid_value_msat == 0 {
1112 assert!(cur_route.len() > 0);
1115 // Now, substract the overpaid value from the most-expensive path.
1116 // TODO: this could also be optimized by also sorting by feerate_per_sat_routed,
1117 // so that the sender pays less fees overall. And also htlc_minimum_msat.
1118 cur_route.sort_by_key(|path| { path.hops.iter().map(|hop| hop.0.channel_fees.proportional_millionths as u64).sum::<u64>() });
1119 let expensive_payment_path = cur_route.first_mut().unwrap();
1120 // We already dropped all the small channels above, meaning all the
1121 // remaining channels are larger than remaining overpaid_value_msat.
1122 // Thus, this can't be negative.
1123 let expensive_path_new_value_msat = expensive_payment_path.get_value_msat() - overpaid_value_msat;
1124 expensive_payment_path.update_value_and_recompute_fees(expensive_path_new_value_msat);
1128 drawn_routes.push(cur_route);
1132 // Select the best route by lowest total fee.
1133 drawn_routes.sort_by_key(|paths| paths.iter().map(|path| path.get_total_fee_paid_msat()).sum::<u64>());
1134 let mut selected_paths = Vec::<Vec<RouteHop>>::new();
1135 for payment_path in drawn_routes.first().unwrap() {
1136 selected_paths.push(payment_path.hops.iter().map(|(payment_hop, node_features)| {
1138 pubkey: payment_hop.pubkey,
1139 node_features: node_features.clone(),
1140 short_channel_id: payment_hop.short_channel_id,
1141 channel_features: payment_hop.channel_features.clone(),
1142 fee_msat: payment_hop.fee_msat,
1143 cltv_expiry_delta: payment_hop.cltv_expiry_delta,
1148 if let Some(features) = &payee_features {
1149 for path in selected_paths.iter_mut() {
1150 path.last_mut().unwrap().node_features = features.to_context();
1154 let route = Route { paths: selected_paths };
1155 log_trace!(logger, "Got route: {}", log_route!(route));
1161 use routing::router::{get_route, RouteHint, RouteHintHop, RoutingFees};
1162 use routing::network_graph::{NetworkGraph, NetGraphMsgHandler};
1163 use chain::transaction::OutPoint;
1164 use ln::features::{ChannelFeatures, InitFeatures, InvoiceFeatures, NodeFeatures};
1165 use ln::msgs::{ErrorAction, LightningError, OptionalField, UnsignedChannelAnnouncement, ChannelAnnouncement, RoutingMessageHandler,
1166 NodeAnnouncement, UnsignedNodeAnnouncement, ChannelUpdate, UnsignedChannelUpdate};
1167 use ln::channelmanager;
1168 use util::test_utils;
1169 use util::ser::Writeable;
1171 use bitcoin::hashes::sha256d::Hash as Sha256dHash;
1172 use bitcoin::hashes::Hash;
1173 use bitcoin::network::constants::Network;
1174 use bitcoin::blockdata::constants::genesis_block;
1175 use bitcoin::blockdata::script::Builder;
1176 use bitcoin::blockdata::opcodes;
1177 use bitcoin::blockdata::transaction::TxOut;
1181 use bitcoin::secp256k1::key::{PublicKey,SecretKey};
1182 use bitcoin::secp256k1::{Secp256k1, All};
1187 // Using the same keys for LN and BTC ids
1188 fn add_channel(net_graph_msg_handler: &NetGraphMsgHandler<Arc<test_utils::TestChainSource>, Arc<test_utils::TestLogger>>, secp_ctx: &Secp256k1<All>, node_1_privkey: &SecretKey,
1189 node_2_privkey: &SecretKey, features: ChannelFeatures, short_channel_id: u64) {
1190 let node_id_1 = PublicKey::from_secret_key(&secp_ctx, node_1_privkey);
1191 let node_id_2 = PublicKey::from_secret_key(&secp_ctx, node_2_privkey);
1193 let unsigned_announcement = UnsignedChannelAnnouncement {
1195 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1199 bitcoin_key_1: node_id_1,
1200 bitcoin_key_2: node_id_2,
1201 excess_data: Vec::new(),
1204 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1205 let valid_announcement = ChannelAnnouncement {
1206 node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
1207 node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
1208 bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
1209 bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
1210 contents: unsigned_announcement.clone(),
1212 match net_graph_msg_handler.handle_channel_announcement(&valid_announcement) {
1213 Ok(res) => assert!(res),
1218 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) {
1219 let msghash = hash_to_message!(&Sha256dHash::hash(&update.encode()[..])[..]);
1220 let valid_channel_update = ChannelUpdate {
1221 signature: secp_ctx.sign(&msghash, node_privkey),
1222 contents: update.clone()
1225 match net_graph_msg_handler.handle_channel_update(&valid_channel_update) {
1226 Ok(res) => assert!(res),
1231 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,
1232 features: NodeFeatures, timestamp: u32) {
1233 let node_id = PublicKey::from_secret_key(&secp_ctx, node_privkey);
1234 let unsigned_announcement = UnsignedNodeAnnouncement {
1240 addresses: Vec::new(),
1241 excess_address_data: Vec::new(),
1242 excess_data: Vec::new(),
1244 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1245 let valid_announcement = NodeAnnouncement {
1246 signature: secp_ctx.sign(&msghash, node_privkey),
1247 contents: unsigned_announcement.clone()
1250 match net_graph_msg_handler.handle_node_announcement(&valid_announcement) {
1256 fn get_nodes(secp_ctx: &Secp256k1<All>) -> (SecretKey, PublicKey, Vec<SecretKey>, Vec<PublicKey>) {
1257 let privkeys: Vec<SecretKey> = (2..10).map(|i| {
1258 SecretKey::from_slice(&hex::decode(format!("{:02}", i).repeat(32)).unwrap()[..]).unwrap()
1261 let pubkeys = privkeys.iter().map(|secret| PublicKey::from_secret_key(&secp_ctx, secret)).collect();
1263 let our_privkey = SecretKey::from_slice(&hex::decode("01".repeat(32)).unwrap()[..]).unwrap();
1264 let our_id = PublicKey::from_secret_key(&secp_ctx, &our_privkey);
1266 (our_privkey, our_id, privkeys, pubkeys)
1269 fn id_to_feature_flags(id: u8) -> Vec<u8> {
1270 // Set the feature flags to the id'th odd (ie non-required) feature bit so that we can
1271 // test for it later.
1272 let idx = (id - 1) * 2 + 1;
1274 vec![1 << (idx - 8*3), 0, 0, 0]
1275 } else if idx > 8*2 {
1276 vec![1 << (idx - 8*2), 0, 0]
1277 } else if idx > 8*1 {
1278 vec![1 << (idx - 8*1), 0]
1284 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>) {
1285 let secp_ctx = Secp256k1::new();
1286 let logger = Arc::new(test_utils::TestLogger::new());
1287 let chain_monitor = Arc::new(test_utils::TestChainSource::new(Network::Testnet));
1288 let net_graph_msg_handler = NetGraphMsgHandler::new(genesis_block(Network::Testnet).header.block_hash(), None, Arc::clone(&logger));
1289 // Build network from our_id to node7:
1291 // -1(1)2- node0 -1(3)2-
1293 // our_id -1(12)2- node7 -1(13)2--- node2
1295 // -1(2)2- node1 -1(4)2-
1298 // chan1 1-to-2: disabled
1299 // chan1 2-to-1: enabled, 0 fee
1301 // chan2 1-to-2: enabled, ignored fee
1302 // chan2 2-to-1: enabled, 0 fee
1304 // chan3 1-to-2: enabled, 0 fee
1305 // chan3 2-to-1: enabled, 100 msat fee
1307 // chan4 1-to-2: enabled, 100% fee
1308 // chan4 2-to-1: enabled, 0 fee
1310 // chan12 1-to-2: enabled, ignored fee
1311 // chan12 2-to-1: enabled, 0 fee
1313 // chan13 1-to-2: enabled, 200% fee
1314 // chan13 2-to-1: enabled, 0 fee
1317 // -1(5)2- node3 -1(8)2--
1321 // node2--1(6)2- node4 -1(9)2--- node6 (not in global route map)
1323 // -1(7)2- node5 -1(10)2-
1325 // chan5 1-to-2: enabled, 100 msat fee
1326 // chan5 2-to-1: enabled, 0 fee
1328 // chan6 1-to-2: enabled, 0 fee
1329 // chan6 2-to-1: enabled, 0 fee
1331 // chan7 1-to-2: enabled, 100% fee
1332 // chan7 2-to-1: enabled, 0 fee
1334 // chan8 1-to-2: enabled, variable fee (0 then 1000 msat)
1335 // chan8 2-to-1: enabled, 0 fee
1337 // chan9 1-to-2: enabled, 1001 msat fee
1338 // chan9 2-to-1: enabled, 0 fee
1340 // chan10 1-to-2: enabled, 0 fee
1341 // chan10 2-to-1: enabled, 0 fee
1343 // chan11 1-to-2: enabled, 0 fee
1344 // chan11 2-to-1: enabled, 0 fee
1346 let (our_privkey, _, privkeys, _) = get_nodes(&secp_ctx);
1348 add_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, &privkeys[0], ChannelFeatures::from_le_bytes(id_to_feature_flags(1)), 1);
1349 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
1350 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1351 short_channel_id: 1,
1354 cltv_expiry_delta: 0,
1355 htlc_minimum_msat: 0,
1356 htlc_maximum_msat: OptionalField::Absent,
1358 fee_proportional_millionths: 0,
1359 excess_data: Vec::new()
1362 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[0], NodeFeatures::from_le_bytes(id_to_feature_flags(1)), 0);
1364 add_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, &privkeys[1], ChannelFeatures::from_le_bytes(id_to_feature_flags(2)), 2);
1365 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
1366 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1367 short_channel_id: 2,
1370 cltv_expiry_delta: u16::max_value(),
1371 htlc_minimum_msat: 0,
1372 htlc_maximum_msat: OptionalField::Absent,
1373 fee_base_msat: u32::max_value(),
1374 fee_proportional_millionths: u32::max_value(),
1375 excess_data: Vec::new()
1377 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
1378 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1379 short_channel_id: 2,
1382 cltv_expiry_delta: 0,
1383 htlc_minimum_msat: 0,
1384 htlc_maximum_msat: OptionalField::Absent,
1386 fee_proportional_millionths: 0,
1387 excess_data: Vec::new()
1390 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[1], NodeFeatures::from_le_bytes(id_to_feature_flags(2)), 0);
1392 add_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, &privkeys[7], ChannelFeatures::from_le_bytes(id_to_feature_flags(12)), 12);
1393 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
1394 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1395 short_channel_id: 12,
1398 cltv_expiry_delta: u16::max_value(),
1399 htlc_minimum_msat: 0,
1400 htlc_maximum_msat: OptionalField::Absent,
1401 fee_base_msat: u32::max_value(),
1402 fee_proportional_millionths: u32::max_value(),
1403 excess_data: Vec::new()
1405 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
1406 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1407 short_channel_id: 12,
1410 cltv_expiry_delta: 0,
1411 htlc_minimum_msat: 0,
1412 htlc_maximum_msat: OptionalField::Absent,
1414 fee_proportional_millionths: 0,
1415 excess_data: Vec::new()
1418 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[7], NodeFeatures::from_le_bytes(id_to_feature_flags(8)), 0);
1420 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], &privkeys[2], ChannelFeatures::from_le_bytes(id_to_feature_flags(3)), 3);
1421 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
1422 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1423 short_channel_id: 3,
1426 cltv_expiry_delta: (3 << 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[2], UnsignedChannelUpdate {
1434 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1435 short_channel_id: 3,
1438 cltv_expiry_delta: (3 << 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_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], &privkeys[2], ChannelFeatures::from_le_bytes(id_to_feature_flags(4)), 4);
1447 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
1448 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1449 short_channel_id: 4,
1452 cltv_expiry_delta: (4 << 8) | 1,
1453 htlc_minimum_msat: 0,
1454 htlc_maximum_msat: OptionalField::Absent,
1456 fee_proportional_millionths: 1000000,
1457 excess_data: Vec::new()
1459 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
1460 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1461 short_channel_id: 4,
1464 cltv_expiry_delta: (4 << 8) | 2,
1465 htlc_minimum_msat: 0,
1466 htlc_maximum_msat: OptionalField::Absent,
1468 fee_proportional_millionths: 0,
1469 excess_data: Vec::new()
1472 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], &privkeys[2], ChannelFeatures::from_le_bytes(id_to_feature_flags(13)), 13);
1473 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
1474 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1475 short_channel_id: 13,
1478 cltv_expiry_delta: (13 << 8) | 1,
1479 htlc_minimum_msat: 0,
1480 htlc_maximum_msat: OptionalField::Absent,
1482 fee_proportional_millionths: 2000000,
1483 excess_data: Vec::new()
1485 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
1486 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1487 short_channel_id: 13,
1490 cltv_expiry_delta: (13 << 8) | 2,
1491 htlc_minimum_msat: 0,
1492 htlc_maximum_msat: OptionalField::Absent,
1494 fee_proportional_millionths: 0,
1495 excess_data: Vec::new()
1498 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[2], NodeFeatures::from_le_bytes(id_to_feature_flags(3)), 0);
1500 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], &privkeys[4], ChannelFeatures::from_le_bytes(id_to_feature_flags(6)), 6);
1501 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
1502 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1503 short_channel_id: 6,
1506 cltv_expiry_delta: (6 << 8) | 1,
1507 htlc_minimum_msat: 0,
1508 htlc_maximum_msat: OptionalField::Absent,
1510 fee_proportional_millionths: 0,
1511 excess_data: Vec::new()
1513 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
1514 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1515 short_channel_id: 6,
1518 cltv_expiry_delta: (6 << 8) | 2,
1519 htlc_minimum_msat: 0,
1520 htlc_maximum_msat: OptionalField::Absent,
1522 fee_proportional_millionths: 0,
1523 excess_data: Vec::new(),
1526 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(11)), 11);
1527 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
1528 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1529 short_channel_id: 11,
1532 cltv_expiry_delta: (11 << 8) | 1,
1533 htlc_minimum_msat: 0,
1534 htlc_maximum_msat: OptionalField::Absent,
1536 fee_proportional_millionths: 0,
1537 excess_data: Vec::new()
1539 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[3], UnsignedChannelUpdate {
1540 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1541 short_channel_id: 11,
1544 cltv_expiry_delta: (11 << 8) | 2,
1545 htlc_minimum_msat: 0,
1546 htlc_maximum_msat: OptionalField::Absent,
1548 fee_proportional_millionths: 0,
1549 excess_data: Vec::new()
1552 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[4], NodeFeatures::from_le_bytes(id_to_feature_flags(5)), 0);
1554 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[3], NodeFeatures::from_le_bytes(id_to_feature_flags(4)), 0);
1556 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], &privkeys[5], ChannelFeatures::from_le_bytes(id_to_feature_flags(7)), 7);
1557 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
1558 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1559 short_channel_id: 7,
1562 cltv_expiry_delta: (7 << 8) | 1,
1563 htlc_minimum_msat: 0,
1564 htlc_maximum_msat: OptionalField::Absent,
1566 fee_proportional_millionths: 1000000,
1567 excess_data: Vec::new()
1569 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[5], UnsignedChannelUpdate {
1570 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1571 short_channel_id: 7,
1574 cltv_expiry_delta: (7 << 8) | 2,
1575 htlc_minimum_msat: 0,
1576 htlc_maximum_msat: OptionalField::Absent,
1578 fee_proportional_millionths: 0,
1579 excess_data: Vec::new()
1582 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[5], NodeFeatures::from_le_bytes(id_to_feature_flags(6)), 0);
1584 (secp_ctx, net_graph_msg_handler, chain_monitor, logger)
1588 fn simple_route_test() {
1589 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
1590 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
1592 // Simple route to 2 via 1
1594 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)) {
1595 assert_eq!(err, "Cannot send a payment of 0 msat");
1596 } else { panic!(); }
1598 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();
1599 assert_eq!(route.paths[0].len(), 2);
1601 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
1602 assert_eq!(route.paths[0][0].short_channel_id, 2);
1603 assert_eq!(route.paths[0][0].fee_msat, 100);
1604 assert_eq!(route.paths[0][0].cltv_expiry_delta, (4 << 8) | 1);
1605 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
1606 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
1608 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
1609 assert_eq!(route.paths[0][1].short_channel_id, 4);
1610 assert_eq!(route.paths[0][1].fee_msat, 100);
1611 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
1612 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
1613 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
1617 fn invalid_first_hop_test() {
1618 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
1619 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
1621 // Simple route to 2 via 1
1623 let our_chans = vec![channelmanager::ChannelDetails {
1624 channel_id: [0; 32],
1625 funding_txo: Some(OutPoint { txid: bitcoin::Txid::from_slice(&[0; 32]).unwrap(), index: 0 }),
1626 short_channel_id: Some(2),
1627 remote_network_id: our_id,
1628 counterparty_features: InitFeatures::from_le_bytes(vec![0b11]),
1629 channel_value_satoshis: 100000,
1631 outbound_capacity_msat: 100000,
1632 inbound_capacity_msat: 100000,
1633 is_outbound: true, is_funding_locked: true,
1634 is_usable: true, is_public: true,
1635 counterparty_forwarding_info: None,
1638 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)) {
1639 assert_eq!(err, "First hop cannot have our_node_id as a destination.");
1640 } else { panic!(); }
1642 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();
1643 assert_eq!(route.paths[0].len(), 2);
1647 fn htlc_minimum_test() {
1648 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
1649 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
1651 // Simple route to 2 via 1
1653 // Disable other paths
1654 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
1655 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1656 short_channel_id: 12,
1658 flags: 2, // to disable
1659 cltv_expiry_delta: 0,
1660 htlc_minimum_msat: 0,
1661 htlc_maximum_msat: OptionalField::Absent,
1663 fee_proportional_millionths: 0,
1664 excess_data: Vec::new()
1666 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
1667 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1668 short_channel_id: 3,
1670 flags: 2, // to disable
1671 cltv_expiry_delta: 0,
1672 htlc_minimum_msat: 0,
1673 htlc_maximum_msat: OptionalField::Absent,
1675 fee_proportional_millionths: 0,
1676 excess_data: Vec::new()
1678 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
1679 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1680 short_channel_id: 13,
1682 flags: 2, // to disable
1683 cltv_expiry_delta: 0,
1684 htlc_minimum_msat: 0,
1685 htlc_maximum_msat: OptionalField::Absent,
1687 fee_proportional_millionths: 0,
1688 excess_data: Vec::new()
1690 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
1691 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1692 short_channel_id: 6,
1694 flags: 2, // to disable
1695 cltv_expiry_delta: 0,
1696 htlc_minimum_msat: 0,
1697 htlc_maximum_msat: OptionalField::Absent,
1699 fee_proportional_millionths: 0,
1700 excess_data: Vec::new()
1702 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
1703 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1704 short_channel_id: 7,
1706 flags: 2, // to disable
1707 cltv_expiry_delta: 0,
1708 htlc_minimum_msat: 0,
1709 htlc_maximum_msat: OptionalField::Absent,
1711 fee_proportional_millionths: 0,
1712 excess_data: Vec::new()
1715 // Check against amount_to_transfer_over_msat.
1716 // Set minimal HTLC of 200_000_000 msat.
1717 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
1718 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1719 short_channel_id: 2,
1722 cltv_expiry_delta: 0,
1723 htlc_minimum_msat: 200_000_000,
1724 htlc_maximum_msat: OptionalField::Absent,
1726 fee_proportional_millionths: 0,
1727 excess_data: Vec::new()
1730 // Second hop only allows to forward 199_999_999 at most, thus not allowing the first hop to
1732 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
1733 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1734 short_channel_id: 4,
1737 cltv_expiry_delta: 0,
1738 htlc_minimum_msat: 0,
1739 htlc_maximum_msat: OptionalField::Present(199_999_999),
1741 fee_proportional_millionths: 0,
1742 excess_data: Vec::new()
1745 // Not possible to send 199_999_999, because the minimum on channel=2 is 200_000_000.
1746 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)) {
1747 assert_eq!(err, "Failed to find a path to the given destination");
1748 } else { panic!(); }
1750 // Lift the restriction on the first hop.
1751 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
1752 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1753 short_channel_id: 2,
1756 cltv_expiry_delta: 0,
1757 htlc_minimum_msat: 0,
1758 htlc_maximum_msat: OptionalField::Absent,
1760 fee_proportional_millionths: 0,
1761 excess_data: Vec::new()
1764 // A payment above the minimum should pass
1765 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();
1766 assert_eq!(route.paths[0].len(), 2);
1770 fn htlc_minimum_overpay_test() {
1771 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
1772 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
1774 // A route to node#2 via two paths.
1775 // One path allows transferring 35-40 sats, another one also allows 35-40 sats.
1776 // Thus, they can't send 60 without overpaying.
1777 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
1778 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1779 short_channel_id: 2,
1782 cltv_expiry_delta: 0,
1783 htlc_minimum_msat: 35_000,
1784 htlc_maximum_msat: OptionalField::Present(40_000),
1786 fee_proportional_millionths: 0,
1787 excess_data: Vec::new()
1789 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
1790 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1791 short_channel_id: 12,
1794 cltv_expiry_delta: 0,
1795 htlc_minimum_msat: 35_000,
1796 htlc_maximum_msat: OptionalField::Present(40_000),
1798 fee_proportional_millionths: 0,
1799 excess_data: Vec::new()
1803 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
1804 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1805 short_channel_id: 13,
1808 cltv_expiry_delta: 0,
1809 htlc_minimum_msat: 0,
1810 htlc_maximum_msat: OptionalField::Absent,
1812 fee_proportional_millionths: 0,
1813 excess_data: Vec::new()
1815 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
1816 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1817 short_channel_id: 4,
1820 cltv_expiry_delta: 0,
1821 htlc_minimum_msat: 0,
1822 htlc_maximum_msat: OptionalField::Absent,
1824 fee_proportional_millionths: 0,
1825 excess_data: Vec::new()
1828 // Disable other paths
1829 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
1830 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1831 short_channel_id: 1,
1833 flags: 2, // to disable
1834 cltv_expiry_delta: 0,
1835 htlc_minimum_msat: 0,
1836 htlc_maximum_msat: OptionalField::Absent,
1838 fee_proportional_millionths: 0,
1839 excess_data: Vec::new()
1842 let route = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2],
1843 Some(InvoiceFeatures::known()), None, &Vec::new(), 60_000, 42, Arc::clone(&logger)).unwrap();
1844 // Overpay fees to hit htlc_minimum_msat.
1845 let overpaid_fees = route.paths[0][0].fee_msat + route.paths[1][0].fee_msat;
1846 // TODO: this could be better balanced to overpay 10k and not 15k.
1847 assert_eq!(overpaid_fees, 15_000);
1849 // Now, test that if there are 2 paths, a "cheaper" by fee path wouldn't be prioritized
1850 // while taking even more fee to match htlc_minimum_msat.
1851 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
1852 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1853 short_channel_id: 12,
1856 cltv_expiry_delta: 0,
1857 htlc_minimum_msat: 65_000,
1858 htlc_maximum_msat: OptionalField::Present(80_000),
1860 fee_proportional_millionths: 0,
1861 excess_data: Vec::new()
1863 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
1864 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1865 short_channel_id: 2,
1868 cltv_expiry_delta: 0,
1869 htlc_minimum_msat: 0,
1870 htlc_maximum_msat: OptionalField::Absent,
1872 fee_proportional_millionths: 0,
1873 excess_data: Vec::new()
1875 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
1876 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1877 short_channel_id: 4,
1880 cltv_expiry_delta: 0,
1881 htlc_minimum_msat: 0,
1882 htlc_maximum_msat: OptionalField::Absent,
1884 fee_proportional_millionths: 100_000,
1885 excess_data: Vec::new()
1888 let route = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2],
1889 Some(InvoiceFeatures::known()), None, &Vec::new(), 60_000, 42, Arc::clone(&logger)).unwrap();
1890 // Fine to overpay for htlc_minimum_msat if it allows us to save fee.
1891 assert_eq!(route.paths.len(), 1);
1892 assert_eq!(route.paths[0][0].short_channel_id, 12);
1893 let fees = route.paths[0][0].fee_msat;
1894 assert_eq!(fees, 5_000);
1896 let route = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2],
1897 Some(InvoiceFeatures::known()), None, &Vec::new(), 50_000, 42, Arc::clone(&logger)).unwrap();
1898 // Not fine to overpay for htlc_minimum_msat if it requires paying more than fee on
1899 // the other channel.
1900 assert_eq!(route.paths.len(), 1);
1901 assert_eq!(route.paths[0][0].short_channel_id, 2);
1902 let fees = route.paths[0][0].fee_msat;
1903 assert_eq!(fees, 5_000);
1907 fn disable_channels_test() {
1908 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
1909 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
1911 // // Disable channels 4 and 12 by flags=2
1912 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
1913 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1914 short_channel_id: 4,
1916 flags: 2, // to disable
1917 cltv_expiry_delta: 0,
1918 htlc_minimum_msat: 0,
1919 htlc_maximum_msat: OptionalField::Absent,
1921 fee_proportional_millionths: 0,
1922 excess_data: Vec::new()
1924 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
1925 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1926 short_channel_id: 12,
1928 flags: 2, // to disable
1929 cltv_expiry_delta: 0,
1930 htlc_minimum_msat: 0,
1931 htlc_maximum_msat: OptionalField::Absent,
1933 fee_proportional_millionths: 0,
1934 excess_data: Vec::new()
1937 // If all the channels require some features we don't understand, route should fail
1938 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)) {
1939 assert_eq!(err, "Failed to find a path to the given destination");
1940 } else { panic!(); }
1942 // If we specify a channel to node7, that overrides our local channel view and that gets used
1943 let our_chans = vec![channelmanager::ChannelDetails {
1944 channel_id: [0; 32],
1945 funding_txo: Some(OutPoint { txid: bitcoin::Txid::from_slice(&[0; 32]).unwrap(), index: 0 }),
1946 short_channel_id: Some(42),
1947 remote_network_id: nodes[7].clone(),
1948 counterparty_features: InitFeatures::from_le_bytes(vec![0b11]),
1949 channel_value_satoshis: 0,
1951 outbound_capacity_msat: 250_000_000,
1952 inbound_capacity_msat: 0,
1953 is_outbound: true, is_funding_locked: true,
1954 is_usable: true, is_public: true,
1955 counterparty_forwarding_info: None,
1957 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();
1958 assert_eq!(route.paths[0].len(), 2);
1960 assert_eq!(route.paths[0][0].pubkey, nodes[7]);
1961 assert_eq!(route.paths[0][0].short_channel_id, 42);
1962 assert_eq!(route.paths[0][0].fee_msat, 200);
1963 assert_eq!(route.paths[0][0].cltv_expiry_delta, (13 << 8) | 1);
1964 assert_eq!(route.paths[0][0].node_features.le_flags(), &vec![0b11]); // it should also override our view of their features
1965 assert_eq!(route.paths[0][0].channel_features.le_flags(), &Vec::<u8>::new()); // No feature flags will meet the relevant-to-channel conversion
1967 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
1968 assert_eq!(route.paths[0][1].short_channel_id, 13);
1969 assert_eq!(route.paths[0][1].fee_msat, 100);
1970 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
1971 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
1972 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(13));
1976 fn disable_node_test() {
1977 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
1978 let (_, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
1980 // Disable nodes 1, 2, and 8 by requiring unknown feature bits
1981 let mut unknown_features = NodeFeatures::known();
1982 unknown_features.set_required_unknown_bits();
1983 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[0], unknown_features.clone(), 1);
1984 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[1], unknown_features.clone(), 1);
1985 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[7], unknown_features.clone(), 1);
1987 // If all nodes require some features we don't understand, route should fail
1988 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)) {
1989 assert_eq!(err, "Failed to find a path to the given destination");
1990 } else { panic!(); }
1992 // If we specify a channel to node7, that overrides our local channel view and that gets used
1993 let our_chans = vec![channelmanager::ChannelDetails {
1994 channel_id: [0; 32],
1995 funding_txo: Some(OutPoint { txid: bitcoin::Txid::from_slice(&[0; 32]).unwrap(), index: 0 }),
1996 short_channel_id: Some(42),
1997 remote_network_id: nodes[7].clone(),
1998 counterparty_features: InitFeatures::from_le_bytes(vec![0b11]),
1999 channel_value_satoshis: 0,
2001 outbound_capacity_msat: 250_000_000,
2002 inbound_capacity_msat: 0,
2003 is_outbound: true, is_funding_locked: true,
2004 is_usable: true, is_public: true,
2005 counterparty_forwarding_info: None,
2007 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();
2008 assert_eq!(route.paths[0].len(), 2);
2010 assert_eq!(route.paths[0][0].pubkey, nodes[7]);
2011 assert_eq!(route.paths[0][0].short_channel_id, 42);
2012 assert_eq!(route.paths[0][0].fee_msat, 200);
2013 assert_eq!(route.paths[0][0].cltv_expiry_delta, (13 << 8) | 1);
2014 assert_eq!(route.paths[0][0].node_features.le_flags(), &vec![0b11]); // it should also override our view of their features
2015 assert_eq!(route.paths[0][0].channel_features.le_flags(), &Vec::<u8>::new()); // No feature flags will meet the relevant-to-channel conversion
2017 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2018 assert_eq!(route.paths[0][1].short_channel_id, 13);
2019 assert_eq!(route.paths[0][1].fee_msat, 100);
2020 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
2021 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2022 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(13));
2024 // Note that we don't test disabling node 3 and failing to route to it, as we (somewhat
2025 // naively) assume that the user checked the feature bits on the invoice, which override
2026 // the node_announcement.
2030 fn our_chans_test() {
2031 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
2032 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
2034 // Route to 1 via 2 and 3 because our channel to 1 is disabled
2035 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();
2036 assert_eq!(route.paths[0].len(), 3);
2038 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
2039 assert_eq!(route.paths[0][0].short_channel_id, 2);
2040 assert_eq!(route.paths[0][0].fee_msat, 200);
2041 assert_eq!(route.paths[0][0].cltv_expiry_delta, (4 << 8) | 1);
2042 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
2043 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
2045 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2046 assert_eq!(route.paths[0][1].short_channel_id, 4);
2047 assert_eq!(route.paths[0][1].fee_msat, 100);
2048 assert_eq!(route.paths[0][1].cltv_expiry_delta, (3 << 8) | 2);
2049 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2050 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
2052 assert_eq!(route.paths[0][2].pubkey, nodes[0]);
2053 assert_eq!(route.paths[0][2].short_channel_id, 3);
2054 assert_eq!(route.paths[0][2].fee_msat, 100);
2055 assert_eq!(route.paths[0][2].cltv_expiry_delta, 42);
2056 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(1));
2057 assert_eq!(route.paths[0][2].channel_features.le_flags(), &id_to_feature_flags(3));
2059 // If we specify a channel to node7, that overrides our local channel view and that gets used
2060 let our_chans = vec![channelmanager::ChannelDetails {
2061 channel_id: [0; 32],
2062 funding_txo: Some(OutPoint { txid: bitcoin::Txid::from_slice(&[0; 32]).unwrap(), index: 0 }),
2063 short_channel_id: Some(42),
2064 remote_network_id: nodes[7].clone(),
2065 counterparty_features: InitFeatures::from_le_bytes(vec![0b11]),
2066 channel_value_satoshis: 0,
2068 outbound_capacity_msat: 250_000_000,
2069 inbound_capacity_msat: 0,
2070 is_outbound: true, is_funding_locked: true,
2071 is_usable: true, is_public: true,
2072 counterparty_forwarding_info: None,
2074 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();
2075 assert_eq!(route.paths[0].len(), 2);
2077 assert_eq!(route.paths[0][0].pubkey, nodes[7]);
2078 assert_eq!(route.paths[0][0].short_channel_id, 42);
2079 assert_eq!(route.paths[0][0].fee_msat, 200);
2080 assert_eq!(route.paths[0][0].cltv_expiry_delta, (13 << 8) | 1);
2081 assert_eq!(route.paths[0][0].node_features.le_flags(), &vec![0b11]);
2082 assert_eq!(route.paths[0][0].channel_features.le_flags(), &Vec::<u8>::new()); // No feature flags will meet the relevant-to-channel conversion
2084 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2085 assert_eq!(route.paths[0][1].short_channel_id, 13);
2086 assert_eq!(route.paths[0][1].fee_msat, 100);
2087 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
2088 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2089 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(13));
2092 fn last_hops(nodes: &Vec<PublicKey>) -> Vec<RouteHint> {
2093 let zero_fees = RoutingFees {
2095 proportional_millionths: 0,
2097 vec![RouteHint(vec![RouteHintHop {
2098 src_node_id: nodes[3].clone(),
2099 short_channel_id: 8,
2101 cltv_expiry_delta: (8 << 8) | 1,
2102 htlc_minimum_msat: None,
2103 htlc_maximum_msat: None,
2104 }]), RouteHint(vec![RouteHintHop {
2105 src_node_id: nodes[4].clone(),
2106 short_channel_id: 9,
2109 proportional_millionths: 0,
2111 cltv_expiry_delta: (9 << 8) | 1,
2112 htlc_minimum_msat: None,
2113 htlc_maximum_msat: None,
2114 }]), RouteHint(vec![RouteHintHop {
2115 src_node_id: nodes[5].clone(),
2116 short_channel_id: 10,
2118 cltv_expiry_delta: (10 << 8) | 1,
2119 htlc_minimum_msat: None,
2120 htlc_maximum_msat: None,
2125 fn last_hops_test() {
2126 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
2127 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
2129 // Simple test across 2, 3, 5, and 4 via a last_hop channel
2131 // First check that last hop can't have its source as the payee.
2132 let invalid_last_hop = RouteHint(vec![RouteHintHop {
2133 src_node_id: nodes[6],
2134 short_channel_id: 8,
2137 proportional_millionths: 0,
2139 cltv_expiry_delta: (8 << 8) | 1,
2140 htlc_minimum_msat: None,
2141 htlc_maximum_msat: None,
2144 let mut invalid_last_hops = last_hops(&nodes);
2145 invalid_last_hops.push(invalid_last_hop);
2147 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)) {
2148 assert_eq!(err, "Last hop cannot have a payee as a source.");
2149 } else { panic!(); }
2152 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();
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, 100);
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, 0);
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, 100);
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 our_chans_last_hop_connect_test() {
2195 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
2196 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
2198 // Simple test with outbound channel to 4 to test that last_hops and first_hops connect
2199 let our_chans = vec![channelmanager::ChannelDetails {
2200 channel_id: [0; 32],
2201 funding_txo: Some(OutPoint { txid: bitcoin::Txid::from_slice(&[0; 32]).unwrap(), index: 0 }),
2202 short_channel_id: Some(42),
2203 remote_network_id: nodes[3].clone(),
2204 counterparty_features: InitFeatures::from_le_bytes(vec![0b11]),
2205 channel_value_satoshis: 0,
2207 outbound_capacity_msat: 250_000_000,
2208 inbound_capacity_msat: 0,
2209 is_outbound: true, is_funding_locked: true,
2210 is_usable: true, is_public: true,
2211 counterparty_forwarding_info: None,
2213 let mut last_hops = last_hops(&nodes);
2214 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();
2215 assert_eq!(route.paths[0].len(), 2);
2217 assert_eq!(route.paths[0][0].pubkey, nodes[3]);
2218 assert_eq!(route.paths[0][0].short_channel_id, 42);
2219 assert_eq!(route.paths[0][0].fee_msat, 0);
2220 assert_eq!(route.paths[0][0].cltv_expiry_delta, (8 << 8) | 1);
2221 assert_eq!(route.paths[0][0].node_features.le_flags(), &vec![0b11]);
2222 assert_eq!(route.paths[0][0].channel_features.le_flags(), &Vec::<u8>::new()); // No feature flags will meet the relevant-to-channel conversion
2224 assert_eq!(route.paths[0][1].pubkey, nodes[6]);
2225 assert_eq!(route.paths[0][1].short_channel_id, 8);
2226 assert_eq!(route.paths[0][1].fee_msat, 100);
2227 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
2228 assert_eq!(route.paths[0][1].node_features.le_flags(), &Vec::<u8>::new()); // We dont pass flags in from invoices yet
2229 assert_eq!(route.paths[0][1].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
2231 last_hops[0].0[0].fees.base_msat = 1000;
2233 // Revert to via 6 as the fee on 8 goes up
2234 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();
2235 assert_eq!(route.paths[0].len(), 4);
2237 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
2238 assert_eq!(route.paths[0][0].short_channel_id, 2);
2239 assert_eq!(route.paths[0][0].fee_msat, 200); // fee increased as its % of value transferred across node
2240 assert_eq!(route.paths[0][0].cltv_expiry_delta, (4 << 8) | 1);
2241 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
2242 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
2244 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2245 assert_eq!(route.paths[0][1].short_channel_id, 4);
2246 assert_eq!(route.paths[0][1].fee_msat, 100);
2247 assert_eq!(route.paths[0][1].cltv_expiry_delta, (7 << 8) | 1);
2248 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2249 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
2251 assert_eq!(route.paths[0][2].pubkey, nodes[5]);
2252 assert_eq!(route.paths[0][2].short_channel_id, 7);
2253 assert_eq!(route.paths[0][2].fee_msat, 0);
2254 assert_eq!(route.paths[0][2].cltv_expiry_delta, (10 << 8) | 1);
2255 // If we have a peer in the node map, we'll use their features here since we don't have
2256 // a way of figuring out their features from the invoice:
2257 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(6));
2258 assert_eq!(route.paths[0][2].channel_features.le_flags(), &id_to_feature_flags(7));
2260 assert_eq!(route.paths[0][3].pubkey, nodes[6]);
2261 assert_eq!(route.paths[0][3].short_channel_id, 10);
2262 assert_eq!(route.paths[0][3].fee_msat, 100);
2263 assert_eq!(route.paths[0][3].cltv_expiry_delta, 42);
2264 assert_eq!(route.paths[0][3].node_features.le_flags(), &Vec::<u8>::new()); // We dont pass flags in from invoices yet
2265 assert_eq!(route.paths[0][3].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
2267 // ...but still use 8 for larger payments as 6 has a variable feerate
2268 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();
2269 assert_eq!(route.paths[0].len(), 5);
2271 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
2272 assert_eq!(route.paths[0][0].short_channel_id, 2);
2273 assert_eq!(route.paths[0][0].fee_msat, 3000);
2274 assert_eq!(route.paths[0][0].cltv_expiry_delta, (4 << 8) | 1);
2275 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
2276 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
2278 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2279 assert_eq!(route.paths[0][1].short_channel_id, 4);
2280 assert_eq!(route.paths[0][1].fee_msat, 0);
2281 assert_eq!(route.paths[0][1].cltv_expiry_delta, (6 << 8) | 1);
2282 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2283 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
2285 assert_eq!(route.paths[0][2].pubkey, nodes[4]);
2286 assert_eq!(route.paths[0][2].short_channel_id, 6);
2287 assert_eq!(route.paths[0][2].fee_msat, 0);
2288 assert_eq!(route.paths[0][2].cltv_expiry_delta, (11 << 8) | 1);
2289 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(5));
2290 assert_eq!(route.paths[0][2].channel_features.le_flags(), &id_to_feature_flags(6));
2292 assert_eq!(route.paths[0][3].pubkey, nodes[3]);
2293 assert_eq!(route.paths[0][3].short_channel_id, 11);
2294 assert_eq!(route.paths[0][3].fee_msat, 1000);
2295 assert_eq!(route.paths[0][3].cltv_expiry_delta, (8 << 8) | 1);
2296 // If we have a peer in the node map, we'll use their features here since we don't have
2297 // a way of figuring out their features from the invoice:
2298 assert_eq!(route.paths[0][3].node_features.le_flags(), &id_to_feature_flags(4));
2299 assert_eq!(route.paths[0][3].channel_features.le_flags(), &id_to_feature_flags(11));
2301 assert_eq!(route.paths[0][4].pubkey, nodes[6]);
2302 assert_eq!(route.paths[0][4].short_channel_id, 8);
2303 assert_eq!(route.paths[0][4].fee_msat, 2000);
2304 assert_eq!(route.paths[0][4].cltv_expiry_delta, 42);
2305 assert_eq!(route.paths[0][4].node_features.le_flags(), &Vec::<u8>::new()); // We dont pass flags in from invoices yet
2306 assert_eq!(route.paths[0][4].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
2310 fn unannounced_path_test() {
2311 // We should be able to send a payment to a destination without any help of a routing graph
2312 // if we have a channel with a common counterparty that appears in the first and last hop
2314 let source_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&hex::decode(format!("{:02}", 41).repeat(32)).unwrap()[..]).unwrap());
2315 let middle_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&hex::decode(format!("{:02}", 42).repeat(32)).unwrap()[..]).unwrap());
2316 let target_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&hex::decode(format!("{:02}", 43).repeat(32)).unwrap()[..]).unwrap());
2318 // If we specify a channel to a middle hop, that overrides our local channel view and that gets used
2319 let last_hops = RouteHint(vec![RouteHintHop {
2320 src_node_id: middle_node_id,
2321 short_channel_id: 8,
2324 proportional_millionths: 0,
2326 cltv_expiry_delta: (8 << 8) | 1,
2327 htlc_minimum_msat: None,
2328 htlc_maximum_msat: None,
2330 let our_chans = vec![channelmanager::ChannelDetails {
2331 channel_id: [0; 32],
2332 funding_txo: Some(OutPoint { txid: bitcoin::Txid::from_slice(&[0; 32]).unwrap(), index: 0 }),
2333 short_channel_id: Some(42),
2334 remote_network_id: middle_node_id,
2335 counterparty_features: InitFeatures::from_le_bytes(vec![0b11]),
2336 channel_value_satoshis: 100000,
2338 outbound_capacity_msat: 100000,
2339 inbound_capacity_msat: 100000,
2340 is_outbound: true, is_funding_locked: true,
2341 is_usable: true, is_public: true,
2342 counterparty_forwarding_info: None,
2344 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<_>>()), &vec![&last_hops], 100, 42, Arc::new(test_utils::TestLogger::new())).unwrap();
2346 assert_eq!(route.paths[0].len(), 2);
2348 assert_eq!(route.paths[0][0].pubkey, middle_node_id);
2349 assert_eq!(route.paths[0][0].short_channel_id, 42);
2350 assert_eq!(route.paths[0][0].fee_msat, 1000);
2351 assert_eq!(route.paths[0][0].cltv_expiry_delta, (8 << 8) | 1);
2352 assert_eq!(route.paths[0][0].node_features.le_flags(), &[0b11]);
2353 assert_eq!(route.paths[0][0].channel_features.le_flags(), &[0; 0]); // We can't learn any flags from invoices, sadly
2355 assert_eq!(route.paths[0][1].pubkey, target_node_id);
2356 assert_eq!(route.paths[0][1].short_channel_id, 8);
2357 assert_eq!(route.paths[0][1].fee_msat, 100);
2358 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
2359 assert_eq!(route.paths[0][1].node_features.le_flags(), &[0; 0]); // We dont pass flags in from invoices yet
2360 assert_eq!(route.paths[0][1].channel_features.le_flags(), &[0; 0]); // We can't learn any flags from invoices, sadly
2364 fn available_amount_while_routing_test() {
2365 // Tests whether we choose the correct available channel amount while routing.
2367 let (secp_ctx, mut net_graph_msg_handler, chain_monitor, logger) = build_graph();
2368 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
2370 // We will use a simple single-path route from
2371 // our node to node2 via node0: channels {1, 3}.
2373 // First disable all other paths.
2374 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2375 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2376 short_channel_id: 2,
2379 cltv_expiry_delta: 0,
2380 htlc_minimum_msat: 0,
2381 htlc_maximum_msat: OptionalField::Present(100_000),
2383 fee_proportional_millionths: 0,
2384 excess_data: Vec::new()
2386 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2387 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2388 short_channel_id: 12,
2391 cltv_expiry_delta: 0,
2392 htlc_minimum_msat: 0,
2393 htlc_maximum_msat: OptionalField::Present(100_000),
2395 fee_proportional_millionths: 0,
2396 excess_data: Vec::new()
2399 // Make the first channel (#1) very permissive,
2400 // and we will be testing all limits on the second channel.
2401 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2402 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2403 short_channel_id: 1,
2406 cltv_expiry_delta: 0,
2407 htlc_minimum_msat: 0,
2408 htlc_maximum_msat: OptionalField::Present(1_000_000_000),
2410 fee_proportional_millionths: 0,
2411 excess_data: Vec::new()
2414 // First, let's see if routing works if we have absolutely no idea about the available amount.
2415 // In this case, it should be set to 250_000 sats.
2416 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
2417 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2418 short_channel_id: 3,
2421 cltv_expiry_delta: 0,
2422 htlc_minimum_msat: 0,
2423 htlc_maximum_msat: OptionalField::Absent,
2425 fee_proportional_millionths: 0,
2426 excess_data: Vec::new()
2430 // Attempt to route more than available results in a failure.
2431 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2],
2432 Some(InvoiceFeatures::known()), None, &Vec::new(), 250_000_001, 42, Arc::clone(&logger)) {
2433 assert_eq!(err, "Failed to find a sufficient route to the given destination");
2434 } else { panic!(); }
2438 // Now, attempt to route an exact amount we have should be fine.
2439 let route = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2],
2440 Some(InvoiceFeatures::known()), None, &Vec::new(), 250_000_000, 42, Arc::clone(&logger)).unwrap();
2441 assert_eq!(route.paths.len(), 1);
2442 let path = route.paths.last().unwrap();
2443 assert_eq!(path.len(), 2);
2444 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
2445 assert_eq!(path.last().unwrap().fee_msat, 250_000_000);
2448 // Check that setting outbound_capacity_msat in first_hops limits the channels.
2449 // Disable channel #1 and use another first hop.
2450 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2451 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2452 short_channel_id: 1,
2455 cltv_expiry_delta: 0,
2456 htlc_minimum_msat: 0,
2457 htlc_maximum_msat: OptionalField::Present(1_000_000_000),
2459 fee_proportional_millionths: 0,
2460 excess_data: Vec::new()
2463 // Now, limit the first_hop by the outbound_capacity_msat of 200_000 sats.
2464 let our_chans = vec![channelmanager::ChannelDetails {
2465 channel_id: [0; 32],
2466 funding_txo: Some(OutPoint { txid: bitcoin::Txid::from_slice(&[0; 32]).unwrap(), index: 0 }),
2467 short_channel_id: Some(42),
2468 remote_network_id: nodes[0].clone(),
2469 counterparty_features: InitFeatures::from_le_bytes(vec![0b11]),
2470 channel_value_satoshis: 0,
2472 outbound_capacity_msat: 200_000_000,
2473 inbound_capacity_msat: 0,
2474 is_outbound: true, is_funding_locked: true,
2475 is_usable: true, is_public: true,
2476 counterparty_forwarding_info: None,
2480 // Attempt to route more than available results in a failure.
2481 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2],
2482 Some(InvoiceFeatures::known()), Some(&our_chans.iter().collect::<Vec<_>>()), &Vec::new(), 200_000_001, 42, Arc::clone(&logger)) {
2483 assert_eq!(err, "Failed to find a sufficient route to the given destination");
2484 } else { panic!(); }
2488 // Now, attempt to route an exact amount we have should be fine.
2489 let route = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2],
2490 Some(InvoiceFeatures::known()), Some(&our_chans.iter().collect::<Vec<_>>()), &Vec::new(), 200_000_000, 42, Arc::clone(&logger)).unwrap();
2491 assert_eq!(route.paths.len(), 1);
2492 let path = route.paths.last().unwrap();
2493 assert_eq!(path.len(), 2);
2494 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
2495 assert_eq!(path.last().unwrap().fee_msat, 200_000_000);
2498 // Enable channel #1 back.
2499 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2500 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2501 short_channel_id: 1,
2504 cltv_expiry_delta: 0,
2505 htlc_minimum_msat: 0,
2506 htlc_maximum_msat: OptionalField::Present(1_000_000_000),
2508 fee_proportional_millionths: 0,
2509 excess_data: Vec::new()
2513 // Now let's see if routing works if we know only htlc_maximum_msat.
2514 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
2515 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2516 short_channel_id: 3,
2519 cltv_expiry_delta: 0,
2520 htlc_minimum_msat: 0,
2521 htlc_maximum_msat: OptionalField::Present(15_000),
2523 fee_proportional_millionths: 0,
2524 excess_data: Vec::new()
2528 // Attempt to route more than available results in a failure.
2529 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2],
2530 Some(InvoiceFeatures::known()), None, &Vec::new(), 15_001, 42, Arc::clone(&logger)) {
2531 assert_eq!(err, "Failed to find a sufficient route to the given destination");
2532 } else { panic!(); }
2536 // Now, attempt to route an exact amount we have should be fine.
2537 let route = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2],
2538 Some(InvoiceFeatures::known()), None, &Vec::new(), 15_000, 42, Arc::clone(&logger)).unwrap();
2539 assert_eq!(route.paths.len(), 1);
2540 let path = route.paths.last().unwrap();
2541 assert_eq!(path.len(), 2);
2542 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
2543 assert_eq!(path.last().unwrap().fee_msat, 15_000);
2546 // Now let's see if routing works if we know only capacity from the UTXO.
2548 // We can't change UTXO capacity on the fly, so we'll disable
2549 // the existing channel and add another one with the capacity we need.
2550 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
2551 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2552 short_channel_id: 3,
2555 cltv_expiry_delta: 0,
2556 htlc_minimum_msat: 0,
2557 htlc_maximum_msat: OptionalField::Absent,
2559 fee_proportional_millionths: 0,
2560 excess_data: Vec::new()
2563 let good_script = Builder::new().push_opcode(opcodes::all::OP_PUSHNUM_2)
2564 .push_slice(&PublicKey::from_secret_key(&secp_ctx, &privkeys[0]).serialize())
2565 .push_slice(&PublicKey::from_secret_key(&secp_ctx, &privkeys[2]).serialize())
2566 .push_opcode(opcodes::all::OP_PUSHNUM_2)
2567 .push_opcode(opcodes::all::OP_CHECKMULTISIG).into_script().to_v0_p2wsh();
2569 *chain_monitor.utxo_ret.lock().unwrap() = Ok(TxOut { value: 15, script_pubkey: good_script.clone() });
2570 net_graph_msg_handler.add_chain_access(Some(chain_monitor));
2572 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], &privkeys[2], ChannelFeatures::from_le_bytes(id_to_feature_flags(3)), 333);
2573 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
2574 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2575 short_channel_id: 333,
2578 cltv_expiry_delta: (3 << 8) | 1,
2579 htlc_minimum_msat: 0,
2580 htlc_maximum_msat: OptionalField::Absent,
2582 fee_proportional_millionths: 0,
2583 excess_data: Vec::new()
2585 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
2586 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2587 short_channel_id: 333,
2590 cltv_expiry_delta: (3 << 8) | 2,
2591 htlc_minimum_msat: 0,
2592 htlc_maximum_msat: OptionalField::Absent,
2594 fee_proportional_millionths: 0,
2595 excess_data: Vec::new()
2599 // Attempt to route more than available results in a failure.
2600 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2],
2601 Some(InvoiceFeatures::known()), None, &Vec::new(), 15_001, 42, Arc::clone(&logger)) {
2602 assert_eq!(err, "Failed to find a sufficient route to the given destination");
2603 } else { panic!(); }
2607 // Now, attempt to route an exact amount we have should be fine.
2608 let route = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2],
2609 Some(InvoiceFeatures::known()), None, &Vec::new(), 15_000, 42, Arc::clone(&logger)).unwrap();
2610 assert_eq!(route.paths.len(), 1);
2611 let path = route.paths.last().unwrap();
2612 assert_eq!(path.len(), 2);
2613 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
2614 assert_eq!(path.last().unwrap().fee_msat, 15_000);
2617 // Now let's see if routing chooses htlc_maximum_msat over UTXO capacity.
2618 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
2619 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2620 short_channel_id: 333,
2623 cltv_expiry_delta: 0,
2624 htlc_minimum_msat: 0,
2625 htlc_maximum_msat: OptionalField::Present(10_000),
2627 fee_proportional_millionths: 0,
2628 excess_data: Vec::new()
2632 // Attempt to route more than available results in a failure.
2633 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2],
2634 Some(InvoiceFeatures::known()), None, &Vec::new(), 10_001, 42, Arc::clone(&logger)) {
2635 assert_eq!(err, "Failed to find a sufficient route to the given destination");
2636 } else { panic!(); }
2640 // Now, attempt to route an exact amount we have should be fine.
2641 let route = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2],
2642 Some(InvoiceFeatures::known()), None, &Vec::new(), 10_000, 42, Arc::clone(&logger)).unwrap();
2643 assert_eq!(route.paths.len(), 1);
2644 let path = route.paths.last().unwrap();
2645 assert_eq!(path.len(), 2);
2646 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
2647 assert_eq!(path.last().unwrap().fee_msat, 10_000);
2652 fn available_liquidity_last_hop_test() {
2653 // Check that available liquidity properly limits the path even when only
2654 // one of the latter hops is limited.
2655 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
2656 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
2658 // Path via {node7, node2, node4} is channels {12, 13, 6, 11}.
2659 // {12, 13, 11} have the capacities of 100, {6} has a capacity of 50.
2660 // Total capacity: 50 sats.
2662 // Disable other potential paths.
2663 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2664 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2665 short_channel_id: 2,
2668 cltv_expiry_delta: 0,
2669 htlc_minimum_msat: 0,
2670 htlc_maximum_msat: OptionalField::Present(100_000),
2672 fee_proportional_millionths: 0,
2673 excess_data: Vec::new()
2675 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
2676 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2677 short_channel_id: 7,
2680 cltv_expiry_delta: 0,
2681 htlc_minimum_msat: 0,
2682 htlc_maximum_msat: OptionalField::Present(100_000),
2684 fee_proportional_millionths: 0,
2685 excess_data: Vec::new()
2690 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2691 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2692 short_channel_id: 12,
2695 cltv_expiry_delta: 0,
2696 htlc_minimum_msat: 0,
2697 htlc_maximum_msat: OptionalField::Present(100_000),
2699 fee_proportional_millionths: 0,
2700 excess_data: Vec::new()
2702 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
2703 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2704 short_channel_id: 13,
2707 cltv_expiry_delta: 0,
2708 htlc_minimum_msat: 0,
2709 htlc_maximum_msat: OptionalField::Present(100_000),
2711 fee_proportional_millionths: 0,
2712 excess_data: Vec::new()
2715 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
2716 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2717 short_channel_id: 6,
2720 cltv_expiry_delta: 0,
2721 htlc_minimum_msat: 0,
2722 htlc_maximum_msat: OptionalField::Present(50_000),
2724 fee_proportional_millionths: 0,
2725 excess_data: Vec::new()
2727 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
2728 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2729 short_channel_id: 11,
2732 cltv_expiry_delta: 0,
2733 htlc_minimum_msat: 0,
2734 htlc_maximum_msat: OptionalField::Present(100_000),
2736 fee_proportional_millionths: 0,
2737 excess_data: Vec::new()
2740 // Attempt to route more than available results in a failure.
2741 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[3],
2742 Some(InvoiceFeatures::known()), None, &Vec::new(), 60_000, 42, Arc::clone(&logger)) {
2743 assert_eq!(err, "Failed to find a sufficient route to the given destination");
2744 } else { panic!(); }
2748 // Now, attempt to route 49 sats (just a bit below the capacity).
2749 let route = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[3],
2750 Some(InvoiceFeatures::known()), None, &Vec::new(), 49_000, 42, Arc::clone(&logger)).unwrap();
2751 assert_eq!(route.paths.len(), 1);
2752 let mut total_amount_paid_msat = 0;
2753 for path in &route.paths {
2754 assert_eq!(path.len(), 4);
2755 assert_eq!(path.last().unwrap().pubkey, nodes[3]);
2756 total_amount_paid_msat += path.last().unwrap().fee_msat;
2758 assert_eq!(total_amount_paid_msat, 49_000);
2762 // Attempt to route an exact amount is also fine
2763 let route = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[3],
2764 Some(InvoiceFeatures::known()), None, &Vec::new(), 50_000, 42, Arc::clone(&logger)).unwrap();
2765 assert_eq!(route.paths.len(), 1);
2766 let mut total_amount_paid_msat = 0;
2767 for path in &route.paths {
2768 assert_eq!(path.len(), 4);
2769 assert_eq!(path.last().unwrap().pubkey, nodes[3]);
2770 total_amount_paid_msat += path.last().unwrap().fee_msat;
2772 assert_eq!(total_amount_paid_msat, 50_000);
2777 fn ignore_fee_first_hop_test() {
2778 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
2779 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
2781 // Path via node0 is channels {1, 3}. Limit them to 100 and 50 sats (total limit 50).
2782 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2783 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2784 short_channel_id: 1,
2787 cltv_expiry_delta: 0,
2788 htlc_minimum_msat: 0,
2789 htlc_maximum_msat: OptionalField::Present(100_000),
2790 fee_base_msat: 1_000_000,
2791 fee_proportional_millionths: 0,
2792 excess_data: Vec::new()
2794 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
2795 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2796 short_channel_id: 3,
2799 cltv_expiry_delta: 0,
2800 htlc_minimum_msat: 0,
2801 htlc_maximum_msat: OptionalField::Present(50_000),
2803 fee_proportional_millionths: 0,
2804 excess_data: Vec::new()
2808 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();
2809 assert_eq!(route.paths.len(), 1);
2810 let mut total_amount_paid_msat = 0;
2811 for path in &route.paths {
2812 assert_eq!(path.len(), 2);
2813 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
2814 total_amount_paid_msat += path.last().unwrap().fee_msat;
2816 assert_eq!(total_amount_paid_msat, 50_000);
2821 fn simple_mpp_route_test() {
2822 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
2823 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
2825 // We need a route consisting of 3 paths:
2826 // From our node to node2 via node0, node7, node1 (three paths one hop each).
2827 // To achieve this, the amount being transferred should be around
2828 // the total capacity of these 3 paths.
2830 // First, we set limits on these (previously unlimited) channels.
2831 // Their aggregate capacity will be 50 + 60 + 180 = 290 sats.
2833 // Path via node0 is channels {1, 3}. Limit them to 100 and 50 sats (total limit 50).
2834 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2835 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2836 short_channel_id: 1,
2839 cltv_expiry_delta: 0,
2840 htlc_minimum_msat: 0,
2841 htlc_maximum_msat: OptionalField::Present(100_000),
2843 fee_proportional_millionths: 0,
2844 excess_data: Vec::new()
2846 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
2847 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2848 short_channel_id: 3,
2851 cltv_expiry_delta: 0,
2852 htlc_minimum_msat: 0,
2853 htlc_maximum_msat: OptionalField::Present(50_000),
2855 fee_proportional_millionths: 0,
2856 excess_data: Vec::new()
2859 // Path via node7 is channels {12, 13}. Limit them to 60 and 60 sats
2860 // (total limit 60).
2861 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2862 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2863 short_channel_id: 12,
2866 cltv_expiry_delta: 0,
2867 htlc_minimum_msat: 0,
2868 htlc_maximum_msat: OptionalField::Present(60_000),
2870 fee_proportional_millionths: 0,
2871 excess_data: Vec::new()
2873 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
2874 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2875 short_channel_id: 13,
2878 cltv_expiry_delta: 0,
2879 htlc_minimum_msat: 0,
2880 htlc_maximum_msat: OptionalField::Present(60_000),
2882 fee_proportional_millionths: 0,
2883 excess_data: Vec::new()
2886 // Path via node1 is channels {2, 4}. Limit them to 200 and 180 sats
2887 // (total capacity 180 sats).
2888 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2889 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2890 short_channel_id: 2,
2893 cltv_expiry_delta: 0,
2894 htlc_minimum_msat: 0,
2895 htlc_maximum_msat: OptionalField::Present(200_000),
2897 fee_proportional_millionths: 0,
2898 excess_data: Vec::new()
2900 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
2901 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2902 short_channel_id: 4,
2905 cltv_expiry_delta: 0,
2906 htlc_minimum_msat: 0,
2907 htlc_maximum_msat: OptionalField::Present(180_000),
2909 fee_proportional_millionths: 0,
2910 excess_data: Vec::new()
2914 // Attempt to route more than available results in a failure.
2915 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(),
2916 &nodes[2], Some(InvoiceFeatures::known()), None, &Vec::new(), 300_000, 42, Arc::clone(&logger)) {
2917 assert_eq!(err, "Failed to find a sufficient route to the given destination");
2918 } else { panic!(); }
2922 // Now, attempt to route 250 sats (just a bit below the capacity).
2923 // Our algorithm should provide us with these 3 paths.
2924 let route = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2],
2925 Some(InvoiceFeatures::known()), None, &Vec::new(), 250_000, 42, Arc::clone(&logger)).unwrap();
2926 assert_eq!(route.paths.len(), 3);
2927 let mut total_amount_paid_msat = 0;
2928 for path in &route.paths {
2929 assert_eq!(path.len(), 2);
2930 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
2931 total_amount_paid_msat += path.last().unwrap().fee_msat;
2933 assert_eq!(total_amount_paid_msat, 250_000);
2937 // Attempt to route an exact amount is also fine
2938 let route = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2],
2939 Some(InvoiceFeatures::known()), None, &Vec::new(), 290_000, 42, Arc::clone(&logger)).unwrap();
2940 assert_eq!(route.paths.len(), 3);
2941 let mut total_amount_paid_msat = 0;
2942 for path in &route.paths {
2943 assert_eq!(path.len(), 2);
2944 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
2945 total_amount_paid_msat += path.last().unwrap().fee_msat;
2947 assert_eq!(total_amount_paid_msat, 290_000);
2952 fn long_mpp_route_test() {
2953 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
2954 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
2956 // We need a route consisting of 3 paths:
2957 // From our node to node3 via {node0, node2}, {node7, node2, node4} and {node7, node2}.
2958 // Note that these paths overlap (channels 5, 12, 13).
2959 // We will route 300 sats.
2960 // Each path will have 100 sats capacity, those channels which
2961 // are used twice will have 200 sats capacity.
2963 // Disable other potential paths.
2964 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2965 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2966 short_channel_id: 2,
2969 cltv_expiry_delta: 0,
2970 htlc_minimum_msat: 0,
2971 htlc_maximum_msat: OptionalField::Present(100_000),
2973 fee_proportional_millionths: 0,
2974 excess_data: Vec::new()
2976 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
2977 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2978 short_channel_id: 7,
2981 cltv_expiry_delta: 0,
2982 htlc_minimum_msat: 0,
2983 htlc_maximum_msat: OptionalField::Present(100_000),
2985 fee_proportional_millionths: 0,
2986 excess_data: Vec::new()
2989 // Path via {node0, node2} is channels {1, 3, 5}.
2990 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2991 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2992 short_channel_id: 1,
2995 cltv_expiry_delta: 0,
2996 htlc_minimum_msat: 0,
2997 htlc_maximum_msat: OptionalField::Present(100_000),
2999 fee_proportional_millionths: 0,
3000 excess_data: Vec::new()
3002 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3003 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3004 short_channel_id: 3,
3007 cltv_expiry_delta: 0,
3008 htlc_minimum_msat: 0,
3009 htlc_maximum_msat: OptionalField::Present(100_000),
3011 fee_proportional_millionths: 0,
3012 excess_data: Vec::new()
3015 // Capacity of 200 sats because this channel will be used by 3rd path as well.
3016 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(5)), 5);
3017 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3018 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3019 short_channel_id: 5,
3022 cltv_expiry_delta: 0,
3023 htlc_minimum_msat: 0,
3024 htlc_maximum_msat: OptionalField::Present(200_000),
3026 fee_proportional_millionths: 0,
3027 excess_data: Vec::new()
3030 // Path via {node7, node2, node4} is channels {12, 13, 6, 11}.
3031 // Add 100 sats to the capacities of {12, 13}, because these channels
3032 // are also used for 3rd path. 100 sats for the rest. Total capacity: 100 sats.
3033 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3034 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3035 short_channel_id: 12,
3038 cltv_expiry_delta: 0,
3039 htlc_minimum_msat: 0,
3040 htlc_maximum_msat: OptionalField::Present(200_000),
3042 fee_proportional_millionths: 0,
3043 excess_data: Vec::new()
3045 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
3046 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3047 short_channel_id: 13,
3050 cltv_expiry_delta: 0,
3051 htlc_minimum_msat: 0,
3052 htlc_maximum_msat: OptionalField::Present(200_000),
3054 fee_proportional_millionths: 0,
3055 excess_data: Vec::new()
3058 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3059 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3060 short_channel_id: 6,
3063 cltv_expiry_delta: 0,
3064 htlc_minimum_msat: 0,
3065 htlc_maximum_msat: OptionalField::Present(100_000),
3067 fee_proportional_millionths: 0,
3068 excess_data: Vec::new()
3070 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
3071 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3072 short_channel_id: 11,
3075 cltv_expiry_delta: 0,
3076 htlc_minimum_msat: 0,
3077 htlc_maximum_msat: OptionalField::Present(100_000),
3079 fee_proportional_millionths: 0,
3080 excess_data: Vec::new()
3083 // Path via {node7, node2} is channels {12, 13, 5}.
3084 // We already limited them to 200 sats (they are used twice for 100 sats).
3085 // Nothing to do here.
3088 // Attempt to route more than available results in a failure.
3089 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[3],
3090 Some(InvoiceFeatures::known()), None, &Vec::new(), 350_000, 42, Arc::clone(&logger)) {
3091 assert_eq!(err, "Failed to find a sufficient route to the given destination");
3092 } else { panic!(); }
3096 // Now, attempt to route 300 sats (exact amount we can route).
3097 // Our algorithm should provide us with these 3 paths, 100 sats each.
3098 let route = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[3],
3099 Some(InvoiceFeatures::known()), None, &Vec::new(), 300_000, 42, Arc::clone(&logger)).unwrap();
3100 assert_eq!(route.paths.len(), 3);
3102 let mut total_amount_paid_msat = 0;
3103 for path in &route.paths {
3104 assert_eq!(path.last().unwrap().pubkey, nodes[3]);
3105 total_amount_paid_msat += path.last().unwrap().fee_msat;
3107 assert_eq!(total_amount_paid_msat, 300_000);
3113 fn mpp_cheaper_route_test() {
3114 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
3115 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3117 // This test checks that if we have two cheaper paths and one more expensive path,
3118 // so that liquidity-wise any 2 of 3 combination is sufficient,
3119 // two cheaper paths will be taken.
3120 // These paths have equal available liquidity.
3122 // We need a combination of 3 paths:
3123 // From our node to node3 via {node0, node2}, {node7, node2, node4} and {node7, node2}.
3124 // Note that these paths overlap (channels 5, 12, 13).
3125 // Each path will have 100 sats capacity, those channels which
3126 // are used twice will have 200 sats capacity.
3128 // Disable other potential paths.
3129 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3130 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3131 short_channel_id: 2,
3134 cltv_expiry_delta: 0,
3135 htlc_minimum_msat: 0,
3136 htlc_maximum_msat: OptionalField::Present(100_000),
3138 fee_proportional_millionths: 0,
3139 excess_data: Vec::new()
3141 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3142 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3143 short_channel_id: 7,
3146 cltv_expiry_delta: 0,
3147 htlc_minimum_msat: 0,
3148 htlc_maximum_msat: OptionalField::Present(100_000),
3150 fee_proportional_millionths: 0,
3151 excess_data: Vec::new()
3154 // Path via {node0, node2} is channels {1, 3, 5}.
3155 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3156 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3157 short_channel_id: 1,
3160 cltv_expiry_delta: 0,
3161 htlc_minimum_msat: 0,
3162 htlc_maximum_msat: OptionalField::Present(100_000),
3164 fee_proportional_millionths: 0,
3165 excess_data: Vec::new()
3167 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3168 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3169 short_channel_id: 3,
3172 cltv_expiry_delta: 0,
3173 htlc_minimum_msat: 0,
3174 htlc_maximum_msat: OptionalField::Present(100_000),
3176 fee_proportional_millionths: 0,
3177 excess_data: Vec::new()
3180 // Capacity of 200 sats because this channel will be used by 3rd path as well.
3181 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(5)), 5);
3182 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3183 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3184 short_channel_id: 5,
3187 cltv_expiry_delta: 0,
3188 htlc_minimum_msat: 0,
3189 htlc_maximum_msat: OptionalField::Present(200_000),
3191 fee_proportional_millionths: 0,
3192 excess_data: Vec::new()
3195 // Path via {node7, node2, node4} is channels {12, 13, 6, 11}.
3196 // Add 100 sats to the capacities of {12, 13}, because these channels
3197 // are also used for 3rd path. 100 sats for the rest. Total capacity: 100 sats.
3198 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3199 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3200 short_channel_id: 12,
3203 cltv_expiry_delta: 0,
3204 htlc_minimum_msat: 0,
3205 htlc_maximum_msat: OptionalField::Present(200_000),
3207 fee_proportional_millionths: 0,
3208 excess_data: Vec::new()
3210 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
3211 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3212 short_channel_id: 13,
3215 cltv_expiry_delta: 0,
3216 htlc_minimum_msat: 0,
3217 htlc_maximum_msat: OptionalField::Present(200_000),
3219 fee_proportional_millionths: 0,
3220 excess_data: Vec::new()
3223 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3224 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3225 short_channel_id: 6,
3228 cltv_expiry_delta: 0,
3229 htlc_minimum_msat: 0,
3230 htlc_maximum_msat: OptionalField::Present(100_000),
3231 fee_base_msat: 1_000,
3232 fee_proportional_millionths: 0,
3233 excess_data: Vec::new()
3235 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
3236 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3237 short_channel_id: 11,
3240 cltv_expiry_delta: 0,
3241 htlc_minimum_msat: 0,
3242 htlc_maximum_msat: OptionalField::Present(100_000),
3244 fee_proportional_millionths: 0,
3245 excess_data: Vec::new()
3248 // Path via {node7, node2} is channels {12, 13, 5}.
3249 // We already limited them to 200 sats (they are used twice for 100 sats).
3250 // Nothing to do here.
3253 // Now, attempt to route 180 sats.
3254 // Our algorithm should provide us with these 2 paths.
3255 let route = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[3],
3256 Some(InvoiceFeatures::known()), None, &Vec::new(), 180_000, 42, Arc::clone(&logger)).unwrap();
3257 assert_eq!(route.paths.len(), 2);
3259 let mut total_value_transferred_msat = 0;
3260 let mut total_paid_msat = 0;
3261 for path in &route.paths {
3262 assert_eq!(path.last().unwrap().pubkey, nodes[3]);
3263 total_value_transferred_msat += path.last().unwrap().fee_msat;
3265 total_paid_msat += hop.fee_msat;
3268 // If we paid fee, this would be higher.
3269 assert_eq!(total_value_transferred_msat, 180_000);
3270 let total_fees_paid = total_paid_msat - total_value_transferred_msat;
3271 assert_eq!(total_fees_paid, 0);
3276 fn fees_on_mpp_route_test() {
3277 // This test makes sure that MPP algorithm properly takes into account
3278 // fees charged on the channels, by making the fees impactful:
3279 // if the fee is not properly accounted for, the behavior is different.
3280 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
3281 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3283 // We need a route consisting of 2 paths:
3284 // From our node to node3 via {node0, node2} and {node7, node2, node4}.
3285 // We will route 200 sats, Each path will have 100 sats capacity.
3287 // This test is not particularly stable: e.g.,
3288 // there's a way to route via {node0, node2, node4}.
3289 // It works while pathfinding is deterministic, but can be broken otherwise.
3290 // It's fine to ignore this concern for now.
3292 // Disable other potential paths.
3293 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3294 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3295 short_channel_id: 2,
3298 cltv_expiry_delta: 0,
3299 htlc_minimum_msat: 0,
3300 htlc_maximum_msat: OptionalField::Present(100_000),
3302 fee_proportional_millionths: 0,
3303 excess_data: Vec::new()
3306 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3307 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3308 short_channel_id: 7,
3311 cltv_expiry_delta: 0,
3312 htlc_minimum_msat: 0,
3313 htlc_maximum_msat: OptionalField::Present(100_000),
3315 fee_proportional_millionths: 0,
3316 excess_data: Vec::new()
3319 // Path via {node0, node2} is channels {1, 3, 5}.
3320 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3321 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3322 short_channel_id: 1,
3325 cltv_expiry_delta: 0,
3326 htlc_minimum_msat: 0,
3327 htlc_maximum_msat: OptionalField::Present(100_000),
3329 fee_proportional_millionths: 0,
3330 excess_data: Vec::new()
3332 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3333 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3334 short_channel_id: 3,
3337 cltv_expiry_delta: 0,
3338 htlc_minimum_msat: 0,
3339 htlc_maximum_msat: OptionalField::Present(100_000),
3341 fee_proportional_millionths: 0,
3342 excess_data: Vec::new()
3345 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(5)), 5);
3346 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3347 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3348 short_channel_id: 5,
3351 cltv_expiry_delta: 0,
3352 htlc_minimum_msat: 0,
3353 htlc_maximum_msat: OptionalField::Present(100_000),
3355 fee_proportional_millionths: 0,
3356 excess_data: Vec::new()
3359 // Path via {node7, node2, node4} is channels {12, 13, 6, 11}.
3360 // All channels should be 100 sats capacity. But for the fee experiment,
3361 // we'll add absolute fee of 150 sats paid for the use channel 6 (paid to node2 on channel 13).
3362 // Since channel 12 allows to deliver only 250 sats to channel 13, channel 13 can transfer only
3363 // 100 sats (and pay 150 sats in fees for the use of channel 6),
3364 // so no matter how large are other channels,
3365 // the whole path will be limited by 100 sats with just these 2 conditions:
3366 // - channel 12 capacity is 250 sats
3367 // - fee for channel 6 is 150 sats
3368 // Let's test this by enforcing these 2 conditions and removing other limits.
3369 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3370 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3371 short_channel_id: 12,
3374 cltv_expiry_delta: 0,
3375 htlc_minimum_msat: 0,
3376 htlc_maximum_msat: OptionalField::Present(250_000),
3378 fee_proportional_millionths: 0,
3379 excess_data: Vec::new()
3381 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
3382 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3383 short_channel_id: 13,
3386 cltv_expiry_delta: 0,
3387 htlc_minimum_msat: 0,
3388 htlc_maximum_msat: OptionalField::Absent,
3390 fee_proportional_millionths: 0,
3391 excess_data: Vec::new()
3394 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3395 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3396 short_channel_id: 6,
3399 cltv_expiry_delta: 0,
3400 htlc_minimum_msat: 0,
3401 htlc_maximum_msat: OptionalField::Absent,
3402 fee_base_msat: 150_000,
3403 fee_proportional_millionths: 0,
3404 excess_data: Vec::new()
3406 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
3407 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3408 short_channel_id: 11,
3411 cltv_expiry_delta: 0,
3412 htlc_minimum_msat: 0,
3413 htlc_maximum_msat: OptionalField::Absent,
3415 fee_proportional_millionths: 0,
3416 excess_data: Vec::new()
3420 // Attempt to route more than available results in a failure.
3421 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[3],
3422 Some(InvoiceFeatures::known()), None, &Vec::new(), 210_000, 42, Arc::clone(&logger)) {
3423 assert_eq!(err, "Failed to find a sufficient route to the given destination");
3424 } else { panic!(); }
3428 // Now, attempt to route 200 sats (exact amount we can route).
3429 let route = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[3],
3430 Some(InvoiceFeatures::known()), None, &Vec::new(), 200_000, 42, Arc::clone(&logger)).unwrap();
3431 assert_eq!(route.paths.len(), 2);
3433 let mut total_amount_paid_msat = 0;
3434 for path in &route.paths {
3435 assert_eq!(path.last().unwrap().pubkey, nodes[3]);
3436 total_amount_paid_msat += path.last().unwrap().fee_msat;
3438 assert_eq!(total_amount_paid_msat, 200_000);
3444 fn drop_lowest_channel_mpp_route_test() {
3445 // This test checks that low-capacity channel is dropped when after
3446 // path finding we realize that we found more capacity than we need.
3447 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
3448 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3450 // We need a route consisting of 3 paths:
3451 // From our node to node2 via node0, node7, node1 (three paths one hop each).
3453 // The first and the second paths should be sufficient, but the third should be
3454 // cheaper, so that we select it but drop later.
3456 // First, we set limits on these (previously unlimited) channels.
3457 // Their aggregate capacity will be 50 + 60 + 20 = 130 sats.
3459 // Path via node0 is channels {1, 3}. Limit them to 100 and 50 sats (total limit 50);
3460 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3461 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3462 short_channel_id: 1,
3465 cltv_expiry_delta: 0,
3466 htlc_minimum_msat: 0,
3467 htlc_maximum_msat: OptionalField::Present(100_000),
3469 fee_proportional_millionths: 0,
3470 excess_data: Vec::new()
3472 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3473 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3474 short_channel_id: 3,
3477 cltv_expiry_delta: 0,
3478 htlc_minimum_msat: 0,
3479 htlc_maximum_msat: OptionalField::Present(50_000),
3481 fee_proportional_millionths: 0,
3482 excess_data: Vec::new()
3485 // Path via node7 is channels {12, 13}. Limit them to 60 and 60 sats (total limit 60);
3486 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3487 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3488 short_channel_id: 12,
3491 cltv_expiry_delta: 0,
3492 htlc_minimum_msat: 0,
3493 htlc_maximum_msat: OptionalField::Present(60_000),
3495 fee_proportional_millionths: 0,
3496 excess_data: Vec::new()
3498 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
3499 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3500 short_channel_id: 13,
3503 cltv_expiry_delta: 0,
3504 htlc_minimum_msat: 0,
3505 htlc_maximum_msat: OptionalField::Present(60_000),
3507 fee_proportional_millionths: 0,
3508 excess_data: Vec::new()
3511 // Path via node1 is channels {2, 4}. Limit them to 20 and 20 sats (total capacity 20 sats).
3512 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3513 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3514 short_channel_id: 2,
3517 cltv_expiry_delta: 0,
3518 htlc_minimum_msat: 0,
3519 htlc_maximum_msat: OptionalField::Present(20_000),
3521 fee_proportional_millionths: 0,
3522 excess_data: Vec::new()
3524 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
3525 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3526 short_channel_id: 4,
3529 cltv_expiry_delta: 0,
3530 htlc_minimum_msat: 0,
3531 htlc_maximum_msat: OptionalField::Present(20_000),
3533 fee_proportional_millionths: 0,
3534 excess_data: Vec::new()
3538 // Attempt to route more than available results in a failure.
3539 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2],
3540 Some(InvoiceFeatures::known()), None, &Vec::new(), 150_000, 42, Arc::clone(&logger)) {
3541 assert_eq!(err, "Failed to find a sufficient route to the given destination");
3542 } else { panic!(); }
3546 // Now, attempt to route 125 sats (just a bit below the capacity of 3 channels).
3547 // Our algorithm should provide us with these 3 paths.
3548 let route = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2],
3549 Some(InvoiceFeatures::known()), None, &Vec::new(), 125_000, 42, Arc::clone(&logger)).unwrap();
3550 assert_eq!(route.paths.len(), 3);
3551 let mut total_amount_paid_msat = 0;
3552 for path in &route.paths {
3553 assert_eq!(path.len(), 2);
3554 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
3555 total_amount_paid_msat += path.last().unwrap().fee_msat;
3557 assert_eq!(total_amount_paid_msat, 125_000);
3561 // Attempt to route without the last small cheap channel
3562 let route = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2],
3563 Some(InvoiceFeatures::known()), None, &Vec::new(), 90_000, 42, Arc::clone(&logger)).unwrap();
3564 assert_eq!(route.paths.len(), 2);
3565 let mut total_amount_paid_msat = 0;
3566 for path in &route.paths {
3567 assert_eq!(path.len(), 2);
3568 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
3569 total_amount_paid_msat += path.last().unwrap().fee_msat;
3571 assert_eq!(total_amount_paid_msat, 90_000);
3576 fn min_criteria_consistency() {
3577 // Test that we don't use an inconsistent metric between updating and walking nodes during
3578 // our Dijkstra's pass. In the initial version of MPP, the "best source" for a given node
3579 // was updated with a different criterion from the heap sorting, resulting in loops in
3580 // calculated paths. We test for that specific case here.
3582 // We construct a network that looks like this:
3584 // node2 -1(3)2- node3
3588 // node1 -1(5)2- node4 -1(1)2- node6
3594 // We create a loop on the side of our real path - our destination is node 6, with a
3595 // previous hop of node 4. From 4, the cheapest previous path is channel 2 from node 2,
3596 // followed by node 3 over channel 3. Thereafter, the cheapest next-hop is back to node 4
3597 // (this time over channel 4). Channel 4 has 0 htlc_minimum_msat whereas channel 1 (the
3598 // other channel with a previous-hop of node 4) has a high (but irrelevant to the overall
3599 // payment) htlc_minimum_msat. In the original algorithm, this resulted in node4's
3600 // "previous hop" being set to node 3, creating a loop in the path.
3601 let secp_ctx = Secp256k1::new();
3602 let logger = Arc::new(test_utils::TestLogger::new());
3603 let net_graph_msg_handler = NetGraphMsgHandler::new(genesis_block(Network::Testnet).header.block_hash(), None, Arc::clone(&logger));
3604 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3606 add_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, &privkeys[1], ChannelFeatures::from_le_bytes(id_to_feature_flags(6)), 6);
3607 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3608 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3609 short_channel_id: 6,
3612 cltv_expiry_delta: (6 << 8) | 0,
3613 htlc_minimum_msat: 0,
3614 htlc_maximum_msat: OptionalField::Absent,
3616 fee_proportional_millionths: 0,
3617 excess_data: Vec::new()
3619 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[1], NodeFeatures::from_le_bytes(id_to_feature_flags(1)), 0);
3621 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], &privkeys[4], ChannelFeatures::from_le_bytes(id_to_feature_flags(5)), 5);
3622 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
3623 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3624 short_channel_id: 5,
3627 cltv_expiry_delta: (5 << 8) | 0,
3628 htlc_minimum_msat: 0,
3629 htlc_maximum_msat: OptionalField::Absent,
3631 fee_proportional_millionths: 0,
3632 excess_data: Vec::new()
3634 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[4], NodeFeatures::from_le_bytes(id_to_feature_flags(4)), 0);
3636 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(4)), 4);
3637 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
3638 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3639 short_channel_id: 4,
3642 cltv_expiry_delta: (4 << 8) | 0,
3643 htlc_minimum_msat: 0,
3644 htlc_maximum_msat: OptionalField::Absent,
3646 fee_proportional_millionths: 0,
3647 excess_data: Vec::new()
3649 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[3], NodeFeatures::from_le_bytes(id_to_feature_flags(3)), 0);
3651 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[3], &privkeys[2], ChannelFeatures::from_le_bytes(id_to_feature_flags(3)), 3);
3652 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[3], UnsignedChannelUpdate {
3653 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3654 short_channel_id: 3,
3657 cltv_expiry_delta: (3 << 8) | 0,
3658 htlc_minimum_msat: 0,
3659 htlc_maximum_msat: OptionalField::Absent,
3661 fee_proportional_millionths: 0,
3662 excess_data: Vec::new()
3664 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[2], NodeFeatures::from_le_bytes(id_to_feature_flags(2)), 0);
3666 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], &privkeys[4], ChannelFeatures::from_le_bytes(id_to_feature_flags(2)), 2);
3667 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3668 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3669 short_channel_id: 2,
3672 cltv_expiry_delta: (2 << 8) | 0,
3673 htlc_minimum_msat: 0,
3674 htlc_maximum_msat: OptionalField::Absent,
3676 fee_proportional_millionths: 0,
3677 excess_data: Vec::new()
3680 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], &privkeys[6], ChannelFeatures::from_le_bytes(id_to_feature_flags(1)), 1);
3681 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
3682 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3683 short_channel_id: 1,
3686 cltv_expiry_delta: (1 << 8) | 0,
3687 htlc_minimum_msat: 100,
3688 htlc_maximum_msat: OptionalField::Absent,
3690 fee_proportional_millionths: 0,
3691 excess_data: Vec::new()
3693 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[6], NodeFeatures::from_le_bytes(id_to_feature_flags(6)), 0);
3696 // Now ensure the route flows simply over nodes 1 and 4 to 6.
3697 let route = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[6], None, None, &Vec::new(), 10_000, 42, Arc::clone(&logger)).unwrap();
3698 assert_eq!(route.paths.len(), 1);
3699 assert_eq!(route.paths[0].len(), 3);
3701 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
3702 assert_eq!(route.paths[0][0].short_channel_id, 6);
3703 assert_eq!(route.paths[0][0].fee_msat, 100);
3704 assert_eq!(route.paths[0][0].cltv_expiry_delta, (5 << 8) | 0);
3705 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(1));
3706 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(6));
3708 assert_eq!(route.paths[0][1].pubkey, nodes[4]);
3709 assert_eq!(route.paths[0][1].short_channel_id, 5);
3710 assert_eq!(route.paths[0][1].fee_msat, 0);
3711 assert_eq!(route.paths[0][1].cltv_expiry_delta, (1 << 8) | 0);
3712 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(4));
3713 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(5));
3715 assert_eq!(route.paths[0][2].pubkey, nodes[6]);
3716 assert_eq!(route.paths[0][2].short_channel_id, 1);
3717 assert_eq!(route.paths[0][2].fee_msat, 10_000);
3718 assert_eq!(route.paths[0][2].cltv_expiry_delta, 42);
3719 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(6));
3720 assert_eq!(route.paths[0][2].channel_features.le_flags(), &id_to_feature_flags(1));
3726 fn exact_fee_liquidity_limit() {
3727 // Test that if, while walking the graph, we find a hop that has exactly enough liquidity
3728 // for us, including later hop fees, we take it. In the first version of our MPP algorithm
3729 // we calculated fees on a higher value, resulting in us ignoring such paths.
3730 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
3731 let (our_privkey, our_id, _, nodes) = get_nodes(&secp_ctx);
3733 // We modify the graph to set the htlc_maximum of channel 2 to below the value we wish to
3735 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3736 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3737 short_channel_id: 2,
3740 cltv_expiry_delta: 0,
3741 htlc_minimum_msat: 0,
3742 htlc_maximum_msat: OptionalField::Present(85_000),
3744 fee_proportional_millionths: 0,
3745 excess_data: Vec::new()
3748 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3749 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3750 short_channel_id: 12,
3753 cltv_expiry_delta: (4 << 8) | 1,
3754 htlc_minimum_msat: 0,
3755 htlc_maximum_msat: OptionalField::Present(270_000),
3757 fee_proportional_millionths: 1000000,
3758 excess_data: Vec::new()
3762 // Now, attempt to route 90 sats, which is exactly 90 sats at the last hop, plus the
3763 // 200% fee charged channel 13 in the 1-to-2 direction.
3764 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();
3765 assert_eq!(route.paths.len(), 1);
3766 assert_eq!(route.paths[0].len(), 2);
3768 assert_eq!(route.paths[0][0].pubkey, nodes[7]);
3769 assert_eq!(route.paths[0][0].short_channel_id, 12);
3770 assert_eq!(route.paths[0][0].fee_msat, 90_000*2);
3771 assert_eq!(route.paths[0][0].cltv_expiry_delta, (13 << 8) | 1);
3772 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(8));
3773 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(12));
3775 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
3776 assert_eq!(route.paths[0][1].short_channel_id, 13);
3777 assert_eq!(route.paths[0][1].fee_msat, 90_000);
3778 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
3779 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
3780 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(13));
3785 fn htlc_max_reduction_below_min() {
3786 // Test that if, while walking the graph, we reduce the value being sent to meet an
3787 // htlc_maximum_msat, we don't end up undershooting a later htlc_minimum_msat. In the
3788 // initial version of MPP we'd accept such routes but reject them while recalculating fees,
3789 // resulting in us thinking there is no possible path, even if other paths exist.
3790 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
3791 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3793 // We modify the graph to set the htlc_minimum of channel 2 and 4 as needed - channel 2
3794 // gets an htlc_maximum_msat of 80_000 and channel 4 an htlc_minimum_msat of 90_000. We
3795 // then try to send 90_000.
3796 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3797 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3798 short_channel_id: 2,
3801 cltv_expiry_delta: 0,
3802 htlc_minimum_msat: 0,
3803 htlc_maximum_msat: OptionalField::Present(80_000),
3805 fee_proportional_millionths: 0,
3806 excess_data: Vec::new()
3808 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
3809 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3810 short_channel_id: 4,
3813 cltv_expiry_delta: (4 << 8) | 1,
3814 htlc_minimum_msat: 90_000,
3815 htlc_maximum_msat: OptionalField::Absent,
3817 fee_proportional_millionths: 0,
3818 excess_data: Vec::new()
3822 // Now, attempt to route 90 sats, hitting the htlc_minimum on channel 4, but
3823 // overshooting the htlc_maximum on channel 2. Thus, we should pick the (absurdly
3824 // expensive) channels 12-13 path.
3825 let route = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2], Some(InvoiceFeatures::known()), None, &Vec::new(), 90_000, 42, Arc::clone(&logger)).unwrap();
3826 assert_eq!(route.paths.len(), 1);
3827 assert_eq!(route.paths[0].len(), 2);
3829 assert_eq!(route.paths[0][0].pubkey, nodes[7]);
3830 assert_eq!(route.paths[0][0].short_channel_id, 12);
3831 assert_eq!(route.paths[0][0].fee_msat, 90_000*2);
3832 assert_eq!(route.paths[0][0].cltv_expiry_delta, (13 << 8) | 1);
3833 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(8));
3834 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(12));
3836 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
3837 assert_eq!(route.paths[0][1].short_channel_id, 13);
3838 assert_eq!(route.paths[0][1].fee_msat, 90_000);
3839 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
3840 assert_eq!(route.paths[0][1].node_features.le_flags(), InvoiceFeatures::known().le_flags());
3841 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(13));
3845 #[cfg(not(feature = "no_std"))]
3846 pub(super) fn random_init_seed() -> u64 {
3847 // Because the default HashMap in std pulls OS randomness, we can use it as a (bad) RNG.
3848 use core::hash::{BuildHasher, Hasher};
3849 let seed = std::collections::hash_map::RandomState::new().build_hasher().finish();
3850 println!("Using seed of {}", seed);
3853 #[cfg(not(feature = "no_std"))]
3854 use util::ser::Readable;
3857 #[cfg(not(feature = "no_std"))]
3858 fn generate_routes() {
3859 let mut d = match super::test_utils::get_route_file() {
3866 let graph = NetworkGraph::read(&mut d).unwrap();
3868 // First, get 100 (source, destination) pairs for which route-getting actually succeeds...
3869 let mut seed = random_init_seed() as usize;
3870 'load_endpoints: for _ in 0..10 {
3872 seed = seed.overflowing_mul(0xdeadbeef).0;
3873 let src = graph.get_nodes().keys().skip(seed % graph.get_nodes().len()).next().unwrap();
3874 seed = seed.overflowing_mul(0xdeadbeef).0;
3875 let dst = graph.get_nodes().keys().skip(seed % graph.get_nodes().len()).next().unwrap();
3876 let amt = seed as u64 % 200_000_000;
3877 if get_route(src, &graph, dst, None, None, &[], amt, 42, &test_utils::TestLogger::new()).is_ok() {
3878 continue 'load_endpoints;
3885 #[cfg(not(feature = "no_std"))]
3886 fn generate_routes_mpp() {
3887 let mut d = match super::test_utils::get_route_file() {
3894 let graph = NetworkGraph::read(&mut d).unwrap();
3896 // First, get 100 (source, destination) pairs for which route-getting actually succeeds...
3897 let mut seed = random_init_seed() as usize;
3898 'load_endpoints: for _ in 0..10 {
3900 seed = seed.overflowing_mul(0xdeadbeef).0;
3901 let src = graph.get_nodes().keys().skip(seed % graph.get_nodes().len()).next().unwrap();
3902 seed = seed.overflowing_mul(0xdeadbeef).0;
3903 let dst = graph.get_nodes().keys().skip(seed % graph.get_nodes().len()).next().unwrap();
3904 let amt = seed as u64 % 200_000_000;
3905 if get_route(src, &graph, dst, Some(InvoiceFeatures::known()), None, &[], amt, 42, &test_utils::TestLogger::new()).is_ok() {
3906 continue 'load_endpoints;
3913 #[cfg(all(test, not(feature = "no_std")))]
3914 pub(crate) mod test_utils {
3916 /// Tries to open a network graph file, or panics with a URL to fetch it.
3917 pub(crate) fn get_route_file() -> Result<std::fs::File, &'static str> {
3918 let res = File::open("net_graph-2021-05-31.bin") // By default we're run in RL/lightning
3919 .or_else(|_| File::open("lightning/net_graph-2021-05-31.bin")) // We may be run manually in RL/
3920 .or_else(|_| { // Fall back to guessing based on the binary location
3921 // path is likely something like .../rust-lightning/target/debug/deps/lightning-...
3922 let mut path = std::env::current_exe().unwrap();
3923 path.pop(); // lightning-...
3925 path.pop(); // debug
3926 path.pop(); // target
3927 path.push("lightning");
3928 path.push("net_graph-2021-05-31.bin");
3929 eprintln!("{}", path.to_str().unwrap());
3932 .map_err(|_| "Please fetch https://bitcoin.ninja/ldk-net_graph-v0.0.15-2021-05-31.bin and place it at lightning/net_graph-2021-05-31.bin");
3933 #[cfg(require_route_graph_test)]
3934 return Ok(res.unwrap());
3935 #[cfg(not(require_route_graph_test))]
3940 #[cfg(all(test, feature = "unstable", not(feature = "no_std")))]
3943 use util::logger::{Logger, Record};
3947 struct DummyLogger {}
3948 impl Logger for DummyLogger {
3949 fn log(&self, _record: &Record) {}
3953 fn generate_routes(bench: &mut Bencher) {
3954 let mut d = test_utils::get_route_file().unwrap();
3955 let graph = NetworkGraph::read(&mut d).unwrap();
3957 // First, get 100 (source, destination) pairs for which route-getting actually succeeds...
3958 let mut path_endpoints = Vec::new();
3959 let mut seed: usize = 0xdeadbeef;
3960 'load_endpoints: for _ in 0..100 {
3963 let src = graph.get_nodes().keys().skip(seed % graph.get_nodes().len()).next().unwrap();
3965 let dst = graph.get_nodes().keys().skip(seed % graph.get_nodes().len()).next().unwrap();
3966 let amt = seed as u64 % 1_000_000;
3967 if get_route(src, &graph, dst, None, None, &[], amt, 42, &DummyLogger{}).is_ok() {
3968 path_endpoints.push((src, dst, amt));
3969 continue 'load_endpoints;
3974 // ...then benchmark finding paths between the nodes we learned.
3977 let (src, dst, amt) = path_endpoints[idx % path_endpoints.len()];
3978 assert!(get_route(src, &graph, dst, None, None, &[], amt, 42, &DummyLogger{}).is_ok());
3984 fn generate_mpp_routes(bench: &mut Bencher) {
3985 let mut d = test_utils::get_route_file().unwrap();
3986 let graph = NetworkGraph::read(&mut d).unwrap();
3988 // First, get 100 (source, destination) pairs for which route-getting actually succeeds...
3989 let mut path_endpoints = Vec::new();
3990 let mut seed: usize = 0xdeadbeef;
3991 'load_endpoints: for _ in 0..100 {
3994 let src = graph.get_nodes().keys().skip(seed % graph.get_nodes().len()).next().unwrap();
3996 let dst = graph.get_nodes().keys().skip(seed % graph.get_nodes().len()).next().unwrap();
3997 let amt = seed as u64 % 1_000_000;
3998 if get_route(src, &graph, dst, Some(InvoiceFeatures::known()), None, &[], amt, 42, &DummyLogger{}).is_ok() {
3999 path_endpoints.push((src, dst, amt));
4000 continue 'load_endpoints;
4005 // ...then benchmark finding paths between the nodes we learned.
4008 let (src, dst, amt) = path_endpoints[idx % path_endpoints.len()];
4009 assert!(get_route(src, &graph, dst, Some(InvoiceFeatures::known()), None, &[], amt, 42, &DummyLogger{}).is_ok());