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::features::{ChannelFeatures, NodeFeatures};
18 use ln::msgs::{DecodeError,ErrorAction,LightningError,RoutingMessageHandler,NetAddress};
20 use util::ser::{Writeable, Readable, Writer, ReadableArgs};
21 use util::logger::Logger;
24 use std::sync::{RwLock,Arc};
25 use std::collections::{HashMap,BinaryHeap,BTreeMap};
26 use std::collections::btree_map::Entry as BtreeEntry;
30 #[derive(Clone, PartialEq)]
32 /// The node_id of the node at this hop.
33 pub pubkey: PublicKey,
34 /// The node_announcement features of the node at this hop. For the last hop, these may be
35 /// amended to match the features present in the invoice this node generated.
36 pub node_features: NodeFeatures,
37 /// The channel that should be used from the previous hop to reach this node.
38 pub short_channel_id: u64,
39 /// The channel_announcement features of the channel that should be used from the previous hop
40 /// to reach this node.
41 pub channel_features: ChannelFeatures,
42 /// The fee taken on this hop. For the last hop, this should be the full value of the payment.
44 /// The CLTV delta added for this hop. For the last hop, this should be the full CLTV value
45 /// expected at the destination, in excess of the current block height.
46 pub cltv_expiry_delta: u32,
49 /// A route from us through the network to a destination
50 #[derive(Clone, PartialEq)]
52 /// The list of hops, NOT INCLUDING our own, where the last hop is the destination. Thus, this
53 /// must always be at least length one. By protocol rules, this may not currently exceed 20 in
55 pub hops: Vec<RouteHop>,
58 impl Writeable for Route {
59 fn write<W: ::util::ser::Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
60 (self.hops.len() as u8).write(writer)?;
61 for hop in self.hops.iter() {
62 hop.pubkey.write(writer)?;
63 hop.node_features.write(writer)?;
64 hop.short_channel_id.write(writer)?;
65 hop.channel_features.write(writer)?;
66 hop.fee_msat.write(writer)?;
67 hop.cltv_expiry_delta.write(writer)?;
73 impl<R: ::std::io::Read> Readable<R> for Route {
74 fn read(reader: &mut R) -> Result<Route, DecodeError> {
75 let hops_count: u8 = Readable::read(reader)?;
76 let mut hops = Vec::with_capacity(hops_count as usize);
77 for _ in 0..hops_count {
79 pubkey: Readable::read(reader)?,
80 node_features: Readable::read(reader)?,
81 short_channel_id: Readable::read(reader)?,
82 channel_features: Readable::read(reader)?,
83 fee_msat: Readable::read(reader)?,
84 cltv_expiry_delta: Readable::read(reader)?,
94 struct DirectionalChannelInfo {
95 src_node_id: PublicKey,
98 cltv_expiry_delta: u16,
99 htlc_minimum_msat: u64,
101 fee_proportional_millionths: u32,
102 last_update_message: Option<msgs::ChannelUpdate>,
105 impl std::fmt::Display for DirectionalChannelInfo {
106 fn fmt(&self, f: &mut std::fmt::Formatter) -> Result<(), std::fmt::Error> {
107 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)?;
112 impl_writeable!(DirectionalChannelInfo, 0, {
119 fee_proportional_millionths,
125 features: ChannelFeatures,
126 one_to_two: DirectionalChannelInfo,
127 two_to_one: DirectionalChannelInfo,
128 //this is cached here so we can send out it later if required by route_init_sync
129 //keep an eye on this to see if the extra memory is a problem
130 announcement_message: Option<msgs::ChannelAnnouncement>,
133 impl std::fmt::Display for ChannelInfo {
134 fn fmt(&self, f: &mut std::fmt::Formatter) -> Result<(), std::fmt::Error> {
135 write!(f, "features: {}, one_to_two: {}, two_to_one: {}", log_bytes!(self.features.encode()), self.one_to_two, self.two_to_one)?;
140 impl_writeable!(ChannelInfo, 0, {
149 #[cfg(feature = "non_bitcoin_chain_hash_routing")]
150 channels: Vec<(u64, Sha256dHash)>,
151 #[cfg(not(feature = "non_bitcoin_chain_hash_routing"))]
154 lowest_inbound_channel_fee_base_msat: u32,
155 lowest_inbound_channel_fee_proportional_millionths: u32,
157 features: NodeFeatures,
161 addresses: Vec<NetAddress>,
162 //this is cached here so we can send out it later if required by route_init_sync
163 //keep an eye on this to see if the extra memory is a problem
164 announcement_message: Option<msgs::NodeAnnouncement>,
167 impl std::fmt::Display for NodeInfo {
168 fn fmt(&self, f: &mut std::fmt::Formatter) -> Result<(), std::fmt::Error> {
169 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[..])?;
174 impl Writeable for NodeInfo {
175 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
176 (self.channels.len() as u64).write(writer)?;
177 for ref chan in self.channels.iter() {
180 self.lowest_inbound_channel_fee_base_msat.write(writer)?;
181 self.lowest_inbound_channel_fee_proportional_millionths.write(writer)?;
182 self.features.write(writer)?;
183 self.last_update.write(writer)?;
184 self.rgb.write(writer)?;
185 self.alias.write(writer)?;
186 (self.addresses.len() as u64).write(writer)?;
187 for ref addr in &self.addresses {
190 self.announcement_message.write(writer)?;
195 const MAX_ALLOC_SIZE: u64 = 64*1024;
197 impl<R: ::std::io::Read> Readable<R> for NodeInfo {
198 fn read(reader: &mut R) -> Result<NodeInfo, DecodeError> {
199 let channels_count: u64 = Readable::read(reader)?;
200 let mut channels = Vec::with_capacity(cmp::min(channels_count, MAX_ALLOC_SIZE / 8) as usize);
201 for _ in 0..channels_count {
202 channels.push(Readable::read(reader)?);
204 let lowest_inbound_channel_fee_base_msat = Readable::read(reader)?;
205 let lowest_inbound_channel_fee_proportional_millionths = Readable::read(reader)?;
206 let features = Readable::read(reader)?;
207 let last_update = Readable::read(reader)?;
208 let rgb = Readable::read(reader)?;
209 let alias = Readable::read(reader)?;
210 let addresses_count: u64 = Readable::read(reader)?;
211 let mut addresses = Vec::with_capacity(cmp::min(addresses_count, MAX_ALLOC_SIZE / 40) as usize);
212 for _ in 0..addresses_count {
213 match Readable::read(reader) {
214 Ok(Ok(addr)) => { addresses.push(addr); },
215 Ok(Err(_)) => return Err(DecodeError::InvalidValue),
216 Err(DecodeError::ShortRead) => return Err(DecodeError::BadLengthDescriptor),
220 let announcement_message = Readable::read(reader)?;
223 lowest_inbound_channel_fee_base_msat,
224 lowest_inbound_channel_fee_proportional_millionths,
237 #[cfg(feature = "non_bitcoin_chain_hash_routing")]
238 channels: BTreeMap<(u64, Sha256dHash), ChannelInfo>,
239 #[cfg(not(feature = "non_bitcoin_chain_hash_routing"))]
240 channels: BTreeMap<u64, ChannelInfo>,
242 our_node_id: PublicKey,
243 nodes: BTreeMap<PublicKey, NodeInfo>,
246 impl Writeable for NetworkMap {
247 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
248 (self.channels.len() as u64).write(writer)?;
249 for (ref chan_id, ref chan_info) in self.channels.iter() {
250 (*chan_id).write(writer)?;
251 chan_info.write(writer)?;
253 self.our_node_id.write(writer)?;
254 (self.nodes.len() as u64).write(writer)?;
255 for (ref node_id, ref node_info) in self.nodes.iter() {
256 node_id.write(writer)?;
257 node_info.write(writer)?;
263 impl<R: ::std::io::Read> Readable<R> for NetworkMap {
264 fn read(reader: &mut R) -> Result<NetworkMap, DecodeError> {
265 let channels_count: u64 = Readable::read(reader)?;
266 let mut channels = BTreeMap::new();
267 for _ in 0..channels_count {
268 let chan_id: u64 = Readable::read(reader)?;
269 let chan_info = Readable::read(reader)?;
270 channels.insert(chan_id, chan_info);
272 let our_node_id = Readable::read(reader)?;
273 let nodes_count: u64 = Readable::read(reader)?;
274 let mut nodes = BTreeMap::new();
275 for _ in 0..nodes_count {
276 let node_id = Readable::read(reader)?;
277 let node_info = Readable::read(reader)?;
278 nodes.insert(node_id, node_info);
288 impl std::fmt::Display for NetworkMap {
289 fn fmt(&self, f: &mut std::fmt::Formatter) -> Result<(), std::fmt::Error> {
290 write!(f, "Node id {} network map\n[Channels]\n", log_pubkey!(self.our_node_id))?;
291 for (key, val) in self.channels.iter() {
292 write!(f, " {}: {}\n", key, val)?;
294 write!(f, "[Nodes]\n")?;
295 for (key, val) in self.nodes.iter() {
296 write!(f, " {}: {}\n", log_pubkey!(key), val)?;
303 #[cfg(feature = "non_bitcoin_chain_hash_routing")]
305 fn get_key(short_channel_id: u64, chain_hash: Sha256dHash) -> (u64, Sha256dHash) {
306 (short_channel_id, chain_hash)
309 #[cfg(not(feature = "non_bitcoin_chain_hash_routing"))]
311 fn get_key(short_channel_id: u64, _: Sha256dHash) -> u64 {
315 #[cfg(feature = "non_bitcoin_chain_hash_routing")]
317 fn get_short_id(id: &(u64, Sha256dHash)) -> &u64 {
321 #[cfg(not(feature = "non_bitcoin_chain_hash_routing"))]
323 fn get_short_id(id: &u64) -> &u64 {
328 /// A channel descriptor which provides a last-hop route to get_route
329 pub struct RouteHint {
330 /// The node_id of the non-target end of the route
331 pub src_node_id: PublicKey,
332 /// The short_channel_id of this channel
333 pub short_channel_id: u64,
334 /// The static msat-denominated fee which must be paid to use this channel
335 pub fee_base_msat: u32,
336 /// The dynamic proportional fee which must be paid to use this channel, denominated in
337 /// millionths of the value being forwarded to the next hop.
338 pub fee_proportional_millionths: u32,
339 /// The difference in CLTV values between this node and the next node.
340 pub cltv_expiry_delta: u16,
341 /// The minimum value, in msat, which must be relayed to the next hop.
342 pub htlc_minimum_msat: u64,
345 /// Tracks a view of the network, receiving updates from peers and generating Routes to
346 /// payment destinations.
348 secp_ctx: Secp256k1<secp256k1::VerifyOnly>,
349 network_map: RwLock<NetworkMap>,
350 chain_monitor: Arc<ChainWatchInterface>,
354 const SERIALIZATION_VERSION: u8 = 1;
355 const MIN_SERIALIZATION_VERSION: u8 = 1;
357 impl Writeable for Router {
358 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
359 writer.write_all(&[SERIALIZATION_VERSION; 1])?;
360 writer.write_all(&[MIN_SERIALIZATION_VERSION; 1])?;
362 let network = self.network_map.read().unwrap();
363 network.write(writer)?;
368 /// Arguments for the creation of a Router that are not deserialized.
369 /// At a high-level, the process for deserializing a Router and resuming normal operation is:
370 /// 1) Deserialize the Router by filling in this struct and calling <Router>::read(reaser, args).
371 /// 2) Register the new Router with your ChainWatchInterface
372 pub struct RouterReadArgs {
373 /// The ChainWatchInterface for use in the Router in the future.
375 /// No calls to the ChainWatchInterface will be made during deserialization.
376 pub chain_monitor: Arc<ChainWatchInterface>,
377 /// The Logger for use in the ChannelManager and which may be used to log information during
379 pub logger: Arc<Logger>,
382 impl<R: ::std::io::Read> ReadableArgs<R, RouterReadArgs> for Router {
383 fn read(reader: &mut R, args: RouterReadArgs) -> Result<Router, DecodeError> {
384 let _ver: u8 = Readable::read(reader)?;
385 let min_ver: u8 = Readable::read(reader)?;
386 if min_ver > SERIALIZATION_VERSION {
387 return Err(DecodeError::UnknownVersion);
389 let network_map = Readable::read(reader)?;
391 secp_ctx: Secp256k1::verification_only(),
392 network_map: RwLock::new(network_map),
393 chain_monitor: args.chain_monitor,
399 macro_rules! secp_verify_sig {
400 ( $secp_ctx: expr, $msg: expr, $sig: expr, $pubkey: expr ) => {
401 match $secp_ctx.verify($msg, $sig, $pubkey) {
403 Err(_) => return Err(LightningError{err: "Invalid signature from remote node", action: ErrorAction::IgnoreError}),
408 impl RoutingMessageHandler for Router {
409 fn handle_node_announcement(&self, msg: &msgs::NodeAnnouncement) -> Result<bool, LightningError> {
410 let msg_hash = hash_to_message!(&Sha256dHash::hash(&msg.contents.encode()[..])[..]);
411 secp_verify_sig!(self.secp_ctx, &msg_hash, &msg.signature, &msg.contents.node_id);
413 let mut network = self.network_map.write().unwrap();
414 match network.nodes.get_mut(&msg.contents.node_id) {
415 None => Err(LightningError{err: "No existing channels for node_announcement", action: ErrorAction::IgnoreError}),
417 if node.last_update >= msg.contents.timestamp {
418 return Err(LightningError{err: "Update older than last processed update", action: ErrorAction::IgnoreError});
421 node.features = msg.contents.features.clone();
422 node.last_update = msg.contents.timestamp;
423 node.rgb = msg.contents.rgb;
424 node.alias = msg.contents.alias;
425 node.addresses = msg.contents.addresses.clone();
427 let should_relay = msg.contents.excess_data.is_empty() && msg.contents.excess_address_data.is_empty();
428 node.announcement_message = if should_relay { Some(msg.clone()) } else { None };
434 fn handle_channel_announcement(&self, msg: &msgs::ChannelAnnouncement) -> Result<bool, LightningError> {
435 if msg.contents.node_id_1 == msg.contents.node_id_2 || msg.contents.bitcoin_key_1 == msg.contents.bitcoin_key_2 {
436 return Err(LightningError{err: "Channel announcement node had a channel with itself", action: ErrorAction::IgnoreError});
439 let msg_hash = hash_to_message!(&Sha256dHash::hash(&msg.contents.encode()[..])[..]);
440 secp_verify_sig!(self.secp_ctx, &msg_hash, &msg.node_signature_1, &msg.contents.node_id_1);
441 secp_verify_sig!(self.secp_ctx, &msg_hash, &msg.node_signature_2, &msg.contents.node_id_2);
442 secp_verify_sig!(self.secp_ctx, &msg_hash, &msg.bitcoin_signature_1, &msg.contents.bitcoin_key_1);
443 secp_verify_sig!(self.secp_ctx, &msg_hash, &msg.bitcoin_signature_2, &msg.contents.bitcoin_key_2);
445 let checked_utxo = match self.chain_monitor.get_chain_utxo(msg.contents.chain_hash, msg.contents.short_channel_id) {
446 Ok((script_pubkey, _value)) => {
447 let expected_script = Builder::new().push_opcode(opcodes::all::OP_PUSHNUM_2)
448 .push_slice(&msg.contents.bitcoin_key_1.serialize())
449 .push_slice(&msg.contents.bitcoin_key_2.serialize())
450 .push_opcode(opcodes::all::OP_PUSHNUM_2)
451 .push_opcode(opcodes::all::OP_CHECKMULTISIG).into_script().to_v0_p2wsh();
452 if script_pubkey != expected_script {
453 return Err(LightningError{err: "Channel announcement keys didn't match on-chain script", action: ErrorAction::IgnoreError});
455 //TODO: Check if value is worth storing, use it to inform routing, and compare it
456 //to the new HTLC max field in channel_update
459 Err(ChainError::NotSupported) => {
460 // Tentatively accept, potentially exposing us to DoS attacks
463 Err(ChainError::NotWatched) => {
464 return Err(LightningError{err: "Channel announced on an unknown chain", action: ErrorAction::IgnoreError});
466 Err(ChainError::UnknownTx) => {
467 return Err(LightningError{err: "Channel announced without corresponding UTXO entry", action: ErrorAction::IgnoreError});
471 let mut network_lock = self.network_map.write().unwrap();
472 let network = &mut *network_lock;
474 let should_relay = msg.contents.excess_data.is_empty();
476 let chan_info = ChannelInfo {
477 features: msg.contents.features.clone(),
478 one_to_two: DirectionalChannelInfo {
479 src_node_id: msg.contents.node_id_1.clone(),
482 cltv_expiry_delta: u16::max_value(),
483 htlc_minimum_msat: u64::max_value(),
484 fee_base_msat: u32::max_value(),
485 fee_proportional_millionths: u32::max_value(),
486 last_update_message: None,
488 two_to_one: DirectionalChannelInfo {
489 src_node_id: msg.contents.node_id_2.clone(),
492 cltv_expiry_delta: u16::max_value(),
493 htlc_minimum_msat: u64::max_value(),
494 fee_base_msat: u32::max_value(),
495 fee_proportional_millionths: u32::max_value(),
496 last_update_message: None,
498 announcement_message: if should_relay { Some(msg.clone()) } else { None },
501 match network.channels.entry(NetworkMap::get_key(msg.contents.short_channel_id, msg.contents.chain_hash)) {
502 BtreeEntry::Occupied(mut entry) => {
503 //TODO: because asking the blockchain if short_channel_id is valid is only optional
504 //in the blockchain API, we need to handle it smartly here, though it's unclear
507 // Either our UTXO provider is busted, there was a reorg, or the UTXO provider
508 // only sometimes returns results. In any case remove the previous entry. Note
509 // that the spec expects us to "blacklist" the node_ids involved, but we can't
511 // a) we don't *require* a UTXO provider that always returns results.
512 // b) we don't track UTXOs of channels we know about and remove them if they
514 // c) it's unclear how to do so without exposing ourselves to massive DoS risk.
515 Self::remove_channel_in_nodes(&mut network.nodes, &entry.get(), msg.contents.short_channel_id);
516 *entry.get_mut() = chan_info;
518 return Err(LightningError{err: "Already have knowledge of channel", action: ErrorAction::IgnoreError})
521 BtreeEntry::Vacant(entry) => {
522 entry.insert(chan_info);
526 macro_rules! add_channel_to_node {
527 ( $node_id: expr ) => {
528 match network.nodes.entry($node_id) {
529 BtreeEntry::Occupied(node_entry) => {
530 node_entry.into_mut().channels.push(NetworkMap::get_key(msg.contents.short_channel_id, msg.contents.chain_hash));
532 BtreeEntry::Vacant(node_entry) => {
533 node_entry.insert(NodeInfo {
534 channels: vec!(NetworkMap::get_key(msg.contents.short_channel_id, msg.contents.chain_hash)),
535 lowest_inbound_channel_fee_base_msat: u32::max_value(),
536 lowest_inbound_channel_fee_proportional_millionths: u32::max_value(),
537 features: NodeFeatures::empty(),
541 addresses: Vec::new(),
542 announcement_message: None,
549 add_channel_to_node!(msg.contents.node_id_1);
550 add_channel_to_node!(msg.contents.node_id_2);
555 fn handle_htlc_fail_channel_update(&self, update: &msgs::HTLCFailChannelUpdate) {
557 &msgs::HTLCFailChannelUpdate::ChannelUpdateMessage { ref msg } => {
558 let _ = self.handle_channel_update(msg);
560 &msgs::HTLCFailChannelUpdate::ChannelClosed { ref short_channel_id, ref is_permanent } => {
561 let mut network = self.network_map.write().unwrap();
563 if let Some(chan) = network.channels.remove(short_channel_id) {
564 Self::remove_channel_in_nodes(&mut network.nodes, &chan, *short_channel_id);
567 if let Some(chan) = network.channels.get_mut(short_channel_id) {
568 chan.one_to_two.enabled = false;
569 chan.two_to_one.enabled = false;
573 &msgs::HTLCFailChannelUpdate::NodeFailure { ref node_id, ref is_permanent } => {
575 //TODO: Wholly remove the node
577 self.mark_node_bad(node_id, false);
583 fn handle_channel_update(&self, msg: &msgs::ChannelUpdate) -> Result<bool, LightningError> {
584 let mut network = self.network_map.write().unwrap();
586 let chan_enabled = msg.contents.flags & (1 << 1) != (1 << 1);
587 let chan_was_enabled;
589 match network.channels.get_mut(&NetworkMap::get_key(msg.contents.short_channel_id, msg.contents.chain_hash)) {
590 None => return Err(LightningError{err: "Couldn't find channel for update", action: ErrorAction::IgnoreError}),
592 macro_rules! maybe_update_channel_info {
593 ( $target: expr) => {
594 if $target.last_update >= msg.contents.timestamp {
595 return Err(LightningError{err: "Update older than last processed update", action: ErrorAction::IgnoreError});
597 chan_was_enabled = $target.enabled;
598 $target.last_update = msg.contents.timestamp;
599 $target.enabled = chan_enabled;
600 $target.cltv_expiry_delta = msg.contents.cltv_expiry_delta;
601 $target.htlc_minimum_msat = msg.contents.htlc_minimum_msat;
602 $target.fee_base_msat = msg.contents.fee_base_msat;
603 $target.fee_proportional_millionths = msg.contents.fee_proportional_millionths;
604 $target.last_update_message = if msg.contents.excess_data.is_empty() {
611 let msg_hash = hash_to_message!(&Sha256dHash::hash(&msg.contents.encode()[..])[..]);
612 if msg.contents.flags & 1 == 1 {
613 dest_node_id = channel.one_to_two.src_node_id.clone();
614 secp_verify_sig!(self.secp_ctx, &msg_hash, &msg.signature, &channel.two_to_one.src_node_id);
615 maybe_update_channel_info!(channel.two_to_one);
617 dest_node_id = channel.two_to_one.src_node_id.clone();
618 secp_verify_sig!(self.secp_ctx, &msg_hash, &msg.signature, &channel.one_to_two.src_node_id);
619 maybe_update_channel_info!(channel.one_to_two);
625 let node = network.nodes.get_mut(&dest_node_id).unwrap();
626 node.lowest_inbound_channel_fee_base_msat = cmp::min(node.lowest_inbound_channel_fee_base_msat, msg.contents.fee_base_msat);
627 node.lowest_inbound_channel_fee_proportional_millionths = cmp::min(node.lowest_inbound_channel_fee_proportional_millionths, msg.contents.fee_proportional_millionths);
628 } else if chan_was_enabled {
629 let mut lowest_inbound_channel_fee_base_msat = u32::max_value();
630 let mut lowest_inbound_channel_fee_proportional_millionths = u32::max_value();
633 let node = network.nodes.get(&dest_node_id).unwrap();
635 for chan_id in node.channels.iter() {
636 let chan = network.channels.get(chan_id).unwrap();
637 if chan.one_to_two.src_node_id == dest_node_id {
638 lowest_inbound_channel_fee_base_msat = cmp::min(lowest_inbound_channel_fee_base_msat, chan.two_to_one.fee_base_msat);
639 lowest_inbound_channel_fee_proportional_millionths = cmp::min(lowest_inbound_channel_fee_proportional_millionths, chan.two_to_one.fee_proportional_millionths);
641 lowest_inbound_channel_fee_base_msat = cmp::min(lowest_inbound_channel_fee_base_msat, chan.one_to_two.fee_base_msat);
642 lowest_inbound_channel_fee_proportional_millionths = cmp::min(lowest_inbound_channel_fee_proportional_millionths, chan.one_to_two.fee_proportional_millionths);
647 //TODO: satisfy the borrow-checker without a double-map-lookup :(
648 let mut_node = network.nodes.get_mut(&dest_node_id).unwrap();
649 mut_node.lowest_inbound_channel_fee_base_msat = lowest_inbound_channel_fee_base_msat;
650 mut_node.lowest_inbound_channel_fee_proportional_millionths = lowest_inbound_channel_fee_proportional_millionths;
653 Ok(msg.contents.excess_data.is_empty())
657 fn get_next_channel_announcements(&self, starting_point: u64, batch_amount: u8) -> Vec<(msgs::ChannelAnnouncement, msgs::ChannelUpdate,msgs::ChannelUpdate)> {
658 let mut result = Vec::with_capacity(batch_amount as usize);
659 let network = self.network_map.read().unwrap();
660 let mut iter = network.channels.range(starting_point..);
661 while result.len() < batch_amount as usize {
662 if let Some((_, ref chan)) = iter.next() {
663 if chan.announcement_message.is_some() &&
664 chan.one_to_two.last_update_message.is_some() &&
665 chan.two_to_one.last_update_message.is_some() {
666 result.push((chan.announcement_message.clone().unwrap(),
667 chan.one_to_two.last_update_message.clone().unwrap(),
668 chan.two_to_one.last_update_message.clone().unwrap()));
670 // TODO: We may end up sending un-announced channel_updates if we are sending
671 // initial sync data while receiving announce/updates for this channel.
680 fn get_next_node_announcements(&self, starting_point: Option<&PublicKey>, batch_amount: u8) -> Vec<msgs::NodeAnnouncement> {
681 let mut result = Vec::with_capacity(batch_amount as usize);
682 let network = self.network_map.read().unwrap();
683 let mut iter = if let Some(pubkey) = starting_point {
684 let mut iter = network.nodes.range((*pubkey)..);
688 network.nodes.range(..)
690 while result.len() < batch_amount as usize {
691 if let Some((_, ref node)) = iter.next() {
692 if node.announcement_message.is_some() {
693 result.push(node.announcement_message.clone().unwrap());
703 #[derive(Eq, PartialEq)]
704 struct RouteGraphNode {
706 lowest_fee_to_peer_through_node: u64,
707 lowest_fee_to_node: u64,
710 impl cmp::Ord for RouteGraphNode {
711 fn cmp(&self, other: &RouteGraphNode) -> cmp::Ordering {
712 other.lowest_fee_to_peer_through_node.cmp(&self.lowest_fee_to_peer_through_node)
713 .then_with(|| other.pubkey.serialize().cmp(&self.pubkey.serialize()))
717 impl cmp::PartialOrd for RouteGraphNode {
718 fn partial_cmp(&self, other: &RouteGraphNode) -> Option<cmp::Ordering> {
719 Some(self.cmp(other))
723 struct DummyDirectionalChannelInfo {
724 src_node_id: PublicKey,
725 cltv_expiry_delta: u32,
726 htlc_minimum_msat: u64,
728 fee_proportional_millionths: u32,
732 /// Creates a new router with the given node_id to be used as the source for get_route()
733 pub fn new(our_pubkey: PublicKey, chain_monitor: Arc<ChainWatchInterface>, logger: Arc<Logger>) -> Router {
734 let mut nodes = BTreeMap::new();
735 nodes.insert(our_pubkey.clone(), NodeInfo {
736 channels: Vec::new(),
737 lowest_inbound_channel_fee_base_msat: u32::max_value(),
738 lowest_inbound_channel_fee_proportional_millionths: u32::max_value(),
739 features: NodeFeatures::empty(),
743 addresses: Vec::new(),
744 announcement_message: None,
747 secp_ctx: Secp256k1::verification_only(),
748 network_map: RwLock::new(NetworkMap {
749 channels: BTreeMap::new(),
750 our_node_id: our_pubkey,
758 /// Dumps the entire network view of this Router to the logger provided in the constructor at
760 pub fn trace_state(&self) {
761 log_trace!(self, "{}", self.network_map.read().unwrap());
764 /// Get network addresses by node id
765 pub fn get_addresses(&self, pubkey: &PublicKey) -> Option<Vec<NetAddress>> {
766 let network = self.network_map.read().unwrap();
767 network.nodes.get(pubkey).map(|n| n.addresses.clone())
770 /// Marks a node as having failed a route. This will avoid re-using the node in routes for now,
771 /// with an exponential decay in node "badness". Note that there is deliberately no
772 /// mark_channel_bad as a node may simply lie and suggest that an upstream channel from it is
773 /// what failed the route and not the node itself. Instead, setting the blamed_upstream_node
774 /// boolean will reduce the penalty, returning the node to usability faster. If the node is
775 /// behaving correctly, it will disable the failing channel and we will use it again next time.
776 pub fn mark_node_bad(&self, _node_id: &PublicKey, _blamed_upstream_node: bool) {
780 fn remove_channel_in_nodes(nodes: &mut BTreeMap<PublicKey, NodeInfo>, chan: &ChannelInfo, short_channel_id: u64) {
781 macro_rules! remove_from_node {
782 ($node_id: expr) => {
783 if let BtreeEntry::Occupied(mut entry) = nodes.entry($node_id) {
784 entry.get_mut().channels.retain(|chan_id| {
785 short_channel_id != *NetworkMap::get_short_id(chan_id)
787 if entry.get().channels.is_empty() {
788 entry.remove_entry();
791 panic!("Had channel that pointed to unknown node (ie inconsistent network map)!");
795 remove_from_node!(chan.one_to_two.src_node_id);
796 remove_from_node!(chan.two_to_one.src_node_id);
799 /// Gets a route from us to the given target node.
801 /// Extra routing hops between known nodes and the target will be used if they are included in
804 /// If some channels aren't announced, it may be useful to fill in a first_hops with the
805 /// results from a local ChannelManager::list_usable_channels() call. If it is filled in, our
806 /// (this Router's) view of our local channels will be ignored, and only those in first_hops
809 /// Panics if first_hops contains channels without short_channel_ids
810 /// (ChannelManager::list_usable_channels will never include such channels).
812 /// The fees on channels from us to next-hops are ignored (as they are assumed to all be
813 /// equal), however the enabled/disabled bit on such channels as well as the htlc_minimum_msat
814 /// *is* checked as they may change based on the receiving node.
815 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> {
816 // TODO: Obviously *only* using total fee cost sucks. We should consider weighting by
817 // uptime/success in using a node in the past.
818 let network = self.network_map.read().unwrap();
820 if *target == network.our_node_id {
821 return Err(LightningError{err: "Cannot generate a route to ourselves", action: ErrorAction::IgnoreError});
824 if final_value_msat > 21_000_000 * 1_0000_0000 * 1000 {
825 return Err(LightningError{err: "Cannot generate a route of more value than all existing satoshis", action: ErrorAction::IgnoreError});
828 // We do a dest-to-source Dijkstra's sorting by each node's distance from the destination
829 // plus the minimum per-HTLC fee to get from it to another node (aka "shitty A*").
830 // TODO: There are a few tweaks we could do, including possibly pre-calculating more stuff
831 // to use as the A* heuristic beyond just the cost to get one node further than the current
834 let dummy_directional_info = DummyDirectionalChannelInfo { // used for first_hops routes
835 src_node_id: network.our_node_id.clone(),
836 cltv_expiry_delta: 0,
837 htlc_minimum_msat: 0,
839 fee_proportional_millionths: 0,
842 let mut targets = BinaryHeap::new(); //TODO: Do we care about switching to eg Fibbonaci heap?
843 let mut dist = HashMap::with_capacity(network.nodes.len());
845 let mut first_hop_targets = HashMap::with_capacity(if first_hops.is_some() { first_hops.as_ref().unwrap().len() } else { 0 });
846 if let Some(hops) = first_hops {
848 let short_channel_id = chan.short_channel_id.expect("first_hops should be filled in with usable channels, not pending ones");
849 if chan.remote_network_id == *target {
851 hops: vec![RouteHop {
852 pubkey: chan.remote_network_id,
853 node_features: NodeFeatures::with_known_relevant_init_flags(&chan.counterparty_features),
855 channel_features: ChannelFeatures::with_known_relevant_init_flags(&chan.counterparty_features),
856 fee_msat: final_value_msat,
857 cltv_expiry_delta: final_cltv,
861 first_hop_targets.insert(chan.remote_network_id, (short_channel_id, chan.counterparty_features.clone()));
863 if first_hop_targets.is_empty() {
864 return Err(LightningError{err: "Cannot route when there are no outbound routes away from us", action: ErrorAction::IgnoreError});
868 macro_rules! add_entry {
869 // Adds entry which goes from the node pointed to by $directional_info to
870 // $dest_node_id over the channel with id $chan_id with fees described in
871 // $directional_info.
872 ( $chan_id: expr, $dest_node_id: expr, $directional_info: expr, $chan_features: expr, $starting_fee_msat: expr ) => {
873 //TODO: Explore simply adding fee to hit htlc_minimum_msat
874 if $starting_fee_msat as u64 + final_value_msat >= $directional_info.htlc_minimum_msat {
875 let proportional_fee_millions = ($starting_fee_msat + final_value_msat).checked_mul($directional_info.fee_proportional_millionths as u64);
876 if let Some(new_fee) = proportional_fee_millions.and_then(|part| {
877 ($directional_info.fee_base_msat as u64).checked_add(part / 1000000) })
879 let mut total_fee = $starting_fee_msat as u64;
880 let hm_entry = dist.entry(&$directional_info.src_node_id);
881 let old_entry = hm_entry.or_insert_with(|| {
882 let node = network.nodes.get(&$directional_info.src_node_id).unwrap();
884 node.lowest_inbound_channel_fee_base_msat,
885 node.lowest_inbound_channel_fee_proportional_millionths,
887 pubkey: $dest_node_id.clone(),
888 node_features: NodeFeatures::empty(),
890 channel_features: $chan_features.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 node_features: NodeFeatures::empty(),
917 short_channel_id: $chan_id.clone(),
918 channel_features: $chan_features.clone(),
919 fee_msat: new_fee, // This field is ignored on the last-hop anyway
920 cltv_expiry_delta: $directional_info.cltv_expiry_delta as u32,
928 macro_rules! add_entries_to_cheapest_to_target_node {
929 ( $node: expr, $node_id: expr, $fee_to_target_msat: expr ) => {
930 if first_hops.is_some() {
931 if let Some(&(ref first_hop, ref features)) = first_hop_targets.get(&$node_id) {
932 add_entry!(first_hop, $node_id, dummy_directional_info, ChannelFeatures::with_known_relevant_init_flags(&features), $fee_to_target_msat);
936 if !$node.features.requires_unknown_bits() {
937 for chan_id in $node.channels.iter() {
938 let chan = network.channels.get(chan_id).unwrap();
939 if !chan.features.requires_unknown_bits() {
940 if chan.one_to_two.src_node_id == *$node_id {
941 // ie $node is one, ie next hop in A* is two, via the two_to_one channel
942 if first_hops.is_none() || chan.two_to_one.src_node_id != network.our_node_id {
943 if chan.two_to_one.enabled {
944 add_entry!(chan_id, chan.one_to_two.src_node_id, chan.two_to_one, chan.features, $fee_to_target_msat);
948 if first_hops.is_none() || chan.one_to_two.src_node_id != network.our_node_id {
949 if chan.one_to_two.enabled {
950 add_entry!(chan_id, chan.two_to_one.src_node_id, chan.one_to_two, chan.features, $fee_to_target_msat);
960 match network.nodes.get(target) {
963 add_entries_to_cheapest_to_target_node!(node, target, 0);
967 for hop in last_hops.iter() {
968 if first_hops.is_none() || hop.src_node_id != network.our_node_id { // first_hop overrules last_hops
969 if network.nodes.get(&hop.src_node_id).is_some() {
970 if first_hops.is_some() {
971 if let Some(&(ref first_hop, ref features)) = first_hop_targets.get(&hop.src_node_id) {
972 // Currently there are no channel-context features defined, so we are a
973 // bit lazy here. In the future, we should pull them out via our
974 // ChannelManager, but there's no reason to waste the space until we
976 add_entry!(first_hop, hop.src_node_id, dummy_directional_info, ChannelFeatures::with_known_relevant_init_flags(&features), 0);
979 // BOLT 11 doesn't allow inclusion of features for the last hop hints, which
980 // really sucks, cause we're gonna need that eventually.
981 add_entry!(hop.short_channel_id, target, hop, ChannelFeatures::empty(), 0);
986 while let Some(RouteGraphNode { pubkey, lowest_fee_to_node, .. }) = targets.pop() {
987 if pubkey == network.our_node_id {
988 let mut res = vec!(dist.remove(&network.our_node_id).unwrap().3);
990 if let Some(&(_, ref features)) = first_hop_targets.get(&res.last().unwrap().pubkey) {
991 res.last_mut().unwrap().node_features = NodeFeatures::with_known_relevant_init_flags(&features);
992 } else if let Some(node) = network.nodes.get(&res.last().unwrap().pubkey) {
993 res.last_mut().unwrap().node_features = node.features.clone();
995 // We should be able to fill in features for everything except the last
996 // hop, if the last hop was provided via a BOLT 11 invoice (though we
997 // should be able to extend it further as BOLT 11 does have feature
998 // flags for the last hop node itself).
999 assert!(res.last().unwrap().pubkey == *target);
1001 if res.last().unwrap().pubkey == *target {
1005 let new_entry = match dist.remove(&res.last().unwrap().pubkey) {
1007 None => return Err(LightningError{err: "Failed to find a non-fee-overflowing path to the given destination", action: ErrorAction::IgnoreError}),
1009 res.last_mut().unwrap().fee_msat = new_entry.fee_msat;
1010 res.last_mut().unwrap().cltv_expiry_delta = new_entry.cltv_expiry_delta;
1011 res.push(new_entry);
1013 res.last_mut().unwrap().fee_msat = final_value_msat;
1014 res.last_mut().unwrap().cltv_expiry_delta = final_cltv;
1015 let route = Route { hops: res };
1016 log_trace!(self, "Got route: {}", log_route!(route));
1020 match network.nodes.get(&pubkey) {
1023 add_entries_to_cheapest_to_target_node!(node, &pubkey, lowest_fee_to_node);
1028 Err(LightningError{err: "Failed to find a path to the given destination", action: ErrorAction::IgnoreError})
1034 use chain::chaininterface;
1035 use ln::channelmanager;
1036 use ln::router::{Router,NodeInfo,NetworkMap,ChannelInfo,DirectionalChannelInfo,RouteHint};
1037 use ln::features::{ChannelFeatures, InitFeatures, NodeFeatures};
1038 use ln::msgs::{LightningError, ErrorAction};
1039 use util::test_utils;
1040 use util::test_utils::TestVecWriter;
1041 use util::logger::Logger;
1042 use util::ser::{Writeable, Readable};
1044 use bitcoin_hashes::sha256d::Hash as Sha256dHash;
1045 use bitcoin_hashes::Hash;
1046 use bitcoin::network::constants::Network;
1050 use secp256k1::key::{PublicKey,SecretKey};
1051 use secp256k1::Secp256k1;
1057 let secp_ctx = Secp256k1::new();
1058 let our_id = PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&hex::decode("0101010101010101010101010101010101010101010101010101010101010101").unwrap()[..]).unwrap());
1059 let logger: Arc<Logger> = Arc::new(test_utils::TestLogger::new());
1060 let chain_monitor = Arc::new(chaininterface::ChainWatchInterfaceUtil::new(Network::Testnet, Arc::clone(&logger)));
1061 let router = Router::new(our_id, chain_monitor, Arc::clone(&logger));
1063 // Build network from our_id to node8:
1065 // -1(1)2- node1 -1(3)2-
1067 // our_id -1(12)2- node8 -1(13)2--- node3
1069 // -1(2)2- node2 -1(4)2-
1072 // chan1 1-to-2: disabled
1073 // chan1 2-to-1: enabled, 0 fee
1075 // chan2 1-to-2: enabled, ignored fee
1076 // chan2 2-to-1: enabled, 0 fee
1078 // chan3 1-to-2: enabled, 0 fee
1079 // chan3 2-to-1: enabled, 100 msat fee
1081 // chan4 1-to-2: enabled, 100% fee
1082 // chan4 2-to-1: enabled, 0 fee
1084 // chan12 1-to-2: enabled, ignored fee
1085 // chan12 2-to-1: enabled, 0 fee
1087 // chan13 1-to-2: enabled, 200% fee
1088 // chan13 2-to-1: enabled, 0 fee
1091 // -1(5)2- node4 -1(8)2--
1095 // node3--1(6)2- node5 -1(9)2--- node7 (not in global route map)
1097 // -1(7)2- node6 -1(10)2-
1099 // chan5 1-to-2: enabled, 100 msat fee
1100 // chan5 2-to-1: enabled, 0 fee
1102 // chan6 1-to-2: enabled, 0 fee
1103 // chan6 2-to-1: enabled, 0 fee
1105 // chan7 1-to-2: enabled, 100% fee
1106 // chan7 2-to-1: enabled, 0 fee
1108 // chan8 1-to-2: enabled, variable fee (0 then 1000 msat)
1109 // chan8 2-to-1: enabled, 0 fee
1111 // chan9 1-to-2: enabled, 1001 msat fee
1112 // chan9 2-to-1: enabled, 0 fee
1114 // chan10 1-to-2: enabled, 0 fee
1115 // chan10 2-to-1: enabled, 0 fee
1117 // chan11 1-to-2: enabled, 0 fee
1118 // chan11 2-to-1: enabled, 0 fee
1120 let node1 = PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&hex::decode("0202020202020202020202020202020202020202020202020202020202020202").unwrap()[..]).unwrap());
1121 let node2 = PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&hex::decode("0303030303030303030303030303030303030303030303030303030303030303").unwrap()[..]).unwrap());
1122 let node3 = PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&hex::decode("0404040404040404040404040404040404040404040404040404040404040404").unwrap()[..]).unwrap());
1123 let node4 = PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&hex::decode("0505050505050505050505050505050505050505050505050505050505050505").unwrap()[..]).unwrap());
1124 let node5 = PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&hex::decode("0606060606060606060606060606060606060606060606060606060606060606").unwrap()[..]).unwrap());
1125 let node6 = PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&hex::decode("0707070707070707070707070707070707070707070707070707070707070707").unwrap()[..]).unwrap());
1126 let node7 = PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&hex::decode("0808080808080808080808080808080808080808080808080808080808080808").unwrap()[..]).unwrap());
1127 let node8 = PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&hex::decode("0909090909090909090909090909090909090909090909090909090909090909").unwrap()[..]).unwrap());
1129 let zero_hash = Sha256dHash::hash(&[0; 32]);
1131 macro_rules! id_to_feature_flags {
1132 // Set the feature flags to the id'th odd (ie non-required) feature bit so that we can
1133 // test for it later.
1135 let idx = ($id - 1) * 2 + 1;
1137 vec![1 << (idx - 8*3), 0, 0, 0]
1138 } else if idx > 8*2 {
1139 vec![1 << (idx - 8*2), 0, 0]
1140 } else if idx > 8*1 {
1141 vec![1 << (idx - 8*1), 0]
1149 let mut network = router.network_map.write().unwrap();
1151 network.nodes.insert(node1.clone(), NodeInfo {
1152 channels: vec!(NetworkMap::get_key(1, zero_hash.clone()), NetworkMap::get_key(3, zero_hash.clone())),
1153 lowest_inbound_channel_fee_base_msat: 100,
1154 lowest_inbound_channel_fee_proportional_millionths: 0,
1155 features: NodeFeatures::from_le_bytes(id_to_feature_flags!(1)),
1159 addresses: Vec::new(),
1160 announcement_message: None,
1162 network.channels.insert(NetworkMap::get_key(1, zero_hash.clone()), ChannelInfo {
1163 features: ChannelFeatures::from_le_bytes(id_to_feature_flags!(1)),
1164 one_to_two: DirectionalChannelInfo {
1165 src_node_id: our_id.clone(),
1168 cltv_expiry_delta: u16::max_value(), // This value should be ignored
1169 htlc_minimum_msat: 0,
1170 fee_base_msat: u32::max_value(), // This value should be ignored
1171 fee_proportional_millionths: u32::max_value(), // This value should be ignored
1172 last_update_message: None,
1173 }, two_to_one: DirectionalChannelInfo {
1174 src_node_id: node1.clone(),
1177 cltv_expiry_delta: 0,
1178 htlc_minimum_msat: 0,
1180 fee_proportional_millionths: 0,
1181 last_update_message: None,
1183 announcement_message: None,
1185 network.nodes.insert(node2.clone(), NodeInfo {
1186 channels: vec!(NetworkMap::get_key(2, zero_hash.clone()), NetworkMap::get_key(4, zero_hash.clone())),
1187 lowest_inbound_channel_fee_base_msat: 0,
1188 lowest_inbound_channel_fee_proportional_millionths: 0,
1189 features: NodeFeatures::from_le_bytes(id_to_feature_flags!(2)),
1193 addresses: Vec::new(),
1194 announcement_message: None,
1196 network.channels.insert(NetworkMap::get_key(2, zero_hash.clone()), ChannelInfo {
1197 features: ChannelFeatures::from_le_bytes(id_to_feature_flags!(2)),
1198 one_to_two: DirectionalChannelInfo {
1199 src_node_id: our_id.clone(),
1202 cltv_expiry_delta: u16::max_value(), // This value should be ignored
1203 htlc_minimum_msat: 0,
1204 fee_base_msat: u32::max_value(), // This value should be ignored
1205 fee_proportional_millionths: u32::max_value(), // This value should be ignored
1206 last_update_message: None,
1207 }, two_to_one: DirectionalChannelInfo {
1208 src_node_id: node2.clone(),
1211 cltv_expiry_delta: 0,
1212 htlc_minimum_msat: 0,
1214 fee_proportional_millionths: 0,
1215 last_update_message: None,
1217 announcement_message: None,
1219 network.nodes.insert(node8.clone(), NodeInfo {
1220 channels: vec!(NetworkMap::get_key(12, zero_hash.clone()), NetworkMap::get_key(13, zero_hash.clone())),
1221 lowest_inbound_channel_fee_base_msat: 0,
1222 lowest_inbound_channel_fee_proportional_millionths: 0,
1223 features: NodeFeatures::from_le_bytes(id_to_feature_flags!(8)),
1227 addresses: Vec::new(),
1228 announcement_message: None,
1230 network.channels.insert(NetworkMap::get_key(12, zero_hash.clone()), ChannelInfo {
1231 features: ChannelFeatures::from_le_bytes(id_to_feature_flags!(12)),
1232 one_to_two: DirectionalChannelInfo {
1233 src_node_id: our_id.clone(),
1236 cltv_expiry_delta: u16::max_value(), // This value should be ignored
1237 htlc_minimum_msat: 0,
1238 fee_base_msat: u32::max_value(), // This value should be ignored
1239 fee_proportional_millionths: u32::max_value(), // This value should be ignored
1240 last_update_message: None,
1241 }, two_to_one: DirectionalChannelInfo {
1242 src_node_id: node8.clone(),
1245 cltv_expiry_delta: 0,
1246 htlc_minimum_msat: 0,
1248 fee_proportional_millionths: 0,
1249 last_update_message: None,
1251 announcement_message: None,
1253 network.nodes.insert(node3.clone(), NodeInfo {
1255 NetworkMap::get_key(3, zero_hash.clone()),
1256 NetworkMap::get_key(4, zero_hash.clone()),
1257 NetworkMap::get_key(13, zero_hash.clone()),
1258 NetworkMap::get_key(5, zero_hash.clone()),
1259 NetworkMap::get_key(6, zero_hash.clone()),
1260 NetworkMap::get_key(7, zero_hash.clone())),
1261 lowest_inbound_channel_fee_base_msat: 0,
1262 lowest_inbound_channel_fee_proportional_millionths: 0,
1263 features: NodeFeatures::from_le_bytes(id_to_feature_flags!(3)),
1267 addresses: Vec::new(),
1268 announcement_message: None,
1270 network.channels.insert(NetworkMap::get_key(3, zero_hash.clone()), ChannelInfo {
1271 features: ChannelFeatures::from_le_bytes(id_to_feature_flags!(3)),
1272 one_to_two: DirectionalChannelInfo {
1273 src_node_id: node1.clone(),
1276 cltv_expiry_delta: (3 << 8) | 1,
1277 htlc_minimum_msat: 0,
1279 fee_proportional_millionths: 0,
1280 last_update_message: None,
1281 }, two_to_one: DirectionalChannelInfo {
1282 src_node_id: node3.clone(),
1285 cltv_expiry_delta: (3 << 8) | 2,
1286 htlc_minimum_msat: 0,
1288 fee_proportional_millionths: 0,
1289 last_update_message: None,
1291 announcement_message: None,
1293 network.channels.insert(NetworkMap::get_key(4, zero_hash.clone()), ChannelInfo {
1294 features: ChannelFeatures::from_le_bytes(id_to_feature_flags!(4)),
1295 one_to_two: DirectionalChannelInfo {
1296 src_node_id: node2.clone(),
1299 cltv_expiry_delta: (4 << 8) | 1,
1300 htlc_minimum_msat: 0,
1302 fee_proportional_millionths: 1000000,
1303 last_update_message: None,
1304 }, two_to_one: DirectionalChannelInfo {
1305 src_node_id: node3.clone(),
1308 cltv_expiry_delta: (4 << 8) | 2,
1309 htlc_minimum_msat: 0,
1311 fee_proportional_millionths: 0,
1312 last_update_message: None,
1314 announcement_message: None,
1316 network.channels.insert(NetworkMap::get_key(13, zero_hash.clone()), ChannelInfo {
1317 features: ChannelFeatures::from_le_bytes(id_to_feature_flags!(13)),
1318 one_to_two: DirectionalChannelInfo {
1319 src_node_id: node8.clone(),
1322 cltv_expiry_delta: (13 << 8) | 1,
1323 htlc_minimum_msat: 0,
1325 fee_proportional_millionths: 2000000,
1326 last_update_message: None,
1327 }, two_to_one: DirectionalChannelInfo {
1328 src_node_id: node3.clone(),
1331 cltv_expiry_delta: (13 << 8) | 2,
1332 htlc_minimum_msat: 0,
1334 fee_proportional_millionths: 0,
1335 last_update_message: None,
1337 announcement_message: None,
1339 network.nodes.insert(node4.clone(), NodeInfo {
1340 channels: vec!(NetworkMap::get_key(5, zero_hash.clone()), NetworkMap::get_key(11, zero_hash.clone())),
1341 lowest_inbound_channel_fee_base_msat: 0,
1342 lowest_inbound_channel_fee_proportional_millionths: 0,
1343 features: NodeFeatures::from_le_bytes(id_to_feature_flags!(4)),
1347 addresses: Vec::new(),
1348 announcement_message: None,
1350 network.channels.insert(NetworkMap::get_key(5, zero_hash.clone()), ChannelInfo {
1351 features: ChannelFeatures::from_le_bytes(id_to_feature_flags!(5)),
1352 one_to_two: DirectionalChannelInfo {
1353 src_node_id: node3.clone(),
1356 cltv_expiry_delta: (5 << 8) | 1,
1357 htlc_minimum_msat: 0,
1359 fee_proportional_millionths: 0,
1360 last_update_message: None,
1361 }, two_to_one: DirectionalChannelInfo {
1362 src_node_id: node4.clone(),
1365 cltv_expiry_delta: (5 << 8) | 2,
1366 htlc_minimum_msat: 0,
1368 fee_proportional_millionths: 0,
1369 last_update_message: None,
1371 announcement_message: None,
1373 network.nodes.insert(node5.clone(), NodeInfo {
1374 channels: vec!(NetworkMap::get_key(6, zero_hash.clone()), NetworkMap::get_key(11, zero_hash.clone())),
1375 lowest_inbound_channel_fee_base_msat: 0,
1376 lowest_inbound_channel_fee_proportional_millionths: 0,
1377 features: NodeFeatures::from_le_bytes(id_to_feature_flags!(5)),
1381 addresses: Vec::new(),
1382 announcement_message: None,
1384 network.channels.insert(NetworkMap::get_key(6, zero_hash.clone()), ChannelInfo {
1385 features: ChannelFeatures::from_le_bytes(id_to_feature_flags!(6)),
1386 one_to_two: DirectionalChannelInfo {
1387 src_node_id: node3.clone(),
1390 cltv_expiry_delta: (6 << 8) | 1,
1391 htlc_minimum_msat: 0,
1393 fee_proportional_millionths: 0,
1394 last_update_message: None,
1395 }, two_to_one: DirectionalChannelInfo {
1396 src_node_id: node5.clone(),
1399 cltv_expiry_delta: (6 << 8) | 2,
1400 htlc_minimum_msat: 0,
1402 fee_proportional_millionths: 0,
1403 last_update_message: None,
1405 announcement_message: None,
1407 network.channels.insert(NetworkMap::get_key(11, zero_hash.clone()), ChannelInfo {
1408 features: ChannelFeatures::from_le_bytes(id_to_feature_flags!(11)),
1409 one_to_two: DirectionalChannelInfo {
1410 src_node_id: node5.clone(),
1413 cltv_expiry_delta: (11 << 8) | 1,
1414 htlc_minimum_msat: 0,
1416 fee_proportional_millionths: 0,
1417 last_update_message: None,
1418 }, two_to_one: DirectionalChannelInfo {
1419 src_node_id: node4.clone(),
1422 cltv_expiry_delta: (11 << 8) | 2,
1423 htlc_minimum_msat: 0,
1425 fee_proportional_millionths: 0,
1426 last_update_message: None,
1428 announcement_message: None,
1430 network.nodes.insert(node6.clone(), NodeInfo {
1431 channels: vec!(NetworkMap::get_key(7, zero_hash.clone())),
1432 lowest_inbound_channel_fee_base_msat: 0,
1433 lowest_inbound_channel_fee_proportional_millionths: 0,
1434 features: NodeFeatures::from_le_bytes(id_to_feature_flags!(6)),
1438 addresses: Vec::new(),
1439 announcement_message: None,
1441 network.channels.insert(NetworkMap::get_key(7, zero_hash.clone()), ChannelInfo {
1442 features: ChannelFeatures::from_le_bytes(id_to_feature_flags!(7)),
1443 one_to_two: DirectionalChannelInfo {
1444 src_node_id: node3.clone(),
1447 cltv_expiry_delta: (7 << 8) | 1,
1448 htlc_minimum_msat: 0,
1450 fee_proportional_millionths: 1000000,
1451 last_update_message: None,
1452 }, two_to_one: DirectionalChannelInfo {
1453 src_node_id: node6.clone(),
1456 cltv_expiry_delta: (7 << 8) | 2,
1457 htlc_minimum_msat: 0,
1459 fee_proportional_millionths: 0,
1460 last_update_message: None,
1462 announcement_message: None,
1466 { // Simple route to 3 via 2
1467 let route = router.get_route(&node3, None, &Vec::new(), 100, 42).unwrap();
1468 assert_eq!(route.hops.len(), 2);
1470 assert_eq!(route.hops[0].pubkey, node2);
1471 assert_eq!(route.hops[0].short_channel_id, 2);
1472 assert_eq!(route.hops[0].fee_msat, 100);
1473 assert_eq!(route.hops[0].cltv_expiry_delta, (4 << 8) | 1);
1474 assert_eq!(route.hops[0].node_features.le_flags(), &id_to_feature_flags!(2));
1475 assert_eq!(route.hops[0].channel_features.le_flags(), &id_to_feature_flags!(2));
1477 assert_eq!(route.hops[1].pubkey, node3);
1478 assert_eq!(route.hops[1].short_channel_id, 4);
1479 assert_eq!(route.hops[1].fee_msat, 100);
1480 assert_eq!(route.hops[1].cltv_expiry_delta, 42);
1481 assert_eq!(route.hops[1].node_features.le_flags(), &id_to_feature_flags!(3));
1482 assert_eq!(route.hops[1].channel_features.le_flags(), &id_to_feature_flags!(4));
1485 { // Disable channels 4 and 12 by requiring unknown feature bits
1486 let mut network = router.network_map.write().unwrap();
1487 network.channels.get_mut(&NetworkMap::get_key(4, zero_hash.clone())).unwrap().features.set_require_unknown_bits();
1488 network.channels.get_mut(&NetworkMap::get_key(12, zero_hash.clone())).unwrap().features.set_require_unknown_bits();
1491 { // If all the channels require some features we don't understand, route should fail
1492 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = router.get_route(&node3, None, &Vec::new(), 100, 42) {
1493 assert_eq!(err, "Failed to find a path to the given destination");
1494 } else { panic!(); }
1497 { // If we specify a channel to node8, that overrides our local channel view and that gets used
1498 let our_chans = vec![channelmanager::ChannelDetails {
1499 channel_id: [0; 32],
1500 short_channel_id: Some(42),
1501 remote_network_id: node8.clone(),
1502 counterparty_features: InitFeatures::from_le_bytes(vec![0b11]),
1503 channel_value_satoshis: 0,
1505 outbound_capacity_msat: 0,
1506 inbound_capacity_msat: 0,
1509 let route = router.get_route(&node3, Some(&our_chans), &Vec::new(), 100, 42).unwrap();
1510 assert_eq!(route.hops.len(), 2);
1512 assert_eq!(route.hops[0].pubkey, node8);
1513 assert_eq!(route.hops[0].short_channel_id, 42);
1514 assert_eq!(route.hops[0].fee_msat, 200);
1515 assert_eq!(route.hops[0].cltv_expiry_delta, (13 << 8) | 1);
1516 assert_eq!(route.hops[0].node_features.le_flags(), &vec![0b11]); // it should also override our view of their features
1517 assert_eq!(route.hops[0].channel_features.le_flags(), &Vec::new()); // No feature flags will meet the relevant-to-channel conversion
1519 assert_eq!(route.hops[1].pubkey, node3);
1520 assert_eq!(route.hops[1].short_channel_id, 13);
1521 assert_eq!(route.hops[1].fee_msat, 100);
1522 assert_eq!(route.hops[1].cltv_expiry_delta, 42);
1523 assert_eq!(route.hops[1].node_features.le_flags(), &id_to_feature_flags!(3));
1524 assert_eq!(route.hops[1].channel_features.le_flags(), &id_to_feature_flags!(13));
1527 { // Re-enable channels 4 and 12 by wiping the unknown feature bits
1528 let mut network = router.network_map.write().unwrap();
1529 network.channels.get_mut(&NetworkMap::get_key(4, zero_hash.clone())).unwrap().features.clear_require_unknown_bits();
1530 network.channels.get_mut(&NetworkMap::get_key(12, zero_hash.clone())).unwrap().features.clear_require_unknown_bits();
1533 { // Disable nodes 1, 2, and 8 by requiring unknown feature bits
1534 let mut network = router.network_map.write().unwrap();
1535 network.nodes.get_mut(&node1).unwrap().features.set_require_unknown_bits();
1536 network.nodes.get_mut(&node2).unwrap().features.set_require_unknown_bits();
1537 network.nodes.get_mut(&node8).unwrap().features.set_require_unknown_bits();
1540 { // If all nodes require some features we don't understand, route should fail
1541 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = router.get_route(&node3, None, &Vec::new(), 100, 42) {
1542 assert_eq!(err, "Failed to find a path to the given destination");
1543 } else { panic!(); }
1546 { // If we specify a channel to node8, that overrides our local channel view and that gets used
1547 let our_chans = vec![channelmanager::ChannelDetails {
1548 channel_id: [0; 32],
1549 short_channel_id: Some(42),
1550 remote_network_id: node8.clone(),
1551 counterparty_features: InitFeatures::from_le_bytes(vec![0b11]),
1552 channel_value_satoshis: 0,
1554 outbound_capacity_msat: 0,
1555 inbound_capacity_msat: 0,
1558 let route = router.get_route(&node3, Some(&our_chans), &Vec::new(), 100, 42).unwrap();
1559 assert_eq!(route.hops.len(), 2);
1561 assert_eq!(route.hops[0].pubkey, node8);
1562 assert_eq!(route.hops[0].short_channel_id, 42);
1563 assert_eq!(route.hops[0].fee_msat, 200);
1564 assert_eq!(route.hops[0].cltv_expiry_delta, (13 << 8) | 1);
1565 assert_eq!(route.hops[0].node_features.le_flags(), &vec![0b11]); // it should also override our view of their features
1566 assert_eq!(route.hops[0].channel_features.le_flags(), &Vec::new()); // No feature flags will meet the relevant-to-channel conversion
1568 assert_eq!(route.hops[1].pubkey, node3);
1569 assert_eq!(route.hops[1].short_channel_id, 13);
1570 assert_eq!(route.hops[1].fee_msat, 100);
1571 assert_eq!(route.hops[1].cltv_expiry_delta, 42);
1572 assert_eq!(route.hops[1].node_features.le_flags(), &id_to_feature_flags!(3));
1573 assert_eq!(route.hops[1].channel_features.le_flags(), &id_to_feature_flags!(13));
1576 { // Re-enable nodes 1, 2, and 8
1577 let mut network = router.network_map.write().unwrap();
1578 network.nodes.get_mut(&node1).unwrap().features.clear_require_unknown_bits();
1579 network.nodes.get_mut(&node2).unwrap().features.clear_require_unknown_bits();
1580 network.nodes.get_mut(&node8).unwrap().features.clear_require_unknown_bits();
1583 // Note that we don't test disabling node 3 and failing to route to it, as we (somewhat
1584 // naively) assume that the user checked the feature bits on the invoice, which override
1585 // the node_announcement.
1587 { // Route to 1 via 2 and 3 because our channel to 1 is disabled
1588 let route = router.get_route(&node1, None, &Vec::new(), 100, 42).unwrap();
1589 assert_eq!(route.hops.len(), 3);
1591 assert_eq!(route.hops[0].pubkey, node2);
1592 assert_eq!(route.hops[0].short_channel_id, 2);
1593 assert_eq!(route.hops[0].fee_msat, 200);
1594 assert_eq!(route.hops[0].cltv_expiry_delta, (4 << 8) | 1);
1595 assert_eq!(route.hops[0].node_features.le_flags(), &id_to_feature_flags!(2));
1596 assert_eq!(route.hops[0].channel_features.le_flags(), &id_to_feature_flags!(2));
1598 assert_eq!(route.hops[1].pubkey, node3);
1599 assert_eq!(route.hops[1].short_channel_id, 4);
1600 assert_eq!(route.hops[1].fee_msat, 100);
1601 assert_eq!(route.hops[1].cltv_expiry_delta, (3 << 8) | 2);
1602 assert_eq!(route.hops[1].node_features.le_flags(), &id_to_feature_flags!(3));
1603 assert_eq!(route.hops[1].channel_features.le_flags(), &id_to_feature_flags!(4));
1605 assert_eq!(route.hops[2].pubkey, node1);
1606 assert_eq!(route.hops[2].short_channel_id, 3);
1607 assert_eq!(route.hops[2].fee_msat, 100);
1608 assert_eq!(route.hops[2].cltv_expiry_delta, 42);
1609 assert_eq!(route.hops[2].node_features.le_flags(), &id_to_feature_flags!(1));
1610 assert_eq!(route.hops[2].channel_features.le_flags(), &id_to_feature_flags!(3));
1613 { // If we specify a channel to node8, that overrides our local channel view and that gets used
1614 let our_chans = vec![channelmanager::ChannelDetails {
1615 channel_id: [0; 32],
1616 short_channel_id: Some(42),
1617 remote_network_id: node8.clone(),
1618 counterparty_features: InitFeatures::from_le_bytes(vec![0b11]),
1619 channel_value_satoshis: 0,
1621 outbound_capacity_msat: 0,
1622 inbound_capacity_msat: 0,
1625 let route = router.get_route(&node3, Some(&our_chans), &Vec::new(), 100, 42).unwrap();
1626 assert_eq!(route.hops.len(), 2);
1628 assert_eq!(route.hops[0].pubkey, node8);
1629 assert_eq!(route.hops[0].short_channel_id, 42);
1630 assert_eq!(route.hops[0].fee_msat, 200);
1631 assert_eq!(route.hops[0].cltv_expiry_delta, (13 << 8) | 1);
1632 assert_eq!(route.hops[0].node_features.le_flags(), &vec![0b11]);
1633 assert_eq!(route.hops[0].channel_features.le_flags(), &Vec::new()); // No feature flags will meet the relevant-to-channel conversion
1635 assert_eq!(route.hops[1].pubkey, node3);
1636 assert_eq!(route.hops[1].short_channel_id, 13);
1637 assert_eq!(route.hops[1].fee_msat, 100);
1638 assert_eq!(route.hops[1].cltv_expiry_delta, 42);
1639 assert_eq!(route.hops[1].node_features.le_flags(), &id_to_feature_flags!(3));
1640 assert_eq!(route.hops[1].channel_features.le_flags(), &id_to_feature_flags!(13));
1643 let mut last_hops = vec!(RouteHint {
1644 src_node_id: node4.clone(),
1645 short_channel_id: 8,
1647 fee_proportional_millionths: 0,
1648 cltv_expiry_delta: (8 << 8) | 1,
1649 htlc_minimum_msat: 0,
1651 src_node_id: node5.clone(),
1652 short_channel_id: 9,
1653 fee_base_msat: 1001,
1654 fee_proportional_millionths: 0,
1655 cltv_expiry_delta: (9 << 8) | 1,
1656 htlc_minimum_msat: 0,
1658 src_node_id: node6.clone(),
1659 short_channel_id: 10,
1661 fee_proportional_millionths: 0,
1662 cltv_expiry_delta: (10 << 8) | 1,
1663 htlc_minimum_msat: 0,
1666 { // Simple test across 2, 3, 5, and 4 via a last_hop channel
1667 let route = router.get_route(&node7, None, &last_hops, 100, 42).unwrap();
1668 assert_eq!(route.hops.len(), 5);
1670 assert_eq!(route.hops[0].pubkey, node2);
1671 assert_eq!(route.hops[0].short_channel_id, 2);
1672 assert_eq!(route.hops[0].fee_msat, 100);
1673 assert_eq!(route.hops[0].cltv_expiry_delta, (4 << 8) | 1);
1674 assert_eq!(route.hops[0].node_features.le_flags(), &id_to_feature_flags!(2));
1675 assert_eq!(route.hops[0].channel_features.le_flags(), &id_to_feature_flags!(2));
1677 assert_eq!(route.hops[1].pubkey, node3);
1678 assert_eq!(route.hops[1].short_channel_id, 4);
1679 assert_eq!(route.hops[1].fee_msat, 0);
1680 assert_eq!(route.hops[1].cltv_expiry_delta, (6 << 8) | 1);
1681 assert_eq!(route.hops[1].node_features.le_flags(), &id_to_feature_flags!(3));
1682 assert_eq!(route.hops[1].channel_features.le_flags(), &id_to_feature_flags!(4));
1684 assert_eq!(route.hops[2].pubkey, node5);
1685 assert_eq!(route.hops[2].short_channel_id, 6);
1686 assert_eq!(route.hops[2].fee_msat, 0);
1687 assert_eq!(route.hops[2].cltv_expiry_delta, (11 << 8) | 1);
1688 assert_eq!(route.hops[2].node_features.le_flags(), &id_to_feature_flags!(5));
1689 assert_eq!(route.hops[2].channel_features.le_flags(), &id_to_feature_flags!(6));
1691 assert_eq!(route.hops[3].pubkey, node4);
1692 assert_eq!(route.hops[3].short_channel_id, 11);
1693 assert_eq!(route.hops[3].fee_msat, 0);
1694 assert_eq!(route.hops[3].cltv_expiry_delta, (8 << 8) | 1);
1695 // If we have a peer in the node map, we'll use their features here since we don't have
1696 // a way of figuring out their features from the invoice:
1697 assert_eq!(route.hops[3].node_features.le_flags(), &id_to_feature_flags!(4));
1698 assert_eq!(route.hops[3].channel_features.le_flags(), &id_to_feature_flags!(11));
1700 assert_eq!(route.hops[4].pubkey, node7);
1701 assert_eq!(route.hops[4].short_channel_id, 8);
1702 assert_eq!(route.hops[4].fee_msat, 100);
1703 assert_eq!(route.hops[4].cltv_expiry_delta, 42);
1704 assert_eq!(route.hops[4].node_features.le_flags(), &Vec::new()); // We dont pass flags in from invoices yet
1705 assert_eq!(route.hops[4].channel_features.le_flags(), &Vec::new()); // We can't learn any flags from invoices, sadly
1708 { // Simple test with outbound channel to 4 to test that last_hops and first_hops connect
1709 let our_chans = vec![channelmanager::ChannelDetails {
1710 channel_id: [0; 32],
1711 short_channel_id: Some(42),
1712 remote_network_id: node4.clone(),
1713 counterparty_features: InitFeatures::from_le_bytes(vec![0b11]),
1714 channel_value_satoshis: 0,
1716 outbound_capacity_msat: 0,
1717 inbound_capacity_msat: 0,
1720 let route = router.get_route(&node7, Some(&our_chans), &last_hops, 100, 42).unwrap();
1721 assert_eq!(route.hops.len(), 2);
1723 assert_eq!(route.hops[0].pubkey, node4);
1724 assert_eq!(route.hops[0].short_channel_id, 42);
1725 assert_eq!(route.hops[0].fee_msat, 0);
1726 assert_eq!(route.hops[0].cltv_expiry_delta, (8 << 8) | 1);
1727 assert_eq!(route.hops[0].node_features.le_flags(), &vec![0b11]);
1728 assert_eq!(route.hops[0].channel_features.le_flags(), &Vec::new()); // No feature flags will meet the relevant-to-channel conversion
1730 assert_eq!(route.hops[1].pubkey, node7);
1731 assert_eq!(route.hops[1].short_channel_id, 8);
1732 assert_eq!(route.hops[1].fee_msat, 100);
1733 assert_eq!(route.hops[1].cltv_expiry_delta, 42);
1734 assert_eq!(route.hops[1].node_features.le_flags(), &Vec::new()); // We dont pass flags in from invoices yet
1735 assert_eq!(route.hops[1].channel_features.le_flags(), &Vec::new()); // We can't learn any flags from invoices, sadly
1738 last_hops[0].fee_base_msat = 1000;
1740 { // Revert to via 6 as the fee on 8 goes up
1741 let route = router.get_route(&node7, None, &last_hops, 100, 42).unwrap();
1742 assert_eq!(route.hops.len(), 4);
1744 assert_eq!(route.hops[0].pubkey, node2);
1745 assert_eq!(route.hops[0].short_channel_id, 2);
1746 assert_eq!(route.hops[0].fee_msat, 200); // fee increased as its % of value transferred across node
1747 assert_eq!(route.hops[0].cltv_expiry_delta, (4 << 8) | 1);
1748 assert_eq!(route.hops[0].node_features.le_flags(), &id_to_feature_flags!(2));
1749 assert_eq!(route.hops[0].channel_features.le_flags(), &id_to_feature_flags!(2));
1751 assert_eq!(route.hops[1].pubkey, node3);
1752 assert_eq!(route.hops[1].short_channel_id, 4);
1753 assert_eq!(route.hops[1].fee_msat, 100);
1754 assert_eq!(route.hops[1].cltv_expiry_delta, (7 << 8) | 1);
1755 assert_eq!(route.hops[1].node_features.le_flags(), &id_to_feature_flags!(3));
1756 assert_eq!(route.hops[1].channel_features.le_flags(), &id_to_feature_flags!(4));
1758 assert_eq!(route.hops[2].pubkey, node6);
1759 assert_eq!(route.hops[2].short_channel_id, 7);
1760 assert_eq!(route.hops[2].fee_msat, 0);
1761 assert_eq!(route.hops[2].cltv_expiry_delta, (10 << 8) | 1);
1762 // If we have a peer in the node map, we'll use their features here since we don't have
1763 // a way of figuring out their features from the invoice:
1764 assert_eq!(route.hops[2].node_features.le_flags(), &id_to_feature_flags!(6));
1765 assert_eq!(route.hops[2].channel_features.le_flags(), &id_to_feature_flags!(7));
1767 assert_eq!(route.hops[3].pubkey, node7);
1768 assert_eq!(route.hops[3].short_channel_id, 10);
1769 assert_eq!(route.hops[3].fee_msat, 100);
1770 assert_eq!(route.hops[3].cltv_expiry_delta, 42);
1771 assert_eq!(route.hops[3].node_features.le_flags(), &Vec::new()); // We dont pass flags in from invoices yet
1772 assert_eq!(route.hops[3].channel_features.le_flags(), &Vec::new()); // We can't learn any flags from invoices, sadly
1775 { // ...but still use 8 for larger payments as 6 has a variable feerate
1776 let route = router.get_route(&node7, None, &last_hops, 2000, 42).unwrap();
1777 assert_eq!(route.hops.len(), 5);
1779 assert_eq!(route.hops[0].pubkey, node2);
1780 assert_eq!(route.hops[0].short_channel_id, 2);
1781 assert_eq!(route.hops[0].fee_msat, 3000);
1782 assert_eq!(route.hops[0].cltv_expiry_delta, (4 << 8) | 1);
1783 assert_eq!(route.hops[0].node_features.le_flags(), &id_to_feature_flags!(2));
1784 assert_eq!(route.hops[0].channel_features.le_flags(), &id_to_feature_flags!(2));
1786 assert_eq!(route.hops[1].pubkey, node3);
1787 assert_eq!(route.hops[1].short_channel_id, 4);
1788 assert_eq!(route.hops[1].fee_msat, 0);
1789 assert_eq!(route.hops[1].cltv_expiry_delta, (6 << 8) | 1);
1790 assert_eq!(route.hops[1].node_features.le_flags(), &id_to_feature_flags!(3));
1791 assert_eq!(route.hops[1].channel_features.le_flags(), &id_to_feature_flags!(4));
1793 assert_eq!(route.hops[2].pubkey, node5);
1794 assert_eq!(route.hops[2].short_channel_id, 6);
1795 assert_eq!(route.hops[2].fee_msat, 0);
1796 assert_eq!(route.hops[2].cltv_expiry_delta, (11 << 8) | 1);
1797 assert_eq!(route.hops[2].node_features.le_flags(), &id_to_feature_flags!(5));
1798 assert_eq!(route.hops[2].channel_features.le_flags(), &id_to_feature_flags!(6));
1800 assert_eq!(route.hops[3].pubkey, node4);
1801 assert_eq!(route.hops[3].short_channel_id, 11);
1802 assert_eq!(route.hops[3].fee_msat, 1000);
1803 assert_eq!(route.hops[3].cltv_expiry_delta, (8 << 8) | 1);
1804 // If we have a peer in the node map, we'll use their features here since we don't have
1805 // a way of figuring out their features from the invoice:
1806 assert_eq!(route.hops[3].node_features.le_flags(), &id_to_feature_flags!(4));
1807 assert_eq!(route.hops[3].channel_features.le_flags(), &id_to_feature_flags!(11));
1809 assert_eq!(route.hops[4].pubkey, node7);
1810 assert_eq!(route.hops[4].short_channel_id, 8);
1811 assert_eq!(route.hops[4].fee_msat, 2000);
1812 assert_eq!(route.hops[4].cltv_expiry_delta, 42);
1813 assert_eq!(route.hops[4].node_features.le_flags(), &Vec::new()); // We dont pass flags in from invoices yet
1814 assert_eq!(route.hops[4].channel_features.le_flags(), &Vec::new()); // We can't learn any flags from invoices, sadly
1817 { // Test Router serialization/deserialization
1818 let mut w = TestVecWriter(Vec::new());
1819 let network = router.network_map.read().unwrap();
1820 assert!(!network.channels.is_empty());
1821 assert!(!network.nodes.is_empty());
1822 network.write(&mut w).unwrap();
1823 assert!(<NetworkMap>::read(&mut ::std::io::Cursor::new(&w.0)).unwrap() == *network);