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::sync::atomic::{AtomicUsize, Ordering};
26 use std::collections::{HashMap,BinaryHeap,BTreeMap};
27 use std::collections::btree_map::Entry as BtreeEntry;
31 #[derive(Clone, PartialEq)]
33 /// The node_id of the node at this hop.
34 pub pubkey: PublicKey,
35 /// The node_announcement features of the node at this hop. For the last hop, these may be
36 /// amended to match the features present in the invoice this node generated.
37 pub node_features: NodeFeatures,
38 /// The channel that should be used from the previous hop to reach this node.
39 pub short_channel_id: u64,
40 /// The channel_announcement features of the channel that should be used from the previous hop
41 /// to reach this node.
42 pub channel_features: ChannelFeatures,
43 /// The fee taken on this hop. For the last hop, this should be the full value of the payment.
45 /// The CLTV delta added for this hop. For the last hop, this should be the full CLTV value
46 /// expected at the destination, in excess of the current block height.
47 pub cltv_expiry_delta: u32,
50 /// A route from us through the network to a destination
51 #[derive(Clone, PartialEq)]
53 /// The list of hops, NOT INCLUDING our own, where the last hop is the destination. Thus, this
54 /// must always be at least length one. By protocol rules, this may not currently exceed 20 in
56 pub hops: Vec<RouteHop>,
59 impl Writeable for Route {
60 fn write<W: ::util::ser::Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
61 (self.hops.len() as u8).write(writer)?;
62 for hop in self.hops.iter() {
63 hop.pubkey.write(writer)?;
64 hop.node_features.write(writer)?;
65 hop.short_channel_id.write(writer)?;
66 hop.channel_features.write(writer)?;
67 hop.fee_msat.write(writer)?;
68 hop.cltv_expiry_delta.write(writer)?;
74 impl<R: ::std::io::Read> Readable<R> for Route {
75 fn read(reader: &mut R) -> Result<Route, DecodeError> {
76 let hops_count: u8 = Readable::read(reader)?;
77 let mut hops = Vec::with_capacity(hops_count as usize);
78 for _ in 0..hops_count {
80 pubkey: Readable::read(reader)?,
81 node_features: Readable::read(reader)?,
82 short_channel_id: Readable::read(reader)?,
83 channel_features: Readable::read(reader)?,
84 fee_msat: Readable::read(reader)?,
85 cltv_expiry_delta: Readable::read(reader)?,
95 struct DirectionalChannelInfo {
96 src_node_id: PublicKey,
99 cltv_expiry_delta: u16,
100 htlc_minimum_msat: u64,
102 fee_proportional_millionths: u32,
103 last_update_message: Option<msgs::ChannelUpdate>,
106 impl std::fmt::Display for DirectionalChannelInfo {
107 fn fmt(&self, f: &mut std::fmt::Formatter) -> Result<(), std::fmt::Error> {
108 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)?;
113 impl_writeable!(DirectionalChannelInfo, 0, {
120 fee_proportional_millionths,
126 features: ChannelFeatures,
127 one_to_two: DirectionalChannelInfo,
128 two_to_one: DirectionalChannelInfo,
129 //this is cached here so we can send out it later if required by route_init_sync
130 //keep an eye on this to see if the extra memory is a problem
131 announcement_message: Option<msgs::ChannelAnnouncement>,
134 impl std::fmt::Display for ChannelInfo {
135 fn fmt(&self, f: &mut std::fmt::Formatter) -> Result<(), std::fmt::Error> {
136 write!(f, "features: {}, one_to_two: {}, two_to_one: {}", log_bytes!(self.features.encode()), self.one_to_two, self.two_to_one)?;
141 impl_writeable!(ChannelInfo, 0, {
150 #[cfg(feature = "non_bitcoin_chain_hash_routing")]
151 channels: Vec<(u64, Sha256dHash)>,
152 #[cfg(not(feature = "non_bitcoin_chain_hash_routing"))]
155 lowest_inbound_channel_fee_base_msat: u32,
156 lowest_inbound_channel_fee_proportional_millionths: u32,
158 features: NodeFeatures,
162 addresses: Vec<NetAddress>,
163 //this is cached here so we can send out it later if required by route_init_sync
164 //keep an eye on this to see if the extra memory is a problem
165 announcement_message: Option<msgs::NodeAnnouncement>,
168 impl std::fmt::Display for NodeInfo {
169 fn fmt(&self, f: &mut std::fmt::Formatter) -> Result<(), std::fmt::Error> {
170 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[..])?;
175 impl Writeable for NodeInfo {
176 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
177 (self.channels.len() as u64).write(writer)?;
178 for ref chan in self.channels.iter() {
181 self.lowest_inbound_channel_fee_base_msat.write(writer)?;
182 self.lowest_inbound_channel_fee_proportional_millionths.write(writer)?;
183 self.features.write(writer)?;
184 self.last_update.write(writer)?;
185 self.rgb.write(writer)?;
186 self.alias.write(writer)?;
187 (self.addresses.len() as u64).write(writer)?;
188 for ref addr in &self.addresses {
191 self.announcement_message.write(writer)?;
196 const MAX_ALLOC_SIZE: u64 = 64*1024;
198 impl<R: ::std::io::Read> Readable<R> for NodeInfo {
199 fn read(reader: &mut R) -> Result<NodeInfo, DecodeError> {
200 let channels_count: u64 = Readable::read(reader)?;
201 let mut channels = Vec::with_capacity(cmp::min(channels_count, MAX_ALLOC_SIZE / 8) as usize);
202 for _ in 0..channels_count {
203 channels.push(Readable::read(reader)?);
205 let lowest_inbound_channel_fee_base_msat = Readable::read(reader)?;
206 let lowest_inbound_channel_fee_proportional_millionths = Readable::read(reader)?;
207 let features = Readable::read(reader)?;
208 let last_update = Readable::read(reader)?;
209 let rgb = Readable::read(reader)?;
210 let alias = Readable::read(reader)?;
211 let addresses_count: u64 = Readable::read(reader)?;
212 let mut addresses = Vec::with_capacity(cmp::min(addresses_count, MAX_ALLOC_SIZE / 40) as usize);
213 for _ in 0..addresses_count {
214 match Readable::read(reader) {
215 Ok(Ok(addr)) => { addresses.push(addr); },
216 Ok(Err(_)) => return Err(DecodeError::InvalidValue),
217 Err(DecodeError::ShortRead) => return Err(DecodeError::BadLengthDescriptor),
221 let announcement_message = Readable::read(reader)?;
224 lowest_inbound_channel_fee_base_msat,
225 lowest_inbound_channel_fee_proportional_millionths,
238 #[cfg(feature = "non_bitcoin_chain_hash_routing")]
239 channels: BTreeMap<(u64, Sha256dHash), ChannelInfo>,
240 #[cfg(not(feature = "non_bitcoin_chain_hash_routing"))]
241 channels: BTreeMap<u64, ChannelInfo>,
243 our_node_id: PublicKey,
244 nodes: BTreeMap<PublicKey, NodeInfo>,
247 impl Writeable for NetworkMap {
248 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
249 (self.channels.len() as u64).write(writer)?;
250 for (ref chan_id, ref chan_info) in self.channels.iter() {
251 (*chan_id).write(writer)?;
252 chan_info.write(writer)?;
254 self.our_node_id.write(writer)?;
255 (self.nodes.len() as u64).write(writer)?;
256 for (ref node_id, ref node_info) in self.nodes.iter() {
257 node_id.write(writer)?;
258 node_info.write(writer)?;
264 impl<R: ::std::io::Read> Readable<R> for NetworkMap {
265 fn read(reader: &mut R) -> Result<NetworkMap, DecodeError> {
266 let channels_count: u64 = Readable::read(reader)?;
267 let mut channels = BTreeMap::new();
268 for _ in 0..channels_count {
269 let chan_id: u64 = Readable::read(reader)?;
270 let chan_info = Readable::read(reader)?;
271 channels.insert(chan_id, chan_info);
273 let our_node_id = Readable::read(reader)?;
274 let nodes_count: u64 = Readable::read(reader)?;
275 let mut nodes = BTreeMap::new();
276 for _ in 0..nodes_count {
277 let node_id = Readable::read(reader)?;
278 let node_info = Readable::read(reader)?;
279 nodes.insert(node_id, node_info);
289 impl std::fmt::Display for NetworkMap {
290 fn fmt(&self, f: &mut std::fmt::Formatter) -> Result<(), std::fmt::Error> {
291 write!(f, "Node id {} network map\n[Channels]\n", log_pubkey!(self.our_node_id))?;
292 for (key, val) in self.channels.iter() {
293 write!(f, " {}: {}\n", key, val)?;
295 write!(f, "[Nodes]\n")?;
296 for (key, val) in self.nodes.iter() {
297 write!(f, " {}: {}\n", log_pubkey!(key), val)?;
304 #[cfg(feature = "non_bitcoin_chain_hash_routing")]
306 fn get_key(short_channel_id: u64, chain_hash: Sha256dHash) -> (u64, Sha256dHash) {
307 (short_channel_id, chain_hash)
310 #[cfg(not(feature = "non_bitcoin_chain_hash_routing"))]
312 fn get_key(short_channel_id: u64, _: Sha256dHash) -> u64 {
316 #[cfg(feature = "non_bitcoin_chain_hash_routing")]
318 fn get_short_id(id: &(u64, Sha256dHash)) -> &u64 {
322 #[cfg(not(feature = "non_bitcoin_chain_hash_routing"))]
324 fn get_short_id(id: &u64) -> &u64 {
329 /// A channel descriptor which provides a last-hop route to get_route
330 pub struct RouteHint {
331 /// The node_id of the non-target end of the route
332 pub src_node_id: PublicKey,
333 /// The short_channel_id of this channel
334 pub short_channel_id: u64,
335 /// The static msat-denominated fee which must be paid to use this channel
336 pub fee_base_msat: u32,
337 /// The dynamic proportional fee which must be paid to use this channel, denominated in
338 /// millionths of the value being forwarded to the next hop.
339 pub fee_proportional_millionths: u32,
340 /// The difference in CLTV values between this node and the next node.
341 pub cltv_expiry_delta: u16,
342 /// The minimum value, in msat, which must be relayed to the next hop.
343 pub htlc_minimum_msat: u64,
346 /// Tracks a view of the network, receiving updates from peers and generating Routes to
347 /// payment destinations.
349 secp_ctx: Secp256k1<secp256k1::VerifyOnly>,
350 network_map: RwLock<NetworkMap>,
351 full_syncs_requested: AtomicUsize,
352 chain_monitor: Arc<ChainWatchInterface>,
356 const SERIALIZATION_VERSION: u8 = 1;
357 const MIN_SERIALIZATION_VERSION: u8 = 1;
359 impl Writeable for Router {
360 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
361 writer.write_all(&[SERIALIZATION_VERSION; 1])?;
362 writer.write_all(&[MIN_SERIALIZATION_VERSION; 1])?;
364 let network = self.network_map.read().unwrap();
365 network.write(writer)?;
370 /// Arguments for the creation of a Router that are not deserialized.
371 /// At a high-level, the process for deserializing a Router and resuming normal operation is:
372 /// 1) Deserialize the Router by filling in this struct and calling <Router>::read(reaser, args).
373 /// 2) Register the new Router with your ChainWatchInterface
374 pub struct RouterReadArgs {
375 /// The ChainWatchInterface for use in the Router in the future.
377 /// No calls to the ChainWatchInterface will be made during deserialization.
378 pub chain_monitor: Arc<ChainWatchInterface>,
379 /// The Logger for use in the ChannelManager and which may be used to log information during
381 pub logger: Arc<Logger>,
384 impl<R: ::std::io::Read> ReadableArgs<R, RouterReadArgs> for Router {
385 fn read(reader: &mut R, args: RouterReadArgs) -> Result<Router, DecodeError> {
386 let _ver: u8 = Readable::read(reader)?;
387 let min_ver: u8 = Readable::read(reader)?;
388 if min_ver > SERIALIZATION_VERSION {
389 return Err(DecodeError::UnknownVersion);
391 let network_map = Readable::read(reader)?;
393 secp_ctx: Secp256k1::verification_only(),
394 network_map: RwLock::new(network_map),
395 full_syncs_requested: AtomicUsize::new(0),
396 chain_monitor: args.chain_monitor,
402 macro_rules! secp_verify_sig {
403 ( $secp_ctx: expr, $msg: expr, $sig: expr, $pubkey: expr ) => {
404 match $secp_ctx.verify($msg, $sig, $pubkey) {
406 Err(_) => return Err(LightningError{err: "Invalid signature from remote node", action: ErrorAction::IgnoreError}),
411 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 = &mut *network_lock;
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(&mut 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::empty(),
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());
706 fn should_request_full_sync(&self, _node_id: &PublicKey) -> bool {
707 //TODO: Determine whether to request a full sync based on the network map.
708 const FULL_SYNCS_TO_REQUEST: usize = 5;
709 if self.full_syncs_requested.load(Ordering::Acquire) < FULL_SYNCS_TO_REQUEST {
710 self.full_syncs_requested.fetch_add(1, Ordering::AcqRel);
718 #[derive(Eq, PartialEq)]
719 struct RouteGraphNode {
721 lowest_fee_to_peer_through_node: u64,
722 lowest_fee_to_node: u64,
725 impl cmp::Ord for RouteGraphNode {
726 fn cmp(&self, other: &RouteGraphNode) -> cmp::Ordering {
727 other.lowest_fee_to_peer_through_node.cmp(&self.lowest_fee_to_peer_through_node)
728 .then_with(|| other.pubkey.serialize().cmp(&self.pubkey.serialize()))
732 impl cmp::PartialOrd for RouteGraphNode {
733 fn partial_cmp(&self, other: &RouteGraphNode) -> Option<cmp::Ordering> {
734 Some(self.cmp(other))
738 struct DummyDirectionalChannelInfo {
739 src_node_id: PublicKey,
740 cltv_expiry_delta: u32,
741 htlc_minimum_msat: u64,
743 fee_proportional_millionths: u32,
747 /// Creates a new router with the given node_id to be used as the source for get_route()
748 pub fn new(our_pubkey: PublicKey, chain_monitor: Arc<ChainWatchInterface>, logger: Arc<Logger>) -> Router {
749 let mut nodes = BTreeMap::new();
750 nodes.insert(our_pubkey.clone(), NodeInfo {
751 channels: Vec::new(),
752 lowest_inbound_channel_fee_base_msat: u32::max_value(),
753 lowest_inbound_channel_fee_proportional_millionths: u32::max_value(),
754 features: NodeFeatures::empty(),
758 addresses: Vec::new(),
759 announcement_message: None,
762 secp_ctx: Secp256k1::verification_only(),
763 network_map: RwLock::new(NetworkMap {
764 channels: BTreeMap::new(),
765 our_node_id: our_pubkey,
768 full_syncs_requested: AtomicUsize::new(0),
774 /// Dumps the entire network view of this Router to the logger provided in the constructor at
776 pub fn trace_state(&self) {
777 log_trace!(self, "{}", self.network_map.read().unwrap());
780 /// Get network addresses by node id
781 pub fn get_addresses(&self, pubkey: &PublicKey) -> Option<Vec<NetAddress>> {
782 let network = self.network_map.read().unwrap();
783 network.nodes.get(pubkey).map(|n| n.addresses.clone())
786 /// Marks a node as having failed a route. This will avoid re-using the node in routes for now,
787 /// with an exponential decay in node "badness". Note that there is deliberately no
788 /// mark_channel_bad as a node may simply lie and suggest that an upstream channel from it is
789 /// what failed the route and not the node itself. Instead, setting the blamed_upstream_node
790 /// boolean will reduce the penalty, returning the node to usability faster. If the node is
791 /// behaving correctly, it will disable the failing channel and we will use it again next time.
792 pub fn mark_node_bad(&self, _node_id: &PublicKey, _blamed_upstream_node: bool) {
796 fn remove_channel_in_nodes(nodes: &mut BTreeMap<PublicKey, NodeInfo>, chan: &ChannelInfo, short_channel_id: u64) {
797 macro_rules! remove_from_node {
798 ($node_id: expr) => {
799 if let BtreeEntry::Occupied(mut entry) = nodes.entry($node_id) {
800 entry.get_mut().channels.retain(|chan_id| {
801 short_channel_id != *NetworkMap::get_short_id(chan_id)
803 if entry.get().channels.is_empty() {
804 entry.remove_entry();
807 panic!("Had channel that pointed to unknown node (ie inconsistent network map)!");
811 remove_from_node!(chan.one_to_two.src_node_id);
812 remove_from_node!(chan.two_to_one.src_node_id);
815 /// Gets a route from us to the given target node.
817 /// Extra routing hops between known nodes and the target will be used if they are included in
820 /// If some channels aren't announced, it may be useful to fill in a first_hops with the
821 /// results from a local ChannelManager::list_usable_channels() call. If it is filled in, our
822 /// (this Router's) view of our local channels will be ignored, and only those in first_hops
825 /// Panics if first_hops contains channels without short_channel_ids
826 /// (ChannelManager::list_usable_channels will never include such channels).
828 /// The fees on channels from us to next-hops are ignored (as they are assumed to all be
829 /// equal), however the enabled/disabled bit on such channels as well as the htlc_minimum_msat
830 /// *is* checked as they may change based on the receiving node.
831 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> {
832 // TODO: Obviously *only* using total fee cost sucks. We should consider weighting by
833 // uptime/success in using a node in the past.
834 let network = self.network_map.read().unwrap();
836 if *target == network.our_node_id {
837 return Err(LightningError{err: "Cannot generate a route to ourselves", action: ErrorAction::IgnoreError});
840 if final_value_msat > 21_000_000 * 1_0000_0000 * 1000 {
841 return Err(LightningError{err: "Cannot generate a route of more value than all existing satoshis", action: ErrorAction::IgnoreError});
844 // We do a dest-to-source Dijkstra's sorting by each node's distance from the destination
845 // plus the minimum per-HTLC fee to get from it to another node (aka "shitty A*").
846 // TODO: There are a few tweaks we could do, including possibly pre-calculating more stuff
847 // to use as the A* heuristic beyond just the cost to get one node further than the current
850 let dummy_directional_info = DummyDirectionalChannelInfo { // used for first_hops routes
851 src_node_id: network.our_node_id.clone(),
852 cltv_expiry_delta: 0,
853 htlc_minimum_msat: 0,
855 fee_proportional_millionths: 0,
858 let mut targets = BinaryHeap::new(); //TODO: Do we care about switching to eg Fibbonaci heap?
859 let mut dist = HashMap::with_capacity(network.nodes.len());
861 let mut first_hop_targets = HashMap::with_capacity(if first_hops.is_some() { first_hops.as_ref().unwrap().len() } else { 0 });
862 if let Some(hops) = first_hops {
864 let short_channel_id = chan.short_channel_id.expect("first_hops should be filled in with usable channels, not pending ones");
865 if chan.remote_network_id == *target {
867 hops: vec![RouteHop {
868 pubkey: chan.remote_network_id,
869 node_features: NodeFeatures::with_known_relevant_init_flags(&chan.counterparty_features),
871 channel_features: ChannelFeatures::with_known_relevant_init_flags(&chan.counterparty_features),
872 fee_msat: final_value_msat,
873 cltv_expiry_delta: final_cltv,
877 first_hop_targets.insert(chan.remote_network_id, (short_channel_id, chan.counterparty_features.clone()));
879 if first_hop_targets.is_empty() {
880 return Err(LightningError{err: "Cannot route when there are no outbound routes away from us", action: ErrorAction::IgnoreError});
884 macro_rules! add_entry {
885 // Adds entry which goes from the node pointed to by $directional_info to
886 // $dest_node_id over the channel with id $chan_id with fees described in
887 // $directional_info.
888 ( $chan_id: expr, $dest_node_id: expr, $directional_info: expr, $chan_features: expr, $starting_fee_msat: expr ) => {
889 //TODO: Explore simply adding fee to hit htlc_minimum_msat
890 if $starting_fee_msat as u64 + final_value_msat >= $directional_info.htlc_minimum_msat {
891 let proportional_fee_millions = ($starting_fee_msat + final_value_msat).checked_mul($directional_info.fee_proportional_millionths as u64);
892 if let Some(new_fee) = proportional_fee_millions.and_then(|part| {
893 ($directional_info.fee_base_msat as u64).checked_add(part / 1000000) })
895 let mut total_fee = $starting_fee_msat as u64;
896 let hm_entry = dist.entry(&$directional_info.src_node_id);
897 let old_entry = hm_entry.or_insert_with(|| {
898 let node = network.nodes.get(&$directional_info.src_node_id).unwrap();
900 node.lowest_inbound_channel_fee_base_msat,
901 node.lowest_inbound_channel_fee_proportional_millionths,
903 pubkey: $dest_node_id.clone(),
904 node_features: NodeFeatures::empty(),
906 channel_features: $chan_features.clone(),
908 cltv_expiry_delta: 0,
911 if $directional_info.src_node_id != network.our_node_id {
912 // Ignore new_fee for channel-from-us as we assume all channels-from-us
913 // will have the same effective-fee
914 total_fee += new_fee;
915 if let Some(fee_inc) = final_value_msat.checked_add(total_fee).and_then(|inc| { (old_entry.2 as u64).checked_mul(inc) }) {
916 total_fee += fee_inc / 1000000 + (old_entry.1 as u64);
918 // max_value means we'll always fail the old_entry.0 > total_fee check
919 total_fee = u64::max_value();
922 let new_graph_node = RouteGraphNode {
923 pubkey: $directional_info.src_node_id,
924 lowest_fee_to_peer_through_node: total_fee,
925 lowest_fee_to_node: $starting_fee_msat as u64 + new_fee,
927 if old_entry.0 > total_fee {
928 targets.push(new_graph_node);
929 old_entry.0 = total_fee;
930 old_entry.3 = RouteHop {
931 pubkey: $dest_node_id.clone(),
932 node_features: NodeFeatures::empty(),
933 short_channel_id: $chan_id.clone(),
934 channel_features: $chan_features.clone(),
935 fee_msat: new_fee, // This field is ignored on the last-hop anyway
936 cltv_expiry_delta: $directional_info.cltv_expiry_delta as u32,
944 macro_rules! add_entries_to_cheapest_to_target_node {
945 ( $node: expr, $node_id: expr, $fee_to_target_msat: expr ) => {
946 if first_hops.is_some() {
947 if let Some(&(ref first_hop, ref features)) = first_hop_targets.get(&$node_id) {
948 add_entry!(first_hop, $node_id, dummy_directional_info, ChannelFeatures::with_known_relevant_init_flags(&features), $fee_to_target_msat);
952 if !$node.features.requires_unknown_bits() {
953 for chan_id in $node.channels.iter() {
954 let chan = network.channels.get(chan_id).unwrap();
955 if !chan.features.requires_unknown_bits() {
956 if chan.one_to_two.src_node_id == *$node_id {
957 // ie $node is one, ie next hop in A* is two, via the two_to_one channel
958 if first_hops.is_none() || chan.two_to_one.src_node_id != network.our_node_id {
959 if chan.two_to_one.enabled {
960 add_entry!(chan_id, chan.one_to_two.src_node_id, chan.two_to_one, chan.features, $fee_to_target_msat);
964 if first_hops.is_none() || chan.one_to_two.src_node_id != network.our_node_id {
965 if chan.one_to_two.enabled {
966 add_entry!(chan_id, chan.two_to_one.src_node_id, chan.one_to_two, chan.features, $fee_to_target_msat);
976 match network.nodes.get(target) {
979 add_entries_to_cheapest_to_target_node!(node, target, 0);
983 for hop in last_hops.iter() {
984 if first_hops.is_none() || hop.src_node_id != network.our_node_id { // first_hop overrules last_hops
985 if network.nodes.get(&hop.src_node_id).is_some() {
986 if first_hops.is_some() {
987 if let Some(&(ref first_hop, ref features)) = first_hop_targets.get(&hop.src_node_id) {
988 // Currently there are no channel-context features defined, so we are a
989 // bit lazy here. In the future, we should pull them out via our
990 // ChannelManager, but there's no reason to waste the space until we
992 add_entry!(first_hop, hop.src_node_id, dummy_directional_info, ChannelFeatures::with_known_relevant_init_flags(&features), 0);
995 // BOLT 11 doesn't allow inclusion of features for the last hop hints, which
996 // really sucks, cause we're gonna need that eventually.
997 add_entry!(hop.short_channel_id, target, hop, ChannelFeatures::empty(), 0);
1002 while let Some(RouteGraphNode { pubkey, lowest_fee_to_node, .. }) = targets.pop() {
1003 if pubkey == network.our_node_id {
1004 let mut res = vec!(dist.remove(&network.our_node_id).unwrap().3);
1006 if let Some(&(_, ref features)) = first_hop_targets.get(&res.last().unwrap().pubkey) {
1007 res.last_mut().unwrap().node_features = NodeFeatures::with_known_relevant_init_flags(&features);
1008 } else if let Some(node) = network.nodes.get(&res.last().unwrap().pubkey) {
1009 res.last_mut().unwrap().node_features = node.features.clone();
1011 // We should be able to fill in features for everything except the last
1012 // hop, if the last hop was provided via a BOLT 11 invoice (though we
1013 // should be able to extend it further as BOLT 11 does have feature
1014 // flags for the last hop node itself).
1015 assert!(res.last().unwrap().pubkey == *target);
1017 if res.last().unwrap().pubkey == *target {
1021 let new_entry = match dist.remove(&res.last().unwrap().pubkey) {
1023 None => return Err(LightningError{err: "Failed to find a non-fee-overflowing path to the given destination", action: ErrorAction::IgnoreError}),
1025 res.last_mut().unwrap().fee_msat = new_entry.fee_msat;
1026 res.last_mut().unwrap().cltv_expiry_delta = new_entry.cltv_expiry_delta;
1027 res.push(new_entry);
1029 res.last_mut().unwrap().fee_msat = final_value_msat;
1030 res.last_mut().unwrap().cltv_expiry_delta = final_cltv;
1031 let route = Route { hops: res };
1032 log_trace!(self, "Got route: {}", log_route!(route));
1036 match network.nodes.get(&pubkey) {
1039 add_entries_to_cheapest_to_target_node!(node, &pubkey, lowest_fee_to_node);
1044 Err(LightningError{err: "Failed to find a path to the given destination", action: ErrorAction::IgnoreError})
1050 use chain::chaininterface;
1051 use ln::channelmanager;
1052 use ln::router::{Router,NodeInfo,NetworkMap,ChannelInfo,DirectionalChannelInfo,RouteHint};
1053 use ln::features::{ChannelFeatures, InitFeatures, NodeFeatures};
1054 use ln::msgs::{ErrorAction, LightningError, RoutingMessageHandler};
1055 use util::test_utils;
1056 use util::test_utils::TestVecWriter;
1057 use util::logger::Logger;
1058 use util::ser::{Writeable, Readable};
1060 use bitcoin_hashes::sha256d::Hash as Sha256dHash;
1061 use bitcoin_hashes::Hash;
1062 use bitcoin::network::constants::Network;
1066 use secp256k1::key::{PublicKey,SecretKey};
1068 use secp256k1::Secp256k1;
1072 fn create_router() -> (Secp256k1<All>, PublicKey, Router) {
1073 let secp_ctx = Secp256k1::new();
1074 let our_id = PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&hex::decode("0101010101010101010101010101010101010101010101010101010101010101").unwrap()[..]).unwrap());
1075 let logger: Arc<Logger> = Arc::new(test_utils::TestLogger::new());
1076 let chain_monitor = Arc::new(chaininterface::ChainWatchInterfaceUtil::new(Network::Testnet, Arc::clone(&logger)));
1077 let router = Router::new(our_id, chain_monitor, Arc::clone(&logger));
1078 (secp_ctx, our_id, router)
1083 let (secp_ctx, our_id, router) = create_router();
1085 // Build network from our_id to node8:
1087 // -1(1)2- node1 -1(3)2-
1089 // our_id -1(12)2- node8 -1(13)2--- node3
1091 // -1(2)2- node2 -1(4)2-
1094 // chan1 1-to-2: disabled
1095 // chan1 2-to-1: enabled, 0 fee
1097 // chan2 1-to-2: enabled, ignored fee
1098 // chan2 2-to-1: enabled, 0 fee
1100 // chan3 1-to-2: enabled, 0 fee
1101 // chan3 2-to-1: enabled, 100 msat fee
1103 // chan4 1-to-2: enabled, 100% fee
1104 // chan4 2-to-1: enabled, 0 fee
1106 // chan12 1-to-2: enabled, ignored fee
1107 // chan12 2-to-1: enabled, 0 fee
1109 // chan13 1-to-2: enabled, 200% fee
1110 // chan13 2-to-1: enabled, 0 fee
1113 // -1(5)2- node4 -1(8)2--
1117 // node3--1(6)2- node5 -1(9)2--- node7 (not in global route map)
1119 // -1(7)2- node6 -1(10)2-
1121 // chan5 1-to-2: enabled, 100 msat fee
1122 // chan5 2-to-1: enabled, 0 fee
1124 // chan6 1-to-2: enabled, 0 fee
1125 // chan6 2-to-1: enabled, 0 fee
1127 // chan7 1-to-2: enabled, 100% fee
1128 // chan7 2-to-1: enabled, 0 fee
1130 // chan8 1-to-2: enabled, variable fee (0 then 1000 msat)
1131 // chan8 2-to-1: enabled, 0 fee
1133 // chan9 1-to-2: enabled, 1001 msat fee
1134 // chan9 2-to-1: enabled, 0 fee
1136 // chan10 1-to-2: enabled, 0 fee
1137 // chan10 2-to-1: enabled, 0 fee
1139 // chan11 1-to-2: enabled, 0 fee
1140 // chan11 2-to-1: enabled, 0 fee
1142 let node1 = PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&hex::decode("0202020202020202020202020202020202020202020202020202020202020202").unwrap()[..]).unwrap());
1143 let node2 = PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&hex::decode("0303030303030303030303030303030303030303030303030303030303030303").unwrap()[..]).unwrap());
1144 let node3 = PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&hex::decode("0404040404040404040404040404040404040404040404040404040404040404").unwrap()[..]).unwrap());
1145 let node4 = PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&hex::decode("0505050505050505050505050505050505050505050505050505050505050505").unwrap()[..]).unwrap());
1146 let node5 = PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&hex::decode("0606060606060606060606060606060606060606060606060606060606060606").unwrap()[..]).unwrap());
1147 let node6 = PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&hex::decode("0707070707070707070707070707070707070707070707070707070707070707").unwrap()[..]).unwrap());
1148 let node7 = PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&hex::decode("0808080808080808080808080808080808080808080808080808080808080808").unwrap()[..]).unwrap());
1149 let node8 = PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&hex::decode("0909090909090909090909090909090909090909090909090909090909090909").unwrap()[..]).unwrap());
1151 let zero_hash = Sha256dHash::hash(&[0; 32]);
1153 macro_rules! id_to_feature_flags {
1154 // Set the feature flags to the id'th odd (ie non-required) feature bit so that we can
1155 // test for it later.
1157 let idx = ($id - 1) * 2 + 1;
1159 vec![1 << (idx - 8*3), 0, 0, 0]
1160 } else if idx > 8*2 {
1161 vec![1 << (idx - 8*2), 0, 0]
1162 } else if idx > 8*1 {
1163 vec![1 << (idx - 8*1), 0]
1171 let mut network = router.network_map.write().unwrap();
1173 network.nodes.insert(node1.clone(), NodeInfo {
1174 channels: vec!(NetworkMap::get_key(1, zero_hash.clone()), NetworkMap::get_key(3, zero_hash.clone())),
1175 lowest_inbound_channel_fee_base_msat: 100,
1176 lowest_inbound_channel_fee_proportional_millionths: 0,
1177 features: NodeFeatures::from_le_bytes(id_to_feature_flags!(1)),
1181 addresses: Vec::new(),
1182 announcement_message: None,
1184 network.channels.insert(NetworkMap::get_key(1, zero_hash.clone()), ChannelInfo {
1185 features: ChannelFeatures::from_le_bytes(id_to_feature_flags!(1)),
1186 one_to_two: DirectionalChannelInfo {
1187 src_node_id: our_id.clone(),
1190 cltv_expiry_delta: u16::max_value(), // This value should be ignored
1191 htlc_minimum_msat: 0,
1192 fee_base_msat: u32::max_value(), // This value should be ignored
1193 fee_proportional_millionths: u32::max_value(), // This value should be ignored
1194 last_update_message: None,
1195 }, two_to_one: DirectionalChannelInfo {
1196 src_node_id: node1.clone(),
1199 cltv_expiry_delta: 0,
1200 htlc_minimum_msat: 0,
1202 fee_proportional_millionths: 0,
1203 last_update_message: None,
1205 announcement_message: None,
1207 network.nodes.insert(node2.clone(), NodeInfo {
1208 channels: vec!(NetworkMap::get_key(2, zero_hash.clone()), NetworkMap::get_key(4, zero_hash.clone())),
1209 lowest_inbound_channel_fee_base_msat: 0,
1210 lowest_inbound_channel_fee_proportional_millionths: 0,
1211 features: NodeFeatures::from_le_bytes(id_to_feature_flags!(2)),
1215 addresses: Vec::new(),
1216 announcement_message: None,
1218 network.channels.insert(NetworkMap::get_key(2, zero_hash.clone()), ChannelInfo {
1219 features: ChannelFeatures::from_le_bytes(id_to_feature_flags!(2)),
1220 one_to_two: DirectionalChannelInfo {
1221 src_node_id: our_id.clone(),
1224 cltv_expiry_delta: u16::max_value(), // This value should be ignored
1225 htlc_minimum_msat: 0,
1226 fee_base_msat: u32::max_value(), // This value should be ignored
1227 fee_proportional_millionths: u32::max_value(), // This value should be ignored
1228 last_update_message: None,
1229 }, two_to_one: DirectionalChannelInfo {
1230 src_node_id: node2.clone(),
1233 cltv_expiry_delta: 0,
1234 htlc_minimum_msat: 0,
1236 fee_proportional_millionths: 0,
1237 last_update_message: None,
1239 announcement_message: None,
1241 network.nodes.insert(node8.clone(), NodeInfo {
1242 channels: vec!(NetworkMap::get_key(12, zero_hash.clone()), NetworkMap::get_key(13, zero_hash.clone())),
1243 lowest_inbound_channel_fee_base_msat: 0,
1244 lowest_inbound_channel_fee_proportional_millionths: 0,
1245 features: NodeFeatures::from_le_bytes(id_to_feature_flags!(8)),
1249 addresses: Vec::new(),
1250 announcement_message: None,
1252 network.channels.insert(NetworkMap::get_key(12, zero_hash.clone()), ChannelInfo {
1253 features: ChannelFeatures::from_le_bytes(id_to_feature_flags!(12)),
1254 one_to_two: DirectionalChannelInfo {
1255 src_node_id: our_id.clone(),
1258 cltv_expiry_delta: u16::max_value(), // This value should be ignored
1259 htlc_minimum_msat: 0,
1260 fee_base_msat: u32::max_value(), // This value should be ignored
1261 fee_proportional_millionths: u32::max_value(), // This value should be ignored
1262 last_update_message: None,
1263 }, two_to_one: DirectionalChannelInfo {
1264 src_node_id: node8.clone(),
1267 cltv_expiry_delta: 0,
1268 htlc_minimum_msat: 0,
1270 fee_proportional_millionths: 0,
1271 last_update_message: None,
1273 announcement_message: None,
1275 network.nodes.insert(node3.clone(), NodeInfo {
1277 NetworkMap::get_key(3, zero_hash.clone()),
1278 NetworkMap::get_key(4, zero_hash.clone()),
1279 NetworkMap::get_key(13, zero_hash.clone()),
1280 NetworkMap::get_key(5, zero_hash.clone()),
1281 NetworkMap::get_key(6, zero_hash.clone()),
1282 NetworkMap::get_key(7, zero_hash.clone())),
1283 lowest_inbound_channel_fee_base_msat: 0,
1284 lowest_inbound_channel_fee_proportional_millionths: 0,
1285 features: NodeFeatures::from_le_bytes(id_to_feature_flags!(3)),
1289 addresses: Vec::new(),
1290 announcement_message: None,
1292 network.channels.insert(NetworkMap::get_key(3, zero_hash.clone()), ChannelInfo {
1293 features: ChannelFeatures::from_le_bytes(id_to_feature_flags!(3)),
1294 one_to_two: DirectionalChannelInfo {
1295 src_node_id: node1.clone(),
1298 cltv_expiry_delta: (3 << 8) | 1,
1299 htlc_minimum_msat: 0,
1301 fee_proportional_millionths: 0,
1302 last_update_message: None,
1303 }, two_to_one: DirectionalChannelInfo {
1304 src_node_id: node3.clone(),
1307 cltv_expiry_delta: (3 << 8) | 2,
1308 htlc_minimum_msat: 0,
1310 fee_proportional_millionths: 0,
1311 last_update_message: None,
1313 announcement_message: None,
1315 network.channels.insert(NetworkMap::get_key(4, zero_hash.clone()), ChannelInfo {
1316 features: ChannelFeatures::from_le_bytes(id_to_feature_flags!(4)),
1317 one_to_two: DirectionalChannelInfo {
1318 src_node_id: node2.clone(),
1321 cltv_expiry_delta: (4 << 8) | 1,
1322 htlc_minimum_msat: 0,
1324 fee_proportional_millionths: 1000000,
1325 last_update_message: None,
1326 }, two_to_one: DirectionalChannelInfo {
1327 src_node_id: node3.clone(),
1330 cltv_expiry_delta: (4 << 8) | 2,
1331 htlc_minimum_msat: 0,
1333 fee_proportional_millionths: 0,
1334 last_update_message: None,
1336 announcement_message: None,
1338 network.channels.insert(NetworkMap::get_key(13, zero_hash.clone()), ChannelInfo {
1339 features: ChannelFeatures::from_le_bytes(id_to_feature_flags!(13)),
1340 one_to_two: DirectionalChannelInfo {
1341 src_node_id: node8.clone(),
1344 cltv_expiry_delta: (13 << 8) | 1,
1345 htlc_minimum_msat: 0,
1347 fee_proportional_millionths: 2000000,
1348 last_update_message: None,
1349 }, two_to_one: DirectionalChannelInfo {
1350 src_node_id: node3.clone(),
1353 cltv_expiry_delta: (13 << 8) | 2,
1354 htlc_minimum_msat: 0,
1356 fee_proportional_millionths: 0,
1357 last_update_message: None,
1359 announcement_message: None,
1361 network.nodes.insert(node4.clone(), NodeInfo {
1362 channels: vec!(NetworkMap::get_key(5, zero_hash.clone()), NetworkMap::get_key(11, zero_hash.clone())),
1363 lowest_inbound_channel_fee_base_msat: 0,
1364 lowest_inbound_channel_fee_proportional_millionths: 0,
1365 features: NodeFeatures::from_le_bytes(id_to_feature_flags!(4)),
1369 addresses: Vec::new(),
1370 announcement_message: None,
1372 network.channels.insert(NetworkMap::get_key(5, zero_hash.clone()), ChannelInfo {
1373 features: ChannelFeatures::from_le_bytes(id_to_feature_flags!(5)),
1374 one_to_two: DirectionalChannelInfo {
1375 src_node_id: node3.clone(),
1378 cltv_expiry_delta: (5 << 8) | 1,
1379 htlc_minimum_msat: 0,
1381 fee_proportional_millionths: 0,
1382 last_update_message: None,
1383 }, two_to_one: DirectionalChannelInfo {
1384 src_node_id: node4.clone(),
1387 cltv_expiry_delta: (5 << 8) | 2,
1388 htlc_minimum_msat: 0,
1390 fee_proportional_millionths: 0,
1391 last_update_message: None,
1393 announcement_message: None,
1395 network.nodes.insert(node5.clone(), NodeInfo {
1396 channels: vec!(NetworkMap::get_key(6, zero_hash.clone()), NetworkMap::get_key(11, zero_hash.clone())),
1397 lowest_inbound_channel_fee_base_msat: 0,
1398 lowest_inbound_channel_fee_proportional_millionths: 0,
1399 features: NodeFeatures::from_le_bytes(id_to_feature_flags!(5)),
1403 addresses: Vec::new(),
1404 announcement_message: None,
1406 network.channels.insert(NetworkMap::get_key(6, zero_hash.clone()), ChannelInfo {
1407 features: ChannelFeatures::from_le_bytes(id_to_feature_flags!(6)),
1408 one_to_two: DirectionalChannelInfo {
1409 src_node_id: node3.clone(),
1412 cltv_expiry_delta: (6 << 8) | 1,
1413 htlc_minimum_msat: 0,
1415 fee_proportional_millionths: 0,
1416 last_update_message: None,
1417 }, two_to_one: DirectionalChannelInfo {
1418 src_node_id: node5.clone(),
1421 cltv_expiry_delta: (6 << 8) | 2,
1422 htlc_minimum_msat: 0,
1424 fee_proportional_millionths: 0,
1425 last_update_message: None,
1427 announcement_message: None,
1429 network.channels.insert(NetworkMap::get_key(11, zero_hash.clone()), ChannelInfo {
1430 features: ChannelFeatures::from_le_bytes(id_to_feature_flags!(11)),
1431 one_to_two: DirectionalChannelInfo {
1432 src_node_id: node5.clone(),
1435 cltv_expiry_delta: (11 << 8) | 1,
1436 htlc_minimum_msat: 0,
1438 fee_proportional_millionths: 0,
1439 last_update_message: None,
1440 }, two_to_one: DirectionalChannelInfo {
1441 src_node_id: node4.clone(),
1444 cltv_expiry_delta: (11 << 8) | 2,
1445 htlc_minimum_msat: 0,
1447 fee_proportional_millionths: 0,
1448 last_update_message: None,
1450 announcement_message: None,
1452 network.nodes.insert(node6.clone(), NodeInfo {
1453 channels: vec!(NetworkMap::get_key(7, zero_hash.clone())),
1454 lowest_inbound_channel_fee_base_msat: 0,
1455 lowest_inbound_channel_fee_proportional_millionths: 0,
1456 features: NodeFeatures::from_le_bytes(id_to_feature_flags!(6)),
1460 addresses: Vec::new(),
1461 announcement_message: None,
1463 network.channels.insert(NetworkMap::get_key(7, zero_hash.clone()), ChannelInfo {
1464 features: ChannelFeatures::from_le_bytes(id_to_feature_flags!(7)),
1465 one_to_two: DirectionalChannelInfo {
1466 src_node_id: node3.clone(),
1469 cltv_expiry_delta: (7 << 8) | 1,
1470 htlc_minimum_msat: 0,
1472 fee_proportional_millionths: 1000000,
1473 last_update_message: None,
1474 }, two_to_one: DirectionalChannelInfo {
1475 src_node_id: node6.clone(),
1478 cltv_expiry_delta: (7 << 8) | 2,
1479 htlc_minimum_msat: 0,
1481 fee_proportional_millionths: 0,
1482 last_update_message: None,
1484 announcement_message: None,
1488 { // Simple route to 3 via 2
1489 let route = router.get_route(&node3, None, &Vec::new(), 100, 42).unwrap();
1490 assert_eq!(route.hops.len(), 2);
1492 assert_eq!(route.hops[0].pubkey, node2);
1493 assert_eq!(route.hops[0].short_channel_id, 2);
1494 assert_eq!(route.hops[0].fee_msat, 100);
1495 assert_eq!(route.hops[0].cltv_expiry_delta, (4 << 8) | 1);
1496 assert_eq!(route.hops[0].node_features.le_flags(), &id_to_feature_flags!(2));
1497 assert_eq!(route.hops[0].channel_features.le_flags(), &id_to_feature_flags!(2));
1499 assert_eq!(route.hops[1].pubkey, node3);
1500 assert_eq!(route.hops[1].short_channel_id, 4);
1501 assert_eq!(route.hops[1].fee_msat, 100);
1502 assert_eq!(route.hops[1].cltv_expiry_delta, 42);
1503 assert_eq!(route.hops[1].node_features.le_flags(), &id_to_feature_flags!(3));
1504 assert_eq!(route.hops[1].channel_features.le_flags(), &id_to_feature_flags!(4));
1507 { // Disable channels 4 and 12 by requiring unknown feature bits
1508 let mut network = router.network_map.write().unwrap();
1509 network.channels.get_mut(&NetworkMap::get_key(4, zero_hash.clone())).unwrap().features.set_require_unknown_bits();
1510 network.channels.get_mut(&NetworkMap::get_key(12, zero_hash.clone())).unwrap().features.set_require_unknown_bits();
1513 { // If all the channels require some features we don't understand, route should fail
1514 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = router.get_route(&node3, None, &Vec::new(), 100, 42) {
1515 assert_eq!(err, "Failed to find a path to the given destination");
1516 } else { panic!(); }
1519 { // If we specify a channel to node8, that overrides our local channel view and that gets used
1520 let our_chans = vec![channelmanager::ChannelDetails {
1521 channel_id: [0; 32],
1522 short_channel_id: Some(42),
1523 remote_network_id: node8.clone(),
1524 counterparty_features: InitFeatures::from_le_bytes(vec![0b11]),
1525 channel_value_satoshis: 0,
1527 outbound_capacity_msat: 0,
1528 inbound_capacity_msat: 0,
1531 let route = router.get_route(&node3, Some(&our_chans), &Vec::new(), 100, 42).unwrap();
1532 assert_eq!(route.hops.len(), 2);
1534 assert_eq!(route.hops[0].pubkey, node8);
1535 assert_eq!(route.hops[0].short_channel_id, 42);
1536 assert_eq!(route.hops[0].fee_msat, 200);
1537 assert_eq!(route.hops[0].cltv_expiry_delta, (13 << 8) | 1);
1538 assert_eq!(route.hops[0].node_features.le_flags(), &vec![0b11]); // it should also override our view of their features
1539 assert_eq!(route.hops[0].channel_features.le_flags(), &Vec::new()); // No feature flags will meet the relevant-to-channel conversion
1541 assert_eq!(route.hops[1].pubkey, node3);
1542 assert_eq!(route.hops[1].short_channel_id, 13);
1543 assert_eq!(route.hops[1].fee_msat, 100);
1544 assert_eq!(route.hops[1].cltv_expiry_delta, 42);
1545 assert_eq!(route.hops[1].node_features.le_flags(), &id_to_feature_flags!(3));
1546 assert_eq!(route.hops[1].channel_features.le_flags(), &id_to_feature_flags!(13));
1549 { // Re-enable channels 4 and 12 by wiping the unknown feature bits
1550 let mut network = router.network_map.write().unwrap();
1551 network.channels.get_mut(&NetworkMap::get_key(4, zero_hash.clone())).unwrap().features.clear_require_unknown_bits();
1552 network.channels.get_mut(&NetworkMap::get_key(12, zero_hash.clone())).unwrap().features.clear_require_unknown_bits();
1555 { // Disable nodes 1, 2, and 8 by requiring unknown feature bits
1556 let mut network = router.network_map.write().unwrap();
1557 network.nodes.get_mut(&node1).unwrap().features.set_require_unknown_bits();
1558 network.nodes.get_mut(&node2).unwrap().features.set_require_unknown_bits();
1559 network.nodes.get_mut(&node8).unwrap().features.set_require_unknown_bits();
1562 { // If all nodes require some features we don't understand, route should fail
1563 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = router.get_route(&node3, None, &Vec::new(), 100, 42) {
1564 assert_eq!(err, "Failed to find a path to the given destination");
1565 } else { panic!(); }
1568 { // If we specify a channel to node8, that overrides our local channel view and that gets used
1569 let our_chans = vec![channelmanager::ChannelDetails {
1570 channel_id: [0; 32],
1571 short_channel_id: Some(42),
1572 remote_network_id: node8.clone(),
1573 counterparty_features: InitFeatures::from_le_bytes(vec![0b11]),
1574 channel_value_satoshis: 0,
1576 outbound_capacity_msat: 0,
1577 inbound_capacity_msat: 0,
1580 let route = router.get_route(&node3, Some(&our_chans), &Vec::new(), 100, 42).unwrap();
1581 assert_eq!(route.hops.len(), 2);
1583 assert_eq!(route.hops[0].pubkey, node8);
1584 assert_eq!(route.hops[0].short_channel_id, 42);
1585 assert_eq!(route.hops[0].fee_msat, 200);
1586 assert_eq!(route.hops[0].cltv_expiry_delta, (13 << 8) | 1);
1587 assert_eq!(route.hops[0].node_features.le_flags(), &vec![0b11]); // it should also override our view of their features
1588 assert_eq!(route.hops[0].channel_features.le_flags(), &Vec::new()); // No feature flags will meet the relevant-to-channel conversion
1590 assert_eq!(route.hops[1].pubkey, node3);
1591 assert_eq!(route.hops[1].short_channel_id, 13);
1592 assert_eq!(route.hops[1].fee_msat, 100);
1593 assert_eq!(route.hops[1].cltv_expiry_delta, 42);
1594 assert_eq!(route.hops[1].node_features.le_flags(), &id_to_feature_flags!(3));
1595 assert_eq!(route.hops[1].channel_features.le_flags(), &id_to_feature_flags!(13));
1598 { // Re-enable nodes 1, 2, and 8
1599 let mut network = router.network_map.write().unwrap();
1600 network.nodes.get_mut(&node1).unwrap().features.clear_require_unknown_bits();
1601 network.nodes.get_mut(&node2).unwrap().features.clear_require_unknown_bits();
1602 network.nodes.get_mut(&node8).unwrap().features.clear_require_unknown_bits();
1605 // Note that we don't test disabling node 3 and failing to route to it, as we (somewhat
1606 // naively) assume that the user checked the feature bits on the invoice, which override
1607 // the node_announcement.
1609 { // Route to 1 via 2 and 3 because our channel to 1 is disabled
1610 let route = router.get_route(&node1, None, &Vec::new(), 100, 42).unwrap();
1611 assert_eq!(route.hops.len(), 3);
1613 assert_eq!(route.hops[0].pubkey, node2);
1614 assert_eq!(route.hops[0].short_channel_id, 2);
1615 assert_eq!(route.hops[0].fee_msat, 200);
1616 assert_eq!(route.hops[0].cltv_expiry_delta, (4 << 8) | 1);
1617 assert_eq!(route.hops[0].node_features.le_flags(), &id_to_feature_flags!(2));
1618 assert_eq!(route.hops[0].channel_features.le_flags(), &id_to_feature_flags!(2));
1620 assert_eq!(route.hops[1].pubkey, node3);
1621 assert_eq!(route.hops[1].short_channel_id, 4);
1622 assert_eq!(route.hops[1].fee_msat, 100);
1623 assert_eq!(route.hops[1].cltv_expiry_delta, (3 << 8) | 2);
1624 assert_eq!(route.hops[1].node_features.le_flags(), &id_to_feature_flags!(3));
1625 assert_eq!(route.hops[1].channel_features.le_flags(), &id_to_feature_flags!(4));
1627 assert_eq!(route.hops[2].pubkey, node1);
1628 assert_eq!(route.hops[2].short_channel_id, 3);
1629 assert_eq!(route.hops[2].fee_msat, 100);
1630 assert_eq!(route.hops[2].cltv_expiry_delta, 42);
1631 assert_eq!(route.hops[2].node_features.le_flags(), &id_to_feature_flags!(1));
1632 assert_eq!(route.hops[2].channel_features.le_flags(), &id_to_feature_flags!(3));
1635 { // If we specify a channel to node8, that overrides our local channel view and that gets used
1636 let our_chans = vec![channelmanager::ChannelDetails {
1637 channel_id: [0; 32],
1638 short_channel_id: Some(42),
1639 remote_network_id: node8.clone(),
1640 counterparty_features: InitFeatures::from_le_bytes(vec![0b11]),
1641 channel_value_satoshis: 0,
1643 outbound_capacity_msat: 0,
1644 inbound_capacity_msat: 0,
1647 let route = router.get_route(&node3, Some(&our_chans), &Vec::new(), 100, 42).unwrap();
1648 assert_eq!(route.hops.len(), 2);
1650 assert_eq!(route.hops[0].pubkey, node8);
1651 assert_eq!(route.hops[0].short_channel_id, 42);
1652 assert_eq!(route.hops[0].fee_msat, 200);
1653 assert_eq!(route.hops[0].cltv_expiry_delta, (13 << 8) | 1);
1654 assert_eq!(route.hops[0].node_features.le_flags(), &vec![0b11]);
1655 assert_eq!(route.hops[0].channel_features.le_flags(), &Vec::new()); // No feature flags will meet the relevant-to-channel conversion
1657 assert_eq!(route.hops[1].pubkey, node3);
1658 assert_eq!(route.hops[1].short_channel_id, 13);
1659 assert_eq!(route.hops[1].fee_msat, 100);
1660 assert_eq!(route.hops[1].cltv_expiry_delta, 42);
1661 assert_eq!(route.hops[1].node_features.le_flags(), &id_to_feature_flags!(3));
1662 assert_eq!(route.hops[1].channel_features.le_flags(), &id_to_feature_flags!(13));
1665 let mut last_hops = vec!(RouteHint {
1666 src_node_id: node4.clone(),
1667 short_channel_id: 8,
1669 fee_proportional_millionths: 0,
1670 cltv_expiry_delta: (8 << 8) | 1,
1671 htlc_minimum_msat: 0,
1673 src_node_id: node5.clone(),
1674 short_channel_id: 9,
1675 fee_base_msat: 1001,
1676 fee_proportional_millionths: 0,
1677 cltv_expiry_delta: (9 << 8) | 1,
1678 htlc_minimum_msat: 0,
1680 src_node_id: node6.clone(),
1681 short_channel_id: 10,
1683 fee_proportional_millionths: 0,
1684 cltv_expiry_delta: (10 << 8) | 1,
1685 htlc_minimum_msat: 0,
1688 { // Simple test across 2, 3, 5, and 4 via a last_hop channel
1689 let route = router.get_route(&node7, None, &last_hops, 100, 42).unwrap();
1690 assert_eq!(route.hops.len(), 5);
1692 assert_eq!(route.hops[0].pubkey, node2);
1693 assert_eq!(route.hops[0].short_channel_id, 2);
1694 assert_eq!(route.hops[0].fee_msat, 100);
1695 assert_eq!(route.hops[0].cltv_expiry_delta, (4 << 8) | 1);
1696 assert_eq!(route.hops[0].node_features.le_flags(), &id_to_feature_flags!(2));
1697 assert_eq!(route.hops[0].channel_features.le_flags(), &id_to_feature_flags!(2));
1699 assert_eq!(route.hops[1].pubkey, node3);
1700 assert_eq!(route.hops[1].short_channel_id, 4);
1701 assert_eq!(route.hops[1].fee_msat, 0);
1702 assert_eq!(route.hops[1].cltv_expiry_delta, (6 << 8) | 1);
1703 assert_eq!(route.hops[1].node_features.le_flags(), &id_to_feature_flags!(3));
1704 assert_eq!(route.hops[1].channel_features.le_flags(), &id_to_feature_flags!(4));
1706 assert_eq!(route.hops[2].pubkey, node5);
1707 assert_eq!(route.hops[2].short_channel_id, 6);
1708 assert_eq!(route.hops[2].fee_msat, 0);
1709 assert_eq!(route.hops[2].cltv_expiry_delta, (11 << 8) | 1);
1710 assert_eq!(route.hops[2].node_features.le_flags(), &id_to_feature_flags!(5));
1711 assert_eq!(route.hops[2].channel_features.le_flags(), &id_to_feature_flags!(6));
1713 assert_eq!(route.hops[3].pubkey, node4);
1714 assert_eq!(route.hops[3].short_channel_id, 11);
1715 assert_eq!(route.hops[3].fee_msat, 0);
1716 assert_eq!(route.hops[3].cltv_expiry_delta, (8 << 8) | 1);
1717 // If we have a peer in the node map, we'll use their features here since we don't have
1718 // a way of figuring out their features from the invoice:
1719 assert_eq!(route.hops[3].node_features.le_flags(), &id_to_feature_flags!(4));
1720 assert_eq!(route.hops[3].channel_features.le_flags(), &id_to_feature_flags!(11));
1722 assert_eq!(route.hops[4].pubkey, node7);
1723 assert_eq!(route.hops[4].short_channel_id, 8);
1724 assert_eq!(route.hops[4].fee_msat, 100);
1725 assert_eq!(route.hops[4].cltv_expiry_delta, 42);
1726 assert_eq!(route.hops[4].node_features.le_flags(), &Vec::new()); // We dont pass flags in from invoices yet
1727 assert_eq!(route.hops[4].channel_features.le_flags(), &Vec::new()); // We can't learn any flags from invoices, sadly
1730 { // Simple test with outbound channel to 4 to test that last_hops and first_hops connect
1731 let our_chans = vec![channelmanager::ChannelDetails {
1732 channel_id: [0; 32],
1733 short_channel_id: Some(42),
1734 remote_network_id: node4.clone(),
1735 counterparty_features: InitFeatures::from_le_bytes(vec![0b11]),
1736 channel_value_satoshis: 0,
1738 outbound_capacity_msat: 0,
1739 inbound_capacity_msat: 0,
1742 let route = router.get_route(&node7, Some(&our_chans), &last_hops, 100, 42).unwrap();
1743 assert_eq!(route.hops.len(), 2);
1745 assert_eq!(route.hops[0].pubkey, node4);
1746 assert_eq!(route.hops[0].short_channel_id, 42);
1747 assert_eq!(route.hops[0].fee_msat, 0);
1748 assert_eq!(route.hops[0].cltv_expiry_delta, (8 << 8) | 1);
1749 assert_eq!(route.hops[0].node_features.le_flags(), &vec![0b11]);
1750 assert_eq!(route.hops[0].channel_features.le_flags(), &Vec::new()); // No feature flags will meet the relevant-to-channel conversion
1752 assert_eq!(route.hops[1].pubkey, node7);
1753 assert_eq!(route.hops[1].short_channel_id, 8);
1754 assert_eq!(route.hops[1].fee_msat, 100);
1755 assert_eq!(route.hops[1].cltv_expiry_delta, 42);
1756 assert_eq!(route.hops[1].node_features.le_flags(), &Vec::new()); // We dont pass flags in from invoices yet
1757 assert_eq!(route.hops[1].channel_features.le_flags(), &Vec::new()); // We can't learn any flags from invoices, sadly
1760 last_hops[0].fee_base_msat = 1000;
1762 { // Revert to via 6 as the fee on 8 goes up
1763 let route = router.get_route(&node7, None, &last_hops, 100, 42).unwrap();
1764 assert_eq!(route.hops.len(), 4);
1766 assert_eq!(route.hops[0].pubkey, node2);
1767 assert_eq!(route.hops[0].short_channel_id, 2);
1768 assert_eq!(route.hops[0].fee_msat, 200); // fee increased as its % of value transferred across node
1769 assert_eq!(route.hops[0].cltv_expiry_delta, (4 << 8) | 1);
1770 assert_eq!(route.hops[0].node_features.le_flags(), &id_to_feature_flags!(2));
1771 assert_eq!(route.hops[0].channel_features.le_flags(), &id_to_feature_flags!(2));
1773 assert_eq!(route.hops[1].pubkey, node3);
1774 assert_eq!(route.hops[1].short_channel_id, 4);
1775 assert_eq!(route.hops[1].fee_msat, 100);
1776 assert_eq!(route.hops[1].cltv_expiry_delta, (7 << 8) | 1);
1777 assert_eq!(route.hops[1].node_features.le_flags(), &id_to_feature_flags!(3));
1778 assert_eq!(route.hops[1].channel_features.le_flags(), &id_to_feature_flags!(4));
1780 assert_eq!(route.hops[2].pubkey, node6);
1781 assert_eq!(route.hops[2].short_channel_id, 7);
1782 assert_eq!(route.hops[2].fee_msat, 0);
1783 assert_eq!(route.hops[2].cltv_expiry_delta, (10 << 8) | 1);
1784 // If we have a peer in the node map, we'll use their features here since we don't have
1785 // a way of figuring out their features from the invoice:
1786 assert_eq!(route.hops[2].node_features.le_flags(), &id_to_feature_flags!(6));
1787 assert_eq!(route.hops[2].channel_features.le_flags(), &id_to_feature_flags!(7));
1789 assert_eq!(route.hops[3].pubkey, node7);
1790 assert_eq!(route.hops[3].short_channel_id, 10);
1791 assert_eq!(route.hops[3].fee_msat, 100);
1792 assert_eq!(route.hops[3].cltv_expiry_delta, 42);
1793 assert_eq!(route.hops[3].node_features.le_flags(), &Vec::new()); // We dont pass flags in from invoices yet
1794 assert_eq!(route.hops[3].channel_features.le_flags(), &Vec::new()); // We can't learn any flags from invoices, sadly
1797 { // ...but still use 8 for larger payments as 6 has a variable feerate
1798 let route = router.get_route(&node7, None, &last_hops, 2000, 42).unwrap();
1799 assert_eq!(route.hops.len(), 5);
1801 assert_eq!(route.hops[0].pubkey, node2);
1802 assert_eq!(route.hops[0].short_channel_id, 2);
1803 assert_eq!(route.hops[0].fee_msat, 3000);
1804 assert_eq!(route.hops[0].cltv_expiry_delta, (4 << 8) | 1);
1805 assert_eq!(route.hops[0].node_features.le_flags(), &id_to_feature_flags!(2));
1806 assert_eq!(route.hops[0].channel_features.le_flags(), &id_to_feature_flags!(2));
1808 assert_eq!(route.hops[1].pubkey, node3);
1809 assert_eq!(route.hops[1].short_channel_id, 4);
1810 assert_eq!(route.hops[1].fee_msat, 0);
1811 assert_eq!(route.hops[1].cltv_expiry_delta, (6 << 8) | 1);
1812 assert_eq!(route.hops[1].node_features.le_flags(), &id_to_feature_flags!(3));
1813 assert_eq!(route.hops[1].channel_features.le_flags(), &id_to_feature_flags!(4));
1815 assert_eq!(route.hops[2].pubkey, node5);
1816 assert_eq!(route.hops[2].short_channel_id, 6);
1817 assert_eq!(route.hops[2].fee_msat, 0);
1818 assert_eq!(route.hops[2].cltv_expiry_delta, (11 << 8) | 1);
1819 assert_eq!(route.hops[2].node_features.le_flags(), &id_to_feature_flags!(5));
1820 assert_eq!(route.hops[2].channel_features.le_flags(), &id_to_feature_flags!(6));
1822 assert_eq!(route.hops[3].pubkey, node4);
1823 assert_eq!(route.hops[3].short_channel_id, 11);
1824 assert_eq!(route.hops[3].fee_msat, 1000);
1825 assert_eq!(route.hops[3].cltv_expiry_delta, (8 << 8) | 1);
1826 // If we have a peer in the node map, we'll use their features here since we don't have
1827 // a way of figuring out their features from the invoice:
1828 assert_eq!(route.hops[3].node_features.le_flags(), &id_to_feature_flags!(4));
1829 assert_eq!(route.hops[3].channel_features.le_flags(), &id_to_feature_flags!(11));
1831 assert_eq!(route.hops[4].pubkey, node7);
1832 assert_eq!(route.hops[4].short_channel_id, 8);
1833 assert_eq!(route.hops[4].fee_msat, 2000);
1834 assert_eq!(route.hops[4].cltv_expiry_delta, 42);
1835 assert_eq!(route.hops[4].node_features.le_flags(), &Vec::new()); // We dont pass flags in from invoices yet
1836 assert_eq!(route.hops[4].channel_features.le_flags(), &Vec::new()); // We can't learn any flags from invoices, sadly
1839 { // Test Router serialization/deserialization
1840 let mut w = TestVecWriter(Vec::new());
1841 let network = router.network_map.read().unwrap();
1842 assert!(!network.channels.is_empty());
1843 assert!(!network.nodes.is_empty());
1844 network.write(&mut w).unwrap();
1845 assert!(<NetworkMap>::read(&mut ::std::io::Cursor::new(&w.0)).unwrap() == *network);
1850 fn request_full_sync_finite_times() {
1851 let (secp_ctx, _, router) = create_router();
1852 let node_id = PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&hex::decode("0202020202020202020202020202020202020202020202020202020202020202").unwrap()[..]).unwrap());
1854 assert!(router.should_request_full_sync(&node_id));
1855 assert!(router.should_request_full_sync(&node_id));
1856 assert!(router.should_request_full_sync(&node_id));
1857 assert!(router.should_request_full_sync(&node_id));
1858 assert!(router.should_request_full_sync(&node_id));
1859 assert!(!router.should_request_full_sync(&node_id));