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 let mut network = self.network_map.write().unwrap();
176 match network.nodes.get_mut(&msg.contents.node_id) {
177 None => Err(HandleError{err: "No existing channels for node_announcement", action: Some(ErrorAction::IgnoreError)}),
179 if node.last_update >= msg.contents.timestamp {
180 return Err(HandleError{err: "Update older than last processed update", action: Some(ErrorAction::IgnoreError)});
183 node.features = msg.contents.features.clone();
184 node.last_update = msg.contents.timestamp;
185 node.rgb = msg.contents.rgb;
186 node.alias = msg.contents.alias;
187 node.addresses = msg.contents.addresses.clone();
193 fn handle_channel_announcement(&self, msg: &msgs::ChannelAnnouncement) -> Result<bool, HandleError> {
194 let msg_hash = Message::from_slice(&Sha256dHash::from_data(&msg.contents.encode()[..])[..]).unwrap();
195 secp_verify_sig!(self.secp_ctx, &msg_hash, &msg.node_signature_1, &msg.contents.node_id_1);
196 secp_verify_sig!(self.secp_ctx, &msg_hash, &msg.node_signature_2, &msg.contents.node_id_2);
197 secp_verify_sig!(self.secp_ctx, &msg_hash, &msg.bitcoin_signature_1, &msg.contents.bitcoin_key_1);
198 secp_verify_sig!(self.secp_ctx, &msg_hash, &msg.bitcoin_signature_2, &msg.contents.bitcoin_key_2);
200 //TODO: Call blockchain thing to ask if the short_channel_id is valid
201 //TODO: Only allow bitcoin chain_hash
203 if msg.contents.features.requires_unknown_bits() {
204 return Err(HandleError{err: "Channel announcement required unknown feature flags", action: None});
207 let mut network = self.network_map.write().unwrap();
209 match network.channels.entry(NetworkMap::get_key(msg.contents.short_channel_id, msg.contents.chain_hash)) {
210 Entry::Occupied(_) => {
211 //TODO: because asking the blockchain if short_channel_id is valid is only optional
212 //in the blockchain API, we need to handle it smartly here, though its unclear
214 return Err(HandleError{err: "Already have knowledge of channel", action: Some(ErrorAction::IgnoreError)})
216 Entry::Vacant(entry) => {
217 entry.insert(ChannelInfo {
218 features: msg.contents.features.clone(),
219 one_to_two: DirectionalChannelInfo {
220 src_node_id: msg.contents.node_id_1.clone(),
223 cltv_expiry_delta: u16::max_value(),
224 htlc_minimum_msat: u64::max_value(),
225 fee_base_msat: u32::max_value(),
226 fee_proportional_millionths: u32::max_value(),
228 two_to_one: DirectionalChannelInfo {
229 src_node_id: msg.contents.node_id_2.clone(),
232 cltv_expiry_delta: u16::max_value(),
233 htlc_minimum_msat: u64::max_value(),
234 fee_base_msat: u32::max_value(),
235 fee_proportional_millionths: u32::max_value(),
241 macro_rules! add_channel_to_node {
242 ( $node_id: expr ) => {
243 match network.nodes.entry($node_id) {
244 Entry::Occupied(node_entry) => {
245 node_entry.into_mut().channels.push(NetworkMap::get_key(msg.contents.short_channel_id, msg.contents.chain_hash));
247 Entry::Vacant(node_entry) => {
248 node_entry.insert(NodeInfo {
249 channels: vec!(NetworkMap::get_key(msg.contents.short_channel_id, msg.contents.chain_hash)),
250 lowest_inbound_channel_fee_base_msat: u32::max_value(),
251 lowest_inbound_channel_fee_proportional_millionths: u32::max_value(),
252 features: GlobalFeatures::new(),
256 addresses: Vec::new(),
263 add_channel_to_node!(msg.contents.node_id_1);
264 add_channel_to_node!(msg.contents.node_id_2);
266 Ok(msg.contents.excess_data.is_empty() && !msg.contents.features.supports_unknown_bits())
269 fn handle_htlc_fail_channel_update(&self, update: &msgs::HTLCFailChannelUpdate) {
271 &msgs::HTLCFailChannelUpdate::ChannelUpdateMessage { ref msg } => {
272 let _ = self.handle_channel_update(msg);
274 &msgs::HTLCFailChannelUpdate::ChannelClosed { ref short_channel_id } => {
275 let mut network = self.network_map.write().unwrap();
276 if let Some(chan) = network.channels.remove(short_channel_id) {
277 network.nodes.get_mut(&chan.one_to_two.src_node_id).unwrap().channels.retain(|chan_id| {
278 chan_id != NetworkMap::get_short_id(chan_id)
280 network.nodes.get_mut(&chan.two_to_one.src_node_id).unwrap().channels.retain(|chan_id| {
281 chan_id != NetworkMap::get_short_id(chan_id)
288 fn handle_channel_update(&self, msg: &msgs::ChannelUpdate) -> Result<(), HandleError> {
289 let mut network = self.network_map.write().unwrap();
291 let chan_enabled = msg.contents.flags & (1 << 1) != (1 << 1);
292 let chan_was_enabled;
294 match network.channels.get_mut(&NetworkMap::get_key(msg.contents.short_channel_id, msg.contents.chain_hash)) {
295 None => return Err(HandleError{err: "Couldn't find channel for update", action: Some(ErrorAction::IgnoreError)}),
297 macro_rules! maybe_update_channel_info {
298 ( $target: expr) => {
299 if $target.last_update >= msg.contents.timestamp {
300 return Err(HandleError{err: "Update older than last processed update", action: Some(ErrorAction::IgnoreError)});
302 chan_was_enabled = $target.enabled;
303 $target.last_update = msg.contents.timestamp;
304 $target.enabled = chan_enabled;
305 $target.cltv_expiry_delta = msg.contents.cltv_expiry_delta;
306 $target.htlc_minimum_msat = msg.contents.htlc_minimum_msat;
307 $target.fee_base_msat = msg.contents.fee_base_msat;
308 $target.fee_proportional_millionths = msg.contents.fee_proportional_millionths;
312 let msg_hash = Message::from_slice(&Sha256dHash::from_data(&msg.contents.encode()[..])[..]).unwrap();
313 if msg.contents.flags & 1 == 1 {
314 dest_node_id = channel.one_to_two.src_node_id.clone();
315 secp_verify_sig!(self.secp_ctx, &msg_hash, &msg.signature, &channel.two_to_one.src_node_id);
316 maybe_update_channel_info!(channel.two_to_one);
318 dest_node_id = channel.two_to_one.src_node_id.clone();
319 secp_verify_sig!(self.secp_ctx, &msg_hash, &msg.signature, &channel.one_to_two.src_node_id);
320 maybe_update_channel_info!(channel.one_to_two);
326 let node = network.nodes.get_mut(&dest_node_id).unwrap();
327 node.lowest_inbound_channel_fee_base_msat = cmp::min(node.lowest_inbound_channel_fee_base_msat, msg.contents.fee_base_msat);
328 node.lowest_inbound_channel_fee_proportional_millionths = cmp::min(node.lowest_inbound_channel_fee_proportional_millionths, msg.contents.fee_proportional_millionths);
329 } else if chan_was_enabled {
330 let mut lowest_inbound_channel_fee_base_msat = u32::max_value();
331 let mut lowest_inbound_channel_fee_proportional_millionths = u32::max_value();
334 let node = network.nodes.get(&dest_node_id).unwrap();
336 for chan_id in node.channels.iter() {
337 let chan = network.channels.get(chan_id).unwrap();
338 if chan.one_to_two.src_node_id == dest_node_id {
339 lowest_inbound_channel_fee_base_msat = cmp::min(lowest_inbound_channel_fee_base_msat, chan.two_to_one.fee_base_msat);
340 lowest_inbound_channel_fee_proportional_millionths = cmp::min(lowest_inbound_channel_fee_proportional_millionths, chan.two_to_one.fee_proportional_millionths);
342 lowest_inbound_channel_fee_base_msat = cmp::min(lowest_inbound_channel_fee_base_msat, chan.one_to_two.fee_base_msat);
343 lowest_inbound_channel_fee_proportional_millionths = cmp::min(lowest_inbound_channel_fee_proportional_millionths, chan.one_to_two.fee_proportional_millionths);
348 //TODO: satisfy the borrow-checker without a double-map-lookup :(
349 let mut_node = network.nodes.get_mut(&dest_node_id).unwrap();
350 mut_node.lowest_inbound_channel_fee_base_msat = lowest_inbound_channel_fee_base_msat;
351 mut_node.lowest_inbound_channel_fee_proportional_millionths = lowest_inbound_channel_fee_proportional_millionths;
358 #[derive(Eq, PartialEq)]
359 struct RouteGraphNode {
361 lowest_fee_to_peer_through_node: u64,
362 lowest_fee_to_node: u64,
365 impl cmp::Ord for RouteGraphNode {
366 fn cmp(&self, other: &RouteGraphNode) -> cmp::Ordering {
367 other.lowest_fee_to_peer_through_node.cmp(&self.lowest_fee_to_peer_through_node)
368 .then_with(|| other.pubkey.serialize().cmp(&self.pubkey.serialize()))
372 impl cmp::PartialOrd for RouteGraphNode {
373 fn partial_cmp(&self, other: &RouteGraphNode) -> Option<cmp::Ordering> {
374 Some(self.cmp(other))
378 struct DummyDirectionalChannelInfo {
379 src_node_id: PublicKey,
380 cltv_expiry_delta: u32,
381 htlc_minimum_msat: u64,
383 fee_proportional_millionths: u32,
387 pub fn new(our_pubkey: PublicKey, logger: Arc<Logger>) -> Router {
388 let mut nodes = HashMap::new();
389 nodes.insert(our_pubkey.clone(), NodeInfo {
390 channels: Vec::new(),
391 lowest_inbound_channel_fee_base_msat: u32::max_value(),
392 lowest_inbound_channel_fee_proportional_millionths: u32::max_value(),
393 features: GlobalFeatures::new(),
397 addresses: Vec::new(),
400 secp_ctx: Secp256k1::verification_only(),
401 network_map: RwLock::new(NetworkMap {
402 channels: HashMap::new(),
403 our_node_id: our_pubkey,
410 /// Dumps the entire network view of this Router to the logger provided in the constructor at
412 pub fn trace_state(&self) {
413 log_trace!(self, "{}", self.network_map.read().unwrap());
416 /// Get network addresses by node id
417 pub fn get_addresses(&self, pubkey: &PublicKey) -> Option<Vec<NetAddress>> {
418 let network = self.network_map.read().unwrap();
419 network.nodes.get(pubkey).map(|n| n.addresses.clone())
422 /// Marks a node as having failed a route. This will avoid re-using the node in routes for now,
423 /// with an expotnential decay in node "badness". Note that there is deliberately no
424 /// mark_channel_bad as a node may simply lie and suggest that an upstream channel from it is
425 /// what failed the route and not the node itself. Instead, setting the blamed_upstream_node
426 /// boolean will reduce the penalty, returning the node to usability faster. If the node is
427 /// behaving correctly, it will disable the failing channel and we will use it again next time.
428 pub fn mark_node_bad(&self, _node_id: &PublicKey, _blamed_upstream_node: bool) {
432 /// Gets a route from us to the given target node.
433 /// Extra routing hops between known nodes and the target will be used if they are included in
435 /// If some channels aren't announced, it may be useful to fill in a first_hops with the
436 /// results from a local ChannelManager::list_usable_channels() call. If it is filled in, our
437 /// (this Router's) view of our local channels will be ignored, and only those in first_hops
438 /// will be used. Panics if first_hops contains channels without short_channel_ids
439 /// (ChannelManager::list_usable_channels will never include such channels).
440 /// The fees on channels from us to next-hops are ignored (as they are assumed to all be
441 /// equal), however the enabled/disabled bit on such channels as well as the htlc_minimum_msat
442 /// *is* checked as they may change based on the receiving node.
443 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> {
444 // TODO: Obviously *only* using total fee cost sucks. We should consider weighting by
445 // uptime/success in using a node in the past.
446 let network = self.network_map.read().unwrap();
448 if *target == network.our_node_id {
449 return Err(HandleError{err: "Cannot generate a route to ourselves", action: None});
452 if final_value_msat > 21_000_000 * 1_0000_0000 * 1000 {
453 return Err(HandleError{err: "Cannot generate a route of more value than all existing satoshis", action: None});
456 // We do a dest-to-source Dijkstra's sorting by each node's distance from the destination
457 // plus the minimum per-HTLC fee to get from it to another node (aka "shitty A*").
458 // TODO: There are a few tweaks we could do, including possibly pre-calculating more stuff
459 // to use as the A* heuristic beyond just the cost to get one node further than the current
462 let dummy_directional_info = DummyDirectionalChannelInfo { // used for first_hops routes
463 src_node_id: network.our_node_id.clone(),
464 cltv_expiry_delta: 0,
465 htlc_minimum_msat: 0,
467 fee_proportional_millionths: 0,
470 let mut targets = BinaryHeap::new(); //TODO: Do we care about switching to eg Fibbonaci heap?
471 let mut dist = HashMap::with_capacity(network.nodes.len());
473 let mut first_hop_targets = HashMap::with_capacity(if first_hops.is_some() { first_hops.as_ref().unwrap().len() } else { 0 });
474 if let Some(hops) = first_hops {
476 let short_channel_id = chan.short_channel_id.expect("first_hops should be filled in with usable channels, not pending ones");
477 if chan.remote_network_id == *target {
479 hops: vec![RouteHop {
480 pubkey: chan.remote_network_id,
482 fee_msat: final_value_msat,
483 cltv_expiry_delta: final_cltv,
487 first_hop_targets.insert(chan.remote_network_id, short_channel_id);
489 if first_hop_targets.is_empty() {
490 return Err(HandleError{err: "Cannot route when there are no outbound routes away from us", action: None});
494 macro_rules! add_entry {
495 // Adds entry which goes from the node pointed to by $directional_info to
496 // $dest_node_id over the channel with id $chan_id with fees described in
497 // $directional_info.
498 ( $chan_id: expr, $dest_node_id: expr, $directional_info: expr, $starting_fee_msat: expr ) => {
499 //TODO: Explore simply adding fee to hit htlc_minimum_msat
500 if $starting_fee_msat as u64 + final_value_msat > $directional_info.htlc_minimum_msat {
501 let proportional_fee_millions = ($starting_fee_msat + final_value_msat).checked_mul($directional_info.fee_proportional_millionths as u64);
502 if let Some(new_fee) = proportional_fee_millions.and_then(|part| {
503 ($directional_info.fee_base_msat as u64).checked_add(part / 1000000) })
505 let mut total_fee = $starting_fee_msat as u64;
506 let hm_entry = dist.entry(&$directional_info.src_node_id);
507 let old_entry = hm_entry.or_insert_with(|| {
508 let node = network.nodes.get(&$directional_info.src_node_id).unwrap();
510 node.lowest_inbound_channel_fee_base_msat,
511 node.lowest_inbound_channel_fee_proportional_millionths,
513 pubkey: $dest_node_id.clone(),
516 cltv_expiry_delta: 0,
519 if $directional_info.src_node_id != network.our_node_id {
520 // Ignore new_fee for channel-from-us as we assume all channels-from-us
521 // will have the same effective-fee
522 total_fee += new_fee;
523 if let Some(fee_inc) = final_value_msat.checked_add(total_fee).and_then(|inc| { (old_entry.2 as u64).checked_mul(inc) }) {
524 total_fee += fee_inc / 1000000 + (old_entry.1 as u64);
526 // max_value means we'll always fail the old_entry.0 > total_fee check
527 total_fee = u64::max_value();
530 let new_graph_node = RouteGraphNode {
531 pubkey: $directional_info.src_node_id,
532 lowest_fee_to_peer_through_node: total_fee,
533 lowest_fee_to_node: $starting_fee_msat as u64 + new_fee,
535 if old_entry.0 > total_fee {
536 targets.push(new_graph_node);
537 old_entry.0 = total_fee;
538 old_entry.3 = RouteHop {
539 pubkey: $dest_node_id.clone(),
540 short_channel_id: $chan_id.clone(),
541 fee_msat: new_fee, // This field is ignored on the last-hop anyway
542 cltv_expiry_delta: $directional_info.cltv_expiry_delta as u32,
550 macro_rules! add_entries_to_cheapest_to_target_node {
551 ( $node: expr, $node_id: expr, $fee_to_target_msat: expr ) => {
552 if first_hops.is_some() {
553 if let Some(first_hop) = first_hop_targets.get(&$node_id) {
554 add_entry!(first_hop, $node_id, dummy_directional_info, $fee_to_target_msat);
558 for chan_id in $node.channels.iter() {
559 let chan = network.channels.get(chan_id).unwrap();
560 if chan.one_to_two.src_node_id == *$node_id {
561 // ie $node is one, ie next hop in A* is two, via the two_to_one channel
562 if first_hops.is_none() || chan.two_to_one.src_node_id != network.our_node_id {
563 if chan.two_to_one.enabled {
564 add_entry!(chan_id, chan.one_to_two.src_node_id, chan.two_to_one, $fee_to_target_msat);
568 if first_hops.is_none() || chan.one_to_two.src_node_id != network.our_node_id {
569 if chan.one_to_two.enabled {
570 add_entry!(chan_id, chan.two_to_one.src_node_id, chan.one_to_two, $fee_to_target_msat);
578 match network.nodes.get(target) {
581 add_entries_to_cheapest_to_target_node!(node, target, 0);
585 for hop in last_hops.iter() {
586 if first_hops.is_none() || hop.src_node_id != network.our_node_id { // first_hop overrules last_hops
587 if network.nodes.get(&hop.src_node_id).is_some() {
588 if first_hops.is_some() {
589 if let Some(first_hop) = first_hop_targets.get(&hop.src_node_id) {
590 add_entry!(first_hop, hop.src_node_id, dummy_directional_info, 0);
593 add_entry!(hop.short_channel_id, target, hop, 0);
598 while let Some(RouteGraphNode { pubkey, lowest_fee_to_node, .. }) = targets.pop() {
599 if pubkey == network.our_node_id {
600 let mut res = vec!(dist.remove(&network.our_node_id).unwrap().3);
601 while res.last().unwrap().pubkey != *target {
602 let new_entry = match dist.remove(&res.last().unwrap().pubkey) {
604 None => return Err(HandleError{err: "Failed to find a non-fee-overflowing path to the given destination", action: None}),
606 res.last_mut().unwrap().fee_msat = new_entry.fee_msat;
607 res.last_mut().unwrap().cltv_expiry_delta = new_entry.cltv_expiry_delta;
610 res.last_mut().unwrap().fee_msat = final_value_msat;
611 res.last_mut().unwrap().cltv_expiry_delta = final_cltv;
612 let route = Route { hops: res };
613 log_trace!(self, "Got route: {}", log_route!(route));
617 match network.nodes.get(&pubkey) {
620 add_entries_to_cheapest_to_target_node!(node, &pubkey, lowest_fee_to_node);
625 Err(HandleError{err: "Failed to find a path to the given destination", action: None})
631 use ln::channelmanager;
632 use ln::router::{Router,NodeInfo,NetworkMap,ChannelInfo,DirectionalChannelInfo,RouteHint};
633 use ln::msgs::GlobalFeatures;
634 use util::test_utils;
635 use util::logger::Logger;
637 use bitcoin::util::hash::Sha256dHash;
641 use secp256k1::key::{PublicKey,SecretKey};
642 use secp256k1::Secp256k1;
648 let secp_ctx = Secp256k1::new();
649 let our_id = PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&secp_ctx, &hex::decode("0101010101010101010101010101010101010101010101010101010101010101").unwrap()[..]).unwrap());
650 let logger: Arc<Logger> = Arc::new(test_utils::TestLogger::new());
651 let router = Router::new(our_id, Arc::clone(&logger));
653 // Build network from our_id to node8:
655 // -1(1)2- node1 -1(3)2-
657 // our_id -1(12)2- node8 -1(13)2--- node3
659 // -1(2)2- node2 -1(4)2-
662 // chan1 1-to-2: disabled
663 // chan1 2-to-1: enabled, 0 fee
665 // chan2 1-to-2: enabled, ignored fee
666 // chan2 2-to-1: enabled, 0 fee
668 // chan3 1-to-2: enabled, 0 fee
669 // chan3 2-to-1: enabled, 100 msat fee
671 // chan4 1-to-2: enabled, 100% fee
672 // chan4 2-to-1: enabled, 0 fee
674 // chan12 1-to-2: enabled, ignored fee
675 // chan12 2-to-1: enabled, 0 fee
677 // chan13 1-to-2: enabled, 200% fee
678 // chan13 2-to-1: enabled, 0 fee
681 // -1(5)2- node4 -1(8)2--
685 // node3--1(6)2- node5 -1(9)2--- node7 (not in global route map)
687 // -1(7)2- node6 -1(10)2-
689 // chan5 1-to-2: enabled, 100 msat fee
690 // chan5 2-to-1: enabled, 0 fee
692 // chan6 1-to-2: enabled, 0 fee
693 // chan6 2-to-1: enabled, 0 fee
695 // chan7 1-to-2: enabled, 100% fee
696 // chan7 2-to-1: enabled, 0 fee
698 // chan8 1-to-2: enabled, variable fee (0 then 1000 msat)
699 // chan8 2-to-1: enabled, 0 fee
701 // chan9 1-to-2: enabled, 1001 msat fee
702 // chan9 2-to-1: enabled, 0 fee
704 // chan10 1-to-2: enabled, 0 fee
705 // chan10 2-to-1: enabled, 0 fee
707 // chan11 1-to-2: enabled, 0 fee
708 // chan11 2-to-1: enabled, 0 fee
710 let node1 = PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&secp_ctx, &hex::decode("0202020202020202020202020202020202020202020202020202020202020202").unwrap()[..]).unwrap());
711 let node2 = PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&secp_ctx, &hex::decode("0303030303030303030303030303030303030303030303030303030303030303").unwrap()[..]).unwrap());
712 let node3 = PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&secp_ctx, &hex::decode("0404040404040404040404040404040404040404040404040404040404040404").unwrap()[..]).unwrap());
713 let node4 = PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&secp_ctx, &hex::decode("0505050505050505050505050505050505050505050505050505050505050505").unwrap()[..]).unwrap());
714 let node5 = PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&secp_ctx, &hex::decode("0606060606060606060606060606060606060606060606060606060606060606").unwrap()[..]).unwrap());
715 let node6 = PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&secp_ctx, &hex::decode("0707070707070707070707070707070707070707070707070707070707070707").unwrap()[..]).unwrap());
716 let node7 = PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&secp_ctx, &hex::decode("0808080808080808080808080808080808080808080808080808080808080808").unwrap()[..]).unwrap());
717 let node8 = PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&secp_ctx, &hex::decode("0909090909090909090909090909090909090909090909090909090909090909").unwrap()[..]).unwrap());
719 let zero_hash = Sha256dHash::from_data(&[0; 32]);
722 let mut network = router.network_map.write().unwrap();
724 network.nodes.insert(node1.clone(), NodeInfo {
725 channels: vec!(NetworkMap::get_key(1, zero_hash.clone()), NetworkMap::get_key(3, zero_hash.clone())),
726 lowest_inbound_channel_fee_base_msat: 100,
727 lowest_inbound_channel_fee_proportional_millionths: 0,
728 features: GlobalFeatures::new(),
732 addresses: Vec::new(),
734 network.channels.insert(NetworkMap::get_key(1, zero_hash.clone()), ChannelInfo {
735 features: GlobalFeatures::new(),
736 one_to_two: DirectionalChannelInfo {
737 src_node_id: our_id.clone(),
740 cltv_expiry_delta: u16::max_value(), // This value should be ignored
741 htlc_minimum_msat: 0,
742 fee_base_msat: u32::max_value(), // This value should be ignored
743 fee_proportional_millionths: u32::max_value(), // This value should be ignored
744 }, two_to_one: DirectionalChannelInfo {
745 src_node_id: node1.clone(),
748 cltv_expiry_delta: 0,
749 htlc_minimum_msat: 0,
751 fee_proportional_millionths: 0,
754 network.nodes.insert(node2.clone(), NodeInfo {
755 channels: vec!(NetworkMap::get_key(2, zero_hash.clone()), NetworkMap::get_key(4, zero_hash.clone())),
756 lowest_inbound_channel_fee_base_msat: 0,
757 lowest_inbound_channel_fee_proportional_millionths: 0,
758 features: GlobalFeatures::new(),
762 addresses: Vec::new(),
764 network.channels.insert(NetworkMap::get_key(2, zero_hash.clone()), ChannelInfo {
765 features: GlobalFeatures::new(),
766 one_to_two: DirectionalChannelInfo {
767 src_node_id: our_id.clone(),
770 cltv_expiry_delta: u16::max_value(), // This value should be ignored
771 htlc_minimum_msat: 0,
772 fee_base_msat: u32::max_value(), // This value should be ignored
773 fee_proportional_millionths: u32::max_value(), // This value should be ignored
774 }, two_to_one: DirectionalChannelInfo {
775 src_node_id: node2.clone(),
778 cltv_expiry_delta: 0,
779 htlc_minimum_msat: 0,
781 fee_proportional_millionths: 0,
784 network.nodes.insert(node8.clone(), NodeInfo {
785 channels: vec!(NetworkMap::get_key(12, zero_hash.clone()), NetworkMap::get_key(13, zero_hash.clone())),
786 lowest_inbound_channel_fee_base_msat: 0,
787 lowest_inbound_channel_fee_proportional_millionths: 0,
788 features: GlobalFeatures::new(),
792 addresses: Vec::new(),
794 network.channels.insert(NetworkMap::get_key(12, zero_hash.clone()), ChannelInfo {
795 features: GlobalFeatures::new(),
796 one_to_two: DirectionalChannelInfo {
797 src_node_id: our_id.clone(),
800 cltv_expiry_delta: u16::max_value(), // This value should be ignored
801 htlc_minimum_msat: 0,
802 fee_base_msat: u32::max_value(), // This value should be ignored
803 fee_proportional_millionths: u32::max_value(), // This value should be ignored
804 }, two_to_one: DirectionalChannelInfo {
805 src_node_id: node8.clone(),
808 cltv_expiry_delta: 0,
809 htlc_minimum_msat: 0,
811 fee_proportional_millionths: 0,
814 network.nodes.insert(node3.clone(), NodeInfo {
816 NetworkMap::get_key(3, zero_hash.clone()),
817 NetworkMap::get_key(4, zero_hash.clone()),
818 NetworkMap::get_key(13, zero_hash.clone()),
819 NetworkMap::get_key(5, zero_hash.clone()),
820 NetworkMap::get_key(6, zero_hash.clone()),
821 NetworkMap::get_key(7, zero_hash.clone())),
822 lowest_inbound_channel_fee_base_msat: 0,
823 lowest_inbound_channel_fee_proportional_millionths: 0,
824 features: GlobalFeatures::new(),
828 addresses: Vec::new(),
830 network.channels.insert(NetworkMap::get_key(3, zero_hash.clone()), ChannelInfo {
831 features: GlobalFeatures::new(),
832 one_to_two: DirectionalChannelInfo {
833 src_node_id: node1.clone(),
836 cltv_expiry_delta: (3 << 8) | 1,
837 htlc_minimum_msat: 0,
839 fee_proportional_millionths: 0,
840 }, two_to_one: DirectionalChannelInfo {
841 src_node_id: node3.clone(),
844 cltv_expiry_delta: (3 << 8) | 2,
845 htlc_minimum_msat: 0,
847 fee_proportional_millionths: 0,
850 network.channels.insert(NetworkMap::get_key(4, zero_hash.clone()), ChannelInfo {
851 features: GlobalFeatures::new(),
852 one_to_two: DirectionalChannelInfo {
853 src_node_id: node2.clone(),
856 cltv_expiry_delta: (4 << 8) | 1,
857 htlc_minimum_msat: 0,
859 fee_proportional_millionths: 1000000,
860 }, two_to_one: DirectionalChannelInfo {
861 src_node_id: node3.clone(),
864 cltv_expiry_delta: (4 << 8) | 2,
865 htlc_minimum_msat: 0,
867 fee_proportional_millionths: 0,
870 network.channels.insert(NetworkMap::get_key(13, zero_hash.clone()), ChannelInfo {
871 features: GlobalFeatures::new(),
872 one_to_two: DirectionalChannelInfo {
873 src_node_id: node8.clone(),
876 cltv_expiry_delta: (13 << 8) | 1,
877 htlc_minimum_msat: 0,
879 fee_proportional_millionths: 2000000,
880 }, two_to_one: DirectionalChannelInfo {
881 src_node_id: node3.clone(),
884 cltv_expiry_delta: (13 << 8) | 2,
885 htlc_minimum_msat: 0,
887 fee_proportional_millionths: 0,
890 network.nodes.insert(node4.clone(), NodeInfo {
891 channels: vec!(NetworkMap::get_key(5, zero_hash.clone()), NetworkMap::get_key(11, zero_hash.clone())),
892 lowest_inbound_channel_fee_base_msat: 0,
893 lowest_inbound_channel_fee_proportional_millionths: 0,
894 features: GlobalFeatures::new(),
898 addresses: Vec::new(),
900 network.channels.insert(NetworkMap::get_key(5, zero_hash.clone()), ChannelInfo {
901 features: GlobalFeatures::new(),
902 one_to_two: DirectionalChannelInfo {
903 src_node_id: node3.clone(),
906 cltv_expiry_delta: (5 << 8) | 1,
907 htlc_minimum_msat: 0,
909 fee_proportional_millionths: 0,
910 }, two_to_one: DirectionalChannelInfo {
911 src_node_id: node4.clone(),
914 cltv_expiry_delta: (5 << 8) | 2,
915 htlc_minimum_msat: 0,
917 fee_proportional_millionths: 0,
920 network.nodes.insert(node5.clone(), NodeInfo {
921 channels: vec!(NetworkMap::get_key(6, zero_hash.clone()), NetworkMap::get_key(11, zero_hash.clone())),
922 lowest_inbound_channel_fee_base_msat: 0,
923 lowest_inbound_channel_fee_proportional_millionths: 0,
924 features: GlobalFeatures::new(),
928 addresses: Vec::new(),
930 network.channels.insert(NetworkMap::get_key(6, zero_hash.clone()), ChannelInfo {
931 features: GlobalFeatures::new(),
932 one_to_two: DirectionalChannelInfo {
933 src_node_id: node3.clone(),
936 cltv_expiry_delta: (6 << 8) | 1,
937 htlc_minimum_msat: 0,
939 fee_proportional_millionths: 0,
940 }, two_to_one: DirectionalChannelInfo {
941 src_node_id: node5.clone(),
944 cltv_expiry_delta: (6 << 8) | 2,
945 htlc_minimum_msat: 0,
947 fee_proportional_millionths: 0,
950 network.channels.insert(NetworkMap::get_key(11, zero_hash.clone()), ChannelInfo {
951 features: GlobalFeatures::new(),
952 one_to_two: DirectionalChannelInfo {
953 src_node_id: node5.clone(),
956 cltv_expiry_delta: (11 << 8) | 1,
957 htlc_minimum_msat: 0,
959 fee_proportional_millionths: 0,
960 }, two_to_one: DirectionalChannelInfo {
961 src_node_id: node4.clone(),
964 cltv_expiry_delta: (11 << 8) | 2,
965 htlc_minimum_msat: 0,
967 fee_proportional_millionths: 0,
970 network.nodes.insert(node6.clone(), NodeInfo {
971 channels: vec!(NetworkMap::get_key(7, zero_hash.clone())),
972 lowest_inbound_channel_fee_base_msat: 0,
973 lowest_inbound_channel_fee_proportional_millionths: 0,
974 features: GlobalFeatures::new(),
978 addresses: Vec::new(),
980 network.channels.insert(NetworkMap::get_key(7, zero_hash.clone()), ChannelInfo {
981 features: GlobalFeatures::new(),
982 one_to_two: DirectionalChannelInfo {
983 src_node_id: node3.clone(),
986 cltv_expiry_delta: (7 << 8) | 1,
987 htlc_minimum_msat: 0,
989 fee_proportional_millionths: 1000000,
990 }, two_to_one: DirectionalChannelInfo {
991 src_node_id: node6.clone(),
994 cltv_expiry_delta: (7 << 8) | 2,
995 htlc_minimum_msat: 0,
997 fee_proportional_millionths: 0,
1002 { // Simple route to 3 via 2
1003 let route = router.get_route(&node3, None, &Vec::new(), 100, 42).unwrap();
1004 assert_eq!(route.hops.len(), 2);
1006 assert_eq!(route.hops[0].pubkey, node2);
1007 assert_eq!(route.hops[0].short_channel_id, 2);
1008 assert_eq!(route.hops[0].fee_msat, 100);
1009 assert_eq!(route.hops[0].cltv_expiry_delta, (4 << 8) | 1);
1011 assert_eq!(route.hops[1].pubkey, node3);
1012 assert_eq!(route.hops[1].short_channel_id, 4);
1013 assert_eq!(route.hops[1].fee_msat, 100);
1014 assert_eq!(route.hops[1].cltv_expiry_delta, 42);
1017 { // Route to 1 via 2 and 3 because our channel to 1 is disabled
1018 let route = router.get_route(&node1, None, &Vec::new(), 100, 42).unwrap();
1019 assert_eq!(route.hops.len(), 3);
1021 assert_eq!(route.hops[0].pubkey, node2);
1022 assert_eq!(route.hops[0].short_channel_id, 2);
1023 assert_eq!(route.hops[0].fee_msat, 200);
1024 assert_eq!(route.hops[0].cltv_expiry_delta, (4 << 8) | 1);
1026 assert_eq!(route.hops[1].pubkey, node3);
1027 assert_eq!(route.hops[1].short_channel_id, 4);
1028 assert_eq!(route.hops[1].fee_msat, 100);
1029 assert_eq!(route.hops[1].cltv_expiry_delta, (3 << 8) | 2);
1031 assert_eq!(route.hops[2].pubkey, node1);
1032 assert_eq!(route.hops[2].short_channel_id, 3);
1033 assert_eq!(route.hops[2].fee_msat, 100);
1034 assert_eq!(route.hops[2].cltv_expiry_delta, 42);
1037 { // If we specify a channel to node8, that overrides our local channel view and that gets used
1038 let our_chans = vec![channelmanager::ChannelDetails {
1039 channel_id: [0; 32],
1040 short_channel_id: Some(42),
1041 remote_network_id: node8.clone(),
1042 channel_value_satoshis: 0,
1045 let route = router.get_route(&node3, Some(&our_chans), &Vec::new(), 100, 42).unwrap();
1046 assert_eq!(route.hops.len(), 2);
1048 assert_eq!(route.hops[0].pubkey, node8);
1049 assert_eq!(route.hops[0].short_channel_id, 42);
1050 assert_eq!(route.hops[0].fee_msat, 200);
1051 assert_eq!(route.hops[0].cltv_expiry_delta, (13 << 8) | 1);
1053 assert_eq!(route.hops[1].pubkey, node3);
1054 assert_eq!(route.hops[1].short_channel_id, 13);
1055 assert_eq!(route.hops[1].fee_msat, 100);
1056 assert_eq!(route.hops[1].cltv_expiry_delta, 42);
1059 let mut last_hops = vec!(RouteHint {
1060 src_node_id: node4.clone(),
1061 short_channel_id: 8,
1063 fee_proportional_millionths: 0,
1064 cltv_expiry_delta: (8 << 8) | 1,
1065 htlc_minimum_msat: 0,
1067 src_node_id: node5.clone(),
1068 short_channel_id: 9,
1069 fee_base_msat: 1001,
1070 fee_proportional_millionths: 0,
1071 cltv_expiry_delta: (9 << 8) | 1,
1072 htlc_minimum_msat: 0,
1074 src_node_id: node6.clone(),
1075 short_channel_id: 10,
1077 fee_proportional_millionths: 0,
1078 cltv_expiry_delta: (10 << 8) | 1,
1079 htlc_minimum_msat: 0,
1082 { // Simple test across 2, 3, 5, and 4 via a last_hop channel
1083 let route = router.get_route(&node7, None, &last_hops, 100, 42).unwrap();
1084 assert_eq!(route.hops.len(), 5);
1086 assert_eq!(route.hops[0].pubkey, node2);
1087 assert_eq!(route.hops[0].short_channel_id, 2);
1088 assert_eq!(route.hops[0].fee_msat, 100);
1089 assert_eq!(route.hops[0].cltv_expiry_delta, (4 << 8) | 1);
1091 assert_eq!(route.hops[1].pubkey, node3);
1092 assert_eq!(route.hops[1].short_channel_id, 4);
1093 assert_eq!(route.hops[1].fee_msat, 0);
1094 assert_eq!(route.hops[1].cltv_expiry_delta, (6 << 8) | 1);
1096 assert_eq!(route.hops[2].pubkey, node5);
1097 assert_eq!(route.hops[2].short_channel_id, 6);
1098 assert_eq!(route.hops[2].fee_msat, 0);
1099 assert_eq!(route.hops[2].cltv_expiry_delta, (11 << 8) | 1);
1101 assert_eq!(route.hops[3].pubkey, node4);
1102 assert_eq!(route.hops[3].short_channel_id, 11);
1103 assert_eq!(route.hops[3].fee_msat, 0);
1104 assert_eq!(route.hops[3].cltv_expiry_delta, (8 << 8) | 1);
1106 assert_eq!(route.hops[4].pubkey, node7);
1107 assert_eq!(route.hops[4].short_channel_id, 8);
1108 assert_eq!(route.hops[4].fee_msat, 100);
1109 assert_eq!(route.hops[4].cltv_expiry_delta, 42);
1112 { // Simple test with outbound channel to 4 to test that last_hops and first_hops connect
1113 let our_chans = vec![channelmanager::ChannelDetails {
1114 channel_id: [0; 32],
1115 short_channel_id: Some(42),
1116 remote_network_id: node4.clone(),
1117 channel_value_satoshis: 0,
1120 let route = router.get_route(&node7, Some(&our_chans), &last_hops, 100, 42).unwrap();
1121 assert_eq!(route.hops.len(), 2);
1123 assert_eq!(route.hops[0].pubkey, node4);
1124 assert_eq!(route.hops[0].short_channel_id, 42);
1125 assert_eq!(route.hops[0].fee_msat, 0);
1126 assert_eq!(route.hops[0].cltv_expiry_delta, (8 << 8) | 1);
1128 assert_eq!(route.hops[1].pubkey, node7);
1129 assert_eq!(route.hops[1].short_channel_id, 8);
1130 assert_eq!(route.hops[1].fee_msat, 100);
1131 assert_eq!(route.hops[1].cltv_expiry_delta, 42);
1134 last_hops[0].fee_base_msat = 1000;
1136 { // Revert to via 6 as the fee on 8 goes up
1137 let route = router.get_route(&node7, None, &last_hops, 100, 42).unwrap();
1138 assert_eq!(route.hops.len(), 4);
1140 assert_eq!(route.hops[0].pubkey, node2);
1141 assert_eq!(route.hops[0].short_channel_id, 2);
1142 assert_eq!(route.hops[0].fee_msat, 200); // fee increased as its % of value transferred across node
1143 assert_eq!(route.hops[0].cltv_expiry_delta, (4 << 8) | 1);
1145 assert_eq!(route.hops[1].pubkey, node3);
1146 assert_eq!(route.hops[1].short_channel_id, 4);
1147 assert_eq!(route.hops[1].fee_msat, 100);
1148 assert_eq!(route.hops[1].cltv_expiry_delta, (7 << 8) | 1);
1150 assert_eq!(route.hops[2].pubkey, node6);
1151 assert_eq!(route.hops[2].short_channel_id, 7);
1152 assert_eq!(route.hops[2].fee_msat, 0);
1153 assert_eq!(route.hops[2].cltv_expiry_delta, (10 << 8) | 1);
1155 assert_eq!(route.hops[3].pubkey, node7);
1156 assert_eq!(route.hops[3].short_channel_id, 10);
1157 assert_eq!(route.hops[3].fee_msat, 100);
1158 assert_eq!(route.hops[3].cltv_expiry_delta, 42);
1161 { // ...but still use 8 for larger payments as 6 has a variable feerate
1162 let route = router.get_route(&node7, None, &last_hops, 2000, 42).unwrap();
1163 assert_eq!(route.hops.len(), 5);
1165 assert_eq!(route.hops[0].pubkey, node2);
1166 assert_eq!(route.hops[0].short_channel_id, 2);
1167 assert_eq!(route.hops[0].fee_msat, 3000);
1168 assert_eq!(route.hops[0].cltv_expiry_delta, (4 << 8) | 1);
1170 assert_eq!(route.hops[1].pubkey, node3);
1171 assert_eq!(route.hops[1].short_channel_id, 4);
1172 assert_eq!(route.hops[1].fee_msat, 0);
1173 assert_eq!(route.hops[1].cltv_expiry_delta, (6 << 8) | 1);
1175 assert_eq!(route.hops[2].pubkey, node5);
1176 assert_eq!(route.hops[2].short_channel_id, 6);
1177 assert_eq!(route.hops[2].fee_msat, 0);
1178 assert_eq!(route.hops[2].cltv_expiry_delta, (11 << 8) | 1);
1180 assert_eq!(route.hops[3].pubkey, node4);
1181 assert_eq!(route.hops[3].short_channel_id, 11);
1182 assert_eq!(route.hops[3].fee_msat, 1000);
1183 assert_eq!(route.hops[3].cltv_expiry_delta, (8 << 8) | 1);
1185 assert_eq!(route.hops[4].pubkey, node7);
1186 assert_eq!(route.hops[4].short_channel_id, 8);
1187 assert_eq!(route.hops[4].fee_msat, 2000);
1188 assert_eq!(route.hops[4].cltv_expiry_delta, 42);