1 use secp256k1::key::PublicKey;
2 use secp256k1::{Secp256k1,Message};
4 use bitcoin::util::hash::Sha256dHash;
6 use ln::channelmanager;
7 use ln::msgs::{ErrorAction,HandleError,RoutingMessageHandler,MsgEncodable,NetAddress,GlobalFeatures};
9 use util::logger::Logger;
12 use std::sync::{RwLock,Arc};
13 use std::collections::{HashMap,BinaryHeap};
14 use std::collections::hash_map::Entry;
20 pub pubkey: PublicKey,
21 /// The channel that should be used from the previous hop to reach this node.
22 pub short_channel_id: u64,
23 /// The fee taken on this hop. For the last hop, this should be the full value of the payment.
25 /// The CLTV delta added for this hop. For the last hop, this should be the full CLTV value
26 /// expected at the destination, in excess of the current block height.
27 pub cltv_expiry_delta: u32,
30 /// A route from us through the network to a destination
33 /// The list of hops, NOT INCLUDING our own, where the last hop is the destination. Thus, this
34 /// must always be at least length one. By protocol rules, this may not currently exceed 20 in
36 pub hops: Vec<RouteHop>,
39 struct DirectionalChannelInfo {
40 src_node_id: PublicKey,
43 cltv_expiry_delta: u16,
44 htlc_minimum_msat: u64,
46 fee_proportional_millionths: u32,
49 impl std::fmt::Display for DirectionalChannelInfo {
50 fn fmt(&self, f: &mut std::fmt::Formatter) -> Result<(), std::fmt::Error> {
51 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)?;
57 features: GlobalFeatures,
58 one_to_two: DirectionalChannelInfo,
59 two_to_one: DirectionalChannelInfo,
62 impl std::fmt::Display for ChannelInfo {
63 fn fmt(&self, f: &mut std::fmt::Formatter) -> Result<(), std::fmt::Error> {
64 write!(f, "features: {}, one_to_two: {}, two_to_one: {}", log_bytes!(self.features.encode()), self.one_to_two, self.two_to_one)?;
70 #[cfg(feature = "non_bitcoin_chain_hash_routing")]
71 channels: Vec<(u64, Sha256dHash)>,
72 #[cfg(not(feature = "non_bitcoin_chain_hash_routing"))]
75 lowest_inbound_channel_fee_base_msat: u32,
76 lowest_inbound_channel_fee_proportional_millionths: u32,
78 features: GlobalFeatures,
82 addresses: Vec<NetAddress>,
85 impl std::fmt::Display for NodeInfo {
86 fn fmt(&self, f: &mut std::fmt::Formatter) -> Result<(), std::fmt::Error> {
87 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[..])?;
93 #[cfg(feature = "non_bitcoin_chain_hash_routing")]
94 channels: HashMap<(u64, Sha256dHash), ChannelInfo>,
95 #[cfg(not(feature = "non_bitcoin_chain_hash_routing"))]
96 channels: HashMap<u64, ChannelInfo>,
98 our_node_id: PublicKey,
99 nodes: HashMap<PublicKey, NodeInfo>,
102 impl std::fmt::Display for NetworkMap {
103 fn fmt(&self, f: &mut std::fmt::Formatter) -> Result<(), std::fmt::Error> {
104 write!(f, "Node id {} network map\n[Channels]\n", log_pubkey!(self.our_node_id))?;
105 for (key, val) in self.channels.iter() {
106 write!(f, " {}: {}\n", key, val)?;
108 write!(f, "[Nodes]\n")?;
109 for (key, val) in self.nodes.iter() {
110 write!(f, " {}: {}\n", log_pubkey!(key), val)?;
117 #[cfg(feature = "non_bitcoin_chain_hash_routing")]
119 fn get_key(short_channel_id: u64, chain_hash: Sha256dHash) -> (u64, Sha256dHash) {
120 (short_channel_id, chain_hash)
123 #[cfg(not(feature = "non_bitcoin_chain_hash_routing"))]
125 fn get_key(short_channel_id: u64, _: Sha256dHash) -> u64 {
129 #[cfg(feature = "non_bitcoin_chain_hash_routing")]
131 fn get_short_id(id: &(u64, Sha256dHash)) -> &u64 {
135 #[cfg(not(feature = "non_bitcoin_chain_hash_routing"))]
137 fn get_short_id(id: &u64) -> &u64 {
142 /// A channel descriptor which provides a last-hop route to get_route
143 pub struct RouteHint {
144 pub src_node_id: PublicKey,
145 pub short_channel_id: u64,
146 pub fee_base_msat: u32,
147 pub fee_proportional_millionths: u32,
148 pub cltv_expiry_delta: u16,
149 pub htlc_minimum_msat: u64,
152 /// Tracks a view of the network, receiving updates from peers and generating Routes to
153 /// payment destinations.
156 network_map: RwLock<NetworkMap>,
160 macro_rules! secp_verify_sig {
161 ( $secp_ctx: expr, $msg: expr, $sig: expr, $pubkey: expr ) => {
162 match $secp_ctx.verify($msg, $sig, $pubkey) {
164 Err(_) => return Err(HandleError{err: "Invalid signature from remote node", action: None}),
169 impl RoutingMessageHandler for Router {
170 fn handle_node_announcement(&self, msg: &msgs::NodeAnnouncement) -> Result<(), HandleError> {
171 let msg_hash = Message::from_slice(&Sha256dHash::from_data(&msg.contents.encode()[..])[..]).unwrap();
172 secp_verify_sig!(self.secp_ctx, &msg_hash, &msg.signature, &msg.contents.node_id);
174 let mut network = self.network_map.write().unwrap();
175 match network.nodes.get_mut(&msg.contents.node_id) {
176 None => Err(HandleError{err: "No existing channels for node_announcement", action: Some(ErrorAction::IgnoreError)}),
178 if node.last_update >= msg.contents.timestamp {
179 return Err(HandleError{err: "Update older than last processed update", action: Some(ErrorAction::IgnoreError)});
182 node.features = msg.contents.features.clone();
183 node.last_update = msg.contents.timestamp;
184 node.rgb = msg.contents.rgb;
185 node.alias = msg.contents.alias;
186 node.addresses = msg.contents.addresses.clone();
192 fn handle_channel_announcement(&self, msg: &msgs::ChannelAnnouncement) -> Result<bool, HandleError> {
193 let msg_hash = Message::from_slice(&Sha256dHash::from_data(&msg.contents.encode()[..])[..]).unwrap();
194 secp_verify_sig!(self.secp_ctx, &msg_hash, &msg.node_signature_1, &msg.contents.node_id_1);
195 secp_verify_sig!(self.secp_ctx, &msg_hash, &msg.node_signature_2, &msg.contents.node_id_2);
196 secp_verify_sig!(self.secp_ctx, &msg_hash, &msg.bitcoin_signature_1, &msg.contents.bitcoin_key_1);
197 secp_verify_sig!(self.secp_ctx, &msg_hash, &msg.bitcoin_signature_2, &msg.contents.bitcoin_key_2);
199 //TODO: Call blockchain thing to ask if the short_channel_id is valid
200 //TODO: Only allow bitcoin chain_hash
202 if msg.contents.features.requires_unknown_bits() {
203 return Err(HandleError{err: "Channel announcement required unknown feature flags", action: None});
206 let mut network = self.network_map.write().unwrap();
208 match network.channels.entry(NetworkMap::get_key(msg.contents.short_channel_id, msg.contents.chain_hash)) {
209 Entry::Occupied(_) => {
210 //TODO: because asking the blockchain if short_channel_id is valid is only optional
211 //in the blockchain API, we need to handle it smartly here, though its unclear
213 return Err(HandleError{err: "Already have knowledge of channel", action: Some(ErrorAction::IgnoreError)})
215 Entry::Vacant(entry) => {
216 entry.insert(ChannelInfo {
217 features: msg.contents.features.clone(),
218 one_to_two: DirectionalChannelInfo {
219 src_node_id: msg.contents.node_id_1.clone(),
222 cltv_expiry_delta: u16::max_value(),
223 htlc_minimum_msat: u64::max_value(),
224 fee_base_msat: u32::max_value(),
225 fee_proportional_millionths: u32::max_value(),
227 two_to_one: DirectionalChannelInfo {
228 src_node_id: msg.contents.node_id_2.clone(),
231 cltv_expiry_delta: u16::max_value(),
232 htlc_minimum_msat: u64::max_value(),
233 fee_base_msat: u32::max_value(),
234 fee_proportional_millionths: u32::max_value(),
240 macro_rules! add_channel_to_node {
241 ( $node_id: expr ) => {
242 match network.nodes.entry($node_id) {
243 Entry::Occupied(node_entry) => {
244 node_entry.into_mut().channels.push(NetworkMap::get_key(msg.contents.short_channel_id, msg.contents.chain_hash));
246 Entry::Vacant(node_entry) => {
247 node_entry.insert(NodeInfo {
248 channels: vec!(NetworkMap::get_key(msg.contents.short_channel_id, msg.contents.chain_hash)),
249 lowest_inbound_channel_fee_base_msat: u32::max_value(),
250 lowest_inbound_channel_fee_proportional_millionths: u32::max_value(),
251 features: GlobalFeatures::new(),
255 addresses: Vec::new(),
262 add_channel_to_node!(msg.contents.node_id_1);
263 add_channel_to_node!(msg.contents.node_id_2);
265 Ok(!msg.contents.features.supports_unknown_bits())
268 fn handle_htlc_fail_channel_update(&self, update: &msgs::HTLCFailChannelUpdate) {
270 &msgs::HTLCFailChannelUpdate::ChannelUpdateMessage { ref msg } => {
271 let _ = self.handle_channel_update(msg);
273 &msgs::HTLCFailChannelUpdate::ChannelClosed { ref short_channel_id } => {
274 let mut network = self.network_map.write().unwrap();
275 if let Some(chan) = network.channels.remove(short_channel_id) {
276 network.nodes.get_mut(&chan.one_to_two.src_node_id).unwrap().channels.retain(|chan_id| {
277 chan_id != NetworkMap::get_short_id(chan_id)
279 network.nodes.get_mut(&chan.two_to_one.src_node_id).unwrap().channels.retain(|chan_id| {
280 chan_id != NetworkMap::get_short_id(chan_id)
287 fn handle_channel_update(&self, msg: &msgs::ChannelUpdate) -> Result<(), HandleError> {
288 let mut network = self.network_map.write().unwrap();
290 let chan_enabled = msg.contents.flags & (1 << 1) != (1 << 1);
291 let chan_was_enabled;
293 match network.channels.get_mut(&NetworkMap::get_key(msg.contents.short_channel_id, msg.contents.chain_hash)) {
294 None => return Err(HandleError{err: "Couldn't find channel for update", action: Some(ErrorAction::IgnoreError)}),
296 macro_rules! maybe_update_channel_info {
297 ( $target: expr) => {
298 if $target.last_update >= msg.contents.timestamp {
299 return Err(HandleError{err: "Update older than last processed update", action: Some(ErrorAction::IgnoreError)});
301 chan_was_enabled = $target.enabled;
302 $target.last_update = msg.contents.timestamp;
303 $target.enabled = chan_enabled;
304 $target.cltv_expiry_delta = msg.contents.cltv_expiry_delta;
305 $target.htlc_minimum_msat = msg.contents.htlc_minimum_msat;
306 $target.fee_base_msat = msg.contents.fee_base_msat;
307 $target.fee_proportional_millionths = msg.contents.fee_proportional_millionths;
311 let msg_hash = Message::from_slice(&Sha256dHash::from_data(&msg.contents.encode()[..])[..]).unwrap();
312 if msg.contents.flags & 1 == 1 {
313 dest_node_id = channel.one_to_two.src_node_id.clone();
314 secp_verify_sig!(self.secp_ctx, &msg_hash, &msg.signature, &channel.two_to_one.src_node_id);
315 maybe_update_channel_info!(channel.two_to_one);
317 dest_node_id = channel.two_to_one.src_node_id.clone();
318 secp_verify_sig!(self.secp_ctx, &msg_hash, &msg.signature, &channel.one_to_two.src_node_id);
319 maybe_update_channel_info!(channel.one_to_two);
325 let node = network.nodes.get_mut(&dest_node_id).unwrap();
326 node.lowest_inbound_channel_fee_base_msat = cmp::min(node.lowest_inbound_channel_fee_base_msat, msg.contents.fee_base_msat);
327 node.lowest_inbound_channel_fee_proportional_millionths = cmp::min(node.lowest_inbound_channel_fee_proportional_millionths, msg.contents.fee_proportional_millionths);
328 } else if chan_was_enabled {
329 let mut lowest_inbound_channel_fee_base_msat = u32::max_value();
330 let mut lowest_inbound_channel_fee_proportional_millionths = u32::max_value();
333 let node = network.nodes.get(&dest_node_id).unwrap();
335 for chan_id in node.channels.iter() {
336 let chan = network.channels.get(chan_id).unwrap();
337 if chan.one_to_two.src_node_id == dest_node_id {
338 lowest_inbound_channel_fee_base_msat = cmp::min(lowest_inbound_channel_fee_base_msat, chan.two_to_one.fee_base_msat);
339 lowest_inbound_channel_fee_proportional_millionths = cmp::min(lowest_inbound_channel_fee_proportional_millionths, chan.two_to_one.fee_proportional_millionths);
341 lowest_inbound_channel_fee_base_msat = cmp::min(lowest_inbound_channel_fee_base_msat, chan.one_to_two.fee_base_msat);
342 lowest_inbound_channel_fee_proportional_millionths = cmp::min(lowest_inbound_channel_fee_proportional_millionths, chan.one_to_two.fee_proportional_millionths);
347 //TODO: satisfy the borrow-checker without a double-map-lookup :(
348 let mut_node = network.nodes.get_mut(&dest_node_id).unwrap();
349 mut_node.lowest_inbound_channel_fee_base_msat = lowest_inbound_channel_fee_base_msat;
350 mut_node.lowest_inbound_channel_fee_proportional_millionths = lowest_inbound_channel_fee_proportional_millionths;
357 #[derive(Eq, PartialEq)]
358 struct RouteGraphNode {
360 lowest_fee_to_peer_through_node: u64,
361 lowest_fee_to_node: u64,
364 impl cmp::Ord for RouteGraphNode {
365 fn cmp(&self, other: &RouteGraphNode) -> cmp::Ordering {
366 other.lowest_fee_to_peer_through_node.cmp(&self.lowest_fee_to_peer_through_node)
367 .then_with(|| other.pubkey.serialize().cmp(&self.pubkey.serialize()))
371 impl cmp::PartialOrd for RouteGraphNode {
372 fn partial_cmp(&self, other: &RouteGraphNode) -> Option<cmp::Ordering> {
373 Some(self.cmp(other))
377 struct DummyDirectionalChannelInfo {
378 src_node_id: PublicKey,
379 cltv_expiry_delta: u32,
380 htlc_minimum_msat: u64,
382 fee_proportional_millionths: u32,
386 pub fn new(our_pubkey: PublicKey, logger: Arc<Logger>) -> Router {
387 let mut nodes = HashMap::new();
388 nodes.insert(our_pubkey.clone(), NodeInfo {
389 channels: Vec::new(),
390 lowest_inbound_channel_fee_base_msat: u32::max_value(),
391 lowest_inbound_channel_fee_proportional_millionths: u32::max_value(),
392 features: GlobalFeatures::new(),
396 addresses: Vec::new(),
399 secp_ctx: Secp256k1::new(),
400 network_map: RwLock::new(NetworkMap {
401 channels: HashMap::new(),
402 our_node_id: our_pubkey,
409 /// Dumps the entire network view of this Router to the logger provided in the constructor at
411 pub fn trace_state(&self) {
412 log_trace!(self, "{}", self.network_map.read().unwrap());
415 /// Get network addresses by node id
416 pub fn get_addresses(&self, pubkey: &PublicKey) -> Option<Vec<NetAddress>> {
417 let network = self.network_map.read().unwrap();
418 network.nodes.get(pubkey).map(|n| n.addresses.clone())
421 /// Marks a node as having failed a route. This will avoid re-using the node in routes for now,
422 /// with an expotnential decay in node "badness". Note that there is deliberately no
423 /// mark_channel_bad as a node may simply lie and suggest that an upstream channel from it is
424 /// what failed the route and not the node itself. Instead, setting the blamed_upstream_node
425 /// boolean will reduce the penalty, returning the node to usability faster. If the node is
426 /// behaving correctly, it will disable the failing channel and we will use it again next time.
427 pub fn mark_node_bad(&self, _node_id: &PublicKey, _blamed_upstream_node: bool) {
431 /// Gets a route from us to the given target node.
432 /// Extra routing hops between known nodes and the target will be used if they are included in
434 /// If some channels aren't announced, it may be useful to fill in a first_hops with the
435 /// results from a local ChannelManager::list_usable_channels() call. If it is filled in, our
436 /// (this Router's) view of our local channels will be ignored, and only those in first_hops
437 /// will be used. Panics if first_hops contains channels without short_channel_ids
438 /// (ChannelManager::list_usable_channels will never include such channels).
439 /// The fees on channels from us to next-hops are ignored (as they are assumed to all be
440 /// equal), however the enabled/disabled bit on such channels as well as the htlc_minimum_msat
441 /// *is* checked as they may change based on the receiving node.
442 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> {
443 // TODO: Obviously *only* using total fee cost sucks. We should consider weighting by
444 // uptime/success in using a node in the past.
445 let network = self.network_map.read().unwrap();
447 if *target == network.our_node_id {
448 return Err(HandleError{err: "Cannot generate a route to ourselves", action: None});
451 if final_value_msat > 21_000_000 * 1_0000_0000 * 1000 {
452 return Err(HandleError{err: "Cannot generate a route of more value than all existing satoshis", action: None});
455 // We do a dest-to-source Dijkstra's sorting by each node's distance from the destination
456 // plus the minimum per-HTLC fee to get from it to another node (aka "shitty A*").
457 // TODO: There are a few tweaks we could do, including possibly pre-calculating more stuff
458 // to use as the A* heuristic beyond just the cost to get one node further than the current
461 let dummy_directional_info = DummyDirectionalChannelInfo { // used for first_hops routes
462 src_node_id: network.our_node_id.clone(),
463 cltv_expiry_delta: 0,
464 htlc_minimum_msat: 0,
466 fee_proportional_millionths: 0,
469 let mut targets = BinaryHeap::new(); //TODO: Do we care about switching to eg Fibbonaci heap?
470 let mut dist = HashMap::with_capacity(network.nodes.len());
472 let mut first_hop_targets = HashMap::with_capacity(if first_hops.is_some() { first_hops.as_ref().unwrap().len() } else { 0 });
473 if let Some(hops) = first_hops {
475 let short_channel_id = chan.short_channel_id.expect("first_hops should be filled in with usable channels, not pending ones");
476 if chan.remote_network_id == *target {
478 hops: vec![RouteHop {
479 pubkey: chan.remote_network_id,
481 fee_msat: final_value_msat,
482 cltv_expiry_delta: final_cltv,
486 first_hop_targets.insert(chan.remote_network_id, short_channel_id);
488 if first_hop_targets.is_empty() {
489 return Err(HandleError{err: "Cannot route when there are no outbound routes away from us", action: None});
493 macro_rules! add_entry {
494 // Adds entry which goes from the node pointed to by $directional_info to
495 // $dest_node_id over the channel with id $chan_id with fees described in
496 // $directional_info.
497 ( $chan_id: expr, $dest_node_id: expr, $directional_info: expr, $starting_fee_msat: expr ) => {
498 //TODO: Explore simply adding fee to hit htlc_minimum_msat
499 if $starting_fee_msat as u64 + final_value_msat > $directional_info.htlc_minimum_msat {
500 let proportional_fee_millions = ($starting_fee_msat + final_value_msat).checked_mul($directional_info.fee_proportional_millionths as u64);
501 if let Some(new_fee) = proportional_fee_millions.and_then(|part| {
502 ($directional_info.fee_base_msat as u64).checked_add(part / 1000000) })
504 let mut total_fee = $starting_fee_msat as u64;
505 let hm_entry = dist.entry(&$directional_info.src_node_id);
506 let old_entry = hm_entry.or_insert_with(|| {
507 let node = network.nodes.get(&$directional_info.src_node_id).unwrap();
509 node.lowest_inbound_channel_fee_base_msat,
510 node.lowest_inbound_channel_fee_proportional_millionths,
512 pubkey: $dest_node_id.clone(),
515 cltv_expiry_delta: 0,
518 if $directional_info.src_node_id != network.our_node_id {
519 // Ignore new_fee for channel-from-us as we assume all channels-from-us
520 // will have the same effective-fee
521 total_fee += new_fee;
522 if let Some(fee_inc) = final_value_msat.checked_add(total_fee).and_then(|inc| { (old_entry.2 as u64).checked_mul(inc) }) {
523 total_fee += fee_inc / 1000000 + (old_entry.1 as u64);
525 // max_value means we'll always fail the old_entry.0 > total_fee check
526 total_fee = u64::max_value();
529 let new_graph_node = RouteGraphNode {
530 pubkey: $directional_info.src_node_id,
531 lowest_fee_to_peer_through_node: total_fee,
532 lowest_fee_to_node: $starting_fee_msat as u64 + new_fee,
534 if old_entry.0 > total_fee {
535 targets.push(new_graph_node);
536 old_entry.0 = total_fee;
537 old_entry.3 = RouteHop {
538 pubkey: $dest_node_id.clone(),
539 short_channel_id: $chan_id.clone(),
540 fee_msat: new_fee, // This field is ignored on the last-hop anyway
541 cltv_expiry_delta: $directional_info.cltv_expiry_delta as u32,
549 macro_rules! add_entries_to_cheapest_to_target_node {
550 ( $node: expr, $node_id: expr, $fee_to_target_msat: expr ) => {
551 if first_hops.is_some() {
552 if let Some(first_hop) = first_hop_targets.get(&$node_id) {
553 add_entry!(first_hop, $node_id, dummy_directional_info, $fee_to_target_msat);
557 for chan_id in $node.channels.iter() {
558 let chan = network.channels.get(chan_id).unwrap();
559 if chan.one_to_two.src_node_id == *$node_id {
560 // ie $node is one, ie next hop in A* is two, via the two_to_one channel
561 if first_hops.is_none() || chan.two_to_one.src_node_id != network.our_node_id {
562 if chan.two_to_one.enabled {
563 add_entry!(chan_id, chan.one_to_two.src_node_id, chan.two_to_one, $fee_to_target_msat);
567 if first_hops.is_none() || chan.one_to_two.src_node_id != network.our_node_id {
568 if chan.one_to_two.enabled {
569 add_entry!(chan_id, chan.two_to_one.src_node_id, chan.one_to_two, $fee_to_target_msat);
577 match network.nodes.get(target) {
580 add_entries_to_cheapest_to_target_node!(node, target, 0);
584 for hop in last_hops.iter() {
585 if first_hops.is_none() || hop.src_node_id != network.our_node_id { // first_hop overrules last_hops
586 if network.nodes.get(&hop.src_node_id).is_some() {
587 if first_hops.is_some() {
588 if let Some(first_hop) = first_hop_targets.get(&hop.src_node_id) {
589 add_entry!(first_hop, hop.src_node_id, dummy_directional_info, 0);
592 add_entry!(hop.short_channel_id, target, hop, 0);
597 while let Some(RouteGraphNode { pubkey, lowest_fee_to_node, .. }) = targets.pop() {
598 if pubkey == network.our_node_id {
599 let mut res = vec!(dist.remove(&network.our_node_id).unwrap().3);
600 while res.last().unwrap().pubkey != *target {
601 let new_entry = match dist.remove(&res.last().unwrap().pubkey) {
603 None => return Err(HandleError{err: "Failed to find a non-fee-overflowing path to the given destination", action: None}),
605 res.last_mut().unwrap().fee_msat = new_entry.fee_msat;
606 res.last_mut().unwrap().cltv_expiry_delta = new_entry.cltv_expiry_delta;
609 res.last_mut().unwrap().fee_msat = final_value_msat;
610 res.last_mut().unwrap().cltv_expiry_delta = final_cltv;
611 let route = Route { hops: res };
612 log_trace!(self, "Got route: {}", log_route!(route));
616 match network.nodes.get(&pubkey) {
619 add_entries_to_cheapest_to_target_node!(node, &pubkey, lowest_fee_to_node);
624 Err(HandleError{err: "Failed to find a path to the given destination", action: None})
630 use ln::channelmanager;
631 use ln::router::{Router,NodeInfo,NetworkMap,ChannelInfo,DirectionalChannelInfo,RouteHint};
632 use ln::msgs::GlobalFeatures;
633 use util::test_utils;
634 use util::logger::Logger;
636 use bitcoin::util::hash::Sha256dHash;
640 use secp256k1::key::{PublicKey,SecretKey};
641 use secp256k1::Secp256k1;
647 let secp_ctx = Secp256k1::new();
648 let our_id = PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&secp_ctx, &hex::decode("0101010101010101010101010101010101010101010101010101010101010101").unwrap()[..]).unwrap()).unwrap();
649 let logger: Arc<Logger> = Arc::new(test_utils::TestLogger::new());
650 let router = Router::new(our_id, Arc::clone(&logger));
652 // Build network from our_id to node8:
654 // -1(1)2- node1 -1(3)2-
656 // our_id -1(12)2- node8 -1(13)2--- node3
658 // -1(2)2- node2 -1(4)2-
661 // chan1 1-to-2: disabled
662 // chan1 2-to-1: enabled, 0 fee
664 // chan2 1-to-2: enabled, ignored fee
665 // chan2 2-to-1: enabled, 0 fee
667 // chan3 1-to-2: enabled, 0 fee
668 // chan3 2-to-1: enabled, 100 msat fee
670 // chan4 1-to-2: enabled, 100% fee
671 // chan4 2-to-1: enabled, 0 fee
673 // chan12 1-to-2: enabled, ignored fee
674 // chan12 2-to-1: enabled, 0 fee
676 // chan13 1-to-2: enabled, 200% fee
677 // chan13 2-to-1: enabled, 0 fee
680 // -1(5)2- node4 -1(8)2--
684 // node3--1(6)2- node5 -1(9)2--- node7 (not in global route map)
686 // -1(7)2- node6 -1(10)2-
688 // chan5 1-to-2: enabled, 100 msat fee
689 // chan5 2-to-1: enabled, 0 fee
691 // chan6 1-to-2: enabled, 0 fee
692 // chan6 2-to-1: enabled, 0 fee
694 // chan7 1-to-2: enabled, 100% fee
695 // chan7 2-to-1: enabled, 0 fee
697 // chan8 1-to-2: enabled, variable fee (0 then 1000 msat)
698 // chan8 2-to-1: enabled, 0 fee
700 // chan9 1-to-2: enabled, 1001 msat fee
701 // chan9 2-to-1: enabled, 0 fee
703 // chan10 1-to-2: enabled, 0 fee
704 // chan10 2-to-1: enabled, 0 fee
706 // chan11 1-to-2: enabled, 0 fee
707 // chan11 2-to-1: enabled, 0 fee
709 let node1 = PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&secp_ctx, &hex::decode("0202020202020202020202020202020202020202020202020202020202020202").unwrap()[..]).unwrap()).unwrap();
710 let node2 = PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&secp_ctx, &hex::decode("0303030303030303030303030303030303030303030303030303030303030303").unwrap()[..]).unwrap()).unwrap();
711 let node3 = PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&secp_ctx, &hex::decode("0404040404040404040404040404040404040404040404040404040404040404").unwrap()[..]).unwrap()).unwrap();
712 let node4 = PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&secp_ctx, &hex::decode("0505050505050505050505050505050505050505050505050505050505050505").unwrap()[..]).unwrap()).unwrap();
713 let node5 = PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&secp_ctx, &hex::decode("0606060606060606060606060606060606060606060606060606060606060606").unwrap()[..]).unwrap()).unwrap();
714 let node6 = PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&secp_ctx, &hex::decode("0707070707070707070707070707070707070707070707070707070707070707").unwrap()[..]).unwrap()).unwrap();
715 let node7 = PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&secp_ctx, &hex::decode("0808080808080808080808080808080808080808080808080808080808080808").unwrap()[..]).unwrap()).unwrap();
716 let node8 = PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&secp_ctx, &hex::decode("0909090909090909090909090909090909090909090909090909090909090909").unwrap()[..]).unwrap()).unwrap();
718 let zero_hash = Sha256dHash::from_data(&[0; 32]);
721 let mut network = router.network_map.write().unwrap();
723 network.nodes.insert(node1.clone(), NodeInfo {
724 channels: vec!(NetworkMap::get_key(1, zero_hash.clone()), NetworkMap::get_key(3, zero_hash.clone())),
725 lowest_inbound_channel_fee_base_msat: 100,
726 lowest_inbound_channel_fee_proportional_millionths: 0,
727 features: GlobalFeatures::new(),
731 addresses: Vec::new(),
733 network.channels.insert(NetworkMap::get_key(1, zero_hash.clone()), ChannelInfo {
734 features: GlobalFeatures::new(),
735 one_to_two: DirectionalChannelInfo {
736 src_node_id: our_id.clone(),
739 cltv_expiry_delta: u16::max_value(), // This value should be ignored
740 htlc_minimum_msat: 0,
741 fee_base_msat: u32::max_value(), // This value should be ignored
742 fee_proportional_millionths: u32::max_value(), // This value should be ignored
743 }, two_to_one: DirectionalChannelInfo {
744 src_node_id: node1.clone(),
747 cltv_expiry_delta: 0,
748 htlc_minimum_msat: 0,
750 fee_proportional_millionths: 0,
753 network.nodes.insert(node2.clone(), NodeInfo {
754 channels: vec!(NetworkMap::get_key(2, zero_hash.clone()), NetworkMap::get_key(4, zero_hash.clone())),
755 lowest_inbound_channel_fee_base_msat: 0,
756 lowest_inbound_channel_fee_proportional_millionths: 0,
757 features: GlobalFeatures::new(),
761 addresses: Vec::new(),
763 network.channels.insert(NetworkMap::get_key(2, zero_hash.clone()), ChannelInfo {
764 features: GlobalFeatures::new(),
765 one_to_two: DirectionalChannelInfo {
766 src_node_id: our_id.clone(),
769 cltv_expiry_delta: u16::max_value(), // This value should be ignored
770 htlc_minimum_msat: 0,
771 fee_base_msat: u32::max_value(), // This value should be ignored
772 fee_proportional_millionths: u32::max_value(), // This value should be ignored
773 }, two_to_one: DirectionalChannelInfo {
774 src_node_id: node2.clone(),
777 cltv_expiry_delta: 0,
778 htlc_minimum_msat: 0,
780 fee_proportional_millionths: 0,
783 network.nodes.insert(node8.clone(), NodeInfo {
784 channels: vec!(NetworkMap::get_key(12, zero_hash.clone()), NetworkMap::get_key(13, zero_hash.clone())),
785 lowest_inbound_channel_fee_base_msat: 0,
786 lowest_inbound_channel_fee_proportional_millionths: 0,
787 features: GlobalFeatures::new(),
791 addresses: Vec::new(),
793 network.channels.insert(NetworkMap::get_key(12, zero_hash.clone()), ChannelInfo {
794 features: GlobalFeatures::new(),
795 one_to_two: DirectionalChannelInfo {
796 src_node_id: our_id.clone(),
799 cltv_expiry_delta: u16::max_value(), // This value should be ignored
800 htlc_minimum_msat: 0,
801 fee_base_msat: u32::max_value(), // This value should be ignored
802 fee_proportional_millionths: u32::max_value(), // This value should be ignored
803 }, two_to_one: DirectionalChannelInfo {
804 src_node_id: node8.clone(),
807 cltv_expiry_delta: 0,
808 htlc_minimum_msat: 0,
810 fee_proportional_millionths: 0,
813 network.nodes.insert(node3.clone(), NodeInfo {
815 NetworkMap::get_key(3, zero_hash.clone()),
816 NetworkMap::get_key(4, zero_hash.clone()),
817 NetworkMap::get_key(13, zero_hash.clone()),
818 NetworkMap::get_key(5, zero_hash.clone()),
819 NetworkMap::get_key(6, zero_hash.clone()),
820 NetworkMap::get_key(7, zero_hash.clone())),
821 lowest_inbound_channel_fee_base_msat: 0,
822 lowest_inbound_channel_fee_proportional_millionths: 0,
823 features: GlobalFeatures::new(),
827 addresses: Vec::new(),
829 network.channels.insert(NetworkMap::get_key(3, zero_hash.clone()), ChannelInfo {
830 features: GlobalFeatures::new(),
831 one_to_two: DirectionalChannelInfo {
832 src_node_id: node1.clone(),
835 cltv_expiry_delta: (3 << 8) | 1,
836 htlc_minimum_msat: 0,
838 fee_proportional_millionths: 0,
839 }, two_to_one: DirectionalChannelInfo {
840 src_node_id: node3.clone(),
843 cltv_expiry_delta: (3 << 8) | 2,
844 htlc_minimum_msat: 0,
846 fee_proportional_millionths: 0,
849 network.channels.insert(NetworkMap::get_key(4, zero_hash.clone()), ChannelInfo {
850 features: GlobalFeatures::new(),
851 one_to_two: DirectionalChannelInfo {
852 src_node_id: node2.clone(),
855 cltv_expiry_delta: (4 << 8) | 1,
856 htlc_minimum_msat: 0,
858 fee_proportional_millionths: 1000000,
859 }, two_to_one: DirectionalChannelInfo {
860 src_node_id: node3.clone(),
863 cltv_expiry_delta: (4 << 8) | 2,
864 htlc_minimum_msat: 0,
866 fee_proportional_millionths: 0,
869 network.channels.insert(NetworkMap::get_key(13, zero_hash.clone()), ChannelInfo {
870 features: GlobalFeatures::new(),
871 one_to_two: DirectionalChannelInfo {
872 src_node_id: node8.clone(),
875 cltv_expiry_delta: (13 << 8) | 1,
876 htlc_minimum_msat: 0,
878 fee_proportional_millionths: 2000000,
879 }, two_to_one: DirectionalChannelInfo {
880 src_node_id: node3.clone(),
883 cltv_expiry_delta: (13 << 8) | 2,
884 htlc_minimum_msat: 0,
886 fee_proportional_millionths: 0,
889 network.nodes.insert(node4.clone(), NodeInfo {
890 channels: vec!(NetworkMap::get_key(5, zero_hash.clone()), NetworkMap::get_key(11, zero_hash.clone())),
891 lowest_inbound_channel_fee_base_msat: 0,
892 lowest_inbound_channel_fee_proportional_millionths: 0,
893 features: GlobalFeatures::new(),
897 addresses: Vec::new(),
899 network.channels.insert(NetworkMap::get_key(5, zero_hash.clone()), ChannelInfo {
900 features: GlobalFeatures::new(),
901 one_to_two: DirectionalChannelInfo {
902 src_node_id: node3.clone(),
905 cltv_expiry_delta: (5 << 8) | 1,
906 htlc_minimum_msat: 0,
908 fee_proportional_millionths: 0,
909 }, two_to_one: DirectionalChannelInfo {
910 src_node_id: node4.clone(),
913 cltv_expiry_delta: (5 << 8) | 2,
914 htlc_minimum_msat: 0,
916 fee_proportional_millionths: 0,
919 network.nodes.insert(node5.clone(), NodeInfo {
920 channels: vec!(NetworkMap::get_key(6, zero_hash.clone()), NetworkMap::get_key(11, zero_hash.clone())),
921 lowest_inbound_channel_fee_base_msat: 0,
922 lowest_inbound_channel_fee_proportional_millionths: 0,
923 features: GlobalFeatures::new(),
927 addresses: Vec::new(),
929 network.channels.insert(NetworkMap::get_key(6, zero_hash.clone()), ChannelInfo {
930 features: GlobalFeatures::new(),
931 one_to_two: DirectionalChannelInfo {
932 src_node_id: node3.clone(),
935 cltv_expiry_delta: (6 << 8) | 1,
936 htlc_minimum_msat: 0,
938 fee_proportional_millionths: 0,
939 }, two_to_one: DirectionalChannelInfo {
940 src_node_id: node5.clone(),
943 cltv_expiry_delta: (6 << 8) | 2,
944 htlc_minimum_msat: 0,
946 fee_proportional_millionths: 0,
949 network.channels.insert(NetworkMap::get_key(11, zero_hash.clone()), ChannelInfo {
950 features: GlobalFeatures::new(),
951 one_to_two: DirectionalChannelInfo {
952 src_node_id: node5.clone(),
955 cltv_expiry_delta: (11 << 8) | 1,
956 htlc_minimum_msat: 0,
958 fee_proportional_millionths: 0,
959 }, two_to_one: DirectionalChannelInfo {
960 src_node_id: node4.clone(),
963 cltv_expiry_delta: (11 << 8) | 2,
964 htlc_minimum_msat: 0,
966 fee_proportional_millionths: 0,
969 network.nodes.insert(node6.clone(), NodeInfo {
970 channels: vec!(NetworkMap::get_key(7, zero_hash.clone())),
971 lowest_inbound_channel_fee_base_msat: 0,
972 lowest_inbound_channel_fee_proportional_millionths: 0,
973 features: GlobalFeatures::new(),
977 addresses: Vec::new(),
979 network.channels.insert(NetworkMap::get_key(7, zero_hash.clone()), ChannelInfo {
980 features: GlobalFeatures::new(),
981 one_to_two: DirectionalChannelInfo {
982 src_node_id: node3.clone(),
985 cltv_expiry_delta: (7 << 8) | 1,
986 htlc_minimum_msat: 0,
988 fee_proportional_millionths: 1000000,
989 }, two_to_one: DirectionalChannelInfo {
990 src_node_id: node6.clone(),
993 cltv_expiry_delta: (7 << 8) | 2,
994 htlc_minimum_msat: 0,
996 fee_proportional_millionths: 0,
1001 { // Simple route to 3 via 2
1002 let route = router.get_route(&node3, None, &Vec::new(), 100, 42).unwrap();
1003 assert_eq!(route.hops.len(), 2);
1005 assert_eq!(route.hops[0].pubkey, node2);
1006 assert_eq!(route.hops[0].short_channel_id, 2);
1007 assert_eq!(route.hops[0].fee_msat, 100);
1008 assert_eq!(route.hops[0].cltv_expiry_delta, (4 << 8) | 1);
1010 assert_eq!(route.hops[1].pubkey, node3);
1011 assert_eq!(route.hops[1].short_channel_id, 4);
1012 assert_eq!(route.hops[1].fee_msat, 100);
1013 assert_eq!(route.hops[1].cltv_expiry_delta, 42);
1016 { // Route to 1 via 2 and 3 because our channel to 1 is disabled
1017 let route = router.get_route(&node1, None, &Vec::new(), 100, 42).unwrap();
1018 assert_eq!(route.hops.len(), 3);
1020 assert_eq!(route.hops[0].pubkey, node2);
1021 assert_eq!(route.hops[0].short_channel_id, 2);
1022 assert_eq!(route.hops[0].fee_msat, 200);
1023 assert_eq!(route.hops[0].cltv_expiry_delta, (4 << 8) | 1);
1025 assert_eq!(route.hops[1].pubkey, node3);
1026 assert_eq!(route.hops[1].short_channel_id, 4);
1027 assert_eq!(route.hops[1].fee_msat, 100);
1028 assert_eq!(route.hops[1].cltv_expiry_delta, (3 << 8) | 2);
1030 assert_eq!(route.hops[2].pubkey, node1);
1031 assert_eq!(route.hops[2].short_channel_id, 3);
1032 assert_eq!(route.hops[2].fee_msat, 100);
1033 assert_eq!(route.hops[2].cltv_expiry_delta, 42);
1036 { // If we specify a channel to node8, that overrides our local channel view and that gets used
1037 let our_chans = vec![channelmanager::ChannelDetails {
1038 channel_id: [0; 32],
1039 short_channel_id: Some(42),
1040 remote_network_id: node8.clone(),
1041 channel_value_satoshis: 0,
1044 let route = router.get_route(&node3, Some(&our_chans), &Vec::new(), 100, 42).unwrap();
1045 assert_eq!(route.hops.len(), 2);
1047 assert_eq!(route.hops[0].pubkey, node8);
1048 assert_eq!(route.hops[0].short_channel_id, 42);
1049 assert_eq!(route.hops[0].fee_msat, 200);
1050 assert_eq!(route.hops[0].cltv_expiry_delta, (13 << 8) | 1);
1052 assert_eq!(route.hops[1].pubkey, node3);
1053 assert_eq!(route.hops[1].short_channel_id, 13);
1054 assert_eq!(route.hops[1].fee_msat, 100);
1055 assert_eq!(route.hops[1].cltv_expiry_delta, 42);
1058 let mut last_hops = vec!(RouteHint {
1059 src_node_id: node4.clone(),
1060 short_channel_id: 8,
1062 fee_proportional_millionths: 0,
1063 cltv_expiry_delta: (8 << 8) | 1,
1064 htlc_minimum_msat: 0,
1066 src_node_id: node5.clone(),
1067 short_channel_id: 9,
1068 fee_base_msat: 1001,
1069 fee_proportional_millionths: 0,
1070 cltv_expiry_delta: (9 << 8) | 1,
1071 htlc_minimum_msat: 0,
1073 src_node_id: node6.clone(),
1074 short_channel_id: 10,
1076 fee_proportional_millionths: 0,
1077 cltv_expiry_delta: (10 << 8) | 1,
1078 htlc_minimum_msat: 0,
1081 { // Simple test across 2, 3, 5, and 4 via a last_hop channel
1082 let route = router.get_route(&node7, None, &last_hops, 100, 42).unwrap();
1083 assert_eq!(route.hops.len(), 5);
1085 assert_eq!(route.hops[0].pubkey, node2);
1086 assert_eq!(route.hops[0].short_channel_id, 2);
1087 assert_eq!(route.hops[0].fee_msat, 100);
1088 assert_eq!(route.hops[0].cltv_expiry_delta, (4 << 8) | 1);
1090 assert_eq!(route.hops[1].pubkey, node3);
1091 assert_eq!(route.hops[1].short_channel_id, 4);
1092 assert_eq!(route.hops[1].fee_msat, 0);
1093 assert_eq!(route.hops[1].cltv_expiry_delta, (6 << 8) | 1);
1095 assert_eq!(route.hops[2].pubkey, node5);
1096 assert_eq!(route.hops[2].short_channel_id, 6);
1097 assert_eq!(route.hops[2].fee_msat, 0);
1098 assert_eq!(route.hops[2].cltv_expiry_delta, (11 << 8) | 1);
1100 assert_eq!(route.hops[3].pubkey, node4);
1101 assert_eq!(route.hops[3].short_channel_id, 11);
1102 assert_eq!(route.hops[3].fee_msat, 0);
1103 assert_eq!(route.hops[3].cltv_expiry_delta, (8 << 8) | 1);
1105 assert_eq!(route.hops[4].pubkey, node7);
1106 assert_eq!(route.hops[4].short_channel_id, 8);
1107 assert_eq!(route.hops[4].fee_msat, 100);
1108 assert_eq!(route.hops[4].cltv_expiry_delta, 42);
1111 { // Simple test with outbound channel to 4 to test that last_hops and first_hops connect
1112 let our_chans = vec![channelmanager::ChannelDetails {
1113 channel_id: [0; 32],
1114 short_channel_id: Some(42),
1115 remote_network_id: node4.clone(),
1116 channel_value_satoshis: 0,
1119 let route = router.get_route(&node7, Some(&our_chans), &last_hops, 100, 42).unwrap();
1120 assert_eq!(route.hops.len(), 2);
1122 assert_eq!(route.hops[0].pubkey, node4);
1123 assert_eq!(route.hops[0].short_channel_id, 42);
1124 assert_eq!(route.hops[0].fee_msat, 0);
1125 assert_eq!(route.hops[0].cltv_expiry_delta, (8 << 8) | 1);
1127 assert_eq!(route.hops[1].pubkey, node7);
1128 assert_eq!(route.hops[1].short_channel_id, 8);
1129 assert_eq!(route.hops[1].fee_msat, 100);
1130 assert_eq!(route.hops[1].cltv_expiry_delta, 42);
1133 last_hops[0].fee_base_msat = 1000;
1135 { // Revert to via 6 as the fee on 8 goes up
1136 let route = router.get_route(&node7, None, &last_hops, 100, 42).unwrap();
1137 assert_eq!(route.hops.len(), 4);
1139 assert_eq!(route.hops[0].pubkey, node2);
1140 assert_eq!(route.hops[0].short_channel_id, 2);
1141 assert_eq!(route.hops[0].fee_msat, 200); // fee increased as its % of value transferred across node
1142 assert_eq!(route.hops[0].cltv_expiry_delta, (4 << 8) | 1);
1144 assert_eq!(route.hops[1].pubkey, node3);
1145 assert_eq!(route.hops[1].short_channel_id, 4);
1146 assert_eq!(route.hops[1].fee_msat, 100);
1147 assert_eq!(route.hops[1].cltv_expiry_delta, (7 << 8) | 1);
1149 assert_eq!(route.hops[2].pubkey, node6);
1150 assert_eq!(route.hops[2].short_channel_id, 7);
1151 assert_eq!(route.hops[2].fee_msat, 0);
1152 assert_eq!(route.hops[2].cltv_expiry_delta, (10 << 8) | 1);
1154 assert_eq!(route.hops[3].pubkey, node7);
1155 assert_eq!(route.hops[3].short_channel_id, 10);
1156 assert_eq!(route.hops[3].fee_msat, 100);
1157 assert_eq!(route.hops[3].cltv_expiry_delta, 42);
1160 { // ...but still use 8 for larger payments as 6 has a variable feerate
1161 let route = router.get_route(&node7, None, &last_hops, 2000, 42).unwrap();
1162 assert_eq!(route.hops.len(), 5);
1164 assert_eq!(route.hops[0].pubkey, node2);
1165 assert_eq!(route.hops[0].short_channel_id, 2);
1166 assert_eq!(route.hops[0].fee_msat, 3000);
1167 assert_eq!(route.hops[0].cltv_expiry_delta, (4 << 8) | 1);
1169 assert_eq!(route.hops[1].pubkey, node3);
1170 assert_eq!(route.hops[1].short_channel_id, 4);
1171 assert_eq!(route.hops[1].fee_msat, 0);
1172 assert_eq!(route.hops[1].cltv_expiry_delta, (6 << 8) | 1);
1174 assert_eq!(route.hops[2].pubkey, node5);
1175 assert_eq!(route.hops[2].short_channel_id, 6);
1176 assert_eq!(route.hops[2].fee_msat, 0);
1177 assert_eq!(route.hops[2].cltv_expiry_delta, (11 << 8) | 1);
1179 assert_eq!(route.hops[3].pubkey, node4);
1180 assert_eq!(route.hops[3].short_channel_id, 11);
1181 assert_eq!(route.hops[3].fee_msat, 1000);
1182 assert_eq!(route.hops[3].cltv_expiry_delta, (8 << 8) | 1);
1184 assert_eq!(route.hops[4].pubkey, node7);
1185 assert_eq!(route.hops[4].short_channel_id, 8);
1186 assert_eq!(route.hops[4].fee_msat, 2000);
1187 assert_eq!(route.hops[4].cltv_expiry_delta, 42);