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};
11 use std::sync::RwLock;
12 use std::collections::{HashMap,BinaryHeap};
13 use std::collections::hash_map::Entry;
18 pub pubkey: PublicKey,
19 /// The channel that should be used from the previous hop to reach this node.
20 pub short_channel_id: u64,
21 /// The fee taken on this hop. For the last hop, this should be the full value of the payment.
23 /// The CLTV delta added for this hop. For the last hop, this should be the full CLTV value
24 /// expected at the destination, in excess of the current block height.
25 pub cltv_expiry_delta: u32,
28 /// A route from us through the network to a destination
31 /// The list of hops, NOT INCLUDING our own, where the last hop is the destination. Thus, this
32 /// must always be at least length one. By protocol rules, this may not currently exceed 20 in
34 pub hops: Vec<RouteHop>,
37 struct DirectionalChannelInfo {
38 src_node_id: PublicKey,
41 cltv_expiry_delta: u16,
42 htlc_minimum_msat: u64,
44 fee_proportional_millionths: u32,
48 features: GlobalFeatures,
49 one_to_two: DirectionalChannelInfo,
50 two_to_one: DirectionalChannelInfo,
54 #[cfg(feature = "non_bitcoin_chain_hash_routing")]
55 channels: Vec<(u64, Sha256dHash)>,
56 #[cfg(not(feature = "non_bitcoin_chain_hash_routing"))]
59 lowest_inbound_channel_fee_base_msat: u32,
60 lowest_inbound_channel_fee_proportional_millionths: u32,
62 features: GlobalFeatures,
66 addresses: Vec<NetAddress>,
70 #[cfg(feature = "non_bitcoin_chain_hash_routing")]
71 channels: HashMap<(u64, Sha256dHash), ChannelInfo>,
72 #[cfg(not(feature = "non_bitcoin_chain_hash_routing"))]
73 channels: HashMap<u64, ChannelInfo>,
75 our_node_id: PublicKey,
76 nodes: HashMap<PublicKey, NodeInfo>,
80 #[cfg(feature = "non_bitcoin_chain_hash_routing")]
82 fn get_key(short_channel_id: u64, chain_hash: Sha256dHash) -> (u64, Sha256dHash) {
83 (short_channel_id, chain_hash)
86 #[cfg(not(feature = "non_bitcoin_chain_hash_routing"))]
88 fn get_key(short_channel_id: u64, _: Sha256dHash) -> u64 {
93 /// A channel descriptor which provides a last-hop route to get_route
94 pub struct RouteHint {
95 pub src_node_id: PublicKey,
96 pub short_channel_id: u64,
97 pub fee_base_msat: u64,
98 pub fee_proportional_millionths: u32,
99 pub cltv_expiry_delta: u16,
100 pub htlc_minimum_msat: u64,
103 /// Tracks a view of the network, receiving updates from peers and generating Routes to
104 /// payment destinations.
107 network_map: RwLock<NetworkMap>,
110 macro_rules! secp_verify_sig {
111 ( $secp_ctx: expr, $msg: expr, $sig: expr, $pubkey: expr ) => {
112 match $secp_ctx.verify($msg, $sig, $pubkey) {
114 Err(_) => return Err(HandleError{err: "Invalid signature from remote node", action: None}),
119 impl RoutingMessageHandler for Router {
120 fn handle_node_announcement(&self, msg: &msgs::NodeAnnouncement) -> Result<(), HandleError> {
121 let msg_hash = Message::from_slice(&Sha256dHash::from_data(&msg.contents.encode()[..])[..]).unwrap();
122 secp_verify_sig!(self.secp_ctx, &msg_hash, &msg.signature, &msg.contents.node_id);
124 let mut network = self.network_map.write().unwrap();
125 match network.nodes.get_mut(&msg.contents.node_id) {
126 None => Err(HandleError{err: "No existing channels for node_announcement", action: Some(ErrorAction::IgnoreError)}),
128 if node.last_update >= msg.contents.timestamp {
129 return Err(HandleError{err: "Update older than last processed update", action: Some(ErrorAction::IgnoreError)});
132 node.features = msg.contents.features.clone();
133 node.last_update = msg.contents.timestamp;
134 node.rgb = msg.contents.rgb;
135 node.alias = msg.contents.alias;
136 node.addresses = msg.contents.addresses.clone();
142 fn handle_channel_announcement(&self, msg: &msgs::ChannelAnnouncement) -> Result<bool, HandleError> {
143 let msg_hash = Message::from_slice(&Sha256dHash::from_data(&msg.contents.encode()[..])[..]).unwrap();
144 secp_verify_sig!(self.secp_ctx, &msg_hash, &msg.node_signature_1, &msg.contents.node_id_1);
145 secp_verify_sig!(self.secp_ctx, &msg_hash, &msg.node_signature_2, &msg.contents.node_id_2);
146 secp_verify_sig!(self.secp_ctx, &msg_hash, &msg.bitcoin_signature_1, &msg.contents.bitcoin_key_1);
147 secp_verify_sig!(self.secp_ctx, &msg_hash, &msg.bitcoin_signature_2, &msg.contents.bitcoin_key_2);
149 //TODO: Call blockchain thing to ask if the short_channel_id is valid
150 //TODO: Only allow bitcoin chain_hash
152 if msg.contents.features.requires_unknown_bits() {
153 return Err(HandleError{err: "Channel announcement required unknown feature flags", action: None});
156 let mut network = self.network_map.write().unwrap();
158 match network.channels.entry(NetworkMap::get_key(msg.contents.short_channel_id, msg.contents.chain_hash)) {
159 Entry::Occupied(_) => {
160 //TODO: because asking the blockchain if short_channel_id is valid is only optional
161 //in the blockchain API, we need to handle it smartly here, though its unclear
163 return Err(HandleError{err: "Already have knowledge of channel", action: Some(ErrorAction::IgnoreError)})
165 Entry::Vacant(entry) => {
166 entry.insert(ChannelInfo {
167 features: msg.contents.features.clone(),
168 one_to_two: DirectionalChannelInfo {
169 src_node_id: msg.contents.node_id_1.clone(),
172 cltv_expiry_delta: u16::max_value(),
173 htlc_minimum_msat: u64::max_value(),
174 fee_base_msat: u32::max_value(),
175 fee_proportional_millionths: u32::max_value(),
177 two_to_one: DirectionalChannelInfo {
178 src_node_id: msg.contents.node_id_2.clone(),
181 cltv_expiry_delta: u16::max_value(),
182 htlc_minimum_msat: u64::max_value(),
183 fee_base_msat: u32::max_value(),
184 fee_proportional_millionths: u32::max_value(),
190 macro_rules! add_channel_to_node {
191 ( $node_id: expr ) => {
192 match network.nodes.entry($node_id) {
193 Entry::Occupied(node_entry) => {
194 node_entry.into_mut().channels.push(NetworkMap::get_key(msg.contents.short_channel_id, msg.contents.chain_hash));
196 Entry::Vacant(node_entry) => {
197 node_entry.insert(NodeInfo {
198 channels: vec!(NetworkMap::get_key(msg.contents.short_channel_id, msg.contents.chain_hash)),
199 lowest_inbound_channel_fee_base_msat: u32::max_value(),
200 lowest_inbound_channel_fee_proportional_millionths: u32::max_value(),
201 features: GlobalFeatures::new(),
205 addresses: Vec::new(),
212 add_channel_to_node!(msg.contents.node_id_1);
213 add_channel_to_node!(msg.contents.node_id_2);
215 Ok(!msg.contents.features.supports_unknown_bits())
218 fn handle_htlc_fail_channel_update(&self, update: &msgs::HTLCFailChannelUpdate) {
220 &msgs::HTLCFailChannelUpdate::ChannelUpdateMessage { ref msg } => {
221 let _ = self.handle_channel_update(msg);
223 &msgs::HTLCFailChannelUpdate::ChannelClosed { ref short_channel_id } => {
224 let mut network = self.network_map.write().unwrap();
225 network.channels.remove(short_channel_id);
230 fn handle_channel_update(&self, msg: &msgs::ChannelUpdate) -> Result<(), HandleError> {
231 let mut network = self.network_map.write().unwrap();
233 let chan_enabled = msg.contents.flags & (1 << 1) != (1 << 1);
234 let chan_was_enabled;
236 match network.channels.get_mut(&NetworkMap::get_key(msg.contents.short_channel_id, msg.contents.chain_hash)) {
237 None => return Err(HandleError{err: "Couldn't find channel for update", action: Some(ErrorAction::IgnoreError)}),
239 macro_rules! maybe_update_channel_info {
240 ( $target: expr) => {
241 if $target.last_update >= msg.contents.timestamp {
242 return Err(HandleError{err: "Update older than last processed update", action: Some(ErrorAction::IgnoreError)});
244 chan_was_enabled = $target.enabled;
245 $target.last_update = msg.contents.timestamp;
246 $target.enabled = chan_enabled;
247 $target.cltv_expiry_delta = msg.contents.cltv_expiry_delta;
248 $target.htlc_minimum_msat = msg.contents.htlc_minimum_msat;
249 $target.fee_base_msat = msg.contents.fee_base_msat;
250 $target.fee_proportional_millionths = msg.contents.fee_proportional_millionths;
254 let msg_hash = Message::from_slice(&Sha256dHash::from_data(&msg.contents.encode()[..])[..]).unwrap();
255 if msg.contents.flags & 1 == 1 {
256 dest_node_id = channel.one_to_two.src_node_id.clone();
257 secp_verify_sig!(self.secp_ctx, &msg_hash, &msg.signature, &channel.two_to_one.src_node_id);
258 maybe_update_channel_info!(channel.two_to_one);
260 dest_node_id = channel.two_to_one.src_node_id.clone();
261 secp_verify_sig!(self.secp_ctx, &msg_hash, &msg.signature, &channel.one_to_two.src_node_id);
262 maybe_update_channel_info!(channel.one_to_two);
268 let node = network.nodes.get_mut(&dest_node_id).unwrap();
269 node.lowest_inbound_channel_fee_base_msat = cmp::min(node.lowest_inbound_channel_fee_base_msat, msg.contents.fee_base_msat);
270 node.lowest_inbound_channel_fee_proportional_millionths = cmp::min(node.lowest_inbound_channel_fee_proportional_millionths, msg.contents.fee_proportional_millionths);
271 } else if chan_was_enabled {
272 let mut lowest_inbound_channel_fee_base_msat = u32::max_value();
273 let mut lowest_inbound_channel_fee_proportional_millionths = u32::max_value();
276 let node = network.nodes.get(&dest_node_id).unwrap();
278 for chan_id in node.channels.iter() {
279 let chan = network.channels.get(chan_id).unwrap();
280 if chan.one_to_two.src_node_id == dest_node_id {
281 lowest_inbound_channel_fee_base_msat = cmp::min(lowest_inbound_channel_fee_base_msat, chan.two_to_one.fee_base_msat);
282 lowest_inbound_channel_fee_proportional_millionths = cmp::min(lowest_inbound_channel_fee_proportional_millionths, chan.two_to_one.fee_proportional_millionths);
284 lowest_inbound_channel_fee_base_msat = cmp::min(lowest_inbound_channel_fee_base_msat, chan.one_to_two.fee_base_msat);
285 lowest_inbound_channel_fee_proportional_millionths = cmp::min(lowest_inbound_channel_fee_proportional_millionths, chan.one_to_two.fee_proportional_millionths);
290 //TODO: satisfy the borrow-checker without a double-map-lookup :(
291 let mut_node = network.nodes.get_mut(&dest_node_id).unwrap();
292 mut_node.lowest_inbound_channel_fee_base_msat = lowest_inbound_channel_fee_base_msat;
293 mut_node.lowest_inbound_channel_fee_proportional_millionths = lowest_inbound_channel_fee_proportional_millionths;
300 #[derive(Eq, PartialEq)]
301 struct RouteGraphNode {
303 lowest_fee_to_peer_through_node: u64,
306 impl cmp::Ord for RouteGraphNode {
307 fn cmp(&self, other: &RouteGraphNode) -> cmp::Ordering {
308 other.lowest_fee_to_peer_through_node.cmp(&self.lowest_fee_to_peer_through_node)
309 .then_with(|| other.pubkey.serialize().cmp(&self.pubkey.serialize()))
313 impl cmp::PartialOrd for RouteGraphNode {
314 fn partial_cmp(&self, other: &RouteGraphNode) -> Option<cmp::Ordering> {
315 Some(self.cmp(other))
319 struct DummyDirectionalChannelInfo {
320 src_node_id: PublicKey,
321 cltv_expiry_delta: u32,
322 htlc_minimum_msat: u64,
324 fee_proportional_millionths: u32,
328 pub fn new(our_pubkey: PublicKey) -> Router {
329 let mut nodes = HashMap::new();
330 nodes.insert(our_pubkey.clone(), NodeInfo {
331 channels: Vec::new(),
332 lowest_inbound_channel_fee_base_msat: u32::max_value(),
333 lowest_inbound_channel_fee_proportional_millionths: u32::max_value(),
334 features: GlobalFeatures::new(),
338 addresses: Vec::new(),
341 secp_ctx: Secp256k1::new(),
342 network_map: RwLock::new(NetworkMap {
343 channels: HashMap::new(),
344 our_node_id: our_pubkey,
350 /// Get network addresses by node id
351 pub fn get_addresses(&self, pubkey: &PublicKey) -> Option<Vec<NetAddress>> {
352 let network = self.network_map.read().unwrap();
353 network.nodes.get(pubkey).map(|n| n.addresses.clone())
356 /// Marks a node as having failed a route. This will avoid re-using the node in routes for now,
357 /// with an expotnential decay in node "badness". Note that there is deliberately no
358 /// mark_channel_bad as a node may simply lie and suggest that an upstream channel from it is
359 /// what failed the route and not the node itself. Instead, setting the blamed_upstream_node
360 /// boolean will reduce the penalty, returning the node to usability faster. If the node is
361 /// behaving correctly, it will disable the failing channel and we will use it again next time.
362 pub fn mark_node_bad(&self, _node_id: &PublicKey, _blamed_upstream_node: bool) {
366 /// Gets a route from us to the given target node.
367 /// Extra routing hops between known nodes and the target will be used if they are included in
369 /// If some channels aren't announced, it may be useful to fill in a first_hops with the
370 /// results from a local ChannelManager::list_usable_channels() call. If it is filled in, our
371 /// (this Router's) view of our local channels will be ignored, and only those in first_hops
372 /// will be used. Panics if first_hops contains channels without short_channel_ids
373 /// (ChannelManager::list_usable_channels will never include such channels).
374 /// The fees on channels from us to next-hops are ignored (as they are assumed to all be
375 /// equal), however the enabled/disabled bit on such channels as well as the htlc_minimum_msat
376 /// *is* checked as they may change based on the receiving node.
377 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> {
378 // TODO: Obviously *only* using total fee cost sucks. We should consider weighting by
379 // uptime/success in using a node in the past.
380 let network = self.network_map.read().unwrap();
382 if *target == network.our_node_id {
383 return Err(HandleError{err: "Cannot generate a route to ourselves", action: None});
386 // We do a dest-to-source Dijkstra's sorting by each node's distance from the destination
387 // plus the minimum per-HTLC fee to get from it to another node (aka "shitty A*").
388 // TODO: There are a few tweaks we could do, including possibly pre-calculating more stuff
389 // to use as the A* heuristic beyond just the cost to get one node further than the current
392 let dummy_directional_info = DummyDirectionalChannelInfo { // used for first_hops routes
393 src_node_id: network.our_node_id.clone(),
394 cltv_expiry_delta: 0,
395 htlc_minimum_msat: 0,
397 fee_proportional_millionths: 0,
400 let mut targets = BinaryHeap::new(); //TODO: Do we care about switching to eg Fibbonaci heap?
401 let mut dist = HashMap::with_capacity(network.nodes.len());
403 let mut first_hop_targets = HashMap::with_capacity(if first_hops.is_some() { first_hops.as_ref().unwrap().len() } else { 0 });
404 if let Some(hops) = first_hops {
406 let short_channel_id = chan.short_channel_id.expect("first_hops should be filled in with usable channels, not pending ones");
407 if chan.remote_network_id == *target {
409 hops: vec![RouteHop {
410 pubkey: chan.remote_network_id,
412 fee_msat: final_value_msat,
413 cltv_expiry_delta: final_cltv,
417 first_hop_targets.insert(chan.remote_network_id, short_channel_id);
419 if first_hop_targets.is_empty() {
420 return Err(HandleError{err: "Cannot route when there are no outbound routes away from us", action: None});
424 macro_rules! add_entry {
425 // Adds entry which goes from the node pointed to by $directional_info to
426 // $dest_node_id over the channel with id $chan_id with fees described in
427 // $directional_info.
428 ( $chan_id: expr, $dest_node_id: expr, $directional_info: expr, $starting_fee_msat: expr ) => {
429 //TODO: Explore simply adding fee to hit htlc_minimum_msat
430 if $starting_fee_msat as u64 + final_value_msat > $directional_info.htlc_minimum_msat {
431 let proportional_fee_millions = ($starting_fee_msat + final_value_msat).checked_mul($directional_info.fee_proportional_millionths as u64);
432 if let Some(new_fee) = proportional_fee_millions.and_then(|part| {
433 ($directional_info.fee_base_msat as u64).checked_add(part / 1000000) })
435 let mut total_fee = $starting_fee_msat as u64;
436 let mut hm_entry = dist.entry(&$directional_info.src_node_id);
437 let old_entry = hm_entry.or_insert_with(|| {
438 let node = network.nodes.get(&$directional_info.src_node_id).unwrap();
440 node.lowest_inbound_channel_fee_base_msat as u64,
441 node.lowest_inbound_channel_fee_proportional_millionths as u64,
443 pubkey: PublicKey::new(),
446 cltv_expiry_delta: 0,
449 if $directional_info.src_node_id != network.our_node_id {
450 // Ignore new_fee for channel-from-us as we assume all channels-from-us
451 // will have the same effective-fee
452 total_fee += new_fee;
453 total_fee += old_entry.2 * (final_value_msat + total_fee) / 1000000 + old_entry.1;
455 let new_graph_node = RouteGraphNode {
456 pubkey: $directional_info.src_node_id,
457 lowest_fee_to_peer_through_node: total_fee,
459 if old_entry.0 > total_fee {
460 targets.push(new_graph_node);
461 old_entry.0 = total_fee;
462 old_entry.3 = RouteHop {
463 pubkey: $dest_node_id.clone(),
464 short_channel_id: $chan_id.clone(),
465 fee_msat: new_fee, // This field is ignored on the last-hop anyway
466 cltv_expiry_delta: $directional_info.cltv_expiry_delta as u32,
474 macro_rules! add_entries_to_cheapest_to_target_node {
475 ( $node: expr, $node_id: expr, $fee_to_target_msat: expr ) => {
476 if first_hops.is_some() {
477 if let Some(first_hop) = first_hop_targets.get(&$node_id) {
478 add_entry!(first_hop, $node_id, dummy_directional_info, $fee_to_target_msat);
482 for chan_id in $node.channels.iter() {
483 let chan = network.channels.get(chan_id).unwrap();
484 if chan.one_to_two.src_node_id == *$node_id {
485 // ie $node is one, ie next hop in A* is two, via the two_to_one channel
486 if first_hops.is_none() || chan.two_to_one.src_node_id != network.our_node_id {
487 if chan.two_to_one.enabled {
488 add_entry!(chan_id, chan.one_to_two.src_node_id, chan.two_to_one, $fee_to_target_msat);
492 if first_hops.is_none() || chan.one_to_two.src_node_id != network.our_node_id {
493 if chan.one_to_two.enabled {
494 add_entry!(chan_id, chan.two_to_one.src_node_id, chan.one_to_two, $fee_to_target_msat);
502 match network.nodes.get(target) {
505 add_entries_to_cheapest_to_target_node!(node, target, 0);
509 for hop in last_hops.iter() {
510 if first_hops.is_none() || hop.src_node_id != network.our_node_id { // first_hop overrules last_hops
511 if network.nodes.get(&hop.src_node_id).is_some() {
512 if first_hops.is_some() {
513 if let Some(first_hop) = first_hop_targets.get(&hop.src_node_id) {
514 add_entry!(first_hop, hop.src_node_id, dummy_directional_info, 0);
517 add_entry!(hop.short_channel_id, target, hop, 0);
522 while let Some(RouteGraphNode { pubkey, lowest_fee_to_peer_through_node }) = targets.pop() {
523 if pubkey == network.our_node_id {
524 let mut res = vec!(dist.remove(&network.our_node_id).unwrap().3);
525 while res.last().unwrap().pubkey != *target {
526 let new_entry = dist.remove(&res.last().unwrap().pubkey).unwrap().3;
527 res.last_mut().unwrap().fee_msat = new_entry.fee_msat;
528 res.last_mut().unwrap().cltv_expiry_delta = new_entry.cltv_expiry_delta;
531 res.last_mut().unwrap().fee_msat = final_value_msat;
532 res.last_mut().unwrap().cltv_expiry_delta = final_cltv;
538 match network.nodes.get(&pubkey) {
541 let mut fee = lowest_fee_to_peer_through_node - node.lowest_inbound_channel_fee_base_msat as u64;
542 fee -= node.lowest_inbound_channel_fee_proportional_millionths as u64 * (fee + final_value_msat) / 1000000;
543 add_entries_to_cheapest_to_target_node!(node, &pubkey, fee);
548 Err(HandleError{err: "Failed to find a path to the given destination", action: None})
554 use ln::channelmanager;
555 use ln::router::{Router,NodeInfo,NetworkMap,ChannelInfo,DirectionalChannelInfo,RouteHint};
556 use ln::msgs::GlobalFeatures;
558 use bitcoin::util::misc::hex_bytes;
559 use bitcoin::util::hash::Sha256dHash;
561 use secp256k1::key::{PublicKey,SecretKey};
562 use secp256k1::Secp256k1;
566 let secp_ctx = Secp256k1::new();
567 let our_id = PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&secp_ctx, &hex_bytes("0101010101010101010101010101010101010101010101010101010101010101").unwrap()[..]).unwrap()).unwrap();
568 let router = Router::new(our_id);
570 // Build network from our_id to node8:
572 // -1(1)2- node1 -1(3)2-
574 // our_id -1(12)2- node8 -1(13)2--- node3
576 // -1(2)2- node2 -1(4)2-
579 // chan1 1-to-2: disabled
580 // chan1 2-to-1: enabled, 0 fee
582 // chan2 1-to-2: enabled, ignored fee
583 // chan2 2-to-1: enabled, 0 fee
585 // chan3 1-to-2: enabled, 0 fee
586 // chan3 2-to-1: enabled, 100 msat fee
588 // chan4 1-to-2: enabled, 100% fee
589 // chan4 2-to-1: enabled, 0 fee
591 // chan12 1-to-2: enabled, ignored fee
592 // chan12 2-to-1: enabled, 0 fee
594 // chan13 1-to-2: enabled, 200% fee
595 // chan13 2-to-1: enabled, 0 fee
598 // -1(5)2- node4 -1(8)2--
602 // node3--1(6)2- node5 -1(9)2--- node7 (not in global route map)
604 // -1(7)2- node6 -1(10)2-
606 // chan5 1-to-2: enabled, 100 msat fee
607 // chan5 2-to-1: enabled, 0 fee
609 // chan6 1-to-2: enabled, 0 fee
610 // chan6 2-to-1: enabled, 0 fee
612 // chan7 1-to-2: enabled, 100% fee
613 // chan7 2-to-1: enabled, 0 fee
615 // chan8 1-to-2: enabled, variable fee (0 then 1000 msat)
616 // chan8 2-to-1: enabled, 0 fee
618 // chan9 1-to-2: enabled, 1001 msat fee
619 // chan9 2-to-1: enabled, 0 fee
621 // chan10 1-to-2: enabled, 0 fee
622 // chan10 2-to-1: enabled, 0 fee
624 // chan11 1-to-2: enabled, 0 fee
625 // chan11 2-to-1: enabled, 0 fee
627 let node1 = PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&secp_ctx, &hex_bytes("0202020202020202020202020202020202020202020202020202020202020202").unwrap()[..]).unwrap()).unwrap();
628 let node2 = PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&secp_ctx, &hex_bytes("0303030303030303030303030303030303030303030303030303030303030303").unwrap()[..]).unwrap()).unwrap();
629 let node3 = PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&secp_ctx, &hex_bytes("0404040404040404040404040404040404040404040404040404040404040404").unwrap()[..]).unwrap()).unwrap();
630 let node4 = PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&secp_ctx, &hex_bytes("0505050505050505050505050505050505050505050505050505050505050505").unwrap()[..]).unwrap()).unwrap();
631 let node5 = PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&secp_ctx, &hex_bytes("0606060606060606060606060606060606060606060606060606060606060606").unwrap()[..]).unwrap()).unwrap();
632 let node6 = PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&secp_ctx, &hex_bytes("0707070707070707070707070707070707070707070707070707070707070707").unwrap()[..]).unwrap()).unwrap();
633 let node7 = PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&secp_ctx, &hex_bytes("0808080808080808080808080808080808080808080808080808080808080808").unwrap()[..]).unwrap()).unwrap();
634 let node8 = PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&secp_ctx, &hex_bytes("0909090909090909090909090909090909090909090909090909090909090909").unwrap()[..]).unwrap()).unwrap();
636 let zero_hash = Sha256dHash::from_data(&[0; 32]);
639 let mut network = router.network_map.write().unwrap();
641 network.nodes.insert(node1.clone(), NodeInfo {
642 channels: vec!(NetworkMap::get_key(1, zero_hash.clone()), NetworkMap::get_key(3, zero_hash.clone())),
643 lowest_inbound_channel_fee_base_msat: 100,
644 lowest_inbound_channel_fee_proportional_millionths: 0,
645 features: GlobalFeatures::new(),
649 addresses: Vec::new(),
651 network.channels.insert(NetworkMap::get_key(1, zero_hash.clone()), ChannelInfo {
652 features: GlobalFeatures::new(),
653 one_to_two: DirectionalChannelInfo {
654 src_node_id: our_id.clone(),
657 cltv_expiry_delta: u16::max_value(), // This value should be ignored
658 htlc_minimum_msat: 0,
659 fee_base_msat: u32::max_value(), // This value should be ignored
660 fee_proportional_millionths: u32::max_value(), // This value should be ignored
661 }, two_to_one: DirectionalChannelInfo {
662 src_node_id: node1.clone(),
665 cltv_expiry_delta: 0,
666 htlc_minimum_msat: 0,
668 fee_proportional_millionths: 0,
671 network.nodes.insert(node2.clone(), NodeInfo {
672 channels: vec!(NetworkMap::get_key(2, zero_hash.clone()), NetworkMap::get_key(4, zero_hash.clone())),
673 lowest_inbound_channel_fee_base_msat: 0,
674 lowest_inbound_channel_fee_proportional_millionths: 0,
675 features: GlobalFeatures::new(),
679 addresses: Vec::new(),
681 network.channels.insert(NetworkMap::get_key(2, zero_hash.clone()), ChannelInfo {
682 features: GlobalFeatures::new(),
683 one_to_two: DirectionalChannelInfo {
684 src_node_id: our_id.clone(),
687 cltv_expiry_delta: u16::max_value(), // This value should be ignored
688 htlc_minimum_msat: 0,
689 fee_base_msat: u32::max_value(), // This value should be ignored
690 fee_proportional_millionths: u32::max_value(), // This value should be ignored
691 }, two_to_one: DirectionalChannelInfo {
692 src_node_id: node2.clone(),
695 cltv_expiry_delta: 0,
696 htlc_minimum_msat: 0,
698 fee_proportional_millionths: 0,
701 network.nodes.insert(node8.clone(), NodeInfo {
702 channels: vec!(NetworkMap::get_key(12, zero_hash.clone()), NetworkMap::get_key(13, zero_hash.clone())),
703 lowest_inbound_channel_fee_base_msat: 0,
704 lowest_inbound_channel_fee_proportional_millionths: 0,
705 features: GlobalFeatures::new(),
709 addresses: Vec::new(),
711 network.channels.insert(NetworkMap::get_key(12, zero_hash.clone()), ChannelInfo {
712 features: GlobalFeatures::new(),
713 one_to_two: DirectionalChannelInfo {
714 src_node_id: our_id.clone(),
717 cltv_expiry_delta: u16::max_value(), // This value should be ignored
718 htlc_minimum_msat: 0,
719 fee_base_msat: u32::max_value(), // This value should be ignored
720 fee_proportional_millionths: u32::max_value(), // This value should be ignored
721 }, two_to_one: DirectionalChannelInfo {
722 src_node_id: node8.clone(),
725 cltv_expiry_delta: 0,
726 htlc_minimum_msat: 0,
728 fee_proportional_millionths: 0,
731 network.nodes.insert(node3.clone(), NodeInfo {
733 NetworkMap::get_key(3, zero_hash.clone()),
734 NetworkMap::get_key(4, zero_hash.clone()),
735 NetworkMap::get_key(13, zero_hash.clone()),
736 NetworkMap::get_key(5, zero_hash.clone()),
737 NetworkMap::get_key(6, zero_hash.clone()),
738 NetworkMap::get_key(7, zero_hash.clone())),
739 lowest_inbound_channel_fee_base_msat: 0,
740 lowest_inbound_channel_fee_proportional_millionths: 0,
741 features: GlobalFeatures::new(),
745 addresses: Vec::new(),
747 network.channels.insert(NetworkMap::get_key(3, zero_hash.clone()), ChannelInfo {
748 features: GlobalFeatures::new(),
749 one_to_two: DirectionalChannelInfo {
750 src_node_id: node1.clone(),
753 cltv_expiry_delta: (3 << 8) | 1,
754 htlc_minimum_msat: 0,
756 fee_proportional_millionths: 0,
757 }, two_to_one: DirectionalChannelInfo {
758 src_node_id: node3.clone(),
761 cltv_expiry_delta: (3 << 8) | 2,
762 htlc_minimum_msat: 0,
764 fee_proportional_millionths: 0,
767 network.channels.insert(NetworkMap::get_key(4, zero_hash.clone()), ChannelInfo {
768 features: GlobalFeatures::new(),
769 one_to_two: DirectionalChannelInfo {
770 src_node_id: node2.clone(),
773 cltv_expiry_delta: (4 << 8) | 1,
774 htlc_minimum_msat: 0,
776 fee_proportional_millionths: 1000000,
777 }, two_to_one: DirectionalChannelInfo {
778 src_node_id: node3.clone(),
781 cltv_expiry_delta: (4 << 8) | 2,
782 htlc_minimum_msat: 0,
784 fee_proportional_millionths: 0,
787 network.channels.insert(NetworkMap::get_key(13, zero_hash.clone()), ChannelInfo {
788 features: GlobalFeatures::new(),
789 one_to_two: DirectionalChannelInfo {
790 src_node_id: node8.clone(),
793 cltv_expiry_delta: (13 << 8) | 1,
794 htlc_minimum_msat: 0,
796 fee_proportional_millionths: 2000000,
797 }, two_to_one: DirectionalChannelInfo {
798 src_node_id: node3.clone(),
801 cltv_expiry_delta: (13 << 8) | 2,
802 htlc_minimum_msat: 0,
804 fee_proportional_millionths: 0,
807 network.nodes.insert(node4.clone(), NodeInfo {
808 channels: vec!(NetworkMap::get_key(5, zero_hash.clone()), NetworkMap::get_key(11, zero_hash.clone())),
809 lowest_inbound_channel_fee_base_msat: 0,
810 lowest_inbound_channel_fee_proportional_millionths: 0,
811 features: GlobalFeatures::new(),
815 addresses: Vec::new(),
817 network.channels.insert(NetworkMap::get_key(5, zero_hash.clone()), ChannelInfo {
818 features: GlobalFeatures::new(),
819 one_to_two: DirectionalChannelInfo {
820 src_node_id: node3.clone(),
823 cltv_expiry_delta: (5 << 8) | 1,
824 htlc_minimum_msat: 0,
826 fee_proportional_millionths: 0,
827 }, two_to_one: DirectionalChannelInfo {
828 src_node_id: node4.clone(),
831 cltv_expiry_delta: (5 << 8) | 2,
832 htlc_minimum_msat: 0,
834 fee_proportional_millionths: 0,
837 network.nodes.insert(node5.clone(), NodeInfo {
838 channels: vec!(NetworkMap::get_key(6, zero_hash.clone()), NetworkMap::get_key(11, zero_hash.clone())),
839 lowest_inbound_channel_fee_base_msat: 0,
840 lowest_inbound_channel_fee_proportional_millionths: 0,
841 features: GlobalFeatures::new(),
845 addresses: Vec::new(),
847 network.channels.insert(NetworkMap::get_key(6, zero_hash.clone()), ChannelInfo {
848 features: GlobalFeatures::new(),
849 one_to_two: DirectionalChannelInfo {
850 src_node_id: node3.clone(),
853 cltv_expiry_delta: (6 << 8) | 1,
854 htlc_minimum_msat: 0,
856 fee_proportional_millionths: 0,
857 }, two_to_one: DirectionalChannelInfo {
858 src_node_id: node5.clone(),
861 cltv_expiry_delta: (6 << 8) | 2,
862 htlc_minimum_msat: 0,
864 fee_proportional_millionths: 0,
867 network.channels.insert(NetworkMap::get_key(11, zero_hash.clone()), ChannelInfo {
868 features: GlobalFeatures::new(),
869 one_to_two: DirectionalChannelInfo {
870 src_node_id: node5.clone(),
873 cltv_expiry_delta: (11 << 8) | 1,
874 htlc_minimum_msat: 0,
876 fee_proportional_millionths: 0,
877 }, two_to_one: DirectionalChannelInfo {
878 src_node_id: node4.clone(),
881 cltv_expiry_delta: (11 << 8) | 2,
882 htlc_minimum_msat: 0,
884 fee_proportional_millionths: 0,
887 network.nodes.insert(node6.clone(), NodeInfo {
888 channels: vec!(NetworkMap::get_key(7, zero_hash.clone())),
889 lowest_inbound_channel_fee_base_msat: 0,
890 lowest_inbound_channel_fee_proportional_millionths: 0,
891 features: GlobalFeatures::new(),
895 addresses: Vec::new(),
897 network.channels.insert(NetworkMap::get_key(7, zero_hash.clone()), ChannelInfo {
898 features: GlobalFeatures::new(),
899 one_to_two: DirectionalChannelInfo {
900 src_node_id: node3.clone(),
903 cltv_expiry_delta: (7 << 8) | 1,
904 htlc_minimum_msat: 0,
906 fee_proportional_millionths: 1000000,
907 }, two_to_one: DirectionalChannelInfo {
908 src_node_id: node6.clone(),
911 cltv_expiry_delta: (7 << 8) | 2,
912 htlc_minimum_msat: 0,
914 fee_proportional_millionths: 0,
919 { // Simple route to 3 via 2
920 let route = router.get_route(&node3, None, &Vec::new(), 100, 42).unwrap();
921 assert_eq!(route.hops.len(), 2);
923 assert_eq!(route.hops[0].pubkey, node2);
924 assert_eq!(route.hops[0].short_channel_id, 2);
925 assert_eq!(route.hops[0].fee_msat, 100);
926 assert_eq!(route.hops[0].cltv_expiry_delta, (4 << 8) | 1);
928 assert_eq!(route.hops[1].pubkey, node3);
929 assert_eq!(route.hops[1].short_channel_id, 4);
930 assert_eq!(route.hops[1].fee_msat, 100);
931 assert_eq!(route.hops[1].cltv_expiry_delta, 42);
934 { // Route to 1 via 2 and 3 because our channel to 1 is disabled
935 let route = router.get_route(&node1, None, &Vec::new(), 100, 42).unwrap();
936 assert_eq!(route.hops.len(), 3);
938 assert_eq!(route.hops[0].pubkey, node2);
939 assert_eq!(route.hops[0].short_channel_id, 2);
940 assert_eq!(route.hops[0].fee_msat, 200);
941 assert_eq!(route.hops[0].cltv_expiry_delta, (4 << 8) | 1);
943 assert_eq!(route.hops[1].pubkey, node3);
944 assert_eq!(route.hops[1].short_channel_id, 4);
945 assert_eq!(route.hops[1].fee_msat, 100);
946 assert_eq!(route.hops[1].cltv_expiry_delta, (3 << 8) | 2);
948 assert_eq!(route.hops[2].pubkey, node1);
949 assert_eq!(route.hops[2].short_channel_id, 3);
950 assert_eq!(route.hops[2].fee_msat, 100);
951 assert_eq!(route.hops[2].cltv_expiry_delta, 42);
954 { // If we specify a channel to node8, that overrides our local channel view and that gets used
955 let our_chans = vec![channelmanager::ChannelDetails {
957 short_channel_id: Some(42),
958 remote_network_id: node8.clone(),
959 channel_value_satoshis: 0,
962 let route = router.get_route(&node3, Some(&our_chans), &Vec::new(), 100, 42).unwrap();
963 assert_eq!(route.hops.len(), 2);
965 assert_eq!(route.hops[0].pubkey, node8);
966 assert_eq!(route.hops[0].short_channel_id, 42);
967 assert_eq!(route.hops[0].fee_msat, 200);
968 assert_eq!(route.hops[0].cltv_expiry_delta, (13 << 8) | 1);
970 assert_eq!(route.hops[1].pubkey, node3);
971 assert_eq!(route.hops[1].short_channel_id, 13);
972 assert_eq!(route.hops[1].fee_msat, 100);
973 assert_eq!(route.hops[1].cltv_expiry_delta, 42);
976 let mut last_hops = vec!(RouteHint {
977 src_node_id: node4.clone(),
980 fee_proportional_millionths: 0,
981 cltv_expiry_delta: (8 << 8) | 1,
982 htlc_minimum_msat: 0,
984 src_node_id: node5.clone(),
987 fee_proportional_millionths: 0,
988 cltv_expiry_delta: (9 << 8) | 1,
989 htlc_minimum_msat: 0,
991 src_node_id: node6.clone(),
992 short_channel_id: 10,
994 fee_proportional_millionths: 0,
995 cltv_expiry_delta: (10 << 8) | 1,
996 htlc_minimum_msat: 0,
999 { // Simple test across 2, 3, 5, and 4 via a last_hop channel
1000 let route = router.get_route(&node7, None, &last_hops, 100, 42).unwrap();
1001 assert_eq!(route.hops.len(), 5);
1003 assert_eq!(route.hops[0].pubkey, node2);
1004 assert_eq!(route.hops[0].short_channel_id, 2);
1005 assert_eq!(route.hops[0].fee_msat, 100);
1006 assert_eq!(route.hops[0].cltv_expiry_delta, (4 << 8) | 1);
1008 assert_eq!(route.hops[1].pubkey, node3);
1009 assert_eq!(route.hops[1].short_channel_id, 4);
1010 assert_eq!(route.hops[1].fee_msat, 0);
1011 assert_eq!(route.hops[1].cltv_expiry_delta, (6 << 8) | 1);
1013 assert_eq!(route.hops[2].pubkey, node5);
1014 assert_eq!(route.hops[2].short_channel_id, 6);
1015 assert_eq!(route.hops[2].fee_msat, 0);
1016 assert_eq!(route.hops[2].cltv_expiry_delta, (11 << 8) | 1);
1018 assert_eq!(route.hops[3].pubkey, node4);
1019 assert_eq!(route.hops[3].short_channel_id, 11);
1020 assert_eq!(route.hops[3].fee_msat, 0);
1021 assert_eq!(route.hops[3].cltv_expiry_delta, (8 << 8) | 1);
1023 assert_eq!(route.hops[4].pubkey, node7);
1024 assert_eq!(route.hops[4].short_channel_id, 8);
1025 assert_eq!(route.hops[4].fee_msat, 100);
1026 assert_eq!(route.hops[4].cltv_expiry_delta, 42);
1029 { // Simple test with outbound channel to 4 to test that last_hops and first_hops connect
1030 let our_chans = vec![channelmanager::ChannelDetails {
1031 channel_id: [0; 32],
1032 short_channel_id: Some(42),
1033 remote_network_id: node4.clone(),
1034 channel_value_satoshis: 0,
1037 let route = router.get_route(&node7, Some(&our_chans), &last_hops, 100, 42).unwrap();
1038 assert_eq!(route.hops.len(), 2);
1040 assert_eq!(route.hops[0].pubkey, node4);
1041 assert_eq!(route.hops[0].short_channel_id, 42);
1042 assert_eq!(route.hops[0].fee_msat, 0);
1043 assert_eq!(route.hops[0].cltv_expiry_delta, (8 << 8) | 1);
1045 assert_eq!(route.hops[1].pubkey, node7);
1046 assert_eq!(route.hops[1].short_channel_id, 8);
1047 assert_eq!(route.hops[1].fee_msat, 100);
1048 assert_eq!(route.hops[1].cltv_expiry_delta, 42);
1051 last_hops[0].fee_base_msat = 1000;
1053 { // Revert to via 6 as the fee on 8 goes up
1054 let route = router.get_route(&node7, None, &last_hops, 100, 42).unwrap();
1055 assert_eq!(route.hops.len(), 4);
1057 assert_eq!(route.hops[0].pubkey, node2);
1058 assert_eq!(route.hops[0].short_channel_id, 2);
1059 assert_eq!(route.hops[0].fee_msat, 200); // fee increased as its % of value transferred across node
1060 assert_eq!(route.hops[0].cltv_expiry_delta, (4 << 8) | 1);
1062 assert_eq!(route.hops[1].pubkey, node3);
1063 assert_eq!(route.hops[1].short_channel_id, 4);
1064 assert_eq!(route.hops[1].fee_msat, 100);
1065 assert_eq!(route.hops[1].cltv_expiry_delta, (7 << 8) | 1);
1067 assert_eq!(route.hops[2].pubkey, node6);
1068 assert_eq!(route.hops[2].short_channel_id, 7);
1069 assert_eq!(route.hops[2].fee_msat, 0);
1070 assert_eq!(route.hops[2].cltv_expiry_delta, (10 << 8) | 1);
1072 assert_eq!(route.hops[3].pubkey, node7);
1073 assert_eq!(route.hops[3].short_channel_id, 10);
1074 assert_eq!(route.hops[3].fee_msat, 100);
1075 assert_eq!(route.hops[3].cltv_expiry_delta, 42);
1078 { // ...but still use 8 for larger payments as 6 has a variable feerate
1079 let route = router.get_route(&node7, None, &last_hops, 2000, 42).unwrap();
1080 assert_eq!(route.hops.len(), 5);
1082 assert_eq!(route.hops[0].pubkey, node2);
1083 assert_eq!(route.hops[0].short_channel_id, 2);
1084 assert_eq!(route.hops[0].fee_msat, 3000);
1085 assert_eq!(route.hops[0].cltv_expiry_delta, (4 << 8) | 1);
1087 assert_eq!(route.hops[1].pubkey, node3);
1088 assert_eq!(route.hops[1].short_channel_id, 4);
1089 assert_eq!(route.hops[1].fee_msat, 0);
1090 assert_eq!(route.hops[1].cltv_expiry_delta, (6 << 8) | 1);
1092 assert_eq!(route.hops[2].pubkey, node5);
1093 assert_eq!(route.hops[2].short_channel_id, 6);
1094 assert_eq!(route.hops[2].fee_msat, 0);
1095 assert_eq!(route.hops[2].cltv_expiry_delta, (11 << 8) | 1);
1097 assert_eq!(route.hops[3].pubkey, node4);
1098 assert_eq!(route.hops[3].short_channel_id, 11);
1099 assert_eq!(route.hops[3].fee_msat, 1000);
1100 assert_eq!(route.hops[3].cltv_expiry_delta, (8 << 8) | 1);
1102 assert_eq!(route.hops[4].pubkey, node7);
1103 assert_eq!(route.hops[4].short_channel_id, 8);
1104 assert_eq!(route.hops[4].fee_msat, 2000);
1105 assert_eq!(route.hops[4].cltv_expiry_delta, 42);