1 use secp256k1::key::PublicKey;
2 use secp256k1::{Secp256k1,Message};
5 use bitcoin::util::hash::Sha256dHash;
7 use ln::channelmanager;
8 use ln::msgs::{ErrorAction,HandleError,RoutingMessageHandler,MsgEncodable,NetAddress,GlobalFeatures};
10 use util::logger::Logger;
13 use std::sync::{RwLock,Arc};
14 use std::collections::{HashMap,BinaryHeap};
15 use std::collections::hash_map::Entry;
21 pub pubkey: PublicKey,
22 /// The channel that should be used from the previous hop to reach this node.
23 pub short_channel_id: u64,
24 /// The fee taken on this hop. For the last hop, this should be the full value of the payment.
26 /// The CLTV delta added for this hop. For the last hop, this should be the full CLTV value
27 /// expected at the destination, in excess of the current block height.
28 pub cltv_expiry_delta: u32,
31 /// A route from us through the network to a destination
34 /// The list of hops, NOT INCLUDING our own, where the last hop is the destination. Thus, this
35 /// must always be at least length one. By protocol rules, this may not currently exceed 20 in
37 pub hops: Vec<RouteHop>,
40 struct DirectionalChannelInfo {
41 src_node_id: PublicKey,
44 cltv_expiry_delta: u16,
45 htlc_minimum_msat: u64,
47 fee_proportional_millionths: u32,
50 impl std::fmt::Display for DirectionalChannelInfo {
51 fn fmt(&self, f: &mut std::fmt::Formatter) -> Result<(), std::fmt::Error> {
52 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)?;
58 features: GlobalFeatures,
59 one_to_two: DirectionalChannelInfo,
60 two_to_one: DirectionalChannelInfo,
63 impl std::fmt::Display for ChannelInfo {
64 fn fmt(&self, f: &mut std::fmt::Formatter) -> Result<(), std::fmt::Error> {
65 write!(f, "features: {}, one_to_two: {}, two_to_one: {}", log_bytes!(self.features.encode()), self.one_to_two, self.two_to_one)?;
71 #[cfg(feature = "non_bitcoin_chain_hash_routing")]
72 channels: Vec<(u64, Sha256dHash)>,
73 #[cfg(not(feature = "non_bitcoin_chain_hash_routing"))]
76 lowest_inbound_channel_fee_base_msat: u32,
77 lowest_inbound_channel_fee_proportional_millionths: u32,
79 features: GlobalFeatures,
83 addresses: Vec<NetAddress>,
86 impl std::fmt::Display for NodeInfo {
87 fn fmt(&self, f: &mut std::fmt::Formatter) -> Result<(), std::fmt::Error> {
88 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[..])?;
94 #[cfg(feature = "non_bitcoin_chain_hash_routing")]
95 channels: HashMap<(u64, Sha256dHash), ChannelInfo>,
96 #[cfg(not(feature = "non_bitcoin_chain_hash_routing"))]
97 channels: HashMap<u64, ChannelInfo>,
99 our_node_id: PublicKey,
100 nodes: HashMap<PublicKey, NodeInfo>,
103 impl std::fmt::Display for NetworkMap {
104 fn fmt(&self, f: &mut std::fmt::Formatter) -> Result<(), std::fmt::Error> {
105 write!(f, "Node id {} network map\n[Channels]\n", log_pubkey!(self.our_node_id))?;
106 for (key, val) in self.channels.iter() {
107 write!(f, " {}: {}\n", key, val)?;
109 write!(f, "[Nodes]\n")?;
110 for (key, val) in self.nodes.iter() {
111 write!(f, " {}: {}\n", log_pubkey!(key), val)?;
118 #[cfg(feature = "non_bitcoin_chain_hash_routing")]
120 fn get_key(short_channel_id: u64, chain_hash: Sha256dHash) -> (u64, Sha256dHash) {
121 (short_channel_id, chain_hash)
124 #[cfg(not(feature = "non_bitcoin_chain_hash_routing"))]
126 fn get_key(short_channel_id: u64, _: Sha256dHash) -> u64 {
130 #[cfg(feature = "non_bitcoin_chain_hash_routing")]
132 fn get_short_id(id: &(u64, Sha256dHash)) -> &u64 {
136 #[cfg(not(feature = "non_bitcoin_chain_hash_routing"))]
138 fn get_short_id(id: &u64) -> &u64 {
143 /// A channel descriptor which provides a last-hop route to get_route
144 pub struct RouteHint {
145 pub src_node_id: PublicKey,
146 pub short_channel_id: u64,
147 pub fee_base_msat: u32,
148 pub fee_proportional_millionths: u32,
149 pub cltv_expiry_delta: u16,
150 pub htlc_minimum_msat: u64,
153 /// Tracks a view of the network, receiving updates from peers and generating Routes to
154 /// payment destinations.
156 secp_ctx: Secp256k1<secp256k1::VerifyOnly>,
157 network_map: RwLock<NetworkMap>,
161 macro_rules! secp_verify_sig {
162 ( $secp_ctx: expr, $msg: expr, $sig: expr, $pubkey: expr ) => {
163 match $secp_ctx.verify($msg, $sig, $pubkey) {
165 Err(_) => return Err(HandleError{err: "Invalid signature from remote node", action: None}),
170 impl RoutingMessageHandler for Router {
171 fn handle_node_announcement(&self, msg: &msgs::NodeAnnouncement) -> Result<(), HandleError> {
172 let msg_hash = Message::from_slice(&Sha256dHash::from_data(&msg.contents.encode()[..])[..]).unwrap();
173 secp_verify_sig!(self.secp_ctx, &msg_hash, &msg.signature, &msg.contents.node_id);
175 if msg.contents.features.requires_unknown_bits() {
176 panic!("Unknown-required-features NodeAnnouncements should never deserialize!");
179 let mut network = self.network_map.write().unwrap();
180 match network.nodes.get_mut(&msg.contents.node_id) {
181 None => Err(HandleError{err: "No existing channels for node_announcement", action: Some(ErrorAction::IgnoreError)}),
183 if node.last_update >= msg.contents.timestamp {
184 return Err(HandleError{err: "Update older than last processed update", action: Some(ErrorAction::IgnoreError)});
187 node.features = msg.contents.features.clone();
188 node.last_update = msg.contents.timestamp;
189 node.rgb = msg.contents.rgb;
190 node.alias = msg.contents.alias;
191 node.addresses = msg.contents.addresses.clone();
197 fn handle_channel_announcement(&self, msg: &msgs::ChannelAnnouncement) -> Result<bool, HandleError> {
198 let msg_hash = Message::from_slice(&Sha256dHash::from_data(&msg.contents.encode()[..])[..]).unwrap();
199 secp_verify_sig!(self.secp_ctx, &msg_hash, &msg.node_signature_1, &msg.contents.node_id_1);
200 secp_verify_sig!(self.secp_ctx, &msg_hash, &msg.node_signature_2, &msg.contents.node_id_2);
201 secp_verify_sig!(self.secp_ctx, &msg_hash, &msg.bitcoin_signature_1, &msg.contents.bitcoin_key_1);
202 secp_verify_sig!(self.secp_ctx, &msg_hash, &msg.bitcoin_signature_2, &msg.contents.bitcoin_key_2);
204 //TODO: Call blockchain thing to ask if the short_channel_id is valid
205 //TODO: Only allow bitcoin chain_hash
207 if msg.contents.features.requires_unknown_bits() {
208 panic!("Unknown-required-features ChannelAnnouncements should never deserialize!");
211 let mut network = self.network_map.write().unwrap();
213 match network.channels.entry(NetworkMap::get_key(msg.contents.short_channel_id, msg.contents.chain_hash)) {
214 Entry::Occupied(_) => {
215 //TODO: because asking the blockchain if short_channel_id is valid is only optional
216 //in the blockchain API, we need to handle it smartly here, though its unclear
218 return Err(HandleError{err: "Already have knowledge of channel", action: Some(ErrorAction::IgnoreError)})
220 Entry::Vacant(entry) => {
221 entry.insert(ChannelInfo {
222 features: msg.contents.features.clone(),
223 one_to_two: DirectionalChannelInfo {
224 src_node_id: msg.contents.node_id_1.clone(),
227 cltv_expiry_delta: u16::max_value(),
228 htlc_minimum_msat: u64::max_value(),
229 fee_base_msat: u32::max_value(),
230 fee_proportional_millionths: u32::max_value(),
232 two_to_one: DirectionalChannelInfo {
233 src_node_id: msg.contents.node_id_2.clone(),
236 cltv_expiry_delta: u16::max_value(),
237 htlc_minimum_msat: u64::max_value(),
238 fee_base_msat: u32::max_value(),
239 fee_proportional_millionths: u32::max_value(),
245 macro_rules! add_channel_to_node {
246 ( $node_id: expr ) => {
247 match network.nodes.entry($node_id) {
248 Entry::Occupied(node_entry) => {
249 node_entry.into_mut().channels.push(NetworkMap::get_key(msg.contents.short_channel_id, msg.contents.chain_hash));
251 Entry::Vacant(node_entry) => {
252 node_entry.insert(NodeInfo {
253 channels: vec!(NetworkMap::get_key(msg.contents.short_channel_id, msg.contents.chain_hash)),
254 lowest_inbound_channel_fee_base_msat: u32::max_value(),
255 lowest_inbound_channel_fee_proportional_millionths: u32::max_value(),
256 features: GlobalFeatures::new(),
260 addresses: Vec::new(),
267 add_channel_to_node!(msg.contents.node_id_1);
268 add_channel_to_node!(msg.contents.node_id_2);
270 Ok(msg.contents.excess_data.is_empty() && !msg.contents.features.supports_unknown_bits())
273 fn handle_htlc_fail_channel_update(&self, update: &msgs::HTLCFailChannelUpdate) {
275 &msgs::HTLCFailChannelUpdate::ChannelUpdateMessage { ref msg } => {
276 let _ = self.handle_channel_update(msg);
278 &msgs::HTLCFailChannelUpdate::ChannelClosed { ref short_channel_id } => {
279 let mut network = self.network_map.write().unwrap();
280 if let Some(chan) = network.channels.remove(short_channel_id) {
281 network.nodes.get_mut(&chan.one_to_two.src_node_id).unwrap().channels.retain(|chan_id| {
282 chan_id != NetworkMap::get_short_id(chan_id)
284 network.nodes.get_mut(&chan.two_to_one.src_node_id).unwrap().channels.retain(|chan_id| {
285 chan_id != NetworkMap::get_short_id(chan_id)
292 fn handle_channel_update(&self, msg: &msgs::ChannelUpdate) -> Result<(), HandleError> {
293 let mut network = self.network_map.write().unwrap();
295 let chan_enabled = msg.contents.flags & (1 << 1) != (1 << 1);
296 let chan_was_enabled;
298 match network.channels.get_mut(&NetworkMap::get_key(msg.contents.short_channel_id, msg.contents.chain_hash)) {
299 None => return Err(HandleError{err: "Couldn't find channel for update", action: Some(ErrorAction::IgnoreError)}),
301 macro_rules! maybe_update_channel_info {
302 ( $target: expr) => {
303 if $target.last_update >= msg.contents.timestamp {
304 return Err(HandleError{err: "Update older than last processed update", action: Some(ErrorAction::IgnoreError)});
306 chan_was_enabled = $target.enabled;
307 $target.last_update = msg.contents.timestamp;
308 $target.enabled = chan_enabled;
309 $target.cltv_expiry_delta = msg.contents.cltv_expiry_delta;
310 $target.htlc_minimum_msat = msg.contents.htlc_minimum_msat;
311 $target.fee_base_msat = msg.contents.fee_base_msat;
312 $target.fee_proportional_millionths = msg.contents.fee_proportional_millionths;
316 let msg_hash = Message::from_slice(&Sha256dHash::from_data(&msg.contents.encode()[..])[..]).unwrap();
317 if msg.contents.flags & 1 == 1 {
318 dest_node_id = channel.one_to_two.src_node_id.clone();
319 secp_verify_sig!(self.secp_ctx, &msg_hash, &msg.signature, &channel.two_to_one.src_node_id);
320 maybe_update_channel_info!(channel.two_to_one);
322 dest_node_id = channel.two_to_one.src_node_id.clone();
323 secp_verify_sig!(self.secp_ctx, &msg_hash, &msg.signature, &channel.one_to_two.src_node_id);
324 maybe_update_channel_info!(channel.one_to_two);
330 let node = network.nodes.get_mut(&dest_node_id).unwrap();
331 node.lowest_inbound_channel_fee_base_msat = cmp::min(node.lowest_inbound_channel_fee_base_msat, msg.contents.fee_base_msat);
332 node.lowest_inbound_channel_fee_proportional_millionths = cmp::min(node.lowest_inbound_channel_fee_proportional_millionths, msg.contents.fee_proportional_millionths);
333 } else if chan_was_enabled {
334 let mut lowest_inbound_channel_fee_base_msat = u32::max_value();
335 let mut lowest_inbound_channel_fee_proportional_millionths = u32::max_value();
338 let node = network.nodes.get(&dest_node_id).unwrap();
340 for chan_id in node.channels.iter() {
341 let chan = network.channels.get(chan_id).unwrap();
342 if chan.one_to_two.src_node_id == dest_node_id {
343 lowest_inbound_channel_fee_base_msat = cmp::min(lowest_inbound_channel_fee_base_msat, chan.two_to_one.fee_base_msat);
344 lowest_inbound_channel_fee_proportional_millionths = cmp::min(lowest_inbound_channel_fee_proportional_millionths, chan.two_to_one.fee_proportional_millionths);
346 lowest_inbound_channel_fee_base_msat = cmp::min(lowest_inbound_channel_fee_base_msat, chan.one_to_two.fee_base_msat);
347 lowest_inbound_channel_fee_proportional_millionths = cmp::min(lowest_inbound_channel_fee_proportional_millionths, chan.one_to_two.fee_proportional_millionths);
352 //TODO: satisfy the borrow-checker without a double-map-lookup :(
353 let mut_node = network.nodes.get_mut(&dest_node_id).unwrap();
354 mut_node.lowest_inbound_channel_fee_base_msat = lowest_inbound_channel_fee_base_msat;
355 mut_node.lowest_inbound_channel_fee_proportional_millionths = lowest_inbound_channel_fee_proportional_millionths;
362 #[derive(Eq, PartialEq)]
363 struct RouteGraphNode {
365 lowest_fee_to_peer_through_node: u64,
366 lowest_fee_to_node: u64,
369 impl cmp::Ord for RouteGraphNode {
370 fn cmp(&self, other: &RouteGraphNode) -> cmp::Ordering {
371 other.lowest_fee_to_peer_through_node.cmp(&self.lowest_fee_to_peer_through_node)
372 .then_with(|| other.pubkey.serialize().cmp(&self.pubkey.serialize()))
376 impl cmp::PartialOrd for RouteGraphNode {
377 fn partial_cmp(&self, other: &RouteGraphNode) -> Option<cmp::Ordering> {
378 Some(self.cmp(other))
382 struct DummyDirectionalChannelInfo {
383 src_node_id: PublicKey,
384 cltv_expiry_delta: u32,
385 htlc_minimum_msat: u64,
387 fee_proportional_millionths: u32,
391 pub fn new(our_pubkey: PublicKey, logger: Arc<Logger>) -> Router {
392 let mut nodes = HashMap::new();
393 nodes.insert(our_pubkey.clone(), NodeInfo {
394 channels: Vec::new(),
395 lowest_inbound_channel_fee_base_msat: u32::max_value(),
396 lowest_inbound_channel_fee_proportional_millionths: u32::max_value(),
397 features: GlobalFeatures::new(),
401 addresses: Vec::new(),
404 secp_ctx: Secp256k1::verification_only(),
405 network_map: RwLock::new(NetworkMap {
406 channels: HashMap::new(),
407 our_node_id: our_pubkey,
414 /// Dumps the entire network view of this Router to the logger provided in the constructor at
416 pub fn trace_state(&self) {
417 log_trace!(self, "{}", self.network_map.read().unwrap());
420 /// Get network addresses by node id
421 pub fn get_addresses(&self, pubkey: &PublicKey) -> Option<Vec<NetAddress>> {
422 let network = self.network_map.read().unwrap();
423 network.nodes.get(pubkey).map(|n| n.addresses.clone())
426 /// Marks a node as having failed a route. This will avoid re-using the node in routes for now,
427 /// with an expotnential decay in node "badness". Note that there is deliberately no
428 /// mark_channel_bad as a node may simply lie and suggest that an upstream channel from it is
429 /// what failed the route and not the node itself. Instead, setting the blamed_upstream_node
430 /// boolean will reduce the penalty, returning the node to usability faster. If the node is
431 /// behaving correctly, it will disable the failing channel and we will use it again next time.
432 pub fn mark_node_bad(&self, _node_id: &PublicKey, _blamed_upstream_node: bool) {
436 /// Gets a route from us to the given target node.
437 /// Extra routing hops between known nodes and the target will be used if they are included in
439 /// If some channels aren't announced, it may be useful to fill in a first_hops with the
440 /// results from a local ChannelManager::list_usable_channels() call. If it is filled in, our
441 /// (this Router's) view of our local channels will be ignored, and only those in first_hops
442 /// will be used. Panics if first_hops contains channels without short_channel_ids
443 /// (ChannelManager::list_usable_channels will never include such channels).
444 /// The fees on channels from us to next-hops are ignored (as they are assumed to all be
445 /// equal), however the enabled/disabled bit on such channels as well as the htlc_minimum_msat
446 /// *is* checked as they may change based on the receiving node.
447 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> {
448 // TODO: Obviously *only* using total fee cost sucks. We should consider weighting by
449 // uptime/success in using a node in the past.
450 let network = self.network_map.read().unwrap();
452 if *target == network.our_node_id {
453 return Err(HandleError{err: "Cannot generate a route to ourselves", action: None});
456 if final_value_msat > 21_000_000 * 1_0000_0000 * 1000 {
457 return Err(HandleError{err: "Cannot generate a route of more value than all existing satoshis", action: None});
460 // We do a dest-to-source Dijkstra's sorting by each node's distance from the destination
461 // plus the minimum per-HTLC fee to get from it to another node (aka "shitty A*").
462 // TODO: There are a few tweaks we could do, including possibly pre-calculating more stuff
463 // to use as the A* heuristic beyond just the cost to get one node further than the current
466 let dummy_directional_info = DummyDirectionalChannelInfo { // used for first_hops routes
467 src_node_id: network.our_node_id.clone(),
468 cltv_expiry_delta: 0,
469 htlc_minimum_msat: 0,
471 fee_proportional_millionths: 0,
474 let mut targets = BinaryHeap::new(); //TODO: Do we care about switching to eg Fibbonaci heap?
475 let mut dist = HashMap::with_capacity(network.nodes.len());
477 let mut first_hop_targets = HashMap::with_capacity(if first_hops.is_some() { first_hops.as_ref().unwrap().len() } else { 0 });
478 if let Some(hops) = first_hops {
480 let short_channel_id = chan.short_channel_id.expect("first_hops should be filled in with usable channels, not pending ones");
481 if chan.remote_network_id == *target {
483 hops: vec![RouteHop {
484 pubkey: chan.remote_network_id,
486 fee_msat: final_value_msat,
487 cltv_expiry_delta: final_cltv,
491 first_hop_targets.insert(chan.remote_network_id, short_channel_id);
493 if first_hop_targets.is_empty() {
494 return Err(HandleError{err: "Cannot route when there are no outbound routes away from us", action: None});
498 macro_rules! add_entry {
499 // Adds entry which goes from the node pointed to by $directional_info to
500 // $dest_node_id over the channel with id $chan_id with fees described in
501 // $directional_info.
502 ( $chan_id: expr, $dest_node_id: expr, $directional_info: expr, $starting_fee_msat: expr ) => {
503 //TODO: Explore simply adding fee to hit htlc_minimum_msat
504 if $starting_fee_msat as u64 + final_value_msat > $directional_info.htlc_minimum_msat {
505 let proportional_fee_millions = ($starting_fee_msat + final_value_msat).checked_mul($directional_info.fee_proportional_millionths as u64);
506 if let Some(new_fee) = proportional_fee_millions.and_then(|part| {
507 ($directional_info.fee_base_msat as u64).checked_add(part / 1000000) })
509 let mut total_fee = $starting_fee_msat as u64;
510 let hm_entry = dist.entry(&$directional_info.src_node_id);
511 let old_entry = hm_entry.or_insert_with(|| {
512 let node = network.nodes.get(&$directional_info.src_node_id).unwrap();
514 node.lowest_inbound_channel_fee_base_msat,
515 node.lowest_inbound_channel_fee_proportional_millionths,
517 pubkey: $dest_node_id.clone(),
520 cltv_expiry_delta: 0,
523 if $directional_info.src_node_id != network.our_node_id {
524 // Ignore new_fee for channel-from-us as we assume all channels-from-us
525 // will have the same effective-fee
526 total_fee += new_fee;
527 if let Some(fee_inc) = final_value_msat.checked_add(total_fee).and_then(|inc| { (old_entry.2 as u64).checked_mul(inc) }) {
528 total_fee += fee_inc / 1000000 + (old_entry.1 as u64);
530 // max_value means we'll always fail the old_entry.0 > total_fee check
531 total_fee = u64::max_value();
534 let new_graph_node = RouteGraphNode {
535 pubkey: $directional_info.src_node_id,
536 lowest_fee_to_peer_through_node: total_fee,
537 lowest_fee_to_node: $starting_fee_msat as u64 + new_fee,
539 if old_entry.0 > total_fee {
540 targets.push(new_graph_node);
541 old_entry.0 = total_fee;
542 old_entry.3 = RouteHop {
543 pubkey: $dest_node_id.clone(),
544 short_channel_id: $chan_id.clone(),
545 fee_msat: new_fee, // This field is ignored on the last-hop anyway
546 cltv_expiry_delta: $directional_info.cltv_expiry_delta as u32,
554 macro_rules! add_entries_to_cheapest_to_target_node {
555 ( $node: expr, $node_id: expr, $fee_to_target_msat: expr ) => {
556 if first_hops.is_some() {
557 if let Some(first_hop) = first_hop_targets.get(&$node_id) {
558 add_entry!(first_hop, $node_id, dummy_directional_info, $fee_to_target_msat);
562 for chan_id in $node.channels.iter() {
563 let chan = network.channels.get(chan_id).unwrap();
564 if chan.one_to_two.src_node_id == *$node_id {
565 // ie $node is one, ie next hop in A* is two, via the two_to_one channel
566 if first_hops.is_none() || chan.two_to_one.src_node_id != network.our_node_id {
567 if chan.two_to_one.enabled {
568 add_entry!(chan_id, chan.one_to_two.src_node_id, chan.two_to_one, $fee_to_target_msat);
572 if first_hops.is_none() || chan.one_to_two.src_node_id != network.our_node_id {
573 if chan.one_to_two.enabled {
574 add_entry!(chan_id, chan.two_to_one.src_node_id, chan.one_to_two, $fee_to_target_msat);
582 match network.nodes.get(target) {
585 add_entries_to_cheapest_to_target_node!(node, target, 0);
589 for hop in last_hops.iter() {
590 if first_hops.is_none() || hop.src_node_id != network.our_node_id { // first_hop overrules last_hops
591 if network.nodes.get(&hop.src_node_id).is_some() {
592 if first_hops.is_some() {
593 if let Some(first_hop) = first_hop_targets.get(&hop.src_node_id) {
594 add_entry!(first_hop, hop.src_node_id, dummy_directional_info, 0);
597 add_entry!(hop.short_channel_id, target, hop, 0);
602 while let Some(RouteGraphNode { pubkey, lowest_fee_to_node, .. }) = targets.pop() {
603 if pubkey == network.our_node_id {
604 let mut res = vec!(dist.remove(&network.our_node_id).unwrap().3);
605 while res.last().unwrap().pubkey != *target {
606 let new_entry = match dist.remove(&res.last().unwrap().pubkey) {
608 None => return Err(HandleError{err: "Failed to find a non-fee-overflowing path to the given destination", action: None}),
610 res.last_mut().unwrap().fee_msat = new_entry.fee_msat;
611 res.last_mut().unwrap().cltv_expiry_delta = new_entry.cltv_expiry_delta;
614 res.last_mut().unwrap().fee_msat = final_value_msat;
615 res.last_mut().unwrap().cltv_expiry_delta = final_cltv;
616 let route = Route { hops: res };
617 log_trace!(self, "Got route: {}", log_route!(route));
621 match network.nodes.get(&pubkey) {
624 add_entries_to_cheapest_to_target_node!(node, &pubkey, lowest_fee_to_node);
629 Err(HandleError{err: "Failed to find a path to the given destination", action: None})
635 use ln::channelmanager;
636 use ln::router::{Router,NodeInfo,NetworkMap,ChannelInfo,DirectionalChannelInfo,RouteHint};
637 use ln::msgs::GlobalFeatures;
638 use util::test_utils;
639 use util::logger::Logger;
641 use bitcoin::util::hash::Sha256dHash;
645 use secp256k1::key::{PublicKey,SecretKey};
646 use secp256k1::Secp256k1;
652 let secp_ctx = Secp256k1::new();
653 let our_id = PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&secp_ctx, &hex::decode("0101010101010101010101010101010101010101010101010101010101010101").unwrap()[..]).unwrap());
654 let logger: Arc<Logger> = Arc::new(test_utils::TestLogger::new());
655 let router = Router::new(our_id, Arc::clone(&logger));
657 // Build network from our_id to node8:
659 // -1(1)2- node1 -1(3)2-
661 // our_id -1(12)2- node8 -1(13)2--- node3
663 // -1(2)2- node2 -1(4)2-
666 // chan1 1-to-2: disabled
667 // chan1 2-to-1: enabled, 0 fee
669 // chan2 1-to-2: enabled, ignored fee
670 // chan2 2-to-1: enabled, 0 fee
672 // chan3 1-to-2: enabled, 0 fee
673 // chan3 2-to-1: enabled, 100 msat fee
675 // chan4 1-to-2: enabled, 100% fee
676 // chan4 2-to-1: enabled, 0 fee
678 // chan12 1-to-2: enabled, ignored fee
679 // chan12 2-to-1: enabled, 0 fee
681 // chan13 1-to-2: enabled, 200% fee
682 // chan13 2-to-1: enabled, 0 fee
685 // -1(5)2- node4 -1(8)2--
689 // node3--1(6)2- node5 -1(9)2--- node7 (not in global route map)
691 // -1(7)2- node6 -1(10)2-
693 // chan5 1-to-2: enabled, 100 msat fee
694 // chan5 2-to-1: enabled, 0 fee
696 // chan6 1-to-2: enabled, 0 fee
697 // chan6 2-to-1: enabled, 0 fee
699 // chan7 1-to-2: enabled, 100% fee
700 // chan7 2-to-1: enabled, 0 fee
702 // chan8 1-to-2: enabled, variable fee (0 then 1000 msat)
703 // chan8 2-to-1: enabled, 0 fee
705 // chan9 1-to-2: enabled, 1001 msat fee
706 // chan9 2-to-1: enabled, 0 fee
708 // chan10 1-to-2: enabled, 0 fee
709 // chan10 2-to-1: enabled, 0 fee
711 // chan11 1-to-2: enabled, 0 fee
712 // chan11 2-to-1: enabled, 0 fee
714 let node1 = PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&secp_ctx, &hex::decode("0202020202020202020202020202020202020202020202020202020202020202").unwrap()[..]).unwrap());
715 let node2 = PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&secp_ctx, &hex::decode("0303030303030303030303030303030303030303030303030303030303030303").unwrap()[..]).unwrap());
716 let node3 = PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&secp_ctx, &hex::decode("0404040404040404040404040404040404040404040404040404040404040404").unwrap()[..]).unwrap());
717 let node4 = PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&secp_ctx, &hex::decode("0505050505050505050505050505050505050505050505050505050505050505").unwrap()[..]).unwrap());
718 let node5 = PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&secp_ctx, &hex::decode("0606060606060606060606060606060606060606060606060606060606060606").unwrap()[..]).unwrap());
719 let node6 = PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&secp_ctx, &hex::decode("0707070707070707070707070707070707070707070707070707070707070707").unwrap()[..]).unwrap());
720 let node7 = PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&secp_ctx, &hex::decode("0808080808080808080808080808080808080808080808080808080808080808").unwrap()[..]).unwrap());
721 let node8 = PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&secp_ctx, &hex::decode("0909090909090909090909090909090909090909090909090909090909090909").unwrap()[..]).unwrap());
723 let zero_hash = Sha256dHash::from_data(&[0; 32]);
726 let mut network = router.network_map.write().unwrap();
728 network.nodes.insert(node1.clone(), NodeInfo {
729 channels: vec!(NetworkMap::get_key(1, zero_hash.clone()), NetworkMap::get_key(3, zero_hash.clone())),
730 lowest_inbound_channel_fee_base_msat: 100,
731 lowest_inbound_channel_fee_proportional_millionths: 0,
732 features: GlobalFeatures::new(),
736 addresses: Vec::new(),
738 network.channels.insert(NetworkMap::get_key(1, zero_hash.clone()), ChannelInfo {
739 features: GlobalFeatures::new(),
740 one_to_two: DirectionalChannelInfo {
741 src_node_id: our_id.clone(),
744 cltv_expiry_delta: u16::max_value(), // This value should be ignored
745 htlc_minimum_msat: 0,
746 fee_base_msat: u32::max_value(), // This value should be ignored
747 fee_proportional_millionths: u32::max_value(), // This value should be ignored
748 }, two_to_one: DirectionalChannelInfo {
749 src_node_id: node1.clone(),
752 cltv_expiry_delta: 0,
753 htlc_minimum_msat: 0,
755 fee_proportional_millionths: 0,
758 network.nodes.insert(node2.clone(), NodeInfo {
759 channels: vec!(NetworkMap::get_key(2, zero_hash.clone()), NetworkMap::get_key(4, zero_hash.clone())),
760 lowest_inbound_channel_fee_base_msat: 0,
761 lowest_inbound_channel_fee_proportional_millionths: 0,
762 features: GlobalFeatures::new(),
766 addresses: Vec::new(),
768 network.channels.insert(NetworkMap::get_key(2, zero_hash.clone()), ChannelInfo {
769 features: GlobalFeatures::new(),
770 one_to_two: DirectionalChannelInfo {
771 src_node_id: our_id.clone(),
774 cltv_expiry_delta: u16::max_value(), // This value should be ignored
775 htlc_minimum_msat: 0,
776 fee_base_msat: u32::max_value(), // This value should be ignored
777 fee_proportional_millionths: u32::max_value(), // This value should be ignored
778 }, two_to_one: DirectionalChannelInfo {
779 src_node_id: node2.clone(),
782 cltv_expiry_delta: 0,
783 htlc_minimum_msat: 0,
785 fee_proportional_millionths: 0,
788 network.nodes.insert(node8.clone(), NodeInfo {
789 channels: vec!(NetworkMap::get_key(12, zero_hash.clone()), NetworkMap::get_key(13, zero_hash.clone())),
790 lowest_inbound_channel_fee_base_msat: 0,
791 lowest_inbound_channel_fee_proportional_millionths: 0,
792 features: GlobalFeatures::new(),
796 addresses: Vec::new(),
798 network.channels.insert(NetworkMap::get_key(12, zero_hash.clone()), ChannelInfo {
799 features: GlobalFeatures::new(),
800 one_to_two: DirectionalChannelInfo {
801 src_node_id: our_id.clone(),
804 cltv_expiry_delta: u16::max_value(), // This value should be ignored
805 htlc_minimum_msat: 0,
806 fee_base_msat: u32::max_value(), // This value should be ignored
807 fee_proportional_millionths: u32::max_value(), // This value should be ignored
808 }, two_to_one: DirectionalChannelInfo {
809 src_node_id: node8.clone(),
812 cltv_expiry_delta: 0,
813 htlc_minimum_msat: 0,
815 fee_proportional_millionths: 0,
818 network.nodes.insert(node3.clone(), NodeInfo {
820 NetworkMap::get_key(3, zero_hash.clone()),
821 NetworkMap::get_key(4, zero_hash.clone()),
822 NetworkMap::get_key(13, zero_hash.clone()),
823 NetworkMap::get_key(5, zero_hash.clone()),
824 NetworkMap::get_key(6, zero_hash.clone()),
825 NetworkMap::get_key(7, zero_hash.clone())),
826 lowest_inbound_channel_fee_base_msat: 0,
827 lowest_inbound_channel_fee_proportional_millionths: 0,
828 features: GlobalFeatures::new(),
832 addresses: Vec::new(),
834 network.channels.insert(NetworkMap::get_key(3, zero_hash.clone()), ChannelInfo {
835 features: GlobalFeatures::new(),
836 one_to_two: DirectionalChannelInfo {
837 src_node_id: node1.clone(),
840 cltv_expiry_delta: (3 << 8) | 1,
841 htlc_minimum_msat: 0,
843 fee_proportional_millionths: 0,
844 }, two_to_one: DirectionalChannelInfo {
845 src_node_id: node3.clone(),
848 cltv_expiry_delta: (3 << 8) | 2,
849 htlc_minimum_msat: 0,
851 fee_proportional_millionths: 0,
854 network.channels.insert(NetworkMap::get_key(4, zero_hash.clone()), ChannelInfo {
855 features: GlobalFeatures::new(),
856 one_to_two: DirectionalChannelInfo {
857 src_node_id: node2.clone(),
860 cltv_expiry_delta: (4 << 8) | 1,
861 htlc_minimum_msat: 0,
863 fee_proportional_millionths: 1000000,
864 }, two_to_one: DirectionalChannelInfo {
865 src_node_id: node3.clone(),
868 cltv_expiry_delta: (4 << 8) | 2,
869 htlc_minimum_msat: 0,
871 fee_proportional_millionths: 0,
874 network.channels.insert(NetworkMap::get_key(13, zero_hash.clone()), ChannelInfo {
875 features: GlobalFeatures::new(),
876 one_to_two: DirectionalChannelInfo {
877 src_node_id: node8.clone(),
880 cltv_expiry_delta: (13 << 8) | 1,
881 htlc_minimum_msat: 0,
883 fee_proportional_millionths: 2000000,
884 }, two_to_one: DirectionalChannelInfo {
885 src_node_id: node3.clone(),
888 cltv_expiry_delta: (13 << 8) | 2,
889 htlc_minimum_msat: 0,
891 fee_proportional_millionths: 0,
894 network.nodes.insert(node4.clone(), NodeInfo {
895 channels: vec!(NetworkMap::get_key(5, zero_hash.clone()), NetworkMap::get_key(11, zero_hash.clone())),
896 lowest_inbound_channel_fee_base_msat: 0,
897 lowest_inbound_channel_fee_proportional_millionths: 0,
898 features: GlobalFeatures::new(),
902 addresses: Vec::new(),
904 network.channels.insert(NetworkMap::get_key(5, zero_hash.clone()), ChannelInfo {
905 features: GlobalFeatures::new(),
906 one_to_two: DirectionalChannelInfo {
907 src_node_id: node3.clone(),
910 cltv_expiry_delta: (5 << 8) | 1,
911 htlc_minimum_msat: 0,
913 fee_proportional_millionths: 0,
914 }, two_to_one: DirectionalChannelInfo {
915 src_node_id: node4.clone(),
918 cltv_expiry_delta: (5 << 8) | 2,
919 htlc_minimum_msat: 0,
921 fee_proportional_millionths: 0,
924 network.nodes.insert(node5.clone(), NodeInfo {
925 channels: vec!(NetworkMap::get_key(6, zero_hash.clone()), NetworkMap::get_key(11, 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(6, zero_hash.clone()), ChannelInfo {
935 features: GlobalFeatures::new(),
936 one_to_two: DirectionalChannelInfo {
937 src_node_id: node3.clone(),
940 cltv_expiry_delta: (6 << 8) | 1,
941 htlc_minimum_msat: 0,
943 fee_proportional_millionths: 0,
944 }, two_to_one: DirectionalChannelInfo {
945 src_node_id: node5.clone(),
948 cltv_expiry_delta: (6 << 8) | 2,
949 htlc_minimum_msat: 0,
951 fee_proportional_millionths: 0,
954 network.channels.insert(NetworkMap::get_key(11, zero_hash.clone()), ChannelInfo {
955 features: GlobalFeatures::new(),
956 one_to_two: DirectionalChannelInfo {
957 src_node_id: node5.clone(),
960 cltv_expiry_delta: (11 << 8) | 1,
961 htlc_minimum_msat: 0,
963 fee_proportional_millionths: 0,
964 }, two_to_one: DirectionalChannelInfo {
965 src_node_id: node4.clone(),
968 cltv_expiry_delta: (11 << 8) | 2,
969 htlc_minimum_msat: 0,
971 fee_proportional_millionths: 0,
974 network.nodes.insert(node6.clone(), NodeInfo {
975 channels: vec!(NetworkMap::get_key(7, zero_hash.clone())),
976 lowest_inbound_channel_fee_base_msat: 0,
977 lowest_inbound_channel_fee_proportional_millionths: 0,
978 features: GlobalFeatures::new(),
982 addresses: Vec::new(),
984 network.channels.insert(NetworkMap::get_key(7, zero_hash.clone()), ChannelInfo {
985 features: GlobalFeatures::new(),
986 one_to_two: DirectionalChannelInfo {
987 src_node_id: node3.clone(),
990 cltv_expiry_delta: (7 << 8) | 1,
991 htlc_minimum_msat: 0,
993 fee_proportional_millionths: 1000000,
994 }, two_to_one: DirectionalChannelInfo {
995 src_node_id: node6.clone(),
998 cltv_expiry_delta: (7 << 8) | 2,
999 htlc_minimum_msat: 0,
1001 fee_proportional_millionths: 0,
1006 { // Simple route to 3 via 2
1007 let route = router.get_route(&node3, None, &Vec::new(), 100, 42).unwrap();
1008 assert_eq!(route.hops.len(), 2);
1010 assert_eq!(route.hops[0].pubkey, node2);
1011 assert_eq!(route.hops[0].short_channel_id, 2);
1012 assert_eq!(route.hops[0].fee_msat, 100);
1013 assert_eq!(route.hops[0].cltv_expiry_delta, (4 << 8) | 1);
1015 assert_eq!(route.hops[1].pubkey, node3);
1016 assert_eq!(route.hops[1].short_channel_id, 4);
1017 assert_eq!(route.hops[1].fee_msat, 100);
1018 assert_eq!(route.hops[1].cltv_expiry_delta, 42);
1021 { // Route to 1 via 2 and 3 because our channel to 1 is disabled
1022 let route = router.get_route(&node1, None, &Vec::new(), 100, 42).unwrap();
1023 assert_eq!(route.hops.len(), 3);
1025 assert_eq!(route.hops[0].pubkey, node2);
1026 assert_eq!(route.hops[0].short_channel_id, 2);
1027 assert_eq!(route.hops[0].fee_msat, 200);
1028 assert_eq!(route.hops[0].cltv_expiry_delta, (4 << 8) | 1);
1030 assert_eq!(route.hops[1].pubkey, node3);
1031 assert_eq!(route.hops[1].short_channel_id, 4);
1032 assert_eq!(route.hops[1].fee_msat, 100);
1033 assert_eq!(route.hops[1].cltv_expiry_delta, (3 << 8) | 2);
1035 assert_eq!(route.hops[2].pubkey, node1);
1036 assert_eq!(route.hops[2].short_channel_id, 3);
1037 assert_eq!(route.hops[2].fee_msat, 100);
1038 assert_eq!(route.hops[2].cltv_expiry_delta, 42);
1041 { // If we specify a channel to node8, that overrides our local channel view and that gets used
1042 let our_chans = vec![channelmanager::ChannelDetails {
1043 channel_id: [0; 32],
1044 short_channel_id: Some(42),
1045 remote_network_id: node8.clone(),
1046 channel_value_satoshis: 0,
1049 let route = router.get_route(&node3, Some(&our_chans), &Vec::new(), 100, 42).unwrap();
1050 assert_eq!(route.hops.len(), 2);
1052 assert_eq!(route.hops[0].pubkey, node8);
1053 assert_eq!(route.hops[0].short_channel_id, 42);
1054 assert_eq!(route.hops[0].fee_msat, 200);
1055 assert_eq!(route.hops[0].cltv_expiry_delta, (13 << 8) | 1);
1057 assert_eq!(route.hops[1].pubkey, node3);
1058 assert_eq!(route.hops[1].short_channel_id, 13);
1059 assert_eq!(route.hops[1].fee_msat, 100);
1060 assert_eq!(route.hops[1].cltv_expiry_delta, 42);
1063 let mut last_hops = vec!(RouteHint {
1064 src_node_id: node4.clone(),
1065 short_channel_id: 8,
1067 fee_proportional_millionths: 0,
1068 cltv_expiry_delta: (8 << 8) | 1,
1069 htlc_minimum_msat: 0,
1071 src_node_id: node5.clone(),
1072 short_channel_id: 9,
1073 fee_base_msat: 1001,
1074 fee_proportional_millionths: 0,
1075 cltv_expiry_delta: (9 << 8) | 1,
1076 htlc_minimum_msat: 0,
1078 src_node_id: node6.clone(),
1079 short_channel_id: 10,
1081 fee_proportional_millionths: 0,
1082 cltv_expiry_delta: (10 << 8) | 1,
1083 htlc_minimum_msat: 0,
1086 { // Simple test across 2, 3, 5, and 4 via a last_hop channel
1087 let route = router.get_route(&node7, None, &last_hops, 100, 42).unwrap();
1088 assert_eq!(route.hops.len(), 5);
1090 assert_eq!(route.hops[0].pubkey, node2);
1091 assert_eq!(route.hops[0].short_channel_id, 2);
1092 assert_eq!(route.hops[0].fee_msat, 100);
1093 assert_eq!(route.hops[0].cltv_expiry_delta, (4 << 8) | 1);
1095 assert_eq!(route.hops[1].pubkey, node3);
1096 assert_eq!(route.hops[1].short_channel_id, 4);
1097 assert_eq!(route.hops[1].fee_msat, 0);
1098 assert_eq!(route.hops[1].cltv_expiry_delta, (6 << 8) | 1);
1100 assert_eq!(route.hops[2].pubkey, node5);
1101 assert_eq!(route.hops[2].short_channel_id, 6);
1102 assert_eq!(route.hops[2].fee_msat, 0);
1103 assert_eq!(route.hops[2].cltv_expiry_delta, (11 << 8) | 1);
1105 assert_eq!(route.hops[3].pubkey, node4);
1106 assert_eq!(route.hops[3].short_channel_id, 11);
1107 assert_eq!(route.hops[3].fee_msat, 0);
1108 assert_eq!(route.hops[3].cltv_expiry_delta, (8 << 8) | 1);
1110 assert_eq!(route.hops[4].pubkey, node7);
1111 assert_eq!(route.hops[4].short_channel_id, 8);
1112 assert_eq!(route.hops[4].fee_msat, 100);
1113 assert_eq!(route.hops[4].cltv_expiry_delta, 42);
1116 { // Simple test with outbound channel to 4 to test that last_hops and first_hops connect
1117 let our_chans = vec![channelmanager::ChannelDetails {
1118 channel_id: [0; 32],
1119 short_channel_id: Some(42),
1120 remote_network_id: node4.clone(),
1121 channel_value_satoshis: 0,
1124 let route = router.get_route(&node7, Some(&our_chans), &last_hops, 100, 42).unwrap();
1125 assert_eq!(route.hops.len(), 2);
1127 assert_eq!(route.hops[0].pubkey, node4);
1128 assert_eq!(route.hops[0].short_channel_id, 42);
1129 assert_eq!(route.hops[0].fee_msat, 0);
1130 assert_eq!(route.hops[0].cltv_expiry_delta, (8 << 8) | 1);
1132 assert_eq!(route.hops[1].pubkey, node7);
1133 assert_eq!(route.hops[1].short_channel_id, 8);
1134 assert_eq!(route.hops[1].fee_msat, 100);
1135 assert_eq!(route.hops[1].cltv_expiry_delta, 42);
1138 last_hops[0].fee_base_msat = 1000;
1140 { // Revert to via 6 as the fee on 8 goes up
1141 let route = router.get_route(&node7, None, &last_hops, 100, 42).unwrap();
1142 assert_eq!(route.hops.len(), 4);
1144 assert_eq!(route.hops[0].pubkey, node2);
1145 assert_eq!(route.hops[0].short_channel_id, 2);
1146 assert_eq!(route.hops[0].fee_msat, 200); // fee increased as its % of value transferred across node
1147 assert_eq!(route.hops[0].cltv_expiry_delta, (4 << 8) | 1);
1149 assert_eq!(route.hops[1].pubkey, node3);
1150 assert_eq!(route.hops[1].short_channel_id, 4);
1151 assert_eq!(route.hops[1].fee_msat, 100);
1152 assert_eq!(route.hops[1].cltv_expiry_delta, (7 << 8) | 1);
1154 assert_eq!(route.hops[2].pubkey, node6);
1155 assert_eq!(route.hops[2].short_channel_id, 7);
1156 assert_eq!(route.hops[2].fee_msat, 0);
1157 assert_eq!(route.hops[2].cltv_expiry_delta, (10 << 8) | 1);
1159 assert_eq!(route.hops[3].pubkey, node7);
1160 assert_eq!(route.hops[3].short_channel_id, 10);
1161 assert_eq!(route.hops[3].fee_msat, 100);
1162 assert_eq!(route.hops[3].cltv_expiry_delta, 42);
1165 { // ...but still use 8 for larger payments as 6 has a variable feerate
1166 let route = router.get_route(&node7, None, &last_hops, 2000, 42).unwrap();
1167 assert_eq!(route.hops.len(), 5);
1169 assert_eq!(route.hops[0].pubkey, node2);
1170 assert_eq!(route.hops[0].short_channel_id, 2);
1171 assert_eq!(route.hops[0].fee_msat, 3000);
1172 assert_eq!(route.hops[0].cltv_expiry_delta, (4 << 8) | 1);
1174 assert_eq!(route.hops[1].pubkey, node3);
1175 assert_eq!(route.hops[1].short_channel_id, 4);
1176 assert_eq!(route.hops[1].fee_msat, 0);
1177 assert_eq!(route.hops[1].cltv_expiry_delta, (6 << 8) | 1);
1179 assert_eq!(route.hops[2].pubkey, node5);
1180 assert_eq!(route.hops[2].short_channel_id, 6);
1181 assert_eq!(route.hops[2].fee_msat, 0);
1182 assert_eq!(route.hops[2].cltv_expiry_delta, (11 << 8) | 1);
1184 assert_eq!(route.hops[3].pubkey, node4);
1185 assert_eq!(route.hops[3].short_channel_id, 11);
1186 assert_eq!(route.hops[3].fee_msat, 1000);
1187 assert_eq!(route.hops[3].cltv_expiry_delta, (8 << 8) | 1);
1189 assert_eq!(route.hops[4].pubkey, node7);
1190 assert_eq!(route.hops[4].short_channel_id, 8);
1191 assert_eq!(route.hops[4].fee_msat, 2000);
1192 assert_eq!(route.hops[4].cltv_expiry_delta, 42);