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::{DecodeError,ErrorAction,HandleError,RoutingMessageHandler,NetAddress,GlobalFeatures};
18 use util::ser::{Writeable, Readable};
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,
41 /// A route from us through the network to a destination
44 /// The list of hops, NOT INCLUDING our own, where the last hop is the destination. Thus, this
45 /// must always be at least length one. By protocol rules, this may not currently exceed 20 in
47 pub hops: Vec<RouteHop>,
50 impl Writeable for Route {
51 fn write<W: ::util::ser::Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
52 (self.hops.len() as u8).write(writer)?;
53 for hop in self.hops.iter() {
54 hop.pubkey.write(writer)?;
55 hop.short_channel_id.write(writer)?;
56 hop.fee_msat.write(writer)?;
57 hop.cltv_expiry_delta.write(writer)?;
63 impl<R: ::std::io::Read> Readable<R> for Route {
64 fn read(reader: &mut R) -> Result<Route, DecodeError> {
65 let hops_count: u8 = Readable::read(reader)?;
66 let mut hops = Vec::with_capacity(hops_count as usize);
67 for _ in 0..hops_count {
69 pubkey: Readable::read(reader)?,
70 short_channel_id: Readable::read(reader)?,
71 fee_msat: Readable::read(reader)?,
72 cltv_expiry_delta: Readable::read(reader)?,
81 struct DirectionalChannelInfo {
82 src_node_id: PublicKey,
85 cltv_expiry_delta: u16,
86 htlc_minimum_msat: u64,
88 fee_proportional_millionths: u32,
91 impl std::fmt::Display for DirectionalChannelInfo {
92 fn fmt(&self, f: &mut std::fmt::Formatter) -> Result<(), std::fmt::Error> {
93 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)?;
99 features: GlobalFeatures,
100 one_to_two: DirectionalChannelInfo,
101 two_to_one: DirectionalChannelInfo,
104 impl std::fmt::Display for ChannelInfo {
105 fn fmt(&self, f: &mut std::fmt::Formatter) -> Result<(), std::fmt::Error> {
106 write!(f, "features: {}, one_to_two: {}, two_to_one: {}", log_bytes!(self.features.encode()), self.one_to_two, self.two_to_one)?;
112 #[cfg(feature = "non_bitcoin_chain_hash_routing")]
113 channels: Vec<(u64, Sha256dHash)>,
114 #[cfg(not(feature = "non_bitcoin_chain_hash_routing"))]
117 lowest_inbound_channel_fee_base_msat: u32,
118 lowest_inbound_channel_fee_proportional_millionths: u32,
120 features: GlobalFeatures,
124 addresses: Vec<NetAddress>,
127 impl std::fmt::Display for NodeInfo {
128 fn fmt(&self, f: &mut std::fmt::Formatter) -> Result<(), std::fmt::Error> {
129 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[..])?;
135 #[cfg(feature = "non_bitcoin_chain_hash_routing")]
136 channels: HashMap<(u64, Sha256dHash), ChannelInfo>,
137 #[cfg(not(feature = "non_bitcoin_chain_hash_routing"))]
138 channels: HashMap<u64, ChannelInfo>,
140 our_node_id: PublicKey,
141 nodes: HashMap<PublicKey, NodeInfo>,
143 struct MutNetworkMap<'a> {
144 #[cfg(feature = "non_bitcoin_chain_hash_routing")]
145 channels: &'a mut HashMap<(u64, Sha256dHash), ChannelInfo>,
146 #[cfg(not(feature = "non_bitcoin_chain_hash_routing"))]
147 channels: &'a mut HashMap<u64, ChannelInfo>,
148 nodes: &'a mut HashMap<PublicKey, NodeInfo>,
151 fn borrow_parts(&mut self) -> MutNetworkMap {
153 channels: &mut self.channels,
154 nodes: &mut self.nodes,
158 impl std::fmt::Display for NetworkMap {
159 fn fmt(&self, f: &mut std::fmt::Formatter) -> Result<(), std::fmt::Error> {
160 write!(f, "Node id {} network map\n[Channels]\n", log_pubkey!(self.our_node_id))?;
161 for (key, val) in self.channels.iter() {
162 write!(f, " {}: {}\n", key, val)?;
164 write!(f, "[Nodes]\n")?;
165 for (key, val) in self.nodes.iter() {
166 write!(f, " {}: {}\n", log_pubkey!(key), val)?;
173 #[cfg(feature = "non_bitcoin_chain_hash_routing")]
175 fn get_key(short_channel_id: u64, chain_hash: Sha256dHash) -> (u64, Sha256dHash) {
176 (short_channel_id, chain_hash)
179 #[cfg(not(feature = "non_bitcoin_chain_hash_routing"))]
181 fn get_key(short_channel_id: u64, _: Sha256dHash) -> u64 {
185 #[cfg(feature = "non_bitcoin_chain_hash_routing")]
187 fn get_short_id(id: &(u64, Sha256dHash)) -> &u64 {
191 #[cfg(not(feature = "non_bitcoin_chain_hash_routing"))]
193 fn get_short_id(id: &u64) -> &u64 {
198 /// A channel descriptor which provides a last-hop route to get_route
199 pub struct RouteHint {
200 /// The node_id of the non-target end of the route
201 pub src_node_id: PublicKey,
202 /// The short_channel_id of this channel
203 pub short_channel_id: u64,
204 /// The static msat-denominated fee which must be paid to use this channel
205 pub fee_base_msat: u32,
206 /// The dynamic proportional fee which must be paid to use this channel, denominated in
207 /// millionths of the value being forwarded to the next hop.
208 pub fee_proportional_millionths: u32,
209 /// The difference in CLTV values between this node and the next node.
210 pub cltv_expiry_delta: u16,
211 /// The minimum value, in msat, which must be relayed to the next hop.
212 pub htlc_minimum_msat: u64,
215 /// Tracks a view of the network, receiving updates from peers and generating Routes to
216 /// payment destinations.
218 secp_ctx: Secp256k1<secp256k1::VerifyOnly>,
219 network_map: RwLock<NetworkMap>,
220 chain_monitor: Arc<ChainWatchInterface>,
224 macro_rules! secp_verify_sig {
225 ( $secp_ctx: expr, $msg: expr, $sig: expr, $pubkey: expr ) => {
226 match $secp_ctx.verify($msg, $sig, $pubkey) {
228 Err(_) => return Err(HandleError{err: "Invalid signature from remote node", action: None}),
233 impl RoutingMessageHandler for Router {
234 fn handle_node_announcement(&self, msg: &msgs::NodeAnnouncement) -> Result<bool, HandleError> {
235 let msg_hash = Message::from_slice(&Sha256dHash::from_data(&msg.contents.encode()[..])[..]).unwrap();
236 secp_verify_sig!(self.secp_ctx, &msg_hash, &msg.signature, &msg.contents.node_id);
238 if msg.contents.features.requires_unknown_bits() {
239 panic!("Unknown-required-features NodeAnnouncements should never deserialize!");
242 let mut network = self.network_map.write().unwrap();
243 match network.nodes.get_mut(&msg.contents.node_id) {
244 None => Err(HandleError{err: "No existing channels for node_announcement", action: Some(ErrorAction::IgnoreError)}),
246 if node.last_update >= msg.contents.timestamp {
247 return Err(HandleError{err: "Update older than last processed update", action: Some(ErrorAction::IgnoreError)});
250 node.features = msg.contents.features.clone();
251 node.last_update = msg.contents.timestamp;
252 node.rgb = msg.contents.rgb;
253 node.alias = msg.contents.alias;
254 node.addresses = msg.contents.addresses.clone();
255 Ok(msg.contents.excess_data.is_empty() && msg.contents.excess_address_data.is_empty() && !msg.contents.features.supports_unknown_bits())
260 fn handle_channel_announcement(&self, msg: &msgs::ChannelAnnouncement) -> Result<bool, HandleError> {
261 if msg.contents.node_id_1 == msg.contents.node_id_2 || msg.contents.bitcoin_key_1 == msg.contents.bitcoin_key_2 {
262 return Err(HandleError{err: "Channel announcement node had a channel with itself", action: Some(ErrorAction::IgnoreError)});
265 let msg_hash = Message::from_slice(&Sha256dHash::from_data(&msg.contents.encode()[..])[..]).unwrap();
266 secp_verify_sig!(self.secp_ctx, &msg_hash, &msg.node_signature_1, &msg.contents.node_id_1);
267 secp_verify_sig!(self.secp_ctx, &msg_hash, &msg.node_signature_2, &msg.contents.node_id_2);
268 secp_verify_sig!(self.secp_ctx, &msg_hash, &msg.bitcoin_signature_1, &msg.contents.bitcoin_key_1);
269 secp_verify_sig!(self.secp_ctx, &msg_hash, &msg.bitcoin_signature_2, &msg.contents.bitcoin_key_2);
271 if msg.contents.features.requires_unknown_bits() {
272 panic!("Unknown-required-features ChannelAnnouncements should never deserialize!");
275 let checked_utxo = match self.chain_monitor.get_chain_utxo(msg.contents.chain_hash, msg.contents.short_channel_id) {
276 Ok((script_pubkey, _value)) => {
277 let expected_script = Builder::new().push_opcode(opcodes::All::OP_PUSHNUM_2)
278 .push_slice(&msg.contents.bitcoin_key_1.serialize())
279 .push_slice(&msg.contents.bitcoin_key_2.serialize())
280 .push_opcode(opcodes::All::OP_PUSHNUM_2).push_opcode(opcodes::All::OP_CHECKMULTISIG).into_script().to_v0_p2wsh();
281 if script_pubkey != expected_script {
282 return Err(HandleError{err: "Channel announcement keys didn't match on-chain script", action: Some(ErrorAction::IgnoreError)});
284 //TODO: Check if value is worth storing, use it to inform routing, and compare it
285 //to the new HTLC max field in channel_update
288 Err(ChainError::NotSupported) => {
289 // Tentatively accept, potentially exposing us to DoS attacks
292 Err(ChainError::NotWatched) => {
293 return Err(HandleError{err: "Channel announced on an unknown chain", action: Some(ErrorAction::IgnoreError)});
295 Err(ChainError::UnknownTx) => {
296 return Err(HandleError{err: "Channel announced without corresponding UTXO entry", action: Some(ErrorAction::IgnoreError)});
300 let mut network_lock = self.network_map.write().unwrap();
301 let network = network_lock.borrow_parts();
303 let chan_info = ChannelInfo {
304 features: msg.contents.features.clone(),
305 one_to_two: DirectionalChannelInfo {
306 src_node_id: msg.contents.node_id_1.clone(),
309 cltv_expiry_delta: u16::max_value(),
310 htlc_minimum_msat: u64::max_value(),
311 fee_base_msat: u32::max_value(),
312 fee_proportional_millionths: u32::max_value(),
314 two_to_one: DirectionalChannelInfo {
315 src_node_id: msg.contents.node_id_2.clone(),
318 cltv_expiry_delta: u16::max_value(),
319 htlc_minimum_msat: u64::max_value(),
320 fee_base_msat: u32::max_value(),
321 fee_proportional_millionths: u32::max_value(),
325 match network.channels.entry(NetworkMap::get_key(msg.contents.short_channel_id, msg.contents.chain_hash)) {
326 Entry::Occupied(mut entry) => {
327 //TODO: because asking the blockchain if short_channel_id is valid is only optional
328 //in the blockchain API, we need to handle it smartly here, though its unclear
331 // Either our UTXO provider is busted, there was a reorg, or the UTXO provider
332 // only sometimes returns results. In any case remove the previous entry. Note
333 // that the spec expects us to "blacklist" the node_ids involved, but we can't
335 // a) we don't *require* a UTXO provider that always returns results.
336 // b) we don't track UTXOs of channels we know about and remove them if they
338 // c) it's unclear how to do so without exposing ourselves to massive DoS risk.
339 Self::remove_channel_in_nodes(network.nodes, &entry.get(), msg.contents.short_channel_id);
340 *entry.get_mut() = chan_info;
342 return Err(HandleError{err: "Already have knowledge of channel", action: Some(ErrorAction::IgnoreError)})
345 Entry::Vacant(entry) => {
346 entry.insert(chan_info);
350 macro_rules! add_channel_to_node {
351 ( $node_id: expr ) => {
352 match network.nodes.entry($node_id) {
353 Entry::Occupied(node_entry) => {
354 node_entry.into_mut().channels.push(NetworkMap::get_key(msg.contents.short_channel_id, msg.contents.chain_hash));
356 Entry::Vacant(node_entry) => {
357 node_entry.insert(NodeInfo {
358 channels: vec!(NetworkMap::get_key(msg.contents.short_channel_id, msg.contents.chain_hash)),
359 lowest_inbound_channel_fee_base_msat: u32::max_value(),
360 lowest_inbound_channel_fee_proportional_millionths: u32::max_value(),
361 features: GlobalFeatures::new(),
365 addresses: Vec::new(),
372 add_channel_to_node!(msg.contents.node_id_1);
373 add_channel_to_node!(msg.contents.node_id_2);
375 Ok(msg.contents.excess_data.is_empty() && !msg.contents.features.supports_unknown_bits())
378 fn handle_htlc_fail_channel_update(&self, update: &msgs::HTLCFailChannelUpdate) {
380 &msgs::HTLCFailChannelUpdate::ChannelUpdateMessage { ref msg } => {
381 let _ = self.handle_channel_update(msg);
383 &msgs::HTLCFailChannelUpdate::ChannelClosed { ref short_channel_id, ref is_permanent } => {
384 let mut network = self.network_map.write().unwrap();
386 if let Some(chan) = network.channels.remove(short_channel_id) {
387 Self::remove_channel_in_nodes(&mut network.nodes, &chan, *short_channel_id);
390 if let Some(chan) = network.channels.get_mut(short_channel_id) {
391 chan.one_to_two.enabled = false;
392 chan.two_to_one.enabled = false;
396 &msgs::HTLCFailChannelUpdate::NodeFailure { ref node_id, ref is_permanent } => {
398 //TODO: Wholly remove the node
400 self.mark_node_bad(node_id, false);
406 fn handle_channel_update(&self, msg: &msgs::ChannelUpdate) -> Result<bool, HandleError> {
407 let mut network = self.network_map.write().unwrap();
409 let chan_enabled = msg.contents.flags & (1 << 1) != (1 << 1);
410 let chan_was_enabled;
412 match network.channels.get_mut(&NetworkMap::get_key(msg.contents.short_channel_id, msg.contents.chain_hash)) {
413 None => return Err(HandleError{err: "Couldn't find channel for update", action: Some(ErrorAction::IgnoreError)}),
415 macro_rules! maybe_update_channel_info {
416 ( $target: expr) => {
417 if $target.last_update >= msg.contents.timestamp {
418 return Err(HandleError{err: "Update older than last processed update", action: Some(ErrorAction::IgnoreError)});
420 chan_was_enabled = $target.enabled;
421 $target.last_update = msg.contents.timestamp;
422 $target.enabled = chan_enabled;
423 $target.cltv_expiry_delta = msg.contents.cltv_expiry_delta;
424 $target.htlc_minimum_msat = msg.contents.htlc_minimum_msat;
425 $target.fee_base_msat = msg.contents.fee_base_msat;
426 $target.fee_proportional_millionths = msg.contents.fee_proportional_millionths;
430 let msg_hash = Message::from_slice(&Sha256dHash::from_data(&msg.contents.encode()[..])[..]).unwrap();
431 if msg.contents.flags & 1 == 1 {
432 dest_node_id = channel.one_to_two.src_node_id.clone();
433 secp_verify_sig!(self.secp_ctx, &msg_hash, &msg.signature, &channel.two_to_one.src_node_id);
434 maybe_update_channel_info!(channel.two_to_one);
436 dest_node_id = channel.two_to_one.src_node_id.clone();
437 secp_verify_sig!(self.secp_ctx, &msg_hash, &msg.signature, &channel.one_to_two.src_node_id);
438 maybe_update_channel_info!(channel.one_to_two);
444 let node = network.nodes.get_mut(&dest_node_id).unwrap();
445 node.lowest_inbound_channel_fee_base_msat = cmp::min(node.lowest_inbound_channel_fee_base_msat, msg.contents.fee_base_msat);
446 node.lowest_inbound_channel_fee_proportional_millionths = cmp::min(node.lowest_inbound_channel_fee_proportional_millionths, msg.contents.fee_proportional_millionths);
447 } else if chan_was_enabled {
448 let mut lowest_inbound_channel_fee_base_msat = u32::max_value();
449 let mut lowest_inbound_channel_fee_proportional_millionths = u32::max_value();
452 let node = network.nodes.get(&dest_node_id).unwrap();
454 for chan_id in node.channels.iter() {
455 let chan = network.channels.get(chan_id).unwrap();
456 if chan.one_to_two.src_node_id == dest_node_id {
457 lowest_inbound_channel_fee_base_msat = cmp::min(lowest_inbound_channel_fee_base_msat, chan.two_to_one.fee_base_msat);
458 lowest_inbound_channel_fee_proportional_millionths = cmp::min(lowest_inbound_channel_fee_proportional_millionths, chan.two_to_one.fee_proportional_millionths);
460 lowest_inbound_channel_fee_base_msat = cmp::min(lowest_inbound_channel_fee_base_msat, chan.one_to_two.fee_base_msat);
461 lowest_inbound_channel_fee_proportional_millionths = cmp::min(lowest_inbound_channel_fee_proportional_millionths, chan.one_to_two.fee_proportional_millionths);
466 //TODO: satisfy the borrow-checker without a double-map-lookup :(
467 let mut_node = network.nodes.get_mut(&dest_node_id).unwrap();
468 mut_node.lowest_inbound_channel_fee_base_msat = lowest_inbound_channel_fee_base_msat;
469 mut_node.lowest_inbound_channel_fee_proportional_millionths = lowest_inbound_channel_fee_proportional_millionths;
472 Ok(msg.contents.excess_data.is_empty())
476 #[derive(Eq, PartialEq)]
477 struct RouteGraphNode {
479 lowest_fee_to_peer_through_node: u64,
480 lowest_fee_to_node: u64,
483 impl cmp::Ord for RouteGraphNode {
484 fn cmp(&self, other: &RouteGraphNode) -> cmp::Ordering {
485 other.lowest_fee_to_peer_through_node.cmp(&self.lowest_fee_to_peer_through_node)
486 .then_with(|| other.pubkey.serialize().cmp(&self.pubkey.serialize()))
490 impl cmp::PartialOrd for RouteGraphNode {
491 fn partial_cmp(&self, other: &RouteGraphNode) -> Option<cmp::Ordering> {
492 Some(self.cmp(other))
496 struct DummyDirectionalChannelInfo {
497 src_node_id: PublicKey,
498 cltv_expiry_delta: u32,
499 htlc_minimum_msat: u64,
501 fee_proportional_millionths: u32,
505 /// Creates a new router with the given node_id to be used as the source for get_route()
506 pub fn new(our_pubkey: PublicKey, chain_monitor: Arc<ChainWatchInterface>, logger: Arc<Logger>) -> Router {
507 let mut nodes = HashMap::new();
508 nodes.insert(our_pubkey.clone(), NodeInfo {
509 channels: Vec::new(),
510 lowest_inbound_channel_fee_base_msat: u32::max_value(),
511 lowest_inbound_channel_fee_proportional_millionths: u32::max_value(),
512 features: GlobalFeatures::new(),
516 addresses: Vec::new(),
519 secp_ctx: Secp256k1::verification_only(),
520 network_map: RwLock::new(NetworkMap {
521 channels: HashMap::new(),
522 our_node_id: our_pubkey,
530 /// Dumps the entire network view of this Router to the logger provided in the constructor at
532 pub fn trace_state(&self) {
533 log_trace!(self, "{}", self.network_map.read().unwrap());
536 /// Get network addresses by node id
537 pub fn get_addresses(&self, pubkey: &PublicKey) -> Option<Vec<NetAddress>> {
538 let network = self.network_map.read().unwrap();
539 network.nodes.get(pubkey).map(|n| n.addresses.clone())
542 /// Marks a node as having failed a route. This will avoid re-using the node in routes for now,
543 /// with an expotnential decay in node "badness". Note that there is deliberately no
544 /// mark_channel_bad as a node may simply lie and suggest that an upstream channel from it is
545 /// what failed the route and not the node itself. Instead, setting the blamed_upstream_node
546 /// boolean will reduce the penalty, returning the node to usability faster. If the node is
547 /// behaving correctly, it will disable the failing channel and we will use it again next time.
548 pub fn mark_node_bad(&self, _node_id: &PublicKey, _blamed_upstream_node: bool) {
552 fn remove_channel_in_nodes(nodes: &mut HashMap<PublicKey, NodeInfo>, chan: &ChannelInfo, short_channel_id: u64) {
553 macro_rules! remove_from_node {
554 ($node_id: expr) => {
555 if let Entry::Occupied(mut entry) = nodes.entry($node_id) {
556 entry.get_mut().channels.retain(|chan_id| {
557 short_channel_id != *NetworkMap::get_short_id(chan_id)
559 if entry.get().channels.is_empty() {
560 entry.remove_entry();
563 panic!("Had channel that pointed to unknown node (ie inconsistent network map)!");
567 remove_from_node!(chan.one_to_two.src_node_id);
568 remove_from_node!(chan.two_to_one.src_node_id);
571 /// Gets a route from us to the given target node.
573 /// Extra routing hops between known nodes and the target will be used if they are included in
576 /// If some channels aren't announced, it may be useful to fill in a first_hops with the
577 /// results from a local ChannelManager::list_usable_channels() call. If it is filled in, our
578 /// (this Router's) view of our local channels will be ignored, and only those in first_hops
581 /// Panics if first_hops contains channels without short_channel_ids
582 /// (ChannelManager::list_usable_channels will never include such channels).
584 /// The fees on channels from us to next-hops are ignored (as they are assumed to all be
585 /// equal), however the enabled/disabled bit on such channels as well as the htlc_minimum_msat
586 /// *is* checked as they may change based on the receiving node.
587 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> {
588 // TODO: Obviously *only* using total fee cost sucks. We should consider weighting by
589 // uptime/success in using a node in the past.
590 let network = self.network_map.read().unwrap();
592 if *target == network.our_node_id {
593 return Err(HandleError{err: "Cannot generate a route to ourselves", action: None});
596 if final_value_msat > 21_000_000 * 1_0000_0000 * 1000 {
597 return Err(HandleError{err: "Cannot generate a route of more value than all existing satoshis", action: None});
600 // We do a dest-to-source Dijkstra's sorting by each node's distance from the destination
601 // plus the minimum per-HTLC fee to get from it to another node (aka "shitty A*").
602 // TODO: There are a few tweaks we could do, including possibly pre-calculating more stuff
603 // to use as the A* heuristic beyond just the cost to get one node further than the current
606 let dummy_directional_info = DummyDirectionalChannelInfo { // used for first_hops routes
607 src_node_id: network.our_node_id.clone(),
608 cltv_expiry_delta: 0,
609 htlc_minimum_msat: 0,
611 fee_proportional_millionths: 0,
614 let mut targets = BinaryHeap::new(); //TODO: Do we care about switching to eg Fibbonaci heap?
615 let mut dist = HashMap::with_capacity(network.nodes.len());
617 let mut first_hop_targets = HashMap::with_capacity(if first_hops.is_some() { first_hops.as_ref().unwrap().len() } else { 0 });
618 if let Some(hops) = first_hops {
620 let short_channel_id = chan.short_channel_id.expect("first_hops should be filled in with usable channels, not pending ones");
621 if chan.remote_network_id == *target {
623 hops: vec![RouteHop {
624 pubkey: chan.remote_network_id,
626 fee_msat: final_value_msat,
627 cltv_expiry_delta: final_cltv,
631 first_hop_targets.insert(chan.remote_network_id, short_channel_id);
633 if first_hop_targets.is_empty() {
634 return Err(HandleError{err: "Cannot route when there are no outbound routes away from us", action: None});
638 macro_rules! add_entry {
639 // Adds entry which goes from the node pointed to by $directional_info to
640 // $dest_node_id over the channel with id $chan_id with fees described in
641 // $directional_info.
642 ( $chan_id: expr, $dest_node_id: expr, $directional_info: expr, $starting_fee_msat: expr ) => {
643 //TODO: Explore simply adding fee to hit htlc_minimum_msat
644 if $starting_fee_msat as u64 + final_value_msat > $directional_info.htlc_minimum_msat {
645 let proportional_fee_millions = ($starting_fee_msat + final_value_msat).checked_mul($directional_info.fee_proportional_millionths as u64);
646 if let Some(new_fee) = proportional_fee_millions.and_then(|part| {
647 ($directional_info.fee_base_msat as u64).checked_add(part / 1000000) })
649 let mut total_fee = $starting_fee_msat as u64;
650 let hm_entry = dist.entry(&$directional_info.src_node_id);
651 let old_entry = hm_entry.or_insert_with(|| {
652 let node = network.nodes.get(&$directional_info.src_node_id).unwrap();
654 node.lowest_inbound_channel_fee_base_msat,
655 node.lowest_inbound_channel_fee_proportional_millionths,
657 pubkey: $dest_node_id.clone(),
660 cltv_expiry_delta: 0,
663 if $directional_info.src_node_id != network.our_node_id {
664 // Ignore new_fee for channel-from-us as we assume all channels-from-us
665 // will have the same effective-fee
666 total_fee += new_fee;
667 if let Some(fee_inc) = final_value_msat.checked_add(total_fee).and_then(|inc| { (old_entry.2 as u64).checked_mul(inc) }) {
668 total_fee += fee_inc / 1000000 + (old_entry.1 as u64);
670 // max_value means we'll always fail the old_entry.0 > total_fee check
671 total_fee = u64::max_value();
674 let new_graph_node = RouteGraphNode {
675 pubkey: $directional_info.src_node_id,
676 lowest_fee_to_peer_through_node: total_fee,
677 lowest_fee_to_node: $starting_fee_msat as u64 + new_fee,
679 if old_entry.0 > total_fee {
680 targets.push(new_graph_node);
681 old_entry.0 = total_fee;
682 old_entry.3 = RouteHop {
683 pubkey: $dest_node_id.clone(),
684 short_channel_id: $chan_id.clone(),
685 fee_msat: new_fee, // This field is ignored on the last-hop anyway
686 cltv_expiry_delta: $directional_info.cltv_expiry_delta as u32,
694 macro_rules! add_entries_to_cheapest_to_target_node {
695 ( $node: expr, $node_id: expr, $fee_to_target_msat: expr ) => {
696 if first_hops.is_some() {
697 if let Some(first_hop) = first_hop_targets.get(&$node_id) {
698 add_entry!(first_hop, $node_id, dummy_directional_info, $fee_to_target_msat);
702 for chan_id in $node.channels.iter() {
703 let chan = network.channels.get(chan_id).unwrap();
704 if chan.one_to_two.src_node_id == *$node_id {
705 // ie $node is one, ie next hop in A* is two, via the two_to_one channel
706 if first_hops.is_none() || chan.two_to_one.src_node_id != network.our_node_id {
707 if chan.two_to_one.enabled {
708 add_entry!(chan_id, chan.one_to_two.src_node_id, chan.two_to_one, $fee_to_target_msat);
712 if first_hops.is_none() || chan.one_to_two.src_node_id != network.our_node_id {
713 if chan.one_to_two.enabled {
714 add_entry!(chan_id, chan.two_to_one.src_node_id, chan.one_to_two, $fee_to_target_msat);
722 match network.nodes.get(target) {
725 add_entries_to_cheapest_to_target_node!(node, target, 0);
729 for hop in last_hops.iter() {
730 if first_hops.is_none() || hop.src_node_id != network.our_node_id { // first_hop overrules last_hops
731 if network.nodes.get(&hop.src_node_id).is_some() {
732 if first_hops.is_some() {
733 if let Some(first_hop) = first_hop_targets.get(&hop.src_node_id) {
734 add_entry!(first_hop, hop.src_node_id, dummy_directional_info, 0);
737 add_entry!(hop.short_channel_id, target, hop, 0);
742 while let Some(RouteGraphNode { pubkey, lowest_fee_to_node, .. }) = targets.pop() {
743 if pubkey == network.our_node_id {
744 let mut res = vec!(dist.remove(&network.our_node_id).unwrap().3);
745 while res.last().unwrap().pubkey != *target {
746 let new_entry = match dist.remove(&res.last().unwrap().pubkey) {
748 None => return Err(HandleError{err: "Failed to find a non-fee-overflowing path to the given destination", action: None}),
750 res.last_mut().unwrap().fee_msat = new_entry.fee_msat;
751 res.last_mut().unwrap().cltv_expiry_delta = new_entry.cltv_expiry_delta;
754 res.last_mut().unwrap().fee_msat = final_value_msat;
755 res.last_mut().unwrap().cltv_expiry_delta = final_cltv;
756 let route = Route { hops: res };
757 log_trace!(self, "Got route: {}", log_route!(route));
761 match network.nodes.get(&pubkey) {
764 add_entries_to_cheapest_to_target_node!(node, &pubkey, lowest_fee_to_node);
769 Err(HandleError{err: "Failed to find a path to the given destination", action: None})
775 use chain::chaininterface;
776 use ln::channelmanager;
777 use ln::router::{Router,NodeInfo,NetworkMap,ChannelInfo,DirectionalChannelInfo,RouteHint};
778 use ln::msgs::GlobalFeatures;
779 use util::test_utils;
780 use util::logger::Logger;
782 use bitcoin::util::hash::Sha256dHash;
783 use bitcoin::network::constants::Network;
787 use secp256k1::key::{PublicKey,SecretKey};
788 use secp256k1::Secp256k1;
794 let secp_ctx = Secp256k1::new();
795 let our_id = PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&secp_ctx, &hex::decode("0101010101010101010101010101010101010101010101010101010101010101").unwrap()[..]).unwrap());
796 let logger: Arc<Logger> = Arc::new(test_utils::TestLogger::new());
797 let chain_monitor = Arc::new(chaininterface::ChainWatchInterfaceUtil::new(Network::Testnet, Arc::clone(&logger)));
798 let router = Router::new(our_id, chain_monitor, Arc::clone(&logger));
800 // Build network from our_id to node8:
802 // -1(1)2- node1 -1(3)2-
804 // our_id -1(12)2- node8 -1(13)2--- node3
806 // -1(2)2- node2 -1(4)2-
809 // chan1 1-to-2: disabled
810 // chan1 2-to-1: enabled, 0 fee
812 // chan2 1-to-2: enabled, ignored fee
813 // chan2 2-to-1: enabled, 0 fee
815 // chan3 1-to-2: enabled, 0 fee
816 // chan3 2-to-1: enabled, 100 msat fee
818 // chan4 1-to-2: enabled, 100% fee
819 // chan4 2-to-1: enabled, 0 fee
821 // chan12 1-to-2: enabled, ignored fee
822 // chan12 2-to-1: enabled, 0 fee
824 // chan13 1-to-2: enabled, 200% fee
825 // chan13 2-to-1: enabled, 0 fee
828 // -1(5)2- node4 -1(8)2--
832 // node3--1(6)2- node5 -1(9)2--- node7 (not in global route map)
834 // -1(7)2- node6 -1(10)2-
836 // chan5 1-to-2: enabled, 100 msat fee
837 // chan5 2-to-1: enabled, 0 fee
839 // chan6 1-to-2: enabled, 0 fee
840 // chan6 2-to-1: enabled, 0 fee
842 // chan7 1-to-2: enabled, 100% fee
843 // chan7 2-to-1: enabled, 0 fee
845 // chan8 1-to-2: enabled, variable fee (0 then 1000 msat)
846 // chan8 2-to-1: enabled, 0 fee
848 // chan9 1-to-2: enabled, 1001 msat fee
849 // chan9 2-to-1: enabled, 0 fee
851 // chan10 1-to-2: enabled, 0 fee
852 // chan10 2-to-1: enabled, 0 fee
854 // chan11 1-to-2: enabled, 0 fee
855 // chan11 2-to-1: enabled, 0 fee
857 let node1 = PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&secp_ctx, &hex::decode("0202020202020202020202020202020202020202020202020202020202020202").unwrap()[..]).unwrap());
858 let node2 = PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&secp_ctx, &hex::decode("0303030303030303030303030303030303030303030303030303030303030303").unwrap()[..]).unwrap());
859 let node3 = PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&secp_ctx, &hex::decode("0404040404040404040404040404040404040404040404040404040404040404").unwrap()[..]).unwrap());
860 let node4 = PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&secp_ctx, &hex::decode("0505050505050505050505050505050505050505050505050505050505050505").unwrap()[..]).unwrap());
861 let node5 = PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&secp_ctx, &hex::decode("0606060606060606060606060606060606060606060606060606060606060606").unwrap()[..]).unwrap());
862 let node6 = PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&secp_ctx, &hex::decode("0707070707070707070707070707070707070707070707070707070707070707").unwrap()[..]).unwrap());
863 let node7 = PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&secp_ctx, &hex::decode("0808080808080808080808080808080808080808080808080808080808080808").unwrap()[..]).unwrap());
864 let node8 = PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&secp_ctx, &hex::decode("0909090909090909090909090909090909090909090909090909090909090909").unwrap()[..]).unwrap());
866 let zero_hash = Sha256dHash::from_data(&[0; 32]);
869 let mut network = router.network_map.write().unwrap();
871 network.nodes.insert(node1.clone(), NodeInfo {
872 channels: vec!(NetworkMap::get_key(1, zero_hash.clone()), NetworkMap::get_key(3, zero_hash.clone())),
873 lowest_inbound_channel_fee_base_msat: 100,
874 lowest_inbound_channel_fee_proportional_millionths: 0,
875 features: GlobalFeatures::new(),
879 addresses: Vec::new(),
881 network.channels.insert(NetworkMap::get_key(1, 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: node1.clone(),
895 cltv_expiry_delta: 0,
896 htlc_minimum_msat: 0,
898 fee_proportional_millionths: 0,
901 network.nodes.insert(node2.clone(), NodeInfo {
902 channels: vec!(NetworkMap::get_key(2, zero_hash.clone()), NetworkMap::get_key(4, 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(2, 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: node2.clone(),
925 cltv_expiry_delta: 0,
926 htlc_minimum_msat: 0,
928 fee_proportional_millionths: 0,
931 network.nodes.insert(node8.clone(), NodeInfo {
932 channels: vec!(NetworkMap::get_key(12, zero_hash.clone()), NetworkMap::get_key(13, zero_hash.clone())),
933 lowest_inbound_channel_fee_base_msat: 0,
934 lowest_inbound_channel_fee_proportional_millionths: 0,
935 features: GlobalFeatures::new(),
939 addresses: Vec::new(),
941 network.channels.insert(NetworkMap::get_key(12, zero_hash.clone()), ChannelInfo {
942 features: GlobalFeatures::new(),
943 one_to_two: DirectionalChannelInfo {
944 src_node_id: our_id.clone(),
947 cltv_expiry_delta: u16::max_value(), // This value should be ignored
948 htlc_minimum_msat: 0,
949 fee_base_msat: u32::max_value(), // This value should be ignored
950 fee_proportional_millionths: u32::max_value(), // This value should be ignored
951 }, two_to_one: DirectionalChannelInfo {
952 src_node_id: node8.clone(),
955 cltv_expiry_delta: 0,
956 htlc_minimum_msat: 0,
958 fee_proportional_millionths: 0,
961 network.nodes.insert(node3.clone(), NodeInfo {
963 NetworkMap::get_key(3, zero_hash.clone()),
964 NetworkMap::get_key(4, zero_hash.clone()),
965 NetworkMap::get_key(13, zero_hash.clone()),
966 NetworkMap::get_key(5, zero_hash.clone()),
967 NetworkMap::get_key(6, zero_hash.clone()),
968 NetworkMap::get_key(7, zero_hash.clone())),
969 lowest_inbound_channel_fee_base_msat: 0,
970 lowest_inbound_channel_fee_proportional_millionths: 0,
971 features: GlobalFeatures::new(),
975 addresses: Vec::new(),
977 network.channels.insert(NetworkMap::get_key(3, zero_hash.clone()), ChannelInfo {
978 features: GlobalFeatures::new(),
979 one_to_two: DirectionalChannelInfo {
980 src_node_id: node1.clone(),
983 cltv_expiry_delta: (3 << 8) | 1,
984 htlc_minimum_msat: 0,
986 fee_proportional_millionths: 0,
987 }, two_to_one: DirectionalChannelInfo {
988 src_node_id: node3.clone(),
991 cltv_expiry_delta: (3 << 8) | 2,
992 htlc_minimum_msat: 0,
994 fee_proportional_millionths: 0,
997 network.channels.insert(NetworkMap::get_key(4, zero_hash.clone()), ChannelInfo {
998 features: GlobalFeatures::new(),
999 one_to_two: DirectionalChannelInfo {
1000 src_node_id: node2.clone(),
1003 cltv_expiry_delta: (4 << 8) | 1,
1004 htlc_minimum_msat: 0,
1006 fee_proportional_millionths: 1000000,
1007 }, two_to_one: DirectionalChannelInfo {
1008 src_node_id: node3.clone(),
1011 cltv_expiry_delta: (4 << 8) | 2,
1012 htlc_minimum_msat: 0,
1014 fee_proportional_millionths: 0,
1017 network.channels.insert(NetworkMap::get_key(13, zero_hash.clone()), ChannelInfo {
1018 features: GlobalFeatures::new(),
1019 one_to_two: DirectionalChannelInfo {
1020 src_node_id: node8.clone(),
1023 cltv_expiry_delta: (13 << 8) | 1,
1024 htlc_minimum_msat: 0,
1026 fee_proportional_millionths: 2000000,
1027 }, two_to_one: DirectionalChannelInfo {
1028 src_node_id: node3.clone(),
1031 cltv_expiry_delta: (13 << 8) | 2,
1032 htlc_minimum_msat: 0,
1034 fee_proportional_millionths: 0,
1037 network.nodes.insert(node4.clone(), NodeInfo {
1038 channels: vec!(NetworkMap::get_key(5, 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(5, zero_hash.clone()), ChannelInfo {
1048 features: GlobalFeatures::new(),
1049 one_to_two: DirectionalChannelInfo {
1050 src_node_id: node3.clone(),
1053 cltv_expiry_delta: (5 << 8) | 1,
1054 htlc_minimum_msat: 0,
1056 fee_proportional_millionths: 0,
1057 }, two_to_one: DirectionalChannelInfo {
1058 src_node_id: node4.clone(),
1061 cltv_expiry_delta: (5 << 8) | 2,
1062 htlc_minimum_msat: 0,
1064 fee_proportional_millionths: 0,
1067 network.nodes.insert(node5.clone(), NodeInfo {
1068 channels: vec!(NetworkMap::get_key(6, zero_hash.clone()), NetworkMap::get_key(11, zero_hash.clone())),
1069 lowest_inbound_channel_fee_base_msat: 0,
1070 lowest_inbound_channel_fee_proportional_millionths: 0,
1071 features: GlobalFeatures::new(),
1075 addresses: Vec::new(),
1077 network.channels.insert(NetworkMap::get_key(6, zero_hash.clone()), ChannelInfo {
1078 features: GlobalFeatures::new(),
1079 one_to_two: DirectionalChannelInfo {
1080 src_node_id: node3.clone(),
1083 cltv_expiry_delta: (6 << 8) | 1,
1084 htlc_minimum_msat: 0,
1086 fee_proportional_millionths: 0,
1087 }, two_to_one: DirectionalChannelInfo {
1088 src_node_id: node5.clone(),
1091 cltv_expiry_delta: (6 << 8) | 2,
1092 htlc_minimum_msat: 0,
1094 fee_proportional_millionths: 0,
1097 network.channels.insert(NetworkMap::get_key(11, zero_hash.clone()), ChannelInfo {
1098 features: GlobalFeatures::new(),
1099 one_to_two: DirectionalChannelInfo {
1100 src_node_id: node5.clone(),
1103 cltv_expiry_delta: (11 << 8) | 1,
1104 htlc_minimum_msat: 0,
1106 fee_proportional_millionths: 0,
1107 }, two_to_one: DirectionalChannelInfo {
1108 src_node_id: node4.clone(),
1111 cltv_expiry_delta: (11 << 8) | 2,
1112 htlc_minimum_msat: 0,
1114 fee_proportional_millionths: 0,
1117 network.nodes.insert(node6.clone(), NodeInfo {
1118 channels: vec!(NetworkMap::get_key(7, zero_hash.clone())),
1119 lowest_inbound_channel_fee_base_msat: 0,
1120 lowest_inbound_channel_fee_proportional_millionths: 0,
1121 features: GlobalFeatures::new(),
1125 addresses: Vec::new(),
1127 network.channels.insert(NetworkMap::get_key(7, zero_hash.clone()), ChannelInfo {
1128 features: GlobalFeatures::new(),
1129 one_to_two: DirectionalChannelInfo {
1130 src_node_id: node3.clone(),
1133 cltv_expiry_delta: (7 << 8) | 1,
1134 htlc_minimum_msat: 0,
1136 fee_proportional_millionths: 1000000,
1137 }, two_to_one: DirectionalChannelInfo {
1138 src_node_id: node6.clone(),
1141 cltv_expiry_delta: (7 << 8) | 2,
1142 htlc_minimum_msat: 0,
1144 fee_proportional_millionths: 0,
1149 { // Simple route to 3 via 2
1150 let route = router.get_route(&node3, None, &Vec::new(), 100, 42).unwrap();
1151 assert_eq!(route.hops.len(), 2);
1153 assert_eq!(route.hops[0].pubkey, node2);
1154 assert_eq!(route.hops[0].short_channel_id, 2);
1155 assert_eq!(route.hops[0].fee_msat, 100);
1156 assert_eq!(route.hops[0].cltv_expiry_delta, (4 << 8) | 1);
1158 assert_eq!(route.hops[1].pubkey, node3);
1159 assert_eq!(route.hops[1].short_channel_id, 4);
1160 assert_eq!(route.hops[1].fee_msat, 100);
1161 assert_eq!(route.hops[1].cltv_expiry_delta, 42);
1164 { // Route to 1 via 2 and 3 because our channel to 1 is disabled
1165 let route = router.get_route(&node1, None, &Vec::new(), 100, 42).unwrap();
1166 assert_eq!(route.hops.len(), 3);
1168 assert_eq!(route.hops[0].pubkey, node2);
1169 assert_eq!(route.hops[0].short_channel_id, 2);
1170 assert_eq!(route.hops[0].fee_msat, 200);
1171 assert_eq!(route.hops[0].cltv_expiry_delta, (4 << 8) | 1);
1173 assert_eq!(route.hops[1].pubkey, node3);
1174 assert_eq!(route.hops[1].short_channel_id, 4);
1175 assert_eq!(route.hops[1].fee_msat, 100);
1176 assert_eq!(route.hops[1].cltv_expiry_delta, (3 << 8) | 2);
1178 assert_eq!(route.hops[2].pubkey, node1);
1179 assert_eq!(route.hops[2].short_channel_id, 3);
1180 assert_eq!(route.hops[2].fee_msat, 100);
1181 assert_eq!(route.hops[2].cltv_expiry_delta, 42);
1184 { // If we specify a channel to node8, that overrides our local channel view and that gets used
1185 let our_chans = vec![channelmanager::ChannelDetails {
1186 channel_id: [0; 32],
1187 short_channel_id: Some(42),
1188 remote_network_id: node8.clone(),
1189 channel_value_satoshis: 0,
1192 let route = router.get_route(&node3, Some(&our_chans), &Vec::new(), 100, 42).unwrap();
1193 assert_eq!(route.hops.len(), 2);
1195 assert_eq!(route.hops[0].pubkey, node8);
1196 assert_eq!(route.hops[0].short_channel_id, 42);
1197 assert_eq!(route.hops[0].fee_msat, 200);
1198 assert_eq!(route.hops[0].cltv_expiry_delta, (13 << 8) | 1);
1200 assert_eq!(route.hops[1].pubkey, node3);
1201 assert_eq!(route.hops[1].short_channel_id, 13);
1202 assert_eq!(route.hops[1].fee_msat, 100);
1203 assert_eq!(route.hops[1].cltv_expiry_delta, 42);
1206 let mut last_hops = vec!(RouteHint {
1207 src_node_id: node4.clone(),
1208 short_channel_id: 8,
1210 fee_proportional_millionths: 0,
1211 cltv_expiry_delta: (8 << 8) | 1,
1212 htlc_minimum_msat: 0,
1214 src_node_id: node5.clone(),
1215 short_channel_id: 9,
1216 fee_base_msat: 1001,
1217 fee_proportional_millionths: 0,
1218 cltv_expiry_delta: (9 << 8) | 1,
1219 htlc_minimum_msat: 0,
1221 src_node_id: node6.clone(),
1222 short_channel_id: 10,
1224 fee_proportional_millionths: 0,
1225 cltv_expiry_delta: (10 << 8) | 1,
1226 htlc_minimum_msat: 0,
1229 { // Simple test across 2, 3, 5, and 4 via a last_hop channel
1230 let route = router.get_route(&node7, None, &last_hops, 100, 42).unwrap();
1231 assert_eq!(route.hops.len(), 5);
1233 assert_eq!(route.hops[0].pubkey, node2);
1234 assert_eq!(route.hops[0].short_channel_id, 2);
1235 assert_eq!(route.hops[0].fee_msat, 100);
1236 assert_eq!(route.hops[0].cltv_expiry_delta, (4 << 8) | 1);
1238 assert_eq!(route.hops[1].pubkey, node3);
1239 assert_eq!(route.hops[1].short_channel_id, 4);
1240 assert_eq!(route.hops[1].fee_msat, 0);
1241 assert_eq!(route.hops[1].cltv_expiry_delta, (6 << 8) | 1);
1243 assert_eq!(route.hops[2].pubkey, node5);
1244 assert_eq!(route.hops[2].short_channel_id, 6);
1245 assert_eq!(route.hops[2].fee_msat, 0);
1246 assert_eq!(route.hops[2].cltv_expiry_delta, (11 << 8) | 1);
1248 assert_eq!(route.hops[3].pubkey, node4);
1249 assert_eq!(route.hops[3].short_channel_id, 11);
1250 assert_eq!(route.hops[3].fee_msat, 0);
1251 assert_eq!(route.hops[3].cltv_expiry_delta, (8 << 8) | 1);
1253 assert_eq!(route.hops[4].pubkey, node7);
1254 assert_eq!(route.hops[4].short_channel_id, 8);
1255 assert_eq!(route.hops[4].fee_msat, 100);
1256 assert_eq!(route.hops[4].cltv_expiry_delta, 42);
1259 { // Simple test with outbound channel to 4 to test that last_hops and first_hops connect
1260 let our_chans = vec![channelmanager::ChannelDetails {
1261 channel_id: [0; 32],
1262 short_channel_id: Some(42),
1263 remote_network_id: node4.clone(),
1264 channel_value_satoshis: 0,
1267 let route = router.get_route(&node7, Some(&our_chans), &last_hops, 100, 42).unwrap();
1268 assert_eq!(route.hops.len(), 2);
1270 assert_eq!(route.hops[0].pubkey, node4);
1271 assert_eq!(route.hops[0].short_channel_id, 42);
1272 assert_eq!(route.hops[0].fee_msat, 0);
1273 assert_eq!(route.hops[0].cltv_expiry_delta, (8 << 8) | 1);
1275 assert_eq!(route.hops[1].pubkey, node7);
1276 assert_eq!(route.hops[1].short_channel_id, 8);
1277 assert_eq!(route.hops[1].fee_msat, 100);
1278 assert_eq!(route.hops[1].cltv_expiry_delta, 42);
1281 last_hops[0].fee_base_msat = 1000;
1283 { // Revert to via 6 as the fee on 8 goes up
1284 let route = router.get_route(&node7, None, &last_hops, 100, 42).unwrap();
1285 assert_eq!(route.hops.len(), 4);
1287 assert_eq!(route.hops[0].pubkey, node2);
1288 assert_eq!(route.hops[0].short_channel_id, 2);
1289 assert_eq!(route.hops[0].fee_msat, 200); // fee increased as its % of value transferred across node
1290 assert_eq!(route.hops[0].cltv_expiry_delta, (4 << 8) | 1);
1292 assert_eq!(route.hops[1].pubkey, node3);
1293 assert_eq!(route.hops[1].short_channel_id, 4);
1294 assert_eq!(route.hops[1].fee_msat, 100);
1295 assert_eq!(route.hops[1].cltv_expiry_delta, (7 << 8) | 1);
1297 assert_eq!(route.hops[2].pubkey, node6);
1298 assert_eq!(route.hops[2].short_channel_id, 7);
1299 assert_eq!(route.hops[2].fee_msat, 0);
1300 assert_eq!(route.hops[2].cltv_expiry_delta, (10 << 8) | 1);
1302 assert_eq!(route.hops[3].pubkey, node7);
1303 assert_eq!(route.hops[3].short_channel_id, 10);
1304 assert_eq!(route.hops[3].fee_msat, 100);
1305 assert_eq!(route.hops[3].cltv_expiry_delta, 42);
1308 { // ...but still use 8 for larger payments as 6 has a variable feerate
1309 let route = router.get_route(&node7, None, &last_hops, 2000, 42).unwrap();
1310 assert_eq!(route.hops.len(), 5);
1312 assert_eq!(route.hops[0].pubkey, node2);
1313 assert_eq!(route.hops[0].short_channel_id, 2);
1314 assert_eq!(route.hops[0].fee_msat, 3000);
1315 assert_eq!(route.hops[0].cltv_expiry_delta, (4 << 8) | 1);
1317 assert_eq!(route.hops[1].pubkey, node3);
1318 assert_eq!(route.hops[1].short_channel_id, 4);
1319 assert_eq!(route.hops[1].fee_msat, 0);
1320 assert_eq!(route.hops[1].cltv_expiry_delta, (6 << 8) | 1);
1322 assert_eq!(route.hops[2].pubkey, node5);
1323 assert_eq!(route.hops[2].short_channel_id, 6);
1324 assert_eq!(route.hops[2].fee_msat, 0);
1325 assert_eq!(route.hops[2].cltv_expiry_delta, (11 << 8) | 1);
1327 assert_eq!(route.hops[3].pubkey, node4);
1328 assert_eq!(route.hops[3].short_channel_id, 11);
1329 assert_eq!(route.hops[3].fee_msat, 1000);
1330 assert_eq!(route.hops[3].cltv_expiry_delta, (8 << 8) | 1);
1332 assert_eq!(route.hops[4].pubkey, node7);
1333 assert_eq!(route.hops[4].short_channel_id, 8);
1334 assert_eq!(route.hops[4].fee_msat, 2000);
1335 assert_eq!(route.hops[4].cltv_expiry_delta, 42);