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;
26 use alloc::collections::BinaryHeap;
31 #[derive(Clone, Hash, PartialEq, Eq)]
33 /// The node_id of the node at this hop.
34 pub pubkey: PublicKey,
35 /// The node_announcement features of the node at this hop. For the last hop, these may be
36 /// amended to match the features present in the invoice this node generated.
37 pub node_features: NodeFeatures,
38 /// The channel that should be used from the previous hop to reach this node.
39 pub short_channel_id: u64,
40 /// The channel_announcement features of the channel that should be used from the previous hop
41 /// to reach this node.
42 pub channel_features: ChannelFeatures,
43 /// The fee taken on this hop (for paying for the use of the *next* channel in the path).
44 /// For the last hop, this should be the full value of the payment (might be more than
45 /// requested if we had to match htlc_minimum_msat).
47 /// The CLTV delta added for this hop. For the last hop, this should be the full CLTV value
48 /// expected at the destination, in excess of the current block height.
49 pub cltv_expiry_delta: u32,
52 impl_writeable_tlv_based!(RouteHop, {
53 (0, pubkey, required),
54 (2, node_features, required),
55 (4, short_channel_id, required),
56 (6, channel_features, required),
57 (8, fee_msat, required),
58 (10, cltv_expiry_delta, required),
61 /// A route directs a payment from the sender (us) to the recipient. If the recipient supports MPP,
62 /// it can take multiple paths. Each path is composed of one or more hops through the network.
63 #[derive(Clone, Hash, PartialEq, Eq)]
65 /// The list of routes taken for a single (potentially-)multi-part payment. The pubkey of the
66 /// last RouteHop in each path must be the same.
67 /// Each entry represents a list of hops, NOT INCLUDING our own, where the last hop is the
68 /// destination. Thus, this must always be at least length one. While the maximum length of any
69 /// given path is variable, keeping the length of any path to less than 20 should currently
70 /// ensure it is viable.
71 pub paths: Vec<Vec<RouteHop>>,
74 const SERIALIZATION_VERSION: u8 = 1;
75 const MIN_SERIALIZATION_VERSION: u8 = 1;
77 impl Writeable for Route {
78 fn write<W: ::util::ser::Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
79 write_ver_prefix!(writer, SERIALIZATION_VERSION, MIN_SERIALIZATION_VERSION);
80 (self.paths.len() as u64).write(writer)?;
81 for hops in self.paths.iter() {
82 (hops.len() as u8).write(writer)?;
83 for hop in hops.iter() {
87 write_tlv_fields!(writer, {});
92 impl Readable for Route {
93 fn read<R: io::Read>(reader: &mut R) -> Result<Route, DecodeError> {
94 let _ver = read_ver_prefix!(reader, SERIALIZATION_VERSION);
95 let path_count: u64 = Readable::read(reader)?;
96 let mut paths = Vec::with_capacity(cmp::min(path_count, 128) as usize);
97 for _ in 0..path_count {
98 let hop_count: u8 = Readable::read(reader)?;
99 let mut hops = Vec::with_capacity(hop_count as usize);
100 for _ in 0..hop_count {
101 hops.push(Readable::read(reader)?);
105 read_tlv_fields!(reader, {});
110 /// A list of hops along a payment path terminating with a channel to the recipient.
111 #[derive(Clone, Debug, Hash, Eq, PartialEq)]
112 pub struct RouteHint(pub Vec<RouteHintHop>);
114 /// A channel descriptor for a hop along a payment path.
115 #[derive(Clone, Debug, Hash, Eq, PartialEq)]
116 pub struct RouteHintHop {
117 /// The node_id of the non-target end of the route
118 pub src_node_id: PublicKey,
119 /// The short_channel_id of this channel
120 pub short_channel_id: u64,
121 /// The fees which must be paid to use this channel
122 pub fees: RoutingFees,
123 /// The difference in CLTV values between this node and the next node.
124 pub cltv_expiry_delta: u16,
125 /// The minimum value, in msat, which must be relayed to the next hop.
126 pub htlc_minimum_msat: Option<u64>,
127 /// The maximum value in msat available for routing with a single HTLC.
128 pub htlc_maximum_msat: Option<u64>,
131 #[derive(Eq, PartialEq)]
132 struct RouteGraphNode {
134 lowest_fee_to_peer_through_node: u64,
135 lowest_fee_to_node: u64,
136 // The maximum value a yet-to-be-constructed payment path might flow through this node.
137 // This value is upper-bounded by us by:
138 // - how much is needed for a path being constructed
139 // - how much value can channels following this node (up to the destination) can contribute,
140 // considering their capacity and fees
141 value_contribution_msat: u64,
142 /// The effective htlc_minimum_msat at this hop. If a later hop on the path had a higher HTLC
143 /// minimum, we use it, plus the fees required at each earlier hop to meet it.
144 path_htlc_minimum_msat: u64,
147 impl cmp::Ord for RouteGraphNode {
148 fn cmp(&self, other: &RouteGraphNode) -> cmp::Ordering {
149 let other_score = cmp::max(other.lowest_fee_to_peer_through_node, other.path_htlc_minimum_msat);
150 let self_score = cmp::max(self.lowest_fee_to_peer_through_node, self.path_htlc_minimum_msat);
151 other_score.cmp(&self_score).then_with(|| other.pubkey.serialize().cmp(&self.pubkey.serialize()))
155 impl cmp::PartialOrd for RouteGraphNode {
156 fn partial_cmp(&self, other: &RouteGraphNode) -> Option<cmp::Ordering> {
157 Some(self.cmp(other))
161 struct DummyDirectionalChannelInfo {
162 cltv_expiry_delta: u32,
163 htlc_minimum_msat: u64,
164 htlc_maximum_msat: Option<u64>,
168 /// It's useful to keep track of the hops associated with the fees required to use them,
169 /// so that we can choose cheaper paths (as per Dijkstra's algorithm).
170 /// Fee values should be updated only in the context of the whole path, see update_value_and_recompute_fees.
171 /// These fee values are useful to choose hops as we traverse the graph "payee-to-payer".
172 #[derive(Clone, Debug)]
173 struct PathBuildingHop<'a> {
174 // The RouteHintHop fields which will eventually be used if this hop is used in a final Route.
175 // Note that node_features is calculated separately after our initial graph walk.
177 short_channel_id: u64,
178 channel_features: &'a ChannelFeatures,
180 cltv_expiry_delta: u32,
182 /// Minimal fees required to route to the source node of the current hop via any of its inbound channels.
183 src_lowest_inbound_fees: RoutingFees,
184 /// Fees of the channel used in this hop.
185 channel_fees: RoutingFees,
186 /// All the fees paid *after* this channel on the way to the destination
187 next_hops_fee_msat: u64,
188 /// Fee paid for the use of the current channel (see channel_fees).
189 /// The value will be actually deducted from the counterparty balance on the previous link.
190 hop_use_fee_msat: u64,
191 /// Used to compare channels when choosing the for routing.
192 /// Includes paying for the use of a hop and the following hops, as well as
193 /// an estimated cost of reaching this hop.
194 /// Might get stale when fees are recomputed. Primarily for internal use.
196 /// This is useful for update_value_and_recompute_fees to make sure
197 /// we don't fall below the minimum. Should not be updated manually and
198 /// generally should not be accessed.
199 htlc_minimum_msat: u64,
200 /// A mirror of the same field in RouteGraphNode. Note that this is only used during the graph
201 /// walk and may be invalid thereafter.
202 path_htlc_minimum_msat: u64,
203 /// If we've already processed a node as the best node, we shouldn't process it again. Normally
204 /// we'd just ignore it if we did as all channels would have a higher new fee, but because we
205 /// may decrease the amounts in use as we walk the graph, the actual calculated fee may
206 /// decrease as well. Thus, we have to explicitly track which nodes have been processed and
207 /// avoid processing them again.
209 #[cfg(any(test, feature = "fuzztarget"))]
210 // In tests, we apply further sanity checks on cases where we skip nodes we already processed
211 // to ensure it is specifically in cases where the fee has gone down because of a decrease in
212 // value_contribution_msat, which requires tracking it here. See comments below where it is
213 // used for more info.
214 value_contribution_msat: u64,
217 // Instantiated with a list of hops with correct data in them collected during path finding,
218 // an instance of this struct should be further modified only via given methods.
220 struct PaymentPath<'a> {
221 hops: Vec<(PathBuildingHop<'a>, NodeFeatures)>,
224 impl<'a> PaymentPath<'a> {
225 // TODO: Add a value_msat field to PaymentPath and use it instead of this function.
226 fn get_value_msat(&self) -> u64 {
227 self.hops.last().unwrap().0.fee_msat
230 fn get_total_fee_paid_msat(&self) -> u64 {
231 if self.hops.len() < 1 {
235 // Can't use next_hops_fee_msat because it gets outdated.
236 for (i, (hop, _)) in self.hops.iter().enumerate() {
237 if i != self.hops.len() - 1 {
238 result += hop.fee_msat;
244 // If the amount transferred by the path is updated, the fees should be adjusted. Any other way
245 // to change fees may result in an inconsistency.
247 // Sometimes we call this function right after constructing a path which is inconsistent in
248 // that it the value being transferred has decreased while we were doing path finding, leading
249 // to the fees being paid not lining up with the actual limits.
251 // Note that this function is not aware of the available_liquidity limit, and thus does not
252 // support increasing the value being transferred.
253 fn update_value_and_recompute_fees(&mut self, value_msat: u64) {
254 assert!(value_msat <= self.hops.last().unwrap().0.fee_msat);
256 let mut total_fee_paid_msat = 0 as u64;
257 for i in (0..self.hops.len()).rev() {
258 let last_hop = i == self.hops.len() - 1;
260 // For non-last-hop, this value will represent the fees paid on the current hop. It
261 // will consist of the fees for the use of the next hop, and extra fees to match
262 // htlc_minimum_msat of the current channel. Last hop is handled separately.
263 let mut cur_hop_fees_msat = 0;
265 cur_hop_fees_msat = self.hops.get(i + 1).unwrap().0.hop_use_fee_msat;
268 let mut cur_hop = &mut self.hops.get_mut(i).unwrap().0;
269 cur_hop.next_hops_fee_msat = total_fee_paid_msat;
270 // Overpay in fees if we can't save these funds due to htlc_minimum_msat.
271 // We try to account for htlc_minimum_msat in scoring (add_entry!), so that nodes don't
272 // set it too high just to maliciously take more fees by exploiting this
273 // match htlc_minimum_msat logic.
274 let mut cur_hop_transferred_amount_msat = total_fee_paid_msat + value_msat;
275 if let Some(extra_fees_msat) = cur_hop.htlc_minimum_msat.checked_sub(cur_hop_transferred_amount_msat) {
276 // Note that there is a risk that *previous hops* (those closer to us, as we go
277 // payee->our_node here) would exceed their htlc_maximum_msat or available balance.
279 // This might make us end up with a broken route, although this should be super-rare
280 // in practice, both because of how healthy channels look like, and how we pick
281 // channels in add_entry.
282 // Also, this can't be exploited more heavily than *announce a free path and fail
284 cur_hop_transferred_amount_msat += extra_fees_msat;
285 total_fee_paid_msat += extra_fees_msat;
286 cur_hop_fees_msat += extra_fees_msat;
290 // Final hop is a special case: it usually has just value_msat (by design), but also
291 // it still could overpay for the htlc_minimum_msat.
292 cur_hop.fee_msat = cur_hop_transferred_amount_msat;
294 // Propagate updated fees for the use of the channels to one hop back, where they
295 // will be actually paid (fee_msat). The last hop is handled above separately.
296 cur_hop.fee_msat = cur_hop_fees_msat;
299 // Fee for the use of the current hop which will be deducted on the previous hop.
300 // Irrelevant for the first hop, as it doesn't have the previous hop, and the use of
301 // this channel is free for us.
303 if let Some(new_fee) = compute_fees(cur_hop_transferred_amount_msat, cur_hop.channel_fees) {
304 cur_hop.hop_use_fee_msat = new_fee;
305 total_fee_paid_msat += new_fee;
307 // It should not be possible because this function is called only to reduce the
308 // value. In that case, compute_fee was already called with the same fees for
309 // larger amount and there was no overflow.
317 fn compute_fees(amount_msat: u64, channel_fees: RoutingFees) -> Option<u64> {
318 let proportional_fee_millions =
319 amount_msat.checked_mul(channel_fees.proportional_millionths as u64);
320 if let Some(new_fee) = proportional_fee_millions.and_then(|part| {
321 (channel_fees.base_msat as u64).checked_add(part / 1_000_000) }) {
325 // This function may be (indirectly) called without any verification,
326 // with channel_fees provided by a caller. We should handle it gracefully.
331 /// Gets a keysend route from us (payer) to the given target node (payee). This is needed because
332 /// keysend payments do not have an invoice from which to pull the payee's supported features, which
333 /// makes it tricky to otherwise supply the `payee_features` parameter of `get_route`.
334 pub fn get_keysend_route<L: Deref>(our_node_id: &PublicKey, network: &NetworkGraph, payee:
335 &PublicKey, first_hops: Option<&[&ChannelDetails]>, last_hops: &[&RouteHint],
336 final_value_msat: u64, final_cltv: u32, logger: L) -> Result<Route,
337 LightningError> where L::Target: Logger {
338 let invoice_features = InvoiceFeatures::for_keysend();
339 get_route(our_node_id, network, payee, Some(invoice_features), first_hops, last_hops,
340 final_value_msat, final_cltv, logger)
343 /// Gets a route from us (payer) to the given target node (payee).
345 /// If the payee provided features in their invoice, they should be provided via payee_features.
346 /// Without this, MPP will only be used if the payee's features are available in the network graph.
348 /// Private routing paths between a public node and the target may be included in `last_hops`.
349 /// Currently, only the last hop in each path is considered.
351 /// If some channels aren't announced, it may be useful to fill in a first_hops with the
352 /// results from a local ChannelManager::list_usable_channels() call. If it is filled in, our
353 /// view of our local channels (from net_graph_msg_handler) will be ignored, and only those
354 /// in first_hops will be used.
356 /// Panics if first_hops contains channels without short_channel_ids
357 /// (ChannelManager::list_usable_channels will never include such channels).
359 /// The fees on channels from us to next-hops are ignored (as they are assumed to all be
360 /// equal), however the enabled/disabled bit on such channels as well as the
361 /// htlc_minimum_msat/htlc_maximum_msat *are* checked as they may change based on the receiving node.
362 pub fn get_route<L: Deref>(our_node_id: &PublicKey, network: &NetworkGraph, payee: &PublicKey, payee_features: Option<InvoiceFeatures>, first_hops: Option<&[&ChannelDetails]>,
363 last_hops: &[&RouteHint], final_value_msat: u64, final_cltv: u32, logger: L) -> Result<Route, LightningError> where L::Target: Logger {
364 // TODO: Obviously *only* using total fee cost sucks. We should consider weighting by
365 // uptime/success in using a node in the past.
366 if *payee == *our_node_id {
367 return Err(LightningError{err: "Cannot generate a route to ourselves".to_owned(), action: ErrorAction::IgnoreError});
370 if final_value_msat > MAX_VALUE_MSAT {
371 return Err(LightningError{err: "Cannot generate a route of more value than all existing satoshis".to_owned(), action: ErrorAction::IgnoreError});
374 if final_value_msat == 0 {
375 return Err(LightningError{err: "Cannot send a payment of 0 msat".to_owned(), action: ErrorAction::IgnoreError});
378 for route in last_hops.iter() {
379 for hop in &route.0 {
380 if hop.src_node_id == *payee {
381 return Err(LightningError{err: "Last hop cannot have a payee as a source.".to_owned(), action: ErrorAction::IgnoreError});
386 // The general routing idea is the following:
387 // 1. Fill first/last hops communicated by the caller.
388 // 2. Attempt to construct a path from payer to payee for transferring
389 // any ~sufficient (described later) value.
390 // If succeed, remember which channels were used and how much liquidity they have available,
391 // so that future paths don't rely on the same liquidity.
392 // 3. Prooceed to the next step if:
393 // - we hit the recommended target value;
394 // - OR if we could not construct a new path. Any next attempt will fail too.
395 // Otherwise, repeat step 2.
396 // 4. See if we managed to collect paths which aggregately are able to transfer target value
397 // (not recommended value). If yes, proceed. If not, fail routing.
398 // 5. Randomly combine paths into routes having enough to fulfill the payment. (TODO: knapsack)
399 // 6. Of all the found paths, select only those with the lowest total fee.
400 // 7. The last path in every selected route is likely to be more than we need.
401 // Reduce its value-to-transfer and recompute fees.
402 // 8. Choose the best route by the lowest total fee.
404 // As for the actual search algorithm,
405 // we do a payee-to-payer pseudo-Dijkstra's sorting by each node's distance from the payee
406 // plus the minimum per-HTLC fee to get from it to another node (aka "shitty pseudo-A*").
408 // We are not a faithful Dijkstra's implementation because we can change values which impact
409 // earlier nodes while processing later nodes. Specifically, if we reach a channel with a lower
410 // liquidity limit (via htlc_maximum_msat, on-chain capacity or assumed liquidity limits) then
411 // the value we are currently attempting to send over a path, we simply reduce the value being
412 // sent along the path for any hops after that channel. This may imply that later fees (which
413 // we've already tabulated) are lower because a smaller value is passing through the channels
414 // (and the proportional fee is thus lower). There isn't a trivial way to recalculate the
415 // channels which were selected earlier (and which may still be used for other paths without a
416 // lower liquidity limit), so we simply accept that some liquidity-limited paths may be
419 // One potentially problematic case for this algorithm would be if there are many
420 // liquidity-limited paths which are liquidity-limited near the destination (ie early in our
421 // graph walking), we may never find a path which is not liquidity-limited and has lower
422 // proportional fee (and only lower absolute fee when considering the ultimate value sent).
423 // Because we only consider paths with at least 5% of the total value being sent, the damage
424 // from such a case should be limited, however this could be further reduced in the future by
425 // calculating fees on the amount we wish to route over a path, ie ignoring the liquidity
426 // limits for the purposes of fee calculation.
428 // Alternatively, we could store more detailed path information in the heap (targets, below)
429 // and index the best-path map (dist, below) by node *and* HTLC limits, however that would blow
430 // up the runtime significantly both algorithmically (as we'd traverse nodes multiple times)
431 // and practically (as we would need to store dynamically-allocated path information in heap
432 // objects, increasing malloc traffic and indirect memory access significantly). Further, the
433 // results of such an algorithm would likely be biased towards lower-value paths.
435 // Further, we could return to a faithful Dijkstra's algorithm by rejecting paths with limits
436 // outside of our current search value, running a path search more times to gather candidate
437 // paths at different values. While this may be acceptable, further path searches may increase
438 // runtime for little gain. Specifically, the current algorithm rather efficiently explores the
439 // graph for candidate paths, calculating the maximum value which can realistically be sent at
440 // the same time, remaining generic across different payment values.
442 // TODO: There are a few tweaks we could do, including possibly pre-calculating more stuff
443 // to use as the A* heuristic beyond just the cost to get one node further than the current
446 let network_channels = network.get_channels();
447 let network_nodes = network.get_nodes();
448 let dummy_directional_info = DummyDirectionalChannelInfo { // used for first_hops routes
449 cltv_expiry_delta: 0,
450 htlc_minimum_msat: 0,
451 htlc_maximum_msat: None,
454 proportional_millionths: 0,
458 // Allow MPP only if we have a features set from somewhere that indicates the payee supports
459 // it. If the payee supports it they're supposed to include it in the invoice, so that should
461 let allow_mpp = if let Some(features) = &payee_features {
462 features.supports_basic_mpp()
463 } else if let Some(node) = network_nodes.get(&payee) {
464 if let Some(node_info) = node.announcement_info.as_ref() {
465 node_info.features.supports_basic_mpp()
470 // Prepare the data we'll use for payee-to-payer search by
471 // inserting first hops suggested by the caller as targets.
472 // Our search will then attempt to reach them while traversing from the payee node.
473 let mut first_hop_targets: HashMap<_, (_, ChannelFeatures, _, NodeFeatures)> =
474 HashMap::with_capacity(if first_hops.is_some() { first_hops.as_ref().unwrap().len() } else { 0 });
475 if let Some(hops) = first_hops {
477 let short_channel_id = chan.short_channel_id.expect("first_hops should be filled in with usable channels, not pending ones");
478 if chan.counterparty.node_id == *our_node_id {
479 return Err(LightningError{err: "First hop cannot have our_node_id as a destination.".to_owned(), action: ErrorAction::IgnoreError});
481 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()));
483 if first_hop_targets.is_empty() {
484 return Err(LightningError{err: "Cannot route when there are no outbound routes away from us".to_owned(), action: ErrorAction::IgnoreError});
488 let empty_channel_features = ChannelFeatures::empty();
490 // The main heap containing all candidate next-hops sorted by their score (max(A* fee,
491 // htlc_minimum)). Ideally this would be a heap which allowed cheap score reduction instead of
492 // adding duplicate entries when we find a better path to a given node.
493 let mut targets = BinaryHeap::new();
495 // Map from node_id to information about the best current path to that node, including feerate
497 let mut dist = HashMap::with_capacity(network_nodes.len());
499 // During routing, if we ignore a path due to an htlc_minimum_msat limit, we set this,
500 // indicating that we may wish to try again with a higher value, potentially paying to meet an
501 // htlc_minimum with extra fees while still finding a cheaper path.
502 let mut hit_minimum_limit;
504 // When arranging a route, we select multiple paths so that we can make a multi-path payment.
505 // We start with a path_value of the exact amount we want, and if that generates a route we may
506 // return it immediately. Otherwise, we don't stop searching for paths until we have 3x the
507 // amount we want in total across paths, selecting the best subset at the end.
508 const ROUTE_CAPACITY_PROVISION_FACTOR: u64 = 3;
509 let recommended_value_msat = final_value_msat * ROUTE_CAPACITY_PROVISION_FACTOR as u64;
510 let mut path_value_msat = final_value_msat;
512 // We don't want multiple paths (as per MPP) share liquidity of the same channels.
513 // This map allows paths to be aware of the channel use by other paths in the same call.
514 // This would help to make a better path finding decisions and not "overbook" channels.
515 // It is unaware of the directions (except for `outbound_capacity_msat` in `first_hops`).
516 let mut bookkeeped_channels_liquidity_available_msat = HashMap::with_capacity(network_nodes.len());
518 // Keeping track of how much value we already collected across other paths. Helps to decide:
519 // - how much a new path should be transferring (upper bound);
520 // - whether a channel should be disregarded because
521 // it's available liquidity is too small comparing to how much more we need to collect;
522 // - when we want to stop looking for new paths.
523 let mut already_collected_value_msat = 0;
525 log_trace!(logger, "Building path from {} (payee) to {} (us/payer) for value {} msat.", payee, our_node_id, final_value_msat);
527 macro_rules! add_entry {
528 // Adds entry which goes from $src_node_id to $dest_node_id
529 // over the channel with id $chan_id with fees described in
530 // $directional_info.
531 // $next_hops_fee_msat represents the fees paid for using all the channel *after* this one,
532 // since that value has to be transferred over this channel.
533 // Returns whether this channel caused an update to `targets`.
534 ( $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,
535 $next_hops_value_contribution: expr, $next_hops_path_htlc_minimum_msat: expr ) => { {
536 // We "return" whether we updated the path at the end, via this:
537 let mut did_add_update_path_to_src_node = false;
538 // Channels to self should not be used. This is more of belt-and-suspenders, because in
539 // practice these cases should be caught earlier:
540 // - for regular channels at channel announcement (TODO)
541 // - for first and last hops early in get_route
542 if $src_node_id != $dest_node_id.clone() {
543 let available_liquidity_msat = bookkeeped_channels_liquidity_available_msat.entry($chan_id.clone()).or_insert_with(|| {
544 let mut initial_liquidity_available_msat = None;
545 if let Some(capacity_sats) = $capacity_sats {
546 initial_liquidity_available_msat = Some(capacity_sats * 1000);
549 if let Some(htlc_maximum_msat) = $directional_info.htlc_maximum_msat {
550 if let Some(available_msat) = initial_liquidity_available_msat {
551 initial_liquidity_available_msat = Some(cmp::min(available_msat, htlc_maximum_msat));
553 initial_liquidity_available_msat = Some(htlc_maximum_msat);
557 match initial_liquidity_available_msat {
558 Some(available_msat) => available_msat,
559 // We assume channels with unknown balance have
560 // a capacity of 0.0025 BTC (or 250_000 sats).
561 None => 250_000 * 1000
565 // It is tricky to substract $next_hops_fee_msat from available liquidity here.
566 // It may be misleading because we might later choose to reduce the value transferred
567 // over these channels, and the channel which was insufficient might become sufficient.
568 // Worst case: we drop a good channel here because it can't cover the high following
569 // fees caused by one expensive channel, but then this channel could have been used
570 // if the amount being transferred over this path is lower.
571 // We do this for now, but this is a subject for removal.
572 if let Some(available_value_contribution_msat) = available_liquidity_msat.checked_sub($next_hops_fee_msat) {
574 // Routing Fragmentation Mitigation heuristic:
576 // Routing fragmentation across many payment paths increases the overall routing
577 // fees as you have irreducible routing fees per-link used (`fee_base_msat`).
578 // Taking too many smaller paths also increases the chance of payment failure.
579 // Thus to avoid this effect, we require from our collected links to provide
580 // at least a minimal contribution to the recommended value yet-to-be-fulfilled.
582 // This requirement is currently 5% of the remaining-to-be-collected value.
583 // This means as we successfully advance in our collection,
584 // the absolute liquidity contribution is lowered,
585 // thus increasing the number of potential channels to be selected.
587 // Derive the minimal liquidity contribution with a ratio of 20 (5%, rounded up)
588 // or 100% if we're not allowed to do multipath payments.
589 let minimal_value_contribution_msat: u64 = if allow_mpp {
590 (recommended_value_msat - already_collected_value_msat + 19) / 20
594 // Verify the liquidity offered by this channel complies to the minimal contribution.
595 let contributes_sufficient_value = available_value_contribution_msat >= minimal_value_contribution_msat;
597 let value_contribution_msat = cmp::min(available_value_contribution_msat, $next_hops_value_contribution);
598 // Includes paying fees for the use of the following channels.
599 let amount_to_transfer_over_msat: u64 = match value_contribution_msat.checked_add($next_hops_fee_msat) {
600 Some(result) => result,
601 // Can't overflow due to how the values were computed right above.
602 None => unreachable!(),
604 #[allow(unused_comparisons)] // $next_hops_path_htlc_minimum_msat is 0 in some calls so rustc complains
605 let over_path_minimum_msat = amount_to_transfer_over_msat >= $directional_info.htlc_minimum_msat &&
606 amount_to_transfer_over_msat >= $next_hops_path_htlc_minimum_msat;
608 // If HTLC minimum is larger than the amount we're going to transfer, we shouldn't
609 // bother considering this channel.
610 // Since we're choosing amount_to_transfer_over_msat as maximum possible, it can
611 // be only reduced later (not increased), so this channel should just be skipped
612 // as not sufficient.
613 if !over_path_minimum_msat {
614 hit_minimum_limit = true;
615 } else if contributes_sufficient_value {
616 // Note that low contribution here (limited by available_liquidity_msat)
617 // might violate htlc_minimum_msat on the hops which are next along the
618 // payment path (upstream to the payee). To avoid that, we recompute path
619 // path fees knowing the final path contribution after constructing it.
620 let path_htlc_minimum_msat = match compute_fees($next_hops_path_htlc_minimum_msat, $directional_info.fees)
621 .map(|fee_msat| fee_msat.checked_add($next_hops_path_htlc_minimum_msat)) {
622 Some(Some(value_msat)) => cmp::max(value_msat, $directional_info.htlc_minimum_msat),
623 _ => u64::max_value()
625 let hm_entry = dist.entry(&$src_node_id);
626 let old_entry = hm_entry.or_insert_with(|| {
627 // If there was previously no known way to access
628 // the source node (recall it goes payee-to-payer) of $chan_id, first add
629 // a semi-dummy record just to compute the fees to reach the source node.
630 // This will affect our decision on selecting $chan_id
631 // as a way to reach the $dest_node_id.
632 let mut fee_base_msat = u32::max_value();
633 let mut fee_proportional_millionths = u32::max_value();
634 if let Some(Some(fees)) = network_nodes.get(&$src_node_id).map(|node| node.lowest_inbound_channel_fees) {
635 fee_base_msat = fees.base_msat;
636 fee_proportional_millionths = fees.proportional_millionths;
639 pubkey: $dest_node_id.clone(),
641 channel_features: $chan_features,
643 cltv_expiry_delta: 0,
644 src_lowest_inbound_fees: RoutingFees {
645 base_msat: fee_base_msat,
646 proportional_millionths: fee_proportional_millionths,
648 channel_fees: $directional_info.fees,
649 next_hops_fee_msat: u64::max_value(),
650 hop_use_fee_msat: u64::max_value(),
651 total_fee_msat: u64::max_value(),
652 htlc_minimum_msat: $directional_info.htlc_minimum_msat,
653 path_htlc_minimum_msat,
654 was_processed: false,
655 #[cfg(any(test, feature = "fuzztarget"))]
656 value_contribution_msat,
660 #[allow(unused_mut)] // We only use the mut in cfg(test)
661 let mut should_process = !old_entry.was_processed;
662 #[cfg(any(test, feature = "fuzztarget"))]
664 // In test/fuzzing builds, we do extra checks to make sure the skipping
665 // of already-seen nodes only happens in cases we expect (see below).
666 if !should_process { should_process = true; }
670 let mut hop_use_fee_msat = 0;
671 let mut total_fee_msat = $next_hops_fee_msat;
673 // Ignore hop_use_fee_msat for channel-from-us as we assume all channels-from-us
674 // will have the same effective-fee
675 if $src_node_id != *our_node_id {
676 match compute_fees(amount_to_transfer_over_msat, $directional_info.fees) {
677 // max_value means we'll always fail
678 // the old_entry.total_fee_msat > total_fee_msat check
679 None => total_fee_msat = u64::max_value(),
681 hop_use_fee_msat = fee_msat;
682 total_fee_msat += hop_use_fee_msat;
683 // When calculating the lowest inbound fees to a node, we
684 // calculate fees here not based on the actual value we think
685 // will flow over this channel, but on the minimum value that
686 // we'll accept flowing over it. The minimum accepted value
687 // is a constant through each path collection run, ensuring
688 // consistent basis. Otherwise we may later find a
689 // different path to the source node that is more expensive,
690 // but which we consider to be cheaper because we are capacity
691 // constrained and the relative fee becomes lower.
692 match compute_fees(minimal_value_contribution_msat, old_entry.src_lowest_inbound_fees)
693 .map(|a| a.checked_add(total_fee_msat)) {
698 total_fee_msat = u64::max_value();
705 let new_graph_node = RouteGraphNode {
706 pubkey: $src_node_id,
707 lowest_fee_to_peer_through_node: total_fee_msat,
708 lowest_fee_to_node: $next_hops_fee_msat as u64 + hop_use_fee_msat,
709 value_contribution_msat: value_contribution_msat,
710 path_htlc_minimum_msat,
713 // Update the way of reaching $src_node_id with the given $chan_id (from $dest_node_id),
714 // if this way is cheaper than the already known
715 // (considering the cost to "reach" this channel from the route destination,
716 // the cost of using this channel,
717 // and the cost of routing to the source node of this channel).
718 // Also, consider that htlc_minimum_msat_difference, because we might end up
719 // paying it. Consider the following exploit:
720 // we use 2 paths to transfer 1.5 BTC. One of them is 0-fee normal 1 BTC path,
721 // and for the other one we picked a 1sat-fee path with htlc_minimum_msat of
722 // 1 BTC. Now, since the latter is more expensive, we gonna try to cut it
723 // by 0.5 BTC, but then match htlc_minimum_msat by paying a fee of 0.5 BTC
725 // Ideally the scoring could be smarter (e.g. 0.5*htlc_minimum_msat here),
726 // but it may require additional tracking - we don't want to double-count
727 // the fees included in $next_hops_path_htlc_minimum_msat, but also
728 // can't use something that may decrease on future hops.
729 let old_cost = cmp::max(old_entry.total_fee_msat, old_entry.path_htlc_minimum_msat);
730 let new_cost = cmp::max(total_fee_msat, path_htlc_minimum_msat);
732 if !old_entry.was_processed && new_cost < old_cost {
733 targets.push(new_graph_node);
734 old_entry.next_hops_fee_msat = $next_hops_fee_msat;
735 old_entry.hop_use_fee_msat = hop_use_fee_msat;
736 old_entry.total_fee_msat = total_fee_msat;
737 old_entry.pubkey = $dest_node_id.clone();
738 old_entry.short_channel_id = $chan_id.clone();
739 old_entry.channel_features = $chan_features;
740 old_entry.fee_msat = 0; // This value will be later filled with hop_use_fee_msat of the following channel
741 old_entry.cltv_expiry_delta = $directional_info.cltv_expiry_delta as u32;
742 old_entry.channel_fees = $directional_info.fees;
743 old_entry.htlc_minimum_msat = $directional_info.htlc_minimum_msat;
744 old_entry.path_htlc_minimum_msat = path_htlc_minimum_msat;
745 #[cfg(any(test, feature = "fuzztarget"))]
747 old_entry.value_contribution_msat = value_contribution_msat;
749 did_add_update_path_to_src_node = true;
750 } else if old_entry.was_processed && new_cost < old_cost {
751 #[cfg(any(test, feature = "fuzztarget"))]
753 // If we're skipping processing a node which was previously
754 // processed even though we found another path to it with a
755 // cheaper fee, check that it was because the second path we
756 // found (which we are processing now) has a lower value
757 // contribution due to an HTLC minimum limit.
759 // e.g. take a graph with two paths from node 1 to node 2, one
760 // through channel A, and one through channel B. Channel A and
761 // B are both in the to-process heap, with their scores set by
762 // a higher htlc_minimum than fee.
763 // Channel A is processed first, and the channels onwards from
764 // node 1 are added to the to-process heap. Thereafter, we pop
765 // Channel B off of the heap, note that it has a much more
766 // restrictive htlc_maximum_msat, and recalculate the fees for
767 // all of node 1's channels using the new, reduced, amount.
769 // This would be bogus - we'd be selecting a higher-fee path
770 // with a lower htlc_maximum_msat instead of the one we'd
771 // already decided to use.
772 debug_assert!(path_htlc_minimum_msat < old_entry.path_htlc_minimum_msat);
773 debug_assert!(value_contribution_msat < old_entry.value_contribution_msat);
780 did_add_update_path_to_src_node
784 let empty_node_features = NodeFeatures::empty();
785 // Find ways (channels with destination) to reach a given node and store them
786 // in the corresponding data structures (routing graph etc).
787 // $fee_to_target_msat represents how much it costs to reach to this node from the payee,
788 // meaning how much will be paid in fees after this node (to the best of our knowledge).
789 // This data can later be helpful to optimize routing (pay lower fees).
790 macro_rules! add_entries_to_cheapest_to_target_node {
791 ( $node: expr, $node_id: expr, $fee_to_target_msat: expr, $next_hops_value_contribution: expr, $next_hops_path_htlc_minimum_msat: expr ) => {
792 let skip_node = if let Some(elem) = dist.get_mut($node_id) {
793 let was_processed = elem.was_processed;
794 elem.was_processed = true;
797 // Entries are added to dist in add_entry!() when there is a channel from a node.
798 // Because there are no channels from payee, it will not have a dist entry at this point.
799 // If we're processing any other node, it is always be the result of a channel from it.
800 assert_eq!($node_id, payee);
805 if first_hops.is_some() {
806 if let Some(&(ref first_hop, ref features, ref outbound_capacity_msat, _)) = first_hop_targets.get(&$node_id) {
807 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);
811 let features = if let Some(node_info) = $node.announcement_info.as_ref() {
817 if !features.requires_unknown_bits() {
818 for chan_id in $node.channels.iter() {
819 let chan = network_channels.get(chan_id).unwrap();
820 if !chan.features.requires_unknown_bits() {
821 if chan.node_one == *$node_id {
822 // ie $node is one, ie next hop in A* is two, via the two_to_one channel
823 if first_hops.is_none() || chan.node_two != *our_node_id {
824 if let Some(two_to_one) = chan.two_to_one.as_ref() {
825 if two_to_one.enabled {
826 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);
831 if first_hops.is_none() || chan.node_one != *our_node_id {
832 if let Some(one_to_two) = chan.one_to_two.as_ref() {
833 if one_to_two.enabled {
834 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);
846 let mut payment_paths = Vec::<PaymentPath>::new();
848 // TODO: diversify by nodes (so that all paths aren't doomed if one node is offline).
849 'paths_collection: loop {
850 // For every new path, start from scratch, except
851 // bookkeeped_channels_liquidity_available_msat, which will improve
852 // the further iterations of path finding. Also don't erase first_hop_targets.
855 hit_minimum_limit = false;
857 // If first hop is a private channel and the only way to reach the payee, this is the only
858 // place where it could be added.
859 if first_hops.is_some() {
860 if let Some(&(ref first_hop, ref features, ref outbound_capacity_msat, _)) = first_hop_targets.get(&payee) {
861 add_entry!(first_hop, *our_node_id, payee, dummy_directional_info, Some(outbound_capacity_msat / 1000), features, 0, path_value_msat, 0);
865 // Add the payee as a target, so that the payee-to-payer
866 // search algorithm knows what to start with.
867 match network_nodes.get(payee) {
868 // The payee is not in our network graph, so nothing to add here.
869 // There is still a chance of reaching them via last_hops though,
870 // so don't yet fail the payment here.
871 // If not, targets.pop() will not even let us enter the loop in step 2.
874 add_entries_to_cheapest_to_target_node!(node, payee, 0, path_value_msat, 0);
879 // If a caller provided us with last hops, add them to routing targets. Since this happens
880 // earlier than general path finding, they will be somewhat prioritized, although currently
881 // it matters only if the fees are exactly the same.
882 for route in last_hops.iter().filter(|route| !route.0.is_empty()) {
883 let first_hop_in_route = &(route.0)[0];
884 let have_hop_src_in_graph =
885 // Only add the hops in this route to our candidate set if either
886 // we have a direct channel to the first hop or the first hop is
887 // in the regular network graph.
888 first_hop_targets.get(&first_hop_in_route.src_node_id).is_some() ||
889 network_nodes.get(&first_hop_in_route.src_node_id).is_some();
890 if have_hop_src_in_graph {
891 // We start building the path from reverse, i.e., from payee
892 // to the first RouteHintHop in the path.
893 let hop_iter = route.0.iter().rev();
894 let prev_hop_iter = core::iter::once(payee).chain(
895 route.0.iter().skip(1).rev().map(|hop| &hop.src_node_id));
896 let mut hop_used = true;
897 let mut aggregate_next_hops_fee_msat: u64 = 0;
898 let mut aggregate_next_hops_path_htlc_minimum_msat: u64 = 0;
900 for (idx, (hop, prev_hop_id)) in hop_iter.zip(prev_hop_iter).enumerate() {
901 // BOLT 11 doesn't allow inclusion of features for the last hop hints, which
902 // really sucks, cause we're gonna need that eventually.
903 let hop_htlc_minimum_msat: u64 = hop.htlc_minimum_msat.unwrap_or(0);
905 let directional_info = DummyDirectionalChannelInfo {
906 cltv_expiry_delta: hop.cltv_expiry_delta as u32,
907 htlc_minimum_msat: hop_htlc_minimum_msat,
908 htlc_maximum_msat: hop.htlc_maximum_msat,
912 let reqd_channel_cap = if let Some (val) = final_value_msat.checked_add(match idx {
914 _ => aggregate_next_hops_fee_msat.checked_add(999).unwrap_or(u64::max_value())
915 }) { Some( val / 1000 ) } else { break; }; // converting from msat or breaking if max ~ infinity
918 // We assume that the recipient only included route hints for routes which had
919 // sufficient value to route `final_value_msat`. Note that in the case of "0-value"
920 // invoices where the invoice does not specify value this may not be the case, but
921 // better to include the hints than not.
922 if !add_entry!(hop.short_channel_id, hop.src_node_id, prev_hop_id, directional_info, reqd_channel_cap, &empty_channel_features, aggregate_next_hops_fee_msat, path_value_msat, aggregate_next_hops_path_htlc_minimum_msat) {
923 // If this hop was not used then there is no use checking the preceding hops
924 // in the RouteHint. We can break by just searching for a direct channel between
925 // last checked hop and first_hop_targets
929 // Searching for a direct channel between last checked hop and first_hop_targets
930 if let Some(&(ref first_hop, ref features, ref outbound_capacity_msat, _)) = first_hop_targets.get(&prev_hop_id) {
931 add_entry!(first_hop, *our_node_id , prev_hop_id, dummy_directional_info, Some(outbound_capacity_msat / 1000), features, aggregate_next_hops_fee_msat, path_value_msat, aggregate_next_hops_path_htlc_minimum_msat);
938 // In the next values of the iterator, the aggregate fees already reflects
939 // the sum of value sent from payer (final_value_msat) and routing fees
940 // for the last node in the RouteHint. We need to just add the fees to
941 // route through the current node so that the preceeding node (next iteration)
943 let hops_fee = compute_fees(aggregate_next_hops_fee_msat + final_value_msat, hop.fees)
944 .map_or(None, |inc| inc.checked_add(aggregate_next_hops_fee_msat));
945 aggregate_next_hops_fee_msat = if let Some(val) = hops_fee { val } else { break; };
947 let hop_htlc_minimum_msat_inc = if let Some(val) = compute_fees(aggregate_next_hops_path_htlc_minimum_msat, hop.fees) { val } else { break; };
948 let hops_path_htlc_minimum = aggregate_next_hops_path_htlc_minimum_msat
949 .checked_add(hop_htlc_minimum_msat_inc);
950 aggregate_next_hops_path_htlc_minimum_msat = if let Some(val) = hops_path_htlc_minimum { cmp::max(hop_htlc_minimum_msat, val) } else { break; };
952 if idx == route.0.len() - 1 {
953 // The last hop in this iterator is the first hop in
954 // overall RouteHint.
955 // If this hop connects to a node with which we have a direct channel,
956 // ignore the network graph and, if the last hop was added, add our
957 // direct channel to the candidate set.
959 // Note that we *must* check if the last hop was added as `add_entry`
960 // always assumes that the third argument is a node to which we have a
962 if let Some(&(ref first_hop, ref features, ref outbound_capacity_msat, _)) = first_hop_targets.get(&hop.src_node_id) {
963 add_entry!(first_hop, *our_node_id , hop.src_node_id, dummy_directional_info, Some(outbound_capacity_msat / 1000), features, aggregate_next_hops_fee_msat, path_value_msat, aggregate_next_hops_path_htlc_minimum_msat);
970 log_trace!(logger, "Starting main path collection loop with {} nodes pre-filled from first/last hops.", targets.len());
972 // At this point, targets are filled with the data from first and
973 // last hops communicated by the caller, and the payment receiver.
974 let mut found_new_path = false;
977 // If this loop terminates due the exhaustion of targets, two situations are possible:
978 // - not enough outgoing liquidity:
979 // 0 < already_collected_value_msat < final_value_msat
980 // - enough outgoing liquidity:
981 // final_value_msat <= already_collected_value_msat < recommended_value_msat
982 // Both these cases (and other cases except reaching recommended_value_msat) mean that
983 // paths_collection will be stopped because found_new_path==false.
984 // This is not necessarily a routing failure.
985 'path_construction: while let Some(RouteGraphNode { pubkey, lowest_fee_to_node, value_contribution_msat, path_htlc_minimum_msat, .. }) = targets.pop() {
987 // Since we're going payee-to-payer, hitting our node as a target means we should stop
988 // traversing the graph and arrange the path out of what we found.
989 if pubkey == *our_node_id {
990 let mut new_entry = dist.remove(&our_node_id).unwrap();
991 let mut ordered_hops = vec!((new_entry.clone(), NodeFeatures::empty()));
994 if let Some(&(_, _, _, ref features)) = first_hop_targets.get(&ordered_hops.last().unwrap().0.pubkey) {
995 ordered_hops.last_mut().unwrap().1 = features.clone();
996 } else if let Some(node) = network_nodes.get(&ordered_hops.last().unwrap().0.pubkey) {
997 if let Some(node_info) = node.announcement_info.as_ref() {
998 ordered_hops.last_mut().unwrap().1 = node_info.features.clone();
1000 ordered_hops.last_mut().unwrap().1 = NodeFeatures::empty();
1003 // We should be able to fill in features for everything except the last
1004 // hop, if the last hop was provided via a BOLT 11 invoice (though we
1005 // should be able to extend it further as BOLT 11 does have feature
1006 // flags for the last hop node itself).
1007 assert!(ordered_hops.last().unwrap().0.pubkey == *payee);
1010 // Means we succesfully traversed from the payer to the payee, now
1011 // save this path for the payment route. Also, update the liquidity
1012 // remaining on the used hops, so that we take them into account
1013 // while looking for more paths.
1014 if ordered_hops.last().unwrap().0.pubkey == *payee {
1018 new_entry = match dist.remove(&ordered_hops.last().unwrap().0.pubkey) {
1019 Some(payment_hop) => payment_hop,
1020 // We can't arrive at None because, if we ever add an entry to targets,
1021 // we also fill in the entry in dist (see add_entry!).
1022 None => unreachable!(),
1024 // We "propagate" the fees one hop backward (topologically) here,
1025 // so that fees paid for a HTLC forwarding on the current channel are
1026 // associated with the previous channel (where they will be subtracted).
1027 ordered_hops.last_mut().unwrap().0.fee_msat = new_entry.hop_use_fee_msat;
1028 ordered_hops.last_mut().unwrap().0.cltv_expiry_delta = new_entry.cltv_expiry_delta;
1029 ordered_hops.push((new_entry.clone(), NodeFeatures::empty()));
1031 ordered_hops.last_mut().unwrap().0.fee_msat = value_contribution_msat;
1032 ordered_hops.last_mut().unwrap().0.hop_use_fee_msat = 0;
1033 ordered_hops.last_mut().unwrap().0.cltv_expiry_delta = final_cltv;
1035 log_trace!(logger, "Found a path back to us from the target with {} hops contributing up to {} msat: {:?}",
1036 ordered_hops.len(), value_contribution_msat, ordered_hops);
1038 let mut payment_path = PaymentPath {hops: ordered_hops};
1040 // We could have possibly constructed a slightly inconsistent path: since we reduce
1041 // value being transferred along the way, we could have violated htlc_minimum_msat
1042 // on some channels we already passed (assuming dest->source direction). Here, we
1043 // recompute the fees again, so that if that's the case, we match the currently
1044 // underpaid htlc_minimum_msat with fees.
1045 payment_path.update_value_and_recompute_fees(cmp::min(value_contribution_msat, final_value_msat));
1047 // Since a path allows to transfer as much value as
1048 // the smallest channel it has ("bottleneck"), we should recompute
1049 // the fees so sender HTLC don't overpay fees when traversing
1050 // larger channels than the bottleneck. This may happen because
1051 // when we were selecting those channels we were not aware how much value
1052 // this path will transfer, and the relative fee for them
1053 // might have been computed considering a larger value.
1054 // Remember that we used these channels so that we don't rely
1055 // on the same liquidity in future paths.
1056 let mut prevented_redundant_path_selection = false;
1057 for (payment_hop, _) in payment_path.hops.iter() {
1058 let channel_liquidity_available_msat = bookkeeped_channels_liquidity_available_msat.get_mut(&payment_hop.short_channel_id).unwrap();
1059 let mut spent_on_hop_msat = value_contribution_msat;
1060 let next_hops_fee_msat = payment_hop.next_hops_fee_msat;
1061 spent_on_hop_msat += next_hops_fee_msat;
1062 if spent_on_hop_msat == *channel_liquidity_available_msat {
1063 // If this path used all of this channel's available liquidity, we know
1064 // this path will not be selected again in the next loop iteration.
1065 prevented_redundant_path_selection = true;
1067 *channel_liquidity_available_msat -= spent_on_hop_msat;
1069 if !prevented_redundant_path_selection {
1070 // If we weren't capped by hitting a liquidity limit on a channel in the path,
1071 // we'll probably end up picking the same path again on the next iteration.
1072 // Decrease the available liquidity of a hop in the middle of the path.
1073 let victim_scid = payment_path.hops[(payment_path.hops.len() - 1) / 2].0.short_channel_id;
1074 log_trace!(logger, "Disabling channel {} for future path building iterations to avoid duplicates.", victim_scid);
1075 let victim_liquidity = bookkeeped_channels_liquidity_available_msat.get_mut(&victim_scid).unwrap();
1076 *victim_liquidity = 0;
1079 // Track the total amount all our collected paths allow to send so that we:
1080 // - know when to stop looking for more paths
1081 // - know which of the hops are useless considering how much more sats we need
1082 // (contributes_sufficient_value)
1083 already_collected_value_msat += value_contribution_msat;
1085 payment_paths.push(payment_path);
1086 found_new_path = true;
1087 break 'path_construction;
1090 // If we found a path back to the payee, we shouldn't try to process it again. This is
1091 // the equivalent of the `elem.was_processed` check in
1092 // add_entries_to_cheapest_to_target_node!() (see comment there for more info).
1093 if pubkey == *payee { continue 'path_construction; }
1095 // Otherwise, since the current target node is not us,
1096 // keep "unrolling" the payment graph from payee to payer by
1097 // finding a way to reach the current target from the payer side.
1098 match network_nodes.get(&pubkey) {
1101 add_entries_to_cheapest_to_target_node!(node, &pubkey, lowest_fee_to_node, value_contribution_msat, path_htlc_minimum_msat);
1107 // If we don't support MPP, no use trying to gather more value ever.
1108 break 'paths_collection;
1112 // Stop either when the recommended value is reached or if no new path was found in this
1114 // In the latter case, making another path finding attempt won't help,
1115 // because we deterministically terminated the search due to low liquidity.
1116 if already_collected_value_msat >= recommended_value_msat || !found_new_path {
1117 log_trace!(logger, "Have now collected {} msat (seeking {} msat) in paths. Last path loop {} a new path.",
1118 already_collected_value_msat, recommended_value_msat, if found_new_path { "found" } else { "did not find" });
1119 break 'paths_collection;
1120 } else if found_new_path && already_collected_value_msat == final_value_msat && payment_paths.len() == 1 {
1121 // Further, if this was our first walk of the graph, and we weren't limited by an
1122 // htlc_minimum_msat, return immediately because this path should suffice. If we were
1123 // limited by an htlc_minimum_msat value, find another path with a higher value,
1124 // potentially allowing us to pay fees to meet the htlc_minimum on the new path while
1125 // still keeping a lower total fee than this path.
1126 if !hit_minimum_limit {
1127 log_trace!(logger, "Collected exactly our payment amount on the first pass, without hitting an htlc_minimum_msat limit, exiting.");
1128 break 'paths_collection;
1130 log_trace!(logger, "Collected our payment amount on the first pass, but running again to collect extra paths with a potentially higher limit.");
1131 path_value_msat = recommended_value_msat;
1136 if payment_paths.len() == 0 {
1137 return Err(LightningError{err: "Failed to find a path to the given destination".to_owned(), action: ErrorAction::IgnoreError});
1140 if already_collected_value_msat < final_value_msat {
1141 return Err(LightningError{err: "Failed to find a sufficient route to the given destination".to_owned(), action: ErrorAction::IgnoreError});
1144 // Sort by total fees and take the best paths.
1145 payment_paths.sort_by_key(|path| path.get_total_fee_paid_msat());
1146 if payment_paths.len() > 50 {
1147 payment_paths.truncate(50);
1150 // Draw multiple sufficient routes by randomly combining the selected paths.
1151 let mut drawn_routes = Vec::new();
1152 for i in 0..payment_paths.len() {
1153 let mut cur_route = Vec::<PaymentPath>::new();
1154 let mut aggregate_route_value_msat = 0;
1157 // TODO: real random shuffle
1158 // Currently just starts with i_th and goes up to i-1_th in a looped way.
1159 let cur_payment_paths = [&payment_paths[i..], &payment_paths[..i]].concat();
1162 for payment_path in cur_payment_paths {
1163 cur_route.push(payment_path.clone());
1164 aggregate_route_value_msat += payment_path.get_value_msat();
1165 if aggregate_route_value_msat > final_value_msat {
1166 // Last path likely overpaid. Substract it from the most expensive
1167 // (in terms of proportional fee) path in this route and recompute fees.
1168 // This might be not the most economically efficient way, but fewer paths
1169 // also makes routing more reliable.
1170 let mut overpaid_value_msat = aggregate_route_value_msat - final_value_msat;
1172 // First, drop some expensive low-value paths entirely if possible.
1173 // Sort by value so that we drop many really-low values first, since
1174 // fewer paths is better: the payment is less likely to fail.
1175 // TODO: this could also be optimized by also sorting by feerate_per_sat_routed,
1176 // so that the sender pays less fees overall. And also htlc_minimum_msat.
1177 cur_route.sort_by_key(|path| path.get_value_msat());
1178 // We should make sure that at least 1 path left.
1179 let mut paths_left = cur_route.len();
1180 cur_route.retain(|path| {
1181 if paths_left == 1 {
1184 let mut keep = true;
1185 let path_value_msat = path.get_value_msat();
1186 if path_value_msat <= overpaid_value_msat {
1188 overpaid_value_msat -= path_value_msat;
1194 if overpaid_value_msat == 0 {
1198 assert!(cur_route.len() > 0);
1201 // Now, substract the overpaid value from the most-expensive path.
1202 // TODO: this could also be optimized by also sorting by feerate_per_sat_routed,
1203 // so that the sender pays less fees overall. And also htlc_minimum_msat.
1204 cur_route.sort_by_key(|path| { path.hops.iter().map(|hop| hop.0.channel_fees.proportional_millionths as u64).sum::<u64>() });
1205 let expensive_payment_path = cur_route.first_mut().unwrap();
1206 // We already dropped all the small channels above, meaning all the
1207 // remaining channels are larger than remaining overpaid_value_msat.
1208 // Thus, this can't be negative.
1209 let expensive_path_new_value_msat = expensive_payment_path.get_value_msat() - overpaid_value_msat;
1210 expensive_payment_path.update_value_and_recompute_fees(expensive_path_new_value_msat);
1214 drawn_routes.push(cur_route);
1218 // Select the best route by lowest total fee.
1219 drawn_routes.sort_by_key(|paths| paths.iter().map(|path| path.get_total_fee_paid_msat()).sum::<u64>());
1220 let mut selected_paths = Vec::<Vec<RouteHop>>::new();
1221 for payment_path in drawn_routes.first().unwrap() {
1222 selected_paths.push(payment_path.hops.iter().map(|(payment_hop, node_features)| {
1224 pubkey: payment_hop.pubkey,
1225 node_features: node_features.clone(),
1226 short_channel_id: payment_hop.short_channel_id,
1227 channel_features: payment_hop.channel_features.clone(),
1228 fee_msat: payment_hop.fee_msat,
1229 cltv_expiry_delta: payment_hop.cltv_expiry_delta,
1234 if let Some(features) = &payee_features {
1235 for path in selected_paths.iter_mut() {
1236 path.last_mut().unwrap().node_features = features.to_context();
1240 let route = Route { paths: selected_paths };
1241 log_info!(logger, "Got route to {}: {}", payee, log_route!(route));
1247 use routing::router::{get_route, Route, RouteHint, RouteHintHop, RoutingFees};
1248 use routing::network_graph::{NetworkGraph, NetGraphMsgHandler};
1249 use chain::transaction::OutPoint;
1250 use ln::features::{ChannelFeatures, InitFeatures, InvoiceFeatures, NodeFeatures};
1251 use ln::msgs::{ErrorAction, LightningError, OptionalField, UnsignedChannelAnnouncement, ChannelAnnouncement, RoutingMessageHandler,
1252 NodeAnnouncement, UnsignedNodeAnnouncement, ChannelUpdate, UnsignedChannelUpdate};
1253 use ln::channelmanager;
1254 use util::test_utils;
1255 use util::ser::Writeable;
1257 use bitcoin::hashes::sha256d::Hash as Sha256dHash;
1258 use bitcoin::hashes::Hash;
1259 use bitcoin::network::constants::Network;
1260 use bitcoin::blockdata::constants::genesis_block;
1261 use bitcoin::blockdata::script::Builder;
1262 use bitcoin::blockdata::opcodes;
1263 use bitcoin::blockdata::transaction::TxOut;
1267 use bitcoin::secp256k1::key::{PublicKey,SecretKey};
1268 use bitcoin::secp256k1::{Secp256k1, All};
1271 use sync::{self, Arc};
1273 fn get_channel_details(short_channel_id: Option<u64>, node_id: PublicKey,
1274 features: InitFeatures, outbound_capacity_msat: u64) -> channelmanager::ChannelDetails {
1275 channelmanager::ChannelDetails {
1276 channel_id: [0; 32],
1277 counterparty: channelmanager::ChannelCounterparty {
1280 unspendable_punishment_reserve: 0,
1281 forwarding_info: None,
1283 funding_txo: Some(OutPoint { txid: bitcoin::Txid::from_slice(&[0; 32]).unwrap(), index: 0 }),
1285 channel_value_satoshis: 0,
1287 outbound_capacity_msat,
1288 inbound_capacity_msat: 42,
1289 unspendable_punishment_reserve: None,
1290 confirmations_required: None,
1291 force_close_spend_delay: None,
1292 is_outbound: true, is_funding_locked: true,
1293 is_usable: true, is_public: true,
1297 // Using the same keys for LN and BTC ids
1298 fn add_channel(net_graph_msg_handler: &NetGraphMsgHandler<Arc<test_utils::TestChainSource>, Arc<test_utils::TestLogger>>, secp_ctx: &Secp256k1<All>, node_1_privkey: &SecretKey,
1299 node_2_privkey: &SecretKey, features: ChannelFeatures, short_channel_id: u64) {
1300 let node_id_1 = PublicKey::from_secret_key(&secp_ctx, node_1_privkey);
1301 let node_id_2 = PublicKey::from_secret_key(&secp_ctx, node_2_privkey);
1303 let unsigned_announcement = UnsignedChannelAnnouncement {
1305 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1309 bitcoin_key_1: node_id_1,
1310 bitcoin_key_2: node_id_2,
1311 excess_data: Vec::new(),
1314 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1315 let valid_announcement = ChannelAnnouncement {
1316 node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
1317 node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
1318 bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
1319 bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
1320 contents: unsigned_announcement.clone(),
1322 match net_graph_msg_handler.handle_channel_announcement(&valid_announcement) {
1323 Ok(res) => assert!(res),
1328 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) {
1329 let msghash = hash_to_message!(&Sha256dHash::hash(&update.encode()[..])[..]);
1330 let valid_channel_update = ChannelUpdate {
1331 signature: secp_ctx.sign(&msghash, node_privkey),
1332 contents: update.clone()
1335 match net_graph_msg_handler.handle_channel_update(&valid_channel_update) {
1336 Ok(res) => assert!(res),
1341 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,
1342 features: NodeFeatures, timestamp: u32) {
1343 let node_id = PublicKey::from_secret_key(&secp_ctx, node_privkey);
1344 let unsigned_announcement = UnsignedNodeAnnouncement {
1350 addresses: Vec::new(),
1351 excess_address_data: Vec::new(),
1352 excess_data: Vec::new(),
1354 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1355 let valid_announcement = NodeAnnouncement {
1356 signature: secp_ctx.sign(&msghash, node_privkey),
1357 contents: unsigned_announcement.clone()
1360 match net_graph_msg_handler.handle_node_announcement(&valid_announcement) {
1366 fn get_nodes(secp_ctx: &Secp256k1<All>) -> (SecretKey, PublicKey, Vec<SecretKey>, Vec<PublicKey>) {
1367 let privkeys: Vec<SecretKey> = (2..10).map(|i| {
1368 SecretKey::from_slice(&hex::decode(format!("{:02}", i).repeat(32)).unwrap()[..]).unwrap()
1371 let pubkeys = privkeys.iter().map(|secret| PublicKey::from_secret_key(&secp_ctx, secret)).collect();
1373 let our_privkey = SecretKey::from_slice(&hex::decode("01".repeat(32)).unwrap()[..]).unwrap();
1374 let our_id = PublicKey::from_secret_key(&secp_ctx, &our_privkey);
1376 (our_privkey, our_id, privkeys, pubkeys)
1379 fn id_to_feature_flags(id: u8) -> Vec<u8> {
1380 // Set the feature flags to the id'th odd (ie non-required) feature bit so that we can
1381 // test for it later.
1382 let idx = (id - 1) * 2 + 1;
1384 vec![1 << (idx - 8*3), 0, 0, 0]
1385 } else if idx > 8*2 {
1386 vec![1 << (idx - 8*2), 0, 0]
1387 } else if idx > 8*1 {
1388 vec![1 << (idx - 8*1), 0]
1394 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>) {
1395 let secp_ctx = Secp256k1::new();
1396 let logger = Arc::new(test_utils::TestLogger::new());
1397 let chain_monitor = Arc::new(test_utils::TestChainSource::new(Network::Testnet));
1398 let net_graph_msg_handler = NetGraphMsgHandler::new(genesis_block(Network::Testnet).header.block_hash(), None, Arc::clone(&logger));
1399 // Build network from our_id to node6:
1401 // -1(1)2- node0 -1(3)2-
1403 // our_id -1(12)2- node7 -1(13)2--- node2
1405 // -1(2)2- node1 -1(4)2-
1408 // chan1 1-to-2: disabled
1409 // chan1 2-to-1: enabled, 0 fee
1411 // chan2 1-to-2: enabled, ignored fee
1412 // chan2 2-to-1: enabled, 0 fee
1414 // chan3 1-to-2: enabled, 0 fee
1415 // chan3 2-to-1: enabled, 100 msat fee
1417 // chan4 1-to-2: enabled, 100% fee
1418 // chan4 2-to-1: enabled, 0 fee
1420 // chan12 1-to-2: enabled, ignored fee
1421 // chan12 2-to-1: enabled, 0 fee
1423 // chan13 1-to-2: enabled, 200% fee
1424 // chan13 2-to-1: enabled, 0 fee
1427 // -1(5)2- node3 -1(8)2--
1431 // node2--1(6)2- node4 -1(9)2--- node6 (not in global route map)
1433 // -1(7)2- node5 -1(10)2-
1435 // Channels 5, 8, 9 and 10 are private channels.
1437 // chan5 1-to-2: enabled, 100 msat fee
1438 // chan5 2-to-1: enabled, 0 fee
1440 // chan6 1-to-2: enabled, 0 fee
1441 // chan6 2-to-1: enabled, 0 fee
1443 // chan7 1-to-2: enabled, 100% fee
1444 // chan7 2-to-1: enabled, 0 fee
1446 // chan8 1-to-2: enabled, variable fee (0 then 1000 msat)
1447 // chan8 2-to-1: enabled, 0 fee
1449 // chan9 1-to-2: enabled, 1001 msat fee
1450 // chan9 2-to-1: enabled, 0 fee
1452 // chan10 1-to-2: enabled, 0 fee
1453 // chan10 2-to-1: enabled, 0 fee
1455 // chan11 1-to-2: enabled, 0 fee
1456 // chan11 2-to-1: enabled, 0 fee
1458 let (our_privkey, _, privkeys, _) = get_nodes(&secp_ctx);
1460 add_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, &privkeys[0], ChannelFeatures::from_le_bytes(id_to_feature_flags(1)), 1);
1461 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
1462 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1463 short_channel_id: 1,
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[0], NodeFeatures::from_le_bytes(id_to_feature_flags(1)), 0);
1476 add_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, &privkeys[1], ChannelFeatures::from_le_bytes(id_to_feature_flags(2)), 2);
1477 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
1478 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1479 short_channel_id: 2,
1482 cltv_expiry_delta: u16::max_value(),
1483 htlc_minimum_msat: 0,
1484 htlc_maximum_msat: OptionalField::Absent,
1485 fee_base_msat: u32::max_value(),
1486 fee_proportional_millionths: u32::max_value(),
1487 excess_data: Vec::new()
1489 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
1490 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1491 short_channel_id: 2,
1494 cltv_expiry_delta: 0,
1495 htlc_minimum_msat: 0,
1496 htlc_maximum_msat: OptionalField::Absent,
1498 fee_proportional_millionths: 0,
1499 excess_data: Vec::new()
1502 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[1], NodeFeatures::from_le_bytes(id_to_feature_flags(2)), 0);
1504 add_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, &privkeys[7], ChannelFeatures::from_le_bytes(id_to_feature_flags(12)), 12);
1505 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
1506 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1507 short_channel_id: 12,
1510 cltv_expiry_delta: u16::max_value(),
1511 htlc_minimum_msat: 0,
1512 htlc_maximum_msat: OptionalField::Absent,
1513 fee_base_msat: u32::max_value(),
1514 fee_proportional_millionths: u32::max_value(),
1515 excess_data: Vec::new()
1517 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
1518 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1519 short_channel_id: 12,
1522 cltv_expiry_delta: 0,
1523 htlc_minimum_msat: 0,
1524 htlc_maximum_msat: OptionalField::Absent,
1526 fee_proportional_millionths: 0,
1527 excess_data: Vec::new()
1530 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[7], NodeFeatures::from_le_bytes(id_to_feature_flags(8)), 0);
1532 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], &privkeys[2], ChannelFeatures::from_le_bytes(id_to_feature_flags(3)), 3);
1533 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
1534 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1535 short_channel_id: 3,
1538 cltv_expiry_delta: (3 << 8) | 1,
1539 htlc_minimum_msat: 0,
1540 htlc_maximum_msat: OptionalField::Absent,
1542 fee_proportional_millionths: 0,
1543 excess_data: Vec::new()
1545 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
1546 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1547 short_channel_id: 3,
1550 cltv_expiry_delta: (3 << 8) | 2,
1551 htlc_minimum_msat: 0,
1552 htlc_maximum_msat: OptionalField::Absent,
1554 fee_proportional_millionths: 0,
1555 excess_data: Vec::new()
1558 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], &privkeys[2], ChannelFeatures::from_le_bytes(id_to_feature_flags(4)), 4);
1559 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
1560 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1561 short_channel_id: 4,
1564 cltv_expiry_delta: (4 << 8) | 1,
1565 htlc_minimum_msat: 0,
1566 htlc_maximum_msat: OptionalField::Absent,
1568 fee_proportional_millionths: 1000000,
1569 excess_data: Vec::new()
1571 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
1572 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1573 short_channel_id: 4,
1576 cltv_expiry_delta: (4 << 8) | 2,
1577 htlc_minimum_msat: 0,
1578 htlc_maximum_msat: OptionalField::Absent,
1580 fee_proportional_millionths: 0,
1581 excess_data: Vec::new()
1584 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], &privkeys[2], ChannelFeatures::from_le_bytes(id_to_feature_flags(13)), 13);
1585 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
1586 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1587 short_channel_id: 13,
1590 cltv_expiry_delta: (13 << 8) | 1,
1591 htlc_minimum_msat: 0,
1592 htlc_maximum_msat: OptionalField::Absent,
1594 fee_proportional_millionths: 2000000,
1595 excess_data: Vec::new()
1597 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
1598 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1599 short_channel_id: 13,
1602 cltv_expiry_delta: (13 << 8) | 2,
1603 htlc_minimum_msat: 0,
1604 htlc_maximum_msat: OptionalField::Absent,
1606 fee_proportional_millionths: 0,
1607 excess_data: Vec::new()
1610 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[2], NodeFeatures::from_le_bytes(id_to_feature_flags(3)), 0);
1612 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], &privkeys[4], ChannelFeatures::from_le_bytes(id_to_feature_flags(6)), 6);
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: 6,
1618 cltv_expiry_delta: (6 << 8) | 1,
1619 htlc_minimum_msat: 0,
1620 htlc_maximum_msat: OptionalField::Absent,
1622 fee_proportional_millionths: 0,
1623 excess_data: Vec::new()
1625 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
1626 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1627 short_channel_id: 6,
1630 cltv_expiry_delta: (6 << 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_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(11)), 11);
1639 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
1640 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1641 short_channel_id: 11,
1644 cltv_expiry_delta: (11 << 8) | 1,
1645 htlc_minimum_msat: 0,
1646 htlc_maximum_msat: OptionalField::Absent,
1648 fee_proportional_millionths: 0,
1649 excess_data: Vec::new()
1651 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[3], UnsignedChannelUpdate {
1652 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1653 short_channel_id: 11,
1656 cltv_expiry_delta: (11 << 8) | 2,
1657 htlc_minimum_msat: 0,
1658 htlc_maximum_msat: OptionalField::Absent,
1660 fee_proportional_millionths: 0,
1661 excess_data: Vec::new()
1664 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[4], NodeFeatures::from_le_bytes(id_to_feature_flags(5)), 0);
1666 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[3], NodeFeatures::from_le_bytes(id_to_feature_flags(4)), 0);
1668 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], &privkeys[5], ChannelFeatures::from_le_bytes(id_to_feature_flags(7)), 7);
1669 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
1670 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1671 short_channel_id: 7,
1674 cltv_expiry_delta: (7 << 8) | 1,
1675 htlc_minimum_msat: 0,
1676 htlc_maximum_msat: OptionalField::Absent,
1678 fee_proportional_millionths: 1000000,
1679 excess_data: Vec::new()
1681 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[5], UnsignedChannelUpdate {
1682 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1683 short_channel_id: 7,
1686 cltv_expiry_delta: (7 << 8) | 2,
1687 htlc_minimum_msat: 0,
1688 htlc_maximum_msat: OptionalField::Absent,
1690 fee_proportional_millionths: 0,
1691 excess_data: Vec::new()
1694 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[5], NodeFeatures::from_le_bytes(id_to_feature_flags(6)), 0);
1696 (secp_ctx, net_graph_msg_handler, chain_monitor, logger)
1700 fn simple_route_test() {
1701 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
1702 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
1704 // Simple route to 2 via 1
1706 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)) {
1707 assert_eq!(err, "Cannot send a payment of 0 msat");
1708 } else { panic!(); }
1710 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();
1711 assert_eq!(route.paths[0].len(), 2);
1713 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
1714 assert_eq!(route.paths[0][0].short_channel_id, 2);
1715 assert_eq!(route.paths[0][0].fee_msat, 100);
1716 assert_eq!(route.paths[0][0].cltv_expiry_delta, (4 << 8) | 1);
1717 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
1718 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
1720 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
1721 assert_eq!(route.paths[0][1].short_channel_id, 4);
1722 assert_eq!(route.paths[0][1].fee_msat, 100);
1723 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
1724 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
1725 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
1729 fn invalid_first_hop_test() {
1730 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
1731 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
1733 // Simple route to 2 via 1
1735 let our_chans = vec![get_channel_details(Some(2), our_id, InitFeatures::from_le_bytes(vec![0b11]), 100000)];
1737 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)) {
1738 assert_eq!(err, "First hop cannot have our_node_id as a destination.");
1739 } else { panic!(); }
1741 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();
1742 assert_eq!(route.paths[0].len(), 2);
1746 fn htlc_minimum_test() {
1747 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
1748 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
1750 // Simple route to 2 via 1
1752 // Disable other paths
1753 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
1754 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1755 short_channel_id: 12,
1757 flags: 2, // to disable
1758 cltv_expiry_delta: 0,
1759 htlc_minimum_msat: 0,
1760 htlc_maximum_msat: OptionalField::Absent,
1762 fee_proportional_millionths: 0,
1763 excess_data: Vec::new()
1765 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
1766 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1767 short_channel_id: 3,
1769 flags: 2, // to disable
1770 cltv_expiry_delta: 0,
1771 htlc_minimum_msat: 0,
1772 htlc_maximum_msat: OptionalField::Absent,
1774 fee_proportional_millionths: 0,
1775 excess_data: Vec::new()
1777 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
1778 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1779 short_channel_id: 13,
1781 flags: 2, // to disable
1782 cltv_expiry_delta: 0,
1783 htlc_minimum_msat: 0,
1784 htlc_maximum_msat: OptionalField::Absent,
1786 fee_proportional_millionths: 0,
1787 excess_data: Vec::new()
1789 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
1790 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1791 short_channel_id: 6,
1793 flags: 2, // to disable
1794 cltv_expiry_delta: 0,
1795 htlc_minimum_msat: 0,
1796 htlc_maximum_msat: OptionalField::Absent,
1798 fee_proportional_millionths: 0,
1799 excess_data: Vec::new()
1801 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
1802 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1803 short_channel_id: 7,
1805 flags: 2, // to disable
1806 cltv_expiry_delta: 0,
1807 htlc_minimum_msat: 0,
1808 htlc_maximum_msat: OptionalField::Absent,
1810 fee_proportional_millionths: 0,
1811 excess_data: Vec::new()
1814 // Check against amount_to_transfer_over_msat.
1815 // Set minimal HTLC of 200_000_000 msat.
1816 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
1817 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1818 short_channel_id: 2,
1821 cltv_expiry_delta: 0,
1822 htlc_minimum_msat: 200_000_000,
1823 htlc_maximum_msat: OptionalField::Absent,
1825 fee_proportional_millionths: 0,
1826 excess_data: Vec::new()
1829 // Second hop only allows to forward 199_999_999 at most, thus not allowing the first hop to
1831 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
1832 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1833 short_channel_id: 4,
1836 cltv_expiry_delta: 0,
1837 htlc_minimum_msat: 0,
1838 htlc_maximum_msat: OptionalField::Present(199_999_999),
1840 fee_proportional_millionths: 0,
1841 excess_data: Vec::new()
1844 // Not possible to send 199_999_999, because the minimum on channel=2 is 200_000_000.
1845 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)) {
1846 assert_eq!(err, "Failed to find a path to the given destination");
1847 } else { panic!(); }
1849 // Lift the restriction on the first hop.
1850 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
1851 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1852 short_channel_id: 2,
1855 cltv_expiry_delta: 0,
1856 htlc_minimum_msat: 0,
1857 htlc_maximum_msat: OptionalField::Absent,
1859 fee_proportional_millionths: 0,
1860 excess_data: Vec::new()
1863 // A payment above the minimum should pass
1864 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();
1865 assert_eq!(route.paths[0].len(), 2);
1869 fn htlc_minimum_overpay_test() {
1870 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
1871 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
1873 // A route to node#2 via two paths.
1874 // One path allows transferring 35-40 sats, another one also allows 35-40 sats.
1875 // Thus, they can't send 60 without overpaying.
1876 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
1877 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1878 short_channel_id: 2,
1881 cltv_expiry_delta: 0,
1882 htlc_minimum_msat: 35_000,
1883 htlc_maximum_msat: OptionalField::Present(40_000),
1885 fee_proportional_millionths: 0,
1886 excess_data: Vec::new()
1888 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
1889 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1890 short_channel_id: 12,
1893 cltv_expiry_delta: 0,
1894 htlc_minimum_msat: 35_000,
1895 htlc_maximum_msat: OptionalField::Present(40_000),
1897 fee_proportional_millionths: 0,
1898 excess_data: Vec::new()
1902 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
1903 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1904 short_channel_id: 13,
1907 cltv_expiry_delta: 0,
1908 htlc_minimum_msat: 0,
1909 htlc_maximum_msat: OptionalField::Absent,
1911 fee_proportional_millionths: 0,
1912 excess_data: Vec::new()
1914 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
1915 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1916 short_channel_id: 4,
1919 cltv_expiry_delta: 0,
1920 htlc_minimum_msat: 0,
1921 htlc_maximum_msat: OptionalField::Absent,
1923 fee_proportional_millionths: 0,
1924 excess_data: Vec::new()
1927 // Disable other paths
1928 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
1929 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1930 short_channel_id: 1,
1932 flags: 2, // to disable
1933 cltv_expiry_delta: 0,
1934 htlc_minimum_msat: 0,
1935 htlc_maximum_msat: OptionalField::Absent,
1937 fee_proportional_millionths: 0,
1938 excess_data: Vec::new()
1941 let route = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2],
1942 Some(InvoiceFeatures::known()), None, &Vec::new(), 60_000, 42, Arc::clone(&logger)).unwrap();
1943 // Overpay fees to hit htlc_minimum_msat.
1944 let overpaid_fees = route.paths[0][0].fee_msat + route.paths[1][0].fee_msat;
1945 // TODO: this could be better balanced to overpay 10k and not 15k.
1946 assert_eq!(overpaid_fees, 15_000);
1948 // Now, test that if there are 2 paths, a "cheaper" by fee path wouldn't be prioritized
1949 // while taking even more fee to match htlc_minimum_msat.
1950 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
1951 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1952 short_channel_id: 12,
1955 cltv_expiry_delta: 0,
1956 htlc_minimum_msat: 65_000,
1957 htlc_maximum_msat: OptionalField::Present(80_000),
1959 fee_proportional_millionths: 0,
1960 excess_data: Vec::new()
1962 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
1963 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1964 short_channel_id: 2,
1967 cltv_expiry_delta: 0,
1968 htlc_minimum_msat: 0,
1969 htlc_maximum_msat: OptionalField::Absent,
1971 fee_proportional_millionths: 0,
1972 excess_data: Vec::new()
1974 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
1975 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1976 short_channel_id: 4,
1979 cltv_expiry_delta: 0,
1980 htlc_minimum_msat: 0,
1981 htlc_maximum_msat: OptionalField::Absent,
1983 fee_proportional_millionths: 100_000,
1984 excess_data: Vec::new()
1987 let route = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2],
1988 Some(InvoiceFeatures::known()), None, &Vec::new(), 60_000, 42, Arc::clone(&logger)).unwrap();
1989 // Fine to overpay for htlc_minimum_msat if it allows us to save fee.
1990 assert_eq!(route.paths.len(), 1);
1991 assert_eq!(route.paths[0][0].short_channel_id, 12);
1992 let fees = route.paths[0][0].fee_msat;
1993 assert_eq!(fees, 5_000);
1995 let route = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2],
1996 Some(InvoiceFeatures::known()), None, &Vec::new(), 50_000, 42, Arc::clone(&logger)).unwrap();
1997 // Not fine to overpay for htlc_minimum_msat if it requires paying more than fee on
1998 // the other channel.
1999 assert_eq!(route.paths.len(), 1);
2000 assert_eq!(route.paths[0][0].short_channel_id, 2);
2001 let fees = route.paths[0][0].fee_msat;
2002 assert_eq!(fees, 5_000);
2006 fn disable_channels_test() {
2007 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
2008 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
2010 // // Disable channels 4 and 12 by flags=2
2011 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
2012 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2013 short_channel_id: 4,
2015 flags: 2, // to disable
2016 cltv_expiry_delta: 0,
2017 htlc_minimum_msat: 0,
2018 htlc_maximum_msat: OptionalField::Absent,
2020 fee_proportional_millionths: 0,
2021 excess_data: Vec::new()
2023 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2024 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2025 short_channel_id: 12,
2027 flags: 2, // to disable
2028 cltv_expiry_delta: 0,
2029 htlc_minimum_msat: 0,
2030 htlc_maximum_msat: OptionalField::Absent,
2032 fee_proportional_millionths: 0,
2033 excess_data: Vec::new()
2036 // If all the channels require some features we don't understand, route should fail
2037 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)) {
2038 assert_eq!(err, "Failed to find a path to the given destination");
2039 } else { panic!(); }
2041 // If we specify a channel to node7, that overrides our local channel view and that gets used
2042 let our_chans = vec![get_channel_details(Some(42), nodes[7].clone(), InitFeatures::from_le_bytes(vec![0b11]), 250_000_000)];
2043 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();
2044 assert_eq!(route.paths[0].len(), 2);
2046 assert_eq!(route.paths[0][0].pubkey, nodes[7]);
2047 assert_eq!(route.paths[0][0].short_channel_id, 42);
2048 assert_eq!(route.paths[0][0].fee_msat, 200);
2049 assert_eq!(route.paths[0][0].cltv_expiry_delta, (13 << 8) | 1);
2050 assert_eq!(route.paths[0][0].node_features.le_flags(), &vec![0b11]); // it should also override our view of their features
2051 assert_eq!(route.paths[0][0].channel_features.le_flags(), &Vec::<u8>::new()); // No feature flags will meet the relevant-to-channel conversion
2053 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2054 assert_eq!(route.paths[0][1].short_channel_id, 13);
2055 assert_eq!(route.paths[0][1].fee_msat, 100);
2056 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
2057 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2058 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(13));
2062 fn disable_node_test() {
2063 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
2064 let (_, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
2066 // Disable nodes 1, 2, and 8 by requiring unknown feature bits
2067 let unknown_features = NodeFeatures::known().set_unknown_feature_required();
2068 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[0], unknown_features.clone(), 1);
2069 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[1], unknown_features.clone(), 1);
2070 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[7], unknown_features.clone(), 1);
2072 // If all nodes require some features we don't understand, route should fail
2073 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)) {
2074 assert_eq!(err, "Failed to find a path to the given destination");
2075 } else { panic!(); }
2077 // If we specify a channel to node7, that overrides our local channel view and that gets used
2078 let our_chans = vec![get_channel_details(Some(42), nodes[7].clone(), InitFeatures::from_le_bytes(vec![0b11]), 250_000_000)];
2079 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();
2080 assert_eq!(route.paths[0].len(), 2);
2082 assert_eq!(route.paths[0][0].pubkey, nodes[7]);
2083 assert_eq!(route.paths[0][0].short_channel_id, 42);
2084 assert_eq!(route.paths[0][0].fee_msat, 200);
2085 assert_eq!(route.paths[0][0].cltv_expiry_delta, (13 << 8) | 1);
2086 assert_eq!(route.paths[0][0].node_features.le_flags(), &vec![0b11]); // it should also override our view of their features
2087 assert_eq!(route.paths[0][0].channel_features.le_flags(), &Vec::<u8>::new()); // No feature flags will meet the relevant-to-channel conversion
2089 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2090 assert_eq!(route.paths[0][1].short_channel_id, 13);
2091 assert_eq!(route.paths[0][1].fee_msat, 100);
2092 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
2093 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2094 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(13));
2096 // Note that we don't test disabling node 3 and failing to route to it, as we (somewhat
2097 // naively) assume that the user checked the feature bits on the invoice, which override
2098 // the node_announcement.
2102 fn our_chans_test() {
2103 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
2104 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
2106 // Route to 1 via 2 and 3 because our channel to 1 is disabled
2107 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();
2108 assert_eq!(route.paths[0].len(), 3);
2110 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
2111 assert_eq!(route.paths[0][0].short_channel_id, 2);
2112 assert_eq!(route.paths[0][0].fee_msat, 200);
2113 assert_eq!(route.paths[0][0].cltv_expiry_delta, (4 << 8) | 1);
2114 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
2115 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
2117 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2118 assert_eq!(route.paths[0][1].short_channel_id, 4);
2119 assert_eq!(route.paths[0][1].fee_msat, 100);
2120 assert_eq!(route.paths[0][1].cltv_expiry_delta, (3 << 8) | 2);
2121 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2122 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
2124 assert_eq!(route.paths[0][2].pubkey, nodes[0]);
2125 assert_eq!(route.paths[0][2].short_channel_id, 3);
2126 assert_eq!(route.paths[0][2].fee_msat, 100);
2127 assert_eq!(route.paths[0][2].cltv_expiry_delta, 42);
2128 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(1));
2129 assert_eq!(route.paths[0][2].channel_features.le_flags(), &id_to_feature_flags(3));
2131 // If we specify a channel to node7, that overrides our local channel view and that gets used
2132 let our_chans = vec![get_channel_details(Some(42), nodes[7].clone(), InitFeatures::from_le_bytes(vec![0b11]), 250_000_000)];
2133 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();
2134 assert_eq!(route.paths[0].len(), 2);
2136 assert_eq!(route.paths[0][0].pubkey, nodes[7]);
2137 assert_eq!(route.paths[0][0].short_channel_id, 42);
2138 assert_eq!(route.paths[0][0].fee_msat, 200);
2139 assert_eq!(route.paths[0][0].cltv_expiry_delta, (13 << 8) | 1);
2140 assert_eq!(route.paths[0][0].node_features.le_flags(), &vec![0b11]);
2141 assert_eq!(route.paths[0][0].channel_features.le_flags(), &Vec::<u8>::new()); // No feature flags will meet the relevant-to-channel conversion
2143 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2144 assert_eq!(route.paths[0][1].short_channel_id, 13);
2145 assert_eq!(route.paths[0][1].fee_msat, 100);
2146 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
2147 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2148 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(13));
2151 fn last_hops(nodes: &Vec<PublicKey>) -> Vec<RouteHint> {
2152 let zero_fees = RoutingFees {
2154 proportional_millionths: 0,
2156 vec![RouteHint(vec![RouteHintHop {
2157 src_node_id: nodes[3].clone(),
2158 short_channel_id: 8,
2160 cltv_expiry_delta: (8 << 8) | 1,
2161 htlc_minimum_msat: None,
2162 htlc_maximum_msat: None,
2164 ]), RouteHint(vec![RouteHintHop {
2165 src_node_id: nodes[4].clone(),
2166 short_channel_id: 9,
2169 proportional_millionths: 0,
2171 cltv_expiry_delta: (9 << 8) | 1,
2172 htlc_minimum_msat: None,
2173 htlc_maximum_msat: None,
2174 }]), RouteHint(vec![RouteHintHop {
2175 src_node_id: nodes[5].clone(),
2176 short_channel_id: 10,
2178 cltv_expiry_delta: (10 << 8) | 1,
2179 htlc_minimum_msat: None,
2180 htlc_maximum_msat: None,
2184 fn last_hops_multi_private_channels(nodes: &Vec<PublicKey>) -> Vec<RouteHint> {
2185 let zero_fees = RoutingFees {
2187 proportional_millionths: 0,
2189 vec![RouteHint(vec![RouteHintHop {
2190 src_node_id: nodes[2].clone(),
2191 short_channel_id: 5,
2194 proportional_millionths: 0,
2196 cltv_expiry_delta: (5 << 8) | 1,
2197 htlc_minimum_msat: None,
2198 htlc_maximum_msat: None,
2200 src_node_id: nodes[3].clone(),
2201 short_channel_id: 8,
2203 cltv_expiry_delta: (8 << 8) | 1,
2204 htlc_minimum_msat: None,
2205 htlc_maximum_msat: None,
2207 ]), RouteHint(vec![RouteHintHop {
2208 src_node_id: nodes[4].clone(),
2209 short_channel_id: 9,
2212 proportional_millionths: 0,
2214 cltv_expiry_delta: (9 << 8) | 1,
2215 htlc_minimum_msat: None,
2216 htlc_maximum_msat: None,
2217 }]), RouteHint(vec![RouteHintHop {
2218 src_node_id: nodes[5].clone(),
2219 short_channel_id: 10,
2221 cltv_expiry_delta: (10 << 8) | 1,
2222 htlc_minimum_msat: None,
2223 htlc_maximum_msat: None,
2228 fn partial_route_hint_test() {
2229 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
2230 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
2232 // Simple test across 2, 3, 5, and 4 via a last_hop channel
2233 // Tests the behaviour when the RouteHint contains a suboptimal hop.
2234 // RouteHint may be partially used by the algo to build the best path.
2236 // First check that last hop can't have its source as the payee.
2237 let invalid_last_hop = RouteHint(vec![RouteHintHop {
2238 src_node_id: nodes[6],
2239 short_channel_id: 8,
2242 proportional_millionths: 0,
2244 cltv_expiry_delta: (8 << 8) | 1,
2245 htlc_minimum_msat: None,
2246 htlc_maximum_msat: None,
2249 let mut invalid_last_hops = last_hops_multi_private_channels(&nodes);
2250 invalid_last_hops.push(invalid_last_hop);
2252 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)) {
2253 assert_eq!(err, "Last hop cannot have a payee as a source.");
2254 } else { panic!(); }
2257 let route = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[6], None, None, &last_hops_multi_private_channels(&nodes).iter().collect::<Vec<_>>(), 100, 42, Arc::clone(&logger)).unwrap();
2258 assert_eq!(route.paths[0].len(), 5);
2260 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
2261 assert_eq!(route.paths[0][0].short_channel_id, 2);
2262 assert_eq!(route.paths[0][0].fee_msat, 100);
2263 assert_eq!(route.paths[0][0].cltv_expiry_delta, (4 << 8) | 1);
2264 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
2265 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
2267 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2268 assert_eq!(route.paths[0][1].short_channel_id, 4);
2269 assert_eq!(route.paths[0][1].fee_msat, 0);
2270 assert_eq!(route.paths[0][1].cltv_expiry_delta, (6 << 8) | 1);
2271 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2272 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
2274 assert_eq!(route.paths[0][2].pubkey, nodes[4]);
2275 assert_eq!(route.paths[0][2].short_channel_id, 6);
2276 assert_eq!(route.paths[0][2].fee_msat, 0);
2277 assert_eq!(route.paths[0][2].cltv_expiry_delta, (11 << 8) | 1);
2278 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(5));
2279 assert_eq!(route.paths[0][2].channel_features.le_flags(), &id_to_feature_flags(6));
2281 assert_eq!(route.paths[0][3].pubkey, nodes[3]);
2282 assert_eq!(route.paths[0][3].short_channel_id, 11);
2283 assert_eq!(route.paths[0][3].fee_msat, 0);
2284 assert_eq!(route.paths[0][3].cltv_expiry_delta, (8 << 8) | 1);
2285 // If we have a peer in the node map, we'll use their features here since we don't have
2286 // a way of figuring out their features from the invoice:
2287 assert_eq!(route.paths[0][3].node_features.le_flags(), &id_to_feature_flags(4));
2288 assert_eq!(route.paths[0][3].channel_features.le_flags(), &id_to_feature_flags(11));
2290 assert_eq!(route.paths[0][4].pubkey, nodes[6]);
2291 assert_eq!(route.paths[0][4].short_channel_id, 8);
2292 assert_eq!(route.paths[0][4].fee_msat, 100);
2293 assert_eq!(route.paths[0][4].cltv_expiry_delta, 42);
2294 assert_eq!(route.paths[0][4].node_features.le_flags(), &Vec::<u8>::new()); // We dont pass flags in from invoices yet
2295 assert_eq!(route.paths[0][4].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
2298 fn empty_last_hop(nodes: &Vec<PublicKey>) -> Vec<RouteHint> {
2299 let zero_fees = RoutingFees {
2301 proportional_millionths: 0,
2303 vec![RouteHint(vec![RouteHintHop {
2304 src_node_id: nodes[3].clone(),
2305 short_channel_id: 8,
2307 cltv_expiry_delta: (8 << 8) | 1,
2308 htlc_minimum_msat: None,
2309 htlc_maximum_msat: None,
2310 }]), RouteHint(vec![
2312 ]), RouteHint(vec![RouteHintHop {
2313 src_node_id: nodes[5].clone(),
2314 short_channel_id: 10,
2316 cltv_expiry_delta: (10 << 8) | 1,
2317 htlc_minimum_msat: None,
2318 htlc_maximum_msat: None,
2323 fn ignores_empty_last_hops_test() {
2324 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
2325 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
2327 // Test handling of an empty RouteHint passed in Invoice.
2329 let route = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[6], None, None, &empty_last_hop(&nodes).iter().collect::<Vec<_>>(), 100, 42, Arc::clone(&logger)).unwrap();
2330 assert_eq!(route.paths[0].len(), 5);
2332 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
2333 assert_eq!(route.paths[0][0].short_channel_id, 2);
2334 assert_eq!(route.paths[0][0].fee_msat, 100);
2335 assert_eq!(route.paths[0][0].cltv_expiry_delta, (4 << 8) | 1);
2336 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
2337 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
2339 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2340 assert_eq!(route.paths[0][1].short_channel_id, 4);
2341 assert_eq!(route.paths[0][1].fee_msat, 0);
2342 assert_eq!(route.paths[0][1].cltv_expiry_delta, (6 << 8) | 1);
2343 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2344 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
2346 assert_eq!(route.paths[0][2].pubkey, nodes[4]);
2347 assert_eq!(route.paths[0][2].short_channel_id, 6);
2348 assert_eq!(route.paths[0][2].fee_msat, 0);
2349 assert_eq!(route.paths[0][2].cltv_expiry_delta, (11 << 8) | 1);
2350 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(5));
2351 assert_eq!(route.paths[0][2].channel_features.le_flags(), &id_to_feature_flags(6));
2353 assert_eq!(route.paths[0][3].pubkey, nodes[3]);
2354 assert_eq!(route.paths[0][3].short_channel_id, 11);
2355 assert_eq!(route.paths[0][3].fee_msat, 0);
2356 assert_eq!(route.paths[0][3].cltv_expiry_delta, (8 << 8) | 1);
2357 // If we have a peer in the node map, we'll use their features here since we don't have
2358 // a way of figuring out their features from the invoice:
2359 assert_eq!(route.paths[0][3].node_features.le_flags(), &id_to_feature_flags(4));
2360 assert_eq!(route.paths[0][3].channel_features.le_flags(), &id_to_feature_flags(11));
2362 assert_eq!(route.paths[0][4].pubkey, nodes[6]);
2363 assert_eq!(route.paths[0][4].short_channel_id, 8);
2364 assert_eq!(route.paths[0][4].fee_msat, 100);
2365 assert_eq!(route.paths[0][4].cltv_expiry_delta, 42);
2366 assert_eq!(route.paths[0][4].node_features.le_flags(), &Vec::<u8>::new()); // We dont pass flags in from invoices yet
2367 assert_eq!(route.paths[0][4].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
2370 fn multi_hint_last_hops(nodes: &Vec<PublicKey>) -> Vec<RouteHint> {
2371 let zero_fees = RoutingFees {
2373 proportional_millionths: 0,
2375 vec![RouteHint(vec![RouteHintHop {
2376 src_node_id: nodes[2].clone(),
2377 short_channel_id: 5,
2380 proportional_millionths: 0,
2382 cltv_expiry_delta: (5 << 8) | 1,
2383 htlc_minimum_msat: None,
2384 htlc_maximum_msat: None,
2386 src_node_id: nodes[3].clone(),
2387 short_channel_id: 8,
2389 cltv_expiry_delta: (8 << 8) | 1,
2390 htlc_minimum_msat: None,
2391 htlc_maximum_msat: None,
2392 }]), RouteHint(vec![RouteHintHop {
2393 src_node_id: nodes[5].clone(),
2394 short_channel_id: 10,
2396 cltv_expiry_delta: (10 << 8) | 1,
2397 htlc_minimum_msat: None,
2398 htlc_maximum_msat: None,
2403 fn multi_hint_last_hops_test() {
2404 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
2405 let (_, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
2406 // Test through channels 2, 3, 5, 8.
2407 // Test shows that multiple hop hints are considered.
2409 // Disabling channels 6 & 7 by flags=2
2410 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
2411 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2412 short_channel_id: 6,
2414 flags: 2, // to disable
2415 cltv_expiry_delta: 0,
2416 htlc_minimum_msat: 0,
2417 htlc_maximum_msat: OptionalField::Absent,
2419 fee_proportional_millionths: 0,
2420 excess_data: Vec::new()
2422 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
2423 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2424 short_channel_id: 7,
2426 flags: 2, // to disable
2427 cltv_expiry_delta: 0,
2428 htlc_minimum_msat: 0,
2429 htlc_maximum_msat: OptionalField::Absent,
2431 fee_proportional_millionths: 0,
2432 excess_data: Vec::new()
2435 let route = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[6], None, None, &multi_hint_last_hops(&nodes).iter().collect::<Vec<_>>(), 100, 42, Arc::clone(&logger)).unwrap();
2436 assert_eq!(route.paths[0].len(), 4);
2438 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
2439 assert_eq!(route.paths[0][0].short_channel_id, 2);
2440 assert_eq!(route.paths[0][0].fee_msat, 200);
2441 assert_eq!(route.paths[0][0].cltv_expiry_delta, 1025);
2442 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
2443 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
2445 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2446 assert_eq!(route.paths[0][1].short_channel_id, 4);
2447 assert_eq!(route.paths[0][1].fee_msat, 100);
2448 assert_eq!(route.paths[0][1].cltv_expiry_delta, 1281);
2449 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2450 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
2452 assert_eq!(route.paths[0][2].pubkey, nodes[3]);
2453 assert_eq!(route.paths[0][2].short_channel_id, 5);
2454 assert_eq!(route.paths[0][2].fee_msat, 0);
2455 assert_eq!(route.paths[0][2].cltv_expiry_delta, 2049);
2456 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(4));
2457 assert_eq!(route.paths[0][2].channel_features.le_flags(), &Vec::<u8>::new());
2459 assert_eq!(route.paths[0][3].pubkey, nodes[6]);
2460 assert_eq!(route.paths[0][3].short_channel_id, 8);
2461 assert_eq!(route.paths[0][3].fee_msat, 100);
2462 assert_eq!(route.paths[0][3].cltv_expiry_delta, 42);
2463 assert_eq!(route.paths[0][3].node_features.le_flags(), &Vec::<u8>::new()); // We dont pass flags in from invoices yet
2464 assert_eq!(route.paths[0][3].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
2467 fn last_hops_with_public_channel(nodes: &Vec<PublicKey>) -> Vec<RouteHint> {
2468 let zero_fees = RoutingFees {
2470 proportional_millionths: 0,
2472 vec![RouteHint(vec![RouteHintHop {
2473 src_node_id: nodes[4].clone(),
2474 short_channel_id: 11,
2476 cltv_expiry_delta: (11 << 8) | 1,
2477 htlc_minimum_msat: None,
2478 htlc_maximum_msat: None,
2480 src_node_id: nodes[3].clone(),
2481 short_channel_id: 8,
2483 cltv_expiry_delta: (8 << 8) | 1,
2484 htlc_minimum_msat: None,
2485 htlc_maximum_msat: None,
2486 }]), RouteHint(vec![RouteHintHop {
2487 src_node_id: nodes[4].clone(),
2488 short_channel_id: 9,
2491 proportional_millionths: 0,
2493 cltv_expiry_delta: (9 << 8) | 1,
2494 htlc_minimum_msat: None,
2495 htlc_maximum_msat: None,
2496 }]), RouteHint(vec![RouteHintHop {
2497 src_node_id: nodes[5].clone(),
2498 short_channel_id: 10,
2500 cltv_expiry_delta: (10 << 8) | 1,
2501 htlc_minimum_msat: None,
2502 htlc_maximum_msat: None,
2507 fn last_hops_with_public_channel_test() {
2508 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
2509 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
2510 // This test shows that public routes can be present in the invoice
2511 // which would be handled in the same manner.
2513 let route = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[6], None, None, &last_hops_with_public_channel(&nodes).iter().collect::<Vec<_>>(), 100, 42, Arc::clone(&logger)).unwrap();
2514 assert_eq!(route.paths[0].len(), 5);
2516 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
2517 assert_eq!(route.paths[0][0].short_channel_id, 2);
2518 assert_eq!(route.paths[0][0].fee_msat, 100);
2519 assert_eq!(route.paths[0][0].cltv_expiry_delta, (4 << 8) | 1);
2520 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
2521 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
2523 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2524 assert_eq!(route.paths[0][1].short_channel_id, 4);
2525 assert_eq!(route.paths[0][1].fee_msat, 0);
2526 assert_eq!(route.paths[0][1].cltv_expiry_delta, (6 << 8) | 1);
2527 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2528 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
2530 assert_eq!(route.paths[0][2].pubkey, nodes[4]);
2531 assert_eq!(route.paths[0][2].short_channel_id, 6);
2532 assert_eq!(route.paths[0][2].fee_msat, 0);
2533 assert_eq!(route.paths[0][2].cltv_expiry_delta, (11 << 8) | 1);
2534 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(5));
2535 assert_eq!(route.paths[0][2].channel_features.le_flags(), &id_to_feature_flags(6));
2537 assert_eq!(route.paths[0][3].pubkey, nodes[3]);
2538 assert_eq!(route.paths[0][3].short_channel_id, 11);
2539 assert_eq!(route.paths[0][3].fee_msat, 0);
2540 assert_eq!(route.paths[0][3].cltv_expiry_delta, (8 << 8) | 1);
2541 // If we have a peer in the node map, we'll use their features here since we don't have
2542 // a way of figuring out their features from the invoice:
2543 assert_eq!(route.paths[0][3].node_features.le_flags(), &id_to_feature_flags(4));
2544 assert_eq!(route.paths[0][3].channel_features.le_flags(), &Vec::<u8>::new());
2546 assert_eq!(route.paths[0][4].pubkey, nodes[6]);
2547 assert_eq!(route.paths[0][4].short_channel_id, 8);
2548 assert_eq!(route.paths[0][4].fee_msat, 100);
2549 assert_eq!(route.paths[0][4].cltv_expiry_delta, 42);
2550 assert_eq!(route.paths[0][4].node_features.le_flags(), &Vec::<u8>::new()); // We dont pass flags in from invoices yet
2551 assert_eq!(route.paths[0][4].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
2555 fn our_chans_last_hop_connect_test() {
2556 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
2557 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
2559 // Simple test with outbound channel to 4 to test that last_hops and first_hops connect
2560 let our_chans = vec![get_channel_details(Some(42), nodes[3].clone(), InitFeatures::from_le_bytes(vec![0b11]), 250_000_000)];
2561 let mut last_hops = last_hops(&nodes);
2562 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();
2563 assert_eq!(route.paths[0].len(), 2);
2565 assert_eq!(route.paths[0][0].pubkey, nodes[3]);
2566 assert_eq!(route.paths[0][0].short_channel_id, 42);
2567 assert_eq!(route.paths[0][0].fee_msat, 0);
2568 assert_eq!(route.paths[0][0].cltv_expiry_delta, (8 << 8) | 1);
2569 assert_eq!(route.paths[0][0].node_features.le_flags(), &vec![0b11]);
2570 assert_eq!(route.paths[0][0].channel_features.le_flags(), &Vec::<u8>::new()); // No feature flags will meet the relevant-to-channel conversion
2572 assert_eq!(route.paths[0][1].pubkey, nodes[6]);
2573 assert_eq!(route.paths[0][1].short_channel_id, 8);
2574 assert_eq!(route.paths[0][1].fee_msat, 100);
2575 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
2576 assert_eq!(route.paths[0][1].node_features.le_flags(), &Vec::<u8>::new()); // We dont pass flags in from invoices yet
2577 assert_eq!(route.paths[0][1].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
2579 last_hops[0].0[0].fees.base_msat = 1000;
2581 // Revert to via 6 as the fee on 8 goes up
2582 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();
2583 assert_eq!(route.paths[0].len(), 4);
2585 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
2586 assert_eq!(route.paths[0][0].short_channel_id, 2);
2587 assert_eq!(route.paths[0][0].fee_msat, 200); // fee increased as its % of value transferred across node
2588 assert_eq!(route.paths[0][0].cltv_expiry_delta, (4 << 8) | 1);
2589 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
2590 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
2592 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2593 assert_eq!(route.paths[0][1].short_channel_id, 4);
2594 assert_eq!(route.paths[0][1].fee_msat, 100);
2595 assert_eq!(route.paths[0][1].cltv_expiry_delta, (7 << 8) | 1);
2596 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2597 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
2599 assert_eq!(route.paths[0][2].pubkey, nodes[5]);
2600 assert_eq!(route.paths[0][2].short_channel_id, 7);
2601 assert_eq!(route.paths[0][2].fee_msat, 0);
2602 assert_eq!(route.paths[0][2].cltv_expiry_delta, (10 << 8) | 1);
2603 // If we have a peer in the node map, we'll use their features here since we don't have
2604 // a way of figuring out their features from the invoice:
2605 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(6));
2606 assert_eq!(route.paths[0][2].channel_features.le_flags(), &id_to_feature_flags(7));
2608 assert_eq!(route.paths[0][3].pubkey, nodes[6]);
2609 assert_eq!(route.paths[0][3].short_channel_id, 10);
2610 assert_eq!(route.paths[0][3].fee_msat, 100);
2611 assert_eq!(route.paths[0][3].cltv_expiry_delta, 42);
2612 assert_eq!(route.paths[0][3].node_features.le_flags(), &Vec::<u8>::new()); // We dont pass flags in from invoices yet
2613 assert_eq!(route.paths[0][3].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
2615 // ...but still use 8 for larger payments as 6 has a variable feerate
2616 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();
2617 assert_eq!(route.paths[0].len(), 5);
2619 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
2620 assert_eq!(route.paths[0][0].short_channel_id, 2);
2621 assert_eq!(route.paths[0][0].fee_msat, 3000);
2622 assert_eq!(route.paths[0][0].cltv_expiry_delta, (4 << 8) | 1);
2623 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
2624 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
2626 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2627 assert_eq!(route.paths[0][1].short_channel_id, 4);
2628 assert_eq!(route.paths[0][1].fee_msat, 0);
2629 assert_eq!(route.paths[0][1].cltv_expiry_delta, (6 << 8) | 1);
2630 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2631 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
2633 assert_eq!(route.paths[0][2].pubkey, nodes[4]);
2634 assert_eq!(route.paths[0][2].short_channel_id, 6);
2635 assert_eq!(route.paths[0][2].fee_msat, 0);
2636 assert_eq!(route.paths[0][2].cltv_expiry_delta, (11 << 8) | 1);
2637 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(5));
2638 assert_eq!(route.paths[0][2].channel_features.le_flags(), &id_to_feature_flags(6));
2640 assert_eq!(route.paths[0][3].pubkey, nodes[3]);
2641 assert_eq!(route.paths[0][3].short_channel_id, 11);
2642 assert_eq!(route.paths[0][3].fee_msat, 1000);
2643 assert_eq!(route.paths[0][3].cltv_expiry_delta, (8 << 8) | 1);
2644 // If we have a peer in the node map, we'll use their features here since we don't have
2645 // a way of figuring out their features from the invoice:
2646 assert_eq!(route.paths[0][3].node_features.le_flags(), &id_to_feature_flags(4));
2647 assert_eq!(route.paths[0][3].channel_features.le_flags(), &id_to_feature_flags(11));
2649 assert_eq!(route.paths[0][4].pubkey, nodes[6]);
2650 assert_eq!(route.paths[0][4].short_channel_id, 8);
2651 assert_eq!(route.paths[0][4].fee_msat, 2000);
2652 assert_eq!(route.paths[0][4].cltv_expiry_delta, 42);
2653 assert_eq!(route.paths[0][4].node_features.le_flags(), &Vec::<u8>::new()); // We dont pass flags in from invoices yet
2654 assert_eq!(route.paths[0][4].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
2657 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> {
2658 let source_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&hex::decode(format!("{:02}", 41).repeat(32)).unwrap()[..]).unwrap());
2659 let middle_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&hex::decode(format!("{:02}", 42).repeat(32)).unwrap()[..]).unwrap());
2660 let target_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&hex::decode(format!("{:02}", 43).repeat(32)).unwrap()[..]).unwrap());
2662 // If we specify a channel to a middle hop, that overrides our local channel view and that gets used
2663 let last_hops = RouteHint(vec![RouteHintHop {
2664 src_node_id: middle_node_id,
2665 short_channel_id: 8,
2668 proportional_millionths: last_hop_fee_prop,
2670 cltv_expiry_delta: (8 << 8) | 1,
2671 htlc_minimum_msat: None,
2672 htlc_maximum_msat: last_hop_htlc_max,
2674 let our_chans = vec![get_channel_details(Some(42), middle_node_id, InitFeatures::from_le_bytes(vec![0b11]), outbound_capacity_msat)];
2675 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()))
2679 fn unannounced_path_test() {
2680 // We should be able to send a payment to a destination without any help of a routing graph
2681 // if we have a channel with a common counterparty that appears in the first and last hop
2683 let route = do_unannounced_path_test(None, 1, 2000000, 1000000).unwrap();
2685 let middle_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&hex::decode(format!("{:02}", 42).repeat(32)).unwrap()[..]).unwrap());
2686 let target_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&hex::decode(format!("{:02}", 43).repeat(32)).unwrap()[..]).unwrap());
2687 assert_eq!(route.paths[0].len(), 2);
2689 assert_eq!(route.paths[0][0].pubkey, middle_node_id);
2690 assert_eq!(route.paths[0][0].short_channel_id, 42);
2691 assert_eq!(route.paths[0][0].fee_msat, 1001);
2692 assert_eq!(route.paths[0][0].cltv_expiry_delta, (8 << 8) | 1);
2693 assert_eq!(route.paths[0][0].node_features.le_flags(), &[0b11]);
2694 assert_eq!(route.paths[0][0].channel_features.le_flags(), &[0; 0]); // We can't learn any flags from invoices, sadly
2696 assert_eq!(route.paths[0][1].pubkey, target_node_id);
2697 assert_eq!(route.paths[0][1].short_channel_id, 8);
2698 assert_eq!(route.paths[0][1].fee_msat, 1000000);
2699 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
2700 assert_eq!(route.paths[0][1].node_features.le_flags(), &[0; 0]); // We dont pass flags in from invoices yet
2701 assert_eq!(route.paths[0][1].channel_features.le_flags(), &[0; 0]); // We can't learn any flags from invoices, sadly
2705 fn overflow_unannounced_path_test_liquidity_underflow() {
2706 // Previously, when we had a last-hop hint connected directly to a first-hop channel, where
2707 // the last-hop had a fee which overflowed a u64, we'd panic.
2708 // This was due to us adding the first-hop from us unconditionally, causing us to think
2709 // we'd built a path (as our node is in the "best candidate" set), when we had not.
2710 // In this test, we previously hit a subtraction underflow due to having less available
2711 // liquidity at the last hop than 0.
2712 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());
2716 fn overflow_unannounced_path_test_feerate_overflow() {
2717 // This tests for the same case as above, except instead of hitting a subtraction
2718 // underflow, we hit a case where the fee charged at a hop overflowed.
2719 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());
2723 fn available_amount_while_routing_test() {
2724 // Tests whether we choose the correct available channel amount while routing.
2726 let (secp_ctx, mut net_graph_msg_handler, chain_monitor, logger) = build_graph();
2727 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
2729 // We will use a simple single-path route from
2730 // our node to node2 via node0: channels {1, 3}.
2732 // First disable all other paths.
2733 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2734 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2735 short_channel_id: 2,
2738 cltv_expiry_delta: 0,
2739 htlc_minimum_msat: 0,
2740 htlc_maximum_msat: OptionalField::Present(100_000),
2742 fee_proportional_millionths: 0,
2743 excess_data: Vec::new()
2745 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2746 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2747 short_channel_id: 12,
2750 cltv_expiry_delta: 0,
2751 htlc_minimum_msat: 0,
2752 htlc_maximum_msat: OptionalField::Present(100_000),
2754 fee_proportional_millionths: 0,
2755 excess_data: Vec::new()
2758 // Make the first channel (#1) very permissive,
2759 // and we will be testing all limits on the second channel.
2760 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2761 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2762 short_channel_id: 1,
2765 cltv_expiry_delta: 0,
2766 htlc_minimum_msat: 0,
2767 htlc_maximum_msat: OptionalField::Present(1_000_000_000),
2769 fee_proportional_millionths: 0,
2770 excess_data: Vec::new()
2773 // First, let's see if routing works if we have absolutely no idea about the available amount.
2774 // In this case, it should be set to 250_000 sats.
2775 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
2776 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2777 short_channel_id: 3,
2780 cltv_expiry_delta: 0,
2781 htlc_minimum_msat: 0,
2782 htlc_maximum_msat: OptionalField::Absent,
2784 fee_proportional_millionths: 0,
2785 excess_data: Vec::new()
2789 // Attempt to route more than available results in a failure.
2790 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2],
2791 Some(InvoiceFeatures::known()), None, &Vec::new(), 250_000_001, 42, Arc::clone(&logger)) {
2792 assert_eq!(err, "Failed to find a sufficient route to the given destination");
2793 } else { panic!(); }
2797 // Now, attempt to route an exact amount we have should be fine.
2798 let route = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2],
2799 Some(InvoiceFeatures::known()), None, &Vec::new(), 250_000_000, 42, Arc::clone(&logger)).unwrap();
2800 assert_eq!(route.paths.len(), 1);
2801 let path = route.paths.last().unwrap();
2802 assert_eq!(path.len(), 2);
2803 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
2804 assert_eq!(path.last().unwrap().fee_msat, 250_000_000);
2807 // Check that setting outbound_capacity_msat in first_hops limits the channels.
2808 // Disable channel #1 and use another first hop.
2809 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2810 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2811 short_channel_id: 1,
2814 cltv_expiry_delta: 0,
2815 htlc_minimum_msat: 0,
2816 htlc_maximum_msat: OptionalField::Present(1_000_000_000),
2818 fee_proportional_millionths: 0,
2819 excess_data: Vec::new()
2822 // Now, limit the first_hop by the outbound_capacity_msat of 200_000 sats.
2823 let our_chans = vec![get_channel_details(Some(42), nodes[0].clone(), InitFeatures::from_le_bytes(vec![0b11]), 200_000_000)];
2826 // Attempt to route more than available results in a failure.
2827 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2],
2828 Some(InvoiceFeatures::known()), Some(&our_chans.iter().collect::<Vec<_>>()), &Vec::new(), 200_000_001, 42, Arc::clone(&logger)) {
2829 assert_eq!(err, "Failed to find a sufficient route to the given destination");
2830 } else { panic!(); }
2834 // Now, attempt to route an exact amount we have should be fine.
2835 let route = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2],
2836 Some(InvoiceFeatures::known()), Some(&our_chans.iter().collect::<Vec<_>>()), &Vec::new(), 200_000_000, 42, Arc::clone(&logger)).unwrap();
2837 assert_eq!(route.paths.len(), 1);
2838 let path = route.paths.last().unwrap();
2839 assert_eq!(path.len(), 2);
2840 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
2841 assert_eq!(path.last().unwrap().fee_msat, 200_000_000);
2844 // Enable channel #1 back.
2845 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2846 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2847 short_channel_id: 1,
2850 cltv_expiry_delta: 0,
2851 htlc_minimum_msat: 0,
2852 htlc_maximum_msat: OptionalField::Present(1_000_000_000),
2854 fee_proportional_millionths: 0,
2855 excess_data: Vec::new()
2859 // Now let's see if routing works if we know only htlc_maximum_msat.
2860 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
2861 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2862 short_channel_id: 3,
2865 cltv_expiry_delta: 0,
2866 htlc_minimum_msat: 0,
2867 htlc_maximum_msat: OptionalField::Present(15_000),
2869 fee_proportional_millionths: 0,
2870 excess_data: Vec::new()
2874 // Attempt to route more than available results in a failure.
2875 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2],
2876 Some(InvoiceFeatures::known()), None, &Vec::new(), 15_001, 42, Arc::clone(&logger)) {
2877 assert_eq!(err, "Failed to find a sufficient route to the given destination");
2878 } else { panic!(); }
2882 // Now, attempt to route an exact amount we have should be fine.
2883 let route = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2],
2884 Some(InvoiceFeatures::known()), None, &Vec::new(), 15_000, 42, Arc::clone(&logger)).unwrap();
2885 assert_eq!(route.paths.len(), 1);
2886 let path = route.paths.last().unwrap();
2887 assert_eq!(path.len(), 2);
2888 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
2889 assert_eq!(path.last().unwrap().fee_msat, 15_000);
2892 // Now let's see if routing works if we know only capacity from the UTXO.
2894 // We can't change UTXO capacity on the fly, so we'll disable
2895 // the existing channel and add another one with the capacity we need.
2896 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
2897 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2898 short_channel_id: 3,
2901 cltv_expiry_delta: 0,
2902 htlc_minimum_msat: 0,
2903 htlc_maximum_msat: OptionalField::Absent,
2905 fee_proportional_millionths: 0,
2906 excess_data: Vec::new()
2909 let good_script = Builder::new().push_opcode(opcodes::all::OP_PUSHNUM_2)
2910 .push_slice(&PublicKey::from_secret_key(&secp_ctx, &privkeys[0]).serialize())
2911 .push_slice(&PublicKey::from_secret_key(&secp_ctx, &privkeys[2]).serialize())
2912 .push_opcode(opcodes::all::OP_PUSHNUM_2)
2913 .push_opcode(opcodes::all::OP_CHECKMULTISIG).into_script().to_v0_p2wsh();
2915 *chain_monitor.utxo_ret.lock().unwrap() = Ok(TxOut { value: 15, script_pubkey: good_script.clone() });
2916 net_graph_msg_handler.add_chain_access(Some(chain_monitor));
2918 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], &privkeys[2], ChannelFeatures::from_le_bytes(id_to_feature_flags(3)), 333);
2919 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
2920 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2921 short_channel_id: 333,
2924 cltv_expiry_delta: (3 << 8) | 1,
2925 htlc_minimum_msat: 0,
2926 htlc_maximum_msat: OptionalField::Absent,
2928 fee_proportional_millionths: 0,
2929 excess_data: Vec::new()
2931 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
2932 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2933 short_channel_id: 333,
2936 cltv_expiry_delta: (3 << 8) | 2,
2937 htlc_minimum_msat: 0,
2938 htlc_maximum_msat: OptionalField::Absent,
2940 fee_proportional_millionths: 0,
2941 excess_data: Vec::new()
2945 // Attempt to route more than available results in a failure.
2946 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2],
2947 Some(InvoiceFeatures::known()), None, &Vec::new(), 15_001, 42, Arc::clone(&logger)) {
2948 assert_eq!(err, "Failed to find a sufficient route to the given destination");
2949 } else { panic!(); }
2953 // Now, attempt to route an exact amount we have should be fine.
2954 let route = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2],
2955 Some(InvoiceFeatures::known()), None, &Vec::new(), 15_000, 42, Arc::clone(&logger)).unwrap();
2956 assert_eq!(route.paths.len(), 1);
2957 let path = route.paths.last().unwrap();
2958 assert_eq!(path.len(), 2);
2959 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
2960 assert_eq!(path.last().unwrap().fee_msat, 15_000);
2963 // Now let's see if routing chooses htlc_maximum_msat over UTXO capacity.
2964 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
2965 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2966 short_channel_id: 333,
2969 cltv_expiry_delta: 0,
2970 htlc_minimum_msat: 0,
2971 htlc_maximum_msat: OptionalField::Present(10_000),
2973 fee_proportional_millionths: 0,
2974 excess_data: Vec::new()
2978 // Attempt to route more than available results in a failure.
2979 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2],
2980 Some(InvoiceFeatures::known()), None, &Vec::new(), 10_001, 42, Arc::clone(&logger)) {
2981 assert_eq!(err, "Failed to find a sufficient route to the given destination");
2982 } else { panic!(); }
2986 // Now, attempt to route an exact amount we have should be fine.
2987 let route = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2],
2988 Some(InvoiceFeatures::known()), None, &Vec::new(), 10_000, 42, Arc::clone(&logger)).unwrap();
2989 assert_eq!(route.paths.len(), 1);
2990 let path = route.paths.last().unwrap();
2991 assert_eq!(path.len(), 2);
2992 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
2993 assert_eq!(path.last().unwrap().fee_msat, 10_000);
2998 fn available_liquidity_last_hop_test() {
2999 // Check that available liquidity properly limits the path even when only
3000 // one of the latter hops is limited.
3001 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
3002 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3004 // Path via {node7, node2, node4} is channels {12, 13, 6, 11}.
3005 // {12, 13, 11} have the capacities of 100, {6} has a capacity of 50.
3006 // Total capacity: 50 sats.
3008 // Disable other potential paths.
3009 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3010 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3011 short_channel_id: 2,
3014 cltv_expiry_delta: 0,
3015 htlc_minimum_msat: 0,
3016 htlc_maximum_msat: OptionalField::Present(100_000),
3018 fee_proportional_millionths: 0,
3019 excess_data: Vec::new()
3021 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3022 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3023 short_channel_id: 7,
3026 cltv_expiry_delta: 0,
3027 htlc_minimum_msat: 0,
3028 htlc_maximum_msat: OptionalField::Present(100_000),
3030 fee_proportional_millionths: 0,
3031 excess_data: Vec::new()
3036 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3037 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3038 short_channel_id: 12,
3041 cltv_expiry_delta: 0,
3042 htlc_minimum_msat: 0,
3043 htlc_maximum_msat: OptionalField::Present(100_000),
3045 fee_proportional_millionths: 0,
3046 excess_data: Vec::new()
3048 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
3049 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3050 short_channel_id: 13,
3053 cltv_expiry_delta: 0,
3054 htlc_minimum_msat: 0,
3055 htlc_maximum_msat: OptionalField::Present(100_000),
3057 fee_proportional_millionths: 0,
3058 excess_data: Vec::new()
3061 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3062 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3063 short_channel_id: 6,
3066 cltv_expiry_delta: 0,
3067 htlc_minimum_msat: 0,
3068 htlc_maximum_msat: OptionalField::Present(50_000),
3070 fee_proportional_millionths: 0,
3071 excess_data: Vec::new()
3073 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
3074 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3075 short_channel_id: 11,
3078 cltv_expiry_delta: 0,
3079 htlc_minimum_msat: 0,
3080 htlc_maximum_msat: OptionalField::Present(100_000),
3082 fee_proportional_millionths: 0,
3083 excess_data: Vec::new()
3086 // Attempt to route more than available results in a failure.
3087 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[3],
3088 Some(InvoiceFeatures::known()), None, &Vec::new(), 60_000, 42, Arc::clone(&logger)) {
3089 assert_eq!(err, "Failed to find a sufficient route to the given destination");
3090 } else { panic!(); }
3094 // Now, attempt to route 49 sats (just a bit below the capacity).
3095 let route = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[3],
3096 Some(InvoiceFeatures::known()), None, &Vec::new(), 49_000, 42, Arc::clone(&logger)).unwrap();
3097 assert_eq!(route.paths.len(), 1);
3098 let mut total_amount_paid_msat = 0;
3099 for path in &route.paths {
3100 assert_eq!(path.len(), 4);
3101 assert_eq!(path.last().unwrap().pubkey, nodes[3]);
3102 total_amount_paid_msat += path.last().unwrap().fee_msat;
3104 assert_eq!(total_amount_paid_msat, 49_000);
3108 // Attempt to route an exact amount is also fine
3109 let route = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[3],
3110 Some(InvoiceFeatures::known()), None, &Vec::new(), 50_000, 42, Arc::clone(&logger)).unwrap();
3111 assert_eq!(route.paths.len(), 1);
3112 let mut total_amount_paid_msat = 0;
3113 for path in &route.paths {
3114 assert_eq!(path.len(), 4);
3115 assert_eq!(path.last().unwrap().pubkey, nodes[3]);
3116 total_amount_paid_msat += path.last().unwrap().fee_msat;
3118 assert_eq!(total_amount_paid_msat, 50_000);
3123 fn ignore_fee_first_hop_test() {
3124 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
3125 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3127 // Path via node0 is channels {1, 3}. Limit them to 100 and 50 sats (total limit 50).
3128 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3129 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3130 short_channel_id: 1,
3133 cltv_expiry_delta: 0,
3134 htlc_minimum_msat: 0,
3135 htlc_maximum_msat: OptionalField::Present(100_000),
3136 fee_base_msat: 1_000_000,
3137 fee_proportional_millionths: 0,
3138 excess_data: Vec::new()
3140 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3141 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3142 short_channel_id: 3,
3145 cltv_expiry_delta: 0,
3146 htlc_minimum_msat: 0,
3147 htlc_maximum_msat: OptionalField::Present(50_000),
3149 fee_proportional_millionths: 0,
3150 excess_data: Vec::new()
3154 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();
3155 assert_eq!(route.paths.len(), 1);
3156 let mut total_amount_paid_msat = 0;
3157 for path in &route.paths {
3158 assert_eq!(path.len(), 2);
3159 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
3160 total_amount_paid_msat += path.last().unwrap().fee_msat;
3162 assert_eq!(total_amount_paid_msat, 50_000);
3167 fn simple_mpp_route_test() {
3168 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
3169 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3171 // We need a route consisting of 3 paths:
3172 // From our node to node2 via node0, node7, node1 (three paths one hop each).
3173 // To achieve this, the amount being transferred should be around
3174 // the total capacity of these 3 paths.
3176 // First, we set limits on these (previously unlimited) channels.
3177 // Their aggregate capacity will be 50 + 60 + 180 = 290 sats.
3179 // Path via node0 is channels {1, 3}. Limit them to 100 and 50 sats (total limit 50).
3180 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3181 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3182 short_channel_id: 1,
3185 cltv_expiry_delta: 0,
3186 htlc_minimum_msat: 0,
3187 htlc_maximum_msat: OptionalField::Present(100_000),
3189 fee_proportional_millionths: 0,
3190 excess_data: Vec::new()
3192 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3193 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3194 short_channel_id: 3,
3197 cltv_expiry_delta: 0,
3198 htlc_minimum_msat: 0,
3199 htlc_maximum_msat: OptionalField::Present(50_000),
3201 fee_proportional_millionths: 0,
3202 excess_data: Vec::new()
3205 // Path via node7 is channels {12, 13}. Limit them to 60 and 60 sats
3206 // (total limit 60).
3207 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3208 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3209 short_channel_id: 12,
3212 cltv_expiry_delta: 0,
3213 htlc_minimum_msat: 0,
3214 htlc_maximum_msat: OptionalField::Present(60_000),
3216 fee_proportional_millionths: 0,
3217 excess_data: Vec::new()
3219 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
3220 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3221 short_channel_id: 13,
3224 cltv_expiry_delta: 0,
3225 htlc_minimum_msat: 0,
3226 htlc_maximum_msat: OptionalField::Present(60_000),
3228 fee_proportional_millionths: 0,
3229 excess_data: Vec::new()
3232 // Path via node1 is channels {2, 4}. Limit them to 200 and 180 sats
3233 // (total capacity 180 sats).
3234 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3235 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3236 short_channel_id: 2,
3239 cltv_expiry_delta: 0,
3240 htlc_minimum_msat: 0,
3241 htlc_maximum_msat: OptionalField::Present(200_000),
3243 fee_proportional_millionths: 0,
3244 excess_data: Vec::new()
3246 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
3247 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3248 short_channel_id: 4,
3251 cltv_expiry_delta: 0,
3252 htlc_minimum_msat: 0,
3253 htlc_maximum_msat: OptionalField::Present(180_000),
3255 fee_proportional_millionths: 0,
3256 excess_data: Vec::new()
3260 // Attempt to route more than available results in a failure.
3261 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(),
3262 &nodes[2], Some(InvoiceFeatures::known()), None, &Vec::new(), 300_000, 42, Arc::clone(&logger)) {
3263 assert_eq!(err, "Failed to find a sufficient route to the given destination");
3264 } else { panic!(); }
3268 // Now, attempt to route 250 sats (just a bit below the capacity).
3269 // Our algorithm should provide us with these 3 paths.
3270 let route = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2],
3271 Some(InvoiceFeatures::known()), None, &Vec::new(), 250_000, 42, Arc::clone(&logger)).unwrap();
3272 assert_eq!(route.paths.len(), 3);
3273 let mut total_amount_paid_msat = 0;
3274 for path in &route.paths {
3275 assert_eq!(path.len(), 2);
3276 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
3277 total_amount_paid_msat += path.last().unwrap().fee_msat;
3279 assert_eq!(total_amount_paid_msat, 250_000);
3283 // Attempt to route an exact amount is also fine
3284 let route = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2],
3285 Some(InvoiceFeatures::known()), None, &Vec::new(), 290_000, 42, Arc::clone(&logger)).unwrap();
3286 assert_eq!(route.paths.len(), 3);
3287 let mut total_amount_paid_msat = 0;
3288 for path in &route.paths {
3289 assert_eq!(path.len(), 2);
3290 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
3291 total_amount_paid_msat += path.last().unwrap().fee_msat;
3293 assert_eq!(total_amount_paid_msat, 290_000);
3298 fn long_mpp_route_test() {
3299 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
3300 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3302 // We need a route consisting of 3 paths:
3303 // From our node to node3 via {node0, node2}, {node7, node2, node4} and {node7, node2}.
3304 // Note that these paths overlap (channels 5, 12, 13).
3305 // We will route 300 sats.
3306 // Each path will have 100 sats capacity, those channels which
3307 // are used twice will have 200 sats capacity.
3309 // Disable other potential paths.
3310 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3311 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3312 short_channel_id: 2,
3315 cltv_expiry_delta: 0,
3316 htlc_minimum_msat: 0,
3317 htlc_maximum_msat: OptionalField::Present(100_000),
3319 fee_proportional_millionths: 0,
3320 excess_data: Vec::new()
3322 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3323 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3324 short_channel_id: 7,
3327 cltv_expiry_delta: 0,
3328 htlc_minimum_msat: 0,
3329 htlc_maximum_msat: OptionalField::Present(100_000),
3331 fee_proportional_millionths: 0,
3332 excess_data: Vec::new()
3335 // Path via {node0, node2} is channels {1, 3, 5}.
3336 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3337 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3338 short_channel_id: 1,
3341 cltv_expiry_delta: 0,
3342 htlc_minimum_msat: 0,
3343 htlc_maximum_msat: OptionalField::Present(100_000),
3345 fee_proportional_millionths: 0,
3346 excess_data: Vec::new()
3348 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3349 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3350 short_channel_id: 3,
3353 cltv_expiry_delta: 0,
3354 htlc_minimum_msat: 0,
3355 htlc_maximum_msat: OptionalField::Present(100_000),
3357 fee_proportional_millionths: 0,
3358 excess_data: Vec::new()
3361 // Capacity of 200 sats because this channel will be used by 3rd path as well.
3362 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(5)), 5);
3363 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3364 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3365 short_channel_id: 5,
3368 cltv_expiry_delta: 0,
3369 htlc_minimum_msat: 0,
3370 htlc_maximum_msat: OptionalField::Present(200_000),
3372 fee_proportional_millionths: 0,
3373 excess_data: Vec::new()
3376 // Path via {node7, node2, node4} is channels {12, 13, 6, 11}.
3377 // Add 100 sats to the capacities of {12, 13}, because these channels
3378 // are also used for 3rd path. 100 sats for the rest. Total capacity: 100 sats.
3379 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3380 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3381 short_channel_id: 12,
3384 cltv_expiry_delta: 0,
3385 htlc_minimum_msat: 0,
3386 htlc_maximum_msat: OptionalField::Present(200_000),
3388 fee_proportional_millionths: 0,
3389 excess_data: Vec::new()
3391 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
3392 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3393 short_channel_id: 13,
3396 cltv_expiry_delta: 0,
3397 htlc_minimum_msat: 0,
3398 htlc_maximum_msat: OptionalField::Present(200_000),
3400 fee_proportional_millionths: 0,
3401 excess_data: Vec::new()
3404 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3405 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3406 short_channel_id: 6,
3409 cltv_expiry_delta: 0,
3410 htlc_minimum_msat: 0,
3411 htlc_maximum_msat: OptionalField::Present(100_000),
3413 fee_proportional_millionths: 0,
3414 excess_data: Vec::new()
3416 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
3417 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3418 short_channel_id: 11,
3421 cltv_expiry_delta: 0,
3422 htlc_minimum_msat: 0,
3423 htlc_maximum_msat: OptionalField::Present(100_000),
3425 fee_proportional_millionths: 0,
3426 excess_data: Vec::new()
3429 // Path via {node7, node2} is channels {12, 13, 5}.
3430 // We already limited them to 200 sats (they are used twice for 100 sats).
3431 // Nothing to do here.
3434 // Attempt to route more than available results in a failure.
3435 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[3],
3436 Some(InvoiceFeatures::known()), None, &Vec::new(), 350_000, 42, Arc::clone(&logger)) {
3437 assert_eq!(err, "Failed to find a sufficient route to the given destination");
3438 } else { panic!(); }
3442 // Now, attempt to route 300 sats (exact amount we can route).
3443 // Our algorithm should provide us with these 3 paths, 100 sats each.
3444 let route = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[3],
3445 Some(InvoiceFeatures::known()), None, &Vec::new(), 300_000, 42, Arc::clone(&logger)).unwrap();
3446 assert_eq!(route.paths.len(), 3);
3448 let mut total_amount_paid_msat = 0;
3449 for path in &route.paths {
3450 assert_eq!(path.last().unwrap().pubkey, nodes[3]);
3451 total_amount_paid_msat += path.last().unwrap().fee_msat;
3453 assert_eq!(total_amount_paid_msat, 300_000);
3459 fn mpp_cheaper_route_test() {
3460 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
3461 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3463 // This test checks that if we have two cheaper paths and one more expensive path,
3464 // so that liquidity-wise any 2 of 3 combination is sufficient,
3465 // two cheaper paths will be taken.
3466 // These paths have equal available liquidity.
3468 // We need a combination of 3 paths:
3469 // From our node to node3 via {node0, node2}, {node7, node2, node4} and {node7, node2}.
3470 // Note that these paths overlap (channels 5, 12, 13).
3471 // Each path will have 100 sats capacity, those channels which
3472 // are used twice will have 200 sats capacity.
3474 // Disable other potential paths.
3475 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3476 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3477 short_channel_id: 2,
3480 cltv_expiry_delta: 0,
3481 htlc_minimum_msat: 0,
3482 htlc_maximum_msat: OptionalField::Present(100_000),
3484 fee_proportional_millionths: 0,
3485 excess_data: Vec::new()
3487 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3488 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3489 short_channel_id: 7,
3492 cltv_expiry_delta: 0,
3493 htlc_minimum_msat: 0,
3494 htlc_maximum_msat: OptionalField::Present(100_000),
3496 fee_proportional_millionths: 0,
3497 excess_data: Vec::new()
3500 // Path via {node0, node2} is channels {1, 3, 5}.
3501 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3502 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3503 short_channel_id: 1,
3506 cltv_expiry_delta: 0,
3507 htlc_minimum_msat: 0,
3508 htlc_maximum_msat: OptionalField::Present(100_000),
3510 fee_proportional_millionths: 0,
3511 excess_data: Vec::new()
3513 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3514 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3515 short_channel_id: 3,
3518 cltv_expiry_delta: 0,
3519 htlc_minimum_msat: 0,
3520 htlc_maximum_msat: OptionalField::Present(100_000),
3522 fee_proportional_millionths: 0,
3523 excess_data: Vec::new()
3526 // Capacity of 200 sats because this channel will be used by 3rd path as well.
3527 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(5)), 5);
3528 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3529 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3530 short_channel_id: 5,
3533 cltv_expiry_delta: 0,
3534 htlc_minimum_msat: 0,
3535 htlc_maximum_msat: OptionalField::Present(200_000),
3537 fee_proportional_millionths: 0,
3538 excess_data: Vec::new()
3541 // Path via {node7, node2, node4} is channels {12, 13, 6, 11}.
3542 // Add 100 sats to the capacities of {12, 13}, because these channels
3543 // are also used for 3rd path. 100 sats for the rest. Total capacity: 100 sats.
3544 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3545 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3546 short_channel_id: 12,
3549 cltv_expiry_delta: 0,
3550 htlc_minimum_msat: 0,
3551 htlc_maximum_msat: OptionalField::Present(200_000),
3553 fee_proportional_millionths: 0,
3554 excess_data: Vec::new()
3556 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
3557 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3558 short_channel_id: 13,
3561 cltv_expiry_delta: 0,
3562 htlc_minimum_msat: 0,
3563 htlc_maximum_msat: OptionalField::Present(200_000),
3565 fee_proportional_millionths: 0,
3566 excess_data: Vec::new()
3569 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3570 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3571 short_channel_id: 6,
3574 cltv_expiry_delta: 0,
3575 htlc_minimum_msat: 0,
3576 htlc_maximum_msat: OptionalField::Present(100_000),
3577 fee_base_msat: 1_000,
3578 fee_proportional_millionths: 0,
3579 excess_data: Vec::new()
3581 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
3582 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3583 short_channel_id: 11,
3586 cltv_expiry_delta: 0,
3587 htlc_minimum_msat: 0,
3588 htlc_maximum_msat: OptionalField::Present(100_000),
3590 fee_proportional_millionths: 0,
3591 excess_data: Vec::new()
3594 // Path via {node7, node2} is channels {12, 13, 5}.
3595 // We already limited them to 200 sats (they are used twice for 100 sats).
3596 // Nothing to do here.
3599 // Now, attempt to route 180 sats.
3600 // Our algorithm should provide us with these 2 paths.
3601 let route = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[3],
3602 Some(InvoiceFeatures::known()), None, &Vec::new(), 180_000, 42, Arc::clone(&logger)).unwrap();
3603 assert_eq!(route.paths.len(), 2);
3605 let mut total_value_transferred_msat = 0;
3606 let mut total_paid_msat = 0;
3607 for path in &route.paths {
3608 assert_eq!(path.last().unwrap().pubkey, nodes[3]);
3609 total_value_transferred_msat += path.last().unwrap().fee_msat;
3611 total_paid_msat += hop.fee_msat;
3614 // If we paid fee, this would be higher.
3615 assert_eq!(total_value_transferred_msat, 180_000);
3616 let total_fees_paid = total_paid_msat - total_value_transferred_msat;
3617 assert_eq!(total_fees_paid, 0);
3622 fn fees_on_mpp_route_test() {
3623 // This test makes sure that MPP algorithm properly takes into account
3624 // fees charged on the channels, by making the fees impactful:
3625 // if the fee is not properly accounted for, the behavior is different.
3626 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
3627 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3629 // We need a route consisting of 2 paths:
3630 // From our node to node3 via {node0, node2} and {node7, node2, node4}.
3631 // We will route 200 sats, Each path will have 100 sats capacity.
3633 // This test is not particularly stable: e.g.,
3634 // there's a way to route via {node0, node2, node4}.
3635 // It works while pathfinding is deterministic, but can be broken otherwise.
3636 // It's fine to ignore this concern for now.
3638 // Disable other potential paths.
3639 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3640 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3641 short_channel_id: 2,
3644 cltv_expiry_delta: 0,
3645 htlc_minimum_msat: 0,
3646 htlc_maximum_msat: OptionalField::Present(100_000),
3648 fee_proportional_millionths: 0,
3649 excess_data: Vec::new()
3652 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3653 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3654 short_channel_id: 7,
3657 cltv_expiry_delta: 0,
3658 htlc_minimum_msat: 0,
3659 htlc_maximum_msat: OptionalField::Present(100_000),
3661 fee_proportional_millionths: 0,
3662 excess_data: Vec::new()
3665 // Path via {node0, node2} is channels {1, 3, 5}.
3666 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3667 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3668 short_channel_id: 1,
3671 cltv_expiry_delta: 0,
3672 htlc_minimum_msat: 0,
3673 htlc_maximum_msat: OptionalField::Present(100_000),
3675 fee_proportional_millionths: 0,
3676 excess_data: Vec::new()
3678 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3679 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3680 short_channel_id: 3,
3683 cltv_expiry_delta: 0,
3684 htlc_minimum_msat: 0,
3685 htlc_maximum_msat: OptionalField::Present(100_000),
3687 fee_proportional_millionths: 0,
3688 excess_data: Vec::new()
3691 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(5)), 5);
3692 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3693 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3694 short_channel_id: 5,
3697 cltv_expiry_delta: 0,
3698 htlc_minimum_msat: 0,
3699 htlc_maximum_msat: OptionalField::Present(100_000),
3701 fee_proportional_millionths: 0,
3702 excess_data: Vec::new()
3705 // Path via {node7, node2, node4} is channels {12, 13, 6, 11}.
3706 // All channels should be 100 sats capacity. But for the fee experiment,
3707 // we'll add absolute fee of 150 sats paid for the use channel 6 (paid to node2 on channel 13).
3708 // Since channel 12 allows to deliver only 250 sats to channel 13, channel 13 can transfer only
3709 // 100 sats (and pay 150 sats in fees for the use of channel 6),
3710 // so no matter how large are other channels,
3711 // the whole path will be limited by 100 sats with just these 2 conditions:
3712 // - channel 12 capacity is 250 sats
3713 // - fee for channel 6 is 150 sats
3714 // Let's test this by enforcing these 2 conditions and removing other limits.
3715 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3716 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3717 short_channel_id: 12,
3720 cltv_expiry_delta: 0,
3721 htlc_minimum_msat: 0,
3722 htlc_maximum_msat: OptionalField::Present(250_000),
3724 fee_proportional_millionths: 0,
3725 excess_data: Vec::new()
3727 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
3728 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3729 short_channel_id: 13,
3732 cltv_expiry_delta: 0,
3733 htlc_minimum_msat: 0,
3734 htlc_maximum_msat: OptionalField::Absent,
3736 fee_proportional_millionths: 0,
3737 excess_data: Vec::new()
3740 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3741 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3742 short_channel_id: 6,
3745 cltv_expiry_delta: 0,
3746 htlc_minimum_msat: 0,
3747 htlc_maximum_msat: OptionalField::Absent,
3748 fee_base_msat: 150_000,
3749 fee_proportional_millionths: 0,
3750 excess_data: Vec::new()
3752 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
3753 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3754 short_channel_id: 11,
3757 cltv_expiry_delta: 0,
3758 htlc_minimum_msat: 0,
3759 htlc_maximum_msat: OptionalField::Absent,
3761 fee_proportional_millionths: 0,
3762 excess_data: Vec::new()
3766 // Attempt to route more than available results in a failure.
3767 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[3],
3768 Some(InvoiceFeatures::known()), None, &Vec::new(), 210_000, 42, Arc::clone(&logger)) {
3769 assert_eq!(err, "Failed to find a sufficient route to the given destination");
3770 } else { panic!(); }
3774 // Now, attempt to route 200 sats (exact amount we can route).
3775 let route = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[3],
3776 Some(InvoiceFeatures::known()), None, &Vec::new(), 200_000, 42, Arc::clone(&logger)).unwrap();
3777 assert_eq!(route.paths.len(), 2);
3779 let mut total_amount_paid_msat = 0;
3780 for path in &route.paths {
3781 assert_eq!(path.last().unwrap().pubkey, nodes[3]);
3782 total_amount_paid_msat += path.last().unwrap().fee_msat;
3784 assert_eq!(total_amount_paid_msat, 200_000);
3790 fn drop_lowest_channel_mpp_route_test() {
3791 // This test checks that low-capacity channel is dropped when after
3792 // path finding we realize that we found more capacity than we need.
3793 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
3794 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3796 // We need a route consisting of 3 paths:
3797 // From our node to node2 via node0, node7, node1 (three paths one hop each).
3799 // The first and the second paths should be sufficient, but the third should be
3800 // cheaper, so that we select it but drop later.
3802 // First, we set limits on these (previously unlimited) channels.
3803 // Their aggregate capacity will be 50 + 60 + 20 = 130 sats.
3805 // Path via node0 is channels {1, 3}. Limit them to 100 and 50 sats (total limit 50);
3806 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3807 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3808 short_channel_id: 1,
3811 cltv_expiry_delta: 0,
3812 htlc_minimum_msat: 0,
3813 htlc_maximum_msat: OptionalField::Present(100_000),
3815 fee_proportional_millionths: 0,
3816 excess_data: Vec::new()
3818 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3819 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3820 short_channel_id: 3,
3823 cltv_expiry_delta: 0,
3824 htlc_minimum_msat: 0,
3825 htlc_maximum_msat: OptionalField::Present(50_000),
3827 fee_proportional_millionths: 0,
3828 excess_data: Vec::new()
3831 // Path via node7 is channels {12, 13}. Limit them to 60 and 60 sats (total limit 60);
3832 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3833 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3834 short_channel_id: 12,
3837 cltv_expiry_delta: 0,
3838 htlc_minimum_msat: 0,
3839 htlc_maximum_msat: OptionalField::Present(60_000),
3841 fee_proportional_millionths: 0,
3842 excess_data: Vec::new()
3844 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
3845 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3846 short_channel_id: 13,
3849 cltv_expiry_delta: 0,
3850 htlc_minimum_msat: 0,
3851 htlc_maximum_msat: OptionalField::Present(60_000),
3853 fee_proportional_millionths: 0,
3854 excess_data: Vec::new()
3857 // Path via node1 is channels {2, 4}. Limit them to 20 and 20 sats (total capacity 20 sats).
3858 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3859 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3860 short_channel_id: 2,
3863 cltv_expiry_delta: 0,
3864 htlc_minimum_msat: 0,
3865 htlc_maximum_msat: OptionalField::Present(20_000),
3867 fee_proportional_millionths: 0,
3868 excess_data: Vec::new()
3870 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
3871 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3872 short_channel_id: 4,
3875 cltv_expiry_delta: 0,
3876 htlc_minimum_msat: 0,
3877 htlc_maximum_msat: OptionalField::Present(20_000),
3879 fee_proportional_millionths: 0,
3880 excess_data: Vec::new()
3884 // Attempt to route more than available results in a failure.
3885 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2],
3886 Some(InvoiceFeatures::known()), None, &Vec::new(), 150_000, 42, Arc::clone(&logger)) {
3887 assert_eq!(err, "Failed to find a sufficient route to the given destination");
3888 } else { panic!(); }
3892 // Now, attempt to route 125 sats (just a bit below the capacity of 3 channels).
3893 // Our algorithm should provide us with these 3 paths.
3894 let route = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2],
3895 Some(InvoiceFeatures::known()), None, &Vec::new(), 125_000, 42, Arc::clone(&logger)).unwrap();
3896 assert_eq!(route.paths.len(), 3);
3897 let mut total_amount_paid_msat = 0;
3898 for path in &route.paths {
3899 assert_eq!(path.len(), 2);
3900 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
3901 total_amount_paid_msat += path.last().unwrap().fee_msat;
3903 assert_eq!(total_amount_paid_msat, 125_000);
3907 // Attempt to route without the last small cheap channel
3908 let route = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2],
3909 Some(InvoiceFeatures::known()), None, &Vec::new(), 90_000, 42, Arc::clone(&logger)).unwrap();
3910 assert_eq!(route.paths.len(), 2);
3911 let mut total_amount_paid_msat = 0;
3912 for path in &route.paths {
3913 assert_eq!(path.len(), 2);
3914 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
3915 total_amount_paid_msat += path.last().unwrap().fee_msat;
3917 assert_eq!(total_amount_paid_msat, 90_000);
3922 fn min_criteria_consistency() {
3923 // Test that we don't use an inconsistent metric between updating and walking nodes during
3924 // our Dijkstra's pass. In the initial version of MPP, the "best source" for a given node
3925 // was updated with a different criterion from the heap sorting, resulting in loops in
3926 // calculated paths. We test for that specific case here.
3928 // We construct a network that looks like this:
3930 // node2 -1(3)2- node3
3934 // node1 -1(5)2- node4 -1(1)2- node6
3940 // We create a loop on the side of our real path - our destination is node 6, with a
3941 // previous hop of node 4. From 4, the cheapest previous path is channel 2 from node 2,
3942 // followed by node 3 over channel 3. Thereafter, the cheapest next-hop is back to node 4
3943 // (this time over channel 4). Channel 4 has 0 htlc_minimum_msat whereas channel 1 (the
3944 // other channel with a previous-hop of node 4) has a high (but irrelevant to the overall
3945 // payment) htlc_minimum_msat. In the original algorithm, this resulted in node4's
3946 // "previous hop" being set to node 3, creating a loop in the path.
3947 let secp_ctx = Secp256k1::new();
3948 let logger = Arc::new(test_utils::TestLogger::new());
3949 let net_graph_msg_handler = NetGraphMsgHandler::new(genesis_block(Network::Testnet).header.block_hash(), None, Arc::clone(&logger));
3950 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3952 add_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, &privkeys[1], ChannelFeatures::from_le_bytes(id_to_feature_flags(6)), 6);
3953 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3954 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3955 short_channel_id: 6,
3958 cltv_expiry_delta: (6 << 8) | 0,
3959 htlc_minimum_msat: 0,
3960 htlc_maximum_msat: OptionalField::Absent,
3962 fee_proportional_millionths: 0,
3963 excess_data: Vec::new()
3965 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[1], NodeFeatures::from_le_bytes(id_to_feature_flags(1)), 0);
3967 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], &privkeys[4], ChannelFeatures::from_le_bytes(id_to_feature_flags(5)), 5);
3968 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
3969 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3970 short_channel_id: 5,
3973 cltv_expiry_delta: (5 << 8) | 0,
3974 htlc_minimum_msat: 0,
3975 htlc_maximum_msat: OptionalField::Absent,
3977 fee_proportional_millionths: 0,
3978 excess_data: Vec::new()
3980 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[4], NodeFeatures::from_le_bytes(id_to_feature_flags(4)), 0);
3982 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(4)), 4);
3983 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
3984 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3985 short_channel_id: 4,
3988 cltv_expiry_delta: (4 << 8) | 0,
3989 htlc_minimum_msat: 0,
3990 htlc_maximum_msat: OptionalField::Absent,
3992 fee_proportional_millionths: 0,
3993 excess_data: Vec::new()
3995 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[3], NodeFeatures::from_le_bytes(id_to_feature_flags(3)), 0);
3997 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[3], &privkeys[2], ChannelFeatures::from_le_bytes(id_to_feature_flags(3)), 3);
3998 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[3], UnsignedChannelUpdate {
3999 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4000 short_channel_id: 3,
4003 cltv_expiry_delta: (3 << 8) | 0,
4004 htlc_minimum_msat: 0,
4005 htlc_maximum_msat: OptionalField::Absent,
4007 fee_proportional_millionths: 0,
4008 excess_data: Vec::new()
4010 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[2], NodeFeatures::from_le_bytes(id_to_feature_flags(2)), 0);
4012 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], &privkeys[4], ChannelFeatures::from_le_bytes(id_to_feature_flags(2)), 2);
4013 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4014 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4015 short_channel_id: 2,
4018 cltv_expiry_delta: (2 << 8) | 0,
4019 htlc_minimum_msat: 0,
4020 htlc_maximum_msat: OptionalField::Absent,
4022 fee_proportional_millionths: 0,
4023 excess_data: Vec::new()
4026 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], &privkeys[6], ChannelFeatures::from_le_bytes(id_to_feature_flags(1)), 1);
4027 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
4028 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4029 short_channel_id: 1,
4032 cltv_expiry_delta: (1 << 8) | 0,
4033 htlc_minimum_msat: 100,
4034 htlc_maximum_msat: OptionalField::Absent,
4036 fee_proportional_millionths: 0,
4037 excess_data: Vec::new()
4039 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[6], NodeFeatures::from_le_bytes(id_to_feature_flags(6)), 0);
4042 // Now ensure the route flows simply over nodes 1 and 4 to 6.
4043 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();
4044 assert_eq!(route.paths.len(), 1);
4045 assert_eq!(route.paths[0].len(), 3);
4047 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
4048 assert_eq!(route.paths[0][0].short_channel_id, 6);
4049 assert_eq!(route.paths[0][0].fee_msat, 100);
4050 assert_eq!(route.paths[0][0].cltv_expiry_delta, (5 << 8) | 0);
4051 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(1));
4052 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(6));
4054 assert_eq!(route.paths[0][1].pubkey, nodes[4]);
4055 assert_eq!(route.paths[0][1].short_channel_id, 5);
4056 assert_eq!(route.paths[0][1].fee_msat, 0);
4057 assert_eq!(route.paths[0][1].cltv_expiry_delta, (1 << 8) | 0);
4058 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(4));
4059 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(5));
4061 assert_eq!(route.paths[0][2].pubkey, nodes[6]);
4062 assert_eq!(route.paths[0][2].short_channel_id, 1);
4063 assert_eq!(route.paths[0][2].fee_msat, 10_000);
4064 assert_eq!(route.paths[0][2].cltv_expiry_delta, 42);
4065 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(6));
4066 assert_eq!(route.paths[0][2].channel_features.le_flags(), &id_to_feature_flags(1));
4072 fn exact_fee_liquidity_limit() {
4073 // Test that if, while walking the graph, we find a hop that has exactly enough liquidity
4074 // for us, including later hop fees, we take it. In the first version of our MPP algorithm
4075 // we calculated fees on a higher value, resulting in us ignoring such paths.
4076 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
4077 let (our_privkey, our_id, _, nodes) = get_nodes(&secp_ctx);
4079 // We modify the graph to set the htlc_maximum of channel 2 to below the value we wish to
4081 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4082 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4083 short_channel_id: 2,
4086 cltv_expiry_delta: 0,
4087 htlc_minimum_msat: 0,
4088 htlc_maximum_msat: OptionalField::Present(85_000),
4090 fee_proportional_millionths: 0,
4091 excess_data: Vec::new()
4094 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4095 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4096 short_channel_id: 12,
4099 cltv_expiry_delta: (4 << 8) | 1,
4100 htlc_minimum_msat: 0,
4101 htlc_maximum_msat: OptionalField::Present(270_000),
4103 fee_proportional_millionths: 1000000,
4104 excess_data: Vec::new()
4108 // Now, attempt to route 90 sats, which is exactly 90 sats at the last hop, plus the
4109 // 200% fee charged channel 13 in the 1-to-2 direction.
4110 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();
4111 assert_eq!(route.paths.len(), 1);
4112 assert_eq!(route.paths[0].len(), 2);
4114 assert_eq!(route.paths[0][0].pubkey, nodes[7]);
4115 assert_eq!(route.paths[0][0].short_channel_id, 12);
4116 assert_eq!(route.paths[0][0].fee_msat, 90_000*2);
4117 assert_eq!(route.paths[0][0].cltv_expiry_delta, (13 << 8) | 1);
4118 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(8));
4119 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(12));
4121 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
4122 assert_eq!(route.paths[0][1].short_channel_id, 13);
4123 assert_eq!(route.paths[0][1].fee_msat, 90_000);
4124 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
4125 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
4126 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(13));
4131 fn htlc_max_reduction_below_min() {
4132 // Test that if, while walking the graph, we reduce the value being sent to meet an
4133 // htlc_maximum_msat, we don't end up undershooting a later htlc_minimum_msat. In the
4134 // initial version of MPP we'd accept such routes but reject them while recalculating fees,
4135 // resulting in us thinking there is no possible path, even if other paths exist.
4136 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
4137 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
4139 // We modify the graph to set the htlc_minimum of channel 2 and 4 as needed - channel 2
4140 // gets an htlc_maximum_msat of 80_000 and channel 4 an htlc_minimum_msat of 90_000. We
4141 // then try to send 90_000.
4142 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4143 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4144 short_channel_id: 2,
4147 cltv_expiry_delta: 0,
4148 htlc_minimum_msat: 0,
4149 htlc_maximum_msat: OptionalField::Present(80_000),
4151 fee_proportional_millionths: 0,
4152 excess_data: Vec::new()
4154 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
4155 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4156 short_channel_id: 4,
4159 cltv_expiry_delta: (4 << 8) | 1,
4160 htlc_minimum_msat: 90_000,
4161 htlc_maximum_msat: OptionalField::Absent,
4163 fee_proportional_millionths: 0,
4164 excess_data: Vec::new()
4168 // Now, attempt to route 90 sats, hitting the htlc_minimum on channel 4, but
4169 // overshooting the htlc_maximum on channel 2. Thus, we should pick the (absurdly
4170 // expensive) channels 12-13 path.
4171 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();
4172 assert_eq!(route.paths.len(), 1);
4173 assert_eq!(route.paths[0].len(), 2);
4175 assert_eq!(route.paths[0][0].pubkey, nodes[7]);
4176 assert_eq!(route.paths[0][0].short_channel_id, 12);
4177 assert_eq!(route.paths[0][0].fee_msat, 90_000*2);
4178 assert_eq!(route.paths[0][0].cltv_expiry_delta, (13 << 8) | 1);
4179 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(8));
4180 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(12));
4182 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
4183 assert_eq!(route.paths[0][1].short_channel_id, 13);
4184 assert_eq!(route.paths[0][1].fee_msat, 90_000);
4185 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
4186 assert_eq!(route.paths[0][1].node_features.le_flags(), InvoiceFeatures::known().le_flags());
4187 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(13));
4191 #[cfg(not(feature = "no-std"))]
4192 pub(super) fn random_init_seed() -> u64 {
4193 // Because the default HashMap in std pulls OS randomness, we can use it as a (bad) RNG.
4194 use core::hash::{BuildHasher, Hasher};
4195 let seed = std::collections::hash_map::RandomState::new().build_hasher().finish();
4196 println!("Using seed of {}", seed);
4199 #[cfg(not(feature = "no-std"))]
4200 use util::ser::Readable;
4203 #[cfg(not(feature = "no-std"))]
4204 fn generate_routes() {
4205 let mut d = match super::test_utils::get_route_file() {
4212 let graph = NetworkGraph::read(&mut d).unwrap();
4214 // First, get 100 (source, destination) pairs for which route-getting actually succeeds...
4215 let mut seed = random_init_seed() as usize;
4216 let nodes = graph.get_nodes();
4217 'load_endpoints: for _ in 0..10 {
4219 seed = seed.overflowing_mul(0xdeadbeef).0;
4220 let src = nodes.keys().skip(seed % nodes.len()).next().unwrap();
4221 seed = seed.overflowing_mul(0xdeadbeef).0;
4222 let dst = nodes.keys().skip(seed % nodes.len()).next().unwrap();
4223 let amt = seed as u64 % 200_000_000;
4224 if get_route(src, &graph, dst, None, None, &[], amt, 42, &test_utils::TestLogger::new()).is_ok() {
4225 continue 'load_endpoints;
4232 #[cfg(not(feature = "no-std"))]
4233 fn generate_routes_mpp() {
4234 let mut d = match super::test_utils::get_route_file() {
4241 let graph = NetworkGraph::read(&mut d).unwrap();
4243 // First, get 100 (source, destination) pairs for which route-getting actually succeeds...
4244 let mut seed = random_init_seed() as usize;
4245 let nodes = graph.get_nodes();
4246 'load_endpoints: for _ in 0..10 {
4248 seed = seed.overflowing_mul(0xdeadbeef).0;
4249 let src = nodes.keys().skip(seed % nodes.len()).next().unwrap();
4250 seed = seed.overflowing_mul(0xdeadbeef).0;
4251 let dst = nodes.keys().skip(seed % nodes.len()).next().unwrap();
4252 let amt = seed as u64 % 200_000_000;
4253 if get_route(src, &graph, dst, Some(InvoiceFeatures::known()), None, &[], amt, 42, &test_utils::TestLogger::new()).is_ok() {
4254 continue 'load_endpoints;
4261 #[cfg(all(test, not(feature = "no-std")))]
4262 pub(crate) mod test_utils {
4264 /// Tries to open a network graph file, or panics with a URL to fetch it.
4265 pub(crate) fn get_route_file() -> Result<std::fs::File, &'static str> {
4266 let res = File::open("net_graph-2021-05-31.bin") // By default we're run in RL/lightning
4267 .or_else(|_| File::open("lightning/net_graph-2021-05-31.bin")) // We may be run manually in RL/
4268 .or_else(|_| { // Fall back to guessing based on the binary location
4269 // path is likely something like .../rust-lightning/target/debug/deps/lightning-...
4270 let mut path = std::env::current_exe().unwrap();
4271 path.pop(); // lightning-...
4273 path.pop(); // debug
4274 path.pop(); // target
4275 path.push("lightning");
4276 path.push("net_graph-2021-05-31.bin");
4277 eprintln!("{}", path.to_str().unwrap());
4280 .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");
4281 #[cfg(require_route_graph_test)]
4282 return Ok(res.unwrap());
4283 #[cfg(not(require_route_graph_test))]
4288 #[cfg(all(test, feature = "unstable", not(feature = "no-std")))]
4291 use util::logger::{Logger, Record};
4295 struct DummyLogger {}
4296 impl Logger for DummyLogger {
4297 fn log(&self, _record: &Record) {}
4301 fn generate_routes(bench: &mut Bencher) {
4302 let mut d = test_utils::get_route_file().unwrap();
4303 let graph = NetworkGraph::read(&mut d).unwrap();
4304 let nodes = graph.get_nodes();
4306 // First, get 100 (source, destination) pairs for which route-getting actually succeeds...
4307 let mut path_endpoints = Vec::new();
4308 let mut seed: usize = 0xdeadbeef;
4309 'load_endpoints: for _ in 0..100 {
4312 let src = nodes.keys().skip(seed % nodes.len()).next().unwrap();
4314 let dst = nodes.keys().skip(seed % nodes.len()).next().unwrap();
4315 let amt = seed as u64 % 1_000_000;
4316 if get_route(src, &graph, dst, None, None, &[], amt, 42, &DummyLogger{}).is_ok() {
4317 path_endpoints.push((src, dst, amt));
4318 continue 'load_endpoints;
4323 // ...then benchmark finding paths between the nodes we learned.
4326 let (src, dst, amt) = path_endpoints[idx % path_endpoints.len()];
4327 assert!(get_route(src, &graph, dst, None, None, &[], amt, 42, &DummyLogger{}).is_ok());
4333 fn generate_mpp_routes(bench: &mut Bencher) {
4334 let mut d = test_utils::get_route_file().unwrap();
4335 let graph = NetworkGraph::read(&mut d).unwrap();
4336 let nodes = graph.get_nodes();
4338 // First, get 100 (source, destination) pairs for which route-getting actually succeeds...
4339 let mut path_endpoints = Vec::new();
4340 let mut seed: usize = 0xdeadbeef;
4341 'load_endpoints: for _ in 0..100 {
4344 let src = nodes.keys().skip(seed % nodes.len()).next().unwrap();
4346 let dst = nodes.keys().skip(seed % nodes.len()).next().unwrap();
4347 let amt = seed as u64 % 1_000_000;
4348 if get_route(src, &graph, dst, Some(InvoiceFeatures::known()), None, &[], amt, 42, &DummyLogger{}).is_ok() {
4349 path_endpoints.push((src, dst, amt));
4350 continue 'load_endpoints;
4355 // ...then benchmark finding paths between the nodes we learned.
4358 let (src, dst, amt) = path_endpoints[idx % path_endpoints.len()];
4359 assert!(get_route(src, &graph, dst, Some(InvoiceFeatures::known()), None, &[], amt, 42, &DummyLogger{}).is_ok());