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_hashes::sha256d::Hash as Sha256dHash;
11 use bitcoin_hashes::Hash;
12 use bitcoin::blockdata::script::Builder;
13 use bitcoin::blockdata::opcodes;
15 use chain::chaininterface::{ChainError, ChainWatchInterface};
16 use ln::channelmanager;
17 use ln::msgs::{DecodeError,ErrorAction,LightningError,RoutingMessageHandler,NetAddress,ChannelFeatures,NodeFeatures};
19 use util::ser::{Writeable, Readable, Writer, ReadableArgs};
20 use util::logger::Logger;
23 use std::sync::{RwLock,Arc};
24 use std::collections::{HashMap,BinaryHeap,BTreeMap};
25 use std::collections::btree_map::Entry as BtreeEntry;
29 #[derive(Clone, PartialEq)]
31 /// The node_id of the node at this hop.
32 pub pubkey: PublicKey,
33 /// The channel that should be used from the previous hop to reach this node.
34 pub short_channel_id: u64,
35 /// The fee taken on this hop. For the last hop, this should be the full value of the payment.
37 /// The CLTV delta added for this hop. For the last hop, this should be the full CLTV value
38 /// expected at the destination, in excess of the current block height.
39 pub cltv_expiry_delta: u32,
42 /// A route from us through the network to a destination
43 #[derive(Clone, PartialEq)]
45 /// The list of hops, NOT INCLUDING our own, where the last hop is the destination. Thus, this
46 /// must always be at least length one. By protocol rules, this may not currently exceed 20 in
48 pub hops: Vec<RouteHop>,
51 impl Writeable for Route {
52 fn write<W: ::util::ser::Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
53 (self.hops.len() as u8).write(writer)?;
54 for hop in self.hops.iter() {
55 hop.pubkey.write(writer)?;
56 hop.short_channel_id.write(writer)?;
57 hop.fee_msat.write(writer)?;
58 hop.cltv_expiry_delta.write(writer)?;
64 impl<R: ::std::io::Read> Readable<R> for Route {
65 fn read(reader: &mut R) -> Result<Route, DecodeError> {
66 let hops_count: u8 = Readable::read(reader)?;
67 let mut hops = Vec::with_capacity(hops_count as usize);
68 for _ in 0..hops_count {
70 pubkey: Readable::read(reader)?,
71 short_channel_id: Readable::read(reader)?,
72 fee_msat: Readable::read(reader)?,
73 cltv_expiry_delta: Readable::read(reader)?,
83 struct DirectionalChannelInfo {
84 src_node_id: PublicKey,
87 cltv_expiry_delta: u16,
88 htlc_minimum_msat: u64,
90 fee_proportional_millionths: u32,
91 last_update_message: Option<msgs::ChannelUpdate>,
94 impl std::fmt::Display for DirectionalChannelInfo {
95 fn fmt(&self, f: &mut std::fmt::Formatter) -> Result<(), std::fmt::Error> {
96 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)?;
101 impl_writeable!(DirectionalChannelInfo, 0, {
108 fee_proportional_millionths,
114 features: ChannelFeatures,
115 one_to_two: DirectionalChannelInfo,
116 two_to_one: DirectionalChannelInfo,
117 //this is cached here so we can send out it later if required by route_init_sync
118 //keep an eye on this to see if the extra memory is a problem
119 announcement_message: Option<msgs::ChannelAnnouncement>,
122 impl std::fmt::Display for ChannelInfo {
123 fn fmt(&self, f: &mut std::fmt::Formatter) -> Result<(), std::fmt::Error> {
124 write!(f, "features: {}, one_to_two: {}, two_to_one: {}", log_bytes!(self.features.encode()), self.one_to_two, self.two_to_one)?;
129 impl_writeable!(ChannelInfo, 0, {
138 #[cfg(feature = "non_bitcoin_chain_hash_routing")]
139 channels: Vec<(u64, Sha256dHash)>,
140 #[cfg(not(feature = "non_bitcoin_chain_hash_routing"))]
143 lowest_inbound_channel_fee_base_msat: u32,
144 lowest_inbound_channel_fee_proportional_millionths: u32,
146 features: NodeFeatures,
150 addresses: Vec<NetAddress>,
151 //this is cached here so we can send out it later if required by route_init_sync
152 //keep an eye on this to see if the extra memory is a problem
153 announcement_message: Option<msgs::NodeAnnouncement>,
156 impl std::fmt::Display for NodeInfo {
157 fn fmt(&self, f: &mut std::fmt::Formatter) -> Result<(), std::fmt::Error> {
158 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[..])?;
163 impl Writeable for NodeInfo {
164 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
165 (self.channels.len() as u64).write(writer)?;
166 for ref chan in self.channels.iter() {
169 self.lowest_inbound_channel_fee_base_msat.write(writer)?;
170 self.lowest_inbound_channel_fee_proportional_millionths.write(writer)?;
171 self.features.write(writer)?;
172 self.last_update.write(writer)?;
173 self.rgb.write(writer)?;
174 self.alias.write(writer)?;
175 (self.addresses.len() as u64).write(writer)?;
176 for ref addr in &self.addresses {
179 self.announcement_message.write(writer)?;
184 const MAX_ALLOC_SIZE: u64 = 64*1024;
186 impl<R: ::std::io::Read> Readable<R> for NodeInfo {
187 fn read(reader: &mut R) -> Result<NodeInfo, DecodeError> {
188 let channels_count: u64 = Readable::read(reader)?;
189 let mut channels = Vec::with_capacity(cmp::min(channels_count, MAX_ALLOC_SIZE / 8) as usize);
190 for _ in 0..channels_count {
191 channels.push(Readable::read(reader)?);
193 let lowest_inbound_channel_fee_base_msat = Readable::read(reader)?;
194 let lowest_inbound_channel_fee_proportional_millionths = Readable::read(reader)?;
195 let features = Readable::read(reader)?;
196 let last_update = Readable::read(reader)?;
197 let rgb = Readable::read(reader)?;
198 let alias = Readable::read(reader)?;
199 let addresses_count: u64 = Readable::read(reader)?;
200 let mut addresses = Vec::with_capacity(cmp::min(addresses_count, MAX_ALLOC_SIZE / 40) as usize);
201 for _ in 0..addresses_count {
202 match Readable::read(reader) {
203 Ok(Ok(addr)) => { addresses.push(addr); },
204 Ok(Err(_)) => return Err(DecodeError::InvalidValue),
205 Err(DecodeError::ShortRead) => return Err(DecodeError::BadLengthDescriptor),
209 let announcement_message = Readable::read(reader)?;
212 lowest_inbound_channel_fee_base_msat,
213 lowest_inbound_channel_fee_proportional_millionths,
226 #[cfg(feature = "non_bitcoin_chain_hash_routing")]
227 channels: BTreeMap<(u64, Sha256dHash), ChannelInfo>,
228 #[cfg(not(feature = "non_bitcoin_chain_hash_routing"))]
229 channels: BTreeMap<u64, ChannelInfo>,
231 our_node_id: PublicKey,
232 nodes: BTreeMap<PublicKey, NodeInfo>,
235 impl Writeable for NetworkMap {
236 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
237 (self.channels.len() as u64).write(writer)?;
238 for (ref chan_id, ref chan_info) in self.channels.iter() {
239 (*chan_id).write(writer)?;
240 chan_info.write(writer)?;
242 self.our_node_id.write(writer)?;
243 (self.nodes.len() as u64).write(writer)?;
244 for (ref node_id, ref node_info) in self.nodes.iter() {
245 node_id.write(writer)?;
246 node_info.write(writer)?;
252 impl<R: ::std::io::Read> Readable<R> for NetworkMap {
253 fn read(reader: &mut R) -> Result<NetworkMap, DecodeError> {
254 let channels_count: u64 = Readable::read(reader)?;
255 let mut channels = BTreeMap::new();
256 for _ in 0..channels_count {
257 let chan_id: u64 = Readable::read(reader)?;
258 let chan_info = Readable::read(reader)?;
259 channels.insert(chan_id, chan_info);
261 let our_node_id = Readable::read(reader)?;
262 let nodes_count: u64 = Readable::read(reader)?;
263 let mut nodes = BTreeMap::new();
264 for _ in 0..nodes_count {
265 let node_id = Readable::read(reader)?;
266 let node_info = Readable::read(reader)?;
267 nodes.insert(node_id, node_info);
277 struct MutNetworkMap<'a> {
278 #[cfg(feature = "non_bitcoin_chain_hash_routing")]
279 channels: &'a mut BTreeMap<(u64, Sha256dHash), ChannelInfo>,
280 #[cfg(not(feature = "non_bitcoin_chain_hash_routing"))]
281 channels: &'a mut BTreeMap<u64, ChannelInfo>,
282 nodes: &'a mut BTreeMap<PublicKey, NodeInfo>,
285 fn borrow_parts(&mut self) -> MutNetworkMap {
287 channels: &mut self.channels,
288 nodes: &mut self.nodes,
292 impl std::fmt::Display for NetworkMap {
293 fn fmt(&self, f: &mut std::fmt::Formatter) -> Result<(), std::fmt::Error> {
294 write!(f, "Node id {} network map\n[Channels]\n", log_pubkey!(self.our_node_id))?;
295 for (key, val) in self.channels.iter() {
296 write!(f, " {}: {}\n", key, val)?;
298 write!(f, "[Nodes]\n")?;
299 for (key, val) in self.nodes.iter() {
300 write!(f, " {}: {}\n", log_pubkey!(key), val)?;
307 #[cfg(feature = "non_bitcoin_chain_hash_routing")]
309 fn get_key(short_channel_id: u64, chain_hash: Sha256dHash) -> (u64, Sha256dHash) {
310 (short_channel_id, chain_hash)
313 #[cfg(not(feature = "non_bitcoin_chain_hash_routing"))]
315 fn get_key(short_channel_id: u64, _: Sha256dHash) -> u64 {
319 #[cfg(feature = "non_bitcoin_chain_hash_routing")]
321 fn get_short_id(id: &(u64, Sha256dHash)) -> &u64 {
325 #[cfg(not(feature = "non_bitcoin_chain_hash_routing"))]
327 fn get_short_id(id: &u64) -> &u64 {
332 /// A channel descriptor which provides a last-hop route to get_route
333 pub struct RouteHint {
334 /// The node_id of the non-target end of the route
335 pub src_node_id: PublicKey,
336 /// The short_channel_id of this channel
337 pub short_channel_id: u64,
338 /// The static msat-denominated fee which must be paid to use this channel
339 pub fee_base_msat: u32,
340 /// The dynamic proportional fee which must be paid to use this channel, denominated in
341 /// millionths of the value being forwarded to the next hop.
342 pub fee_proportional_millionths: u32,
343 /// The difference in CLTV values between this node and the next node.
344 pub cltv_expiry_delta: u16,
345 /// The minimum value, in msat, which must be relayed to the next hop.
346 pub htlc_minimum_msat: u64,
349 /// Tracks a view of the network, receiving updates from peers and generating Routes to
350 /// payment destinations.
352 secp_ctx: Secp256k1<secp256k1::VerifyOnly>,
353 network_map: RwLock<NetworkMap>,
354 chain_monitor: Arc<ChainWatchInterface>,
358 const SERIALIZATION_VERSION: u8 = 1;
359 const MIN_SERIALIZATION_VERSION: u8 = 1;
361 impl Writeable for Router {
362 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
363 writer.write_all(&[SERIALIZATION_VERSION; 1])?;
364 writer.write_all(&[MIN_SERIALIZATION_VERSION; 1])?;
366 let network = self.network_map.read().unwrap();
367 network.write(writer)?;
372 /// Arguments for the creation of a Router that are not deserialized.
373 /// At a high-level, the process for deserializing a Router and resuming normal operation is:
374 /// 1) Deserialize the Router by filling in this struct and calling <Router>::read(reaser, args).
375 /// 2) Register the new Router with your ChainWatchInterface
376 pub struct RouterReadArgs {
377 /// The ChainWatchInterface for use in the Router in the future.
379 /// No calls to the ChainWatchInterface will be made during deserialization.
380 pub chain_monitor: Arc<ChainWatchInterface>,
381 /// The Logger for use in the ChannelManager and which may be used to log information during
383 pub logger: Arc<Logger>,
386 impl<R: ::std::io::Read> ReadableArgs<R, RouterReadArgs> for Router {
387 fn read(reader: &mut R, args: RouterReadArgs) -> Result<Router, DecodeError> {
388 let _ver: u8 = Readable::read(reader)?;
389 let min_ver: u8 = Readable::read(reader)?;
390 if min_ver > SERIALIZATION_VERSION {
391 return Err(DecodeError::UnknownVersion);
393 let network_map = Readable::read(reader)?;
395 secp_ctx: Secp256k1::verification_only(),
396 network_map: RwLock::new(network_map),
397 chain_monitor: args.chain_monitor,
403 macro_rules! secp_verify_sig {
404 ( $secp_ctx: expr, $msg: expr, $sig: expr, $pubkey: expr ) => {
405 match $secp_ctx.verify($msg, $sig, $pubkey) {
407 Err(_) => return Err(LightningError{err: "Invalid signature from remote node", action: ErrorAction::IgnoreError}),
412 impl RoutingMessageHandler for Router {
413 fn handle_node_announcement(&self, msg: &msgs::NodeAnnouncement) -> Result<bool, LightningError> {
414 let msg_hash = hash_to_message!(&Sha256dHash::hash(&msg.contents.encode()[..])[..]);
415 secp_verify_sig!(self.secp_ctx, &msg_hash, &msg.signature, &msg.contents.node_id);
417 let mut network = self.network_map.write().unwrap();
418 match network.nodes.get_mut(&msg.contents.node_id) {
419 None => Err(LightningError{err: "No existing channels for node_announcement", action: ErrorAction::IgnoreError}),
421 if node.last_update >= msg.contents.timestamp {
422 return Err(LightningError{err: "Update older than last processed update", action: ErrorAction::IgnoreError});
425 node.features = msg.contents.features.clone();
426 node.last_update = msg.contents.timestamp;
427 node.rgb = msg.contents.rgb;
428 node.alias = msg.contents.alias;
429 node.addresses = msg.contents.addresses.clone();
431 let should_relay = msg.contents.excess_data.is_empty() && msg.contents.excess_address_data.is_empty();
432 node.announcement_message = if should_relay { Some(msg.clone()) } else { None };
438 fn handle_channel_announcement(&self, msg: &msgs::ChannelAnnouncement) -> Result<bool, LightningError> {
439 if msg.contents.node_id_1 == msg.contents.node_id_2 || msg.contents.bitcoin_key_1 == msg.contents.bitcoin_key_2 {
440 return Err(LightningError{err: "Channel announcement node had a channel with itself", action: ErrorAction::IgnoreError});
443 let msg_hash = hash_to_message!(&Sha256dHash::hash(&msg.contents.encode()[..])[..]);
444 secp_verify_sig!(self.secp_ctx, &msg_hash, &msg.node_signature_1, &msg.contents.node_id_1);
445 secp_verify_sig!(self.secp_ctx, &msg_hash, &msg.node_signature_2, &msg.contents.node_id_2);
446 secp_verify_sig!(self.secp_ctx, &msg_hash, &msg.bitcoin_signature_1, &msg.contents.bitcoin_key_1);
447 secp_verify_sig!(self.secp_ctx, &msg_hash, &msg.bitcoin_signature_2, &msg.contents.bitcoin_key_2);
449 let checked_utxo = match self.chain_monitor.get_chain_utxo(msg.contents.chain_hash, msg.contents.short_channel_id) {
450 Ok((script_pubkey, _value)) => {
451 let expected_script = Builder::new().push_opcode(opcodes::all::OP_PUSHNUM_2)
452 .push_slice(&msg.contents.bitcoin_key_1.serialize())
453 .push_slice(&msg.contents.bitcoin_key_2.serialize())
454 .push_opcode(opcodes::all::OP_PUSHNUM_2)
455 .push_opcode(opcodes::all::OP_CHECKMULTISIG).into_script().to_v0_p2wsh();
456 if script_pubkey != expected_script {
457 return Err(LightningError{err: "Channel announcement keys didn't match on-chain script", action: ErrorAction::IgnoreError});
459 //TODO: Check if value is worth storing, use it to inform routing, and compare it
460 //to the new HTLC max field in channel_update
463 Err(ChainError::NotSupported) => {
464 // Tentatively accept, potentially exposing us to DoS attacks
467 Err(ChainError::NotWatched) => {
468 return Err(LightningError{err: "Channel announced on an unknown chain", action: ErrorAction::IgnoreError});
470 Err(ChainError::UnknownTx) => {
471 return Err(LightningError{err: "Channel announced without corresponding UTXO entry", action: ErrorAction::IgnoreError});
475 let mut network_lock = self.network_map.write().unwrap();
476 let network = network_lock.borrow_parts();
478 let should_relay = msg.contents.excess_data.is_empty();
480 let chan_info = ChannelInfo {
481 features: msg.contents.features.clone(),
482 one_to_two: DirectionalChannelInfo {
483 src_node_id: msg.contents.node_id_1.clone(),
486 cltv_expiry_delta: u16::max_value(),
487 htlc_minimum_msat: u64::max_value(),
488 fee_base_msat: u32::max_value(),
489 fee_proportional_millionths: u32::max_value(),
490 last_update_message: None,
492 two_to_one: DirectionalChannelInfo {
493 src_node_id: msg.contents.node_id_2.clone(),
496 cltv_expiry_delta: u16::max_value(),
497 htlc_minimum_msat: u64::max_value(),
498 fee_base_msat: u32::max_value(),
499 fee_proportional_millionths: u32::max_value(),
500 last_update_message: None,
502 announcement_message: if should_relay { Some(msg.clone()) } else { None },
505 match network.channels.entry(NetworkMap::get_key(msg.contents.short_channel_id, msg.contents.chain_hash)) {
506 BtreeEntry::Occupied(mut entry) => {
507 //TODO: because asking the blockchain if short_channel_id is valid is only optional
508 //in the blockchain API, we need to handle it smartly here, though it's unclear
511 // Either our UTXO provider is busted, there was a reorg, or the UTXO provider
512 // only sometimes returns results. In any case remove the previous entry. Note
513 // that the spec expects us to "blacklist" the node_ids involved, but we can't
515 // a) we don't *require* a UTXO provider that always returns results.
516 // b) we don't track UTXOs of channels we know about and remove them if they
518 // c) it's unclear how to do so without exposing ourselves to massive DoS risk.
519 Self::remove_channel_in_nodes(network.nodes, &entry.get(), msg.contents.short_channel_id);
520 *entry.get_mut() = chan_info;
522 return Err(LightningError{err: "Already have knowledge of channel", action: ErrorAction::IgnoreError})
525 BtreeEntry::Vacant(entry) => {
526 entry.insert(chan_info);
530 macro_rules! add_channel_to_node {
531 ( $node_id: expr ) => {
532 match network.nodes.entry($node_id) {
533 BtreeEntry::Occupied(node_entry) => {
534 node_entry.into_mut().channels.push(NetworkMap::get_key(msg.contents.short_channel_id, msg.contents.chain_hash));
536 BtreeEntry::Vacant(node_entry) => {
537 node_entry.insert(NodeInfo {
538 channels: vec!(NetworkMap::get_key(msg.contents.short_channel_id, msg.contents.chain_hash)),
539 lowest_inbound_channel_fee_base_msat: u32::max_value(),
540 lowest_inbound_channel_fee_proportional_millionths: u32::max_value(),
541 features: NodeFeatures::new(),
545 addresses: Vec::new(),
546 announcement_message: None,
553 add_channel_to_node!(msg.contents.node_id_1);
554 add_channel_to_node!(msg.contents.node_id_2);
559 fn handle_htlc_fail_channel_update(&self, update: &msgs::HTLCFailChannelUpdate) {
561 &msgs::HTLCFailChannelUpdate::ChannelUpdateMessage { ref msg } => {
562 let _ = self.handle_channel_update(msg);
564 &msgs::HTLCFailChannelUpdate::ChannelClosed { ref short_channel_id, ref is_permanent } => {
565 let mut network = self.network_map.write().unwrap();
567 if let Some(chan) = network.channels.remove(short_channel_id) {
568 Self::remove_channel_in_nodes(&mut network.nodes, &chan, *short_channel_id);
571 if let Some(chan) = network.channels.get_mut(short_channel_id) {
572 chan.one_to_two.enabled = false;
573 chan.two_to_one.enabled = false;
577 &msgs::HTLCFailChannelUpdate::NodeFailure { ref node_id, ref is_permanent } => {
579 //TODO: Wholly remove the node
581 self.mark_node_bad(node_id, false);
587 fn handle_channel_update(&self, msg: &msgs::ChannelUpdate) -> Result<bool, LightningError> {
588 let mut network = self.network_map.write().unwrap();
590 let chan_enabled = msg.contents.flags & (1 << 1) != (1 << 1);
591 let chan_was_enabled;
593 match network.channels.get_mut(&NetworkMap::get_key(msg.contents.short_channel_id, msg.contents.chain_hash)) {
594 None => return Err(LightningError{err: "Couldn't find channel for update", action: ErrorAction::IgnoreError}),
596 macro_rules! maybe_update_channel_info {
597 ( $target: expr) => {
598 if $target.last_update >= msg.contents.timestamp {
599 return Err(LightningError{err: "Update older than last processed update", action: ErrorAction::IgnoreError});
601 chan_was_enabled = $target.enabled;
602 $target.last_update = msg.contents.timestamp;
603 $target.enabled = chan_enabled;
604 $target.cltv_expiry_delta = msg.contents.cltv_expiry_delta;
605 $target.htlc_minimum_msat = msg.contents.htlc_minimum_msat;
606 $target.fee_base_msat = msg.contents.fee_base_msat;
607 $target.fee_proportional_millionths = msg.contents.fee_proportional_millionths;
608 $target.last_update_message = if msg.contents.excess_data.is_empty() {
615 let msg_hash = hash_to_message!(&Sha256dHash::hash(&msg.contents.encode()[..])[..]);
616 if msg.contents.flags & 1 == 1 {
617 dest_node_id = channel.one_to_two.src_node_id.clone();
618 secp_verify_sig!(self.secp_ctx, &msg_hash, &msg.signature, &channel.two_to_one.src_node_id);
619 maybe_update_channel_info!(channel.two_to_one);
621 dest_node_id = channel.two_to_one.src_node_id.clone();
622 secp_verify_sig!(self.secp_ctx, &msg_hash, &msg.signature, &channel.one_to_two.src_node_id);
623 maybe_update_channel_info!(channel.one_to_two);
629 let node = network.nodes.get_mut(&dest_node_id).unwrap();
630 node.lowest_inbound_channel_fee_base_msat = cmp::min(node.lowest_inbound_channel_fee_base_msat, msg.contents.fee_base_msat);
631 node.lowest_inbound_channel_fee_proportional_millionths = cmp::min(node.lowest_inbound_channel_fee_proportional_millionths, msg.contents.fee_proportional_millionths);
632 } else if chan_was_enabled {
633 let mut lowest_inbound_channel_fee_base_msat = u32::max_value();
634 let mut lowest_inbound_channel_fee_proportional_millionths = u32::max_value();
637 let node = network.nodes.get(&dest_node_id).unwrap();
639 for chan_id in node.channels.iter() {
640 let chan = network.channels.get(chan_id).unwrap();
641 if chan.one_to_two.src_node_id == dest_node_id {
642 lowest_inbound_channel_fee_base_msat = cmp::min(lowest_inbound_channel_fee_base_msat, chan.two_to_one.fee_base_msat);
643 lowest_inbound_channel_fee_proportional_millionths = cmp::min(lowest_inbound_channel_fee_proportional_millionths, chan.two_to_one.fee_proportional_millionths);
645 lowest_inbound_channel_fee_base_msat = cmp::min(lowest_inbound_channel_fee_base_msat, chan.one_to_two.fee_base_msat);
646 lowest_inbound_channel_fee_proportional_millionths = cmp::min(lowest_inbound_channel_fee_proportional_millionths, chan.one_to_two.fee_proportional_millionths);
651 //TODO: satisfy the borrow-checker without a double-map-lookup :(
652 let mut_node = network.nodes.get_mut(&dest_node_id).unwrap();
653 mut_node.lowest_inbound_channel_fee_base_msat = lowest_inbound_channel_fee_base_msat;
654 mut_node.lowest_inbound_channel_fee_proportional_millionths = lowest_inbound_channel_fee_proportional_millionths;
657 Ok(msg.contents.excess_data.is_empty())
661 fn get_next_channel_announcements(&self, starting_point: u64, batch_amount: u8) -> Vec<(msgs::ChannelAnnouncement, msgs::ChannelUpdate,msgs::ChannelUpdate)> {
662 let mut result = Vec::with_capacity(batch_amount as usize);
663 let network = self.network_map.read().unwrap();
664 let mut iter = network.channels.range(starting_point..);
665 while result.len() < batch_amount as usize {
666 if let Some((_, ref chan)) = iter.next() {
667 if chan.announcement_message.is_some() &&
668 chan.one_to_two.last_update_message.is_some() &&
669 chan.two_to_one.last_update_message.is_some() {
670 result.push((chan.announcement_message.clone().unwrap(),
671 chan.one_to_two.last_update_message.clone().unwrap(),
672 chan.two_to_one.last_update_message.clone().unwrap()));
674 // TODO: We may end up sending un-announced channel_updates if we are sending
675 // initial sync data while receiving announce/updates for this channel.
684 fn get_next_node_announcements(&self, starting_point: Option<&PublicKey>, batch_amount: u8) -> Vec<msgs::NodeAnnouncement> {
685 let mut result = Vec::with_capacity(batch_amount as usize);
686 let network = self.network_map.read().unwrap();
687 let mut iter = if let Some(pubkey) = starting_point {
688 let mut iter = network.nodes.range((*pubkey)..);
692 network.nodes.range(..)
694 while result.len() < batch_amount as usize {
695 if let Some((_, ref node)) = iter.next() {
696 if node.announcement_message.is_some() {
697 result.push(node.announcement_message.clone().unwrap());
707 #[derive(Eq, PartialEq)]
708 struct RouteGraphNode {
710 lowest_fee_to_peer_through_node: u64,
711 lowest_fee_to_node: u64,
714 impl cmp::Ord for RouteGraphNode {
715 fn cmp(&self, other: &RouteGraphNode) -> cmp::Ordering {
716 other.lowest_fee_to_peer_through_node.cmp(&self.lowest_fee_to_peer_through_node)
717 .then_with(|| other.pubkey.serialize().cmp(&self.pubkey.serialize()))
721 impl cmp::PartialOrd for RouteGraphNode {
722 fn partial_cmp(&self, other: &RouteGraphNode) -> Option<cmp::Ordering> {
723 Some(self.cmp(other))
727 struct DummyDirectionalChannelInfo {
728 src_node_id: PublicKey,
729 cltv_expiry_delta: u32,
730 htlc_minimum_msat: u64,
732 fee_proportional_millionths: u32,
736 /// Creates a new router with the given node_id to be used as the source for get_route()
737 pub fn new(our_pubkey: PublicKey, chain_monitor: Arc<ChainWatchInterface>, logger: Arc<Logger>) -> Router {
738 let mut nodes = BTreeMap::new();
739 nodes.insert(our_pubkey.clone(), NodeInfo {
740 channels: Vec::new(),
741 lowest_inbound_channel_fee_base_msat: u32::max_value(),
742 lowest_inbound_channel_fee_proportional_millionths: u32::max_value(),
743 features: NodeFeatures::new(),
747 addresses: Vec::new(),
748 announcement_message: None,
751 secp_ctx: Secp256k1::verification_only(),
752 network_map: RwLock::new(NetworkMap {
753 channels: BTreeMap::new(),
754 our_node_id: our_pubkey,
762 /// Dumps the entire network view of this Router to the logger provided in the constructor at
764 pub fn trace_state(&self) {
765 log_trace!(self, "{}", self.network_map.read().unwrap());
768 /// Get network addresses by node id
769 pub fn get_addresses(&self, pubkey: &PublicKey) -> Option<Vec<NetAddress>> {
770 let network = self.network_map.read().unwrap();
771 network.nodes.get(pubkey).map(|n| n.addresses.clone())
774 /// Marks a node as having failed a route. This will avoid re-using the node in routes for now,
775 /// with an exponential decay in node "badness". Note that there is deliberately no
776 /// mark_channel_bad as a node may simply lie and suggest that an upstream channel from it is
777 /// what failed the route and not the node itself. Instead, setting the blamed_upstream_node
778 /// boolean will reduce the penalty, returning the node to usability faster. If the node is
779 /// behaving correctly, it will disable the failing channel and we will use it again next time.
780 pub fn mark_node_bad(&self, _node_id: &PublicKey, _blamed_upstream_node: bool) {
784 fn remove_channel_in_nodes(nodes: &mut BTreeMap<PublicKey, NodeInfo>, chan: &ChannelInfo, short_channel_id: u64) {
785 macro_rules! remove_from_node {
786 ($node_id: expr) => {
787 if let BtreeEntry::Occupied(mut entry) = nodes.entry($node_id) {
788 entry.get_mut().channels.retain(|chan_id| {
789 short_channel_id != *NetworkMap::get_short_id(chan_id)
791 if entry.get().channels.is_empty() {
792 entry.remove_entry();
795 panic!("Had channel that pointed to unknown node (ie inconsistent network map)!");
799 remove_from_node!(chan.one_to_two.src_node_id);
800 remove_from_node!(chan.two_to_one.src_node_id);
803 /// Gets a route from us to the given target node.
805 /// Extra routing hops between known nodes and the target will be used if they are included in
808 /// If some channels aren't announced, it may be useful to fill in a first_hops with the
809 /// results from a local ChannelManager::list_usable_channels() call. If it is filled in, our
810 /// (this Router's) view of our local channels will be ignored, and only those in first_hops
813 /// Panics if first_hops contains channels without short_channel_ids
814 /// (ChannelManager::list_usable_channels will never include such channels).
816 /// The fees on channels from us to next-hops are ignored (as they are assumed to all be
817 /// equal), however the enabled/disabled bit on such channels as well as the htlc_minimum_msat
818 /// *is* checked as they may change based on the receiving node.
819 pub fn get_route(&self, target: &PublicKey, first_hops: Option<&[channelmanager::ChannelDetails]>, last_hops: &[RouteHint], final_value_msat: u64, final_cltv: u32) -> Result<Route, LightningError> {
820 // TODO: Obviously *only* using total fee cost sucks. We should consider weighting by
821 // uptime/success in using a node in the past.
822 let network = self.network_map.read().unwrap();
824 if *target == network.our_node_id {
825 return Err(LightningError{err: "Cannot generate a route to ourselves", action: ErrorAction::IgnoreError});
828 if final_value_msat > 21_000_000 * 1_0000_0000 * 1000 {
829 return Err(LightningError{err: "Cannot generate a route of more value than all existing satoshis", action: ErrorAction::IgnoreError});
832 // We do a dest-to-source Dijkstra's sorting by each node's distance from the destination
833 // plus the minimum per-HTLC fee to get from it to another node (aka "shitty A*").
834 // TODO: There are a few tweaks we could do, including possibly pre-calculating more stuff
835 // to use as the A* heuristic beyond just the cost to get one node further than the current
838 let dummy_directional_info = DummyDirectionalChannelInfo { // used for first_hops routes
839 src_node_id: network.our_node_id.clone(),
840 cltv_expiry_delta: 0,
841 htlc_minimum_msat: 0,
843 fee_proportional_millionths: 0,
846 let mut targets = BinaryHeap::new(); //TODO: Do we care about switching to eg Fibbonaci heap?
847 let mut dist = HashMap::with_capacity(network.nodes.len());
849 let mut first_hop_targets = HashMap::with_capacity(if first_hops.is_some() { first_hops.as_ref().unwrap().len() } else { 0 });
850 if let Some(hops) = first_hops {
852 let short_channel_id = chan.short_channel_id.expect("first_hops should be filled in with usable channels, not pending ones");
853 if chan.remote_network_id == *target {
855 hops: vec![RouteHop {
856 pubkey: chan.remote_network_id,
858 fee_msat: final_value_msat,
859 cltv_expiry_delta: final_cltv,
863 first_hop_targets.insert(chan.remote_network_id, short_channel_id);
865 if first_hop_targets.is_empty() {
866 return Err(LightningError{err: "Cannot route when there are no outbound routes away from us", action: ErrorAction::IgnoreError});
870 macro_rules! add_entry {
871 // Adds entry which goes from the node pointed to by $directional_info to
872 // $dest_node_id over the channel with id $chan_id with fees described in
873 // $directional_info.
874 ( $chan_id: expr, $dest_node_id: expr, $directional_info: expr, $starting_fee_msat: expr ) => {
875 //TODO: Explore simply adding fee to hit htlc_minimum_msat
876 if $starting_fee_msat as u64 + final_value_msat >= $directional_info.htlc_minimum_msat {
877 let proportional_fee_millions = ($starting_fee_msat + final_value_msat).checked_mul($directional_info.fee_proportional_millionths as u64);
878 if let Some(new_fee) = proportional_fee_millions.and_then(|part| {
879 ($directional_info.fee_base_msat as u64).checked_add(part / 1000000) })
881 let mut total_fee = $starting_fee_msat as u64;
882 let hm_entry = dist.entry(&$directional_info.src_node_id);
883 let old_entry = hm_entry.or_insert_with(|| {
884 let node = network.nodes.get(&$directional_info.src_node_id).unwrap();
886 node.lowest_inbound_channel_fee_base_msat,
887 node.lowest_inbound_channel_fee_proportional_millionths,
889 pubkey: $dest_node_id.clone(),
892 cltv_expiry_delta: 0,
895 if $directional_info.src_node_id != network.our_node_id {
896 // Ignore new_fee for channel-from-us as we assume all channels-from-us
897 // will have the same effective-fee
898 total_fee += new_fee;
899 if let Some(fee_inc) = final_value_msat.checked_add(total_fee).and_then(|inc| { (old_entry.2 as u64).checked_mul(inc) }) {
900 total_fee += fee_inc / 1000000 + (old_entry.1 as u64);
902 // max_value means we'll always fail the old_entry.0 > total_fee check
903 total_fee = u64::max_value();
906 let new_graph_node = RouteGraphNode {
907 pubkey: $directional_info.src_node_id,
908 lowest_fee_to_peer_through_node: total_fee,
909 lowest_fee_to_node: $starting_fee_msat as u64 + new_fee,
911 if old_entry.0 > total_fee {
912 targets.push(new_graph_node);
913 old_entry.0 = total_fee;
914 old_entry.3 = RouteHop {
915 pubkey: $dest_node_id.clone(),
916 short_channel_id: $chan_id.clone(),
917 fee_msat: new_fee, // This field is ignored on the last-hop anyway
918 cltv_expiry_delta: $directional_info.cltv_expiry_delta as u32,
926 macro_rules! add_entries_to_cheapest_to_target_node {
927 ( $node: expr, $node_id: expr, $fee_to_target_msat: expr ) => {
928 if first_hops.is_some() {
929 if let Some(first_hop) = first_hop_targets.get(&$node_id) {
930 add_entry!(first_hop, $node_id, dummy_directional_info, $fee_to_target_msat);
934 if !$node.features.requires_unknown_bits() {
935 for chan_id in $node.channels.iter() {
936 let chan = network.channels.get(chan_id).unwrap();
937 if !chan.features.requires_unknown_bits() {
938 if chan.one_to_two.src_node_id == *$node_id {
939 // ie $node is one, ie next hop in A* is two, via the two_to_one channel
940 if first_hops.is_none() || chan.two_to_one.src_node_id != network.our_node_id {
941 if chan.two_to_one.enabled {
942 add_entry!(chan_id, chan.one_to_two.src_node_id, chan.two_to_one, $fee_to_target_msat);
946 if first_hops.is_none() || chan.one_to_two.src_node_id != network.our_node_id {
947 if chan.one_to_two.enabled {
948 add_entry!(chan_id, chan.two_to_one.src_node_id, chan.one_to_two, $fee_to_target_msat);
958 match network.nodes.get(target) {
961 add_entries_to_cheapest_to_target_node!(node, target, 0);
965 for hop in last_hops.iter() {
966 if first_hops.is_none() || hop.src_node_id != network.our_node_id { // first_hop overrules last_hops
967 if network.nodes.get(&hop.src_node_id).is_some() {
968 if first_hops.is_some() {
969 if let Some(first_hop) = first_hop_targets.get(&hop.src_node_id) {
970 add_entry!(first_hop, hop.src_node_id, dummy_directional_info, 0);
973 add_entry!(hop.short_channel_id, target, hop, 0);
978 while let Some(RouteGraphNode { pubkey, lowest_fee_to_node, .. }) = targets.pop() {
979 if pubkey == network.our_node_id {
980 let mut res = vec!(dist.remove(&network.our_node_id).unwrap().3);
981 while res.last().unwrap().pubkey != *target {
982 let new_entry = match dist.remove(&res.last().unwrap().pubkey) {
984 None => return Err(LightningError{err: "Failed to find a non-fee-overflowing path to the given destination", action: ErrorAction::IgnoreError}),
986 res.last_mut().unwrap().fee_msat = new_entry.fee_msat;
987 res.last_mut().unwrap().cltv_expiry_delta = new_entry.cltv_expiry_delta;
990 res.last_mut().unwrap().fee_msat = final_value_msat;
991 res.last_mut().unwrap().cltv_expiry_delta = final_cltv;
992 let route = Route { hops: res };
993 log_trace!(self, "Got route: {}", log_route!(route));
997 match network.nodes.get(&pubkey) {
1000 add_entries_to_cheapest_to_target_node!(node, &pubkey, lowest_fee_to_node);
1005 Err(LightningError{err: "Failed to find a path to the given destination", action: ErrorAction::IgnoreError})
1011 use chain::chaininterface;
1012 use ln::channelmanager;
1013 use ln::router::{Router,NodeInfo,NetworkMap,ChannelInfo,DirectionalChannelInfo,RouteHint};
1014 use ln::msgs::{ChannelFeatures, NodeFeatures, LightningError, ErrorAction};
1015 use util::test_utils;
1016 use util::test_utils::TestVecWriter;
1017 use util::logger::Logger;
1018 use util::ser::{Writeable, Readable};
1020 use bitcoin_hashes::sha256d::Hash as Sha256dHash;
1021 use bitcoin_hashes::Hash;
1022 use bitcoin::network::constants::Network;
1026 use secp256k1::key::{PublicKey,SecretKey};
1027 use secp256k1::Secp256k1;
1033 let secp_ctx = Secp256k1::new();
1034 let our_id = PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&hex::decode("0101010101010101010101010101010101010101010101010101010101010101").unwrap()[..]).unwrap());
1035 let logger: Arc<Logger> = Arc::new(test_utils::TestLogger::new());
1036 let chain_monitor = Arc::new(chaininterface::ChainWatchInterfaceUtil::new(Network::Testnet, Arc::clone(&logger)));
1037 let router = Router::new(our_id, chain_monitor, Arc::clone(&logger));
1039 // Build network from our_id to node8:
1041 // -1(1)2- node1 -1(3)2-
1043 // our_id -1(12)2- node8 -1(13)2--- node3
1045 // -1(2)2- node2 -1(4)2-
1048 // chan1 1-to-2: disabled
1049 // chan1 2-to-1: enabled, 0 fee
1051 // chan2 1-to-2: enabled, ignored fee
1052 // chan2 2-to-1: enabled, 0 fee
1054 // chan3 1-to-2: enabled, 0 fee
1055 // chan3 2-to-1: enabled, 100 msat fee
1057 // chan4 1-to-2: enabled, 100% fee
1058 // chan4 2-to-1: enabled, 0 fee
1060 // chan12 1-to-2: enabled, ignored fee
1061 // chan12 2-to-1: enabled, 0 fee
1063 // chan13 1-to-2: enabled, 200% fee
1064 // chan13 2-to-1: enabled, 0 fee
1067 // -1(5)2- node4 -1(8)2--
1071 // node3--1(6)2- node5 -1(9)2--- node7 (not in global route map)
1073 // -1(7)2- node6 -1(10)2-
1075 // chan5 1-to-2: enabled, 100 msat fee
1076 // chan5 2-to-1: enabled, 0 fee
1078 // chan6 1-to-2: enabled, 0 fee
1079 // chan6 2-to-1: enabled, 0 fee
1081 // chan7 1-to-2: enabled, 100% fee
1082 // chan7 2-to-1: enabled, 0 fee
1084 // chan8 1-to-2: enabled, variable fee (0 then 1000 msat)
1085 // chan8 2-to-1: enabled, 0 fee
1087 // chan9 1-to-2: enabled, 1001 msat fee
1088 // chan9 2-to-1: enabled, 0 fee
1090 // chan10 1-to-2: enabled, 0 fee
1091 // chan10 2-to-1: enabled, 0 fee
1093 // chan11 1-to-2: enabled, 0 fee
1094 // chan11 2-to-1: enabled, 0 fee
1096 let node1 = PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&hex::decode("0202020202020202020202020202020202020202020202020202020202020202").unwrap()[..]).unwrap());
1097 let node2 = PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&hex::decode("0303030303030303030303030303030303030303030303030303030303030303").unwrap()[..]).unwrap());
1098 let node3 = PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&hex::decode("0404040404040404040404040404040404040404040404040404040404040404").unwrap()[..]).unwrap());
1099 let node4 = PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&hex::decode("0505050505050505050505050505050505050505050505050505050505050505").unwrap()[..]).unwrap());
1100 let node5 = PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&hex::decode("0606060606060606060606060606060606060606060606060606060606060606").unwrap()[..]).unwrap());
1101 let node6 = PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&hex::decode("0707070707070707070707070707070707070707070707070707070707070707").unwrap()[..]).unwrap());
1102 let node7 = PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&hex::decode("0808080808080808080808080808080808080808080808080808080808080808").unwrap()[..]).unwrap());
1103 let node8 = PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&hex::decode("0909090909090909090909090909090909090909090909090909090909090909").unwrap()[..]).unwrap());
1105 let zero_hash = Sha256dHash::hash(&[0; 32]);
1108 let mut network = router.network_map.write().unwrap();
1110 network.nodes.insert(node1.clone(), NodeInfo {
1111 channels: vec!(NetworkMap::get_key(1, zero_hash.clone()), NetworkMap::get_key(3, zero_hash.clone())),
1112 lowest_inbound_channel_fee_base_msat: 100,
1113 lowest_inbound_channel_fee_proportional_millionths: 0,
1114 features: NodeFeatures::new(),
1118 addresses: Vec::new(),
1119 announcement_message: None,
1121 network.channels.insert(NetworkMap::get_key(1, zero_hash.clone()), ChannelInfo {
1122 features: ChannelFeatures::new(),
1123 one_to_two: DirectionalChannelInfo {
1124 src_node_id: our_id.clone(),
1127 cltv_expiry_delta: u16::max_value(), // This value should be ignored
1128 htlc_minimum_msat: 0,
1129 fee_base_msat: u32::max_value(), // This value should be ignored
1130 fee_proportional_millionths: u32::max_value(), // This value should be ignored
1131 last_update_message: None,
1132 }, two_to_one: DirectionalChannelInfo {
1133 src_node_id: node1.clone(),
1136 cltv_expiry_delta: 0,
1137 htlc_minimum_msat: 0,
1139 fee_proportional_millionths: 0,
1140 last_update_message: None,
1142 announcement_message: None,
1144 network.nodes.insert(node2.clone(), NodeInfo {
1145 channels: vec!(NetworkMap::get_key(2, zero_hash.clone()), NetworkMap::get_key(4, zero_hash.clone())),
1146 lowest_inbound_channel_fee_base_msat: 0,
1147 lowest_inbound_channel_fee_proportional_millionths: 0,
1148 features: NodeFeatures::new(),
1152 addresses: Vec::new(),
1153 announcement_message: None,
1155 network.channels.insert(NetworkMap::get_key(2, zero_hash.clone()), ChannelInfo {
1156 features: ChannelFeatures::new(),
1157 one_to_two: DirectionalChannelInfo {
1158 src_node_id: our_id.clone(),
1161 cltv_expiry_delta: u16::max_value(), // This value should be ignored
1162 htlc_minimum_msat: 0,
1163 fee_base_msat: u32::max_value(), // This value should be ignored
1164 fee_proportional_millionths: u32::max_value(), // This value should be ignored
1165 last_update_message: None,
1166 }, two_to_one: DirectionalChannelInfo {
1167 src_node_id: node2.clone(),
1170 cltv_expiry_delta: 0,
1171 htlc_minimum_msat: 0,
1173 fee_proportional_millionths: 0,
1174 last_update_message: None,
1176 announcement_message: None,
1178 network.nodes.insert(node8.clone(), NodeInfo {
1179 channels: vec!(NetworkMap::get_key(12, zero_hash.clone()), NetworkMap::get_key(13, zero_hash.clone())),
1180 lowest_inbound_channel_fee_base_msat: 0,
1181 lowest_inbound_channel_fee_proportional_millionths: 0,
1182 features: NodeFeatures::new(),
1186 addresses: Vec::new(),
1187 announcement_message: None,
1189 network.channels.insert(NetworkMap::get_key(12, zero_hash.clone()), ChannelInfo {
1190 features: ChannelFeatures::new(),
1191 one_to_two: DirectionalChannelInfo {
1192 src_node_id: our_id.clone(),
1195 cltv_expiry_delta: u16::max_value(), // This value should be ignored
1196 htlc_minimum_msat: 0,
1197 fee_base_msat: u32::max_value(), // This value should be ignored
1198 fee_proportional_millionths: u32::max_value(), // This value should be ignored
1199 last_update_message: None,
1200 }, two_to_one: DirectionalChannelInfo {
1201 src_node_id: node8.clone(),
1204 cltv_expiry_delta: 0,
1205 htlc_minimum_msat: 0,
1207 fee_proportional_millionths: 0,
1208 last_update_message: None,
1210 announcement_message: None,
1212 network.nodes.insert(node3.clone(), NodeInfo {
1214 NetworkMap::get_key(3, zero_hash.clone()),
1215 NetworkMap::get_key(4, zero_hash.clone()),
1216 NetworkMap::get_key(13, zero_hash.clone()),
1217 NetworkMap::get_key(5, zero_hash.clone()),
1218 NetworkMap::get_key(6, zero_hash.clone()),
1219 NetworkMap::get_key(7, zero_hash.clone())),
1220 lowest_inbound_channel_fee_base_msat: 0,
1221 lowest_inbound_channel_fee_proportional_millionths: 0,
1222 features: NodeFeatures::new(),
1226 addresses: Vec::new(),
1227 announcement_message: None,
1229 network.channels.insert(NetworkMap::get_key(3, zero_hash.clone()), ChannelInfo {
1230 features: ChannelFeatures::new(),
1231 one_to_two: DirectionalChannelInfo {
1232 src_node_id: node1.clone(),
1235 cltv_expiry_delta: (3 << 8) | 1,
1236 htlc_minimum_msat: 0,
1238 fee_proportional_millionths: 0,
1239 last_update_message: None,
1240 }, two_to_one: DirectionalChannelInfo {
1241 src_node_id: node3.clone(),
1244 cltv_expiry_delta: (3 << 8) | 2,
1245 htlc_minimum_msat: 0,
1247 fee_proportional_millionths: 0,
1248 last_update_message: None,
1250 announcement_message: None,
1252 network.channels.insert(NetworkMap::get_key(4, zero_hash.clone()), ChannelInfo {
1253 features: ChannelFeatures::new(),
1254 one_to_two: DirectionalChannelInfo {
1255 src_node_id: node2.clone(),
1258 cltv_expiry_delta: (4 << 8) | 1,
1259 htlc_minimum_msat: 0,
1261 fee_proportional_millionths: 1000000,
1262 last_update_message: None,
1263 }, two_to_one: DirectionalChannelInfo {
1264 src_node_id: node3.clone(),
1267 cltv_expiry_delta: (4 << 8) | 2,
1268 htlc_minimum_msat: 0,
1270 fee_proportional_millionths: 0,
1271 last_update_message: None,
1273 announcement_message: None,
1275 network.channels.insert(NetworkMap::get_key(13, zero_hash.clone()), ChannelInfo {
1276 features: ChannelFeatures::new(),
1277 one_to_two: DirectionalChannelInfo {
1278 src_node_id: node8.clone(),
1281 cltv_expiry_delta: (13 << 8) | 1,
1282 htlc_minimum_msat: 0,
1284 fee_proportional_millionths: 2000000,
1285 last_update_message: None,
1286 }, two_to_one: DirectionalChannelInfo {
1287 src_node_id: node3.clone(),
1290 cltv_expiry_delta: (13 << 8) | 2,
1291 htlc_minimum_msat: 0,
1293 fee_proportional_millionths: 0,
1294 last_update_message: None,
1296 announcement_message: None,
1298 network.nodes.insert(node4.clone(), NodeInfo {
1299 channels: vec!(NetworkMap::get_key(5, zero_hash.clone()), NetworkMap::get_key(11, zero_hash.clone())),
1300 lowest_inbound_channel_fee_base_msat: 0,
1301 lowest_inbound_channel_fee_proportional_millionths: 0,
1302 features: NodeFeatures::new(),
1306 addresses: Vec::new(),
1307 announcement_message: None,
1309 network.channels.insert(NetworkMap::get_key(5, zero_hash.clone()), ChannelInfo {
1310 features: ChannelFeatures::new(),
1311 one_to_two: DirectionalChannelInfo {
1312 src_node_id: node3.clone(),
1315 cltv_expiry_delta: (5 << 8) | 1,
1316 htlc_minimum_msat: 0,
1318 fee_proportional_millionths: 0,
1319 last_update_message: None,
1320 }, two_to_one: DirectionalChannelInfo {
1321 src_node_id: node4.clone(),
1324 cltv_expiry_delta: (5 << 8) | 2,
1325 htlc_minimum_msat: 0,
1327 fee_proportional_millionths: 0,
1328 last_update_message: None,
1330 announcement_message: None,
1332 network.nodes.insert(node5.clone(), NodeInfo {
1333 channels: vec!(NetworkMap::get_key(6, zero_hash.clone()), NetworkMap::get_key(11, zero_hash.clone())),
1334 lowest_inbound_channel_fee_base_msat: 0,
1335 lowest_inbound_channel_fee_proportional_millionths: 0,
1336 features: NodeFeatures::new(),
1340 addresses: Vec::new(),
1341 announcement_message: None,
1343 network.channels.insert(NetworkMap::get_key(6, zero_hash.clone()), ChannelInfo {
1344 features: ChannelFeatures::new(),
1345 one_to_two: DirectionalChannelInfo {
1346 src_node_id: node3.clone(),
1349 cltv_expiry_delta: (6 << 8) | 1,
1350 htlc_minimum_msat: 0,
1352 fee_proportional_millionths: 0,
1353 last_update_message: None,
1354 }, two_to_one: DirectionalChannelInfo {
1355 src_node_id: node5.clone(),
1358 cltv_expiry_delta: (6 << 8) | 2,
1359 htlc_minimum_msat: 0,
1361 fee_proportional_millionths: 0,
1362 last_update_message: None,
1364 announcement_message: None,
1366 network.channels.insert(NetworkMap::get_key(11, zero_hash.clone()), ChannelInfo {
1367 features: ChannelFeatures::new(),
1368 one_to_two: DirectionalChannelInfo {
1369 src_node_id: node5.clone(),
1372 cltv_expiry_delta: (11 << 8) | 1,
1373 htlc_minimum_msat: 0,
1375 fee_proportional_millionths: 0,
1376 last_update_message: None,
1377 }, two_to_one: DirectionalChannelInfo {
1378 src_node_id: node4.clone(),
1381 cltv_expiry_delta: (11 << 8) | 2,
1382 htlc_minimum_msat: 0,
1384 fee_proportional_millionths: 0,
1385 last_update_message: None,
1387 announcement_message: None,
1389 network.nodes.insert(node6.clone(), NodeInfo {
1390 channels: vec!(NetworkMap::get_key(7, zero_hash.clone())),
1391 lowest_inbound_channel_fee_base_msat: 0,
1392 lowest_inbound_channel_fee_proportional_millionths: 0,
1393 features: NodeFeatures::new(),
1397 addresses: Vec::new(),
1398 announcement_message: None,
1400 network.channels.insert(NetworkMap::get_key(7, zero_hash.clone()), ChannelInfo {
1401 features: ChannelFeatures::new(),
1402 one_to_two: DirectionalChannelInfo {
1403 src_node_id: node3.clone(),
1406 cltv_expiry_delta: (7 << 8) | 1,
1407 htlc_minimum_msat: 0,
1409 fee_proportional_millionths: 1000000,
1410 last_update_message: None,
1411 }, two_to_one: DirectionalChannelInfo {
1412 src_node_id: node6.clone(),
1415 cltv_expiry_delta: (7 << 8) | 2,
1416 htlc_minimum_msat: 0,
1418 fee_proportional_millionths: 0,
1419 last_update_message: None,
1421 announcement_message: None,
1425 { // Simple route to 3 via 2
1426 let route = router.get_route(&node3, None, &Vec::new(), 100, 42).unwrap();
1427 assert_eq!(route.hops.len(), 2);
1429 assert_eq!(route.hops[0].pubkey, node2);
1430 assert_eq!(route.hops[0].short_channel_id, 2);
1431 assert_eq!(route.hops[0].fee_msat, 100);
1432 assert_eq!(route.hops[0].cltv_expiry_delta, (4 << 8) | 1);
1434 assert_eq!(route.hops[1].pubkey, node3);
1435 assert_eq!(route.hops[1].short_channel_id, 4);
1436 assert_eq!(route.hops[1].fee_msat, 100);
1437 assert_eq!(route.hops[1].cltv_expiry_delta, 42);
1440 { // Disable channels 4 and 12 by requiring unknown feature bits
1441 let mut network = router.network_map.write().unwrap();
1442 network.channels.get_mut(&NetworkMap::get_key(4, zero_hash.clone())).unwrap().features.set_require_unknown_bits();
1443 network.channels.get_mut(&NetworkMap::get_key(12, zero_hash.clone())).unwrap().features.set_require_unknown_bits();
1446 { // If all the channels require some features we don't understand, route should fail
1447 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = router.get_route(&node3, None, &Vec::new(), 100, 42) {
1448 assert_eq!(err, "Failed to find a path to the given destination");
1449 } else { panic!(); }
1452 { // If we specify a channel to node8, that overrides our local channel view and that gets used
1453 let our_chans = vec![channelmanager::ChannelDetails {
1454 channel_id: [0; 32],
1455 short_channel_id: Some(42),
1456 remote_network_id: node8.clone(),
1457 channel_value_satoshis: 0,
1459 outbound_capacity_msat: 0,
1460 inbound_capacity_msat: 0,
1463 let route = router.get_route(&node3, Some(&our_chans), &Vec::new(), 100, 42).unwrap();
1464 assert_eq!(route.hops.len(), 2);
1466 assert_eq!(route.hops[0].pubkey, node8);
1467 assert_eq!(route.hops[0].short_channel_id, 42);
1468 assert_eq!(route.hops[0].fee_msat, 200);
1469 assert_eq!(route.hops[0].cltv_expiry_delta, (13 << 8) | 1);
1471 assert_eq!(route.hops[1].pubkey, node3);
1472 assert_eq!(route.hops[1].short_channel_id, 13);
1473 assert_eq!(route.hops[1].fee_msat, 100);
1474 assert_eq!(route.hops[1].cltv_expiry_delta, 42);
1477 { // Re-enable channels 4 and 12 by wiping the unknown feature bits
1478 let mut network = router.network_map.write().unwrap();
1479 network.channels.get_mut(&NetworkMap::get_key(4, zero_hash.clone())).unwrap().features.clear_require_unknown_bits();
1480 network.channels.get_mut(&NetworkMap::get_key(12, zero_hash.clone())).unwrap().features.clear_require_unknown_bits();
1483 { // Disable nodes 1, 2, and 8 by requiring unknown feature bits
1484 let mut network = router.network_map.write().unwrap();
1485 network.nodes.get_mut(&node1).unwrap().features.set_require_unknown_bits();
1486 network.nodes.get_mut(&node2).unwrap().features.set_require_unknown_bits();
1487 network.nodes.get_mut(&node8).unwrap().features.set_require_unknown_bits();
1490 { // If all nodes require some features we don't understand, route should fail
1491 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = router.get_route(&node3, None, &Vec::new(), 100, 42) {
1492 assert_eq!(err, "Failed to find a path to the given destination");
1493 } else { panic!(); }
1496 { // If we specify a channel to node8, that overrides our local channel view and that gets used
1497 let our_chans = vec![channelmanager::ChannelDetails {
1498 channel_id: [0; 32],
1499 short_channel_id: Some(42),
1500 remote_network_id: node8.clone(),
1501 channel_value_satoshis: 0,
1503 outbound_capacity_msat: 0,
1504 inbound_capacity_msat: 0,
1507 let route = router.get_route(&node3, Some(&our_chans), &Vec::new(), 100, 42).unwrap();
1508 assert_eq!(route.hops.len(), 2);
1510 assert_eq!(route.hops[0].pubkey, node8);
1511 assert_eq!(route.hops[0].short_channel_id, 42);
1512 assert_eq!(route.hops[0].fee_msat, 200);
1513 assert_eq!(route.hops[0].cltv_expiry_delta, (13 << 8) | 1);
1515 assert_eq!(route.hops[1].pubkey, node3);
1516 assert_eq!(route.hops[1].short_channel_id, 13);
1517 assert_eq!(route.hops[1].fee_msat, 100);
1518 assert_eq!(route.hops[1].cltv_expiry_delta, 42);
1521 { // Re-enable nodes 1, 2, and 8
1522 let mut network = router.network_map.write().unwrap();
1523 network.nodes.get_mut(&node1).unwrap().features.clear_require_unknown_bits();
1524 network.nodes.get_mut(&node2).unwrap().features.clear_require_unknown_bits();
1525 network.nodes.get_mut(&node8).unwrap().features.clear_require_unknown_bits();
1528 // Note that we don't test disabling node 3 and failing to route to it, as we (somewhat
1529 // naively) assume that the user checked the feature bits on the invoice, which override
1530 // the node_announcement.
1532 { // Route to 1 via 2 and 3 because our channel to 1 is disabled
1533 let route = router.get_route(&node1, None, &Vec::new(), 100, 42).unwrap();
1534 assert_eq!(route.hops.len(), 3);
1536 assert_eq!(route.hops[0].pubkey, node2);
1537 assert_eq!(route.hops[0].short_channel_id, 2);
1538 assert_eq!(route.hops[0].fee_msat, 200);
1539 assert_eq!(route.hops[0].cltv_expiry_delta, (4 << 8) | 1);
1541 assert_eq!(route.hops[1].pubkey, node3);
1542 assert_eq!(route.hops[1].short_channel_id, 4);
1543 assert_eq!(route.hops[1].fee_msat, 100);
1544 assert_eq!(route.hops[1].cltv_expiry_delta, (3 << 8) | 2);
1546 assert_eq!(route.hops[2].pubkey, node1);
1547 assert_eq!(route.hops[2].short_channel_id, 3);
1548 assert_eq!(route.hops[2].fee_msat, 100);
1549 assert_eq!(route.hops[2].cltv_expiry_delta, 42);
1552 { // If we specify a channel to node8, that overrides our local channel view and that gets used
1553 let our_chans = vec![channelmanager::ChannelDetails {
1554 channel_id: [0; 32],
1555 short_channel_id: Some(42),
1556 remote_network_id: node8.clone(),
1557 channel_value_satoshis: 0,
1559 outbound_capacity_msat: 0,
1560 inbound_capacity_msat: 0,
1563 let route = router.get_route(&node3, Some(&our_chans), &Vec::new(), 100, 42).unwrap();
1564 assert_eq!(route.hops.len(), 2);
1566 assert_eq!(route.hops[0].pubkey, node8);
1567 assert_eq!(route.hops[0].short_channel_id, 42);
1568 assert_eq!(route.hops[0].fee_msat, 200);
1569 assert_eq!(route.hops[0].cltv_expiry_delta, (13 << 8) | 1);
1571 assert_eq!(route.hops[1].pubkey, node3);
1572 assert_eq!(route.hops[1].short_channel_id, 13);
1573 assert_eq!(route.hops[1].fee_msat, 100);
1574 assert_eq!(route.hops[1].cltv_expiry_delta, 42);
1577 let mut last_hops = vec!(RouteHint {
1578 src_node_id: node4.clone(),
1579 short_channel_id: 8,
1581 fee_proportional_millionths: 0,
1582 cltv_expiry_delta: (8 << 8) | 1,
1583 htlc_minimum_msat: 0,
1585 src_node_id: node5.clone(),
1586 short_channel_id: 9,
1587 fee_base_msat: 1001,
1588 fee_proportional_millionths: 0,
1589 cltv_expiry_delta: (9 << 8) | 1,
1590 htlc_minimum_msat: 0,
1592 src_node_id: node6.clone(),
1593 short_channel_id: 10,
1595 fee_proportional_millionths: 0,
1596 cltv_expiry_delta: (10 << 8) | 1,
1597 htlc_minimum_msat: 0,
1600 { // Simple test across 2, 3, 5, and 4 via a last_hop channel
1601 let route = router.get_route(&node7, None, &last_hops, 100, 42).unwrap();
1602 assert_eq!(route.hops.len(), 5);
1604 assert_eq!(route.hops[0].pubkey, node2);
1605 assert_eq!(route.hops[0].short_channel_id, 2);
1606 assert_eq!(route.hops[0].fee_msat, 100);
1607 assert_eq!(route.hops[0].cltv_expiry_delta, (4 << 8) | 1);
1609 assert_eq!(route.hops[1].pubkey, node3);
1610 assert_eq!(route.hops[1].short_channel_id, 4);
1611 assert_eq!(route.hops[1].fee_msat, 0);
1612 assert_eq!(route.hops[1].cltv_expiry_delta, (6 << 8) | 1);
1614 assert_eq!(route.hops[2].pubkey, node5);
1615 assert_eq!(route.hops[2].short_channel_id, 6);
1616 assert_eq!(route.hops[2].fee_msat, 0);
1617 assert_eq!(route.hops[2].cltv_expiry_delta, (11 << 8) | 1);
1619 assert_eq!(route.hops[3].pubkey, node4);
1620 assert_eq!(route.hops[3].short_channel_id, 11);
1621 assert_eq!(route.hops[3].fee_msat, 0);
1622 assert_eq!(route.hops[3].cltv_expiry_delta, (8 << 8) | 1);
1624 assert_eq!(route.hops[4].pubkey, node7);
1625 assert_eq!(route.hops[4].short_channel_id, 8);
1626 assert_eq!(route.hops[4].fee_msat, 100);
1627 assert_eq!(route.hops[4].cltv_expiry_delta, 42);
1630 { // Simple test with outbound channel to 4 to test that last_hops and first_hops connect
1631 let our_chans = vec![channelmanager::ChannelDetails {
1632 channel_id: [0; 32],
1633 short_channel_id: Some(42),
1634 remote_network_id: node4.clone(),
1635 channel_value_satoshis: 0,
1637 outbound_capacity_msat: 0,
1638 inbound_capacity_msat: 0,
1641 let route = router.get_route(&node7, Some(&our_chans), &last_hops, 100, 42).unwrap();
1642 assert_eq!(route.hops.len(), 2);
1644 assert_eq!(route.hops[0].pubkey, node4);
1645 assert_eq!(route.hops[0].short_channel_id, 42);
1646 assert_eq!(route.hops[0].fee_msat, 0);
1647 assert_eq!(route.hops[0].cltv_expiry_delta, (8 << 8) | 1);
1649 assert_eq!(route.hops[1].pubkey, node7);
1650 assert_eq!(route.hops[1].short_channel_id, 8);
1651 assert_eq!(route.hops[1].fee_msat, 100);
1652 assert_eq!(route.hops[1].cltv_expiry_delta, 42);
1655 last_hops[0].fee_base_msat = 1000;
1657 { // Revert to via 6 as the fee on 8 goes up
1658 let route = router.get_route(&node7, None, &last_hops, 100, 42).unwrap();
1659 assert_eq!(route.hops.len(), 4);
1661 assert_eq!(route.hops[0].pubkey, node2);
1662 assert_eq!(route.hops[0].short_channel_id, 2);
1663 assert_eq!(route.hops[0].fee_msat, 200); // fee increased as its % of value transferred across node
1664 assert_eq!(route.hops[0].cltv_expiry_delta, (4 << 8) | 1);
1666 assert_eq!(route.hops[1].pubkey, node3);
1667 assert_eq!(route.hops[1].short_channel_id, 4);
1668 assert_eq!(route.hops[1].fee_msat, 100);
1669 assert_eq!(route.hops[1].cltv_expiry_delta, (7 << 8) | 1);
1671 assert_eq!(route.hops[2].pubkey, node6);
1672 assert_eq!(route.hops[2].short_channel_id, 7);
1673 assert_eq!(route.hops[2].fee_msat, 0);
1674 assert_eq!(route.hops[2].cltv_expiry_delta, (10 << 8) | 1);
1676 assert_eq!(route.hops[3].pubkey, node7);
1677 assert_eq!(route.hops[3].short_channel_id, 10);
1678 assert_eq!(route.hops[3].fee_msat, 100);
1679 assert_eq!(route.hops[3].cltv_expiry_delta, 42);
1682 { // ...but still use 8 for larger payments as 6 has a variable feerate
1683 let route = router.get_route(&node7, None, &last_hops, 2000, 42).unwrap();
1684 assert_eq!(route.hops.len(), 5);
1686 assert_eq!(route.hops[0].pubkey, node2);
1687 assert_eq!(route.hops[0].short_channel_id, 2);
1688 assert_eq!(route.hops[0].fee_msat, 3000);
1689 assert_eq!(route.hops[0].cltv_expiry_delta, (4 << 8) | 1);
1691 assert_eq!(route.hops[1].pubkey, node3);
1692 assert_eq!(route.hops[1].short_channel_id, 4);
1693 assert_eq!(route.hops[1].fee_msat, 0);
1694 assert_eq!(route.hops[1].cltv_expiry_delta, (6 << 8) | 1);
1696 assert_eq!(route.hops[2].pubkey, node5);
1697 assert_eq!(route.hops[2].short_channel_id, 6);
1698 assert_eq!(route.hops[2].fee_msat, 0);
1699 assert_eq!(route.hops[2].cltv_expiry_delta, (11 << 8) | 1);
1701 assert_eq!(route.hops[3].pubkey, node4);
1702 assert_eq!(route.hops[3].short_channel_id, 11);
1703 assert_eq!(route.hops[3].fee_msat, 1000);
1704 assert_eq!(route.hops[3].cltv_expiry_delta, (8 << 8) | 1);
1706 assert_eq!(route.hops[4].pubkey, node7);
1707 assert_eq!(route.hops[4].short_channel_id, 8);
1708 assert_eq!(route.hops[4].fee_msat, 2000);
1709 assert_eq!(route.hops[4].cltv_expiry_delta, 42);
1712 { // Test Router serialization/deserialization
1713 let mut w = TestVecWriter(Vec::new());
1714 let network = router.network_map.read().unwrap();
1715 assert!(!network.channels.is_empty());
1716 assert!(!network.nodes.is_empty());
1717 network.write(&mut w).unwrap();
1718 assert!(<NetworkMap>::read(&mut ::std::io::Cursor::new(&w.0)).unwrap() == *network);