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 keysend route from us (payer) to the given target node (payee). This is needed because
331 /// keysend payments do not have an invoice from which to pull the payee's supported features, which
332 /// makes it tricky to otherwise supply the `payee_features` parameter of `get_route`.
333 pub fn get_keysend_route<L: Deref>(our_node_id: &PublicKey, network: &NetworkGraph, payee:
334 &PublicKey, first_hops: Option<&[&ChannelDetails]>, last_hops: &[&RouteHint],
335 final_value_msat: u64, final_cltv: u32, logger: L) -> Result<Route,
336 LightningError> where L::Target: Logger {
337 let invoice_features = InvoiceFeatures::for_keysend();
338 get_route(our_node_id, network, payee, Some(invoice_features), first_hops, last_hops,
339 final_value_msat, final_cltv, logger)
342 /// Gets a route from us (payer) to the given target node (payee).
344 /// If the payee provided features in their invoice, they should be provided via payee_features.
345 /// Without this, MPP will only be used if the payee's features are available in the network graph.
347 /// Private routing paths between a public node and the target may be included in `last_hops`.
348 /// Currently, only the last hop in each path is considered.
350 /// If some channels aren't announced, it may be useful to fill in a first_hops with the
351 /// results from a local ChannelManager::list_usable_channels() call. If it is filled in, our
352 /// view of our local channels (from net_graph_msg_handler) will be ignored, and only those
353 /// in first_hops will be used.
355 /// Panics if first_hops contains channels without short_channel_ids
356 /// (ChannelManager::list_usable_channels will never include such channels).
358 /// The fees on channels from us to next-hops are ignored (as they are assumed to all be
359 /// equal), however the enabled/disabled bit on such channels as well as the
360 /// htlc_minimum_msat/htlc_maximum_msat *are* checked as they may change based on the receiving node.
361 pub fn get_route<L: Deref>(our_node_id: &PublicKey, network: &NetworkGraph, payee: &PublicKey, payee_features: Option<InvoiceFeatures>, first_hops: Option<&[&ChannelDetails]>,
362 last_hops: &[&RouteHint], final_value_msat: u64, final_cltv: u32, logger: L) -> Result<Route, LightningError> where L::Target: Logger {
363 // TODO: Obviously *only* using total fee cost sucks. We should consider weighting by
364 // uptime/success in using a node in the past.
365 if *payee == *our_node_id {
366 return Err(LightningError{err: "Cannot generate a route to ourselves".to_owned(), action: ErrorAction::IgnoreError});
369 if final_value_msat > MAX_VALUE_MSAT {
370 return Err(LightningError{err: "Cannot generate a route of more value than all existing satoshis".to_owned(), action: ErrorAction::IgnoreError});
373 if final_value_msat == 0 {
374 return Err(LightningError{err: "Cannot send a payment of 0 msat".to_owned(), action: ErrorAction::IgnoreError});
377 let last_hops = last_hops.iter().filter_map(|hops| hops.0.last()).collect::<Vec<_>>();
378 for last_hop in last_hops.iter() {
379 if last_hop.src_node_id == *payee {
380 return Err(LightningError{err: "Last hop cannot have a payee as a source.".to_owned(), action: ErrorAction::IgnoreError});
384 // The general routing idea is the following:
385 // 1. Fill first/last hops communicated by the caller.
386 // 2. Attempt to construct a path from payer to payee for transferring
387 // any ~sufficient (described later) value.
388 // If succeed, remember which channels were used and how much liquidity they have available,
389 // so that future paths don't rely on the same liquidity.
390 // 3. Prooceed to the next step if:
391 // - we hit the recommended target value;
392 // - OR if we could not construct a new path. Any next attempt will fail too.
393 // Otherwise, repeat step 2.
394 // 4. See if we managed to collect paths which aggregately are able to transfer target value
395 // (not recommended value). If yes, proceed. If not, fail routing.
396 // 5. Randomly combine paths into routes having enough to fulfill the payment. (TODO: knapsack)
397 // 6. Of all the found paths, select only those with the lowest total fee.
398 // 7. The last path in every selected route is likely to be more than we need.
399 // Reduce its value-to-transfer and recompute fees.
400 // 8. Choose the best route by the lowest total fee.
402 // As for the actual search algorithm,
403 // we do a payee-to-payer pseudo-Dijkstra's sorting by each node's distance from the payee
404 // plus the minimum per-HTLC fee to get from it to another node (aka "shitty pseudo-A*").
406 // We are not a faithful Dijkstra's implementation because we can change values which impact
407 // earlier nodes while processing later nodes. Specifically, if we reach a channel with a lower
408 // liquidity limit (via htlc_maximum_msat, on-chain capacity or assumed liquidity limits) then
409 // the value we are currently attempting to send over a path, we simply reduce the value being
410 // sent along the path for any hops after that channel. This may imply that later fees (which
411 // we've already tabulated) are lower because a smaller value is passing through the channels
412 // (and the proportional fee is thus lower). There isn't a trivial way to recalculate the
413 // channels which were selected earlier (and which may still be used for other paths without a
414 // lower liquidity limit), so we simply accept that some liquidity-limited paths may be
417 // One potentially problematic case for this algorithm would be if there are many
418 // liquidity-limited paths which are liquidity-limited near the destination (ie early in our
419 // graph walking), we may never find a path which is not liquidity-limited and has lower
420 // proportional fee (and only lower absolute fee when considering the ultimate value sent).
421 // Because we only consider paths with at least 5% of the total value being sent, the damage
422 // from such a case should be limited, however this could be further reduced in the future by
423 // calculating fees on the amount we wish to route over a path, ie ignoring the liquidity
424 // limits for the purposes of fee calculation.
426 // Alternatively, we could store more detailed path information in the heap (targets, below)
427 // and index the best-path map (dist, below) by node *and* HTLC limits, however that would blow
428 // up the runtime significantly both algorithmically (as we'd traverse nodes multiple times)
429 // and practically (as we would need to store dynamically-allocated path information in heap
430 // objects, increasing malloc traffic and indirect memory access significantly). Further, the
431 // results of such an algorithm would likely be biased towards lower-value paths.
433 // Further, we could return to a faithful Dijkstra's algorithm by rejecting paths with limits
434 // outside of our current search value, running a path search more times to gather candidate
435 // paths at different values. While this may be acceptable, further path searches may increase
436 // runtime for little gain. Specifically, the current algorithm rather efficiently explores the
437 // graph for candidate paths, calculating the maximum value which can realistically be sent at
438 // the same time, remaining generic across different payment values.
440 // TODO: There are a few tweaks we could do, including possibly pre-calculating more stuff
441 // to use as the A* heuristic beyond just the cost to get one node further than the current
444 let dummy_directional_info = DummyDirectionalChannelInfo { // used for first_hops routes
445 cltv_expiry_delta: 0,
446 htlc_minimum_msat: 0,
447 htlc_maximum_msat: None,
450 proportional_millionths: 0,
454 // Allow MPP only if we have a features set from somewhere that indicates the payee supports
455 // it. If the payee supports it they're supposed to include it in the invoice, so that should
457 let allow_mpp = if let Some(features) = &payee_features {
458 features.supports_basic_mpp()
459 } else if let Some(node) = network.get_nodes().get(&payee) {
460 if let Some(node_info) = node.announcement_info.as_ref() {
461 node_info.features.supports_basic_mpp()
466 // Prepare the data we'll use for payee-to-payer search by
467 // inserting first hops suggested by the caller as targets.
468 // Our search will then attempt to reach them while traversing from the payee node.
469 let mut first_hop_targets: HashMap<_, (_, ChannelFeatures, _, NodeFeatures)> =
470 HashMap::with_capacity(if first_hops.is_some() { first_hops.as_ref().unwrap().len() } else { 0 });
471 if let Some(hops) = first_hops {
473 let short_channel_id = chan.short_channel_id.expect("first_hops should be filled in with usable channels, not pending ones");
474 if chan.counterparty.node_id == *our_node_id {
475 return Err(LightningError{err: "First hop cannot have our_node_id as a destination.".to_owned(), action: ErrorAction::IgnoreError});
477 first_hop_targets.insert(chan.counterparty.node_id, (short_channel_id, chan.counterparty.features.to_context(), chan.outbound_capacity_msat, chan.counterparty.features.to_context()));
479 if first_hop_targets.is_empty() {
480 return Err(LightningError{err: "Cannot route when there are no outbound routes away from us".to_owned(), action: ErrorAction::IgnoreError});
484 let empty_channel_features = ChannelFeatures::empty();
486 // The main heap containing all candidate next-hops sorted by their score (max(A* fee,
487 // htlc_minimum)). Ideally this would be a heap which allowed cheap score reduction instead of
488 // adding duplicate entries when we find a better path to a given node.
489 let mut targets = BinaryHeap::new();
491 // Map from node_id to information about the best current path to that node, including feerate
493 let mut dist = HashMap::with_capacity(network.get_nodes().len());
495 // During routing, if we ignore a path due to an htlc_minimum_msat limit, we set this,
496 // indicating that we may wish to try again with a higher value, potentially paying to meet an
497 // htlc_minimum with extra fees while still finding a cheaper path.
498 let mut hit_minimum_limit;
500 // When arranging a route, we select multiple paths so that we can make a multi-path payment.
501 // We start with a path_value of the exact amount we want, and if that generates a route we may
502 // return it immediately. Otherwise, we don't stop searching for paths until we have 3x the
503 // amount we want in total across paths, selecting the best subset at the end.
504 const ROUTE_CAPACITY_PROVISION_FACTOR: u64 = 3;
505 let recommended_value_msat = final_value_msat * ROUTE_CAPACITY_PROVISION_FACTOR as u64;
506 let mut path_value_msat = final_value_msat;
508 // We don't want multiple paths (as per MPP) share liquidity of the same channels.
509 // This map allows paths to be aware of the channel use by other paths in the same call.
510 // This would help to make a better path finding decisions and not "overbook" channels.
511 // It is unaware of the directions (except for `outbound_capacity_msat` in `first_hops`).
512 let mut bookkeeped_channels_liquidity_available_msat = HashMap::with_capacity(network.get_nodes().len());
514 // Keeping track of how much value we already collected across other paths. Helps to decide:
515 // - how much a new path should be transferring (upper bound);
516 // - whether a channel should be disregarded because
517 // it's available liquidity is too small comparing to how much more we need to collect;
518 // - when we want to stop looking for new paths.
519 let mut already_collected_value_msat = 0;
521 log_trace!(logger, "Building path from {} (payee) to {} (us/payer) for value {} msat.", payee, our_node_id, final_value_msat);
523 macro_rules! add_entry {
524 // Adds entry which goes from $src_node_id to $dest_node_id
525 // over the channel with id $chan_id with fees described in
526 // $directional_info.
527 // $next_hops_fee_msat represents the fees paid for using all the channel *after* this one,
528 // since that value has to be transferred over this channel.
529 // Returns whether this channel caused an update to `targets`.
530 ( $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,
531 $next_hops_value_contribution: expr, $next_hops_path_htlc_minimum_msat: expr ) => { {
532 // We "return" whether we updated the path at the end, via this:
533 let mut did_add_update_path_to_src_node = false;
534 // Channels to self should not be used. This is more of belt-and-suspenders, because in
535 // practice these cases should be caught earlier:
536 // - for regular channels at channel announcement (TODO)
537 // - for first and last hops early in get_route
538 if $src_node_id != $dest_node_id.clone() {
539 let available_liquidity_msat = bookkeeped_channels_liquidity_available_msat.entry($chan_id.clone()).or_insert_with(|| {
540 let mut initial_liquidity_available_msat = None;
541 if let Some(capacity_sats) = $capacity_sats {
542 initial_liquidity_available_msat = Some(capacity_sats * 1000);
545 if let Some(htlc_maximum_msat) = $directional_info.htlc_maximum_msat {
546 if let Some(available_msat) = initial_liquidity_available_msat {
547 initial_liquidity_available_msat = Some(cmp::min(available_msat, htlc_maximum_msat));
549 initial_liquidity_available_msat = Some(htlc_maximum_msat);
553 match initial_liquidity_available_msat {
554 Some(available_msat) => available_msat,
555 // We assume channels with unknown balance have
556 // a capacity of 0.0025 BTC (or 250_000 sats).
557 None => 250_000 * 1000
561 // It is tricky to substract $next_hops_fee_msat from available liquidity here.
562 // It may be misleading because we might later choose to reduce the value transferred
563 // over these channels, and the channel which was insufficient might become sufficient.
564 // Worst case: we drop a good channel here because it can't cover the high following
565 // fees caused by one expensive channel, but then this channel could have been used
566 // if the amount being transferred over this path is lower.
567 // We do this for now, but this is a subject for removal.
568 if let Some(available_value_contribution_msat) = available_liquidity_msat.checked_sub($next_hops_fee_msat) {
570 // Routing Fragmentation Mitigation heuristic:
572 // Routing fragmentation across many payment paths increases the overall routing
573 // fees as you have irreducible routing fees per-link used (`fee_base_msat`).
574 // Taking too many smaller paths also increases the chance of payment failure.
575 // Thus to avoid this effect, we require from our collected links to provide
576 // at least a minimal contribution to the recommended value yet-to-be-fulfilled.
578 // This requirement is currently 5% of the remaining-to-be-collected value.
579 // This means as we successfully advance in our collection,
580 // the absolute liquidity contribution is lowered,
581 // thus increasing the number of potential channels to be selected.
583 // Derive the minimal liquidity contribution with a ratio of 20 (5%, rounded up)
584 // or 100% if we're not allowed to do multipath payments.
585 let minimal_value_contribution_msat: u64 = if allow_mpp {
586 (recommended_value_msat - already_collected_value_msat + 19) / 20
590 // Verify the liquidity offered by this channel complies to the minimal contribution.
591 let contributes_sufficient_value = available_value_contribution_msat >= minimal_value_contribution_msat;
593 let value_contribution_msat = cmp::min(available_value_contribution_msat, $next_hops_value_contribution);
594 // Includes paying fees for the use of the following channels.
595 let amount_to_transfer_over_msat: u64 = match value_contribution_msat.checked_add($next_hops_fee_msat) {
596 Some(result) => result,
597 // Can't overflow due to how the values were computed right above.
598 None => unreachable!(),
600 #[allow(unused_comparisons)] // $next_hops_path_htlc_minimum_msat is 0 in some calls so rustc complains
601 let over_path_minimum_msat = amount_to_transfer_over_msat >= $directional_info.htlc_minimum_msat &&
602 amount_to_transfer_over_msat >= $next_hops_path_htlc_minimum_msat;
604 // If HTLC minimum is larger than the amount we're going to transfer, we shouldn't
605 // bother considering this channel.
606 // Since we're choosing amount_to_transfer_over_msat as maximum possible, it can
607 // be only reduced later (not increased), so this channel should just be skipped
608 // as not sufficient.
609 if !over_path_minimum_msat {
610 hit_minimum_limit = true;
611 } else if contributes_sufficient_value {
612 // Note that low contribution here (limited by available_liquidity_msat)
613 // might violate htlc_minimum_msat on the hops which are next along the
614 // payment path (upstream to the payee). To avoid that, we recompute path
615 // path fees knowing the final path contribution after constructing it.
616 let path_htlc_minimum_msat = match compute_fees($next_hops_path_htlc_minimum_msat, $directional_info.fees)
617 .map(|fee_msat| fee_msat.checked_add($next_hops_path_htlc_minimum_msat)) {
618 Some(Some(value_msat)) => cmp::max(value_msat, $directional_info.htlc_minimum_msat),
619 _ => u64::max_value()
621 let hm_entry = dist.entry(&$src_node_id);
622 let old_entry = hm_entry.or_insert_with(|| {
623 // If there was previously no known way to access
624 // the source node (recall it goes payee-to-payer) of $chan_id, first add
625 // a semi-dummy record just to compute the fees to reach the source node.
626 // This will affect our decision on selecting $chan_id
627 // as a way to reach the $dest_node_id.
628 let mut fee_base_msat = u32::max_value();
629 let mut fee_proportional_millionths = u32::max_value();
630 if let Some(Some(fees)) = network.get_nodes().get(&$src_node_id).map(|node| node.lowest_inbound_channel_fees) {
631 fee_base_msat = fees.base_msat;
632 fee_proportional_millionths = fees.proportional_millionths;
635 pubkey: $dest_node_id.clone(),
637 channel_features: $chan_features,
639 cltv_expiry_delta: 0,
640 src_lowest_inbound_fees: RoutingFees {
641 base_msat: fee_base_msat,
642 proportional_millionths: fee_proportional_millionths,
644 channel_fees: $directional_info.fees,
645 next_hops_fee_msat: u64::max_value(),
646 hop_use_fee_msat: u64::max_value(),
647 total_fee_msat: u64::max_value(),
648 htlc_minimum_msat: $directional_info.htlc_minimum_msat,
649 path_htlc_minimum_msat,
650 was_processed: false,
651 #[cfg(any(test, feature = "fuzztarget"))]
652 value_contribution_msat,
656 #[allow(unused_mut)] // We only use the mut in cfg(test)
657 let mut should_process = !old_entry.was_processed;
658 #[cfg(any(test, feature = "fuzztarget"))]
660 // In test/fuzzing builds, we do extra checks to make sure the skipping
661 // of already-seen nodes only happens in cases we expect (see below).
662 if !should_process { should_process = true; }
666 let mut hop_use_fee_msat = 0;
667 let mut total_fee_msat = $next_hops_fee_msat;
669 // Ignore hop_use_fee_msat for channel-from-us as we assume all channels-from-us
670 // will have the same effective-fee
671 if $src_node_id != *our_node_id {
672 match compute_fees(amount_to_transfer_over_msat, $directional_info.fees) {
673 // max_value means we'll always fail
674 // the old_entry.total_fee_msat > total_fee_msat check
675 None => total_fee_msat = u64::max_value(),
677 hop_use_fee_msat = fee_msat;
678 total_fee_msat += hop_use_fee_msat;
679 // When calculating the lowest inbound fees to a node, we
680 // calculate fees here not based on the actual value we think
681 // will flow over this channel, but on the minimum value that
682 // we'll accept flowing over it. The minimum accepted value
683 // is a constant through each path collection run, ensuring
684 // consistent basis. Otherwise we may later find a
685 // different path to the source node that is more expensive,
686 // but which we consider to be cheaper because we are capacity
687 // constrained and the relative fee becomes lower.
688 match compute_fees(minimal_value_contribution_msat, old_entry.src_lowest_inbound_fees)
689 .map(|a| a.checked_add(total_fee_msat)) {
694 total_fee_msat = u64::max_value();
701 let new_graph_node = RouteGraphNode {
702 pubkey: $src_node_id,
703 lowest_fee_to_peer_through_node: total_fee_msat,
704 lowest_fee_to_node: $next_hops_fee_msat as u64 + hop_use_fee_msat,
705 value_contribution_msat: value_contribution_msat,
706 path_htlc_minimum_msat,
709 // Update the way of reaching $src_node_id with the given $chan_id (from $dest_node_id),
710 // if this way is cheaper than the already known
711 // (considering the cost to "reach" this channel from the route destination,
712 // the cost of using this channel,
713 // and the cost of routing to the source node of this channel).
714 // Also, consider that htlc_minimum_msat_difference, because we might end up
715 // paying it. Consider the following exploit:
716 // we use 2 paths to transfer 1.5 BTC. One of them is 0-fee normal 1 BTC path,
717 // and for the other one we picked a 1sat-fee path with htlc_minimum_msat of
718 // 1 BTC. Now, since the latter is more expensive, we gonna try to cut it
719 // by 0.5 BTC, but then match htlc_minimum_msat by paying a fee of 0.5 BTC
721 // Ideally the scoring could be smarter (e.g. 0.5*htlc_minimum_msat here),
722 // but it may require additional tracking - we don't want to double-count
723 // the fees included in $next_hops_path_htlc_minimum_msat, but also
724 // can't use something that may decrease on future hops.
725 let old_cost = cmp::max(old_entry.total_fee_msat, old_entry.path_htlc_minimum_msat);
726 let new_cost = cmp::max(total_fee_msat, path_htlc_minimum_msat);
728 if !old_entry.was_processed && new_cost < old_cost {
729 targets.push(new_graph_node);
730 old_entry.next_hops_fee_msat = $next_hops_fee_msat;
731 old_entry.hop_use_fee_msat = hop_use_fee_msat;
732 old_entry.total_fee_msat = total_fee_msat;
733 old_entry.pubkey = $dest_node_id.clone();
734 old_entry.short_channel_id = $chan_id.clone();
735 old_entry.channel_features = $chan_features;
736 old_entry.fee_msat = 0; // This value will be later filled with hop_use_fee_msat of the following channel
737 old_entry.cltv_expiry_delta = $directional_info.cltv_expiry_delta as u32;
738 old_entry.channel_fees = $directional_info.fees;
739 old_entry.htlc_minimum_msat = $directional_info.htlc_minimum_msat;
740 old_entry.path_htlc_minimum_msat = path_htlc_minimum_msat;
741 #[cfg(any(test, feature = "fuzztarget"))]
743 old_entry.value_contribution_msat = value_contribution_msat;
745 did_add_update_path_to_src_node = true;
746 } else if old_entry.was_processed && new_cost < old_cost {
747 #[cfg(any(test, feature = "fuzztarget"))]
749 // If we're skipping processing a node which was previously
750 // processed even though we found another path to it with a
751 // cheaper fee, check that it was because the second path we
752 // found (which we are processing now) has a lower value
753 // contribution due to an HTLC minimum limit.
755 // e.g. take a graph with two paths from node 1 to node 2, one
756 // through channel A, and one through channel B. Channel A and
757 // B are both in the to-process heap, with their scores set by
758 // a higher htlc_minimum than fee.
759 // Channel A is processed first, and the channels onwards from
760 // node 1 are added to the to-process heap. Thereafter, we pop
761 // Channel B off of the heap, note that it has a much more
762 // restrictive htlc_maximum_msat, and recalculate the fees for
763 // all of node 1's channels using the new, reduced, amount.
765 // This would be bogus - we'd be selecting a higher-fee path
766 // with a lower htlc_maximum_msat instead of the one we'd
767 // already decided to use.
768 debug_assert!(path_htlc_minimum_msat < old_entry.path_htlc_minimum_msat);
769 debug_assert!(value_contribution_msat < old_entry.value_contribution_msat);
776 did_add_update_path_to_src_node
780 let empty_node_features = NodeFeatures::empty();
781 // Find ways (channels with destination) to reach a given node and store them
782 // in the corresponding data structures (routing graph etc).
783 // $fee_to_target_msat represents how much it costs to reach to this node from the payee,
784 // meaning how much will be paid in fees after this node (to the best of our knowledge).
785 // This data can later be helpful to optimize routing (pay lower fees).
786 macro_rules! add_entries_to_cheapest_to_target_node {
787 ( $node: expr, $node_id: expr, $fee_to_target_msat: expr, $next_hops_value_contribution: expr, $next_hops_path_htlc_minimum_msat: expr ) => {
788 let skip_node = if let Some(elem) = dist.get_mut($node_id) {
789 let was_processed = elem.was_processed;
790 elem.was_processed = true;
793 // Entries are added to dist in add_entry!() when there is a channel from a node.
794 // Because there are no channels from payee, it will not have a dist entry at this point.
795 // If we're processing any other node, it is always be the result of a channel from it.
796 assert_eq!($node_id, payee);
801 if first_hops.is_some() {
802 if let Some(&(ref first_hop, ref features, ref outbound_capacity_msat, _)) = first_hop_targets.get(&$node_id) {
803 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);
807 let features = if let Some(node_info) = $node.announcement_info.as_ref() {
813 if !features.requires_unknown_bits() {
814 for chan_id in $node.channels.iter() {
815 let chan = network.get_channels().get(chan_id).unwrap();
816 if !chan.features.requires_unknown_bits() {
817 if chan.node_one == *$node_id {
818 // ie $node is one, ie next hop in A* is two, via the two_to_one channel
819 if first_hops.is_none() || chan.node_two != *our_node_id {
820 if let Some(two_to_one) = chan.two_to_one.as_ref() {
821 if two_to_one.enabled {
822 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);
827 if first_hops.is_none() || chan.node_one != *our_node_id {
828 if let Some(one_to_two) = chan.one_to_two.as_ref() {
829 if one_to_two.enabled {
830 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);
842 let mut payment_paths = Vec::<PaymentPath>::new();
844 // TODO: diversify by nodes (so that all paths aren't doomed if one node is offline).
845 'paths_collection: loop {
846 // For every new path, start from scratch, except
847 // bookkeeped_channels_liquidity_available_msat, which will improve
848 // the further iterations of path finding. Also don't erase first_hop_targets.
851 hit_minimum_limit = false;
853 // If first hop is a private channel and the only way to reach the payee, this is the only
854 // place where it could be added.
855 if first_hops.is_some() {
856 if let Some(&(ref first_hop, ref features, ref outbound_capacity_msat, _)) = first_hop_targets.get(&payee) {
857 add_entry!(first_hop, *our_node_id, payee, dummy_directional_info, Some(outbound_capacity_msat / 1000), features, 0, path_value_msat, 0);
861 // Add the payee as a target, so that the payee-to-payer
862 // search algorithm knows what to start with.
863 match network.get_nodes().get(payee) {
864 // The payee is not in our network graph, so nothing to add here.
865 // There is still a chance of reaching them via last_hops though,
866 // so don't yet fail the payment here.
867 // If not, targets.pop() will not even let us enter the loop in step 2.
870 add_entries_to_cheapest_to_target_node!(node, payee, 0, path_value_msat, 0);
875 // If a caller provided us with last hops, add them to routing targets. Since this happens
876 // earlier than general path finding, they will be somewhat prioritized, although currently
877 // it matters only if the fees are exactly the same.
878 for hop in last_hops.iter() {
879 let have_hop_src_in_graph =
880 // Only add the last hop to our candidate set if either we have a direct channel or
881 // they are in the regular network graph.
882 first_hop_targets.get(&hop.src_node_id).is_some() ||
883 network.get_nodes().get(&hop.src_node_id).is_some();
884 if have_hop_src_in_graph {
885 // BOLT 11 doesn't allow inclusion of features for the last hop hints, which
886 // really sucks, cause we're gonna need that eventually.
887 let last_hop_htlc_minimum_msat: u64 = match hop.htlc_minimum_msat {
888 Some(htlc_minimum_msat) => htlc_minimum_msat,
891 let directional_info = DummyDirectionalChannelInfo {
892 cltv_expiry_delta: hop.cltv_expiry_delta as u32,
893 htlc_minimum_msat: last_hop_htlc_minimum_msat,
894 htlc_maximum_msat: hop.htlc_maximum_msat,
897 // We assume that the recipient only included route hints for routes which had
898 // sufficient value to route `final_value_msat`. Note that in the case of "0-value"
899 // invoices where the invoice does not specify value this may not be the case, but
900 // better to include the hints than not.
901 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) {
902 // If this hop connects to a node with which we have a direct channel,
903 // ignore the network graph and, if the last hop was added, add our
904 // direct channel to the candidate set.
906 // Note that we *must* check if the last hop was added as `add_entry`
907 // always assumes that the third argument is a node to which we have a
909 if let Some(&(ref first_hop, ref features, ref outbound_capacity_msat, _)) = first_hop_targets.get(&hop.src_node_id) {
910 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);
916 log_trace!(logger, "Starting main path collection loop with {} nodes pre-filled from first/last hops.", targets.len());
918 // At this point, targets are filled with the data from first and
919 // last hops communicated by the caller, and the payment receiver.
920 let mut found_new_path = false;
923 // If this loop terminates due the exhaustion of targets, two situations are possible:
924 // - not enough outgoing liquidity:
925 // 0 < already_collected_value_msat < final_value_msat
926 // - enough outgoing liquidity:
927 // final_value_msat <= already_collected_value_msat < recommended_value_msat
928 // Both these cases (and other cases except reaching recommended_value_msat) mean that
929 // paths_collection will be stopped because found_new_path==false.
930 // This is not necessarily a routing failure.
931 'path_construction: while let Some(RouteGraphNode { pubkey, lowest_fee_to_node, value_contribution_msat, path_htlc_minimum_msat, .. }) = targets.pop() {
933 // Since we're going payee-to-payer, hitting our node as a target means we should stop
934 // traversing the graph and arrange the path out of what we found.
935 if pubkey == *our_node_id {
936 let mut new_entry = dist.remove(&our_node_id).unwrap();
937 let mut ordered_hops = vec!((new_entry.clone(), NodeFeatures::empty()));
940 if let Some(&(_, _, _, ref features)) = first_hop_targets.get(&ordered_hops.last().unwrap().0.pubkey) {
941 ordered_hops.last_mut().unwrap().1 = features.clone();
942 } else if let Some(node) = network.get_nodes().get(&ordered_hops.last().unwrap().0.pubkey) {
943 if let Some(node_info) = node.announcement_info.as_ref() {
944 ordered_hops.last_mut().unwrap().1 = node_info.features.clone();
946 ordered_hops.last_mut().unwrap().1 = NodeFeatures::empty();
949 // We should be able to fill in features for everything except the last
950 // hop, if the last hop was provided via a BOLT 11 invoice (though we
951 // should be able to extend it further as BOLT 11 does have feature
952 // flags for the last hop node itself).
953 assert!(ordered_hops.last().unwrap().0.pubkey == *payee);
956 // Means we succesfully traversed from the payer to the payee, now
957 // save this path for the payment route. Also, update the liquidity
958 // remaining on the used hops, so that we take them into account
959 // while looking for more paths.
960 if ordered_hops.last().unwrap().0.pubkey == *payee {
964 new_entry = match dist.remove(&ordered_hops.last().unwrap().0.pubkey) {
965 Some(payment_hop) => payment_hop,
966 // We can't arrive at None because, if we ever add an entry to targets,
967 // we also fill in the entry in dist (see add_entry!).
968 None => unreachable!(),
970 // We "propagate" the fees one hop backward (topologically) here,
971 // so that fees paid for a HTLC forwarding on the current channel are
972 // associated with the previous channel (where they will be subtracted).
973 ordered_hops.last_mut().unwrap().0.fee_msat = new_entry.hop_use_fee_msat;
974 ordered_hops.last_mut().unwrap().0.cltv_expiry_delta = new_entry.cltv_expiry_delta;
975 ordered_hops.push((new_entry.clone(), NodeFeatures::empty()));
977 ordered_hops.last_mut().unwrap().0.fee_msat = value_contribution_msat;
978 ordered_hops.last_mut().unwrap().0.hop_use_fee_msat = 0;
979 ordered_hops.last_mut().unwrap().0.cltv_expiry_delta = final_cltv;
981 log_trace!(logger, "Found a path back to us from the target with {} hops contributing up to {} msat: {:?}",
982 ordered_hops.len(), value_contribution_msat, ordered_hops);
984 let mut payment_path = PaymentPath {hops: ordered_hops};
986 // We could have possibly constructed a slightly inconsistent path: since we reduce
987 // value being transferred along the way, we could have violated htlc_minimum_msat
988 // on some channels we already passed (assuming dest->source direction). Here, we
989 // recompute the fees again, so that if that's the case, we match the currently
990 // underpaid htlc_minimum_msat with fees.
991 payment_path.update_value_and_recompute_fees(cmp::min(value_contribution_msat, final_value_msat));
993 // Since a path allows to transfer as much value as
994 // the smallest channel it has ("bottleneck"), we should recompute
995 // the fees so sender HTLC don't overpay fees when traversing
996 // larger channels than the bottleneck. This may happen because
997 // when we were selecting those channels we were not aware how much value
998 // this path will transfer, and the relative fee for them
999 // might have been computed considering a larger value.
1000 // Remember that we used these channels so that we don't rely
1001 // on the same liquidity in future paths.
1002 let mut prevented_redundant_path_selection = false;
1003 for (payment_hop, _) in payment_path.hops.iter() {
1004 let channel_liquidity_available_msat = bookkeeped_channels_liquidity_available_msat.get_mut(&payment_hop.short_channel_id).unwrap();
1005 let mut spent_on_hop_msat = value_contribution_msat;
1006 let next_hops_fee_msat = payment_hop.next_hops_fee_msat;
1007 spent_on_hop_msat += next_hops_fee_msat;
1008 if spent_on_hop_msat == *channel_liquidity_available_msat {
1009 // If this path used all of this channel's available liquidity, we know
1010 // this path will not be selected again in the next loop iteration.
1011 prevented_redundant_path_selection = true;
1013 *channel_liquidity_available_msat -= spent_on_hop_msat;
1015 if !prevented_redundant_path_selection {
1016 // If we weren't capped by hitting a liquidity limit on a channel in the path,
1017 // we'll probably end up picking the same path again on the next iteration.
1018 // Decrease the available liquidity of a hop in the middle of the path.
1019 let victim_scid = payment_path.hops[(payment_path.hops.len() - 1) / 2].0.short_channel_id;
1020 log_trace!(logger, "Disabling channel {} for future path building iterations to avoid duplicates.", victim_scid);
1021 let victim_liquidity = bookkeeped_channels_liquidity_available_msat.get_mut(&victim_scid).unwrap();
1022 *victim_liquidity = 0;
1025 // Track the total amount all our collected paths allow to send so that we:
1026 // - know when to stop looking for more paths
1027 // - know which of the hops are useless considering how much more sats we need
1028 // (contributes_sufficient_value)
1029 already_collected_value_msat += value_contribution_msat;
1031 payment_paths.push(payment_path);
1032 found_new_path = true;
1033 break 'path_construction;
1036 // If we found a path back to the payee, we shouldn't try to process it again. This is
1037 // the equivalent of the `elem.was_processed` check in
1038 // add_entries_to_cheapest_to_target_node!() (see comment there for more info).
1039 if pubkey == *payee { continue 'path_construction; }
1041 // Otherwise, since the current target node is not us,
1042 // keep "unrolling" the payment graph from payee to payer by
1043 // finding a way to reach the current target from the payer side.
1044 match network.get_nodes().get(&pubkey) {
1047 add_entries_to_cheapest_to_target_node!(node, &pubkey, lowest_fee_to_node, value_contribution_msat, path_htlc_minimum_msat);
1053 // If we don't support MPP, no use trying to gather more value ever.
1054 break 'paths_collection;
1058 // Stop either when the recommended value is reached or if no new path was found in this
1060 // In the latter case, making another path finding attempt won't help,
1061 // because we deterministically terminated the search due to low liquidity.
1062 if already_collected_value_msat >= recommended_value_msat || !found_new_path {
1063 log_trace!(logger, "Have now collected {} msat (seeking {} msat) in paths. Last path loop {} a new path.",
1064 already_collected_value_msat, recommended_value_msat, if found_new_path { "found" } else { "did not find" });
1065 break 'paths_collection;
1066 } else if found_new_path && already_collected_value_msat == final_value_msat && payment_paths.len() == 1 {
1067 // Further, if this was our first walk of the graph, and we weren't limited by an
1068 // htlc_minimum_msat, return immediately because this path should suffice. If we were
1069 // limited by an htlc_minimum_msat value, find another path with a higher value,
1070 // potentially allowing us to pay fees to meet the htlc_minimum on the new path while
1071 // still keeping a lower total fee than this path.
1072 if !hit_minimum_limit {
1073 log_trace!(logger, "Collected exactly our payment amount on the first pass, without hitting an htlc_minimum_msat limit, exiting.");
1074 break 'paths_collection;
1076 log_trace!(logger, "Collected our payment amount on the first pass, but running again to collect extra paths with a potentially higher limit.");
1077 path_value_msat = recommended_value_msat;
1082 if payment_paths.len() == 0 {
1083 return Err(LightningError{err: "Failed to find a path to the given destination".to_owned(), action: ErrorAction::IgnoreError});
1086 if already_collected_value_msat < final_value_msat {
1087 return Err(LightningError{err: "Failed to find a sufficient route to the given destination".to_owned(), action: ErrorAction::IgnoreError});
1090 // Sort by total fees and take the best paths.
1091 payment_paths.sort_by_key(|path| path.get_total_fee_paid_msat());
1092 if payment_paths.len() > 50 {
1093 payment_paths.truncate(50);
1096 // Draw multiple sufficient routes by randomly combining the selected paths.
1097 let mut drawn_routes = Vec::new();
1098 for i in 0..payment_paths.len() {
1099 let mut cur_route = Vec::<PaymentPath>::new();
1100 let mut aggregate_route_value_msat = 0;
1103 // TODO: real random shuffle
1104 // Currently just starts with i_th and goes up to i-1_th in a looped way.
1105 let cur_payment_paths = [&payment_paths[i..], &payment_paths[..i]].concat();
1108 for payment_path in cur_payment_paths {
1109 cur_route.push(payment_path.clone());
1110 aggregate_route_value_msat += payment_path.get_value_msat();
1111 if aggregate_route_value_msat > final_value_msat {
1112 // Last path likely overpaid. Substract it from the most expensive
1113 // (in terms of proportional fee) path in this route and recompute fees.
1114 // This might be not the most economically efficient way, but fewer paths
1115 // also makes routing more reliable.
1116 let mut overpaid_value_msat = aggregate_route_value_msat - final_value_msat;
1118 // First, drop some expensive low-value paths entirely if possible.
1119 // Sort by value so that we drop many really-low values first, since
1120 // fewer paths is better: the payment is less likely to fail.
1121 // TODO: this could also be optimized by also sorting by feerate_per_sat_routed,
1122 // so that the sender pays less fees overall. And also htlc_minimum_msat.
1123 cur_route.sort_by_key(|path| path.get_value_msat());
1124 // We should make sure that at least 1 path left.
1125 let mut paths_left = cur_route.len();
1126 cur_route.retain(|path| {
1127 if paths_left == 1 {
1130 let mut keep = true;
1131 let path_value_msat = path.get_value_msat();
1132 if path_value_msat <= overpaid_value_msat {
1134 overpaid_value_msat -= path_value_msat;
1140 if overpaid_value_msat == 0 {
1144 assert!(cur_route.len() > 0);
1147 // Now, substract the overpaid value from the most-expensive path.
1148 // TODO: this could also be optimized by also sorting by feerate_per_sat_routed,
1149 // so that the sender pays less fees overall. And also htlc_minimum_msat.
1150 cur_route.sort_by_key(|path| { path.hops.iter().map(|hop| hop.0.channel_fees.proportional_millionths as u64).sum::<u64>() });
1151 let expensive_payment_path = cur_route.first_mut().unwrap();
1152 // We already dropped all the small channels above, meaning all the
1153 // remaining channels are larger than remaining overpaid_value_msat.
1154 // Thus, this can't be negative.
1155 let expensive_path_new_value_msat = expensive_payment_path.get_value_msat() - overpaid_value_msat;
1156 expensive_payment_path.update_value_and_recompute_fees(expensive_path_new_value_msat);
1160 drawn_routes.push(cur_route);
1164 // Select the best route by lowest total fee.
1165 drawn_routes.sort_by_key(|paths| paths.iter().map(|path| path.get_total_fee_paid_msat()).sum::<u64>());
1166 let mut selected_paths = Vec::<Vec<RouteHop>>::new();
1167 for payment_path in drawn_routes.first().unwrap() {
1168 selected_paths.push(payment_path.hops.iter().map(|(payment_hop, node_features)| {
1170 pubkey: payment_hop.pubkey,
1171 node_features: node_features.clone(),
1172 short_channel_id: payment_hop.short_channel_id,
1173 channel_features: payment_hop.channel_features.clone(),
1174 fee_msat: payment_hop.fee_msat,
1175 cltv_expiry_delta: payment_hop.cltv_expiry_delta,
1180 if let Some(features) = &payee_features {
1181 for path in selected_paths.iter_mut() {
1182 path.last_mut().unwrap().node_features = features.to_context();
1186 let route = Route { paths: selected_paths };
1187 log_info!(logger, "Got route to {}: {}", payee, log_route!(route));
1193 use routing::router::{get_route, Route, RouteHint, RouteHintHop, RoutingFees};
1194 use routing::network_graph::{NetworkGraph, NetGraphMsgHandler};
1195 use chain::transaction::OutPoint;
1196 use ln::features::{ChannelFeatures, InitFeatures, InvoiceFeatures, NodeFeatures};
1197 use ln::msgs::{ErrorAction, LightningError, OptionalField, UnsignedChannelAnnouncement, ChannelAnnouncement, RoutingMessageHandler,
1198 NodeAnnouncement, UnsignedNodeAnnouncement, ChannelUpdate, UnsignedChannelUpdate};
1199 use ln::channelmanager;
1200 use util::test_utils;
1201 use util::ser::Writeable;
1203 use bitcoin::hashes::sha256d::Hash as Sha256dHash;
1204 use bitcoin::hashes::Hash;
1205 use bitcoin::network::constants::Network;
1206 use bitcoin::blockdata::constants::genesis_block;
1207 use bitcoin::blockdata::script::Builder;
1208 use bitcoin::blockdata::opcodes;
1209 use bitcoin::blockdata::transaction::TxOut;
1213 use bitcoin::secp256k1::key::{PublicKey,SecretKey};
1214 use bitcoin::secp256k1::{Secp256k1, All};
1217 use sync::{self, Arc};
1219 fn get_channel_details(short_channel_id: Option<u64>, node_id: PublicKey,
1220 features: InitFeatures, outbound_capacity_msat: u64) -> channelmanager::ChannelDetails {
1221 channelmanager::ChannelDetails {
1222 channel_id: [0; 32],
1223 counterparty: channelmanager::ChannelCounterparty {
1226 unspendable_punishment_reserve: 0,
1227 forwarding_info: None,
1229 funding_txo: Some(OutPoint { txid: bitcoin::Txid::from_slice(&[0; 32]).unwrap(), index: 0 }),
1231 channel_value_satoshis: 0,
1233 outbound_capacity_msat,
1234 inbound_capacity_msat: 42,
1235 unspendable_punishment_reserve: None,
1236 confirmations_required: None,
1237 force_close_spend_delay: None,
1238 is_outbound: true, is_funding_locked: true,
1239 is_usable: true, is_public: true,
1243 // Using the same keys for LN and BTC ids
1244 fn add_channel(net_graph_msg_handler: &NetGraphMsgHandler<Arc<test_utils::TestChainSource>, Arc<test_utils::TestLogger>>, secp_ctx: &Secp256k1<All>, node_1_privkey: &SecretKey,
1245 node_2_privkey: &SecretKey, features: ChannelFeatures, short_channel_id: u64) {
1246 let node_id_1 = PublicKey::from_secret_key(&secp_ctx, node_1_privkey);
1247 let node_id_2 = PublicKey::from_secret_key(&secp_ctx, node_2_privkey);
1249 let unsigned_announcement = UnsignedChannelAnnouncement {
1251 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1255 bitcoin_key_1: node_id_1,
1256 bitcoin_key_2: node_id_2,
1257 excess_data: Vec::new(),
1260 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1261 let valid_announcement = ChannelAnnouncement {
1262 node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
1263 node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
1264 bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
1265 bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
1266 contents: unsigned_announcement.clone(),
1268 match net_graph_msg_handler.handle_channel_announcement(&valid_announcement) {
1269 Ok(res) => assert!(res),
1274 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) {
1275 let msghash = hash_to_message!(&Sha256dHash::hash(&update.encode()[..])[..]);
1276 let valid_channel_update = ChannelUpdate {
1277 signature: secp_ctx.sign(&msghash, node_privkey),
1278 contents: update.clone()
1281 match net_graph_msg_handler.handle_channel_update(&valid_channel_update) {
1282 Ok(res) => assert!(res),
1287 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,
1288 features: NodeFeatures, timestamp: u32) {
1289 let node_id = PublicKey::from_secret_key(&secp_ctx, node_privkey);
1290 let unsigned_announcement = UnsignedNodeAnnouncement {
1296 addresses: Vec::new(),
1297 excess_address_data: Vec::new(),
1298 excess_data: Vec::new(),
1300 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1301 let valid_announcement = NodeAnnouncement {
1302 signature: secp_ctx.sign(&msghash, node_privkey),
1303 contents: unsigned_announcement.clone()
1306 match net_graph_msg_handler.handle_node_announcement(&valid_announcement) {
1312 fn get_nodes(secp_ctx: &Secp256k1<All>) -> (SecretKey, PublicKey, Vec<SecretKey>, Vec<PublicKey>) {
1313 let privkeys: Vec<SecretKey> = (2..10).map(|i| {
1314 SecretKey::from_slice(&hex::decode(format!("{:02}", i).repeat(32)).unwrap()[..]).unwrap()
1317 let pubkeys = privkeys.iter().map(|secret| PublicKey::from_secret_key(&secp_ctx, secret)).collect();
1319 let our_privkey = SecretKey::from_slice(&hex::decode("01".repeat(32)).unwrap()[..]).unwrap();
1320 let our_id = PublicKey::from_secret_key(&secp_ctx, &our_privkey);
1322 (our_privkey, our_id, privkeys, pubkeys)
1325 fn id_to_feature_flags(id: u8) -> Vec<u8> {
1326 // Set the feature flags to the id'th odd (ie non-required) feature bit so that we can
1327 // test for it later.
1328 let idx = (id - 1) * 2 + 1;
1330 vec![1 << (idx - 8*3), 0, 0, 0]
1331 } else if idx > 8*2 {
1332 vec![1 << (idx - 8*2), 0, 0]
1333 } else if idx > 8*1 {
1334 vec![1 << (idx - 8*1), 0]
1340 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>) {
1341 let secp_ctx = Secp256k1::new();
1342 let logger = Arc::new(test_utils::TestLogger::new());
1343 let chain_monitor = Arc::new(test_utils::TestChainSource::new(Network::Testnet));
1344 let net_graph_msg_handler = NetGraphMsgHandler::new(genesis_block(Network::Testnet).header.block_hash(), None, Arc::clone(&logger));
1345 // Build network from our_id to node7:
1347 // -1(1)2- node0 -1(3)2-
1349 // our_id -1(12)2- node7 -1(13)2--- node2
1351 // -1(2)2- node1 -1(4)2-
1354 // chan1 1-to-2: disabled
1355 // chan1 2-to-1: enabled, 0 fee
1357 // chan2 1-to-2: enabled, ignored fee
1358 // chan2 2-to-1: enabled, 0 fee
1360 // chan3 1-to-2: enabled, 0 fee
1361 // chan3 2-to-1: enabled, 100 msat fee
1363 // chan4 1-to-2: enabled, 100% fee
1364 // chan4 2-to-1: enabled, 0 fee
1366 // chan12 1-to-2: enabled, ignored fee
1367 // chan12 2-to-1: enabled, 0 fee
1369 // chan13 1-to-2: enabled, 200% fee
1370 // chan13 2-to-1: enabled, 0 fee
1373 // -1(5)2- node3 -1(8)2--
1377 // node2--1(6)2- node4 -1(9)2--- node6 (not in global route map)
1379 // -1(7)2- node5 -1(10)2-
1381 // chan5 1-to-2: enabled, 100 msat fee
1382 // chan5 2-to-1: enabled, 0 fee
1384 // chan6 1-to-2: enabled, 0 fee
1385 // chan6 2-to-1: enabled, 0 fee
1387 // chan7 1-to-2: enabled, 100% fee
1388 // chan7 2-to-1: enabled, 0 fee
1390 // chan8 1-to-2: enabled, variable fee (0 then 1000 msat)
1391 // chan8 2-to-1: enabled, 0 fee
1393 // chan9 1-to-2: enabled, 1001 msat fee
1394 // chan9 2-to-1: enabled, 0 fee
1396 // chan10 1-to-2: enabled, 0 fee
1397 // chan10 2-to-1: enabled, 0 fee
1399 // chan11 1-to-2: enabled, 0 fee
1400 // chan11 2-to-1: enabled, 0 fee
1402 let (our_privkey, _, privkeys, _) = get_nodes(&secp_ctx);
1404 add_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, &privkeys[0], ChannelFeatures::from_le_bytes(id_to_feature_flags(1)), 1);
1405 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
1406 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1407 short_channel_id: 1,
1410 cltv_expiry_delta: 0,
1411 htlc_minimum_msat: 0,
1412 htlc_maximum_msat: OptionalField::Absent,
1414 fee_proportional_millionths: 0,
1415 excess_data: Vec::new()
1418 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[0], NodeFeatures::from_le_bytes(id_to_feature_flags(1)), 0);
1420 add_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, &privkeys[1], ChannelFeatures::from_le_bytes(id_to_feature_flags(2)), 2);
1421 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
1422 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1423 short_channel_id: 2,
1426 cltv_expiry_delta: u16::max_value(),
1427 htlc_minimum_msat: 0,
1428 htlc_maximum_msat: OptionalField::Absent,
1429 fee_base_msat: u32::max_value(),
1430 fee_proportional_millionths: u32::max_value(),
1431 excess_data: Vec::new()
1433 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
1434 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1435 short_channel_id: 2,
1438 cltv_expiry_delta: 0,
1439 htlc_minimum_msat: 0,
1440 htlc_maximum_msat: OptionalField::Absent,
1442 fee_proportional_millionths: 0,
1443 excess_data: Vec::new()
1446 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[1], NodeFeatures::from_le_bytes(id_to_feature_flags(2)), 0);
1448 add_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, &privkeys[7], ChannelFeatures::from_le_bytes(id_to_feature_flags(12)), 12);
1449 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
1450 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1451 short_channel_id: 12,
1454 cltv_expiry_delta: u16::max_value(),
1455 htlc_minimum_msat: 0,
1456 htlc_maximum_msat: OptionalField::Absent,
1457 fee_base_msat: u32::max_value(),
1458 fee_proportional_millionths: u32::max_value(),
1459 excess_data: Vec::new()
1461 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
1462 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1463 short_channel_id: 12,
1466 cltv_expiry_delta: 0,
1467 htlc_minimum_msat: 0,
1468 htlc_maximum_msat: OptionalField::Absent,
1470 fee_proportional_millionths: 0,
1471 excess_data: Vec::new()
1474 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[7], NodeFeatures::from_le_bytes(id_to_feature_flags(8)), 0);
1476 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], &privkeys[2], ChannelFeatures::from_le_bytes(id_to_feature_flags(3)), 3);
1477 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
1478 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1479 short_channel_id: 3,
1482 cltv_expiry_delta: (3 << 8) | 1,
1483 htlc_minimum_msat: 0,
1484 htlc_maximum_msat: OptionalField::Absent,
1486 fee_proportional_millionths: 0,
1487 excess_data: Vec::new()
1489 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
1490 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1491 short_channel_id: 3,
1494 cltv_expiry_delta: (3 << 8) | 2,
1495 htlc_minimum_msat: 0,
1496 htlc_maximum_msat: OptionalField::Absent,
1498 fee_proportional_millionths: 0,
1499 excess_data: Vec::new()
1502 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], &privkeys[2], ChannelFeatures::from_le_bytes(id_to_feature_flags(4)), 4);
1503 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
1504 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1505 short_channel_id: 4,
1508 cltv_expiry_delta: (4 << 8) | 1,
1509 htlc_minimum_msat: 0,
1510 htlc_maximum_msat: OptionalField::Absent,
1512 fee_proportional_millionths: 1000000,
1513 excess_data: Vec::new()
1515 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
1516 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1517 short_channel_id: 4,
1520 cltv_expiry_delta: (4 << 8) | 2,
1521 htlc_minimum_msat: 0,
1522 htlc_maximum_msat: OptionalField::Absent,
1524 fee_proportional_millionths: 0,
1525 excess_data: Vec::new()
1528 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], &privkeys[2], ChannelFeatures::from_le_bytes(id_to_feature_flags(13)), 13);
1529 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
1530 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1531 short_channel_id: 13,
1534 cltv_expiry_delta: (13 << 8) | 1,
1535 htlc_minimum_msat: 0,
1536 htlc_maximum_msat: OptionalField::Absent,
1538 fee_proportional_millionths: 2000000,
1539 excess_data: Vec::new()
1541 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
1542 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1543 short_channel_id: 13,
1546 cltv_expiry_delta: (13 << 8) | 2,
1547 htlc_minimum_msat: 0,
1548 htlc_maximum_msat: OptionalField::Absent,
1550 fee_proportional_millionths: 0,
1551 excess_data: Vec::new()
1554 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[2], NodeFeatures::from_le_bytes(id_to_feature_flags(3)), 0);
1556 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], &privkeys[4], ChannelFeatures::from_le_bytes(id_to_feature_flags(6)), 6);
1557 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
1558 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1559 short_channel_id: 6,
1562 cltv_expiry_delta: (6 << 8) | 1,
1563 htlc_minimum_msat: 0,
1564 htlc_maximum_msat: OptionalField::Absent,
1566 fee_proportional_millionths: 0,
1567 excess_data: Vec::new()
1569 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
1570 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1571 short_channel_id: 6,
1574 cltv_expiry_delta: (6 << 8) | 2,
1575 htlc_minimum_msat: 0,
1576 htlc_maximum_msat: OptionalField::Absent,
1578 fee_proportional_millionths: 0,
1579 excess_data: Vec::new(),
1582 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(11)), 11);
1583 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
1584 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1585 short_channel_id: 11,
1588 cltv_expiry_delta: (11 << 8) | 1,
1589 htlc_minimum_msat: 0,
1590 htlc_maximum_msat: OptionalField::Absent,
1592 fee_proportional_millionths: 0,
1593 excess_data: Vec::new()
1595 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[3], UnsignedChannelUpdate {
1596 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1597 short_channel_id: 11,
1600 cltv_expiry_delta: (11 << 8) | 2,
1601 htlc_minimum_msat: 0,
1602 htlc_maximum_msat: OptionalField::Absent,
1604 fee_proportional_millionths: 0,
1605 excess_data: Vec::new()
1608 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[4], NodeFeatures::from_le_bytes(id_to_feature_flags(5)), 0);
1610 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[3], NodeFeatures::from_le_bytes(id_to_feature_flags(4)), 0);
1612 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], &privkeys[5], ChannelFeatures::from_le_bytes(id_to_feature_flags(7)), 7);
1613 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
1614 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1615 short_channel_id: 7,
1618 cltv_expiry_delta: (7 << 8) | 1,
1619 htlc_minimum_msat: 0,
1620 htlc_maximum_msat: OptionalField::Absent,
1622 fee_proportional_millionths: 1000000,
1623 excess_data: Vec::new()
1625 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[5], UnsignedChannelUpdate {
1626 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1627 short_channel_id: 7,
1630 cltv_expiry_delta: (7 << 8) | 2,
1631 htlc_minimum_msat: 0,
1632 htlc_maximum_msat: OptionalField::Absent,
1634 fee_proportional_millionths: 0,
1635 excess_data: Vec::new()
1638 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[5], NodeFeatures::from_le_bytes(id_to_feature_flags(6)), 0);
1640 (secp_ctx, net_graph_msg_handler, chain_monitor, logger)
1644 fn simple_route_test() {
1645 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
1646 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
1648 // Simple route to 2 via 1
1650 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)) {
1651 assert_eq!(err, "Cannot send a payment of 0 msat");
1652 } else { panic!(); }
1654 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();
1655 assert_eq!(route.paths[0].len(), 2);
1657 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
1658 assert_eq!(route.paths[0][0].short_channel_id, 2);
1659 assert_eq!(route.paths[0][0].fee_msat, 100);
1660 assert_eq!(route.paths[0][0].cltv_expiry_delta, (4 << 8) | 1);
1661 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
1662 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
1664 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
1665 assert_eq!(route.paths[0][1].short_channel_id, 4);
1666 assert_eq!(route.paths[0][1].fee_msat, 100);
1667 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
1668 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
1669 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
1673 fn invalid_first_hop_test() {
1674 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
1675 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
1677 // Simple route to 2 via 1
1679 let our_chans = vec![get_channel_details(Some(2), our_id, InitFeatures::from_le_bytes(vec![0b11]), 100000)];
1681 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)) {
1682 assert_eq!(err, "First hop cannot have our_node_id as a destination.");
1683 } else { panic!(); }
1685 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();
1686 assert_eq!(route.paths[0].len(), 2);
1690 fn htlc_minimum_test() {
1691 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
1692 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
1694 // Simple route to 2 via 1
1696 // Disable other paths
1697 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
1698 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1699 short_channel_id: 12,
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[0], UnsignedChannelUpdate {
1710 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1711 short_channel_id: 3,
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[7], UnsignedChannelUpdate {
1722 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1723 short_channel_id: 13,
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: 6,
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()
1745 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
1746 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1747 short_channel_id: 7,
1749 flags: 2, // to disable
1750 cltv_expiry_delta: 0,
1751 htlc_minimum_msat: 0,
1752 htlc_maximum_msat: OptionalField::Absent,
1754 fee_proportional_millionths: 0,
1755 excess_data: Vec::new()
1758 // Check against amount_to_transfer_over_msat.
1759 // Set minimal HTLC of 200_000_000 msat.
1760 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
1761 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1762 short_channel_id: 2,
1765 cltv_expiry_delta: 0,
1766 htlc_minimum_msat: 200_000_000,
1767 htlc_maximum_msat: OptionalField::Absent,
1769 fee_proportional_millionths: 0,
1770 excess_data: Vec::new()
1773 // Second hop only allows to forward 199_999_999 at most, thus not allowing the first hop to
1775 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
1776 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1777 short_channel_id: 4,
1780 cltv_expiry_delta: 0,
1781 htlc_minimum_msat: 0,
1782 htlc_maximum_msat: OptionalField::Present(199_999_999),
1784 fee_proportional_millionths: 0,
1785 excess_data: Vec::new()
1788 // Not possible to send 199_999_999, because the minimum on channel=2 is 200_000_000.
1789 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)) {
1790 assert_eq!(err, "Failed to find a path to the given destination");
1791 } else { panic!(); }
1793 // Lift the restriction on the first hop.
1794 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
1795 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1796 short_channel_id: 2,
1799 cltv_expiry_delta: 0,
1800 htlc_minimum_msat: 0,
1801 htlc_maximum_msat: OptionalField::Absent,
1803 fee_proportional_millionths: 0,
1804 excess_data: Vec::new()
1807 // A payment above the minimum should pass
1808 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();
1809 assert_eq!(route.paths[0].len(), 2);
1813 fn htlc_minimum_overpay_test() {
1814 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
1815 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
1817 // A route to node#2 via two paths.
1818 // One path allows transferring 35-40 sats, another one also allows 35-40 sats.
1819 // Thus, they can't send 60 without overpaying.
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: 2,
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()
1832 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
1833 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1834 short_channel_id: 12,
1837 cltv_expiry_delta: 0,
1838 htlc_minimum_msat: 35_000,
1839 htlc_maximum_msat: OptionalField::Present(40_000),
1841 fee_proportional_millionths: 0,
1842 excess_data: Vec::new()
1846 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
1847 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1848 short_channel_id: 13,
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()
1858 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
1859 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1860 short_channel_id: 4,
1863 cltv_expiry_delta: 0,
1864 htlc_minimum_msat: 0,
1865 htlc_maximum_msat: OptionalField::Absent,
1867 fee_proportional_millionths: 0,
1868 excess_data: Vec::new()
1871 // Disable other paths
1872 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
1873 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1874 short_channel_id: 1,
1876 flags: 2, // to disable
1877 cltv_expiry_delta: 0,
1878 htlc_minimum_msat: 0,
1879 htlc_maximum_msat: OptionalField::Absent,
1881 fee_proportional_millionths: 0,
1882 excess_data: Vec::new()
1885 let route = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2],
1886 Some(InvoiceFeatures::known()), None, &Vec::new(), 60_000, 42, Arc::clone(&logger)).unwrap();
1887 // Overpay fees to hit htlc_minimum_msat.
1888 let overpaid_fees = route.paths[0][0].fee_msat + route.paths[1][0].fee_msat;
1889 // TODO: this could be better balanced to overpay 10k and not 15k.
1890 assert_eq!(overpaid_fees, 15_000);
1892 // Now, test that if there are 2 paths, a "cheaper" by fee path wouldn't be prioritized
1893 // while taking even more fee to match htlc_minimum_msat.
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: 12,
1899 cltv_expiry_delta: 0,
1900 htlc_minimum_msat: 65_000,
1901 htlc_maximum_msat: OptionalField::Present(80_000),
1903 fee_proportional_millionths: 0,
1904 excess_data: Vec::new()
1906 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
1907 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1908 short_channel_id: 2,
1911 cltv_expiry_delta: 0,
1912 htlc_minimum_msat: 0,
1913 htlc_maximum_msat: OptionalField::Absent,
1915 fee_proportional_millionths: 0,
1916 excess_data: Vec::new()
1918 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
1919 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1920 short_channel_id: 4,
1923 cltv_expiry_delta: 0,
1924 htlc_minimum_msat: 0,
1925 htlc_maximum_msat: OptionalField::Absent,
1927 fee_proportional_millionths: 100_000,
1928 excess_data: Vec::new()
1931 let route = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2],
1932 Some(InvoiceFeatures::known()), None, &Vec::new(), 60_000, 42, Arc::clone(&logger)).unwrap();
1933 // Fine to overpay for htlc_minimum_msat if it allows us to save fee.
1934 assert_eq!(route.paths.len(), 1);
1935 assert_eq!(route.paths[0][0].short_channel_id, 12);
1936 let fees = route.paths[0][0].fee_msat;
1937 assert_eq!(fees, 5_000);
1939 let route = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2],
1940 Some(InvoiceFeatures::known()), None, &Vec::new(), 50_000, 42, Arc::clone(&logger)).unwrap();
1941 // Not fine to overpay for htlc_minimum_msat if it requires paying more than fee on
1942 // the other channel.
1943 assert_eq!(route.paths.len(), 1);
1944 assert_eq!(route.paths[0][0].short_channel_id, 2);
1945 let fees = route.paths[0][0].fee_msat;
1946 assert_eq!(fees, 5_000);
1950 fn disable_channels_test() {
1951 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
1952 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
1954 // // Disable channels 4 and 12 by flags=2
1955 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
1956 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1957 short_channel_id: 4,
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()
1967 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
1968 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1969 short_channel_id: 12,
1971 flags: 2, // to disable
1972 cltv_expiry_delta: 0,
1973 htlc_minimum_msat: 0,
1974 htlc_maximum_msat: OptionalField::Absent,
1976 fee_proportional_millionths: 0,
1977 excess_data: Vec::new()
1980 // If all the channels require some features we don't understand, route should fail
1981 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)) {
1982 assert_eq!(err, "Failed to find a path to the given destination");
1983 } else { panic!(); }
1985 // If we specify a channel to node7, that overrides our local channel view and that gets used
1986 let our_chans = vec![get_channel_details(Some(42), nodes[7].clone(), InitFeatures::from_le_bytes(vec![0b11]), 250_000_000)];
1987 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();
1988 assert_eq!(route.paths[0].len(), 2);
1990 assert_eq!(route.paths[0][0].pubkey, nodes[7]);
1991 assert_eq!(route.paths[0][0].short_channel_id, 42);
1992 assert_eq!(route.paths[0][0].fee_msat, 200);
1993 assert_eq!(route.paths[0][0].cltv_expiry_delta, (13 << 8) | 1);
1994 assert_eq!(route.paths[0][0].node_features.le_flags(), &vec![0b11]); // it should also override our view of their features
1995 assert_eq!(route.paths[0][0].channel_features.le_flags(), &Vec::<u8>::new()); // No feature flags will meet the relevant-to-channel conversion
1997 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
1998 assert_eq!(route.paths[0][1].short_channel_id, 13);
1999 assert_eq!(route.paths[0][1].fee_msat, 100);
2000 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
2001 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2002 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(13));
2006 fn disable_node_test() {
2007 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
2008 let (_, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
2010 // Disable nodes 1, 2, and 8 by requiring unknown feature bits
2011 let unknown_features = NodeFeatures::known().set_unknown_feature_required();
2012 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[0], unknown_features.clone(), 1);
2013 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[1], unknown_features.clone(), 1);
2014 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[7], unknown_features.clone(), 1);
2016 // If all nodes require some features we don't understand, route should fail
2017 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)) {
2018 assert_eq!(err, "Failed to find a path to the given destination");
2019 } else { panic!(); }
2021 // If we specify a channel to node7, that overrides our local channel view and that gets used
2022 let our_chans = vec![get_channel_details(Some(42), nodes[7].clone(), InitFeatures::from_le_bytes(vec![0b11]), 250_000_000)];
2023 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();
2024 assert_eq!(route.paths[0].len(), 2);
2026 assert_eq!(route.paths[0][0].pubkey, nodes[7]);
2027 assert_eq!(route.paths[0][0].short_channel_id, 42);
2028 assert_eq!(route.paths[0][0].fee_msat, 200);
2029 assert_eq!(route.paths[0][0].cltv_expiry_delta, (13 << 8) | 1);
2030 assert_eq!(route.paths[0][0].node_features.le_flags(), &vec![0b11]); // it should also override our view of their features
2031 assert_eq!(route.paths[0][0].channel_features.le_flags(), &Vec::<u8>::new()); // No feature flags will meet the relevant-to-channel conversion
2033 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2034 assert_eq!(route.paths[0][1].short_channel_id, 13);
2035 assert_eq!(route.paths[0][1].fee_msat, 100);
2036 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
2037 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2038 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(13));
2040 // Note that we don't test disabling node 3 and failing to route to it, as we (somewhat
2041 // naively) assume that the user checked the feature bits on the invoice, which override
2042 // the node_announcement.
2046 fn our_chans_test() {
2047 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
2048 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
2050 // Route to 1 via 2 and 3 because our channel to 1 is disabled
2051 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();
2052 assert_eq!(route.paths[0].len(), 3);
2054 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
2055 assert_eq!(route.paths[0][0].short_channel_id, 2);
2056 assert_eq!(route.paths[0][0].fee_msat, 200);
2057 assert_eq!(route.paths[0][0].cltv_expiry_delta, (4 << 8) | 1);
2058 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
2059 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
2061 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2062 assert_eq!(route.paths[0][1].short_channel_id, 4);
2063 assert_eq!(route.paths[0][1].fee_msat, 100);
2064 assert_eq!(route.paths[0][1].cltv_expiry_delta, (3 << 8) | 2);
2065 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2066 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
2068 assert_eq!(route.paths[0][2].pubkey, nodes[0]);
2069 assert_eq!(route.paths[0][2].short_channel_id, 3);
2070 assert_eq!(route.paths[0][2].fee_msat, 100);
2071 assert_eq!(route.paths[0][2].cltv_expiry_delta, 42);
2072 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(1));
2073 assert_eq!(route.paths[0][2].channel_features.le_flags(), &id_to_feature_flags(3));
2075 // If we specify a channel to node7, that overrides our local channel view and that gets used
2076 let our_chans = vec![get_channel_details(Some(42), nodes[7].clone(), InitFeatures::from_le_bytes(vec![0b11]), 250_000_000)];
2077 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();
2078 assert_eq!(route.paths[0].len(), 2);
2080 assert_eq!(route.paths[0][0].pubkey, nodes[7]);
2081 assert_eq!(route.paths[0][0].short_channel_id, 42);
2082 assert_eq!(route.paths[0][0].fee_msat, 200);
2083 assert_eq!(route.paths[0][0].cltv_expiry_delta, (13 << 8) | 1);
2084 assert_eq!(route.paths[0][0].node_features.le_flags(), &vec![0b11]);
2085 assert_eq!(route.paths[0][0].channel_features.le_flags(), &Vec::<u8>::new()); // No feature flags will meet the relevant-to-channel conversion
2087 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2088 assert_eq!(route.paths[0][1].short_channel_id, 13);
2089 assert_eq!(route.paths[0][1].fee_msat, 100);
2090 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
2091 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2092 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(13));
2095 fn last_hops(nodes: &Vec<PublicKey>) -> Vec<RouteHint> {
2096 let zero_fees = RoutingFees {
2098 proportional_millionths: 0,
2100 vec![RouteHint(vec![RouteHintHop {
2101 src_node_id: nodes[3].clone(),
2102 short_channel_id: 8,
2104 cltv_expiry_delta: (8 << 8) | 1,
2105 htlc_minimum_msat: None,
2106 htlc_maximum_msat: None,
2107 }]), RouteHint(vec![RouteHintHop {
2108 src_node_id: nodes[4].clone(),
2109 short_channel_id: 9,
2112 proportional_millionths: 0,
2114 cltv_expiry_delta: (9 << 8) | 1,
2115 htlc_minimum_msat: None,
2116 htlc_maximum_msat: None,
2117 }]), RouteHint(vec![RouteHintHop {
2118 src_node_id: nodes[5].clone(),
2119 short_channel_id: 10,
2121 cltv_expiry_delta: (10 << 8) | 1,
2122 htlc_minimum_msat: None,
2123 htlc_maximum_msat: None,
2128 fn last_hops_test() {
2129 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
2130 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
2132 // Simple test across 2, 3, 5, and 4 via a last_hop channel
2134 // First check that last hop can't have its source as the payee.
2135 let invalid_last_hop = RouteHint(vec![RouteHintHop {
2136 src_node_id: nodes[6],
2137 short_channel_id: 8,
2140 proportional_millionths: 0,
2142 cltv_expiry_delta: (8 << 8) | 1,
2143 htlc_minimum_msat: None,
2144 htlc_maximum_msat: None,
2147 let mut invalid_last_hops = last_hops(&nodes);
2148 invalid_last_hops.push(invalid_last_hop);
2150 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)) {
2151 assert_eq!(err, "Last hop cannot have a payee as a source.");
2152 } else { panic!(); }
2155 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();
2156 assert_eq!(route.paths[0].len(), 5);
2158 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
2159 assert_eq!(route.paths[0][0].short_channel_id, 2);
2160 assert_eq!(route.paths[0][0].fee_msat, 100);
2161 assert_eq!(route.paths[0][0].cltv_expiry_delta, (4 << 8) | 1);
2162 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
2163 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
2165 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2166 assert_eq!(route.paths[0][1].short_channel_id, 4);
2167 assert_eq!(route.paths[0][1].fee_msat, 0);
2168 assert_eq!(route.paths[0][1].cltv_expiry_delta, (6 << 8) | 1);
2169 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2170 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
2172 assert_eq!(route.paths[0][2].pubkey, nodes[4]);
2173 assert_eq!(route.paths[0][2].short_channel_id, 6);
2174 assert_eq!(route.paths[0][2].fee_msat, 0);
2175 assert_eq!(route.paths[0][2].cltv_expiry_delta, (11 << 8) | 1);
2176 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(5));
2177 assert_eq!(route.paths[0][2].channel_features.le_flags(), &id_to_feature_flags(6));
2179 assert_eq!(route.paths[0][3].pubkey, nodes[3]);
2180 assert_eq!(route.paths[0][3].short_channel_id, 11);
2181 assert_eq!(route.paths[0][3].fee_msat, 0);
2182 assert_eq!(route.paths[0][3].cltv_expiry_delta, (8 << 8) | 1);
2183 // If we have a peer in the node map, we'll use their features here since we don't have
2184 // a way of figuring out their features from the invoice:
2185 assert_eq!(route.paths[0][3].node_features.le_flags(), &id_to_feature_flags(4));
2186 assert_eq!(route.paths[0][3].channel_features.le_flags(), &id_to_feature_flags(11));
2188 assert_eq!(route.paths[0][4].pubkey, nodes[6]);
2189 assert_eq!(route.paths[0][4].short_channel_id, 8);
2190 assert_eq!(route.paths[0][4].fee_msat, 100);
2191 assert_eq!(route.paths[0][4].cltv_expiry_delta, 42);
2192 assert_eq!(route.paths[0][4].node_features.le_flags(), &Vec::<u8>::new()); // We dont pass flags in from invoices yet
2193 assert_eq!(route.paths[0][4].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
2197 fn our_chans_last_hop_connect_test() {
2198 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
2199 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
2201 // Simple test with outbound channel to 4 to test that last_hops and first_hops connect
2202 let our_chans = vec![get_channel_details(Some(42), nodes[3].clone(), InitFeatures::from_le_bytes(vec![0b11]), 250_000_000)];
2203 let mut last_hops = last_hops(&nodes);
2204 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();
2205 assert_eq!(route.paths[0].len(), 2);
2207 assert_eq!(route.paths[0][0].pubkey, nodes[3]);
2208 assert_eq!(route.paths[0][0].short_channel_id, 42);
2209 assert_eq!(route.paths[0][0].fee_msat, 0);
2210 assert_eq!(route.paths[0][0].cltv_expiry_delta, (8 << 8) | 1);
2211 assert_eq!(route.paths[0][0].node_features.le_flags(), &vec![0b11]);
2212 assert_eq!(route.paths[0][0].channel_features.le_flags(), &Vec::<u8>::new()); // No feature flags will meet the relevant-to-channel conversion
2214 assert_eq!(route.paths[0][1].pubkey, nodes[6]);
2215 assert_eq!(route.paths[0][1].short_channel_id, 8);
2216 assert_eq!(route.paths[0][1].fee_msat, 100);
2217 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
2218 assert_eq!(route.paths[0][1].node_features.le_flags(), &Vec::<u8>::new()); // We dont pass flags in from invoices yet
2219 assert_eq!(route.paths[0][1].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
2221 last_hops[0].0[0].fees.base_msat = 1000;
2223 // Revert to via 6 as the fee on 8 goes up
2224 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();
2225 assert_eq!(route.paths[0].len(), 4);
2227 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
2228 assert_eq!(route.paths[0][0].short_channel_id, 2);
2229 assert_eq!(route.paths[0][0].fee_msat, 200); // fee increased as its % of value transferred across node
2230 assert_eq!(route.paths[0][0].cltv_expiry_delta, (4 << 8) | 1);
2231 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
2232 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
2234 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2235 assert_eq!(route.paths[0][1].short_channel_id, 4);
2236 assert_eq!(route.paths[0][1].fee_msat, 100);
2237 assert_eq!(route.paths[0][1].cltv_expiry_delta, (7 << 8) | 1);
2238 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2239 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
2241 assert_eq!(route.paths[0][2].pubkey, nodes[5]);
2242 assert_eq!(route.paths[0][2].short_channel_id, 7);
2243 assert_eq!(route.paths[0][2].fee_msat, 0);
2244 assert_eq!(route.paths[0][2].cltv_expiry_delta, (10 << 8) | 1);
2245 // If we have a peer in the node map, we'll use their features here since we don't have
2246 // a way of figuring out their features from the invoice:
2247 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(6));
2248 assert_eq!(route.paths[0][2].channel_features.le_flags(), &id_to_feature_flags(7));
2250 assert_eq!(route.paths[0][3].pubkey, nodes[6]);
2251 assert_eq!(route.paths[0][3].short_channel_id, 10);
2252 assert_eq!(route.paths[0][3].fee_msat, 100);
2253 assert_eq!(route.paths[0][3].cltv_expiry_delta, 42);
2254 assert_eq!(route.paths[0][3].node_features.le_flags(), &Vec::<u8>::new()); // We dont pass flags in from invoices yet
2255 assert_eq!(route.paths[0][3].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
2257 // ...but still use 8 for larger payments as 6 has a variable feerate
2258 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();
2259 assert_eq!(route.paths[0].len(), 5);
2261 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
2262 assert_eq!(route.paths[0][0].short_channel_id, 2);
2263 assert_eq!(route.paths[0][0].fee_msat, 3000);
2264 assert_eq!(route.paths[0][0].cltv_expiry_delta, (4 << 8) | 1);
2265 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
2266 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
2268 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2269 assert_eq!(route.paths[0][1].short_channel_id, 4);
2270 assert_eq!(route.paths[0][1].fee_msat, 0);
2271 assert_eq!(route.paths[0][1].cltv_expiry_delta, (6 << 8) | 1);
2272 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2273 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
2275 assert_eq!(route.paths[0][2].pubkey, nodes[4]);
2276 assert_eq!(route.paths[0][2].short_channel_id, 6);
2277 assert_eq!(route.paths[0][2].fee_msat, 0);
2278 assert_eq!(route.paths[0][2].cltv_expiry_delta, (11 << 8) | 1);
2279 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(5));
2280 assert_eq!(route.paths[0][2].channel_features.le_flags(), &id_to_feature_flags(6));
2282 assert_eq!(route.paths[0][3].pubkey, nodes[3]);
2283 assert_eq!(route.paths[0][3].short_channel_id, 11);
2284 assert_eq!(route.paths[0][3].fee_msat, 1000);
2285 assert_eq!(route.paths[0][3].cltv_expiry_delta, (8 << 8) | 1);
2286 // If we have a peer in the node map, we'll use their features here since we don't have
2287 // a way of figuring out their features from the invoice:
2288 assert_eq!(route.paths[0][3].node_features.le_flags(), &id_to_feature_flags(4));
2289 assert_eq!(route.paths[0][3].channel_features.le_flags(), &id_to_feature_flags(11));
2291 assert_eq!(route.paths[0][4].pubkey, nodes[6]);
2292 assert_eq!(route.paths[0][4].short_channel_id, 8);
2293 assert_eq!(route.paths[0][4].fee_msat, 2000);
2294 assert_eq!(route.paths[0][4].cltv_expiry_delta, 42);
2295 assert_eq!(route.paths[0][4].node_features.le_flags(), &Vec::<u8>::new()); // We dont pass flags in from invoices yet
2296 assert_eq!(route.paths[0][4].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
2299 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> {
2300 let source_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&hex::decode(format!("{:02}", 41).repeat(32)).unwrap()[..]).unwrap());
2301 let middle_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&hex::decode(format!("{:02}", 42).repeat(32)).unwrap()[..]).unwrap());
2302 let target_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&hex::decode(format!("{:02}", 43).repeat(32)).unwrap()[..]).unwrap());
2304 // If we specify a channel to a middle hop, that overrides our local channel view and that gets used
2305 let last_hops = RouteHint(vec![RouteHintHop {
2306 src_node_id: middle_node_id,
2307 short_channel_id: 8,
2310 proportional_millionths: last_hop_fee_prop,
2312 cltv_expiry_delta: (8 << 8) | 1,
2313 htlc_minimum_msat: None,
2314 htlc_maximum_msat: last_hop_htlc_max,
2316 let our_chans = vec![get_channel_details(Some(42), middle_node_id, InitFeatures::from_le_bytes(vec![0b11]), outbound_capacity_msat)];
2317 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()))
2321 fn unannounced_path_test() {
2322 // We should be able to send a payment to a destination without any help of a routing graph
2323 // if we have a channel with a common counterparty that appears in the first and last hop
2325 let route = do_unannounced_path_test(None, 1, 2000000, 1000000).unwrap();
2327 let middle_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&hex::decode(format!("{:02}", 42).repeat(32)).unwrap()[..]).unwrap());
2328 let target_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&hex::decode(format!("{:02}", 43).repeat(32)).unwrap()[..]).unwrap());
2329 assert_eq!(route.paths[0].len(), 2);
2331 assert_eq!(route.paths[0][0].pubkey, middle_node_id);
2332 assert_eq!(route.paths[0][0].short_channel_id, 42);
2333 assert_eq!(route.paths[0][0].fee_msat, 1001);
2334 assert_eq!(route.paths[0][0].cltv_expiry_delta, (8 << 8) | 1);
2335 assert_eq!(route.paths[0][0].node_features.le_flags(), &[0b11]);
2336 assert_eq!(route.paths[0][0].channel_features.le_flags(), &[0; 0]); // We can't learn any flags from invoices, sadly
2338 assert_eq!(route.paths[0][1].pubkey, target_node_id);
2339 assert_eq!(route.paths[0][1].short_channel_id, 8);
2340 assert_eq!(route.paths[0][1].fee_msat, 1000000);
2341 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
2342 assert_eq!(route.paths[0][1].node_features.le_flags(), &[0; 0]); // We dont pass flags in from invoices yet
2343 assert_eq!(route.paths[0][1].channel_features.le_flags(), &[0; 0]); // We can't learn any flags from invoices, sadly
2347 fn overflow_unannounced_path_test_liquidity_underflow() {
2348 // Previously, when we had a last-hop hint connected directly to a first-hop channel, where
2349 // the last-hop had a fee which overflowed a u64, we'd panic.
2350 // This was due to us adding the first-hop from us unconditionally, causing us to think
2351 // we'd built a path (as our node is in the "best candidate" set), when we had not.
2352 // In this test, we previously hit a subtraction underflow due to having less available
2353 // liquidity at the last hop than 0.
2354 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());
2358 fn overflow_unannounced_path_test_feerate_overflow() {
2359 // This tests for the same case as above, except instead of hitting a subtraction
2360 // underflow, we hit a case where the fee charged at a hop overflowed.
2361 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());
2365 fn available_amount_while_routing_test() {
2366 // Tests whether we choose the correct available channel amount while routing.
2368 let (secp_ctx, mut net_graph_msg_handler, chain_monitor, logger) = build_graph();
2369 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
2371 // We will use a simple single-path route from
2372 // our node to node2 via node0: channels {1, 3}.
2374 // First disable all other paths.
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: 2,
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()
2387 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2388 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2389 short_channel_id: 12,
2392 cltv_expiry_delta: 0,
2393 htlc_minimum_msat: 0,
2394 htlc_maximum_msat: OptionalField::Present(100_000),
2396 fee_proportional_millionths: 0,
2397 excess_data: Vec::new()
2400 // Make the first channel (#1) very permissive,
2401 // and we will be testing all limits on the second channel.
2402 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2403 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2404 short_channel_id: 1,
2407 cltv_expiry_delta: 0,
2408 htlc_minimum_msat: 0,
2409 htlc_maximum_msat: OptionalField::Present(1_000_000_000),
2411 fee_proportional_millionths: 0,
2412 excess_data: Vec::new()
2415 // First, let's see if routing works if we have absolutely no idea about the available amount.
2416 // In this case, it should be set to 250_000 sats.
2417 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
2418 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2419 short_channel_id: 3,
2422 cltv_expiry_delta: 0,
2423 htlc_minimum_msat: 0,
2424 htlc_maximum_msat: OptionalField::Absent,
2426 fee_proportional_millionths: 0,
2427 excess_data: Vec::new()
2431 // Attempt to route more than available results in a failure.
2432 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2],
2433 Some(InvoiceFeatures::known()), None, &Vec::new(), 250_000_001, 42, Arc::clone(&logger)) {
2434 assert_eq!(err, "Failed to find a sufficient route to the given destination");
2435 } else { panic!(); }
2439 // Now, attempt to route an exact amount we have should be fine.
2440 let route = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2],
2441 Some(InvoiceFeatures::known()), None, &Vec::new(), 250_000_000, 42, Arc::clone(&logger)).unwrap();
2442 assert_eq!(route.paths.len(), 1);
2443 let path = route.paths.last().unwrap();
2444 assert_eq!(path.len(), 2);
2445 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
2446 assert_eq!(path.last().unwrap().fee_msat, 250_000_000);
2449 // Check that setting outbound_capacity_msat in first_hops limits the channels.
2450 // Disable channel #1 and use another first hop.
2451 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2452 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2453 short_channel_id: 1,
2456 cltv_expiry_delta: 0,
2457 htlc_minimum_msat: 0,
2458 htlc_maximum_msat: OptionalField::Present(1_000_000_000),
2460 fee_proportional_millionths: 0,
2461 excess_data: Vec::new()
2464 // Now, limit the first_hop by the outbound_capacity_msat of 200_000 sats.
2465 let our_chans = vec![get_channel_details(Some(42), nodes[0].clone(), InitFeatures::from_le_bytes(vec![0b11]), 200_000_000)];
2468 // Attempt to route more than available results in a failure.
2469 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2],
2470 Some(InvoiceFeatures::known()), Some(&our_chans.iter().collect::<Vec<_>>()), &Vec::new(), 200_000_001, 42, Arc::clone(&logger)) {
2471 assert_eq!(err, "Failed to find a sufficient route to the given destination");
2472 } else { panic!(); }
2476 // Now, attempt to route an exact amount we have should be fine.
2477 let route = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2],
2478 Some(InvoiceFeatures::known()), Some(&our_chans.iter().collect::<Vec<_>>()), &Vec::new(), 200_000_000, 42, Arc::clone(&logger)).unwrap();
2479 assert_eq!(route.paths.len(), 1);
2480 let path = route.paths.last().unwrap();
2481 assert_eq!(path.len(), 2);
2482 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
2483 assert_eq!(path.last().unwrap().fee_msat, 200_000_000);
2486 // Enable channel #1 back.
2487 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2488 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2489 short_channel_id: 1,
2492 cltv_expiry_delta: 0,
2493 htlc_minimum_msat: 0,
2494 htlc_maximum_msat: OptionalField::Present(1_000_000_000),
2496 fee_proportional_millionths: 0,
2497 excess_data: Vec::new()
2501 // Now let's see if routing works if we know only htlc_maximum_msat.
2502 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
2503 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2504 short_channel_id: 3,
2507 cltv_expiry_delta: 0,
2508 htlc_minimum_msat: 0,
2509 htlc_maximum_msat: OptionalField::Present(15_000),
2511 fee_proportional_millionths: 0,
2512 excess_data: Vec::new()
2516 // Attempt to route more than available results in a failure.
2517 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2],
2518 Some(InvoiceFeatures::known()), None, &Vec::new(), 15_001, 42, Arc::clone(&logger)) {
2519 assert_eq!(err, "Failed to find a sufficient route to the given destination");
2520 } else { panic!(); }
2524 // Now, attempt to route an exact amount we have should be fine.
2525 let route = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2],
2526 Some(InvoiceFeatures::known()), None, &Vec::new(), 15_000, 42, Arc::clone(&logger)).unwrap();
2527 assert_eq!(route.paths.len(), 1);
2528 let path = route.paths.last().unwrap();
2529 assert_eq!(path.len(), 2);
2530 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
2531 assert_eq!(path.last().unwrap().fee_msat, 15_000);
2534 // Now let's see if routing works if we know only capacity from the UTXO.
2536 // We can't change UTXO capacity on the fly, so we'll disable
2537 // the existing channel and add another one with the capacity we need.
2538 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
2539 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2540 short_channel_id: 3,
2543 cltv_expiry_delta: 0,
2544 htlc_minimum_msat: 0,
2545 htlc_maximum_msat: OptionalField::Absent,
2547 fee_proportional_millionths: 0,
2548 excess_data: Vec::new()
2551 let good_script = Builder::new().push_opcode(opcodes::all::OP_PUSHNUM_2)
2552 .push_slice(&PublicKey::from_secret_key(&secp_ctx, &privkeys[0]).serialize())
2553 .push_slice(&PublicKey::from_secret_key(&secp_ctx, &privkeys[2]).serialize())
2554 .push_opcode(opcodes::all::OP_PUSHNUM_2)
2555 .push_opcode(opcodes::all::OP_CHECKMULTISIG).into_script().to_v0_p2wsh();
2557 *chain_monitor.utxo_ret.lock().unwrap() = Ok(TxOut { value: 15, script_pubkey: good_script.clone() });
2558 net_graph_msg_handler.add_chain_access(Some(chain_monitor));
2560 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], &privkeys[2], ChannelFeatures::from_le_bytes(id_to_feature_flags(3)), 333);
2561 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
2562 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2563 short_channel_id: 333,
2566 cltv_expiry_delta: (3 << 8) | 1,
2567 htlc_minimum_msat: 0,
2568 htlc_maximum_msat: OptionalField::Absent,
2570 fee_proportional_millionths: 0,
2571 excess_data: Vec::new()
2573 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
2574 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2575 short_channel_id: 333,
2578 cltv_expiry_delta: (3 << 8) | 2,
2579 htlc_minimum_msat: 0,
2580 htlc_maximum_msat: OptionalField::Absent,
2582 fee_proportional_millionths: 0,
2583 excess_data: Vec::new()
2587 // Attempt to route more than available results in a failure.
2588 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2],
2589 Some(InvoiceFeatures::known()), None, &Vec::new(), 15_001, 42, Arc::clone(&logger)) {
2590 assert_eq!(err, "Failed to find a sufficient route to the given destination");
2591 } else { panic!(); }
2595 // Now, attempt to route an exact amount we have should be fine.
2596 let route = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2],
2597 Some(InvoiceFeatures::known()), None, &Vec::new(), 15_000, 42, Arc::clone(&logger)).unwrap();
2598 assert_eq!(route.paths.len(), 1);
2599 let path = route.paths.last().unwrap();
2600 assert_eq!(path.len(), 2);
2601 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
2602 assert_eq!(path.last().unwrap().fee_msat, 15_000);
2605 // Now let's see if routing chooses htlc_maximum_msat over UTXO capacity.
2606 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
2607 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2608 short_channel_id: 333,
2611 cltv_expiry_delta: 0,
2612 htlc_minimum_msat: 0,
2613 htlc_maximum_msat: OptionalField::Present(10_000),
2615 fee_proportional_millionths: 0,
2616 excess_data: Vec::new()
2620 // Attempt to route more than available results in a failure.
2621 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2],
2622 Some(InvoiceFeatures::known()), None, &Vec::new(), 10_001, 42, Arc::clone(&logger)) {
2623 assert_eq!(err, "Failed to find a sufficient route to the given destination");
2624 } else { panic!(); }
2628 // Now, attempt to route an exact amount we have should be fine.
2629 let route = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2],
2630 Some(InvoiceFeatures::known()), None, &Vec::new(), 10_000, 42, Arc::clone(&logger)).unwrap();
2631 assert_eq!(route.paths.len(), 1);
2632 let path = route.paths.last().unwrap();
2633 assert_eq!(path.len(), 2);
2634 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
2635 assert_eq!(path.last().unwrap().fee_msat, 10_000);
2640 fn available_liquidity_last_hop_test() {
2641 // Check that available liquidity properly limits the path even when only
2642 // one of the latter hops is limited.
2643 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
2644 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
2646 // Path via {node7, node2, node4} is channels {12, 13, 6, 11}.
2647 // {12, 13, 11} have the capacities of 100, {6} has a capacity of 50.
2648 // Total capacity: 50 sats.
2650 // Disable other potential paths.
2651 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2652 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2653 short_channel_id: 2,
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()
2663 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
2664 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2665 short_channel_id: 7,
2668 cltv_expiry_delta: 0,
2669 htlc_minimum_msat: 0,
2670 htlc_maximum_msat: OptionalField::Present(100_000),
2672 fee_proportional_millionths: 0,
2673 excess_data: Vec::new()
2678 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2679 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2680 short_channel_id: 12,
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()
2690 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
2691 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2692 short_channel_id: 13,
2695 cltv_expiry_delta: 0,
2696 htlc_minimum_msat: 0,
2697 htlc_maximum_msat: OptionalField::Present(100_000),
2699 fee_proportional_millionths: 0,
2700 excess_data: Vec::new()
2703 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
2704 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2705 short_channel_id: 6,
2708 cltv_expiry_delta: 0,
2709 htlc_minimum_msat: 0,
2710 htlc_maximum_msat: OptionalField::Present(50_000),
2712 fee_proportional_millionths: 0,
2713 excess_data: Vec::new()
2715 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
2716 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2717 short_channel_id: 11,
2720 cltv_expiry_delta: 0,
2721 htlc_minimum_msat: 0,
2722 htlc_maximum_msat: OptionalField::Present(100_000),
2724 fee_proportional_millionths: 0,
2725 excess_data: Vec::new()
2728 // Attempt to route more than available results in a failure.
2729 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[3],
2730 Some(InvoiceFeatures::known()), None, &Vec::new(), 60_000, 42, Arc::clone(&logger)) {
2731 assert_eq!(err, "Failed to find a sufficient route to the given destination");
2732 } else { panic!(); }
2736 // Now, attempt to route 49 sats (just a bit below the capacity).
2737 let route = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[3],
2738 Some(InvoiceFeatures::known()), None, &Vec::new(), 49_000, 42, Arc::clone(&logger)).unwrap();
2739 assert_eq!(route.paths.len(), 1);
2740 let mut total_amount_paid_msat = 0;
2741 for path in &route.paths {
2742 assert_eq!(path.len(), 4);
2743 assert_eq!(path.last().unwrap().pubkey, nodes[3]);
2744 total_amount_paid_msat += path.last().unwrap().fee_msat;
2746 assert_eq!(total_amount_paid_msat, 49_000);
2750 // Attempt to route an exact amount is also fine
2751 let route = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[3],
2752 Some(InvoiceFeatures::known()), None, &Vec::new(), 50_000, 42, Arc::clone(&logger)).unwrap();
2753 assert_eq!(route.paths.len(), 1);
2754 let mut total_amount_paid_msat = 0;
2755 for path in &route.paths {
2756 assert_eq!(path.len(), 4);
2757 assert_eq!(path.last().unwrap().pubkey, nodes[3]);
2758 total_amount_paid_msat += path.last().unwrap().fee_msat;
2760 assert_eq!(total_amount_paid_msat, 50_000);
2765 fn ignore_fee_first_hop_test() {
2766 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
2767 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
2769 // Path via node0 is channels {1, 3}. Limit them to 100 and 50 sats (total limit 50).
2770 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2771 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2772 short_channel_id: 1,
2775 cltv_expiry_delta: 0,
2776 htlc_minimum_msat: 0,
2777 htlc_maximum_msat: OptionalField::Present(100_000),
2778 fee_base_msat: 1_000_000,
2779 fee_proportional_millionths: 0,
2780 excess_data: Vec::new()
2782 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
2783 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2784 short_channel_id: 3,
2787 cltv_expiry_delta: 0,
2788 htlc_minimum_msat: 0,
2789 htlc_maximum_msat: OptionalField::Present(50_000),
2791 fee_proportional_millionths: 0,
2792 excess_data: Vec::new()
2796 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();
2797 assert_eq!(route.paths.len(), 1);
2798 let mut total_amount_paid_msat = 0;
2799 for path in &route.paths {
2800 assert_eq!(path.len(), 2);
2801 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
2802 total_amount_paid_msat += path.last().unwrap().fee_msat;
2804 assert_eq!(total_amount_paid_msat, 50_000);
2809 fn simple_mpp_route_test() {
2810 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
2811 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
2813 // We need a route consisting of 3 paths:
2814 // From our node to node2 via node0, node7, node1 (three paths one hop each).
2815 // To achieve this, the amount being transferred should be around
2816 // the total capacity of these 3 paths.
2818 // First, we set limits on these (previously unlimited) channels.
2819 // Their aggregate capacity will be 50 + 60 + 180 = 290 sats.
2821 // Path via node0 is channels {1, 3}. Limit them to 100 and 50 sats (total limit 50).
2822 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2823 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2824 short_channel_id: 1,
2827 cltv_expiry_delta: 0,
2828 htlc_minimum_msat: 0,
2829 htlc_maximum_msat: OptionalField::Present(100_000),
2831 fee_proportional_millionths: 0,
2832 excess_data: Vec::new()
2834 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
2835 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2836 short_channel_id: 3,
2839 cltv_expiry_delta: 0,
2840 htlc_minimum_msat: 0,
2841 htlc_maximum_msat: OptionalField::Present(50_000),
2843 fee_proportional_millionths: 0,
2844 excess_data: Vec::new()
2847 // Path via node7 is channels {12, 13}. Limit them to 60 and 60 sats
2848 // (total limit 60).
2849 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2850 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2851 short_channel_id: 12,
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()
2861 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
2862 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2863 short_channel_id: 13,
2866 cltv_expiry_delta: 0,
2867 htlc_minimum_msat: 0,
2868 htlc_maximum_msat: OptionalField::Present(60_000),
2870 fee_proportional_millionths: 0,
2871 excess_data: Vec::new()
2874 // Path via node1 is channels {2, 4}. Limit them to 200 and 180 sats
2875 // (total capacity 180 sats).
2876 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2877 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2878 short_channel_id: 2,
2881 cltv_expiry_delta: 0,
2882 htlc_minimum_msat: 0,
2883 htlc_maximum_msat: OptionalField::Present(200_000),
2885 fee_proportional_millionths: 0,
2886 excess_data: Vec::new()
2888 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
2889 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2890 short_channel_id: 4,
2893 cltv_expiry_delta: 0,
2894 htlc_minimum_msat: 0,
2895 htlc_maximum_msat: OptionalField::Present(180_000),
2897 fee_proportional_millionths: 0,
2898 excess_data: Vec::new()
2902 // Attempt to route more than available results in a failure.
2903 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(),
2904 &nodes[2], Some(InvoiceFeatures::known()), None, &Vec::new(), 300_000, 42, Arc::clone(&logger)) {
2905 assert_eq!(err, "Failed to find a sufficient route to the given destination");
2906 } else { panic!(); }
2910 // Now, attempt to route 250 sats (just a bit below the capacity).
2911 // Our algorithm should provide us with these 3 paths.
2912 let route = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2],
2913 Some(InvoiceFeatures::known()), None, &Vec::new(), 250_000, 42, Arc::clone(&logger)).unwrap();
2914 assert_eq!(route.paths.len(), 3);
2915 let mut total_amount_paid_msat = 0;
2916 for path in &route.paths {
2917 assert_eq!(path.len(), 2);
2918 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
2919 total_amount_paid_msat += path.last().unwrap().fee_msat;
2921 assert_eq!(total_amount_paid_msat, 250_000);
2925 // Attempt to route an exact amount is also fine
2926 let route = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2],
2927 Some(InvoiceFeatures::known()), None, &Vec::new(), 290_000, 42, Arc::clone(&logger)).unwrap();
2928 assert_eq!(route.paths.len(), 3);
2929 let mut total_amount_paid_msat = 0;
2930 for path in &route.paths {
2931 assert_eq!(path.len(), 2);
2932 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
2933 total_amount_paid_msat += path.last().unwrap().fee_msat;
2935 assert_eq!(total_amount_paid_msat, 290_000);
2940 fn long_mpp_route_test() {
2941 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
2942 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
2944 // We need a route consisting of 3 paths:
2945 // From our node to node3 via {node0, node2}, {node7, node2, node4} and {node7, node2}.
2946 // Note that these paths overlap (channels 5, 12, 13).
2947 // We will route 300 sats.
2948 // Each path will have 100 sats capacity, those channels which
2949 // are used twice will have 200 sats capacity.
2951 // Disable other potential paths.
2952 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2953 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2954 short_channel_id: 2,
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()
2964 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
2965 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2966 short_channel_id: 7,
2969 cltv_expiry_delta: 0,
2970 htlc_minimum_msat: 0,
2971 htlc_maximum_msat: OptionalField::Present(100_000),
2973 fee_proportional_millionths: 0,
2974 excess_data: Vec::new()
2977 // Path via {node0, node2} is channels {1, 3, 5}.
2978 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2979 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2980 short_channel_id: 1,
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()
2990 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
2991 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2992 short_channel_id: 3,
2995 cltv_expiry_delta: 0,
2996 htlc_minimum_msat: 0,
2997 htlc_maximum_msat: OptionalField::Present(100_000),
2999 fee_proportional_millionths: 0,
3000 excess_data: Vec::new()
3003 // Capacity of 200 sats because this channel will be used by 3rd path as well.
3004 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(5)), 5);
3005 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3006 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3007 short_channel_id: 5,
3010 cltv_expiry_delta: 0,
3011 htlc_minimum_msat: 0,
3012 htlc_maximum_msat: OptionalField::Present(200_000),
3014 fee_proportional_millionths: 0,
3015 excess_data: Vec::new()
3018 // Path via {node7, node2, node4} is channels {12, 13, 6, 11}.
3019 // Add 100 sats to the capacities of {12, 13}, because these channels
3020 // are also used for 3rd path. 100 sats for the rest. Total capacity: 100 sats.
3021 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3022 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3023 short_channel_id: 12,
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()
3033 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
3034 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3035 short_channel_id: 13,
3038 cltv_expiry_delta: 0,
3039 htlc_minimum_msat: 0,
3040 htlc_maximum_msat: OptionalField::Present(200_000),
3042 fee_proportional_millionths: 0,
3043 excess_data: Vec::new()
3046 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3047 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3048 short_channel_id: 6,
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()
3058 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
3059 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3060 short_channel_id: 11,
3063 cltv_expiry_delta: 0,
3064 htlc_minimum_msat: 0,
3065 htlc_maximum_msat: OptionalField::Present(100_000),
3067 fee_proportional_millionths: 0,
3068 excess_data: Vec::new()
3071 // Path via {node7, node2} is channels {12, 13, 5}.
3072 // We already limited them to 200 sats (they are used twice for 100 sats).
3073 // Nothing to do here.
3076 // Attempt to route more than available results in a failure.
3077 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[3],
3078 Some(InvoiceFeatures::known()), None, &Vec::new(), 350_000, 42, Arc::clone(&logger)) {
3079 assert_eq!(err, "Failed to find a sufficient route to the given destination");
3080 } else { panic!(); }
3084 // Now, attempt to route 300 sats (exact amount we can route).
3085 // Our algorithm should provide us with these 3 paths, 100 sats each.
3086 let route = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[3],
3087 Some(InvoiceFeatures::known()), None, &Vec::new(), 300_000, 42, Arc::clone(&logger)).unwrap();
3088 assert_eq!(route.paths.len(), 3);
3090 let mut total_amount_paid_msat = 0;
3091 for path in &route.paths {
3092 assert_eq!(path.last().unwrap().pubkey, nodes[3]);
3093 total_amount_paid_msat += path.last().unwrap().fee_msat;
3095 assert_eq!(total_amount_paid_msat, 300_000);
3101 fn mpp_cheaper_route_test() {
3102 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
3103 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3105 // This test checks that if we have two cheaper paths and one more expensive path,
3106 // so that liquidity-wise any 2 of 3 combination is sufficient,
3107 // two cheaper paths will be taken.
3108 // These paths have equal available liquidity.
3110 // We need a combination of 3 paths:
3111 // From our node to node3 via {node0, node2}, {node7, node2, node4} and {node7, node2}.
3112 // Note that these paths overlap (channels 5, 12, 13).
3113 // Each path will have 100 sats capacity, those channels which
3114 // are used twice will have 200 sats capacity.
3116 // Disable other potential paths.
3117 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3118 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3119 short_channel_id: 2,
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()
3129 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3130 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3131 short_channel_id: 7,
3134 cltv_expiry_delta: 0,
3135 htlc_minimum_msat: 0,
3136 htlc_maximum_msat: OptionalField::Present(100_000),
3138 fee_proportional_millionths: 0,
3139 excess_data: Vec::new()
3142 // Path via {node0, node2} is channels {1, 3, 5}.
3143 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3144 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3145 short_channel_id: 1,
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()
3155 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3156 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3157 short_channel_id: 3,
3160 cltv_expiry_delta: 0,
3161 htlc_minimum_msat: 0,
3162 htlc_maximum_msat: OptionalField::Present(100_000),
3164 fee_proportional_millionths: 0,
3165 excess_data: Vec::new()
3168 // Capacity of 200 sats because this channel will be used by 3rd path as well.
3169 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(5)), 5);
3170 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3171 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3172 short_channel_id: 5,
3175 cltv_expiry_delta: 0,
3176 htlc_minimum_msat: 0,
3177 htlc_maximum_msat: OptionalField::Present(200_000),
3179 fee_proportional_millionths: 0,
3180 excess_data: Vec::new()
3183 // Path via {node7, node2, node4} is channels {12, 13, 6, 11}.
3184 // Add 100 sats to the capacities of {12, 13}, because these channels
3185 // are also used for 3rd path. 100 sats for the rest. Total capacity: 100 sats.
3186 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3187 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3188 short_channel_id: 12,
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()
3198 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
3199 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3200 short_channel_id: 13,
3203 cltv_expiry_delta: 0,
3204 htlc_minimum_msat: 0,
3205 htlc_maximum_msat: OptionalField::Present(200_000),
3207 fee_proportional_millionths: 0,
3208 excess_data: Vec::new()
3211 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3212 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3213 short_channel_id: 6,
3216 cltv_expiry_delta: 0,
3217 htlc_minimum_msat: 0,
3218 htlc_maximum_msat: OptionalField::Present(100_000),
3219 fee_base_msat: 1_000,
3220 fee_proportional_millionths: 0,
3221 excess_data: Vec::new()
3223 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
3224 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3225 short_channel_id: 11,
3228 cltv_expiry_delta: 0,
3229 htlc_minimum_msat: 0,
3230 htlc_maximum_msat: OptionalField::Present(100_000),
3232 fee_proportional_millionths: 0,
3233 excess_data: Vec::new()
3236 // Path via {node7, node2} is channels {12, 13, 5}.
3237 // We already limited them to 200 sats (they are used twice for 100 sats).
3238 // Nothing to do here.
3241 // Now, attempt to route 180 sats.
3242 // Our algorithm should provide us with these 2 paths.
3243 let route = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[3],
3244 Some(InvoiceFeatures::known()), None, &Vec::new(), 180_000, 42, Arc::clone(&logger)).unwrap();
3245 assert_eq!(route.paths.len(), 2);
3247 let mut total_value_transferred_msat = 0;
3248 let mut total_paid_msat = 0;
3249 for path in &route.paths {
3250 assert_eq!(path.last().unwrap().pubkey, nodes[3]);
3251 total_value_transferred_msat += path.last().unwrap().fee_msat;
3253 total_paid_msat += hop.fee_msat;
3256 // If we paid fee, this would be higher.
3257 assert_eq!(total_value_transferred_msat, 180_000);
3258 let total_fees_paid = total_paid_msat - total_value_transferred_msat;
3259 assert_eq!(total_fees_paid, 0);
3264 fn fees_on_mpp_route_test() {
3265 // This test makes sure that MPP algorithm properly takes into account
3266 // fees charged on the channels, by making the fees impactful:
3267 // if the fee is not properly accounted for, the behavior is different.
3268 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
3269 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3271 // We need a route consisting of 2 paths:
3272 // From our node to node3 via {node0, node2} and {node7, node2, node4}.
3273 // We will route 200 sats, Each path will have 100 sats capacity.
3275 // This test is not particularly stable: e.g.,
3276 // there's a way to route via {node0, node2, node4}.
3277 // It works while pathfinding is deterministic, but can be broken otherwise.
3278 // It's fine to ignore this concern for now.
3280 // Disable other potential paths.
3281 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3282 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3283 short_channel_id: 2,
3286 cltv_expiry_delta: 0,
3287 htlc_minimum_msat: 0,
3288 htlc_maximum_msat: OptionalField::Present(100_000),
3290 fee_proportional_millionths: 0,
3291 excess_data: Vec::new()
3294 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3295 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3296 short_channel_id: 7,
3299 cltv_expiry_delta: 0,
3300 htlc_minimum_msat: 0,
3301 htlc_maximum_msat: OptionalField::Present(100_000),
3303 fee_proportional_millionths: 0,
3304 excess_data: Vec::new()
3307 // Path via {node0, node2} is channels {1, 3, 5}.
3308 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3309 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3310 short_channel_id: 1,
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()
3320 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3321 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3322 short_channel_id: 3,
3325 cltv_expiry_delta: 0,
3326 htlc_minimum_msat: 0,
3327 htlc_maximum_msat: OptionalField::Present(100_000),
3329 fee_proportional_millionths: 0,
3330 excess_data: Vec::new()
3333 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(5)), 5);
3334 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3335 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3336 short_channel_id: 5,
3339 cltv_expiry_delta: 0,
3340 htlc_minimum_msat: 0,
3341 htlc_maximum_msat: OptionalField::Present(100_000),
3343 fee_proportional_millionths: 0,
3344 excess_data: Vec::new()
3347 // Path via {node7, node2, node4} is channels {12, 13, 6, 11}.
3348 // All channels should be 100 sats capacity. But for the fee experiment,
3349 // we'll add absolute fee of 150 sats paid for the use channel 6 (paid to node2 on channel 13).
3350 // Since channel 12 allows to deliver only 250 sats to channel 13, channel 13 can transfer only
3351 // 100 sats (and pay 150 sats in fees for the use of channel 6),
3352 // so no matter how large are other channels,
3353 // the whole path will be limited by 100 sats with just these 2 conditions:
3354 // - channel 12 capacity is 250 sats
3355 // - fee for channel 6 is 150 sats
3356 // Let's test this by enforcing these 2 conditions and removing other limits.
3357 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3358 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3359 short_channel_id: 12,
3362 cltv_expiry_delta: 0,
3363 htlc_minimum_msat: 0,
3364 htlc_maximum_msat: OptionalField::Present(250_000),
3366 fee_proportional_millionths: 0,
3367 excess_data: Vec::new()
3369 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
3370 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3371 short_channel_id: 13,
3374 cltv_expiry_delta: 0,
3375 htlc_minimum_msat: 0,
3376 htlc_maximum_msat: OptionalField::Absent,
3378 fee_proportional_millionths: 0,
3379 excess_data: Vec::new()
3382 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3383 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3384 short_channel_id: 6,
3387 cltv_expiry_delta: 0,
3388 htlc_minimum_msat: 0,
3389 htlc_maximum_msat: OptionalField::Absent,
3390 fee_base_msat: 150_000,
3391 fee_proportional_millionths: 0,
3392 excess_data: Vec::new()
3394 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
3395 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3396 short_channel_id: 11,
3399 cltv_expiry_delta: 0,
3400 htlc_minimum_msat: 0,
3401 htlc_maximum_msat: OptionalField::Absent,
3403 fee_proportional_millionths: 0,
3404 excess_data: Vec::new()
3408 // Attempt to route more than available results in a failure.
3409 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[3],
3410 Some(InvoiceFeatures::known()), None, &Vec::new(), 210_000, 42, Arc::clone(&logger)) {
3411 assert_eq!(err, "Failed to find a sufficient route to the given destination");
3412 } else { panic!(); }
3416 // Now, attempt to route 200 sats (exact amount we can route).
3417 let route = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[3],
3418 Some(InvoiceFeatures::known()), None, &Vec::new(), 200_000, 42, Arc::clone(&logger)).unwrap();
3419 assert_eq!(route.paths.len(), 2);
3421 let mut total_amount_paid_msat = 0;
3422 for path in &route.paths {
3423 assert_eq!(path.last().unwrap().pubkey, nodes[3]);
3424 total_amount_paid_msat += path.last().unwrap().fee_msat;
3426 assert_eq!(total_amount_paid_msat, 200_000);
3432 fn drop_lowest_channel_mpp_route_test() {
3433 // This test checks that low-capacity channel is dropped when after
3434 // path finding we realize that we found more capacity than we need.
3435 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
3436 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3438 // We need a route consisting of 3 paths:
3439 // From our node to node2 via node0, node7, node1 (three paths one hop each).
3441 // The first and the second paths should be sufficient, but the third should be
3442 // cheaper, so that we select it but drop later.
3444 // First, we set limits on these (previously unlimited) channels.
3445 // Their aggregate capacity will be 50 + 60 + 20 = 130 sats.
3447 // Path via node0 is channels {1, 3}. Limit them to 100 and 50 sats (total limit 50);
3448 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3449 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3450 short_channel_id: 1,
3453 cltv_expiry_delta: 0,
3454 htlc_minimum_msat: 0,
3455 htlc_maximum_msat: OptionalField::Present(100_000),
3457 fee_proportional_millionths: 0,
3458 excess_data: Vec::new()
3460 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3461 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3462 short_channel_id: 3,
3465 cltv_expiry_delta: 0,
3466 htlc_minimum_msat: 0,
3467 htlc_maximum_msat: OptionalField::Present(50_000),
3469 fee_proportional_millionths: 0,
3470 excess_data: Vec::new()
3473 // Path via node7 is channels {12, 13}. Limit them to 60 and 60 sats (total limit 60);
3474 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3475 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3476 short_channel_id: 12,
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()
3486 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
3487 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3488 short_channel_id: 13,
3491 cltv_expiry_delta: 0,
3492 htlc_minimum_msat: 0,
3493 htlc_maximum_msat: OptionalField::Present(60_000),
3495 fee_proportional_millionths: 0,
3496 excess_data: Vec::new()
3499 // Path via node1 is channels {2, 4}. Limit them to 20 and 20 sats (total capacity 20 sats).
3500 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3501 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3502 short_channel_id: 2,
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()
3512 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
3513 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3514 short_channel_id: 4,
3517 cltv_expiry_delta: 0,
3518 htlc_minimum_msat: 0,
3519 htlc_maximum_msat: OptionalField::Present(20_000),
3521 fee_proportional_millionths: 0,
3522 excess_data: Vec::new()
3526 // Attempt to route more than available results in a failure.
3527 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2],
3528 Some(InvoiceFeatures::known()), None, &Vec::new(), 150_000, 42, Arc::clone(&logger)) {
3529 assert_eq!(err, "Failed to find a sufficient route to the given destination");
3530 } else { panic!(); }
3534 // Now, attempt to route 125 sats (just a bit below the capacity of 3 channels).
3535 // Our algorithm should provide us with these 3 paths.
3536 let route = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2],
3537 Some(InvoiceFeatures::known()), None, &Vec::new(), 125_000, 42, Arc::clone(&logger)).unwrap();
3538 assert_eq!(route.paths.len(), 3);
3539 let mut total_amount_paid_msat = 0;
3540 for path in &route.paths {
3541 assert_eq!(path.len(), 2);
3542 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
3543 total_amount_paid_msat += path.last().unwrap().fee_msat;
3545 assert_eq!(total_amount_paid_msat, 125_000);
3549 // Attempt to route without the last small cheap channel
3550 let route = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2],
3551 Some(InvoiceFeatures::known()), None, &Vec::new(), 90_000, 42, Arc::clone(&logger)).unwrap();
3552 assert_eq!(route.paths.len(), 2);
3553 let mut total_amount_paid_msat = 0;
3554 for path in &route.paths {
3555 assert_eq!(path.len(), 2);
3556 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
3557 total_amount_paid_msat += path.last().unwrap().fee_msat;
3559 assert_eq!(total_amount_paid_msat, 90_000);
3564 fn min_criteria_consistency() {
3565 // Test that we don't use an inconsistent metric between updating and walking nodes during
3566 // our Dijkstra's pass. In the initial version of MPP, the "best source" for a given node
3567 // was updated with a different criterion from the heap sorting, resulting in loops in
3568 // calculated paths. We test for that specific case here.
3570 // We construct a network that looks like this:
3572 // node2 -1(3)2- node3
3576 // node1 -1(5)2- node4 -1(1)2- node6
3582 // We create a loop on the side of our real path - our destination is node 6, with a
3583 // previous hop of node 4. From 4, the cheapest previous path is channel 2 from node 2,
3584 // followed by node 3 over channel 3. Thereafter, the cheapest next-hop is back to node 4
3585 // (this time over channel 4). Channel 4 has 0 htlc_minimum_msat whereas channel 1 (the
3586 // other channel with a previous-hop of node 4) has a high (but irrelevant to the overall
3587 // payment) htlc_minimum_msat. In the original algorithm, this resulted in node4's
3588 // "previous hop" being set to node 3, creating a loop in the path.
3589 let secp_ctx = Secp256k1::new();
3590 let logger = Arc::new(test_utils::TestLogger::new());
3591 let net_graph_msg_handler = NetGraphMsgHandler::new(genesis_block(Network::Testnet).header.block_hash(), None, Arc::clone(&logger));
3592 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3594 add_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, &privkeys[1], ChannelFeatures::from_le_bytes(id_to_feature_flags(6)), 6);
3595 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3596 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3597 short_channel_id: 6,
3600 cltv_expiry_delta: (6 << 8) | 0,
3601 htlc_minimum_msat: 0,
3602 htlc_maximum_msat: OptionalField::Absent,
3604 fee_proportional_millionths: 0,
3605 excess_data: Vec::new()
3607 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[1], NodeFeatures::from_le_bytes(id_to_feature_flags(1)), 0);
3609 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], &privkeys[4], ChannelFeatures::from_le_bytes(id_to_feature_flags(5)), 5);
3610 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
3611 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3612 short_channel_id: 5,
3615 cltv_expiry_delta: (5 << 8) | 0,
3616 htlc_minimum_msat: 0,
3617 htlc_maximum_msat: OptionalField::Absent,
3619 fee_proportional_millionths: 0,
3620 excess_data: Vec::new()
3622 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[4], NodeFeatures::from_le_bytes(id_to_feature_flags(4)), 0);
3624 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(4)), 4);
3625 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
3626 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3627 short_channel_id: 4,
3630 cltv_expiry_delta: (4 << 8) | 0,
3631 htlc_minimum_msat: 0,
3632 htlc_maximum_msat: OptionalField::Absent,
3634 fee_proportional_millionths: 0,
3635 excess_data: Vec::new()
3637 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[3], NodeFeatures::from_le_bytes(id_to_feature_flags(3)), 0);
3639 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[3], &privkeys[2], ChannelFeatures::from_le_bytes(id_to_feature_flags(3)), 3);
3640 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[3], UnsignedChannelUpdate {
3641 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3642 short_channel_id: 3,
3645 cltv_expiry_delta: (3 << 8) | 0,
3646 htlc_minimum_msat: 0,
3647 htlc_maximum_msat: OptionalField::Absent,
3649 fee_proportional_millionths: 0,
3650 excess_data: Vec::new()
3652 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[2], NodeFeatures::from_le_bytes(id_to_feature_flags(2)), 0);
3654 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], &privkeys[4], ChannelFeatures::from_le_bytes(id_to_feature_flags(2)), 2);
3655 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3656 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3657 short_channel_id: 2,
3660 cltv_expiry_delta: (2 << 8) | 0,
3661 htlc_minimum_msat: 0,
3662 htlc_maximum_msat: OptionalField::Absent,
3664 fee_proportional_millionths: 0,
3665 excess_data: Vec::new()
3668 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], &privkeys[6], ChannelFeatures::from_le_bytes(id_to_feature_flags(1)), 1);
3669 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
3670 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3671 short_channel_id: 1,
3674 cltv_expiry_delta: (1 << 8) | 0,
3675 htlc_minimum_msat: 100,
3676 htlc_maximum_msat: OptionalField::Absent,
3678 fee_proportional_millionths: 0,
3679 excess_data: Vec::new()
3681 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[6], NodeFeatures::from_le_bytes(id_to_feature_flags(6)), 0);
3684 // Now ensure the route flows simply over nodes 1 and 4 to 6.
3685 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();
3686 assert_eq!(route.paths.len(), 1);
3687 assert_eq!(route.paths[0].len(), 3);
3689 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
3690 assert_eq!(route.paths[0][0].short_channel_id, 6);
3691 assert_eq!(route.paths[0][0].fee_msat, 100);
3692 assert_eq!(route.paths[0][0].cltv_expiry_delta, (5 << 8) | 0);
3693 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(1));
3694 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(6));
3696 assert_eq!(route.paths[0][1].pubkey, nodes[4]);
3697 assert_eq!(route.paths[0][1].short_channel_id, 5);
3698 assert_eq!(route.paths[0][1].fee_msat, 0);
3699 assert_eq!(route.paths[0][1].cltv_expiry_delta, (1 << 8) | 0);
3700 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(4));
3701 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(5));
3703 assert_eq!(route.paths[0][2].pubkey, nodes[6]);
3704 assert_eq!(route.paths[0][2].short_channel_id, 1);
3705 assert_eq!(route.paths[0][2].fee_msat, 10_000);
3706 assert_eq!(route.paths[0][2].cltv_expiry_delta, 42);
3707 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(6));
3708 assert_eq!(route.paths[0][2].channel_features.le_flags(), &id_to_feature_flags(1));
3714 fn exact_fee_liquidity_limit() {
3715 // Test that if, while walking the graph, we find a hop that has exactly enough liquidity
3716 // for us, including later hop fees, we take it. In the first version of our MPP algorithm
3717 // we calculated fees on a higher value, resulting in us ignoring such paths.
3718 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
3719 let (our_privkey, our_id, _, nodes) = get_nodes(&secp_ctx);
3721 // We modify the graph to set the htlc_maximum of channel 2 to below the value we wish to
3723 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3724 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3725 short_channel_id: 2,
3728 cltv_expiry_delta: 0,
3729 htlc_minimum_msat: 0,
3730 htlc_maximum_msat: OptionalField::Present(85_000),
3732 fee_proportional_millionths: 0,
3733 excess_data: Vec::new()
3736 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3737 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3738 short_channel_id: 12,
3741 cltv_expiry_delta: (4 << 8) | 1,
3742 htlc_minimum_msat: 0,
3743 htlc_maximum_msat: OptionalField::Present(270_000),
3745 fee_proportional_millionths: 1000000,
3746 excess_data: Vec::new()
3750 // Now, attempt to route 90 sats, which is exactly 90 sats at the last hop, plus the
3751 // 200% fee charged channel 13 in the 1-to-2 direction.
3752 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();
3753 assert_eq!(route.paths.len(), 1);
3754 assert_eq!(route.paths[0].len(), 2);
3756 assert_eq!(route.paths[0][0].pubkey, nodes[7]);
3757 assert_eq!(route.paths[0][0].short_channel_id, 12);
3758 assert_eq!(route.paths[0][0].fee_msat, 90_000*2);
3759 assert_eq!(route.paths[0][0].cltv_expiry_delta, (13 << 8) | 1);
3760 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(8));
3761 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(12));
3763 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
3764 assert_eq!(route.paths[0][1].short_channel_id, 13);
3765 assert_eq!(route.paths[0][1].fee_msat, 90_000);
3766 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
3767 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
3768 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(13));
3773 fn htlc_max_reduction_below_min() {
3774 // Test that if, while walking the graph, we reduce the value being sent to meet an
3775 // htlc_maximum_msat, we don't end up undershooting a later htlc_minimum_msat. In the
3776 // initial version of MPP we'd accept such routes but reject them while recalculating fees,
3777 // resulting in us thinking there is no possible path, even if other paths exist.
3778 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
3779 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3781 // We modify the graph to set the htlc_minimum of channel 2 and 4 as needed - channel 2
3782 // gets an htlc_maximum_msat of 80_000 and channel 4 an htlc_minimum_msat of 90_000. We
3783 // then try to send 90_000.
3784 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3785 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3786 short_channel_id: 2,
3789 cltv_expiry_delta: 0,
3790 htlc_minimum_msat: 0,
3791 htlc_maximum_msat: OptionalField::Present(80_000),
3793 fee_proportional_millionths: 0,
3794 excess_data: Vec::new()
3796 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
3797 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3798 short_channel_id: 4,
3801 cltv_expiry_delta: (4 << 8) | 1,
3802 htlc_minimum_msat: 90_000,
3803 htlc_maximum_msat: OptionalField::Absent,
3805 fee_proportional_millionths: 0,
3806 excess_data: Vec::new()
3810 // Now, attempt to route 90 sats, hitting the htlc_minimum on channel 4, but
3811 // overshooting the htlc_maximum on channel 2. Thus, we should pick the (absurdly
3812 // expensive) channels 12-13 path.
3813 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();
3814 assert_eq!(route.paths.len(), 1);
3815 assert_eq!(route.paths[0].len(), 2);
3817 assert_eq!(route.paths[0][0].pubkey, nodes[7]);
3818 assert_eq!(route.paths[0][0].short_channel_id, 12);
3819 assert_eq!(route.paths[0][0].fee_msat, 90_000*2);
3820 assert_eq!(route.paths[0][0].cltv_expiry_delta, (13 << 8) | 1);
3821 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(8));
3822 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(12));
3824 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
3825 assert_eq!(route.paths[0][1].short_channel_id, 13);
3826 assert_eq!(route.paths[0][1].fee_msat, 90_000);
3827 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
3828 assert_eq!(route.paths[0][1].node_features.le_flags(), InvoiceFeatures::known().le_flags());
3829 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(13));
3833 #[cfg(not(feature = "no_std"))]
3834 pub(super) fn random_init_seed() -> u64 {
3835 // Because the default HashMap in std pulls OS randomness, we can use it as a (bad) RNG.
3836 use core::hash::{BuildHasher, Hasher};
3837 let seed = std::collections::hash_map::RandomState::new().build_hasher().finish();
3838 println!("Using seed of {}", seed);
3841 #[cfg(not(feature = "no_std"))]
3842 use util::ser::Readable;
3845 #[cfg(not(feature = "no_std"))]
3846 fn generate_routes() {
3847 let mut d = match super::test_utils::get_route_file() {
3854 let graph = NetworkGraph::read(&mut d).unwrap();
3856 // First, get 100 (source, destination) pairs for which route-getting actually succeeds...
3857 let mut seed = random_init_seed() as usize;
3858 'load_endpoints: for _ in 0..10 {
3860 seed = seed.overflowing_mul(0xdeadbeef).0;
3861 let src = graph.get_nodes().keys().skip(seed % graph.get_nodes().len()).next().unwrap();
3862 seed = seed.overflowing_mul(0xdeadbeef).0;
3863 let dst = graph.get_nodes().keys().skip(seed % graph.get_nodes().len()).next().unwrap();
3864 let amt = seed as u64 % 200_000_000;
3865 if get_route(src, &graph, dst, None, None, &[], amt, 42, &test_utils::TestLogger::new()).is_ok() {
3866 continue 'load_endpoints;
3873 #[cfg(not(feature = "no_std"))]
3874 fn generate_routes_mpp() {
3875 let mut d = match super::test_utils::get_route_file() {
3882 let graph = NetworkGraph::read(&mut d).unwrap();
3884 // First, get 100 (source, destination) pairs for which route-getting actually succeeds...
3885 let mut seed = random_init_seed() as usize;
3886 'load_endpoints: for _ in 0..10 {
3888 seed = seed.overflowing_mul(0xdeadbeef).0;
3889 let src = graph.get_nodes().keys().skip(seed % graph.get_nodes().len()).next().unwrap();
3890 seed = seed.overflowing_mul(0xdeadbeef).0;
3891 let dst = graph.get_nodes().keys().skip(seed % graph.get_nodes().len()).next().unwrap();
3892 let amt = seed as u64 % 200_000_000;
3893 if get_route(src, &graph, dst, Some(InvoiceFeatures::known()), None, &[], amt, 42, &test_utils::TestLogger::new()).is_ok() {
3894 continue 'load_endpoints;
3901 #[cfg(all(test, not(feature = "no_std")))]
3902 pub(crate) mod test_utils {
3904 /// Tries to open a network graph file, or panics with a URL to fetch it.
3905 pub(crate) fn get_route_file() -> Result<std::fs::File, &'static str> {
3906 let res = File::open("net_graph-2021-05-31.bin") // By default we're run in RL/lightning
3907 .or_else(|_| File::open("lightning/net_graph-2021-05-31.bin")) // We may be run manually in RL/
3908 .or_else(|_| { // Fall back to guessing based on the binary location
3909 // path is likely something like .../rust-lightning/target/debug/deps/lightning-...
3910 let mut path = std::env::current_exe().unwrap();
3911 path.pop(); // lightning-...
3913 path.pop(); // debug
3914 path.pop(); // target
3915 path.push("lightning");
3916 path.push("net_graph-2021-05-31.bin");
3917 eprintln!("{}", path.to_str().unwrap());
3920 .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");
3921 #[cfg(require_route_graph_test)]
3922 return Ok(res.unwrap());
3923 #[cfg(not(require_route_graph_test))]
3928 #[cfg(all(test, feature = "unstable", not(feature = "no_std")))]
3931 use util::logger::{Logger, Record};
3935 struct DummyLogger {}
3936 impl Logger for DummyLogger {
3937 fn log(&self, _record: &Record) {}
3941 fn generate_routes(bench: &mut Bencher) {
3942 let mut d = test_utils::get_route_file().unwrap();
3943 let graph = NetworkGraph::read(&mut d).unwrap();
3945 // First, get 100 (source, destination) pairs for which route-getting actually succeeds...
3946 let mut path_endpoints = Vec::new();
3947 let mut seed: usize = 0xdeadbeef;
3948 'load_endpoints: for _ in 0..100 {
3951 let src = graph.get_nodes().keys().skip(seed % graph.get_nodes().len()).next().unwrap();
3953 let dst = graph.get_nodes().keys().skip(seed % graph.get_nodes().len()).next().unwrap();
3954 let amt = seed as u64 % 1_000_000;
3955 if get_route(src, &graph, dst, None, None, &[], amt, 42, &DummyLogger{}).is_ok() {
3956 path_endpoints.push((src, dst, amt));
3957 continue 'load_endpoints;
3962 // ...then benchmark finding paths between the nodes we learned.
3965 let (src, dst, amt) = path_endpoints[idx % path_endpoints.len()];
3966 assert!(get_route(src, &graph, dst, None, None, &[], amt, 42, &DummyLogger{}).is_ok());
3972 fn generate_mpp_routes(bench: &mut Bencher) {
3973 let mut d = test_utils::get_route_file().unwrap();
3974 let graph = NetworkGraph::read(&mut d).unwrap();
3976 // First, get 100 (source, destination) pairs for which route-getting actually succeeds...
3977 let mut path_endpoints = Vec::new();
3978 let mut seed: usize = 0xdeadbeef;
3979 'load_endpoints: for _ in 0..100 {
3982 let src = graph.get_nodes().keys().skip(seed % graph.get_nodes().len()).next().unwrap();
3984 let dst = graph.get_nodes().keys().skip(seed % graph.get_nodes().len()).next().unwrap();
3985 let amt = seed as u64 % 1_000_000;
3986 if get_route(src, &graph, dst, Some(InvoiceFeatures::known()), None, &[], amt, 42, &DummyLogger{}).is_ok() {
3987 path_endpoints.push((src, dst, amt));
3988 continue 'load_endpoints;
3993 // ...then benchmark finding paths between the nodes we learned.
3996 let (src, dst, amt) = path_endpoints[idx % path_endpoints.len()];
3997 assert!(get_route(src, &graph, dst, Some(InvoiceFeatures::known()), None, &[], amt, 42, &DummyLogger{}).is_ok());