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_graph = network.read_only();
447 let network_channels = network_graph.channels();
448 let network_nodes = network_graph.nodes();
449 let dummy_directional_info = DummyDirectionalChannelInfo { // used for first_hops routes
450 cltv_expiry_delta: 0,
451 htlc_minimum_msat: 0,
452 htlc_maximum_msat: None,
455 proportional_millionths: 0,
459 // Allow MPP only if we have a features set from somewhere that indicates the payee supports
460 // it. If the payee supports it they're supposed to include it in the invoice, so that should
462 let allow_mpp = if let Some(features) = &payee_features {
463 features.supports_basic_mpp()
464 } else if let Some(node) = network_nodes.get(&payee) {
465 if let Some(node_info) = node.announcement_info.as_ref() {
466 node_info.features.supports_basic_mpp()
471 // Prepare the data we'll use for payee-to-payer search by
472 // inserting first hops suggested by the caller as targets.
473 // Our search will then attempt to reach them while traversing from the payee node.
474 let mut first_hop_targets: HashMap<_, (_, ChannelFeatures, _, NodeFeatures)> =
475 HashMap::with_capacity(if first_hops.is_some() { first_hops.as_ref().unwrap().len() } else { 0 });
476 if let Some(hops) = first_hops {
478 let short_channel_id = chan.short_channel_id.expect("first_hops should be filled in with usable channels, not pending ones");
479 if chan.counterparty.node_id == *our_node_id {
480 return Err(LightningError{err: "First hop cannot have our_node_id as a destination.".to_owned(), action: ErrorAction::IgnoreError});
482 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()));
484 if first_hop_targets.is_empty() {
485 return Err(LightningError{err: "Cannot route when there are no outbound routes away from us".to_owned(), action: ErrorAction::IgnoreError});
489 let empty_channel_features = ChannelFeatures::empty();
491 // The main heap containing all candidate next-hops sorted by their score (max(A* fee,
492 // htlc_minimum)). Ideally this would be a heap which allowed cheap score reduction instead of
493 // adding duplicate entries when we find a better path to a given node.
494 let mut targets = BinaryHeap::new();
496 // Map from node_id to information about the best current path to that node, including feerate
498 let mut dist = HashMap::with_capacity(network_nodes.len());
500 // During routing, if we ignore a path due to an htlc_minimum_msat limit, we set this,
501 // indicating that we may wish to try again with a higher value, potentially paying to meet an
502 // htlc_minimum with extra fees while still finding a cheaper path.
503 let mut hit_minimum_limit;
505 // When arranging a route, we select multiple paths so that we can make a multi-path payment.
506 // We start with a path_value of the exact amount we want, and if that generates a route we may
507 // return it immediately. Otherwise, we don't stop searching for paths until we have 3x the
508 // amount we want in total across paths, selecting the best subset at the end.
509 const ROUTE_CAPACITY_PROVISION_FACTOR: u64 = 3;
510 let recommended_value_msat = final_value_msat * ROUTE_CAPACITY_PROVISION_FACTOR as u64;
511 let mut path_value_msat = final_value_msat;
513 // We don't want multiple paths (as per MPP) share liquidity of the same channels.
514 // This map allows paths to be aware of the channel use by other paths in the same call.
515 // This would help to make a better path finding decisions and not "overbook" channels.
516 // It is unaware of the directions (except for `outbound_capacity_msat` in `first_hops`).
517 let mut bookkeeped_channels_liquidity_available_msat = HashMap::with_capacity(network_nodes.len());
519 // Keeping track of how much value we already collected across other paths. Helps to decide:
520 // - how much a new path should be transferring (upper bound);
521 // - whether a channel should be disregarded because
522 // it's available liquidity is too small comparing to how much more we need to collect;
523 // - when we want to stop looking for new paths.
524 let mut already_collected_value_msat = 0;
526 log_trace!(logger, "Building path from {} (payee) to {} (us/payer) for value {} msat.", payee, our_node_id, final_value_msat);
528 macro_rules! add_entry {
529 // Adds entry which goes from $src_node_id to $dest_node_id
530 // over the channel with id $chan_id with fees described in
531 // $directional_info.
532 // $next_hops_fee_msat represents the fees paid for using all the channel *after* this one,
533 // since that value has to be transferred over this channel.
534 // Returns whether this channel caused an update to `targets`.
535 ( $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,
536 $next_hops_value_contribution: expr, $next_hops_path_htlc_minimum_msat: expr ) => { {
537 // We "return" whether we updated the path at the end, via this:
538 let mut did_add_update_path_to_src_node = false;
539 // Channels to self should not be used. This is more of belt-and-suspenders, because in
540 // practice these cases should be caught earlier:
541 // - for regular channels at channel announcement (TODO)
542 // - for first and last hops early in get_route
543 if $src_node_id != $dest_node_id.clone() {
544 let available_liquidity_msat = bookkeeped_channels_liquidity_available_msat.entry($chan_id.clone()).or_insert_with(|| {
545 let mut initial_liquidity_available_msat = None;
546 if let Some(capacity_sats) = $capacity_sats {
547 initial_liquidity_available_msat = Some(capacity_sats * 1000);
550 if let Some(htlc_maximum_msat) = $directional_info.htlc_maximum_msat {
551 if let Some(available_msat) = initial_liquidity_available_msat {
552 initial_liquidity_available_msat = Some(cmp::min(available_msat, htlc_maximum_msat));
554 initial_liquidity_available_msat = Some(htlc_maximum_msat);
558 match initial_liquidity_available_msat {
559 Some(available_msat) => available_msat,
560 // We assume channels with unknown balance have
561 // a capacity of 0.0025 BTC (or 250_000 sats).
562 None => 250_000 * 1000
566 // It is tricky to substract $next_hops_fee_msat from available liquidity here.
567 // It may be misleading because we might later choose to reduce the value transferred
568 // over these channels, and the channel which was insufficient might become sufficient.
569 // Worst case: we drop a good channel here because it can't cover the high following
570 // fees caused by one expensive channel, but then this channel could have been used
571 // if the amount being transferred over this path is lower.
572 // We do this for now, but this is a subject for removal.
573 if let Some(available_value_contribution_msat) = available_liquidity_msat.checked_sub($next_hops_fee_msat) {
575 // Routing Fragmentation Mitigation heuristic:
577 // Routing fragmentation across many payment paths increases the overall routing
578 // fees as you have irreducible routing fees per-link used (`fee_base_msat`).
579 // Taking too many smaller paths also increases the chance of payment failure.
580 // Thus to avoid this effect, we require from our collected links to provide
581 // at least a minimal contribution to the recommended value yet-to-be-fulfilled.
583 // This requirement is currently 5% of the remaining-to-be-collected value.
584 // This means as we successfully advance in our collection,
585 // the absolute liquidity contribution is lowered,
586 // thus increasing the number of potential channels to be selected.
588 // Derive the minimal liquidity contribution with a ratio of 20 (5%, rounded up)
589 // or 100% if we're not allowed to do multipath payments.
590 let minimal_value_contribution_msat: u64 = if allow_mpp {
591 (recommended_value_msat - already_collected_value_msat + 19) / 20
595 // Verify the liquidity offered by this channel complies to the minimal contribution.
596 let contributes_sufficient_value = available_value_contribution_msat >= minimal_value_contribution_msat;
598 let value_contribution_msat = cmp::min(available_value_contribution_msat, $next_hops_value_contribution);
599 // Includes paying fees for the use of the following channels.
600 let amount_to_transfer_over_msat: u64 = match value_contribution_msat.checked_add($next_hops_fee_msat) {
601 Some(result) => result,
602 // Can't overflow due to how the values were computed right above.
603 None => unreachable!(),
605 #[allow(unused_comparisons)] // $next_hops_path_htlc_minimum_msat is 0 in some calls so rustc complains
606 let over_path_minimum_msat = amount_to_transfer_over_msat >= $directional_info.htlc_minimum_msat &&
607 amount_to_transfer_over_msat >= $next_hops_path_htlc_minimum_msat;
609 // If HTLC minimum is larger than the amount we're going to transfer, we shouldn't
610 // bother considering this channel.
611 // Since we're choosing amount_to_transfer_over_msat as maximum possible, it can
612 // be only reduced later (not increased), so this channel should just be skipped
613 // as not sufficient.
614 if !over_path_minimum_msat {
615 hit_minimum_limit = true;
616 } else if contributes_sufficient_value {
617 // Note that low contribution here (limited by available_liquidity_msat)
618 // might violate htlc_minimum_msat on the hops which are next along the
619 // payment path (upstream to the payee). To avoid that, we recompute path
620 // path fees knowing the final path contribution after constructing it.
621 let path_htlc_minimum_msat = match compute_fees($next_hops_path_htlc_minimum_msat, $directional_info.fees)
622 .map(|fee_msat| fee_msat.checked_add($next_hops_path_htlc_minimum_msat)) {
623 Some(Some(value_msat)) => cmp::max(value_msat, $directional_info.htlc_minimum_msat),
624 _ => u64::max_value()
626 let hm_entry = dist.entry(&$src_node_id);
627 let old_entry = hm_entry.or_insert_with(|| {
628 // If there was previously no known way to access
629 // the source node (recall it goes payee-to-payer) of $chan_id, first add
630 // a semi-dummy record just to compute the fees to reach the source node.
631 // This will affect our decision on selecting $chan_id
632 // as a way to reach the $dest_node_id.
633 let mut fee_base_msat = u32::max_value();
634 let mut fee_proportional_millionths = u32::max_value();
635 if let Some(Some(fees)) = network_nodes.get(&$src_node_id).map(|node| node.lowest_inbound_channel_fees) {
636 fee_base_msat = fees.base_msat;
637 fee_proportional_millionths = fees.proportional_millionths;
640 pubkey: $dest_node_id.clone(),
642 channel_features: $chan_features,
644 cltv_expiry_delta: 0,
645 src_lowest_inbound_fees: RoutingFees {
646 base_msat: fee_base_msat,
647 proportional_millionths: fee_proportional_millionths,
649 channel_fees: $directional_info.fees,
650 next_hops_fee_msat: u64::max_value(),
651 hop_use_fee_msat: u64::max_value(),
652 total_fee_msat: u64::max_value(),
653 htlc_minimum_msat: $directional_info.htlc_minimum_msat,
654 path_htlc_minimum_msat,
655 was_processed: false,
656 #[cfg(any(test, feature = "fuzztarget"))]
657 value_contribution_msat,
661 #[allow(unused_mut)] // We only use the mut in cfg(test)
662 let mut should_process = !old_entry.was_processed;
663 #[cfg(any(test, feature = "fuzztarget"))]
665 // In test/fuzzing builds, we do extra checks to make sure the skipping
666 // of already-seen nodes only happens in cases we expect (see below).
667 if !should_process { should_process = true; }
671 let mut hop_use_fee_msat = 0;
672 let mut total_fee_msat = $next_hops_fee_msat;
674 // Ignore hop_use_fee_msat for channel-from-us as we assume all channels-from-us
675 // will have the same effective-fee
676 if $src_node_id != *our_node_id {
677 match compute_fees(amount_to_transfer_over_msat, $directional_info.fees) {
678 // max_value means we'll always fail
679 // the old_entry.total_fee_msat > total_fee_msat check
680 None => total_fee_msat = u64::max_value(),
682 hop_use_fee_msat = fee_msat;
683 total_fee_msat += hop_use_fee_msat;
684 // When calculating the lowest inbound fees to a node, we
685 // calculate fees here not based on the actual value we think
686 // will flow over this channel, but on the minimum value that
687 // we'll accept flowing over it. The minimum accepted value
688 // is a constant through each path collection run, ensuring
689 // consistent basis. Otherwise we may later find a
690 // different path to the source node that is more expensive,
691 // but which we consider to be cheaper because we are capacity
692 // constrained and the relative fee becomes lower.
693 match compute_fees(minimal_value_contribution_msat, old_entry.src_lowest_inbound_fees)
694 .map(|a| a.checked_add(total_fee_msat)) {
699 total_fee_msat = u64::max_value();
706 let new_graph_node = RouteGraphNode {
707 pubkey: $src_node_id,
708 lowest_fee_to_peer_through_node: total_fee_msat,
709 lowest_fee_to_node: $next_hops_fee_msat as u64 + hop_use_fee_msat,
710 value_contribution_msat: value_contribution_msat,
711 path_htlc_minimum_msat,
714 // Update the way of reaching $src_node_id with the given $chan_id (from $dest_node_id),
715 // if this way is cheaper than the already known
716 // (considering the cost to "reach" this channel from the route destination,
717 // the cost of using this channel,
718 // and the cost of routing to the source node of this channel).
719 // Also, consider that htlc_minimum_msat_difference, because we might end up
720 // paying it. Consider the following exploit:
721 // we use 2 paths to transfer 1.5 BTC. One of them is 0-fee normal 1 BTC path,
722 // and for the other one we picked a 1sat-fee path with htlc_minimum_msat of
723 // 1 BTC. Now, since the latter is more expensive, we gonna try to cut it
724 // by 0.5 BTC, but then match htlc_minimum_msat by paying a fee of 0.5 BTC
726 // Ideally the scoring could be smarter (e.g. 0.5*htlc_minimum_msat here),
727 // but it may require additional tracking - we don't want to double-count
728 // the fees included in $next_hops_path_htlc_minimum_msat, but also
729 // can't use something that may decrease on future hops.
730 let old_cost = cmp::max(old_entry.total_fee_msat, old_entry.path_htlc_minimum_msat);
731 let new_cost = cmp::max(total_fee_msat, path_htlc_minimum_msat);
733 if !old_entry.was_processed && new_cost < old_cost {
734 targets.push(new_graph_node);
735 old_entry.next_hops_fee_msat = $next_hops_fee_msat;
736 old_entry.hop_use_fee_msat = hop_use_fee_msat;
737 old_entry.total_fee_msat = total_fee_msat;
738 old_entry.pubkey = $dest_node_id.clone();
739 old_entry.short_channel_id = $chan_id.clone();
740 old_entry.channel_features = $chan_features;
741 old_entry.fee_msat = 0; // This value will be later filled with hop_use_fee_msat of the following channel
742 old_entry.cltv_expiry_delta = $directional_info.cltv_expiry_delta as u32;
743 old_entry.channel_fees = $directional_info.fees;
744 old_entry.htlc_minimum_msat = $directional_info.htlc_minimum_msat;
745 old_entry.path_htlc_minimum_msat = path_htlc_minimum_msat;
746 #[cfg(any(test, feature = "fuzztarget"))]
748 old_entry.value_contribution_msat = value_contribution_msat;
750 did_add_update_path_to_src_node = true;
751 } else if old_entry.was_processed && new_cost < old_cost {
752 #[cfg(any(test, feature = "fuzztarget"))]
754 // If we're skipping processing a node which was previously
755 // processed even though we found another path to it with a
756 // cheaper fee, check that it was because the second path we
757 // found (which we are processing now) has a lower value
758 // contribution due to an HTLC minimum limit.
760 // e.g. take a graph with two paths from node 1 to node 2, one
761 // through channel A, and one through channel B. Channel A and
762 // B are both in the to-process heap, with their scores set by
763 // a higher htlc_minimum than fee.
764 // Channel A is processed first, and the channels onwards from
765 // node 1 are added to the to-process heap. Thereafter, we pop
766 // Channel B off of the heap, note that it has a much more
767 // restrictive htlc_maximum_msat, and recalculate the fees for
768 // all of node 1's channels using the new, reduced, amount.
770 // This would be bogus - we'd be selecting a higher-fee path
771 // with a lower htlc_maximum_msat instead of the one we'd
772 // already decided to use.
773 debug_assert!(path_htlc_minimum_msat < old_entry.path_htlc_minimum_msat);
774 debug_assert!(value_contribution_msat < old_entry.value_contribution_msat);
781 did_add_update_path_to_src_node
785 let empty_node_features = NodeFeatures::empty();
786 // Find ways (channels with destination) to reach a given node and store them
787 // in the corresponding data structures (routing graph etc).
788 // $fee_to_target_msat represents how much it costs to reach to this node from the payee,
789 // meaning how much will be paid in fees after this node (to the best of our knowledge).
790 // This data can later be helpful to optimize routing (pay lower fees).
791 macro_rules! add_entries_to_cheapest_to_target_node {
792 ( $node: expr, $node_id: expr, $fee_to_target_msat: expr, $next_hops_value_contribution: expr, $next_hops_path_htlc_minimum_msat: expr ) => {
793 let skip_node = if let Some(elem) = dist.get_mut($node_id) {
794 let was_processed = elem.was_processed;
795 elem.was_processed = true;
798 // Entries are added to dist in add_entry!() when there is a channel from a node.
799 // Because there are no channels from payee, it will not have a dist entry at this point.
800 // If we're processing any other node, it is always be the result of a channel from it.
801 assert_eq!($node_id, payee);
806 if first_hops.is_some() {
807 if let Some(&(ref first_hop, ref features, ref outbound_capacity_msat, _)) = first_hop_targets.get(&$node_id) {
808 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);
812 let features = if let Some(node_info) = $node.announcement_info.as_ref() {
818 if !features.requires_unknown_bits() {
819 for chan_id in $node.channels.iter() {
820 let chan = network_channels.get(chan_id).unwrap();
821 if !chan.features.requires_unknown_bits() {
822 if chan.node_one == *$node_id {
823 // ie $node is one, ie next hop in A* is two, via the two_to_one channel
824 if first_hops.is_none() || chan.node_two != *our_node_id {
825 if let Some(two_to_one) = chan.two_to_one.as_ref() {
826 if two_to_one.enabled {
827 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);
832 if first_hops.is_none() || chan.node_one != *our_node_id {
833 if let Some(one_to_two) = chan.one_to_two.as_ref() {
834 if one_to_two.enabled {
835 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);
847 let mut payment_paths = Vec::<PaymentPath>::new();
849 // TODO: diversify by nodes (so that all paths aren't doomed if one node is offline).
850 'paths_collection: loop {
851 // For every new path, start from scratch, except
852 // bookkeeped_channels_liquidity_available_msat, which will improve
853 // the further iterations of path finding. Also don't erase first_hop_targets.
856 hit_minimum_limit = false;
858 // If first hop is a private channel and the only way to reach the payee, this is the only
859 // place where it could be added.
860 if first_hops.is_some() {
861 if let Some(&(ref first_hop, ref features, ref outbound_capacity_msat, _)) = first_hop_targets.get(&payee) {
862 add_entry!(first_hop, *our_node_id, payee, dummy_directional_info, Some(outbound_capacity_msat / 1000), features, 0, path_value_msat, 0);
866 // Add the payee as a target, so that the payee-to-payer
867 // search algorithm knows what to start with.
868 match network_nodes.get(payee) {
869 // The payee is not in our network graph, so nothing to add here.
870 // There is still a chance of reaching them via last_hops though,
871 // so don't yet fail the payment here.
872 // If not, targets.pop() will not even let us enter the loop in step 2.
875 add_entries_to_cheapest_to_target_node!(node, payee, 0, path_value_msat, 0);
880 // If a caller provided us with last hops, add them to routing targets. Since this happens
881 // earlier than general path finding, they will be somewhat prioritized, although currently
882 // it matters only if the fees are exactly the same.
883 for route in last_hops.iter().filter(|route| !route.0.is_empty()) {
884 let first_hop_in_route = &(route.0)[0];
885 let have_hop_src_in_graph =
886 // Only add the hops in this route to our candidate set if either
887 // we have a direct channel to the first hop or the first hop is
888 // in the regular network graph.
889 first_hop_targets.get(&first_hop_in_route.src_node_id).is_some() ||
890 network_nodes.get(&first_hop_in_route.src_node_id).is_some();
891 if have_hop_src_in_graph {
892 // We start building the path from reverse, i.e., from payee
893 // to the first RouteHintHop in the path.
894 let hop_iter = route.0.iter().rev();
895 let prev_hop_iter = core::iter::once(payee).chain(
896 route.0.iter().skip(1).rev().map(|hop| &hop.src_node_id));
897 let mut hop_used = true;
898 let mut aggregate_next_hops_fee_msat: u64 = 0;
899 let mut aggregate_next_hops_path_htlc_minimum_msat: u64 = 0;
901 for (idx, (hop, prev_hop_id)) in hop_iter.zip(prev_hop_iter).enumerate() {
902 // BOLT 11 doesn't allow inclusion of features for the last hop hints, which
903 // really sucks, cause we're gonna need that eventually.
904 let hop_htlc_minimum_msat: u64 = hop.htlc_minimum_msat.unwrap_or(0);
906 let directional_info = DummyDirectionalChannelInfo {
907 cltv_expiry_delta: hop.cltv_expiry_delta as u32,
908 htlc_minimum_msat: hop_htlc_minimum_msat,
909 htlc_maximum_msat: hop.htlc_maximum_msat,
913 let reqd_channel_cap = if let Some (val) = final_value_msat.checked_add(match idx {
915 _ => aggregate_next_hops_fee_msat.checked_add(999).unwrap_or(u64::max_value())
916 }) { Some( val / 1000 ) } else { break; }; // converting from msat or breaking if max ~ infinity
919 // We assume that the recipient only included route hints for routes which had
920 // sufficient value to route `final_value_msat`. Note that in the case of "0-value"
921 // invoices where the invoice does not specify value this may not be the case, but
922 // better to include the hints than not.
923 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) {
924 // If this hop was not used then there is no use checking the preceding hops
925 // in the RouteHint. We can break by just searching for a direct channel between
926 // last checked hop and first_hop_targets
930 // Searching for a direct channel between last checked hop and first_hop_targets
931 if let Some(&(ref first_hop, ref features, ref outbound_capacity_msat, _)) = first_hop_targets.get(&prev_hop_id) {
932 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);
939 // In the next values of the iterator, the aggregate fees already reflects
940 // the sum of value sent from payer (final_value_msat) and routing fees
941 // for the last node in the RouteHint. We need to just add the fees to
942 // route through the current node so that the preceeding node (next iteration)
944 let hops_fee = compute_fees(aggregate_next_hops_fee_msat + final_value_msat, hop.fees)
945 .map_or(None, |inc| inc.checked_add(aggregate_next_hops_fee_msat));
946 aggregate_next_hops_fee_msat = if let Some(val) = hops_fee { val } else { break; };
948 let hop_htlc_minimum_msat_inc = if let Some(val) = compute_fees(aggregate_next_hops_path_htlc_minimum_msat, hop.fees) { val } else { break; };
949 let hops_path_htlc_minimum = aggregate_next_hops_path_htlc_minimum_msat
950 .checked_add(hop_htlc_minimum_msat_inc);
951 aggregate_next_hops_path_htlc_minimum_msat = if let Some(val) = hops_path_htlc_minimum { cmp::max(hop_htlc_minimum_msat, val) } else { break; };
953 if idx == route.0.len() - 1 {
954 // The last hop in this iterator is the first hop in
955 // overall RouteHint.
956 // If this hop connects to a node with which we have a direct channel,
957 // ignore the network graph and, if the last hop was added, add our
958 // direct channel to the candidate set.
960 // Note that we *must* check if the last hop was added as `add_entry`
961 // always assumes that the third argument is a node to which we have a
963 if let Some(&(ref first_hop, ref features, ref outbound_capacity_msat, _)) = first_hop_targets.get(&hop.src_node_id) {
964 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);
971 log_trace!(logger, "Starting main path collection loop with {} nodes pre-filled from first/last hops.", targets.len());
973 // At this point, targets are filled with the data from first and
974 // last hops communicated by the caller, and the payment receiver.
975 let mut found_new_path = false;
978 // If this loop terminates due the exhaustion of targets, two situations are possible:
979 // - not enough outgoing liquidity:
980 // 0 < already_collected_value_msat < final_value_msat
981 // - enough outgoing liquidity:
982 // final_value_msat <= already_collected_value_msat < recommended_value_msat
983 // Both these cases (and other cases except reaching recommended_value_msat) mean that
984 // paths_collection will be stopped because found_new_path==false.
985 // This is not necessarily a routing failure.
986 'path_construction: while let Some(RouteGraphNode { pubkey, lowest_fee_to_node, value_contribution_msat, path_htlc_minimum_msat, .. }) = targets.pop() {
988 // Since we're going payee-to-payer, hitting our node as a target means we should stop
989 // traversing the graph and arrange the path out of what we found.
990 if pubkey == *our_node_id {
991 let mut new_entry = dist.remove(&our_node_id).unwrap();
992 let mut ordered_hops = vec!((new_entry.clone(), NodeFeatures::empty()));
995 if let Some(&(_, _, _, ref features)) = first_hop_targets.get(&ordered_hops.last().unwrap().0.pubkey) {
996 ordered_hops.last_mut().unwrap().1 = features.clone();
997 } else if let Some(node) = network_nodes.get(&ordered_hops.last().unwrap().0.pubkey) {
998 if let Some(node_info) = node.announcement_info.as_ref() {
999 ordered_hops.last_mut().unwrap().1 = node_info.features.clone();
1001 ordered_hops.last_mut().unwrap().1 = NodeFeatures::empty();
1004 // We should be able to fill in features for everything except the last
1005 // hop, if the last hop was provided via a BOLT 11 invoice (though we
1006 // should be able to extend it further as BOLT 11 does have feature
1007 // flags for the last hop node itself).
1008 assert!(ordered_hops.last().unwrap().0.pubkey == *payee);
1011 // Means we succesfully traversed from the payer to the payee, now
1012 // save this path for the payment route. Also, update the liquidity
1013 // remaining on the used hops, so that we take them into account
1014 // while looking for more paths.
1015 if ordered_hops.last().unwrap().0.pubkey == *payee {
1019 new_entry = match dist.remove(&ordered_hops.last().unwrap().0.pubkey) {
1020 Some(payment_hop) => payment_hop,
1021 // We can't arrive at None because, if we ever add an entry to targets,
1022 // we also fill in the entry in dist (see add_entry!).
1023 None => unreachable!(),
1025 // We "propagate" the fees one hop backward (topologically) here,
1026 // so that fees paid for a HTLC forwarding on the current channel are
1027 // associated with the previous channel (where they will be subtracted).
1028 ordered_hops.last_mut().unwrap().0.fee_msat = new_entry.hop_use_fee_msat;
1029 ordered_hops.last_mut().unwrap().0.cltv_expiry_delta = new_entry.cltv_expiry_delta;
1030 ordered_hops.push((new_entry.clone(), NodeFeatures::empty()));
1032 ordered_hops.last_mut().unwrap().0.fee_msat = value_contribution_msat;
1033 ordered_hops.last_mut().unwrap().0.hop_use_fee_msat = 0;
1034 ordered_hops.last_mut().unwrap().0.cltv_expiry_delta = final_cltv;
1036 log_trace!(logger, "Found a path back to us from the target with {} hops contributing up to {} msat: {:?}",
1037 ordered_hops.len(), value_contribution_msat, ordered_hops);
1039 let mut payment_path = PaymentPath {hops: ordered_hops};
1041 // We could have possibly constructed a slightly inconsistent path: since we reduce
1042 // value being transferred along the way, we could have violated htlc_minimum_msat
1043 // on some channels we already passed (assuming dest->source direction). Here, we
1044 // recompute the fees again, so that if that's the case, we match the currently
1045 // underpaid htlc_minimum_msat with fees.
1046 payment_path.update_value_and_recompute_fees(cmp::min(value_contribution_msat, final_value_msat));
1048 // Since a path allows to transfer as much value as
1049 // the smallest channel it has ("bottleneck"), we should recompute
1050 // the fees so sender HTLC don't overpay fees when traversing
1051 // larger channels than the bottleneck. This may happen because
1052 // when we were selecting those channels we were not aware how much value
1053 // this path will transfer, and the relative fee for them
1054 // might have been computed considering a larger value.
1055 // Remember that we used these channels so that we don't rely
1056 // on the same liquidity in future paths.
1057 let mut prevented_redundant_path_selection = false;
1058 for (payment_hop, _) in payment_path.hops.iter() {
1059 let channel_liquidity_available_msat = bookkeeped_channels_liquidity_available_msat.get_mut(&payment_hop.short_channel_id).unwrap();
1060 let mut spent_on_hop_msat = value_contribution_msat;
1061 let next_hops_fee_msat = payment_hop.next_hops_fee_msat;
1062 spent_on_hop_msat += next_hops_fee_msat;
1063 if spent_on_hop_msat == *channel_liquidity_available_msat {
1064 // If this path used all of this channel's available liquidity, we know
1065 // this path will not be selected again in the next loop iteration.
1066 prevented_redundant_path_selection = true;
1068 *channel_liquidity_available_msat -= spent_on_hop_msat;
1070 if !prevented_redundant_path_selection {
1071 // If we weren't capped by hitting a liquidity limit on a channel in the path,
1072 // we'll probably end up picking the same path again on the next iteration.
1073 // Decrease the available liquidity of a hop in the middle of the path.
1074 let victim_scid = payment_path.hops[(payment_path.hops.len() - 1) / 2].0.short_channel_id;
1075 log_trace!(logger, "Disabling channel {} for future path building iterations to avoid duplicates.", victim_scid);
1076 let victim_liquidity = bookkeeped_channels_liquidity_available_msat.get_mut(&victim_scid).unwrap();
1077 *victim_liquidity = 0;
1080 // Track the total amount all our collected paths allow to send so that we:
1081 // - know when to stop looking for more paths
1082 // - know which of the hops are useless considering how much more sats we need
1083 // (contributes_sufficient_value)
1084 already_collected_value_msat += value_contribution_msat;
1086 payment_paths.push(payment_path);
1087 found_new_path = true;
1088 break 'path_construction;
1091 // If we found a path back to the payee, we shouldn't try to process it again. This is
1092 // the equivalent of the `elem.was_processed` check in
1093 // add_entries_to_cheapest_to_target_node!() (see comment there for more info).
1094 if pubkey == *payee { continue 'path_construction; }
1096 // Otherwise, since the current target node is not us,
1097 // keep "unrolling" the payment graph from payee to payer by
1098 // finding a way to reach the current target from the payer side.
1099 match network_nodes.get(&pubkey) {
1102 add_entries_to_cheapest_to_target_node!(node, &pubkey, lowest_fee_to_node, value_contribution_msat, path_htlc_minimum_msat);
1108 // If we don't support MPP, no use trying to gather more value ever.
1109 break 'paths_collection;
1113 // Stop either when the recommended value is reached or if no new path was found in this
1115 // In the latter case, making another path finding attempt won't help,
1116 // because we deterministically terminated the search due to low liquidity.
1117 if already_collected_value_msat >= recommended_value_msat || !found_new_path {
1118 log_trace!(logger, "Have now collected {} msat (seeking {} msat) in paths. Last path loop {} a new path.",
1119 already_collected_value_msat, recommended_value_msat, if found_new_path { "found" } else { "did not find" });
1120 break 'paths_collection;
1121 } else if found_new_path && already_collected_value_msat == final_value_msat && payment_paths.len() == 1 {
1122 // Further, if this was our first walk of the graph, and we weren't limited by an
1123 // htlc_minimum_msat, return immediately because this path should suffice. If we were
1124 // limited by an htlc_minimum_msat value, find another path with a higher value,
1125 // potentially allowing us to pay fees to meet the htlc_minimum on the new path while
1126 // still keeping a lower total fee than this path.
1127 if !hit_minimum_limit {
1128 log_trace!(logger, "Collected exactly our payment amount on the first pass, without hitting an htlc_minimum_msat limit, exiting.");
1129 break 'paths_collection;
1131 log_trace!(logger, "Collected our payment amount on the first pass, but running again to collect extra paths with a potentially higher limit.");
1132 path_value_msat = recommended_value_msat;
1137 if payment_paths.len() == 0 {
1138 return Err(LightningError{err: "Failed to find a path to the given destination".to_owned(), action: ErrorAction::IgnoreError});
1141 if already_collected_value_msat < final_value_msat {
1142 return Err(LightningError{err: "Failed to find a sufficient route to the given destination".to_owned(), action: ErrorAction::IgnoreError});
1145 // Sort by total fees and take the best paths.
1146 payment_paths.sort_by_key(|path| path.get_total_fee_paid_msat());
1147 if payment_paths.len() > 50 {
1148 payment_paths.truncate(50);
1151 // Draw multiple sufficient routes by randomly combining the selected paths.
1152 let mut drawn_routes = Vec::new();
1153 for i in 0..payment_paths.len() {
1154 let mut cur_route = Vec::<PaymentPath>::new();
1155 let mut aggregate_route_value_msat = 0;
1158 // TODO: real random shuffle
1159 // Currently just starts with i_th and goes up to i-1_th in a looped way.
1160 let cur_payment_paths = [&payment_paths[i..], &payment_paths[..i]].concat();
1163 for payment_path in cur_payment_paths {
1164 cur_route.push(payment_path.clone());
1165 aggregate_route_value_msat += payment_path.get_value_msat();
1166 if aggregate_route_value_msat > final_value_msat {
1167 // Last path likely overpaid. Substract it from the most expensive
1168 // (in terms of proportional fee) path in this route and recompute fees.
1169 // This might be not the most economically efficient way, but fewer paths
1170 // also makes routing more reliable.
1171 let mut overpaid_value_msat = aggregate_route_value_msat - final_value_msat;
1173 // First, drop some expensive low-value paths entirely if possible.
1174 // Sort by value so that we drop many really-low values first, since
1175 // fewer paths is better: the payment is less likely to fail.
1176 // TODO: this could also be optimized by also sorting by feerate_per_sat_routed,
1177 // so that the sender pays less fees overall. And also htlc_minimum_msat.
1178 cur_route.sort_by_key(|path| path.get_value_msat());
1179 // We should make sure that at least 1 path left.
1180 let mut paths_left = cur_route.len();
1181 cur_route.retain(|path| {
1182 if paths_left == 1 {
1185 let mut keep = true;
1186 let path_value_msat = path.get_value_msat();
1187 if path_value_msat <= overpaid_value_msat {
1189 overpaid_value_msat -= path_value_msat;
1195 if overpaid_value_msat == 0 {
1199 assert!(cur_route.len() > 0);
1202 // Now, substract the overpaid value from the most-expensive path.
1203 // TODO: this could also be optimized by also sorting by feerate_per_sat_routed,
1204 // so that the sender pays less fees overall. And also htlc_minimum_msat.
1205 cur_route.sort_by_key(|path| { path.hops.iter().map(|hop| hop.0.channel_fees.proportional_millionths as u64).sum::<u64>() });
1206 let expensive_payment_path = cur_route.first_mut().unwrap();
1207 // We already dropped all the small channels above, meaning all the
1208 // remaining channels are larger than remaining overpaid_value_msat.
1209 // Thus, this can't be negative.
1210 let expensive_path_new_value_msat = expensive_payment_path.get_value_msat() - overpaid_value_msat;
1211 expensive_payment_path.update_value_and_recompute_fees(expensive_path_new_value_msat);
1215 drawn_routes.push(cur_route);
1219 // Select the best route by lowest total fee.
1220 drawn_routes.sort_by_key(|paths| paths.iter().map(|path| path.get_total_fee_paid_msat()).sum::<u64>());
1221 let mut selected_paths = Vec::<Vec<RouteHop>>::new();
1222 for payment_path in drawn_routes.first().unwrap() {
1223 selected_paths.push(payment_path.hops.iter().map(|(payment_hop, node_features)| {
1225 pubkey: payment_hop.pubkey,
1226 node_features: node_features.clone(),
1227 short_channel_id: payment_hop.short_channel_id,
1228 channel_features: payment_hop.channel_features.clone(),
1229 fee_msat: payment_hop.fee_msat,
1230 cltv_expiry_delta: payment_hop.cltv_expiry_delta,
1235 if let Some(features) = &payee_features {
1236 for path in selected_paths.iter_mut() {
1237 path.last_mut().unwrap().node_features = features.to_context();
1241 let route = Route { paths: selected_paths };
1242 log_info!(logger, "Got route to {}: {}", payee, log_route!(route));
1248 use routing::router::{get_route, Route, RouteHint, RouteHintHop, RoutingFees};
1249 use routing::network_graph::{NetworkGraph, NetGraphMsgHandler};
1250 use chain::transaction::OutPoint;
1251 use ln::features::{ChannelFeatures, InitFeatures, InvoiceFeatures, NodeFeatures};
1252 use ln::msgs::{ErrorAction, LightningError, OptionalField, UnsignedChannelAnnouncement, ChannelAnnouncement, RoutingMessageHandler,
1253 NodeAnnouncement, UnsignedNodeAnnouncement, ChannelUpdate, UnsignedChannelUpdate};
1254 use ln::channelmanager;
1255 use util::test_utils;
1256 use util::ser::Writeable;
1258 use bitcoin::hashes::sha256d::Hash as Sha256dHash;
1259 use bitcoin::hashes::Hash;
1260 use bitcoin::network::constants::Network;
1261 use bitcoin::blockdata::constants::genesis_block;
1262 use bitcoin::blockdata::script::Builder;
1263 use bitcoin::blockdata::opcodes;
1264 use bitcoin::blockdata::transaction::TxOut;
1268 use bitcoin::secp256k1::key::{PublicKey,SecretKey};
1269 use bitcoin::secp256k1::{Secp256k1, All};
1272 use sync::{self, Arc};
1274 fn get_channel_details(short_channel_id: Option<u64>, node_id: PublicKey,
1275 features: InitFeatures, outbound_capacity_msat: u64) -> channelmanager::ChannelDetails {
1276 channelmanager::ChannelDetails {
1277 channel_id: [0; 32],
1278 counterparty: channelmanager::ChannelCounterparty {
1281 unspendable_punishment_reserve: 0,
1282 forwarding_info: None,
1284 funding_txo: Some(OutPoint { txid: bitcoin::Txid::from_slice(&[0; 32]).unwrap(), index: 0 }),
1286 channel_value_satoshis: 0,
1288 outbound_capacity_msat,
1289 inbound_capacity_msat: 42,
1290 unspendable_punishment_reserve: None,
1291 confirmations_required: None,
1292 force_close_spend_delay: None,
1293 is_outbound: true, is_funding_locked: true,
1294 is_usable: true, is_public: true,
1298 // Using the same keys for LN and BTC ids
1299 fn add_channel(net_graph_msg_handler: &NetGraphMsgHandler<Arc<test_utils::TestChainSource>, Arc<test_utils::TestLogger>>, secp_ctx: &Secp256k1<All>, node_1_privkey: &SecretKey,
1300 node_2_privkey: &SecretKey, features: ChannelFeatures, short_channel_id: u64) {
1301 let node_id_1 = PublicKey::from_secret_key(&secp_ctx, node_1_privkey);
1302 let node_id_2 = PublicKey::from_secret_key(&secp_ctx, node_2_privkey);
1304 let unsigned_announcement = UnsignedChannelAnnouncement {
1306 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1310 bitcoin_key_1: node_id_1,
1311 bitcoin_key_2: node_id_2,
1312 excess_data: Vec::new(),
1315 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1316 let valid_announcement = ChannelAnnouncement {
1317 node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
1318 node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
1319 bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
1320 bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
1321 contents: unsigned_announcement.clone(),
1323 match net_graph_msg_handler.handle_channel_announcement(&valid_announcement) {
1324 Ok(res) => assert!(res),
1329 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) {
1330 let msghash = hash_to_message!(&Sha256dHash::hash(&update.encode()[..])[..]);
1331 let valid_channel_update = ChannelUpdate {
1332 signature: secp_ctx.sign(&msghash, node_privkey),
1333 contents: update.clone()
1336 match net_graph_msg_handler.handle_channel_update(&valid_channel_update) {
1337 Ok(res) => assert!(res),
1342 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,
1343 features: NodeFeatures, timestamp: u32) {
1344 let node_id = PublicKey::from_secret_key(&secp_ctx, node_privkey);
1345 let unsigned_announcement = UnsignedNodeAnnouncement {
1351 addresses: Vec::new(),
1352 excess_address_data: Vec::new(),
1353 excess_data: Vec::new(),
1355 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1356 let valid_announcement = NodeAnnouncement {
1357 signature: secp_ctx.sign(&msghash, node_privkey),
1358 contents: unsigned_announcement.clone()
1361 match net_graph_msg_handler.handle_node_announcement(&valid_announcement) {
1367 fn get_nodes(secp_ctx: &Secp256k1<All>) -> (SecretKey, PublicKey, Vec<SecretKey>, Vec<PublicKey>) {
1368 let privkeys: Vec<SecretKey> = (2..10).map(|i| {
1369 SecretKey::from_slice(&hex::decode(format!("{:02}", i).repeat(32)).unwrap()[..]).unwrap()
1372 let pubkeys = privkeys.iter().map(|secret| PublicKey::from_secret_key(&secp_ctx, secret)).collect();
1374 let our_privkey = SecretKey::from_slice(&hex::decode("01".repeat(32)).unwrap()[..]).unwrap();
1375 let our_id = PublicKey::from_secret_key(&secp_ctx, &our_privkey);
1377 (our_privkey, our_id, privkeys, pubkeys)
1380 fn id_to_feature_flags(id: u8) -> Vec<u8> {
1381 // Set the feature flags to the id'th odd (ie non-required) feature bit so that we can
1382 // test for it later.
1383 let idx = (id - 1) * 2 + 1;
1385 vec![1 << (idx - 8*3), 0, 0, 0]
1386 } else if idx > 8*2 {
1387 vec![1 << (idx - 8*2), 0, 0]
1388 } else if idx > 8*1 {
1389 vec![1 << (idx - 8*1), 0]
1395 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>) {
1396 let secp_ctx = Secp256k1::new();
1397 let logger = Arc::new(test_utils::TestLogger::new());
1398 let chain_monitor = Arc::new(test_utils::TestChainSource::new(Network::Testnet));
1399 let net_graph_msg_handler = NetGraphMsgHandler::new(genesis_block(Network::Testnet).header.block_hash(), None, Arc::clone(&logger));
1400 // Build network from our_id to node6:
1402 // -1(1)2- node0 -1(3)2-
1404 // our_id -1(12)2- node7 -1(13)2--- node2
1406 // -1(2)2- node1 -1(4)2-
1409 // chan1 1-to-2: disabled
1410 // chan1 2-to-1: enabled, 0 fee
1412 // chan2 1-to-2: enabled, ignored fee
1413 // chan2 2-to-1: enabled, 0 fee
1415 // chan3 1-to-2: enabled, 0 fee
1416 // chan3 2-to-1: enabled, 100 msat fee
1418 // chan4 1-to-2: enabled, 100% fee
1419 // chan4 2-to-1: enabled, 0 fee
1421 // chan12 1-to-2: enabled, ignored fee
1422 // chan12 2-to-1: enabled, 0 fee
1424 // chan13 1-to-2: enabled, 200% fee
1425 // chan13 2-to-1: enabled, 0 fee
1428 // -1(5)2- node3 -1(8)2--
1432 // node2--1(6)2- node4 -1(9)2--- node6 (not in global route map)
1434 // -1(7)2- node5 -1(10)2-
1436 // Channels 5, 8, 9 and 10 are private channels.
1438 // chan5 1-to-2: enabled, 100 msat fee
1439 // chan5 2-to-1: enabled, 0 fee
1441 // chan6 1-to-2: enabled, 0 fee
1442 // chan6 2-to-1: enabled, 0 fee
1444 // chan7 1-to-2: enabled, 100% fee
1445 // chan7 2-to-1: enabled, 0 fee
1447 // chan8 1-to-2: enabled, variable fee (0 then 1000 msat)
1448 // chan8 2-to-1: enabled, 0 fee
1450 // chan9 1-to-2: enabled, 1001 msat fee
1451 // chan9 2-to-1: enabled, 0 fee
1453 // chan10 1-to-2: enabled, 0 fee
1454 // chan10 2-to-1: enabled, 0 fee
1456 // chan11 1-to-2: enabled, 0 fee
1457 // chan11 2-to-1: enabled, 0 fee
1459 let (our_privkey, _, privkeys, _) = get_nodes(&secp_ctx);
1461 add_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, &privkeys[0], ChannelFeatures::from_le_bytes(id_to_feature_flags(1)), 1);
1462 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
1463 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1464 short_channel_id: 1,
1467 cltv_expiry_delta: 0,
1468 htlc_minimum_msat: 0,
1469 htlc_maximum_msat: OptionalField::Absent,
1471 fee_proportional_millionths: 0,
1472 excess_data: Vec::new()
1475 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[0], NodeFeatures::from_le_bytes(id_to_feature_flags(1)), 0);
1477 add_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, &privkeys[1], ChannelFeatures::from_le_bytes(id_to_feature_flags(2)), 2);
1478 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
1479 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1480 short_channel_id: 2,
1483 cltv_expiry_delta: u16::max_value(),
1484 htlc_minimum_msat: 0,
1485 htlc_maximum_msat: OptionalField::Absent,
1486 fee_base_msat: u32::max_value(),
1487 fee_proportional_millionths: u32::max_value(),
1488 excess_data: Vec::new()
1490 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
1491 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1492 short_channel_id: 2,
1495 cltv_expiry_delta: 0,
1496 htlc_minimum_msat: 0,
1497 htlc_maximum_msat: OptionalField::Absent,
1499 fee_proportional_millionths: 0,
1500 excess_data: Vec::new()
1503 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[1], NodeFeatures::from_le_bytes(id_to_feature_flags(2)), 0);
1505 add_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, &privkeys[7], ChannelFeatures::from_le_bytes(id_to_feature_flags(12)), 12);
1506 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
1507 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1508 short_channel_id: 12,
1511 cltv_expiry_delta: u16::max_value(),
1512 htlc_minimum_msat: 0,
1513 htlc_maximum_msat: OptionalField::Absent,
1514 fee_base_msat: u32::max_value(),
1515 fee_proportional_millionths: u32::max_value(),
1516 excess_data: Vec::new()
1518 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
1519 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1520 short_channel_id: 12,
1523 cltv_expiry_delta: 0,
1524 htlc_minimum_msat: 0,
1525 htlc_maximum_msat: OptionalField::Absent,
1527 fee_proportional_millionths: 0,
1528 excess_data: Vec::new()
1531 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[7], NodeFeatures::from_le_bytes(id_to_feature_flags(8)), 0);
1533 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], &privkeys[2], ChannelFeatures::from_le_bytes(id_to_feature_flags(3)), 3);
1534 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
1535 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1536 short_channel_id: 3,
1539 cltv_expiry_delta: (3 << 8) | 1,
1540 htlc_minimum_msat: 0,
1541 htlc_maximum_msat: OptionalField::Absent,
1543 fee_proportional_millionths: 0,
1544 excess_data: Vec::new()
1546 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
1547 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1548 short_channel_id: 3,
1551 cltv_expiry_delta: (3 << 8) | 2,
1552 htlc_minimum_msat: 0,
1553 htlc_maximum_msat: OptionalField::Absent,
1555 fee_proportional_millionths: 0,
1556 excess_data: Vec::new()
1559 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], &privkeys[2], ChannelFeatures::from_le_bytes(id_to_feature_flags(4)), 4);
1560 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
1561 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1562 short_channel_id: 4,
1565 cltv_expiry_delta: (4 << 8) | 1,
1566 htlc_minimum_msat: 0,
1567 htlc_maximum_msat: OptionalField::Absent,
1569 fee_proportional_millionths: 1000000,
1570 excess_data: Vec::new()
1572 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
1573 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1574 short_channel_id: 4,
1577 cltv_expiry_delta: (4 << 8) | 2,
1578 htlc_minimum_msat: 0,
1579 htlc_maximum_msat: OptionalField::Absent,
1581 fee_proportional_millionths: 0,
1582 excess_data: Vec::new()
1585 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], &privkeys[2], ChannelFeatures::from_le_bytes(id_to_feature_flags(13)), 13);
1586 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
1587 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1588 short_channel_id: 13,
1591 cltv_expiry_delta: (13 << 8) | 1,
1592 htlc_minimum_msat: 0,
1593 htlc_maximum_msat: OptionalField::Absent,
1595 fee_proportional_millionths: 2000000,
1596 excess_data: Vec::new()
1598 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
1599 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1600 short_channel_id: 13,
1603 cltv_expiry_delta: (13 << 8) | 2,
1604 htlc_minimum_msat: 0,
1605 htlc_maximum_msat: OptionalField::Absent,
1607 fee_proportional_millionths: 0,
1608 excess_data: Vec::new()
1611 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[2], NodeFeatures::from_le_bytes(id_to_feature_flags(3)), 0);
1613 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], &privkeys[4], ChannelFeatures::from_le_bytes(id_to_feature_flags(6)), 6);
1614 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
1615 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1616 short_channel_id: 6,
1619 cltv_expiry_delta: (6 << 8) | 1,
1620 htlc_minimum_msat: 0,
1621 htlc_maximum_msat: OptionalField::Absent,
1623 fee_proportional_millionths: 0,
1624 excess_data: Vec::new()
1626 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
1627 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1628 short_channel_id: 6,
1631 cltv_expiry_delta: (6 << 8) | 2,
1632 htlc_minimum_msat: 0,
1633 htlc_maximum_msat: OptionalField::Absent,
1635 fee_proportional_millionths: 0,
1636 excess_data: Vec::new(),
1639 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(11)), 11);
1640 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
1641 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1642 short_channel_id: 11,
1645 cltv_expiry_delta: (11 << 8) | 1,
1646 htlc_minimum_msat: 0,
1647 htlc_maximum_msat: OptionalField::Absent,
1649 fee_proportional_millionths: 0,
1650 excess_data: Vec::new()
1652 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[3], UnsignedChannelUpdate {
1653 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1654 short_channel_id: 11,
1657 cltv_expiry_delta: (11 << 8) | 2,
1658 htlc_minimum_msat: 0,
1659 htlc_maximum_msat: OptionalField::Absent,
1661 fee_proportional_millionths: 0,
1662 excess_data: Vec::new()
1665 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[4], NodeFeatures::from_le_bytes(id_to_feature_flags(5)), 0);
1667 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[3], NodeFeatures::from_le_bytes(id_to_feature_flags(4)), 0);
1669 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], &privkeys[5], ChannelFeatures::from_le_bytes(id_to_feature_flags(7)), 7);
1670 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
1671 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1672 short_channel_id: 7,
1675 cltv_expiry_delta: (7 << 8) | 1,
1676 htlc_minimum_msat: 0,
1677 htlc_maximum_msat: OptionalField::Absent,
1679 fee_proportional_millionths: 1000000,
1680 excess_data: Vec::new()
1682 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[5], UnsignedChannelUpdate {
1683 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1684 short_channel_id: 7,
1687 cltv_expiry_delta: (7 << 8) | 2,
1688 htlc_minimum_msat: 0,
1689 htlc_maximum_msat: OptionalField::Absent,
1691 fee_proportional_millionths: 0,
1692 excess_data: Vec::new()
1695 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[5], NodeFeatures::from_le_bytes(id_to_feature_flags(6)), 0);
1697 (secp_ctx, net_graph_msg_handler, chain_monitor, logger)
1701 fn simple_route_test() {
1702 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
1703 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
1705 // Simple route to 2 via 1
1707 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id, &net_graph_msg_handler.network_graph, &nodes[2], None, None, &Vec::new(), 0, 42, Arc::clone(&logger)) {
1708 assert_eq!(err, "Cannot send a payment of 0 msat");
1709 } else { panic!(); }
1711 let route = get_route(&our_id, &net_graph_msg_handler.network_graph, &nodes[2], None, None, &Vec::new(), 100, 42, Arc::clone(&logger)).unwrap();
1712 assert_eq!(route.paths[0].len(), 2);
1714 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
1715 assert_eq!(route.paths[0][0].short_channel_id, 2);
1716 assert_eq!(route.paths[0][0].fee_msat, 100);
1717 assert_eq!(route.paths[0][0].cltv_expiry_delta, (4 << 8) | 1);
1718 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
1719 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
1721 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
1722 assert_eq!(route.paths[0][1].short_channel_id, 4);
1723 assert_eq!(route.paths[0][1].fee_msat, 100);
1724 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
1725 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
1726 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
1730 fn invalid_first_hop_test() {
1731 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
1732 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
1734 // Simple route to 2 via 1
1736 let our_chans = vec![get_channel_details(Some(2), our_id, InitFeatures::from_le_bytes(vec![0b11]), 100000)];
1738 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id, &net_graph_msg_handler.network_graph, &nodes[2], None, Some(&our_chans.iter().collect::<Vec<_>>()), &Vec::new(), 100, 42, Arc::clone(&logger)) {
1739 assert_eq!(err, "First hop cannot have our_node_id as a destination.");
1740 } else { panic!(); }
1742 let route = get_route(&our_id, &net_graph_msg_handler.network_graph, &nodes[2], None, None, &Vec::new(), 100, 42, Arc::clone(&logger)).unwrap();
1743 assert_eq!(route.paths[0].len(), 2);
1747 fn htlc_minimum_test() {
1748 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
1749 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
1751 // Simple route to 2 via 1
1753 // Disable other paths
1754 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
1755 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1756 short_channel_id: 12,
1758 flags: 2, // to disable
1759 cltv_expiry_delta: 0,
1760 htlc_minimum_msat: 0,
1761 htlc_maximum_msat: OptionalField::Absent,
1763 fee_proportional_millionths: 0,
1764 excess_data: Vec::new()
1766 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
1767 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1768 short_channel_id: 3,
1770 flags: 2, // to disable
1771 cltv_expiry_delta: 0,
1772 htlc_minimum_msat: 0,
1773 htlc_maximum_msat: OptionalField::Absent,
1775 fee_proportional_millionths: 0,
1776 excess_data: Vec::new()
1778 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
1779 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1780 short_channel_id: 13,
1782 flags: 2, // to disable
1783 cltv_expiry_delta: 0,
1784 htlc_minimum_msat: 0,
1785 htlc_maximum_msat: OptionalField::Absent,
1787 fee_proportional_millionths: 0,
1788 excess_data: Vec::new()
1790 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
1791 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1792 short_channel_id: 6,
1794 flags: 2, // to disable
1795 cltv_expiry_delta: 0,
1796 htlc_minimum_msat: 0,
1797 htlc_maximum_msat: OptionalField::Absent,
1799 fee_proportional_millionths: 0,
1800 excess_data: Vec::new()
1802 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
1803 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1804 short_channel_id: 7,
1806 flags: 2, // to disable
1807 cltv_expiry_delta: 0,
1808 htlc_minimum_msat: 0,
1809 htlc_maximum_msat: OptionalField::Absent,
1811 fee_proportional_millionths: 0,
1812 excess_data: Vec::new()
1815 // Check against amount_to_transfer_over_msat.
1816 // Set minimal HTLC of 200_000_000 msat.
1817 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
1818 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1819 short_channel_id: 2,
1822 cltv_expiry_delta: 0,
1823 htlc_minimum_msat: 200_000_000,
1824 htlc_maximum_msat: OptionalField::Absent,
1826 fee_proportional_millionths: 0,
1827 excess_data: Vec::new()
1830 // Second hop only allows to forward 199_999_999 at most, thus not allowing the first hop to
1832 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
1833 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1834 short_channel_id: 4,
1837 cltv_expiry_delta: 0,
1838 htlc_minimum_msat: 0,
1839 htlc_maximum_msat: OptionalField::Present(199_999_999),
1841 fee_proportional_millionths: 0,
1842 excess_data: Vec::new()
1845 // Not possible to send 199_999_999, because the minimum on channel=2 is 200_000_000.
1846 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id, &net_graph_msg_handler.network_graph, &nodes[2], None, None, &Vec::new(), 199_999_999, 42, Arc::clone(&logger)) {
1847 assert_eq!(err, "Failed to find a path to the given destination");
1848 } else { panic!(); }
1850 // Lift the restriction on the first hop.
1851 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
1852 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1853 short_channel_id: 2,
1856 cltv_expiry_delta: 0,
1857 htlc_minimum_msat: 0,
1858 htlc_maximum_msat: OptionalField::Absent,
1860 fee_proportional_millionths: 0,
1861 excess_data: Vec::new()
1864 // A payment above the minimum should pass
1865 let route = get_route(&our_id, &net_graph_msg_handler.network_graph, &nodes[2], None, None, &Vec::new(), 199_999_999, 42, Arc::clone(&logger)).unwrap();
1866 assert_eq!(route.paths[0].len(), 2);
1870 fn htlc_minimum_overpay_test() {
1871 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
1872 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
1874 // A route to node#2 via two paths.
1875 // One path allows transferring 35-40 sats, another one also allows 35-40 sats.
1876 // Thus, they can't send 60 without overpaying.
1877 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
1878 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1879 short_channel_id: 2,
1882 cltv_expiry_delta: 0,
1883 htlc_minimum_msat: 35_000,
1884 htlc_maximum_msat: OptionalField::Present(40_000),
1886 fee_proportional_millionths: 0,
1887 excess_data: Vec::new()
1889 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
1890 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1891 short_channel_id: 12,
1894 cltv_expiry_delta: 0,
1895 htlc_minimum_msat: 35_000,
1896 htlc_maximum_msat: OptionalField::Present(40_000),
1898 fee_proportional_millionths: 0,
1899 excess_data: Vec::new()
1903 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
1904 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1905 short_channel_id: 13,
1908 cltv_expiry_delta: 0,
1909 htlc_minimum_msat: 0,
1910 htlc_maximum_msat: OptionalField::Absent,
1912 fee_proportional_millionths: 0,
1913 excess_data: Vec::new()
1915 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
1916 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1917 short_channel_id: 4,
1920 cltv_expiry_delta: 0,
1921 htlc_minimum_msat: 0,
1922 htlc_maximum_msat: OptionalField::Absent,
1924 fee_proportional_millionths: 0,
1925 excess_data: Vec::new()
1928 // Disable other paths
1929 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
1930 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1931 short_channel_id: 1,
1933 flags: 2, // to disable
1934 cltv_expiry_delta: 0,
1935 htlc_minimum_msat: 0,
1936 htlc_maximum_msat: OptionalField::Absent,
1938 fee_proportional_millionths: 0,
1939 excess_data: Vec::new()
1942 let route = get_route(&our_id, &net_graph_msg_handler.network_graph, &nodes[2],
1943 Some(InvoiceFeatures::known()), None, &Vec::new(), 60_000, 42, Arc::clone(&logger)).unwrap();
1944 // Overpay fees to hit htlc_minimum_msat.
1945 let overpaid_fees = route.paths[0][0].fee_msat + route.paths[1][0].fee_msat;
1946 // TODO: this could be better balanced to overpay 10k and not 15k.
1947 assert_eq!(overpaid_fees, 15_000);
1949 // Now, test that if there are 2 paths, a "cheaper" by fee path wouldn't be prioritized
1950 // while taking even more fee to match htlc_minimum_msat.
1951 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
1952 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1953 short_channel_id: 12,
1956 cltv_expiry_delta: 0,
1957 htlc_minimum_msat: 65_000,
1958 htlc_maximum_msat: OptionalField::Present(80_000),
1960 fee_proportional_millionths: 0,
1961 excess_data: Vec::new()
1963 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
1964 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1965 short_channel_id: 2,
1968 cltv_expiry_delta: 0,
1969 htlc_minimum_msat: 0,
1970 htlc_maximum_msat: OptionalField::Absent,
1972 fee_proportional_millionths: 0,
1973 excess_data: Vec::new()
1975 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
1976 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1977 short_channel_id: 4,
1980 cltv_expiry_delta: 0,
1981 htlc_minimum_msat: 0,
1982 htlc_maximum_msat: OptionalField::Absent,
1984 fee_proportional_millionths: 100_000,
1985 excess_data: Vec::new()
1988 let route = get_route(&our_id, &net_graph_msg_handler.network_graph, &nodes[2],
1989 Some(InvoiceFeatures::known()), None, &Vec::new(), 60_000, 42, Arc::clone(&logger)).unwrap();
1990 // Fine to overpay for htlc_minimum_msat if it allows us to save fee.
1991 assert_eq!(route.paths.len(), 1);
1992 assert_eq!(route.paths[0][0].short_channel_id, 12);
1993 let fees = route.paths[0][0].fee_msat;
1994 assert_eq!(fees, 5_000);
1996 let route = get_route(&our_id, &net_graph_msg_handler.network_graph, &nodes[2],
1997 Some(InvoiceFeatures::known()), None, &Vec::new(), 50_000, 42, Arc::clone(&logger)).unwrap();
1998 // Not fine to overpay for htlc_minimum_msat if it requires paying more than fee on
1999 // the other channel.
2000 assert_eq!(route.paths.len(), 1);
2001 assert_eq!(route.paths[0][0].short_channel_id, 2);
2002 let fees = route.paths[0][0].fee_msat;
2003 assert_eq!(fees, 5_000);
2007 fn disable_channels_test() {
2008 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
2009 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
2011 // // Disable channels 4 and 12 by flags=2
2012 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
2013 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2014 short_channel_id: 4,
2016 flags: 2, // to disable
2017 cltv_expiry_delta: 0,
2018 htlc_minimum_msat: 0,
2019 htlc_maximum_msat: OptionalField::Absent,
2021 fee_proportional_millionths: 0,
2022 excess_data: Vec::new()
2024 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2025 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2026 short_channel_id: 12,
2028 flags: 2, // to disable
2029 cltv_expiry_delta: 0,
2030 htlc_minimum_msat: 0,
2031 htlc_maximum_msat: OptionalField::Absent,
2033 fee_proportional_millionths: 0,
2034 excess_data: Vec::new()
2037 // If all the channels require some features we don't understand, route should fail
2038 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id, &net_graph_msg_handler.network_graph, &nodes[2], None, None, &Vec::new(), 100, 42, Arc::clone(&logger)) {
2039 assert_eq!(err, "Failed to find a path to the given destination");
2040 } else { panic!(); }
2042 // If we specify a channel to node7, that overrides our local channel view and that gets used
2043 let our_chans = vec![get_channel_details(Some(42), nodes[7].clone(), InitFeatures::from_le_bytes(vec![0b11]), 250_000_000)];
2044 let route = get_route(&our_id, &net_graph_msg_handler.network_graph, &nodes[2], None, Some(&our_chans.iter().collect::<Vec<_>>()), &Vec::new(), 100, 42, Arc::clone(&logger)).unwrap();
2045 assert_eq!(route.paths[0].len(), 2);
2047 assert_eq!(route.paths[0][0].pubkey, nodes[7]);
2048 assert_eq!(route.paths[0][0].short_channel_id, 42);
2049 assert_eq!(route.paths[0][0].fee_msat, 200);
2050 assert_eq!(route.paths[0][0].cltv_expiry_delta, (13 << 8) | 1);
2051 assert_eq!(route.paths[0][0].node_features.le_flags(), &vec![0b11]); // it should also override our view of their features
2052 assert_eq!(route.paths[0][0].channel_features.le_flags(), &Vec::<u8>::new()); // No feature flags will meet the relevant-to-channel conversion
2054 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2055 assert_eq!(route.paths[0][1].short_channel_id, 13);
2056 assert_eq!(route.paths[0][1].fee_msat, 100);
2057 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
2058 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2059 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(13));
2063 fn disable_node_test() {
2064 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
2065 let (_, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
2067 // Disable nodes 1, 2, and 8 by requiring unknown feature bits
2068 let unknown_features = NodeFeatures::known().set_unknown_feature_required();
2069 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[0], unknown_features.clone(), 1);
2070 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[1], unknown_features.clone(), 1);
2071 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[7], unknown_features.clone(), 1);
2073 // If all nodes require some features we don't understand, route should fail
2074 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id, &net_graph_msg_handler.network_graph, &nodes[2], None, None, &Vec::new(), 100, 42, Arc::clone(&logger)) {
2075 assert_eq!(err, "Failed to find a path to the given destination");
2076 } else { panic!(); }
2078 // If we specify a channel to node7, that overrides our local channel view and that gets used
2079 let our_chans = vec![get_channel_details(Some(42), nodes[7].clone(), InitFeatures::from_le_bytes(vec![0b11]), 250_000_000)];
2080 let route = get_route(&our_id, &net_graph_msg_handler.network_graph, &nodes[2], None, Some(&our_chans.iter().collect::<Vec<_>>()), &Vec::new(), 100, 42, Arc::clone(&logger)).unwrap();
2081 assert_eq!(route.paths[0].len(), 2);
2083 assert_eq!(route.paths[0][0].pubkey, nodes[7]);
2084 assert_eq!(route.paths[0][0].short_channel_id, 42);
2085 assert_eq!(route.paths[0][0].fee_msat, 200);
2086 assert_eq!(route.paths[0][0].cltv_expiry_delta, (13 << 8) | 1);
2087 assert_eq!(route.paths[0][0].node_features.le_flags(), &vec![0b11]); // it should also override our view of their features
2088 assert_eq!(route.paths[0][0].channel_features.le_flags(), &Vec::<u8>::new()); // No feature flags will meet the relevant-to-channel conversion
2090 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2091 assert_eq!(route.paths[0][1].short_channel_id, 13);
2092 assert_eq!(route.paths[0][1].fee_msat, 100);
2093 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
2094 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2095 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(13));
2097 // Note that we don't test disabling node 3 and failing to route to it, as we (somewhat
2098 // naively) assume that the user checked the feature bits on the invoice, which override
2099 // the node_announcement.
2103 fn our_chans_test() {
2104 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
2105 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
2107 // Route to 1 via 2 and 3 because our channel to 1 is disabled
2108 let route = get_route(&our_id, &net_graph_msg_handler.network_graph, &nodes[0], None, None, &Vec::new(), 100, 42, Arc::clone(&logger)).unwrap();
2109 assert_eq!(route.paths[0].len(), 3);
2111 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
2112 assert_eq!(route.paths[0][0].short_channel_id, 2);
2113 assert_eq!(route.paths[0][0].fee_msat, 200);
2114 assert_eq!(route.paths[0][0].cltv_expiry_delta, (4 << 8) | 1);
2115 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
2116 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
2118 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2119 assert_eq!(route.paths[0][1].short_channel_id, 4);
2120 assert_eq!(route.paths[0][1].fee_msat, 100);
2121 assert_eq!(route.paths[0][1].cltv_expiry_delta, (3 << 8) | 2);
2122 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2123 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
2125 assert_eq!(route.paths[0][2].pubkey, nodes[0]);
2126 assert_eq!(route.paths[0][2].short_channel_id, 3);
2127 assert_eq!(route.paths[0][2].fee_msat, 100);
2128 assert_eq!(route.paths[0][2].cltv_expiry_delta, 42);
2129 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(1));
2130 assert_eq!(route.paths[0][2].channel_features.le_flags(), &id_to_feature_flags(3));
2132 // If we specify a channel to node7, that overrides our local channel view and that gets used
2133 let our_chans = vec![get_channel_details(Some(42), nodes[7].clone(), InitFeatures::from_le_bytes(vec![0b11]), 250_000_000)];
2134 let route = get_route(&our_id, &net_graph_msg_handler.network_graph, &nodes[2], None, Some(&our_chans.iter().collect::<Vec<_>>()), &Vec::new(), 100, 42, Arc::clone(&logger)).unwrap();
2135 assert_eq!(route.paths[0].len(), 2);
2137 assert_eq!(route.paths[0][0].pubkey, nodes[7]);
2138 assert_eq!(route.paths[0][0].short_channel_id, 42);
2139 assert_eq!(route.paths[0][0].fee_msat, 200);
2140 assert_eq!(route.paths[0][0].cltv_expiry_delta, (13 << 8) | 1);
2141 assert_eq!(route.paths[0][0].node_features.le_flags(), &vec![0b11]);
2142 assert_eq!(route.paths[0][0].channel_features.le_flags(), &Vec::<u8>::new()); // No feature flags will meet the relevant-to-channel conversion
2144 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2145 assert_eq!(route.paths[0][1].short_channel_id, 13);
2146 assert_eq!(route.paths[0][1].fee_msat, 100);
2147 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
2148 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2149 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(13));
2152 fn last_hops(nodes: &Vec<PublicKey>) -> Vec<RouteHint> {
2153 let zero_fees = RoutingFees {
2155 proportional_millionths: 0,
2157 vec![RouteHint(vec![RouteHintHop {
2158 src_node_id: nodes[3].clone(),
2159 short_channel_id: 8,
2161 cltv_expiry_delta: (8 << 8) | 1,
2162 htlc_minimum_msat: None,
2163 htlc_maximum_msat: None,
2165 ]), RouteHint(vec![RouteHintHop {
2166 src_node_id: nodes[4].clone(),
2167 short_channel_id: 9,
2170 proportional_millionths: 0,
2172 cltv_expiry_delta: (9 << 8) | 1,
2173 htlc_minimum_msat: None,
2174 htlc_maximum_msat: None,
2175 }]), RouteHint(vec![RouteHintHop {
2176 src_node_id: nodes[5].clone(),
2177 short_channel_id: 10,
2179 cltv_expiry_delta: (10 << 8) | 1,
2180 htlc_minimum_msat: None,
2181 htlc_maximum_msat: None,
2185 fn last_hops_multi_private_channels(nodes: &Vec<PublicKey>) -> Vec<RouteHint> {
2186 let zero_fees = RoutingFees {
2188 proportional_millionths: 0,
2190 vec![RouteHint(vec![RouteHintHop {
2191 src_node_id: nodes[2].clone(),
2192 short_channel_id: 5,
2195 proportional_millionths: 0,
2197 cltv_expiry_delta: (5 << 8) | 1,
2198 htlc_minimum_msat: None,
2199 htlc_maximum_msat: None,
2201 src_node_id: nodes[3].clone(),
2202 short_channel_id: 8,
2204 cltv_expiry_delta: (8 << 8) | 1,
2205 htlc_minimum_msat: None,
2206 htlc_maximum_msat: None,
2208 ]), RouteHint(vec![RouteHintHop {
2209 src_node_id: nodes[4].clone(),
2210 short_channel_id: 9,
2213 proportional_millionths: 0,
2215 cltv_expiry_delta: (9 << 8) | 1,
2216 htlc_minimum_msat: None,
2217 htlc_maximum_msat: None,
2218 }]), RouteHint(vec![RouteHintHop {
2219 src_node_id: nodes[5].clone(),
2220 short_channel_id: 10,
2222 cltv_expiry_delta: (10 << 8) | 1,
2223 htlc_minimum_msat: None,
2224 htlc_maximum_msat: None,
2229 fn partial_route_hint_test() {
2230 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
2231 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
2233 // Simple test across 2, 3, 5, and 4 via a last_hop channel
2234 // Tests the behaviour when the RouteHint contains a suboptimal hop.
2235 // RouteHint may be partially used by the algo to build the best path.
2237 // First check that last hop can't have its source as the payee.
2238 let invalid_last_hop = RouteHint(vec![RouteHintHop {
2239 src_node_id: nodes[6],
2240 short_channel_id: 8,
2243 proportional_millionths: 0,
2245 cltv_expiry_delta: (8 << 8) | 1,
2246 htlc_minimum_msat: None,
2247 htlc_maximum_msat: None,
2250 let mut invalid_last_hops = last_hops_multi_private_channels(&nodes);
2251 invalid_last_hops.push(invalid_last_hop);
2253 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id, &net_graph_msg_handler.network_graph, &nodes[6], None, None, &invalid_last_hops.iter().collect::<Vec<_>>(), 100, 42, Arc::clone(&logger)) {
2254 assert_eq!(err, "Last hop cannot have a payee as a source.");
2255 } else { panic!(); }
2258 let route = get_route(&our_id, &net_graph_msg_handler.network_graph, &nodes[6], None, None, &last_hops_multi_private_channels(&nodes).iter().collect::<Vec<_>>(), 100, 42, Arc::clone(&logger)).unwrap();
2259 assert_eq!(route.paths[0].len(), 5);
2261 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
2262 assert_eq!(route.paths[0][0].short_channel_id, 2);
2263 assert_eq!(route.paths[0][0].fee_msat, 100);
2264 assert_eq!(route.paths[0][0].cltv_expiry_delta, (4 << 8) | 1);
2265 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
2266 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
2268 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2269 assert_eq!(route.paths[0][1].short_channel_id, 4);
2270 assert_eq!(route.paths[0][1].fee_msat, 0);
2271 assert_eq!(route.paths[0][1].cltv_expiry_delta, (6 << 8) | 1);
2272 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2273 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
2275 assert_eq!(route.paths[0][2].pubkey, nodes[4]);
2276 assert_eq!(route.paths[0][2].short_channel_id, 6);
2277 assert_eq!(route.paths[0][2].fee_msat, 0);
2278 assert_eq!(route.paths[0][2].cltv_expiry_delta, (11 << 8) | 1);
2279 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(5));
2280 assert_eq!(route.paths[0][2].channel_features.le_flags(), &id_to_feature_flags(6));
2282 assert_eq!(route.paths[0][3].pubkey, nodes[3]);
2283 assert_eq!(route.paths[0][3].short_channel_id, 11);
2284 assert_eq!(route.paths[0][3].fee_msat, 0);
2285 assert_eq!(route.paths[0][3].cltv_expiry_delta, (8 << 8) | 1);
2286 // If we have a peer in the node map, we'll use their features here since we don't have
2287 // a way of figuring out their features from the invoice:
2288 assert_eq!(route.paths[0][3].node_features.le_flags(), &id_to_feature_flags(4));
2289 assert_eq!(route.paths[0][3].channel_features.le_flags(), &id_to_feature_flags(11));
2291 assert_eq!(route.paths[0][4].pubkey, nodes[6]);
2292 assert_eq!(route.paths[0][4].short_channel_id, 8);
2293 assert_eq!(route.paths[0][4].fee_msat, 100);
2294 assert_eq!(route.paths[0][4].cltv_expiry_delta, 42);
2295 assert_eq!(route.paths[0][4].node_features.le_flags(), &Vec::<u8>::new()); // We dont pass flags in from invoices yet
2296 assert_eq!(route.paths[0][4].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
2299 fn empty_last_hop(nodes: &Vec<PublicKey>) -> Vec<RouteHint> {
2300 let zero_fees = RoutingFees {
2302 proportional_millionths: 0,
2304 vec![RouteHint(vec![RouteHintHop {
2305 src_node_id: nodes[3].clone(),
2306 short_channel_id: 8,
2308 cltv_expiry_delta: (8 << 8) | 1,
2309 htlc_minimum_msat: None,
2310 htlc_maximum_msat: None,
2311 }]), RouteHint(vec![
2313 ]), RouteHint(vec![RouteHintHop {
2314 src_node_id: nodes[5].clone(),
2315 short_channel_id: 10,
2317 cltv_expiry_delta: (10 << 8) | 1,
2318 htlc_minimum_msat: None,
2319 htlc_maximum_msat: None,
2324 fn ignores_empty_last_hops_test() {
2325 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
2326 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
2328 // Test handling of an empty RouteHint passed in Invoice.
2330 let route = get_route(&our_id, &net_graph_msg_handler.network_graph, &nodes[6], None, None, &empty_last_hop(&nodes).iter().collect::<Vec<_>>(), 100, 42, Arc::clone(&logger)).unwrap();
2331 assert_eq!(route.paths[0].len(), 5);
2333 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
2334 assert_eq!(route.paths[0][0].short_channel_id, 2);
2335 assert_eq!(route.paths[0][0].fee_msat, 100);
2336 assert_eq!(route.paths[0][0].cltv_expiry_delta, (4 << 8) | 1);
2337 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
2338 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
2340 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2341 assert_eq!(route.paths[0][1].short_channel_id, 4);
2342 assert_eq!(route.paths[0][1].fee_msat, 0);
2343 assert_eq!(route.paths[0][1].cltv_expiry_delta, (6 << 8) | 1);
2344 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2345 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
2347 assert_eq!(route.paths[0][2].pubkey, nodes[4]);
2348 assert_eq!(route.paths[0][2].short_channel_id, 6);
2349 assert_eq!(route.paths[0][2].fee_msat, 0);
2350 assert_eq!(route.paths[0][2].cltv_expiry_delta, (11 << 8) | 1);
2351 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(5));
2352 assert_eq!(route.paths[0][2].channel_features.le_flags(), &id_to_feature_flags(6));
2354 assert_eq!(route.paths[0][3].pubkey, nodes[3]);
2355 assert_eq!(route.paths[0][3].short_channel_id, 11);
2356 assert_eq!(route.paths[0][3].fee_msat, 0);
2357 assert_eq!(route.paths[0][3].cltv_expiry_delta, (8 << 8) | 1);
2358 // If we have a peer in the node map, we'll use their features here since we don't have
2359 // a way of figuring out their features from the invoice:
2360 assert_eq!(route.paths[0][3].node_features.le_flags(), &id_to_feature_flags(4));
2361 assert_eq!(route.paths[0][3].channel_features.le_flags(), &id_to_feature_flags(11));
2363 assert_eq!(route.paths[0][4].pubkey, nodes[6]);
2364 assert_eq!(route.paths[0][4].short_channel_id, 8);
2365 assert_eq!(route.paths[0][4].fee_msat, 100);
2366 assert_eq!(route.paths[0][4].cltv_expiry_delta, 42);
2367 assert_eq!(route.paths[0][4].node_features.le_flags(), &Vec::<u8>::new()); // We dont pass flags in from invoices yet
2368 assert_eq!(route.paths[0][4].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
2371 fn multi_hint_last_hops(nodes: &Vec<PublicKey>) -> Vec<RouteHint> {
2372 let zero_fees = RoutingFees {
2374 proportional_millionths: 0,
2376 vec![RouteHint(vec![RouteHintHop {
2377 src_node_id: nodes[2].clone(),
2378 short_channel_id: 5,
2381 proportional_millionths: 0,
2383 cltv_expiry_delta: (5 << 8) | 1,
2384 htlc_minimum_msat: None,
2385 htlc_maximum_msat: None,
2387 src_node_id: nodes[3].clone(),
2388 short_channel_id: 8,
2390 cltv_expiry_delta: (8 << 8) | 1,
2391 htlc_minimum_msat: None,
2392 htlc_maximum_msat: None,
2393 }]), RouteHint(vec![RouteHintHop {
2394 src_node_id: nodes[5].clone(),
2395 short_channel_id: 10,
2397 cltv_expiry_delta: (10 << 8) | 1,
2398 htlc_minimum_msat: None,
2399 htlc_maximum_msat: None,
2404 fn multi_hint_last_hops_test() {
2405 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
2406 let (_, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
2407 // Test through channels 2, 3, 5, 8.
2408 // Test shows that multiple hop hints are considered.
2410 // Disabling channels 6 & 7 by flags=2
2411 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
2412 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2413 short_channel_id: 6,
2415 flags: 2, // to disable
2416 cltv_expiry_delta: 0,
2417 htlc_minimum_msat: 0,
2418 htlc_maximum_msat: OptionalField::Absent,
2420 fee_proportional_millionths: 0,
2421 excess_data: Vec::new()
2423 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
2424 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2425 short_channel_id: 7,
2427 flags: 2, // to disable
2428 cltv_expiry_delta: 0,
2429 htlc_minimum_msat: 0,
2430 htlc_maximum_msat: OptionalField::Absent,
2432 fee_proportional_millionths: 0,
2433 excess_data: Vec::new()
2436 let route = get_route(&our_id, &net_graph_msg_handler.network_graph, &nodes[6], None, None, &multi_hint_last_hops(&nodes).iter().collect::<Vec<_>>(), 100, 42, Arc::clone(&logger)).unwrap();
2437 assert_eq!(route.paths[0].len(), 4);
2439 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
2440 assert_eq!(route.paths[0][0].short_channel_id, 2);
2441 assert_eq!(route.paths[0][0].fee_msat, 200);
2442 assert_eq!(route.paths[0][0].cltv_expiry_delta, 1025);
2443 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
2444 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
2446 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2447 assert_eq!(route.paths[0][1].short_channel_id, 4);
2448 assert_eq!(route.paths[0][1].fee_msat, 100);
2449 assert_eq!(route.paths[0][1].cltv_expiry_delta, 1281);
2450 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2451 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
2453 assert_eq!(route.paths[0][2].pubkey, nodes[3]);
2454 assert_eq!(route.paths[0][2].short_channel_id, 5);
2455 assert_eq!(route.paths[0][2].fee_msat, 0);
2456 assert_eq!(route.paths[0][2].cltv_expiry_delta, 2049);
2457 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(4));
2458 assert_eq!(route.paths[0][2].channel_features.le_flags(), &Vec::<u8>::new());
2460 assert_eq!(route.paths[0][3].pubkey, nodes[6]);
2461 assert_eq!(route.paths[0][3].short_channel_id, 8);
2462 assert_eq!(route.paths[0][3].fee_msat, 100);
2463 assert_eq!(route.paths[0][3].cltv_expiry_delta, 42);
2464 assert_eq!(route.paths[0][3].node_features.le_flags(), &Vec::<u8>::new()); // We dont pass flags in from invoices yet
2465 assert_eq!(route.paths[0][3].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
2468 fn last_hops_with_public_channel(nodes: &Vec<PublicKey>) -> Vec<RouteHint> {
2469 let zero_fees = RoutingFees {
2471 proportional_millionths: 0,
2473 vec![RouteHint(vec![RouteHintHop {
2474 src_node_id: nodes[4].clone(),
2475 short_channel_id: 11,
2477 cltv_expiry_delta: (11 << 8) | 1,
2478 htlc_minimum_msat: None,
2479 htlc_maximum_msat: None,
2481 src_node_id: nodes[3].clone(),
2482 short_channel_id: 8,
2484 cltv_expiry_delta: (8 << 8) | 1,
2485 htlc_minimum_msat: None,
2486 htlc_maximum_msat: None,
2487 }]), RouteHint(vec![RouteHintHop {
2488 src_node_id: nodes[4].clone(),
2489 short_channel_id: 9,
2492 proportional_millionths: 0,
2494 cltv_expiry_delta: (9 << 8) | 1,
2495 htlc_minimum_msat: None,
2496 htlc_maximum_msat: None,
2497 }]), RouteHint(vec![RouteHintHop {
2498 src_node_id: nodes[5].clone(),
2499 short_channel_id: 10,
2501 cltv_expiry_delta: (10 << 8) | 1,
2502 htlc_minimum_msat: None,
2503 htlc_maximum_msat: None,
2508 fn last_hops_with_public_channel_test() {
2509 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
2510 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
2511 // This test shows that public routes can be present in the invoice
2512 // which would be handled in the same manner.
2514 let route = get_route(&our_id, &net_graph_msg_handler.network_graph, &nodes[6], None, None, &last_hops_with_public_channel(&nodes).iter().collect::<Vec<_>>(), 100, 42, Arc::clone(&logger)).unwrap();
2515 assert_eq!(route.paths[0].len(), 5);
2517 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
2518 assert_eq!(route.paths[0][0].short_channel_id, 2);
2519 assert_eq!(route.paths[0][0].fee_msat, 100);
2520 assert_eq!(route.paths[0][0].cltv_expiry_delta, (4 << 8) | 1);
2521 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
2522 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
2524 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2525 assert_eq!(route.paths[0][1].short_channel_id, 4);
2526 assert_eq!(route.paths[0][1].fee_msat, 0);
2527 assert_eq!(route.paths[0][1].cltv_expiry_delta, (6 << 8) | 1);
2528 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2529 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
2531 assert_eq!(route.paths[0][2].pubkey, nodes[4]);
2532 assert_eq!(route.paths[0][2].short_channel_id, 6);
2533 assert_eq!(route.paths[0][2].fee_msat, 0);
2534 assert_eq!(route.paths[0][2].cltv_expiry_delta, (11 << 8) | 1);
2535 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(5));
2536 assert_eq!(route.paths[0][2].channel_features.le_flags(), &id_to_feature_flags(6));
2538 assert_eq!(route.paths[0][3].pubkey, nodes[3]);
2539 assert_eq!(route.paths[0][3].short_channel_id, 11);
2540 assert_eq!(route.paths[0][3].fee_msat, 0);
2541 assert_eq!(route.paths[0][3].cltv_expiry_delta, (8 << 8) | 1);
2542 // If we have a peer in the node map, we'll use their features here since we don't have
2543 // a way of figuring out their features from the invoice:
2544 assert_eq!(route.paths[0][3].node_features.le_flags(), &id_to_feature_flags(4));
2545 assert_eq!(route.paths[0][3].channel_features.le_flags(), &Vec::<u8>::new());
2547 assert_eq!(route.paths[0][4].pubkey, nodes[6]);
2548 assert_eq!(route.paths[0][4].short_channel_id, 8);
2549 assert_eq!(route.paths[0][4].fee_msat, 100);
2550 assert_eq!(route.paths[0][4].cltv_expiry_delta, 42);
2551 assert_eq!(route.paths[0][4].node_features.le_flags(), &Vec::<u8>::new()); // We dont pass flags in from invoices yet
2552 assert_eq!(route.paths[0][4].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
2556 fn our_chans_last_hop_connect_test() {
2557 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
2558 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
2560 // Simple test with outbound channel to 4 to test that last_hops and first_hops connect
2561 let our_chans = vec![get_channel_details(Some(42), nodes[3].clone(), InitFeatures::from_le_bytes(vec![0b11]), 250_000_000)];
2562 let mut last_hops = last_hops(&nodes);
2563 let route = get_route(&our_id, &net_graph_msg_handler.network_graph, &nodes[6], None, Some(&our_chans.iter().collect::<Vec<_>>()), &last_hops.iter().collect::<Vec<_>>(), 100, 42, Arc::clone(&logger)).unwrap();
2564 assert_eq!(route.paths[0].len(), 2);
2566 assert_eq!(route.paths[0][0].pubkey, nodes[3]);
2567 assert_eq!(route.paths[0][0].short_channel_id, 42);
2568 assert_eq!(route.paths[0][0].fee_msat, 0);
2569 assert_eq!(route.paths[0][0].cltv_expiry_delta, (8 << 8) | 1);
2570 assert_eq!(route.paths[0][0].node_features.le_flags(), &vec![0b11]);
2571 assert_eq!(route.paths[0][0].channel_features.le_flags(), &Vec::<u8>::new()); // No feature flags will meet the relevant-to-channel conversion
2573 assert_eq!(route.paths[0][1].pubkey, nodes[6]);
2574 assert_eq!(route.paths[0][1].short_channel_id, 8);
2575 assert_eq!(route.paths[0][1].fee_msat, 100);
2576 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
2577 assert_eq!(route.paths[0][1].node_features.le_flags(), &Vec::<u8>::new()); // We dont pass flags in from invoices yet
2578 assert_eq!(route.paths[0][1].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
2580 last_hops[0].0[0].fees.base_msat = 1000;
2582 // Revert to via 6 as the fee on 8 goes up
2583 let route = get_route(&our_id, &net_graph_msg_handler.network_graph, &nodes[6], None, None, &last_hops.iter().collect::<Vec<_>>(), 100, 42, Arc::clone(&logger)).unwrap();
2584 assert_eq!(route.paths[0].len(), 4);
2586 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
2587 assert_eq!(route.paths[0][0].short_channel_id, 2);
2588 assert_eq!(route.paths[0][0].fee_msat, 200); // fee increased as its % of value transferred across node
2589 assert_eq!(route.paths[0][0].cltv_expiry_delta, (4 << 8) | 1);
2590 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
2591 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
2593 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2594 assert_eq!(route.paths[0][1].short_channel_id, 4);
2595 assert_eq!(route.paths[0][1].fee_msat, 100);
2596 assert_eq!(route.paths[0][1].cltv_expiry_delta, (7 << 8) | 1);
2597 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2598 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
2600 assert_eq!(route.paths[0][2].pubkey, nodes[5]);
2601 assert_eq!(route.paths[0][2].short_channel_id, 7);
2602 assert_eq!(route.paths[0][2].fee_msat, 0);
2603 assert_eq!(route.paths[0][2].cltv_expiry_delta, (10 << 8) | 1);
2604 // If we have a peer in the node map, we'll use their features here since we don't have
2605 // a way of figuring out their features from the invoice:
2606 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(6));
2607 assert_eq!(route.paths[0][2].channel_features.le_flags(), &id_to_feature_flags(7));
2609 assert_eq!(route.paths[0][3].pubkey, nodes[6]);
2610 assert_eq!(route.paths[0][3].short_channel_id, 10);
2611 assert_eq!(route.paths[0][3].fee_msat, 100);
2612 assert_eq!(route.paths[0][3].cltv_expiry_delta, 42);
2613 assert_eq!(route.paths[0][3].node_features.le_flags(), &Vec::<u8>::new()); // We dont pass flags in from invoices yet
2614 assert_eq!(route.paths[0][3].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
2616 // ...but still use 8 for larger payments as 6 has a variable feerate
2617 let route = get_route(&our_id, &net_graph_msg_handler.network_graph, &nodes[6], None, None, &last_hops.iter().collect::<Vec<_>>(), 2000, 42, Arc::clone(&logger)).unwrap();
2618 assert_eq!(route.paths[0].len(), 5);
2620 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
2621 assert_eq!(route.paths[0][0].short_channel_id, 2);
2622 assert_eq!(route.paths[0][0].fee_msat, 3000);
2623 assert_eq!(route.paths[0][0].cltv_expiry_delta, (4 << 8) | 1);
2624 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
2625 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
2627 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2628 assert_eq!(route.paths[0][1].short_channel_id, 4);
2629 assert_eq!(route.paths[0][1].fee_msat, 0);
2630 assert_eq!(route.paths[0][1].cltv_expiry_delta, (6 << 8) | 1);
2631 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2632 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
2634 assert_eq!(route.paths[0][2].pubkey, nodes[4]);
2635 assert_eq!(route.paths[0][2].short_channel_id, 6);
2636 assert_eq!(route.paths[0][2].fee_msat, 0);
2637 assert_eq!(route.paths[0][2].cltv_expiry_delta, (11 << 8) | 1);
2638 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(5));
2639 assert_eq!(route.paths[0][2].channel_features.le_flags(), &id_to_feature_flags(6));
2641 assert_eq!(route.paths[0][3].pubkey, nodes[3]);
2642 assert_eq!(route.paths[0][3].short_channel_id, 11);
2643 assert_eq!(route.paths[0][3].fee_msat, 1000);
2644 assert_eq!(route.paths[0][3].cltv_expiry_delta, (8 << 8) | 1);
2645 // If we have a peer in the node map, we'll use their features here since we don't have
2646 // a way of figuring out their features from the invoice:
2647 assert_eq!(route.paths[0][3].node_features.le_flags(), &id_to_feature_flags(4));
2648 assert_eq!(route.paths[0][3].channel_features.le_flags(), &id_to_feature_flags(11));
2650 assert_eq!(route.paths[0][4].pubkey, nodes[6]);
2651 assert_eq!(route.paths[0][4].short_channel_id, 8);
2652 assert_eq!(route.paths[0][4].fee_msat, 2000);
2653 assert_eq!(route.paths[0][4].cltv_expiry_delta, 42);
2654 assert_eq!(route.paths[0][4].node_features.le_flags(), &Vec::<u8>::new()); // We dont pass flags in from invoices yet
2655 assert_eq!(route.paths[0][4].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
2658 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> {
2659 let source_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&hex::decode(format!("{:02}", 41).repeat(32)).unwrap()[..]).unwrap());
2660 let middle_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&hex::decode(format!("{:02}", 42).repeat(32)).unwrap()[..]).unwrap());
2661 let target_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&hex::decode(format!("{:02}", 43).repeat(32)).unwrap()[..]).unwrap());
2663 // If we specify a channel to a middle hop, that overrides our local channel view and that gets used
2664 let last_hops = RouteHint(vec![RouteHintHop {
2665 src_node_id: middle_node_id,
2666 short_channel_id: 8,
2669 proportional_millionths: last_hop_fee_prop,
2671 cltv_expiry_delta: (8 << 8) | 1,
2672 htlc_minimum_msat: None,
2673 htlc_maximum_msat: last_hop_htlc_max,
2675 let our_chans = vec![get_channel_details(Some(42), middle_node_id, InitFeatures::from_le_bytes(vec![0b11]), outbound_capacity_msat)];
2676 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()))
2680 fn unannounced_path_test() {
2681 // We should be able to send a payment to a destination without any help of a routing graph
2682 // if we have a channel with a common counterparty that appears in the first and last hop
2684 let route = do_unannounced_path_test(None, 1, 2000000, 1000000).unwrap();
2686 let middle_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&hex::decode(format!("{:02}", 42).repeat(32)).unwrap()[..]).unwrap());
2687 let target_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&hex::decode(format!("{:02}", 43).repeat(32)).unwrap()[..]).unwrap());
2688 assert_eq!(route.paths[0].len(), 2);
2690 assert_eq!(route.paths[0][0].pubkey, middle_node_id);
2691 assert_eq!(route.paths[0][0].short_channel_id, 42);
2692 assert_eq!(route.paths[0][0].fee_msat, 1001);
2693 assert_eq!(route.paths[0][0].cltv_expiry_delta, (8 << 8) | 1);
2694 assert_eq!(route.paths[0][0].node_features.le_flags(), &[0b11]);
2695 assert_eq!(route.paths[0][0].channel_features.le_flags(), &[0; 0]); // We can't learn any flags from invoices, sadly
2697 assert_eq!(route.paths[0][1].pubkey, target_node_id);
2698 assert_eq!(route.paths[0][1].short_channel_id, 8);
2699 assert_eq!(route.paths[0][1].fee_msat, 1000000);
2700 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
2701 assert_eq!(route.paths[0][1].node_features.le_flags(), &[0; 0]); // We dont pass flags in from invoices yet
2702 assert_eq!(route.paths[0][1].channel_features.le_flags(), &[0; 0]); // We can't learn any flags from invoices, sadly
2706 fn overflow_unannounced_path_test_liquidity_underflow() {
2707 // Previously, when we had a last-hop hint connected directly to a first-hop channel, where
2708 // the last-hop had a fee which overflowed a u64, we'd panic.
2709 // This was due to us adding the first-hop from us unconditionally, causing us to think
2710 // we'd built a path (as our node is in the "best candidate" set), when we had not.
2711 // In this test, we previously hit a subtraction underflow due to having less available
2712 // liquidity at the last hop than 0.
2713 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());
2717 fn overflow_unannounced_path_test_feerate_overflow() {
2718 // This tests for the same case as above, except instead of hitting a subtraction
2719 // underflow, we hit a case where the fee charged at a hop overflowed.
2720 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());
2724 fn available_amount_while_routing_test() {
2725 // Tests whether we choose the correct available channel amount while routing.
2727 let (secp_ctx, mut net_graph_msg_handler, chain_monitor, logger) = build_graph();
2728 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
2730 // We will use a simple single-path route from
2731 // our node to node2 via node0: channels {1, 3}.
2733 // First disable all other paths.
2734 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2735 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2736 short_channel_id: 2,
2739 cltv_expiry_delta: 0,
2740 htlc_minimum_msat: 0,
2741 htlc_maximum_msat: OptionalField::Present(100_000),
2743 fee_proportional_millionths: 0,
2744 excess_data: Vec::new()
2746 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2747 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2748 short_channel_id: 12,
2751 cltv_expiry_delta: 0,
2752 htlc_minimum_msat: 0,
2753 htlc_maximum_msat: OptionalField::Present(100_000),
2755 fee_proportional_millionths: 0,
2756 excess_data: Vec::new()
2759 // Make the first channel (#1) very permissive,
2760 // and we will be testing all limits on the second channel.
2761 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2762 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2763 short_channel_id: 1,
2766 cltv_expiry_delta: 0,
2767 htlc_minimum_msat: 0,
2768 htlc_maximum_msat: OptionalField::Present(1_000_000_000),
2770 fee_proportional_millionths: 0,
2771 excess_data: Vec::new()
2774 // First, let's see if routing works if we have absolutely no idea about the available amount.
2775 // In this case, it should be set to 250_000 sats.
2776 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
2777 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2778 short_channel_id: 3,
2781 cltv_expiry_delta: 0,
2782 htlc_minimum_msat: 0,
2783 htlc_maximum_msat: OptionalField::Absent,
2785 fee_proportional_millionths: 0,
2786 excess_data: Vec::new()
2790 // Attempt to route more than available results in a failure.
2791 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id, &net_graph_msg_handler.network_graph, &nodes[2],
2792 Some(InvoiceFeatures::known()), None, &Vec::new(), 250_000_001, 42, Arc::clone(&logger)) {
2793 assert_eq!(err, "Failed to find a sufficient route to the given destination");
2794 } else { panic!(); }
2798 // Now, attempt to route an exact amount we have should be fine.
2799 let route = get_route(&our_id, &net_graph_msg_handler.network_graph, &nodes[2],
2800 Some(InvoiceFeatures::known()), None, &Vec::new(), 250_000_000, 42, Arc::clone(&logger)).unwrap();
2801 assert_eq!(route.paths.len(), 1);
2802 let path = route.paths.last().unwrap();
2803 assert_eq!(path.len(), 2);
2804 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
2805 assert_eq!(path.last().unwrap().fee_msat, 250_000_000);
2808 // Check that setting outbound_capacity_msat in first_hops limits the channels.
2809 // Disable channel #1 and use another first hop.
2810 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2811 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2812 short_channel_id: 1,
2815 cltv_expiry_delta: 0,
2816 htlc_minimum_msat: 0,
2817 htlc_maximum_msat: OptionalField::Present(1_000_000_000),
2819 fee_proportional_millionths: 0,
2820 excess_data: Vec::new()
2823 // Now, limit the first_hop by the outbound_capacity_msat of 200_000 sats.
2824 let our_chans = vec![get_channel_details(Some(42), nodes[0].clone(), InitFeatures::from_le_bytes(vec![0b11]), 200_000_000)];
2827 // Attempt to route more than available results in a failure.
2828 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id, &net_graph_msg_handler.network_graph, &nodes[2],
2829 Some(InvoiceFeatures::known()), Some(&our_chans.iter().collect::<Vec<_>>()), &Vec::new(), 200_000_001, 42, Arc::clone(&logger)) {
2830 assert_eq!(err, "Failed to find a sufficient route to the given destination");
2831 } else { panic!(); }
2835 // Now, attempt to route an exact amount we have should be fine.
2836 let route = get_route(&our_id, &net_graph_msg_handler.network_graph, &nodes[2],
2837 Some(InvoiceFeatures::known()), Some(&our_chans.iter().collect::<Vec<_>>()), &Vec::new(), 200_000_000, 42, Arc::clone(&logger)).unwrap();
2838 assert_eq!(route.paths.len(), 1);
2839 let path = route.paths.last().unwrap();
2840 assert_eq!(path.len(), 2);
2841 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
2842 assert_eq!(path.last().unwrap().fee_msat, 200_000_000);
2845 // Enable channel #1 back.
2846 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2847 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2848 short_channel_id: 1,
2851 cltv_expiry_delta: 0,
2852 htlc_minimum_msat: 0,
2853 htlc_maximum_msat: OptionalField::Present(1_000_000_000),
2855 fee_proportional_millionths: 0,
2856 excess_data: Vec::new()
2860 // Now let's see if routing works if we know only htlc_maximum_msat.
2861 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
2862 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2863 short_channel_id: 3,
2866 cltv_expiry_delta: 0,
2867 htlc_minimum_msat: 0,
2868 htlc_maximum_msat: OptionalField::Present(15_000),
2870 fee_proportional_millionths: 0,
2871 excess_data: Vec::new()
2875 // Attempt to route more than available results in a failure.
2876 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id, &net_graph_msg_handler.network_graph, &nodes[2],
2877 Some(InvoiceFeatures::known()), None, &Vec::new(), 15_001, 42, Arc::clone(&logger)) {
2878 assert_eq!(err, "Failed to find a sufficient route to the given destination");
2879 } else { panic!(); }
2883 // Now, attempt to route an exact amount we have should be fine.
2884 let route = get_route(&our_id, &net_graph_msg_handler.network_graph, &nodes[2],
2885 Some(InvoiceFeatures::known()), None, &Vec::new(), 15_000, 42, Arc::clone(&logger)).unwrap();
2886 assert_eq!(route.paths.len(), 1);
2887 let path = route.paths.last().unwrap();
2888 assert_eq!(path.len(), 2);
2889 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
2890 assert_eq!(path.last().unwrap().fee_msat, 15_000);
2893 // Now let's see if routing works if we know only capacity from the UTXO.
2895 // We can't change UTXO capacity on the fly, so we'll disable
2896 // the existing channel and add another one with the capacity we need.
2897 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
2898 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2899 short_channel_id: 3,
2902 cltv_expiry_delta: 0,
2903 htlc_minimum_msat: 0,
2904 htlc_maximum_msat: OptionalField::Absent,
2906 fee_proportional_millionths: 0,
2907 excess_data: Vec::new()
2910 let good_script = Builder::new().push_opcode(opcodes::all::OP_PUSHNUM_2)
2911 .push_slice(&PublicKey::from_secret_key(&secp_ctx, &privkeys[0]).serialize())
2912 .push_slice(&PublicKey::from_secret_key(&secp_ctx, &privkeys[2]).serialize())
2913 .push_opcode(opcodes::all::OP_PUSHNUM_2)
2914 .push_opcode(opcodes::all::OP_CHECKMULTISIG).into_script().to_v0_p2wsh();
2916 *chain_monitor.utxo_ret.lock().unwrap() = Ok(TxOut { value: 15, script_pubkey: good_script.clone() });
2917 net_graph_msg_handler.add_chain_access(Some(chain_monitor));
2919 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], &privkeys[2], ChannelFeatures::from_le_bytes(id_to_feature_flags(3)), 333);
2920 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
2921 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2922 short_channel_id: 333,
2925 cltv_expiry_delta: (3 << 8) | 1,
2926 htlc_minimum_msat: 0,
2927 htlc_maximum_msat: OptionalField::Absent,
2929 fee_proportional_millionths: 0,
2930 excess_data: Vec::new()
2932 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
2933 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2934 short_channel_id: 333,
2937 cltv_expiry_delta: (3 << 8) | 2,
2938 htlc_minimum_msat: 0,
2939 htlc_maximum_msat: OptionalField::Absent,
2941 fee_proportional_millionths: 0,
2942 excess_data: Vec::new()
2946 // Attempt to route more than available results in a failure.
2947 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id, &net_graph_msg_handler.network_graph, &nodes[2],
2948 Some(InvoiceFeatures::known()), None, &Vec::new(), 15_001, 42, Arc::clone(&logger)) {
2949 assert_eq!(err, "Failed to find a sufficient route to the given destination");
2950 } else { panic!(); }
2954 // Now, attempt to route an exact amount we have should be fine.
2955 let route = get_route(&our_id, &net_graph_msg_handler.network_graph, &nodes[2],
2956 Some(InvoiceFeatures::known()), None, &Vec::new(), 15_000, 42, Arc::clone(&logger)).unwrap();
2957 assert_eq!(route.paths.len(), 1);
2958 let path = route.paths.last().unwrap();
2959 assert_eq!(path.len(), 2);
2960 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
2961 assert_eq!(path.last().unwrap().fee_msat, 15_000);
2964 // Now let's see if routing chooses htlc_maximum_msat over UTXO capacity.
2965 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
2966 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2967 short_channel_id: 333,
2970 cltv_expiry_delta: 0,
2971 htlc_minimum_msat: 0,
2972 htlc_maximum_msat: OptionalField::Present(10_000),
2974 fee_proportional_millionths: 0,
2975 excess_data: Vec::new()
2979 // Attempt to route more than available results in a failure.
2980 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id, &net_graph_msg_handler.network_graph, &nodes[2],
2981 Some(InvoiceFeatures::known()), None, &Vec::new(), 10_001, 42, Arc::clone(&logger)) {
2982 assert_eq!(err, "Failed to find a sufficient route to the given destination");
2983 } else { panic!(); }
2987 // Now, attempt to route an exact amount we have should be fine.
2988 let route = get_route(&our_id, &net_graph_msg_handler.network_graph, &nodes[2],
2989 Some(InvoiceFeatures::known()), None, &Vec::new(), 10_000, 42, Arc::clone(&logger)).unwrap();
2990 assert_eq!(route.paths.len(), 1);
2991 let path = route.paths.last().unwrap();
2992 assert_eq!(path.len(), 2);
2993 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
2994 assert_eq!(path.last().unwrap().fee_msat, 10_000);
2999 fn available_liquidity_last_hop_test() {
3000 // Check that available liquidity properly limits the path even when only
3001 // one of the latter hops is limited.
3002 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
3003 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3005 // Path via {node7, node2, node4} is channels {12, 13, 6, 11}.
3006 // {12, 13, 11} have the capacities of 100, {6} has a capacity of 50.
3007 // Total capacity: 50 sats.
3009 // Disable other potential paths.
3010 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3011 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3012 short_channel_id: 2,
3015 cltv_expiry_delta: 0,
3016 htlc_minimum_msat: 0,
3017 htlc_maximum_msat: OptionalField::Present(100_000),
3019 fee_proportional_millionths: 0,
3020 excess_data: Vec::new()
3022 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3023 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3024 short_channel_id: 7,
3027 cltv_expiry_delta: 0,
3028 htlc_minimum_msat: 0,
3029 htlc_maximum_msat: OptionalField::Present(100_000),
3031 fee_proportional_millionths: 0,
3032 excess_data: Vec::new()
3037 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3038 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3039 short_channel_id: 12,
3042 cltv_expiry_delta: 0,
3043 htlc_minimum_msat: 0,
3044 htlc_maximum_msat: OptionalField::Present(100_000),
3046 fee_proportional_millionths: 0,
3047 excess_data: Vec::new()
3049 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
3050 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3051 short_channel_id: 13,
3054 cltv_expiry_delta: 0,
3055 htlc_minimum_msat: 0,
3056 htlc_maximum_msat: OptionalField::Present(100_000),
3058 fee_proportional_millionths: 0,
3059 excess_data: Vec::new()
3062 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3063 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3064 short_channel_id: 6,
3067 cltv_expiry_delta: 0,
3068 htlc_minimum_msat: 0,
3069 htlc_maximum_msat: OptionalField::Present(50_000),
3071 fee_proportional_millionths: 0,
3072 excess_data: Vec::new()
3074 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
3075 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3076 short_channel_id: 11,
3079 cltv_expiry_delta: 0,
3080 htlc_minimum_msat: 0,
3081 htlc_maximum_msat: OptionalField::Present(100_000),
3083 fee_proportional_millionths: 0,
3084 excess_data: Vec::new()
3087 // Attempt to route more than available results in a failure.
3088 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id, &net_graph_msg_handler.network_graph, &nodes[3],
3089 Some(InvoiceFeatures::known()), None, &Vec::new(), 60_000, 42, Arc::clone(&logger)) {
3090 assert_eq!(err, "Failed to find a sufficient route to the given destination");
3091 } else { panic!(); }
3095 // Now, attempt to route 49 sats (just a bit below the capacity).
3096 let route = get_route(&our_id, &net_graph_msg_handler.network_graph, &nodes[3],
3097 Some(InvoiceFeatures::known()), None, &Vec::new(), 49_000, 42, Arc::clone(&logger)).unwrap();
3098 assert_eq!(route.paths.len(), 1);
3099 let mut total_amount_paid_msat = 0;
3100 for path in &route.paths {
3101 assert_eq!(path.len(), 4);
3102 assert_eq!(path.last().unwrap().pubkey, nodes[3]);
3103 total_amount_paid_msat += path.last().unwrap().fee_msat;
3105 assert_eq!(total_amount_paid_msat, 49_000);
3109 // Attempt to route an exact amount is also fine
3110 let route = get_route(&our_id, &net_graph_msg_handler.network_graph, &nodes[3],
3111 Some(InvoiceFeatures::known()), None, &Vec::new(), 50_000, 42, Arc::clone(&logger)).unwrap();
3112 assert_eq!(route.paths.len(), 1);
3113 let mut total_amount_paid_msat = 0;
3114 for path in &route.paths {
3115 assert_eq!(path.len(), 4);
3116 assert_eq!(path.last().unwrap().pubkey, nodes[3]);
3117 total_amount_paid_msat += path.last().unwrap().fee_msat;
3119 assert_eq!(total_amount_paid_msat, 50_000);
3124 fn ignore_fee_first_hop_test() {
3125 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
3126 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3128 // Path via node0 is channels {1, 3}. Limit them to 100 and 50 sats (total limit 50).
3129 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3130 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3131 short_channel_id: 1,
3134 cltv_expiry_delta: 0,
3135 htlc_minimum_msat: 0,
3136 htlc_maximum_msat: OptionalField::Present(100_000),
3137 fee_base_msat: 1_000_000,
3138 fee_proportional_millionths: 0,
3139 excess_data: Vec::new()
3141 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3142 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3143 short_channel_id: 3,
3146 cltv_expiry_delta: 0,
3147 htlc_minimum_msat: 0,
3148 htlc_maximum_msat: OptionalField::Present(50_000),
3150 fee_proportional_millionths: 0,
3151 excess_data: Vec::new()
3155 let route = get_route(&our_id, &net_graph_msg_handler.network_graph, &nodes[2], None, None, &Vec::new(), 50_000, 42, Arc::clone(&logger)).unwrap();
3156 assert_eq!(route.paths.len(), 1);
3157 let mut total_amount_paid_msat = 0;
3158 for path in &route.paths {
3159 assert_eq!(path.len(), 2);
3160 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
3161 total_amount_paid_msat += path.last().unwrap().fee_msat;
3163 assert_eq!(total_amount_paid_msat, 50_000);
3168 fn simple_mpp_route_test() {
3169 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
3170 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3172 // We need a route consisting of 3 paths:
3173 // From our node to node2 via node0, node7, node1 (three paths one hop each).
3174 // To achieve this, the amount being transferred should be around
3175 // the total capacity of these 3 paths.
3177 // First, we set limits on these (previously unlimited) channels.
3178 // Their aggregate capacity will be 50 + 60 + 180 = 290 sats.
3180 // Path via node0 is channels {1, 3}. Limit them to 100 and 50 sats (total limit 50).
3181 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3182 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3183 short_channel_id: 1,
3186 cltv_expiry_delta: 0,
3187 htlc_minimum_msat: 0,
3188 htlc_maximum_msat: OptionalField::Present(100_000),
3190 fee_proportional_millionths: 0,
3191 excess_data: Vec::new()
3193 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3194 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3195 short_channel_id: 3,
3198 cltv_expiry_delta: 0,
3199 htlc_minimum_msat: 0,
3200 htlc_maximum_msat: OptionalField::Present(50_000),
3202 fee_proportional_millionths: 0,
3203 excess_data: Vec::new()
3206 // Path via node7 is channels {12, 13}. Limit them to 60 and 60 sats
3207 // (total limit 60).
3208 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3209 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3210 short_channel_id: 12,
3213 cltv_expiry_delta: 0,
3214 htlc_minimum_msat: 0,
3215 htlc_maximum_msat: OptionalField::Present(60_000),
3217 fee_proportional_millionths: 0,
3218 excess_data: Vec::new()
3220 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
3221 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3222 short_channel_id: 13,
3225 cltv_expiry_delta: 0,
3226 htlc_minimum_msat: 0,
3227 htlc_maximum_msat: OptionalField::Present(60_000),
3229 fee_proportional_millionths: 0,
3230 excess_data: Vec::new()
3233 // Path via node1 is channels {2, 4}. Limit them to 200 and 180 sats
3234 // (total capacity 180 sats).
3235 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3236 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3237 short_channel_id: 2,
3240 cltv_expiry_delta: 0,
3241 htlc_minimum_msat: 0,
3242 htlc_maximum_msat: OptionalField::Present(200_000),
3244 fee_proportional_millionths: 0,
3245 excess_data: Vec::new()
3247 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
3248 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3249 short_channel_id: 4,
3252 cltv_expiry_delta: 0,
3253 htlc_minimum_msat: 0,
3254 htlc_maximum_msat: OptionalField::Present(180_000),
3256 fee_proportional_millionths: 0,
3257 excess_data: Vec::new()
3261 // Attempt to route more than available results in a failure.
3262 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id, &net_graph_msg_handler.network_graph,
3263 &nodes[2], Some(InvoiceFeatures::known()), None, &Vec::new(), 300_000, 42, Arc::clone(&logger)) {
3264 assert_eq!(err, "Failed to find a sufficient route to the given destination");
3265 } else { panic!(); }
3269 // Now, attempt to route 250 sats (just a bit below the capacity).
3270 // Our algorithm should provide us with these 3 paths.
3271 let route = get_route(&our_id, &net_graph_msg_handler.network_graph, &nodes[2],
3272 Some(InvoiceFeatures::known()), None, &Vec::new(), 250_000, 42, Arc::clone(&logger)).unwrap();
3273 assert_eq!(route.paths.len(), 3);
3274 let mut total_amount_paid_msat = 0;
3275 for path in &route.paths {
3276 assert_eq!(path.len(), 2);
3277 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
3278 total_amount_paid_msat += path.last().unwrap().fee_msat;
3280 assert_eq!(total_amount_paid_msat, 250_000);
3284 // Attempt to route an exact amount is also fine
3285 let route = get_route(&our_id, &net_graph_msg_handler.network_graph, &nodes[2],
3286 Some(InvoiceFeatures::known()), None, &Vec::new(), 290_000, 42, Arc::clone(&logger)).unwrap();
3287 assert_eq!(route.paths.len(), 3);
3288 let mut total_amount_paid_msat = 0;
3289 for path in &route.paths {
3290 assert_eq!(path.len(), 2);
3291 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
3292 total_amount_paid_msat += path.last().unwrap().fee_msat;
3294 assert_eq!(total_amount_paid_msat, 290_000);
3299 fn long_mpp_route_test() {
3300 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
3301 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3303 // We need a route consisting of 3 paths:
3304 // From our node to node3 via {node0, node2}, {node7, node2, node4} and {node7, node2}.
3305 // Note that these paths overlap (channels 5, 12, 13).
3306 // We will route 300 sats.
3307 // Each path will have 100 sats capacity, those channels which
3308 // are used twice will have 200 sats capacity.
3310 // Disable other potential paths.
3311 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3312 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3313 short_channel_id: 2,
3316 cltv_expiry_delta: 0,
3317 htlc_minimum_msat: 0,
3318 htlc_maximum_msat: OptionalField::Present(100_000),
3320 fee_proportional_millionths: 0,
3321 excess_data: Vec::new()
3323 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3324 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3325 short_channel_id: 7,
3328 cltv_expiry_delta: 0,
3329 htlc_minimum_msat: 0,
3330 htlc_maximum_msat: OptionalField::Present(100_000),
3332 fee_proportional_millionths: 0,
3333 excess_data: Vec::new()
3336 // Path via {node0, node2} is channels {1, 3, 5}.
3337 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3338 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3339 short_channel_id: 1,
3342 cltv_expiry_delta: 0,
3343 htlc_minimum_msat: 0,
3344 htlc_maximum_msat: OptionalField::Present(100_000),
3346 fee_proportional_millionths: 0,
3347 excess_data: Vec::new()
3349 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3350 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3351 short_channel_id: 3,
3354 cltv_expiry_delta: 0,
3355 htlc_minimum_msat: 0,
3356 htlc_maximum_msat: OptionalField::Present(100_000),
3358 fee_proportional_millionths: 0,
3359 excess_data: Vec::new()
3362 // Capacity of 200 sats because this channel will be used by 3rd path as well.
3363 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(5)), 5);
3364 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3365 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3366 short_channel_id: 5,
3369 cltv_expiry_delta: 0,
3370 htlc_minimum_msat: 0,
3371 htlc_maximum_msat: OptionalField::Present(200_000),
3373 fee_proportional_millionths: 0,
3374 excess_data: Vec::new()
3377 // Path via {node7, node2, node4} is channels {12, 13, 6, 11}.
3378 // Add 100 sats to the capacities of {12, 13}, because these channels
3379 // are also used for 3rd path. 100 sats for the rest. Total capacity: 100 sats.
3380 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3381 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3382 short_channel_id: 12,
3385 cltv_expiry_delta: 0,
3386 htlc_minimum_msat: 0,
3387 htlc_maximum_msat: OptionalField::Present(200_000),
3389 fee_proportional_millionths: 0,
3390 excess_data: Vec::new()
3392 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
3393 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3394 short_channel_id: 13,
3397 cltv_expiry_delta: 0,
3398 htlc_minimum_msat: 0,
3399 htlc_maximum_msat: OptionalField::Present(200_000),
3401 fee_proportional_millionths: 0,
3402 excess_data: Vec::new()
3405 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3406 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3407 short_channel_id: 6,
3410 cltv_expiry_delta: 0,
3411 htlc_minimum_msat: 0,
3412 htlc_maximum_msat: OptionalField::Present(100_000),
3414 fee_proportional_millionths: 0,
3415 excess_data: Vec::new()
3417 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
3418 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3419 short_channel_id: 11,
3422 cltv_expiry_delta: 0,
3423 htlc_minimum_msat: 0,
3424 htlc_maximum_msat: OptionalField::Present(100_000),
3426 fee_proportional_millionths: 0,
3427 excess_data: Vec::new()
3430 // Path via {node7, node2} is channels {12, 13, 5}.
3431 // We already limited them to 200 sats (they are used twice for 100 sats).
3432 // Nothing to do here.
3435 // Attempt to route more than available results in a failure.
3436 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id, &net_graph_msg_handler.network_graph, &nodes[3],
3437 Some(InvoiceFeatures::known()), None, &Vec::new(), 350_000, 42, Arc::clone(&logger)) {
3438 assert_eq!(err, "Failed to find a sufficient route to the given destination");
3439 } else { panic!(); }
3443 // Now, attempt to route 300 sats (exact amount we can route).
3444 // Our algorithm should provide us with these 3 paths, 100 sats each.
3445 let route = get_route(&our_id, &net_graph_msg_handler.network_graph, &nodes[3],
3446 Some(InvoiceFeatures::known()), None, &Vec::new(), 300_000, 42, Arc::clone(&logger)).unwrap();
3447 assert_eq!(route.paths.len(), 3);
3449 let mut total_amount_paid_msat = 0;
3450 for path in &route.paths {
3451 assert_eq!(path.last().unwrap().pubkey, nodes[3]);
3452 total_amount_paid_msat += path.last().unwrap().fee_msat;
3454 assert_eq!(total_amount_paid_msat, 300_000);
3460 fn mpp_cheaper_route_test() {
3461 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
3462 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3464 // This test checks that if we have two cheaper paths and one more expensive path,
3465 // so that liquidity-wise any 2 of 3 combination is sufficient,
3466 // two cheaper paths will be taken.
3467 // These paths have equal available liquidity.
3469 // We need a combination of 3 paths:
3470 // From our node to node3 via {node0, node2}, {node7, node2, node4} and {node7, node2}.
3471 // Note that these paths overlap (channels 5, 12, 13).
3472 // Each path will have 100 sats capacity, those channels which
3473 // are used twice will have 200 sats capacity.
3475 // Disable other potential paths.
3476 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3477 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3478 short_channel_id: 2,
3481 cltv_expiry_delta: 0,
3482 htlc_minimum_msat: 0,
3483 htlc_maximum_msat: OptionalField::Present(100_000),
3485 fee_proportional_millionths: 0,
3486 excess_data: Vec::new()
3488 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3489 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3490 short_channel_id: 7,
3493 cltv_expiry_delta: 0,
3494 htlc_minimum_msat: 0,
3495 htlc_maximum_msat: OptionalField::Present(100_000),
3497 fee_proportional_millionths: 0,
3498 excess_data: Vec::new()
3501 // Path via {node0, node2} is channels {1, 3, 5}.
3502 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3503 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3504 short_channel_id: 1,
3507 cltv_expiry_delta: 0,
3508 htlc_minimum_msat: 0,
3509 htlc_maximum_msat: OptionalField::Present(100_000),
3511 fee_proportional_millionths: 0,
3512 excess_data: Vec::new()
3514 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3515 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3516 short_channel_id: 3,
3519 cltv_expiry_delta: 0,
3520 htlc_minimum_msat: 0,
3521 htlc_maximum_msat: OptionalField::Present(100_000),
3523 fee_proportional_millionths: 0,
3524 excess_data: Vec::new()
3527 // Capacity of 200 sats because this channel will be used by 3rd path as well.
3528 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(5)), 5);
3529 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3530 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3531 short_channel_id: 5,
3534 cltv_expiry_delta: 0,
3535 htlc_minimum_msat: 0,
3536 htlc_maximum_msat: OptionalField::Present(200_000),
3538 fee_proportional_millionths: 0,
3539 excess_data: Vec::new()
3542 // Path via {node7, node2, node4} is channels {12, 13, 6, 11}.
3543 // Add 100 sats to the capacities of {12, 13}, because these channels
3544 // are also used for 3rd path. 100 sats for the rest. Total capacity: 100 sats.
3545 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3546 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3547 short_channel_id: 12,
3550 cltv_expiry_delta: 0,
3551 htlc_minimum_msat: 0,
3552 htlc_maximum_msat: OptionalField::Present(200_000),
3554 fee_proportional_millionths: 0,
3555 excess_data: Vec::new()
3557 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
3558 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3559 short_channel_id: 13,
3562 cltv_expiry_delta: 0,
3563 htlc_minimum_msat: 0,
3564 htlc_maximum_msat: OptionalField::Present(200_000),
3566 fee_proportional_millionths: 0,
3567 excess_data: Vec::new()
3570 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3571 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3572 short_channel_id: 6,
3575 cltv_expiry_delta: 0,
3576 htlc_minimum_msat: 0,
3577 htlc_maximum_msat: OptionalField::Present(100_000),
3578 fee_base_msat: 1_000,
3579 fee_proportional_millionths: 0,
3580 excess_data: Vec::new()
3582 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
3583 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3584 short_channel_id: 11,
3587 cltv_expiry_delta: 0,
3588 htlc_minimum_msat: 0,
3589 htlc_maximum_msat: OptionalField::Present(100_000),
3591 fee_proportional_millionths: 0,
3592 excess_data: Vec::new()
3595 // Path via {node7, node2} is channels {12, 13, 5}.
3596 // We already limited them to 200 sats (they are used twice for 100 sats).
3597 // Nothing to do here.
3600 // Now, attempt to route 180 sats.
3601 // Our algorithm should provide us with these 2 paths.
3602 let route = get_route(&our_id, &net_graph_msg_handler.network_graph, &nodes[3],
3603 Some(InvoiceFeatures::known()), None, &Vec::new(), 180_000, 42, Arc::clone(&logger)).unwrap();
3604 assert_eq!(route.paths.len(), 2);
3606 let mut total_value_transferred_msat = 0;
3607 let mut total_paid_msat = 0;
3608 for path in &route.paths {
3609 assert_eq!(path.last().unwrap().pubkey, nodes[3]);
3610 total_value_transferred_msat += path.last().unwrap().fee_msat;
3612 total_paid_msat += hop.fee_msat;
3615 // If we paid fee, this would be higher.
3616 assert_eq!(total_value_transferred_msat, 180_000);
3617 let total_fees_paid = total_paid_msat - total_value_transferred_msat;
3618 assert_eq!(total_fees_paid, 0);
3623 fn fees_on_mpp_route_test() {
3624 // This test makes sure that MPP algorithm properly takes into account
3625 // fees charged on the channels, by making the fees impactful:
3626 // if the fee is not properly accounted for, the behavior is different.
3627 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
3628 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3630 // We need a route consisting of 2 paths:
3631 // From our node to node3 via {node0, node2} and {node7, node2, node4}.
3632 // We will route 200 sats, Each path will have 100 sats capacity.
3634 // This test is not particularly stable: e.g.,
3635 // there's a way to route via {node0, node2, node4}.
3636 // It works while pathfinding is deterministic, but can be broken otherwise.
3637 // It's fine to ignore this concern for now.
3639 // Disable other potential paths.
3640 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3641 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3642 short_channel_id: 2,
3645 cltv_expiry_delta: 0,
3646 htlc_minimum_msat: 0,
3647 htlc_maximum_msat: OptionalField::Present(100_000),
3649 fee_proportional_millionths: 0,
3650 excess_data: Vec::new()
3653 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3654 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3655 short_channel_id: 7,
3658 cltv_expiry_delta: 0,
3659 htlc_minimum_msat: 0,
3660 htlc_maximum_msat: OptionalField::Present(100_000),
3662 fee_proportional_millionths: 0,
3663 excess_data: Vec::new()
3666 // Path via {node0, node2} is channels {1, 3, 5}.
3667 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3668 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3669 short_channel_id: 1,
3672 cltv_expiry_delta: 0,
3673 htlc_minimum_msat: 0,
3674 htlc_maximum_msat: OptionalField::Present(100_000),
3676 fee_proportional_millionths: 0,
3677 excess_data: Vec::new()
3679 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3680 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3681 short_channel_id: 3,
3684 cltv_expiry_delta: 0,
3685 htlc_minimum_msat: 0,
3686 htlc_maximum_msat: OptionalField::Present(100_000),
3688 fee_proportional_millionths: 0,
3689 excess_data: Vec::new()
3692 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(5)), 5);
3693 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3694 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3695 short_channel_id: 5,
3698 cltv_expiry_delta: 0,
3699 htlc_minimum_msat: 0,
3700 htlc_maximum_msat: OptionalField::Present(100_000),
3702 fee_proportional_millionths: 0,
3703 excess_data: Vec::new()
3706 // Path via {node7, node2, node4} is channels {12, 13, 6, 11}.
3707 // All channels should be 100 sats capacity. But for the fee experiment,
3708 // we'll add absolute fee of 150 sats paid for the use channel 6 (paid to node2 on channel 13).
3709 // Since channel 12 allows to deliver only 250 sats to channel 13, channel 13 can transfer only
3710 // 100 sats (and pay 150 sats in fees for the use of channel 6),
3711 // so no matter how large are other channels,
3712 // the whole path will be limited by 100 sats with just these 2 conditions:
3713 // - channel 12 capacity is 250 sats
3714 // - fee for channel 6 is 150 sats
3715 // Let's test this by enforcing these 2 conditions and removing other limits.
3716 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3717 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3718 short_channel_id: 12,
3721 cltv_expiry_delta: 0,
3722 htlc_minimum_msat: 0,
3723 htlc_maximum_msat: OptionalField::Present(250_000),
3725 fee_proportional_millionths: 0,
3726 excess_data: Vec::new()
3728 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
3729 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3730 short_channel_id: 13,
3733 cltv_expiry_delta: 0,
3734 htlc_minimum_msat: 0,
3735 htlc_maximum_msat: OptionalField::Absent,
3737 fee_proportional_millionths: 0,
3738 excess_data: Vec::new()
3741 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3742 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3743 short_channel_id: 6,
3746 cltv_expiry_delta: 0,
3747 htlc_minimum_msat: 0,
3748 htlc_maximum_msat: OptionalField::Absent,
3749 fee_base_msat: 150_000,
3750 fee_proportional_millionths: 0,
3751 excess_data: Vec::new()
3753 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
3754 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3755 short_channel_id: 11,
3758 cltv_expiry_delta: 0,
3759 htlc_minimum_msat: 0,
3760 htlc_maximum_msat: OptionalField::Absent,
3762 fee_proportional_millionths: 0,
3763 excess_data: Vec::new()
3767 // Attempt to route more than available results in a failure.
3768 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id, &net_graph_msg_handler.network_graph, &nodes[3],
3769 Some(InvoiceFeatures::known()), None, &Vec::new(), 210_000, 42, Arc::clone(&logger)) {
3770 assert_eq!(err, "Failed to find a sufficient route to the given destination");
3771 } else { panic!(); }
3775 // Now, attempt to route 200 sats (exact amount we can route).
3776 let route = get_route(&our_id, &net_graph_msg_handler.network_graph, &nodes[3],
3777 Some(InvoiceFeatures::known()), None, &Vec::new(), 200_000, 42, Arc::clone(&logger)).unwrap();
3778 assert_eq!(route.paths.len(), 2);
3780 let mut total_amount_paid_msat = 0;
3781 for path in &route.paths {
3782 assert_eq!(path.last().unwrap().pubkey, nodes[3]);
3783 total_amount_paid_msat += path.last().unwrap().fee_msat;
3785 assert_eq!(total_amount_paid_msat, 200_000);
3791 fn drop_lowest_channel_mpp_route_test() {
3792 // This test checks that low-capacity channel is dropped when after
3793 // path finding we realize that we found more capacity than we need.
3794 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
3795 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3797 // We need a route consisting of 3 paths:
3798 // From our node to node2 via node0, node7, node1 (three paths one hop each).
3800 // The first and the second paths should be sufficient, but the third should be
3801 // cheaper, so that we select it but drop later.
3803 // First, we set limits on these (previously unlimited) channels.
3804 // Their aggregate capacity will be 50 + 60 + 20 = 130 sats.
3806 // Path via node0 is channels {1, 3}. Limit them to 100 and 50 sats (total limit 50);
3807 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3808 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3809 short_channel_id: 1,
3812 cltv_expiry_delta: 0,
3813 htlc_minimum_msat: 0,
3814 htlc_maximum_msat: OptionalField::Present(100_000),
3816 fee_proportional_millionths: 0,
3817 excess_data: Vec::new()
3819 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3820 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3821 short_channel_id: 3,
3824 cltv_expiry_delta: 0,
3825 htlc_minimum_msat: 0,
3826 htlc_maximum_msat: OptionalField::Present(50_000),
3828 fee_proportional_millionths: 0,
3829 excess_data: Vec::new()
3832 // Path via node7 is channels {12, 13}. Limit them to 60 and 60 sats (total limit 60);
3833 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3834 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3835 short_channel_id: 12,
3838 cltv_expiry_delta: 0,
3839 htlc_minimum_msat: 0,
3840 htlc_maximum_msat: OptionalField::Present(60_000),
3842 fee_proportional_millionths: 0,
3843 excess_data: Vec::new()
3845 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
3846 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3847 short_channel_id: 13,
3850 cltv_expiry_delta: 0,
3851 htlc_minimum_msat: 0,
3852 htlc_maximum_msat: OptionalField::Present(60_000),
3854 fee_proportional_millionths: 0,
3855 excess_data: Vec::new()
3858 // Path via node1 is channels {2, 4}. Limit them to 20 and 20 sats (total capacity 20 sats).
3859 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3860 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3861 short_channel_id: 2,
3864 cltv_expiry_delta: 0,
3865 htlc_minimum_msat: 0,
3866 htlc_maximum_msat: OptionalField::Present(20_000),
3868 fee_proportional_millionths: 0,
3869 excess_data: Vec::new()
3871 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
3872 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3873 short_channel_id: 4,
3876 cltv_expiry_delta: 0,
3877 htlc_minimum_msat: 0,
3878 htlc_maximum_msat: OptionalField::Present(20_000),
3880 fee_proportional_millionths: 0,
3881 excess_data: Vec::new()
3885 // Attempt to route more than available results in a failure.
3886 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id, &net_graph_msg_handler.network_graph, &nodes[2],
3887 Some(InvoiceFeatures::known()), None, &Vec::new(), 150_000, 42, Arc::clone(&logger)) {
3888 assert_eq!(err, "Failed to find a sufficient route to the given destination");
3889 } else { panic!(); }
3893 // Now, attempt to route 125 sats (just a bit below the capacity of 3 channels).
3894 // Our algorithm should provide us with these 3 paths.
3895 let route = get_route(&our_id, &net_graph_msg_handler.network_graph, &nodes[2],
3896 Some(InvoiceFeatures::known()), None, &Vec::new(), 125_000, 42, Arc::clone(&logger)).unwrap();
3897 assert_eq!(route.paths.len(), 3);
3898 let mut total_amount_paid_msat = 0;
3899 for path in &route.paths {
3900 assert_eq!(path.len(), 2);
3901 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
3902 total_amount_paid_msat += path.last().unwrap().fee_msat;
3904 assert_eq!(total_amount_paid_msat, 125_000);
3908 // Attempt to route without the last small cheap channel
3909 let route = get_route(&our_id, &net_graph_msg_handler.network_graph, &nodes[2],
3910 Some(InvoiceFeatures::known()), None, &Vec::new(), 90_000, 42, Arc::clone(&logger)).unwrap();
3911 assert_eq!(route.paths.len(), 2);
3912 let mut total_amount_paid_msat = 0;
3913 for path in &route.paths {
3914 assert_eq!(path.len(), 2);
3915 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
3916 total_amount_paid_msat += path.last().unwrap().fee_msat;
3918 assert_eq!(total_amount_paid_msat, 90_000);
3923 fn min_criteria_consistency() {
3924 // Test that we don't use an inconsistent metric between updating and walking nodes during
3925 // our Dijkstra's pass. In the initial version of MPP, the "best source" for a given node
3926 // was updated with a different criterion from the heap sorting, resulting in loops in
3927 // calculated paths. We test for that specific case here.
3929 // We construct a network that looks like this:
3931 // node2 -1(3)2- node3
3935 // node1 -1(5)2- node4 -1(1)2- node6
3941 // We create a loop on the side of our real path - our destination is node 6, with a
3942 // previous hop of node 4. From 4, the cheapest previous path is channel 2 from node 2,
3943 // followed by node 3 over channel 3. Thereafter, the cheapest next-hop is back to node 4
3944 // (this time over channel 4). Channel 4 has 0 htlc_minimum_msat whereas channel 1 (the
3945 // other channel with a previous-hop of node 4) has a high (but irrelevant to the overall
3946 // payment) htlc_minimum_msat. In the original algorithm, this resulted in node4's
3947 // "previous hop" being set to node 3, creating a loop in the path.
3948 let secp_ctx = Secp256k1::new();
3949 let logger = Arc::new(test_utils::TestLogger::new());
3950 let net_graph_msg_handler = NetGraphMsgHandler::new(genesis_block(Network::Testnet).header.block_hash(), None, Arc::clone(&logger));
3951 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3953 add_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, &privkeys[1], ChannelFeatures::from_le_bytes(id_to_feature_flags(6)), 6);
3954 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3955 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3956 short_channel_id: 6,
3959 cltv_expiry_delta: (6 << 8) | 0,
3960 htlc_minimum_msat: 0,
3961 htlc_maximum_msat: OptionalField::Absent,
3963 fee_proportional_millionths: 0,
3964 excess_data: Vec::new()
3966 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[1], NodeFeatures::from_le_bytes(id_to_feature_flags(1)), 0);
3968 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], &privkeys[4], ChannelFeatures::from_le_bytes(id_to_feature_flags(5)), 5);
3969 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
3970 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3971 short_channel_id: 5,
3974 cltv_expiry_delta: (5 << 8) | 0,
3975 htlc_minimum_msat: 0,
3976 htlc_maximum_msat: OptionalField::Absent,
3978 fee_proportional_millionths: 0,
3979 excess_data: Vec::new()
3981 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[4], NodeFeatures::from_le_bytes(id_to_feature_flags(4)), 0);
3983 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(4)), 4);
3984 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
3985 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3986 short_channel_id: 4,
3989 cltv_expiry_delta: (4 << 8) | 0,
3990 htlc_minimum_msat: 0,
3991 htlc_maximum_msat: OptionalField::Absent,
3993 fee_proportional_millionths: 0,
3994 excess_data: Vec::new()
3996 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[3], NodeFeatures::from_le_bytes(id_to_feature_flags(3)), 0);
3998 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[3], &privkeys[2], ChannelFeatures::from_le_bytes(id_to_feature_flags(3)), 3);
3999 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[3], UnsignedChannelUpdate {
4000 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4001 short_channel_id: 3,
4004 cltv_expiry_delta: (3 << 8) | 0,
4005 htlc_minimum_msat: 0,
4006 htlc_maximum_msat: OptionalField::Absent,
4008 fee_proportional_millionths: 0,
4009 excess_data: Vec::new()
4011 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[2], NodeFeatures::from_le_bytes(id_to_feature_flags(2)), 0);
4013 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], &privkeys[4], ChannelFeatures::from_le_bytes(id_to_feature_flags(2)), 2);
4014 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4015 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4016 short_channel_id: 2,
4019 cltv_expiry_delta: (2 << 8) | 0,
4020 htlc_minimum_msat: 0,
4021 htlc_maximum_msat: OptionalField::Absent,
4023 fee_proportional_millionths: 0,
4024 excess_data: Vec::new()
4027 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], &privkeys[6], ChannelFeatures::from_le_bytes(id_to_feature_flags(1)), 1);
4028 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
4029 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4030 short_channel_id: 1,
4033 cltv_expiry_delta: (1 << 8) | 0,
4034 htlc_minimum_msat: 100,
4035 htlc_maximum_msat: OptionalField::Absent,
4037 fee_proportional_millionths: 0,
4038 excess_data: Vec::new()
4040 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[6], NodeFeatures::from_le_bytes(id_to_feature_flags(6)), 0);
4043 // Now ensure the route flows simply over nodes 1 and 4 to 6.
4044 let route = get_route(&our_id, &net_graph_msg_handler.network_graph, &nodes[6], None, None, &Vec::new(), 10_000, 42, Arc::clone(&logger)).unwrap();
4045 assert_eq!(route.paths.len(), 1);
4046 assert_eq!(route.paths[0].len(), 3);
4048 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
4049 assert_eq!(route.paths[0][0].short_channel_id, 6);
4050 assert_eq!(route.paths[0][0].fee_msat, 100);
4051 assert_eq!(route.paths[0][0].cltv_expiry_delta, (5 << 8) | 0);
4052 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(1));
4053 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(6));
4055 assert_eq!(route.paths[0][1].pubkey, nodes[4]);
4056 assert_eq!(route.paths[0][1].short_channel_id, 5);
4057 assert_eq!(route.paths[0][1].fee_msat, 0);
4058 assert_eq!(route.paths[0][1].cltv_expiry_delta, (1 << 8) | 0);
4059 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(4));
4060 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(5));
4062 assert_eq!(route.paths[0][2].pubkey, nodes[6]);
4063 assert_eq!(route.paths[0][2].short_channel_id, 1);
4064 assert_eq!(route.paths[0][2].fee_msat, 10_000);
4065 assert_eq!(route.paths[0][2].cltv_expiry_delta, 42);
4066 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(6));
4067 assert_eq!(route.paths[0][2].channel_features.le_flags(), &id_to_feature_flags(1));
4073 fn exact_fee_liquidity_limit() {
4074 // Test that if, while walking the graph, we find a hop that has exactly enough liquidity
4075 // for us, including later hop fees, we take it. In the first version of our MPP algorithm
4076 // we calculated fees on a higher value, resulting in us ignoring such paths.
4077 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
4078 let (our_privkey, our_id, _, nodes) = get_nodes(&secp_ctx);
4080 // We modify the graph to set the htlc_maximum of channel 2 to below the value we wish to
4082 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4083 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4084 short_channel_id: 2,
4087 cltv_expiry_delta: 0,
4088 htlc_minimum_msat: 0,
4089 htlc_maximum_msat: OptionalField::Present(85_000),
4091 fee_proportional_millionths: 0,
4092 excess_data: Vec::new()
4095 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4096 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4097 short_channel_id: 12,
4100 cltv_expiry_delta: (4 << 8) | 1,
4101 htlc_minimum_msat: 0,
4102 htlc_maximum_msat: OptionalField::Present(270_000),
4104 fee_proportional_millionths: 1000000,
4105 excess_data: Vec::new()
4109 // Now, attempt to route 90 sats, which is exactly 90 sats at the last hop, plus the
4110 // 200% fee charged channel 13 in the 1-to-2 direction.
4111 let route = get_route(&our_id, &net_graph_msg_handler.network_graph, &nodes[2], None, None, &Vec::new(), 90_000, 42, Arc::clone(&logger)).unwrap();
4112 assert_eq!(route.paths.len(), 1);
4113 assert_eq!(route.paths[0].len(), 2);
4115 assert_eq!(route.paths[0][0].pubkey, nodes[7]);
4116 assert_eq!(route.paths[0][0].short_channel_id, 12);
4117 assert_eq!(route.paths[0][0].fee_msat, 90_000*2);
4118 assert_eq!(route.paths[0][0].cltv_expiry_delta, (13 << 8) | 1);
4119 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(8));
4120 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(12));
4122 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
4123 assert_eq!(route.paths[0][1].short_channel_id, 13);
4124 assert_eq!(route.paths[0][1].fee_msat, 90_000);
4125 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
4126 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
4127 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(13));
4132 fn htlc_max_reduction_below_min() {
4133 // Test that if, while walking the graph, we reduce the value being sent to meet an
4134 // htlc_maximum_msat, we don't end up undershooting a later htlc_minimum_msat. In the
4135 // initial version of MPP we'd accept such routes but reject them while recalculating fees,
4136 // resulting in us thinking there is no possible path, even if other paths exist.
4137 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
4138 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
4140 // We modify the graph to set the htlc_minimum of channel 2 and 4 as needed - channel 2
4141 // gets an htlc_maximum_msat of 80_000 and channel 4 an htlc_minimum_msat of 90_000. We
4142 // then try to send 90_000.
4143 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4144 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4145 short_channel_id: 2,
4148 cltv_expiry_delta: 0,
4149 htlc_minimum_msat: 0,
4150 htlc_maximum_msat: OptionalField::Present(80_000),
4152 fee_proportional_millionths: 0,
4153 excess_data: Vec::new()
4155 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
4156 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4157 short_channel_id: 4,
4160 cltv_expiry_delta: (4 << 8) | 1,
4161 htlc_minimum_msat: 90_000,
4162 htlc_maximum_msat: OptionalField::Absent,
4164 fee_proportional_millionths: 0,
4165 excess_data: Vec::new()
4169 // Now, attempt to route 90 sats, hitting the htlc_minimum on channel 4, but
4170 // overshooting the htlc_maximum on channel 2. Thus, we should pick the (absurdly
4171 // expensive) channels 12-13 path.
4172 let route = get_route(&our_id, &net_graph_msg_handler.network_graph, &nodes[2], Some(InvoiceFeatures::known()), None, &Vec::new(), 90_000, 42, Arc::clone(&logger)).unwrap();
4173 assert_eq!(route.paths.len(), 1);
4174 assert_eq!(route.paths[0].len(), 2);
4176 assert_eq!(route.paths[0][0].pubkey, nodes[7]);
4177 assert_eq!(route.paths[0][0].short_channel_id, 12);
4178 assert_eq!(route.paths[0][0].fee_msat, 90_000*2);
4179 assert_eq!(route.paths[0][0].cltv_expiry_delta, (13 << 8) | 1);
4180 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(8));
4181 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(12));
4183 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
4184 assert_eq!(route.paths[0][1].short_channel_id, 13);
4185 assert_eq!(route.paths[0][1].fee_msat, 90_000);
4186 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
4187 assert_eq!(route.paths[0][1].node_features.le_flags(), InvoiceFeatures::known().le_flags());
4188 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(13));
4192 #[cfg(not(feature = "no-std"))]
4193 pub(super) fn random_init_seed() -> u64 {
4194 // Because the default HashMap in std pulls OS randomness, we can use it as a (bad) RNG.
4195 use core::hash::{BuildHasher, Hasher};
4196 let seed = std::collections::hash_map::RandomState::new().build_hasher().finish();
4197 println!("Using seed of {}", seed);
4200 #[cfg(not(feature = "no-std"))]
4201 use util::ser::Readable;
4204 #[cfg(not(feature = "no-std"))]
4205 fn generate_routes() {
4206 let mut d = match super::test_utils::get_route_file() {
4213 let graph = NetworkGraph::read(&mut d).unwrap();
4215 // First, get 100 (source, destination) pairs for which route-getting actually succeeds...
4216 let mut seed = random_init_seed() as usize;
4217 let nodes = graph.read_only().nodes().clone();
4218 'load_endpoints: for _ in 0..10 {
4220 seed = seed.overflowing_mul(0xdeadbeef).0;
4221 let src = nodes.keys().skip(seed % nodes.len()).next().unwrap();
4222 seed = seed.overflowing_mul(0xdeadbeef).0;
4223 let dst = nodes.keys().skip(seed % nodes.len()).next().unwrap();
4224 let amt = seed as u64 % 200_000_000;
4225 if get_route(src, &graph, dst, None, None, &[], amt, 42, &test_utils::TestLogger::new()).is_ok() {
4226 continue 'load_endpoints;
4233 #[cfg(not(feature = "no-std"))]
4234 fn generate_routes_mpp() {
4235 let mut d = match super::test_utils::get_route_file() {
4242 let graph = NetworkGraph::read(&mut d).unwrap();
4244 // First, get 100 (source, destination) pairs for which route-getting actually succeeds...
4245 let mut seed = random_init_seed() as usize;
4246 let nodes = graph.read_only().nodes().clone();
4247 'load_endpoints: for _ in 0..10 {
4249 seed = seed.overflowing_mul(0xdeadbeef).0;
4250 let src = nodes.keys().skip(seed % nodes.len()).next().unwrap();
4251 seed = seed.overflowing_mul(0xdeadbeef).0;
4252 let dst = nodes.keys().skip(seed % nodes.len()).next().unwrap();
4253 let amt = seed as u64 % 200_000_000;
4254 if get_route(src, &graph, dst, Some(InvoiceFeatures::known()), None, &[], amt, 42, &test_utils::TestLogger::new()).is_ok() {
4255 continue 'load_endpoints;
4262 #[cfg(all(test, not(feature = "no-std")))]
4263 pub(crate) mod test_utils {
4265 /// Tries to open a network graph file, or panics with a URL to fetch it.
4266 pub(crate) fn get_route_file() -> Result<std::fs::File, &'static str> {
4267 let res = File::open("net_graph-2021-05-31.bin") // By default we're run in RL/lightning
4268 .or_else(|_| File::open("lightning/net_graph-2021-05-31.bin")) // We may be run manually in RL/
4269 .or_else(|_| { // Fall back to guessing based on the binary location
4270 // path is likely something like .../rust-lightning/target/debug/deps/lightning-...
4271 let mut path = std::env::current_exe().unwrap();
4272 path.pop(); // lightning-...
4274 path.pop(); // debug
4275 path.pop(); // target
4276 path.push("lightning");
4277 path.push("net_graph-2021-05-31.bin");
4278 eprintln!("{}", path.to_str().unwrap());
4281 .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");
4282 #[cfg(require_route_graph_test)]
4283 return Ok(res.unwrap());
4284 #[cfg(not(require_route_graph_test))]
4289 #[cfg(all(test, feature = "unstable", not(feature = "no-std")))]
4292 use util::logger::{Logger, Record};
4296 struct DummyLogger {}
4297 impl Logger for DummyLogger {
4298 fn log(&self, _record: &Record) {}
4302 fn generate_routes(bench: &mut Bencher) {
4303 let mut d = test_utils::get_route_file().unwrap();
4304 let graph = NetworkGraph::read(&mut d).unwrap();
4305 let nodes = graph.read_only().nodes().clone();
4307 // First, get 100 (source, destination) pairs for which route-getting actually succeeds...
4308 let mut path_endpoints = Vec::new();
4309 let mut seed: usize = 0xdeadbeef;
4310 'load_endpoints: for _ in 0..100 {
4313 let src = nodes.keys().skip(seed % nodes.len()).next().unwrap();
4315 let dst = nodes.keys().skip(seed % nodes.len()).next().unwrap();
4316 let amt = seed as u64 % 1_000_000;
4317 if get_route(src, &graph, dst, None, None, &[], amt, 42, &DummyLogger{}).is_ok() {
4318 path_endpoints.push((src, dst, amt));
4319 continue 'load_endpoints;
4324 // ...then benchmark finding paths between the nodes we learned.
4327 let (src, dst, amt) = path_endpoints[idx % path_endpoints.len()];
4328 assert!(get_route(src, &graph, dst, None, None, &[], amt, 42, &DummyLogger{}).is_ok());
4334 fn generate_mpp_routes(bench: &mut Bencher) {
4335 let mut d = test_utils::get_route_file().unwrap();
4336 let graph = NetworkGraph::read(&mut d).unwrap();
4337 let nodes = graph.read_only().nodes().clone();
4339 // First, get 100 (source, destination) pairs for which route-getting actually succeeds...
4340 let mut path_endpoints = Vec::new();
4341 let mut seed: usize = 0xdeadbeef;
4342 'load_endpoints: for _ in 0..100 {
4345 let src = nodes.keys().skip(seed % nodes.len()).next().unwrap();
4347 let dst = nodes.keys().skip(seed % nodes.len()).next().unwrap();
4348 let amt = seed as u64 % 1_000_000;
4349 if get_route(src, &graph, dst, Some(InvoiceFeatures::known()), None, &[], amt, 42, &DummyLogger{}).is_ok() {
4350 path_endpoints.push((src, dst, amt));
4351 continue 'load_endpoints;
4356 // ...then benchmark finding paths between the nodes we learned.
4359 let (src, dst, amt) = path_endpoints[idx % path_endpoints.len()];
4360 assert!(get_route(src, &graph, dst, Some(InvoiceFeatures::known()), None, &[], amt, 42, &DummyLogger{}).is_ok());