1 //! The top-level routing/network map tracking logic lives here.
2 //! You probably want to create a Router and use that as your RoutingMessageHandler and then
3 //! interrogate it to get routes for your own payments.
5 use secp256k1::key::PublicKey;
6 use secp256k1::{Secp256k1,Message};
9 use bitcoin::util::hash::Sha256dHash;
10 use bitcoin::blockdata::script::Builder;
11 use bitcoin::blockdata::opcodes;
13 use chain::chaininterface::{ChainError, ChainWatchInterface};
14 use ln::channelmanager;
15 use ln::msgs::{ErrorAction,HandleError,RoutingMessageHandler,NetAddress,GlobalFeatures};
17 use util::ser::Writeable;
18 use util::logger::Logger;
21 use std::sync::{RwLock,Arc};
22 use std::collections::{HashMap,BinaryHeap};
23 use std::collections::hash_map::Entry;
29 /// The node_id of the node at this hop.
30 pub pubkey: PublicKey,
31 /// The channel that should be used from the previous hop to reach this node.
32 pub short_channel_id: u64,
33 /// The fee taken on this hop. For the last hop, this should be the full value of the payment.
35 /// The CLTV delta added for this hop. For the last hop, this should be the full CLTV value
36 /// expected at the destination, in excess of the current block height.
37 pub cltv_expiry_delta: u32,
40 /// A route from us through the network to a destination
43 /// The list of hops, NOT INCLUDING our own, where the last hop is the destination. Thus, this
44 /// must always be at least length one. By protocol rules, this may not currently exceed 20 in
46 pub hops: Vec<RouteHop>,
49 struct DirectionalChannelInfo {
50 src_node_id: PublicKey,
53 cltv_expiry_delta: u16,
54 htlc_minimum_msat: u64,
56 fee_proportional_millionths: u32,
59 impl std::fmt::Display for DirectionalChannelInfo {
60 fn fmt(&self, f: &mut std::fmt::Formatter) -> Result<(), std::fmt::Error> {
61 write!(f, "src_node_id {}, last_update {}, enabled {}, cltv_expiry_delta {}, htlc_minimum_msat {}, fee_base_msat {}, fee_proportional_millionths {}", log_pubkey!(self.src_node_id), self.last_update, self.enabled, self.cltv_expiry_delta, self.htlc_minimum_msat, self.fee_base_msat, self.fee_proportional_millionths)?;
67 features: GlobalFeatures,
68 one_to_two: DirectionalChannelInfo,
69 two_to_one: DirectionalChannelInfo,
72 impl std::fmt::Display for ChannelInfo {
73 fn fmt(&self, f: &mut std::fmt::Formatter) -> Result<(), std::fmt::Error> {
74 write!(f, "features: {}, one_to_two: {}, two_to_one: {}", log_bytes!(self.features.encode()), self.one_to_two, self.two_to_one)?;
80 #[cfg(feature = "non_bitcoin_chain_hash_routing")]
81 channels: Vec<(u64, Sha256dHash)>,
82 #[cfg(not(feature = "non_bitcoin_chain_hash_routing"))]
85 lowest_inbound_channel_fee_base_msat: u32,
86 lowest_inbound_channel_fee_proportional_millionths: u32,
88 features: GlobalFeatures,
92 addresses: Vec<NetAddress>,
95 impl std::fmt::Display for NodeInfo {
96 fn fmt(&self, f: &mut std::fmt::Formatter) -> Result<(), std::fmt::Error> {
97 write!(f, "features: {}, last_update: {}, lowest_inbound_channel_fee_base_msat: {}, lowest_inbound_channel_fee_proportional_millionths: {}, channels: {:?}", log_bytes!(self.features.encode()), self.last_update, self.lowest_inbound_channel_fee_base_msat, self.lowest_inbound_channel_fee_proportional_millionths, &self.channels[..])?;
103 #[cfg(feature = "non_bitcoin_chain_hash_routing")]
104 channels: HashMap<(u64, Sha256dHash), ChannelInfo>,
105 #[cfg(not(feature = "non_bitcoin_chain_hash_routing"))]
106 channels: HashMap<u64, ChannelInfo>,
108 our_node_id: PublicKey,
109 nodes: HashMap<PublicKey, NodeInfo>,
111 struct MutNetworkMap<'a> {
112 #[cfg(feature = "non_bitcoin_chain_hash_routing")]
113 channels: &'a mut HashMap<(u64, Sha256dHash), ChannelInfo>,
114 #[cfg(not(feature = "non_bitcoin_chain_hash_routing"))]
115 channels: &'a mut HashMap<u64, ChannelInfo>,
116 nodes: &'a mut HashMap<PublicKey, NodeInfo>,
119 fn borrow_parts(&mut self) -> MutNetworkMap {
121 channels: &mut self.channels,
122 nodes: &mut self.nodes,
126 impl std::fmt::Display for NetworkMap {
127 fn fmt(&self, f: &mut std::fmt::Formatter) -> Result<(), std::fmt::Error> {
128 write!(f, "Node id {} network map\n[Channels]\n", log_pubkey!(self.our_node_id))?;
129 for (key, val) in self.channels.iter() {
130 write!(f, " {}: {}\n", key, val)?;
132 write!(f, "[Nodes]\n")?;
133 for (key, val) in self.nodes.iter() {
134 write!(f, " {}: {}\n", log_pubkey!(key), val)?;
141 #[cfg(feature = "non_bitcoin_chain_hash_routing")]
143 fn get_key(short_channel_id: u64, chain_hash: Sha256dHash) -> (u64, Sha256dHash) {
144 (short_channel_id, chain_hash)
147 #[cfg(not(feature = "non_bitcoin_chain_hash_routing"))]
149 fn get_key(short_channel_id: u64, _: Sha256dHash) -> u64 {
153 #[cfg(feature = "non_bitcoin_chain_hash_routing")]
155 fn get_short_id(id: &(u64, Sha256dHash)) -> &u64 {
159 #[cfg(not(feature = "non_bitcoin_chain_hash_routing"))]
161 fn get_short_id(id: &u64) -> &u64 {
166 /// A channel descriptor which provides a last-hop route to get_route
167 pub struct RouteHint {
168 /// The node_id of the non-target end of the route
169 pub src_node_id: PublicKey,
170 /// The short_channel_id of this channel
171 pub short_channel_id: u64,
172 /// The static msat-denominated fee which must be paid to use this channel
173 pub fee_base_msat: u32,
174 /// The dynamic proportional fee which must be paid to use this channel, denominated in
175 /// millionths of the value being forwarded to the next hop.
176 pub fee_proportional_millionths: u32,
177 /// The difference in CLTV values between this node and the next node.
178 pub cltv_expiry_delta: u16,
179 /// The minimum value, in msat, which must be relayed to the next hop.
180 pub htlc_minimum_msat: u64,
183 /// Tracks a view of the network, receiving updates from peers and generating Routes to
184 /// payment destinations.
186 secp_ctx: Secp256k1<secp256k1::VerifyOnly>,
187 network_map: RwLock<NetworkMap>,
188 chain_monitor: Arc<ChainWatchInterface>,
192 macro_rules! secp_verify_sig {
193 ( $secp_ctx: expr, $msg: expr, $sig: expr, $pubkey: expr ) => {
194 match $secp_ctx.verify($msg, $sig, $pubkey) {
196 Err(_) => return Err(HandleError{err: "Invalid signature from remote node", action: None}),
201 impl RoutingMessageHandler for Router {
202 fn handle_node_announcement(&self, msg: &msgs::NodeAnnouncement) -> Result<bool, HandleError> {
203 let msg_hash = Message::from_slice(&Sha256dHash::from_data(&msg.contents.encode()[..])[..]).unwrap();
204 secp_verify_sig!(self.secp_ctx, &msg_hash, &msg.signature, &msg.contents.node_id);
206 if msg.contents.features.requires_unknown_bits() {
207 panic!("Unknown-required-features NodeAnnouncements should never deserialize!");
210 let mut network = self.network_map.write().unwrap();
211 match network.nodes.get_mut(&msg.contents.node_id) {
212 None => Err(HandleError{err: "No existing channels for node_announcement", action: Some(ErrorAction::IgnoreError)}),
214 if node.last_update >= msg.contents.timestamp {
215 return Err(HandleError{err: "Update older than last processed update", action: Some(ErrorAction::IgnoreError)});
218 node.features = msg.contents.features.clone();
219 node.last_update = msg.contents.timestamp;
220 node.rgb = msg.contents.rgb;
221 node.alias = msg.contents.alias;
222 node.addresses = msg.contents.addresses.clone();
223 Ok(msg.contents.excess_data.is_empty() && msg.contents.excess_address_data.is_empty() && !msg.contents.features.supports_unknown_bits())
228 fn handle_channel_announcement(&self, msg: &msgs::ChannelAnnouncement) -> Result<bool, HandleError> {
229 if msg.contents.node_id_1 == msg.contents.node_id_2 || msg.contents.bitcoin_key_1 == msg.contents.bitcoin_key_2 {
230 return Err(HandleError{err: "Channel announcement node had a channel with itself", action: Some(ErrorAction::IgnoreError)});
233 let msg_hash = Message::from_slice(&Sha256dHash::from_data(&msg.contents.encode()[..])[..]).unwrap();
234 secp_verify_sig!(self.secp_ctx, &msg_hash, &msg.node_signature_1, &msg.contents.node_id_1);
235 secp_verify_sig!(self.secp_ctx, &msg_hash, &msg.node_signature_2, &msg.contents.node_id_2);
236 secp_verify_sig!(self.secp_ctx, &msg_hash, &msg.bitcoin_signature_1, &msg.contents.bitcoin_key_1);
237 secp_verify_sig!(self.secp_ctx, &msg_hash, &msg.bitcoin_signature_2, &msg.contents.bitcoin_key_2);
239 if msg.contents.features.requires_unknown_bits() {
240 panic!("Unknown-required-features ChannelAnnouncements should never deserialize!");
243 let checked_utxo = match self.chain_monitor.get_chain_utxo(msg.contents.chain_hash, msg.contents.short_channel_id) {
244 Ok((script_pubkey, _value)) => {
245 let expected_script = Builder::new().push_opcode(opcodes::All::OP_PUSHNUM_2)
246 .push_slice(&msg.contents.bitcoin_key_1.serialize())
247 .push_slice(&msg.contents.bitcoin_key_2.serialize())
248 .push_opcode(opcodes::All::OP_PUSHNUM_2).push_opcode(opcodes::All::OP_CHECKMULTISIG).into_script().to_v0_p2wsh();
249 if script_pubkey != expected_script {
250 return Err(HandleError{err: "Channel announcement keys didn't match on-chain script", action: Some(ErrorAction::IgnoreError)});
252 //TODO: Check if value is worth storing, use it to inform routing, and compare it
253 //to the new HTLC max field in channel_update
256 Err(ChainError::NotSupported) => {
257 // Tentatively accept, potentially exposing us to DoS attacks
260 Err(ChainError::NotWatched) => {
261 return Err(HandleError{err: "Channel announced on an unknown chain", action: Some(ErrorAction::IgnoreError)});
263 Err(ChainError::UnknownTx) => {
264 return Err(HandleError{err: "Channel announced without corresponding UTXO entry", action: Some(ErrorAction::IgnoreError)});
268 let mut network_lock = self.network_map.write().unwrap();
269 let network = network_lock.borrow_parts();
271 let chan_info = ChannelInfo {
272 features: msg.contents.features.clone(),
273 one_to_two: DirectionalChannelInfo {
274 src_node_id: msg.contents.node_id_1.clone(),
277 cltv_expiry_delta: u16::max_value(),
278 htlc_minimum_msat: u64::max_value(),
279 fee_base_msat: u32::max_value(),
280 fee_proportional_millionths: u32::max_value(),
282 two_to_one: DirectionalChannelInfo {
283 src_node_id: msg.contents.node_id_2.clone(),
286 cltv_expiry_delta: u16::max_value(),
287 htlc_minimum_msat: u64::max_value(),
288 fee_base_msat: u32::max_value(),
289 fee_proportional_millionths: u32::max_value(),
293 match network.channels.entry(NetworkMap::get_key(msg.contents.short_channel_id, msg.contents.chain_hash)) {
294 Entry::Occupied(mut entry) => {
295 //TODO: because asking the blockchain if short_channel_id is valid is only optional
296 //in the blockchain API, we need to handle it smartly here, though its unclear
299 // Either our UTXO provider is busted, there was a reorg, or the UTXO provider
300 // only sometimes returns results. In any case remove the previous entry. Note
301 // that the spec expects us to "blacklist" the node_ids involved, but we can't
303 // a) we don't *require* a UTXO provider that always returns results.
304 // b) we don't track UTXOs of channels we know about and remove them if they
306 // c) it's unclear how to do so without exposing ourselves to massive DoS risk.
307 Self::remove_channel_in_nodes(network.nodes, &entry.get(), msg.contents.short_channel_id);
308 *entry.get_mut() = chan_info;
310 return Err(HandleError{err: "Already have knowledge of channel", action: Some(ErrorAction::IgnoreError)})
313 Entry::Vacant(entry) => {
314 entry.insert(chan_info);
318 macro_rules! add_channel_to_node {
319 ( $node_id: expr ) => {
320 match network.nodes.entry($node_id) {
321 Entry::Occupied(node_entry) => {
322 node_entry.into_mut().channels.push(NetworkMap::get_key(msg.contents.short_channel_id, msg.contents.chain_hash));
324 Entry::Vacant(node_entry) => {
325 node_entry.insert(NodeInfo {
326 channels: vec!(NetworkMap::get_key(msg.contents.short_channel_id, msg.contents.chain_hash)),
327 lowest_inbound_channel_fee_base_msat: u32::max_value(),
328 lowest_inbound_channel_fee_proportional_millionths: u32::max_value(),
329 features: GlobalFeatures::new(),
333 addresses: Vec::new(),
340 add_channel_to_node!(msg.contents.node_id_1);
341 add_channel_to_node!(msg.contents.node_id_2);
343 Ok(msg.contents.excess_data.is_empty() && !msg.contents.features.supports_unknown_bits())
346 fn handle_htlc_fail_channel_update(&self, update: &msgs::HTLCFailChannelUpdate) {
348 &msgs::HTLCFailChannelUpdate::ChannelUpdateMessage { ref msg } => {
349 let _ = self.handle_channel_update(msg);
351 &msgs::HTLCFailChannelUpdate::ChannelClosed { ref short_channel_id } => {
352 let mut network = self.network_map.write().unwrap();
353 if let Some(chan) = network.channels.remove(short_channel_id) {
354 Self::remove_channel_in_nodes(&mut network.nodes, &chan, *short_channel_id);
360 fn handle_channel_update(&self, msg: &msgs::ChannelUpdate) -> Result<bool, HandleError> {
361 let mut network = self.network_map.write().unwrap();
363 let chan_enabled = msg.contents.flags & (1 << 1) != (1 << 1);
364 let chan_was_enabled;
366 match network.channels.get_mut(&NetworkMap::get_key(msg.contents.short_channel_id, msg.contents.chain_hash)) {
367 None => return Err(HandleError{err: "Couldn't find channel for update", action: Some(ErrorAction::IgnoreError)}),
369 macro_rules! maybe_update_channel_info {
370 ( $target: expr) => {
371 if $target.last_update >= msg.contents.timestamp {
372 return Err(HandleError{err: "Update older than last processed update", action: Some(ErrorAction::IgnoreError)});
374 chan_was_enabled = $target.enabled;
375 $target.last_update = msg.contents.timestamp;
376 $target.enabled = chan_enabled;
377 $target.cltv_expiry_delta = msg.contents.cltv_expiry_delta;
378 $target.htlc_minimum_msat = msg.contents.htlc_minimum_msat;
379 $target.fee_base_msat = msg.contents.fee_base_msat;
380 $target.fee_proportional_millionths = msg.contents.fee_proportional_millionths;
384 let msg_hash = Message::from_slice(&Sha256dHash::from_data(&msg.contents.encode()[..])[..]).unwrap();
385 if msg.contents.flags & 1 == 1 {
386 dest_node_id = channel.one_to_two.src_node_id.clone();
387 secp_verify_sig!(self.secp_ctx, &msg_hash, &msg.signature, &channel.two_to_one.src_node_id);
388 maybe_update_channel_info!(channel.two_to_one);
390 dest_node_id = channel.two_to_one.src_node_id.clone();
391 secp_verify_sig!(self.secp_ctx, &msg_hash, &msg.signature, &channel.one_to_two.src_node_id);
392 maybe_update_channel_info!(channel.one_to_two);
398 let node = network.nodes.get_mut(&dest_node_id).unwrap();
399 node.lowest_inbound_channel_fee_base_msat = cmp::min(node.lowest_inbound_channel_fee_base_msat, msg.contents.fee_base_msat);
400 node.lowest_inbound_channel_fee_proportional_millionths = cmp::min(node.lowest_inbound_channel_fee_proportional_millionths, msg.contents.fee_proportional_millionths);
401 } else if chan_was_enabled {
402 let mut lowest_inbound_channel_fee_base_msat = u32::max_value();
403 let mut lowest_inbound_channel_fee_proportional_millionths = u32::max_value();
406 let node = network.nodes.get(&dest_node_id).unwrap();
408 for chan_id in node.channels.iter() {
409 let chan = network.channels.get(chan_id).unwrap();
410 if chan.one_to_two.src_node_id == dest_node_id {
411 lowest_inbound_channel_fee_base_msat = cmp::min(lowest_inbound_channel_fee_base_msat, chan.two_to_one.fee_base_msat);
412 lowest_inbound_channel_fee_proportional_millionths = cmp::min(lowest_inbound_channel_fee_proportional_millionths, chan.two_to_one.fee_proportional_millionths);
414 lowest_inbound_channel_fee_base_msat = cmp::min(lowest_inbound_channel_fee_base_msat, chan.one_to_two.fee_base_msat);
415 lowest_inbound_channel_fee_proportional_millionths = cmp::min(lowest_inbound_channel_fee_proportional_millionths, chan.one_to_two.fee_proportional_millionths);
420 //TODO: satisfy the borrow-checker without a double-map-lookup :(
421 let mut_node = network.nodes.get_mut(&dest_node_id).unwrap();
422 mut_node.lowest_inbound_channel_fee_base_msat = lowest_inbound_channel_fee_base_msat;
423 mut_node.lowest_inbound_channel_fee_proportional_millionths = lowest_inbound_channel_fee_proportional_millionths;
426 Ok(msg.contents.excess_data.is_empty())
430 #[derive(Eq, PartialEq)]
431 struct RouteGraphNode {
433 lowest_fee_to_peer_through_node: u64,
434 lowest_fee_to_node: u64,
437 impl cmp::Ord for RouteGraphNode {
438 fn cmp(&self, other: &RouteGraphNode) -> cmp::Ordering {
439 other.lowest_fee_to_peer_through_node.cmp(&self.lowest_fee_to_peer_through_node)
440 .then_with(|| other.pubkey.serialize().cmp(&self.pubkey.serialize()))
444 impl cmp::PartialOrd for RouteGraphNode {
445 fn partial_cmp(&self, other: &RouteGraphNode) -> Option<cmp::Ordering> {
446 Some(self.cmp(other))
450 struct DummyDirectionalChannelInfo {
451 src_node_id: PublicKey,
452 cltv_expiry_delta: u32,
453 htlc_minimum_msat: u64,
455 fee_proportional_millionths: u32,
459 /// Creates a new router with the given node_id to be used as the source for get_route()
460 pub fn new(our_pubkey: PublicKey, chain_monitor: Arc<ChainWatchInterface>, logger: Arc<Logger>) -> Router {
461 let mut nodes = HashMap::new();
462 nodes.insert(our_pubkey.clone(), NodeInfo {
463 channels: Vec::new(),
464 lowest_inbound_channel_fee_base_msat: u32::max_value(),
465 lowest_inbound_channel_fee_proportional_millionths: u32::max_value(),
466 features: GlobalFeatures::new(),
470 addresses: Vec::new(),
473 secp_ctx: Secp256k1::verification_only(),
474 network_map: RwLock::new(NetworkMap {
475 channels: HashMap::new(),
476 our_node_id: our_pubkey,
484 /// Dumps the entire network view of this Router to the logger provided in the constructor at
486 pub fn trace_state(&self) {
487 log_trace!(self, "{}", self.network_map.read().unwrap());
490 /// Get network addresses by node id
491 pub fn get_addresses(&self, pubkey: &PublicKey) -> Option<Vec<NetAddress>> {
492 let network = self.network_map.read().unwrap();
493 network.nodes.get(pubkey).map(|n| n.addresses.clone())
496 /// Marks a node as having failed a route. This will avoid re-using the node in routes for now,
497 /// with an expotnential decay in node "badness". Note that there is deliberately no
498 /// mark_channel_bad as a node may simply lie and suggest that an upstream channel from it is
499 /// what failed the route and not the node itself. Instead, setting the blamed_upstream_node
500 /// boolean will reduce the penalty, returning the node to usability faster. If the node is
501 /// behaving correctly, it will disable the failing channel and we will use it again next time.
502 pub fn mark_node_bad(&self, _node_id: &PublicKey, _blamed_upstream_node: bool) {
506 fn remove_channel_in_nodes(nodes: &mut HashMap<PublicKey, NodeInfo>, chan: &ChannelInfo, short_channel_id: u64) {
507 macro_rules! remove_from_node {
508 ($node_id: expr) => {
509 if let Entry::Occupied(mut entry) = nodes.entry($node_id) {
510 entry.get_mut().channels.retain(|chan_id| {
511 short_channel_id != *NetworkMap::get_short_id(chan_id)
513 if entry.get().channels.is_empty() {
514 entry.remove_entry();
517 panic!("Had channel that pointed to unknown node (ie inconsistent network map)!");
521 remove_from_node!(chan.one_to_two.src_node_id);
522 remove_from_node!(chan.two_to_one.src_node_id);
525 /// Gets a route from us to the given target node.
526 /// Extra routing hops between known nodes and the target will be used if they are included in
528 /// If some channels aren't announced, it may be useful to fill in a first_hops with the
529 /// results from a local ChannelManager::list_usable_channels() call. If it is filled in, our
530 /// (this Router's) view of our local channels will be ignored, and only those in first_hops
531 /// will be used. Panics if first_hops contains channels without short_channel_ids
532 /// (ChannelManager::list_usable_channels will never include such channels).
533 /// The fees on channels from us to next-hops are ignored (as they are assumed to all be
534 /// equal), however the enabled/disabled bit on such channels as well as the htlc_minimum_msat
535 /// *is* checked as they may change based on the receiving node.
536 pub fn get_route(&self, target: &PublicKey, first_hops: Option<&[channelmanager::ChannelDetails]>, last_hops: &[RouteHint], final_value_msat: u64, final_cltv: u32) -> Result<Route, HandleError> {
537 // TODO: Obviously *only* using total fee cost sucks. We should consider weighting by
538 // uptime/success in using a node in the past.
539 let network = self.network_map.read().unwrap();
541 if *target == network.our_node_id {
542 return Err(HandleError{err: "Cannot generate a route to ourselves", action: None});
545 if final_value_msat > 21_000_000 * 1_0000_0000 * 1000 {
546 return Err(HandleError{err: "Cannot generate a route of more value than all existing satoshis", action: None});
549 // We do a dest-to-source Dijkstra's sorting by each node's distance from the destination
550 // plus the minimum per-HTLC fee to get from it to another node (aka "shitty A*").
551 // TODO: There are a few tweaks we could do, including possibly pre-calculating more stuff
552 // to use as the A* heuristic beyond just the cost to get one node further than the current
555 let dummy_directional_info = DummyDirectionalChannelInfo { // used for first_hops routes
556 src_node_id: network.our_node_id.clone(),
557 cltv_expiry_delta: 0,
558 htlc_minimum_msat: 0,
560 fee_proportional_millionths: 0,
563 let mut targets = BinaryHeap::new(); //TODO: Do we care about switching to eg Fibbonaci heap?
564 let mut dist = HashMap::with_capacity(network.nodes.len());
566 let mut first_hop_targets = HashMap::with_capacity(if first_hops.is_some() { first_hops.as_ref().unwrap().len() } else { 0 });
567 if let Some(hops) = first_hops {
569 let short_channel_id = chan.short_channel_id.expect("first_hops should be filled in with usable channels, not pending ones");
570 if chan.remote_network_id == *target {
572 hops: vec![RouteHop {
573 pubkey: chan.remote_network_id,
575 fee_msat: final_value_msat,
576 cltv_expiry_delta: final_cltv,
580 first_hop_targets.insert(chan.remote_network_id, short_channel_id);
582 if first_hop_targets.is_empty() {
583 return Err(HandleError{err: "Cannot route when there are no outbound routes away from us", action: None});
587 macro_rules! add_entry {
588 // Adds entry which goes from the node pointed to by $directional_info to
589 // $dest_node_id over the channel with id $chan_id with fees described in
590 // $directional_info.
591 ( $chan_id: expr, $dest_node_id: expr, $directional_info: expr, $starting_fee_msat: expr ) => {
592 //TODO: Explore simply adding fee to hit htlc_minimum_msat
593 if $starting_fee_msat as u64 + final_value_msat > $directional_info.htlc_minimum_msat {
594 let proportional_fee_millions = ($starting_fee_msat + final_value_msat).checked_mul($directional_info.fee_proportional_millionths as u64);
595 if let Some(new_fee) = proportional_fee_millions.and_then(|part| {
596 ($directional_info.fee_base_msat as u64).checked_add(part / 1000000) })
598 let mut total_fee = $starting_fee_msat as u64;
599 let hm_entry = dist.entry(&$directional_info.src_node_id);
600 let old_entry = hm_entry.or_insert_with(|| {
601 let node = network.nodes.get(&$directional_info.src_node_id).unwrap();
603 node.lowest_inbound_channel_fee_base_msat,
604 node.lowest_inbound_channel_fee_proportional_millionths,
606 pubkey: $dest_node_id.clone(),
609 cltv_expiry_delta: 0,
612 if $directional_info.src_node_id != network.our_node_id {
613 // Ignore new_fee for channel-from-us as we assume all channels-from-us
614 // will have the same effective-fee
615 total_fee += new_fee;
616 if let Some(fee_inc) = final_value_msat.checked_add(total_fee).and_then(|inc| { (old_entry.2 as u64).checked_mul(inc) }) {
617 total_fee += fee_inc / 1000000 + (old_entry.1 as u64);
619 // max_value means we'll always fail the old_entry.0 > total_fee check
620 total_fee = u64::max_value();
623 let new_graph_node = RouteGraphNode {
624 pubkey: $directional_info.src_node_id,
625 lowest_fee_to_peer_through_node: total_fee,
626 lowest_fee_to_node: $starting_fee_msat as u64 + new_fee,
628 if old_entry.0 > total_fee {
629 targets.push(new_graph_node);
630 old_entry.0 = total_fee;
631 old_entry.3 = RouteHop {
632 pubkey: $dest_node_id.clone(),
633 short_channel_id: $chan_id.clone(),
634 fee_msat: new_fee, // This field is ignored on the last-hop anyway
635 cltv_expiry_delta: $directional_info.cltv_expiry_delta as u32,
643 macro_rules! add_entries_to_cheapest_to_target_node {
644 ( $node: expr, $node_id: expr, $fee_to_target_msat: expr ) => {
645 if first_hops.is_some() {
646 if let Some(first_hop) = first_hop_targets.get(&$node_id) {
647 add_entry!(first_hop, $node_id, dummy_directional_info, $fee_to_target_msat);
651 for chan_id in $node.channels.iter() {
652 let chan = network.channels.get(chan_id).unwrap();
653 if chan.one_to_two.src_node_id == *$node_id {
654 // ie $node is one, ie next hop in A* is two, via the two_to_one channel
655 if first_hops.is_none() || chan.two_to_one.src_node_id != network.our_node_id {
656 if chan.two_to_one.enabled {
657 add_entry!(chan_id, chan.one_to_two.src_node_id, chan.two_to_one, $fee_to_target_msat);
661 if first_hops.is_none() || chan.one_to_two.src_node_id != network.our_node_id {
662 if chan.one_to_two.enabled {
663 add_entry!(chan_id, chan.two_to_one.src_node_id, chan.one_to_two, $fee_to_target_msat);
671 match network.nodes.get(target) {
674 add_entries_to_cheapest_to_target_node!(node, target, 0);
678 for hop in last_hops.iter() {
679 if first_hops.is_none() || hop.src_node_id != network.our_node_id { // first_hop overrules last_hops
680 if network.nodes.get(&hop.src_node_id).is_some() {
681 if first_hops.is_some() {
682 if let Some(first_hop) = first_hop_targets.get(&hop.src_node_id) {
683 add_entry!(first_hop, hop.src_node_id, dummy_directional_info, 0);
686 add_entry!(hop.short_channel_id, target, hop, 0);
691 while let Some(RouteGraphNode { pubkey, lowest_fee_to_node, .. }) = targets.pop() {
692 if pubkey == network.our_node_id {
693 let mut res = vec!(dist.remove(&network.our_node_id).unwrap().3);
694 while res.last().unwrap().pubkey != *target {
695 let new_entry = match dist.remove(&res.last().unwrap().pubkey) {
697 None => return Err(HandleError{err: "Failed to find a non-fee-overflowing path to the given destination", action: None}),
699 res.last_mut().unwrap().fee_msat = new_entry.fee_msat;
700 res.last_mut().unwrap().cltv_expiry_delta = new_entry.cltv_expiry_delta;
703 res.last_mut().unwrap().fee_msat = final_value_msat;
704 res.last_mut().unwrap().cltv_expiry_delta = final_cltv;
705 let route = Route { hops: res };
706 log_trace!(self, "Got route: {}", log_route!(route));
710 match network.nodes.get(&pubkey) {
713 add_entries_to_cheapest_to_target_node!(node, &pubkey, lowest_fee_to_node);
718 Err(HandleError{err: "Failed to find a path to the given destination", action: None})
724 use chain::chaininterface;
725 use ln::channelmanager;
726 use ln::router::{Router,NodeInfo,NetworkMap,ChannelInfo,DirectionalChannelInfo,RouteHint};
727 use ln::msgs::GlobalFeatures;
728 use util::test_utils;
729 use util::logger::Logger;
731 use bitcoin::util::hash::Sha256dHash;
732 use bitcoin::network::constants::Network;
736 use secp256k1::key::{PublicKey,SecretKey};
737 use secp256k1::Secp256k1;
743 let secp_ctx = Secp256k1::new();
744 let our_id = PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&secp_ctx, &hex::decode("0101010101010101010101010101010101010101010101010101010101010101").unwrap()[..]).unwrap());
745 let logger: Arc<Logger> = Arc::new(test_utils::TestLogger::new());
746 let chain_monitor = Arc::new(chaininterface::ChainWatchInterfaceUtil::new(Network::Testnet, Arc::clone(&logger)));
747 let router = Router::new(our_id, chain_monitor, Arc::clone(&logger));
749 // Build network from our_id to node8:
751 // -1(1)2- node1 -1(3)2-
753 // our_id -1(12)2- node8 -1(13)2--- node3
755 // -1(2)2- node2 -1(4)2-
758 // chan1 1-to-2: disabled
759 // chan1 2-to-1: enabled, 0 fee
761 // chan2 1-to-2: enabled, ignored fee
762 // chan2 2-to-1: enabled, 0 fee
764 // chan3 1-to-2: enabled, 0 fee
765 // chan3 2-to-1: enabled, 100 msat fee
767 // chan4 1-to-2: enabled, 100% fee
768 // chan4 2-to-1: enabled, 0 fee
770 // chan12 1-to-2: enabled, ignored fee
771 // chan12 2-to-1: enabled, 0 fee
773 // chan13 1-to-2: enabled, 200% fee
774 // chan13 2-to-1: enabled, 0 fee
777 // -1(5)2- node4 -1(8)2--
781 // node3--1(6)2- node5 -1(9)2--- node7 (not in global route map)
783 // -1(7)2- node6 -1(10)2-
785 // chan5 1-to-2: enabled, 100 msat fee
786 // chan5 2-to-1: enabled, 0 fee
788 // chan6 1-to-2: enabled, 0 fee
789 // chan6 2-to-1: enabled, 0 fee
791 // chan7 1-to-2: enabled, 100% fee
792 // chan7 2-to-1: enabled, 0 fee
794 // chan8 1-to-2: enabled, variable fee (0 then 1000 msat)
795 // chan8 2-to-1: enabled, 0 fee
797 // chan9 1-to-2: enabled, 1001 msat fee
798 // chan9 2-to-1: enabled, 0 fee
800 // chan10 1-to-2: enabled, 0 fee
801 // chan10 2-to-1: enabled, 0 fee
803 // chan11 1-to-2: enabled, 0 fee
804 // chan11 2-to-1: enabled, 0 fee
806 let node1 = PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&secp_ctx, &hex::decode("0202020202020202020202020202020202020202020202020202020202020202").unwrap()[..]).unwrap());
807 let node2 = PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&secp_ctx, &hex::decode("0303030303030303030303030303030303030303030303030303030303030303").unwrap()[..]).unwrap());
808 let node3 = PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&secp_ctx, &hex::decode("0404040404040404040404040404040404040404040404040404040404040404").unwrap()[..]).unwrap());
809 let node4 = PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&secp_ctx, &hex::decode("0505050505050505050505050505050505050505050505050505050505050505").unwrap()[..]).unwrap());
810 let node5 = PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&secp_ctx, &hex::decode("0606060606060606060606060606060606060606060606060606060606060606").unwrap()[..]).unwrap());
811 let node6 = PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&secp_ctx, &hex::decode("0707070707070707070707070707070707070707070707070707070707070707").unwrap()[..]).unwrap());
812 let node7 = PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&secp_ctx, &hex::decode("0808080808080808080808080808080808080808080808080808080808080808").unwrap()[..]).unwrap());
813 let node8 = PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&secp_ctx, &hex::decode("0909090909090909090909090909090909090909090909090909090909090909").unwrap()[..]).unwrap());
815 let zero_hash = Sha256dHash::from_data(&[0; 32]);
818 let mut network = router.network_map.write().unwrap();
820 network.nodes.insert(node1.clone(), NodeInfo {
821 channels: vec!(NetworkMap::get_key(1, zero_hash.clone()), NetworkMap::get_key(3, zero_hash.clone())),
822 lowest_inbound_channel_fee_base_msat: 100,
823 lowest_inbound_channel_fee_proportional_millionths: 0,
824 features: GlobalFeatures::new(),
828 addresses: Vec::new(),
830 network.channels.insert(NetworkMap::get_key(1, zero_hash.clone()), ChannelInfo {
831 features: GlobalFeatures::new(),
832 one_to_two: DirectionalChannelInfo {
833 src_node_id: our_id.clone(),
836 cltv_expiry_delta: u16::max_value(), // This value should be ignored
837 htlc_minimum_msat: 0,
838 fee_base_msat: u32::max_value(), // This value should be ignored
839 fee_proportional_millionths: u32::max_value(), // This value should be ignored
840 }, two_to_one: DirectionalChannelInfo {
841 src_node_id: node1.clone(),
844 cltv_expiry_delta: 0,
845 htlc_minimum_msat: 0,
847 fee_proportional_millionths: 0,
850 network.nodes.insert(node2.clone(), NodeInfo {
851 channels: vec!(NetworkMap::get_key(2, zero_hash.clone()), NetworkMap::get_key(4, zero_hash.clone())),
852 lowest_inbound_channel_fee_base_msat: 0,
853 lowest_inbound_channel_fee_proportional_millionths: 0,
854 features: GlobalFeatures::new(),
858 addresses: Vec::new(),
860 network.channels.insert(NetworkMap::get_key(2, zero_hash.clone()), ChannelInfo {
861 features: GlobalFeatures::new(),
862 one_to_two: DirectionalChannelInfo {
863 src_node_id: our_id.clone(),
866 cltv_expiry_delta: u16::max_value(), // This value should be ignored
867 htlc_minimum_msat: 0,
868 fee_base_msat: u32::max_value(), // This value should be ignored
869 fee_proportional_millionths: u32::max_value(), // This value should be ignored
870 }, two_to_one: DirectionalChannelInfo {
871 src_node_id: node2.clone(),
874 cltv_expiry_delta: 0,
875 htlc_minimum_msat: 0,
877 fee_proportional_millionths: 0,
880 network.nodes.insert(node8.clone(), NodeInfo {
881 channels: vec!(NetworkMap::get_key(12, zero_hash.clone()), NetworkMap::get_key(13, zero_hash.clone())),
882 lowest_inbound_channel_fee_base_msat: 0,
883 lowest_inbound_channel_fee_proportional_millionths: 0,
884 features: GlobalFeatures::new(),
888 addresses: Vec::new(),
890 network.channels.insert(NetworkMap::get_key(12, zero_hash.clone()), ChannelInfo {
891 features: GlobalFeatures::new(),
892 one_to_two: DirectionalChannelInfo {
893 src_node_id: our_id.clone(),
896 cltv_expiry_delta: u16::max_value(), // This value should be ignored
897 htlc_minimum_msat: 0,
898 fee_base_msat: u32::max_value(), // This value should be ignored
899 fee_proportional_millionths: u32::max_value(), // This value should be ignored
900 }, two_to_one: DirectionalChannelInfo {
901 src_node_id: node8.clone(),
904 cltv_expiry_delta: 0,
905 htlc_minimum_msat: 0,
907 fee_proportional_millionths: 0,
910 network.nodes.insert(node3.clone(), NodeInfo {
912 NetworkMap::get_key(3, zero_hash.clone()),
913 NetworkMap::get_key(4, zero_hash.clone()),
914 NetworkMap::get_key(13, zero_hash.clone()),
915 NetworkMap::get_key(5, zero_hash.clone()),
916 NetworkMap::get_key(6, zero_hash.clone()),
917 NetworkMap::get_key(7, zero_hash.clone())),
918 lowest_inbound_channel_fee_base_msat: 0,
919 lowest_inbound_channel_fee_proportional_millionths: 0,
920 features: GlobalFeatures::new(),
924 addresses: Vec::new(),
926 network.channels.insert(NetworkMap::get_key(3, zero_hash.clone()), ChannelInfo {
927 features: GlobalFeatures::new(),
928 one_to_two: DirectionalChannelInfo {
929 src_node_id: node1.clone(),
932 cltv_expiry_delta: (3 << 8) | 1,
933 htlc_minimum_msat: 0,
935 fee_proportional_millionths: 0,
936 }, two_to_one: DirectionalChannelInfo {
937 src_node_id: node3.clone(),
940 cltv_expiry_delta: (3 << 8) | 2,
941 htlc_minimum_msat: 0,
943 fee_proportional_millionths: 0,
946 network.channels.insert(NetworkMap::get_key(4, zero_hash.clone()), ChannelInfo {
947 features: GlobalFeatures::new(),
948 one_to_two: DirectionalChannelInfo {
949 src_node_id: node2.clone(),
952 cltv_expiry_delta: (4 << 8) | 1,
953 htlc_minimum_msat: 0,
955 fee_proportional_millionths: 1000000,
956 }, two_to_one: DirectionalChannelInfo {
957 src_node_id: node3.clone(),
960 cltv_expiry_delta: (4 << 8) | 2,
961 htlc_minimum_msat: 0,
963 fee_proportional_millionths: 0,
966 network.channels.insert(NetworkMap::get_key(13, zero_hash.clone()), ChannelInfo {
967 features: GlobalFeatures::new(),
968 one_to_two: DirectionalChannelInfo {
969 src_node_id: node8.clone(),
972 cltv_expiry_delta: (13 << 8) | 1,
973 htlc_minimum_msat: 0,
975 fee_proportional_millionths: 2000000,
976 }, two_to_one: DirectionalChannelInfo {
977 src_node_id: node3.clone(),
980 cltv_expiry_delta: (13 << 8) | 2,
981 htlc_minimum_msat: 0,
983 fee_proportional_millionths: 0,
986 network.nodes.insert(node4.clone(), NodeInfo {
987 channels: vec!(NetworkMap::get_key(5, zero_hash.clone()), NetworkMap::get_key(11, zero_hash.clone())),
988 lowest_inbound_channel_fee_base_msat: 0,
989 lowest_inbound_channel_fee_proportional_millionths: 0,
990 features: GlobalFeatures::new(),
994 addresses: Vec::new(),
996 network.channels.insert(NetworkMap::get_key(5, zero_hash.clone()), ChannelInfo {
997 features: GlobalFeatures::new(),
998 one_to_two: DirectionalChannelInfo {
999 src_node_id: node3.clone(),
1002 cltv_expiry_delta: (5 << 8) | 1,
1003 htlc_minimum_msat: 0,
1005 fee_proportional_millionths: 0,
1006 }, two_to_one: DirectionalChannelInfo {
1007 src_node_id: node4.clone(),
1010 cltv_expiry_delta: (5 << 8) | 2,
1011 htlc_minimum_msat: 0,
1013 fee_proportional_millionths: 0,
1016 network.nodes.insert(node5.clone(), NodeInfo {
1017 channels: vec!(NetworkMap::get_key(6, zero_hash.clone()), NetworkMap::get_key(11, zero_hash.clone())),
1018 lowest_inbound_channel_fee_base_msat: 0,
1019 lowest_inbound_channel_fee_proportional_millionths: 0,
1020 features: GlobalFeatures::new(),
1024 addresses: Vec::new(),
1026 network.channels.insert(NetworkMap::get_key(6, zero_hash.clone()), ChannelInfo {
1027 features: GlobalFeatures::new(),
1028 one_to_two: DirectionalChannelInfo {
1029 src_node_id: node3.clone(),
1032 cltv_expiry_delta: (6 << 8) | 1,
1033 htlc_minimum_msat: 0,
1035 fee_proportional_millionths: 0,
1036 }, two_to_one: DirectionalChannelInfo {
1037 src_node_id: node5.clone(),
1040 cltv_expiry_delta: (6 << 8) | 2,
1041 htlc_minimum_msat: 0,
1043 fee_proportional_millionths: 0,
1046 network.channels.insert(NetworkMap::get_key(11, zero_hash.clone()), ChannelInfo {
1047 features: GlobalFeatures::new(),
1048 one_to_two: DirectionalChannelInfo {
1049 src_node_id: node5.clone(),
1052 cltv_expiry_delta: (11 << 8) | 1,
1053 htlc_minimum_msat: 0,
1055 fee_proportional_millionths: 0,
1056 }, two_to_one: DirectionalChannelInfo {
1057 src_node_id: node4.clone(),
1060 cltv_expiry_delta: (11 << 8) | 2,
1061 htlc_minimum_msat: 0,
1063 fee_proportional_millionths: 0,
1066 network.nodes.insert(node6.clone(), NodeInfo {
1067 channels: vec!(NetworkMap::get_key(7, zero_hash.clone())),
1068 lowest_inbound_channel_fee_base_msat: 0,
1069 lowest_inbound_channel_fee_proportional_millionths: 0,
1070 features: GlobalFeatures::new(),
1074 addresses: Vec::new(),
1076 network.channels.insert(NetworkMap::get_key(7, zero_hash.clone()), ChannelInfo {
1077 features: GlobalFeatures::new(),
1078 one_to_two: DirectionalChannelInfo {
1079 src_node_id: node3.clone(),
1082 cltv_expiry_delta: (7 << 8) | 1,
1083 htlc_minimum_msat: 0,
1085 fee_proportional_millionths: 1000000,
1086 }, two_to_one: DirectionalChannelInfo {
1087 src_node_id: node6.clone(),
1090 cltv_expiry_delta: (7 << 8) | 2,
1091 htlc_minimum_msat: 0,
1093 fee_proportional_millionths: 0,
1098 { // Simple route to 3 via 2
1099 let route = router.get_route(&node3, None, &Vec::new(), 100, 42).unwrap();
1100 assert_eq!(route.hops.len(), 2);
1102 assert_eq!(route.hops[0].pubkey, node2);
1103 assert_eq!(route.hops[0].short_channel_id, 2);
1104 assert_eq!(route.hops[0].fee_msat, 100);
1105 assert_eq!(route.hops[0].cltv_expiry_delta, (4 << 8) | 1);
1107 assert_eq!(route.hops[1].pubkey, node3);
1108 assert_eq!(route.hops[1].short_channel_id, 4);
1109 assert_eq!(route.hops[1].fee_msat, 100);
1110 assert_eq!(route.hops[1].cltv_expiry_delta, 42);
1113 { // Route to 1 via 2 and 3 because our channel to 1 is disabled
1114 let route = router.get_route(&node1, None, &Vec::new(), 100, 42).unwrap();
1115 assert_eq!(route.hops.len(), 3);
1117 assert_eq!(route.hops[0].pubkey, node2);
1118 assert_eq!(route.hops[0].short_channel_id, 2);
1119 assert_eq!(route.hops[0].fee_msat, 200);
1120 assert_eq!(route.hops[0].cltv_expiry_delta, (4 << 8) | 1);
1122 assert_eq!(route.hops[1].pubkey, node3);
1123 assert_eq!(route.hops[1].short_channel_id, 4);
1124 assert_eq!(route.hops[1].fee_msat, 100);
1125 assert_eq!(route.hops[1].cltv_expiry_delta, (3 << 8) | 2);
1127 assert_eq!(route.hops[2].pubkey, node1);
1128 assert_eq!(route.hops[2].short_channel_id, 3);
1129 assert_eq!(route.hops[2].fee_msat, 100);
1130 assert_eq!(route.hops[2].cltv_expiry_delta, 42);
1133 { // If we specify a channel to node8, that overrides our local channel view and that gets used
1134 let our_chans = vec![channelmanager::ChannelDetails {
1135 channel_id: [0; 32],
1136 short_channel_id: Some(42),
1137 remote_network_id: node8.clone(),
1138 channel_value_satoshis: 0,
1141 let route = router.get_route(&node3, Some(&our_chans), &Vec::new(), 100, 42).unwrap();
1142 assert_eq!(route.hops.len(), 2);
1144 assert_eq!(route.hops[0].pubkey, node8);
1145 assert_eq!(route.hops[0].short_channel_id, 42);
1146 assert_eq!(route.hops[0].fee_msat, 200);
1147 assert_eq!(route.hops[0].cltv_expiry_delta, (13 << 8) | 1);
1149 assert_eq!(route.hops[1].pubkey, node3);
1150 assert_eq!(route.hops[1].short_channel_id, 13);
1151 assert_eq!(route.hops[1].fee_msat, 100);
1152 assert_eq!(route.hops[1].cltv_expiry_delta, 42);
1155 let mut last_hops = vec!(RouteHint {
1156 src_node_id: node4.clone(),
1157 short_channel_id: 8,
1159 fee_proportional_millionths: 0,
1160 cltv_expiry_delta: (8 << 8) | 1,
1161 htlc_minimum_msat: 0,
1163 src_node_id: node5.clone(),
1164 short_channel_id: 9,
1165 fee_base_msat: 1001,
1166 fee_proportional_millionths: 0,
1167 cltv_expiry_delta: (9 << 8) | 1,
1168 htlc_minimum_msat: 0,
1170 src_node_id: node6.clone(),
1171 short_channel_id: 10,
1173 fee_proportional_millionths: 0,
1174 cltv_expiry_delta: (10 << 8) | 1,
1175 htlc_minimum_msat: 0,
1178 { // Simple test across 2, 3, 5, and 4 via a last_hop channel
1179 let route = router.get_route(&node7, None, &last_hops, 100, 42).unwrap();
1180 assert_eq!(route.hops.len(), 5);
1182 assert_eq!(route.hops[0].pubkey, node2);
1183 assert_eq!(route.hops[0].short_channel_id, 2);
1184 assert_eq!(route.hops[0].fee_msat, 100);
1185 assert_eq!(route.hops[0].cltv_expiry_delta, (4 << 8) | 1);
1187 assert_eq!(route.hops[1].pubkey, node3);
1188 assert_eq!(route.hops[1].short_channel_id, 4);
1189 assert_eq!(route.hops[1].fee_msat, 0);
1190 assert_eq!(route.hops[1].cltv_expiry_delta, (6 << 8) | 1);
1192 assert_eq!(route.hops[2].pubkey, node5);
1193 assert_eq!(route.hops[2].short_channel_id, 6);
1194 assert_eq!(route.hops[2].fee_msat, 0);
1195 assert_eq!(route.hops[2].cltv_expiry_delta, (11 << 8) | 1);
1197 assert_eq!(route.hops[3].pubkey, node4);
1198 assert_eq!(route.hops[3].short_channel_id, 11);
1199 assert_eq!(route.hops[3].fee_msat, 0);
1200 assert_eq!(route.hops[3].cltv_expiry_delta, (8 << 8) | 1);
1202 assert_eq!(route.hops[4].pubkey, node7);
1203 assert_eq!(route.hops[4].short_channel_id, 8);
1204 assert_eq!(route.hops[4].fee_msat, 100);
1205 assert_eq!(route.hops[4].cltv_expiry_delta, 42);
1208 { // Simple test with outbound channel to 4 to test that last_hops and first_hops connect
1209 let our_chans = vec![channelmanager::ChannelDetails {
1210 channel_id: [0; 32],
1211 short_channel_id: Some(42),
1212 remote_network_id: node4.clone(),
1213 channel_value_satoshis: 0,
1216 let route = router.get_route(&node7, Some(&our_chans), &last_hops, 100, 42).unwrap();
1217 assert_eq!(route.hops.len(), 2);
1219 assert_eq!(route.hops[0].pubkey, node4);
1220 assert_eq!(route.hops[0].short_channel_id, 42);
1221 assert_eq!(route.hops[0].fee_msat, 0);
1222 assert_eq!(route.hops[0].cltv_expiry_delta, (8 << 8) | 1);
1224 assert_eq!(route.hops[1].pubkey, node7);
1225 assert_eq!(route.hops[1].short_channel_id, 8);
1226 assert_eq!(route.hops[1].fee_msat, 100);
1227 assert_eq!(route.hops[1].cltv_expiry_delta, 42);
1230 last_hops[0].fee_base_msat = 1000;
1232 { // Revert to via 6 as the fee on 8 goes up
1233 let route = router.get_route(&node7, None, &last_hops, 100, 42).unwrap();
1234 assert_eq!(route.hops.len(), 4);
1236 assert_eq!(route.hops[0].pubkey, node2);
1237 assert_eq!(route.hops[0].short_channel_id, 2);
1238 assert_eq!(route.hops[0].fee_msat, 200); // fee increased as its % of value transferred across node
1239 assert_eq!(route.hops[0].cltv_expiry_delta, (4 << 8) | 1);
1241 assert_eq!(route.hops[1].pubkey, node3);
1242 assert_eq!(route.hops[1].short_channel_id, 4);
1243 assert_eq!(route.hops[1].fee_msat, 100);
1244 assert_eq!(route.hops[1].cltv_expiry_delta, (7 << 8) | 1);
1246 assert_eq!(route.hops[2].pubkey, node6);
1247 assert_eq!(route.hops[2].short_channel_id, 7);
1248 assert_eq!(route.hops[2].fee_msat, 0);
1249 assert_eq!(route.hops[2].cltv_expiry_delta, (10 << 8) | 1);
1251 assert_eq!(route.hops[3].pubkey, node7);
1252 assert_eq!(route.hops[3].short_channel_id, 10);
1253 assert_eq!(route.hops[3].fee_msat, 100);
1254 assert_eq!(route.hops[3].cltv_expiry_delta, 42);
1257 { // ...but still use 8 for larger payments as 6 has a variable feerate
1258 let route = router.get_route(&node7, None, &last_hops, 2000, 42).unwrap();
1259 assert_eq!(route.hops.len(), 5);
1261 assert_eq!(route.hops[0].pubkey, node2);
1262 assert_eq!(route.hops[0].short_channel_id, 2);
1263 assert_eq!(route.hops[0].fee_msat, 3000);
1264 assert_eq!(route.hops[0].cltv_expiry_delta, (4 << 8) | 1);
1266 assert_eq!(route.hops[1].pubkey, node3);
1267 assert_eq!(route.hops[1].short_channel_id, 4);
1268 assert_eq!(route.hops[1].fee_msat, 0);
1269 assert_eq!(route.hops[1].cltv_expiry_delta, (6 << 8) | 1);
1271 assert_eq!(route.hops[2].pubkey, node5);
1272 assert_eq!(route.hops[2].short_channel_id, 6);
1273 assert_eq!(route.hops[2].fee_msat, 0);
1274 assert_eq!(route.hops[2].cltv_expiry_delta, (11 << 8) | 1);
1276 assert_eq!(route.hops[3].pubkey, node4);
1277 assert_eq!(route.hops[3].short_channel_id, 11);
1278 assert_eq!(route.hops[3].fee_msat, 1000);
1279 assert_eq!(route.hops[3].cltv_expiry_delta, (8 << 8) | 1);
1281 assert_eq!(route.hops[4].pubkey, node7);
1282 assert_eq!(route.hops[4].short_channel_id, 8);
1283 assert_eq!(route.hops[4].fee_msat, 2000);
1284 assert_eq!(route.hops[4].cltv_expiry_delta, 42);