1 //! The top-level routing/network map tracking logic lives here.
3 //! You probably want to create a Router and use that as your RoutingMessageHandler and then
4 //! interrogate it to get routes for your own payments.
6 use secp256k1::key::PublicKey;
7 use secp256k1::Secp256k1;
10 use bitcoin::util::hash::Sha256dHash;
11 use bitcoin::blockdata::script::Builder;
12 use bitcoin::blockdata::opcodes;
14 use chain::chaininterface::{ChainError, ChainWatchInterface};
15 use ln::channelmanager;
16 use ln::msgs::{DecodeError,ErrorAction,HandleError,RoutingMessageHandler,NetAddress,GlobalFeatures};
18 use util::ser::{Writeable, Readable, Writer, ReadableArgs};
19 use util::logger::Logger;
22 use std::sync::{RwLock,Arc};
23 use std::collections::{HashMap,BinaryHeap,BTreeMap};
24 use std::collections::btree_map::Entry as BtreeEntry;
28 #[derive(Clone, PartialEq)]
30 /// The node_id of the node at this hop.
31 pub pubkey: PublicKey,
32 /// The channel that should be used from the previous hop to reach this node.
33 pub short_channel_id: u64,
34 /// The fee taken on this hop. For the last hop, this should be the full value of the payment.
36 /// The CLTV delta added for this hop. For the last hop, this should be the full CLTV value
37 /// expected at the destination, in excess of the current block height.
38 pub cltv_expiry_delta: u32,
41 /// A route from us through the network to a destination
42 #[derive(Clone, PartialEq)]
44 /// The list of hops, NOT INCLUDING our own, where the last hop is the destination. Thus, this
45 /// must always be at least length one. By protocol rules, this may not currently exceed 20 in
47 pub hops: Vec<RouteHop>,
50 impl Writeable for Route {
51 fn write<W: ::util::ser::Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
52 (self.hops.len() as u8).write(writer)?;
53 for hop in self.hops.iter() {
54 hop.pubkey.write(writer)?;
55 hop.short_channel_id.write(writer)?;
56 hop.fee_msat.write(writer)?;
57 hop.cltv_expiry_delta.write(writer)?;
63 impl<R: ::std::io::Read> Readable<R> for Route {
64 fn read(reader: &mut R) -> Result<Route, DecodeError> {
65 let hops_count: u8 = Readable::read(reader)?;
66 let mut hops = Vec::with_capacity(hops_count as usize);
67 for _ in 0..hops_count {
69 pubkey: Readable::read(reader)?,
70 short_channel_id: Readable::read(reader)?,
71 fee_msat: Readable::read(reader)?,
72 cltv_expiry_delta: Readable::read(reader)?,
82 struct DirectionalChannelInfo {
83 src_node_id: PublicKey,
86 cltv_expiry_delta: u16,
87 htlc_minimum_msat: u64,
89 fee_proportional_millionths: u32,
90 last_update_message: Option<msgs::ChannelUpdate>,
93 impl std::fmt::Display for DirectionalChannelInfo {
94 fn fmt(&self, f: &mut std::fmt::Formatter) -> Result<(), std::fmt::Error> {
95 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)?;
100 impl_writeable!(DirectionalChannelInfo, 0, {
107 fee_proportional_millionths,
113 features: GlobalFeatures,
114 one_to_two: DirectionalChannelInfo,
115 two_to_one: DirectionalChannelInfo,
116 //this is cached here so we can send out it later if required by route_init_sync
117 //keep an eye on this to see if the extra memory is a problem
118 announcement_message: Option<msgs::ChannelAnnouncement>,
121 impl std::fmt::Display for ChannelInfo {
122 fn fmt(&self, f: &mut std::fmt::Formatter) -> Result<(), std::fmt::Error> {
123 write!(f, "features: {}, one_to_two: {}, two_to_one: {}", log_bytes!(self.features.encode()), self.one_to_two, self.two_to_one)?;
128 impl_writeable!(ChannelInfo, 0, {
137 #[cfg(feature = "non_bitcoin_chain_hash_routing")]
138 channels: Vec<(u64, Sha256dHash)>,
139 #[cfg(not(feature = "non_bitcoin_chain_hash_routing"))]
142 lowest_inbound_channel_fee_base_msat: u32,
143 lowest_inbound_channel_fee_proportional_millionths: u32,
145 features: GlobalFeatures,
149 addresses: Vec<NetAddress>,
150 //this is cached here so we can send out it later if required by route_init_sync
151 //keep an eye on this to see if the extra memory is a problem
152 announcement_message: Option<msgs::NodeAnnouncement>,
155 impl std::fmt::Display for NodeInfo {
156 fn fmt(&self, f: &mut std::fmt::Formatter) -> Result<(), std::fmt::Error> {
157 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[..])?;
162 impl Writeable for NodeInfo {
163 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
164 (self.channels.len() as u64).write(writer)?;
165 for ref chan in self.channels.iter() {
168 self.lowest_inbound_channel_fee_base_msat.write(writer)?;
169 self.lowest_inbound_channel_fee_proportional_millionths.write(writer)?;
170 self.features.write(writer)?;
171 self.last_update.write(writer)?;
172 self.rgb.write(writer)?;
173 self.alias.write(writer)?;
174 (self.addresses.len() as u64).write(writer)?;
175 for ref addr in &self.addresses {
178 self.announcement_message.write(writer)?;
183 const MAX_ALLOC_SIZE: u64 = 64*1024;
185 impl<R: ::std::io::Read> Readable<R> for NodeInfo {
186 fn read(reader: &mut R) -> Result<NodeInfo, DecodeError> {
187 let channels_count: u64 = Readable::read(reader)?;
188 let mut channels = Vec::with_capacity(cmp::min(channels_count, MAX_ALLOC_SIZE / 8) as usize);
189 for _ in 0..channels_count {
190 channels.push(Readable::read(reader)?);
192 let lowest_inbound_channel_fee_base_msat = Readable::read(reader)?;
193 let lowest_inbound_channel_fee_proportional_millionths = Readable::read(reader)?;
194 let features = Readable::read(reader)?;
195 let last_update = Readable::read(reader)?;
196 let rgb = Readable::read(reader)?;
197 let alias = Readable::read(reader)?;
198 let addresses_count: u64 = Readable::read(reader)?;
199 let mut addresses = Vec::with_capacity(cmp::min(addresses_count, MAX_ALLOC_SIZE / 40) as usize);
200 for _ in 0..addresses_count {
201 match Readable::read(reader) {
202 Ok(Ok(addr)) => { addresses.push(addr); },
203 Ok(Err(_)) => return Err(DecodeError::InvalidValue),
204 Err(DecodeError::ShortRead) => return Err(DecodeError::BadLengthDescriptor),
208 let announcement_message = Readable::read(reader)?;
211 lowest_inbound_channel_fee_base_msat,
212 lowest_inbound_channel_fee_proportional_millionths,
225 #[cfg(feature = "non_bitcoin_chain_hash_routing")]
226 channels: BTreeMap<(u64, Sha256dHash), ChannelInfo>,
227 #[cfg(not(feature = "non_bitcoin_chain_hash_routing"))]
228 channels: BTreeMap<u64, ChannelInfo>,
230 our_node_id: PublicKey,
231 nodes: BTreeMap<PublicKey, NodeInfo>,
234 impl Writeable for NetworkMap {
235 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
236 (self.channels.len() as u64).write(writer)?;
237 for (ref chan_id, ref chan_info) in self.channels.iter() {
238 (*chan_id).write(writer)?;
239 chan_info.write(writer)?;
241 self.our_node_id.write(writer)?;
242 (self.nodes.len() as u64).write(writer)?;
243 for (ref node_id, ref node_info) in self.nodes.iter() {
244 node_id.write(writer)?;
245 node_info.write(writer)?;
251 impl<R: ::std::io::Read> Readable<R> for NetworkMap {
252 fn read(reader: &mut R) -> Result<NetworkMap, DecodeError> {
253 let channels_count: u64 = Readable::read(reader)?;
254 let mut channels = BTreeMap::new();
255 for _ in 0..channels_count {
256 let chan_id: u64 = Readable::read(reader)?;
257 let chan_info = Readable::read(reader)?;
258 channels.insert(chan_id, chan_info);
260 let our_node_id = Readable::read(reader)?;
261 let nodes_count: u64 = Readable::read(reader)?;
262 let mut nodes = BTreeMap::new();
263 for _ in 0..nodes_count {
264 let node_id = Readable::read(reader)?;
265 let node_info = Readable::read(reader)?;
266 nodes.insert(node_id, node_info);
276 struct MutNetworkMap<'a> {
277 #[cfg(feature = "non_bitcoin_chain_hash_routing")]
278 channels: &'a mut BTreeMap<(u64, Sha256dHash), ChannelInfo>,
279 #[cfg(not(feature = "non_bitcoin_chain_hash_routing"))]
280 channels: &'a mut BTreeMap<u64, ChannelInfo>,
281 nodes: &'a mut BTreeMap<PublicKey, NodeInfo>,
284 fn borrow_parts(&mut self) -> MutNetworkMap {
286 channels: &mut self.channels,
287 nodes: &mut self.nodes,
291 impl std::fmt::Display for NetworkMap {
292 fn fmt(&self, f: &mut std::fmt::Formatter) -> Result<(), std::fmt::Error> {
293 write!(f, "Node id {} network map\n[Channels]\n", log_pubkey!(self.our_node_id))?;
294 for (key, val) in self.channels.iter() {
295 write!(f, " {}: {}\n", key, val)?;
297 write!(f, "[Nodes]\n")?;
298 for (key, val) in self.nodes.iter() {
299 write!(f, " {}: {}\n", log_pubkey!(key), val)?;
306 #[cfg(feature = "non_bitcoin_chain_hash_routing")]
308 fn get_key(short_channel_id: u64, chain_hash: Sha256dHash) -> (u64, Sha256dHash) {
309 (short_channel_id, chain_hash)
312 #[cfg(not(feature = "non_bitcoin_chain_hash_routing"))]
314 fn get_key(short_channel_id: u64, _: Sha256dHash) -> u64 {
318 #[cfg(feature = "non_bitcoin_chain_hash_routing")]
320 fn get_short_id(id: &(u64, Sha256dHash)) -> &u64 {
324 #[cfg(not(feature = "non_bitcoin_chain_hash_routing"))]
326 fn get_short_id(id: &u64) -> &u64 {
331 /// A channel descriptor which provides a last-hop route to get_route
332 pub struct RouteHint {
333 /// The node_id of the non-target end of the route
334 pub src_node_id: PublicKey,
335 /// The short_channel_id of this channel
336 pub short_channel_id: u64,
337 /// The static msat-denominated fee which must be paid to use this channel
338 pub fee_base_msat: u32,
339 /// The dynamic proportional fee which must be paid to use this channel, denominated in
340 /// millionths of the value being forwarded to the next hop.
341 pub fee_proportional_millionths: u32,
342 /// The difference in CLTV values between this node and the next node.
343 pub cltv_expiry_delta: u16,
344 /// The minimum value, in msat, which must be relayed to the next hop.
345 pub htlc_minimum_msat: u64,
348 /// Tracks a view of the network, receiving updates from peers and generating Routes to
349 /// payment destinations.
351 secp_ctx: Secp256k1<secp256k1::VerifyOnly>,
352 network_map: RwLock<NetworkMap>,
353 chain_monitor: Arc<ChainWatchInterface>,
357 const SERIALIZATION_VERSION: u8 = 1;
358 const MIN_SERIALIZATION_VERSION: u8 = 1;
360 impl Writeable for Router {
361 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
362 writer.write_all(&[SERIALIZATION_VERSION; 1])?;
363 writer.write_all(&[MIN_SERIALIZATION_VERSION; 1])?;
365 let network = self.network_map.read().unwrap();
366 network.write(writer)?;
371 /// Arguments for the creation of a Router that are not deserialized.
372 /// At a high-level, the process for deserializing a Router and resuming normal operation is:
373 /// 1) Deserialize the Router by filling in this struct and calling <Router>::read(reaser, args).
374 /// 2) Register the new Router with your ChainWatchInterface
375 pub struct RouterReadArgs {
376 /// The ChainWatchInterface for use in the Router in the future.
378 /// No calls to the ChainWatchInterface will be made during deserialization.
379 pub chain_monitor: Arc<ChainWatchInterface>,
380 /// The Logger for use in the ChannelManager and which may be used to log information during
382 pub logger: Arc<Logger>,
385 impl<R: ::std::io::Read> ReadableArgs<R, RouterReadArgs> for Router {
386 fn read(reader: &mut R, args: RouterReadArgs) -> Result<Router, DecodeError> {
387 let _ver: u8 = Readable::read(reader)?;
388 let min_ver: u8 = Readable::read(reader)?;
389 if min_ver > SERIALIZATION_VERSION {
390 return Err(DecodeError::UnknownVersion);
392 let network_map = Readable::read(reader)?;
394 secp_ctx: Secp256k1::verification_only(),
395 network_map: RwLock::new(network_map),
396 chain_monitor: args.chain_monitor,
402 macro_rules! secp_verify_sig {
403 ( $secp_ctx: expr, $msg: expr, $sig: expr, $pubkey: expr ) => {
404 match $secp_ctx.verify($msg, $sig, $pubkey) {
406 Err(_) => return Err(HandleError{err: "Invalid signature from remote node", action: None}),
411 impl RoutingMessageHandler for Router {
412 fn handle_node_announcement(&self, msg: &msgs::NodeAnnouncement) -> Result<bool, HandleError> {
413 let msg_hash = hash_to_message!(&Sha256dHash::from_data(&msg.contents.encode()[..])[..]);
414 secp_verify_sig!(self.secp_ctx, &msg_hash, &msg.signature, &msg.contents.node_id);
416 if msg.contents.features.requires_unknown_bits() {
417 panic!("Unknown-required-features NodeAnnouncements should never deserialize!");
420 let mut network = self.network_map.write().unwrap();
421 match network.nodes.get_mut(&msg.contents.node_id) {
422 None => Err(HandleError{err: "No existing channels for node_announcement", action: Some(ErrorAction::IgnoreError)}),
424 if node.last_update >= msg.contents.timestamp {
425 return Err(HandleError{err: "Update older than last processed update", action: Some(ErrorAction::IgnoreError)});
428 node.features = msg.contents.features.clone();
429 node.last_update = msg.contents.timestamp;
430 node.rgb = msg.contents.rgb;
431 node.alias = msg.contents.alias;
432 node.addresses = msg.contents.addresses.clone();
434 let should_relay = msg.contents.excess_data.is_empty() && msg.contents.excess_address_data.is_empty() && !msg.contents.features.supports_unknown_bits();
435 node.announcement_message = if should_relay { Some(msg.clone()) } else { None };
441 fn handle_channel_announcement(&self, msg: &msgs::ChannelAnnouncement) -> Result<bool, HandleError> {
442 if msg.contents.node_id_1 == msg.contents.node_id_2 || msg.contents.bitcoin_key_1 == msg.contents.bitcoin_key_2 {
443 return Err(HandleError{err: "Channel announcement node had a channel with itself", action: Some(ErrorAction::IgnoreError)});
446 let msg_hash = hash_to_message!(&Sha256dHash::from_data(&msg.contents.encode()[..])[..]);
447 secp_verify_sig!(self.secp_ctx, &msg_hash, &msg.node_signature_1, &msg.contents.node_id_1);
448 secp_verify_sig!(self.secp_ctx, &msg_hash, &msg.node_signature_2, &msg.contents.node_id_2);
449 secp_verify_sig!(self.secp_ctx, &msg_hash, &msg.bitcoin_signature_1, &msg.contents.bitcoin_key_1);
450 secp_verify_sig!(self.secp_ctx, &msg_hash, &msg.bitcoin_signature_2, &msg.contents.bitcoin_key_2);
452 if msg.contents.features.requires_unknown_bits() {
453 panic!("Unknown-required-features ChannelAnnouncements should never deserialize!");
456 let checked_utxo = match self.chain_monitor.get_chain_utxo(msg.contents.chain_hash, msg.contents.short_channel_id) {
457 Ok((script_pubkey, _value)) => {
458 let expected_script = Builder::new().push_opcode(opcodes::all::OP_PUSHNUM_2)
459 .push_slice(&msg.contents.bitcoin_key_1.serialize())
460 .push_slice(&msg.contents.bitcoin_key_2.serialize())
461 .push_opcode(opcodes::all::OP_PUSHNUM_2)
462 .push_opcode(opcodes::all::OP_CHECKMULTISIG).into_script().to_v0_p2wsh();
463 if script_pubkey != expected_script {
464 return Err(HandleError{err: "Channel announcement keys didn't match on-chain script", action: Some(ErrorAction::IgnoreError)});
466 //TODO: Check if value is worth storing, use it to inform routing, and compare it
467 //to the new HTLC max field in channel_update
470 Err(ChainError::NotSupported) => {
471 // Tentatively accept, potentially exposing us to DoS attacks
474 Err(ChainError::NotWatched) => {
475 return Err(HandleError{err: "Channel announced on an unknown chain", action: Some(ErrorAction::IgnoreError)});
477 Err(ChainError::UnknownTx) => {
478 return Err(HandleError{err: "Channel announced without corresponding UTXO entry", action: Some(ErrorAction::IgnoreError)});
482 let mut network_lock = self.network_map.write().unwrap();
483 let network = network_lock.borrow_parts();
485 let should_relay = msg.contents.excess_data.is_empty() && !msg.contents.features.supports_unknown_bits();
487 let chan_info = ChannelInfo {
488 features: msg.contents.features.clone(),
489 one_to_two: DirectionalChannelInfo {
490 src_node_id: msg.contents.node_id_1.clone(),
493 cltv_expiry_delta: u16::max_value(),
494 htlc_minimum_msat: u64::max_value(),
495 fee_base_msat: u32::max_value(),
496 fee_proportional_millionths: u32::max_value(),
497 last_update_message: None,
499 two_to_one: DirectionalChannelInfo {
500 src_node_id: msg.contents.node_id_2.clone(),
503 cltv_expiry_delta: u16::max_value(),
504 htlc_minimum_msat: u64::max_value(),
505 fee_base_msat: u32::max_value(),
506 fee_proportional_millionths: u32::max_value(),
507 last_update_message: None,
509 announcement_message: if should_relay { Some(msg.clone()) } else { None },
512 match network.channels.entry(NetworkMap::get_key(msg.contents.short_channel_id, msg.contents.chain_hash)) {
513 BtreeEntry::Occupied(mut entry) => {
514 //TODO: because asking the blockchain if short_channel_id is valid is only optional
515 //in the blockchain API, we need to handle it smartly here, though it's unclear
518 // Either our UTXO provider is busted, there was a reorg, or the UTXO provider
519 // only sometimes returns results. In any case remove the previous entry. Note
520 // that the spec expects us to "blacklist" the node_ids involved, but we can't
522 // a) we don't *require* a UTXO provider that always returns results.
523 // b) we don't track UTXOs of channels we know about and remove them if they
525 // c) it's unclear how to do so without exposing ourselves to massive DoS risk.
526 Self::remove_channel_in_nodes(network.nodes, &entry.get(), msg.contents.short_channel_id);
527 *entry.get_mut() = chan_info;
529 return Err(HandleError{err: "Already have knowledge of channel", action: Some(ErrorAction::IgnoreError)})
532 BtreeEntry::Vacant(entry) => {
533 entry.insert(chan_info);
537 macro_rules! add_channel_to_node {
538 ( $node_id: expr ) => {
539 match network.nodes.entry($node_id) {
540 BtreeEntry::Occupied(node_entry) => {
541 node_entry.into_mut().channels.push(NetworkMap::get_key(msg.contents.short_channel_id, msg.contents.chain_hash));
543 BtreeEntry::Vacant(node_entry) => {
544 node_entry.insert(NodeInfo {
545 channels: vec!(NetworkMap::get_key(msg.contents.short_channel_id, msg.contents.chain_hash)),
546 lowest_inbound_channel_fee_base_msat: u32::max_value(),
547 lowest_inbound_channel_fee_proportional_millionths: u32::max_value(),
548 features: GlobalFeatures::new(),
552 addresses: Vec::new(),
553 announcement_message: None,
560 add_channel_to_node!(msg.contents.node_id_1);
561 add_channel_to_node!(msg.contents.node_id_2);
566 fn handle_htlc_fail_channel_update(&self, update: &msgs::HTLCFailChannelUpdate) {
568 &msgs::HTLCFailChannelUpdate::ChannelUpdateMessage { ref msg } => {
569 let _ = self.handle_channel_update(msg);
571 &msgs::HTLCFailChannelUpdate::ChannelClosed { ref short_channel_id, ref is_permanent } => {
572 let mut network = self.network_map.write().unwrap();
574 if let Some(chan) = network.channels.remove(short_channel_id) {
575 Self::remove_channel_in_nodes(&mut network.nodes, &chan, *short_channel_id);
578 if let Some(chan) = network.channels.get_mut(short_channel_id) {
579 chan.one_to_two.enabled = false;
580 chan.two_to_one.enabled = false;
584 &msgs::HTLCFailChannelUpdate::NodeFailure { ref node_id, ref is_permanent } => {
586 //TODO: Wholly remove the node
588 self.mark_node_bad(node_id, false);
594 fn handle_channel_update(&self, msg: &msgs::ChannelUpdate) -> Result<bool, HandleError> {
595 let mut network = self.network_map.write().unwrap();
597 let chan_enabled = msg.contents.flags & (1 << 1) != (1 << 1);
598 let chan_was_enabled;
600 match network.channels.get_mut(&NetworkMap::get_key(msg.contents.short_channel_id, msg.contents.chain_hash)) {
601 None => return Err(HandleError{err: "Couldn't find channel for update", action: Some(ErrorAction::IgnoreError)}),
603 macro_rules! maybe_update_channel_info {
604 ( $target: expr) => {
605 if $target.last_update >= msg.contents.timestamp {
606 return Err(HandleError{err: "Update older than last processed update", action: Some(ErrorAction::IgnoreError)});
608 chan_was_enabled = $target.enabled;
609 $target.last_update = msg.contents.timestamp;
610 $target.enabled = chan_enabled;
611 $target.cltv_expiry_delta = msg.contents.cltv_expiry_delta;
612 $target.htlc_minimum_msat = msg.contents.htlc_minimum_msat;
613 $target.fee_base_msat = msg.contents.fee_base_msat;
614 $target.fee_proportional_millionths = msg.contents.fee_proportional_millionths;
615 $target.last_update_message = if msg.contents.excess_data.is_empty() {
622 let msg_hash = hash_to_message!(&Sha256dHash::from_data(&msg.contents.encode()[..])[..]);
623 if msg.contents.flags & 1 == 1 {
624 dest_node_id = channel.one_to_two.src_node_id.clone();
625 secp_verify_sig!(self.secp_ctx, &msg_hash, &msg.signature, &channel.two_to_one.src_node_id);
626 maybe_update_channel_info!(channel.two_to_one);
628 dest_node_id = channel.two_to_one.src_node_id.clone();
629 secp_verify_sig!(self.secp_ctx, &msg_hash, &msg.signature, &channel.one_to_two.src_node_id);
630 maybe_update_channel_info!(channel.one_to_two);
636 let node = network.nodes.get_mut(&dest_node_id).unwrap();
637 node.lowest_inbound_channel_fee_base_msat = cmp::min(node.lowest_inbound_channel_fee_base_msat, msg.contents.fee_base_msat);
638 node.lowest_inbound_channel_fee_proportional_millionths = cmp::min(node.lowest_inbound_channel_fee_proportional_millionths, msg.contents.fee_proportional_millionths);
639 } else if chan_was_enabled {
640 let mut lowest_inbound_channel_fee_base_msat = u32::max_value();
641 let mut lowest_inbound_channel_fee_proportional_millionths = u32::max_value();
644 let node = network.nodes.get(&dest_node_id).unwrap();
646 for chan_id in node.channels.iter() {
647 let chan = network.channels.get(chan_id).unwrap();
648 if chan.one_to_two.src_node_id == dest_node_id {
649 lowest_inbound_channel_fee_base_msat = cmp::min(lowest_inbound_channel_fee_base_msat, chan.two_to_one.fee_base_msat);
650 lowest_inbound_channel_fee_proportional_millionths = cmp::min(lowest_inbound_channel_fee_proportional_millionths, chan.two_to_one.fee_proportional_millionths);
652 lowest_inbound_channel_fee_base_msat = cmp::min(lowest_inbound_channel_fee_base_msat, chan.one_to_two.fee_base_msat);
653 lowest_inbound_channel_fee_proportional_millionths = cmp::min(lowest_inbound_channel_fee_proportional_millionths, chan.one_to_two.fee_proportional_millionths);
658 //TODO: satisfy the borrow-checker without a double-map-lookup :(
659 let mut_node = network.nodes.get_mut(&dest_node_id).unwrap();
660 mut_node.lowest_inbound_channel_fee_base_msat = lowest_inbound_channel_fee_base_msat;
661 mut_node.lowest_inbound_channel_fee_proportional_millionths = lowest_inbound_channel_fee_proportional_millionths;
664 Ok(msg.contents.excess_data.is_empty())
668 fn get_next_channel_announcements(&self, starting_point: u64, batch_amount: u8) -> Vec<(msgs::ChannelAnnouncement, msgs::ChannelUpdate,msgs::ChannelUpdate)> {
669 let mut result = Vec::with_capacity(batch_amount as usize);
670 let network = self.network_map.read().unwrap();
671 let mut iter = network.channels.range(starting_point..);
672 while result.len() < batch_amount as usize {
673 if let Some((_, ref chan)) = iter.next() {
674 if chan.announcement_message.is_some() &&
675 chan.one_to_two.last_update_message.is_some() &&
676 chan.two_to_one.last_update_message.is_some() {
677 result.push((chan.announcement_message.clone().unwrap(),
678 chan.one_to_two.last_update_message.clone().unwrap(),
679 chan.two_to_one.last_update_message.clone().unwrap()));
681 // TODO: We may end up sending un-announced channel_updates if we are sending
682 // initial sync data while receiving announce/updates for this channel.
691 fn get_next_node_announcements(&self, starting_point: Option<&PublicKey>, batch_amount: u8) -> Vec<msgs::NodeAnnouncement> {
692 let mut result = Vec::with_capacity(batch_amount as usize);
693 let network = self.network_map.read().unwrap();
694 let mut iter = if let Some(pubkey) = starting_point {
695 let mut iter = network.nodes.range((*pubkey)..);
699 network.nodes.range(..)
701 while result.len() < batch_amount as usize {
702 if let Some((_, ref node)) = iter.next() {
703 if node.announcement_message.is_some() {
704 result.push(node.announcement_message.clone().unwrap());
714 #[derive(Eq, PartialEq)]
715 struct RouteGraphNode {
717 lowest_fee_to_peer_through_node: u64,
718 lowest_fee_to_node: u64,
721 impl cmp::Ord for RouteGraphNode {
722 fn cmp(&self, other: &RouteGraphNode) -> cmp::Ordering {
723 other.lowest_fee_to_peer_through_node.cmp(&self.lowest_fee_to_peer_through_node)
724 .then_with(|| other.pubkey.serialize().cmp(&self.pubkey.serialize()))
728 impl cmp::PartialOrd for RouteGraphNode {
729 fn partial_cmp(&self, other: &RouteGraphNode) -> Option<cmp::Ordering> {
730 Some(self.cmp(other))
734 struct DummyDirectionalChannelInfo {
735 src_node_id: PublicKey,
736 cltv_expiry_delta: u32,
737 htlc_minimum_msat: u64,
739 fee_proportional_millionths: u32,
743 /// Creates a new router with the given node_id to be used as the source for get_route()
744 pub fn new(our_pubkey: PublicKey, chain_monitor: Arc<ChainWatchInterface>, logger: Arc<Logger>) -> Router {
745 let mut nodes = BTreeMap::new();
746 nodes.insert(our_pubkey.clone(), NodeInfo {
747 channels: Vec::new(),
748 lowest_inbound_channel_fee_base_msat: u32::max_value(),
749 lowest_inbound_channel_fee_proportional_millionths: u32::max_value(),
750 features: GlobalFeatures::new(),
754 addresses: Vec::new(),
755 announcement_message: None,
758 secp_ctx: Secp256k1::verification_only(),
759 network_map: RwLock::new(NetworkMap {
760 channels: BTreeMap::new(),
761 our_node_id: our_pubkey,
769 /// Dumps the entire network view of this Router to the logger provided in the constructor at
771 pub fn trace_state(&self) {
772 log_trace!(self, "{}", self.network_map.read().unwrap());
775 /// Get network addresses by node id
776 pub fn get_addresses(&self, pubkey: &PublicKey) -> Option<Vec<NetAddress>> {
777 let network = self.network_map.read().unwrap();
778 network.nodes.get(pubkey).map(|n| n.addresses.clone())
781 /// Marks a node as having failed a route. This will avoid re-using the node in routes for now,
782 /// with an exponential decay in node "badness". Note that there is deliberately no
783 /// mark_channel_bad as a node may simply lie and suggest that an upstream channel from it is
784 /// what failed the route and not the node itself. Instead, setting the blamed_upstream_node
785 /// boolean will reduce the penalty, returning the node to usability faster. If the node is
786 /// behaving correctly, it will disable the failing channel and we will use it again next time.
787 pub fn mark_node_bad(&self, _node_id: &PublicKey, _blamed_upstream_node: bool) {
791 fn remove_channel_in_nodes(nodes: &mut BTreeMap<PublicKey, NodeInfo>, chan: &ChannelInfo, short_channel_id: u64) {
792 macro_rules! remove_from_node {
793 ($node_id: expr) => {
794 if let BtreeEntry::Occupied(mut entry) = nodes.entry($node_id) {
795 entry.get_mut().channels.retain(|chan_id| {
796 short_channel_id != *NetworkMap::get_short_id(chan_id)
798 if entry.get().channels.is_empty() {
799 entry.remove_entry();
802 panic!("Had channel that pointed to unknown node (ie inconsistent network map)!");
806 remove_from_node!(chan.one_to_two.src_node_id);
807 remove_from_node!(chan.two_to_one.src_node_id);
810 /// Gets a route from us to the given target node.
812 /// Extra routing hops between known nodes and the target will be used if they are included in
815 /// If some channels aren't announced, it may be useful to fill in a first_hops with the
816 /// results from a local ChannelManager::list_usable_channels() call. If it is filled in, our
817 /// (this Router's) view of our local channels will be ignored, and only those in first_hops
820 /// Panics if first_hops contains channels without short_channel_ids
821 /// (ChannelManager::list_usable_channels will never include such channels).
823 /// The fees on channels from us to next-hops are ignored (as they are assumed to all be
824 /// equal), however the enabled/disabled bit on such channels as well as the htlc_minimum_msat
825 /// *is* checked as they may change based on the receiving node.
826 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> {
827 // TODO: Obviously *only* using total fee cost sucks. We should consider weighting by
828 // uptime/success in using a node in the past.
829 let network = self.network_map.read().unwrap();
831 if *target == network.our_node_id {
832 return Err(HandleError{err: "Cannot generate a route to ourselves", action: None});
835 if final_value_msat > 21_000_000 * 1_0000_0000 * 1000 {
836 return Err(HandleError{err: "Cannot generate a route of more value than all existing satoshis", action: None});
839 // We do a dest-to-source Dijkstra's sorting by each node's distance from the destination
840 // plus the minimum per-HTLC fee to get from it to another node (aka "shitty A*").
841 // TODO: There are a few tweaks we could do, including possibly pre-calculating more stuff
842 // to use as the A* heuristic beyond just the cost to get one node further than the current
845 let dummy_directional_info = DummyDirectionalChannelInfo { // used for first_hops routes
846 src_node_id: network.our_node_id.clone(),
847 cltv_expiry_delta: 0,
848 htlc_minimum_msat: 0,
850 fee_proportional_millionths: 0,
853 let mut targets = BinaryHeap::new(); //TODO: Do we care about switching to eg Fibbonaci heap?
854 let mut dist = HashMap::with_capacity(network.nodes.len());
856 let mut first_hop_targets = HashMap::with_capacity(if first_hops.is_some() { first_hops.as_ref().unwrap().len() } else { 0 });
857 if let Some(hops) = first_hops {
859 let short_channel_id = chan.short_channel_id.expect("first_hops should be filled in with usable channels, not pending ones");
860 if chan.remote_network_id == *target {
862 hops: vec![RouteHop {
863 pubkey: chan.remote_network_id,
865 fee_msat: final_value_msat,
866 cltv_expiry_delta: final_cltv,
870 first_hop_targets.insert(chan.remote_network_id, short_channel_id);
872 if first_hop_targets.is_empty() {
873 return Err(HandleError{err: "Cannot route when there are no outbound routes away from us", action: None});
877 macro_rules! add_entry {
878 // Adds entry which goes from the node pointed to by $directional_info to
879 // $dest_node_id over the channel with id $chan_id with fees described in
880 // $directional_info.
881 ( $chan_id: expr, $dest_node_id: expr, $directional_info: expr, $starting_fee_msat: expr ) => {
882 //TODO: Explore simply adding fee to hit htlc_minimum_msat
883 if $starting_fee_msat as u64 + final_value_msat >= $directional_info.htlc_minimum_msat {
884 let proportional_fee_millions = ($starting_fee_msat + final_value_msat).checked_mul($directional_info.fee_proportional_millionths as u64);
885 if let Some(new_fee) = proportional_fee_millions.and_then(|part| {
886 ($directional_info.fee_base_msat as u64).checked_add(part / 1000000) })
888 let mut total_fee = $starting_fee_msat as u64;
889 let hm_entry = dist.entry(&$directional_info.src_node_id);
890 let old_entry = hm_entry.or_insert_with(|| {
891 let node = network.nodes.get(&$directional_info.src_node_id).unwrap();
893 node.lowest_inbound_channel_fee_base_msat,
894 node.lowest_inbound_channel_fee_proportional_millionths,
896 pubkey: $dest_node_id.clone(),
899 cltv_expiry_delta: 0,
902 if $directional_info.src_node_id != network.our_node_id {
903 // Ignore new_fee for channel-from-us as we assume all channels-from-us
904 // will have the same effective-fee
905 total_fee += new_fee;
906 if let Some(fee_inc) = final_value_msat.checked_add(total_fee).and_then(|inc| { (old_entry.2 as u64).checked_mul(inc) }) {
907 total_fee += fee_inc / 1000000 + (old_entry.1 as u64);
909 // max_value means we'll always fail the old_entry.0 > total_fee check
910 total_fee = u64::max_value();
913 let new_graph_node = RouteGraphNode {
914 pubkey: $directional_info.src_node_id,
915 lowest_fee_to_peer_through_node: total_fee,
916 lowest_fee_to_node: $starting_fee_msat as u64 + new_fee,
918 if old_entry.0 > total_fee {
919 targets.push(new_graph_node);
920 old_entry.0 = total_fee;
921 old_entry.3 = RouteHop {
922 pubkey: $dest_node_id.clone(),
923 short_channel_id: $chan_id.clone(),
924 fee_msat: new_fee, // This field is ignored on the last-hop anyway
925 cltv_expiry_delta: $directional_info.cltv_expiry_delta as u32,
933 macro_rules! add_entries_to_cheapest_to_target_node {
934 ( $node: expr, $node_id: expr, $fee_to_target_msat: expr ) => {
935 if first_hops.is_some() {
936 if let Some(first_hop) = first_hop_targets.get(&$node_id) {
937 add_entry!(first_hop, $node_id, dummy_directional_info, $fee_to_target_msat);
941 for chan_id in $node.channels.iter() {
942 let chan = network.channels.get(chan_id).unwrap();
943 if chan.one_to_two.src_node_id == *$node_id {
944 // ie $node is one, ie next hop in A* is two, via the two_to_one channel
945 if first_hops.is_none() || chan.two_to_one.src_node_id != network.our_node_id {
946 if chan.two_to_one.enabled {
947 add_entry!(chan_id, chan.one_to_two.src_node_id, chan.two_to_one, $fee_to_target_msat);
951 if first_hops.is_none() || chan.one_to_two.src_node_id != network.our_node_id {
952 if chan.one_to_two.enabled {
953 add_entry!(chan_id, chan.two_to_one.src_node_id, chan.one_to_two, $fee_to_target_msat);
961 match network.nodes.get(target) {
964 add_entries_to_cheapest_to_target_node!(node, target, 0);
968 for hop in last_hops.iter() {
969 if first_hops.is_none() || hop.src_node_id != network.our_node_id { // first_hop overrules last_hops
970 if network.nodes.get(&hop.src_node_id).is_some() {
971 if first_hops.is_some() {
972 if let Some(first_hop) = first_hop_targets.get(&hop.src_node_id) {
973 add_entry!(first_hop, hop.src_node_id, dummy_directional_info, 0);
976 add_entry!(hop.short_channel_id, target, hop, 0);
981 while let Some(RouteGraphNode { pubkey, lowest_fee_to_node, .. }) = targets.pop() {
982 if pubkey == network.our_node_id {
983 let mut res = vec!(dist.remove(&network.our_node_id).unwrap().3);
984 while res.last().unwrap().pubkey != *target {
985 let new_entry = match dist.remove(&res.last().unwrap().pubkey) {
987 None => return Err(HandleError{err: "Failed to find a non-fee-overflowing path to the given destination", action: None}),
989 res.last_mut().unwrap().fee_msat = new_entry.fee_msat;
990 res.last_mut().unwrap().cltv_expiry_delta = new_entry.cltv_expiry_delta;
993 res.last_mut().unwrap().fee_msat = final_value_msat;
994 res.last_mut().unwrap().cltv_expiry_delta = final_cltv;
995 let route = Route { hops: res };
996 log_trace!(self, "Got route: {}", log_route!(route));
1000 match network.nodes.get(&pubkey) {
1003 add_entries_to_cheapest_to_target_node!(node, &pubkey, lowest_fee_to_node);
1008 Err(HandleError{err: "Failed to find a path to the given destination", action: None})
1014 use chain::chaininterface;
1015 use ln::channelmanager;
1016 use ln::router::{Router,NodeInfo,NetworkMap,ChannelInfo,DirectionalChannelInfo,RouteHint};
1017 use ln::msgs::GlobalFeatures;
1018 use util::test_utils;
1019 use util::test_utils::TestVecWriter;
1020 use util::logger::Logger;
1021 use util::ser::{Writeable, Readable};
1023 use bitcoin::util::hash::Sha256dHash;
1024 use bitcoin::network::constants::Network;
1028 use secp256k1::key::{PublicKey,SecretKey};
1029 use secp256k1::Secp256k1;
1035 let secp_ctx = Secp256k1::new();
1036 let our_id = PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&hex::decode("0101010101010101010101010101010101010101010101010101010101010101").unwrap()[..]).unwrap());
1037 let logger: Arc<Logger> = Arc::new(test_utils::TestLogger::new());
1038 let chain_monitor = Arc::new(chaininterface::ChainWatchInterfaceUtil::new(Network::Testnet, Arc::clone(&logger)));
1039 let router = Router::new(our_id, chain_monitor, Arc::clone(&logger));
1041 // Build network from our_id to node8:
1043 // -1(1)2- node1 -1(3)2-
1045 // our_id -1(12)2- node8 -1(13)2--- node3
1047 // -1(2)2- node2 -1(4)2-
1050 // chan1 1-to-2: disabled
1051 // chan1 2-to-1: enabled, 0 fee
1053 // chan2 1-to-2: enabled, ignored fee
1054 // chan2 2-to-1: enabled, 0 fee
1056 // chan3 1-to-2: enabled, 0 fee
1057 // chan3 2-to-1: enabled, 100 msat fee
1059 // chan4 1-to-2: enabled, 100% fee
1060 // chan4 2-to-1: enabled, 0 fee
1062 // chan12 1-to-2: enabled, ignored fee
1063 // chan12 2-to-1: enabled, 0 fee
1065 // chan13 1-to-2: enabled, 200% fee
1066 // chan13 2-to-1: enabled, 0 fee
1069 // -1(5)2- node4 -1(8)2--
1073 // node3--1(6)2- node5 -1(9)2--- node7 (not in global route map)
1075 // -1(7)2- node6 -1(10)2-
1077 // chan5 1-to-2: enabled, 100 msat fee
1078 // chan5 2-to-1: enabled, 0 fee
1080 // chan6 1-to-2: enabled, 0 fee
1081 // chan6 2-to-1: enabled, 0 fee
1083 // chan7 1-to-2: enabled, 100% fee
1084 // chan7 2-to-1: enabled, 0 fee
1086 // chan8 1-to-2: enabled, variable fee (0 then 1000 msat)
1087 // chan8 2-to-1: enabled, 0 fee
1089 // chan9 1-to-2: enabled, 1001 msat fee
1090 // chan9 2-to-1: enabled, 0 fee
1092 // chan10 1-to-2: enabled, 0 fee
1093 // chan10 2-to-1: enabled, 0 fee
1095 // chan11 1-to-2: enabled, 0 fee
1096 // chan11 2-to-1: enabled, 0 fee
1098 let node1 = PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&hex::decode("0202020202020202020202020202020202020202020202020202020202020202").unwrap()[..]).unwrap());
1099 let node2 = PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&hex::decode("0303030303030303030303030303030303030303030303030303030303030303").unwrap()[..]).unwrap());
1100 let node3 = PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&hex::decode("0404040404040404040404040404040404040404040404040404040404040404").unwrap()[..]).unwrap());
1101 let node4 = PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&hex::decode("0505050505050505050505050505050505050505050505050505050505050505").unwrap()[..]).unwrap());
1102 let node5 = PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&hex::decode("0606060606060606060606060606060606060606060606060606060606060606").unwrap()[..]).unwrap());
1103 let node6 = PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&hex::decode("0707070707070707070707070707070707070707070707070707070707070707").unwrap()[..]).unwrap());
1104 let node7 = PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&hex::decode("0808080808080808080808080808080808080808080808080808080808080808").unwrap()[..]).unwrap());
1105 let node8 = PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&hex::decode("0909090909090909090909090909090909090909090909090909090909090909").unwrap()[..]).unwrap());
1107 let zero_hash = Sha256dHash::from_data(&[0; 32]);
1110 let mut network = router.network_map.write().unwrap();
1112 network.nodes.insert(node1.clone(), NodeInfo {
1113 channels: vec!(NetworkMap::get_key(1, zero_hash.clone()), NetworkMap::get_key(3, zero_hash.clone())),
1114 lowest_inbound_channel_fee_base_msat: 100,
1115 lowest_inbound_channel_fee_proportional_millionths: 0,
1116 features: GlobalFeatures::new(),
1120 addresses: Vec::new(),
1121 announcement_message: None,
1123 network.channels.insert(NetworkMap::get_key(1, zero_hash.clone()), ChannelInfo {
1124 features: GlobalFeatures::new(),
1125 one_to_two: DirectionalChannelInfo {
1126 src_node_id: our_id.clone(),
1129 cltv_expiry_delta: u16::max_value(), // This value should be ignored
1130 htlc_minimum_msat: 0,
1131 fee_base_msat: u32::max_value(), // This value should be ignored
1132 fee_proportional_millionths: u32::max_value(), // This value should be ignored
1133 last_update_message: None,
1134 }, two_to_one: DirectionalChannelInfo {
1135 src_node_id: node1.clone(),
1138 cltv_expiry_delta: 0,
1139 htlc_minimum_msat: 0,
1141 fee_proportional_millionths: 0,
1142 last_update_message: None,
1144 announcement_message: None,
1146 network.nodes.insert(node2.clone(), NodeInfo {
1147 channels: vec!(NetworkMap::get_key(2, zero_hash.clone()), NetworkMap::get_key(4, zero_hash.clone())),
1148 lowest_inbound_channel_fee_base_msat: 0,
1149 lowest_inbound_channel_fee_proportional_millionths: 0,
1150 features: GlobalFeatures::new(),
1154 addresses: Vec::new(),
1155 announcement_message: None,
1157 network.channels.insert(NetworkMap::get_key(2, zero_hash.clone()), ChannelInfo {
1158 features: GlobalFeatures::new(),
1159 one_to_two: DirectionalChannelInfo {
1160 src_node_id: our_id.clone(),
1163 cltv_expiry_delta: u16::max_value(), // This value should be ignored
1164 htlc_minimum_msat: 0,
1165 fee_base_msat: u32::max_value(), // This value should be ignored
1166 fee_proportional_millionths: u32::max_value(), // This value should be ignored
1167 last_update_message: None,
1168 }, two_to_one: DirectionalChannelInfo {
1169 src_node_id: node2.clone(),
1172 cltv_expiry_delta: 0,
1173 htlc_minimum_msat: 0,
1175 fee_proportional_millionths: 0,
1176 last_update_message: None,
1178 announcement_message: None,
1180 network.nodes.insert(node8.clone(), NodeInfo {
1181 channels: vec!(NetworkMap::get_key(12, zero_hash.clone()), NetworkMap::get_key(13, zero_hash.clone())),
1182 lowest_inbound_channel_fee_base_msat: 0,
1183 lowest_inbound_channel_fee_proportional_millionths: 0,
1184 features: GlobalFeatures::new(),
1188 addresses: Vec::new(),
1189 announcement_message: None,
1191 network.channels.insert(NetworkMap::get_key(12, zero_hash.clone()), ChannelInfo {
1192 features: GlobalFeatures::new(),
1193 one_to_two: DirectionalChannelInfo {
1194 src_node_id: our_id.clone(),
1197 cltv_expiry_delta: u16::max_value(), // This value should be ignored
1198 htlc_minimum_msat: 0,
1199 fee_base_msat: u32::max_value(), // This value should be ignored
1200 fee_proportional_millionths: u32::max_value(), // This value should be ignored
1201 last_update_message: None,
1202 }, two_to_one: DirectionalChannelInfo {
1203 src_node_id: node8.clone(),
1206 cltv_expiry_delta: 0,
1207 htlc_minimum_msat: 0,
1209 fee_proportional_millionths: 0,
1210 last_update_message: None,
1212 announcement_message: None,
1214 network.nodes.insert(node3.clone(), NodeInfo {
1216 NetworkMap::get_key(3, zero_hash.clone()),
1217 NetworkMap::get_key(4, zero_hash.clone()),
1218 NetworkMap::get_key(13, zero_hash.clone()),
1219 NetworkMap::get_key(5, zero_hash.clone()),
1220 NetworkMap::get_key(6, zero_hash.clone()),
1221 NetworkMap::get_key(7, zero_hash.clone())),
1222 lowest_inbound_channel_fee_base_msat: 0,
1223 lowest_inbound_channel_fee_proportional_millionths: 0,
1224 features: GlobalFeatures::new(),
1228 addresses: Vec::new(),
1229 announcement_message: None,
1231 network.channels.insert(NetworkMap::get_key(3, zero_hash.clone()), ChannelInfo {
1232 features: GlobalFeatures::new(),
1233 one_to_two: DirectionalChannelInfo {
1234 src_node_id: node1.clone(),
1237 cltv_expiry_delta: (3 << 8) | 1,
1238 htlc_minimum_msat: 0,
1240 fee_proportional_millionths: 0,
1241 last_update_message: None,
1242 }, two_to_one: DirectionalChannelInfo {
1243 src_node_id: node3.clone(),
1246 cltv_expiry_delta: (3 << 8) | 2,
1247 htlc_minimum_msat: 0,
1249 fee_proportional_millionths: 0,
1250 last_update_message: None,
1252 announcement_message: None,
1254 network.channels.insert(NetworkMap::get_key(4, zero_hash.clone()), ChannelInfo {
1255 features: GlobalFeatures::new(),
1256 one_to_two: DirectionalChannelInfo {
1257 src_node_id: node2.clone(),
1260 cltv_expiry_delta: (4 << 8) | 1,
1261 htlc_minimum_msat: 0,
1263 fee_proportional_millionths: 1000000,
1264 last_update_message: None,
1265 }, two_to_one: DirectionalChannelInfo {
1266 src_node_id: node3.clone(),
1269 cltv_expiry_delta: (4 << 8) | 2,
1270 htlc_minimum_msat: 0,
1272 fee_proportional_millionths: 0,
1273 last_update_message: None,
1275 announcement_message: None,
1277 network.channels.insert(NetworkMap::get_key(13, zero_hash.clone()), ChannelInfo {
1278 features: GlobalFeatures::new(),
1279 one_to_two: DirectionalChannelInfo {
1280 src_node_id: node8.clone(),
1283 cltv_expiry_delta: (13 << 8) | 1,
1284 htlc_minimum_msat: 0,
1286 fee_proportional_millionths: 2000000,
1287 last_update_message: None,
1288 }, two_to_one: DirectionalChannelInfo {
1289 src_node_id: node3.clone(),
1292 cltv_expiry_delta: (13 << 8) | 2,
1293 htlc_minimum_msat: 0,
1295 fee_proportional_millionths: 0,
1296 last_update_message: None,
1298 announcement_message: None,
1300 network.nodes.insert(node4.clone(), NodeInfo {
1301 channels: vec!(NetworkMap::get_key(5, zero_hash.clone()), NetworkMap::get_key(11, zero_hash.clone())),
1302 lowest_inbound_channel_fee_base_msat: 0,
1303 lowest_inbound_channel_fee_proportional_millionths: 0,
1304 features: GlobalFeatures::new(),
1308 addresses: Vec::new(),
1309 announcement_message: None,
1311 network.channels.insert(NetworkMap::get_key(5, zero_hash.clone()), ChannelInfo {
1312 features: GlobalFeatures::new(),
1313 one_to_two: DirectionalChannelInfo {
1314 src_node_id: node3.clone(),
1317 cltv_expiry_delta: (5 << 8) | 1,
1318 htlc_minimum_msat: 0,
1320 fee_proportional_millionths: 0,
1321 last_update_message: None,
1322 }, two_to_one: DirectionalChannelInfo {
1323 src_node_id: node4.clone(),
1326 cltv_expiry_delta: (5 << 8) | 2,
1327 htlc_minimum_msat: 0,
1329 fee_proportional_millionths: 0,
1330 last_update_message: None,
1332 announcement_message: None,
1334 network.nodes.insert(node5.clone(), NodeInfo {
1335 channels: vec!(NetworkMap::get_key(6, zero_hash.clone()), NetworkMap::get_key(11, zero_hash.clone())),
1336 lowest_inbound_channel_fee_base_msat: 0,
1337 lowest_inbound_channel_fee_proportional_millionths: 0,
1338 features: GlobalFeatures::new(),
1342 addresses: Vec::new(),
1343 announcement_message: None,
1345 network.channels.insert(NetworkMap::get_key(6, zero_hash.clone()), ChannelInfo {
1346 features: GlobalFeatures::new(),
1347 one_to_two: DirectionalChannelInfo {
1348 src_node_id: node3.clone(),
1351 cltv_expiry_delta: (6 << 8) | 1,
1352 htlc_minimum_msat: 0,
1354 fee_proportional_millionths: 0,
1355 last_update_message: None,
1356 }, two_to_one: DirectionalChannelInfo {
1357 src_node_id: node5.clone(),
1360 cltv_expiry_delta: (6 << 8) | 2,
1361 htlc_minimum_msat: 0,
1363 fee_proportional_millionths: 0,
1364 last_update_message: None,
1366 announcement_message: None,
1368 network.channels.insert(NetworkMap::get_key(11, zero_hash.clone()), ChannelInfo {
1369 features: GlobalFeatures::new(),
1370 one_to_two: DirectionalChannelInfo {
1371 src_node_id: node5.clone(),
1374 cltv_expiry_delta: (11 << 8) | 1,
1375 htlc_minimum_msat: 0,
1377 fee_proportional_millionths: 0,
1378 last_update_message: None,
1379 }, two_to_one: DirectionalChannelInfo {
1380 src_node_id: node4.clone(),
1383 cltv_expiry_delta: (11 << 8) | 2,
1384 htlc_minimum_msat: 0,
1386 fee_proportional_millionths: 0,
1387 last_update_message: None,
1389 announcement_message: None,
1391 network.nodes.insert(node6.clone(), NodeInfo {
1392 channels: vec!(NetworkMap::get_key(7, zero_hash.clone())),
1393 lowest_inbound_channel_fee_base_msat: 0,
1394 lowest_inbound_channel_fee_proportional_millionths: 0,
1395 features: GlobalFeatures::new(),
1399 addresses: Vec::new(),
1400 announcement_message: None,
1402 network.channels.insert(NetworkMap::get_key(7, zero_hash.clone()), ChannelInfo {
1403 features: GlobalFeatures::new(),
1404 one_to_two: DirectionalChannelInfo {
1405 src_node_id: node3.clone(),
1408 cltv_expiry_delta: (7 << 8) | 1,
1409 htlc_minimum_msat: 0,
1411 fee_proportional_millionths: 1000000,
1412 last_update_message: None,
1413 }, two_to_one: DirectionalChannelInfo {
1414 src_node_id: node6.clone(),
1417 cltv_expiry_delta: (7 << 8) | 2,
1418 htlc_minimum_msat: 0,
1420 fee_proportional_millionths: 0,
1421 last_update_message: None,
1423 announcement_message: None,
1427 { // Simple route to 3 via 2
1428 let route = router.get_route(&node3, None, &Vec::new(), 100, 42).unwrap();
1429 assert_eq!(route.hops.len(), 2);
1431 assert_eq!(route.hops[0].pubkey, node2);
1432 assert_eq!(route.hops[0].short_channel_id, 2);
1433 assert_eq!(route.hops[0].fee_msat, 100);
1434 assert_eq!(route.hops[0].cltv_expiry_delta, (4 << 8) | 1);
1436 assert_eq!(route.hops[1].pubkey, node3);
1437 assert_eq!(route.hops[1].short_channel_id, 4);
1438 assert_eq!(route.hops[1].fee_msat, 100);
1439 assert_eq!(route.hops[1].cltv_expiry_delta, 42);
1442 { // Route to 1 via 2 and 3 because our channel to 1 is disabled
1443 let route = router.get_route(&node1, None, &Vec::new(), 100, 42).unwrap();
1444 assert_eq!(route.hops.len(), 3);
1446 assert_eq!(route.hops[0].pubkey, node2);
1447 assert_eq!(route.hops[0].short_channel_id, 2);
1448 assert_eq!(route.hops[0].fee_msat, 200);
1449 assert_eq!(route.hops[0].cltv_expiry_delta, (4 << 8) | 1);
1451 assert_eq!(route.hops[1].pubkey, node3);
1452 assert_eq!(route.hops[1].short_channel_id, 4);
1453 assert_eq!(route.hops[1].fee_msat, 100);
1454 assert_eq!(route.hops[1].cltv_expiry_delta, (3 << 8) | 2);
1456 assert_eq!(route.hops[2].pubkey, node1);
1457 assert_eq!(route.hops[2].short_channel_id, 3);
1458 assert_eq!(route.hops[2].fee_msat, 100);
1459 assert_eq!(route.hops[2].cltv_expiry_delta, 42);
1462 { // If we specify a channel to node8, that overrides our local channel view and that gets used
1463 let our_chans = vec![channelmanager::ChannelDetails {
1464 channel_id: [0; 32],
1465 short_channel_id: Some(42),
1466 remote_network_id: node8.clone(),
1467 channel_value_satoshis: 0,
1470 let route = router.get_route(&node3, Some(&our_chans), &Vec::new(), 100, 42).unwrap();
1471 assert_eq!(route.hops.len(), 2);
1473 assert_eq!(route.hops[0].pubkey, node8);
1474 assert_eq!(route.hops[0].short_channel_id, 42);
1475 assert_eq!(route.hops[0].fee_msat, 200);
1476 assert_eq!(route.hops[0].cltv_expiry_delta, (13 << 8) | 1);
1478 assert_eq!(route.hops[1].pubkey, node3);
1479 assert_eq!(route.hops[1].short_channel_id, 13);
1480 assert_eq!(route.hops[1].fee_msat, 100);
1481 assert_eq!(route.hops[1].cltv_expiry_delta, 42);
1484 let mut last_hops = vec!(RouteHint {
1485 src_node_id: node4.clone(),
1486 short_channel_id: 8,
1488 fee_proportional_millionths: 0,
1489 cltv_expiry_delta: (8 << 8) | 1,
1490 htlc_minimum_msat: 0,
1492 src_node_id: node5.clone(),
1493 short_channel_id: 9,
1494 fee_base_msat: 1001,
1495 fee_proportional_millionths: 0,
1496 cltv_expiry_delta: (9 << 8) | 1,
1497 htlc_minimum_msat: 0,
1499 src_node_id: node6.clone(),
1500 short_channel_id: 10,
1502 fee_proportional_millionths: 0,
1503 cltv_expiry_delta: (10 << 8) | 1,
1504 htlc_minimum_msat: 0,
1507 { // Simple test across 2, 3, 5, and 4 via a last_hop channel
1508 let route = router.get_route(&node7, None, &last_hops, 100, 42).unwrap();
1509 assert_eq!(route.hops.len(), 5);
1511 assert_eq!(route.hops[0].pubkey, node2);
1512 assert_eq!(route.hops[0].short_channel_id, 2);
1513 assert_eq!(route.hops[0].fee_msat, 100);
1514 assert_eq!(route.hops[0].cltv_expiry_delta, (4 << 8) | 1);
1516 assert_eq!(route.hops[1].pubkey, node3);
1517 assert_eq!(route.hops[1].short_channel_id, 4);
1518 assert_eq!(route.hops[1].fee_msat, 0);
1519 assert_eq!(route.hops[1].cltv_expiry_delta, (6 << 8) | 1);
1521 assert_eq!(route.hops[2].pubkey, node5);
1522 assert_eq!(route.hops[2].short_channel_id, 6);
1523 assert_eq!(route.hops[2].fee_msat, 0);
1524 assert_eq!(route.hops[2].cltv_expiry_delta, (11 << 8) | 1);
1526 assert_eq!(route.hops[3].pubkey, node4);
1527 assert_eq!(route.hops[3].short_channel_id, 11);
1528 assert_eq!(route.hops[3].fee_msat, 0);
1529 assert_eq!(route.hops[3].cltv_expiry_delta, (8 << 8) | 1);
1531 assert_eq!(route.hops[4].pubkey, node7);
1532 assert_eq!(route.hops[4].short_channel_id, 8);
1533 assert_eq!(route.hops[4].fee_msat, 100);
1534 assert_eq!(route.hops[4].cltv_expiry_delta, 42);
1537 { // Simple test with outbound channel to 4 to test that last_hops and first_hops connect
1538 let our_chans = vec![channelmanager::ChannelDetails {
1539 channel_id: [0; 32],
1540 short_channel_id: Some(42),
1541 remote_network_id: node4.clone(),
1542 channel_value_satoshis: 0,
1545 let route = router.get_route(&node7, Some(&our_chans), &last_hops, 100, 42).unwrap();
1546 assert_eq!(route.hops.len(), 2);
1548 assert_eq!(route.hops[0].pubkey, node4);
1549 assert_eq!(route.hops[0].short_channel_id, 42);
1550 assert_eq!(route.hops[0].fee_msat, 0);
1551 assert_eq!(route.hops[0].cltv_expiry_delta, (8 << 8) | 1);
1553 assert_eq!(route.hops[1].pubkey, node7);
1554 assert_eq!(route.hops[1].short_channel_id, 8);
1555 assert_eq!(route.hops[1].fee_msat, 100);
1556 assert_eq!(route.hops[1].cltv_expiry_delta, 42);
1559 last_hops[0].fee_base_msat = 1000;
1561 { // Revert to via 6 as the fee on 8 goes up
1562 let route = router.get_route(&node7, None, &last_hops, 100, 42).unwrap();
1563 assert_eq!(route.hops.len(), 4);
1565 assert_eq!(route.hops[0].pubkey, node2);
1566 assert_eq!(route.hops[0].short_channel_id, 2);
1567 assert_eq!(route.hops[0].fee_msat, 200); // fee increased as its % of value transferred across node
1568 assert_eq!(route.hops[0].cltv_expiry_delta, (4 << 8) | 1);
1570 assert_eq!(route.hops[1].pubkey, node3);
1571 assert_eq!(route.hops[1].short_channel_id, 4);
1572 assert_eq!(route.hops[1].fee_msat, 100);
1573 assert_eq!(route.hops[1].cltv_expiry_delta, (7 << 8) | 1);
1575 assert_eq!(route.hops[2].pubkey, node6);
1576 assert_eq!(route.hops[2].short_channel_id, 7);
1577 assert_eq!(route.hops[2].fee_msat, 0);
1578 assert_eq!(route.hops[2].cltv_expiry_delta, (10 << 8) | 1);
1580 assert_eq!(route.hops[3].pubkey, node7);
1581 assert_eq!(route.hops[3].short_channel_id, 10);
1582 assert_eq!(route.hops[3].fee_msat, 100);
1583 assert_eq!(route.hops[3].cltv_expiry_delta, 42);
1586 { // ...but still use 8 for larger payments as 6 has a variable feerate
1587 let route = router.get_route(&node7, None, &last_hops, 2000, 42).unwrap();
1588 assert_eq!(route.hops.len(), 5);
1590 assert_eq!(route.hops[0].pubkey, node2);
1591 assert_eq!(route.hops[0].short_channel_id, 2);
1592 assert_eq!(route.hops[0].fee_msat, 3000);
1593 assert_eq!(route.hops[0].cltv_expiry_delta, (4 << 8) | 1);
1595 assert_eq!(route.hops[1].pubkey, node3);
1596 assert_eq!(route.hops[1].short_channel_id, 4);
1597 assert_eq!(route.hops[1].fee_msat, 0);
1598 assert_eq!(route.hops[1].cltv_expiry_delta, (6 << 8) | 1);
1600 assert_eq!(route.hops[2].pubkey, node5);
1601 assert_eq!(route.hops[2].short_channel_id, 6);
1602 assert_eq!(route.hops[2].fee_msat, 0);
1603 assert_eq!(route.hops[2].cltv_expiry_delta, (11 << 8) | 1);
1605 assert_eq!(route.hops[3].pubkey, node4);
1606 assert_eq!(route.hops[3].short_channel_id, 11);
1607 assert_eq!(route.hops[3].fee_msat, 1000);
1608 assert_eq!(route.hops[3].cltv_expiry_delta, (8 << 8) | 1);
1610 assert_eq!(route.hops[4].pubkey, node7);
1611 assert_eq!(route.hops[4].short_channel_id, 8);
1612 assert_eq!(route.hops[4].fee_msat, 2000);
1613 assert_eq!(route.hops[4].cltv_expiry_delta, 42);
1616 { // Test Router serialization/deserialization
1617 let mut w = TestVecWriter(Vec::new());
1618 let network = router.network_map.read().unwrap();
1619 assert!(!network.channels.is_empty());
1620 assert!(!network.nodes.is_empty());
1621 network.write(&mut w).unwrap();
1622 assert!(<NetworkMap>::read(&mut ::std::io::Cursor::new(&w.0)).unwrap() == *network);