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,
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 struct DirectionalChannelInfo {
51 src_node_id: PublicKey,
54 cltv_expiry_delta: u16,
55 htlc_minimum_msat: u64,
57 fee_proportional_millionths: u32,
60 impl std::fmt::Display for DirectionalChannelInfo {
61 fn fmt(&self, f: &mut std::fmt::Formatter) -> Result<(), std::fmt::Error> {
62 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)?;
68 features: GlobalFeatures,
69 one_to_two: DirectionalChannelInfo,
70 two_to_one: DirectionalChannelInfo,
73 impl std::fmt::Display for ChannelInfo {
74 fn fmt(&self, f: &mut std::fmt::Formatter) -> Result<(), std::fmt::Error> {
75 write!(f, "features: {}, one_to_two: {}, two_to_one: {}", log_bytes!(self.features.encode()), self.one_to_two, self.two_to_one)?;
83 #[cfg(feature = "non_bitcoin_chain_hash_routing")]
84 channels: Vec<(u64, Sha256dHash)>,
85 #[cfg(not(feature = "non_bitcoin_chain_hash_routing"))]
88 lowest_inbound_channel_fee_base_msat: u32,
89 lowest_inbound_channel_fee_proportional_millionths: u32,
91 features: GlobalFeatures,
95 addresses: Vec<NetAddress>,
98 impl std::fmt::Display for NodeInfo {
99 fn fmt(&self, f: &mut std::fmt::Formatter) -> Result<(), std::fmt::Error> {
100 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[..])?;
106 #[cfg(feature = "non_bitcoin_chain_hash_routing")]
107 channels: HashMap<(u64, Sha256dHash), ChannelInfo>,
108 #[cfg(not(feature = "non_bitcoin_chain_hash_routing"))]
109 channels: HashMap<u64, ChannelInfo>,
111 our_node_id: PublicKey,
112 nodes: HashMap<PublicKey, NodeInfo>,
114 struct MutNetworkMap<'a> {
115 #[cfg(feature = "non_bitcoin_chain_hash_routing")]
116 channels: &'a mut HashMap<(u64, Sha256dHash), ChannelInfo>,
117 #[cfg(not(feature = "non_bitcoin_chain_hash_routing"))]
118 channels: &'a mut HashMap<u64, ChannelInfo>,
119 nodes: &'a mut HashMap<PublicKey, NodeInfo>,
122 fn borrow_parts(&mut self) -> MutNetworkMap {
124 channels: &mut self.channels,
125 nodes: &mut self.nodes,
129 impl std::fmt::Display for NetworkMap {
130 fn fmt(&self, f: &mut std::fmt::Formatter) -> Result<(), std::fmt::Error> {
131 write!(f, "Node id {} network map\n[Channels]\n", log_pubkey!(self.our_node_id))?;
132 for (key, val) in self.channels.iter() {
133 write!(f, " {}: {}\n", key, val)?;
135 write!(f, "[Nodes]\n")?;
136 for (key, val) in self.nodes.iter() {
137 write!(f, " {}: {}\n", log_pubkey!(key), val)?;
144 #[cfg(feature = "non_bitcoin_chain_hash_routing")]
146 fn get_key(short_channel_id: u64, chain_hash: Sha256dHash) -> (u64, Sha256dHash) {
147 (short_channel_id, chain_hash)
150 #[cfg(not(feature = "non_bitcoin_chain_hash_routing"))]
152 fn get_key(short_channel_id: u64, _: Sha256dHash) -> u64 {
156 #[cfg(feature = "non_bitcoin_chain_hash_routing")]
158 fn get_short_id(id: &(u64, Sha256dHash)) -> &u64 {
162 #[cfg(not(feature = "non_bitcoin_chain_hash_routing"))]
164 fn get_short_id(id: &u64) -> &u64 {
169 /// A channel descriptor which provides a last-hop route to get_route
170 pub struct RouteHint {
171 /// The node_id of the non-target end of the route
172 pub src_node_id: PublicKey,
173 /// The short_channel_id of this channel
174 pub short_channel_id: u64,
175 /// The static msat-denominated fee which must be paid to use this channel
176 pub fee_base_msat: u32,
177 /// The dynamic proportional fee which must be paid to use this channel, denominated in
178 /// millionths of the value being forwarded to the next hop.
179 pub fee_proportional_millionths: u32,
180 /// The difference in CLTV values between this node and the next node.
181 pub cltv_expiry_delta: u16,
182 /// The minimum value, in msat, which must be relayed to the next hop.
183 pub htlc_minimum_msat: u64,
186 /// Tracks a view of the network, receiving updates from peers and generating Routes to
187 /// payment destinations.
189 secp_ctx: Secp256k1<secp256k1::VerifyOnly>,
190 network_map: RwLock<NetworkMap>,
191 chain_monitor: Arc<ChainWatchInterface>,
195 macro_rules! secp_verify_sig {
196 ( $secp_ctx: expr, $msg: expr, $sig: expr, $pubkey: expr ) => {
197 match $secp_ctx.verify($msg, $sig, $pubkey) {
199 Err(_) => return Err(HandleError{err: "Invalid signature from remote node", action: None}),
204 impl RoutingMessageHandler for Router {
205 fn handle_node_announcement(&self, msg: &msgs::NodeAnnouncement) -> Result<bool, HandleError> {
206 let msg_hash = Message::from_slice(&Sha256dHash::from_data(&msg.contents.encode()[..])[..]).unwrap();
207 secp_verify_sig!(self.secp_ctx, &msg_hash, &msg.signature, &msg.contents.node_id);
209 if msg.contents.features.requires_unknown_bits() {
210 panic!("Unknown-required-features NodeAnnouncements should never deserialize!");
213 let mut network = self.network_map.write().unwrap();
214 match network.nodes.get_mut(&msg.contents.node_id) {
215 None => Err(HandleError{err: "No existing channels for node_announcement", action: Some(ErrorAction::IgnoreError)}),
217 if node.last_update >= msg.contents.timestamp {
218 return Err(HandleError{err: "Update older than last processed update", action: Some(ErrorAction::IgnoreError)});
221 node.features = msg.contents.features.clone();
222 node.last_update = msg.contents.timestamp;
223 node.rgb = msg.contents.rgb;
224 node.alias = msg.contents.alias;
225 node.addresses = msg.contents.addresses.clone();
226 Ok(msg.contents.excess_data.is_empty() && msg.contents.excess_address_data.is_empty() && !msg.contents.features.supports_unknown_bits())
231 fn handle_channel_announcement(&self, msg: &msgs::ChannelAnnouncement) -> Result<bool, HandleError> {
232 if msg.contents.node_id_1 == msg.contents.node_id_2 || msg.contents.bitcoin_key_1 == msg.contents.bitcoin_key_2 {
233 return Err(HandleError{err: "Channel announcement node had a channel with itself", action: Some(ErrorAction::IgnoreError)});
236 let msg_hash = Message::from_slice(&Sha256dHash::from_data(&msg.contents.encode()[..])[..]).unwrap();
237 secp_verify_sig!(self.secp_ctx, &msg_hash, &msg.node_signature_1, &msg.contents.node_id_1);
238 secp_verify_sig!(self.secp_ctx, &msg_hash, &msg.node_signature_2, &msg.contents.node_id_2);
239 secp_verify_sig!(self.secp_ctx, &msg_hash, &msg.bitcoin_signature_1, &msg.contents.bitcoin_key_1);
240 secp_verify_sig!(self.secp_ctx, &msg_hash, &msg.bitcoin_signature_2, &msg.contents.bitcoin_key_2);
242 if msg.contents.features.requires_unknown_bits() {
243 panic!("Unknown-required-features ChannelAnnouncements should never deserialize!");
246 let checked_utxo = match self.chain_monitor.get_chain_utxo(msg.contents.chain_hash, msg.contents.short_channel_id) {
247 Ok((script_pubkey, _value)) => {
248 let expected_script = Builder::new().push_opcode(opcodes::All::OP_PUSHNUM_2)
249 .push_slice(&msg.contents.bitcoin_key_1.serialize())
250 .push_slice(&msg.contents.bitcoin_key_2.serialize())
251 .push_opcode(opcodes::All::OP_PUSHNUM_2).push_opcode(opcodes::All::OP_CHECKMULTISIG).into_script().to_v0_p2wsh();
252 if script_pubkey != expected_script {
253 return Err(HandleError{err: "Channel announcement keys didn't match on-chain script", action: Some(ErrorAction::IgnoreError)});
255 //TODO: Check if value is worth storing, use it to inform routing, and compare it
256 //to the new HTLC max field in channel_update
259 Err(ChainError::NotSupported) => {
260 // Tentatively accept, potentially exposing us to DoS attacks
263 Err(ChainError::NotWatched) => {
264 return Err(HandleError{err: "Channel announced on an unknown chain", action: Some(ErrorAction::IgnoreError)});
266 Err(ChainError::UnknownTx) => {
267 return Err(HandleError{err: "Channel announced without corresponding UTXO entry", action: Some(ErrorAction::IgnoreError)});
271 let mut network_lock = self.network_map.write().unwrap();
272 let network = network_lock.borrow_parts();
274 let chan_info = ChannelInfo {
275 features: msg.contents.features.clone(),
276 one_to_two: DirectionalChannelInfo {
277 src_node_id: msg.contents.node_id_1.clone(),
280 cltv_expiry_delta: u16::max_value(),
281 htlc_minimum_msat: u64::max_value(),
282 fee_base_msat: u32::max_value(),
283 fee_proportional_millionths: u32::max_value(),
285 two_to_one: DirectionalChannelInfo {
286 src_node_id: msg.contents.node_id_2.clone(),
289 cltv_expiry_delta: u16::max_value(),
290 htlc_minimum_msat: u64::max_value(),
291 fee_base_msat: u32::max_value(),
292 fee_proportional_millionths: u32::max_value(),
296 match network.channels.entry(NetworkMap::get_key(msg.contents.short_channel_id, msg.contents.chain_hash)) {
297 Entry::Occupied(mut entry) => {
298 //TODO: because asking the blockchain if short_channel_id is valid is only optional
299 //in the blockchain API, we need to handle it smartly here, though its unclear
302 // Either our UTXO provider is busted, there was a reorg, or the UTXO provider
303 // only sometimes returns results. In any case remove the previous entry. Note
304 // that the spec expects us to "blacklist" the node_ids involved, but we can't
306 // a) we don't *require* a UTXO provider that always returns results.
307 // b) we don't track UTXOs of channels we know about and remove them if they
309 // c) it's unclear how to do so without exposing ourselves to massive DoS risk.
310 Self::remove_channel_in_nodes(network.nodes, &entry.get(), msg.contents.short_channel_id);
311 *entry.get_mut() = chan_info;
313 return Err(HandleError{err: "Already have knowledge of channel", action: Some(ErrorAction::IgnoreError)})
316 Entry::Vacant(entry) => {
317 entry.insert(chan_info);
321 macro_rules! add_channel_to_node {
322 ( $node_id: expr ) => {
323 match network.nodes.entry($node_id) {
324 Entry::Occupied(node_entry) => {
325 node_entry.into_mut().channels.push(NetworkMap::get_key(msg.contents.short_channel_id, msg.contents.chain_hash));
327 Entry::Vacant(node_entry) => {
328 node_entry.insert(NodeInfo {
329 channels: vec!(NetworkMap::get_key(msg.contents.short_channel_id, msg.contents.chain_hash)),
330 lowest_inbound_channel_fee_base_msat: u32::max_value(),
331 lowest_inbound_channel_fee_proportional_millionths: u32::max_value(),
332 features: GlobalFeatures::new(),
336 addresses: Vec::new(),
343 add_channel_to_node!(msg.contents.node_id_1);
344 add_channel_to_node!(msg.contents.node_id_2);
346 Ok(msg.contents.excess_data.is_empty() && !msg.contents.features.supports_unknown_bits())
349 fn handle_htlc_fail_channel_update(&self, update: &msgs::HTLCFailChannelUpdate) {
351 &msgs::HTLCFailChannelUpdate::ChannelUpdateMessage { ref msg } => {
352 let _ = self.handle_channel_update(msg);
354 &msgs::HTLCFailChannelUpdate::ChannelClosed { ref short_channel_id } => {
355 let mut network = self.network_map.write().unwrap();
356 if let Some(chan) = network.channels.remove(short_channel_id) {
357 Self::remove_channel_in_nodes(&mut network.nodes, &chan, *short_channel_id);
363 fn handle_channel_update(&self, msg: &msgs::ChannelUpdate) -> Result<bool, HandleError> {
364 let mut network = self.network_map.write().unwrap();
366 let chan_enabled = msg.contents.flags & (1 << 1) != (1 << 1);
367 let chan_was_enabled;
369 match network.channels.get_mut(&NetworkMap::get_key(msg.contents.short_channel_id, msg.contents.chain_hash)) {
370 None => return Err(HandleError{err: "Couldn't find channel for update", action: Some(ErrorAction::IgnoreError)}),
372 macro_rules! maybe_update_channel_info {
373 ( $target: expr) => {
374 if $target.last_update >= msg.contents.timestamp {
375 return Err(HandleError{err: "Update older than last processed update", action: Some(ErrorAction::IgnoreError)});
377 chan_was_enabled = $target.enabled;
378 $target.last_update = msg.contents.timestamp;
379 $target.enabled = chan_enabled;
380 $target.cltv_expiry_delta = msg.contents.cltv_expiry_delta;
381 $target.htlc_minimum_msat = msg.contents.htlc_minimum_msat;
382 $target.fee_base_msat = msg.contents.fee_base_msat;
383 $target.fee_proportional_millionths = msg.contents.fee_proportional_millionths;
387 let msg_hash = Message::from_slice(&Sha256dHash::from_data(&msg.contents.encode()[..])[..]).unwrap();
388 if msg.contents.flags & 1 == 1 {
389 dest_node_id = channel.one_to_two.src_node_id.clone();
390 secp_verify_sig!(self.secp_ctx, &msg_hash, &msg.signature, &channel.two_to_one.src_node_id);
391 maybe_update_channel_info!(channel.two_to_one);
393 dest_node_id = channel.two_to_one.src_node_id.clone();
394 secp_verify_sig!(self.secp_ctx, &msg_hash, &msg.signature, &channel.one_to_two.src_node_id);
395 maybe_update_channel_info!(channel.one_to_two);
401 let node = network.nodes.get_mut(&dest_node_id).unwrap();
402 node.lowest_inbound_channel_fee_base_msat = cmp::min(node.lowest_inbound_channel_fee_base_msat, msg.contents.fee_base_msat);
403 node.lowest_inbound_channel_fee_proportional_millionths = cmp::min(node.lowest_inbound_channel_fee_proportional_millionths, msg.contents.fee_proportional_millionths);
404 } else if chan_was_enabled {
405 let mut lowest_inbound_channel_fee_base_msat = u32::max_value();
406 let mut lowest_inbound_channel_fee_proportional_millionths = u32::max_value();
409 let node = network.nodes.get(&dest_node_id).unwrap();
411 for chan_id in node.channels.iter() {
412 let chan = network.channels.get(chan_id).unwrap();
413 if chan.one_to_two.src_node_id == dest_node_id {
414 lowest_inbound_channel_fee_base_msat = cmp::min(lowest_inbound_channel_fee_base_msat, chan.two_to_one.fee_base_msat);
415 lowest_inbound_channel_fee_proportional_millionths = cmp::min(lowest_inbound_channel_fee_proportional_millionths, chan.two_to_one.fee_proportional_millionths);
417 lowest_inbound_channel_fee_base_msat = cmp::min(lowest_inbound_channel_fee_base_msat, chan.one_to_two.fee_base_msat);
418 lowest_inbound_channel_fee_proportional_millionths = cmp::min(lowest_inbound_channel_fee_proportional_millionths, chan.one_to_two.fee_proportional_millionths);
423 //TODO: satisfy the borrow-checker without a double-map-lookup :(
424 let mut_node = network.nodes.get_mut(&dest_node_id).unwrap();
425 mut_node.lowest_inbound_channel_fee_base_msat = lowest_inbound_channel_fee_base_msat;
426 mut_node.lowest_inbound_channel_fee_proportional_millionths = lowest_inbound_channel_fee_proportional_millionths;
429 Ok(msg.contents.excess_data.is_empty())
433 #[derive(Eq, PartialEq)]
434 struct RouteGraphNode {
436 lowest_fee_to_peer_through_node: u64,
437 lowest_fee_to_node: u64,
440 impl cmp::Ord for RouteGraphNode {
441 fn cmp(&self, other: &RouteGraphNode) -> cmp::Ordering {
442 other.lowest_fee_to_peer_through_node.cmp(&self.lowest_fee_to_peer_through_node)
443 .then_with(|| other.pubkey.serialize().cmp(&self.pubkey.serialize()))
447 impl cmp::PartialOrd for RouteGraphNode {
448 fn partial_cmp(&self, other: &RouteGraphNode) -> Option<cmp::Ordering> {
449 Some(self.cmp(other))
453 struct DummyDirectionalChannelInfo {
454 src_node_id: PublicKey,
455 cltv_expiry_delta: u32,
456 htlc_minimum_msat: u64,
458 fee_proportional_millionths: u32,
462 /// Creates a new router with the given node_id to be used as the source for get_route()
463 pub fn new(our_pubkey: PublicKey, chain_monitor: Arc<ChainWatchInterface>, logger: Arc<Logger>) -> Router {
464 let mut nodes = HashMap::new();
465 nodes.insert(our_pubkey.clone(), NodeInfo {
466 channels: Vec::new(),
467 lowest_inbound_channel_fee_base_msat: u32::max_value(),
468 lowest_inbound_channel_fee_proportional_millionths: u32::max_value(),
469 features: GlobalFeatures::new(),
473 addresses: Vec::new(),
476 secp_ctx: Secp256k1::verification_only(),
477 network_map: RwLock::new(NetworkMap {
478 channels: HashMap::new(),
479 our_node_id: our_pubkey,
487 /// Dumps the entire network view of this Router to the logger provided in the constructor at
489 pub fn trace_state(&self) {
490 log_trace!(self, "{}", self.network_map.read().unwrap());
493 /// Get network addresses by node id
494 pub fn get_addresses(&self, pubkey: &PublicKey) -> Option<Vec<NetAddress>> {
495 let network = self.network_map.read().unwrap();
496 network.nodes.get(pubkey).map(|n| n.addresses.clone())
499 /// Marks a node as having failed a route. This will avoid re-using the node in routes for now,
500 /// with an expotnential decay in node "badness". Note that there is deliberately no
501 /// mark_channel_bad as a node may simply lie and suggest that an upstream channel from it is
502 /// what failed the route and not the node itself. Instead, setting the blamed_upstream_node
503 /// boolean will reduce the penalty, returning the node to usability faster. If the node is
504 /// behaving correctly, it will disable the failing channel and we will use it again next time.
505 pub fn mark_node_bad(&self, _node_id: &PublicKey, _blamed_upstream_node: bool) {
509 fn remove_channel_in_nodes(nodes: &mut HashMap<PublicKey, NodeInfo>, chan: &ChannelInfo, short_channel_id: u64) {
510 macro_rules! remove_from_node {
511 ($node_id: expr) => {
512 if let Entry::Occupied(mut entry) = nodes.entry($node_id) {
513 entry.get_mut().channels.retain(|chan_id| {
514 short_channel_id != *NetworkMap::get_short_id(chan_id)
516 if entry.get().channels.is_empty() {
517 entry.remove_entry();
520 panic!("Had channel that pointed to unknown node (ie inconsistent network map)!");
524 remove_from_node!(chan.one_to_two.src_node_id);
525 remove_from_node!(chan.two_to_one.src_node_id);
528 /// Gets a route from us to the given target node.
530 /// Extra routing hops between known nodes and the target will be used if they are included in
533 /// If some channels aren't announced, it may be useful to fill in a first_hops with the
534 /// results from a local ChannelManager::list_usable_channels() call. If it is filled in, our
535 /// (this Router's) view of our local channels will be ignored, and only those in first_hops
538 /// Panics if first_hops contains channels without short_channel_ids
539 /// (ChannelManager::list_usable_channels will never include such channels).
541 /// The fees on channels from us to next-hops are ignored (as they are assumed to all be
542 /// equal), however the enabled/disabled bit on such channels as well as the htlc_minimum_msat
543 /// *is* checked as they may change based on the receiving node.
544 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> {
545 // TODO: Obviously *only* using total fee cost sucks. We should consider weighting by
546 // uptime/success in using a node in the past.
547 let network = self.network_map.read().unwrap();
549 if *target == network.our_node_id {
550 return Err(HandleError{err: "Cannot generate a route to ourselves", action: None});
553 if final_value_msat > 21_000_000 * 1_0000_0000 * 1000 {
554 return Err(HandleError{err: "Cannot generate a route of more value than all existing satoshis", action: None});
557 // We do a dest-to-source Dijkstra's sorting by each node's distance from the destination
558 // plus the minimum per-HTLC fee to get from it to another node (aka "shitty A*").
559 // TODO: There are a few tweaks we could do, including possibly pre-calculating more stuff
560 // to use as the A* heuristic beyond just the cost to get one node further than the current
563 let dummy_directional_info = DummyDirectionalChannelInfo { // used for first_hops routes
564 src_node_id: network.our_node_id.clone(),
565 cltv_expiry_delta: 0,
566 htlc_minimum_msat: 0,
568 fee_proportional_millionths: 0,
571 let mut targets = BinaryHeap::new(); //TODO: Do we care about switching to eg Fibbonaci heap?
572 let mut dist = HashMap::with_capacity(network.nodes.len());
574 let mut first_hop_targets = HashMap::with_capacity(if first_hops.is_some() { first_hops.as_ref().unwrap().len() } else { 0 });
575 if let Some(hops) = first_hops {
577 let short_channel_id = chan.short_channel_id.expect("first_hops should be filled in with usable channels, not pending ones");
578 if chan.remote_network_id == *target {
580 hops: vec![RouteHop {
581 pubkey: chan.remote_network_id,
583 fee_msat: final_value_msat,
584 cltv_expiry_delta: final_cltv,
588 first_hop_targets.insert(chan.remote_network_id, short_channel_id);
590 if first_hop_targets.is_empty() {
591 return Err(HandleError{err: "Cannot route when there are no outbound routes away from us", action: None});
595 macro_rules! add_entry {
596 // Adds entry which goes from the node pointed to by $directional_info to
597 // $dest_node_id over the channel with id $chan_id with fees described in
598 // $directional_info.
599 ( $chan_id: expr, $dest_node_id: expr, $directional_info: expr, $starting_fee_msat: expr ) => {
600 //TODO: Explore simply adding fee to hit htlc_minimum_msat
601 if $starting_fee_msat as u64 + final_value_msat > $directional_info.htlc_minimum_msat {
602 let proportional_fee_millions = ($starting_fee_msat + final_value_msat).checked_mul($directional_info.fee_proportional_millionths as u64);
603 if let Some(new_fee) = proportional_fee_millions.and_then(|part| {
604 ($directional_info.fee_base_msat as u64).checked_add(part / 1000000) })
606 let mut total_fee = $starting_fee_msat as u64;
607 let hm_entry = dist.entry(&$directional_info.src_node_id);
608 let old_entry = hm_entry.or_insert_with(|| {
609 let node = network.nodes.get(&$directional_info.src_node_id).unwrap();
611 node.lowest_inbound_channel_fee_base_msat,
612 node.lowest_inbound_channel_fee_proportional_millionths,
614 pubkey: $dest_node_id.clone(),
617 cltv_expiry_delta: 0,
620 if $directional_info.src_node_id != network.our_node_id {
621 // Ignore new_fee for channel-from-us as we assume all channels-from-us
622 // will have the same effective-fee
623 total_fee += new_fee;
624 if let Some(fee_inc) = final_value_msat.checked_add(total_fee).and_then(|inc| { (old_entry.2 as u64).checked_mul(inc) }) {
625 total_fee += fee_inc / 1000000 + (old_entry.1 as u64);
627 // max_value means we'll always fail the old_entry.0 > total_fee check
628 total_fee = u64::max_value();
631 let new_graph_node = RouteGraphNode {
632 pubkey: $directional_info.src_node_id,
633 lowest_fee_to_peer_through_node: total_fee,
634 lowest_fee_to_node: $starting_fee_msat as u64 + new_fee,
636 if old_entry.0 > total_fee {
637 targets.push(new_graph_node);
638 old_entry.0 = total_fee;
639 old_entry.3 = RouteHop {
640 pubkey: $dest_node_id.clone(),
641 short_channel_id: $chan_id.clone(),
642 fee_msat: new_fee, // This field is ignored on the last-hop anyway
643 cltv_expiry_delta: $directional_info.cltv_expiry_delta as u32,
651 macro_rules! add_entries_to_cheapest_to_target_node {
652 ( $node: expr, $node_id: expr, $fee_to_target_msat: expr ) => {
653 if first_hops.is_some() {
654 if let Some(first_hop) = first_hop_targets.get(&$node_id) {
655 add_entry!(first_hop, $node_id, dummy_directional_info, $fee_to_target_msat);
659 for chan_id in $node.channels.iter() {
660 let chan = network.channels.get(chan_id).unwrap();
661 if chan.one_to_two.src_node_id == *$node_id {
662 // ie $node is one, ie next hop in A* is two, via the two_to_one channel
663 if first_hops.is_none() || chan.two_to_one.src_node_id != network.our_node_id {
664 if chan.two_to_one.enabled {
665 add_entry!(chan_id, chan.one_to_two.src_node_id, chan.two_to_one, $fee_to_target_msat);
669 if first_hops.is_none() || chan.one_to_two.src_node_id != network.our_node_id {
670 if chan.one_to_two.enabled {
671 add_entry!(chan_id, chan.two_to_one.src_node_id, chan.one_to_two, $fee_to_target_msat);
679 match network.nodes.get(target) {
682 add_entries_to_cheapest_to_target_node!(node, target, 0);
686 for hop in last_hops.iter() {
687 if first_hops.is_none() || hop.src_node_id != network.our_node_id { // first_hop overrules last_hops
688 if network.nodes.get(&hop.src_node_id).is_some() {
689 if first_hops.is_some() {
690 if let Some(first_hop) = first_hop_targets.get(&hop.src_node_id) {
691 add_entry!(first_hop, hop.src_node_id, dummy_directional_info, 0);
694 add_entry!(hop.short_channel_id, target, hop, 0);
699 while let Some(RouteGraphNode { pubkey, lowest_fee_to_node, .. }) = targets.pop() {
700 if pubkey == network.our_node_id {
701 let mut res = vec!(dist.remove(&network.our_node_id).unwrap().3);
702 while res.last().unwrap().pubkey != *target {
703 let new_entry = match dist.remove(&res.last().unwrap().pubkey) {
705 None => return Err(HandleError{err: "Failed to find a non-fee-overflowing path to the given destination", action: None}),
707 res.last_mut().unwrap().fee_msat = new_entry.fee_msat;
708 res.last_mut().unwrap().cltv_expiry_delta = new_entry.cltv_expiry_delta;
711 res.last_mut().unwrap().fee_msat = final_value_msat;
712 res.last_mut().unwrap().cltv_expiry_delta = final_cltv;
713 let route = Route { hops: res };
714 log_trace!(self, "Got route: {}", log_route!(route));
718 match network.nodes.get(&pubkey) {
721 add_entries_to_cheapest_to_target_node!(node, &pubkey, lowest_fee_to_node);
726 Err(HandleError{err: "Failed to find a path to the given destination", action: None})
732 use chain::chaininterface;
733 use ln::channelmanager;
734 use ln::router::{Router,NodeInfo,NetworkMap,ChannelInfo,DirectionalChannelInfo,RouteHint};
735 use ln::msgs::GlobalFeatures;
736 use util::test_utils;
737 use util::logger::Logger;
739 use bitcoin::util::hash::Sha256dHash;
740 use bitcoin::network::constants::Network;
744 use secp256k1::key::{PublicKey,SecretKey};
745 use secp256k1::Secp256k1;
751 let secp_ctx = Secp256k1::new();
752 let our_id = PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&secp_ctx, &hex::decode("0101010101010101010101010101010101010101010101010101010101010101").unwrap()[..]).unwrap());
753 let logger: Arc<Logger> = Arc::new(test_utils::TestLogger::new());
754 let chain_monitor = Arc::new(chaininterface::ChainWatchInterfaceUtil::new(Network::Testnet, Arc::clone(&logger)));
755 let router = Router::new(our_id, chain_monitor, Arc::clone(&logger));
757 // Build network from our_id to node8:
759 // -1(1)2- node1 -1(3)2-
761 // our_id -1(12)2- node8 -1(13)2--- node3
763 // -1(2)2- node2 -1(4)2-
766 // chan1 1-to-2: disabled
767 // chan1 2-to-1: enabled, 0 fee
769 // chan2 1-to-2: enabled, ignored fee
770 // chan2 2-to-1: enabled, 0 fee
772 // chan3 1-to-2: enabled, 0 fee
773 // chan3 2-to-1: enabled, 100 msat fee
775 // chan4 1-to-2: enabled, 100% fee
776 // chan4 2-to-1: enabled, 0 fee
778 // chan12 1-to-2: enabled, ignored fee
779 // chan12 2-to-1: enabled, 0 fee
781 // chan13 1-to-2: enabled, 200% fee
782 // chan13 2-to-1: enabled, 0 fee
785 // -1(5)2- node4 -1(8)2--
789 // node3--1(6)2- node5 -1(9)2--- node7 (not in global route map)
791 // -1(7)2- node6 -1(10)2-
793 // chan5 1-to-2: enabled, 100 msat fee
794 // chan5 2-to-1: enabled, 0 fee
796 // chan6 1-to-2: enabled, 0 fee
797 // chan6 2-to-1: enabled, 0 fee
799 // chan7 1-to-2: enabled, 100% fee
800 // chan7 2-to-1: enabled, 0 fee
802 // chan8 1-to-2: enabled, variable fee (0 then 1000 msat)
803 // chan8 2-to-1: enabled, 0 fee
805 // chan9 1-to-2: enabled, 1001 msat fee
806 // chan9 2-to-1: enabled, 0 fee
808 // chan10 1-to-2: enabled, 0 fee
809 // chan10 2-to-1: enabled, 0 fee
811 // chan11 1-to-2: enabled, 0 fee
812 // chan11 2-to-1: enabled, 0 fee
814 let node1 = PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&secp_ctx, &hex::decode("0202020202020202020202020202020202020202020202020202020202020202").unwrap()[..]).unwrap());
815 let node2 = PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&secp_ctx, &hex::decode("0303030303030303030303030303030303030303030303030303030303030303").unwrap()[..]).unwrap());
816 let node3 = PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&secp_ctx, &hex::decode("0404040404040404040404040404040404040404040404040404040404040404").unwrap()[..]).unwrap());
817 let node4 = PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&secp_ctx, &hex::decode("0505050505050505050505050505050505050505050505050505050505050505").unwrap()[..]).unwrap());
818 let node5 = PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&secp_ctx, &hex::decode("0606060606060606060606060606060606060606060606060606060606060606").unwrap()[..]).unwrap());
819 let node6 = PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&secp_ctx, &hex::decode("0707070707070707070707070707070707070707070707070707070707070707").unwrap()[..]).unwrap());
820 let node7 = PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&secp_ctx, &hex::decode("0808080808080808080808080808080808080808080808080808080808080808").unwrap()[..]).unwrap());
821 let node8 = PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&secp_ctx, &hex::decode("0909090909090909090909090909090909090909090909090909090909090909").unwrap()[..]).unwrap());
823 let zero_hash = Sha256dHash::from_data(&[0; 32]);
826 let mut network = router.network_map.write().unwrap();
828 network.nodes.insert(node1.clone(), NodeInfo {
829 channels: vec!(NetworkMap::get_key(1, zero_hash.clone()), NetworkMap::get_key(3, zero_hash.clone())),
830 lowest_inbound_channel_fee_base_msat: 100,
831 lowest_inbound_channel_fee_proportional_millionths: 0,
832 features: GlobalFeatures::new(),
836 addresses: Vec::new(),
838 network.channels.insert(NetworkMap::get_key(1, zero_hash.clone()), ChannelInfo {
839 features: GlobalFeatures::new(),
840 one_to_two: DirectionalChannelInfo {
841 src_node_id: our_id.clone(),
844 cltv_expiry_delta: u16::max_value(), // This value should be ignored
845 htlc_minimum_msat: 0,
846 fee_base_msat: u32::max_value(), // This value should be ignored
847 fee_proportional_millionths: u32::max_value(), // This value should be ignored
848 }, two_to_one: DirectionalChannelInfo {
849 src_node_id: node1.clone(),
852 cltv_expiry_delta: 0,
853 htlc_minimum_msat: 0,
855 fee_proportional_millionths: 0,
858 network.nodes.insert(node2.clone(), NodeInfo {
859 channels: vec!(NetworkMap::get_key(2, zero_hash.clone()), NetworkMap::get_key(4, zero_hash.clone())),
860 lowest_inbound_channel_fee_base_msat: 0,
861 lowest_inbound_channel_fee_proportional_millionths: 0,
862 features: GlobalFeatures::new(),
866 addresses: Vec::new(),
868 network.channels.insert(NetworkMap::get_key(2, zero_hash.clone()), ChannelInfo {
869 features: GlobalFeatures::new(),
870 one_to_two: DirectionalChannelInfo {
871 src_node_id: our_id.clone(),
874 cltv_expiry_delta: u16::max_value(), // This value should be ignored
875 htlc_minimum_msat: 0,
876 fee_base_msat: u32::max_value(), // This value should be ignored
877 fee_proportional_millionths: u32::max_value(), // This value should be ignored
878 }, two_to_one: DirectionalChannelInfo {
879 src_node_id: node2.clone(),
882 cltv_expiry_delta: 0,
883 htlc_minimum_msat: 0,
885 fee_proportional_millionths: 0,
888 network.nodes.insert(node8.clone(), NodeInfo {
889 channels: vec!(NetworkMap::get_key(12, zero_hash.clone()), NetworkMap::get_key(13, zero_hash.clone())),
890 lowest_inbound_channel_fee_base_msat: 0,
891 lowest_inbound_channel_fee_proportional_millionths: 0,
892 features: GlobalFeatures::new(),
896 addresses: Vec::new(),
898 network.channels.insert(NetworkMap::get_key(12, zero_hash.clone()), ChannelInfo {
899 features: GlobalFeatures::new(),
900 one_to_two: DirectionalChannelInfo {
901 src_node_id: our_id.clone(),
904 cltv_expiry_delta: u16::max_value(), // This value should be ignored
905 htlc_minimum_msat: 0,
906 fee_base_msat: u32::max_value(), // This value should be ignored
907 fee_proportional_millionths: u32::max_value(), // This value should be ignored
908 }, two_to_one: DirectionalChannelInfo {
909 src_node_id: node8.clone(),
912 cltv_expiry_delta: 0,
913 htlc_minimum_msat: 0,
915 fee_proportional_millionths: 0,
918 network.nodes.insert(node3.clone(), NodeInfo {
920 NetworkMap::get_key(3, zero_hash.clone()),
921 NetworkMap::get_key(4, zero_hash.clone()),
922 NetworkMap::get_key(13, zero_hash.clone()),
923 NetworkMap::get_key(5, zero_hash.clone()),
924 NetworkMap::get_key(6, zero_hash.clone()),
925 NetworkMap::get_key(7, zero_hash.clone())),
926 lowest_inbound_channel_fee_base_msat: 0,
927 lowest_inbound_channel_fee_proportional_millionths: 0,
928 features: GlobalFeatures::new(),
932 addresses: Vec::new(),
934 network.channels.insert(NetworkMap::get_key(3, zero_hash.clone()), ChannelInfo {
935 features: GlobalFeatures::new(),
936 one_to_two: DirectionalChannelInfo {
937 src_node_id: node1.clone(),
940 cltv_expiry_delta: (3 << 8) | 1,
941 htlc_minimum_msat: 0,
943 fee_proportional_millionths: 0,
944 }, two_to_one: DirectionalChannelInfo {
945 src_node_id: node3.clone(),
948 cltv_expiry_delta: (3 << 8) | 2,
949 htlc_minimum_msat: 0,
951 fee_proportional_millionths: 0,
954 network.channels.insert(NetworkMap::get_key(4, zero_hash.clone()), ChannelInfo {
955 features: GlobalFeatures::new(),
956 one_to_two: DirectionalChannelInfo {
957 src_node_id: node2.clone(),
960 cltv_expiry_delta: (4 << 8) | 1,
961 htlc_minimum_msat: 0,
963 fee_proportional_millionths: 1000000,
964 }, two_to_one: DirectionalChannelInfo {
965 src_node_id: node3.clone(),
968 cltv_expiry_delta: (4 << 8) | 2,
969 htlc_minimum_msat: 0,
971 fee_proportional_millionths: 0,
974 network.channels.insert(NetworkMap::get_key(13, zero_hash.clone()), ChannelInfo {
975 features: GlobalFeatures::new(),
976 one_to_two: DirectionalChannelInfo {
977 src_node_id: node8.clone(),
980 cltv_expiry_delta: (13 << 8) | 1,
981 htlc_minimum_msat: 0,
983 fee_proportional_millionths: 2000000,
984 }, two_to_one: DirectionalChannelInfo {
985 src_node_id: node3.clone(),
988 cltv_expiry_delta: (13 << 8) | 2,
989 htlc_minimum_msat: 0,
991 fee_proportional_millionths: 0,
994 network.nodes.insert(node4.clone(), NodeInfo {
995 channels: vec!(NetworkMap::get_key(5, zero_hash.clone()), NetworkMap::get_key(11, zero_hash.clone())),
996 lowest_inbound_channel_fee_base_msat: 0,
997 lowest_inbound_channel_fee_proportional_millionths: 0,
998 features: GlobalFeatures::new(),
1002 addresses: Vec::new(),
1004 network.channels.insert(NetworkMap::get_key(5, zero_hash.clone()), ChannelInfo {
1005 features: GlobalFeatures::new(),
1006 one_to_two: DirectionalChannelInfo {
1007 src_node_id: node3.clone(),
1010 cltv_expiry_delta: (5 << 8) | 1,
1011 htlc_minimum_msat: 0,
1013 fee_proportional_millionths: 0,
1014 }, two_to_one: DirectionalChannelInfo {
1015 src_node_id: node4.clone(),
1018 cltv_expiry_delta: (5 << 8) | 2,
1019 htlc_minimum_msat: 0,
1021 fee_proportional_millionths: 0,
1024 network.nodes.insert(node5.clone(), NodeInfo {
1025 channels: vec!(NetworkMap::get_key(6, zero_hash.clone()), NetworkMap::get_key(11, zero_hash.clone())),
1026 lowest_inbound_channel_fee_base_msat: 0,
1027 lowest_inbound_channel_fee_proportional_millionths: 0,
1028 features: GlobalFeatures::new(),
1032 addresses: Vec::new(),
1034 network.channels.insert(NetworkMap::get_key(6, zero_hash.clone()), ChannelInfo {
1035 features: GlobalFeatures::new(),
1036 one_to_two: DirectionalChannelInfo {
1037 src_node_id: node3.clone(),
1040 cltv_expiry_delta: (6 << 8) | 1,
1041 htlc_minimum_msat: 0,
1043 fee_proportional_millionths: 0,
1044 }, two_to_one: DirectionalChannelInfo {
1045 src_node_id: node5.clone(),
1048 cltv_expiry_delta: (6 << 8) | 2,
1049 htlc_minimum_msat: 0,
1051 fee_proportional_millionths: 0,
1054 network.channels.insert(NetworkMap::get_key(11, zero_hash.clone()), ChannelInfo {
1055 features: GlobalFeatures::new(),
1056 one_to_two: DirectionalChannelInfo {
1057 src_node_id: node5.clone(),
1060 cltv_expiry_delta: (11 << 8) | 1,
1061 htlc_minimum_msat: 0,
1063 fee_proportional_millionths: 0,
1064 }, two_to_one: DirectionalChannelInfo {
1065 src_node_id: node4.clone(),
1068 cltv_expiry_delta: (11 << 8) | 2,
1069 htlc_minimum_msat: 0,
1071 fee_proportional_millionths: 0,
1074 network.nodes.insert(node6.clone(), NodeInfo {
1075 channels: vec!(NetworkMap::get_key(7, zero_hash.clone())),
1076 lowest_inbound_channel_fee_base_msat: 0,
1077 lowest_inbound_channel_fee_proportional_millionths: 0,
1078 features: GlobalFeatures::new(),
1082 addresses: Vec::new(),
1084 network.channels.insert(NetworkMap::get_key(7, zero_hash.clone()), ChannelInfo {
1085 features: GlobalFeatures::new(),
1086 one_to_two: DirectionalChannelInfo {
1087 src_node_id: node3.clone(),
1090 cltv_expiry_delta: (7 << 8) | 1,
1091 htlc_minimum_msat: 0,
1093 fee_proportional_millionths: 1000000,
1094 }, two_to_one: DirectionalChannelInfo {
1095 src_node_id: node6.clone(),
1098 cltv_expiry_delta: (7 << 8) | 2,
1099 htlc_minimum_msat: 0,
1101 fee_proportional_millionths: 0,
1106 { // Simple route to 3 via 2
1107 let route = router.get_route(&node3, None, &Vec::new(), 100, 42).unwrap();
1108 assert_eq!(route.hops.len(), 2);
1110 assert_eq!(route.hops[0].pubkey, node2);
1111 assert_eq!(route.hops[0].short_channel_id, 2);
1112 assert_eq!(route.hops[0].fee_msat, 100);
1113 assert_eq!(route.hops[0].cltv_expiry_delta, (4 << 8) | 1);
1115 assert_eq!(route.hops[1].pubkey, node3);
1116 assert_eq!(route.hops[1].short_channel_id, 4);
1117 assert_eq!(route.hops[1].fee_msat, 100);
1118 assert_eq!(route.hops[1].cltv_expiry_delta, 42);
1121 { // Route to 1 via 2 and 3 because our channel to 1 is disabled
1122 let route = router.get_route(&node1, None, &Vec::new(), 100, 42).unwrap();
1123 assert_eq!(route.hops.len(), 3);
1125 assert_eq!(route.hops[0].pubkey, node2);
1126 assert_eq!(route.hops[0].short_channel_id, 2);
1127 assert_eq!(route.hops[0].fee_msat, 200);
1128 assert_eq!(route.hops[0].cltv_expiry_delta, (4 << 8) | 1);
1130 assert_eq!(route.hops[1].pubkey, node3);
1131 assert_eq!(route.hops[1].short_channel_id, 4);
1132 assert_eq!(route.hops[1].fee_msat, 100);
1133 assert_eq!(route.hops[1].cltv_expiry_delta, (3 << 8) | 2);
1135 assert_eq!(route.hops[2].pubkey, node1);
1136 assert_eq!(route.hops[2].short_channel_id, 3);
1137 assert_eq!(route.hops[2].fee_msat, 100);
1138 assert_eq!(route.hops[2].cltv_expiry_delta, 42);
1141 { // If we specify a channel to node8, that overrides our local channel view and that gets used
1142 let our_chans = vec![channelmanager::ChannelDetails {
1143 channel_id: [0; 32],
1144 short_channel_id: Some(42),
1145 remote_network_id: node8.clone(),
1146 channel_value_satoshis: 0,
1149 let route = router.get_route(&node3, Some(&our_chans), &Vec::new(), 100, 42).unwrap();
1150 assert_eq!(route.hops.len(), 2);
1152 assert_eq!(route.hops[0].pubkey, node8);
1153 assert_eq!(route.hops[0].short_channel_id, 42);
1154 assert_eq!(route.hops[0].fee_msat, 200);
1155 assert_eq!(route.hops[0].cltv_expiry_delta, (13 << 8) | 1);
1157 assert_eq!(route.hops[1].pubkey, node3);
1158 assert_eq!(route.hops[1].short_channel_id, 13);
1159 assert_eq!(route.hops[1].fee_msat, 100);
1160 assert_eq!(route.hops[1].cltv_expiry_delta, 42);
1163 let mut last_hops = vec!(RouteHint {
1164 src_node_id: node4.clone(),
1165 short_channel_id: 8,
1167 fee_proportional_millionths: 0,
1168 cltv_expiry_delta: (8 << 8) | 1,
1169 htlc_minimum_msat: 0,
1171 src_node_id: node5.clone(),
1172 short_channel_id: 9,
1173 fee_base_msat: 1001,
1174 fee_proportional_millionths: 0,
1175 cltv_expiry_delta: (9 << 8) | 1,
1176 htlc_minimum_msat: 0,
1178 src_node_id: node6.clone(),
1179 short_channel_id: 10,
1181 fee_proportional_millionths: 0,
1182 cltv_expiry_delta: (10 << 8) | 1,
1183 htlc_minimum_msat: 0,
1186 { // Simple test across 2, 3, 5, and 4 via a last_hop channel
1187 let route = router.get_route(&node7, None, &last_hops, 100, 42).unwrap();
1188 assert_eq!(route.hops.len(), 5);
1190 assert_eq!(route.hops[0].pubkey, node2);
1191 assert_eq!(route.hops[0].short_channel_id, 2);
1192 assert_eq!(route.hops[0].fee_msat, 100);
1193 assert_eq!(route.hops[0].cltv_expiry_delta, (4 << 8) | 1);
1195 assert_eq!(route.hops[1].pubkey, node3);
1196 assert_eq!(route.hops[1].short_channel_id, 4);
1197 assert_eq!(route.hops[1].fee_msat, 0);
1198 assert_eq!(route.hops[1].cltv_expiry_delta, (6 << 8) | 1);
1200 assert_eq!(route.hops[2].pubkey, node5);
1201 assert_eq!(route.hops[2].short_channel_id, 6);
1202 assert_eq!(route.hops[2].fee_msat, 0);
1203 assert_eq!(route.hops[2].cltv_expiry_delta, (11 << 8) | 1);
1205 assert_eq!(route.hops[3].pubkey, node4);
1206 assert_eq!(route.hops[3].short_channel_id, 11);
1207 assert_eq!(route.hops[3].fee_msat, 0);
1208 assert_eq!(route.hops[3].cltv_expiry_delta, (8 << 8) | 1);
1210 assert_eq!(route.hops[4].pubkey, node7);
1211 assert_eq!(route.hops[4].short_channel_id, 8);
1212 assert_eq!(route.hops[4].fee_msat, 100);
1213 assert_eq!(route.hops[4].cltv_expiry_delta, 42);
1216 { // Simple test with outbound channel to 4 to test that last_hops and first_hops connect
1217 let our_chans = vec![channelmanager::ChannelDetails {
1218 channel_id: [0; 32],
1219 short_channel_id: Some(42),
1220 remote_network_id: node4.clone(),
1221 channel_value_satoshis: 0,
1224 let route = router.get_route(&node7, Some(&our_chans), &last_hops, 100, 42).unwrap();
1225 assert_eq!(route.hops.len(), 2);
1227 assert_eq!(route.hops[0].pubkey, node4);
1228 assert_eq!(route.hops[0].short_channel_id, 42);
1229 assert_eq!(route.hops[0].fee_msat, 0);
1230 assert_eq!(route.hops[0].cltv_expiry_delta, (8 << 8) | 1);
1232 assert_eq!(route.hops[1].pubkey, node7);
1233 assert_eq!(route.hops[1].short_channel_id, 8);
1234 assert_eq!(route.hops[1].fee_msat, 100);
1235 assert_eq!(route.hops[1].cltv_expiry_delta, 42);
1238 last_hops[0].fee_base_msat = 1000;
1240 { // Revert to via 6 as the fee on 8 goes up
1241 let route = router.get_route(&node7, None, &last_hops, 100, 42).unwrap();
1242 assert_eq!(route.hops.len(), 4);
1244 assert_eq!(route.hops[0].pubkey, node2);
1245 assert_eq!(route.hops[0].short_channel_id, 2);
1246 assert_eq!(route.hops[0].fee_msat, 200); // fee increased as its % of value transferred across node
1247 assert_eq!(route.hops[0].cltv_expiry_delta, (4 << 8) | 1);
1249 assert_eq!(route.hops[1].pubkey, node3);
1250 assert_eq!(route.hops[1].short_channel_id, 4);
1251 assert_eq!(route.hops[1].fee_msat, 100);
1252 assert_eq!(route.hops[1].cltv_expiry_delta, (7 << 8) | 1);
1254 assert_eq!(route.hops[2].pubkey, node6);
1255 assert_eq!(route.hops[2].short_channel_id, 7);
1256 assert_eq!(route.hops[2].fee_msat, 0);
1257 assert_eq!(route.hops[2].cltv_expiry_delta, (10 << 8) | 1);
1259 assert_eq!(route.hops[3].pubkey, node7);
1260 assert_eq!(route.hops[3].short_channel_id, 10);
1261 assert_eq!(route.hops[3].fee_msat, 100);
1262 assert_eq!(route.hops[3].cltv_expiry_delta, 42);
1265 { // ...but still use 8 for larger payments as 6 has a variable feerate
1266 let route = router.get_route(&node7, None, &last_hops, 2000, 42).unwrap();
1267 assert_eq!(route.hops.len(), 5);
1269 assert_eq!(route.hops[0].pubkey, node2);
1270 assert_eq!(route.hops[0].short_channel_id, 2);
1271 assert_eq!(route.hops[0].fee_msat, 3000);
1272 assert_eq!(route.hops[0].cltv_expiry_delta, (4 << 8) | 1);
1274 assert_eq!(route.hops[1].pubkey, node3);
1275 assert_eq!(route.hops[1].short_channel_id, 4);
1276 assert_eq!(route.hops[1].fee_msat, 0);
1277 assert_eq!(route.hops[1].cltv_expiry_delta, (6 << 8) | 1);
1279 assert_eq!(route.hops[2].pubkey, node5);
1280 assert_eq!(route.hops[2].short_channel_id, 6);
1281 assert_eq!(route.hops[2].fee_msat, 0);
1282 assert_eq!(route.hops[2].cltv_expiry_delta, (11 << 8) | 1);
1284 assert_eq!(route.hops[3].pubkey, node4);
1285 assert_eq!(route.hops[3].short_channel_id, 11);
1286 assert_eq!(route.hops[3].fee_msat, 1000);
1287 assert_eq!(route.hops[3].cltv_expiry_delta, (8 << 8) | 1);
1289 assert_eq!(route.hops[4].pubkey, node7);
1290 assert_eq!(route.hops[4].short_channel_id, 8);
1291 assert_eq!(route.hops[4].fee_msat, 2000);
1292 assert_eq!(route.hops[4].cltv_expiry_delta, 42);