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, {
52 (0, pubkey, required),
53 (2, node_features, required),
54 (4, short_channel_id, required),
55 (6, channel_features, required),
56 (8, fee_msat, required),
57 (10, cltv_expiry_delta, required),
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".
171 #[derive(Clone, Debug)]
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.counterparty.node_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.counterparty.node_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 log_trace!(logger, "Building path from {} (payee) to {} (us/payer) for value {} msat.", payee, our_node_id, final_value_msat);
511 macro_rules! add_entry {
512 // Adds entry which goes from $src_node_id to $dest_node_id
513 // over the channel with id $chan_id with fees described in
514 // $directional_info.
515 // $next_hops_fee_msat represents the fees paid for using all the channel *after* this one,
516 // since that value has to be transferred over this channel.
517 // Returns whether this channel caused an update to `targets`.
518 ( $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,
519 $next_hops_value_contribution: expr, $next_hops_path_htlc_minimum_msat: expr ) => { {
520 // We "return" whether we updated the path at the end, via this:
521 let mut did_add_update_path_to_src_node = false;
522 // Channels to self should not be used. This is more of belt-and-suspenders, because in
523 // practice these cases should be caught earlier:
524 // - for regular channels at channel announcement (TODO)
525 // - for first and last hops early in get_route
526 if $src_node_id != $dest_node_id.clone() {
527 let available_liquidity_msat = bookkeeped_channels_liquidity_available_msat.entry($chan_id.clone()).or_insert_with(|| {
528 let mut initial_liquidity_available_msat = None;
529 if let Some(capacity_sats) = $capacity_sats {
530 initial_liquidity_available_msat = Some(capacity_sats * 1000);
533 if let Some(htlc_maximum_msat) = $directional_info.htlc_maximum_msat {
534 if let Some(available_msat) = initial_liquidity_available_msat {
535 initial_liquidity_available_msat = Some(cmp::min(available_msat, htlc_maximum_msat));
537 initial_liquidity_available_msat = Some(htlc_maximum_msat);
541 match initial_liquidity_available_msat {
542 Some(available_msat) => available_msat,
543 // We assume channels with unknown balance have
544 // a capacity of 0.0025 BTC (or 250_000 sats).
545 None => 250_000 * 1000
549 // It is tricky to substract $next_hops_fee_msat from available liquidity here.
550 // It may be misleading because we might later choose to reduce the value transferred
551 // over these channels, and the channel which was insufficient might become sufficient.
552 // Worst case: we drop a good channel here because it can't cover the high following
553 // fees caused by one expensive channel, but then this channel could have been used
554 // if the amount being transferred over this path is lower.
555 // We do this for now, but this is a subject for removal.
556 if let Some(available_value_contribution_msat) = available_liquidity_msat.checked_sub($next_hops_fee_msat) {
558 // Routing Fragmentation Mitigation heuristic:
560 // Routing fragmentation across many payment paths increases the overall routing
561 // fees as you have irreducible routing fees per-link used (`fee_base_msat`).
562 // Taking too many smaller paths also increases the chance of payment failure.
563 // Thus to avoid this effect, we require from our collected links to provide
564 // at least a minimal contribution to the recommended value yet-to-be-fulfilled.
566 // This requirement is currently 5% of the remaining-to-be-collected value.
567 // This means as we successfully advance in our collection,
568 // the absolute liquidity contribution is lowered,
569 // thus increasing the number of potential channels to be selected.
571 // Derive the minimal liquidity contribution with a ratio of 20 (5%, rounded up)
572 // or 100% if we're not allowed to do multipath payments.
573 let minimal_value_contribution_msat: u64 = if allow_mpp {
574 (recommended_value_msat - already_collected_value_msat + 19) / 20
578 // Verify the liquidity offered by this channel complies to the minimal contribution.
579 let contributes_sufficient_value = available_value_contribution_msat >= minimal_value_contribution_msat;
581 let value_contribution_msat = cmp::min(available_value_contribution_msat, $next_hops_value_contribution);
582 // Includes paying fees for the use of the following channels.
583 let amount_to_transfer_over_msat: u64 = match value_contribution_msat.checked_add($next_hops_fee_msat) {
584 Some(result) => result,
585 // Can't overflow due to how the values were computed right above.
586 None => unreachable!(),
588 #[allow(unused_comparisons)] // $next_hops_path_htlc_minimum_msat is 0 in some calls so rustc complains
589 let over_path_minimum_msat = amount_to_transfer_over_msat >= $directional_info.htlc_minimum_msat &&
590 amount_to_transfer_over_msat >= $next_hops_path_htlc_minimum_msat;
592 // If HTLC minimum is larger than the amount we're going to transfer, we shouldn't
593 // bother considering this channel.
594 // Since we're choosing amount_to_transfer_over_msat as maximum possible, it can
595 // be only reduced later (not increased), so this channel should just be skipped
596 // as not sufficient.
597 if !over_path_minimum_msat {
598 hit_minimum_limit = true;
599 } else if contributes_sufficient_value {
600 // Note that low contribution here (limited by available_liquidity_msat)
601 // might violate htlc_minimum_msat on the hops which are next along the
602 // payment path (upstream to the payee). To avoid that, we recompute path
603 // path fees knowing the final path contribution after constructing it.
604 let path_htlc_minimum_msat = match compute_fees($next_hops_path_htlc_minimum_msat, $directional_info.fees)
605 .map(|fee_msat| fee_msat.checked_add($next_hops_path_htlc_minimum_msat)) {
606 Some(Some(value_msat)) => cmp::max(value_msat, $directional_info.htlc_minimum_msat),
607 _ => u64::max_value()
609 let hm_entry = dist.entry(&$src_node_id);
610 let old_entry = hm_entry.or_insert_with(|| {
611 // If there was previously no known way to access
612 // the source node (recall it goes payee-to-payer) of $chan_id, first add
613 // a semi-dummy record just to compute the fees to reach the source node.
614 // This will affect our decision on selecting $chan_id
615 // as a way to reach the $dest_node_id.
616 let mut fee_base_msat = u32::max_value();
617 let mut fee_proportional_millionths = u32::max_value();
618 if let Some(Some(fees)) = network.get_nodes().get(&$src_node_id).map(|node| node.lowest_inbound_channel_fees) {
619 fee_base_msat = fees.base_msat;
620 fee_proportional_millionths = fees.proportional_millionths;
623 pubkey: $dest_node_id.clone(),
625 channel_features: $chan_features,
627 cltv_expiry_delta: 0,
628 src_lowest_inbound_fees: RoutingFees {
629 base_msat: fee_base_msat,
630 proportional_millionths: fee_proportional_millionths,
632 channel_fees: $directional_info.fees,
633 next_hops_fee_msat: u64::max_value(),
634 hop_use_fee_msat: u64::max_value(),
635 total_fee_msat: u64::max_value(),
636 htlc_minimum_msat: $directional_info.htlc_minimum_msat,
637 path_htlc_minimum_msat,
638 was_processed: false,
639 #[cfg(any(test, feature = "fuzztarget"))]
640 value_contribution_msat,
644 #[allow(unused_mut)] // We only use the mut in cfg(test)
645 let mut should_process = !old_entry.was_processed;
646 #[cfg(any(test, feature = "fuzztarget"))]
648 // In test/fuzzing builds, we do extra checks to make sure the skipping
649 // of already-seen nodes only happens in cases we expect (see below).
650 if !should_process { should_process = true; }
654 let mut hop_use_fee_msat = 0;
655 let mut total_fee_msat = $next_hops_fee_msat;
657 // Ignore hop_use_fee_msat for channel-from-us as we assume all channels-from-us
658 // will have the same effective-fee
659 if $src_node_id != *our_node_id {
660 match compute_fees(amount_to_transfer_over_msat, $directional_info.fees) {
661 // max_value means we'll always fail
662 // the old_entry.total_fee_msat > total_fee_msat check
663 None => total_fee_msat = u64::max_value(),
665 hop_use_fee_msat = fee_msat;
666 total_fee_msat += hop_use_fee_msat;
667 // When calculating the lowest inbound fees to a node, we
668 // calculate fees here not based on the actual value we think
669 // will flow over this channel, but on the minimum value that
670 // we'll accept flowing over it. The minimum accepted value
671 // is a constant through each path collection run, ensuring
672 // consistent basis. Otherwise we may later find a
673 // different path to the source node that is more expensive,
674 // but which we consider to be cheaper because we are capacity
675 // constrained and the relative fee becomes lower.
676 match compute_fees(minimal_value_contribution_msat, old_entry.src_lowest_inbound_fees)
677 .map(|a| a.checked_add(total_fee_msat)) {
682 total_fee_msat = u64::max_value();
689 let new_graph_node = RouteGraphNode {
690 pubkey: $src_node_id,
691 lowest_fee_to_peer_through_node: total_fee_msat,
692 lowest_fee_to_node: $next_hops_fee_msat as u64 + hop_use_fee_msat,
693 value_contribution_msat: value_contribution_msat,
694 path_htlc_minimum_msat,
697 // Update the way of reaching $src_node_id with the given $chan_id (from $dest_node_id),
698 // if this way is cheaper than the already known
699 // (considering the cost to "reach" this channel from the route destination,
700 // the cost of using this channel,
701 // and the cost of routing to the source node of this channel).
702 // Also, consider that htlc_minimum_msat_difference, because we might end up
703 // paying it. Consider the following exploit:
704 // we use 2 paths to transfer 1.5 BTC. One of them is 0-fee normal 1 BTC path,
705 // and for the other one we picked a 1sat-fee path with htlc_minimum_msat of
706 // 1 BTC. Now, since the latter is more expensive, we gonna try to cut it
707 // by 0.5 BTC, but then match htlc_minimum_msat by paying a fee of 0.5 BTC
709 // Ideally the scoring could be smarter (e.g. 0.5*htlc_minimum_msat here),
710 // but it may require additional tracking - we don't want to double-count
711 // the fees included in $next_hops_path_htlc_minimum_msat, but also
712 // can't use something that may decrease on future hops.
713 let old_cost = cmp::max(old_entry.total_fee_msat, old_entry.path_htlc_minimum_msat);
714 let new_cost = cmp::max(total_fee_msat, path_htlc_minimum_msat);
716 if !old_entry.was_processed && new_cost < old_cost {
717 targets.push(new_graph_node);
718 old_entry.next_hops_fee_msat = $next_hops_fee_msat;
719 old_entry.hop_use_fee_msat = hop_use_fee_msat;
720 old_entry.total_fee_msat = total_fee_msat;
721 old_entry.pubkey = $dest_node_id.clone();
722 old_entry.short_channel_id = $chan_id.clone();
723 old_entry.channel_features = $chan_features;
724 old_entry.fee_msat = 0; // This value will be later filled with hop_use_fee_msat of the following channel
725 old_entry.cltv_expiry_delta = $directional_info.cltv_expiry_delta as u32;
726 old_entry.channel_fees = $directional_info.fees;
727 old_entry.htlc_minimum_msat = $directional_info.htlc_minimum_msat;
728 old_entry.path_htlc_minimum_msat = path_htlc_minimum_msat;
729 #[cfg(any(test, feature = "fuzztarget"))]
731 old_entry.value_contribution_msat = value_contribution_msat;
733 did_add_update_path_to_src_node = true;
734 } else if old_entry.was_processed && new_cost < old_cost {
735 #[cfg(any(test, feature = "fuzztarget"))]
737 // If we're skipping processing a node which was previously
738 // processed even though we found another path to it with a
739 // cheaper fee, check that it was because the second path we
740 // found (which we are processing now) has a lower value
741 // contribution due to an HTLC minimum limit.
743 // e.g. take a graph with two paths from node 1 to node 2, one
744 // through channel A, and one through channel B. Channel A and
745 // B are both in the to-process heap, with their scores set by
746 // a higher htlc_minimum than fee.
747 // Channel A is processed first, and the channels onwards from
748 // node 1 are added to the to-process heap. Thereafter, we pop
749 // Channel B off of the heap, note that it has a much more
750 // restrictive htlc_maximum_msat, and recalculate the fees for
751 // all of node 1's channels using the new, reduced, amount.
753 // This would be bogus - we'd be selecting a higher-fee path
754 // with a lower htlc_maximum_msat instead of the one we'd
755 // already decided to use.
756 debug_assert!(path_htlc_minimum_msat < old_entry.path_htlc_minimum_msat);
757 debug_assert!(value_contribution_msat < old_entry.value_contribution_msat);
764 did_add_update_path_to_src_node
768 let empty_node_features = NodeFeatures::empty();
769 // Find ways (channels with destination) to reach a given node and store them
770 // in the corresponding data structures (routing graph etc).
771 // $fee_to_target_msat represents how much it costs to reach to this node from the payee,
772 // meaning how much will be paid in fees after this node (to the best of our knowledge).
773 // This data can later be helpful to optimize routing (pay lower fees).
774 macro_rules! add_entries_to_cheapest_to_target_node {
775 ( $node: expr, $node_id: expr, $fee_to_target_msat: expr, $next_hops_value_contribution: expr, $next_hops_path_htlc_minimum_msat: expr ) => {
776 let skip_node = if let Some(elem) = dist.get_mut($node_id) {
777 let was_processed = elem.was_processed;
778 elem.was_processed = true;
781 // Entries are added to dist in add_entry!() when there is a channel from a node.
782 // Because there are no channels from payee, it will not have a dist entry at this point.
783 // If we're processing any other node, it is always be the result of a channel from it.
784 assert_eq!($node_id, payee);
789 if first_hops.is_some() {
790 if let Some(&(ref first_hop, ref features, ref outbound_capacity_msat, _)) = first_hop_targets.get(&$node_id) {
791 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);
795 let features = if let Some(node_info) = $node.announcement_info.as_ref() {
801 if !features.requires_unknown_bits() {
802 for chan_id in $node.channels.iter() {
803 let chan = network.get_channels().get(chan_id).unwrap();
804 if !chan.features.requires_unknown_bits() {
805 if chan.node_one == *$node_id {
806 // ie $node is one, ie next hop in A* is two, via the two_to_one channel
807 if first_hops.is_none() || chan.node_two != *our_node_id {
808 if let Some(two_to_one) = chan.two_to_one.as_ref() {
809 if two_to_one.enabled {
810 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);
815 if first_hops.is_none() || chan.node_one != *our_node_id {
816 if let Some(one_to_two) = chan.one_to_two.as_ref() {
817 if one_to_two.enabled {
818 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);
830 let mut payment_paths = Vec::<PaymentPath>::new();
832 // TODO: diversify by nodes (so that all paths aren't doomed if one node is offline).
833 'paths_collection: loop {
834 // For every new path, start from scratch, except
835 // bookkeeped_channels_liquidity_available_msat, which will improve
836 // the further iterations of path finding. Also don't erase first_hop_targets.
839 hit_minimum_limit = false;
841 // If first hop is a private channel and the only way to reach the payee, this is the only
842 // place where it could be added.
843 if first_hops.is_some() {
844 if let Some(&(ref first_hop, ref features, ref outbound_capacity_msat, _)) = first_hop_targets.get(&payee) {
845 add_entry!(first_hop, *our_node_id, payee, dummy_directional_info, Some(outbound_capacity_msat / 1000), features, 0, path_value_msat, 0);
849 // Add the payee as a target, so that the payee-to-payer
850 // search algorithm knows what to start with.
851 match network.get_nodes().get(payee) {
852 // The payee is not in our network graph, so nothing to add here.
853 // There is still a chance of reaching them via last_hops though,
854 // so don't yet fail the payment here.
855 // If not, targets.pop() will not even let us enter the loop in step 2.
858 add_entries_to_cheapest_to_target_node!(node, payee, 0, path_value_msat, 0);
863 // If a caller provided us with last hops, add them to routing targets. Since this happens
864 // earlier than general path finding, they will be somewhat prioritized, although currently
865 // it matters only if the fees are exactly the same.
866 for hop in last_hops.iter() {
867 let have_hop_src_in_graph =
868 // Only add the last hop to our candidate set if either we have a direct channel or
869 // they are in the regular network graph.
870 first_hop_targets.get(&hop.src_node_id).is_some() ||
871 network.get_nodes().get(&hop.src_node_id).is_some();
872 if have_hop_src_in_graph {
873 // BOLT 11 doesn't allow inclusion of features for the last hop hints, which
874 // really sucks, cause we're gonna need that eventually.
875 let last_hop_htlc_minimum_msat: u64 = match hop.htlc_minimum_msat {
876 Some(htlc_minimum_msat) => htlc_minimum_msat,
879 let directional_info = DummyDirectionalChannelInfo {
880 cltv_expiry_delta: hop.cltv_expiry_delta as u32,
881 htlc_minimum_msat: last_hop_htlc_minimum_msat,
882 htlc_maximum_msat: hop.htlc_maximum_msat,
885 // We assume that the recipient only included route hints for routes which had
886 // sufficient value to route `final_value_msat`. Note that in the case of "0-value"
887 // invoices where the invoice does not specify value this may not be the case, but
888 // better to include the hints than not.
889 if add_entry!(hop.short_channel_id, hop.src_node_id, payee, directional_info, Some((final_value_msat + 999) / 1000), &empty_channel_features, 0, path_value_msat, 0) {
890 // If this hop connects to a node with which we have a direct channel,
891 // ignore the network graph and, if the last hop was added, add our
892 // direct channel to the candidate set.
894 // Note that we *must* check if the last hop was added as `add_entry`
895 // always assumes that the third argument is a node to which we have a
897 if let Some(&(ref first_hop, ref features, ref outbound_capacity_msat, _)) = first_hop_targets.get(&hop.src_node_id) {
898 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);
904 log_trace!(logger, "Starting main path collection loop with {} nodes pre-filled from first/last hops.", targets.len());
906 // At this point, targets are filled with the data from first and
907 // last hops communicated by the caller, and the payment receiver.
908 let mut found_new_path = false;
911 // If this loop terminates due the exhaustion of targets, two situations are possible:
912 // - not enough outgoing liquidity:
913 // 0 < already_collected_value_msat < final_value_msat
914 // - enough outgoing liquidity:
915 // final_value_msat <= already_collected_value_msat < recommended_value_msat
916 // Both these cases (and other cases except reaching recommended_value_msat) mean that
917 // paths_collection will be stopped because found_new_path==false.
918 // This is not necessarily a routing failure.
919 'path_construction: while let Some(RouteGraphNode { pubkey, lowest_fee_to_node, value_contribution_msat, path_htlc_minimum_msat, .. }) = targets.pop() {
921 // Since we're going payee-to-payer, hitting our node as a target means we should stop
922 // traversing the graph and arrange the path out of what we found.
923 if pubkey == *our_node_id {
924 let mut new_entry = dist.remove(&our_node_id).unwrap();
925 let mut ordered_hops = vec!((new_entry.clone(), NodeFeatures::empty()));
928 if let Some(&(_, _, _, ref features)) = first_hop_targets.get(&ordered_hops.last().unwrap().0.pubkey) {
929 ordered_hops.last_mut().unwrap().1 = features.clone();
930 } else if let Some(node) = network.get_nodes().get(&ordered_hops.last().unwrap().0.pubkey) {
931 if let Some(node_info) = node.announcement_info.as_ref() {
932 ordered_hops.last_mut().unwrap().1 = node_info.features.clone();
934 ordered_hops.last_mut().unwrap().1 = NodeFeatures::empty();
937 // We should be able to fill in features for everything except the last
938 // hop, if the last hop was provided via a BOLT 11 invoice (though we
939 // should be able to extend it further as BOLT 11 does have feature
940 // flags for the last hop node itself).
941 assert!(ordered_hops.last().unwrap().0.pubkey == *payee);
944 // Means we succesfully traversed from the payer to the payee, now
945 // save this path for the payment route. Also, update the liquidity
946 // remaining on the used hops, so that we take them into account
947 // while looking for more paths.
948 if ordered_hops.last().unwrap().0.pubkey == *payee {
952 new_entry = match dist.remove(&ordered_hops.last().unwrap().0.pubkey) {
953 Some(payment_hop) => payment_hop,
954 // We can't arrive at None because, if we ever add an entry to targets,
955 // we also fill in the entry in dist (see add_entry!).
956 None => unreachable!(),
958 // We "propagate" the fees one hop backward (topologically) here,
959 // so that fees paid for a HTLC forwarding on the current channel are
960 // associated with the previous channel (where they will be subtracted).
961 ordered_hops.last_mut().unwrap().0.fee_msat = new_entry.hop_use_fee_msat;
962 ordered_hops.last_mut().unwrap().0.cltv_expiry_delta = new_entry.cltv_expiry_delta;
963 ordered_hops.push((new_entry.clone(), NodeFeatures::empty()));
965 ordered_hops.last_mut().unwrap().0.fee_msat = value_contribution_msat;
966 ordered_hops.last_mut().unwrap().0.hop_use_fee_msat = 0;
967 ordered_hops.last_mut().unwrap().0.cltv_expiry_delta = final_cltv;
969 log_trace!(logger, "Found a path back to us from the target with {} hops contributing up to {} msat: {:?}",
970 ordered_hops.len(), value_contribution_msat, ordered_hops);
972 let mut payment_path = PaymentPath {hops: ordered_hops};
974 // We could have possibly constructed a slightly inconsistent path: since we reduce
975 // value being transferred along the way, we could have violated htlc_minimum_msat
976 // on some channels we already passed (assuming dest->source direction). Here, we
977 // recompute the fees again, so that if that's the case, we match the currently
978 // underpaid htlc_minimum_msat with fees.
979 payment_path.update_value_and_recompute_fees(cmp::min(value_contribution_msat, final_value_msat));
981 // Since a path allows to transfer as much value as
982 // the smallest channel it has ("bottleneck"), we should recompute
983 // the fees so sender HTLC don't overpay fees when traversing
984 // larger channels than the bottleneck. This may happen because
985 // when we were selecting those channels we were not aware how much value
986 // this path will transfer, and the relative fee for them
987 // might have been computed considering a larger value.
988 // Remember that we used these channels so that we don't rely
989 // on the same liquidity in future paths.
990 let mut prevented_redundant_path_selection = false;
991 for (payment_hop, _) in payment_path.hops.iter() {
992 let channel_liquidity_available_msat = bookkeeped_channels_liquidity_available_msat.get_mut(&payment_hop.short_channel_id).unwrap();
993 let mut spent_on_hop_msat = value_contribution_msat;
994 let next_hops_fee_msat = payment_hop.next_hops_fee_msat;
995 spent_on_hop_msat += next_hops_fee_msat;
996 if spent_on_hop_msat == *channel_liquidity_available_msat {
997 // If this path used all of this channel's available liquidity, we know
998 // this path will not be selected again in the next loop iteration.
999 prevented_redundant_path_selection = true;
1001 *channel_liquidity_available_msat -= spent_on_hop_msat;
1003 if !prevented_redundant_path_selection {
1004 // If we weren't capped by hitting a liquidity limit on a channel in the path,
1005 // we'll probably end up picking the same path again on the next iteration.
1006 // Decrease the available liquidity of a hop in the middle of the path.
1007 let victim_scid = payment_path.hops[(payment_path.hops.len() - 1) / 2].0.short_channel_id;
1008 log_trace!(logger, "Disabling channel {} for future path building iterations to avoid duplicates.", victim_scid);
1009 let victim_liquidity = bookkeeped_channels_liquidity_available_msat.get_mut(&victim_scid).unwrap();
1010 *victim_liquidity = 0;
1013 // Track the total amount all our collected paths allow to send so that we:
1014 // - know when to stop looking for more paths
1015 // - know which of the hops are useless considering how much more sats we need
1016 // (contributes_sufficient_value)
1017 already_collected_value_msat += value_contribution_msat;
1019 payment_paths.push(payment_path);
1020 found_new_path = true;
1021 break 'path_construction;
1024 // If we found a path back to the payee, we shouldn't try to process it again. This is
1025 // the equivalent of the `elem.was_processed` check in
1026 // add_entries_to_cheapest_to_target_node!() (see comment there for more info).
1027 if pubkey == *payee { continue 'path_construction; }
1029 // Otherwise, since the current target node is not us,
1030 // keep "unrolling" the payment graph from payee to payer by
1031 // finding a way to reach the current target from the payer side.
1032 match network.get_nodes().get(&pubkey) {
1035 add_entries_to_cheapest_to_target_node!(node, &pubkey, lowest_fee_to_node, value_contribution_msat, path_htlc_minimum_msat);
1041 // If we don't support MPP, no use trying to gather more value ever.
1042 break 'paths_collection;
1046 // Stop either when the recommended value is reached or if no new path was found in this
1048 // In the latter case, making another path finding attempt won't help,
1049 // because we deterministically terminated the search due to low liquidity.
1050 if already_collected_value_msat >= recommended_value_msat || !found_new_path {
1051 log_trace!(logger, "Have now collected {} msat (seeking {} msat) in paths. Last path loop {} a new path.",
1052 already_collected_value_msat, recommended_value_msat, if found_new_path { "found" } else { "did not find" });
1053 break 'paths_collection;
1054 } else if found_new_path && already_collected_value_msat == final_value_msat && payment_paths.len() == 1 {
1055 // Further, if this was our first walk of the graph, and we weren't limited by an
1056 // htlc_minimum_msat, return immediately because this path should suffice. If we were
1057 // limited by an htlc_minimum_msat value, find another path with a higher value,
1058 // potentially allowing us to pay fees to meet the htlc_minimum on the new path while
1059 // still keeping a lower total fee than this path.
1060 if !hit_minimum_limit {
1061 log_trace!(logger, "Collected exactly our payment amount on the first pass, without hitting an htlc_minimum_msat limit, exiting.");
1062 break 'paths_collection;
1064 log_trace!(logger, "Collected our payment amount on the first pass, but running again to collect extra paths with a potentially higher limit.");
1065 path_value_msat = recommended_value_msat;
1070 if payment_paths.len() == 0 {
1071 return Err(LightningError{err: "Failed to find a path to the given destination".to_owned(), action: ErrorAction::IgnoreError});
1074 if already_collected_value_msat < final_value_msat {
1075 return Err(LightningError{err: "Failed to find a sufficient route to the given destination".to_owned(), action: ErrorAction::IgnoreError});
1078 // Sort by total fees and take the best paths.
1079 payment_paths.sort_by_key(|path| path.get_total_fee_paid_msat());
1080 if payment_paths.len() > 50 {
1081 payment_paths.truncate(50);
1084 // Draw multiple sufficient routes by randomly combining the selected paths.
1085 let mut drawn_routes = Vec::new();
1086 for i in 0..payment_paths.len() {
1087 let mut cur_route = Vec::<PaymentPath>::new();
1088 let mut aggregate_route_value_msat = 0;
1091 // TODO: real random shuffle
1092 // Currently just starts with i_th and goes up to i-1_th in a looped way.
1093 let cur_payment_paths = [&payment_paths[i..], &payment_paths[..i]].concat();
1096 for payment_path in cur_payment_paths {
1097 cur_route.push(payment_path.clone());
1098 aggregate_route_value_msat += payment_path.get_value_msat();
1099 if aggregate_route_value_msat > final_value_msat {
1100 // Last path likely overpaid. Substract it from the most expensive
1101 // (in terms of proportional fee) path in this route and recompute fees.
1102 // This might be not the most economically efficient way, but fewer paths
1103 // also makes routing more reliable.
1104 let mut overpaid_value_msat = aggregate_route_value_msat - final_value_msat;
1106 // First, drop some expensive low-value paths entirely if possible.
1107 // Sort by value so that we drop many really-low values first, since
1108 // fewer paths is better: the payment is less likely to fail.
1109 // TODO: this could also be optimized by also sorting by feerate_per_sat_routed,
1110 // so that the sender pays less fees overall. And also htlc_minimum_msat.
1111 cur_route.sort_by_key(|path| path.get_value_msat());
1112 // We should make sure that at least 1 path left.
1113 let mut paths_left = cur_route.len();
1114 cur_route.retain(|path| {
1115 if paths_left == 1 {
1118 let mut keep = true;
1119 let path_value_msat = path.get_value_msat();
1120 if path_value_msat <= overpaid_value_msat {
1122 overpaid_value_msat -= path_value_msat;
1128 if overpaid_value_msat == 0 {
1132 assert!(cur_route.len() > 0);
1135 // Now, substract the overpaid value from the most-expensive path.
1136 // TODO: this could also be optimized by also sorting by feerate_per_sat_routed,
1137 // so that the sender pays less fees overall. And also htlc_minimum_msat.
1138 cur_route.sort_by_key(|path| { path.hops.iter().map(|hop| hop.0.channel_fees.proportional_millionths as u64).sum::<u64>() });
1139 let expensive_payment_path = cur_route.first_mut().unwrap();
1140 // We already dropped all the small channels above, meaning all the
1141 // remaining channels are larger than remaining overpaid_value_msat.
1142 // Thus, this can't be negative.
1143 let expensive_path_new_value_msat = expensive_payment_path.get_value_msat() - overpaid_value_msat;
1144 expensive_payment_path.update_value_and_recompute_fees(expensive_path_new_value_msat);
1148 drawn_routes.push(cur_route);
1152 // Select the best route by lowest total fee.
1153 drawn_routes.sort_by_key(|paths| paths.iter().map(|path| path.get_total_fee_paid_msat()).sum::<u64>());
1154 let mut selected_paths = Vec::<Vec<RouteHop>>::new();
1155 for payment_path in drawn_routes.first().unwrap() {
1156 selected_paths.push(payment_path.hops.iter().map(|(payment_hop, node_features)| {
1158 pubkey: payment_hop.pubkey,
1159 node_features: node_features.clone(),
1160 short_channel_id: payment_hop.short_channel_id,
1161 channel_features: payment_hop.channel_features.clone(),
1162 fee_msat: payment_hop.fee_msat,
1163 cltv_expiry_delta: payment_hop.cltv_expiry_delta,
1168 if let Some(features) = &payee_features {
1169 for path in selected_paths.iter_mut() {
1170 path.last_mut().unwrap().node_features = features.to_context();
1174 let route = Route { paths: selected_paths };
1175 log_info!(logger, "Got route to {}: {}", payee, log_route!(route));
1181 use routing::router::{get_route, Route, RouteHint, RouteHintHop, RoutingFees};
1182 use routing::network_graph::{NetworkGraph, NetGraphMsgHandler};
1183 use chain::transaction::OutPoint;
1184 use ln::features::{ChannelFeatures, InitFeatures, InvoiceFeatures, NodeFeatures};
1185 use ln::msgs::{ErrorAction, LightningError, OptionalField, UnsignedChannelAnnouncement, ChannelAnnouncement, RoutingMessageHandler,
1186 NodeAnnouncement, UnsignedNodeAnnouncement, ChannelUpdate, UnsignedChannelUpdate};
1187 use ln::channelmanager;
1188 use util::test_utils;
1189 use util::ser::Writeable;
1191 use bitcoin::hashes::sha256d::Hash as Sha256dHash;
1192 use bitcoin::hashes::Hash;
1193 use bitcoin::network::constants::Network;
1194 use bitcoin::blockdata::constants::genesis_block;
1195 use bitcoin::blockdata::script::Builder;
1196 use bitcoin::blockdata::opcodes;
1197 use bitcoin::blockdata::transaction::TxOut;
1201 use bitcoin::secp256k1::key::{PublicKey,SecretKey};
1202 use bitcoin::secp256k1::{Secp256k1, All};
1205 use sync::{self, Arc};
1207 fn get_channel_details(short_channel_id: Option<u64>, node_id: PublicKey,
1208 features: InitFeatures, outbound_capacity_msat: u64) -> channelmanager::ChannelDetails {
1209 channelmanager::ChannelDetails {
1210 channel_id: [0; 32],
1211 counterparty: channelmanager::ChannelCounterparty {
1214 unspendable_punishment_reserve: 0,
1215 forwarding_info: None,
1217 funding_txo: Some(OutPoint { txid: bitcoin::Txid::from_slice(&[0; 32]).unwrap(), index: 0 }),
1219 channel_value_satoshis: 0,
1221 outbound_capacity_msat,
1222 inbound_capacity_msat: 42,
1223 unspendable_punishment_reserve: None,
1224 confirmations_required: None,
1225 force_close_spend_delay: None,
1226 is_outbound: true, is_funding_locked: true,
1227 is_usable: true, is_public: true,
1231 // Using the same keys for LN and BTC ids
1232 fn add_channel(net_graph_msg_handler: &NetGraphMsgHandler<Arc<test_utils::TestChainSource>, Arc<test_utils::TestLogger>>, secp_ctx: &Secp256k1<All>, node_1_privkey: &SecretKey,
1233 node_2_privkey: &SecretKey, features: ChannelFeatures, short_channel_id: u64) {
1234 let node_id_1 = PublicKey::from_secret_key(&secp_ctx, node_1_privkey);
1235 let node_id_2 = PublicKey::from_secret_key(&secp_ctx, node_2_privkey);
1237 let unsigned_announcement = UnsignedChannelAnnouncement {
1239 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1243 bitcoin_key_1: node_id_1,
1244 bitcoin_key_2: node_id_2,
1245 excess_data: Vec::new(),
1248 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1249 let valid_announcement = ChannelAnnouncement {
1250 node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
1251 node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
1252 bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
1253 bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
1254 contents: unsigned_announcement.clone(),
1256 match net_graph_msg_handler.handle_channel_announcement(&valid_announcement) {
1257 Ok(res) => assert!(res),
1262 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) {
1263 let msghash = hash_to_message!(&Sha256dHash::hash(&update.encode()[..])[..]);
1264 let valid_channel_update = ChannelUpdate {
1265 signature: secp_ctx.sign(&msghash, node_privkey),
1266 contents: update.clone()
1269 match net_graph_msg_handler.handle_channel_update(&valid_channel_update) {
1270 Ok(res) => assert!(res),
1275 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,
1276 features: NodeFeatures, timestamp: u32) {
1277 let node_id = PublicKey::from_secret_key(&secp_ctx, node_privkey);
1278 let unsigned_announcement = UnsignedNodeAnnouncement {
1284 addresses: Vec::new(),
1285 excess_address_data: Vec::new(),
1286 excess_data: Vec::new(),
1288 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1289 let valid_announcement = NodeAnnouncement {
1290 signature: secp_ctx.sign(&msghash, node_privkey),
1291 contents: unsigned_announcement.clone()
1294 match net_graph_msg_handler.handle_node_announcement(&valid_announcement) {
1300 fn get_nodes(secp_ctx: &Secp256k1<All>) -> (SecretKey, PublicKey, Vec<SecretKey>, Vec<PublicKey>) {
1301 let privkeys: Vec<SecretKey> = (2..10).map(|i| {
1302 SecretKey::from_slice(&hex::decode(format!("{:02}", i).repeat(32)).unwrap()[..]).unwrap()
1305 let pubkeys = privkeys.iter().map(|secret| PublicKey::from_secret_key(&secp_ctx, secret)).collect();
1307 let our_privkey = SecretKey::from_slice(&hex::decode("01".repeat(32)).unwrap()[..]).unwrap();
1308 let our_id = PublicKey::from_secret_key(&secp_ctx, &our_privkey);
1310 (our_privkey, our_id, privkeys, pubkeys)
1313 fn id_to_feature_flags(id: u8) -> Vec<u8> {
1314 // Set the feature flags to the id'th odd (ie non-required) feature bit so that we can
1315 // test for it later.
1316 let idx = (id - 1) * 2 + 1;
1318 vec![1 << (idx - 8*3), 0, 0, 0]
1319 } else if idx > 8*2 {
1320 vec![1 << (idx - 8*2), 0, 0]
1321 } else if idx > 8*1 {
1322 vec![1 << (idx - 8*1), 0]
1328 fn build_graph() -> (Secp256k1<All>, NetGraphMsgHandler<sync::Arc<test_utils::TestChainSource>, sync::Arc<crate::util::test_utils::TestLogger>>, sync::Arc<test_utils::TestChainSource>, sync::Arc<test_utils::TestLogger>) {
1329 let secp_ctx = Secp256k1::new();
1330 let logger = Arc::new(test_utils::TestLogger::new());
1331 let chain_monitor = Arc::new(test_utils::TestChainSource::new(Network::Testnet));
1332 let net_graph_msg_handler = NetGraphMsgHandler::new(genesis_block(Network::Testnet).header.block_hash(), None, Arc::clone(&logger));
1333 // Build network from our_id to node7:
1335 // -1(1)2- node0 -1(3)2-
1337 // our_id -1(12)2- node7 -1(13)2--- node2
1339 // -1(2)2- node1 -1(4)2-
1342 // chan1 1-to-2: disabled
1343 // chan1 2-to-1: enabled, 0 fee
1345 // chan2 1-to-2: enabled, ignored fee
1346 // chan2 2-to-1: enabled, 0 fee
1348 // chan3 1-to-2: enabled, 0 fee
1349 // chan3 2-to-1: enabled, 100 msat fee
1351 // chan4 1-to-2: enabled, 100% fee
1352 // chan4 2-to-1: enabled, 0 fee
1354 // chan12 1-to-2: enabled, ignored fee
1355 // chan12 2-to-1: enabled, 0 fee
1357 // chan13 1-to-2: enabled, 200% fee
1358 // chan13 2-to-1: enabled, 0 fee
1361 // -1(5)2- node3 -1(8)2--
1365 // node2--1(6)2- node4 -1(9)2--- node6 (not in global route map)
1367 // -1(7)2- node5 -1(10)2-
1369 // chan5 1-to-2: enabled, 100 msat fee
1370 // chan5 2-to-1: enabled, 0 fee
1372 // chan6 1-to-2: enabled, 0 fee
1373 // chan6 2-to-1: enabled, 0 fee
1375 // chan7 1-to-2: enabled, 100% fee
1376 // chan7 2-to-1: enabled, 0 fee
1378 // chan8 1-to-2: enabled, variable fee (0 then 1000 msat)
1379 // chan8 2-to-1: enabled, 0 fee
1381 // chan9 1-to-2: enabled, 1001 msat fee
1382 // chan9 2-to-1: enabled, 0 fee
1384 // chan10 1-to-2: enabled, 0 fee
1385 // chan10 2-to-1: enabled, 0 fee
1387 // chan11 1-to-2: enabled, 0 fee
1388 // chan11 2-to-1: enabled, 0 fee
1390 let (our_privkey, _, privkeys, _) = get_nodes(&secp_ctx);
1392 add_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, &privkeys[0], ChannelFeatures::from_le_bytes(id_to_feature_flags(1)), 1);
1393 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
1394 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1395 short_channel_id: 1,
1398 cltv_expiry_delta: 0,
1399 htlc_minimum_msat: 0,
1400 htlc_maximum_msat: OptionalField::Absent,
1402 fee_proportional_millionths: 0,
1403 excess_data: Vec::new()
1406 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[0], NodeFeatures::from_le_bytes(id_to_feature_flags(1)), 0);
1408 add_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, &privkeys[1], ChannelFeatures::from_le_bytes(id_to_feature_flags(2)), 2);
1409 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
1410 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1411 short_channel_id: 2,
1414 cltv_expiry_delta: u16::max_value(),
1415 htlc_minimum_msat: 0,
1416 htlc_maximum_msat: OptionalField::Absent,
1417 fee_base_msat: u32::max_value(),
1418 fee_proportional_millionths: u32::max_value(),
1419 excess_data: Vec::new()
1421 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
1422 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1423 short_channel_id: 2,
1426 cltv_expiry_delta: 0,
1427 htlc_minimum_msat: 0,
1428 htlc_maximum_msat: OptionalField::Absent,
1430 fee_proportional_millionths: 0,
1431 excess_data: Vec::new()
1434 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[1], NodeFeatures::from_le_bytes(id_to_feature_flags(2)), 0);
1436 add_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, &privkeys[7], ChannelFeatures::from_le_bytes(id_to_feature_flags(12)), 12);
1437 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
1438 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1439 short_channel_id: 12,
1442 cltv_expiry_delta: u16::max_value(),
1443 htlc_minimum_msat: 0,
1444 htlc_maximum_msat: OptionalField::Absent,
1445 fee_base_msat: u32::max_value(),
1446 fee_proportional_millionths: u32::max_value(),
1447 excess_data: Vec::new()
1449 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
1450 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1451 short_channel_id: 12,
1454 cltv_expiry_delta: 0,
1455 htlc_minimum_msat: 0,
1456 htlc_maximum_msat: OptionalField::Absent,
1458 fee_proportional_millionths: 0,
1459 excess_data: Vec::new()
1462 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[7], NodeFeatures::from_le_bytes(id_to_feature_flags(8)), 0);
1464 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], &privkeys[2], ChannelFeatures::from_le_bytes(id_to_feature_flags(3)), 3);
1465 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
1466 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1467 short_channel_id: 3,
1470 cltv_expiry_delta: (3 << 8) | 1,
1471 htlc_minimum_msat: 0,
1472 htlc_maximum_msat: OptionalField::Absent,
1474 fee_proportional_millionths: 0,
1475 excess_data: Vec::new()
1477 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
1478 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1479 short_channel_id: 3,
1482 cltv_expiry_delta: (3 << 8) | 2,
1483 htlc_minimum_msat: 0,
1484 htlc_maximum_msat: OptionalField::Absent,
1486 fee_proportional_millionths: 0,
1487 excess_data: Vec::new()
1490 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], &privkeys[2], ChannelFeatures::from_le_bytes(id_to_feature_flags(4)), 4);
1491 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
1492 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1493 short_channel_id: 4,
1496 cltv_expiry_delta: (4 << 8) | 1,
1497 htlc_minimum_msat: 0,
1498 htlc_maximum_msat: OptionalField::Absent,
1500 fee_proportional_millionths: 1000000,
1501 excess_data: Vec::new()
1503 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
1504 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1505 short_channel_id: 4,
1508 cltv_expiry_delta: (4 << 8) | 2,
1509 htlc_minimum_msat: 0,
1510 htlc_maximum_msat: OptionalField::Absent,
1512 fee_proportional_millionths: 0,
1513 excess_data: Vec::new()
1516 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], &privkeys[2], ChannelFeatures::from_le_bytes(id_to_feature_flags(13)), 13);
1517 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
1518 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1519 short_channel_id: 13,
1522 cltv_expiry_delta: (13 << 8) | 1,
1523 htlc_minimum_msat: 0,
1524 htlc_maximum_msat: OptionalField::Absent,
1526 fee_proportional_millionths: 2000000,
1527 excess_data: Vec::new()
1529 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
1530 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1531 short_channel_id: 13,
1534 cltv_expiry_delta: (13 << 8) | 2,
1535 htlc_minimum_msat: 0,
1536 htlc_maximum_msat: OptionalField::Absent,
1538 fee_proportional_millionths: 0,
1539 excess_data: Vec::new()
1542 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[2], NodeFeatures::from_le_bytes(id_to_feature_flags(3)), 0);
1544 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], &privkeys[4], ChannelFeatures::from_le_bytes(id_to_feature_flags(6)), 6);
1545 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
1546 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1547 short_channel_id: 6,
1550 cltv_expiry_delta: (6 << 8) | 1,
1551 htlc_minimum_msat: 0,
1552 htlc_maximum_msat: OptionalField::Absent,
1554 fee_proportional_millionths: 0,
1555 excess_data: Vec::new()
1557 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
1558 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1559 short_channel_id: 6,
1562 cltv_expiry_delta: (6 << 8) | 2,
1563 htlc_minimum_msat: 0,
1564 htlc_maximum_msat: OptionalField::Absent,
1566 fee_proportional_millionths: 0,
1567 excess_data: Vec::new(),
1570 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(11)), 11);
1571 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
1572 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1573 short_channel_id: 11,
1576 cltv_expiry_delta: (11 << 8) | 1,
1577 htlc_minimum_msat: 0,
1578 htlc_maximum_msat: OptionalField::Absent,
1580 fee_proportional_millionths: 0,
1581 excess_data: Vec::new()
1583 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[3], UnsignedChannelUpdate {
1584 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1585 short_channel_id: 11,
1588 cltv_expiry_delta: (11 << 8) | 2,
1589 htlc_minimum_msat: 0,
1590 htlc_maximum_msat: OptionalField::Absent,
1592 fee_proportional_millionths: 0,
1593 excess_data: Vec::new()
1596 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[4], NodeFeatures::from_le_bytes(id_to_feature_flags(5)), 0);
1598 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[3], NodeFeatures::from_le_bytes(id_to_feature_flags(4)), 0);
1600 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], &privkeys[5], ChannelFeatures::from_le_bytes(id_to_feature_flags(7)), 7);
1601 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
1602 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1603 short_channel_id: 7,
1606 cltv_expiry_delta: (7 << 8) | 1,
1607 htlc_minimum_msat: 0,
1608 htlc_maximum_msat: OptionalField::Absent,
1610 fee_proportional_millionths: 1000000,
1611 excess_data: Vec::new()
1613 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[5], UnsignedChannelUpdate {
1614 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1615 short_channel_id: 7,
1618 cltv_expiry_delta: (7 << 8) | 2,
1619 htlc_minimum_msat: 0,
1620 htlc_maximum_msat: OptionalField::Absent,
1622 fee_proportional_millionths: 0,
1623 excess_data: Vec::new()
1626 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[5], NodeFeatures::from_le_bytes(id_to_feature_flags(6)), 0);
1628 (secp_ctx, net_graph_msg_handler, chain_monitor, logger)
1632 fn simple_route_test() {
1633 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
1634 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
1636 // Simple route to 2 via 1
1638 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2], None, None, &Vec::new(), 0, 42, Arc::clone(&logger)) {
1639 assert_eq!(err, "Cannot send a payment of 0 msat");
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);
1645 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
1646 assert_eq!(route.paths[0][0].short_channel_id, 2);
1647 assert_eq!(route.paths[0][0].fee_msat, 100);
1648 assert_eq!(route.paths[0][0].cltv_expiry_delta, (4 << 8) | 1);
1649 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
1650 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
1652 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
1653 assert_eq!(route.paths[0][1].short_channel_id, 4);
1654 assert_eq!(route.paths[0][1].fee_msat, 100);
1655 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
1656 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
1657 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
1661 fn invalid_first_hop_test() {
1662 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
1663 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
1665 // Simple route to 2 via 1
1667 let our_chans = vec![get_channel_details(Some(2), our_id, InitFeatures::from_le_bytes(vec![0b11]), 100000)];
1669 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)) {
1670 assert_eq!(err, "First hop cannot have our_node_id as a destination.");
1671 } else { panic!(); }
1673 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();
1674 assert_eq!(route.paths[0].len(), 2);
1678 fn htlc_minimum_test() {
1679 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
1680 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
1682 // Simple route to 2 via 1
1684 // Disable other paths
1685 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
1686 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1687 short_channel_id: 12,
1689 flags: 2, // to disable
1690 cltv_expiry_delta: 0,
1691 htlc_minimum_msat: 0,
1692 htlc_maximum_msat: OptionalField::Absent,
1694 fee_proportional_millionths: 0,
1695 excess_data: Vec::new()
1697 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
1698 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1699 short_channel_id: 3,
1701 flags: 2, // to disable
1702 cltv_expiry_delta: 0,
1703 htlc_minimum_msat: 0,
1704 htlc_maximum_msat: OptionalField::Absent,
1706 fee_proportional_millionths: 0,
1707 excess_data: Vec::new()
1709 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
1710 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1711 short_channel_id: 13,
1713 flags: 2, // to disable
1714 cltv_expiry_delta: 0,
1715 htlc_minimum_msat: 0,
1716 htlc_maximum_msat: OptionalField::Absent,
1718 fee_proportional_millionths: 0,
1719 excess_data: Vec::new()
1721 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
1722 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1723 short_channel_id: 6,
1725 flags: 2, // to disable
1726 cltv_expiry_delta: 0,
1727 htlc_minimum_msat: 0,
1728 htlc_maximum_msat: OptionalField::Absent,
1730 fee_proportional_millionths: 0,
1731 excess_data: Vec::new()
1733 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
1734 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1735 short_channel_id: 7,
1737 flags: 2, // to disable
1738 cltv_expiry_delta: 0,
1739 htlc_minimum_msat: 0,
1740 htlc_maximum_msat: OptionalField::Absent,
1742 fee_proportional_millionths: 0,
1743 excess_data: Vec::new()
1746 // Check against amount_to_transfer_over_msat.
1747 // Set minimal HTLC of 200_000_000 msat.
1748 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
1749 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1750 short_channel_id: 2,
1753 cltv_expiry_delta: 0,
1754 htlc_minimum_msat: 200_000_000,
1755 htlc_maximum_msat: OptionalField::Absent,
1757 fee_proportional_millionths: 0,
1758 excess_data: Vec::new()
1761 // Second hop only allows to forward 199_999_999 at most, thus not allowing the first hop to
1763 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
1764 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1765 short_channel_id: 4,
1768 cltv_expiry_delta: 0,
1769 htlc_minimum_msat: 0,
1770 htlc_maximum_msat: OptionalField::Present(199_999_999),
1772 fee_proportional_millionths: 0,
1773 excess_data: Vec::new()
1776 // Not possible to send 199_999_999, because the minimum on channel=2 is 200_000_000.
1777 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)) {
1778 assert_eq!(err, "Failed to find a path to the given destination");
1779 } else { panic!(); }
1781 // Lift the restriction on the first hop.
1782 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
1783 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1784 short_channel_id: 2,
1787 cltv_expiry_delta: 0,
1788 htlc_minimum_msat: 0,
1789 htlc_maximum_msat: OptionalField::Absent,
1791 fee_proportional_millionths: 0,
1792 excess_data: Vec::new()
1795 // A payment above the minimum should pass
1796 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();
1797 assert_eq!(route.paths[0].len(), 2);
1801 fn htlc_minimum_overpay_test() {
1802 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
1803 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
1805 // A route to node#2 via two paths.
1806 // One path allows transferring 35-40 sats, another one also allows 35-40 sats.
1807 // Thus, they can't send 60 without overpaying.
1808 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
1809 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1810 short_channel_id: 2,
1813 cltv_expiry_delta: 0,
1814 htlc_minimum_msat: 35_000,
1815 htlc_maximum_msat: OptionalField::Present(40_000),
1817 fee_proportional_millionths: 0,
1818 excess_data: Vec::new()
1820 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
1821 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1822 short_channel_id: 12,
1825 cltv_expiry_delta: 0,
1826 htlc_minimum_msat: 35_000,
1827 htlc_maximum_msat: OptionalField::Present(40_000),
1829 fee_proportional_millionths: 0,
1830 excess_data: Vec::new()
1834 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
1835 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1836 short_channel_id: 13,
1839 cltv_expiry_delta: 0,
1840 htlc_minimum_msat: 0,
1841 htlc_maximum_msat: OptionalField::Absent,
1843 fee_proportional_millionths: 0,
1844 excess_data: Vec::new()
1846 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
1847 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1848 short_channel_id: 4,
1851 cltv_expiry_delta: 0,
1852 htlc_minimum_msat: 0,
1853 htlc_maximum_msat: OptionalField::Absent,
1855 fee_proportional_millionths: 0,
1856 excess_data: Vec::new()
1859 // Disable other paths
1860 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
1861 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1862 short_channel_id: 1,
1864 flags: 2, // to disable
1865 cltv_expiry_delta: 0,
1866 htlc_minimum_msat: 0,
1867 htlc_maximum_msat: OptionalField::Absent,
1869 fee_proportional_millionths: 0,
1870 excess_data: Vec::new()
1873 let route = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2],
1874 Some(InvoiceFeatures::known()), None, &Vec::new(), 60_000, 42, Arc::clone(&logger)).unwrap();
1875 // Overpay fees to hit htlc_minimum_msat.
1876 let overpaid_fees = route.paths[0][0].fee_msat + route.paths[1][0].fee_msat;
1877 // TODO: this could be better balanced to overpay 10k and not 15k.
1878 assert_eq!(overpaid_fees, 15_000);
1880 // Now, test that if there are 2 paths, a "cheaper" by fee path wouldn't be prioritized
1881 // while taking even more fee to match htlc_minimum_msat.
1882 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
1883 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1884 short_channel_id: 12,
1887 cltv_expiry_delta: 0,
1888 htlc_minimum_msat: 65_000,
1889 htlc_maximum_msat: OptionalField::Present(80_000),
1891 fee_proportional_millionths: 0,
1892 excess_data: Vec::new()
1894 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
1895 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1896 short_channel_id: 2,
1899 cltv_expiry_delta: 0,
1900 htlc_minimum_msat: 0,
1901 htlc_maximum_msat: OptionalField::Absent,
1903 fee_proportional_millionths: 0,
1904 excess_data: Vec::new()
1906 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
1907 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1908 short_channel_id: 4,
1911 cltv_expiry_delta: 0,
1912 htlc_minimum_msat: 0,
1913 htlc_maximum_msat: OptionalField::Absent,
1915 fee_proportional_millionths: 100_000,
1916 excess_data: Vec::new()
1919 let route = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2],
1920 Some(InvoiceFeatures::known()), None, &Vec::new(), 60_000, 42, Arc::clone(&logger)).unwrap();
1921 // Fine to overpay for htlc_minimum_msat if it allows us to save fee.
1922 assert_eq!(route.paths.len(), 1);
1923 assert_eq!(route.paths[0][0].short_channel_id, 12);
1924 let fees = route.paths[0][0].fee_msat;
1925 assert_eq!(fees, 5_000);
1927 let route = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2],
1928 Some(InvoiceFeatures::known()), None, &Vec::new(), 50_000, 42, Arc::clone(&logger)).unwrap();
1929 // Not fine to overpay for htlc_minimum_msat if it requires paying more than fee on
1930 // the other channel.
1931 assert_eq!(route.paths.len(), 1);
1932 assert_eq!(route.paths[0][0].short_channel_id, 2);
1933 let fees = route.paths[0][0].fee_msat;
1934 assert_eq!(fees, 5_000);
1938 fn disable_channels_test() {
1939 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
1940 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
1942 // // Disable channels 4 and 12 by flags=2
1943 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
1944 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1945 short_channel_id: 4,
1947 flags: 2, // to disable
1948 cltv_expiry_delta: 0,
1949 htlc_minimum_msat: 0,
1950 htlc_maximum_msat: OptionalField::Absent,
1952 fee_proportional_millionths: 0,
1953 excess_data: Vec::new()
1955 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
1956 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1957 short_channel_id: 12,
1959 flags: 2, // to disable
1960 cltv_expiry_delta: 0,
1961 htlc_minimum_msat: 0,
1962 htlc_maximum_msat: OptionalField::Absent,
1964 fee_proportional_millionths: 0,
1965 excess_data: Vec::new()
1968 // If all the channels require some features we don't understand, route should fail
1969 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)) {
1970 assert_eq!(err, "Failed to find a path to the given destination");
1971 } else { panic!(); }
1973 // If we specify a channel to node7, that overrides our local channel view and that gets used
1974 let our_chans = vec![get_channel_details(Some(42), nodes[7].clone(), InitFeatures::from_le_bytes(vec![0b11]), 250_000_000)];
1975 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();
1976 assert_eq!(route.paths[0].len(), 2);
1978 assert_eq!(route.paths[0][0].pubkey, nodes[7]);
1979 assert_eq!(route.paths[0][0].short_channel_id, 42);
1980 assert_eq!(route.paths[0][0].fee_msat, 200);
1981 assert_eq!(route.paths[0][0].cltv_expiry_delta, (13 << 8) | 1);
1982 assert_eq!(route.paths[0][0].node_features.le_flags(), &vec![0b11]); // it should also override our view of their features
1983 assert_eq!(route.paths[0][0].channel_features.le_flags(), &Vec::<u8>::new()); // No feature flags will meet the relevant-to-channel conversion
1985 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
1986 assert_eq!(route.paths[0][1].short_channel_id, 13);
1987 assert_eq!(route.paths[0][1].fee_msat, 100);
1988 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
1989 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
1990 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(13));
1994 fn disable_node_test() {
1995 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
1996 let (_, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
1998 // Disable nodes 1, 2, and 8 by requiring unknown feature bits
1999 let unknown_features = NodeFeatures::known().set_unknown_feature_required();
2000 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[0], unknown_features.clone(), 1);
2001 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[1], unknown_features.clone(), 1);
2002 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[7], unknown_features.clone(), 1);
2004 // If all nodes require some features we don't understand, route should fail
2005 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)) {
2006 assert_eq!(err, "Failed to find a path to the given destination");
2007 } else { panic!(); }
2009 // If we specify a channel to node7, that overrides our local channel view and that gets used
2010 let our_chans = vec![get_channel_details(Some(42), nodes[7].clone(), InitFeatures::from_le_bytes(vec![0b11]), 250_000_000)];
2011 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();
2012 assert_eq!(route.paths[0].len(), 2);
2014 assert_eq!(route.paths[0][0].pubkey, nodes[7]);
2015 assert_eq!(route.paths[0][0].short_channel_id, 42);
2016 assert_eq!(route.paths[0][0].fee_msat, 200);
2017 assert_eq!(route.paths[0][0].cltv_expiry_delta, (13 << 8) | 1);
2018 assert_eq!(route.paths[0][0].node_features.le_flags(), &vec![0b11]); // it should also override our view of their features
2019 assert_eq!(route.paths[0][0].channel_features.le_flags(), &Vec::<u8>::new()); // No feature flags will meet the relevant-to-channel conversion
2021 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2022 assert_eq!(route.paths[0][1].short_channel_id, 13);
2023 assert_eq!(route.paths[0][1].fee_msat, 100);
2024 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
2025 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2026 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(13));
2028 // Note that we don't test disabling node 3 and failing to route to it, as we (somewhat
2029 // naively) assume that the user checked the feature bits on the invoice, which override
2030 // the node_announcement.
2034 fn our_chans_test() {
2035 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
2036 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
2038 // Route to 1 via 2 and 3 because our channel to 1 is disabled
2039 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();
2040 assert_eq!(route.paths[0].len(), 3);
2042 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
2043 assert_eq!(route.paths[0][0].short_channel_id, 2);
2044 assert_eq!(route.paths[0][0].fee_msat, 200);
2045 assert_eq!(route.paths[0][0].cltv_expiry_delta, (4 << 8) | 1);
2046 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
2047 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
2049 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2050 assert_eq!(route.paths[0][1].short_channel_id, 4);
2051 assert_eq!(route.paths[0][1].fee_msat, 100);
2052 assert_eq!(route.paths[0][1].cltv_expiry_delta, (3 << 8) | 2);
2053 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2054 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
2056 assert_eq!(route.paths[0][2].pubkey, nodes[0]);
2057 assert_eq!(route.paths[0][2].short_channel_id, 3);
2058 assert_eq!(route.paths[0][2].fee_msat, 100);
2059 assert_eq!(route.paths[0][2].cltv_expiry_delta, 42);
2060 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(1));
2061 assert_eq!(route.paths[0][2].channel_features.le_flags(), &id_to_feature_flags(3));
2063 // If we specify a channel to node7, that overrides our local channel view and that gets used
2064 let our_chans = vec![get_channel_details(Some(42), nodes[7].clone(), InitFeatures::from_le_bytes(vec![0b11]), 250_000_000)];
2065 let route = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2], None, Some(&our_chans.iter().collect::<Vec<_>>()), &Vec::new(), 100, 42, Arc::clone(&logger)).unwrap();
2066 assert_eq!(route.paths[0].len(), 2);
2068 assert_eq!(route.paths[0][0].pubkey, nodes[7]);
2069 assert_eq!(route.paths[0][0].short_channel_id, 42);
2070 assert_eq!(route.paths[0][0].fee_msat, 200);
2071 assert_eq!(route.paths[0][0].cltv_expiry_delta, (13 << 8) | 1);
2072 assert_eq!(route.paths[0][0].node_features.le_flags(), &vec![0b11]);
2073 assert_eq!(route.paths[0][0].channel_features.le_flags(), &Vec::<u8>::new()); // No feature flags will meet the relevant-to-channel conversion
2075 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2076 assert_eq!(route.paths[0][1].short_channel_id, 13);
2077 assert_eq!(route.paths[0][1].fee_msat, 100);
2078 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
2079 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2080 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(13));
2083 fn last_hops(nodes: &Vec<PublicKey>) -> Vec<RouteHint> {
2084 let zero_fees = RoutingFees {
2086 proportional_millionths: 0,
2088 vec![RouteHint(vec![RouteHintHop {
2089 src_node_id: nodes[3].clone(),
2090 short_channel_id: 8,
2092 cltv_expiry_delta: (8 << 8) | 1,
2093 htlc_minimum_msat: None,
2094 htlc_maximum_msat: None,
2095 }]), RouteHint(vec![RouteHintHop {
2096 src_node_id: nodes[4].clone(),
2097 short_channel_id: 9,
2100 proportional_millionths: 0,
2102 cltv_expiry_delta: (9 << 8) | 1,
2103 htlc_minimum_msat: None,
2104 htlc_maximum_msat: None,
2105 }]), RouteHint(vec![RouteHintHop {
2106 src_node_id: nodes[5].clone(),
2107 short_channel_id: 10,
2109 cltv_expiry_delta: (10 << 8) | 1,
2110 htlc_minimum_msat: None,
2111 htlc_maximum_msat: None,
2116 fn last_hops_test() {
2117 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
2118 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
2120 // Simple test across 2, 3, 5, and 4 via a last_hop channel
2122 // First check that last hop can't have its source as the payee.
2123 let invalid_last_hop = RouteHint(vec![RouteHintHop {
2124 src_node_id: nodes[6],
2125 short_channel_id: 8,
2128 proportional_millionths: 0,
2130 cltv_expiry_delta: (8 << 8) | 1,
2131 htlc_minimum_msat: None,
2132 htlc_maximum_msat: None,
2135 let mut invalid_last_hops = last_hops(&nodes);
2136 invalid_last_hops.push(invalid_last_hop);
2138 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[6], None, None, &invalid_last_hops.iter().collect::<Vec<_>>(), 100, 42, Arc::clone(&logger)) {
2139 assert_eq!(err, "Last hop cannot have a payee as a source.");
2140 } else { panic!(); }
2143 let route = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[6], None, None, &last_hops(&nodes).iter().collect::<Vec<_>>(), 100, 42, Arc::clone(&logger)).unwrap();
2144 assert_eq!(route.paths[0].len(), 5);
2146 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
2147 assert_eq!(route.paths[0][0].short_channel_id, 2);
2148 assert_eq!(route.paths[0][0].fee_msat, 100);
2149 assert_eq!(route.paths[0][0].cltv_expiry_delta, (4 << 8) | 1);
2150 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
2151 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
2153 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2154 assert_eq!(route.paths[0][1].short_channel_id, 4);
2155 assert_eq!(route.paths[0][1].fee_msat, 0);
2156 assert_eq!(route.paths[0][1].cltv_expiry_delta, (6 << 8) | 1);
2157 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2158 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
2160 assert_eq!(route.paths[0][2].pubkey, nodes[4]);
2161 assert_eq!(route.paths[0][2].short_channel_id, 6);
2162 assert_eq!(route.paths[0][2].fee_msat, 0);
2163 assert_eq!(route.paths[0][2].cltv_expiry_delta, (11 << 8) | 1);
2164 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(5));
2165 assert_eq!(route.paths[0][2].channel_features.le_flags(), &id_to_feature_flags(6));
2167 assert_eq!(route.paths[0][3].pubkey, nodes[3]);
2168 assert_eq!(route.paths[0][3].short_channel_id, 11);
2169 assert_eq!(route.paths[0][3].fee_msat, 0);
2170 assert_eq!(route.paths[0][3].cltv_expiry_delta, (8 << 8) | 1);
2171 // If we have a peer in the node map, we'll use their features here since we don't have
2172 // a way of figuring out their features from the invoice:
2173 assert_eq!(route.paths[0][3].node_features.le_flags(), &id_to_feature_flags(4));
2174 assert_eq!(route.paths[0][3].channel_features.le_flags(), &id_to_feature_flags(11));
2176 assert_eq!(route.paths[0][4].pubkey, nodes[6]);
2177 assert_eq!(route.paths[0][4].short_channel_id, 8);
2178 assert_eq!(route.paths[0][4].fee_msat, 100);
2179 assert_eq!(route.paths[0][4].cltv_expiry_delta, 42);
2180 assert_eq!(route.paths[0][4].node_features.le_flags(), &Vec::<u8>::new()); // We dont pass flags in from invoices yet
2181 assert_eq!(route.paths[0][4].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
2185 fn our_chans_last_hop_connect_test() {
2186 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
2187 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
2189 // Simple test with outbound channel to 4 to test that last_hops and first_hops connect
2190 let our_chans = vec![get_channel_details(Some(42), nodes[3].clone(), InitFeatures::from_le_bytes(vec![0b11]), 250_000_000)];
2191 let mut last_hops = last_hops(&nodes);
2192 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();
2193 assert_eq!(route.paths[0].len(), 2);
2195 assert_eq!(route.paths[0][0].pubkey, nodes[3]);
2196 assert_eq!(route.paths[0][0].short_channel_id, 42);
2197 assert_eq!(route.paths[0][0].fee_msat, 0);
2198 assert_eq!(route.paths[0][0].cltv_expiry_delta, (8 << 8) | 1);
2199 assert_eq!(route.paths[0][0].node_features.le_flags(), &vec![0b11]);
2200 assert_eq!(route.paths[0][0].channel_features.le_flags(), &Vec::<u8>::new()); // No feature flags will meet the relevant-to-channel conversion
2202 assert_eq!(route.paths[0][1].pubkey, nodes[6]);
2203 assert_eq!(route.paths[0][1].short_channel_id, 8);
2204 assert_eq!(route.paths[0][1].fee_msat, 100);
2205 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
2206 assert_eq!(route.paths[0][1].node_features.le_flags(), &Vec::<u8>::new()); // We dont pass flags in from invoices yet
2207 assert_eq!(route.paths[0][1].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
2209 last_hops[0].0[0].fees.base_msat = 1000;
2211 // Revert to via 6 as the fee on 8 goes up
2212 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();
2213 assert_eq!(route.paths[0].len(), 4);
2215 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
2216 assert_eq!(route.paths[0][0].short_channel_id, 2);
2217 assert_eq!(route.paths[0][0].fee_msat, 200); // fee increased as its % of value transferred across node
2218 assert_eq!(route.paths[0][0].cltv_expiry_delta, (4 << 8) | 1);
2219 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
2220 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
2222 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2223 assert_eq!(route.paths[0][1].short_channel_id, 4);
2224 assert_eq!(route.paths[0][1].fee_msat, 100);
2225 assert_eq!(route.paths[0][1].cltv_expiry_delta, (7 << 8) | 1);
2226 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2227 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
2229 assert_eq!(route.paths[0][2].pubkey, nodes[5]);
2230 assert_eq!(route.paths[0][2].short_channel_id, 7);
2231 assert_eq!(route.paths[0][2].fee_msat, 0);
2232 assert_eq!(route.paths[0][2].cltv_expiry_delta, (10 << 8) | 1);
2233 // If we have a peer in the node map, we'll use their features here since we don't have
2234 // a way of figuring out their features from the invoice:
2235 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(6));
2236 assert_eq!(route.paths[0][2].channel_features.le_flags(), &id_to_feature_flags(7));
2238 assert_eq!(route.paths[0][3].pubkey, nodes[6]);
2239 assert_eq!(route.paths[0][3].short_channel_id, 10);
2240 assert_eq!(route.paths[0][3].fee_msat, 100);
2241 assert_eq!(route.paths[0][3].cltv_expiry_delta, 42);
2242 assert_eq!(route.paths[0][3].node_features.le_flags(), &Vec::<u8>::new()); // We dont pass flags in from invoices yet
2243 assert_eq!(route.paths[0][3].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
2245 // ...but still use 8 for larger payments as 6 has a variable feerate
2246 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();
2247 assert_eq!(route.paths[0].len(), 5);
2249 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
2250 assert_eq!(route.paths[0][0].short_channel_id, 2);
2251 assert_eq!(route.paths[0][0].fee_msat, 3000);
2252 assert_eq!(route.paths[0][0].cltv_expiry_delta, (4 << 8) | 1);
2253 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
2254 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
2256 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2257 assert_eq!(route.paths[0][1].short_channel_id, 4);
2258 assert_eq!(route.paths[0][1].fee_msat, 0);
2259 assert_eq!(route.paths[0][1].cltv_expiry_delta, (6 << 8) | 1);
2260 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2261 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
2263 assert_eq!(route.paths[0][2].pubkey, nodes[4]);
2264 assert_eq!(route.paths[0][2].short_channel_id, 6);
2265 assert_eq!(route.paths[0][2].fee_msat, 0);
2266 assert_eq!(route.paths[0][2].cltv_expiry_delta, (11 << 8) | 1);
2267 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(5));
2268 assert_eq!(route.paths[0][2].channel_features.le_flags(), &id_to_feature_flags(6));
2270 assert_eq!(route.paths[0][3].pubkey, nodes[3]);
2271 assert_eq!(route.paths[0][3].short_channel_id, 11);
2272 assert_eq!(route.paths[0][3].fee_msat, 1000);
2273 assert_eq!(route.paths[0][3].cltv_expiry_delta, (8 << 8) | 1);
2274 // If we have a peer in the node map, we'll use their features here since we don't have
2275 // a way of figuring out their features from the invoice:
2276 assert_eq!(route.paths[0][3].node_features.le_flags(), &id_to_feature_flags(4));
2277 assert_eq!(route.paths[0][3].channel_features.le_flags(), &id_to_feature_flags(11));
2279 assert_eq!(route.paths[0][4].pubkey, nodes[6]);
2280 assert_eq!(route.paths[0][4].short_channel_id, 8);
2281 assert_eq!(route.paths[0][4].fee_msat, 2000);
2282 assert_eq!(route.paths[0][4].cltv_expiry_delta, 42);
2283 assert_eq!(route.paths[0][4].node_features.le_flags(), &Vec::<u8>::new()); // We dont pass flags in from invoices yet
2284 assert_eq!(route.paths[0][4].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
2287 fn do_unannounced_path_test(last_hop_htlc_max: Option<u64>, last_hop_fee_prop: u32, outbound_capacity_msat: u64, route_val: u64) -> Result<Route, LightningError> {
2288 let source_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&hex::decode(format!("{:02}", 41).repeat(32)).unwrap()[..]).unwrap());
2289 let middle_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&hex::decode(format!("{:02}", 42).repeat(32)).unwrap()[..]).unwrap());
2290 let target_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&hex::decode(format!("{:02}", 43).repeat(32)).unwrap()[..]).unwrap());
2292 // If we specify a channel to a middle hop, that overrides our local channel view and that gets used
2293 let last_hops = RouteHint(vec![RouteHintHop {
2294 src_node_id: middle_node_id,
2295 short_channel_id: 8,
2298 proportional_millionths: last_hop_fee_prop,
2300 cltv_expiry_delta: (8 << 8) | 1,
2301 htlc_minimum_msat: None,
2302 htlc_maximum_msat: last_hop_htlc_max,
2304 let our_chans = vec![get_channel_details(Some(42), middle_node_id, InitFeatures::from_le_bytes(vec![0b11]), outbound_capacity_msat)];
2305 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], route_val, 42, Arc::new(test_utils::TestLogger::new()))
2309 fn unannounced_path_test() {
2310 // We should be able to send a payment to a destination without any help of a routing graph
2311 // if we have a channel with a common counterparty that appears in the first and last hop
2313 let route = do_unannounced_path_test(None, 1, 2000000, 1000000).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());
2317 assert_eq!(route.paths[0].len(), 2);
2319 assert_eq!(route.paths[0][0].pubkey, middle_node_id);
2320 assert_eq!(route.paths[0][0].short_channel_id, 42);
2321 assert_eq!(route.paths[0][0].fee_msat, 1001);
2322 assert_eq!(route.paths[0][0].cltv_expiry_delta, (8 << 8) | 1);
2323 assert_eq!(route.paths[0][0].node_features.le_flags(), &[0b11]);
2324 assert_eq!(route.paths[0][0].channel_features.le_flags(), &[0; 0]); // We can't learn any flags from invoices, sadly
2326 assert_eq!(route.paths[0][1].pubkey, target_node_id);
2327 assert_eq!(route.paths[0][1].short_channel_id, 8);
2328 assert_eq!(route.paths[0][1].fee_msat, 1000000);
2329 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
2330 assert_eq!(route.paths[0][1].node_features.le_flags(), &[0; 0]); // We dont pass flags in from invoices yet
2331 assert_eq!(route.paths[0][1].channel_features.le_flags(), &[0; 0]); // We can't learn any flags from invoices, sadly
2335 fn overflow_unannounced_path_test_liquidity_underflow() {
2336 // Previously, when we had a last-hop hint connected directly to a first-hop channel, where
2337 // the last-hop had a fee which overflowed a u64, we'd panic.
2338 // This was due to us adding the first-hop from us unconditionally, causing us to think
2339 // we'd built a path (as our node is in the "best candidate" set), when we had not.
2340 // In this test, we previously hit a subtraction underflow due to having less available
2341 // liquidity at the last hop than 0.
2342 assert!(do_unannounced_path_test(Some(21_000_000_0000_0000_000), 0, 21_000_000_0000_0000_000, 21_000_000_0000_0000_000).is_err());
2346 fn overflow_unannounced_path_test_feerate_overflow() {
2347 // This tests for the same case as above, except instead of hitting a subtraction
2348 // underflow, we hit a case where the fee charged at a hop overflowed.
2349 assert!(do_unannounced_path_test(Some(21_000_000_0000_0000_000), 50000, 21_000_000_0000_0000_000, 21_000_000_0000_0000_000).is_err());
2353 fn available_amount_while_routing_test() {
2354 // Tests whether we choose the correct available channel amount while routing.
2356 let (secp_ctx, mut net_graph_msg_handler, chain_monitor, logger) = build_graph();
2357 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
2359 // We will use a simple single-path route from
2360 // our node to node2 via node0: channels {1, 3}.
2362 // First disable all other paths.
2363 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2364 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2365 short_channel_id: 2,
2368 cltv_expiry_delta: 0,
2369 htlc_minimum_msat: 0,
2370 htlc_maximum_msat: OptionalField::Present(100_000),
2372 fee_proportional_millionths: 0,
2373 excess_data: Vec::new()
2375 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2376 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2377 short_channel_id: 12,
2380 cltv_expiry_delta: 0,
2381 htlc_minimum_msat: 0,
2382 htlc_maximum_msat: OptionalField::Present(100_000),
2384 fee_proportional_millionths: 0,
2385 excess_data: Vec::new()
2388 // Make the first channel (#1) very permissive,
2389 // and we will be testing all limits on the second channel.
2390 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2391 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2392 short_channel_id: 1,
2395 cltv_expiry_delta: 0,
2396 htlc_minimum_msat: 0,
2397 htlc_maximum_msat: OptionalField::Present(1_000_000_000),
2399 fee_proportional_millionths: 0,
2400 excess_data: Vec::new()
2403 // First, let's see if routing works if we have absolutely no idea about the available amount.
2404 // In this case, it should be set to 250_000 sats.
2405 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
2406 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2407 short_channel_id: 3,
2410 cltv_expiry_delta: 0,
2411 htlc_minimum_msat: 0,
2412 htlc_maximum_msat: OptionalField::Absent,
2414 fee_proportional_millionths: 0,
2415 excess_data: Vec::new()
2419 // Attempt to route more than available results in a failure.
2420 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2],
2421 Some(InvoiceFeatures::known()), None, &Vec::new(), 250_000_001, 42, Arc::clone(&logger)) {
2422 assert_eq!(err, "Failed to find a sufficient route to the given destination");
2423 } else { panic!(); }
2427 // Now, attempt to route an exact amount we have should be fine.
2428 let route = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2],
2429 Some(InvoiceFeatures::known()), None, &Vec::new(), 250_000_000, 42, Arc::clone(&logger)).unwrap();
2430 assert_eq!(route.paths.len(), 1);
2431 let path = route.paths.last().unwrap();
2432 assert_eq!(path.len(), 2);
2433 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
2434 assert_eq!(path.last().unwrap().fee_msat, 250_000_000);
2437 // Check that setting outbound_capacity_msat in first_hops limits the channels.
2438 // Disable channel #1 and use another first hop.
2439 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2440 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2441 short_channel_id: 1,
2444 cltv_expiry_delta: 0,
2445 htlc_minimum_msat: 0,
2446 htlc_maximum_msat: OptionalField::Present(1_000_000_000),
2448 fee_proportional_millionths: 0,
2449 excess_data: Vec::new()
2452 // Now, limit the first_hop by the outbound_capacity_msat of 200_000 sats.
2453 let our_chans = vec![get_channel_details(Some(42), nodes[0].clone(), InitFeatures::from_le_bytes(vec![0b11]), 200_000_000)];
2456 // Attempt to route more than available results in a failure.
2457 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2],
2458 Some(InvoiceFeatures::known()), Some(&our_chans.iter().collect::<Vec<_>>()), &Vec::new(), 200_000_001, 42, Arc::clone(&logger)) {
2459 assert_eq!(err, "Failed to find a sufficient route to the given destination");
2460 } else { panic!(); }
2464 // Now, attempt to route an exact amount we have should be fine.
2465 let route = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2],
2466 Some(InvoiceFeatures::known()), Some(&our_chans.iter().collect::<Vec<_>>()), &Vec::new(), 200_000_000, 42, Arc::clone(&logger)).unwrap();
2467 assert_eq!(route.paths.len(), 1);
2468 let path = route.paths.last().unwrap();
2469 assert_eq!(path.len(), 2);
2470 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
2471 assert_eq!(path.last().unwrap().fee_msat, 200_000_000);
2474 // Enable channel #1 back.
2475 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2476 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2477 short_channel_id: 1,
2480 cltv_expiry_delta: 0,
2481 htlc_minimum_msat: 0,
2482 htlc_maximum_msat: OptionalField::Present(1_000_000_000),
2484 fee_proportional_millionths: 0,
2485 excess_data: Vec::new()
2489 // Now let's see if routing works if we know only htlc_maximum_msat.
2490 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
2491 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2492 short_channel_id: 3,
2495 cltv_expiry_delta: 0,
2496 htlc_minimum_msat: 0,
2497 htlc_maximum_msat: OptionalField::Present(15_000),
2499 fee_proportional_millionths: 0,
2500 excess_data: Vec::new()
2504 // Attempt to route more than available results in a failure.
2505 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2],
2506 Some(InvoiceFeatures::known()), None, &Vec::new(), 15_001, 42, Arc::clone(&logger)) {
2507 assert_eq!(err, "Failed to find a sufficient route to the given destination");
2508 } else { panic!(); }
2512 // Now, attempt to route an exact amount we have should be fine.
2513 let route = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2],
2514 Some(InvoiceFeatures::known()), None, &Vec::new(), 15_000, 42, Arc::clone(&logger)).unwrap();
2515 assert_eq!(route.paths.len(), 1);
2516 let path = route.paths.last().unwrap();
2517 assert_eq!(path.len(), 2);
2518 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
2519 assert_eq!(path.last().unwrap().fee_msat, 15_000);
2522 // Now let's see if routing works if we know only capacity from the UTXO.
2524 // We can't change UTXO capacity on the fly, so we'll disable
2525 // the existing channel and add another one with the capacity we need.
2526 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
2527 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2528 short_channel_id: 3,
2531 cltv_expiry_delta: 0,
2532 htlc_minimum_msat: 0,
2533 htlc_maximum_msat: OptionalField::Absent,
2535 fee_proportional_millionths: 0,
2536 excess_data: Vec::new()
2539 let good_script = Builder::new().push_opcode(opcodes::all::OP_PUSHNUM_2)
2540 .push_slice(&PublicKey::from_secret_key(&secp_ctx, &privkeys[0]).serialize())
2541 .push_slice(&PublicKey::from_secret_key(&secp_ctx, &privkeys[2]).serialize())
2542 .push_opcode(opcodes::all::OP_PUSHNUM_2)
2543 .push_opcode(opcodes::all::OP_CHECKMULTISIG).into_script().to_v0_p2wsh();
2545 *chain_monitor.utxo_ret.lock().unwrap() = Ok(TxOut { value: 15, script_pubkey: good_script.clone() });
2546 net_graph_msg_handler.add_chain_access(Some(chain_monitor));
2548 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], &privkeys[2], ChannelFeatures::from_le_bytes(id_to_feature_flags(3)), 333);
2549 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
2550 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2551 short_channel_id: 333,
2554 cltv_expiry_delta: (3 << 8) | 1,
2555 htlc_minimum_msat: 0,
2556 htlc_maximum_msat: OptionalField::Absent,
2558 fee_proportional_millionths: 0,
2559 excess_data: Vec::new()
2561 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
2562 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2563 short_channel_id: 333,
2566 cltv_expiry_delta: (3 << 8) | 2,
2567 htlc_minimum_msat: 0,
2568 htlc_maximum_msat: OptionalField::Absent,
2570 fee_proportional_millionths: 0,
2571 excess_data: Vec::new()
2575 // Attempt to route more than available results in a failure.
2576 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2],
2577 Some(InvoiceFeatures::known()), None, &Vec::new(), 15_001, 42, Arc::clone(&logger)) {
2578 assert_eq!(err, "Failed to find a sufficient route to the given destination");
2579 } else { panic!(); }
2583 // Now, attempt to route an exact amount we have should be fine.
2584 let route = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2],
2585 Some(InvoiceFeatures::known()), None, &Vec::new(), 15_000, 42, Arc::clone(&logger)).unwrap();
2586 assert_eq!(route.paths.len(), 1);
2587 let path = route.paths.last().unwrap();
2588 assert_eq!(path.len(), 2);
2589 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
2590 assert_eq!(path.last().unwrap().fee_msat, 15_000);
2593 // Now let's see if routing chooses htlc_maximum_msat over UTXO capacity.
2594 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
2595 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2596 short_channel_id: 333,
2599 cltv_expiry_delta: 0,
2600 htlc_minimum_msat: 0,
2601 htlc_maximum_msat: OptionalField::Present(10_000),
2603 fee_proportional_millionths: 0,
2604 excess_data: Vec::new()
2608 // Attempt to route more than available results in a failure.
2609 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2],
2610 Some(InvoiceFeatures::known()), None, &Vec::new(), 10_001, 42, Arc::clone(&logger)) {
2611 assert_eq!(err, "Failed to find a sufficient route to the given destination");
2612 } else { panic!(); }
2616 // Now, attempt to route an exact amount we have should be fine.
2617 let route = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2],
2618 Some(InvoiceFeatures::known()), None, &Vec::new(), 10_000, 42, Arc::clone(&logger)).unwrap();
2619 assert_eq!(route.paths.len(), 1);
2620 let path = route.paths.last().unwrap();
2621 assert_eq!(path.len(), 2);
2622 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
2623 assert_eq!(path.last().unwrap().fee_msat, 10_000);
2628 fn available_liquidity_last_hop_test() {
2629 // Check that available liquidity properly limits the path even when only
2630 // one of the latter hops is limited.
2631 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
2632 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
2634 // Path via {node7, node2, node4} is channels {12, 13, 6, 11}.
2635 // {12, 13, 11} have the capacities of 100, {6} has a capacity of 50.
2636 // Total capacity: 50 sats.
2638 // Disable other potential paths.
2639 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2640 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2641 short_channel_id: 2,
2644 cltv_expiry_delta: 0,
2645 htlc_minimum_msat: 0,
2646 htlc_maximum_msat: OptionalField::Present(100_000),
2648 fee_proportional_millionths: 0,
2649 excess_data: Vec::new()
2651 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
2652 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2653 short_channel_id: 7,
2656 cltv_expiry_delta: 0,
2657 htlc_minimum_msat: 0,
2658 htlc_maximum_msat: OptionalField::Present(100_000),
2660 fee_proportional_millionths: 0,
2661 excess_data: Vec::new()
2666 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2667 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2668 short_channel_id: 12,
2671 cltv_expiry_delta: 0,
2672 htlc_minimum_msat: 0,
2673 htlc_maximum_msat: OptionalField::Present(100_000),
2675 fee_proportional_millionths: 0,
2676 excess_data: Vec::new()
2678 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
2679 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2680 short_channel_id: 13,
2683 cltv_expiry_delta: 0,
2684 htlc_minimum_msat: 0,
2685 htlc_maximum_msat: OptionalField::Present(100_000),
2687 fee_proportional_millionths: 0,
2688 excess_data: Vec::new()
2691 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
2692 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2693 short_channel_id: 6,
2696 cltv_expiry_delta: 0,
2697 htlc_minimum_msat: 0,
2698 htlc_maximum_msat: OptionalField::Present(50_000),
2700 fee_proportional_millionths: 0,
2701 excess_data: Vec::new()
2703 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
2704 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2705 short_channel_id: 11,
2708 cltv_expiry_delta: 0,
2709 htlc_minimum_msat: 0,
2710 htlc_maximum_msat: OptionalField::Present(100_000),
2712 fee_proportional_millionths: 0,
2713 excess_data: Vec::new()
2716 // Attempt to route more than available results in a failure.
2717 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[3],
2718 Some(InvoiceFeatures::known()), None, &Vec::new(), 60_000, 42, Arc::clone(&logger)) {
2719 assert_eq!(err, "Failed to find a sufficient route to the given destination");
2720 } else { panic!(); }
2724 // Now, attempt to route 49 sats (just a bit below the capacity).
2725 let route = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[3],
2726 Some(InvoiceFeatures::known()), None, &Vec::new(), 49_000, 42, Arc::clone(&logger)).unwrap();
2727 assert_eq!(route.paths.len(), 1);
2728 let mut total_amount_paid_msat = 0;
2729 for path in &route.paths {
2730 assert_eq!(path.len(), 4);
2731 assert_eq!(path.last().unwrap().pubkey, nodes[3]);
2732 total_amount_paid_msat += path.last().unwrap().fee_msat;
2734 assert_eq!(total_amount_paid_msat, 49_000);
2738 // Attempt to route an exact amount is also fine
2739 let route = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[3],
2740 Some(InvoiceFeatures::known()), None, &Vec::new(), 50_000, 42, Arc::clone(&logger)).unwrap();
2741 assert_eq!(route.paths.len(), 1);
2742 let mut total_amount_paid_msat = 0;
2743 for path in &route.paths {
2744 assert_eq!(path.len(), 4);
2745 assert_eq!(path.last().unwrap().pubkey, nodes[3]);
2746 total_amount_paid_msat += path.last().unwrap().fee_msat;
2748 assert_eq!(total_amount_paid_msat, 50_000);
2753 fn ignore_fee_first_hop_test() {
2754 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
2755 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
2757 // Path via node0 is channels {1, 3}. Limit them to 100 and 50 sats (total limit 50).
2758 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2759 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2760 short_channel_id: 1,
2763 cltv_expiry_delta: 0,
2764 htlc_minimum_msat: 0,
2765 htlc_maximum_msat: OptionalField::Present(100_000),
2766 fee_base_msat: 1_000_000,
2767 fee_proportional_millionths: 0,
2768 excess_data: Vec::new()
2770 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
2771 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2772 short_channel_id: 3,
2775 cltv_expiry_delta: 0,
2776 htlc_minimum_msat: 0,
2777 htlc_maximum_msat: OptionalField::Present(50_000),
2779 fee_proportional_millionths: 0,
2780 excess_data: Vec::new()
2784 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();
2785 assert_eq!(route.paths.len(), 1);
2786 let mut total_amount_paid_msat = 0;
2787 for path in &route.paths {
2788 assert_eq!(path.len(), 2);
2789 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
2790 total_amount_paid_msat += path.last().unwrap().fee_msat;
2792 assert_eq!(total_amount_paid_msat, 50_000);
2797 fn simple_mpp_route_test() {
2798 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
2799 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
2801 // We need a route consisting of 3 paths:
2802 // From our node to node2 via node0, node7, node1 (three paths one hop each).
2803 // To achieve this, the amount being transferred should be around
2804 // the total capacity of these 3 paths.
2806 // First, we set limits on these (previously unlimited) channels.
2807 // Their aggregate capacity will be 50 + 60 + 180 = 290 sats.
2809 // Path via node0 is channels {1, 3}. Limit them to 100 and 50 sats (total limit 50).
2810 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2811 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2812 short_channel_id: 1,
2815 cltv_expiry_delta: 0,
2816 htlc_minimum_msat: 0,
2817 htlc_maximum_msat: OptionalField::Present(100_000),
2819 fee_proportional_millionths: 0,
2820 excess_data: Vec::new()
2822 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
2823 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2824 short_channel_id: 3,
2827 cltv_expiry_delta: 0,
2828 htlc_minimum_msat: 0,
2829 htlc_maximum_msat: OptionalField::Present(50_000),
2831 fee_proportional_millionths: 0,
2832 excess_data: Vec::new()
2835 // Path via node7 is channels {12, 13}. Limit them to 60 and 60 sats
2836 // (total limit 60).
2837 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2838 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2839 short_channel_id: 12,
2842 cltv_expiry_delta: 0,
2843 htlc_minimum_msat: 0,
2844 htlc_maximum_msat: OptionalField::Present(60_000),
2846 fee_proportional_millionths: 0,
2847 excess_data: Vec::new()
2849 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
2850 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2851 short_channel_id: 13,
2854 cltv_expiry_delta: 0,
2855 htlc_minimum_msat: 0,
2856 htlc_maximum_msat: OptionalField::Present(60_000),
2858 fee_proportional_millionths: 0,
2859 excess_data: Vec::new()
2862 // Path via node1 is channels {2, 4}. Limit them to 200 and 180 sats
2863 // (total capacity 180 sats).
2864 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2865 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2866 short_channel_id: 2,
2869 cltv_expiry_delta: 0,
2870 htlc_minimum_msat: 0,
2871 htlc_maximum_msat: OptionalField::Present(200_000),
2873 fee_proportional_millionths: 0,
2874 excess_data: Vec::new()
2876 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
2877 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2878 short_channel_id: 4,
2881 cltv_expiry_delta: 0,
2882 htlc_minimum_msat: 0,
2883 htlc_maximum_msat: OptionalField::Present(180_000),
2885 fee_proportional_millionths: 0,
2886 excess_data: Vec::new()
2890 // Attempt to route more than available results in a failure.
2891 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(),
2892 &nodes[2], Some(InvoiceFeatures::known()), None, &Vec::new(), 300_000, 42, Arc::clone(&logger)) {
2893 assert_eq!(err, "Failed to find a sufficient route to the given destination");
2894 } else { panic!(); }
2898 // Now, attempt to route 250 sats (just a bit below the capacity).
2899 // Our algorithm should provide us with these 3 paths.
2900 let route = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2],
2901 Some(InvoiceFeatures::known()), None, &Vec::new(), 250_000, 42, Arc::clone(&logger)).unwrap();
2902 assert_eq!(route.paths.len(), 3);
2903 let mut total_amount_paid_msat = 0;
2904 for path in &route.paths {
2905 assert_eq!(path.len(), 2);
2906 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
2907 total_amount_paid_msat += path.last().unwrap().fee_msat;
2909 assert_eq!(total_amount_paid_msat, 250_000);
2913 // Attempt to route an exact amount is also fine
2914 let route = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2],
2915 Some(InvoiceFeatures::known()), None, &Vec::new(), 290_000, 42, Arc::clone(&logger)).unwrap();
2916 assert_eq!(route.paths.len(), 3);
2917 let mut total_amount_paid_msat = 0;
2918 for path in &route.paths {
2919 assert_eq!(path.len(), 2);
2920 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
2921 total_amount_paid_msat += path.last().unwrap().fee_msat;
2923 assert_eq!(total_amount_paid_msat, 290_000);
2928 fn long_mpp_route_test() {
2929 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
2930 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
2932 // We need a route consisting of 3 paths:
2933 // From our node to node3 via {node0, node2}, {node7, node2, node4} and {node7, node2}.
2934 // Note that these paths overlap (channels 5, 12, 13).
2935 // We will route 300 sats.
2936 // Each path will have 100 sats capacity, those channels which
2937 // are used twice will have 200 sats capacity.
2939 // Disable other potential paths.
2940 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2941 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2942 short_channel_id: 2,
2945 cltv_expiry_delta: 0,
2946 htlc_minimum_msat: 0,
2947 htlc_maximum_msat: OptionalField::Present(100_000),
2949 fee_proportional_millionths: 0,
2950 excess_data: Vec::new()
2952 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
2953 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2954 short_channel_id: 7,
2957 cltv_expiry_delta: 0,
2958 htlc_minimum_msat: 0,
2959 htlc_maximum_msat: OptionalField::Present(100_000),
2961 fee_proportional_millionths: 0,
2962 excess_data: Vec::new()
2965 // Path via {node0, node2} is channels {1, 3, 5}.
2966 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2967 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2968 short_channel_id: 1,
2971 cltv_expiry_delta: 0,
2972 htlc_minimum_msat: 0,
2973 htlc_maximum_msat: OptionalField::Present(100_000),
2975 fee_proportional_millionths: 0,
2976 excess_data: Vec::new()
2978 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
2979 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2980 short_channel_id: 3,
2983 cltv_expiry_delta: 0,
2984 htlc_minimum_msat: 0,
2985 htlc_maximum_msat: OptionalField::Present(100_000),
2987 fee_proportional_millionths: 0,
2988 excess_data: Vec::new()
2991 // Capacity of 200 sats because this channel will be used by 3rd path as well.
2992 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(5)), 5);
2993 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
2994 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2995 short_channel_id: 5,
2998 cltv_expiry_delta: 0,
2999 htlc_minimum_msat: 0,
3000 htlc_maximum_msat: OptionalField::Present(200_000),
3002 fee_proportional_millionths: 0,
3003 excess_data: Vec::new()
3006 // Path via {node7, node2, node4} is channels {12, 13, 6, 11}.
3007 // Add 100 sats to the capacities of {12, 13}, because these channels
3008 // are also used for 3rd path. 100 sats for the rest. Total capacity: 100 sats.
3009 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3010 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3011 short_channel_id: 12,
3014 cltv_expiry_delta: 0,
3015 htlc_minimum_msat: 0,
3016 htlc_maximum_msat: OptionalField::Present(200_000),
3018 fee_proportional_millionths: 0,
3019 excess_data: Vec::new()
3021 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
3022 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3023 short_channel_id: 13,
3026 cltv_expiry_delta: 0,
3027 htlc_minimum_msat: 0,
3028 htlc_maximum_msat: OptionalField::Present(200_000),
3030 fee_proportional_millionths: 0,
3031 excess_data: Vec::new()
3034 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3035 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3036 short_channel_id: 6,
3039 cltv_expiry_delta: 0,
3040 htlc_minimum_msat: 0,
3041 htlc_maximum_msat: OptionalField::Present(100_000),
3043 fee_proportional_millionths: 0,
3044 excess_data: Vec::new()
3046 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
3047 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3048 short_channel_id: 11,
3051 cltv_expiry_delta: 0,
3052 htlc_minimum_msat: 0,
3053 htlc_maximum_msat: OptionalField::Present(100_000),
3055 fee_proportional_millionths: 0,
3056 excess_data: Vec::new()
3059 // Path via {node7, node2} is channels {12, 13, 5}.
3060 // We already limited them to 200 sats (they are used twice for 100 sats).
3061 // Nothing to do here.
3064 // Attempt to route more than available results in a failure.
3065 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[3],
3066 Some(InvoiceFeatures::known()), None, &Vec::new(), 350_000, 42, Arc::clone(&logger)) {
3067 assert_eq!(err, "Failed to find a sufficient route to the given destination");
3068 } else { panic!(); }
3072 // Now, attempt to route 300 sats (exact amount we can route).
3073 // Our algorithm should provide us with these 3 paths, 100 sats each.
3074 let route = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[3],
3075 Some(InvoiceFeatures::known()), None, &Vec::new(), 300_000, 42, Arc::clone(&logger)).unwrap();
3076 assert_eq!(route.paths.len(), 3);
3078 let mut total_amount_paid_msat = 0;
3079 for path in &route.paths {
3080 assert_eq!(path.last().unwrap().pubkey, nodes[3]);
3081 total_amount_paid_msat += path.last().unwrap().fee_msat;
3083 assert_eq!(total_amount_paid_msat, 300_000);
3089 fn mpp_cheaper_route_test() {
3090 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
3091 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3093 // This test checks that if we have two cheaper paths and one more expensive path,
3094 // so that liquidity-wise any 2 of 3 combination is sufficient,
3095 // two cheaper paths will be taken.
3096 // These paths have equal available liquidity.
3098 // We need a combination of 3 paths:
3099 // From our node to node3 via {node0, node2}, {node7, node2, node4} and {node7, node2}.
3100 // Note that these paths overlap (channels 5, 12, 13).
3101 // Each path will have 100 sats capacity, those channels which
3102 // are used twice will have 200 sats capacity.
3104 // Disable other potential paths.
3105 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3106 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3107 short_channel_id: 2,
3110 cltv_expiry_delta: 0,
3111 htlc_minimum_msat: 0,
3112 htlc_maximum_msat: OptionalField::Present(100_000),
3114 fee_proportional_millionths: 0,
3115 excess_data: Vec::new()
3117 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3118 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3119 short_channel_id: 7,
3122 cltv_expiry_delta: 0,
3123 htlc_minimum_msat: 0,
3124 htlc_maximum_msat: OptionalField::Present(100_000),
3126 fee_proportional_millionths: 0,
3127 excess_data: Vec::new()
3130 // Path via {node0, node2} is channels {1, 3, 5}.
3131 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3132 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3133 short_channel_id: 1,
3136 cltv_expiry_delta: 0,
3137 htlc_minimum_msat: 0,
3138 htlc_maximum_msat: OptionalField::Present(100_000),
3140 fee_proportional_millionths: 0,
3141 excess_data: Vec::new()
3143 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3144 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3145 short_channel_id: 3,
3148 cltv_expiry_delta: 0,
3149 htlc_minimum_msat: 0,
3150 htlc_maximum_msat: OptionalField::Present(100_000),
3152 fee_proportional_millionths: 0,
3153 excess_data: Vec::new()
3156 // Capacity of 200 sats because this channel will be used by 3rd path as well.
3157 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(5)), 5);
3158 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3159 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3160 short_channel_id: 5,
3163 cltv_expiry_delta: 0,
3164 htlc_minimum_msat: 0,
3165 htlc_maximum_msat: OptionalField::Present(200_000),
3167 fee_proportional_millionths: 0,
3168 excess_data: Vec::new()
3171 // Path via {node7, node2, node4} is channels {12, 13, 6, 11}.
3172 // Add 100 sats to the capacities of {12, 13}, because these channels
3173 // are also used for 3rd path. 100 sats for the rest. Total capacity: 100 sats.
3174 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3175 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3176 short_channel_id: 12,
3179 cltv_expiry_delta: 0,
3180 htlc_minimum_msat: 0,
3181 htlc_maximum_msat: OptionalField::Present(200_000),
3183 fee_proportional_millionths: 0,
3184 excess_data: Vec::new()
3186 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
3187 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3188 short_channel_id: 13,
3191 cltv_expiry_delta: 0,
3192 htlc_minimum_msat: 0,
3193 htlc_maximum_msat: OptionalField::Present(200_000),
3195 fee_proportional_millionths: 0,
3196 excess_data: Vec::new()
3199 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3200 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3201 short_channel_id: 6,
3204 cltv_expiry_delta: 0,
3205 htlc_minimum_msat: 0,
3206 htlc_maximum_msat: OptionalField::Present(100_000),
3207 fee_base_msat: 1_000,
3208 fee_proportional_millionths: 0,
3209 excess_data: Vec::new()
3211 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
3212 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3213 short_channel_id: 11,
3216 cltv_expiry_delta: 0,
3217 htlc_minimum_msat: 0,
3218 htlc_maximum_msat: OptionalField::Present(100_000),
3220 fee_proportional_millionths: 0,
3221 excess_data: Vec::new()
3224 // Path via {node7, node2} is channels {12, 13, 5}.
3225 // We already limited them to 200 sats (they are used twice for 100 sats).
3226 // Nothing to do here.
3229 // Now, attempt to route 180 sats.
3230 // Our algorithm should provide us with these 2 paths.
3231 let route = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[3],
3232 Some(InvoiceFeatures::known()), None, &Vec::new(), 180_000, 42, Arc::clone(&logger)).unwrap();
3233 assert_eq!(route.paths.len(), 2);
3235 let mut total_value_transferred_msat = 0;
3236 let mut total_paid_msat = 0;
3237 for path in &route.paths {
3238 assert_eq!(path.last().unwrap().pubkey, nodes[3]);
3239 total_value_transferred_msat += path.last().unwrap().fee_msat;
3241 total_paid_msat += hop.fee_msat;
3244 // If we paid fee, this would be higher.
3245 assert_eq!(total_value_transferred_msat, 180_000);
3246 let total_fees_paid = total_paid_msat - total_value_transferred_msat;
3247 assert_eq!(total_fees_paid, 0);
3252 fn fees_on_mpp_route_test() {
3253 // This test makes sure that MPP algorithm properly takes into account
3254 // fees charged on the channels, by making the fees impactful:
3255 // if the fee is not properly accounted for, the behavior is different.
3256 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
3257 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3259 // We need a route consisting of 2 paths:
3260 // From our node to node3 via {node0, node2} and {node7, node2, node4}.
3261 // We will route 200 sats, Each path will have 100 sats capacity.
3263 // This test is not particularly stable: e.g.,
3264 // there's a way to route via {node0, node2, node4}.
3265 // It works while pathfinding is deterministic, but can be broken otherwise.
3266 // It's fine to ignore this concern for now.
3268 // Disable other potential paths.
3269 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3270 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3271 short_channel_id: 2,
3274 cltv_expiry_delta: 0,
3275 htlc_minimum_msat: 0,
3276 htlc_maximum_msat: OptionalField::Present(100_000),
3278 fee_proportional_millionths: 0,
3279 excess_data: Vec::new()
3282 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3283 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3284 short_channel_id: 7,
3287 cltv_expiry_delta: 0,
3288 htlc_minimum_msat: 0,
3289 htlc_maximum_msat: OptionalField::Present(100_000),
3291 fee_proportional_millionths: 0,
3292 excess_data: Vec::new()
3295 // Path via {node0, node2} is channels {1, 3, 5}.
3296 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3297 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3298 short_channel_id: 1,
3301 cltv_expiry_delta: 0,
3302 htlc_minimum_msat: 0,
3303 htlc_maximum_msat: OptionalField::Present(100_000),
3305 fee_proportional_millionths: 0,
3306 excess_data: Vec::new()
3308 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3309 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3310 short_channel_id: 3,
3313 cltv_expiry_delta: 0,
3314 htlc_minimum_msat: 0,
3315 htlc_maximum_msat: OptionalField::Present(100_000),
3317 fee_proportional_millionths: 0,
3318 excess_data: Vec::new()
3321 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(5)), 5);
3322 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3323 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3324 short_channel_id: 5,
3327 cltv_expiry_delta: 0,
3328 htlc_minimum_msat: 0,
3329 htlc_maximum_msat: OptionalField::Present(100_000),
3331 fee_proportional_millionths: 0,
3332 excess_data: Vec::new()
3335 // Path via {node7, node2, node4} is channels {12, 13, 6, 11}.
3336 // All channels should be 100 sats capacity. But for the fee experiment,
3337 // we'll add absolute fee of 150 sats paid for the use channel 6 (paid to node2 on channel 13).
3338 // Since channel 12 allows to deliver only 250 sats to channel 13, channel 13 can transfer only
3339 // 100 sats (and pay 150 sats in fees for the use of channel 6),
3340 // so no matter how large are other channels,
3341 // the whole path will be limited by 100 sats with just these 2 conditions:
3342 // - channel 12 capacity is 250 sats
3343 // - fee for channel 6 is 150 sats
3344 // Let's test this by enforcing these 2 conditions and removing other limits.
3345 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3346 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3347 short_channel_id: 12,
3350 cltv_expiry_delta: 0,
3351 htlc_minimum_msat: 0,
3352 htlc_maximum_msat: OptionalField::Present(250_000),
3354 fee_proportional_millionths: 0,
3355 excess_data: Vec::new()
3357 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
3358 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3359 short_channel_id: 13,
3362 cltv_expiry_delta: 0,
3363 htlc_minimum_msat: 0,
3364 htlc_maximum_msat: OptionalField::Absent,
3366 fee_proportional_millionths: 0,
3367 excess_data: Vec::new()
3370 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3371 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3372 short_channel_id: 6,
3375 cltv_expiry_delta: 0,
3376 htlc_minimum_msat: 0,
3377 htlc_maximum_msat: OptionalField::Absent,
3378 fee_base_msat: 150_000,
3379 fee_proportional_millionths: 0,
3380 excess_data: Vec::new()
3382 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
3383 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3384 short_channel_id: 11,
3387 cltv_expiry_delta: 0,
3388 htlc_minimum_msat: 0,
3389 htlc_maximum_msat: OptionalField::Absent,
3391 fee_proportional_millionths: 0,
3392 excess_data: Vec::new()
3396 // Attempt to route more than available results in a failure.
3397 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[3],
3398 Some(InvoiceFeatures::known()), None, &Vec::new(), 210_000, 42, Arc::clone(&logger)) {
3399 assert_eq!(err, "Failed to find a sufficient route to the given destination");
3400 } else { panic!(); }
3404 // Now, attempt to route 200 sats (exact amount we can route).
3405 let route = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[3],
3406 Some(InvoiceFeatures::known()), None, &Vec::new(), 200_000, 42, Arc::clone(&logger)).unwrap();
3407 assert_eq!(route.paths.len(), 2);
3409 let mut total_amount_paid_msat = 0;
3410 for path in &route.paths {
3411 assert_eq!(path.last().unwrap().pubkey, nodes[3]);
3412 total_amount_paid_msat += path.last().unwrap().fee_msat;
3414 assert_eq!(total_amount_paid_msat, 200_000);
3420 fn drop_lowest_channel_mpp_route_test() {
3421 // This test checks that low-capacity channel is dropped when after
3422 // path finding we realize that we found more capacity than we need.
3423 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
3424 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3426 // We need a route consisting of 3 paths:
3427 // From our node to node2 via node0, node7, node1 (three paths one hop each).
3429 // The first and the second paths should be sufficient, but the third should be
3430 // cheaper, so that we select it but drop later.
3432 // First, we set limits on these (previously unlimited) channels.
3433 // Their aggregate capacity will be 50 + 60 + 20 = 130 sats.
3435 // Path via node0 is channels {1, 3}. Limit them to 100 and 50 sats (total limit 50);
3436 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3437 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3438 short_channel_id: 1,
3441 cltv_expiry_delta: 0,
3442 htlc_minimum_msat: 0,
3443 htlc_maximum_msat: OptionalField::Present(100_000),
3445 fee_proportional_millionths: 0,
3446 excess_data: Vec::new()
3448 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3449 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3450 short_channel_id: 3,
3453 cltv_expiry_delta: 0,
3454 htlc_minimum_msat: 0,
3455 htlc_maximum_msat: OptionalField::Present(50_000),
3457 fee_proportional_millionths: 0,
3458 excess_data: Vec::new()
3461 // Path via node7 is channels {12, 13}. Limit them to 60 and 60 sats (total limit 60);
3462 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3463 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3464 short_channel_id: 12,
3467 cltv_expiry_delta: 0,
3468 htlc_minimum_msat: 0,
3469 htlc_maximum_msat: OptionalField::Present(60_000),
3471 fee_proportional_millionths: 0,
3472 excess_data: Vec::new()
3474 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
3475 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3476 short_channel_id: 13,
3479 cltv_expiry_delta: 0,
3480 htlc_minimum_msat: 0,
3481 htlc_maximum_msat: OptionalField::Present(60_000),
3483 fee_proportional_millionths: 0,
3484 excess_data: Vec::new()
3487 // Path via node1 is channels {2, 4}. Limit them to 20 and 20 sats (total capacity 20 sats).
3488 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3489 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3490 short_channel_id: 2,
3493 cltv_expiry_delta: 0,
3494 htlc_minimum_msat: 0,
3495 htlc_maximum_msat: OptionalField::Present(20_000),
3497 fee_proportional_millionths: 0,
3498 excess_data: Vec::new()
3500 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
3501 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3502 short_channel_id: 4,
3505 cltv_expiry_delta: 0,
3506 htlc_minimum_msat: 0,
3507 htlc_maximum_msat: OptionalField::Present(20_000),
3509 fee_proportional_millionths: 0,
3510 excess_data: Vec::new()
3514 // Attempt to route more than available results in a failure.
3515 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2],
3516 Some(InvoiceFeatures::known()), None, &Vec::new(), 150_000, 42, Arc::clone(&logger)) {
3517 assert_eq!(err, "Failed to find a sufficient route to the given destination");
3518 } else { panic!(); }
3522 // Now, attempt to route 125 sats (just a bit below the capacity of 3 channels).
3523 // Our algorithm should provide us with these 3 paths.
3524 let route = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2],
3525 Some(InvoiceFeatures::known()), None, &Vec::new(), 125_000, 42, Arc::clone(&logger)).unwrap();
3526 assert_eq!(route.paths.len(), 3);
3527 let mut total_amount_paid_msat = 0;
3528 for path in &route.paths {
3529 assert_eq!(path.len(), 2);
3530 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
3531 total_amount_paid_msat += path.last().unwrap().fee_msat;
3533 assert_eq!(total_amount_paid_msat, 125_000);
3537 // Attempt to route without the last small cheap channel
3538 let route = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2],
3539 Some(InvoiceFeatures::known()), None, &Vec::new(), 90_000, 42, Arc::clone(&logger)).unwrap();
3540 assert_eq!(route.paths.len(), 2);
3541 let mut total_amount_paid_msat = 0;
3542 for path in &route.paths {
3543 assert_eq!(path.len(), 2);
3544 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
3545 total_amount_paid_msat += path.last().unwrap().fee_msat;
3547 assert_eq!(total_amount_paid_msat, 90_000);
3552 fn min_criteria_consistency() {
3553 // Test that we don't use an inconsistent metric between updating and walking nodes during
3554 // our Dijkstra's pass. In the initial version of MPP, the "best source" for a given node
3555 // was updated with a different criterion from the heap sorting, resulting in loops in
3556 // calculated paths. We test for that specific case here.
3558 // We construct a network that looks like this:
3560 // node2 -1(3)2- node3
3564 // node1 -1(5)2- node4 -1(1)2- node6
3570 // We create a loop on the side of our real path - our destination is node 6, with a
3571 // previous hop of node 4. From 4, the cheapest previous path is channel 2 from node 2,
3572 // followed by node 3 over channel 3. Thereafter, the cheapest next-hop is back to node 4
3573 // (this time over channel 4). Channel 4 has 0 htlc_minimum_msat whereas channel 1 (the
3574 // other channel with a previous-hop of node 4) has a high (but irrelevant to the overall
3575 // payment) htlc_minimum_msat. In the original algorithm, this resulted in node4's
3576 // "previous hop" being set to node 3, creating a loop in the path.
3577 let secp_ctx = Secp256k1::new();
3578 let logger = Arc::new(test_utils::TestLogger::new());
3579 let net_graph_msg_handler = NetGraphMsgHandler::new(genesis_block(Network::Testnet).header.block_hash(), None, Arc::clone(&logger));
3580 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3582 add_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, &privkeys[1], ChannelFeatures::from_le_bytes(id_to_feature_flags(6)), 6);
3583 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3584 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3585 short_channel_id: 6,
3588 cltv_expiry_delta: (6 << 8) | 0,
3589 htlc_minimum_msat: 0,
3590 htlc_maximum_msat: OptionalField::Absent,
3592 fee_proportional_millionths: 0,
3593 excess_data: Vec::new()
3595 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[1], NodeFeatures::from_le_bytes(id_to_feature_flags(1)), 0);
3597 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], &privkeys[4], ChannelFeatures::from_le_bytes(id_to_feature_flags(5)), 5);
3598 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
3599 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3600 short_channel_id: 5,
3603 cltv_expiry_delta: (5 << 8) | 0,
3604 htlc_minimum_msat: 0,
3605 htlc_maximum_msat: OptionalField::Absent,
3607 fee_proportional_millionths: 0,
3608 excess_data: Vec::new()
3610 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[4], NodeFeatures::from_le_bytes(id_to_feature_flags(4)), 0);
3612 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(4)), 4);
3613 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
3614 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3615 short_channel_id: 4,
3618 cltv_expiry_delta: (4 << 8) | 0,
3619 htlc_minimum_msat: 0,
3620 htlc_maximum_msat: OptionalField::Absent,
3622 fee_proportional_millionths: 0,
3623 excess_data: Vec::new()
3625 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[3], NodeFeatures::from_le_bytes(id_to_feature_flags(3)), 0);
3627 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[3], &privkeys[2], ChannelFeatures::from_le_bytes(id_to_feature_flags(3)), 3);
3628 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[3], UnsignedChannelUpdate {
3629 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3630 short_channel_id: 3,
3633 cltv_expiry_delta: (3 << 8) | 0,
3634 htlc_minimum_msat: 0,
3635 htlc_maximum_msat: OptionalField::Absent,
3637 fee_proportional_millionths: 0,
3638 excess_data: Vec::new()
3640 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[2], NodeFeatures::from_le_bytes(id_to_feature_flags(2)), 0);
3642 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], &privkeys[4], ChannelFeatures::from_le_bytes(id_to_feature_flags(2)), 2);
3643 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3644 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3645 short_channel_id: 2,
3648 cltv_expiry_delta: (2 << 8) | 0,
3649 htlc_minimum_msat: 0,
3650 htlc_maximum_msat: OptionalField::Absent,
3652 fee_proportional_millionths: 0,
3653 excess_data: Vec::new()
3656 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], &privkeys[6], ChannelFeatures::from_le_bytes(id_to_feature_flags(1)), 1);
3657 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
3658 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3659 short_channel_id: 1,
3662 cltv_expiry_delta: (1 << 8) | 0,
3663 htlc_minimum_msat: 100,
3664 htlc_maximum_msat: OptionalField::Absent,
3666 fee_proportional_millionths: 0,
3667 excess_data: Vec::new()
3669 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[6], NodeFeatures::from_le_bytes(id_to_feature_flags(6)), 0);
3672 // Now ensure the route flows simply over nodes 1 and 4 to 6.
3673 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();
3674 assert_eq!(route.paths.len(), 1);
3675 assert_eq!(route.paths[0].len(), 3);
3677 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
3678 assert_eq!(route.paths[0][0].short_channel_id, 6);
3679 assert_eq!(route.paths[0][0].fee_msat, 100);
3680 assert_eq!(route.paths[0][0].cltv_expiry_delta, (5 << 8) | 0);
3681 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(1));
3682 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(6));
3684 assert_eq!(route.paths[0][1].pubkey, nodes[4]);
3685 assert_eq!(route.paths[0][1].short_channel_id, 5);
3686 assert_eq!(route.paths[0][1].fee_msat, 0);
3687 assert_eq!(route.paths[0][1].cltv_expiry_delta, (1 << 8) | 0);
3688 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(4));
3689 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(5));
3691 assert_eq!(route.paths[0][2].pubkey, nodes[6]);
3692 assert_eq!(route.paths[0][2].short_channel_id, 1);
3693 assert_eq!(route.paths[0][2].fee_msat, 10_000);
3694 assert_eq!(route.paths[0][2].cltv_expiry_delta, 42);
3695 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(6));
3696 assert_eq!(route.paths[0][2].channel_features.le_flags(), &id_to_feature_flags(1));
3702 fn exact_fee_liquidity_limit() {
3703 // Test that if, while walking the graph, we find a hop that has exactly enough liquidity
3704 // for us, including later hop fees, we take it. In the first version of our MPP algorithm
3705 // we calculated fees on a higher value, resulting in us ignoring such paths.
3706 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
3707 let (our_privkey, our_id, _, nodes) = get_nodes(&secp_ctx);
3709 // We modify the graph to set the htlc_maximum of channel 2 to below the value we wish to
3711 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3712 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3713 short_channel_id: 2,
3716 cltv_expiry_delta: 0,
3717 htlc_minimum_msat: 0,
3718 htlc_maximum_msat: OptionalField::Present(85_000),
3720 fee_proportional_millionths: 0,
3721 excess_data: Vec::new()
3724 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3725 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3726 short_channel_id: 12,
3729 cltv_expiry_delta: (4 << 8) | 1,
3730 htlc_minimum_msat: 0,
3731 htlc_maximum_msat: OptionalField::Present(270_000),
3733 fee_proportional_millionths: 1000000,
3734 excess_data: Vec::new()
3738 // Now, attempt to route 90 sats, which is exactly 90 sats at the last hop, plus the
3739 // 200% fee charged channel 13 in the 1-to-2 direction.
3740 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();
3741 assert_eq!(route.paths.len(), 1);
3742 assert_eq!(route.paths[0].len(), 2);
3744 assert_eq!(route.paths[0][0].pubkey, nodes[7]);
3745 assert_eq!(route.paths[0][0].short_channel_id, 12);
3746 assert_eq!(route.paths[0][0].fee_msat, 90_000*2);
3747 assert_eq!(route.paths[0][0].cltv_expiry_delta, (13 << 8) | 1);
3748 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(8));
3749 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(12));
3751 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
3752 assert_eq!(route.paths[0][1].short_channel_id, 13);
3753 assert_eq!(route.paths[0][1].fee_msat, 90_000);
3754 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
3755 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
3756 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(13));
3761 fn htlc_max_reduction_below_min() {
3762 // Test that if, while walking the graph, we reduce the value being sent to meet an
3763 // htlc_maximum_msat, we don't end up undershooting a later htlc_minimum_msat. In the
3764 // initial version of MPP we'd accept such routes but reject them while recalculating fees,
3765 // resulting in us thinking there is no possible path, even if other paths exist.
3766 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
3767 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3769 // We modify the graph to set the htlc_minimum of channel 2 and 4 as needed - channel 2
3770 // gets an htlc_maximum_msat of 80_000 and channel 4 an htlc_minimum_msat of 90_000. We
3771 // then try to send 90_000.
3772 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3773 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3774 short_channel_id: 2,
3777 cltv_expiry_delta: 0,
3778 htlc_minimum_msat: 0,
3779 htlc_maximum_msat: OptionalField::Present(80_000),
3781 fee_proportional_millionths: 0,
3782 excess_data: Vec::new()
3784 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
3785 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3786 short_channel_id: 4,
3789 cltv_expiry_delta: (4 << 8) | 1,
3790 htlc_minimum_msat: 90_000,
3791 htlc_maximum_msat: OptionalField::Absent,
3793 fee_proportional_millionths: 0,
3794 excess_data: Vec::new()
3798 // Now, attempt to route 90 sats, hitting the htlc_minimum on channel 4, but
3799 // overshooting the htlc_maximum on channel 2. Thus, we should pick the (absurdly
3800 // expensive) channels 12-13 path.
3801 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();
3802 assert_eq!(route.paths.len(), 1);
3803 assert_eq!(route.paths[0].len(), 2);
3805 assert_eq!(route.paths[0][0].pubkey, nodes[7]);
3806 assert_eq!(route.paths[0][0].short_channel_id, 12);
3807 assert_eq!(route.paths[0][0].fee_msat, 90_000*2);
3808 assert_eq!(route.paths[0][0].cltv_expiry_delta, (13 << 8) | 1);
3809 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(8));
3810 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(12));
3812 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
3813 assert_eq!(route.paths[0][1].short_channel_id, 13);
3814 assert_eq!(route.paths[0][1].fee_msat, 90_000);
3815 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
3816 assert_eq!(route.paths[0][1].node_features.le_flags(), InvoiceFeatures::known().le_flags());
3817 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(13));
3821 #[cfg(not(feature = "no_std"))]
3822 pub(super) fn random_init_seed() -> u64 {
3823 // Because the default HashMap in std pulls OS randomness, we can use it as a (bad) RNG.
3824 use core::hash::{BuildHasher, Hasher};
3825 let seed = std::collections::hash_map::RandomState::new().build_hasher().finish();
3826 println!("Using seed of {}", seed);
3829 #[cfg(not(feature = "no_std"))]
3830 use util::ser::Readable;
3833 #[cfg(not(feature = "no_std"))]
3834 fn generate_routes() {
3835 let mut d = match super::test_utils::get_route_file() {
3842 let graph = NetworkGraph::read(&mut d).unwrap();
3844 // First, get 100 (source, destination) pairs for which route-getting actually succeeds...
3845 let mut seed = random_init_seed() as usize;
3846 'load_endpoints: for _ in 0..10 {
3848 seed = seed.overflowing_mul(0xdeadbeef).0;
3849 let src = graph.get_nodes().keys().skip(seed % graph.get_nodes().len()).next().unwrap();
3850 seed = seed.overflowing_mul(0xdeadbeef).0;
3851 let dst = graph.get_nodes().keys().skip(seed % graph.get_nodes().len()).next().unwrap();
3852 let amt = seed as u64 % 200_000_000;
3853 if get_route(src, &graph, dst, None, None, &[], amt, 42, &test_utils::TestLogger::new()).is_ok() {
3854 continue 'load_endpoints;
3861 #[cfg(not(feature = "no_std"))]
3862 fn generate_routes_mpp() {
3863 let mut d = match super::test_utils::get_route_file() {
3870 let graph = NetworkGraph::read(&mut d).unwrap();
3872 // First, get 100 (source, destination) pairs for which route-getting actually succeeds...
3873 let mut seed = random_init_seed() as usize;
3874 'load_endpoints: for _ in 0..10 {
3876 seed = seed.overflowing_mul(0xdeadbeef).0;
3877 let src = graph.get_nodes().keys().skip(seed % graph.get_nodes().len()).next().unwrap();
3878 seed = seed.overflowing_mul(0xdeadbeef).0;
3879 let dst = graph.get_nodes().keys().skip(seed % graph.get_nodes().len()).next().unwrap();
3880 let amt = seed as u64 % 200_000_000;
3881 if get_route(src, &graph, dst, Some(InvoiceFeatures::known()), None, &[], amt, 42, &test_utils::TestLogger::new()).is_ok() {
3882 continue 'load_endpoints;
3889 #[cfg(all(test, not(feature = "no_std")))]
3890 pub(crate) mod test_utils {
3892 /// Tries to open a network graph file, or panics with a URL to fetch it.
3893 pub(crate) fn get_route_file() -> Result<std::fs::File, &'static str> {
3894 let res = File::open("net_graph-2021-05-31.bin") // By default we're run in RL/lightning
3895 .or_else(|_| File::open("lightning/net_graph-2021-05-31.bin")) // We may be run manually in RL/
3896 .or_else(|_| { // Fall back to guessing based on the binary location
3897 // path is likely something like .../rust-lightning/target/debug/deps/lightning-...
3898 let mut path = std::env::current_exe().unwrap();
3899 path.pop(); // lightning-...
3901 path.pop(); // debug
3902 path.pop(); // target
3903 path.push("lightning");
3904 path.push("net_graph-2021-05-31.bin");
3905 eprintln!("{}", path.to_str().unwrap());
3908 .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");
3909 #[cfg(require_route_graph_test)]
3910 return Ok(res.unwrap());
3911 #[cfg(not(require_route_graph_test))]
3916 #[cfg(all(test, feature = "unstable", not(feature = "no_std")))]
3919 use util::logger::{Logger, Record};
3923 struct DummyLogger {}
3924 impl Logger for DummyLogger {
3925 fn log(&self, _record: &Record) {}
3929 fn generate_routes(bench: &mut Bencher) {
3930 let mut d = test_utils::get_route_file().unwrap();
3931 let graph = NetworkGraph::read(&mut d).unwrap();
3933 // First, get 100 (source, destination) pairs for which route-getting actually succeeds...
3934 let mut path_endpoints = Vec::new();
3935 let mut seed: usize = 0xdeadbeef;
3936 'load_endpoints: for _ in 0..100 {
3939 let src = graph.get_nodes().keys().skip(seed % graph.get_nodes().len()).next().unwrap();
3941 let dst = graph.get_nodes().keys().skip(seed % graph.get_nodes().len()).next().unwrap();
3942 let amt = seed as u64 % 1_000_000;
3943 if get_route(src, &graph, dst, None, None, &[], amt, 42, &DummyLogger{}).is_ok() {
3944 path_endpoints.push((src, dst, amt));
3945 continue 'load_endpoints;
3950 // ...then benchmark finding paths between the nodes we learned.
3953 let (src, dst, amt) = path_endpoints[idx % path_endpoints.len()];
3954 assert!(get_route(src, &graph, dst, None, None, &[], amt, 42, &DummyLogger{}).is_ok());
3960 fn generate_mpp_routes(bench: &mut Bencher) {
3961 let mut d = test_utils::get_route_file().unwrap();
3962 let graph = NetworkGraph::read(&mut d).unwrap();
3964 // First, get 100 (source, destination) pairs for which route-getting actually succeeds...
3965 let mut path_endpoints = Vec::new();
3966 let mut seed: usize = 0xdeadbeef;
3967 'load_endpoints: for _ in 0..100 {
3970 let src = graph.get_nodes().keys().skip(seed % graph.get_nodes().len()).next().unwrap();
3972 let dst = graph.get_nodes().keys().skip(seed % graph.get_nodes().len()).next().unwrap();
3973 let amt = seed as u64 % 1_000_000;
3974 if get_route(src, &graph, dst, Some(InvoiceFeatures::known()), None, &[], amt, 42, &DummyLogger{}).is_ok() {
3975 path_endpoints.push((src, dst, amt));
3976 continue 'load_endpoints;
3981 // ...then benchmark finding paths between the nodes we learned.
3984 let (src, dst, amt) = path_endpoints[idx % path_endpoints.len()];
3985 assert!(get_route(src, &graph, dst, Some(InvoiceFeatures::known()), None, &[], amt, 42, &DummyLogger{}).is_ok());