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, NodeId};
21 use util::ser::{Writeable, Readable};
22 use util::logger::{Level, 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`].
77 /// This doesn't include any extra payment made to the recipient, which can happen in excess of
78 /// the amount passed to [`get_route`]'s `final_value_msat`.
79 pub fn get_total_fees(&self) -> u64 {
80 // Do not count last hop of each path since that's the full value of the payment
81 return self.paths.iter()
82 .flat_map(|path| path.split_last().map(|(_, path_prefix)| path_prefix).unwrap_or(&[]))
83 .map(|hop| &hop.fee_msat)
87 /// Returns the total amount paid on this [`Route`], excluding the fees.
88 pub fn get_total_amount(&self) -> u64 {
89 return self.paths.iter()
90 .map(|path| path.split_last().map(|(hop, _)| hop.fee_msat).unwrap_or(0))
95 const SERIALIZATION_VERSION: u8 = 1;
96 const MIN_SERIALIZATION_VERSION: u8 = 1;
98 impl Writeable for Route {
99 fn write<W: ::util::ser::Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
100 write_ver_prefix!(writer, SERIALIZATION_VERSION, MIN_SERIALIZATION_VERSION);
101 (self.paths.len() as u64).write(writer)?;
102 for hops in self.paths.iter() {
103 (hops.len() as u8).write(writer)?;
104 for hop in hops.iter() {
108 write_tlv_fields!(writer, {});
113 impl Readable for Route {
114 fn read<R: io::Read>(reader: &mut R) -> Result<Route, DecodeError> {
115 let _ver = read_ver_prefix!(reader, SERIALIZATION_VERSION);
116 let path_count: u64 = Readable::read(reader)?;
117 let mut paths = Vec::with_capacity(cmp::min(path_count, 128) as usize);
118 for _ in 0..path_count {
119 let hop_count: u8 = Readable::read(reader)?;
120 let mut hops = Vec::with_capacity(hop_count as usize);
121 for _ in 0..hop_count {
122 hops.push(Readable::read(reader)?);
126 read_tlv_fields!(reader, {});
131 /// A list of hops along a payment path terminating with a channel to the recipient.
132 #[derive(Clone, Debug, Hash, Eq, PartialEq)]
133 pub struct RouteHint(pub Vec<RouteHintHop>);
135 /// A channel descriptor for a hop along a payment path.
136 #[derive(Clone, Debug, Hash, Eq, PartialEq)]
137 pub struct RouteHintHop {
138 /// The node_id of the non-target end of the route
139 pub src_node_id: PublicKey,
140 /// The short_channel_id of this channel
141 pub short_channel_id: u64,
142 /// The fees which must be paid to use this channel
143 pub fees: RoutingFees,
144 /// The difference in CLTV values between this node and the next node.
145 pub cltv_expiry_delta: u16,
146 /// The minimum value, in msat, which must be relayed to the next hop.
147 pub htlc_minimum_msat: Option<u64>,
148 /// The maximum value in msat available for routing with a single HTLC.
149 pub htlc_maximum_msat: Option<u64>,
152 #[derive(Eq, PartialEq)]
153 struct RouteGraphNode {
155 lowest_fee_to_peer_through_node: u64,
156 lowest_fee_to_node: u64,
157 // The maximum value a yet-to-be-constructed payment path might flow through this node.
158 // This value is upper-bounded by us by:
159 // - how much is needed for a path being constructed
160 // - how much value can channels following this node (up to the destination) can contribute,
161 // considering their capacity and fees
162 value_contribution_msat: u64,
163 /// The effective htlc_minimum_msat at this hop. If a later hop on the path had a higher HTLC
164 /// minimum, we use it, plus the fees required at each earlier hop to meet it.
165 path_htlc_minimum_msat: u64,
168 impl cmp::Ord for RouteGraphNode {
169 fn cmp(&self, other: &RouteGraphNode) -> cmp::Ordering {
170 let other_score = cmp::max(other.lowest_fee_to_peer_through_node, other.path_htlc_minimum_msat);
171 let self_score = cmp::max(self.lowest_fee_to_peer_through_node, self.path_htlc_minimum_msat);
172 other_score.cmp(&self_score).then_with(|| other.node_id.cmp(&self.node_id))
176 impl cmp::PartialOrd for RouteGraphNode {
177 fn partial_cmp(&self, other: &RouteGraphNode) -> Option<cmp::Ordering> {
178 Some(self.cmp(other))
182 struct DummyDirectionalChannelInfo {
183 cltv_expiry_delta: u32,
184 htlc_minimum_msat: u64,
185 htlc_maximum_msat: Option<u64>,
189 /// It's useful to keep track of the hops associated with the fees required to use them,
190 /// so that we can choose cheaper paths (as per Dijkstra's algorithm).
191 /// Fee values should be updated only in the context of the whole path, see update_value_and_recompute_fees.
192 /// These fee values are useful to choose hops as we traverse the graph "payee-to-payer".
193 #[derive(Clone, Debug)]
194 struct PathBuildingHop<'a> {
195 // The RouteHintHop fields which will eventually be used if this hop is used in a final Route.
196 // Note that node_features is calculated separately after our initial graph walk.
198 short_channel_id: u64,
199 channel_features: &'a ChannelFeatures,
201 cltv_expiry_delta: u32,
203 /// Minimal fees required to route to the source node of the current hop via any of its inbound channels.
204 src_lowest_inbound_fees: RoutingFees,
205 /// Fees of the channel used in this hop.
206 channel_fees: RoutingFees,
207 /// All the fees paid *after* this channel on the way to the destination
208 next_hops_fee_msat: u64,
209 /// Fee paid for the use of the current channel (see channel_fees).
210 /// The value will be actually deducted from the counterparty balance on the previous link.
211 hop_use_fee_msat: u64,
212 /// Used to compare channels when choosing the for routing.
213 /// Includes paying for the use of a hop and the following hops, as well as
214 /// an estimated cost of reaching this hop.
215 /// Might get stale when fees are recomputed. Primarily for internal use.
217 /// This is useful for update_value_and_recompute_fees to make sure
218 /// we don't fall below the minimum. Should not be updated manually and
219 /// generally should not be accessed.
220 htlc_minimum_msat: u64,
221 /// A mirror of the same field in RouteGraphNode. Note that this is only used during the graph
222 /// walk and may be invalid thereafter.
223 path_htlc_minimum_msat: u64,
224 /// If we've already processed a node as the best node, we shouldn't process it again. Normally
225 /// we'd just ignore it if we did as all channels would have a higher new fee, but because we
226 /// may decrease the amounts in use as we walk the graph, the actual calculated fee may
227 /// decrease as well. Thus, we have to explicitly track which nodes have been processed and
228 /// avoid processing them again.
230 #[cfg(any(test, feature = "fuzztarget"))]
231 // In tests, we apply further sanity checks on cases where we skip nodes we already processed
232 // to ensure it is specifically in cases where the fee has gone down because of a decrease in
233 // value_contribution_msat, which requires tracking it here. See comments below where it is
234 // used for more info.
235 value_contribution_msat: u64,
238 // Instantiated with a list of hops with correct data in them collected during path finding,
239 // an instance of this struct should be further modified only via given methods.
241 struct PaymentPath<'a> {
242 hops: Vec<(PathBuildingHop<'a>, NodeFeatures)>,
245 impl<'a> PaymentPath<'a> {
246 // TODO: Add a value_msat field to PaymentPath and use it instead of this function.
247 fn get_value_msat(&self) -> u64 {
248 self.hops.last().unwrap().0.fee_msat
251 fn get_total_fee_paid_msat(&self) -> u64 {
252 if self.hops.len() < 1 {
256 // Can't use next_hops_fee_msat because it gets outdated.
257 for (i, (hop, _)) in self.hops.iter().enumerate() {
258 if i != self.hops.len() - 1 {
259 result += hop.fee_msat;
265 // If the amount transferred by the path is updated, the fees should be adjusted. Any other way
266 // to change fees may result in an inconsistency.
268 // Sometimes we call this function right after constructing a path which is inconsistent in
269 // that it the value being transferred has decreased while we were doing path finding, leading
270 // to the fees being paid not lining up with the actual limits.
272 // Note that this function is not aware of the available_liquidity limit, and thus does not
273 // support increasing the value being transferred.
274 fn update_value_and_recompute_fees(&mut self, value_msat: u64) {
275 assert!(value_msat <= self.hops.last().unwrap().0.fee_msat);
277 let mut total_fee_paid_msat = 0 as u64;
278 for i in (0..self.hops.len()).rev() {
279 let last_hop = i == self.hops.len() - 1;
281 // For non-last-hop, this value will represent the fees paid on the current hop. It
282 // will consist of the fees for the use of the next hop, and extra fees to match
283 // htlc_minimum_msat of the current channel. Last hop is handled separately.
284 let mut cur_hop_fees_msat = 0;
286 cur_hop_fees_msat = self.hops.get(i + 1).unwrap().0.hop_use_fee_msat;
289 let mut cur_hop = &mut self.hops.get_mut(i).unwrap().0;
290 cur_hop.next_hops_fee_msat = total_fee_paid_msat;
291 // Overpay in fees if we can't save these funds due to htlc_minimum_msat.
292 // We try to account for htlc_minimum_msat in scoring (add_entry!), so that nodes don't
293 // set it too high just to maliciously take more fees by exploiting this
294 // match htlc_minimum_msat logic.
295 let mut cur_hop_transferred_amount_msat = total_fee_paid_msat + value_msat;
296 if let Some(extra_fees_msat) = cur_hop.htlc_minimum_msat.checked_sub(cur_hop_transferred_amount_msat) {
297 // Note that there is a risk that *previous hops* (those closer to us, as we go
298 // payee->our_node here) would exceed their htlc_maximum_msat or available balance.
300 // This might make us end up with a broken route, although this should be super-rare
301 // in practice, both because of how healthy channels look like, and how we pick
302 // channels in add_entry.
303 // Also, this can't be exploited more heavily than *announce a free path and fail
305 cur_hop_transferred_amount_msat += extra_fees_msat;
306 total_fee_paid_msat += extra_fees_msat;
307 cur_hop_fees_msat += extra_fees_msat;
311 // Final hop is a special case: it usually has just value_msat (by design), but also
312 // it still could overpay for the htlc_minimum_msat.
313 cur_hop.fee_msat = cur_hop_transferred_amount_msat;
315 // Propagate updated fees for the use of the channels to one hop back, where they
316 // will be actually paid (fee_msat). The last hop is handled above separately.
317 cur_hop.fee_msat = cur_hop_fees_msat;
320 // Fee for the use of the current hop which will be deducted on the previous hop.
321 // Irrelevant for the first hop, as it doesn't have the previous hop, and the use of
322 // this channel is free for us.
324 if let Some(new_fee) = compute_fees(cur_hop_transferred_amount_msat, cur_hop.channel_fees) {
325 cur_hop.hop_use_fee_msat = new_fee;
326 total_fee_paid_msat += new_fee;
328 // It should not be possible because this function is called only to reduce the
329 // value. In that case, compute_fee was already called with the same fees for
330 // larger amount and there was no overflow.
338 fn compute_fees(amount_msat: u64, channel_fees: RoutingFees) -> Option<u64> {
339 let proportional_fee_millions =
340 amount_msat.checked_mul(channel_fees.proportional_millionths as u64);
341 if let Some(new_fee) = proportional_fee_millions.and_then(|part| {
342 (channel_fees.base_msat as u64).checked_add(part / 1_000_000) }) {
346 // This function may be (indirectly) called without any verification,
347 // with channel_fees provided by a caller. We should handle it gracefully.
352 /// Gets a keysend route from us (payer) to the given target node (payee). This is needed because
353 /// keysend payments do not have an invoice from which to pull the payee's supported features, which
354 /// makes it tricky to otherwise supply the `payee_features` parameter of `get_route`.
355 pub fn get_keysend_route<L: Deref>(our_node_pubkey: &PublicKey, network: &NetworkGraph, payee:
356 &PublicKey, first_hops: Option<&[&ChannelDetails]>, last_hops: &[&RouteHint],
357 final_value_msat: u64, final_cltv: u32, logger: L) -> Result<Route,
358 LightningError> where L::Target: Logger {
359 let invoice_features = InvoiceFeatures::for_keysend();
360 get_route(our_node_pubkey, network, payee, Some(invoice_features), first_hops, last_hops,
361 final_value_msat, final_cltv, logger)
364 /// Gets a route from us (payer) to the given target node (payee).
366 /// If the payee provided features in their invoice, they should be provided via payee_features.
367 /// Without this, MPP will only be used if the payee's features are available in the network graph.
369 /// Private routing paths between a public node and the target may be included in `last_hops`.
370 /// Currently, only the last hop in each path is considered.
372 /// If some channels aren't announced, it may be useful to fill in a first_hops with the
373 /// results from a local ChannelManager::list_usable_channels() call. If it is filled in, our
374 /// view of our local channels (from net_graph_msg_handler) will be ignored, and only those
375 /// in first_hops will be used.
377 /// Panics if first_hops contains channels without short_channel_ids
378 /// (ChannelManager::list_usable_channels will never include such channels).
380 /// The fees on channels from us to next-hops are ignored (as they are assumed to all be
381 /// equal), however the enabled/disabled bit on such channels as well as the
382 /// htlc_minimum_msat/htlc_maximum_msat *are* checked as they may change based on the receiving node.
383 pub fn get_route<L: Deref>(our_node_pubkey: &PublicKey, network: &NetworkGraph, payee: &PublicKey, payee_features: Option<InvoiceFeatures>, first_hops: Option<&[&ChannelDetails]>,
384 last_hops: &[&RouteHint], final_value_msat: u64, final_cltv: u32, logger: L) -> Result<Route, LightningError> where L::Target: Logger {
385 let payee_node_id = NodeId::from_pubkey(&payee);
386 let our_node_id = NodeId::from_pubkey(&our_node_pubkey);
388 // TODO: Obviously *only* using total fee cost sucks. We should consider weighting by
389 // uptime/success in using a node in the past.
390 if payee_node_id == our_node_id {
391 return Err(LightningError{err: "Cannot generate a route to ourselves".to_owned(), action: ErrorAction::IgnoreError});
394 if final_value_msat > MAX_VALUE_MSAT {
395 return Err(LightningError{err: "Cannot generate a route of more value than all existing satoshis".to_owned(), action: ErrorAction::IgnoreError});
398 if final_value_msat == 0 {
399 return Err(LightningError{err: "Cannot send a payment of 0 msat".to_owned(), action: ErrorAction::IgnoreError});
402 for route in last_hops.iter() {
403 for hop in &route.0 {
404 if hop.src_node_id == *payee {
405 return Err(LightningError{err: "Last hop cannot have a payee as a source.".to_owned(), action: ErrorAction::IgnoreError});
410 // The general routing idea is the following:
411 // 1. Fill first/last hops communicated by the caller.
412 // 2. Attempt to construct a path from payer to payee for transferring
413 // any ~sufficient (described later) value.
414 // If succeed, remember which channels were used and how much liquidity they have available,
415 // so that future paths don't rely on the same liquidity.
416 // 3. Prooceed to the next step if:
417 // - we hit the recommended target value;
418 // - OR if we could not construct a new path. Any next attempt will fail too.
419 // Otherwise, repeat step 2.
420 // 4. See if we managed to collect paths which aggregately are able to transfer target value
421 // (not recommended value). If yes, proceed. If not, fail routing.
422 // 5. Randomly combine paths into routes having enough to fulfill the payment. (TODO: knapsack)
423 // 6. Of all the found paths, select only those with the lowest total fee.
424 // 7. The last path in every selected route is likely to be more than we need.
425 // Reduce its value-to-transfer and recompute fees.
426 // 8. Choose the best route by the lowest total fee.
428 // As for the actual search algorithm,
429 // we do a payee-to-payer pseudo-Dijkstra's sorting by each node's distance from the payee
430 // plus the minimum per-HTLC fee to get from it to another node (aka "shitty pseudo-A*").
432 // We are not a faithful Dijkstra's implementation because we can change values which impact
433 // earlier nodes while processing later nodes. Specifically, if we reach a channel with a lower
434 // liquidity limit (via htlc_maximum_msat, on-chain capacity or assumed liquidity limits) then
435 // the value we are currently attempting to send over a path, we simply reduce the value being
436 // sent along the path for any hops after that channel. This may imply that later fees (which
437 // we've already tabulated) are lower because a smaller value is passing through the channels
438 // (and the proportional fee is thus lower). There isn't a trivial way to recalculate the
439 // channels which were selected earlier (and which may still be used for other paths without a
440 // lower liquidity limit), so we simply accept that some liquidity-limited paths may be
443 // One potentially problematic case for this algorithm would be if there are many
444 // liquidity-limited paths which are liquidity-limited near the destination (ie early in our
445 // graph walking), we may never find a path which is not liquidity-limited and has lower
446 // proportional fee (and only lower absolute fee when considering the ultimate value sent).
447 // Because we only consider paths with at least 5% of the total value being sent, the damage
448 // from such a case should be limited, however this could be further reduced in the future by
449 // calculating fees on the amount we wish to route over a path, ie ignoring the liquidity
450 // limits for the purposes of fee calculation.
452 // Alternatively, we could store more detailed path information in the heap (targets, below)
453 // and index the best-path map (dist, below) by node *and* HTLC limits, however that would blow
454 // up the runtime significantly both algorithmically (as we'd traverse nodes multiple times)
455 // and practically (as we would need to store dynamically-allocated path information in heap
456 // objects, increasing malloc traffic and indirect memory access significantly). Further, the
457 // results of such an algorithm would likely be biased towards lower-value paths.
459 // Further, we could return to a faithful Dijkstra's algorithm by rejecting paths with limits
460 // outside of our current search value, running a path search more times to gather candidate
461 // paths at different values. While this may be acceptable, further path searches may increase
462 // runtime for little gain. Specifically, the current algorithm rather efficiently explores the
463 // graph for candidate paths, calculating the maximum value which can realistically be sent at
464 // the same time, remaining generic across different payment values.
466 // TODO: There are a few tweaks we could do, including possibly pre-calculating more stuff
467 // to use as the A* heuristic beyond just the cost to get one node further than the current
470 let network_graph = network.read_only();
471 let network_channels = network_graph.channels();
472 let network_nodes = network_graph.nodes();
473 let dummy_directional_info = DummyDirectionalChannelInfo { // used for first_hops routes
474 cltv_expiry_delta: 0,
475 htlc_minimum_msat: 0,
476 htlc_maximum_msat: None,
479 proportional_millionths: 0,
483 // Allow MPP only if we have a features set from somewhere that indicates the payee supports
484 // it. If the payee supports it they're supposed to include it in the invoice, so that should
486 let allow_mpp = if let Some(features) = &payee_features {
487 features.supports_basic_mpp()
488 } else if let Some(node) = network_nodes.get(&payee_node_id) {
489 if let Some(node_info) = node.announcement_info.as_ref() {
490 node_info.features.supports_basic_mpp()
493 log_trace!(logger, "Searching for a route from payer {} to payee {} {} MPP", our_node_pubkey, payee,
494 if allow_mpp { "with" } else { "without" });
497 // Prepare the data we'll use for payee-to-payer search by
498 // inserting first hops suggested by the caller as targets.
499 // Our search will then attempt to reach them while traversing from the payee node.
500 let mut first_hop_targets: HashMap<_, Vec<(_, ChannelFeatures, _, NodeFeatures)>> =
501 HashMap::with_capacity(if first_hops.is_some() { first_hops.as_ref().unwrap().len() } else { 0 });
502 if let Some(hops) = first_hops {
504 let short_channel_id = chan.short_channel_id.expect("first_hops should be filled in with usable channels, not pending ones");
505 if chan.counterparty.node_id == *our_node_pubkey {
506 return Err(LightningError{err: "First hop cannot have our_node_pubkey as a destination.".to_owned(), action: ErrorAction::IgnoreError});
508 first_hop_targets.entry(NodeId::from_pubkey(&chan.counterparty.node_id)).or_insert(Vec::new())
509 .push((short_channel_id, chan.counterparty.features.to_context(), chan.outbound_capacity_msat, chan.counterparty.features.to_context()));
511 if first_hop_targets.is_empty() {
512 return Err(LightningError{err: "Cannot route when there are no outbound routes away from us".to_owned(), action: ErrorAction::IgnoreError});
516 let empty_channel_features = ChannelFeatures::empty();
518 // The main heap containing all candidate next-hops sorted by their score (max(A* fee,
519 // htlc_minimum)). Ideally this would be a heap which allowed cheap score reduction instead of
520 // adding duplicate entries when we find a better path to a given node.
521 let mut targets = BinaryHeap::new();
523 // Map from node_id to information about the best current path to that node, including feerate
525 let mut dist = HashMap::with_capacity(network_nodes.len());
527 // During routing, if we ignore a path due to an htlc_minimum_msat limit, we set this,
528 // indicating that we may wish to try again with a higher value, potentially paying to meet an
529 // htlc_minimum with extra fees while still finding a cheaper path.
530 let mut hit_minimum_limit;
532 // When arranging a route, we select multiple paths so that we can make a multi-path payment.
533 // We start with a path_value of the exact amount we want, and if that generates a route we may
534 // return it immediately. Otherwise, we don't stop searching for paths until we have 3x the
535 // amount we want in total across paths, selecting the best subset at the end.
536 const ROUTE_CAPACITY_PROVISION_FACTOR: u64 = 3;
537 let recommended_value_msat = final_value_msat * ROUTE_CAPACITY_PROVISION_FACTOR as u64;
538 let mut path_value_msat = final_value_msat;
540 // We don't want multiple paths (as per MPP) share liquidity of the same channels.
541 // This map allows paths to be aware of the channel use by other paths in the same call.
542 // This would help to make a better path finding decisions and not "overbook" channels.
543 // It is unaware of the directions (except for `outbound_capacity_msat` in `first_hops`).
544 let mut bookkeeped_channels_liquidity_available_msat = HashMap::with_capacity(network_nodes.len());
546 // Keeping track of how much value we already collected across other paths. Helps to decide:
547 // - how much a new path should be transferring (upper bound);
548 // - whether a channel should be disregarded because
549 // it's available liquidity is too small comparing to how much more we need to collect;
550 // - when we want to stop looking for new paths.
551 let mut already_collected_value_msat = 0;
553 log_trace!(logger, "Building path from {} (payee) to {} (us/payer) for value {} msat.", payee, our_node_pubkey, final_value_msat);
555 macro_rules! add_entry {
556 // Adds entry which goes from $src_node_id to $dest_node_id
557 // over the channel with id $chan_id with fees described in
558 // $directional_info.
559 // $next_hops_fee_msat represents the fees paid for using all the channel *after* this one,
560 // since that value has to be transferred over this channel.
561 // Returns whether this channel caused an update to `targets`.
562 ( $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,
563 $next_hops_value_contribution: expr, $next_hops_path_htlc_minimum_msat: expr ) => { {
564 // We "return" whether we updated the path at the end, via this:
565 let mut did_add_update_path_to_src_node = false;
566 // Channels to self should not be used. This is more of belt-and-suspenders, because in
567 // practice these cases should be caught earlier:
568 // - for regular channels at channel announcement (TODO)
569 // - for first and last hops early in get_route
570 if $src_node_id != $dest_node_id.clone() {
571 let available_liquidity_msat = bookkeeped_channels_liquidity_available_msat.entry($chan_id.clone()).or_insert_with(|| {
572 let mut initial_liquidity_available_msat = None;
573 if let Some(capacity_sats) = $capacity_sats {
574 initial_liquidity_available_msat = Some(capacity_sats * 1000);
577 if let Some(htlc_maximum_msat) = $directional_info.htlc_maximum_msat {
578 if let Some(available_msat) = initial_liquidity_available_msat {
579 initial_liquidity_available_msat = Some(cmp::min(available_msat, htlc_maximum_msat));
581 initial_liquidity_available_msat = Some(htlc_maximum_msat);
585 match initial_liquidity_available_msat {
586 Some(available_msat) => available_msat,
587 // We assume channels with unknown balance have
588 // a capacity of 0.0025 BTC (or 250_000 sats).
589 None => 250_000 * 1000
593 // It is tricky to substract $next_hops_fee_msat from available liquidity here.
594 // It may be misleading because we might later choose to reduce the value transferred
595 // over these channels, and the channel which was insufficient might become sufficient.
596 // Worst case: we drop a good channel here because it can't cover the high following
597 // fees caused by one expensive channel, but then this channel could have been used
598 // if the amount being transferred over this path is lower.
599 // We do this for now, but this is a subject for removal.
600 if let Some(available_value_contribution_msat) = available_liquidity_msat.checked_sub($next_hops_fee_msat) {
602 // Routing Fragmentation Mitigation heuristic:
604 // Routing fragmentation across many payment paths increases the overall routing
605 // fees as you have irreducible routing fees per-link used (`fee_base_msat`).
606 // Taking too many smaller paths also increases the chance of payment failure.
607 // Thus to avoid this effect, we require from our collected links to provide
608 // at least a minimal contribution to the recommended value yet-to-be-fulfilled.
610 // This requirement is currently 5% of the remaining-to-be-collected value.
611 // This means as we successfully advance in our collection,
612 // the absolute liquidity contribution is lowered,
613 // thus increasing the number of potential channels to be selected.
615 // Derive the minimal liquidity contribution with a ratio of 20 (5%, rounded up)
616 // or 100% if we're not allowed to do multipath payments.
617 let minimal_value_contribution_msat: u64 = if allow_mpp {
618 (recommended_value_msat - already_collected_value_msat + 19) / 20
622 // Verify the liquidity offered by this channel complies to the minimal contribution.
623 let contributes_sufficient_value = available_value_contribution_msat >= minimal_value_contribution_msat;
625 let value_contribution_msat = cmp::min(available_value_contribution_msat, $next_hops_value_contribution);
626 // Includes paying fees for the use of the following channels.
627 let amount_to_transfer_over_msat: u64 = match value_contribution_msat.checked_add($next_hops_fee_msat) {
628 Some(result) => result,
629 // Can't overflow due to how the values were computed right above.
630 None => unreachable!(),
632 #[allow(unused_comparisons)] // $next_hops_path_htlc_minimum_msat is 0 in some calls so rustc complains
633 let over_path_minimum_msat = amount_to_transfer_over_msat >= $directional_info.htlc_minimum_msat &&
634 amount_to_transfer_over_msat >= $next_hops_path_htlc_minimum_msat;
636 // If HTLC minimum is larger than the amount we're going to transfer, we shouldn't
637 // bother considering this channel.
638 // Since we're choosing amount_to_transfer_over_msat as maximum possible, it can
639 // be only reduced later (not increased), so this channel should just be skipped
640 // as not sufficient.
641 if !over_path_minimum_msat {
642 hit_minimum_limit = true;
643 } else if contributes_sufficient_value {
644 // Note that low contribution here (limited by available_liquidity_msat)
645 // might violate htlc_minimum_msat on the hops which are next along the
646 // payment path (upstream to the payee). To avoid that, we recompute path
647 // path fees knowing the final path contribution after constructing it.
648 let path_htlc_minimum_msat = match compute_fees($next_hops_path_htlc_minimum_msat, $directional_info.fees)
649 .map(|fee_msat| fee_msat.checked_add($next_hops_path_htlc_minimum_msat)) {
650 Some(Some(value_msat)) => cmp::max(value_msat, $directional_info.htlc_minimum_msat),
651 _ => u64::max_value()
653 let hm_entry = dist.entry($src_node_id);
654 let old_entry = hm_entry.or_insert_with(|| {
655 // If there was previously no known way to access
656 // the source node (recall it goes payee-to-payer) of $chan_id, first add
657 // a semi-dummy record just to compute the fees to reach the source node.
658 // This will affect our decision on selecting $chan_id
659 // as a way to reach the $dest_node_id.
660 let mut fee_base_msat = u32::max_value();
661 let mut fee_proportional_millionths = u32::max_value();
662 if let Some(Some(fees)) = network_nodes.get(&$src_node_id).map(|node| node.lowest_inbound_channel_fees) {
663 fee_base_msat = fees.base_msat;
664 fee_proportional_millionths = fees.proportional_millionths;
667 node_id: $dest_node_id.clone(),
669 channel_features: $chan_features,
671 cltv_expiry_delta: 0,
672 src_lowest_inbound_fees: RoutingFees {
673 base_msat: fee_base_msat,
674 proportional_millionths: fee_proportional_millionths,
676 channel_fees: $directional_info.fees,
677 next_hops_fee_msat: u64::max_value(),
678 hop_use_fee_msat: u64::max_value(),
679 total_fee_msat: u64::max_value(),
680 htlc_minimum_msat: $directional_info.htlc_minimum_msat,
681 path_htlc_minimum_msat,
682 was_processed: false,
683 #[cfg(any(test, feature = "fuzztarget"))]
684 value_contribution_msat,
688 #[allow(unused_mut)] // We only use the mut in cfg(test)
689 let mut should_process = !old_entry.was_processed;
690 #[cfg(any(test, feature = "fuzztarget"))]
692 // In test/fuzzing builds, we do extra checks to make sure the skipping
693 // of already-seen nodes only happens in cases we expect (see below).
694 if !should_process { should_process = true; }
698 let mut hop_use_fee_msat = 0;
699 let mut total_fee_msat = $next_hops_fee_msat;
701 // Ignore hop_use_fee_msat for channel-from-us as we assume all channels-from-us
702 // will have the same effective-fee
703 if $src_node_id != our_node_id {
704 match compute_fees(amount_to_transfer_over_msat, $directional_info.fees) {
705 // max_value means we'll always fail
706 // the old_entry.total_fee_msat > total_fee_msat check
707 None => total_fee_msat = u64::max_value(),
709 hop_use_fee_msat = fee_msat;
710 total_fee_msat += hop_use_fee_msat;
711 // When calculating the lowest inbound fees to a node, we
712 // calculate fees here not based on the actual value we think
713 // will flow over this channel, but on the minimum value that
714 // we'll accept flowing over it. The minimum accepted value
715 // is a constant through each path collection run, ensuring
716 // consistent basis. Otherwise we may later find a
717 // different path to the source node that is more expensive,
718 // but which we consider to be cheaper because we are capacity
719 // constrained and the relative fee becomes lower.
720 match compute_fees(minimal_value_contribution_msat, old_entry.src_lowest_inbound_fees)
721 .map(|a| a.checked_add(total_fee_msat)) {
726 total_fee_msat = u64::max_value();
733 let new_graph_node = RouteGraphNode {
734 node_id: $src_node_id,
735 lowest_fee_to_peer_through_node: total_fee_msat,
736 lowest_fee_to_node: $next_hops_fee_msat as u64 + hop_use_fee_msat,
737 value_contribution_msat: value_contribution_msat,
738 path_htlc_minimum_msat,
741 // Update the way of reaching $src_node_id with the given $chan_id (from $dest_node_id),
742 // if this way is cheaper than the already known
743 // (considering the cost to "reach" this channel from the route destination,
744 // the cost of using this channel,
745 // and the cost of routing to the source node of this channel).
746 // Also, consider that htlc_minimum_msat_difference, because we might end up
747 // paying it. Consider the following exploit:
748 // we use 2 paths to transfer 1.5 BTC. One of them is 0-fee normal 1 BTC path,
749 // and for the other one we picked a 1sat-fee path with htlc_minimum_msat of
750 // 1 BTC. Now, since the latter is more expensive, we gonna try to cut it
751 // by 0.5 BTC, but then match htlc_minimum_msat by paying a fee of 0.5 BTC
753 // Ideally the scoring could be smarter (e.g. 0.5*htlc_minimum_msat here),
754 // but it may require additional tracking - we don't want to double-count
755 // the fees included in $next_hops_path_htlc_minimum_msat, but also
756 // can't use something that may decrease on future hops.
757 let old_cost = cmp::max(old_entry.total_fee_msat, old_entry.path_htlc_minimum_msat);
758 let new_cost = cmp::max(total_fee_msat, path_htlc_minimum_msat);
760 if !old_entry.was_processed && new_cost < old_cost {
761 targets.push(new_graph_node);
762 old_entry.next_hops_fee_msat = $next_hops_fee_msat;
763 old_entry.hop_use_fee_msat = hop_use_fee_msat;
764 old_entry.total_fee_msat = total_fee_msat;
765 old_entry.node_id = $dest_node_id.clone();
766 old_entry.short_channel_id = $chan_id.clone();
767 old_entry.channel_features = $chan_features;
768 old_entry.fee_msat = 0; // This value will be later filled with hop_use_fee_msat of the following channel
769 old_entry.cltv_expiry_delta = $directional_info.cltv_expiry_delta as u32;
770 old_entry.channel_fees = $directional_info.fees;
771 old_entry.htlc_minimum_msat = $directional_info.htlc_minimum_msat;
772 old_entry.path_htlc_minimum_msat = path_htlc_minimum_msat;
773 #[cfg(any(test, feature = "fuzztarget"))]
775 old_entry.value_contribution_msat = value_contribution_msat;
777 did_add_update_path_to_src_node = true;
778 } else if old_entry.was_processed && new_cost < old_cost {
779 #[cfg(any(test, feature = "fuzztarget"))]
781 // If we're skipping processing a node which was previously
782 // processed even though we found another path to it with a
783 // cheaper fee, check that it was because the second path we
784 // found (which we are processing now) has a lower value
785 // contribution due to an HTLC minimum limit.
787 // e.g. take a graph with two paths from node 1 to node 2, one
788 // through channel A, and one through channel B. Channel A and
789 // B are both in the to-process heap, with their scores set by
790 // a higher htlc_minimum than fee.
791 // Channel A is processed first, and the channels onwards from
792 // node 1 are added to the to-process heap. Thereafter, we pop
793 // Channel B off of the heap, note that it has a much more
794 // restrictive htlc_maximum_msat, and recalculate the fees for
795 // all of node 1's channels using the new, reduced, amount.
797 // This would be bogus - we'd be selecting a higher-fee path
798 // with a lower htlc_maximum_msat instead of the one we'd
799 // already decided to use.
800 debug_assert!(path_htlc_minimum_msat < old_entry.path_htlc_minimum_msat);
801 debug_assert!(value_contribution_msat < old_entry.value_contribution_msat);
808 did_add_update_path_to_src_node
812 let empty_node_features = NodeFeatures::empty();
813 // Find ways (channels with destination) to reach a given node and store them
814 // in the corresponding data structures (routing graph etc).
815 // $fee_to_target_msat represents how much it costs to reach to this node from the payee,
816 // meaning how much will be paid in fees after this node (to the best of our knowledge).
817 // This data can later be helpful to optimize routing (pay lower fees).
818 macro_rules! add_entries_to_cheapest_to_target_node {
819 ( $node: expr, $node_id: expr, $fee_to_target_msat: expr, $next_hops_value_contribution: expr, $next_hops_path_htlc_minimum_msat: expr ) => {
820 let skip_node = if let Some(elem) = dist.get_mut(&$node_id) {
821 let was_processed = elem.was_processed;
822 elem.was_processed = true;
825 // Entries are added to dist in add_entry!() when there is a channel from a node.
826 // Because there are no channels from payee, it will not have a dist entry at this point.
827 // If we're processing any other node, it is always be the result of a channel from it.
828 assert_eq!($node_id, payee_node_id);
833 if let Some(first_channels) = first_hop_targets.get(&$node_id) {
834 for (ref first_hop, ref features, ref outbound_capacity_msat, _) in first_channels {
835 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);
839 let features = if let Some(node_info) = $node.announcement_info.as_ref() {
845 if !features.requires_unknown_bits() {
846 for chan_id in $node.channels.iter() {
847 let chan = network_channels.get(chan_id).unwrap();
848 if !chan.features.requires_unknown_bits() {
849 if chan.node_one == $node_id {
850 // ie $node is one, ie next hop in A* is two, via the two_to_one channel
851 if first_hops.is_none() || chan.node_two != our_node_id {
852 if let Some(two_to_one) = chan.two_to_one.as_ref() {
853 if two_to_one.enabled {
854 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);
859 if first_hops.is_none() || chan.node_one != our_node_id{
860 if let Some(one_to_two) = chan.one_to_two.as_ref() {
861 if one_to_two.enabled {
862 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);
874 let mut payment_paths = Vec::<PaymentPath>::new();
876 // TODO: diversify by nodes (so that all paths aren't doomed if one node is offline).
877 'paths_collection: loop {
878 // For every new path, start from scratch, except
879 // bookkeeped_channels_liquidity_available_msat, which will improve
880 // the further iterations of path finding. Also don't erase first_hop_targets.
883 hit_minimum_limit = false;
885 // If first hop is a private channel and the only way to reach the payee, this is the only
886 // place where it could be added.
887 if let Some(first_channels) = first_hop_targets.get(&payee_node_id) {
888 for (ref first_hop, ref features, ref outbound_capacity_msat, _) in first_channels {
889 let added = add_entry!(first_hop, our_node_id, payee_node_id, dummy_directional_info, Some(outbound_capacity_msat / 1000), features, 0, path_value_msat, 0);
890 log_trace!(logger, "{} direct route to payee via SCID {}", if added { "Added" } else { "Skipped" }, first_hop);
894 // Add the payee as a target, so that the payee-to-payer
895 // search algorithm knows what to start with.
896 match network_nodes.get(&payee_node_id) {
897 // The payee is not in our network graph, so nothing to add here.
898 // There is still a chance of reaching them via last_hops though,
899 // so don't yet fail the payment here.
900 // If not, targets.pop() will not even let us enter the loop in step 2.
903 add_entries_to_cheapest_to_target_node!(node, payee_node_id, 0, path_value_msat, 0);
908 // If a caller provided us with last hops, add them to routing targets. Since this happens
909 // earlier than general path finding, they will be somewhat prioritized, although currently
910 // it matters only if the fees are exactly the same.
911 for route in last_hops.iter().filter(|route| !route.0.is_empty()) {
912 let first_hop_in_route = &(route.0)[0];
913 let have_hop_src_in_graph =
914 // Only add the hops in this route to our candidate set if either
915 // we have a direct channel to the first hop or the first hop is
916 // in the regular network graph.
917 first_hop_targets.get(&NodeId::from_pubkey(&first_hop_in_route.src_node_id)).is_some() ||
918 network_nodes.get(&NodeId::from_pubkey(&first_hop_in_route.src_node_id)).is_some();
919 if have_hop_src_in_graph {
920 // We start building the path from reverse, i.e., from payee
921 // to the first RouteHintHop in the path.
922 let hop_iter = route.0.iter().rev();
923 let prev_hop_iter = core::iter::once(payee).chain(
924 route.0.iter().skip(1).rev().map(|hop| &hop.src_node_id));
925 let mut hop_used = true;
926 let mut aggregate_next_hops_fee_msat: u64 = 0;
927 let mut aggregate_next_hops_path_htlc_minimum_msat: u64 = 0;
929 for (idx, (hop, prev_hop_id)) in hop_iter.zip(prev_hop_iter).enumerate() {
930 // BOLT 11 doesn't allow inclusion of features for the last hop hints, which
931 // really sucks, cause we're gonna need that eventually.
932 let hop_htlc_minimum_msat: u64 = hop.htlc_minimum_msat.unwrap_or(0);
934 let directional_info = DummyDirectionalChannelInfo {
935 cltv_expiry_delta: hop.cltv_expiry_delta as u32,
936 htlc_minimum_msat: hop_htlc_minimum_msat,
937 htlc_maximum_msat: hop.htlc_maximum_msat,
941 let reqd_channel_cap = if let Some (val) = final_value_msat.checked_add(match idx {
943 _ => aggregate_next_hops_fee_msat.checked_add(999).unwrap_or(u64::max_value())
944 }) { Some( val / 1000 ) } else { break; }; // converting from msat or breaking if max ~ infinity
946 // We assume that the recipient only included route hints for routes which had
947 // sufficient value to route `final_value_msat`. Note that in the case of "0-value"
948 // invoices where the invoice does not specify value this may not be the case, but
949 // better to include the hints than not.
950 if !add_entry!(hop.short_channel_id, NodeId::from_pubkey(&hop.src_node_id), NodeId::from_pubkey(&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) {
951 // If this hop was not used then there is no use checking the preceding hops
952 // in the RouteHint. We can break by just searching for a direct channel between
953 // last checked hop and first_hop_targets
957 // Searching for a direct channel between last checked hop and first_hop_targets
958 if let Some(first_channels) = first_hop_targets.get(&NodeId::from_pubkey(&prev_hop_id)) {
959 for (ref first_hop, ref features, ref outbound_capacity_msat, _) in first_channels {
960 add_entry!(first_hop, our_node_id , NodeId::from_pubkey(&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);
968 // In the next values of the iterator, the aggregate fees already reflects
969 // the sum of value sent from payer (final_value_msat) and routing fees
970 // for the last node in the RouteHint. We need to just add the fees to
971 // route through the current node so that the preceeding node (next iteration)
973 let hops_fee = compute_fees(aggregate_next_hops_fee_msat + final_value_msat, hop.fees)
974 .map_or(None, |inc| inc.checked_add(aggregate_next_hops_fee_msat));
975 aggregate_next_hops_fee_msat = if let Some(val) = hops_fee { val } else { break; };
977 let hop_htlc_minimum_msat_inc = if let Some(val) = compute_fees(aggregate_next_hops_path_htlc_minimum_msat, hop.fees) { val } else { break; };
978 let hops_path_htlc_minimum = aggregate_next_hops_path_htlc_minimum_msat
979 .checked_add(hop_htlc_minimum_msat_inc);
980 aggregate_next_hops_path_htlc_minimum_msat = if let Some(val) = hops_path_htlc_minimum { cmp::max(hop_htlc_minimum_msat, val) } else { break; };
982 if idx == route.0.len() - 1 {
983 // The last hop in this iterator is the first hop in
984 // overall RouteHint.
985 // If this hop connects to a node with which we have a direct channel,
986 // ignore the network graph and, if the last hop was added, add our
987 // direct channel to the candidate set.
989 // Note that we *must* check if the last hop was added as `add_entry`
990 // always assumes that the third argument is a node to which we have a
992 if let Some(first_channels) = first_hop_targets.get(&NodeId::from_pubkey(&hop.src_node_id)) {
993 for (ref first_hop, ref features, ref outbound_capacity_msat, _) in first_channels {
994 add_entry!(first_hop, our_node_id , NodeId::from_pubkey(&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);
1002 log_trace!(logger, "Starting main path collection loop with {} nodes pre-filled from first/last hops.", targets.len());
1004 // At this point, targets are filled with the data from first and
1005 // last hops communicated by the caller, and the payment receiver.
1006 let mut found_new_path = false;
1009 // If this loop terminates due the exhaustion of targets, two situations are possible:
1010 // - not enough outgoing liquidity:
1011 // 0 < already_collected_value_msat < final_value_msat
1012 // - enough outgoing liquidity:
1013 // final_value_msat <= already_collected_value_msat < recommended_value_msat
1014 // Both these cases (and other cases except reaching recommended_value_msat) mean that
1015 // paths_collection will be stopped because found_new_path==false.
1016 // This is not necessarily a routing failure.
1017 'path_construction: while let Some(RouteGraphNode { node_id, lowest_fee_to_node, value_contribution_msat, path_htlc_minimum_msat, .. }) = targets.pop() {
1019 // Since we're going payee-to-payer, hitting our node as a target means we should stop
1020 // traversing the graph and arrange the path out of what we found.
1021 if node_id == our_node_id {
1022 let mut new_entry = dist.remove(&our_node_id).unwrap();
1023 let mut ordered_hops = vec!((new_entry.clone(), NodeFeatures::empty()));
1026 let mut features_set = false;
1027 if let Some(first_channels) = first_hop_targets.get(&ordered_hops.last().unwrap().0.node_id) {
1028 for (scid, _, _, ref features) in first_channels {
1029 if *scid == ordered_hops.last().unwrap().0.short_channel_id {
1030 ordered_hops.last_mut().unwrap().1 = features.clone();
1031 features_set = true;
1037 if let Some(node) = network_nodes.get(&ordered_hops.last().unwrap().0.node_id) {
1038 if let Some(node_info) = node.announcement_info.as_ref() {
1039 ordered_hops.last_mut().unwrap().1 = node_info.features.clone();
1041 ordered_hops.last_mut().unwrap().1 = NodeFeatures::empty();
1044 // We should be able to fill in features for everything except the last
1045 // hop, if the last hop was provided via a BOLT 11 invoice (though we
1046 // should be able to extend it further as BOLT 11 does have feature
1047 // flags for the last hop node itself).
1048 assert!(ordered_hops.last().unwrap().0.node_id == payee_node_id);
1052 // Means we succesfully traversed from the payer to the payee, now
1053 // save this path for the payment route. Also, update the liquidity
1054 // remaining on the used hops, so that we take them into account
1055 // while looking for more paths.
1056 if ordered_hops.last().unwrap().0.node_id == payee_node_id {
1060 new_entry = match dist.remove(&ordered_hops.last().unwrap().0.node_id) {
1061 Some(payment_hop) => payment_hop,
1062 // We can't arrive at None because, if we ever add an entry to targets,
1063 // we also fill in the entry in dist (see add_entry!).
1064 None => unreachable!(),
1066 // We "propagate" the fees one hop backward (topologically) here,
1067 // so that fees paid for a HTLC forwarding on the current channel are
1068 // associated with the previous channel (where they will be subtracted).
1069 ordered_hops.last_mut().unwrap().0.fee_msat = new_entry.hop_use_fee_msat;
1070 ordered_hops.last_mut().unwrap().0.cltv_expiry_delta = new_entry.cltv_expiry_delta;
1071 ordered_hops.push((new_entry.clone(), NodeFeatures::empty()));
1073 ordered_hops.last_mut().unwrap().0.fee_msat = value_contribution_msat;
1074 ordered_hops.last_mut().unwrap().0.hop_use_fee_msat = 0;
1075 ordered_hops.last_mut().unwrap().0.cltv_expiry_delta = final_cltv;
1077 log_trace!(logger, "Found a path back to us from the target with {} hops contributing up to {} msat: {:?}",
1078 ordered_hops.len(), value_contribution_msat, ordered_hops);
1080 let mut payment_path = PaymentPath {hops: ordered_hops};
1082 // We could have possibly constructed a slightly inconsistent path: since we reduce
1083 // value being transferred along the way, we could have violated htlc_minimum_msat
1084 // on some channels we already passed (assuming dest->source direction). Here, we
1085 // recompute the fees again, so that if that's the case, we match the currently
1086 // underpaid htlc_minimum_msat with fees.
1087 payment_path.update_value_and_recompute_fees(cmp::min(value_contribution_msat, final_value_msat));
1089 // Since a path allows to transfer as much value as
1090 // the smallest channel it has ("bottleneck"), we should recompute
1091 // the fees so sender HTLC don't overpay fees when traversing
1092 // larger channels than the bottleneck. This may happen because
1093 // when we were selecting those channels we were not aware how much value
1094 // this path will transfer, and the relative fee for them
1095 // might have been computed considering a larger value.
1096 // Remember that we used these channels so that we don't rely
1097 // on the same liquidity in future paths.
1098 let mut prevented_redundant_path_selection = false;
1099 for (payment_hop, _) in payment_path.hops.iter() {
1100 let channel_liquidity_available_msat = bookkeeped_channels_liquidity_available_msat.get_mut(&payment_hop.short_channel_id).unwrap();
1101 let mut spent_on_hop_msat = value_contribution_msat;
1102 let next_hops_fee_msat = payment_hop.next_hops_fee_msat;
1103 spent_on_hop_msat += next_hops_fee_msat;
1104 if spent_on_hop_msat == *channel_liquidity_available_msat {
1105 // If this path used all of this channel's available liquidity, we know
1106 // this path will not be selected again in the next loop iteration.
1107 prevented_redundant_path_selection = true;
1109 *channel_liquidity_available_msat -= spent_on_hop_msat;
1111 if !prevented_redundant_path_selection {
1112 // If we weren't capped by hitting a liquidity limit on a channel in the path,
1113 // we'll probably end up picking the same path again on the next iteration.
1114 // Decrease the available liquidity of a hop in the middle of the path.
1115 let victim_scid = payment_path.hops[(payment_path.hops.len() - 1) / 2].0.short_channel_id;
1116 log_trace!(logger, "Disabling channel {} for future path building iterations to avoid duplicates.", victim_scid);
1117 let victim_liquidity = bookkeeped_channels_liquidity_available_msat.get_mut(&victim_scid).unwrap();
1118 *victim_liquidity = 0;
1121 // Track the total amount all our collected paths allow to send so that we:
1122 // - know when to stop looking for more paths
1123 // - know which of the hops are useless considering how much more sats we need
1124 // (contributes_sufficient_value)
1125 already_collected_value_msat += value_contribution_msat;
1127 payment_paths.push(payment_path);
1128 found_new_path = true;
1129 break 'path_construction;
1132 // If we found a path back to the payee, we shouldn't try to process it again. This is
1133 // the equivalent of the `elem.was_processed` check in
1134 // add_entries_to_cheapest_to_target_node!() (see comment there for more info).
1135 if node_id == payee_node_id { continue 'path_construction; }
1137 // Otherwise, since the current target node is not us,
1138 // keep "unrolling" the payment graph from payee to payer by
1139 // finding a way to reach the current target from the payer side.
1140 match network_nodes.get(&node_id) {
1143 add_entries_to_cheapest_to_target_node!(node, node_id, lowest_fee_to_node, value_contribution_msat, path_htlc_minimum_msat);
1149 // If we don't support MPP, no use trying to gather more value ever.
1150 break 'paths_collection;
1154 // Stop either when the recommended value is reached or if no new path was found in this
1156 // In the latter case, making another path finding attempt won't help,
1157 // because we deterministically terminated the search due to low liquidity.
1158 if already_collected_value_msat >= recommended_value_msat || !found_new_path {
1159 log_trace!(logger, "Have now collected {} msat (seeking {} msat) in paths. Last path loop {} a new path.",
1160 already_collected_value_msat, recommended_value_msat, if found_new_path { "found" } else { "did not find" });
1161 break 'paths_collection;
1162 } else if found_new_path && already_collected_value_msat == final_value_msat && payment_paths.len() == 1 {
1163 // Further, if this was our first walk of the graph, and we weren't limited by an
1164 // htlc_minimum_msat, return immediately because this path should suffice. If we were
1165 // limited by an htlc_minimum_msat value, find another path with a higher value,
1166 // potentially allowing us to pay fees to meet the htlc_minimum on the new path while
1167 // still keeping a lower total fee than this path.
1168 if !hit_minimum_limit {
1169 log_trace!(logger, "Collected exactly our payment amount on the first pass, without hitting an htlc_minimum_msat limit, exiting.");
1170 break 'paths_collection;
1172 log_trace!(logger, "Collected our payment amount on the first pass, but running again to collect extra paths with a potentially higher limit.");
1173 path_value_msat = recommended_value_msat;
1178 if payment_paths.len() == 0 {
1179 return Err(LightningError{err: "Failed to find a path to the given destination".to_owned(), action: ErrorAction::IgnoreError});
1182 if already_collected_value_msat < final_value_msat {
1183 return Err(LightningError{err: "Failed to find a sufficient route to the given destination".to_owned(), action: ErrorAction::IgnoreError});
1186 // Sort by total fees and take the best paths.
1187 payment_paths.sort_by_key(|path| path.get_total_fee_paid_msat());
1188 if payment_paths.len() > 50 {
1189 payment_paths.truncate(50);
1192 // Draw multiple sufficient routes by randomly combining the selected paths.
1193 let mut drawn_routes = Vec::new();
1194 for i in 0..payment_paths.len() {
1195 let mut cur_route = Vec::<PaymentPath>::new();
1196 let mut aggregate_route_value_msat = 0;
1199 // TODO: real random shuffle
1200 // Currently just starts with i_th and goes up to i-1_th in a looped way.
1201 let cur_payment_paths = [&payment_paths[i..], &payment_paths[..i]].concat();
1204 for payment_path in cur_payment_paths {
1205 cur_route.push(payment_path.clone());
1206 aggregate_route_value_msat += payment_path.get_value_msat();
1207 if aggregate_route_value_msat > final_value_msat {
1208 // Last path likely overpaid. Substract it from the most expensive
1209 // (in terms of proportional fee) path in this route and recompute fees.
1210 // This might be not the most economically efficient way, but fewer paths
1211 // also makes routing more reliable.
1212 let mut overpaid_value_msat = aggregate_route_value_msat - final_value_msat;
1214 // First, drop some expensive low-value paths entirely if possible.
1215 // Sort by value so that we drop many really-low values first, since
1216 // fewer paths is better: the payment is less likely to fail.
1217 // TODO: this could also be optimized by also sorting by feerate_per_sat_routed,
1218 // so that the sender pays less fees overall. And also htlc_minimum_msat.
1219 cur_route.sort_by_key(|path| path.get_value_msat());
1220 // We should make sure that at least 1 path left.
1221 let mut paths_left = cur_route.len();
1222 cur_route.retain(|path| {
1223 if paths_left == 1 {
1226 let mut keep = true;
1227 let path_value_msat = path.get_value_msat();
1228 if path_value_msat <= overpaid_value_msat {
1230 overpaid_value_msat -= path_value_msat;
1236 if overpaid_value_msat == 0 {
1240 assert!(cur_route.len() > 0);
1243 // Now, substract the overpaid value from the most-expensive path.
1244 // TODO: this could also be optimized by also sorting by feerate_per_sat_routed,
1245 // so that the sender pays less fees overall. And also htlc_minimum_msat.
1246 cur_route.sort_by_key(|path| { path.hops.iter().map(|hop| hop.0.channel_fees.proportional_millionths as u64).sum::<u64>() });
1247 let expensive_payment_path = cur_route.first_mut().unwrap();
1248 // We already dropped all the small channels above, meaning all the
1249 // remaining channels are larger than remaining overpaid_value_msat.
1250 // Thus, this can't be negative.
1251 let expensive_path_new_value_msat = expensive_payment_path.get_value_msat() - overpaid_value_msat;
1252 expensive_payment_path.update_value_and_recompute_fees(expensive_path_new_value_msat);
1256 drawn_routes.push(cur_route);
1260 // Select the best route by lowest total fee.
1261 drawn_routes.sort_by_key(|paths| paths.iter().map(|path| path.get_total_fee_paid_msat()).sum::<u64>());
1262 let mut selected_paths = Vec::<Vec<Result<RouteHop, LightningError>>>::new();
1263 for payment_path in drawn_routes.first().unwrap() {
1264 selected_paths.push(payment_path.hops.iter().map(|(payment_hop, node_features)| {
1266 pubkey: PublicKey::from_slice(payment_hop.node_id.as_slice()).map_err(|_| LightningError{err: format!("Public key {:?} is invalid", &payment_hop.node_id), action: ErrorAction::IgnoreAndLog(Level::Trace)})?,
1267 node_features: node_features.clone(),
1268 short_channel_id: payment_hop.short_channel_id,
1269 channel_features: payment_hop.channel_features.clone(),
1270 fee_msat: payment_hop.fee_msat,
1271 cltv_expiry_delta: payment_hop.cltv_expiry_delta,
1276 if let Some(features) = &payee_features {
1277 for path in selected_paths.iter_mut() {
1278 if let Ok(route_hop) = path.last_mut().unwrap() {
1279 route_hop.node_features = features.to_context();
1284 let route = Route { paths: selected_paths.into_iter().map(|path| path.into_iter().collect()).collect::<Result<Vec<_>, _>>()? };
1285 log_info!(logger, "Got route to {}: {}", payee, log_route!(route));
1291 use routing::router::{get_route, Route, RouteHint, RouteHintHop, RouteHop, RoutingFees};
1292 use routing::network_graph::{NetworkGraph, NetGraphMsgHandler};
1293 use chain::transaction::OutPoint;
1294 use ln::features::{ChannelFeatures, InitFeatures, InvoiceFeatures, NodeFeatures};
1295 use ln::msgs::{ErrorAction, LightningError, OptionalField, UnsignedChannelAnnouncement, ChannelAnnouncement, RoutingMessageHandler,
1296 NodeAnnouncement, UnsignedNodeAnnouncement, ChannelUpdate, UnsignedChannelUpdate};
1297 use ln::channelmanager;
1298 use util::test_utils;
1299 use util::ser::Writeable;
1301 use bitcoin::hashes::sha256d::Hash as Sha256dHash;
1302 use bitcoin::hashes::Hash;
1303 use bitcoin::network::constants::Network;
1304 use bitcoin::blockdata::constants::genesis_block;
1305 use bitcoin::blockdata::script::Builder;
1306 use bitcoin::blockdata::opcodes;
1307 use bitcoin::blockdata::transaction::TxOut;
1311 use bitcoin::secp256k1::key::{PublicKey,SecretKey};
1312 use bitcoin::secp256k1::{Secp256k1, All};
1315 use sync::{self, Arc};
1317 fn get_channel_details(short_channel_id: Option<u64>, node_id: PublicKey,
1318 features: InitFeatures, outbound_capacity_msat: u64) -> channelmanager::ChannelDetails {
1319 channelmanager::ChannelDetails {
1320 channel_id: [0; 32],
1321 counterparty: channelmanager::ChannelCounterparty {
1324 unspendable_punishment_reserve: 0,
1325 forwarding_info: None,
1327 funding_txo: Some(OutPoint { txid: bitcoin::Txid::from_slice(&[0; 32]).unwrap(), index: 0 }),
1329 channel_value_satoshis: 0,
1331 outbound_capacity_msat,
1332 inbound_capacity_msat: 42,
1333 unspendable_punishment_reserve: None,
1334 confirmations_required: None,
1335 force_close_spend_delay: None,
1336 is_outbound: true, is_funding_locked: true,
1337 is_usable: true, is_public: true,
1341 // Using the same keys for LN and BTC ids
1343 net_graph_msg_handler: &NetGraphMsgHandler<Arc<test_utils::TestChainSource>, Arc<test_utils::TestLogger>>,
1344 secp_ctx: &Secp256k1<All>, node_1_privkey: &SecretKey, node_2_privkey: &SecretKey, features: ChannelFeatures, short_channel_id: u64
1346 let node_id_1 = PublicKey::from_secret_key(&secp_ctx, node_1_privkey);
1347 let node_id_2 = PublicKey::from_secret_key(&secp_ctx, node_2_privkey);
1349 let unsigned_announcement = UnsignedChannelAnnouncement {
1351 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1355 bitcoin_key_1: node_id_1,
1356 bitcoin_key_2: node_id_2,
1357 excess_data: Vec::new(),
1360 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1361 let valid_announcement = ChannelAnnouncement {
1362 node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
1363 node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
1364 bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
1365 bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
1366 contents: unsigned_announcement.clone(),
1368 match net_graph_msg_handler.handle_channel_announcement(&valid_announcement) {
1369 Ok(res) => assert!(res),
1375 net_graph_msg_handler: &NetGraphMsgHandler<Arc<test_utils::TestChainSource>, Arc<test_utils::TestLogger>>,
1376 secp_ctx: &Secp256k1<All>, node_privkey: &SecretKey, update: UnsignedChannelUpdate
1378 let msghash = hash_to_message!(&Sha256dHash::hash(&update.encode()[..])[..]);
1379 let valid_channel_update = ChannelUpdate {
1380 signature: secp_ctx.sign(&msghash, node_privkey),
1381 contents: update.clone()
1384 match net_graph_msg_handler.handle_channel_update(&valid_channel_update) {
1385 Ok(res) => assert!(res),
1390 fn add_or_update_node(
1391 net_graph_msg_handler: &NetGraphMsgHandler<Arc<test_utils::TestChainSource>, Arc<test_utils::TestLogger>>,
1392 secp_ctx: &Secp256k1<All>, node_privkey: &SecretKey, features: NodeFeatures, timestamp: u32
1394 let node_id = PublicKey::from_secret_key(&secp_ctx, node_privkey);
1395 let unsigned_announcement = UnsignedNodeAnnouncement {
1401 addresses: Vec::new(),
1402 excess_address_data: Vec::new(),
1403 excess_data: Vec::new(),
1405 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1406 let valid_announcement = NodeAnnouncement {
1407 signature: secp_ctx.sign(&msghash, node_privkey),
1408 contents: unsigned_announcement.clone()
1411 match net_graph_msg_handler.handle_node_announcement(&valid_announcement) {
1417 fn get_nodes(secp_ctx: &Secp256k1<All>) -> (SecretKey, PublicKey, Vec<SecretKey>, Vec<PublicKey>) {
1418 let privkeys: Vec<SecretKey> = (2..10).map(|i| {
1419 SecretKey::from_slice(&hex::decode(format!("{:02}", i).repeat(32)).unwrap()[..]).unwrap()
1422 let pubkeys = privkeys.iter().map(|secret| PublicKey::from_secret_key(&secp_ctx, secret)).collect();
1424 let our_privkey = SecretKey::from_slice(&hex::decode("01".repeat(32)).unwrap()[..]).unwrap();
1425 let our_id = PublicKey::from_secret_key(&secp_ctx, &our_privkey);
1427 (our_privkey, our_id, privkeys, pubkeys)
1430 fn id_to_feature_flags(id: u8) -> Vec<u8> {
1431 // Set the feature flags to the id'th odd (ie non-required) feature bit so that we can
1432 // test for it later.
1433 let idx = (id - 1) * 2 + 1;
1435 vec![1 << (idx - 8*3), 0, 0, 0]
1436 } else if idx > 8*2 {
1437 vec![1 << (idx - 8*2), 0, 0]
1438 } else if idx > 8*1 {
1439 vec![1 << (idx - 8*1), 0]
1445 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>) {
1446 let secp_ctx = Secp256k1::new();
1447 let logger = Arc::new(test_utils::TestLogger::new());
1448 let chain_monitor = Arc::new(test_utils::TestChainSource::new(Network::Testnet));
1449 let network_graph = NetworkGraph::new(genesis_block(Network::Testnet).header.block_hash());
1450 let net_graph_msg_handler = NetGraphMsgHandler::new(network_graph, None, Arc::clone(&logger));
1451 // Build network from our_id to node6:
1453 // -1(1)2- node0 -1(3)2-
1455 // our_id -1(12)2- node7 -1(13)2--- node2
1457 // -1(2)2- node1 -1(4)2-
1460 // chan1 1-to-2: disabled
1461 // chan1 2-to-1: enabled, 0 fee
1463 // chan2 1-to-2: enabled, ignored fee
1464 // chan2 2-to-1: enabled, 0 fee
1466 // chan3 1-to-2: enabled, 0 fee
1467 // chan3 2-to-1: enabled, 100 msat fee
1469 // chan4 1-to-2: enabled, 100% fee
1470 // chan4 2-to-1: enabled, 0 fee
1472 // chan12 1-to-2: enabled, ignored fee
1473 // chan12 2-to-1: enabled, 0 fee
1475 // chan13 1-to-2: enabled, 200% fee
1476 // chan13 2-to-1: enabled, 0 fee
1479 // -1(5)2- node3 -1(8)2--
1483 // node2--1(6)2- node4 -1(9)2--- node6 (not in global route map)
1485 // -1(7)2- node5 -1(10)2-
1487 // Channels 5, 8, 9 and 10 are private channels.
1489 // chan5 1-to-2: enabled, 100 msat fee
1490 // chan5 2-to-1: enabled, 0 fee
1492 // chan6 1-to-2: enabled, 0 fee
1493 // chan6 2-to-1: enabled, 0 fee
1495 // chan7 1-to-2: enabled, 100% fee
1496 // chan7 2-to-1: enabled, 0 fee
1498 // chan8 1-to-2: enabled, variable fee (0 then 1000 msat)
1499 // chan8 2-to-1: enabled, 0 fee
1501 // chan9 1-to-2: enabled, 1001 msat fee
1502 // chan9 2-to-1: enabled, 0 fee
1504 // chan10 1-to-2: enabled, 0 fee
1505 // chan10 2-to-1: enabled, 0 fee
1507 // chan11 1-to-2: enabled, 0 fee
1508 // chan11 2-to-1: enabled, 0 fee
1510 let (our_privkey, _, privkeys, _) = get_nodes(&secp_ctx);
1512 add_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, &privkeys[0], ChannelFeatures::from_le_bytes(id_to_feature_flags(1)), 1);
1513 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
1514 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1515 short_channel_id: 1,
1518 cltv_expiry_delta: 0,
1519 htlc_minimum_msat: 0,
1520 htlc_maximum_msat: OptionalField::Absent,
1522 fee_proportional_millionths: 0,
1523 excess_data: Vec::new()
1526 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[0], NodeFeatures::from_le_bytes(id_to_feature_flags(1)), 0);
1528 add_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, &privkeys[1], ChannelFeatures::from_le_bytes(id_to_feature_flags(2)), 2);
1529 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
1530 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1531 short_channel_id: 2,
1534 cltv_expiry_delta: u16::max_value(),
1535 htlc_minimum_msat: 0,
1536 htlc_maximum_msat: OptionalField::Absent,
1537 fee_base_msat: u32::max_value(),
1538 fee_proportional_millionths: u32::max_value(),
1539 excess_data: Vec::new()
1541 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
1542 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1543 short_channel_id: 2,
1546 cltv_expiry_delta: 0,
1547 htlc_minimum_msat: 0,
1548 htlc_maximum_msat: OptionalField::Absent,
1550 fee_proportional_millionths: 0,
1551 excess_data: Vec::new()
1554 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[1], NodeFeatures::from_le_bytes(id_to_feature_flags(2)), 0);
1556 add_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, &privkeys[7], ChannelFeatures::from_le_bytes(id_to_feature_flags(12)), 12);
1557 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
1558 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1559 short_channel_id: 12,
1562 cltv_expiry_delta: u16::max_value(),
1563 htlc_minimum_msat: 0,
1564 htlc_maximum_msat: OptionalField::Absent,
1565 fee_base_msat: u32::max_value(),
1566 fee_proportional_millionths: u32::max_value(),
1567 excess_data: Vec::new()
1569 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
1570 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1571 short_channel_id: 12,
1574 cltv_expiry_delta: 0,
1575 htlc_minimum_msat: 0,
1576 htlc_maximum_msat: OptionalField::Absent,
1578 fee_proportional_millionths: 0,
1579 excess_data: Vec::new()
1582 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[7], NodeFeatures::from_le_bytes(id_to_feature_flags(8)), 0);
1584 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], &privkeys[2], ChannelFeatures::from_le_bytes(id_to_feature_flags(3)), 3);
1585 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
1586 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1587 short_channel_id: 3,
1590 cltv_expiry_delta: (3 << 8) | 1,
1591 htlc_minimum_msat: 0,
1592 htlc_maximum_msat: OptionalField::Absent,
1594 fee_proportional_millionths: 0,
1595 excess_data: Vec::new()
1597 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
1598 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1599 short_channel_id: 3,
1602 cltv_expiry_delta: (3 << 8) | 2,
1603 htlc_minimum_msat: 0,
1604 htlc_maximum_msat: OptionalField::Absent,
1606 fee_proportional_millionths: 0,
1607 excess_data: Vec::new()
1610 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], &privkeys[2], ChannelFeatures::from_le_bytes(id_to_feature_flags(4)), 4);
1611 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
1612 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1613 short_channel_id: 4,
1616 cltv_expiry_delta: (4 << 8) | 1,
1617 htlc_minimum_msat: 0,
1618 htlc_maximum_msat: OptionalField::Absent,
1620 fee_proportional_millionths: 1000000,
1621 excess_data: Vec::new()
1623 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
1624 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1625 short_channel_id: 4,
1628 cltv_expiry_delta: (4 << 8) | 2,
1629 htlc_minimum_msat: 0,
1630 htlc_maximum_msat: OptionalField::Absent,
1632 fee_proportional_millionths: 0,
1633 excess_data: Vec::new()
1636 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], &privkeys[2], ChannelFeatures::from_le_bytes(id_to_feature_flags(13)), 13);
1637 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
1638 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1639 short_channel_id: 13,
1642 cltv_expiry_delta: (13 << 8) | 1,
1643 htlc_minimum_msat: 0,
1644 htlc_maximum_msat: OptionalField::Absent,
1646 fee_proportional_millionths: 2000000,
1647 excess_data: Vec::new()
1649 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
1650 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1651 short_channel_id: 13,
1654 cltv_expiry_delta: (13 << 8) | 2,
1655 htlc_minimum_msat: 0,
1656 htlc_maximum_msat: OptionalField::Absent,
1658 fee_proportional_millionths: 0,
1659 excess_data: Vec::new()
1662 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[2], NodeFeatures::from_le_bytes(id_to_feature_flags(3)), 0);
1664 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], &privkeys[4], ChannelFeatures::from_le_bytes(id_to_feature_flags(6)), 6);
1665 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
1666 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1667 short_channel_id: 6,
1670 cltv_expiry_delta: (6 << 8) | 1,
1671 htlc_minimum_msat: 0,
1672 htlc_maximum_msat: OptionalField::Absent,
1674 fee_proportional_millionths: 0,
1675 excess_data: Vec::new()
1677 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
1678 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1679 short_channel_id: 6,
1682 cltv_expiry_delta: (6 << 8) | 2,
1683 htlc_minimum_msat: 0,
1684 htlc_maximum_msat: OptionalField::Absent,
1686 fee_proportional_millionths: 0,
1687 excess_data: Vec::new(),
1690 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(11)), 11);
1691 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
1692 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1693 short_channel_id: 11,
1696 cltv_expiry_delta: (11 << 8) | 1,
1697 htlc_minimum_msat: 0,
1698 htlc_maximum_msat: OptionalField::Absent,
1700 fee_proportional_millionths: 0,
1701 excess_data: Vec::new()
1703 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[3], UnsignedChannelUpdate {
1704 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1705 short_channel_id: 11,
1708 cltv_expiry_delta: (11 << 8) | 2,
1709 htlc_minimum_msat: 0,
1710 htlc_maximum_msat: OptionalField::Absent,
1712 fee_proportional_millionths: 0,
1713 excess_data: Vec::new()
1716 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[4], NodeFeatures::from_le_bytes(id_to_feature_flags(5)), 0);
1718 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[3], NodeFeatures::from_le_bytes(id_to_feature_flags(4)), 0);
1720 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], &privkeys[5], ChannelFeatures::from_le_bytes(id_to_feature_flags(7)), 7);
1721 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
1722 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1723 short_channel_id: 7,
1726 cltv_expiry_delta: (7 << 8) | 1,
1727 htlc_minimum_msat: 0,
1728 htlc_maximum_msat: OptionalField::Absent,
1730 fee_proportional_millionths: 1000000,
1731 excess_data: Vec::new()
1733 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[5], UnsignedChannelUpdate {
1734 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1735 short_channel_id: 7,
1738 cltv_expiry_delta: (7 << 8) | 2,
1739 htlc_minimum_msat: 0,
1740 htlc_maximum_msat: OptionalField::Absent,
1742 fee_proportional_millionths: 0,
1743 excess_data: Vec::new()
1746 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[5], NodeFeatures::from_le_bytes(id_to_feature_flags(6)), 0);
1748 (secp_ctx, net_graph_msg_handler, chain_monitor, logger)
1752 fn simple_route_test() {
1753 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
1754 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
1756 // Simple route to 2 via 1
1758 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)) {
1759 assert_eq!(err, "Cannot send a payment of 0 msat");
1760 } else { panic!(); }
1762 let route = get_route(&our_id, &net_graph_msg_handler.network_graph, &nodes[2], None, None, &Vec::new(), 100, 42, Arc::clone(&logger)).unwrap();
1763 assert_eq!(route.paths[0].len(), 2);
1765 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
1766 assert_eq!(route.paths[0][0].short_channel_id, 2);
1767 assert_eq!(route.paths[0][0].fee_msat, 100);
1768 assert_eq!(route.paths[0][0].cltv_expiry_delta, (4 << 8) | 1);
1769 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
1770 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
1772 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
1773 assert_eq!(route.paths[0][1].short_channel_id, 4);
1774 assert_eq!(route.paths[0][1].fee_msat, 100);
1775 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
1776 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
1777 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
1781 fn invalid_first_hop_test() {
1782 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
1783 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
1785 // Simple route to 2 via 1
1787 let our_chans = vec![get_channel_details(Some(2), our_id, InitFeatures::from_le_bytes(vec![0b11]), 100000)];
1789 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)) {
1790 assert_eq!(err, "First hop cannot have our_node_pubkey as a destination.");
1791 } else { panic!(); }
1793 let route = get_route(&our_id, &net_graph_msg_handler.network_graph, &nodes[2], None, None, &Vec::new(), 100, 42, Arc::clone(&logger)).unwrap();
1794 assert_eq!(route.paths[0].len(), 2);
1798 fn htlc_minimum_test() {
1799 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
1800 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
1802 // Simple route to 2 via 1
1804 // Disable other paths
1805 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
1806 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1807 short_channel_id: 12,
1809 flags: 2, // to disable
1810 cltv_expiry_delta: 0,
1811 htlc_minimum_msat: 0,
1812 htlc_maximum_msat: OptionalField::Absent,
1814 fee_proportional_millionths: 0,
1815 excess_data: Vec::new()
1817 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
1818 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1819 short_channel_id: 3,
1821 flags: 2, // to disable
1822 cltv_expiry_delta: 0,
1823 htlc_minimum_msat: 0,
1824 htlc_maximum_msat: OptionalField::Absent,
1826 fee_proportional_millionths: 0,
1827 excess_data: Vec::new()
1829 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
1830 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1831 short_channel_id: 13,
1833 flags: 2, // to disable
1834 cltv_expiry_delta: 0,
1835 htlc_minimum_msat: 0,
1836 htlc_maximum_msat: OptionalField::Absent,
1838 fee_proportional_millionths: 0,
1839 excess_data: Vec::new()
1841 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
1842 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1843 short_channel_id: 6,
1845 flags: 2, // to disable
1846 cltv_expiry_delta: 0,
1847 htlc_minimum_msat: 0,
1848 htlc_maximum_msat: OptionalField::Absent,
1850 fee_proportional_millionths: 0,
1851 excess_data: Vec::new()
1853 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
1854 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1855 short_channel_id: 7,
1857 flags: 2, // to disable
1858 cltv_expiry_delta: 0,
1859 htlc_minimum_msat: 0,
1860 htlc_maximum_msat: OptionalField::Absent,
1862 fee_proportional_millionths: 0,
1863 excess_data: Vec::new()
1866 // Check against amount_to_transfer_over_msat.
1867 // Set minimal HTLC of 200_000_000 msat.
1868 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
1869 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1870 short_channel_id: 2,
1873 cltv_expiry_delta: 0,
1874 htlc_minimum_msat: 200_000_000,
1875 htlc_maximum_msat: OptionalField::Absent,
1877 fee_proportional_millionths: 0,
1878 excess_data: Vec::new()
1881 // Second hop only allows to forward 199_999_999 at most, thus not allowing the first hop to
1883 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
1884 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1885 short_channel_id: 4,
1888 cltv_expiry_delta: 0,
1889 htlc_minimum_msat: 0,
1890 htlc_maximum_msat: OptionalField::Present(199_999_999),
1892 fee_proportional_millionths: 0,
1893 excess_data: Vec::new()
1896 // Not possible to send 199_999_999, because the minimum on channel=2 is 200_000_000.
1897 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)) {
1898 assert_eq!(err, "Failed to find a path to the given destination");
1899 } else { panic!(); }
1901 // Lift the restriction on the first hop.
1902 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
1903 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1904 short_channel_id: 2,
1907 cltv_expiry_delta: 0,
1908 htlc_minimum_msat: 0,
1909 htlc_maximum_msat: OptionalField::Absent,
1911 fee_proportional_millionths: 0,
1912 excess_data: Vec::new()
1915 // A payment above the minimum should pass
1916 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();
1917 assert_eq!(route.paths[0].len(), 2);
1921 fn htlc_minimum_overpay_test() {
1922 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
1923 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
1925 // A route to node#2 via two paths.
1926 // One path allows transferring 35-40 sats, another one also allows 35-40 sats.
1927 // Thus, they can't send 60 without overpaying.
1928 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
1929 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1930 short_channel_id: 2,
1933 cltv_expiry_delta: 0,
1934 htlc_minimum_msat: 35_000,
1935 htlc_maximum_msat: OptionalField::Present(40_000),
1937 fee_proportional_millionths: 0,
1938 excess_data: Vec::new()
1940 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
1941 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1942 short_channel_id: 12,
1945 cltv_expiry_delta: 0,
1946 htlc_minimum_msat: 35_000,
1947 htlc_maximum_msat: OptionalField::Present(40_000),
1949 fee_proportional_millionths: 0,
1950 excess_data: Vec::new()
1954 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
1955 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1956 short_channel_id: 13,
1959 cltv_expiry_delta: 0,
1960 htlc_minimum_msat: 0,
1961 htlc_maximum_msat: OptionalField::Absent,
1963 fee_proportional_millionths: 0,
1964 excess_data: Vec::new()
1966 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
1967 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1968 short_channel_id: 4,
1971 cltv_expiry_delta: 0,
1972 htlc_minimum_msat: 0,
1973 htlc_maximum_msat: OptionalField::Absent,
1975 fee_proportional_millionths: 0,
1976 excess_data: Vec::new()
1979 // Disable other paths
1980 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
1981 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1982 short_channel_id: 1,
1984 flags: 2, // to disable
1985 cltv_expiry_delta: 0,
1986 htlc_minimum_msat: 0,
1987 htlc_maximum_msat: OptionalField::Absent,
1989 fee_proportional_millionths: 0,
1990 excess_data: Vec::new()
1993 let route = get_route(&our_id, &net_graph_msg_handler.network_graph, &nodes[2],
1994 Some(InvoiceFeatures::known()), None, &Vec::new(), 60_000, 42, Arc::clone(&logger)).unwrap();
1995 // Overpay fees to hit htlc_minimum_msat.
1996 let overpaid_fees = route.paths[0][0].fee_msat + route.paths[1][0].fee_msat;
1997 // TODO: this could be better balanced to overpay 10k and not 15k.
1998 assert_eq!(overpaid_fees, 15_000);
2000 // Now, test that if there are 2 paths, a "cheaper" by fee path wouldn't be prioritized
2001 // while taking even more fee to match htlc_minimum_msat.
2002 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2003 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2004 short_channel_id: 12,
2007 cltv_expiry_delta: 0,
2008 htlc_minimum_msat: 65_000,
2009 htlc_maximum_msat: OptionalField::Present(80_000),
2011 fee_proportional_millionths: 0,
2012 excess_data: Vec::new()
2014 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2015 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2016 short_channel_id: 2,
2019 cltv_expiry_delta: 0,
2020 htlc_minimum_msat: 0,
2021 htlc_maximum_msat: OptionalField::Absent,
2023 fee_proportional_millionths: 0,
2024 excess_data: Vec::new()
2026 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
2027 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2028 short_channel_id: 4,
2031 cltv_expiry_delta: 0,
2032 htlc_minimum_msat: 0,
2033 htlc_maximum_msat: OptionalField::Absent,
2035 fee_proportional_millionths: 100_000,
2036 excess_data: Vec::new()
2039 let route = get_route(&our_id, &net_graph_msg_handler.network_graph, &nodes[2],
2040 Some(InvoiceFeatures::known()), None, &Vec::new(), 60_000, 42, Arc::clone(&logger)).unwrap();
2041 // Fine to overpay for htlc_minimum_msat if it allows us to save fee.
2042 assert_eq!(route.paths.len(), 1);
2043 assert_eq!(route.paths[0][0].short_channel_id, 12);
2044 let fees = route.paths[0][0].fee_msat;
2045 assert_eq!(fees, 5_000);
2047 let route = get_route(&our_id, &net_graph_msg_handler.network_graph, &nodes[2],
2048 Some(InvoiceFeatures::known()), None, &Vec::new(), 50_000, 42, Arc::clone(&logger)).unwrap();
2049 // Not fine to overpay for htlc_minimum_msat if it requires paying more than fee on
2050 // the other channel.
2051 assert_eq!(route.paths.len(), 1);
2052 assert_eq!(route.paths[0][0].short_channel_id, 2);
2053 let fees = route.paths[0][0].fee_msat;
2054 assert_eq!(fees, 5_000);
2058 fn disable_channels_test() {
2059 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
2060 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
2062 // // Disable channels 4 and 12 by flags=2
2063 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
2064 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2065 short_channel_id: 4,
2067 flags: 2, // to disable
2068 cltv_expiry_delta: 0,
2069 htlc_minimum_msat: 0,
2070 htlc_maximum_msat: OptionalField::Absent,
2072 fee_proportional_millionths: 0,
2073 excess_data: Vec::new()
2075 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2076 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2077 short_channel_id: 12,
2079 flags: 2, // to disable
2080 cltv_expiry_delta: 0,
2081 htlc_minimum_msat: 0,
2082 htlc_maximum_msat: OptionalField::Absent,
2084 fee_proportional_millionths: 0,
2085 excess_data: Vec::new()
2088 // If all the channels require some features we don't understand, route should fail
2089 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)) {
2090 assert_eq!(err, "Failed to find a path to the given destination");
2091 } else { panic!(); }
2093 // If we specify a channel to node7, that overrides our local channel view and that gets used
2094 let our_chans = vec![get_channel_details(Some(42), nodes[7].clone(), InitFeatures::from_le_bytes(vec![0b11]), 250_000_000)];
2095 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();
2096 assert_eq!(route.paths[0].len(), 2);
2098 assert_eq!(route.paths[0][0].pubkey, nodes[7]);
2099 assert_eq!(route.paths[0][0].short_channel_id, 42);
2100 assert_eq!(route.paths[0][0].fee_msat, 200);
2101 assert_eq!(route.paths[0][0].cltv_expiry_delta, (13 << 8) | 1);
2102 assert_eq!(route.paths[0][0].node_features.le_flags(), &vec![0b11]); // it should also override our view of their features
2103 assert_eq!(route.paths[0][0].channel_features.le_flags(), &Vec::<u8>::new()); // No feature flags will meet the relevant-to-channel conversion
2105 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2106 assert_eq!(route.paths[0][1].short_channel_id, 13);
2107 assert_eq!(route.paths[0][1].fee_msat, 100);
2108 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
2109 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2110 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(13));
2114 fn disable_node_test() {
2115 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
2116 let (_, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
2118 // Disable nodes 1, 2, and 8 by requiring unknown feature bits
2119 let unknown_features = NodeFeatures::known().set_unknown_feature_required();
2120 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[0], unknown_features.clone(), 1);
2121 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[1], unknown_features.clone(), 1);
2122 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[7], unknown_features.clone(), 1);
2124 // If all nodes require some features we don't understand, route should fail
2125 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)) {
2126 assert_eq!(err, "Failed to find a path to the given destination");
2127 } else { panic!(); }
2129 // If we specify a channel to node7, that overrides our local channel view and that gets used
2130 let our_chans = vec![get_channel_details(Some(42), nodes[7].clone(), InitFeatures::from_le_bytes(vec![0b11]), 250_000_000)];
2131 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();
2132 assert_eq!(route.paths[0].len(), 2);
2134 assert_eq!(route.paths[0][0].pubkey, nodes[7]);
2135 assert_eq!(route.paths[0][0].short_channel_id, 42);
2136 assert_eq!(route.paths[0][0].fee_msat, 200);
2137 assert_eq!(route.paths[0][0].cltv_expiry_delta, (13 << 8) | 1);
2138 assert_eq!(route.paths[0][0].node_features.le_flags(), &vec![0b11]); // it should also override our view of their features
2139 assert_eq!(route.paths[0][0].channel_features.le_flags(), &Vec::<u8>::new()); // No feature flags will meet the relevant-to-channel conversion
2141 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2142 assert_eq!(route.paths[0][1].short_channel_id, 13);
2143 assert_eq!(route.paths[0][1].fee_msat, 100);
2144 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
2145 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2146 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(13));
2148 // Note that we don't test disabling node 3 and failing to route to it, as we (somewhat
2149 // naively) assume that the user checked the feature bits on the invoice, which override
2150 // the node_announcement.
2154 fn our_chans_test() {
2155 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
2156 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
2158 // Route to 1 via 2 and 3 because our channel to 1 is disabled
2159 let route = get_route(&our_id, &net_graph_msg_handler.network_graph, &nodes[0], None, None, &Vec::new(), 100, 42, Arc::clone(&logger)).unwrap();
2160 assert_eq!(route.paths[0].len(), 3);
2162 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
2163 assert_eq!(route.paths[0][0].short_channel_id, 2);
2164 assert_eq!(route.paths[0][0].fee_msat, 200);
2165 assert_eq!(route.paths[0][0].cltv_expiry_delta, (4 << 8) | 1);
2166 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
2167 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
2169 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2170 assert_eq!(route.paths[0][1].short_channel_id, 4);
2171 assert_eq!(route.paths[0][1].fee_msat, 100);
2172 assert_eq!(route.paths[0][1].cltv_expiry_delta, (3 << 8) | 2);
2173 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2174 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
2176 assert_eq!(route.paths[0][2].pubkey, nodes[0]);
2177 assert_eq!(route.paths[0][2].short_channel_id, 3);
2178 assert_eq!(route.paths[0][2].fee_msat, 100);
2179 assert_eq!(route.paths[0][2].cltv_expiry_delta, 42);
2180 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(1));
2181 assert_eq!(route.paths[0][2].channel_features.le_flags(), &id_to_feature_flags(3));
2183 // If we specify a channel to node7, that overrides our local channel view and that gets used
2184 let our_chans = vec![get_channel_details(Some(42), nodes[7].clone(), InitFeatures::from_le_bytes(vec![0b11]), 250_000_000)];
2185 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();
2186 assert_eq!(route.paths[0].len(), 2);
2188 assert_eq!(route.paths[0][0].pubkey, nodes[7]);
2189 assert_eq!(route.paths[0][0].short_channel_id, 42);
2190 assert_eq!(route.paths[0][0].fee_msat, 200);
2191 assert_eq!(route.paths[0][0].cltv_expiry_delta, (13 << 8) | 1);
2192 assert_eq!(route.paths[0][0].node_features.le_flags(), &vec![0b11]);
2193 assert_eq!(route.paths[0][0].channel_features.le_flags(), &Vec::<u8>::new()); // No feature flags will meet the relevant-to-channel conversion
2195 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2196 assert_eq!(route.paths[0][1].short_channel_id, 13);
2197 assert_eq!(route.paths[0][1].fee_msat, 100);
2198 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
2199 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2200 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(13));
2203 fn last_hops(nodes: &Vec<PublicKey>) -> Vec<RouteHint> {
2204 let zero_fees = RoutingFees {
2206 proportional_millionths: 0,
2208 vec![RouteHint(vec![RouteHintHop {
2209 src_node_id: nodes[3],
2210 short_channel_id: 8,
2212 cltv_expiry_delta: (8 << 8) | 1,
2213 htlc_minimum_msat: None,
2214 htlc_maximum_msat: None,
2216 ]), RouteHint(vec![RouteHintHop {
2217 src_node_id: nodes[4],
2218 short_channel_id: 9,
2221 proportional_millionths: 0,
2223 cltv_expiry_delta: (9 << 8) | 1,
2224 htlc_minimum_msat: None,
2225 htlc_maximum_msat: None,
2226 }]), RouteHint(vec![RouteHintHop {
2227 src_node_id: nodes[5],
2228 short_channel_id: 10,
2230 cltv_expiry_delta: (10 << 8) | 1,
2231 htlc_minimum_msat: None,
2232 htlc_maximum_msat: None,
2236 fn last_hops_multi_private_channels(nodes: &Vec<PublicKey>) -> Vec<RouteHint> {
2237 let zero_fees = RoutingFees {
2239 proportional_millionths: 0,
2241 vec![RouteHint(vec![RouteHintHop {
2242 src_node_id: nodes[2],
2243 short_channel_id: 5,
2246 proportional_millionths: 0,
2248 cltv_expiry_delta: (5 << 8) | 1,
2249 htlc_minimum_msat: None,
2250 htlc_maximum_msat: None,
2252 src_node_id: nodes[3],
2253 short_channel_id: 8,
2255 cltv_expiry_delta: (8 << 8) | 1,
2256 htlc_minimum_msat: None,
2257 htlc_maximum_msat: None,
2259 ]), RouteHint(vec![RouteHintHop {
2260 src_node_id: nodes[4],
2261 short_channel_id: 9,
2264 proportional_millionths: 0,
2266 cltv_expiry_delta: (9 << 8) | 1,
2267 htlc_minimum_msat: None,
2268 htlc_maximum_msat: None,
2269 }]), RouteHint(vec![RouteHintHop {
2270 src_node_id: nodes[5],
2271 short_channel_id: 10,
2273 cltv_expiry_delta: (10 << 8) | 1,
2274 htlc_minimum_msat: None,
2275 htlc_maximum_msat: None,
2280 fn partial_route_hint_test() {
2281 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
2282 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
2284 // Simple test across 2, 3, 5, and 4 via a last_hop channel
2285 // Tests the behaviour when the RouteHint contains a suboptimal hop.
2286 // RouteHint may be partially used by the algo to build the best path.
2288 // First check that last hop can't have its source as the payee.
2289 let invalid_last_hop = RouteHint(vec![RouteHintHop {
2290 src_node_id: nodes[6],
2291 short_channel_id: 8,
2294 proportional_millionths: 0,
2296 cltv_expiry_delta: (8 << 8) | 1,
2297 htlc_minimum_msat: None,
2298 htlc_maximum_msat: None,
2301 let mut invalid_last_hops = last_hops_multi_private_channels(&nodes);
2302 invalid_last_hops.push(invalid_last_hop);
2304 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)) {
2305 assert_eq!(err, "Last hop cannot have a payee as a source.");
2306 } else { panic!(); }
2309 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();
2310 assert_eq!(route.paths[0].len(), 5);
2312 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
2313 assert_eq!(route.paths[0][0].short_channel_id, 2);
2314 assert_eq!(route.paths[0][0].fee_msat, 100);
2315 assert_eq!(route.paths[0][0].cltv_expiry_delta, (4 << 8) | 1);
2316 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
2317 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
2319 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2320 assert_eq!(route.paths[0][1].short_channel_id, 4);
2321 assert_eq!(route.paths[0][1].fee_msat, 0);
2322 assert_eq!(route.paths[0][1].cltv_expiry_delta, (6 << 8) | 1);
2323 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2324 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
2326 assert_eq!(route.paths[0][2].pubkey, nodes[4]);
2327 assert_eq!(route.paths[0][2].short_channel_id, 6);
2328 assert_eq!(route.paths[0][2].fee_msat, 0);
2329 assert_eq!(route.paths[0][2].cltv_expiry_delta, (11 << 8) | 1);
2330 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(5));
2331 assert_eq!(route.paths[0][2].channel_features.le_flags(), &id_to_feature_flags(6));
2333 assert_eq!(route.paths[0][3].pubkey, nodes[3]);
2334 assert_eq!(route.paths[0][3].short_channel_id, 11);
2335 assert_eq!(route.paths[0][3].fee_msat, 0);
2336 assert_eq!(route.paths[0][3].cltv_expiry_delta, (8 << 8) | 1);
2337 // If we have a peer in the node map, we'll use their features here since we don't have
2338 // a way of figuring out their features from the invoice:
2339 assert_eq!(route.paths[0][3].node_features.le_flags(), &id_to_feature_flags(4));
2340 assert_eq!(route.paths[0][3].channel_features.le_flags(), &id_to_feature_flags(11));
2342 assert_eq!(route.paths[0][4].pubkey, nodes[6]);
2343 assert_eq!(route.paths[0][4].short_channel_id, 8);
2344 assert_eq!(route.paths[0][4].fee_msat, 100);
2345 assert_eq!(route.paths[0][4].cltv_expiry_delta, 42);
2346 assert_eq!(route.paths[0][4].node_features.le_flags(), &Vec::<u8>::new()); // We dont pass flags in from invoices yet
2347 assert_eq!(route.paths[0][4].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
2350 fn empty_last_hop(nodes: &Vec<PublicKey>) -> Vec<RouteHint> {
2351 let zero_fees = RoutingFees {
2353 proportional_millionths: 0,
2355 vec![RouteHint(vec![RouteHintHop {
2356 src_node_id: nodes[3],
2357 short_channel_id: 8,
2359 cltv_expiry_delta: (8 << 8) | 1,
2360 htlc_minimum_msat: None,
2361 htlc_maximum_msat: None,
2362 }]), RouteHint(vec![
2364 ]), RouteHint(vec![RouteHintHop {
2365 src_node_id: nodes[5],
2366 short_channel_id: 10,
2368 cltv_expiry_delta: (10 << 8) | 1,
2369 htlc_minimum_msat: None,
2370 htlc_maximum_msat: None,
2375 fn ignores_empty_last_hops_test() {
2376 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
2377 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
2379 // Test handling of an empty RouteHint passed in Invoice.
2381 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();
2382 assert_eq!(route.paths[0].len(), 5);
2384 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
2385 assert_eq!(route.paths[0][0].short_channel_id, 2);
2386 assert_eq!(route.paths[0][0].fee_msat, 100);
2387 assert_eq!(route.paths[0][0].cltv_expiry_delta, (4 << 8) | 1);
2388 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
2389 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
2391 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2392 assert_eq!(route.paths[0][1].short_channel_id, 4);
2393 assert_eq!(route.paths[0][1].fee_msat, 0);
2394 assert_eq!(route.paths[0][1].cltv_expiry_delta, (6 << 8) | 1);
2395 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2396 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
2398 assert_eq!(route.paths[0][2].pubkey, nodes[4]);
2399 assert_eq!(route.paths[0][2].short_channel_id, 6);
2400 assert_eq!(route.paths[0][2].fee_msat, 0);
2401 assert_eq!(route.paths[0][2].cltv_expiry_delta, (11 << 8) | 1);
2402 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(5));
2403 assert_eq!(route.paths[0][2].channel_features.le_flags(), &id_to_feature_flags(6));
2405 assert_eq!(route.paths[0][3].pubkey, nodes[3]);
2406 assert_eq!(route.paths[0][3].short_channel_id, 11);
2407 assert_eq!(route.paths[0][3].fee_msat, 0);
2408 assert_eq!(route.paths[0][3].cltv_expiry_delta, (8 << 8) | 1);
2409 // If we have a peer in the node map, we'll use their features here since we don't have
2410 // a way of figuring out their features from the invoice:
2411 assert_eq!(route.paths[0][3].node_features.le_flags(), &id_to_feature_flags(4));
2412 assert_eq!(route.paths[0][3].channel_features.le_flags(), &id_to_feature_flags(11));
2414 assert_eq!(route.paths[0][4].pubkey, nodes[6]);
2415 assert_eq!(route.paths[0][4].short_channel_id, 8);
2416 assert_eq!(route.paths[0][4].fee_msat, 100);
2417 assert_eq!(route.paths[0][4].cltv_expiry_delta, 42);
2418 assert_eq!(route.paths[0][4].node_features.le_flags(), &Vec::<u8>::new()); // We dont pass flags in from invoices yet
2419 assert_eq!(route.paths[0][4].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
2422 fn multi_hint_last_hops(nodes: &Vec<PublicKey>) -> Vec<RouteHint> {
2423 let zero_fees = RoutingFees {
2425 proportional_millionths: 0,
2427 vec![RouteHint(vec![RouteHintHop {
2428 src_node_id: nodes[2],
2429 short_channel_id: 5,
2432 proportional_millionths: 0,
2434 cltv_expiry_delta: (5 << 8) | 1,
2435 htlc_minimum_msat: None,
2436 htlc_maximum_msat: None,
2438 src_node_id: nodes[3],
2439 short_channel_id: 8,
2441 cltv_expiry_delta: (8 << 8) | 1,
2442 htlc_minimum_msat: None,
2443 htlc_maximum_msat: None,
2444 }]), RouteHint(vec![RouteHintHop {
2445 src_node_id: nodes[5],
2446 short_channel_id: 10,
2448 cltv_expiry_delta: (10 << 8) | 1,
2449 htlc_minimum_msat: None,
2450 htlc_maximum_msat: None,
2455 fn multi_hint_last_hops_test() {
2456 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
2457 let (_, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
2458 // Test through channels 2, 3, 5, 8.
2459 // Test shows that multiple hop hints are considered.
2461 // Disabling channels 6 & 7 by flags=2
2462 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
2463 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2464 short_channel_id: 6,
2466 flags: 2, // to disable
2467 cltv_expiry_delta: 0,
2468 htlc_minimum_msat: 0,
2469 htlc_maximum_msat: OptionalField::Absent,
2471 fee_proportional_millionths: 0,
2472 excess_data: Vec::new()
2474 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
2475 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2476 short_channel_id: 7,
2478 flags: 2, // to disable
2479 cltv_expiry_delta: 0,
2480 htlc_minimum_msat: 0,
2481 htlc_maximum_msat: OptionalField::Absent,
2483 fee_proportional_millionths: 0,
2484 excess_data: Vec::new()
2487 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();
2488 assert_eq!(route.paths[0].len(), 4);
2490 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
2491 assert_eq!(route.paths[0][0].short_channel_id, 2);
2492 assert_eq!(route.paths[0][0].fee_msat, 200);
2493 assert_eq!(route.paths[0][0].cltv_expiry_delta, 1025);
2494 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
2495 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
2497 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2498 assert_eq!(route.paths[0][1].short_channel_id, 4);
2499 assert_eq!(route.paths[0][1].fee_msat, 100);
2500 assert_eq!(route.paths[0][1].cltv_expiry_delta, 1281);
2501 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2502 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
2504 assert_eq!(route.paths[0][2].pubkey, nodes[3]);
2505 assert_eq!(route.paths[0][2].short_channel_id, 5);
2506 assert_eq!(route.paths[0][2].fee_msat, 0);
2507 assert_eq!(route.paths[0][2].cltv_expiry_delta, 2049);
2508 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(4));
2509 assert_eq!(route.paths[0][2].channel_features.le_flags(), &Vec::<u8>::new());
2511 assert_eq!(route.paths[0][3].pubkey, nodes[6]);
2512 assert_eq!(route.paths[0][3].short_channel_id, 8);
2513 assert_eq!(route.paths[0][3].fee_msat, 100);
2514 assert_eq!(route.paths[0][3].cltv_expiry_delta, 42);
2515 assert_eq!(route.paths[0][3].node_features.le_flags(), &Vec::<u8>::new()); // We dont pass flags in from invoices yet
2516 assert_eq!(route.paths[0][3].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
2519 fn last_hops_with_public_channel(nodes: &Vec<PublicKey>) -> Vec<RouteHint> {
2520 let zero_fees = RoutingFees {
2522 proportional_millionths: 0,
2524 vec![RouteHint(vec![RouteHintHop {
2525 src_node_id: nodes[4],
2526 short_channel_id: 11,
2528 cltv_expiry_delta: (11 << 8) | 1,
2529 htlc_minimum_msat: None,
2530 htlc_maximum_msat: None,
2532 src_node_id: nodes[3],
2533 short_channel_id: 8,
2535 cltv_expiry_delta: (8 << 8) | 1,
2536 htlc_minimum_msat: None,
2537 htlc_maximum_msat: None,
2538 }]), RouteHint(vec![RouteHintHop {
2539 src_node_id: nodes[4],
2540 short_channel_id: 9,
2543 proportional_millionths: 0,
2545 cltv_expiry_delta: (9 << 8) | 1,
2546 htlc_minimum_msat: None,
2547 htlc_maximum_msat: None,
2548 }]), RouteHint(vec![RouteHintHop {
2549 src_node_id: nodes[5],
2550 short_channel_id: 10,
2552 cltv_expiry_delta: (10 << 8) | 1,
2553 htlc_minimum_msat: None,
2554 htlc_maximum_msat: None,
2559 fn last_hops_with_public_channel_test() {
2560 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
2561 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
2562 // This test shows that public routes can be present in the invoice
2563 // which would be handled in the same manner.
2565 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();
2566 assert_eq!(route.paths[0].len(), 5);
2568 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
2569 assert_eq!(route.paths[0][0].short_channel_id, 2);
2570 assert_eq!(route.paths[0][0].fee_msat, 100);
2571 assert_eq!(route.paths[0][0].cltv_expiry_delta, (4 << 8) | 1);
2572 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
2573 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
2575 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2576 assert_eq!(route.paths[0][1].short_channel_id, 4);
2577 assert_eq!(route.paths[0][1].fee_msat, 0);
2578 assert_eq!(route.paths[0][1].cltv_expiry_delta, (6 << 8) | 1);
2579 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2580 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
2582 assert_eq!(route.paths[0][2].pubkey, nodes[4]);
2583 assert_eq!(route.paths[0][2].short_channel_id, 6);
2584 assert_eq!(route.paths[0][2].fee_msat, 0);
2585 assert_eq!(route.paths[0][2].cltv_expiry_delta, (11 << 8) | 1);
2586 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(5));
2587 assert_eq!(route.paths[0][2].channel_features.le_flags(), &id_to_feature_flags(6));
2589 assert_eq!(route.paths[0][3].pubkey, nodes[3]);
2590 assert_eq!(route.paths[0][3].short_channel_id, 11);
2591 assert_eq!(route.paths[0][3].fee_msat, 0);
2592 assert_eq!(route.paths[0][3].cltv_expiry_delta, (8 << 8) | 1);
2593 // If we have a peer in the node map, we'll use their features here since we don't have
2594 // a way of figuring out their features from the invoice:
2595 assert_eq!(route.paths[0][3].node_features.le_flags(), &id_to_feature_flags(4));
2596 assert_eq!(route.paths[0][3].channel_features.le_flags(), &Vec::<u8>::new());
2598 assert_eq!(route.paths[0][4].pubkey, nodes[6]);
2599 assert_eq!(route.paths[0][4].short_channel_id, 8);
2600 assert_eq!(route.paths[0][4].fee_msat, 100);
2601 assert_eq!(route.paths[0][4].cltv_expiry_delta, 42);
2602 assert_eq!(route.paths[0][4].node_features.le_flags(), &Vec::<u8>::new()); // We dont pass flags in from invoices yet
2603 assert_eq!(route.paths[0][4].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
2607 fn our_chans_last_hop_connect_test() {
2608 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
2609 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
2611 // Simple test with outbound channel to 4 to test that last_hops and first_hops connect
2612 let our_chans = vec![get_channel_details(Some(42), nodes[3].clone(), InitFeatures::from_le_bytes(vec![0b11]), 250_000_000)];
2613 let mut last_hops = last_hops(&nodes);
2614 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();
2615 assert_eq!(route.paths[0].len(), 2);
2617 assert_eq!(route.paths[0][0].pubkey, nodes[3]);
2618 assert_eq!(route.paths[0][0].short_channel_id, 42);
2619 assert_eq!(route.paths[0][0].fee_msat, 0);
2620 assert_eq!(route.paths[0][0].cltv_expiry_delta, (8 << 8) | 1);
2621 assert_eq!(route.paths[0][0].node_features.le_flags(), &vec![0b11]);
2622 assert_eq!(route.paths[0][0].channel_features.le_flags(), &Vec::<u8>::new()); // No feature flags will meet the relevant-to-channel conversion
2624 assert_eq!(route.paths[0][1].pubkey, nodes[6]);
2625 assert_eq!(route.paths[0][1].short_channel_id, 8);
2626 assert_eq!(route.paths[0][1].fee_msat, 100);
2627 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
2628 assert_eq!(route.paths[0][1].node_features.le_flags(), &Vec::<u8>::new()); // We dont pass flags in from invoices yet
2629 assert_eq!(route.paths[0][1].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
2631 last_hops[0].0[0].fees.base_msat = 1000;
2633 // Revert to via 6 as the fee on 8 goes up
2634 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();
2635 assert_eq!(route.paths[0].len(), 4);
2637 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
2638 assert_eq!(route.paths[0][0].short_channel_id, 2);
2639 assert_eq!(route.paths[0][0].fee_msat, 200); // fee increased as its % of value transferred across node
2640 assert_eq!(route.paths[0][0].cltv_expiry_delta, (4 << 8) | 1);
2641 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
2642 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
2644 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2645 assert_eq!(route.paths[0][1].short_channel_id, 4);
2646 assert_eq!(route.paths[0][1].fee_msat, 100);
2647 assert_eq!(route.paths[0][1].cltv_expiry_delta, (7 << 8) | 1);
2648 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2649 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
2651 assert_eq!(route.paths[0][2].pubkey, nodes[5]);
2652 assert_eq!(route.paths[0][2].short_channel_id, 7);
2653 assert_eq!(route.paths[0][2].fee_msat, 0);
2654 assert_eq!(route.paths[0][2].cltv_expiry_delta, (10 << 8) | 1);
2655 // If we have a peer in the node map, we'll use their features here since we don't have
2656 // a way of figuring out their features from the invoice:
2657 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(6));
2658 assert_eq!(route.paths[0][2].channel_features.le_flags(), &id_to_feature_flags(7));
2660 assert_eq!(route.paths[0][3].pubkey, nodes[6]);
2661 assert_eq!(route.paths[0][3].short_channel_id, 10);
2662 assert_eq!(route.paths[0][3].fee_msat, 100);
2663 assert_eq!(route.paths[0][3].cltv_expiry_delta, 42);
2664 assert_eq!(route.paths[0][3].node_features.le_flags(), &Vec::<u8>::new()); // We dont pass flags in from invoices yet
2665 assert_eq!(route.paths[0][3].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
2667 // ...but still use 8 for larger payments as 6 has a variable feerate
2668 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();
2669 assert_eq!(route.paths[0].len(), 5);
2671 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
2672 assert_eq!(route.paths[0][0].short_channel_id, 2);
2673 assert_eq!(route.paths[0][0].fee_msat, 3000);
2674 assert_eq!(route.paths[0][0].cltv_expiry_delta, (4 << 8) | 1);
2675 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
2676 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
2678 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2679 assert_eq!(route.paths[0][1].short_channel_id, 4);
2680 assert_eq!(route.paths[0][1].fee_msat, 0);
2681 assert_eq!(route.paths[0][1].cltv_expiry_delta, (6 << 8) | 1);
2682 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2683 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
2685 assert_eq!(route.paths[0][2].pubkey, nodes[4]);
2686 assert_eq!(route.paths[0][2].short_channel_id, 6);
2687 assert_eq!(route.paths[0][2].fee_msat, 0);
2688 assert_eq!(route.paths[0][2].cltv_expiry_delta, (11 << 8) | 1);
2689 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(5));
2690 assert_eq!(route.paths[0][2].channel_features.le_flags(), &id_to_feature_flags(6));
2692 assert_eq!(route.paths[0][3].pubkey, nodes[3]);
2693 assert_eq!(route.paths[0][3].short_channel_id, 11);
2694 assert_eq!(route.paths[0][3].fee_msat, 1000);
2695 assert_eq!(route.paths[0][3].cltv_expiry_delta, (8 << 8) | 1);
2696 // If we have a peer in the node map, we'll use their features here since we don't have
2697 // a way of figuring out their features from the invoice:
2698 assert_eq!(route.paths[0][3].node_features.le_flags(), &id_to_feature_flags(4));
2699 assert_eq!(route.paths[0][3].channel_features.le_flags(), &id_to_feature_flags(11));
2701 assert_eq!(route.paths[0][4].pubkey, nodes[6]);
2702 assert_eq!(route.paths[0][4].short_channel_id, 8);
2703 assert_eq!(route.paths[0][4].fee_msat, 2000);
2704 assert_eq!(route.paths[0][4].cltv_expiry_delta, 42);
2705 assert_eq!(route.paths[0][4].node_features.le_flags(), &Vec::<u8>::new()); // We dont pass flags in from invoices yet
2706 assert_eq!(route.paths[0][4].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
2709 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> {
2710 let source_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&hex::decode(format!("{:02}", 41).repeat(32)).unwrap()[..]).unwrap());
2711 let middle_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&hex::decode(format!("{:02}", 42).repeat(32)).unwrap()[..]).unwrap());
2712 let target_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&hex::decode(format!("{:02}", 43).repeat(32)).unwrap()[..]).unwrap());
2714 // If we specify a channel to a middle hop, that overrides our local channel view and that gets used
2715 let last_hops = RouteHint(vec![RouteHintHop {
2716 src_node_id: middle_node_id,
2717 short_channel_id: 8,
2720 proportional_millionths: last_hop_fee_prop,
2722 cltv_expiry_delta: (8 << 8) | 1,
2723 htlc_minimum_msat: None,
2724 htlc_maximum_msat: last_hop_htlc_max,
2726 let our_chans = vec![get_channel_details(Some(42), middle_node_id, InitFeatures::from_le_bytes(vec![0b11]), outbound_capacity_msat)];
2727 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()))
2731 fn unannounced_path_test() {
2732 // We should be able to send a payment to a destination without any help of a routing graph
2733 // if we have a channel with a common counterparty that appears in the first and last hop
2735 let route = do_unannounced_path_test(None, 1, 2000000, 1000000).unwrap();
2737 let middle_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&hex::decode(format!("{:02}", 42).repeat(32)).unwrap()[..]).unwrap());
2738 let target_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&hex::decode(format!("{:02}", 43).repeat(32)).unwrap()[..]).unwrap());
2739 assert_eq!(route.paths[0].len(), 2);
2741 assert_eq!(route.paths[0][0].pubkey, middle_node_id);
2742 assert_eq!(route.paths[0][0].short_channel_id, 42);
2743 assert_eq!(route.paths[0][0].fee_msat, 1001);
2744 assert_eq!(route.paths[0][0].cltv_expiry_delta, (8 << 8) | 1);
2745 assert_eq!(route.paths[0][0].node_features.le_flags(), &[0b11]);
2746 assert_eq!(route.paths[0][0].channel_features.le_flags(), &[0; 0]); // We can't learn any flags from invoices, sadly
2748 assert_eq!(route.paths[0][1].pubkey, target_node_id);
2749 assert_eq!(route.paths[0][1].short_channel_id, 8);
2750 assert_eq!(route.paths[0][1].fee_msat, 1000000);
2751 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
2752 assert_eq!(route.paths[0][1].node_features.le_flags(), &[0; 0]); // We dont pass flags in from invoices yet
2753 assert_eq!(route.paths[0][1].channel_features.le_flags(), &[0; 0]); // We can't learn any flags from invoices, sadly
2757 fn overflow_unannounced_path_test_liquidity_underflow() {
2758 // Previously, when we had a last-hop hint connected directly to a first-hop channel, where
2759 // the last-hop had a fee which overflowed a u64, we'd panic.
2760 // This was due to us adding the first-hop from us unconditionally, causing us to think
2761 // we'd built a path (as our node is in the "best candidate" set), when we had not.
2762 // In this test, we previously hit a subtraction underflow due to having less available
2763 // liquidity at the last hop than 0.
2764 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());
2768 fn overflow_unannounced_path_test_feerate_overflow() {
2769 // This tests for the same case as above, except instead of hitting a subtraction
2770 // underflow, we hit a case where the fee charged at a hop overflowed.
2771 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());
2775 fn available_amount_while_routing_test() {
2776 // Tests whether we choose the correct available channel amount while routing.
2778 let (secp_ctx, mut net_graph_msg_handler, chain_monitor, logger) = build_graph();
2779 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
2781 // We will use a simple single-path route from
2782 // our node to node2 via node0: channels {1, 3}.
2784 // First disable all other paths.
2785 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2786 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2787 short_channel_id: 2,
2790 cltv_expiry_delta: 0,
2791 htlc_minimum_msat: 0,
2792 htlc_maximum_msat: OptionalField::Present(100_000),
2794 fee_proportional_millionths: 0,
2795 excess_data: Vec::new()
2797 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2798 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2799 short_channel_id: 12,
2802 cltv_expiry_delta: 0,
2803 htlc_minimum_msat: 0,
2804 htlc_maximum_msat: OptionalField::Present(100_000),
2806 fee_proportional_millionths: 0,
2807 excess_data: Vec::new()
2810 // Make the first channel (#1) very permissive,
2811 // and we will be testing all limits on the second channel.
2812 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2813 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2814 short_channel_id: 1,
2817 cltv_expiry_delta: 0,
2818 htlc_minimum_msat: 0,
2819 htlc_maximum_msat: OptionalField::Present(1_000_000_000),
2821 fee_proportional_millionths: 0,
2822 excess_data: Vec::new()
2825 // First, let's see if routing works if we have absolutely no idea about the available amount.
2826 // In this case, it should be set to 250_000 sats.
2827 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
2828 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2829 short_channel_id: 3,
2832 cltv_expiry_delta: 0,
2833 htlc_minimum_msat: 0,
2834 htlc_maximum_msat: OptionalField::Absent,
2836 fee_proportional_millionths: 0,
2837 excess_data: Vec::new()
2841 // Attempt to route more than available results in a failure.
2842 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id, &net_graph_msg_handler.network_graph, &nodes[2],
2843 Some(InvoiceFeatures::known()), None, &Vec::new(), 250_000_001, 42, Arc::clone(&logger)) {
2844 assert_eq!(err, "Failed to find a sufficient route to the given destination");
2845 } else { panic!(); }
2849 // Now, attempt to route an exact amount we have should be fine.
2850 let route = get_route(&our_id, &net_graph_msg_handler.network_graph, &nodes[2],
2851 Some(InvoiceFeatures::known()), None, &Vec::new(), 250_000_000, 42, Arc::clone(&logger)).unwrap();
2852 assert_eq!(route.paths.len(), 1);
2853 let path = route.paths.last().unwrap();
2854 assert_eq!(path.len(), 2);
2855 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
2856 assert_eq!(path.last().unwrap().fee_msat, 250_000_000);
2859 // Check that setting outbound_capacity_msat in first_hops limits the channels.
2860 // Disable channel #1 and use another first hop.
2861 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2862 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2863 short_channel_id: 1,
2866 cltv_expiry_delta: 0,
2867 htlc_minimum_msat: 0,
2868 htlc_maximum_msat: OptionalField::Present(1_000_000_000),
2870 fee_proportional_millionths: 0,
2871 excess_data: Vec::new()
2874 // Now, limit the first_hop by the outbound_capacity_msat of 200_000 sats.
2875 let our_chans = vec![get_channel_details(Some(42), nodes[0].clone(), InitFeatures::from_le_bytes(vec![0b11]), 200_000_000)];
2878 // Attempt to route more than available results in a failure.
2879 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id, &net_graph_msg_handler.network_graph, &nodes[2],
2880 Some(InvoiceFeatures::known()), Some(&our_chans.iter().collect::<Vec<_>>()), &Vec::new(), 200_000_001, 42, Arc::clone(&logger)) {
2881 assert_eq!(err, "Failed to find a sufficient route to the given destination");
2882 } else { panic!(); }
2886 // Now, attempt to route an exact amount we have should be fine.
2887 let route = get_route(&our_id, &net_graph_msg_handler.network_graph, &nodes[2],
2888 Some(InvoiceFeatures::known()), Some(&our_chans.iter().collect::<Vec<_>>()), &Vec::new(), 200_000_000, 42, Arc::clone(&logger)).unwrap();
2889 assert_eq!(route.paths.len(), 1);
2890 let path = route.paths.last().unwrap();
2891 assert_eq!(path.len(), 2);
2892 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
2893 assert_eq!(path.last().unwrap().fee_msat, 200_000_000);
2896 // Enable channel #1 back.
2897 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2898 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2899 short_channel_id: 1,
2902 cltv_expiry_delta: 0,
2903 htlc_minimum_msat: 0,
2904 htlc_maximum_msat: OptionalField::Present(1_000_000_000),
2906 fee_proportional_millionths: 0,
2907 excess_data: Vec::new()
2911 // Now let's see if routing works if we know only htlc_maximum_msat.
2912 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
2913 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2914 short_channel_id: 3,
2917 cltv_expiry_delta: 0,
2918 htlc_minimum_msat: 0,
2919 htlc_maximum_msat: OptionalField::Present(15_000),
2921 fee_proportional_millionths: 0,
2922 excess_data: Vec::new()
2926 // Attempt to route more than available results in a failure.
2927 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id, &net_graph_msg_handler.network_graph, &nodes[2],
2928 Some(InvoiceFeatures::known()), None, &Vec::new(), 15_001, 42, Arc::clone(&logger)) {
2929 assert_eq!(err, "Failed to find a sufficient route to the given destination");
2930 } else { panic!(); }
2934 // Now, attempt to route an exact amount we have should be fine.
2935 let route = get_route(&our_id, &net_graph_msg_handler.network_graph, &nodes[2],
2936 Some(InvoiceFeatures::known()), None, &Vec::new(), 15_000, 42, Arc::clone(&logger)).unwrap();
2937 assert_eq!(route.paths.len(), 1);
2938 let path = route.paths.last().unwrap();
2939 assert_eq!(path.len(), 2);
2940 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
2941 assert_eq!(path.last().unwrap().fee_msat, 15_000);
2944 // Now let's see if routing works if we know only capacity from the UTXO.
2946 // We can't change UTXO capacity on the fly, so we'll disable
2947 // the existing channel and add another one with the capacity we need.
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: 3,
2953 cltv_expiry_delta: 0,
2954 htlc_minimum_msat: 0,
2955 htlc_maximum_msat: OptionalField::Absent,
2957 fee_proportional_millionths: 0,
2958 excess_data: Vec::new()
2961 let good_script = Builder::new().push_opcode(opcodes::all::OP_PUSHNUM_2)
2962 .push_slice(&PublicKey::from_secret_key(&secp_ctx, &privkeys[0]).serialize())
2963 .push_slice(&PublicKey::from_secret_key(&secp_ctx, &privkeys[2]).serialize())
2964 .push_opcode(opcodes::all::OP_PUSHNUM_2)
2965 .push_opcode(opcodes::all::OP_CHECKMULTISIG).into_script().to_v0_p2wsh();
2967 *chain_monitor.utxo_ret.lock().unwrap() = Ok(TxOut { value: 15, script_pubkey: good_script.clone() });
2968 net_graph_msg_handler.add_chain_access(Some(chain_monitor));
2970 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], &privkeys[2], ChannelFeatures::from_le_bytes(id_to_feature_flags(3)), 333);
2971 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
2972 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2973 short_channel_id: 333,
2976 cltv_expiry_delta: (3 << 8) | 1,
2977 htlc_minimum_msat: 0,
2978 htlc_maximum_msat: OptionalField::Absent,
2980 fee_proportional_millionths: 0,
2981 excess_data: Vec::new()
2983 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
2984 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2985 short_channel_id: 333,
2988 cltv_expiry_delta: (3 << 8) | 2,
2989 htlc_minimum_msat: 0,
2990 htlc_maximum_msat: OptionalField::Absent,
2992 fee_proportional_millionths: 0,
2993 excess_data: Vec::new()
2997 // Attempt to route more than available results in a failure.
2998 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id, &net_graph_msg_handler.network_graph, &nodes[2],
2999 Some(InvoiceFeatures::known()), None, &Vec::new(), 15_001, 42, Arc::clone(&logger)) {
3000 assert_eq!(err, "Failed to find a sufficient route to the given destination");
3001 } else { panic!(); }
3005 // Now, attempt to route an exact amount we have should be fine.
3006 let route = get_route(&our_id, &net_graph_msg_handler.network_graph, &nodes[2],
3007 Some(InvoiceFeatures::known()), None, &Vec::new(), 15_000, 42, Arc::clone(&logger)).unwrap();
3008 assert_eq!(route.paths.len(), 1);
3009 let path = route.paths.last().unwrap();
3010 assert_eq!(path.len(), 2);
3011 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
3012 assert_eq!(path.last().unwrap().fee_msat, 15_000);
3015 // Now let's see if routing chooses htlc_maximum_msat over UTXO capacity.
3016 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3017 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3018 short_channel_id: 333,
3021 cltv_expiry_delta: 0,
3022 htlc_minimum_msat: 0,
3023 htlc_maximum_msat: OptionalField::Present(10_000),
3025 fee_proportional_millionths: 0,
3026 excess_data: Vec::new()
3030 // Attempt to route more than available results in a failure.
3031 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id, &net_graph_msg_handler.network_graph, &nodes[2],
3032 Some(InvoiceFeatures::known()), None, &Vec::new(), 10_001, 42, Arc::clone(&logger)) {
3033 assert_eq!(err, "Failed to find a sufficient route to the given destination");
3034 } else { panic!(); }
3038 // Now, attempt to route an exact amount we have should be fine.
3039 let route = get_route(&our_id, &net_graph_msg_handler.network_graph, &nodes[2],
3040 Some(InvoiceFeatures::known()), None, &Vec::new(), 10_000, 42, Arc::clone(&logger)).unwrap();
3041 assert_eq!(route.paths.len(), 1);
3042 let path = route.paths.last().unwrap();
3043 assert_eq!(path.len(), 2);
3044 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
3045 assert_eq!(path.last().unwrap().fee_msat, 10_000);
3050 fn available_liquidity_last_hop_test() {
3051 // Check that available liquidity properly limits the path even when only
3052 // one of the latter hops is limited.
3053 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
3054 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3056 // Path via {node7, node2, node4} is channels {12, 13, 6, 11}.
3057 // {12, 13, 11} have the capacities of 100, {6} has a capacity of 50.
3058 // Total capacity: 50 sats.
3060 // Disable other potential paths.
3061 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3062 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3063 short_channel_id: 2,
3066 cltv_expiry_delta: 0,
3067 htlc_minimum_msat: 0,
3068 htlc_maximum_msat: OptionalField::Present(100_000),
3070 fee_proportional_millionths: 0,
3071 excess_data: Vec::new()
3073 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3074 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3075 short_channel_id: 7,
3078 cltv_expiry_delta: 0,
3079 htlc_minimum_msat: 0,
3080 htlc_maximum_msat: OptionalField::Present(100_000),
3082 fee_proportional_millionths: 0,
3083 excess_data: Vec::new()
3088 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3089 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3090 short_channel_id: 12,
3093 cltv_expiry_delta: 0,
3094 htlc_minimum_msat: 0,
3095 htlc_maximum_msat: OptionalField::Present(100_000),
3097 fee_proportional_millionths: 0,
3098 excess_data: Vec::new()
3100 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
3101 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3102 short_channel_id: 13,
3105 cltv_expiry_delta: 0,
3106 htlc_minimum_msat: 0,
3107 htlc_maximum_msat: OptionalField::Present(100_000),
3109 fee_proportional_millionths: 0,
3110 excess_data: Vec::new()
3113 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3114 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3115 short_channel_id: 6,
3118 cltv_expiry_delta: 0,
3119 htlc_minimum_msat: 0,
3120 htlc_maximum_msat: OptionalField::Present(50_000),
3122 fee_proportional_millionths: 0,
3123 excess_data: Vec::new()
3125 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
3126 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3127 short_channel_id: 11,
3130 cltv_expiry_delta: 0,
3131 htlc_minimum_msat: 0,
3132 htlc_maximum_msat: OptionalField::Present(100_000),
3134 fee_proportional_millionths: 0,
3135 excess_data: Vec::new()
3138 // Attempt to route more than available results in a failure.
3139 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id, &net_graph_msg_handler.network_graph, &nodes[3],
3140 Some(InvoiceFeatures::known()), None, &Vec::new(), 60_000, 42, Arc::clone(&logger)) {
3141 assert_eq!(err, "Failed to find a sufficient route to the given destination");
3142 } else { panic!(); }
3146 // Now, attempt to route 49 sats (just a bit below the capacity).
3147 let route = get_route(&our_id, &net_graph_msg_handler.network_graph, &nodes[3],
3148 Some(InvoiceFeatures::known()), None, &Vec::new(), 49_000, 42, Arc::clone(&logger)).unwrap();
3149 assert_eq!(route.paths.len(), 1);
3150 let mut total_amount_paid_msat = 0;
3151 for path in &route.paths {
3152 assert_eq!(path.len(), 4);
3153 assert_eq!(path.last().unwrap().pubkey, nodes[3]);
3154 total_amount_paid_msat += path.last().unwrap().fee_msat;
3156 assert_eq!(total_amount_paid_msat, 49_000);
3160 // Attempt to route an exact amount is also fine
3161 let route = get_route(&our_id, &net_graph_msg_handler.network_graph, &nodes[3],
3162 Some(InvoiceFeatures::known()), None, &Vec::new(), 50_000, 42, Arc::clone(&logger)).unwrap();
3163 assert_eq!(route.paths.len(), 1);
3164 let mut total_amount_paid_msat = 0;
3165 for path in &route.paths {
3166 assert_eq!(path.len(), 4);
3167 assert_eq!(path.last().unwrap().pubkey, nodes[3]);
3168 total_amount_paid_msat += path.last().unwrap().fee_msat;
3170 assert_eq!(total_amount_paid_msat, 50_000);
3175 fn ignore_fee_first_hop_test() {
3176 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
3177 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3179 // Path via node0 is channels {1, 3}. Limit them to 100 and 50 sats (total limit 50).
3180 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3181 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3182 short_channel_id: 1,
3185 cltv_expiry_delta: 0,
3186 htlc_minimum_msat: 0,
3187 htlc_maximum_msat: OptionalField::Present(100_000),
3188 fee_base_msat: 1_000_000,
3189 fee_proportional_millionths: 0,
3190 excess_data: Vec::new()
3192 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3193 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3194 short_channel_id: 3,
3197 cltv_expiry_delta: 0,
3198 htlc_minimum_msat: 0,
3199 htlc_maximum_msat: OptionalField::Present(50_000),
3201 fee_proportional_millionths: 0,
3202 excess_data: Vec::new()
3206 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();
3207 assert_eq!(route.paths.len(), 1);
3208 let mut total_amount_paid_msat = 0;
3209 for path in &route.paths {
3210 assert_eq!(path.len(), 2);
3211 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
3212 total_amount_paid_msat += path.last().unwrap().fee_msat;
3214 assert_eq!(total_amount_paid_msat, 50_000);
3219 fn simple_mpp_route_test() {
3220 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
3221 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3223 // We need a route consisting of 3 paths:
3224 // From our node to node2 via node0, node7, node1 (three paths one hop each).
3225 // To achieve this, the amount being transferred should be around
3226 // the total capacity of these 3 paths.
3228 // First, we set limits on these (previously unlimited) channels.
3229 // Their aggregate capacity will be 50 + 60 + 180 = 290 sats.
3231 // Path via node0 is channels {1, 3}. Limit them to 100 and 50 sats (total limit 50).
3232 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3233 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3234 short_channel_id: 1,
3237 cltv_expiry_delta: 0,
3238 htlc_minimum_msat: 0,
3239 htlc_maximum_msat: OptionalField::Present(100_000),
3241 fee_proportional_millionths: 0,
3242 excess_data: Vec::new()
3244 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3245 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3246 short_channel_id: 3,
3249 cltv_expiry_delta: 0,
3250 htlc_minimum_msat: 0,
3251 htlc_maximum_msat: OptionalField::Present(50_000),
3253 fee_proportional_millionths: 0,
3254 excess_data: Vec::new()
3257 // Path via node7 is channels {12, 13}. Limit them to 60 and 60 sats
3258 // (total limit 60).
3259 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3260 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3261 short_channel_id: 12,
3264 cltv_expiry_delta: 0,
3265 htlc_minimum_msat: 0,
3266 htlc_maximum_msat: OptionalField::Present(60_000),
3268 fee_proportional_millionths: 0,
3269 excess_data: Vec::new()
3271 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
3272 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3273 short_channel_id: 13,
3276 cltv_expiry_delta: 0,
3277 htlc_minimum_msat: 0,
3278 htlc_maximum_msat: OptionalField::Present(60_000),
3280 fee_proportional_millionths: 0,
3281 excess_data: Vec::new()
3284 // Path via node1 is channels {2, 4}. Limit them to 200 and 180 sats
3285 // (total capacity 180 sats).
3286 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3287 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3288 short_channel_id: 2,
3291 cltv_expiry_delta: 0,
3292 htlc_minimum_msat: 0,
3293 htlc_maximum_msat: OptionalField::Present(200_000),
3295 fee_proportional_millionths: 0,
3296 excess_data: Vec::new()
3298 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
3299 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3300 short_channel_id: 4,
3303 cltv_expiry_delta: 0,
3304 htlc_minimum_msat: 0,
3305 htlc_maximum_msat: OptionalField::Present(180_000),
3307 fee_proportional_millionths: 0,
3308 excess_data: Vec::new()
3312 // Attempt to route more than available results in a failure.
3313 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id, &net_graph_msg_handler.network_graph,
3314 &nodes[2], Some(InvoiceFeatures::known()), None, &Vec::new(), 300_000, 42, Arc::clone(&logger)) {
3315 assert_eq!(err, "Failed to find a sufficient route to the given destination");
3316 } else { panic!(); }
3320 // Now, attempt to route 250 sats (just a bit below the capacity).
3321 // Our algorithm should provide us with these 3 paths.
3322 let route = get_route(&our_id, &net_graph_msg_handler.network_graph, &nodes[2],
3323 Some(InvoiceFeatures::known()), None, &Vec::new(), 250_000, 42, Arc::clone(&logger)).unwrap();
3324 assert_eq!(route.paths.len(), 3);
3325 let mut total_amount_paid_msat = 0;
3326 for path in &route.paths {
3327 assert_eq!(path.len(), 2);
3328 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
3329 total_amount_paid_msat += path.last().unwrap().fee_msat;
3331 assert_eq!(total_amount_paid_msat, 250_000);
3335 // Attempt to route an exact amount is also fine
3336 let route = get_route(&our_id, &net_graph_msg_handler.network_graph, &nodes[2],
3337 Some(InvoiceFeatures::known()), None, &Vec::new(), 290_000, 42, Arc::clone(&logger)).unwrap();
3338 assert_eq!(route.paths.len(), 3);
3339 let mut total_amount_paid_msat = 0;
3340 for path in &route.paths {
3341 assert_eq!(path.len(), 2);
3342 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
3343 total_amount_paid_msat += path.last().unwrap().fee_msat;
3345 assert_eq!(total_amount_paid_msat, 290_000);
3350 fn long_mpp_route_test() {
3351 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
3352 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3354 // We need a route consisting of 3 paths:
3355 // From our node to node3 via {node0, node2}, {node7, node2, node4} and {node7, node2}.
3356 // Note that these paths overlap (channels 5, 12, 13).
3357 // We will route 300 sats.
3358 // Each path will have 100 sats capacity, those channels which
3359 // are used twice will have 200 sats capacity.
3361 // Disable other potential paths.
3362 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3363 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3364 short_channel_id: 2,
3367 cltv_expiry_delta: 0,
3368 htlc_minimum_msat: 0,
3369 htlc_maximum_msat: OptionalField::Present(100_000),
3371 fee_proportional_millionths: 0,
3372 excess_data: Vec::new()
3374 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3375 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3376 short_channel_id: 7,
3379 cltv_expiry_delta: 0,
3380 htlc_minimum_msat: 0,
3381 htlc_maximum_msat: OptionalField::Present(100_000),
3383 fee_proportional_millionths: 0,
3384 excess_data: Vec::new()
3387 // Path via {node0, node2} is channels {1, 3, 5}.
3388 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3389 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3390 short_channel_id: 1,
3393 cltv_expiry_delta: 0,
3394 htlc_minimum_msat: 0,
3395 htlc_maximum_msat: OptionalField::Present(100_000),
3397 fee_proportional_millionths: 0,
3398 excess_data: Vec::new()
3400 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3401 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3402 short_channel_id: 3,
3405 cltv_expiry_delta: 0,
3406 htlc_minimum_msat: 0,
3407 htlc_maximum_msat: OptionalField::Present(100_000),
3409 fee_proportional_millionths: 0,
3410 excess_data: Vec::new()
3413 // Capacity of 200 sats because this channel will be used by 3rd path as well.
3414 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(5)), 5);
3415 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3416 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3417 short_channel_id: 5,
3420 cltv_expiry_delta: 0,
3421 htlc_minimum_msat: 0,
3422 htlc_maximum_msat: OptionalField::Present(200_000),
3424 fee_proportional_millionths: 0,
3425 excess_data: Vec::new()
3428 // Path via {node7, node2, node4} is channels {12, 13, 6, 11}.
3429 // Add 100 sats to the capacities of {12, 13}, because these channels
3430 // are also used for 3rd path. 100 sats for the rest. Total capacity: 100 sats.
3431 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3432 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3433 short_channel_id: 12,
3436 cltv_expiry_delta: 0,
3437 htlc_minimum_msat: 0,
3438 htlc_maximum_msat: OptionalField::Present(200_000),
3440 fee_proportional_millionths: 0,
3441 excess_data: Vec::new()
3443 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
3444 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3445 short_channel_id: 13,
3448 cltv_expiry_delta: 0,
3449 htlc_minimum_msat: 0,
3450 htlc_maximum_msat: OptionalField::Present(200_000),
3452 fee_proportional_millionths: 0,
3453 excess_data: Vec::new()
3456 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3457 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3458 short_channel_id: 6,
3461 cltv_expiry_delta: 0,
3462 htlc_minimum_msat: 0,
3463 htlc_maximum_msat: OptionalField::Present(100_000),
3465 fee_proportional_millionths: 0,
3466 excess_data: Vec::new()
3468 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
3469 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3470 short_channel_id: 11,
3473 cltv_expiry_delta: 0,
3474 htlc_minimum_msat: 0,
3475 htlc_maximum_msat: OptionalField::Present(100_000),
3477 fee_proportional_millionths: 0,
3478 excess_data: Vec::new()
3481 // Path via {node7, node2} is channels {12, 13, 5}.
3482 // We already limited them to 200 sats (they are used twice for 100 sats).
3483 // Nothing to do here.
3486 // Attempt to route more than available results in a failure.
3487 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id, &net_graph_msg_handler.network_graph, &nodes[3],
3488 Some(InvoiceFeatures::known()), None, &Vec::new(), 350_000, 42, Arc::clone(&logger)) {
3489 assert_eq!(err, "Failed to find a sufficient route to the given destination");
3490 } else { panic!(); }
3494 // Now, attempt to route 300 sats (exact amount we can route).
3495 // Our algorithm should provide us with these 3 paths, 100 sats each.
3496 let route = get_route(&our_id, &net_graph_msg_handler.network_graph, &nodes[3],
3497 Some(InvoiceFeatures::known()), None, &Vec::new(), 300_000, 42, Arc::clone(&logger)).unwrap();
3498 assert_eq!(route.paths.len(), 3);
3500 let mut total_amount_paid_msat = 0;
3501 for path in &route.paths {
3502 assert_eq!(path.last().unwrap().pubkey, nodes[3]);
3503 total_amount_paid_msat += path.last().unwrap().fee_msat;
3505 assert_eq!(total_amount_paid_msat, 300_000);
3511 fn mpp_cheaper_route_test() {
3512 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
3513 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3515 // This test checks that if we have two cheaper paths and one more expensive path,
3516 // so that liquidity-wise any 2 of 3 combination is sufficient,
3517 // two cheaper paths will be taken.
3518 // These paths have equal available liquidity.
3520 // We need a combination of 3 paths:
3521 // From our node to node3 via {node0, node2}, {node7, node2, node4} and {node7, node2}.
3522 // Note that these paths overlap (channels 5, 12, 13).
3523 // Each path will have 100 sats capacity, those channels which
3524 // are used twice will have 200 sats capacity.
3526 // Disable other potential paths.
3527 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3528 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3529 short_channel_id: 2,
3532 cltv_expiry_delta: 0,
3533 htlc_minimum_msat: 0,
3534 htlc_maximum_msat: OptionalField::Present(100_000),
3536 fee_proportional_millionths: 0,
3537 excess_data: Vec::new()
3539 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3540 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3541 short_channel_id: 7,
3544 cltv_expiry_delta: 0,
3545 htlc_minimum_msat: 0,
3546 htlc_maximum_msat: OptionalField::Present(100_000),
3548 fee_proportional_millionths: 0,
3549 excess_data: Vec::new()
3552 // Path via {node0, node2} is channels {1, 3, 5}.
3553 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3554 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3555 short_channel_id: 1,
3558 cltv_expiry_delta: 0,
3559 htlc_minimum_msat: 0,
3560 htlc_maximum_msat: OptionalField::Present(100_000),
3562 fee_proportional_millionths: 0,
3563 excess_data: Vec::new()
3565 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3566 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3567 short_channel_id: 3,
3570 cltv_expiry_delta: 0,
3571 htlc_minimum_msat: 0,
3572 htlc_maximum_msat: OptionalField::Present(100_000),
3574 fee_proportional_millionths: 0,
3575 excess_data: Vec::new()
3578 // Capacity of 200 sats because this channel will be used by 3rd path as well.
3579 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(5)), 5);
3580 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3581 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3582 short_channel_id: 5,
3585 cltv_expiry_delta: 0,
3586 htlc_minimum_msat: 0,
3587 htlc_maximum_msat: OptionalField::Present(200_000),
3589 fee_proportional_millionths: 0,
3590 excess_data: Vec::new()
3593 // Path via {node7, node2, node4} is channels {12, 13, 6, 11}.
3594 // Add 100 sats to the capacities of {12, 13}, because these channels
3595 // are also used for 3rd path. 100 sats for the rest. Total capacity: 100 sats.
3596 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3597 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3598 short_channel_id: 12,
3601 cltv_expiry_delta: 0,
3602 htlc_minimum_msat: 0,
3603 htlc_maximum_msat: OptionalField::Present(200_000),
3605 fee_proportional_millionths: 0,
3606 excess_data: Vec::new()
3608 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
3609 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3610 short_channel_id: 13,
3613 cltv_expiry_delta: 0,
3614 htlc_minimum_msat: 0,
3615 htlc_maximum_msat: OptionalField::Present(200_000),
3617 fee_proportional_millionths: 0,
3618 excess_data: Vec::new()
3621 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3622 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3623 short_channel_id: 6,
3626 cltv_expiry_delta: 0,
3627 htlc_minimum_msat: 0,
3628 htlc_maximum_msat: OptionalField::Present(100_000),
3629 fee_base_msat: 1_000,
3630 fee_proportional_millionths: 0,
3631 excess_data: Vec::new()
3633 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
3634 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3635 short_channel_id: 11,
3638 cltv_expiry_delta: 0,
3639 htlc_minimum_msat: 0,
3640 htlc_maximum_msat: OptionalField::Present(100_000),
3642 fee_proportional_millionths: 0,
3643 excess_data: Vec::new()
3646 // Path via {node7, node2} is channels {12, 13, 5}.
3647 // We already limited them to 200 sats (they are used twice for 100 sats).
3648 // Nothing to do here.
3651 // Now, attempt to route 180 sats.
3652 // Our algorithm should provide us with these 2 paths.
3653 let route = get_route(&our_id, &net_graph_msg_handler.network_graph, &nodes[3],
3654 Some(InvoiceFeatures::known()), None, &Vec::new(), 180_000, 42, Arc::clone(&logger)).unwrap();
3655 assert_eq!(route.paths.len(), 2);
3657 let mut total_value_transferred_msat = 0;
3658 let mut total_paid_msat = 0;
3659 for path in &route.paths {
3660 assert_eq!(path.last().unwrap().pubkey, nodes[3]);
3661 total_value_transferred_msat += path.last().unwrap().fee_msat;
3663 total_paid_msat += hop.fee_msat;
3666 // If we paid fee, this would be higher.
3667 assert_eq!(total_value_transferred_msat, 180_000);
3668 let total_fees_paid = total_paid_msat - total_value_transferred_msat;
3669 assert_eq!(total_fees_paid, 0);
3674 fn fees_on_mpp_route_test() {
3675 // This test makes sure that MPP algorithm properly takes into account
3676 // fees charged on the channels, by making the fees impactful:
3677 // if the fee is not properly accounted for, the behavior is different.
3678 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
3679 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3681 // We need a route consisting of 2 paths:
3682 // From our node to node3 via {node0, node2} and {node7, node2, node4}.
3683 // We will route 200 sats, Each path will have 100 sats capacity.
3685 // This test is not particularly stable: e.g.,
3686 // there's a way to route via {node0, node2, node4}.
3687 // It works while pathfinding is deterministic, but can be broken otherwise.
3688 // It's fine to ignore this concern for now.
3690 // Disable other potential paths.
3691 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3692 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3693 short_channel_id: 2,
3696 cltv_expiry_delta: 0,
3697 htlc_minimum_msat: 0,
3698 htlc_maximum_msat: OptionalField::Present(100_000),
3700 fee_proportional_millionths: 0,
3701 excess_data: Vec::new()
3704 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3705 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3706 short_channel_id: 7,
3709 cltv_expiry_delta: 0,
3710 htlc_minimum_msat: 0,
3711 htlc_maximum_msat: OptionalField::Present(100_000),
3713 fee_proportional_millionths: 0,
3714 excess_data: Vec::new()
3717 // Path via {node0, node2} is channels {1, 3, 5}.
3718 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3719 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3720 short_channel_id: 1,
3723 cltv_expiry_delta: 0,
3724 htlc_minimum_msat: 0,
3725 htlc_maximum_msat: OptionalField::Present(100_000),
3727 fee_proportional_millionths: 0,
3728 excess_data: Vec::new()
3730 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3731 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3732 short_channel_id: 3,
3735 cltv_expiry_delta: 0,
3736 htlc_minimum_msat: 0,
3737 htlc_maximum_msat: OptionalField::Present(100_000),
3739 fee_proportional_millionths: 0,
3740 excess_data: Vec::new()
3743 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(5)), 5);
3744 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3745 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3746 short_channel_id: 5,
3749 cltv_expiry_delta: 0,
3750 htlc_minimum_msat: 0,
3751 htlc_maximum_msat: OptionalField::Present(100_000),
3753 fee_proportional_millionths: 0,
3754 excess_data: Vec::new()
3757 // Path via {node7, node2, node4} is channels {12, 13, 6, 11}.
3758 // All channels should be 100 sats capacity. But for the fee experiment,
3759 // we'll add absolute fee of 150 sats paid for the use channel 6 (paid to node2 on channel 13).
3760 // Since channel 12 allows to deliver only 250 sats to channel 13, channel 13 can transfer only
3761 // 100 sats (and pay 150 sats in fees for the use of channel 6),
3762 // so no matter how large are other channels,
3763 // the whole path will be limited by 100 sats with just these 2 conditions:
3764 // - channel 12 capacity is 250 sats
3765 // - fee for channel 6 is 150 sats
3766 // Let's test this by enforcing these 2 conditions and removing other limits.
3767 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3768 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3769 short_channel_id: 12,
3772 cltv_expiry_delta: 0,
3773 htlc_minimum_msat: 0,
3774 htlc_maximum_msat: OptionalField::Present(250_000),
3776 fee_proportional_millionths: 0,
3777 excess_data: Vec::new()
3779 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
3780 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3781 short_channel_id: 13,
3784 cltv_expiry_delta: 0,
3785 htlc_minimum_msat: 0,
3786 htlc_maximum_msat: OptionalField::Absent,
3788 fee_proportional_millionths: 0,
3789 excess_data: Vec::new()
3792 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3793 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3794 short_channel_id: 6,
3797 cltv_expiry_delta: 0,
3798 htlc_minimum_msat: 0,
3799 htlc_maximum_msat: OptionalField::Absent,
3800 fee_base_msat: 150_000,
3801 fee_proportional_millionths: 0,
3802 excess_data: Vec::new()
3804 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
3805 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3806 short_channel_id: 11,
3809 cltv_expiry_delta: 0,
3810 htlc_minimum_msat: 0,
3811 htlc_maximum_msat: OptionalField::Absent,
3813 fee_proportional_millionths: 0,
3814 excess_data: Vec::new()
3818 // Attempt to route more than available results in a failure.
3819 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id, &net_graph_msg_handler.network_graph, &nodes[3],
3820 Some(InvoiceFeatures::known()), None, &Vec::new(), 210_000, 42, Arc::clone(&logger)) {
3821 assert_eq!(err, "Failed to find a sufficient route to the given destination");
3822 } else { panic!(); }
3826 // Now, attempt to route 200 sats (exact amount we can route).
3827 let route = get_route(&our_id, &net_graph_msg_handler.network_graph, &nodes[3],
3828 Some(InvoiceFeatures::known()), None, &Vec::new(), 200_000, 42, Arc::clone(&logger)).unwrap();
3829 assert_eq!(route.paths.len(), 2);
3831 let mut total_amount_paid_msat = 0;
3832 for path in &route.paths {
3833 assert_eq!(path.last().unwrap().pubkey, nodes[3]);
3834 total_amount_paid_msat += path.last().unwrap().fee_msat;
3836 assert_eq!(total_amount_paid_msat, 200_000);
3837 assert_eq!(route.get_total_fees(), 150_000);
3843 fn drop_lowest_channel_mpp_route_test() {
3844 // This test checks that low-capacity channel is dropped when after
3845 // path finding we realize that we found more capacity than we need.
3846 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
3847 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3849 // We need a route consisting of 3 paths:
3850 // From our node to node2 via node0, node7, node1 (three paths one hop each).
3852 // The first and the second paths should be sufficient, but the third should be
3853 // cheaper, so that we select it but drop later.
3855 // First, we set limits on these (previously unlimited) channels.
3856 // Their aggregate capacity will be 50 + 60 + 20 = 130 sats.
3858 // Path via node0 is channels {1, 3}. Limit them to 100 and 50 sats (total limit 50);
3859 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3860 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3861 short_channel_id: 1,
3864 cltv_expiry_delta: 0,
3865 htlc_minimum_msat: 0,
3866 htlc_maximum_msat: OptionalField::Present(100_000),
3868 fee_proportional_millionths: 0,
3869 excess_data: Vec::new()
3871 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3872 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3873 short_channel_id: 3,
3876 cltv_expiry_delta: 0,
3877 htlc_minimum_msat: 0,
3878 htlc_maximum_msat: OptionalField::Present(50_000),
3880 fee_proportional_millionths: 0,
3881 excess_data: Vec::new()
3884 // Path via node7 is channels {12, 13}. Limit them to 60 and 60 sats (total limit 60);
3885 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3886 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3887 short_channel_id: 12,
3890 cltv_expiry_delta: 0,
3891 htlc_minimum_msat: 0,
3892 htlc_maximum_msat: OptionalField::Present(60_000),
3894 fee_proportional_millionths: 0,
3895 excess_data: Vec::new()
3897 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
3898 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3899 short_channel_id: 13,
3902 cltv_expiry_delta: 0,
3903 htlc_minimum_msat: 0,
3904 htlc_maximum_msat: OptionalField::Present(60_000),
3906 fee_proportional_millionths: 0,
3907 excess_data: Vec::new()
3910 // Path via node1 is channels {2, 4}. Limit them to 20 and 20 sats (total capacity 20 sats).
3911 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3912 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3913 short_channel_id: 2,
3916 cltv_expiry_delta: 0,
3917 htlc_minimum_msat: 0,
3918 htlc_maximum_msat: OptionalField::Present(20_000),
3920 fee_proportional_millionths: 0,
3921 excess_data: Vec::new()
3923 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
3924 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3925 short_channel_id: 4,
3928 cltv_expiry_delta: 0,
3929 htlc_minimum_msat: 0,
3930 htlc_maximum_msat: OptionalField::Present(20_000),
3932 fee_proportional_millionths: 0,
3933 excess_data: Vec::new()
3937 // Attempt to route more than available results in a failure.
3938 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id, &net_graph_msg_handler.network_graph, &nodes[2],
3939 Some(InvoiceFeatures::known()), None, &Vec::new(), 150_000, 42, Arc::clone(&logger)) {
3940 assert_eq!(err, "Failed to find a sufficient route to the given destination");
3941 } else { panic!(); }
3945 // Now, attempt to route 125 sats (just a bit below the capacity of 3 channels).
3946 // Our algorithm should provide us with these 3 paths.
3947 let route = get_route(&our_id, &net_graph_msg_handler.network_graph, &nodes[2],
3948 Some(InvoiceFeatures::known()), None, &Vec::new(), 125_000, 42, Arc::clone(&logger)).unwrap();
3949 assert_eq!(route.paths.len(), 3);
3950 let mut total_amount_paid_msat = 0;
3951 for path in &route.paths {
3952 assert_eq!(path.len(), 2);
3953 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
3954 total_amount_paid_msat += path.last().unwrap().fee_msat;
3956 assert_eq!(total_amount_paid_msat, 125_000);
3960 // Attempt to route without the last small cheap channel
3961 let route = get_route(&our_id, &net_graph_msg_handler.network_graph, &nodes[2],
3962 Some(InvoiceFeatures::known()), None, &Vec::new(), 90_000, 42, Arc::clone(&logger)).unwrap();
3963 assert_eq!(route.paths.len(), 2);
3964 let mut total_amount_paid_msat = 0;
3965 for path in &route.paths {
3966 assert_eq!(path.len(), 2);
3967 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
3968 total_amount_paid_msat += path.last().unwrap().fee_msat;
3970 assert_eq!(total_amount_paid_msat, 90_000);
3975 fn min_criteria_consistency() {
3976 // Test that we don't use an inconsistent metric between updating and walking nodes during
3977 // our Dijkstra's pass. In the initial version of MPP, the "best source" for a given node
3978 // was updated with a different criterion from the heap sorting, resulting in loops in
3979 // calculated paths. We test for that specific case here.
3981 // We construct a network that looks like this:
3983 // node2 -1(3)2- node3
3987 // node1 -1(5)2- node4 -1(1)2- node6
3993 // We create a loop on the side of our real path - our destination is node 6, with a
3994 // previous hop of node 4. From 4, the cheapest previous path is channel 2 from node 2,
3995 // followed by node 3 over channel 3. Thereafter, the cheapest next-hop is back to node 4
3996 // (this time over channel 4). Channel 4 has 0 htlc_minimum_msat whereas channel 1 (the
3997 // other channel with a previous-hop of node 4) has a high (but irrelevant to the overall
3998 // payment) htlc_minimum_msat. In the original algorithm, this resulted in node4's
3999 // "previous hop" being set to node 3, creating a loop in the path.
4000 let secp_ctx = Secp256k1::new();
4001 let logger = Arc::new(test_utils::TestLogger::new());
4002 let network_graph = NetworkGraph::new(genesis_block(Network::Testnet).header.block_hash());
4003 let net_graph_msg_handler = NetGraphMsgHandler::new(network_graph, None, Arc::clone(&logger));
4004 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
4006 add_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, &privkeys[1], ChannelFeatures::from_le_bytes(id_to_feature_flags(6)), 6);
4007 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4008 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4009 short_channel_id: 6,
4012 cltv_expiry_delta: (6 << 8) | 0,
4013 htlc_minimum_msat: 0,
4014 htlc_maximum_msat: OptionalField::Absent,
4016 fee_proportional_millionths: 0,
4017 excess_data: Vec::new()
4019 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[1], NodeFeatures::from_le_bytes(id_to_feature_flags(1)), 0);
4021 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], &privkeys[4], ChannelFeatures::from_le_bytes(id_to_feature_flags(5)), 5);
4022 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
4023 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4024 short_channel_id: 5,
4027 cltv_expiry_delta: (5 << 8) | 0,
4028 htlc_minimum_msat: 0,
4029 htlc_maximum_msat: OptionalField::Absent,
4031 fee_proportional_millionths: 0,
4032 excess_data: Vec::new()
4034 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[4], NodeFeatures::from_le_bytes(id_to_feature_flags(4)), 0);
4036 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(4)), 4);
4037 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
4038 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4039 short_channel_id: 4,
4042 cltv_expiry_delta: (4 << 8) | 0,
4043 htlc_minimum_msat: 0,
4044 htlc_maximum_msat: OptionalField::Absent,
4046 fee_proportional_millionths: 0,
4047 excess_data: Vec::new()
4049 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[3], NodeFeatures::from_le_bytes(id_to_feature_flags(3)), 0);
4051 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[3], &privkeys[2], ChannelFeatures::from_le_bytes(id_to_feature_flags(3)), 3);
4052 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[3], UnsignedChannelUpdate {
4053 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4054 short_channel_id: 3,
4057 cltv_expiry_delta: (3 << 8) | 0,
4058 htlc_minimum_msat: 0,
4059 htlc_maximum_msat: OptionalField::Absent,
4061 fee_proportional_millionths: 0,
4062 excess_data: Vec::new()
4064 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[2], NodeFeatures::from_le_bytes(id_to_feature_flags(2)), 0);
4066 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], &privkeys[4], ChannelFeatures::from_le_bytes(id_to_feature_flags(2)), 2);
4067 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4068 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4069 short_channel_id: 2,
4072 cltv_expiry_delta: (2 << 8) | 0,
4073 htlc_minimum_msat: 0,
4074 htlc_maximum_msat: OptionalField::Absent,
4076 fee_proportional_millionths: 0,
4077 excess_data: Vec::new()
4080 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], &privkeys[6], ChannelFeatures::from_le_bytes(id_to_feature_flags(1)), 1);
4081 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
4082 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4083 short_channel_id: 1,
4086 cltv_expiry_delta: (1 << 8) | 0,
4087 htlc_minimum_msat: 100,
4088 htlc_maximum_msat: OptionalField::Absent,
4090 fee_proportional_millionths: 0,
4091 excess_data: Vec::new()
4093 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[6], NodeFeatures::from_le_bytes(id_to_feature_flags(6)), 0);
4096 // Now ensure the route flows simply over nodes 1 and 4 to 6.
4097 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();
4098 assert_eq!(route.paths.len(), 1);
4099 assert_eq!(route.paths[0].len(), 3);
4101 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
4102 assert_eq!(route.paths[0][0].short_channel_id, 6);
4103 assert_eq!(route.paths[0][0].fee_msat, 100);
4104 assert_eq!(route.paths[0][0].cltv_expiry_delta, (5 << 8) | 0);
4105 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(1));
4106 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(6));
4108 assert_eq!(route.paths[0][1].pubkey, nodes[4]);
4109 assert_eq!(route.paths[0][1].short_channel_id, 5);
4110 assert_eq!(route.paths[0][1].fee_msat, 0);
4111 assert_eq!(route.paths[0][1].cltv_expiry_delta, (1 << 8) | 0);
4112 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(4));
4113 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(5));
4115 assert_eq!(route.paths[0][2].pubkey, nodes[6]);
4116 assert_eq!(route.paths[0][2].short_channel_id, 1);
4117 assert_eq!(route.paths[0][2].fee_msat, 10_000);
4118 assert_eq!(route.paths[0][2].cltv_expiry_delta, 42);
4119 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(6));
4120 assert_eq!(route.paths[0][2].channel_features.le_flags(), &id_to_feature_flags(1));
4126 fn exact_fee_liquidity_limit() {
4127 // Test that if, while walking the graph, we find a hop that has exactly enough liquidity
4128 // for us, including later hop fees, we take it. In the first version of our MPP algorithm
4129 // we calculated fees on a higher value, resulting in us ignoring such paths.
4130 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
4131 let (our_privkey, our_id, _, nodes) = get_nodes(&secp_ctx);
4133 // We modify the graph to set the htlc_maximum of channel 2 to below the value we wish to
4135 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4136 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4137 short_channel_id: 2,
4140 cltv_expiry_delta: 0,
4141 htlc_minimum_msat: 0,
4142 htlc_maximum_msat: OptionalField::Present(85_000),
4144 fee_proportional_millionths: 0,
4145 excess_data: Vec::new()
4148 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4149 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4150 short_channel_id: 12,
4153 cltv_expiry_delta: (4 << 8) | 1,
4154 htlc_minimum_msat: 0,
4155 htlc_maximum_msat: OptionalField::Present(270_000),
4157 fee_proportional_millionths: 1000000,
4158 excess_data: Vec::new()
4162 // Now, attempt to route 90 sats, which is exactly 90 sats at the last hop, plus the
4163 // 200% fee charged channel 13 in the 1-to-2 direction.
4164 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();
4165 assert_eq!(route.paths.len(), 1);
4166 assert_eq!(route.paths[0].len(), 2);
4168 assert_eq!(route.paths[0][0].pubkey, nodes[7]);
4169 assert_eq!(route.paths[0][0].short_channel_id, 12);
4170 assert_eq!(route.paths[0][0].fee_msat, 90_000*2);
4171 assert_eq!(route.paths[0][0].cltv_expiry_delta, (13 << 8) | 1);
4172 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(8));
4173 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(12));
4175 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
4176 assert_eq!(route.paths[0][1].short_channel_id, 13);
4177 assert_eq!(route.paths[0][1].fee_msat, 90_000);
4178 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
4179 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
4180 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(13));
4185 fn htlc_max_reduction_below_min() {
4186 // Test that if, while walking the graph, we reduce the value being sent to meet an
4187 // htlc_maximum_msat, we don't end up undershooting a later htlc_minimum_msat. In the
4188 // initial version of MPP we'd accept such routes but reject them while recalculating fees,
4189 // resulting in us thinking there is no possible path, even if other paths exist.
4190 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
4191 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
4193 // We modify the graph to set the htlc_minimum of channel 2 and 4 as needed - channel 2
4194 // gets an htlc_maximum_msat of 80_000 and channel 4 an htlc_minimum_msat of 90_000. We
4195 // then try to send 90_000.
4196 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4197 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4198 short_channel_id: 2,
4201 cltv_expiry_delta: 0,
4202 htlc_minimum_msat: 0,
4203 htlc_maximum_msat: OptionalField::Present(80_000),
4205 fee_proportional_millionths: 0,
4206 excess_data: Vec::new()
4208 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
4209 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4210 short_channel_id: 4,
4213 cltv_expiry_delta: (4 << 8) | 1,
4214 htlc_minimum_msat: 90_000,
4215 htlc_maximum_msat: OptionalField::Absent,
4217 fee_proportional_millionths: 0,
4218 excess_data: Vec::new()
4222 // Now, attempt to route 90 sats, hitting the htlc_minimum on channel 4, but
4223 // overshooting the htlc_maximum on channel 2. Thus, we should pick the (absurdly
4224 // expensive) channels 12-13 path.
4225 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();
4226 assert_eq!(route.paths.len(), 1);
4227 assert_eq!(route.paths[0].len(), 2);
4229 assert_eq!(route.paths[0][0].pubkey, nodes[7]);
4230 assert_eq!(route.paths[0][0].short_channel_id, 12);
4231 assert_eq!(route.paths[0][0].fee_msat, 90_000*2);
4232 assert_eq!(route.paths[0][0].cltv_expiry_delta, (13 << 8) | 1);
4233 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(8));
4234 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(12));
4236 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
4237 assert_eq!(route.paths[0][1].short_channel_id, 13);
4238 assert_eq!(route.paths[0][1].fee_msat, 90_000);
4239 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
4240 assert_eq!(route.paths[0][1].node_features.le_flags(), InvoiceFeatures::known().le_flags());
4241 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(13));
4246 fn multiple_direct_first_hops() {
4247 // Previously we'd only ever considered one first hop path per counterparty.
4248 // However, as we don't restrict users to one channel per peer, we really need to support
4249 // looking at all first hop paths.
4250 // Here we test that we do not ignore all-but-the-last first hop paths per counterparty (as
4251 // we used to do by overwriting the `first_hop_targets` hashmap entry) and that we can MPP
4252 // route over multiple channels with the same first hop.
4253 let secp_ctx = Secp256k1::new();
4254 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
4255 let logger = Arc::new(test_utils::TestLogger::new());
4256 let network_graph = NetworkGraph::new(genesis_block(Network::Testnet).header.block_hash());
4259 let route = get_route(&our_id, &network_graph, &nodes[0], Some(InvoiceFeatures::known()), Some(&[
4260 &get_channel_details(Some(3), nodes[0], InitFeatures::known(), 200_000),
4261 &get_channel_details(Some(2), nodes[0], InitFeatures::known(), 10_000),
4262 ]), &[], 100_000, 42, Arc::clone(&logger)).unwrap();
4263 assert_eq!(route.paths.len(), 1);
4264 assert_eq!(route.paths[0].len(), 1);
4266 assert_eq!(route.paths[0][0].pubkey, nodes[0]);
4267 assert_eq!(route.paths[0][0].short_channel_id, 3);
4268 assert_eq!(route.paths[0][0].fee_msat, 100_000);
4271 let route = get_route(&our_id, &network_graph, &nodes[0], Some(InvoiceFeatures::known()), Some(&[
4272 &get_channel_details(Some(3), nodes[0], InitFeatures::known(), 50_000),
4273 &get_channel_details(Some(2), nodes[0], InitFeatures::known(), 50_000),
4274 ]), &[], 100_000, 42, Arc::clone(&logger)).unwrap();
4275 assert_eq!(route.paths.len(), 2);
4276 assert_eq!(route.paths[0].len(), 1);
4277 assert_eq!(route.paths[1].len(), 1);
4279 assert_eq!(route.paths[0][0].pubkey, nodes[0]);
4280 assert_eq!(route.paths[0][0].short_channel_id, 3);
4281 assert_eq!(route.paths[0][0].fee_msat, 50_000);
4283 assert_eq!(route.paths[1][0].pubkey, nodes[0]);
4284 assert_eq!(route.paths[1][0].short_channel_id, 2);
4285 assert_eq!(route.paths[1][0].fee_msat, 50_000);
4290 fn total_fees_single_path() {
4294 pubkey: PublicKey::from_slice(&hex::decode("02eec7245d6b7d2ccb30380bfbe2a3648cd7a942653f5aa340edcea1f283686619").unwrap()[..]).unwrap(),
4295 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
4296 short_channel_id: 0, fee_msat: 100, cltv_expiry_delta: 0
4299 pubkey: PublicKey::from_slice(&hex::decode("0324653eac434488002cc06bbfb7f10fe18991e35f9fe4302dbea6d2353dc0ab1c").unwrap()[..]).unwrap(),
4300 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
4301 short_channel_id: 0, fee_msat: 150, cltv_expiry_delta: 0
4304 pubkey: PublicKey::from_slice(&hex::decode("027f31ebc5462c1fdce1b737ecff52d37d75dea43ce11c74d25aa297165faa2007").unwrap()[..]).unwrap(),
4305 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
4306 short_channel_id: 0, fee_msat: 225, cltv_expiry_delta: 0
4311 assert_eq!(route.get_total_fees(), 250);
4312 assert_eq!(route.get_total_amount(), 225);
4316 fn total_fees_multi_path() {
4320 pubkey: PublicKey::from_slice(&hex::decode("02eec7245d6b7d2ccb30380bfbe2a3648cd7a942653f5aa340edcea1f283686619").unwrap()[..]).unwrap(),
4321 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
4322 short_channel_id: 0, fee_msat: 100, cltv_expiry_delta: 0
4325 pubkey: PublicKey::from_slice(&hex::decode("0324653eac434488002cc06bbfb7f10fe18991e35f9fe4302dbea6d2353dc0ab1c").unwrap()[..]).unwrap(),
4326 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
4327 short_channel_id: 0, fee_msat: 150, cltv_expiry_delta: 0
4331 pubkey: PublicKey::from_slice(&hex::decode("02eec7245d6b7d2ccb30380bfbe2a3648cd7a942653f5aa340edcea1f283686619").unwrap()[..]).unwrap(),
4332 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
4333 short_channel_id: 0, fee_msat: 100, cltv_expiry_delta: 0
4336 pubkey: PublicKey::from_slice(&hex::decode("0324653eac434488002cc06bbfb7f10fe18991e35f9fe4302dbea6d2353dc0ab1c").unwrap()[..]).unwrap(),
4337 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
4338 short_channel_id: 0, fee_msat: 150, cltv_expiry_delta: 0
4343 assert_eq!(route.get_total_fees(), 200);
4344 assert_eq!(route.get_total_amount(), 300);
4348 fn total_empty_route_no_panic() {
4349 // In an earlier version of `Route::get_total_fees` and `Route::get_total_amount`, they
4350 // would both panic if the route was completely empty. We test to ensure they return 0
4351 // here, even though its somewhat nonsensical as a route.
4352 let route = Route { paths: Vec::new() };
4354 assert_eq!(route.get_total_fees(), 0);
4355 assert_eq!(route.get_total_amount(), 0);
4358 #[cfg(not(feature = "no-std"))]
4359 pub(super) fn random_init_seed() -> u64 {
4360 // Because the default HashMap in std pulls OS randomness, we can use it as a (bad) RNG.
4361 use core::hash::{BuildHasher, Hasher};
4362 let seed = std::collections::hash_map::RandomState::new().build_hasher().finish();
4363 println!("Using seed of {}", seed);
4366 #[cfg(not(feature = "no-std"))]
4367 use util::ser::Readable;
4370 #[cfg(not(feature = "no-std"))]
4371 fn generate_routes() {
4372 let mut d = match super::test_utils::get_route_file() {
4379 let graph = NetworkGraph::read(&mut d).unwrap();
4381 // First, get 100 (source, destination) pairs for which route-getting actually succeeds...
4382 let mut seed = random_init_seed() as usize;
4383 let nodes = graph.read_only().nodes().clone();
4384 'load_endpoints: for _ in 0..10 {
4386 seed = seed.overflowing_mul(0xdeadbeef).0;
4387 let src = &PublicKey::from_slice(nodes.keys().skip(seed % nodes.len()).next().unwrap().as_slice()).unwrap();
4388 seed = seed.overflowing_mul(0xdeadbeef).0;
4389 let dst = &PublicKey::from_slice(nodes.keys().skip(seed % nodes.len()).next().unwrap().as_slice()).unwrap();
4390 let amt = seed as u64 % 200_000_000;
4391 if get_route(src, &graph, dst, None, None, &[], amt, 42, &test_utils::TestLogger::new()).is_ok() {
4392 continue 'load_endpoints;
4399 #[cfg(not(feature = "no-std"))]
4400 fn generate_routes_mpp() {
4401 let mut d = match super::test_utils::get_route_file() {
4408 let graph = NetworkGraph::read(&mut d).unwrap();
4410 // First, get 100 (source, destination) pairs for which route-getting actually succeeds...
4411 let mut seed = random_init_seed() as usize;
4412 let nodes = graph.read_only().nodes().clone();
4413 'load_endpoints: for _ in 0..10 {
4415 seed = seed.overflowing_mul(0xdeadbeef).0;
4416 let src = &PublicKey::from_slice(nodes.keys().skip(seed % nodes.len()).next().unwrap().as_slice()).unwrap();
4417 seed = seed.overflowing_mul(0xdeadbeef).0;
4418 let dst = &PublicKey::from_slice(nodes.keys().skip(seed % nodes.len()).next().unwrap().as_slice()).unwrap();
4419 let amt = seed as u64 % 200_000_000;
4420 if get_route(src, &graph, dst, Some(InvoiceFeatures::known()), None, &[], amt, 42, &test_utils::TestLogger::new()).is_ok() {
4421 continue 'load_endpoints;
4428 #[cfg(all(test, not(feature = "no-std")))]
4429 pub(crate) mod test_utils {
4431 /// Tries to open a network graph file, or panics with a URL to fetch it.
4432 pub(crate) fn get_route_file() -> Result<std::fs::File, &'static str> {
4433 let res = File::open("net_graph-2021-05-31.bin") // By default we're run in RL/lightning
4434 .or_else(|_| File::open("lightning/net_graph-2021-05-31.bin")) // We may be run manually in RL/
4435 .or_else(|_| { // Fall back to guessing based on the binary location
4436 // path is likely something like .../rust-lightning/target/debug/deps/lightning-...
4437 let mut path = std::env::current_exe().unwrap();
4438 path.pop(); // lightning-...
4440 path.pop(); // debug
4441 path.pop(); // target
4442 path.push("lightning");
4443 path.push("net_graph-2021-05-31.bin");
4444 eprintln!("{}", path.to_str().unwrap());
4447 .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");
4448 #[cfg(require_route_graph_test)]
4449 return Ok(res.unwrap());
4450 #[cfg(not(require_route_graph_test))]
4455 #[cfg(all(test, feature = "unstable", not(feature = "no-std")))]
4458 use util::logger::{Logger, Record};
4462 struct DummyLogger {}
4463 impl Logger for DummyLogger {
4464 fn log(&self, _record: &Record) {}
4468 fn generate_routes(bench: &mut Bencher) {
4469 let mut d = test_utils::get_route_file().unwrap();
4470 let graph = NetworkGraph::read(&mut d).unwrap();
4471 let nodes = graph.read_only().nodes().clone();
4473 // First, get 100 (source, destination) pairs for which route-getting actually succeeds...
4474 let mut path_endpoints = Vec::new();
4475 let mut seed: usize = 0xdeadbeef;
4476 'load_endpoints: for _ in 0..100 {
4479 let src = PublicKey::from_slice(nodes.keys().skip(seed % nodes.len()).next().unwrap().as_slice()).unwrap();
4481 let dst = PublicKey::from_slice(nodes.keys().skip(seed % nodes.len()).next().unwrap().as_slice()).unwrap();
4482 let amt = seed as u64 % 1_000_000;
4483 if get_route(&src, &graph, &dst, None, None, &[], amt, 42, &DummyLogger{}).is_ok() {
4484 path_endpoints.push((src, dst, amt));
4485 continue 'load_endpoints;
4490 // ...then benchmark finding paths between the nodes we learned.
4493 let (src, dst, amt) = path_endpoints[idx % path_endpoints.len()];
4494 assert!(get_route(&src, &graph, &dst, None, None, &[], amt, 42, &DummyLogger{}).is_ok());
4500 fn generate_mpp_routes(bench: &mut Bencher) {
4501 let mut d = test_utils::get_route_file().unwrap();
4502 let graph = NetworkGraph::read(&mut d).unwrap();
4503 let nodes = graph.read_only().nodes().clone();
4505 // First, get 100 (source, destination) pairs for which route-getting actually succeeds...
4506 let mut path_endpoints = Vec::new();
4507 let mut seed: usize = 0xdeadbeef;
4508 'load_endpoints: for _ in 0..100 {
4511 let src = PublicKey::from_slice(nodes.keys().skip(seed % nodes.len()).next().unwrap().as_slice()).unwrap();
4513 let dst = PublicKey::from_slice(nodes.keys().skip(seed % nodes.len()).next().unwrap().as_slice()).unwrap();
4514 let amt = seed as u64 % 1_000_000;
4515 if get_route(&src, &graph, &dst, Some(InvoiceFeatures::known()), None, &[], amt, 42, &DummyLogger{}).is_ok() {
4516 path_endpoints.push((src, dst, amt));
4517 continue 'load_endpoints;
4522 // ...then benchmark finding paths between the nodes we learned.
4525 let (src, dst, amt) = path_endpoints[idx % path_endpoints.len()];
4526 assert!(get_route(&src, &graph, &dst, Some(InvoiceFeatures::known()), None, &[], amt, 42, &DummyLogger{}).is_ok());