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, Debug, 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>>,
75 /// Returns the total amount of fees paid on this Route.
76 /// This doesn't include any extra payment made to the recipient,
77 /// which can happen in excess of the amount passed to `get_route`'s `final_value_msat`.
78 pub fn get_total_fees(&self) -> u64 {
79 // Do not count last hop of each path since that's the full value of the payment
80 return self.paths.iter()
81 .flat_map(|path| path.split_last().unwrap().1)
82 .map(|hop| &hop.fee_msat)
85 /// Returns the total amount paid on this Route, excluding the fees.
86 pub fn get_total_amount(&self) -> u64 {
87 return self.paths.iter()
88 .map(|path| path.split_last().unwrap().0)
89 .map(|hop| &hop.fee_msat)
94 const SERIALIZATION_VERSION: u8 = 1;
95 const MIN_SERIALIZATION_VERSION: u8 = 1;
97 impl Writeable for Route {
98 fn write<W: ::util::ser::Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
99 write_ver_prefix!(writer, SERIALIZATION_VERSION, MIN_SERIALIZATION_VERSION);
100 (self.paths.len() as u64).write(writer)?;
101 for hops in self.paths.iter() {
102 (hops.len() as u8).write(writer)?;
103 for hop in hops.iter() {
107 write_tlv_fields!(writer, {});
112 impl Readable for Route {
113 fn read<R: io::Read>(reader: &mut R) -> Result<Route, DecodeError> {
114 let _ver = read_ver_prefix!(reader, SERIALIZATION_VERSION);
115 let path_count: u64 = Readable::read(reader)?;
116 let mut paths = Vec::with_capacity(cmp::min(path_count, 128) as usize);
117 for _ in 0..path_count {
118 let hop_count: u8 = Readable::read(reader)?;
119 let mut hops = Vec::with_capacity(hop_count as usize);
120 for _ in 0..hop_count {
121 hops.push(Readable::read(reader)?);
125 read_tlv_fields!(reader, {});
130 /// A list of hops along a payment path terminating with a channel to the recipient.
131 #[derive(Clone, Debug, Hash, Eq, PartialEq)]
132 pub struct RouteHint(pub Vec<RouteHintHop>);
134 /// A channel descriptor for a hop along a payment path.
135 #[derive(Clone, Debug, Hash, Eq, PartialEq)]
136 pub struct RouteHintHop {
137 /// The node_id of the non-target end of the route
138 pub src_node_id: PublicKey,
139 /// The short_channel_id of this channel
140 pub short_channel_id: u64,
141 /// The fees which must be paid to use this channel
142 pub fees: RoutingFees,
143 /// The difference in CLTV values between this node and the next node.
144 pub cltv_expiry_delta: u16,
145 /// The minimum value, in msat, which must be relayed to the next hop.
146 pub htlc_minimum_msat: Option<u64>,
147 /// The maximum value in msat available for routing with a single HTLC.
148 pub htlc_maximum_msat: Option<u64>,
151 #[derive(Eq, PartialEq)]
152 struct RouteGraphNode {
154 lowest_fee_to_peer_through_node: u64,
155 lowest_fee_to_node: u64,
156 // The maximum value a yet-to-be-constructed payment path might flow through this node.
157 // This value is upper-bounded by us by:
158 // - how much is needed for a path being constructed
159 // - how much value can channels following this node (up to the destination) can contribute,
160 // considering their capacity and fees
161 value_contribution_msat: u64,
162 /// The effective htlc_minimum_msat at this hop. If a later hop on the path had a higher HTLC
163 /// minimum, we use it, plus the fees required at each earlier hop to meet it.
164 path_htlc_minimum_msat: u64,
167 impl cmp::Ord for RouteGraphNode {
168 fn cmp(&self, other: &RouteGraphNode) -> cmp::Ordering {
169 let other_score = cmp::max(other.lowest_fee_to_peer_through_node, other.path_htlc_minimum_msat);
170 let self_score = cmp::max(self.lowest_fee_to_peer_through_node, self.path_htlc_minimum_msat);
171 other_score.cmp(&self_score).then_with(|| other.pubkey.serialize().cmp(&self.pubkey.serialize()))
175 impl cmp::PartialOrd for RouteGraphNode {
176 fn partial_cmp(&self, other: &RouteGraphNode) -> Option<cmp::Ordering> {
177 Some(self.cmp(other))
181 struct DummyDirectionalChannelInfo {
182 cltv_expiry_delta: u32,
183 htlc_minimum_msat: u64,
184 htlc_maximum_msat: Option<u64>,
188 /// It's useful to keep track of the hops associated with the fees required to use them,
189 /// so that we can choose cheaper paths (as per Dijkstra's algorithm).
190 /// Fee values should be updated only in the context of the whole path, see update_value_and_recompute_fees.
191 /// These fee values are useful to choose hops as we traverse the graph "payee-to-payer".
192 #[derive(Clone, Debug)]
193 struct PathBuildingHop<'a> {
194 // The RouteHintHop fields which will eventually be used if this hop is used in a final Route.
195 // Note that node_features is calculated separately after our initial graph walk.
197 short_channel_id: u64,
198 channel_features: &'a ChannelFeatures,
200 cltv_expiry_delta: u32,
202 /// Minimal fees required to route to the source node of the current hop via any of its inbound channels.
203 src_lowest_inbound_fees: RoutingFees,
204 /// Fees of the channel used in this hop.
205 channel_fees: RoutingFees,
206 /// All the fees paid *after* this channel on the way to the destination
207 next_hops_fee_msat: u64,
208 /// Fee paid for the use of the current channel (see channel_fees).
209 /// The value will be actually deducted from the counterparty balance on the previous link.
210 hop_use_fee_msat: u64,
211 /// Used to compare channels when choosing the for routing.
212 /// Includes paying for the use of a hop and the following hops, as well as
213 /// an estimated cost of reaching this hop.
214 /// Might get stale when fees are recomputed. Primarily for internal use.
216 /// This is useful for update_value_and_recompute_fees to make sure
217 /// we don't fall below the minimum. Should not be updated manually and
218 /// generally should not be accessed.
219 htlc_minimum_msat: u64,
220 /// A mirror of the same field in RouteGraphNode. Note that this is only used during the graph
221 /// walk and may be invalid thereafter.
222 path_htlc_minimum_msat: u64,
223 /// If we've already processed a node as the best node, we shouldn't process it again. Normally
224 /// we'd just ignore it if we did as all channels would have a higher new fee, but because we
225 /// may decrease the amounts in use as we walk the graph, the actual calculated fee may
226 /// decrease as well. Thus, we have to explicitly track which nodes have been processed and
227 /// avoid processing them again.
229 #[cfg(any(test, feature = "fuzztarget"))]
230 // In tests, we apply further sanity checks on cases where we skip nodes we already processed
231 // to ensure it is specifically in cases where the fee has gone down because of a decrease in
232 // value_contribution_msat, which requires tracking it here. See comments below where it is
233 // used for more info.
234 value_contribution_msat: u64,
237 // Instantiated with a list of hops with correct data in them collected during path finding,
238 // an instance of this struct should be further modified only via given methods.
240 struct PaymentPath<'a> {
241 hops: Vec<(PathBuildingHop<'a>, NodeFeatures)>,
244 impl<'a> PaymentPath<'a> {
245 // TODO: Add a value_msat field to PaymentPath and use it instead of this function.
246 fn get_value_msat(&self) -> u64 {
247 self.hops.last().unwrap().0.fee_msat
250 fn get_total_fee_paid_msat(&self) -> u64 {
251 if self.hops.len() < 1 {
255 // Can't use next_hops_fee_msat because it gets outdated.
256 for (i, (hop, _)) in self.hops.iter().enumerate() {
257 if i != self.hops.len() - 1 {
258 result += hop.fee_msat;
264 // If the amount transferred by the path is updated, the fees should be adjusted. Any other way
265 // to change fees may result in an inconsistency.
267 // Sometimes we call this function right after constructing a path which is inconsistent in
268 // that it the value being transferred has decreased while we were doing path finding, leading
269 // to the fees being paid not lining up with the actual limits.
271 // Note that this function is not aware of the available_liquidity limit, and thus does not
272 // support increasing the value being transferred.
273 fn update_value_and_recompute_fees(&mut self, value_msat: u64) {
274 assert!(value_msat <= self.hops.last().unwrap().0.fee_msat);
276 let mut total_fee_paid_msat = 0 as u64;
277 for i in (0..self.hops.len()).rev() {
278 let last_hop = i == self.hops.len() - 1;
280 // For non-last-hop, this value will represent the fees paid on the current hop. It
281 // will consist of the fees for the use of the next hop, and extra fees to match
282 // htlc_minimum_msat of the current channel. Last hop is handled separately.
283 let mut cur_hop_fees_msat = 0;
285 cur_hop_fees_msat = self.hops.get(i + 1).unwrap().0.hop_use_fee_msat;
288 let mut cur_hop = &mut self.hops.get_mut(i).unwrap().0;
289 cur_hop.next_hops_fee_msat = total_fee_paid_msat;
290 // Overpay in fees if we can't save these funds due to htlc_minimum_msat.
291 // We try to account for htlc_minimum_msat in scoring (add_entry!), so that nodes don't
292 // set it too high just to maliciously take more fees by exploiting this
293 // match htlc_minimum_msat logic.
294 let mut cur_hop_transferred_amount_msat = total_fee_paid_msat + value_msat;
295 if let Some(extra_fees_msat) = cur_hop.htlc_minimum_msat.checked_sub(cur_hop_transferred_amount_msat) {
296 // Note that there is a risk that *previous hops* (those closer to us, as we go
297 // payee->our_node here) would exceed their htlc_maximum_msat or available balance.
299 // This might make us end up with a broken route, although this should be super-rare
300 // in practice, both because of how healthy channels look like, and how we pick
301 // channels in add_entry.
302 // Also, this can't be exploited more heavily than *announce a free path and fail
304 cur_hop_transferred_amount_msat += extra_fees_msat;
305 total_fee_paid_msat += extra_fees_msat;
306 cur_hop_fees_msat += extra_fees_msat;
310 // Final hop is a special case: it usually has just value_msat (by design), but also
311 // it still could overpay for the htlc_minimum_msat.
312 cur_hop.fee_msat = cur_hop_transferred_amount_msat;
314 // Propagate updated fees for the use of the channels to one hop back, where they
315 // will be actually paid (fee_msat). The last hop is handled above separately.
316 cur_hop.fee_msat = cur_hop_fees_msat;
319 // Fee for the use of the current hop which will be deducted on the previous hop.
320 // Irrelevant for the first hop, as it doesn't have the previous hop, and the use of
321 // this channel is free for us.
323 if let Some(new_fee) = compute_fees(cur_hop_transferred_amount_msat, cur_hop.channel_fees) {
324 cur_hop.hop_use_fee_msat = new_fee;
325 total_fee_paid_msat += new_fee;
327 // It should not be possible because this function is called only to reduce the
328 // value. In that case, compute_fee was already called with the same fees for
329 // larger amount and there was no overflow.
337 fn compute_fees(amount_msat: u64, channel_fees: RoutingFees) -> Option<u64> {
338 let proportional_fee_millions =
339 amount_msat.checked_mul(channel_fees.proportional_millionths as u64);
340 if let Some(new_fee) = proportional_fee_millions.and_then(|part| {
341 (channel_fees.base_msat as u64).checked_add(part / 1_000_000) }) {
345 // This function may be (indirectly) called without any verification,
346 // with channel_fees provided by a caller. We should handle it gracefully.
351 /// Gets a keysend route from us (payer) to the given target node (payee). This is needed because
352 /// keysend payments do not have an invoice from which to pull the payee's supported features, which
353 /// makes it tricky to otherwise supply the `payee_features` parameter of `get_route`.
354 pub fn get_keysend_route<L: Deref>(our_node_id: &PublicKey, network: &NetworkGraph, payee:
355 &PublicKey, first_hops: Option<&[&ChannelDetails]>, last_hops: &[&RouteHint],
356 final_value_msat: u64, final_cltv: u32, logger: L) -> Result<Route,
357 LightningError> where L::Target: Logger {
358 let invoice_features = InvoiceFeatures::for_keysend();
359 get_route(our_node_id, network, payee, Some(invoice_features), first_hops, last_hops,
360 final_value_msat, final_cltv, logger)
363 /// Gets a route from us (payer) to the given target node (payee).
365 /// If the payee provided features in their invoice, they should be provided via payee_features.
366 /// Without this, MPP will only be used if the payee's features are available in the network graph.
368 /// Private routing paths between a public node and the target may be included in `last_hops`.
369 /// Currently, only the last hop in each path is considered.
371 /// If some channels aren't announced, it may be useful to fill in a first_hops with the
372 /// results from a local ChannelManager::list_usable_channels() call. If it is filled in, our
373 /// view of our local channels (from net_graph_msg_handler) will be ignored, and only those
374 /// in first_hops will be used.
376 /// Panics if first_hops contains channels without short_channel_ids
377 /// (ChannelManager::list_usable_channels will never include such channels).
379 /// The fees on channels from us to next-hops are ignored (as they are assumed to all be
380 /// equal), however the enabled/disabled bit on such channels as well as the
381 /// htlc_minimum_msat/htlc_maximum_msat *are* checked as they may change based on the receiving node.
382 pub fn get_route<L: Deref>(our_node_id: &PublicKey, network: &NetworkGraph, payee: &PublicKey, payee_features: Option<InvoiceFeatures>, first_hops: Option<&[&ChannelDetails]>,
383 last_hops: &[&RouteHint], final_value_msat: u64, final_cltv: u32, logger: L) -> Result<Route, LightningError> where L::Target: Logger {
384 // TODO: Obviously *only* using total fee cost sucks. We should consider weighting by
385 // uptime/success in using a node in the past.
386 if *payee == *our_node_id {
387 return Err(LightningError{err: "Cannot generate a route to ourselves".to_owned(), action: ErrorAction::IgnoreError});
390 if final_value_msat > MAX_VALUE_MSAT {
391 return Err(LightningError{err: "Cannot generate a route of more value than all existing satoshis".to_owned(), action: ErrorAction::IgnoreError});
394 if final_value_msat == 0 {
395 return Err(LightningError{err: "Cannot send a payment of 0 msat".to_owned(), action: ErrorAction::IgnoreError});
398 for route in last_hops.iter() {
399 for hop in &route.0 {
400 if hop.src_node_id == *payee {
401 return Err(LightningError{err: "Last hop cannot have a payee as a source.".to_owned(), action: ErrorAction::IgnoreError});
406 // The general routing idea is the following:
407 // 1. Fill first/last hops communicated by the caller.
408 // 2. Attempt to construct a path from payer to payee for transferring
409 // any ~sufficient (described later) value.
410 // If succeed, remember which channels were used and how much liquidity they have available,
411 // so that future paths don't rely on the same liquidity.
412 // 3. Prooceed to the next step if:
413 // - we hit the recommended target value;
414 // - OR if we could not construct a new path. Any next attempt will fail too.
415 // Otherwise, repeat step 2.
416 // 4. See if we managed to collect paths which aggregately are able to transfer target value
417 // (not recommended value). If yes, proceed. If not, fail routing.
418 // 5. Randomly combine paths into routes having enough to fulfill the payment. (TODO: knapsack)
419 // 6. Of all the found paths, select only those with the lowest total fee.
420 // 7. The last path in every selected route is likely to be more than we need.
421 // Reduce its value-to-transfer and recompute fees.
422 // 8. Choose the best route by the lowest total fee.
424 // As for the actual search algorithm,
425 // we do a payee-to-payer pseudo-Dijkstra's sorting by each node's distance from the payee
426 // plus the minimum per-HTLC fee to get from it to another node (aka "shitty pseudo-A*").
428 // We are not a faithful Dijkstra's implementation because we can change values which impact
429 // earlier nodes while processing later nodes. Specifically, if we reach a channel with a lower
430 // liquidity limit (via htlc_maximum_msat, on-chain capacity or assumed liquidity limits) then
431 // the value we are currently attempting to send over a path, we simply reduce the value being
432 // sent along the path for any hops after that channel. This may imply that later fees (which
433 // we've already tabulated) are lower because a smaller value is passing through the channels
434 // (and the proportional fee is thus lower). There isn't a trivial way to recalculate the
435 // channels which were selected earlier (and which may still be used for other paths without a
436 // lower liquidity limit), so we simply accept that some liquidity-limited paths may be
439 // One potentially problematic case for this algorithm would be if there are many
440 // liquidity-limited paths which are liquidity-limited near the destination (ie early in our
441 // graph walking), we may never find a path which is not liquidity-limited and has lower
442 // proportional fee (and only lower absolute fee when considering the ultimate value sent).
443 // Because we only consider paths with at least 5% of the total value being sent, the damage
444 // from such a case should be limited, however this could be further reduced in the future by
445 // calculating fees on the amount we wish to route over a path, ie ignoring the liquidity
446 // limits for the purposes of fee calculation.
448 // Alternatively, we could store more detailed path information in the heap (targets, below)
449 // and index the best-path map (dist, below) by node *and* HTLC limits, however that would blow
450 // up the runtime significantly both algorithmically (as we'd traverse nodes multiple times)
451 // and practically (as we would need to store dynamically-allocated path information in heap
452 // objects, increasing malloc traffic and indirect memory access significantly). Further, the
453 // results of such an algorithm would likely be biased towards lower-value paths.
455 // Further, we could return to a faithful Dijkstra's algorithm by rejecting paths with limits
456 // outside of our current search value, running a path search more times to gather candidate
457 // paths at different values. While this may be acceptable, further path searches may increase
458 // runtime for little gain. Specifically, the current algorithm rather efficiently explores the
459 // graph for candidate paths, calculating the maximum value which can realistically be sent at
460 // the same time, remaining generic across different payment values.
462 // TODO: There are a few tweaks we could do, including possibly pre-calculating more stuff
463 // to use as the A* heuristic beyond just the cost to get one node further than the current
466 let network_graph = network.read_only();
467 let network_channels = network_graph.channels();
468 let network_nodes = network_graph.nodes();
469 let dummy_directional_info = DummyDirectionalChannelInfo { // used for first_hops routes
470 cltv_expiry_delta: 0,
471 htlc_minimum_msat: 0,
472 htlc_maximum_msat: None,
475 proportional_millionths: 0,
479 // Allow MPP only if we have a features set from somewhere that indicates the payee supports
480 // it. If the payee supports it they're supposed to include it in the invoice, so that should
482 let allow_mpp = if let Some(features) = &payee_features {
483 features.supports_basic_mpp()
484 } else if let Some(node) = network_nodes.get(&payee) {
485 if let Some(node_info) = node.announcement_info.as_ref() {
486 node_info.features.supports_basic_mpp()
491 // Prepare the data we'll use for payee-to-payer search by
492 // inserting first hops suggested by the caller as targets.
493 // Our search will then attempt to reach them while traversing from the payee node.
494 let mut first_hop_targets: HashMap<_, (_, ChannelFeatures, _, NodeFeatures)> =
495 HashMap::with_capacity(if first_hops.is_some() { first_hops.as_ref().unwrap().len() } else { 0 });
496 if let Some(hops) = first_hops {
498 let short_channel_id = chan.short_channel_id.expect("first_hops should be filled in with usable channels, not pending ones");
499 if chan.counterparty.node_id == *our_node_id {
500 return Err(LightningError{err: "First hop cannot have our_node_id as a destination.".to_owned(), action: ErrorAction::IgnoreError});
502 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()));
504 if first_hop_targets.is_empty() {
505 return Err(LightningError{err: "Cannot route when there are no outbound routes away from us".to_owned(), action: ErrorAction::IgnoreError});
509 let empty_channel_features = ChannelFeatures::empty();
511 // The main heap containing all candidate next-hops sorted by their score (max(A* fee,
512 // htlc_minimum)). Ideally this would be a heap which allowed cheap score reduction instead of
513 // adding duplicate entries when we find a better path to a given node.
514 let mut targets = BinaryHeap::new();
516 // Map from node_id to information about the best current path to that node, including feerate
518 let mut dist = HashMap::with_capacity(network_nodes.len());
520 // During routing, if we ignore a path due to an htlc_minimum_msat limit, we set this,
521 // indicating that we may wish to try again with a higher value, potentially paying to meet an
522 // htlc_minimum with extra fees while still finding a cheaper path.
523 let mut hit_minimum_limit;
525 // When arranging a route, we select multiple paths so that we can make a multi-path payment.
526 // We start with a path_value of the exact amount we want, and if that generates a route we may
527 // return it immediately. Otherwise, we don't stop searching for paths until we have 3x the
528 // amount we want in total across paths, selecting the best subset at the end.
529 const ROUTE_CAPACITY_PROVISION_FACTOR: u64 = 3;
530 let recommended_value_msat = final_value_msat * ROUTE_CAPACITY_PROVISION_FACTOR as u64;
531 let mut path_value_msat = final_value_msat;
533 // We don't want multiple paths (as per MPP) share liquidity of the same channels.
534 // This map allows paths to be aware of the channel use by other paths in the same call.
535 // This would help to make a better path finding decisions and not "overbook" channels.
536 // It is unaware of the directions (except for `outbound_capacity_msat` in `first_hops`).
537 let mut bookkeeped_channels_liquidity_available_msat = HashMap::with_capacity(network_nodes.len());
539 // Keeping track of how much value we already collected across other paths. Helps to decide:
540 // - how much a new path should be transferring (upper bound);
541 // - whether a channel should be disregarded because
542 // it's available liquidity is too small comparing to how much more we need to collect;
543 // - when we want to stop looking for new paths.
544 let mut already_collected_value_msat = 0;
546 log_trace!(logger, "Building path from {} (payee) to {} (us/payer) for value {} msat.", payee, our_node_id, final_value_msat);
548 macro_rules! add_entry {
549 // Adds entry which goes from $src_node_id to $dest_node_id
550 // over the channel with id $chan_id with fees described in
551 // $directional_info.
552 // $next_hops_fee_msat represents the fees paid for using all the channel *after* this one,
553 // since that value has to be transferred over this channel.
554 // Returns whether this channel caused an update to `targets`.
555 ( $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,
556 $next_hops_value_contribution: expr, $next_hops_path_htlc_minimum_msat: expr ) => { {
557 // We "return" whether we updated the path at the end, via this:
558 let mut did_add_update_path_to_src_node = false;
559 // Channels to self should not be used. This is more of belt-and-suspenders, because in
560 // practice these cases should be caught earlier:
561 // - for regular channels at channel announcement (TODO)
562 // - for first and last hops early in get_route
563 if $src_node_id != $dest_node_id.clone() {
564 let available_liquidity_msat = bookkeeped_channels_liquidity_available_msat.entry($chan_id.clone()).or_insert_with(|| {
565 let mut initial_liquidity_available_msat = None;
566 if let Some(capacity_sats) = $capacity_sats {
567 initial_liquidity_available_msat = Some(capacity_sats * 1000);
570 if let Some(htlc_maximum_msat) = $directional_info.htlc_maximum_msat {
571 if let Some(available_msat) = initial_liquidity_available_msat {
572 initial_liquidity_available_msat = Some(cmp::min(available_msat, htlc_maximum_msat));
574 initial_liquidity_available_msat = Some(htlc_maximum_msat);
578 match initial_liquidity_available_msat {
579 Some(available_msat) => available_msat,
580 // We assume channels with unknown balance have
581 // a capacity of 0.0025 BTC (or 250_000 sats).
582 None => 250_000 * 1000
586 // It is tricky to substract $next_hops_fee_msat from available liquidity here.
587 // It may be misleading because we might later choose to reduce the value transferred
588 // over these channels, and the channel which was insufficient might become sufficient.
589 // Worst case: we drop a good channel here because it can't cover the high following
590 // fees caused by one expensive channel, but then this channel could have been used
591 // if the amount being transferred over this path is lower.
592 // We do this for now, but this is a subject for removal.
593 if let Some(available_value_contribution_msat) = available_liquidity_msat.checked_sub($next_hops_fee_msat) {
595 // Routing Fragmentation Mitigation heuristic:
597 // Routing fragmentation across many payment paths increases the overall routing
598 // fees as you have irreducible routing fees per-link used (`fee_base_msat`).
599 // Taking too many smaller paths also increases the chance of payment failure.
600 // Thus to avoid this effect, we require from our collected links to provide
601 // at least a minimal contribution to the recommended value yet-to-be-fulfilled.
603 // This requirement is currently 5% of the remaining-to-be-collected value.
604 // This means as we successfully advance in our collection,
605 // the absolute liquidity contribution is lowered,
606 // thus increasing the number of potential channels to be selected.
608 // Derive the minimal liquidity contribution with a ratio of 20 (5%, rounded up)
609 // or 100% if we're not allowed to do multipath payments.
610 let minimal_value_contribution_msat: u64 = if allow_mpp {
611 (recommended_value_msat - already_collected_value_msat + 19) / 20
615 // Verify the liquidity offered by this channel complies to the minimal contribution.
616 let contributes_sufficient_value = available_value_contribution_msat >= minimal_value_contribution_msat;
618 let value_contribution_msat = cmp::min(available_value_contribution_msat, $next_hops_value_contribution);
619 // Includes paying fees for the use of the following channels.
620 let amount_to_transfer_over_msat: u64 = match value_contribution_msat.checked_add($next_hops_fee_msat) {
621 Some(result) => result,
622 // Can't overflow due to how the values were computed right above.
623 None => unreachable!(),
625 #[allow(unused_comparisons)] // $next_hops_path_htlc_minimum_msat is 0 in some calls so rustc complains
626 let over_path_minimum_msat = amount_to_transfer_over_msat >= $directional_info.htlc_minimum_msat &&
627 amount_to_transfer_over_msat >= $next_hops_path_htlc_minimum_msat;
629 // If HTLC minimum is larger than the amount we're going to transfer, we shouldn't
630 // bother considering this channel.
631 // Since we're choosing amount_to_transfer_over_msat as maximum possible, it can
632 // be only reduced later (not increased), so this channel should just be skipped
633 // as not sufficient.
634 if !over_path_minimum_msat {
635 hit_minimum_limit = true;
636 } else if contributes_sufficient_value {
637 // Note that low contribution here (limited by available_liquidity_msat)
638 // might violate htlc_minimum_msat on the hops which are next along the
639 // payment path (upstream to the payee). To avoid that, we recompute path
640 // path fees knowing the final path contribution after constructing it.
641 let path_htlc_minimum_msat = match compute_fees($next_hops_path_htlc_minimum_msat, $directional_info.fees)
642 .map(|fee_msat| fee_msat.checked_add($next_hops_path_htlc_minimum_msat)) {
643 Some(Some(value_msat)) => cmp::max(value_msat, $directional_info.htlc_minimum_msat),
644 _ => u64::max_value()
646 let hm_entry = dist.entry(&$src_node_id);
647 let old_entry = hm_entry.or_insert_with(|| {
648 // If there was previously no known way to access
649 // the source node (recall it goes payee-to-payer) of $chan_id, first add
650 // a semi-dummy record just to compute the fees to reach the source node.
651 // This will affect our decision on selecting $chan_id
652 // as a way to reach the $dest_node_id.
653 let mut fee_base_msat = u32::max_value();
654 let mut fee_proportional_millionths = u32::max_value();
655 if let Some(Some(fees)) = network_nodes.get(&$src_node_id).map(|node| node.lowest_inbound_channel_fees) {
656 fee_base_msat = fees.base_msat;
657 fee_proportional_millionths = fees.proportional_millionths;
660 pubkey: $dest_node_id.clone(),
662 channel_features: $chan_features,
664 cltv_expiry_delta: 0,
665 src_lowest_inbound_fees: RoutingFees {
666 base_msat: fee_base_msat,
667 proportional_millionths: fee_proportional_millionths,
669 channel_fees: $directional_info.fees,
670 next_hops_fee_msat: u64::max_value(),
671 hop_use_fee_msat: u64::max_value(),
672 total_fee_msat: u64::max_value(),
673 htlc_minimum_msat: $directional_info.htlc_minimum_msat,
674 path_htlc_minimum_msat,
675 was_processed: false,
676 #[cfg(any(test, feature = "fuzztarget"))]
677 value_contribution_msat,
681 #[allow(unused_mut)] // We only use the mut in cfg(test)
682 let mut should_process = !old_entry.was_processed;
683 #[cfg(any(test, feature = "fuzztarget"))]
685 // In test/fuzzing builds, we do extra checks to make sure the skipping
686 // of already-seen nodes only happens in cases we expect (see below).
687 if !should_process { should_process = true; }
691 let mut hop_use_fee_msat = 0;
692 let mut total_fee_msat = $next_hops_fee_msat;
694 // Ignore hop_use_fee_msat for channel-from-us as we assume all channels-from-us
695 // will have the same effective-fee
696 if $src_node_id != *our_node_id {
697 match compute_fees(amount_to_transfer_over_msat, $directional_info.fees) {
698 // max_value means we'll always fail
699 // the old_entry.total_fee_msat > total_fee_msat check
700 None => total_fee_msat = u64::max_value(),
702 hop_use_fee_msat = fee_msat;
703 total_fee_msat += hop_use_fee_msat;
704 // When calculating the lowest inbound fees to a node, we
705 // calculate fees here not based on the actual value we think
706 // will flow over this channel, but on the minimum value that
707 // we'll accept flowing over it. The minimum accepted value
708 // is a constant through each path collection run, ensuring
709 // consistent basis. Otherwise we may later find a
710 // different path to the source node that is more expensive,
711 // but which we consider to be cheaper because we are capacity
712 // constrained and the relative fee becomes lower.
713 match compute_fees(minimal_value_contribution_msat, old_entry.src_lowest_inbound_fees)
714 .map(|a| a.checked_add(total_fee_msat)) {
719 total_fee_msat = u64::max_value();
726 let new_graph_node = RouteGraphNode {
727 pubkey: $src_node_id,
728 lowest_fee_to_peer_through_node: total_fee_msat,
729 lowest_fee_to_node: $next_hops_fee_msat as u64 + hop_use_fee_msat,
730 value_contribution_msat: value_contribution_msat,
731 path_htlc_minimum_msat,
734 // Update the way of reaching $src_node_id with the given $chan_id (from $dest_node_id),
735 // if this way is cheaper than the already known
736 // (considering the cost to "reach" this channel from the route destination,
737 // the cost of using this channel,
738 // and the cost of routing to the source node of this channel).
739 // Also, consider that htlc_minimum_msat_difference, because we might end up
740 // paying it. Consider the following exploit:
741 // we use 2 paths to transfer 1.5 BTC. One of them is 0-fee normal 1 BTC path,
742 // and for the other one we picked a 1sat-fee path with htlc_minimum_msat of
743 // 1 BTC. Now, since the latter is more expensive, we gonna try to cut it
744 // by 0.5 BTC, but then match htlc_minimum_msat by paying a fee of 0.5 BTC
746 // Ideally the scoring could be smarter (e.g. 0.5*htlc_minimum_msat here),
747 // but it may require additional tracking - we don't want to double-count
748 // the fees included in $next_hops_path_htlc_minimum_msat, but also
749 // can't use something that may decrease on future hops.
750 let old_cost = cmp::max(old_entry.total_fee_msat, old_entry.path_htlc_minimum_msat);
751 let new_cost = cmp::max(total_fee_msat, path_htlc_minimum_msat);
753 if !old_entry.was_processed && new_cost < old_cost {
754 targets.push(new_graph_node);
755 old_entry.next_hops_fee_msat = $next_hops_fee_msat;
756 old_entry.hop_use_fee_msat = hop_use_fee_msat;
757 old_entry.total_fee_msat = total_fee_msat;
758 old_entry.pubkey = $dest_node_id.clone();
759 old_entry.short_channel_id = $chan_id.clone();
760 old_entry.channel_features = $chan_features;
761 old_entry.fee_msat = 0; // This value will be later filled with hop_use_fee_msat of the following channel
762 old_entry.cltv_expiry_delta = $directional_info.cltv_expiry_delta as u32;
763 old_entry.channel_fees = $directional_info.fees;
764 old_entry.htlc_minimum_msat = $directional_info.htlc_minimum_msat;
765 old_entry.path_htlc_minimum_msat = path_htlc_minimum_msat;
766 #[cfg(any(test, feature = "fuzztarget"))]
768 old_entry.value_contribution_msat = value_contribution_msat;
770 did_add_update_path_to_src_node = true;
771 } else if old_entry.was_processed && new_cost < old_cost {
772 #[cfg(any(test, feature = "fuzztarget"))]
774 // If we're skipping processing a node which was previously
775 // processed even though we found another path to it with a
776 // cheaper fee, check that it was because the second path we
777 // found (which we are processing now) has a lower value
778 // contribution due to an HTLC minimum limit.
780 // e.g. take a graph with two paths from node 1 to node 2, one
781 // through channel A, and one through channel B. Channel A and
782 // B are both in the to-process heap, with their scores set by
783 // a higher htlc_minimum than fee.
784 // Channel A is processed first, and the channels onwards from
785 // node 1 are added to the to-process heap. Thereafter, we pop
786 // Channel B off of the heap, note that it has a much more
787 // restrictive htlc_maximum_msat, and recalculate the fees for
788 // all of node 1's channels using the new, reduced, amount.
790 // This would be bogus - we'd be selecting a higher-fee path
791 // with a lower htlc_maximum_msat instead of the one we'd
792 // already decided to use.
793 debug_assert!(path_htlc_minimum_msat < old_entry.path_htlc_minimum_msat);
794 debug_assert!(value_contribution_msat < old_entry.value_contribution_msat);
801 did_add_update_path_to_src_node
805 let empty_node_features = NodeFeatures::empty();
806 // Find ways (channels with destination) to reach a given node and store them
807 // in the corresponding data structures (routing graph etc).
808 // $fee_to_target_msat represents how much it costs to reach to this node from the payee,
809 // meaning how much will be paid in fees after this node (to the best of our knowledge).
810 // This data can later be helpful to optimize routing (pay lower fees).
811 macro_rules! add_entries_to_cheapest_to_target_node {
812 ( $node: expr, $node_id: expr, $fee_to_target_msat: expr, $next_hops_value_contribution: expr, $next_hops_path_htlc_minimum_msat: expr ) => {
813 let skip_node = if let Some(elem) = dist.get_mut($node_id) {
814 let was_processed = elem.was_processed;
815 elem.was_processed = true;
818 // Entries are added to dist in add_entry!() when there is a channel from a node.
819 // Because there are no channels from payee, it will not have a dist entry at this point.
820 // If we're processing any other node, it is always be the result of a channel from it.
821 assert_eq!($node_id, payee);
826 if first_hops.is_some() {
827 if let Some(&(ref first_hop, ref features, ref outbound_capacity_msat, _)) = first_hop_targets.get(&$node_id) {
828 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);
832 let features = if let Some(node_info) = $node.announcement_info.as_ref() {
838 if !features.requires_unknown_bits() {
839 for chan_id in $node.channels.iter() {
840 let chan = network_channels.get(chan_id).unwrap();
841 if !chan.features.requires_unknown_bits() {
842 if chan.node_one == *$node_id {
843 // ie $node is one, ie next hop in A* is two, via the two_to_one channel
844 if first_hops.is_none() || chan.node_two != *our_node_id {
845 if let Some(two_to_one) = chan.two_to_one.as_ref() {
846 if two_to_one.enabled {
847 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);
852 if first_hops.is_none() || chan.node_one != *our_node_id {
853 if let Some(one_to_two) = chan.one_to_two.as_ref() {
854 if one_to_two.enabled {
855 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);
867 let mut payment_paths = Vec::<PaymentPath>::new();
869 // TODO: diversify by nodes (so that all paths aren't doomed if one node is offline).
870 'paths_collection: loop {
871 // For every new path, start from scratch, except
872 // bookkeeped_channels_liquidity_available_msat, which will improve
873 // the further iterations of path finding. Also don't erase first_hop_targets.
876 hit_minimum_limit = false;
878 // If first hop is a private channel and the only way to reach the payee, this is the only
879 // place where it could be added.
880 if first_hops.is_some() {
881 if let Some(&(ref first_hop, ref features, ref outbound_capacity_msat, _)) = first_hop_targets.get(&payee) {
882 add_entry!(first_hop, *our_node_id, payee, dummy_directional_info, Some(outbound_capacity_msat / 1000), features, 0, path_value_msat, 0);
886 // Add the payee as a target, so that the payee-to-payer
887 // search algorithm knows what to start with.
888 match network_nodes.get(payee) {
889 // The payee is not in our network graph, so nothing to add here.
890 // There is still a chance of reaching them via last_hops though,
891 // so don't yet fail the payment here.
892 // If not, targets.pop() will not even let us enter the loop in step 2.
895 add_entries_to_cheapest_to_target_node!(node, payee, 0, path_value_msat, 0);
900 // If a caller provided us with last hops, add them to routing targets. Since this happens
901 // earlier than general path finding, they will be somewhat prioritized, although currently
902 // it matters only if the fees are exactly the same.
903 for route in last_hops.iter().filter(|route| !route.0.is_empty()) {
904 let first_hop_in_route = &(route.0)[0];
905 let have_hop_src_in_graph =
906 // Only add the hops in this route to our candidate set if either
907 // we have a direct channel to the first hop or the first hop is
908 // in the regular network graph.
909 first_hop_targets.get(&first_hop_in_route.src_node_id).is_some() ||
910 network_nodes.get(&first_hop_in_route.src_node_id).is_some();
911 if have_hop_src_in_graph {
912 // We start building the path from reverse, i.e., from payee
913 // to the first RouteHintHop in the path.
914 let hop_iter = route.0.iter().rev();
915 let prev_hop_iter = core::iter::once(payee).chain(
916 route.0.iter().skip(1).rev().map(|hop| &hop.src_node_id));
917 let mut hop_used = true;
918 let mut aggregate_next_hops_fee_msat: u64 = 0;
919 let mut aggregate_next_hops_path_htlc_minimum_msat: u64 = 0;
921 for (idx, (hop, prev_hop_id)) in hop_iter.zip(prev_hop_iter).enumerate() {
922 // BOLT 11 doesn't allow inclusion of features for the last hop hints, which
923 // really sucks, cause we're gonna need that eventually.
924 let hop_htlc_minimum_msat: u64 = hop.htlc_minimum_msat.unwrap_or(0);
926 let directional_info = DummyDirectionalChannelInfo {
927 cltv_expiry_delta: hop.cltv_expiry_delta as u32,
928 htlc_minimum_msat: hop_htlc_minimum_msat,
929 htlc_maximum_msat: hop.htlc_maximum_msat,
933 let reqd_channel_cap = if let Some (val) = final_value_msat.checked_add(match idx {
935 _ => aggregate_next_hops_fee_msat.checked_add(999).unwrap_or(u64::max_value())
936 }) { Some( val / 1000 ) } else { break; }; // converting from msat or breaking if max ~ infinity
939 // We assume that the recipient only included route hints for routes which had
940 // sufficient value to route `final_value_msat`. Note that in the case of "0-value"
941 // invoices where the invoice does not specify value this may not be the case, but
942 // better to include the hints than not.
943 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) {
944 // If this hop was not used then there is no use checking the preceding hops
945 // in the RouteHint. We can break by just searching for a direct channel between
946 // last checked hop and first_hop_targets
950 // Searching for a direct channel between last checked hop and first_hop_targets
951 if let Some(&(ref first_hop, ref features, ref outbound_capacity_msat, _)) = first_hop_targets.get(&prev_hop_id) {
952 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);
959 // In the next values of the iterator, the aggregate fees already reflects
960 // the sum of value sent from payer (final_value_msat) and routing fees
961 // for the last node in the RouteHint. We need to just add the fees to
962 // route through the current node so that the preceeding node (next iteration)
964 let hops_fee = compute_fees(aggregate_next_hops_fee_msat + final_value_msat, hop.fees)
965 .map_or(None, |inc| inc.checked_add(aggregate_next_hops_fee_msat));
966 aggregate_next_hops_fee_msat = if let Some(val) = hops_fee { val } else { break; };
968 let hop_htlc_minimum_msat_inc = if let Some(val) = compute_fees(aggregate_next_hops_path_htlc_minimum_msat, hop.fees) { val } else { break; };
969 let hops_path_htlc_minimum = aggregate_next_hops_path_htlc_minimum_msat
970 .checked_add(hop_htlc_minimum_msat_inc);
971 aggregate_next_hops_path_htlc_minimum_msat = if let Some(val) = hops_path_htlc_minimum { cmp::max(hop_htlc_minimum_msat, val) } else { break; };
973 if idx == route.0.len() - 1 {
974 // The last hop in this iterator is the first hop in
975 // overall RouteHint.
976 // If this hop connects to a node with which we have a direct channel,
977 // ignore the network graph and, if the last hop was added, add our
978 // direct channel to the candidate set.
980 // Note that we *must* check if the last hop was added as `add_entry`
981 // always assumes that the third argument is a node to which we have a
983 if let Some(&(ref first_hop, ref features, ref outbound_capacity_msat, _)) = first_hop_targets.get(&hop.src_node_id) {
984 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);
991 log_trace!(logger, "Starting main path collection loop with {} nodes pre-filled from first/last hops.", targets.len());
993 // At this point, targets are filled with the data from first and
994 // last hops communicated by the caller, and the payment receiver.
995 let mut found_new_path = false;
998 // If this loop terminates due the exhaustion of targets, two situations are possible:
999 // - not enough outgoing liquidity:
1000 // 0 < already_collected_value_msat < final_value_msat
1001 // - enough outgoing liquidity:
1002 // final_value_msat <= already_collected_value_msat < recommended_value_msat
1003 // Both these cases (and other cases except reaching recommended_value_msat) mean that
1004 // paths_collection will be stopped because found_new_path==false.
1005 // This is not necessarily a routing failure.
1006 'path_construction: while let Some(RouteGraphNode { pubkey, lowest_fee_to_node, value_contribution_msat, path_htlc_minimum_msat, .. }) = targets.pop() {
1008 // Since we're going payee-to-payer, hitting our node as a target means we should stop
1009 // traversing the graph and arrange the path out of what we found.
1010 if pubkey == *our_node_id {
1011 let mut new_entry = dist.remove(&our_node_id).unwrap();
1012 let mut ordered_hops = vec!((new_entry.clone(), NodeFeatures::empty()));
1015 if let Some(&(_, _, _, ref features)) = first_hop_targets.get(&ordered_hops.last().unwrap().0.pubkey) {
1016 ordered_hops.last_mut().unwrap().1 = features.clone();
1017 } else if let Some(node) = network_nodes.get(&ordered_hops.last().unwrap().0.pubkey) {
1018 if let Some(node_info) = node.announcement_info.as_ref() {
1019 ordered_hops.last_mut().unwrap().1 = node_info.features.clone();
1021 ordered_hops.last_mut().unwrap().1 = NodeFeatures::empty();
1024 // We should be able to fill in features for everything except the last
1025 // hop, if the last hop was provided via a BOLT 11 invoice (though we
1026 // should be able to extend it further as BOLT 11 does have feature
1027 // flags for the last hop node itself).
1028 assert!(ordered_hops.last().unwrap().0.pubkey == *payee);
1031 // Means we succesfully traversed from the payer to the payee, now
1032 // save this path for the payment route. Also, update the liquidity
1033 // remaining on the used hops, so that we take them into account
1034 // while looking for more paths.
1035 if ordered_hops.last().unwrap().0.pubkey == *payee {
1039 new_entry = match dist.remove(&ordered_hops.last().unwrap().0.pubkey) {
1040 Some(payment_hop) => payment_hop,
1041 // We can't arrive at None because, if we ever add an entry to targets,
1042 // we also fill in the entry in dist (see add_entry!).
1043 None => unreachable!(),
1045 // We "propagate" the fees one hop backward (topologically) here,
1046 // so that fees paid for a HTLC forwarding on the current channel are
1047 // associated with the previous channel (where they will be subtracted).
1048 ordered_hops.last_mut().unwrap().0.fee_msat = new_entry.hop_use_fee_msat;
1049 ordered_hops.last_mut().unwrap().0.cltv_expiry_delta = new_entry.cltv_expiry_delta;
1050 ordered_hops.push((new_entry.clone(), NodeFeatures::empty()));
1052 ordered_hops.last_mut().unwrap().0.fee_msat = value_contribution_msat;
1053 ordered_hops.last_mut().unwrap().0.hop_use_fee_msat = 0;
1054 ordered_hops.last_mut().unwrap().0.cltv_expiry_delta = final_cltv;
1056 log_trace!(logger, "Found a path back to us from the target with {} hops contributing up to {} msat: {:?}",
1057 ordered_hops.len(), value_contribution_msat, ordered_hops);
1059 let mut payment_path = PaymentPath {hops: ordered_hops};
1061 // We could have possibly constructed a slightly inconsistent path: since we reduce
1062 // value being transferred along the way, we could have violated htlc_minimum_msat
1063 // on some channels we already passed (assuming dest->source direction). Here, we
1064 // recompute the fees again, so that if that's the case, we match the currently
1065 // underpaid htlc_minimum_msat with fees.
1066 payment_path.update_value_and_recompute_fees(cmp::min(value_contribution_msat, final_value_msat));
1068 // Since a path allows to transfer as much value as
1069 // the smallest channel it has ("bottleneck"), we should recompute
1070 // the fees so sender HTLC don't overpay fees when traversing
1071 // larger channels than the bottleneck. This may happen because
1072 // when we were selecting those channels we were not aware how much value
1073 // this path will transfer, and the relative fee for them
1074 // might have been computed considering a larger value.
1075 // Remember that we used these channels so that we don't rely
1076 // on the same liquidity in future paths.
1077 let mut prevented_redundant_path_selection = false;
1078 for (payment_hop, _) in payment_path.hops.iter() {
1079 let channel_liquidity_available_msat = bookkeeped_channels_liquidity_available_msat.get_mut(&payment_hop.short_channel_id).unwrap();
1080 let mut spent_on_hop_msat = value_contribution_msat;
1081 let next_hops_fee_msat = payment_hop.next_hops_fee_msat;
1082 spent_on_hop_msat += next_hops_fee_msat;
1083 if spent_on_hop_msat == *channel_liquidity_available_msat {
1084 // If this path used all of this channel's available liquidity, we know
1085 // this path will not be selected again in the next loop iteration.
1086 prevented_redundant_path_selection = true;
1088 *channel_liquidity_available_msat -= spent_on_hop_msat;
1090 if !prevented_redundant_path_selection {
1091 // If we weren't capped by hitting a liquidity limit on a channel in the path,
1092 // we'll probably end up picking the same path again on the next iteration.
1093 // Decrease the available liquidity of a hop in the middle of the path.
1094 let victim_scid = payment_path.hops[(payment_path.hops.len() - 1) / 2].0.short_channel_id;
1095 log_trace!(logger, "Disabling channel {} for future path building iterations to avoid duplicates.", victim_scid);
1096 let victim_liquidity = bookkeeped_channels_liquidity_available_msat.get_mut(&victim_scid).unwrap();
1097 *victim_liquidity = 0;
1100 // Track the total amount all our collected paths allow to send so that we:
1101 // - know when to stop looking for more paths
1102 // - know which of the hops are useless considering how much more sats we need
1103 // (contributes_sufficient_value)
1104 already_collected_value_msat += value_contribution_msat;
1106 payment_paths.push(payment_path);
1107 found_new_path = true;
1108 break 'path_construction;
1111 // If we found a path back to the payee, we shouldn't try to process it again. This is
1112 // the equivalent of the `elem.was_processed` check in
1113 // add_entries_to_cheapest_to_target_node!() (see comment there for more info).
1114 if pubkey == *payee { continue 'path_construction; }
1116 // Otherwise, since the current target node is not us,
1117 // keep "unrolling" the payment graph from payee to payer by
1118 // finding a way to reach the current target from the payer side.
1119 match network_nodes.get(&pubkey) {
1122 add_entries_to_cheapest_to_target_node!(node, &pubkey, lowest_fee_to_node, value_contribution_msat, path_htlc_minimum_msat);
1128 // If we don't support MPP, no use trying to gather more value ever.
1129 break 'paths_collection;
1133 // Stop either when the recommended value is reached or if no new path was found in this
1135 // In the latter case, making another path finding attempt won't help,
1136 // because we deterministically terminated the search due to low liquidity.
1137 if already_collected_value_msat >= recommended_value_msat || !found_new_path {
1138 log_trace!(logger, "Have now collected {} msat (seeking {} msat) in paths. Last path loop {} a new path.",
1139 already_collected_value_msat, recommended_value_msat, if found_new_path { "found" } else { "did not find" });
1140 break 'paths_collection;
1141 } else if found_new_path && already_collected_value_msat == final_value_msat && payment_paths.len() == 1 {
1142 // Further, if this was our first walk of the graph, and we weren't limited by an
1143 // htlc_minimum_msat, return immediately because this path should suffice. If we were
1144 // limited by an htlc_minimum_msat value, find another path with a higher value,
1145 // potentially allowing us to pay fees to meet the htlc_minimum on the new path while
1146 // still keeping a lower total fee than this path.
1147 if !hit_minimum_limit {
1148 log_trace!(logger, "Collected exactly our payment amount on the first pass, without hitting an htlc_minimum_msat limit, exiting.");
1149 break 'paths_collection;
1151 log_trace!(logger, "Collected our payment amount on the first pass, but running again to collect extra paths with a potentially higher limit.");
1152 path_value_msat = recommended_value_msat;
1157 if payment_paths.len() == 0 {
1158 return Err(LightningError{err: "Failed to find a path to the given destination".to_owned(), action: ErrorAction::IgnoreError});
1161 if already_collected_value_msat < final_value_msat {
1162 return Err(LightningError{err: "Failed to find a sufficient route to the given destination".to_owned(), action: ErrorAction::IgnoreError});
1165 // Sort by total fees and take the best paths.
1166 payment_paths.sort_by_key(|path| path.get_total_fee_paid_msat());
1167 if payment_paths.len() > 50 {
1168 payment_paths.truncate(50);
1171 // Draw multiple sufficient routes by randomly combining the selected paths.
1172 let mut drawn_routes = Vec::new();
1173 for i in 0..payment_paths.len() {
1174 let mut cur_route = Vec::<PaymentPath>::new();
1175 let mut aggregate_route_value_msat = 0;
1178 // TODO: real random shuffle
1179 // Currently just starts with i_th and goes up to i-1_th in a looped way.
1180 let cur_payment_paths = [&payment_paths[i..], &payment_paths[..i]].concat();
1183 for payment_path in cur_payment_paths {
1184 cur_route.push(payment_path.clone());
1185 aggregate_route_value_msat += payment_path.get_value_msat();
1186 if aggregate_route_value_msat > final_value_msat {
1187 // Last path likely overpaid. Substract it from the most expensive
1188 // (in terms of proportional fee) path in this route and recompute fees.
1189 // This might be not the most economically efficient way, but fewer paths
1190 // also makes routing more reliable.
1191 let mut overpaid_value_msat = aggregate_route_value_msat - final_value_msat;
1193 // First, drop some expensive low-value paths entirely if possible.
1194 // Sort by value so that we drop many really-low values first, since
1195 // fewer paths is better: the payment is less likely to fail.
1196 // TODO: this could also be optimized by also sorting by feerate_per_sat_routed,
1197 // so that the sender pays less fees overall. And also htlc_minimum_msat.
1198 cur_route.sort_by_key(|path| path.get_value_msat());
1199 // We should make sure that at least 1 path left.
1200 let mut paths_left = cur_route.len();
1201 cur_route.retain(|path| {
1202 if paths_left == 1 {
1205 let mut keep = true;
1206 let path_value_msat = path.get_value_msat();
1207 if path_value_msat <= overpaid_value_msat {
1209 overpaid_value_msat -= path_value_msat;
1215 if overpaid_value_msat == 0 {
1219 assert!(cur_route.len() > 0);
1222 // Now, substract the overpaid value from the most-expensive path.
1223 // TODO: this could also be optimized by also sorting by feerate_per_sat_routed,
1224 // so that the sender pays less fees overall. And also htlc_minimum_msat.
1225 cur_route.sort_by_key(|path| { path.hops.iter().map(|hop| hop.0.channel_fees.proportional_millionths as u64).sum::<u64>() });
1226 let expensive_payment_path = cur_route.first_mut().unwrap();
1227 // We already dropped all the small channels above, meaning all the
1228 // remaining channels are larger than remaining overpaid_value_msat.
1229 // Thus, this can't be negative.
1230 let expensive_path_new_value_msat = expensive_payment_path.get_value_msat() - overpaid_value_msat;
1231 expensive_payment_path.update_value_and_recompute_fees(expensive_path_new_value_msat);
1235 drawn_routes.push(cur_route);
1239 // Select the best route by lowest total fee.
1240 drawn_routes.sort_by_key(|paths| paths.iter().map(|path| path.get_total_fee_paid_msat()).sum::<u64>());
1241 let mut selected_paths = Vec::<Vec<RouteHop>>::new();
1242 for payment_path in drawn_routes.first().unwrap() {
1243 selected_paths.push(payment_path.hops.iter().map(|(payment_hop, node_features)| {
1245 pubkey: payment_hop.pubkey,
1246 node_features: node_features.clone(),
1247 short_channel_id: payment_hop.short_channel_id,
1248 channel_features: payment_hop.channel_features.clone(),
1249 fee_msat: payment_hop.fee_msat,
1250 cltv_expiry_delta: payment_hop.cltv_expiry_delta,
1255 if let Some(features) = &payee_features {
1256 for path in selected_paths.iter_mut() {
1257 path.last_mut().unwrap().node_features = features.to_context();
1261 let route = Route { paths: selected_paths };
1262 log_info!(logger, "Got route to {}: {}", payee, log_route!(route));
1268 use routing::router::{get_route, Route, RouteHint, RouteHintHop, RouteHop, RoutingFees};
1269 use routing::network_graph::{NetworkGraph, NetGraphMsgHandler};
1270 use chain::transaction::OutPoint;
1271 use ln::features::{ChannelFeatures, InitFeatures, InvoiceFeatures, NodeFeatures};
1272 use ln::msgs::{ErrorAction, LightningError, OptionalField, UnsignedChannelAnnouncement, ChannelAnnouncement, RoutingMessageHandler,
1273 NodeAnnouncement, UnsignedNodeAnnouncement, ChannelUpdate, UnsignedChannelUpdate};
1274 use ln::channelmanager;
1275 use util::test_utils;
1276 use util::ser::Writeable;
1278 use bitcoin::hashes::sha256d::Hash as Sha256dHash;
1279 use bitcoin::hashes::Hash;
1280 use bitcoin::network::constants::Network;
1281 use bitcoin::blockdata::constants::genesis_block;
1282 use bitcoin::blockdata::script::Builder;
1283 use bitcoin::blockdata::opcodes;
1284 use bitcoin::blockdata::transaction::TxOut;
1288 use bitcoin::secp256k1::key::{PublicKey,SecretKey};
1289 use bitcoin::secp256k1::{Secp256k1, All};
1292 use sync::{self, Arc};
1294 fn get_channel_details(short_channel_id: Option<u64>, node_id: PublicKey,
1295 features: InitFeatures, outbound_capacity_msat: u64) -> channelmanager::ChannelDetails {
1296 channelmanager::ChannelDetails {
1297 channel_id: [0; 32],
1298 counterparty: channelmanager::ChannelCounterparty {
1301 unspendable_punishment_reserve: 0,
1302 forwarding_info: None,
1304 funding_txo: Some(OutPoint { txid: bitcoin::Txid::from_slice(&[0; 32]).unwrap(), index: 0 }),
1306 channel_value_satoshis: 0,
1308 outbound_capacity_msat,
1309 inbound_capacity_msat: 42,
1310 unspendable_punishment_reserve: None,
1311 confirmations_required: None,
1312 force_close_spend_delay: None,
1313 is_outbound: true, is_funding_locked: true,
1314 is_usable: true, is_public: true,
1318 // Using the same keys for LN and BTC ids
1320 net_graph_msg_handler: &NetGraphMsgHandler<Arc<test_utils::TestChainSource>, Arc<test_utils::TestLogger>>,
1321 secp_ctx: &Secp256k1<All>, node_1_privkey: &SecretKey, node_2_privkey: &SecretKey, features: ChannelFeatures, short_channel_id: u64
1323 let node_id_1 = PublicKey::from_secret_key(&secp_ctx, node_1_privkey);
1324 let node_id_2 = PublicKey::from_secret_key(&secp_ctx, node_2_privkey);
1326 let unsigned_announcement = UnsignedChannelAnnouncement {
1328 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1332 bitcoin_key_1: node_id_1,
1333 bitcoin_key_2: node_id_2,
1334 excess_data: Vec::new(),
1337 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1338 let valid_announcement = ChannelAnnouncement {
1339 node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
1340 node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
1341 bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
1342 bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
1343 contents: unsigned_announcement.clone(),
1345 match net_graph_msg_handler.handle_channel_announcement(&valid_announcement) {
1346 Ok(res) => assert!(res),
1352 net_graph_msg_handler: &NetGraphMsgHandler<Arc<test_utils::TestChainSource>, Arc<test_utils::TestLogger>>,
1353 secp_ctx: &Secp256k1<All>, node_privkey: &SecretKey, update: UnsignedChannelUpdate
1355 let msghash = hash_to_message!(&Sha256dHash::hash(&update.encode()[..])[..]);
1356 let valid_channel_update = ChannelUpdate {
1357 signature: secp_ctx.sign(&msghash, node_privkey),
1358 contents: update.clone()
1361 match net_graph_msg_handler.handle_channel_update(&valid_channel_update) {
1362 Ok(res) => assert!(res),
1367 fn add_or_update_node(
1368 net_graph_msg_handler: &NetGraphMsgHandler<Arc<test_utils::TestChainSource>, Arc<test_utils::TestLogger>>,
1369 secp_ctx: &Secp256k1<All>, node_privkey: &SecretKey, features: NodeFeatures, timestamp: u32
1371 let node_id = PublicKey::from_secret_key(&secp_ctx, node_privkey);
1372 let unsigned_announcement = UnsignedNodeAnnouncement {
1378 addresses: Vec::new(),
1379 excess_address_data: Vec::new(),
1380 excess_data: Vec::new(),
1382 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1383 let valid_announcement = NodeAnnouncement {
1384 signature: secp_ctx.sign(&msghash, node_privkey),
1385 contents: unsigned_announcement.clone()
1388 match net_graph_msg_handler.handle_node_announcement(&valid_announcement) {
1394 fn get_nodes(secp_ctx: &Secp256k1<All>) -> (SecretKey, PublicKey, Vec<SecretKey>, Vec<PublicKey>) {
1395 let privkeys: Vec<SecretKey> = (2..10).map(|i| {
1396 SecretKey::from_slice(&hex::decode(format!("{:02}", i).repeat(32)).unwrap()[..]).unwrap()
1399 let pubkeys = privkeys.iter().map(|secret| PublicKey::from_secret_key(&secp_ctx, secret)).collect();
1401 let our_privkey = SecretKey::from_slice(&hex::decode("01".repeat(32)).unwrap()[..]).unwrap();
1402 let our_id = PublicKey::from_secret_key(&secp_ctx, &our_privkey);
1404 (our_privkey, our_id, privkeys, pubkeys)
1407 fn id_to_feature_flags(id: u8) -> Vec<u8> {
1408 // Set the feature flags to the id'th odd (ie non-required) feature bit so that we can
1409 // test for it later.
1410 let idx = (id - 1) * 2 + 1;
1412 vec![1 << (idx - 8*3), 0, 0, 0]
1413 } else if idx > 8*2 {
1414 vec![1 << (idx - 8*2), 0, 0]
1415 } else if idx > 8*1 {
1416 vec![1 << (idx - 8*1), 0]
1422 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>) {
1423 let secp_ctx = Secp256k1::new();
1424 let logger = Arc::new(test_utils::TestLogger::new());
1425 let chain_monitor = Arc::new(test_utils::TestChainSource::new(Network::Testnet));
1426 let network_graph = NetworkGraph::new(genesis_block(Network::Testnet).header.block_hash());
1427 let net_graph_msg_handler = NetGraphMsgHandler::new(network_graph, None, Arc::clone(&logger));
1428 // Build network from our_id to node6:
1430 // -1(1)2- node0 -1(3)2-
1432 // our_id -1(12)2- node7 -1(13)2--- node2
1434 // -1(2)2- node1 -1(4)2-
1437 // chan1 1-to-2: disabled
1438 // chan1 2-to-1: enabled, 0 fee
1440 // chan2 1-to-2: enabled, ignored fee
1441 // chan2 2-to-1: enabled, 0 fee
1443 // chan3 1-to-2: enabled, 0 fee
1444 // chan3 2-to-1: enabled, 100 msat fee
1446 // chan4 1-to-2: enabled, 100% fee
1447 // chan4 2-to-1: enabled, 0 fee
1449 // chan12 1-to-2: enabled, ignored fee
1450 // chan12 2-to-1: enabled, 0 fee
1452 // chan13 1-to-2: enabled, 200% fee
1453 // chan13 2-to-1: enabled, 0 fee
1456 // -1(5)2- node3 -1(8)2--
1460 // node2--1(6)2- node4 -1(9)2--- node6 (not in global route map)
1462 // -1(7)2- node5 -1(10)2-
1464 // Channels 5, 8, 9 and 10 are private channels.
1466 // chan5 1-to-2: enabled, 100 msat fee
1467 // chan5 2-to-1: enabled, 0 fee
1469 // chan6 1-to-2: enabled, 0 fee
1470 // chan6 2-to-1: enabled, 0 fee
1472 // chan7 1-to-2: enabled, 100% fee
1473 // chan7 2-to-1: enabled, 0 fee
1475 // chan8 1-to-2: enabled, variable fee (0 then 1000 msat)
1476 // chan8 2-to-1: enabled, 0 fee
1478 // chan9 1-to-2: enabled, 1001 msat fee
1479 // chan9 2-to-1: enabled, 0 fee
1481 // chan10 1-to-2: enabled, 0 fee
1482 // chan10 2-to-1: enabled, 0 fee
1484 // chan11 1-to-2: enabled, 0 fee
1485 // chan11 2-to-1: enabled, 0 fee
1487 let (our_privkey, _, privkeys, _) = get_nodes(&secp_ctx);
1489 add_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, &privkeys[0], ChannelFeatures::from_le_bytes(id_to_feature_flags(1)), 1);
1490 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
1491 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1492 short_channel_id: 1,
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[0], NodeFeatures::from_le_bytes(id_to_feature_flags(1)), 0);
1505 add_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, &privkeys[1], ChannelFeatures::from_le_bytes(id_to_feature_flags(2)), 2);
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: 2,
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[1], UnsignedChannelUpdate {
1519 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1520 short_channel_id: 2,
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[1], NodeFeatures::from_le_bytes(id_to_feature_flags(2)), 0);
1533 add_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, &privkeys[7], ChannelFeatures::from_le_bytes(id_to_feature_flags(12)), 12);
1534 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
1535 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1536 short_channel_id: 12,
1539 cltv_expiry_delta: u16::max_value(),
1540 htlc_minimum_msat: 0,
1541 htlc_maximum_msat: OptionalField::Absent,
1542 fee_base_msat: u32::max_value(),
1543 fee_proportional_millionths: u32::max_value(),
1544 excess_data: Vec::new()
1546 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
1547 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1548 short_channel_id: 12,
1551 cltv_expiry_delta: 0,
1552 htlc_minimum_msat: 0,
1553 htlc_maximum_msat: OptionalField::Absent,
1555 fee_proportional_millionths: 0,
1556 excess_data: Vec::new()
1559 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[7], NodeFeatures::from_le_bytes(id_to_feature_flags(8)), 0);
1561 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], &privkeys[2], ChannelFeatures::from_le_bytes(id_to_feature_flags(3)), 3);
1562 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
1563 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1564 short_channel_id: 3,
1567 cltv_expiry_delta: (3 << 8) | 1,
1568 htlc_minimum_msat: 0,
1569 htlc_maximum_msat: OptionalField::Absent,
1571 fee_proportional_millionths: 0,
1572 excess_data: Vec::new()
1574 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
1575 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1576 short_channel_id: 3,
1579 cltv_expiry_delta: (3 << 8) | 2,
1580 htlc_minimum_msat: 0,
1581 htlc_maximum_msat: OptionalField::Absent,
1583 fee_proportional_millionths: 0,
1584 excess_data: Vec::new()
1587 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], &privkeys[2], ChannelFeatures::from_le_bytes(id_to_feature_flags(4)), 4);
1588 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
1589 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1590 short_channel_id: 4,
1593 cltv_expiry_delta: (4 << 8) | 1,
1594 htlc_minimum_msat: 0,
1595 htlc_maximum_msat: OptionalField::Absent,
1597 fee_proportional_millionths: 1000000,
1598 excess_data: Vec::new()
1600 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
1601 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1602 short_channel_id: 4,
1605 cltv_expiry_delta: (4 << 8) | 2,
1606 htlc_minimum_msat: 0,
1607 htlc_maximum_msat: OptionalField::Absent,
1609 fee_proportional_millionths: 0,
1610 excess_data: Vec::new()
1613 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], &privkeys[2], ChannelFeatures::from_le_bytes(id_to_feature_flags(13)), 13);
1614 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
1615 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1616 short_channel_id: 13,
1619 cltv_expiry_delta: (13 << 8) | 1,
1620 htlc_minimum_msat: 0,
1621 htlc_maximum_msat: OptionalField::Absent,
1623 fee_proportional_millionths: 2000000,
1624 excess_data: Vec::new()
1626 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
1627 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1628 short_channel_id: 13,
1631 cltv_expiry_delta: (13 << 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_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[2], NodeFeatures::from_le_bytes(id_to_feature_flags(3)), 0);
1641 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], &privkeys[4], ChannelFeatures::from_le_bytes(id_to_feature_flags(6)), 6);
1642 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
1643 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1644 short_channel_id: 6,
1647 cltv_expiry_delta: (6 << 8) | 1,
1648 htlc_minimum_msat: 0,
1649 htlc_maximum_msat: OptionalField::Absent,
1651 fee_proportional_millionths: 0,
1652 excess_data: Vec::new()
1654 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
1655 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1656 short_channel_id: 6,
1659 cltv_expiry_delta: (6 << 8) | 2,
1660 htlc_minimum_msat: 0,
1661 htlc_maximum_msat: OptionalField::Absent,
1663 fee_proportional_millionths: 0,
1664 excess_data: Vec::new(),
1667 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(11)), 11);
1668 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
1669 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1670 short_channel_id: 11,
1673 cltv_expiry_delta: (11 << 8) | 1,
1674 htlc_minimum_msat: 0,
1675 htlc_maximum_msat: OptionalField::Absent,
1677 fee_proportional_millionths: 0,
1678 excess_data: Vec::new()
1680 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[3], UnsignedChannelUpdate {
1681 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1682 short_channel_id: 11,
1685 cltv_expiry_delta: (11 << 8) | 2,
1686 htlc_minimum_msat: 0,
1687 htlc_maximum_msat: OptionalField::Absent,
1689 fee_proportional_millionths: 0,
1690 excess_data: Vec::new()
1693 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[4], NodeFeatures::from_le_bytes(id_to_feature_flags(5)), 0);
1695 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[3], NodeFeatures::from_le_bytes(id_to_feature_flags(4)), 0);
1697 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], &privkeys[5], ChannelFeatures::from_le_bytes(id_to_feature_flags(7)), 7);
1698 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
1699 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1700 short_channel_id: 7,
1703 cltv_expiry_delta: (7 << 8) | 1,
1704 htlc_minimum_msat: 0,
1705 htlc_maximum_msat: OptionalField::Absent,
1707 fee_proportional_millionths: 1000000,
1708 excess_data: Vec::new()
1710 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[5], UnsignedChannelUpdate {
1711 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1712 short_channel_id: 7,
1715 cltv_expiry_delta: (7 << 8) | 2,
1716 htlc_minimum_msat: 0,
1717 htlc_maximum_msat: OptionalField::Absent,
1719 fee_proportional_millionths: 0,
1720 excess_data: Vec::new()
1723 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[5], NodeFeatures::from_le_bytes(id_to_feature_flags(6)), 0);
1725 (secp_ctx, net_graph_msg_handler, chain_monitor, logger)
1729 fn simple_route_test() {
1730 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
1731 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
1733 // Simple route to 2 via 1
1735 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)) {
1736 assert_eq!(err, "Cannot send a payment of 0 msat");
1737 } else { panic!(); }
1739 let route = get_route(&our_id, &net_graph_msg_handler.network_graph, &nodes[2], None, None, &Vec::new(), 100, 42, Arc::clone(&logger)).unwrap();
1740 assert_eq!(route.paths[0].len(), 2);
1742 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
1743 assert_eq!(route.paths[0][0].short_channel_id, 2);
1744 assert_eq!(route.paths[0][0].fee_msat, 100);
1745 assert_eq!(route.paths[0][0].cltv_expiry_delta, (4 << 8) | 1);
1746 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
1747 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
1749 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
1750 assert_eq!(route.paths[0][1].short_channel_id, 4);
1751 assert_eq!(route.paths[0][1].fee_msat, 100);
1752 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
1753 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
1754 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
1758 fn invalid_first_hop_test() {
1759 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
1760 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
1762 // Simple route to 2 via 1
1764 let our_chans = vec![get_channel_details(Some(2), our_id, InitFeatures::from_le_bytes(vec![0b11]), 100000)];
1766 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)) {
1767 assert_eq!(err, "First hop cannot have our_node_id as a destination.");
1768 } else { panic!(); }
1770 let route = get_route(&our_id, &net_graph_msg_handler.network_graph, &nodes[2], None, None, &Vec::new(), 100, 42, Arc::clone(&logger)).unwrap();
1771 assert_eq!(route.paths[0].len(), 2);
1775 fn htlc_minimum_test() {
1776 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
1777 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
1779 // Simple route to 2 via 1
1781 // Disable other paths
1782 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
1783 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1784 short_channel_id: 12,
1786 flags: 2, // to disable
1787 cltv_expiry_delta: 0,
1788 htlc_minimum_msat: 0,
1789 htlc_maximum_msat: OptionalField::Absent,
1791 fee_proportional_millionths: 0,
1792 excess_data: Vec::new()
1794 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
1795 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1796 short_channel_id: 3,
1798 flags: 2, // to disable
1799 cltv_expiry_delta: 0,
1800 htlc_minimum_msat: 0,
1801 htlc_maximum_msat: OptionalField::Absent,
1803 fee_proportional_millionths: 0,
1804 excess_data: Vec::new()
1806 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
1807 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1808 short_channel_id: 13,
1810 flags: 2, // to disable
1811 cltv_expiry_delta: 0,
1812 htlc_minimum_msat: 0,
1813 htlc_maximum_msat: OptionalField::Absent,
1815 fee_proportional_millionths: 0,
1816 excess_data: Vec::new()
1818 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
1819 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1820 short_channel_id: 6,
1822 flags: 2, // to disable
1823 cltv_expiry_delta: 0,
1824 htlc_minimum_msat: 0,
1825 htlc_maximum_msat: OptionalField::Absent,
1827 fee_proportional_millionths: 0,
1828 excess_data: Vec::new()
1830 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
1831 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1832 short_channel_id: 7,
1834 flags: 2, // to disable
1835 cltv_expiry_delta: 0,
1836 htlc_minimum_msat: 0,
1837 htlc_maximum_msat: OptionalField::Absent,
1839 fee_proportional_millionths: 0,
1840 excess_data: Vec::new()
1843 // Check against amount_to_transfer_over_msat.
1844 // Set minimal HTLC of 200_000_000 msat.
1845 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
1846 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1847 short_channel_id: 2,
1850 cltv_expiry_delta: 0,
1851 htlc_minimum_msat: 200_000_000,
1852 htlc_maximum_msat: OptionalField::Absent,
1854 fee_proportional_millionths: 0,
1855 excess_data: Vec::new()
1858 // Second hop only allows to forward 199_999_999 at most, thus not allowing the first hop to
1860 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
1861 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1862 short_channel_id: 4,
1865 cltv_expiry_delta: 0,
1866 htlc_minimum_msat: 0,
1867 htlc_maximum_msat: OptionalField::Present(199_999_999),
1869 fee_proportional_millionths: 0,
1870 excess_data: Vec::new()
1873 // Not possible to send 199_999_999, because the minimum on channel=2 is 200_000_000.
1874 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)) {
1875 assert_eq!(err, "Failed to find a path to the given destination");
1876 } else { panic!(); }
1878 // Lift the restriction on the first hop.
1879 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
1880 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1881 short_channel_id: 2,
1884 cltv_expiry_delta: 0,
1885 htlc_minimum_msat: 0,
1886 htlc_maximum_msat: OptionalField::Absent,
1888 fee_proportional_millionths: 0,
1889 excess_data: Vec::new()
1892 // A payment above the minimum should pass
1893 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();
1894 assert_eq!(route.paths[0].len(), 2);
1898 fn htlc_minimum_overpay_test() {
1899 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
1900 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
1902 // A route to node#2 via two paths.
1903 // One path allows transferring 35-40 sats, another one also allows 35-40 sats.
1904 // Thus, they can't send 60 without overpaying.
1905 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
1906 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1907 short_channel_id: 2,
1910 cltv_expiry_delta: 0,
1911 htlc_minimum_msat: 35_000,
1912 htlc_maximum_msat: OptionalField::Present(40_000),
1914 fee_proportional_millionths: 0,
1915 excess_data: Vec::new()
1917 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
1918 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1919 short_channel_id: 12,
1922 cltv_expiry_delta: 0,
1923 htlc_minimum_msat: 35_000,
1924 htlc_maximum_msat: OptionalField::Present(40_000),
1926 fee_proportional_millionths: 0,
1927 excess_data: Vec::new()
1931 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
1932 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1933 short_channel_id: 13,
1936 cltv_expiry_delta: 0,
1937 htlc_minimum_msat: 0,
1938 htlc_maximum_msat: OptionalField::Absent,
1940 fee_proportional_millionths: 0,
1941 excess_data: Vec::new()
1943 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
1944 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1945 short_channel_id: 4,
1948 cltv_expiry_delta: 0,
1949 htlc_minimum_msat: 0,
1950 htlc_maximum_msat: OptionalField::Absent,
1952 fee_proportional_millionths: 0,
1953 excess_data: Vec::new()
1956 // Disable other paths
1957 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
1958 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1959 short_channel_id: 1,
1961 flags: 2, // to disable
1962 cltv_expiry_delta: 0,
1963 htlc_minimum_msat: 0,
1964 htlc_maximum_msat: OptionalField::Absent,
1966 fee_proportional_millionths: 0,
1967 excess_data: Vec::new()
1970 let route = get_route(&our_id, &net_graph_msg_handler.network_graph, &nodes[2],
1971 Some(InvoiceFeatures::known()), None, &Vec::new(), 60_000, 42, Arc::clone(&logger)).unwrap();
1972 // Overpay fees to hit htlc_minimum_msat.
1973 let overpaid_fees = route.paths[0][0].fee_msat + route.paths[1][0].fee_msat;
1974 // TODO: this could be better balanced to overpay 10k and not 15k.
1975 assert_eq!(overpaid_fees, 15_000);
1977 // Now, test that if there are 2 paths, a "cheaper" by fee path wouldn't be prioritized
1978 // while taking even more fee to match htlc_minimum_msat.
1979 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
1980 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1981 short_channel_id: 12,
1984 cltv_expiry_delta: 0,
1985 htlc_minimum_msat: 65_000,
1986 htlc_maximum_msat: OptionalField::Present(80_000),
1988 fee_proportional_millionths: 0,
1989 excess_data: Vec::new()
1991 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
1992 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1993 short_channel_id: 2,
1996 cltv_expiry_delta: 0,
1997 htlc_minimum_msat: 0,
1998 htlc_maximum_msat: OptionalField::Absent,
2000 fee_proportional_millionths: 0,
2001 excess_data: Vec::new()
2003 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
2004 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2005 short_channel_id: 4,
2008 cltv_expiry_delta: 0,
2009 htlc_minimum_msat: 0,
2010 htlc_maximum_msat: OptionalField::Absent,
2012 fee_proportional_millionths: 100_000,
2013 excess_data: Vec::new()
2016 let route = get_route(&our_id, &net_graph_msg_handler.network_graph, &nodes[2],
2017 Some(InvoiceFeatures::known()), None, &Vec::new(), 60_000, 42, Arc::clone(&logger)).unwrap();
2018 // Fine to overpay for htlc_minimum_msat if it allows us to save fee.
2019 assert_eq!(route.paths.len(), 1);
2020 assert_eq!(route.paths[0][0].short_channel_id, 12);
2021 let fees = route.paths[0][0].fee_msat;
2022 assert_eq!(fees, 5_000);
2024 let route = get_route(&our_id, &net_graph_msg_handler.network_graph, &nodes[2],
2025 Some(InvoiceFeatures::known()), None, &Vec::new(), 50_000, 42, Arc::clone(&logger)).unwrap();
2026 // Not fine to overpay for htlc_minimum_msat if it requires paying more than fee on
2027 // the other channel.
2028 assert_eq!(route.paths.len(), 1);
2029 assert_eq!(route.paths[0][0].short_channel_id, 2);
2030 let fees = route.paths[0][0].fee_msat;
2031 assert_eq!(fees, 5_000);
2035 fn disable_channels_test() {
2036 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
2037 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
2039 // // Disable channels 4 and 12 by flags=2
2040 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
2041 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2042 short_channel_id: 4,
2044 flags: 2, // to disable
2045 cltv_expiry_delta: 0,
2046 htlc_minimum_msat: 0,
2047 htlc_maximum_msat: OptionalField::Absent,
2049 fee_proportional_millionths: 0,
2050 excess_data: Vec::new()
2052 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2053 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2054 short_channel_id: 12,
2056 flags: 2, // to disable
2057 cltv_expiry_delta: 0,
2058 htlc_minimum_msat: 0,
2059 htlc_maximum_msat: OptionalField::Absent,
2061 fee_proportional_millionths: 0,
2062 excess_data: Vec::new()
2065 // If all the channels require some features we don't understand, route should fail
2066 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)) {
2067 assert_eq!(err, "Failed to find a path to the given destination");
2068 } else { panic!(); }
2070 // If we specify a channel to node7, that overrides our local channel view and that gets used
2071 let our_chans = vec![get_channel_details(Some(42), nodes[7].clone(), InitFeatures::from_le_bytes(vec![0b11]), 250_000_000)];
2072 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();
2073 assert_eq!(route.paths[0].len(), 2);
2075 assert_eq!(route.paths[0][0].pubkey, nodes[7]);
2076 assert_eq!(route.paths[0][0].short_channel_id, 42);
2077 assert_eq!(route.paths[0][0].fee_msat, 200);
2078 assert_eq!(route.paths[0][0].cltv_expiry_delta, (13 << 8) | 1);
2079 assert_eq!(route.paths[0][0].node_features.le_flags(), &vec![0b11]); // it should also override our view of their features
2080 assert_eq!(route.paths[0][0].channel_features.le_flags(), &Vec::<u8>::new()); // No feature flags will meet the relevant-to-channel conversion
2082 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2083 assert_eq!(route.paths[0][1].short_channel_id, 13);
2084 assert_eq!(route.paths[0][1].fee_msat, 100);
2085 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
2086 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2087 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(13));
2091 fn disable_node_test() {
2092 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
2093 let (_, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
2095 // Disable nodes 1, 2, and 8 by requiring unknown feature bits
2096 let unknown_features = NodeFeatures::known().set_unknown_feature_required();
2097 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[0], unknown_features.clone(), 1);
2098 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[1], unknown_features.clone(), 1);
2099 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[7], unknown_features.clone(), 1);
2101 // If all nodes require some features we don't understand, route should fail
2102 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)) {
2103 assert_eq!(err, "Failed to find a path to the given destination");
2104 } else { panic!(); }
2106 // If we specify a channel to node7, that overrides our local channel view and that gets used
2107 let our_chans = vec![get_channel_details(Some(42), nodes[7].clone(), InitFeatures::from_le_bytes(vec![0b11]), 250_000_000)];
2108 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();
2109 assert_eq!(route.paths[0].len(), 2);
2111 assert_eq!(route.paths[0][0].pubkey, nodes[7]);
2112 assert_eq!(route.paths[0][0].short_channel_id, 42);
2113 assert_eq!(route.paths[0][0].fee_msat, 200);
2114 assert_eq!(route.paths[0][0].cltv_expiry_delta, (13 << 8) | 1);
2115 assert_eq!(route.paths[0][0].node_features.le_flags(), &vec![0b11]); // it should also override our view of their features
2116 assert_eq!(route.paths[0][0].channel_features.le_flags(), &Vec::<u8>::new()); // No feature flags will meet the relevant-to-channel conversion
2118 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2119 assert_eq!(route.paths[0][1].short_channel_id, 13);
2120 assert_eq!(route.paths[0][1].fee_msat, 100);
2121 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
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(13));
2125 // Note that we don't test disabling node 3 and failing to route to it, as we (somewhat
2126 // naively) assume that the user checked the feature bits on the invoice, which override
2127 // the node_announcement.
2131 fn our_chans_test() {
2132 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
2133 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
2135 // Route to 1 via 2 and 3 because our channel to 1 is disabled
2136 let route = get_route(&our_id, &net_graph_msg_handler.network_graph, &nodes[0], None, None, &Vec::new(), 100, 42, Arc::clone(&logger)).unwrap();
2137 assert_eq!(route.paths[0].len(), 3);
2139 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
2140 assert_eq!(route.paths[0][0].short_channel_id, 2);
2141 assert_eq!(route.paths[0][0].fee_msat, 200);
2142 assert_eq!(route.paths[0][0].cltv_expiry_delta, (4 << 8) | 1);
2143 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
2144 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
2146 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2147 assert_eq!(route.paths[0][1].short_channel_id, 4);
2148 assert_eq!(route.paths[0][1].fee_msat, 100);
2149 assert_eq!(route.paths[0][1].cltv_expiry_delta, (3 << 8) | 2);
2150 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2151 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
2153 assert_eq!(route.paths[0][2].pubkey, nodes[0]);
2154 assert_eq!(route.paths[0][2].short_channel_id, 3);
2155 assert_eq!(route.paths[0][2].fee_msat, 100);
2156 assert_eq!(route.paths[0][2].cltv_expiry_delta, 42);
2157 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(1));
2158 assert_eq!(route.paths[0][2].channel_features.le_flags(), &id_to_feature_flags(3));
2160 // If we specify a channel to node7, that overrides our local channel view and that gets used
2161 let our_chans = vec![get_channel_details(Some(42), nodes[7].clone(), InitFeatures::from_le_bytes(vec![0b11]), 250_000_000)];
2162 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();
2163 assert_eq!(route.paths[0].len(), 2);
2165 assert_eq!(route.paths[0][0].pubkey, nodes[7]);
2166 assert_eq!(route.paths[0][0].short_channel_id, 42);
2167 assert_eq!(route.paths[0][0].fee_msat, 200);
2168 assert_eq!(route.paths[0][0].cltv_expiry_delta, (13 << 8) | 1);
2169 assert_eq!(route.paths[0][0].node_features.le_flags(), &vec![0b11]);
2170 assert_eq!(route.paths[0][0].channel_features.le_flags(), &Vec::<u8>::new()); // No feature flags will meet the relevant-to-channel conversion
2172 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2173 assert_eq!(route.paths[0][1].short_channel_id, 13);
2174 assert_eq!(route.paths[0][1].fee_msat, 100);
2175 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
2176 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2177 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(13));
2180 fn last_hops(nodes: &Vec<PublicKey>) -> Vec<RouteHint> {
2181 let zero_fees = RoutingFees {
2183 proportional_millionths: 0,
2185 vec![RouteHint(vec![RouteHintHop {
2186 src_node_id: nodes[3].clone(),
2187 short_channel_id: 8,
2189 cltv_expiry_delta: (8 << 8) | 1,
2190 htlc_minimum_msat: None,
2191 htlc_maximum_msat: None,
2193 ]), RouteHint(vec![RouteHintHop {
2194 src_node_id: nodes[4].clone(),
2195 short_channel_id: 9,
2198 proportional_millionths: 0,
2200 cltv_expiry_delta: (9 << 8) | 1,
2201 htlc_minimum_msat: None,
2202 htlc_maximum_msat: None,
2203 }]), RouteHint(vec![RouteHintHop {
2204 src_node_id: nodes[5].clone(),
2205 short_channel_id: 10,
2207 cltv_expiry_delta: (10 << 8) | 1,
2208 htlc_minimum_msat: None,
2209 htlc_maximum_msat: None,
2213 fn last_hops_multi_private_channels(nodes: &Vec<PublicKey>) -> Vec<RouteHint> {
2214 let zero_fees = RoutingFees {
2216 proportional_millionths: 0,
2218 vec![RouteHint(vec![RouteHintHop {
2219 src_node_id: nodes[2].clone(),
2220 short_channel_id: 5,
2223 proportional_millionths: 0,
2225 cltv_expiry_delta: (5 << 8) | 1,
2226 htlc_minimum_msat: None,
2227 htlc_maximum_msat: None,
2229 src_node_id: nodes[3].clone(),
2230 short_channel_id: 8,
2232 cltv_expiry_delta: (8 << 8) | 1,
2233 htlc_minimum_msat: None,
2234 htlc_maximum_msat: None,
2236 ]), RouteHint(vec![RouteHintHop {
2237 src_node_id: nodes[4].clone(),
2238 short_channel_id: 9,
2241 proportional_millionths: 0,
2243 cltv_expiry_delta: (9 << 8) | 1,
2244 htlc_minimum_msat: None,
2245 htlc_maximum_msat: None,
2246 }]), RouteHint(vec![RouteHintHop {
2247 src_node_id: nodes[5].clone(),
2248 short_channel_id: 10,
2250 cltv_expiry_delta: (10 << 8) | 1,
2251 htlc_minimum_msat: None,
2252 htlc_maximum_msat: None,
2257 fn partial_route_hint_test() {
2258 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
2259 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
2261 // Simple test across 2, 3, 5, and 4 via a last_hop channel
2262 // Tests the behaviour when the RouteHint contains a suboptimal hop.
2263 // RouteHint may be partially used by the algo to build the best path.
2265 // First check that last hop can't have its source as the payee.
2266 let invalid_last_hop = RouteHint(vec![RouteHintHop {
2267 src_node_id: nodes[6],
2268 short_channel_id: 8,
2271 proportional_millionths: 0,
2273 cltv_expiry_delta: (8 << 8) | 1,
2274 htlc_minimum_msat: None,
2275 htlc_maximum_msat: None,
2278 let mut invalid_last_hops = last_hops_multi_private_channels(&nodes);
2279 invalid_last_hops.push(invalid_last_hop);
2281 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)) {
2282 assert_eq!(err, "Last hop cannot have a payee as a source.");
2283 } else { panic!(); }
2286 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();
2287 assert_eq!(route.paths[0].len(), 5);
2289 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
2290 assert_eq!(route.paths[0][0].short_channel_id, 2);
2291 assert_eq!(route.paths[0][0].fee_msat, 100);
2292 assert_eq!(route.paths[0][0].cltv_expiry_delta, (4 << 8) | 1);
2293 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
2294 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
2296 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2297 assert_eq!(route.paths[0][1].short_channel_id, 4);
2298 assert_eq!(route.paths[0][1].fee_msat, 0);
2299 assert_eq!(route.paths[0][1].cltv_expiry_delta, (6 << 8) | 1);
2300 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2301 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
2303 assert_eq!(route.paths[0][2].pubkey, nodes[4]);
2304 assert_eq!(route.paths[0][2].short_channel_id, 6);
2305 assert_eq!(route.paths[0][2].fee_msat, 0);
2306 assert_eq!(route.paths[0][2].cltv_expiry_delta, (11 << 8) | 1);
2307 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(5));
2308 assert_eq!(route.paths[0][2].channel_features.le_flags(), &id_to_feature_flags(6));
2310 assert_eq!(route.paths[0][3].pubkey, nodes[3]);
2311 assert_eq!(route.paths[0][3].short_channel_id, 11);
2312 assert_eq!(route.paths[0][3].fee_msat, 0);
2313 assert_eq!(route.paths[0][3].cltv_expiry_delta, (8 << 8) | 1);
2314 // If we have a peer in the node map, we'll use their features here since we don't have
2315 // a way of figuring out their features from the invoice:
2316 assert_eq!(route.paths[0][3].node_features.le_flags(), &id_to_feature_flags(4));
2317 assert_eq!(route.paths[0][3].channel_features.le_flags(), &id_to_feature_flags(11));
2319 assert_eq!(route.paths[0][4].pubkey, nodes[6]);
2320 assert_eq!(route.paths[0][4].short_channel_id, 8);
2321 assert_eq!(route.paths[0][4].fee_msat, 100);
2322 assert_eq!(route.paths[0][4].cltv_expiry_delta, 42);
2323 assert_eq!(route.paths[0][4].node_features.le_flags(), &Vec::<u8>::new()); // We dont pass flags in from invoices yet
2324 assert_eq!(route.paths[0][4].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
2327 fn empty_last_hop(nodes: &Vec<PublicKey>) -> Vec<RouteHint> {
2328 let zero_fees = RoutingFees {
2330 proportional_millionths: 0,
2332 vec![RouteHint(vec![RouteHintHop {
2333 src_node_id: nodes[3].clone(),
2334 short_channel_id: 8,
2336 cltv_expiry_delta: (8 << 8) | 1,
2337 htlc_minimum_msat: None,
2338 htlc_maximum_msat: None,
2339 }]), RouteHint(vec![
2341 ]), RouteHint(vec![RouteHintHop {
2342 src_node_id: nodes[5].clone(),
2343 short_channel_id: 10,
2345 cltv_expiry_delta: (10 << 8) | 1,
2346 htlc_minimum_msat: None,
2347 htlc_maximum_msat: None,
2352 fn ignores_empty_last_hops_test() {
2353 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
2354 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
2356 // Test handling of an empty RouteHint passed in Invoice.
2358 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();
2359 assert_eq!(route.paths[0].len(), 5);
2361 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
2362 assert_eq!(route.paths[0][0].short_channel_id, 2);
2363 assert_eq!(route.paths[0][0].fee_msat, 100);
2364 assert_eq!(route.paths[0][0].cltv_expiry_delta, (4 << 8) | 1);
2365 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
2366 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
2368 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2369 assert_eq!(route.paths[0][1].short_channel_id, 4);
2370 assert_eq!(route.paths[0][1].fee_msat, 0);
2371 assert_eq!(route.paths[0][1].cltv_expiry_delta, (6 << 8) | 1);
2372 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2373 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
2375 assert_eq!(route.paths[0][2].pubkey, nodes[4]);
2376 assert_eq!(route.paths[0][2].short_channel_id, 6);
2377 assert_eq!(route.paths[0][2].fee_msat, 0);
2378 assert_eq!(route.paths[0][2].cltv_expiry_delta, (11 << 8) | 1);
2379 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(5));
2380 assert_eq!(route.paths[0][2].channel_features.le_flags(), &id_to_feature_flags(6));
2382 assert_eq!(route.paths[0][3].pubkey, nodes[3]);
2383 assert_eq!(route.paths[0][3].short_channel_id, 11);
2384 assert_eq!(route.paths[0][3].fee_msat, 0);
2385 assert_eq!(route.paths[0][3].cltv_expiry_delta, (8 << 8) | 1);
2386 // If we have a peer in the node map, we'll use their features here since we don't have
2387 // a way of figuring out their features from the invoice:
2388 assert_eq!(route.paths[0][3].node_features.le_flags(), &id_to_feature_flags(4));
2389 assert_eq!(route.paths[0][3].channel_features.le_flags(), &id_to_feature_flags(11));
2391 assert_eq!(route.paths[0][4].pubkey, nodes[6]);
2392 assert_eq!(route.paths[0][4].short_channel_id, 8);
2393 assert_eq!(route.paths[0][4].fee_msat, 100);
2394 assert_eq!(route.paths[0][4].cltv_expiry_delta, 42);
2395 assert_eq!(route.paths[0][4].node_features.le_flags(), &Vec::<u8>::new()); // We dont pass flags in from invoices yet
2396 assert_eq!(route.paths[0][4].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
2399 fn multi_hint_last_hops(nodes: &Vec<PublicKey>) -> Vec<RouteHint> {
2400 let zero_fees = RoutingFees {
2402 proportional_millionths: 0,
2404 vec![RouteHint(vec![RouteHintHop {
2405 src_node_id: nodes[2].clone(),
2406 short_channel_id: 5,
2409 proportional_millionths: 0,
2411 cltv_expiry_delta: (5 << 8) | 1,
2412 htlc_minimum_msat: None,
2413 htlc_maximum_msat: None,
2415 src_node_id: nodes[3].clone(),
2416 short_channel_id: 8,
2418 cltv_expiry_delta: (8 << 8) | 1,
2419 htlc_minimum_msat: None,
2420 htlc_maximum_msat: None,
2421 }]), RouteHint(vec![RouteHintHop {
2422 src_node_id: nodes[5].clone(),
2423 short_channel_id: 10,
2425 cltv_expiry_delta: (10 << 8) | 1,
2426 htlc_minimum_msat: None,
2427 htlc_maximum_msat: None,
2432 fn multi_hint_last_hops_test() {
2433 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
2434 let (_, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
2435 // Test through channels 2, 3, 5, 8.
2436 // Test shows that multiple hop hints are considered.
2438 // Disabling channels 6 & 7 by flags=2
2439 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
2440 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2441 short_channel_id: 6,
2443 flags: 2, // to disable
2444 cltv_expiry_delta: 0,
2445 htlc_minimum_msat: 0,
2446 htlc_maximum_msat: OptionalField::Absent,
2448 fee_proportional_millionths: 0,
2449 excess_data: Vec::new()
2451 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
2452 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2453 short_channel_id: 7,
2455 flags: 2, // to disable
2456 cltv_expiry_delta: 0,
2457 htlc_minimum_msat: 0,
2458 htlc_maximum_msat: OptionalField::Absent,
2460 fee_proportional_millionths: 0,
2461 excess_data: Vec::new()
2464 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();
2465 assert_eq!(route.paths[0].len(), 4);
2467 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
2468 assert_eq!(route.paths[0][0].short_channel_id, 2);
2469 assert_eq!(route.paths[0][0].fee_msat, 200);
2470 assert_eq!(route.paths[0][0].cltv_expiry_delta, 1025);
2471 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
2472 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
2474 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2475 assert_eq!(route.paths[0][1].short_channel_id, 4);
2476 assert_eq!(route.paths[0][1].fee_msat, 100);
2477 assert_eq!(route.paths[0][1].cltv_expiry_delta, 1281);
2478 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2479 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
2481 assert_eq!(route.paths[0][2].pubkey, nodes[3]);
2482 assert_eq!(route.paths[0][2].short_channel_id, 5);
2483 assert_eq!(route.paths[0][2].fee_msat, 0);
2484 assert_eq!(route.paths[0][2].cltv_expiry_delta, 2049);
2485 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(4));
2486 assert_eq!(route.paths[0][2].channel_features.le_flags(), &Vec::<u8>::new());
2488 assert_eq!(route.paths[0][3].pubkey, nodes[6]);
2489 assert_eq!(route.paths[0][3].short_channel_id, 8);
2490 assert_eq!(route.paths[0][3].fee_msat, 100);
2491 assert_eq!(route.paths[0][3].cltv_expiry_delta, 42);
2492 assert_eq!(route.paths[0][3].node_features.le_flags(), &Vec::<u8>::new()); // We dont pass flags in from invoices yet
2493 assert_eq!(route.paths[0][3].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
2496 fn last_hops_with_public_channel(nodes: &Vec<PublicKey>) -> Vec<RouteHint> {
2497 let zero_fees = RoutingFees {
2499 proportional_millionths: 0,
2501 vec![RouteHint(vec![RouteHintHop {
2502 src_node_id: nodes[4].clone(),
2503 short_channel_id: 11,
2505 cltv_expiry_delta: (11 << 8) | 1,
2506 htlc_minimum_msat: None,
2507 htlc_maximum_msat: None,
2509 src_node_id: nodes[3].clone(),
2510 short_channel_id: 8,
2512 cltv_expiry_delta: (8 << 8) | 1,
2513 htlc_minimum_msat: None,
2514 htlc_maximum_msat: None,
2515 }]), RouteHint(vec![RouteHintHop {
2516 src_node_id: nodes[4].clone(),
2517 short_channel_id: 9,
2520 proportional_millionths: 0,
2522 cltv_expiry_delta: (9 << 8) | 1,
2523 htlc_minimum_msat: None,
2524 htlc_maximum_msat: None,
2525 }]), RouteHint(vec![RouteHintHop {
2526 src_node_id: nodes[5].clone(),
2527 short_channel_id: 10,
2529 cltv_expiry_delta: (10 << 8) | 1,
2530 htlc_minimum_msat: None,
2531 htlc_maximum_msat: None,
2536 fn last_hops_with_public_channel_test() {
2537 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
2538 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
2539 // This test shows that public routes can be present in the invoice
2540 // which would be handled in the same manner.
2542 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();
2543 assert_eq!(route.paths[0].len(), 5);
2545 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
2546 assert_eq!(route.paths[0][0].short_channel_id, 2);
2547 assert_eq!(route.paths[0][0].fee_msat, 100);
2548 assert_eq!(route.paths[0][0].cltv_expiry_delta, (4 << 8) | 1);
2549 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
2550 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
2552 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2553 assert_eq!(route.paths[0][1].short_channel_id, 4);
2554 assert_eq!(route.paths[0][1].fee_msat, 0);
2555 assert_eq!(route.paths[0][1].cltv_expiry_delta, (6 << 8) | 1);
2556 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2557 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
2559 assert_eq!(route.paths[0][2].pubkey, nodes[4]);
2560 assert_eq!(route.paths[0][2].short_channel_id, 6);
2561 assert_eq!(route.paths[0][2].fee_msat, 0);
2562 assert_eq!(route.paths[0][2].cltv_expiry_delta, (11 << 8) | 1);
2563 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(5));
2564 assert_eq!(route.paths[0][2].channel_features.le_flags(), &id_to_feature_flags(6));
2566 assert_eq!(route.paths[0][3].pubkey, nodes[3]);
2567 assert_eq!(route.paths[0][3].short_channel_id, 11);
2568 assert_eq!(route.paths[0][3].fee_msat, 0);
2569 assert_eq!(route.paths[0][3].cltv_expiry_delta, (8 << 8) | 1);
2570 // If we have a peer in the node map, we'll use their features here since we don't have
2571 // a way of figuring out their features from the invoice:
2572 assert_eq!(route.paths[0][3].node_features.le_flags(), &id_to_feature_flags(4));
2573 assert_eq!(route.paths[0][3].channel_features.le_flags(), &Vec::<u8>::new());
2575 assert_eq!(route.paths[0][4].pubkey, nodes[6]);
2576 assert_eq!(route.paths[0][4].short_channel_id, 8);
2577 assert_eq!(route.paths[0][4].fee_msat, 100);
2578 assert_eq!(route.paths[0][4].cltv_expiry_delta, 42);
2579 assert_eq!(route.paths[0][4].node_features.le_flags(), &Vec::<u8>::new()); // We dont pass flags in from invoices yet
2580 assert_eq!(route.paths[0][4].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
2584 fn our_chans_last_hop_connect_test() {
2585 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
2586 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
2588 // Simple test with outbound channel to 4 to test that last_hops and first_hops connect
2589 let our_chans = vec![get_channel_details(Some(42), nodes[3].clone(), InitFeatures::from_le_bytes(vec![0b11]), 250_000_000)];
2590 let mut last_hops = last_hops(&nodes);
2591 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();
2592 assert_eq!(route.paths[0].len(), 2);
2594 assert_eq!(route.paths[0][0].pubkey, nodes[3]);
2595 assert_eq!(route.paths[0][0].short_channel_id, 42);
2596 assert_eq!(route.paths[0][0].fee_msat, 0);
2597 assert_eq!(route.paths[0][0].cltv_expiry_delta, (8 << 8) | 1);
2598 assert_eq!(route.paths[0][0].node_features.le_flags(), &vec![0b11]);
2599 assert_eq!(route.paths[0][0].channel_features.le_flags(), &Vec::<u8>::new()); // No feature flags will meet the relevant-to-channel conversion
2601 assert_eq!(route.paths[0][1].pubkey, nodes[6]);
2602 assert_eq!(route.paths[0][1].short_channel_id, 8);
2603 assert_eq!(route.paths[0][1].fee_msat, 100);
2604 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
2605 assert_eq!(route.paths[0][1].node_features.le_flags(), &Vec::<u8>::new()); // We dont pass flags in from invoices yet
2606 assert_eq!(route.paths[0][1].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
2608 last_hops[0].0[0].fees.base_msat = 1000;
2610 // Revert to via 6 as the fee on 8 goes up
2611 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();
2612 assert_eq!(route.paths[0].len(), 4);
2614 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
2615 assert_eq!(route.paths[0][0].short_channel_id, 2);
2616 assert_eq!(route.paths[0][0].fee_msat, 200); // fee increased as its % of value transferred across node
2617 assert_eq!(route.paths[0][0].cltv_expiry_delta, (4 << 8) | 1);
2618 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
2619 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
2621 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2622 assert_eq!(route.paths[0][1].short_channel_id, 4);
2623 assert_eq!(route.paths[0][1].fee_msat, 100);
2624 assert_eq!(route.paths[0][1].cltv_expiry_delta, (7 << 8) | 1);
2625 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2626 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
2628 assert_eq!(route.paths[0][2].pubkey, nodes[5]);
2629 assert_eq!(route.paths[0][2].short_channel_id, 7);
2630 assert_eq!(route.paths[0][2].fee_msat, 0);
2631 assert_eq!(route.paths[0][2].cltv_expiry_delta, (10 << 8) | 1);
2632 // If we have a peer in the node map, we'll use their features here since we don't have
2633 // a way of figuring out their features from the invoice:
2634 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(6));
2635 assert_eq!(route.paths[0][2].channel_features.le_flags(), &id_to_feature_flags(7));
2637 assert_eq!(route.paths[0][3].pubkey, nodes[6]);
2638 assert_eq!(route.paths[0][3].short_channel_id, 10);
2639 assert_eq!(route.paths[0][3].fee_msat, 100);
2640 assert_eq!(route.paths[0][3].cltv_expiry_delta, 42);
2641 assert_eq!(route.paths[0][3].node_features.le_flags(), &Vec::<u8>::new()); // We dont pass flags in from invoices yet
2642 assert_eq!(route.paths[0][3].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
2644 // ...but still use 8 for larger payments as 6 has a variable feerate
2645 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();
2646 assert_eq!(route.paths[0].len(), 5);
2648 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
2649 assert_eq!(route.paths[0][0].short_channel_id, 2);
2650 assert_eq!(route.paths[0][0].fee_msat, 3000);
2651 assert_eq!(route.paths[0][0].cltv_expiry_delta, (4 << 8) | 1);
2652 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
2653 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
2655 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2656 assert_eq!(route.paths[0][1].short_channel_id, 4);
2657 assert_eq!(route.paths[0][1].fee_msat, 0);
2658 assert_eq!(route.paths[0][1].cltv_expiry_delta, (6 << 8) | 1);
2659 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2660 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
2662 assert_eq!(route.paths[0][2].pubkey, nodes[4]);
2663 assert_eq!(route.paths[0][2].short_channel_id, 6);
2664 assert_eq!(route.paths[0][2].fee_msat, 0);
2665 assert_eq!(route.paths[0][2].cltv_expiry_delta, (11 << 8) | 1);
2666 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(5));
2667 assert_eq!(route.paths[0][2].channel_features.le_flags(), &id_to_feature_flags(6));
2669 assert_eq!(route.paths[0][3].pubkey, nodes[3]);
2670 assert_eq!(route.paths[0][3].short_channel_id, 11);
2671 assert_eq!(route.paths[0][3].fee_msat, 1000);
2672 assert_eq!(route.paths[0][3].cltv_expiry_delta, (8 << 8) | 1);
2673 // If we have a peer in the node map, we'll use their features here since we don't have
2674 // a way of figuring out their features from the invoice:
2675 assert_eq!(route.paths[0][3].node_features.le_flags(), &id_to_feature_flags(4));
2676 assert_eq!(route.paths[0][3].channel_features.le_flags(), &id_to_feature_flags(11));
2678 assert_eq!(route.paths[0][4].pubkey, nodes[6]);
2679 assert_eq!(route.paths[0][4].short_channel_id, 8);
2680 assert_eq!(route.paths[0][4].fee_msat, 2000);
2681 assert_eq!(route.paths[0][4].cltv_expiry_delta, 42);
2682 assert_eq!(route.paths[0][4].node_features.le_flags(), &Vec::<u8>::new()); // We dont pass flags in from invoices yet
2683 assert_eq!(route.paths[0][4].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
2686 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> {
2687 let source_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&hex::decode(format!("{:02}", 41).repeat(32)).unwrap()[..]).unwrap());
2688 let middle_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&hex::decode(format!("{:02}", 42).repeat(32)).unwrap()[..]).unwrap());
2689 let target_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&hex::decode(format!("{:02}", 43).repeat(32)).unwrap()[..]).unwrap());
2691 // If we specify a channel to a middle hop, that overrides our local channel view and that gets used
2692 let last_hops = RouteHint(vec![RouteHintHop {
2693 src_node_id: middle_node_id,
2694 short_channel_id: 8,
2697 proportional_millionths: last_hop_fee_prop,
2699 cltv_expiry_delta: (8 << 8) | 1,
2700 htlc_minimum_msat: None,
2701 htlc_maximum_msat: last_hop_htlc_max,
2703 let our_chans = vec![get_channel_details(Some(42), middle_node_id, InitFeatures::from_le_bytes(vec![0b11]), outbound_capacity_msat)];
2704 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()))
2708 fn unannounced_path_test() {
2709 // We should be able to send a payment to a destination without any help of a routing graph
2710 // if we have a channel with a common counterparty that appears in the first and last hop
2712 let route = do_unannounced_path_test(None, 1, 2000000, 1000000).unwrap();
2714 let middle_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&hex::decode(format!("{:02}", 42).repeat(32)).unwrap()[..]).unwrap());
2715 let target_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&hex::decode(format!("{:02}", 43).repeat(32)).unwrap()[..]).unwrap());
2716 assert_eq!(route.paths[0].len(), 2);
2718 assert_eq!(route.paths[0][0].pubkey, middle_node_id);
2719 assert_eq!(route.paths[0][0].short_channel_id, 42);
2720 assert_eq!(route.paths[0][0].fee_msat, 1001);
2721 assert_eq!(route.paths[0][0].cltv_expiry_delta, (8 << 8) | 1);
2722 assert_eq!(route.paths[0][0].node_features.le_flags(), &[0b11]);
2723 assert_eq!(route.paths[0][0].channel_features.le_flags(), &[0; 0]); // We can't learn any flags from invoices, sadly
2725 assert_eq!(route.paths[0][1].pubkey, target_node_id);
2726 assert_eq!(route.paths[0][1].short_channel_id, 8);
2727 assert_eq!(route.paths[0][1].fee_msat, 1000000);
2728 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
2729 assert_eq!(route.paths[0][1].node_features.le_flags(), &[0; 0]); // We dont pass flags in from invoices yet
2730 assert_eq!(route.paths[0][1].channel_features.le_flags(), &[0; 0]); // We can't learn any flags from invoices, sadly
2734 fn overflow_unannounced_path_test_liquidity_underflow() {
2735 // Previously, when we had a last-hop hint connected directly to a first-hop channel, where
2736 // the last-hop had a fee which overflowed a u64, we'd panic.
2737 // This was due to us adding the first-hop from us unconditionally, causing us to think
2738 // we'd built a path (as our node is in the "best candidate" set), when we had not.
2739 // In this test, we previously hit a subtraction underflow due to having less available
2740 // liquidity at the last hop than 0.
2741 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());
2745 fn overflow_unannounced_path_test_feerate_overflow() {
2746 // This tests for the same case as above, except instead of hitting a subtraction
2747 // underflow, we hit a case where the fee charged at a hop overflowed.
2748 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());
2752 fn available_amount_while_routing_test() {
2753 // Tests whether we choose the correct available channel amount while routing.
2755 let (secp_ctx, mut net_graph_msg_handler, chain_monitor, logger) = build_graph();
2756 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
2758 // We will use a simple single-path route from
2759 // our node to node2 via node0: channels {1, 3}.
2761 // First disable all other paths.
2762 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2763 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2764 short_channel_id: 2,
2767 cltv_expiry_delta: 0,
2768 htlc_minimum_msat: 0,
2769 htlc_maximum_msat: OptionalField::Present(100_000),
2771 fee_proportional_millionths: 0,
2772 excess_data: Vec::new()
2774 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2775 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2776 short_channel_id: 12,
2779 cltv_expiry_delta: 0,
2780 htlc_minimum_msat: 0,
2781 htlc_maximum_msat: OptionalField::Present(100_000),
2783 fee_proportional_millionths: 0,
2784 excess_data: Vec::new()
2787 // Make the first channel (#1) very permissive,
2788 // and we will be testing all limits on the second channel.
2789 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2790 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2791 short_channel_id: 1,
2794 cltv_expiry_delta: 0,
2795 htlc_minimum_msat: 0,
2796 htlc_maximum_msat: OptionalField::Present(1_000_000_000),
2798 fee_proportional_millionths: 0,
2799 excess_data: Vec::new()
2802 // First, let's see if routing works if we have absolutely no idea about the available amount.
2803 // In this case, it should be set to 250_000 sats.
2804 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
2805 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2806 short_channel_id: 3,
2809 cltv_expiry_delta: 0,
2810 htlc_minimum_msat: 0,
2811 htlc_maximum_msat: OptionalField::Absent,
2813 fee_proportional_millionths: 0,
2814 excess_data: Vec::new()
2818 // Attempt to route more than available results in a failure.
2819 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id, &net_graph_msg_handler.network_graph, &nodes[2],
2820 Some(InvoiceFeatures::known()), None, &Vec::new(), 250_000_001, 42, Arc::clone(&logger)) {
2821 assert_eq!(err, "Failed to find a sufficient route to the given destination");
2822 } else { panic!(); }
2826 // Now, attempt to route an exact amount we have should be fine.
2827 let route = get_route(&our_id, &net_graph_msg_handler.network_graph, &nodes[2],
2828 Some(InvoiceFeatures::known()), None, &Vec::new(), 250_000_000, 42, Arc::clone(&logger)).unwrap();
2829 assert_eq!(route.paths.len(), 1);
2830 let path = route.paths.last().unwrap();
2831 assert_eq!(path.len(), 2);
2832 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
2833 assert_eq!(path.last().unwrap().fee_msat, 250_000_000);
2836 // Check that setting outbound_capacity_msat in first_hops limits the channels.
2837 // Disable channel #1 and use another first hop.
2838 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2839 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2840 short_channel_id: 1,
2843 cltv_expiry_delta: 0,
2844 htlc_minimum_msat: 0,
2845 htlc_maximum_msat: OptionalField::Present(1_000_000_000),
2847 fee_proportional_millionths: 0,
2848 excess_data: Vec::new()
2851 // Now, limit the first_hop by the outbound_capacity_msat of 200_000 sats.
2852 let our_chans = vec![get_channel_details(Some(42), nodes[0].clone(), InitFeatures::from_le_bytes(vec![0b11]), 200_000_000)];
2855 // Attempt to route more than available results in a failure.
2856 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id, &net_graph_msg_handler.network_graph, &nodes[2],
2857 Some(InvoiceFeatures::known()), Some(&our_chans.iter().collect::<Vec<_>>()), &Vec::new(), 200_000_001, 42, Arc::clone(&logger)) {
2858 assert_eq!(err, "Failed to find a sufficient route to the given destination");
2859 } else { panic!(); }
2863 // Now, attempt to route an exact amount we have should be fine.
2864 let route = get_route(&our_id, &net_graph_msg_handler.network_graph, &nodes[2],
2865 Some(InvoiceFeatures::known()), Some(&our_chans.iter().collect::<Vec<_>>()), &Vec::new(), 200_000_000, 42, Arc::clone(&logger)).unwrap();
2866 assert_eq!(route.paths.len(), 1);
2867 let path = route.paths.last().unwrap();
2868 assert_eq!(path.len(), 2);
2869 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
2870 assert_eq!(path.last().unwrap().fee_msat, 200_000_000);
2873 // Enable channel #1 back.
2874 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2875 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2876 short_channel_id: 1,
2879 cltv_expiry_delta: 0,
2880 htlc_minimum_msat: 0,
2881 htlc_maximum_msat: OptionalField::Present(1_000_000_000),
2883 fee_proportional_millionths: 0,
2884 excess_data: Vec::new()
2888 // Now let's see if routing works if we know only htlc_maximum_msat.
2889 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
2890 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2891 short_channel_id: 3,
2894 cltv_expiry_delta: 0,
2895 htlc_minimum_msat: 0,
2896 htlc_maximum_msat: OptionalField::Present(15_000),
2898 fee_proportional_millionths: 0,
2899 excess_data: Vec::new()
2903 // Attempt to route more than available results in a failure.
2904 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id, &net_graph_msg_handler.network_graph, &nodes[2],
2905 Some(InvoiceFeatures::known()), None, &Vec::new(), 15_001, 42, Arc::clone(&logger)) {
2906 assert_eq!(err, "Failed to find a sufficient route to the given destination");
2907 } else { panic!(); }
2911 // Now, attempt to route an exact amount we have should be fine.
2912 let route = get_route(&our_id, &net_graph_msg_handler.network_graph, &nodes[2],
2913 Some(InvoiceFeatures::known()), None, &Vec::new(), 15_000, 42, Arc::clone(&logger)).unwrap();
2914 assert_eq!(route.paths.len(), 1);
2915 let path = route.paths.last().unwrap();
2916 assert_eq!(path.len(), 2);
2917 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
2918 assert_eq!(path.last().unwrap().fee_msat, 15_000);
2921 // Now let's see if routing works if we know only capacity from the UTXO.
2923 // We can't change UTXO capacity on the fly, so we'll disable
2924 // the existing channel and add another one with the capacity we need.
2925 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
2926 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2927 short_channel_id: 3,
2930 cltv_expiry_delta: 0,
2931 htlc_minimum_msat: 0,
2932 htlc_maximum_msat: OptionalField::Absent,
2934 fee_proportional_millionths: 0,
2935 excess_data: Vec::new()
2938 let good_script = Builder::new().push_opcode(opcodes::all::OP_PUSHNUM_2)
2939 .push_slice(&PublicKey::from_secret_key(&secp_ctx, &privkeys[0]).serialize())
2940 .push_slice(&PublicKey::from_secret_key(&secp_ctx, &privkeys[2]).serialize())
2941 .push_opcode(opcodes::all::OP_PUSHNUM_2)
2942 .push_opcode(opcodes::all::OP_CHECKMULTISIG).into_script().to_v0_p2wsh();
2944 *chain_monitor.utxo_ret.lock().unwrap() = Ok(TxOut { value: 15, script_pubkey: good_script.clone() });
2945 net_graph_msg_handler.add_chain_access(Some(chain_monitor));
2947 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], &privkeys[2], ChannelFeatures::from_le_bytes(id_to_feature_flags(3)), 333);
2948 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
2949 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2950 short_channel_id: 333,
2953 cltv_expiry_delta: (3 << 8) | 1,
2954 htlc_minimum_msat: 0,
2955 htlc_maximum_msat: OptionalField::Absent,
2957 fee_proportional_millionths: 0,
2958 excess_data: Vec::new()
2960 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
2961 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2962 short_channel_id: 333,
2965 cltv_expiry_delta: (3 << 8) | 2,
2966 htlc_minimum_msat: 0,
2967 htlc_maximum_msat: OptionalField::Absent,
2969 fee_proportional_millionths: 0,
2970 excess_data: Vec::new()
2974 // Attempt to route more than available results in a failure.
2975 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id, &net_graph_msg_handler.network_graph, &nodes[2],
2976 Some(InvoiceFeatures::known()), None, &Vec::new(), 15_001, 42, Arc::clone(&logger)) {
2977 assert_eq!(err, "Failed to find a sufficient route to the given destination");
2978 } else { panic!(); }
2982 // Now, attempt to route an exact amount we have should be fine.
2983 let route = get_route(&our_id, &net_graph_msg_handler.network_graph, &nodes[2],
2984 Some(InvoiceFeatures::known()), None, &Vec::new(), 15_000, 42, Arc::clone(&logger)).unwrap();
2985 assert_eq!(route.paths.len(), 1);
2986 let path = route.paths.last().unwrap();
2987 assert_eq!(path.len(), 2);
2988 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
2989 assert_eq!(path.last().unwrap().fee_msat, 15_000);
2992 // Now let's see if routing chooses htlc_maximum_msat over UTXO capacity.
2993 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
2994 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2995 short_channel_id: 333,
2998 cltv_expiry_delta: 0,
2999 htlc_minimum_msat: 0,
3000 htlc_maximum_msat: OptionalField::Present(10_000),
3002 fee_proportional_millionths: 0,
3003 excess_data: Vec::new()
3007 // Attempt to route more than available results in a failure.
3008 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id, &net_graph_msg_handler.network_graph, &nodes[2],
3009 Some(InvoiceFeatures::known()), None, &Vec::new(), 10_001, 42, Arc::clone(&logger)) {
3010 assert_eq!(err, "Failed to find a sufficient route to the given destination");
3011 } else { panic!(); }
3015 // Now, attempt to route an exact amount we have should be fine.
3016 let route = get_route(&our_id, &net_graph_msg_handler.network_graph, &nodes[2],
3017 Some(InvoiceFeatures::known()), None, &Vec::new(), 10_000, 42, Arc::clone(&logger)).unwrap();
3018 assert_eq!(route.paths.len(), 1);
3019 let path = route.paths.last().unwrap();
3020 assert_eq!(path.len(), 2);
3021 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
3022 assert_eq!(path.last().unwrap().fee_msat, 10_000);
3027 fn available_liquidity_last_hop_test() {
3028 // Check that available liquidity properly limits the path even when only
3029 // one of the latter hops is limited.
3030 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
3031 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3033 // Path via {node7, node2, node4} is channels {12, 13, 6, 11}.
3034 // {12, 13, 11} have the capacities of 100, {6} has a capacity of 50.
3035 // Total capacity: 50 sats.
3037 // Disable other potential paths.
3038 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3039 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3040 short_channel_id: 2,
3043 cltv_expiry_delta: 0,
3044 htlc_minimum_msat: 0,
3045 htlc_maximum_msat: OptionalField::Present(100_000),
3047 fee_proportional_millionths: 0,
3048 excess_data: Vec::new()
3050 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3051 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3052 short_channel_id: 7,
3055 cltv_expiry_delta: 0,
3056 htlc_minimum_msat: 0,
3057 htlc_maximum_msat: OptionalField::Present(100_000),
3059 fee_proportional_millionths: 0,
3060 excess_data: Vec::new()
3065 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3066 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3067 short_channel_id: 12,
3070 cltv_expiry_delta: 0,
3071 htlc_minimum_msat: 0,
3072 htlc_maximum_msat: OptionalField::Present(100_000),
3074 fee_proportional_millionths: 0,
3075 excess_data: Vec::new()
3077 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
3078 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3079 short_channel_id: 13,
3082 cltv_expiry_delta: 0,
3083 htlc_minimum_msat: 0,
3084 htlc_maximum_msat: OptionalField::Present(100_000),
3086 fee_proportional_millionths: 0,
3087 excess_data: Vec::new()
3090 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3091 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3092 short_channel_id: 6,
3095 cltv_expiry_delta: 0,
3096 htlc_minimum_msat: 0,
3097 htlc_maximum_msat: OptionalField::Present(50_000),
3099 fee_proportional_millionths: 0,
3100 excess_data: Vec::new()
3102 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
3103 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3104 short_channel_id: 11,
3107 cltv_expiry_delta: 0,
3108 htlc_minimum_msat: 0,
3109 htlc_maximum_msat: OptionalField::Present(100_000),
3111 fee_proportional_millionths: 0,
3112 excess_data: Vec::new()
3115 // Attempt to route more than available results in a failure.
3116 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id, &net_graph_msg_handler.network_graph, &nodes[3],
3117 Some(InvoiceFeatures::known()), None, &Vec::new(), 60_000, 42, Arc::clone(&logger)) {
3118 assert_eq!(err, "Failed to find a sufficient route to the given destination");
3119 } else { panic!(); }
3123 // Now, attempt to route 49 sats (just a bit below the capacity).
3124 let route = get_route(&our_id, &net_graph_msg_handler.network_graph, &nodes[3],
3125 Some(InvoiceFeatures::known()), None, &Vec::new(), 49_000, 42, Arc::clone(&logger)).unwrap();
3126 assert_eq!(route.paths.len(), 1);
3127 let mut total_amount_paid_msat = 0;
3128 for path in &route.paths {
3129 assert_eq!(path.len(), 4);
3130 assert_eq!(path.last().unwrap().pubkey, nodes[3]);
3131 total_amount_paid_msat += path.last().unwrap().fee_msat;
3133 assert_eq!(total_amount_paid_msat, 49_000);
3137 // Attempt to route an exact amount is also fine
3138 let route = get_route(&our_id, &net_graph_msg_handler.network_graph, &nodes[3],
3139 Some(InvoiceFeatures::known()), None, &Vec::new(), 50_000, 42, Arc::clone(&logger)).unwrap();
3140 assert_eq!(route.paths.len(), 1);
3141 let mut total_amount_paid_msat = 0;
3142 for path in &route.paths {
3143 assert_eq!(path.len(), 4);
3144 assert_eq!(path.last().unwrap().pubkey, nodes[3]);
3145 total_amount_paid_msat += path.last().unwrap().fee_msat;
3147 assert_eq!(total_amount_paid_msat, 50_000);
3152 fn ignore_fee_first_hop_test() {
3153 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
3154 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3156 // Path via node0 is channels {1, 3}. Limit them to 100 and 50 sats (total limit 50).
3157 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3158 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3159 short_channel_id: 1,
3162 cltv_expiry_delta: 0,
3163 htlc_minimum_msat: 0,
3164 htlc_maximum_msat: OptionalField::Present(100_000),
3165 fee_base_msat: 1_000_000,
3166 fee_proportional_millionths: 0,
3167 excess_data: Vec::new()
3169 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3170 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3171 short_channel_id: 3,
3174 cltv_expiry_delta: 0,
3175 htlc_minimum_msat: 0,
3176 htlc_maximum_msat: OptionalField::Present(50_000),
3178 fee_proportional_millionths: 0,
3179 excess_data: Vec::new()
3183 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();
3184 assert_eq!(route.paths.len(), 1);
3185 let mut total_amount_paid_msat = 0;
3186 for path in &route.paths {
3187 assert_eq!(path.len(), 2);
3188 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
3189 total_amount_paid_msat += path.last().unwrap().fee_msat;
3191 assert_eq!(total_amount_paid_msat, 50_000);
3196 fn simple_mpp_route_test() {
3197 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
3198 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3200 // We need a route consisting of 3 paths:
3201 // From our node to node2 via node0, node7, node1 (three paths one hop each).
3202 // To achieve this, the amount being transferred should be around
3203 // the total capacity of these 3 paths.
3205 // First, we set limits on these (previously unlimited) channels.
3206 // Their aggregate capacity will be 50 + 60 + 180 = 290 sats.
3208 // Path via node0 is channels {1, 3}. Limit them to 100 and 50 sats (total limit 50).
3209 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3210 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3211 short_channel_id: 1,
3214 cltv_expiry_delta: 0,
3215 htlc_minimum_msat: 0,
3216 htlc_maximum_msat: OptionalField::Present(100_000),
3218 fee_proportional_millionths: 0,
3219 excess_data: Vec::new()
3221 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3222 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3223 short_channel_id: 3,
3226 cltv_expiry_delta: 0,
3227 htlc_minimum_msat: 0,
3228 htlc_maximum_msat: OptionalField::Present(50_000),
3230 fee_proportional_millionths: 0,
3231 excess_data: Vec::new()
3234 // Path via node7 is channels {12, 13}. Limit them to 60 and 60 sats
3235 // (total limit 60).
3236 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3237 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3238 short_channel_id: 12,
3241 cltv_expiry_delta: 0,
3242 htlc_minimum_msat: 0,
3243 htlc_maximum_msat: OptionalField::Present(60_000),
3245 fee_proportional_millionths: 0,
3246 excess_data: Vec::new()
3248 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
3249 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3250 short_channel_id: 13,
3253 cltv_expiry_delta: 0,
3254 htlc_minimum_msat: 0,
3255 htlc_maximum_msat: OptionalField::Present(60_000),
3257 fee_proportional_millionths: 0,
3258 excess_data: Vec::new()
3261 // Path via node1 is channels {2, 4}. Limit them to 200 and 180 sats
3262 // (total capacity 180 sats).
3263 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3264 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3265 short_channel_id: 2,
3268 cltv_expiry_delta: 0,
3269 htlc_minimum_msat: 0,
3270 htlc_maximum_msat: OptionalField::Present(200_000),
3272 fee_proportional_millionths: 0,
3273 excess_data: Vec::new()
3275 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
3276 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3277 short_channel_id: 4,
3280 cltv_expiry_delta: 0,
3281 htlc_minimum_msat: 0,
3282 htlc_maximum_msat: OptionalField::Present(180_000),
3284 fee_proportional_millionths: 0,
3285 excess_data: Vec::new()
3289 // Attempt to route more than available results in a failure.
3290 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id, &net_graph_msg_handler.network_graph,
3291 &nodes[2], Some(InvoiceFeatures::known()), None, &Vec::new(), 300_000, 42, Arc::clone(&logger)) {
3292 assert_eq!(err, "Failed to find a sufficient route to the given destination");
3293 } else { panic!(); }
3297 // Now, attempt to route 250 sats (just a bit below the capacity).
3298 // Our algorithm should provide us with these 3 paths.
3299 let route = get_route(&our_id, &net_graph_msg_handler.network_graph, &nodes[2],
3300 Some(InvoiceFeatures::known()), None, &Vec::new(), 250_000, 42, Arc::clone(&logger)).unwrap();
3301 assert_eq!(route.paths.len(), 3);
3302 let mut total_amount_paid_msat = 0;
3303 for path in &route.paths {
3304 assert_eq!(path.len(), 2);
3305 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
3306 total_amount_paid_msat += path.last().unwrap().fee_msat;
3308 assert_eq!(total_amount_paid_msat, 250_000);
3312 // Attempt to route an exact amount is also fine
3313 let route = get_route(&our_id, &net_graph_msg_handler.network_graph, &nodes[2],
3314 Some(InvoiceFeatures::known()), None, &Vec::new(), 290_000, 42, Arc::clone(&logger)).unwrap();
3315 assert_eq!(route.paths.len(), 3);
3316 let mut total_amount_paid_msat = 0;
3317 for path in &route.paths {
3318 assert_eq!(path.len(), 2);
3319 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
3320 total_amount_paid_msat += path.last().unwrap().fee_msat;
3322 assert_eq!(total_amount_paid_msat, 290_000);
3327 fn long_mpp_route_test() {
3328 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
3329 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3331 // We need a route consisting of 3 paths:
3332 // From our node to node3 via {node0, node2}, {node7, node2, node4} and {node7, node2}.
3333 // Note that these paths overlap (channels 5, 12, 13).
3334 // We will route 300 sats.
3335 // Each path will have 100 sats capacity, those channels which
3336 // are used twice will have 200 sats capacity.
3338 // Disable other potential paths.
3339 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3340 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3341 short_channel_id: 2,
3344 cltv_expiry_delta: 0,
3345 htlc_minimum_msat: 0,
3346 htlc_maximum_msat: OptionalField::Present(100_000),
3348 fee_proportional_millionths: 0,
3349 excess_data: Vec::new()
3351 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3352 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3353 short_channel_id: 7,
3356 cltv_expiry_delta: 0,
3357 htlc_minimum_msat: 0,
3358 htlc_maximum_msat: OptionalField::Present(100_000),
3360 fee_proportional_millionths: 0,
3361 excess_data: Vec::new()
3364 // Path via {node0, node2} is channels {1, 3, 5}.
3365 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3366 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3367 short_channel_id: 1,
3370 cltv_expiry_delta: 0,
3371 htlc_minimum_msat: 0,
3372 htlc_maximum_msat: OptionalField::Present(100_000),
3374 fee_proportional_millionths: 0,
3375 excess_data: Vec::new()
3377 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3378 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3379 short_channel_id: 3,
3382 cltv_expiry_delta: 0,
3383 htlc_minimum_msat: 0,
3384 htlc_maximum_msat: OptionalField::Present(100_000),
3386 fee_proportional_millionths: 0,
3387 excess_data: Vec::new()
3390 // Capacity of 200 sats because this channel will be used by 3rd path as well.
3391 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(5)), 5);
3392 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3393 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3394 short_channel_id: 5,
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 // Path via {node7, node2, node4} is channels {12, 13, 6, 11}.
3406 // Add 100 sats to the capacities of {12, 13}, because these channels
3407 // are also used for 3rd path. 100 sats for the rest. Total capacity: 100 sats.
3408 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3409 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3410 short_channel_id: 12,
3413 cltv_expiry_delta: 0,
3414 htlc_minimum_msat: 0,
3415 htlc_maximum_msat: OptionalField::Present(200_000),
3417 fee_proportional_millionths: 0,
3418 excess_data: Vec::new()
3420 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
3421 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3422 short_channel_id: 13,
3425 cltv_expiry_delta: 0,
3426 htlc_minimum_msat: 0,
3427 htlc_maximum_msat: OptionalField::Present(200_000),
3429 fee_proportional_millionths: 0,
3430 excess_data: Vec::new()
3433 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3434 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3435 short_channel_id: 6,
3438 cltv_expiry_delta: 0,
3439 htlc_minimum_msat: 0,
3440 htlc_maximum_msat: OptionalField::Present(100_000),
3442 fee_proportional_millionths: 0,
3443 excess_data: Vec::new()
3445 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
3446 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3447 short_channel_id: 11,
3450 cltv_expiry_delta: 0,
3451 htlc_minimum_msat: 0,
3452 htlc_maximum_msat: OptionalField::Present(100_000),
3454 fee_proportional_millionths: 0,
3455 excess_data: Vec::new()
3458 // Path via {node7, node2} is channels {12, 13, 5}.
3459 // We already limited them to 200 sats (they are used twice for 100 sats).
3460 // Nothing to do here.
3463 // Attempt to route more than available results in a failure.
3464 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id, &net_graph_msg_handler.network_graph, &nodes[3],
3465 Some(InvoiceFeatures::known()), None, &Vec::new(), 350_000, 42, Arc::clone(&logger)) {
3466 assert_eq!(err, "Failed to find a sufficient route to the given destination");
3467 } else { panic!(); }
3471 // Now, attempt to route 300 sats (exact amount we can route).
3472 // Our algorithm should provide us with these 3 paths, 100 sats each.
3473 let route = get_route(&our_id, &net_graph_msg_handler.network_graph, &nodes[3],
3474 Some(InvoiceFeatures::known()), None, &Vec::new(), 300_000, 42, Arc::clone(&logger)).unwrap();
3475 assert_eq!(route.paths.len(), 3);
3477 let mut total_amount_paid_msat = 0;
3478 for path in &route.paths {
3479 assert_eq!(path.last().unwrap().pubkey, nodes[3]);
3480 total_amount_paid_msat += path.last().unwrap().fee_msat;
3482 assert_eq!(total_amount_paid_msat, 300_000);
3488 fn mpp_cheaper_route_test() {
3489 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
3490 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3492 // This test checks that if we have two cheaper paths and one more expensive path,
3493 // so that liquidity-wise any 2 of 3 combination is sufficient,
3494 // two cheaper paths will be taken.
3495 // These paths have equal available liquidity.
3497 // We need a combination of 3 paths:
3498 // From our node to node3 via {node0, node2}, {node7, node2, node4} and {node7, node2}.
3499 // Note that these paths overlap (channels 5, 12, 13).
3500 // Each path will have 100 sats capacity, those channels which
3501 // are used twice will have 200 sats capacity.
3503 // Disable other potential paths.
3504 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3505 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3506 short_channel_id: 2,
3509 cltv_expiry_delta: 0,
3510 htlc_minimum_msat: 0,
3511 htlc_maximum_msat: OptionalField::Present(100_000),
3513 fee_proportional_millionths: 0,
3514 excess_data: Vec::new()
3516 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3517 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3518 short_channel_id: 7,
3521 cltv_expiry_delta: 0,
3522 htlc_minimum_msat: 0,
3523 htlc_maximum_msat: OptionalField::Present(100_000),
3525 fee_proportional_millionths: 0,
3526 excess_data: Vec::new()
3529 // Path via {node0, node2} is channels {1, 3, 5}.
3530 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3531 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3532 short_channel_id: 1,
3535 cltv_expiry_delta: 0,
3536 htlc_minimum_msat: 0,
3537 htlc_maximum_msat: OptionalField::Present(100_000),
3539 fee_proportional_millionths: 0,
3540 excess_data: Vec::new()
3542 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3543 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3544 short_channel_id: 3,
3547 cltv_expiry_delta: 0,
3548 htlc_minimum_msat: 0,
3549 htlc_maximum_msat: OptionalField::Present(100_000),
3551 fee_proportional_millionths: 0,
3552 excess_data: Vec::new()
3555 // Capacity of 200 sats because this channel will be used by 3rd path as well.
3556 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(5)), 5);
3557 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3558 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3559 short_channel_id: 5,
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 // Path via {node7, node2, node4} is channels {12, 13, 6, 11}.
3571 // Add 100 sats to the capacities of {12, 13}, because these channels
3572 // are also used for 3rd path. 100 sats for the rest. Total capacity: 100 sats.
3573 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3574 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3575 short_channel_id: 12,
3578 cltv_expiry_delta: 0,
3579 htlc_minimum_msat: 0,
3580 htlc_maximum_msat: OptionalField::Present(200_000),
3582 fee_proportional_millionths: 0,
3583 excess_data: Vec::new()
3585 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
3586 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3587 short_channel_id: 13,
3590 cltv_expiry_delta: 0,
3591 htlc_minimum_msat: 0,
3592 htlc_maximum_msat: OptionalField::Present(200_000),
3594 fee_proportional_millionths: 0,
3595 excess_data: Vec::new()
3598 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3599 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3600 short_channel_id: 6,
3603 cltv_expiry_delta: 0,
3604 htlc_minimum_msat: 0,
3605 htlc_maximum_msat: OptionalField::Present(100_000),
3606 fee_base_msat: 1_000,
3607 fee_proportional_millionths: 0,
3608 excess_data: Vec::new()
3610 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
3611 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3612 short_channel_id: 11,
3615 cltv_expiry_delta: 0,
3616 htlc_minimum_msat: 0,
3617 htlc_maximum_msat: OptionalField::Present(100_000),
3619 fee_proportional_millionths: 0,
3620 excess_data: Vec::new()
3623 // Path via {node7, node2} is channels {12, 13, 5}.
3624 // We already limited them to 200 sats (they are used twice for 100 sats).
3625 // Nothing to do here.
3628 // Now, attempt to route 180 sats.
3629 // Our algorithm should provide us with these 2 paths.
3630 let route = get_route(&our_id, &net_graph_msg_handler.network_graph, &nodes[3],
3631 Some(InvoiceFeatures::known()), None, &Vec::new(), 180_000, 42, Arc::clone(&logger)).unwrap();
3632 assert_eq!(route.paths.len(), 2);
3634 let mut total_value_transferred_msat = 0;
3635 let mut total_paid_msat = 0;
3636 for path in &route.paths {
3637 assert_eq!(path.last().unwrap().pubkey, nodes[3]);
3638 total_value_transferred_msat += path.last().unwrap().fee_msat;
3640 total_paid_msat += hop.fee_msat;
3643 // If we paid fee, this would be higher.
3644 assert_eq!(total_value_transferred_msat, 180_000);
3645 let total_fees_paid = total_paid_msat - total_value_transferred_msat;
3646 assert_eq!(total_fees_paid, 0);
3651 fn fees_on_mpp_route_test() {
3652 // This test makes sure that MPP algorithm properly takes into account
3653 // fees charged on the channels, by making the fees impactful:
3654 // if the fee is not properly accounted for, the behavior is different.
3655 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
3656 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3658 // We need a route consisting of 2 paths:
3659 // From our node to node3 via {node0, node2} and {node7, node2, node4}.
3660 // We will route 200 sats, Each path will have 100 sats capacity.
3662 // This test is not particularly stable: e.g.,
3663 // there's a way to route via {node0, node2, node4}.
3664 // It works while pathfinding is deterministic, but can be broken otherwise.
3665 // It's fine to ignore this concern for now.
3667 // Disable other potential paths.
3668 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3669 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3670 short_channel_id: 2,
3673 cltv_expiry_delta: 0,
3674 htlc_minimum_msat: 0,
3675 htlc_maximum_msat: OptionalField::Present(100_000),
3677 fee_proportional_millionths: 0,
3678 excess_data: Vec::new()
3681 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3682 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3683 short_channel_id: 7,
3686 cltv_expiry_delta: 0,
3687 htlc_minimum_msat: 0,
3688 htlc_maximum_msat: OptionalField::Present(100_000),
3690 fee_proportional_millionths: 0,
3691 excess_data: Vec::new()
3694 // Path via {node0, node2} is channels {1, 3, 5}.
3695 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3696 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3697 short_channel_id: 1,
3700 cltv_expiry_delta: 0,
3701 htlc_minimum_msat: 0,
3702 htlc_maximum_msat: OptionalField::Present(100_000),
3704 fee_proportional_millionths: 0,
3705 excess_data: Vec::new()
3707 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3708 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3709 short_channel_id: 3,
3712 cltv_expiry_delta: 0,
3713 htlc_minimum_msat: 0,
3714 htlc_maximum_msat: OptionalField::Present(100_000),
3716 fee_proportional_millionths: 0,
3717 excess_data: Vec::new()
3720 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(5)), 5);
3721 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3722 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3723 short_channel_id: 5,
3726 cltv_expiry_delta: 0,
3727 htlc_minimum_msat: 0,
3728 htlc_maximum_msat: OptionalField::Present(100_000),
3730 fee_proportional_millionths: 0,
3731 excess_data: Vec::new()
3734 // Path via {node7, node2, node4} is channels {12, 13, 6, 11}.
3735 // All channels should be 100 sats capacity. But for the fee experiment,
3736 // we'll add absolute fee of 150 sats paid for the use channel 6 (paid to node2 on channel 13).
3737 // Since channel 12 allows to deliver only 250 sats to channel 13, channel 13 can transfer only
3738 // 100 sats (and pay 150 sats in fees for the use of channel 6),
3739 // so no matter how large are other channels,
3740 // the whole path will be limited by 100 sats with just these 2 conditions:
3741 // - channel 12 capacity is 250 sats
3742 // - fee for channel 6 is 150 sats
3743 // Let's test this by enforcing these 2 conditions and removing other limits.
3744 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3745 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3746 short_channel_id: 12,
3749 cltv_expiry_delta: 0,
3750 htlc_minimum_msat: 0,
3751 htlc_maximum_msat: OptionalField::Present(250_000),
3753 fee_proportional_millionths: 0,
3754 excess_data: Vec::new()
3756 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
3757 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3758 short_channel_id: 13,
3761 cltv_expiry_delta: 0,
3762 htlc_minimum_msat: 0,
3763 htlc_maximum_msat: OptionalField::Absent,
3765 fee_proportional_millionths: 0,
3766 excess_data: Vec::new()
3769 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3770 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3771 short_channel_id: 6,
3774 cltv_expiry_delta: 0,
3775 htlc_minimum_msat: 0,
3776 htlc_maximum_msat: OptionalField::Absent,
3777 fee_base_msat: 150_000,
3778 fee_proportional_millionths: 0,
3779 excess_data: Vec::new()
3781 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
3782 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3783 short_channel_id: 11,
3786 cltv_expiry_delta: 0,
3787 htlc_minimum_msat: 0,
3788 htlc_maximum_msat: OptionalField::Absent,
3790 fee_proportional_millionths: 0,
3791 excess_data: Vec::new()
3795 // Attempt to route more than available results in a failure.
3796 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id, &net_graph_msg_handler.network_graph, &nodes[3],
3797 Some(InvoiceFeatures::known()), None, &Vec::new(), 210_000, 42, Arc::clone(&logger)) {
3798 assert_eq!(err, "Failed to find a sufficient route to the given destination");
3799 } else { panic!(); }
3803 // Now, attempt to route 200 sats (exact amount we can route).
3804 let route = get_route(&our_id, &net_graph_msg_handler.network_graph, &nodes[3],
3805 Some(InvoiceFeatures::known()), None, &Vec::new(), 200_000, 42, Arc::clone(&logger)).unwrap();
3806 assert_eq!(route.paths.len(), 2);
3808 let mut total_amount_paid_msat = 0;
3809 for path in &route.paths {
3810 assert_eq!(path.last().unwrap().pubkey, nodes[3]);
3811 total_amount_paid_msat += path.last().unwrap().fee_msat;
3813 assert_eq!(total_amount_paid_msat, 200_000);
3814 assert_eq!(route.get_total_fees(), 150_000);
3820 fn drop_lowest_channel_mpp_route_test() {
3821 // This test checks that low-capacity channel is dropped when after
3822 // path finding we realize that we found more capacity than we need.
3823 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
3824 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3826 // We need a route consisting of 3 paths:
3827 // From our node to node2 via node0, node7, node1 (three paths one hop each).
3829 // The first and the second paths should be sufficient, but the third should be
3830 // cheaper, so that we select it but drop later.
3832 // First, we set limits on these (previously unlimited) channels.
3833 // Their aggregate capacity will be 50 + 60 + 20 = 130 sats.
3835 // Path via node0 is channels {1, 3}. Limit them to 100 and 50 sats (total limit 50);
3836 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3837 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3838 short_channel_id: 1,
3841 cltv_expiry_delta: 0,
3842 htlc_minimum_msat: 0,
3843 htlc_maximum_msat: OptionalField::Present(100_000),
3845 fee_proportional_millionths: 0,
3846 excess_data: Vec::new()
3848 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3849 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3850 short_channel_id: 3,
3853 cltv_expiry_delta: 0,
3854 htlc_minimum_msat: 0,
3855 htlc_maximum_msat: OptionalField::Present(50_000),
3857 fee_proportional_millionths: 0,
3858 excess_data: Vec::new()
3861 // Path via node7 is channels {12, 13}. Limit them to 60 and 60 sats (total limit 60);
3862 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3863 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3864 short_channel_id: 12,
3867 cltv_expiry_delta: 0,
3868 htlc_minimum_msat: 0,
3869 htlc_maximum_msat: OptionalField::Present(60_000),
3871 fee_proportional_millionths: 0,
3872 excess_data: Vec::new()
3874 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
3875 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3876 short_channel_id: 13,
3879 cltv_expiry_delta: 0,
3880 htlc_minimum_msat: 0,
3881 htlc_maximum_msat: OptionalField::Present(60_000),
3883 fee_proportional_millionths: 0,
3884 excess_data: Vec::new()
3887 // Path via node1 is channels {2, 4}. Limit them to 20 and 20 sats (total capacity 20 sats).
3888 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3889 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3890 short_channel_id: 2,
3893 cltv_expiry_delta: 0,
3894 htlc_minimum_msat: 0,
3895 htlc_maximum_msat: OptionalField::Present(20_000),
3897 fee_proportional_millionths: 0,
3898 excess_data: Vec::new()
3900 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
3901 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3902 short_channel_id: 4,
3905 cltv_expiry_delta: 0,
3906 htlc_minimum_msat: 0,
3907 htlc_maximum_msat: OptionalField::Present(20_000),
3909 fee_proportional_millionths: 0,
3910 excess_data: Vec::new()
3914 // Attempt to route more than available results in a failure.
3915 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id, &net_graph_msg_handler.network_graph, &nodes[2],
3916 Some(InvoiceFeatures::known()), None, &Vec::new(), 150_000, 42, Arc::clone(&logger)) {
3917 assert_eq!(err, "Failed to find a sufficient route to the given destination");
3918 } else { panic!(); }
3922 // Now, attempt to route 125 sats (just a bit below the capacity of 3 channels).
3923 // Our algorithm should provide us with these 3 paths.
3924 let route = get_route(&our_id, &net_graph_msg_handler.network_graph, &nodes[2],
3925 Some(InvoiceFeatures::known()), None, &Vec::new(), 125_000, 42, Arc::clone(&logger)).unwrap();
3926 assert_eq!(route.paths.len(), 3);
3927 let mut total_amount_paid_msat = 0;
3928 for path in &route.paths {
3929 assert_eq!(path.len(), 2);
3930 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
3931 total_amount_paid_msat += path.last().unwrap().fee_msat;
3933 assert_eq!(total_amount_paid_msat, 125_000);
3937 // Attempt to route without the last small cheap channel
3938 let route = get_route(&our_id, &net_graph_msg_handler.network_graph, &nodes[2],
3939 Some(InvoiceFeatures::known()), None, &Vec::new(), 90_000, 42, Arc::clone(&logger)).unwrap();
3940 assert_eq!(route.paths.len(), 2);
3941 let mut total_amount_paid_msat = 0;
3942 for path in &route.paths {
3943 assert_eq!(path.len(), 2);
3944 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
3945 total_amount_paid_msat += path.last().unwrap().fee_msat;
3947 assert_eq!(total_amount_paid_msat, 90_000);
3952 fn min_criteria_consistency() {
3953 // Test that we don't use an inconsistent metric between updating and walking nodes during
3954 // our Dijkstra's pass. In the initial version of MPP, the "best source" for a given node
3955 // was updated with a different criterion from the heap sorting, resulting in loops in
3956 // calculated paths. We test for that specific case here.
3958 // We construct a network that looks like this:
3960 // node2 -1(3)2- node3
3964 // node1 -1(5)2- node4 -1(1)2- node6
3970 // We create a loop on the side of our real path - our destination is node 6, with a
3971 // previous hop of node 4. From 4, the cheapest previous path is channel 2 from node 2,
3972 // followed by node 3 over channel 3. Thereafter, the cheapest next-hop is back to node 4
3973 // (this time over channel 4). Channel 4 has 0 htlc_minimum_msat whereas channel 1 (the
3974 // other channel with a previous-hop of node 4) has a high (but irrelevant to the overall
3975 // payment) htlc_minimum_msat. In the original algorithm, this resulted in node4's
3976 // "previous hop" being set to node 3, creating a loop in the path.
3977 let secp_ctx = Secp256k1::new();
3978 let logger = Arc::new(test_utils::TestLogger::new());
3979 let network_graph = NetworkGraph::new(genesis_block(Network::Testnet).header.block_hash());
3980 let net_graph_msg_handler = NetGraphMsgHandler::new(network_graph, None, Arc::clone(&logger));
3981 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3983 add_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, &privkeys[1], ChannelFeatures::from_le_bytes(id_to_feature_flags(6)), 6);
3984 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3985 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3986 short_channel_id: 6,
3989 cltv_expiry_delta: (6 << 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[1], NodeFeatures::from_le_bytes(id_to_feature_flags(1)), 0);
3998 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], &privkeys[4], ChannelFeatures::from_le_bytes(id_to_feature_flags(5)), 5);
3999 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
4000 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4001 short_channel_id: 5,
4004 cltv_expiry_delta: (5 << 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[4], NodeFeatures::from_le_bytes(id_to_feature_flags(4)), 0);
4013 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(4)), 4);
4014 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
4015 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4016 short_channel_id: 4,
4019 cltv_expiry_delta: (4 << 8) | 0,
4020 htlc_minimum_msat: 0,
4021 htlc_maximum_msat: OptionalField::Absent,
4023 fee_proportional_millionths: 0,
4024 excess_data: Vec::new()
4026 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[3], NodeFeatures::from_le_bytes(id_to_feature_flags(3)), 0);
4028 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[3], &privkeys[2], ChannelFeatures::from_le_bytes(id_to_feature_flags(3)), 3);
4029 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[3], UnsignedChannelUpdate {
4030 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4031 short_channel_id: 3,
4034 cltv_expiry_delta: (3 << 8) | 0,
4035 htlc_minimum_msat: 0,
4036 htlc_maximum_msat: OptionalField::Absent,
4038 fee_proportional_millionths: 0,
4039 excess_data: Vec::new()
4041 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[2], NodeFeatures::from_le_bytes(id_to_feature_flags(2)), 0);
4043 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], &privkeys[4], ChannelFeatures::from_le_bytes(id_to_feature_flags(2)), 2);
4044 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4045 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4046 short_channel_id: 2,
4049 cltv_expiry_delta: (2 << 8) | 0,
4050 htlc_minimum_msat: 0,
4051 htlc_maximum_msat: OptionalField::Absent,
4053 fee_proportional_millionths: 0,
4054 excess_data: Vec::new()
4057 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], &privkeys[6], ChannelFeatures::from_le_bytes(id_to_feature_flags(1)), 1);
4058 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
4059 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4060 short_channel_id: 1,
4063 cltv_expiry_delta: (1 << 8) | 0,
4064 htlc_minimum_msat: 100,
4065 htlc_maximum_msat: OptionalField::Absent,
4067 fee_proportional_millionths: 0,
4068 excess_data: Vec::new()
4070 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[6], NodeFeatures::from_le_bytes(id_to_feature_flags(6)), 0);
4073 // Now ensure the route flows simply over nodes 1 and 4 to 6.
4074 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();
4075 assert_eq!(route.paths.len(), 1);
4076 assert_eq!(route.paths[0].len(), 3);
4078 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
4079 assert_eq!(route.paths[0][0].short_channel_id, 6);
4080 assert_eq!(route.paths[0][0].fee_msat, 100);
4081 assert_eq!(route.paths[0][0].cltv_expiry_delta, (5 << 8) | 0);
4082 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(1));
4083 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(6));
4085 assert_eq!(route.paths[0][1].pubkey, nodes[4]);
4086 assert_eq!(route.paths[0][1].short_channel_id, 5);
4087 assert_eq!(route.paths[0][1].fee_msat, 0);
4088 assert_eq!(route.paths[0][1].cltv_expiry_delta, (1 << 8) | 0);
4089 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(4));
4090 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(5));
4092 assert_eq!(route.paths[0][2].pubkey, nodes[6]);
4093 assert_eq!(route.paths[0][2].short_channel_id, 1);
4094 assert_eq!(route.paths[0][2].fee_msat, 10_000);
4095 assert_eq!(route.paths[0][2].cltv_expiry_delta, 42);
4096 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(6));
4097 assert_eq!(route.paths[0][2].channel_features.le_flags(), &id_to_feature_flags(1));
4103 fn exact_fee_liquidity_limit() {
4104 // Test that if, while walking the graph, we find a hop that has exactly enough liquidity
4105 // for us, including later hop fees, we take it. In the first version of our MPP algorithm
4106 // we calculated fees on a higher value, resulting in us ignoring such paths.
4107 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
4108 let (our_privkey, our_id, _, nodes) = get_nodes(&secp_ctx);
4110 // We modify the graph to set the htlc_maximum of channel 2 to below the value we wish to
4112 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4113 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4114 short_channel_id: 2,
4117 cltv_expiry_delta: 0,
4118 htlc_minimum_msat: 0,
4119 htlc_maximum_msat: OptionalField::Present(85_000),
4121 fee_proportional_millionths: 0,
4122 excess_data: Vec::new()
4125 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4126 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4127 short_channel_id: 12,
4130 cltv_expiry_delta: (4 << 8) | 1,
4131 htlc_minimum_msat: 0,
4132 htlc_maximum_msat: OptionalField::Present(270_000),
4134 fee_proportional_millionths: 1000000,
4135 excess_data: Vec::new()
4139 // Now, attempt to route 90 sats, which is exactly 90 sats at the last hop, plus the
4140 // 200% fee charged channel 13 in the 1-to-2 direction.
4141 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();
4142 assert_eq!(route.paths.len(), 1);
4143 assert_eq!(route.paths[0].len(), 2);
4145 assert_eq!(route.paths[0][0].pubkey, nodes[7]);
4146 assert_eq!(route.paths[0][0].short_channel_id, 12);
4147 assert_eq!(route.paths[0][0].fee_msat, 90_000*2);
4148 assert_eq!(route.paths[0][0].cltv_expiry_delta, (13 << 8) | 1);
4149 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(8));
4150 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(12));
4152 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
4153 assert_eq!(route.paths[0][1].short_channel_id, 13);
4154 assert_eq!(route.paths[0][1].fee_msat, 90_000);
4155 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
4156 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
4157 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(13));
4162 fn htlc_max_reduction_below_min() {
4163 // Test that if, while walking the graph, we reduce the value being sent to meet an
4164 // htlc_maximum_msat, we don't end up undershooting a later htlc_minimum_msat. In the
4165 // initial version of MPP we'd accept such routes but reject them while recalculating fees,
4166 // resulting in us thinking there is no possible path, even if other paths exist.
4167 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
4168 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
4170 // We modify the graph to set the htlc_minimum of channel 2 and 4 as needed - channel 2
4171 // gets an htlc_maximum_msat of 80_000 and channel 4 an htlc_minimum_msat of 90_000. We
4172 // then try to send 90_000.
4173 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4174 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4175 short_channel_id: 2,
4178 cltv_expiry_delta: 0,
4179 htlc_minimum_msat: 0,
4180 htlc_maximum_msat: OptionalField::Present(80_000),
4182 fee_proportional_millionths: 0,
4183 excess_data: Vec::new()
4185 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
4186 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4187 short_channel_id: 4,
4190 cltv_expiry_delta: (4 << 8) | 1,
4191 htlc_minimum_msat: 90_000,
4192 htlc_maximum_msat: OptionalField::Absent,
4194 fee_proportional_millionths: 0,
4195 excess_data: Vec::new()
4199 // Now, attempt to route 90 sats, hitting the htlc_minimum on channel 4, but
4200 // overshooting the htlc_maximum on channel 2. Thus, we should pick the (absurdly
4201 // expensive) channels 12-13 path.
4202 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();
4203 assert_eq!(route.paths.len(), 1);
4204 assert_eq!(route.paths[0].len(), 2);
4206 assert_eq!(route.paths[0][0].pubkey, nodes[7]);
4207 assert_eq!(route.paths[0][0].short_channel_id, 12);
4208 assert_eq!(route.paths[0][0].fee_msat, 90_000*2);
4209 assert_eq!(route.paths[0][0].cltv_expiry_delta, (13 << 8) | 1);
4210 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(8));
4211 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(12));
4213 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
4214 assert_eq!(route.paths[0][1].short_channel_id, 13);
4215 assert_eq!(route.paths[0][1].fee_msat, 90_000);
4216 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
4217 assert_eq!(route.paths[0][1].node_features.le_flags(), InvoiceFeatures::known().le_flags());
4218 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(13));
4223 fn total_fees_single_path() {
4227 pubkey: PublicKey::from_slice(&hex::decode("02eec7245d6b7d2ccb30380bfbe2a3648cd7a942653f5aa340edcea1f283686619").unwrap()[..]).unwrap(),
4228 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
4229 short_channel_id: 0, fee_msat: 100, cltv_expiry_delta: 0 // Test vectors are garbage and not generateble from a RouteHop, we fill in payloads manually
4232 pubkey: PublicKey::from_slice(&hex::decode("0324653eac434488002cc06bbfb7f10fe18991e35f9fe4302dbea6d2353dc0ab1c").unwrap()[..]).unwrap(),
4233 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
4234 short_channel_id: 0, fee_msat: 150, cltv_expiry_delta: 0 // Test vectors are garbage and not generateble from a RouteHop, we fill in payloads manually
4237 pubkey: PublicKey::from_slice(&hex::decode("027f31ebc5462c1fdce1b737ecff52d37d75dea43ce11c74d25aa297165faa2007").unwrap()[..]).unwrap(),
4238 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
4239 short_channel_id: 0, fee_msat: 225, cltv_expiry_delta: 0 // Test vectors are garbage and not generateble from a RouteHop, we fill in payloads manually
4244 assert_eq!(route.get_total_fees(), 250);
4245 assert_eq!(route.get_total_amount(), 225);
4249 fn total_fees_multi_path() {
4253 pubkey: PublicKey::from_slice(&hex::decode("02eec7245d6b7d2ccb30380bfbe2a3648cd7a942653f5aa340edcea1f283686619").unwrap()[..]).unwrap(),
4254 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
4255 short_channel_id: 0, fee_msat: 100, cltv_expiry_delta: 0 // Test vectors are garbage and not generateble from a RouteHop, we fill in payloads manually
4258 pubkey: PublicKey::from_slice(&hex::decode("0324653eac434488002cc06bbfb7f10fe18991e35f9fe4302dbea6d2353dc0ab1c").unwrap()[..]).unwrap(),
4259 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
4260 short_channel_id: 0, fee_msat: 150, cltv_expiry_delta: 0 // Test vectors are garbage and not generateble from a RouteHop, we fill in payloads manually
4264 pubkey: PublicKey::from_slice(&hex::decode("02eec7245d6b7d2ccb30380bfbe2a3648cd7a942653f5aa340edcea1f283686619").unwrap()[..]).unwrap(),
4265 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
4266 short_channel_id: 0, fee_msat: 100, cltv_expiry_delta: 0 // Test vectors are garbage and not generateble from a RouteHop, we fill in payloads manually
4269 pubkey: PublicKey::from_slice(&hex::decode("0324653eac434488002cc06bbfb7f10fe18991e35f9fe4302dbea6d2353dc0ab1c").unwrap()[..]).unwrap(),
4270 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
4271 short_channel_id: 0, fee_msat: 150, cltv_expiry_delta: 0 // Test vectors are garbage and not generateble from a RouteHop, we fill in payloads manually
4276 assert_eq!(route.get_total_fees(), 200);
4277 assert_eq!(route.get_total_amount(), 300);
4280 #[cfg(not(feature = "no-std"))]
4281 pub(super) fn random_init_seed() -> u64 {
4282 // Because the default HashMap in std pulls OS randomness, we can use it as a (bad) RNG.
4283 use core::hash::{BuildHasher, Hasher};
4284 let seed = std::collections::hash_map::RandomState::new().build_hasher().finish();
4285 println!("Using seed of {}", seed);
4288 #[cfg(not(feature = "no-std"))]
4289 use util::ser::Readable;
4292 #[cfg(not(feature = "no-std"))]
4293 fn generate_routes() {
4294 let mut d = match super::test_utils::get_route_file() {
4301 let graph = NetworkGraph::read(&mut d).unwrap();
4303 // First, get 100 (source, destination) pairs for which route-getting actually succeeds...
4304 let mut seed = random_init_seed() as usize;
4305 let nodes = graph.read_only().nodes().clone();
4306 'load_endpoints: for _ in 0..10 {
4308 seed = seed.overflowing_mul(0xdeadbeef).0;
4309 let src = nodes.keys().skip(seed % nodes.len()).next().unwrap();
4310 seed = seed.overflowing_mul(0xdeadbeef).0;
4311 let dst = nodes.keys().skip(seed % nodes.len()).next().unwrap();
4312 let amt = seed as u64 % 200_000_000;
4313 if get_route(src, &graph, dst, None, None, &[], amt, 42, &test_utils::TestLogger::new()).is_ok() {
4314 continue 'load_endpoints;
4321 #[cfg(not(feature = "no-std"))]
4322 fn generate_routes_mpp() {
4323 let mut d = match super::test_utils::get_route_file() {
4330 let graph = NetworkGraph::read(&mut d).unwrap();
4332 // First, get 100 (source, destination) pairs for which route-getting actually succeeds...
4333 let mut seed = random_init_seed() as usize;
4334 let nodes = graph.read_only().nodes().clone();
4335 'load_endpoints: for _ in 0..10 {
4337 seed = seed.overflowing_mul(0xdeadbeef).0;
4338 let src = nodes.keys().skip(seed % nodes.len()).next().unwrap();
4339 seed = seed.overflowing_mul(0xdeadbeef).0;
4340 let dst = nodes.keys().skip(seed % nodes.len()).next().unwrap();
4341 let amt = seed as u64 % 200_000_000;
4342 if get_route(src, &graph, dst, Some(InvoiceFeatures::known()), None, &[], amt, 42, &test_utils::TestLogger::new()).is_ok() {
4343 continue 'load_endpoints;
4350 #[cfg(all(test, not(feature = "no-std")))]
4351 pub(crate) mod test_utils {
4353 /// Tries to open a network graph file, or panics with a URL to fetch it.
4354 pub(crate) fn get_route_file() -> Result<std::fs::File, &'static str> {
4355 let res = File::open("net_graph-2021-05-31.bin") // By default we're run in RL/lightning
4356 .or_else(|_| File::open("lightning/net_graph-2021-05-31.bin")) // We may be run manually in RL/
4357 .or_else(|_| { // Fall back to guessing based on the binary location
4358 // path is likely something like .../rust-lightning/target/debug/deps/lightning-...
4359 let mut path = std::env::current_exe().unwrap();
4360 path.pop(); // lightning-...
4362 path.pop(); // debug
4363 path.pop(); // target
4364 path.push("lightning");
4365 path.push("net_graph-2021-05-31.bin");
4366 eprintln!("{}", path.to_str().unwrap());
4369 .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");
4370 #[cfg(require_route_graph_test)]
4371 return Ok(res.unwrap());
4372 #[cfg(not(require_route_graph_test))]
4377 #[cfg(all(test, feature = "unstable", not(feature = "no-std")))]
4380 use util::logger::{Logger, Record};
4384 struct DummyLogger {}
4385 impl Logger for DummyLogger {
4386 fn log(&self, _record: &Record) {}
4390 fn generate_routes(bench: &mut Bencher) {
4391 let mut d = test_utils::get_route_file().unwrap();
4392 let graph = NetworkGraph::read(&mut d).unwrap();
4393 let nodes = graph.read_only().nodes().clone();
4395 // First, get 100 (source, destination) pairs for which route-getting actually succeeds...
4396 let mut path_endpoints = Vec::new();
4397 let mut seed: usize = 0xdeadbeef;
4398 'load_endpoints: for _ in 0..100 {
4401 let src = nodes.keys().skip(seed % nodes.len()).next().unwrap();
4403 let dst = nodes.keys().skip(seed % nodes.len()).next().unwrap();
4404 let amt = seed as u64 % 1_000_000;
4405 if get_route(src, &graph, dst, None, None, &[], amt, 42, &DummyLogger{}).is_ok() {
4406 path_endpoints.push((src, dst, amt));
4407 continue 'load_endpoints;
4412 // ...then benchmark finding paths between the nodes we learned.
4415 let (src, dst, amt) = path_endpoints[idx % path_endpoints.len()];
4416 assert!(get_route(src, &graph, dst, None, None, &[], amt, 42, &DummyLogger{}).is_ok());
4422 fn generate_mpp_routes(bench: &mut Bencher) {
4423 let mut d = test_utils::get_route_file().unwrap();
4424 let graph = NetworkGraph::read(&mut d).unwrap();
4425 let nodes = graph.read_only().nodes().clone();
4427 // First, get 100 (source, destination) pairs for which route-getting actually succeeds...
4428 let mut path_endpoints = Vec::new();
4429 let mut seed: usize = 0xdeadbeef;
4430 'load_endpoints: for _ in 0..100 {
4433 let src = nodes.keys().skip(seed % nodes.len()).next().unwrap();
4435 let dst = nodes.keys().skip(seed % nodes.len()).next().unwrap();
4436 let amt = seed as u64 % 1_000_000;
4437 if get_route(src, &graph, dst, Some(InvoiceFeatures::known()), None, &[], amt, 42, &DummyLogger{}).is_ok() {
4438 path_endpoints.push((src, dst, amt));
4439 continue 'load_endpoints;
4444 // ...then benchmark finding paths between the nodes we learned.
4447 let (src, dst, amt) = path_endpoints[idx % path_endpoints.len()];
4448 assert!(get_route(src, &graph, dst, Some(InvoiceFeatures::known()), None, &[], amt, 42, &DummyLogger{}).is_ok());