1 //! The top-level routing/network map tracking logic lives here.
3 //! You probably want to create a Router and use that as your RoutingMessageHandler and then
4 //! interrogate it to get routes for your own payments.
6 use secp256k1::key::PublicKey;
7 use secp256k1::{Secp256k1,Message};
10 use bitcoin::util::hash::Sha256dHash;
11 use bitcoin::blockdata::script::Builder;
12 use bitcoin::blockdata::opcodes;
14 use chain::chaininterface::{ChainError, ChainWatchInterface};
15 use ln::channelmanager;
16 use ln::msgs::{ErrorAction,HandleError,RoutingMessageHandler,NetAddress,GlobalFeatures};
18 use util::ser::Writeable;
19 use util::logger::Logger;
22 use std::sync::{RwLock,Arc};
23 use std::collections::{HashMap,BinaryHeap};
24 use std::collections::hash_map::Entry;
30 /// The node_id of the node at this hop.
31 pub pubkey: PublicKey,
32 /// The channel that should be used from the previous hop to reach this node.
33 pub short_channel_id: u64,
34 /// The fee taken on this hop. For the last hop, this should be the full value of the payment.
36 /// The CLTV delta added for this hop. For the last hop, this should be the full CLTV value
37 /// expected at the destination, in excess of the current block height.
38 pub cltv_expiry_delta: u32,
39 /// channel update timestamp of the outbound channel of each hop when this route is
41 pub channel_update_timestamp: u32,
44 /// A route from us through the network to a destination
47 /// The list of hops, NOT INCLUDING our own, where the last hop is the destination. Thus, this
48 /// must always be at least length one. By protocol rules, this may not currently exceed 20 in
50 pub hops: Vec<RouteHop>,
53 struct DirectionalChannelInfo {
54 src_node_id: PublicKey,
57 cltv_expiry_delta: u16,
58 htlc_minimum_msat: u64,
60 fee_proportional_millionths: u32,
63 impl std::fmt::Display for DirectionalChannelInfo {
64 fn fmt(&self, f: &mut std::fmt::Formatter) -> Result<(), std::fmt::Error> {
65 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)?;
71 features: GlobalFeatures,
72 one_to_two: DirectionalChannelInfo,
73 two_to_one: DirectionalChannelInfo,
76 impl std::fmt::Display for ChannelInfo {
77 fn fmt(&self, f: &mut std::fmt::Formatter) -> Result<(), std::fmt::Error> {
78 write!(f, "features: {}, one_to_two: {}, two_to_one: {}", log_bytes!(self.features.encode()), self.one_to_two, self.two_to_one)?;
84 #[cfg(feature = "non_bitcoin_chain_hash_routing")]
85 channels: Vec<(u64, Sha256dHash)>,
86 #[cfg(not(feature = "non_bitcoin_chain_hash_routing"))]
89 lowest_inbound_channel_fee_base_msat: u32,
90 lowest_inbound_channel_fee_proportional_millionths: u32,
92 features: GlobalFeatures,
96 addresses: Vec<NetAddress>,
99 impl std::fmt::Display for NodeInfo {
100 fn fmt(&self, f: &mut std::fmt::Formatter) -> Result<(), std::fmt::Error> {
101 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[..])?;
107 #[cfg(feature = "non_bitcoin_chain_hash_routing")]
108 channels: HashMap<(u64, Sha256dHash), ChannelInfo>,
109 #[cfg(not(feature = "non_bitcoin_chain_hash_routing"))]
110 channels: HashMap<u64, ChannelInfo>,
112 our_node_id: PublicKey,
113 nodes: HashMap<PublicKey, NodeInfo>,
115 struct MutNetworkMap<'a> {
116 #[cfg(feature = "non_bitcoin_chain_hash_routing")]
117 channels: &'a mut HashMap<(u64, Sha256dHash), ChannelInfo>,
118 #[cfg(not(feature = "non_bitcoin_chain_hash_routing"))]
119 channels: &'a mut HashMap<u64, ChannelInfo>,
120 nodes: &'a mut HashMap<PublicKey, NodeInfo>,
123 fn borrow_parts(&mut self) -> MutNetworkMap {
125 channels: &mut self.channels,
126 nodes: &mut self.nodes,
130 impl std::fmt::Display for NetworkMap {
131 fn fmt(&self, f: &mut std::fmt::Formatter) -> Result<(), std::fmt::Error> {
132 write!(f, "Node id {} network map\n[Channels]\n", log_pubkey!(self.our_node_id))?;
133 for (key, val) in self.channels.iter() {
134 write!(f, " {}: {}\n", key, val)?;
136 write!(f, "[Nodes]\n")?;
137 for (key, val) in self.nodes.iter() {
138 write!(f, " {}: {}\n", log_pubkey!(key), val)?;
145 #[cfg(feature = "non_bitcoin_chain_hash_routing")]
147 fn get_key(short_channel_id: u64, chain_hash: Sha256dHash) -> (u64, Sha256dHash) {
148 (short_channel_id, chain_hash)
151 #[cfg(not(feature = "non_bitcoin_chain_hash_routing"))]
153 fn get_key(short_channel_id: u64, _: Sha256dHash) -> u64 {
157 #[cfg(feature = "non_bitcoin_chain_hash_routing")]
159 fn get_short_id(id: &(u64, Sha256dHash)) -> &u64 {
163 #[cfg(not(feature = "non_bitcoin_chain_hash_routing"))]
165 fn get_short_id(id: &u64) -> &u64 {
170 /// A channel descriptor which provides a last-hop route to get_route
171 pub struct RouteHint {
172 /// The node_id of the non-target end of the route
173 pub src_node_id: PublicKey,
175 pub last_update: u32,
176 /// The short_channel_id of this channel
177 pub short_channel_id: u64,
178 /// The static msat-denominated fee which must be paid to use this channel
179 pub fee_base_msat: u32,
180 /// The dynamic proportional fee which must be paid to use this channel, denominated in
181 /// millionths of the value being forwarded to the next hop.
182 pub fee_proportional_millionths: u32,
183 /// The difference in CLTV values between this node and the next node.
184 pub cltv_expiry_delta: u16,
185 /// The minimum value, in msat, which must be relayed to the next hop.
186 pub htlc_minimum_msat: u64,
189 /// Tracks a view of the network, receiving updates from peers and generating Routes to
190 /// payment destinations.
192 secp_ctx: Secp256k1<secp256k1::VerifyOnly>,
193 network_map: RwLock<NetworkMap>,
194 chain_monitor: Arc<ChainWatchInterface>,
198 macro_rules! secp_verify_sig {
199 ( $secp_ctx: expr, $msg: expr, $sig: expr, $pubkey: expr ) => {
200 match $secp_ctx.verify($msg, $sig, $pubkey) {
202 Err(_) => return Err(HandleError{err: "Invalid signature from remote node", action: None}),
207 impl RoutingMessageHandler for Router {
208 fn handle_node_announcement(&self, msg: &msgs::NodeAnnouncement) -> Result<bool, HandleError> {
209 let msg_hash = Message::from_slice(&Sha256dHash::from_data(&msg.contents.encode()[..])[..]).unwrap();
210 secp_verify_sig!(self.secp_ctx, &msg_hash, &msg.signature, &msg.contents.node_id);
212 if msg.contents.features.requires_unknown_bits() {
213 panic!("Unknown-required-features NodeAnnouncements should never deserialize!");
216 let mut network = self.network_map.write().unwrap();
217 match network.nodes.get_mut(&msg.contents.node_id) {
218 None => Err(HandleError{err: "No existing channels for node_announcement", action: Some(ErrorAction::IgnoreError)}),
220 if node.last_update >= msg.contents.timestamp {
221 return Err(HandleError{err: "Update older than last processed update", action: Some(ErrorAction::IgnoreError)});
224 node.features = msg.contents.features.clone();
225 node.last_update = msg.contents.timestamp;
226 node.rgb = msg.contents.rgb;
227 node.alias = msg.contents.alias;
228 node.addresses = msg.contents.addresses.clone();
229 Ok(msg.contents.excess_data.is_empty() && msg.contents.excess_address_data.is_empty() && !msg.contents.features.supports_unknown_bits())
234 fn handle_channel_announcement(&self, msg: &msgs::ChannelAnnouncement) -> Result<bool, HandleError> {
235 if msg.contents.node_id_1 == msg.contents.node_id_2 || msg.contents.bitcoin_key_1 == msg.contents.bitcoin_key_2 {
236 return Err(HandleError{err: "Channel announcement node had a channel with itself", action: Some(ErrorAction::IgnoreError)});
239 let msg_hash = Message::from_slice(&Sha256dHash::from_data(&msg.contents.encode()[..])[..]).unwrap();
240 secp_verify_sig!(self.secp_ctx, &msg_hash, &msg.node_signature_1, &msg.contents.node_id_1);
241 secp_verify_sig!(self.secp_ctx, &msg_hash, &msg.node_signature_2, &msg.contents.node_id_2);
242 secp_verify_sig!(self.secp_ctx, &msg_hash, &msg.bitcoin_signature_1, &msg.contents.bitcoin_key_1);
243 secp_verify_sig!(self.secp_ctx, &msg_hash, &msg.bitcoin_signature_2, &msg.contents.bitcoin_key_2);
245 if msg.contents.features.requires_unknown_bits() {
246 panic!("Unknown-required-features ChannelAnnouncements should never deserialize!");
249 let checked_utxo = match self.chain_monitor.get_chain_utxo(msg.contents.chain_hash, msg.contents.short_channel_id) {
250 Ok((script_pubkey, _value)) => {
251 let expected_script = Builder::new().push_opcode(opcodes::All::OP_PUSHNUM_2)
252 .push_slice(&msg.contents.bitcoin_key_1.serialize())
253 .push_slice(&msg.contents.bitcoin_key_2.serialize())
254 .push_opcode(opcodes::All::OP_PUSHNUM_2).push_opcode(opcodes::All::OP_CHECKMULTISIG).into_script().to_v0_p2wsh();
255 if script_pubkey != expected_script {
256 return Err(HandleError{err: "Channel announcement keys didn't match on-chain script", action: Some(ErrorAction::IgnoreError)});
258 //TODO: Check if value is worth storing, use it to inform routing, and compare it
259 //to the new HTLC max field in channel_update
262 Err(ChainError::NotSupported) => {
263 // Tentatively accept, potentially exposing us to DoS attacks
266 Err(ChainError::NotWatched) => {
267 return Err(HandleError{err: "Channel announced on an unknown chain", action: Some(ErrorAction::IgnoreError)});
269 Err(ChainError::UnknownTx) => {
270 return Err(HandleError{err: "Channel announced without corresponding UTXO entry", action: Some(ErrorAction::IgnoreError)});
274 let mut network_lock = self.network_map.write().unwrap();
275 let network = network_lock.borrow_parts();
277 let chan_info = ChannelInfo {
278 features: msg.contents.features.clone(),
279 one_to_two: DirectionalChannelInfo {
280 src_node_id: msg.contents.node_id_1.clone(),
283 cltv_expiry_delta: u16::max_value(),
284 htlc_minimum_msat: u64::max_value(),
285 fee_base_msat: u32::max_value(),
286 fee_proportional_millionths: u32::max_value(),
288 two_to_one: DirectionalChannelInfo {
289 src_node_id: msg.contents.node_id_2.clone(),
292 cltv_expiry_delta: u16::max_value(),
293 htlc_minimum_msat: u64::max_value(),
294 fee_base_msat: u32::max_value(),
295 fee_proportional_millionths: u32::max_value(),
299 match network.channels.entry(NetworkMap::get_key(msg.contents.short_channel_id, msg.contents.chain_hash)) {
300 Entry::Occupied(mut entry) => {
301 //TODO: because asking the blockchain if short_channel_id is valid is only optional
302 //in the blockchain API, we need to handle it smartly here, though its unclear
305 // Either our UTXO provider is busted, there was a reorg, or the UTXO provider
306 // only sometimes returns results. In any case remove the previous entry. Note
307 // that the spec expects us to "blacklist" the node_ids involved, but we can't
309 // a) we don't *require* a UTXO provider that always returns results.
310 // b) we don't track UTXOs of channels we know about and remove them if they
312 // c) it's unclear how to do so without exposing ourselves to massive DoS risk.
313 Self::remove_channel_in_nodes(network.nodes, &entry.get(), msg.contents.short_channel_id);
314 *entry.get_mut() = chan_info;
316 return Err(HandleError{err: "Already have knowledge of channel", action: Some(ErrorAction::IgnoreError)})
319 Entry::Vacant(entry) => {
320 entry.insert(chan_info);
324 macro_rules! add_channel_to_node {
325 ( $node_id: expr ) => {
326 match network.nodes.entry($node_id) {
327 Entry::Occupied(node_entry) => {
328 node_entry.into_mut().channels.push(NetworkMap::get_key(msg.contents.short_channel_id, msg.contents.chain_hash));
330 Entry::Vacant(node_entry) => {
331 node_entry.insert(NodeInfo {
332 channels: vec!(NetworkMap::get_key(msg.contents.short_channel_id, msg.contents.chain_hash)),
333 lowest_inbound_channel_fee_base_msat: u32::max_value(),
334 lowest_inbound_channel_fee_proportional_millionths: u32::max_value(),
335 features: GlobalFeatures::new(),
339 addresses: Vec::new(),
346 add_channel_to_node!(msg.contents.node_id_1);
347 add_channel_to_node!(msg.contents.node_id_2);
349 Ok(msg.contents.excess_data.is_empty() && !msg.contents.features.supports_unknown_bits())
352 fn handle_htlc_fail_channel_update(&self, update: &msgs::HTLCFailChannelUpdate) {
354 &msgs::HTLCFailChannelUpdate::ChannelUpdateMessage { ref msg } => {
355 let _ = self.handle_channel_update(msg);
357 &msgs::HTLCFailChannelUpdate::ChannelClosed { ref short_channel_id, is_permanent:_ } => {
358 let mut network = self.network_map.write().unwrap();
359 if let Some(chan) = network.channels.remove(short_channel_id) {
360 Self::remove_channel_in_nodes(&mut network.nodes, &chan, *short_channel_id);
363 &msgs::HTLCFailChannelUpdate::NodeFailure { ref node_id, is_permanent:_ } => {
364 //let mut network = self.network_map.write().unwrap();
365 //TODO: check _blamed_upstream_node
366 self.mark_node_bad(node_id, false);
371 fn handle_channel_update(&self, msg: &msgs::ChannelUpdate) -> Result<bool, HandleError> {
372 let mut network = self.network_map.write().unwrap();
374 let chan_enabled = msg.contents.flags & (1 << 1) != (1 << 1);
375 let chan_was_enabled;
377 match network.channels.get_mut(&NetworkMap::get_key(msg.contents.short_channel_id, msg.contents.chain_hash)) {
378 None => return Err(HandleError{err: "Couldn't find channel for update", action: Some(ErrorAction::IgnoreError)}),
380 macro_rules! maybe_update_channel_info {
381 ( $target: expr) => {
382 if $target.last_update >= msg.contents.timestamp {
383 return Err(HandleError{err: "Update older than last processed update", action: Some(ErrorAction::IgnoreError)});
385 chan_was_enabled = $target.enabled;
386 $target.last_update = msg.contents.timestamp;
387 $target.enabled = chan_enabled;
388 $target.cltv_expiry_delta = msg.contents.cltv_expiry_delta;
389 $target.htlc_minimum_msat = msg.contents.htlc_minimum_msat;
390 $target.fee_base_msat = msg.contents.fee_base_msat;
391 $target.fee_proportional_millionths = msg.contents.fee_proportional_millionths;
395 let msg_hash = Message::from_slice(&Sha256dHash::from_data(&msg.contents.encode()[..])[..]).unwrap();
396 if msg.contents.flags & 1 == 1 {
397 dest_node_id = channel.one_to_two.src_node_id.clone();
398 secp_verify_sig!(self.secp_ctx, &msg_hash, &msg.signature, &channel.two_to_one.src_node_id);
399 maybe_update_channel_info!(channel.two_to_one);
401 dest_node_id = channel.two_to_one.src_node_id.clone();
402 secp_verify_sig!(self.secp_ctx, &msg_hash, &msg.signature, &channel.one_to_two.src_node_id);
403 maybe_update_channel_info!(channel.one_to_two);
409 let node = network.nodes.get_mut(&dest_node_id).unwrap();
410 node.lowest_inbound_channel_fee_base_msat = cmp::min(node.lowest_inbound_channel_fee_base_msat, msg.contents.fee_base_msat);
411 node.lowest_inbound_channel_fee_proportional_millionths = cmp::min(node.lowest_inbound_channel_fee_proportional_millionths, msg.contents.fee_proportional_millionths);
412 } else if chan_was_enabled {
413 let mut lowest_inbound_channel_fee_base_msat = u32::max_value();
414 let mut lowest_inbound_channel_fee_proportional_millionths = u32::max_value();
417 let node = network.nodes.get(&dest_node_id).unwrap();
419 for chan_id in node.channels.iter() {
420 let chan = network.channels.get(chan_id).unwrap();
421 if chan.one_to_two.src_node_id == dest_node_id {
422 lowest_inbound_channel_fee_base_msat = cmp::min(lowest_inbound_channel_fee_base_msat, chan.two_to_one.fee_base_msat);
423 lowest_inbound_channel_fee_proportional_millionths = cmp::min(lowest_inbound_channel_fee_proportional_millionths, chan.two_to_one.fee_proportional_millionths);
425 lowest_inbound_channel_fee_base_msat = cmp::min(lowest_inbound_channel_fee_base_msat, chan.one_to_two.fee_base_msat);
426 lowest_inbound_channel_fee_proportional_millionths = cmp::min(lowest_inbound_channel_fee_proportional_millionths, chan.one_to_two.fee_proportional_millionths);
431 //TODO: satisfy the borrow-checker without a double-map-lookup :(
432 let mut_node = network.nodes.get_mut(&dest_node_id).unwrap();
433 mut_node.lowest_inbound_channel_fee_base_msat = lowest_inbound_channel_fee_base_msat;
434 mut_node.lowest_inbound_channel_fee_proportional_millionths = lowest_inbound_channel_fee_proportional_millionths;
437 Ok(msg.contents.excess_data.is_empty())
441 #[derive(Eq, PartialEq)]
442 struct RouteGraphNode {
444 lowest_fee_to_peer_through_node: u64,
445 lowest_fee_to_node: u64,
448 impl cmp::Ord for RouteGraphNode {
449 fn cmp(&self, other: &RouteGraphNode) -> cmp::Ordering {
450 other.lowest_fee_to_peer_through_node.cmp(&self.lowest_fee_to_peer_through_node)
451 .then_with(|| other.pubkey.serialize().cmp(&self.pubkey.serialize()))
455 impl cmp::PartialOrd for RouteGraphNode {
456 fn partial_cmp(&self, other: &RouteGraphNode) -> Option<cmp::Ordering> {
457 Some(self.cmp(other))
461 struct DummyDirectionalChannelInfo {
462 src_node_id: PublicKey,
464 cltv_expiry_delta: u32,
465 htlc_minimum_msat: u64,
467 fee_proportional_millionths: u32,
471 /// Creates a new router with the given node_id to be used as the source for get_route()
472 pub fn new(our_pubkey: PublicKey, chain_monitor: Arc<ChainWatchInterface>, logger: Arc<Logger>) -> Router {
473 let mut nodes = HashMap::new();
474 nodes.insert(our_pubkey.clone(), NodeInfo {
475 channels: Vec::new(),
476 lowest_inbound_channel_fee_base_msat: u32::max_value(),
477 lowest_inbound_channel_fee_proportional_millionths: u32::max_value(),
478 features: GlobalFeatures::new(),
482 addresses: Vec::new(),
485 secp_ctx: Secp256k1::verification_only(),
486 network_map: RwLock::new(NetworkMap {
487 channels: HashMap::new(),
488 our_node_id: our_pubkey,
496 /// Dumps the entire network view of this Router to the logger provided in the constructor at
498 pub fn trace_state(&self) {
499 log_trace!(self, "{}", self.network_map.read().unwrap());
502 /// Get network addresses by node id
503 pub fn get_addresses(&self, pubkey: &PublicKey) -> Option<Vec<NetAddress>> {
504 let network = self.network_map.read().unwrap();
505 network.nodes.get(pubkey).map(|n| n.addresses.clone())
508 /// Marks a node as having failed a route. This will avoid re-using the node in routes for now,
509 /// with an expotnential decay in node "badness". Note that there is deliberately no
510 /// mark_channel_bad as a node may simply lie and suggest that an upstream channel from it is
511 /// what failed the route and not the node itself. Instead, setting the blamed_upstream_node
512 /// boolean will reduce the penalty, returning the node to usability faster. If the node is
513 /// behaving correctly, it will disable the failing channel and we will use it again next time.
514 pub fn mark_node_bad(&self, _node_id: &PublicKey, _blamed_upstream_node: bool) {
518 fn remove_channel_in_nodes(nodes: &mut HashMap<PublicKey, NodeInfo>, chan: &ChannelInfo, short_channel_id: u64) {
519 macro_rules! remove_from_node {
520 ($node_id: expr) => {
521 if let Entry::Occupied(mut entry) = nodes.entry($node_id) {
522 entry.get_mut().channels.retain(|chan_id| {
523 short_channel_id != *NetworkMap::get_short_id(chan_id)
525 if entry.get().channels.is_empty() {
526 entry.remove_entry();
529 panic!("Had channel that pointed to unknown node (ie inconsistent network map)!");
533 remove_from_node!(chan.one_to_two.src_node_id);
534 remove_from_node!(chan.two_to_one.src_node_id);
537 /// Gets a route from us to the given target node.
539 /// Extra routing hops between known nodes and the target will be used if they are included in
542 /// If some channels aren't announced, it may be useful to fill in a first_hops with the
543 /// results from a local ChannelManager::list_usable_channels() call. If it is filled in, our
544 /// (this Router's) view of our local channels will be ignored, and only those in first_hops
547 /// Panics if first_hops contains channels without short_channel_ids
548 /// (ChannelManager::list_usable_channels will never include such channels).
550 /// The fees on channels from us to next-hops are ignored (as they are assumed to all be
551 /// equal), however the enabled/disabled bit on such channels as well as the htlc_minimum_msat
552 /// *is* checked as they may change based on the receiving node.
553 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> {
554 // TODO: Obviously *only* using total fee cost sucks. We should consider weighting by
555 // uptime/success in using a node in the past.
556 let network = self.network_map.read().unwrap();
558 if *target == network.our_node_id {
559 return Err(HandleError{err: "Cannot generate a route to ourselves", action: None});
562 if final_value_msat > 21_000_000 * 1_0000_0000 * 1000 {
563 return Err(HandleError{err: "Cannot generate a route of more value than all existing satoshis", action: None});
566 // We do a dest-to-source Dijkstra's sorting by each node's distance from the destination
567 // plus the minimum per-HTLC fee to get from it to another node (aka "shitty A*").
568 // TODO: There are a few tweaks we could do, including possibly pre-calculating more stuff
569 // to use as the A* heuristic beyond just the cost to get one node further than the current
572 let dummy_directional_info = DummyDirectionalChannelInfo { // used for first_hops routes
573 src_node_id: network.our_node_id.clone(),
575 cltv_expiry_delta: 0,
576 htlc_minimum_msat: 0,
578 fee_proportional_millionths: 0,
581 let mut targets = BinaryHeap::new(); //TODO: Do we care about switching to eg Fibbonaci heap?
582 let mut dist = HashMap::with_capacity(network.nodes.len());
584 let mut first_hop_targets = HashMap::with_capacity(if first_hops.is_some() { first_hops.as_ref().unwrap().len() } else { 0 });
585 if let Some(hops) = first_hops {
587 let short_channel_id = chan.short_channel_id.expect("first_hops should be filled in with usable channels, not pending ones");
588 if chan.remote_network_id == *target {
590 hops: vec![RouteHop {
591 pubkey: chan.remote_network_id,
593 fee_msat: final_value_msat,
594 cltv_expiry_delta: final_cltv,
595 channel_update_timestamp: 0, //TODO: related to local channel_update_handling?
599 first_hop_targets.insert(chan.remote_network_id, short_channel_id);
601 if first_hop_targets.is_empty() {
602 return Err(HandleError{err: "Cannot route when there are no outbound routes away from us", action: None});
606 macro_rules! add_entry {
607 // Adds entry which goes from the node pointed to by $directional_info to
608 // $dest_node_id over the channel with id $chan_id with fees described in
609 // $directional_info.
610 ( $chan_id: expr, $dest_node_id: expr, $directional_info: expr, $starting_fee_msat: expr ) => {
611 //TODO: Explore simply adding fee to hit htlc_minimum_msat
612 if $starting_fee_msat as u64 + final_value_msat > $directional_info.htlc_minimum_msat {
613 let proportional_fee_millions = ($starting_fee_msat + final_value_msat).checked_mul($directional_info.fee_proportional_millionths as u64);
614 if let Some(new_fee) = proportional_fee_millions.and_then(|part| {
615 ($directional_info.fee_base_msat as u64).checked_add(part / 1000000) })
617 let mut total_fee = $starting_fee_msat as u64;
618 let hm_entry = dist.entry(&$directional_info.src_node_id);
619 let old_entry = hm_entry.or_insert_with(|| {
620 let node = network.nodes.get(&$directional_info.src_node_id).unwrap();
622 node.lowest_inbound_channel_fee_base_msat,
623 node.lowest_inbound_channel_fee_proportional_millionths,
625 pubkey: $dest_node_id.clone(),
628 cltv_expiry_delta: 0,
629 channel_update_timestamp: $directional_info.last_update,
632 if $directional_info.src_node_id != network.our_node_id {
633 // Ignore new_fee for channel-from-us as we assume all channels-from-us
634 // will have the same effective-fee
635 total_fee += new_fee;
636 if let Some(fee_inc) = final_value_msat.checked_add(total_fee).and_then(|inc| { (old_entry.2 as u64).checked_mul(inc) }) {
637 total_fee += fee_inc / 1000000 + (old_entry.1 as u64);
639 // max_value means we'll always fail the old_entry.0 > total_fee check
640 total_fee = u64::max_value();
643 let new_graph_node = RouteGraphNode {
644 pubkey: $directional_info.src_node_id,
645 lowest_fee_to_peer_through_node: total_fee,
646 lowest_fee_to_node: $starting_fee_msat as u64 + new_fee,
648 if old_entry.0 > total_fee {
649 targets.push(new_graph_node);
650 old_entry.0 = total_fee;
651 old_entry.3 = RouteHop {
652 pubkey: $dest_node_id.clone(),
653 short_channel_id: $chan_id.clone(),
654 fee_msat: new_fee, // This field is ignored on the last-hop anyway
655 cltv_expiry_delta: $directional_info.cltv_expiry_delta as u32,
656 channel_update_timestamp: $directional_info.last_update,
664 macro_rules! add_entries_to_cheapest_to_target_node {
665 ( $node: expr, $node_id: expr, $fee_to_target_msat: expr ) => {
666 if first_hops.is_some() {
667 if let Some(first_hop) = first_hop_targets.get(&$node_id) {
668 add_entry!(first_hop, $node_id, dummy_directional_info, $fee_to_target_msat);
672 for chan_id in $node.channels.iter() {
673 let chan = network.channels.get(chan_id).unwrap();
674 if chan.one_to_two.src_node_id == *$node_id {
675 // ie $node is one, ie next hop in A* is two, via the two_to_one channel
676 if first_hops.is_none() || chan.two_to_one.src_node_id != network.our_node_id {
677 if chan.two_to_one.enabled {
678 add_entry!(chan_id, chan.one_to_two.src_node_id, chan.two_to_one, $fee_to_target_msat);
682 if first_hops.is_none() || chan.one_to_two.src_node_id != network.our_node_id {
683 if chan.one_to_two.enabled {
684 add_entry!(chan_id, chan.two_to_one.src_node_id, chan.one_to_two, $fee_to_target_msat);
692 match network.nodes.get(target) {
695 add_entries_to_cheapest_to_target_node!(node, target, 0);
699 for hop in last_hops.iter() {
700 if first_hops.is_none() || hop.src_node_id != network.our_node_id { // first_hop overrules last_hops
701 if network.nodes.get(&hop.src_node_id).is_some() {
702 if first_hops.is_some() {
703 if let Some(first_hop) = first_hop_targets.get(&hop.src_node_id) {
704 add_entry!(first_hop, hop.src_node_id, dummy_directional_info, 0);
707 add_entry!(hop.short_channel_id, target, hop, 0);
712 while let Some(RouteGraphNode { pubkey, lowest_fee_to_node, .. }) = targets.pop() {
713 if pubkey == network.our_node_id {
714 let mut res = vec!(dist.remove(&network.our_node_id).unwrap().3);
715 while res.last().unwrap().pubkey != *target {
716 let new_entry = match dist.remove(&res.last().unwrap().pubkey) {
718 None => return Err(HandleError{err: "Failed to find a non-fee-overflowing path to the given destination", action: None}),
720 res.last_mut().unwrap().fee_msat = new_entry.fee_msat;
721 res.last_mut().unwrap().cltv_expiry_delta = new_entry.cltv_expiry_delta;
724 res.last_mut().unwrap().fee_msat = final_value_msat;
725 res.last_mut().unwrap().cltv_expiry_delta = final_cltv;
726 let route = Route { hops: res };
727 log_trace!(self, "Got route: {}", log_route!(route));
731 match network.nodes.get(&pubkey) {
734 add_entries_to_cheapest_to_target_node!(node, &pubkey, lowest_fee_to_node);
739 Err(HandleError{err: "Failed to find a path to the given destination", action: None})
745 use chain::chaininterface;
746 use ln::channelmanager;
747 use ln::router::{Router,NodeInfo,NetworkMap,ChannelInfo,DirectionalChannelInfo,RouteHint};
748 use ln::msgs::GlobalFeatures;
749 use util::test_utils;
750 use util::logger::Logger;
752 use bitcoin::util::hash::Sha256dHash;
753 use bitcoin::network::constants::Network;
757 use secp256k1::key::{PublicKey,SecretKey};
758 use secp256k1::Secp256k1;
764 let secp_ctx = Secp256k1::new();
765 let our_id = PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&secp_ctx, &hex::decode("0101010101010101010101010101010101010101010101010101010101010101").unwrap()[..]).unwrap());
766 let logger: Arc<Logger> = Arc::new(test_utils::TestLogger::new());
767 let chain_monitor = Arc::new(chaininterface::ChainWatchInterfaceUtil::new(Network::Testnet, Arc::clone(&logger)));
768 let router = Router::new(our_id, chain_monitor, Arc::clone(&logger));
770 // Build network from our_id to node8:
772 // -1(1)2- node1 -1(3)2-
774 // our_id -1(12)2- node8 -1(13)2--- node3
776 // -1(2)2- node2 -1(4)2-
779 // chan1 1-to-2: disabled
780 // chan1 2-to-1: enabled, 0 fee
782 // chan2 1-to-2: enabled, ignored fee
783 // chan2 2-to-1: enabled, 0 fee
785 // chan3 1-to-2: enabled, 0 fee
786 // chan3 2-to-1: enabled, 100 msat fee
788 // chan4 1-to-2: enabled, 100% fee
789 // chan4 2-to-1: enabled, 0 fee
791 // chan12 1-to-2: enabled, ignored fee
792 // chan12 2-to-1: enabled, 0 fee
794 // chan13 1-to-2: enabled, 200% fee
795 // chan13 2-to-1: enabled, 0 fee
798 // -1(5)2- node4 -1(8)2--
802 // node3--1(6)2- node5 -1(9)2--- node7 (not in global route map)
804 // -1(7)2- node6 -1(10)2-
806 // chan5 1-to-2: enabled, 100 msat fee
807 // chan5 2-to-1: enabled, 0 fee
809 // chan6 1-to-2: enabled, 0 fee
810 // chan6 2-to-1: enabled, 0 fee
812 // chan7 1-to-2: enabled, 100% fee
813 // chan7 2-to-1: enabled, 0 fee
815 // chan8 1-to-2: enabled, variable fee (0 then 1000 msat)
816 // chan8 2-to-1: enabled, 0 fee
818 // chan9 1-to-2: enabled, 1001 msat fee
819 // chan9 2-to-1: enabled, 0 fee
821 // chan10 1-to-2: enabled, 0 fee
822 // chan10 2-to-1: enabled, 0 fee
824 // chan11 1-to-2: enabled, 0 fee
825 // chan11 2-to-1: enabled, 0 fee
827 let node1 = PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&secp_ctx, &hex::decode("0202020202020202020202020202020202020202020202020202020202020202").unwrap()[..]).unwrap());
828 let node2 = PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&secp_ctx, &hex::decode("0303030303030303030303030303030303030303030303030303030303030303").unwrap()[..]).unwrap());
829 let node3 = PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&secp_ctx, &hex::decode("0404040404040404040404040404040404040404040404040404040404040404").unwrap()[..]).unwrap());
830 let node4 = PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&secp_ctx, &hex::decode("0505050505050505050505050505050505050505050505050505050505050505").unwrap()[..]).unwrap());
831 let node5 = PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&secp_ctx, &hex::decode("0606060606060606060606060606060606060606060606060606060606060606").unwrap()[..]).unwrap());
832 let node6 = PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&secp_ctx, &hex::decode("0707070707070707070707070707070707070707070707070707070707070707").unwrap()[..]).unwrap());
833 let node7 = PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&secp_ctx, &hex::decode("0808080808080808080808080808080808080808080808080808080808080808").unwrap()[..]).unwrap());
834 let node8 = PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&secp_ctx, &hex::decode("0909090909090909090909090909090909090909090909090909090909090909").unwrap()[..]).unwrap());
836 let zero_hash = Sha256dHash::from_data(&[0; 32]);
839 let mut network = router.network_map.write().unwrap();
841 network.nodes.insert(node1.clone(), NodeInfo {
842 channels: vec!(NetworkMap::get_key(1, zero_hash.clone()), NetworkMap::get_key(3, zero_hash.clone())),
843 lowest_inbound_channel_fee_base_msat: 100,
844 lowest_inbound_channel_fee_proportional_millionths: 0,
845 features: GlobalFeatures::new(),
849 addresses: Vec::new(),
851 network.channels.insert(NetworkMap::get_key(1, zero_hash.clone()), ChannelInfo {
852 features: GlobalFeatures::new(),
853 one_to_two: DirectionalChannelInfo {
854 src_node_id: our_id.clone(),
857 cltv_expiry_delta: u16::max_value(), // This value should be ignored
858 htlc_minimum_msat: 0,
859 fee_base_msat: u32::max_value(), // This value should be ignored
860 fee_proportional_millionths: u32::max_value(), // This value should be ignored
861 }, two_to_one: DirectionalChannelInfo {
862 src_node_id: node1.clone(),
865 cltv_expiry_delta: 0,
866 htlc_minimum_msat: 0,
868 fee_proportional_millionths: 0,
871 network.nodes.insert(node2.clone(), NodeInfo {
872 channels: vec!(NetworkMap::get_key(2, zero_hash.clone()), NetworkMap::get_key(4, zero_hash.clone())),
873 lowest_inbound_channel_fee_base_msat: 0,
874 lowest_inbound_channel_fee_proportional_millionths: 0,
875 features: GlobalFeatures::new(),
879 addresses: Vec::new(),
881 network.channels.insert(NetworkMap::get_key(2, zero_hash.clone()), ChannelInfo {
882 features: GlobalFeatures::new(),
883 one_to_two: DirectionalChannelInfo {
884 src_node_id: our_id.clone(),
887 cltv_expiry_delta: u16::max_value(), // This value should be ignored
888 htlc_minimum_msat: 0,
889 fee_base_msat: u32::max_value(), // This value should be ignored
890 fee_proportional_millionths: u32::max_value(), // This value should be ignored
891 }, two_to_one: DirectionalChannelInfo {
892 src_node_id: node2.clone(),
895 cltv_expiry_delta: 0,
896 htlc_minimum_msat: 0,
898 fee_proportional_millionths: 0,
901 network.nodes.insert(node8.clone(), NodeInfo {
902 channels: vec!(NetworkMap::get_key(12, zero_hash.clone()), NetworkMap::get_key(13, zero_hash.clone())),
903 lowest_inbound_channel_fee_base_msat: 0,
904 lowest_inbound_channel_fee_proportional_millionths: 0,
905 features: GlobalFeatures::new(),
909 addresses: Vec::new(),
911 network.channels.insert(NetworkMap::get_key(12, zero_hash.clone()), ChannelInfo {
912 features: GlobalFeatures::new(),
913 one_to_two: DirectionalChannelInfo {
914 src_node_id: our_id.clone(),
917 cltv_expiry_delta: u16::max_value(), // This value should be ignored
918 htlc_minimum_msat: 0,
919 fee_base_msat: u32::max_value(), // This value should be ignored
920 fee_proportional_millionths: u32::max_value(), // This value should be ignored
921 }, two_to_one: DirectionalChannelInfo {
922 src_node_id: node8.clone(),
925 cltv_expiry_delta: 0,
926 htlc_minimum_msat: 0,
928 fee_proportional_millionths: 0,
931 network.nodes.insert(node3.clone(), NodeInfo {
933 NetworkMap::get_key(3, zero_hash.clone()),
934 NetworkMap::get_key(4, zero_hash.clone()),
935 NetworkMap::get_key(13, zero_hash.clone()),
936 NetworkMap::get_key(5, zero_hash.clone()),
937 NetworkMap::get_key(6, zero_hash.clone()),
938 NetworkMap::get_key(7, zero_hash.clone())),
939 lowest_inbound_channel_fee_base_msat: 0,
940 lowest_inbound_channel_fee_proportional_millionths: 0,
941 features: GlobalFeatures::new(),
945 addresses: Vec::new(),
947 network.channels.insert(NetworkMap::get_key(3, zero_hash.clone()), ChannelInfo {
948 features: GlobalFeatures::new(),
949 one_to_two: DirectionalChannelInfo {
950 src_node_id: node1.clone(),
953 cltv_expiry_delta: (3 << 8) | 1,
954 htlc_minimum_msat: 0,
956 fee_proportional_millionths: 0,
957 }, two_to_one: DirectionalChannelInfo {
958 src_node_id: node3.clone(),
961 cltv_expiry_delta: (3 << 8) | 2,
962 htlc_minimum_msat: 0,
964 fee_proportional_millionths: 0,
967 network.channels.insert(NetworkMap::get_key(4, zero_hash.clone()), ChannelInfo {
968 features: GlobalFeatures::new(),
969 one_to_two: DirectionalChannelInfo {
970 src_node_id: node2.clone(),
973 cltv_expiry_delta: (4 << 8) | 1,
974 htlc_minimum_msat: 0,
976 fee_proportional_millionths: 1000000,
977 }, two_to_one: DirectionalChannelInfo {
978 src_node_id: node3.clone(),
981 cltv_expiry_delta: (4 << 8) | 2,
982 htlc_minimum_msat: 0,
984 fee_proportional_millionths: 0,
987 network.channels.insert(NetworkMap::get_key(13, zero_hash.clone()), ChannelInfo {
988 features: GlobalFeatures::new(),
989 one_to_two: DirectionalChannelInfo {
990 src_node_id: node8.clone(),
993 cltv_expiry_delta: (13 << 8) | 1,
994 htlc_minimum_msat: 0,
996 fee_proportional_millionths: 2000000,
997 }, two_to_one: DirectionalChannelInfo {
998 src_node_id: node3.clone(),
1001 cltv_expiry_delta: (13 << 8) | 2,
1002 htlc_minimum_msat: 0,
1004 fee_proportional_millionths: 0,
1007 network.nodes.insert(node4.clone(), NodeInfo {
1008 channels: vec!(NetworkMap::get_key(5, zero_hash.clone()), NetworkMap::get_key(11, zero_hash.clone())),
1009 lowest_inbound_channel_fee_base_msat: 0,
1010 lowest_inbound_channel_fee_proportional_millionths: 0,
1011 features: GlobalFeatures::new(),
1015 addresses: Vec::new(),
1017 network.channels.insert(NetworkMap::get_key(5, zero_hash.clone()), ChannelInfo {
1018 features: GlobalFeatures::new(),
1019 one_to_two: DirectionalChannelInfo {
1020 src_node_id: node3.clone(),
1023 cltv_expiry_delta: (5 << 8) | 1,
1024 htlc_minimum_msat: 0,
1026 fee_proportional_millionths: 0,
1027 }, two_to_one: DirectionalChannelInfo {
1028 src_node_id: node4.clone(),
1031 cltv_expiry_delta: (5 << 8) | 2,
1032 htlc_minimum_msat: 0,
1034 fee_proportional_millionths: 0,
1037 network.nodes.insert(node5.clone(), NodeInfo {
1038 channels: vec!(NetworkMap::get_key(6, zero_hash.clone()), NetworkMap::get_key(11, zero_hash.clone())),
1039 lowest_inbound_channel_fee_base_msat: 0,
1040 lowest_inbound_channel_fee_proportional_millionths: 0,
1041 features: GlobalFeatures::new(),
1045 addresses: Vec::new(),
1047 network.channels.insert(NetworkMap::get_key(6, zero_hash.clone()), ChannelInfo {
1048 features: GlobalFeatures::new(),
1049 one_to_two: DirectionalChannelInfo {
1050 src_node_id: node3.clone(),
1053 cltv_expiry_delta: (6 << 8) | 1,
1054 htlc_minimum_msat: 0,
1056 fee_proportional_millionths: 0,
1057 }, two_to_one: DirectionalChannelInfo {
1058 src_node_id: node5.clone(),
1061 cltv_expiry_delta: (6 << 8) | 2,
1062 htlc_minimum_msat: 0,
1064 fee_proportional_millionths: 0,
1067 network.channels.insert(NetworkMap::get_key(11, zero_hash.clone()), ChannelInfo {
1068 features: GlobalFeatures::new(),
1069 one_to_two: DirectionalChannelInfo {
1070 src_node_id: node5.clone(),
1073 cltv_expiry_delta: (11 << 8) | 1,
1074 htlc_minimum_msat: 0,
1076 fee_proportional_millionths: 0,
1077 }, two_to_one: DirectionalChannelInfo {
1078 src_node_id: node4.clone(),
1081 cltv_expiry_delta: (11 << 8) | 2,
1082 htlc_minimum_msat: 0,
1084 fee_proportional_millionths: 0,
1087 network.nodes.insert(node6.clone(), NodeInfo {
1088 channels: vec!(NetworkMap::get_key(7, zero_hash.clone())),
1089 lowest_inbound_channel_fee_base_msat: 0,
1090 lowest_inbound_channel_fee_proportional_millionths: 0,
1091 features: GlobalFeatures::new(),
1095 addresses: Vec::new(),
1097 network.channels.insert(NetworkMap::get_key(7, zero_hash.clone()), ChannelInfo {
1098 features: GlobalFeatures::new(),
1099 one_to_two: DirectionalChannelInfo {
1100 src_node_id: node3.clone(),
1103 cltv_expiry_delta: (7 << 8) | 1,
1104 htlc_minimum_msat: 0,
1106 fee_proportional_millionths: 1000000,
1107 }, two_to_one: DirectionalChannelInfo {
1108 src_node_id: node6.clone(),
1111 cltv_expiry_delta: (7 << 8) | 2,
1112 htlc_minimum_msat: 0,
1114 fee_proportional_millionths: 0,
1119 { // Simple route to 3 via 2
1120 let route = router.get_route(&node3, None, &Vec::new(), 100, 42).unwrap();
1121 assert_eq!(route.hops.len(), 2);
1123 assert_eq!(route.hops[0].pubkey, node2);
1124 assert_eq!(route.hops[0].short_channel_id, 2);
1125 assert_eq!(route.hops[0].fee_msat, 100);
1126 assert_eq!(route.hops[0].cltv_expiry_delta, (4 << 8) | 1);
1128 assert_eq!(route.hops[1].pubkey, node3);
1129 assert_eq!(route.hops[1].short_channel_id, 4);
1130 assert_eq!(route.hops[1].fee_msat, 100);
1131 assert_eq!(route.hops[1].cltv_expiry_delta, 42);
1134 { // Route to 1 via 2 and 3 because our channel to 1 is disabled
1135 let route = router.get_route(&node1, None, &Vec::new(), 100, 42).unwrap();
1136 assert_eq!(route.hops.len(), 3);
1138 assert_eq!(route.hops[0].pubkey, node2);
1139 assert_eq!(route.hops[0].short_channel_id, 2);
1140 assert_eq!(route.hops[0].fee_msat, 200);
1141 assert_eq!(route.hops[0].cltv_expiry_delta, (4 << 8) | 1);
1143 assert_eq!(route.hops[1].pubkey, node3);
1144 assert_eq!(route.hops[1].short_channel_id, 4);
1145 assert_eq!(route.hops[1].fee_msat, 100);
1146 assert_eq!(route.hops[1].cltv_expiry_delta, (3 << 8) | 2);
1148 assert_eq!(route.hops[2].pubkey, node1);
1149 assert_eq!(route.hops[2].short_channel_id, 3);
1150 assert_eq!(route.hops[2].fee_msat, 100);
1151 assert_eq!(route.hops[2].cltv_expiry_delta, 42);
1154 { // If we specify a channel to node8, that overrides our local channel view and that gets used
1155 let our_chans = vec![channelmanager::ChannelDetails {
1156 channel_id: [0; 32],
1157 short_channel_id: Some(42),
1158 remote_network_id: node8.clone(),
1159 channel_value_satoshis: 0,
1162 let route = router.get_route(&node3, Some(&our_chans), &Vec::new(), 100, 42).unwrap();
1163 assert_eq!(route.hops.len(), 2);
1165 assert_eq!(route.hops[0].pubkey, node8);
1166 assert_eq!(route.hops[0].short_channel_id, 42);
1167 assert_eq!(route.hops[0].fee_msat, 200);
1168 assert_eq!(route.hops[0].cltv_expiry_delta, (13 << 8) | 1);
1170 assert_eq!(route.hops[1].pubkey, node3);
1171 assert_eq!(route.hops[1].short_channel_id, 13);
1172 assert_eq!(route.hops[1].fee_msat, 100);
1173 assert_eq!(route.hops[1].cltv_expiry_delta, 42);
1176 let mut last_hops = vec!(RouteHint {
1177 src_node_id: node4.clone(),
1178 short_channel_id: 8,
1181 fee_proportional_millionths: 0,
1182 cltv_expiry_delta: (8 << 8) | 1,
1183 htlc_minimum_msat: 0,
1185 src_node_id: node5.clone(),
1186 short_channel_id: 9,
1188 fee_base_msat: 1001,
1189 fee_proportional_millionths: 0,
1190 cltv_expiry_delta: (9 << 8) | 1,
1191 htlc_minimum_msat: 0,
1193 src_node_id: node6.clone(),
1194 short_channel_id: 10,
1197 fee_proportional_millionths: 0,
1198 cltv_expiry_delta: (10 << 8) | 1,
1199 htlc_minimum_msat: 0,
1202 { // Simple test across 2, 3, 5, and 4 via a last_hop channel
1203 let route = router.get_route(&node7, None, &last_hops, 100, 42).unwrap();
1204 assert_eq!(route.hops.len(), 5);
1206 assert_eq!(route.hops[0].pubkey, node2);
1207 assert_eq!(route.hops[0].short_channel_id, 2);
1208 assert_eq!(route.hops[0].fee_msat, 100);
1209 assert_eq!(route.hops[0].cltv_expiry_delta, (4 << 8) | 1);
1211 assert_eq!(route.hops[1].pubkey, node3);
1212 assert_eq!(route.hops[1].short_channel_id, 4);
1213 assert_eq!(route.hops[1].fee_msat, 0);
1214 assert_eq!(route.hops[1].cltv_expiry_delta, (6 << 8) | 1);
1216 assert_eq!(route.hops[2].pubkey, node5);
1217 assert_eq!(route.hops[2].short_channel_id, 6);
1218 assert_eq!(route.hops[2].fee_msat, 0);
1219 assert_eq!(route.hops[2].cltv_expiry_delta, (11 << 8) | 1);
1221 assert_eq!(route.hops[3].pubkey, node4);
1222 assert_eq!(route.hops[3].short_channel_id, 11);
1223 assert_eq!(route.hops[3].fee_msat, 0);
1224 assert_eq!(route.hops[3].cltv_expiry_delta, (8 << 8) | 1);
1226 assert_eq!(route.hops[4].pubkey, node7);
1227 assert_eq!(route.hops[4].short_channel_id, 8);
1228 assert_eq!(route.hops[4].fee_msat, 100);
1229 assert_eq!(route.hops[4].cltv_expiry_delta, 42);
1232 { // Simple test with outbound channel to 4 to test that last_hops and first_hops connect
1233 let our_chans = vec![channelmanager::ChannelDetails {
1234 channel_id: [0; 32],
1235 short_channel_id: Some(42),
1236 remote_network_id: node4.clone(),
1237 channel_value_satoshis: 0,
1240 let route = router.get_route(&node7, Some(&our_chans), &last_hops, 100, 42).unwrap();
1241 assert_eq!(route.hops.len(), 2);
1243 assert_eq!(route.hops[0].pubkey, node4);
1244 assert_eq!(route.hops[0].short_channel_id, 42);
1245 assert_eq!(route.hops[0].fee_msat, 0);
1246 assert_eq!(route.hops[0].cltv_expiry_delta, (8 << 8) | 1);
1248 assert_eq!(route.hops[1].pubkey, node7);
1249 assert_eq!(route.hops[1].short_channel_id, 8);
1250 assert_eq!(route.hops[1].fee_msat, 100);
1251 assert_eq!(route.hops[1].cltv_expiry_delta, 42);
1254 last_hops[0].fee_base_msat = 1000;
1256 { // Revert to via 6 as the fee on 8 goes up
1257 let route = router.get_route(&node7, None, &last_hops, 100, 42).unwrap();
1258 assert_eq!(route.hops.len(), 4);
1260 assert_eq!(route.hops[0].pubkey, node2);
1261 assert_eq!(route.hops[0].short_channel_id, 2);
1262 assert_eq!(route.hops[0].fee_msat, 200); // fee increased as its % of value transferred across node
1263 assert_eq!(route.hops[0].cltv_expiry_delta, (4 << 8) | 1);
1265 assert_eq!(route.hops[1].pubkey, node3);
1266 assert_eq!(route.hops[1].short_channel_id, 4);
1267 assert_eq!(route.hops[1].fee_msat, 100);
1268 assert_eq!(route.hops[1].cltv_expiry_delta, (7 << 8) | 1);
1270 assert_eq!(route.hops[2].pubkey, node6);
1271 assert_eq!(route.hops[2].short_channel_id, 7);
1272 assert_eq!(route.hops[2].fee_msat, 0);
1273 assert_eq!(route.hops[2].cltv_expiry_delta, (10 << 8) | 1);
1275 assert_eq!(route.hops[3].pubkey, node7);
1276 assert_eq!(route.hops[3].short_channel_id, 10);
1277 assert_eq!(route.hops[3].fee_msat, 100);
1278 assert_eq!(route.hops[3].cltv_expiry_delta, 42);
1281 { // ...but still use 8 for larger payments as 6 has a variable feerate
1282 let route = router.get_route(&node7, None, &last_hops, 2000, 42).unwrap();
1283 assert_eq!(route.hops.len(), 5);
1285 assert_eq!(route.hops[0].pubkey, node2);
1286 assert_eq!(route.hops[0].short_channel_id, 2);
1287 assert_eq!(route.hops[0].fee_msat, 3000);
1288 assert_eq!(route.hops[0].cltv_expiry_delta, (4 << 8) | 1);
1290 assert_eq!(route.hops[1].pubkey, node3);
1291 assert_eq!(route.hops[1].short_channel_id, 4);
1292 assert_eq!(route.hops[1].fee_msat, 0);
1293 assert_eq!(route.hops[1].cltv_expiry_delta, (6 << 8) | 1);
1295 assert_eq!(route.hops[2].pubkey, node5);
1296 assert_eq!(route.hops[2].short_channel_id, 6);
1297 assert_eq!(route.hops[2].fee_msat, 0);
1298 assert_eq!(route.hops[2].cltv_expiry_delta, (11 << 8) | 1);
1300 assert_eq!(route.hops[3].pubkey, node4);
1301 assert_eq!(route.hops[3].short_channel_id, 11);
1302 assert_eq!(route.hops[3].fee_msat, 1000);
1303 assert_eq!(route.hops[3].cltv_expiry_delta, (8 << 8) | 1);
1305 assert_eq!(route.hops[4].pubkey, node7);
1306 assert_eq!(route.hops[4].short_channel_id, 8);
1307 assert_eq!(route.hops[4].fee_msat, 2000);
1308 assert_eq!(route.hops[4].cltv_expiry_delta, 42);