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 bitcoin::secp256k1::key::PublicKey;
7 use bitcoin::secp256k1::Secp256k1;
8 use bitcoin::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 impl Writeable for Vec<RouteHop> {
51 fn write<W: ::util::ser::Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
52 (self.len() as u8).write(writer)?;
53 for hop in self.iter() {
54 hop.pubkey.write(writer)?;
55 hop.node_features.write(writer)?;
56 hop.short_channel_id.write(writer)?;
57 hop.channel_features.write(writer)?;
58 hop.fee_msat.write(writer)?;
59 hop.cltv_expiry_delta.write(writer)?;
65 impl Readable for Vec<RouteHop> {
66 fn read<R: ::std::io::Read>(reader: &mut R) -> Result<Vec<RouteHop>, DecodeError> {
67 let hops_count: u8 = Readable::read(reader)?;
68 let mut hops = Vec::with_capacity(hops_count as usize);
69 for _ in 0..hops_count {
71 pubkey: Readable::read(reader)?,
72 node_features: Readable::read(reader)?,
73 short_channel_id: Readable::read(reader)?,
74 channel_features: Readable::read(reader)?,
75 fee_msat: Readable::read(reader)?,
76 cltv_expiry_delta: Readable::read(reader)?,
83 /// A route directs a payment from the sender (us) to the recipient. If the recipient supports MPP,
84 /// it can take multiple paths. Each path is composed of one or more hops through the network.
85 #[derive(Clone, PartialEq)]
87 /// The list of routes taken for a single (potentially-)multi-part payment. The pubkey of the
88 /// last RouteHop in each path must be the same.
89 /// Each entry represents a list of hops, NOT INCLUDING our own, where the last hop is the
90 /// destination. Thus, this must always be at least length one. While the maximum length of any
91 /// given path is variable, keeping the length of any path to less than 20 should currently
92 /// ensure it is viable.
93 pub paths: Vec<Vec<RouteHop>>,
96 impl Writeable for Route {
97 fn write<W: ::util::ser::Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
98 (self.paths.len() as u64).write(writer)?;
99 for hops in self.paths.iter() {
106 impl Readable for Route {
107 fn read<R: ::std::io::Read>(reader: &mut R) -> Result<Route, DecodeError> {
108 let path_count: u64 = Readable::read(reader)?;
109 let mut paths = Vec::with_capacity(cmp::min(path_count, 128) as usize);
110 for _ in 0..path_count {
111 paths.push(Readable::read(reader)?);
118 struct DirectionalChannelInfo {
119 src_node_id: PublicKey,
122 cltv_expiry_delta: u16,
123 htlc_minimum_msat: u64,
125 fee_proportional_millionths: u32,
126 last_update_message: Option<msgs::ChannelUpdate>,
129 impl std::fmt::Display for DirectionalChannelInfo {
130 fn fmt(&self, f: &mut std::fmt::Formatter) -> Result<(), std::fmt::Error> {
131 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)?;
136 impl_writeable!(DirectionalChannelInfo, 0, {
143 fee_proportional_millionths,
149 features: ChannelFeatures,
150 one_to_two: DirectionalChannelInfo,
151 two_to_one: DirectionalChannelInfo,
152 //this is cached here so we can send out it later if required by route_init_sync
153 //keep an eye on this to see if the extra memory is a problem
154 announcement_message: Option<msgs::ChannelAnnouncement>,
157 impl std::fmt::Display for ChannelInfo {
158 fn fmt(&self, f: &mut std::fmt::Formatter) -> Result<(), std::fmt::Error> {
159 write!(f, "features: {}, one_to_two: {}, two_to_one: {}", log_bytes!(self.features.encode()), self.one_to_two, self.two_to_one)?;
164 impl_writeable!(ChannelInfo, 0, {
175 lowest_inbound_channel_fee_base_msat: u32,
176 lowest_inbound_channel_fee_proportional_millionths: u32,
178 features: NodeFeatures,
179 /// Unlike for channels, we may have a NodeInfo entry before having received a node_update.
180 /// Thus, we have to be able to capture "no update has been received", which we do with an
182 last_update: Option<u32>,
185 addresses: Vec<NetAddress>,
186 //this is cached here so we can send out it later if required by route_init_sync
187 //keep an eye on this to see if the extra memory is a problem
188 announcement_message: Option<msgs::NodeAnnouncement>,
191 impl std::fmt::Display for NodeInfo {
192 fn fmt(&self, f: &mut std::fmt::Formatter) -> Result<(), std::fmt::Error> {
193 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[..])?;
198 impl Writeable for NodeInfo {
199 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
200 (self.channels.len() as u64).write(writer)?;
201 for ref chan in self.channels.iter() {
204 self.lowest_inbound_channel_fee_base_msat.write(writer)?;
205 self.lowest_inbound_channel_fee_proportional_millionths.write(writer)?;
206 self.features.write(writer)?;
207 self.last_update.write(writer)?;
208 self.rgb.write(writer)?;
209 self.alias.write(writer)?;
210 (self.addresses.len() as u64).write(writer)?;
211 for ref addr in &self.addresses {
214 self.announcement_message.write(writer)?;
219 const MAX_ALLOC_SIZE: u64 = 64*1024;
221 impl Readable for NodeInfo {
222 fn read<R: ::std::io::Read>(reader: &mut R) -> Result<NodeInfo, DecodeError> {
223 let channels_count: u64 = Readable::read(reader)?;
224 let mut channels = Vec::with_capacity(cmp::min(channels_count, MAX_ALLOC_SIZE / 8) as usize);
225 for _ in 0..channels_count {
226 channels.push(Readable::read(reader)?);
228 let lowest_inbound_channel_fee_base_msat = Readable::read(reader)?;
229 let lowest_inbound_channel_fee_proportional_millionths = Readable::read(reader)?;
230 let features = Readable::read(reader)?;
231 let last_update = Readable::read(reader)?;
232 let rgb = Readable::read(reader)?;
233 let alias = Readable::read(reader)?;
234 let addresses_count: u64 = Readable::read(reader)?;
235 let mut addresses = Vec::with_capacity(cmp::min(addresses_count, MAX_ALLOC_SIZE / 40) as usize);
236 for _ in 0..addresses_count {
237 match Readable::read(reader) {
238 Ok(Ok(addr)) => { addresses.push(addr); },
239 Ok(Err(_)) => return Err(DecodeError::InvalidValue),
240 Err(DecodeError::ShortRead) => return Err(DecodeError::BadLengthDescriptor),
244 let announcement_message = Readable::read(reader)?;
247 lowest_inbound_channel_fee_base_msat,
248 lowest_inbound_channel_fee_proportional_millionths,
261 channels: BTreeMap<u64, ChannelInfo>,
262 our_node_id: PublicKey,
263 nodes: BTreeMap<PublicKey, NodeInfo>,
266 impl Writeable for NetworkMap {
267 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
268 (self.channels.len() as u64).write(writer)?;
269 for (ref chan_id, ref chan_info) in self.channels.iter() {
270 (*chan_id).write(writer)?;
271 chan_info.write(writer)?;
273 self.our_node_id.write(writer)?;
274 (self.nodes.len() as u64).write(writer)?;
275 for (ref node_id, ref node_info) in self.nodes.iter() {
276 node_id.write(writer)?;
277 node_info.write(writer)?;
283 impl Readable for NetworkMap {
284 fn read<R: ::std::io::Read>(reader: &mut R) -> Result<NetworkMap, DecodeError> {
285 let channels_count: u64 = Readable::read(reader)?;
286 let mut channels = BTreeMap::new();
287 for _ in 0..channels_count {
288 let chan_id: u64 = Readable::read(reader)?;
289 let chan_info = Readable::read(reader)?;
290 channels.insert(chan_id, chan_info);
292 let our_node_id = Readable::read(reader)?;
293 let nodes_count: u64 = Readable::read(reader)?;
294 let mut nodes = BTreeMap::new();
295 for _ in 0..nodes_count {
296 let node_id = Readable::read(reader)?;
297 let node_info = Readable::read(reader)?;
298 nodes.insert(node_id, node_info);
308 impl std::fmt::Display for NetworkMap {
309 fn fmt(&self, f: &mut std::fmt::Formatter) -> Result<(), std::fmt::Error> {
310 write!(f, "Node id {} network map\n[Channels]\n", log_pubkey!(self.our_node_id))?;
311 for (key, val) in self.channels.iter() {
312 write!(f, " {}: {}\n", key, val)?;
314 write!(f, "[Nodes]\n")?;
315 for (key, val) in self.nodes.iter() {
316 write!(f, " {}: {}\n", log_pubkey!(key), val)?;
322 /// A channel descriptor which provides a last-hop route to get_route
323 pub struct RouteHint {
324 /// The node_id of the non-target end of the route
325 pub src_node_id: PublicKey,
326 /// The short_channel_id of this channel
327 pub short_channel_id: u64,
328 /// The static msat-denominated fee which must be paid to use this channel
329 pub fee_base_msat: u32,
330 /// The dynamic proportional fee which must be paid to use this channel, denominated in
331 /// millionths of the value being forwarded to the next hop.
332 pub fee_proportional_millionths: u32,
333 /// The difference in CLTV values between this node and the next node.
334 pub cltv_expiry_delta: u16,
335 /// The minimum value, in msat, which must be relayed to the next hop.
336 pub htlc_minimum_msat: u64,
339 /// Tracks a view of the network, receiving updates from peers and generating Routes to
340 /// payment destinations.
342 secp_ctx: Secp256k1<secp256k1::VerifyOnly>,
343 network_map: RwLock<NetworkMap>,
344 full_syncs_requested: AtomicUsize,
345 chain_monitor: Arc<ChainWatchInterface>,
349 const SERIALIZATION_VERSION: u8 = 1;
350 const MIN_SERIALIZATION_VERSION: u8 = 1;
352 impl Writeable for Router {
353 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
354 writer.write_all(&[SERIALIZATION_VERSION; 1])?;
355 writer.write_all(&[MIN_SERIALIZATION_VERSION; 1])?;
357 let network = self.network_map.read().unwrap();
358 network.write(writer)?;
363 /// Arguments for the creation of a Router that are not deserialized.
364 /// At a high-level, the process for deserializing a Router and resuming normal operation is:
365 /// 1) Deserialize the Router by filling in this struct and calling <Router>::read(reaser, args).
366 /// 2) Register the new Router with your ChainWatchInterface
367 pub struct RouterReadArgs {
368 /// The ChainWatchInterface for use in the Router in the future.
370 /// No calls to the ChainWatchInterface will be made during deserialization.
371 pub chain_monitor: Arc<ChainWatchInterface>,
372 /// The Logger for use in the ChannelManager and which may be used to log information during
374 pub logger: Arc<Logger>,
377 impl ReadableArgs<RouterReadArgs> for Router {
378 fn read<R: ::std::io::Read>(reader: &mut R, args: RouterReadArgs) -> Result<Router, DecodeError> {
379 let _ver: u8 = Readable::read(reader)?;
380 let min_ver: u8 = Readable::read(reader)?;
381 if min_ver > SERIALIZATION_VERSION {
382 return Err(DecodeError::UnknownVersion);
384 let network_map = Readable::read(reader)?;
386 secp_ctx: Secp256k1::verification_only(),
387 network_map: RwLock::new(network_map),
388 full_syncs_requested: AtomicUsize::new(0),
389 chain_monitor: args.chain_monitor,
395 macro_rules! secp_verify_sig {
396 ( $secp_ctx: expr, $msg: expr, $sig: expr, $pubkey: expr ) => {
397 match $secp_ctx.verify($msg, $sig, $pubkey) {
399 Err(_) => return Err(LightningError{err: "Invalid signature from remote node", action: ErrorAction::IgnoreError}),
404 impl RoutingMessageHandler for Router {
406 fn handle_node_announcement(&self, msg: &msgs::NodeAnnouncement) -> Result<bool, LightningError> {
407 let msg_hash = hash_to_message!(&Sha256dHash::hash(&msg.contents.encode()[..])[..]);
408 secp_verify_sig!(self.secp_ctx, &msg_hash, &msg.signature, &msg.contents.node_id);
410 let mut network = self.network_map.write().unwrap();
411 match network.nodes.get_mut(&msg.contents.node_id) {
412 None => Err(LightningError{err: "No existing channels for node_announcement", action: ErrorAction::IgnoreError}),
414 match node.last_update {
415 Some(last_update) => if last_update >= msg.contents.timestamp {
416 return Err(LightningError{err: "Update older than last processed update", action: ErrorAction::IgnoreError});
421 node.features = msg.contents.features.clone();
422 node.last_update = Some(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(msg.contents.short_channel_id) {
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(msg.contents.short_channel_id);
532 BtreeEntry::Vacant(node_entry) => {
533 node_entry.insert(NodeInfo {
534 channels: vec!(msg.contents.short_channel_id),
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);
552 log_trace!(self, "Added channel_announcement for {}{}", msg.contents.short_channel_id, if !should_relay { " with excess uninterpreted data!" } else { "" });
556 fn handle_htlc_fail_channel_update(&self, update: &msgs::HTLCFailChannelUpdate) {
558 &msgs::HTLCFailChannelUpdate::ChannelUpdateMessage { ref msg } => {
559 let _ = self.handle_channel_update(msg);
561 &msgs::HTLCFailChannelUpdate::ChannelClosed { ref short_channel_id, ref is_permanent } => {
562 let mut network = self.network_map.write().unwrap();
564 if let Some(chan) = network.channels.remove(short_channel_id) {
565 Self::remove_channel_in_nodes(&mut network.nodes, &chan, *short_channel_id);
568 if let Some(chan) = network.channels.get_mut(short_channel_id) {
569 chan.one_to_two.enabled = false;
570 chan.two_to_one.enabled = false;
574 &msgs::HTLCFailChannelUpdate::NodeFailure { ref node_id, ref is_permanent } => {
576 //TODO: Wholly remove the node
578 self.mark_node_bad(node_id, false);
584 fn handle_channel_update(&self, msg: &msgs::ChannelUpdate) -> Result<bool, LightningError> {
585 let mut network = self.network_map.write().unwrap();
587 let chan_enabled = msg.contents.flags & (1 << 1) != (1 << 1);
588 let chan_was_enabled;
590 match network.channels.get_mut(&msg.contents.short_channel_id) {
591 None => return Err(LightningError{err: "Couldn't find channel for update", action: ErrorAction::IgnoreError}),
593 macro_rules! maybe_update_channel_info {
594 ( $target: expr) => {
595 if $target.last_update >= msg.contents.timestamp {
596 return Err(LightningError{err: "Update older than last processed update", action: ErrorAction::IgnoreError});
598 chan_was_enabled = $target.enabled;
599 $target.last_update = msg.contents.timestamp;
600 $target.enabled = chan_enabled;
601 $target.cltv_expiry_delta = msg.contents.cltv_expiry_delta;
602 $target.htlc_minimum_msat = msg.contents.htlc_minimum_msat;
603 $target.fee_base_msat = msg.contents.fee_base_msat;
604 $target.fee_proportional_millionths = msg.contents.fee_proportional_millionths;
605 $target.last_update_message = if msg.contents.excess_data.is_empty() {
612 let msg_hash = hash_to_message!(&Sha256dHash::hash(&msg.contents.encode()[..])[..]);
613 if msg.contents.flags & 1 == 1 {
614 dest_node_id = channel.one_to_two.src_node_id.clone();
615 secp_verify_sig!(self.secp_ctx, &msg_hash, &msg.signature, &channel.two_to_one.src_node_id);
616 maybe_update_channel_info!(channel.two_to_one);
618 dest_node_id = channel.two_to_one.src_node_id.clone();
619 secp_verify_sig!(self.secp_ctx, &msg_hash, &msg.signature, &channel.one_to_two.src_node_id);
620 maybe_update_channel_info!(channel.one_to_two);
626 let node = network.nodes.get_mut(&dest_node_id).unwrap();
627 node.lowest_inbound_channel_fee_base_msat = cmp::min(node.lowest_inbound_channel_fee_base_msat, msg.contents.fee_base_msat);
628 node.lowest_inbound_channel_fee_proportional_millionths = cmp::min(node.lowest_inbound_channel_fee_proportional_millionths, msg.contents.fee_proportional_millionths);
629 } else if chan_was_enabled {
630 let mut lowest_inbound_channel_fee_base_msat = u32::max_value();
631 let mut lowest_inbound_channel_fee_proportional_millionths = u32::max_value();
634 let node = network.nodes.get(&dest_node_id).unwrap();
636 for chan_id in node.channels.iter() {
637 let chan = network.channels.get(chan_id).unwrap();
638 if chan.one_to_two.src_node_id == dest_node_id {
639 lowest_inbound_channel_fee_base_msat = cmp::min(lowest_inbound_channel_fee_base_msat, chan.two_to_one.fee_base_msat);
640 lowest_inbound_channel_fee_proportional_millionths = cmp::min(lowest_inbound_channel_fee_proportional_millionths, chan.two_to_one.fee_proportional_millionths);
642 lowest_inbound_channel_fee_base_msat = cmp::min(lowest_inbound_channel_fee_base_msat, chan.one_to_two.fee_base_msat);
643 lowest_inbound_channel_fee_proportional_millionths = cmp::min(lowest_inbound_channel_fee_proportional_millionths, chan.one_to_two.fee_proportional_millionths);
648 //TODO: satisfy the borrow-checker without a double-map-lookup :(
649 let mut_node = network.nodes.get_mut(&dest_node_id).unwrap();
650 mut_node.lowest_inbound_channel_fee_base_msat = lowest_inbound_channel_fee_base_msat;
651 mut_node.lowest_inbound_channel_fee_proportional_millionths = lowest_inbound_channel_fee_proportional_millionths;
654 Ok(msg.contents.excess_data.is_empty())
657 fn get_next_channel_announcements(&self, starting_point: u64, batch_amount: u8) -> Vec<(msgs::ChannelAnnouncement, Option<msgs::ChannelUpdate>, Option<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 result.push((chan.announcement_message.clone().unwrap(),
665 chan.one_to_two.last_update_message.clone(),
666 chan.two_to_one.last_update_message.clone()));
668 // TODO: We may end up sending un-announced channel_updates if we are sending
669 // initial sync data while receiving announce/updates for this channel.
678 fn get_next_node_announcements(&self, starting_point: Option<&PublicKey>, batch_amount: u8) -> Vec<msgs::NodeAnnouncement> {
679 let mut result = Vec::with_capacity(batch_amount as usize);
680 let network = self.network_map.read().unwrap();
681 let mut iter = if let Some(pubkey) = starting_point {
682 let mut iter = network.nodes.range((*pubkey)..);
686 network.nodes.range(..)
688 while result.len() < batch_amount as usize {
689 if let Some((_, ref node)) = iter.next() {
690 if node.announcement_message.is_some() {
691 result.push(node.announcement_message.clone().unwrap());
700 fn should_request_full_sync(&self, _node_id: &PublicKey) -> bool {
701 //TODO: Determine whether to request a full sync based on the network map.
702 const FULL_SYNCS_TO_REQUEST: usize = 5;
703 if self.full_syncs_requested.load(Ordering::Acquire) < FULL_SYNCS_TO_REQUEST {
704 self.full_syncs_requested.fetch_add(1, Ordering::AcqRel);
712 #[derive(Eq, PartialEq)]
713 struct RouteGraphNode {
715 lowest_fee_to_peer_through_node: u64,
716 lowest_fee_to_node: u64,
719 impl cmp::Ord for RouteGraphNode {
720 fn cmp(&self, other: &RouteGraphNode) -> cmp::Ordering {
721 other.lowest_fee_to_peer_through_node.cmp(&self.lowest_fee_to_peer_through_node)
722 .then_with(|| other.pubkey.serialize().cmp(&self.pubkey.serialize()))
726 impl cmp::PartialOrd for RouteGraphNode {
727 fn partial_cmp(&self, other: &RouteGraphNode) -> Option<cmp::Ordering> {
728 Some(self.cmp(other))
732 struct DummyDirectionalChannelInfo {
733 src_node_id: PublicKey,
734 cltv_expiry_delta: u32,
735 htlc_minimum_msat: u64,
737 fee_proportional_millionths: u32,
741 /// Creates a new router with the given node_id to be used as the source for get_route()
742 pub fn new(our_pubkey: PublicKey, chain_monitor: Arc<ChainWatchInterface>, logger: Arc<Logger>) -> Router {
743 let mut nodes = BTreeMap::new();
744 nodes.insert(our_pubkey.clone(), NodeInfo {
745 channels: Vec::new(),
746 lowest_inbound_channel_fee_base_msat: u32::max_value(),
747 lowest_inbound_channel_fee_proportional_millionths: u32::max_value(),
748 features: NodeFeatures::empty(),
752 addresses: Vec::new(),
753 announcement_message: None,
756 secp_ctx: Secp256k1::verification_only(),
757 network_map: RwLock::new(NetworkMap {
758 channels: BTreeMap::new(),
759 our_node_id: our_pubkey,
762 full_syncs_requested: AtomicUsize::new(0),
768 /// Dumps the entire network view of this Router to the logger provided in the constructor at
770 pub fn trace_state(&self) {
771 log_trace!(self, "{}", self.network_map.read().unwrap());
774 /// Get network addresses by node id
775 pub fn get_addresses(&self, pubkey: &PublicKey) -> Option<Vec<NetAddress>> {
776 let network = self.network_map.read().unwrap();
777 network.nodes.get(pubkey).map(|n| n.addresses.clone())
780 /// Marks a node as having failed a route. This will avoid re-using the node in routes for now,
781 /// with an exponential decay in node "badness". Note that there is deliberately no
782 /// mark_channel_bad as a node may simply lie and suggest that an upstream channel from it is
783 /// what failed the route and not the node itself. Instead, setting the blamed_upstream_node
784 /// boolean will reduce the penalty, returning the node to usability faster. If the node is
785 /// behaving correctly, it will disable the failing channel and we will use it again next time.
786 pub fn mark_node_bad(&self, _node_id: &PublicKey, _blamed_upstream_node: bool) {
790 fn remove_channel_in_nodes(nodes: &mut BTreeMap<PublicKey, NodeInfo>, chan: &ChannelInfo, short_channel_id: u64) {
791 macro_rules! remove_from_node {
792 ($node_id: expr) => {
793 if let BtreeEntry::Occupied(mut entry) = nodes.entry($node_id) {
794 entry.get_mut().channels.retain(|chan_id| {
795 short_channel_id != *chan_id
797 if entry.get().channels.is_empty() {
798 entry.remove_entry();
801 panic!("Had channel that pointed to unknown node (ie inconsistent network map)!");
805 remove_from_node!(chan.one_to_two.src_node_id);
806 remove_from_node!(chan.two_to_one.src_node_id);
809 /// Gets a route from us to the given target node.
811 /// Extra routing hops between known nodes and the target will be used if they are included in
814 /// If some channels aren't announced, it may be useful to fill in a first_hops with the
815 /// results from a local ChannelManager::list_usable_channels() call. If it is filled in, our
816 /// (this Router's) view of our local channels will be ignored, and only those in first_hops
819 /// Panics if first_hops contains channels without short_channel_ids
820 /// (ChannelManager::list_usable_channels will never include such channels).
822 /// The fees on channels from us to next-hops are ignored (as they are assumed to all be
823 /// equal), however the enabled/disabled bit on such channels as well as the htlc_minimum_msat
824 /// *is* checked as they may change based on the receiving node.
825 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> {
826 // TODO: Obviously *only* using total fee cost sucks. We should consider weighting by
827 // uptime/success in using a node in the past.
828 let network = self.network_map.read().unwrap();
830 if *target == network.our_node_id {
831 return Err(LightningError{err: "Cannot generate a route to ourselves", action: ErrorAction::IgnoreError});
834 if final_value_msat > 21_000_000 * 1_0000_0000 * 1000 {
835 return Err(LightningError{err: "Cannot generate a route of more value than all existing satoshis", action: ErrorAction::IgnoreError});
838 // We do a dest-to-source Dijkstra's sorting by each node's distance from the destination
839 // plus the minimum per-HTLC fee to get from it to another node (aka "shitty A*").
840 // TODO: There are a few tweaks we could do, including possibly pre-calculating more stuff
841 // to use as the A* heuristic beyond just the cost to get one node further than the current
844 let dummy_directional_info = DummyDirectionalChannelInfo { // used for first_hops routes
845 src_node_id: network.our_node_id.clone(),
846 cltv_expiry_delta: 0,
847 htlc_minimum_msat: 0,
849 fee_proportional_millionths: 0,
852 let mut targets = BinaryHeap::new(); //TODO: Do we care about switching to eg Fibbonaci heap?
853 let mut dist = HashMap::with_capacity(network.nodes.len());
855 let mut first_hop_targets = HashMap::with_capacity(if first_hops.is_some() { first_hops.as_ref().unwrap().len() } else { 0 });
856 if let Some(hops) = first_hops {
858 let short_channel_id = chan.short_channel_id.expect("first_hops should be filled in with usable channels, not pending ones");
859 if chan.remote_network_id == *target {
861 paths: vec![vec![RouteHop {
862 pubkey: chan.remote_network_id,
863 node_features: chan.counterparty_features.to_context(),
865 channel_features: chan.counterparty_features.to_context(),
866 fee_msat: final_value_msat,
867 cltv_expiry_delta: final_cltv,
871 first_hop_targets.insert(chan.remote_network_id, (short_channel_id, chan.counterparty_features.clone()));
873 if first_hop_targets.is_empty() {
874 return Err(LightningError{err: "Cannot route when there are no outbound routes away from us", action: ErrorAction::IgnoreError});
878 macro_rules! add_entry {
879 // Adds entry which goes from the node pointed to by $directional_info to
880 // $dest_node_id over the channel with id $chan_id with fees described in
881 // $directional_info.
882 ( $chan_id: expr, $dest_node_id: expr, $directional_info: expr, $chan_features: expr, $starting_fee_msat: expr ) => {
883 //TODO: Explore simply adding fee to hit htlc_minimum_msat
884 if $starting_fee_msat as u64 + final_value_msat >= $directional_info.htlc_minimum_msat {
885 let proportional_fee_millions = ($starting_fee_msat + final_value_msat).checked_mul($directional_info.fee_proportional_millionths as u64);
886 if let Some(new_fee) = proportional_fee_millions.and_then(|part| {
887 ($directional_info.fee_base_msat as u64).checked_add(part / 1000000) })
889 let mut total_fee = $starting_fee_msat as u64;
890 let hm_entry = dist.entry(&$directional_info.src_node_id);
891 let old_entry = hm_entry.or_insert_with(|| {
892 let node = network.nodes.get(&$directional_info.src_node_id).unwrap();
894 node.lowest_inbound_channel_fee_base_msat,
895 node.lowest_inbound_channel_fee_proportional_millionths,
897 pubkey: $dest_node_id.clone(),
898 node_features: NodeFeatures::empty(),
900 channel_features: $chan_features.clone(),
902 cltv_expiry_delta: 0,
905 if $directional_info.src_node_id != network.our_node_id {
906 // Ignore new_fee for channel-from-us as we assume all channels-from-us
907 // will have the same effective-fee
908 total_fee += new_fee;
909 if let Some(fee_inc) = final_value_msat.checked_add(total_fee).and_then(|inc| { (old_entry.2 as u64).checked_mul(inc) }) {
910 total_fee += fee_inc / 1000000 + (old_entry.1 as u64);
912 // max_value means we'll always fail the old_entry.0 > total_fee check
913 total_fee = u64::max_value();
916 let new_graph_node = RouteGraphNode {
917 pubkey: $directional_info.src_node_id,
918 lowest_fee_to_peer_through_node: total_fee,
919 lowest_fee_to_node: $starting_fee_msat as u64 + new_fee,
921 if old_entry.0 > total_fee {
922 targets.push(new_graph_node);
923 old_entry.0 = total_fee;
924 old_entry.3 = RouteHop {
925 pubkey: $dest_node_id.clone(),
926 node_features: NodeFeatures::empty(),
927 short_channel_id: $chan_id.clone(),
928 channel_features: $chan_features.clone(),
929 fee_msat: new_fee, // This field is ignored on the last-hop anyway
930 cltv_expiry_delta: $directional_info.cltv_expiry_delta as u32,
938 macro_rules! add_entries_to_cheapest_to_target_node {
939 ( $node: expr, $node_id: expr, $fee_to_target_msat: expr ) => {
940 if first_hops.is_some() {
941 if let Some(&(ref first_hop, ref features)) = first_hop_targets.get(&$node_id) {
942 add_entry!(first_hop, $node_id, dummy_directional_info, features.to_context(), $fee_to_target_msat);
946 if !$node.features.requires_unknown_bits() {
947 for chan_id in $node.channels.iter() {
948 let chan = network.channels.get(chan_id).unwrap();
949 if !chan.features.requires_unknown_bits() {
950 if chan.one_to_two.src_node_id == *$node_id {
951 // ie $node is one, ie next hop in A* is two, via the two_to_one channel
952 if first_hops.is_none() || chan.two_to_one.src_node_id != network.our_node_id {
953 if chan.two_to_one.enabled {
954 add_entry!(chan_id, chan.one_to_two.src_node_id, chan.two_to_one, chan.features, $fee_to_target_msat);
958 if first_hops.is_none() || chan.one_to_two.src_node_id != network.our_node_id {
959 if chan.one_to_two.enabled {
960 add_entry!(chan_id, chan.two_to_one.src_node_id, chan.one_to_two, chan.features, $fee_to_target_msat);
970 match network.nodes.get(target) {
973 add_entries_to_cheapest_to_target_node!(node, target, 0);
977 for hop in last_hops.iter() {
978 if first_hops.is_none() || hop.src_node_id != network.our_node_id { // first_hop overrules last_hops
979 if network.nodes.get(&hop.src_node_id).is_some() {
980 if first_hops.is_some() {
981 if let Some(&(ref first_hop, ref features)) = first_hop_targets.get(&hop.src_node_id) {
982 // Currently there are no channel-context features defined, so we are a
983 // bit lazy here. In the future, we should pull them out via our
984 // ChannelManager, but there's no reason to waste the space until we
986 add_entry!(first_hop, hop.src_node_id, dummy_directional_info, features.to_context(), 0);
989 // BOLT 11 doesn't allow inclusion of features for the last hop hints, which
990 // really sucks, cause we're gonna need that eventually.
991 add_entry!(hop.short_channel_id, target, hop, ChannelFeatures::empty(), 0);
996 while let Some(RouteGraphNode { pubkey, lowest_fee_to_node, .. }) = targets.pop() {
997 if pubkey == network.our_node_id {
998 let mut res = vec!(dist.remove(&network.our_node_id).unwrap().3);
1000 if let Some(&(_, ref features)) = first_hop_targets.get(&res.last().unwrap().pubkey) {
1001 res.last_mut().unwrap().node_features = features.to_context();
1002 } else if let Some(node) = network.nodes.get(&res.last().unwrap().pubkey) {
1003 res.last_mut().unwrap().node_features = node.features.clone();
1005 // We should be able to fill in features for everything except the last
1006 // hop, if the last hop was provided via a BOLT 11 invoice (though we
1007 // should be able to extend it further as BOLT 11 does have feature
1008 // flags for the last hop node itself).
1009 assert!(res.last().unwrap().pubkey == *target);
1011 if res.last().unwrap().pubkey == *target {
1015 let new_entry = match dist.remove(&res.last().unwrap().pubkey) {
1017 None => return Err(LightningError{err: "Failed to find a non-fee-overflowing path to the given destination", action: ErrorAction::IgnoreError}),
1019 res.last_mut().unwrap().fee_msat = new_entry.fee_msat;
1020 res.last_mut().unwrap().cltv_expiry_delta = new_entry.cltv_expiry_delta;
1021 res.push(new_entry);
1023 res.last_mut().unwrap().fee_msat = final_value_msat;
1024 res.last_mut().unwrap().cltv_expiry_delta = final_cltv;
1025 let route = Route { paths: vec![res] };
1026 log_trace!(self, "Got route: {}", log_route!(route));
1030 match network.nodes.get(&pubkey) {
1033 add_entries_to_cheapest_to_target_node!(node, &pubkey, lowest_fee_to_node);
1038 Err(LightningError{err: "Failed to find a path to the given destination", action: ErrorAction::IgnoreError})
1044 use chain::chaininterface;
1045 use ln::channelmanager;
1046 use routing::router::{Router,NodeInfo,NetworkMap,ChannelInfo,DirectionalChannelInfo,RouteHint};
1047 use ln::features::{ChannelFeatures, InitFeatures, NodeFeatures};
1048 use ln::msgs::{ErrorAction, LightningError, RoutingMessageHandler, UnsignedNodeAnnouncement, NodeAnnouncement,
1049 UnsignedChannelAnnouncement, ChannelAnnouncement, UnsignedChannelUpdate, ChannelUpdate, HTLCFailChannelUpdate};
1050 use util::test_utils;
1051 use util::test_utils::TestVecWriter;
1052 use util::logger::Logger;
1053 use util::ser::{Writeable, Readable};
1055 use bitcoin::hashes::sha256d::Hash as Sha256dHash;
1056 use bitcoin::hashes::Hash;
1057 use bitcoin::network::constants::Network;
1058 use bitcoin::blockdata::constants::genesis_block;
1059 use bitcoin::blockdata::script::Builder;
1060 use bitcoin::blockdata::opcodes;
1061 use bitcoin::util::hash::BitcoinHash;
1065 use bitcoin::secp256k1::key::{PublicKey,SecretKey};
1066 use bitcoin::secp256k1::All;
1067 use bitcoin::secp256k1::Secp256k1;
1070 use std::collections::btree_map::Entry as BtreeEntry;
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 macro_rules! id_to_feature_flags {
1152 // Set the feature flags to the id'th odd (ie non-required) feature bit so that we can
1153 // test for it later.
1155 let idx = ($id - 1) * 2 + 1;
1157 vec![1 << (idx - 8*3), 0, 0, 0]
1158 } else if idx > 8*2 {
1159 vec![1 << (idx - 8*2), 0, 0]
1160 } else if idx > 8*1 {
1161 vec![1 << (idx - 8*1), 0]
1169 let mut network = router.network_map.write().unwrap();
1171 network.nodes.insert(node1.clone(), NodeInfo {
1172 channels: vec!(1, 3),
1173 lowest_inbound_channel_fee_base_msat: 100,
1174 lowest_inbound_channel_fee_proportional_millionths: 0,
1175 features: NodeFeatures::from_le_bytes(id_to_feature_flags!(1)),
1176 last_update: Some(1),
1179 addresses: Vec::new(),
1180 announcement_message: None,
1182 network.channels.insert(1, ChannelInfo {
1183 features: ChannelFeatures::from_le_bytes(id_to_feature_flags!(1)),
1184 one_to_two: DirectionalChannelInfo {
1185 src_node_id: our_id.clone(),
1188 cltv_expiry_delta: u16::max_value(), // This value should be ignored
1189 htlc_minimum_msat: 0,
1190 fee_base_msat: u32::max_value(), // This value should be ignored
1191 fee_proportional_millionths: u32::max_value(), // This value should be ignored
1192 last_update_message: None,
1193 }, two_to_one: DirectionalChannelInfo {
1194 src_node_id: node1.clone(),
1197 cltv_expiry_delta: 0,
1198 htlc_minimum_msat: 0,
1200 fee_proportional_millionths: 0,
1201 last_update_message: None,
1203 announcement_message: None,
1205 network.nodes.insert(node2.clone(), NodeInfo {
1206 channels: vec!(2, 4),
1207 lowest_inbound_channel_fee_base_msat: 0,
1208 lowest_inbound_channel_fee_proportional_millionths: 0,
1209 features: NodeFeatures::from_le_bytes(id_to_feature_flags!(2)),
1210 last_update: Some(1),
1213 addresses: Vec::new(),
1214 announcement_message: None,
1216 network.channels.insert(2, ChannelInfo {
1217 features: ChannelFeatures::from_le_bytes(id_to_feature_flags!(2)),
1218 one_to_two: DirectionalChannelInfo {
1219 src_node_id: our_id.clone(),
1222 cltv_expiry_delta: u16::max_value(), // This value should be ignored
1223 htlc_minimum_msat: 0,
1224 fee_base_msat: u32::max_value(), // This value should be ignored
1225 fee_proportional_millionths: u32::max_value(), // This value should be ignored
1226 last_update_message: None,
1227 }, two_to_one: DirectionalChannelInfo {
1228 src_node_id: node2.clone(),
1231 cltv_expiry_delta: 0,
1232 htlc_minimum_msat: 0,
1234 fee_proportional_millionths: 0,
1235 last_update_message: None,
1237 announcement_message: None,
1239 network.nodes.insert(node8.clone(), NodeInfo {
1240 channels: vec!(12, 13),
1241 lowest_inbound_channel_fee_base_msat: 0,
1242 lowest_inbound_channel_fee_proportional_millionths: 0,
1243 features: NodeFeatures::from_le_bytes(id_to_feature_flags!(8)),
1244 last_update: Some(1),
1247 addresses: Vec::new(),
1248 announcement_message: None,
1250 network.channels.insert(12, ChannelInfo {
1251 features: ChannelFeatures::from_le_bytes(id_to_feature_flags!(12)),
1252 one_to_two: DirectionalChannelInfo {
1253 src_node_id: our_id.clone(),
1256 cltv_expiry_delta: u16::max_value(), // This value should be ignored
1257 htlc_minimum_msat: 0,
1258 fee_base_msat: u32::max_value(), // This value should be ignored
1259 fee_proportional_millionths: u32::max_value(), // This value should be ignored
1260 last_update_message: None,
1261 }, two_to_one: DirectionalChannelInfo {
1262 src_node_id: node8.clone(),
1265 cltv_expiry_delta: 0,
1266 htlc_minimum_msat: 0,
1268 fee_proportional_millionths: 0,
1269 last_update_message: None,
1271 announcement_message: None,
1273 network.nodes.insert(node3.clone(), NodeInfo {
1281 lowest_inbound_channel_fee_base_msat: 0,
1282 lowest_inbound_channel_fee_proportional_millionths: 0,
1283 features: NodeFeatures::from_le_bytes(id_to_feature_flags!(3)),
1284 last_update: Some(1),
1287 addresses: Vec::new(),
1288 announcement_message: None,
1290 network.channels.insert(3, ChannelInfo {
1291 features: ChannelFeatures::from_le_bytes(id_to_feature_flags!(3)),
1292 one_to_two: DirectionalChannelInfo {
1293 src_node_id: node1.clone(),
1296 cltv_expiry_delta: (3 << 8) | 1,
1297 htlc_minimum_msat: 0,
1299 fee_proportional_millionths: 0,
1300 last_update_message: None,
1301 }, two_to_one: DirectionalChannelInfo {
1302 src_node_id: node3.clone(),
1305 cltv_expiry_delta: (3 << 8) | 2,
1306 htlc_minimum_msat: 0,
1308 fee_proportional_millionths: 0,
1309 last_update_message: None,
1311 announcement_message: None,
1313 network.channels.insert(4, ChannelInfo {
1314 features: ChannelFeatures::from_le_bytes(id_to_feature_flags!(4)),
1315 one_to_two: DirectionalChannelInfo {
1316 src_node_id: node2.clone(),
1319 cltv_expiry_delta: (4 << 8) | 1,
1320 htlc_minimum_msat: 0,
1322 fee_proportional_millionths: 1000000,
1323 last_update_message: None,
1324 }, two_to_one: DirectionalChannelInfo {
1325 src_node_id: node3.clone(),
1328 cltv_expiry_delta: (4 << 8) | 2,
1329 htlc_minimum_msat: 0,
1331 fee_proportional_millionths: 0,
1332 last_update_message: None,
1334 announcement_message: None,
1336 network.channels.insert(13, ChannelInfo {
1337 features: ChannelFeatures::from_le_bytes(id_to_feature_flags!(13)),
1338 one_to_two: DirectionalChannelInfo {
1339 src_node_id: node8.clone(),
1342 cltv_expiry_delta: (13 << 8) | 1,
1343 htlc_minimum_msat: 0,
1345 fee_proportional_millionths: 2000000,
1346 last_update_message: None,
1347 }, two_to_one: DirectionalChannelInfo {
1348 src_node_id: node3.clone(),
1351 cltv_expiry_delta: (13 << 8) | 2,
1352 htlc_minimum_msat: 0,
1354 fee_proportional_millionths: 0,
1355 last_update_message: None,
1357 announcement_message: None,
1359 network.nodes.insert(node4.clone(), NodeInfo {
1360 channels: vec!(5, 11),
1361 lowest_inbound_channel_fee_base_msat: 0,
1362 lowest_inbound_channel_fee_proportional_millionths: 0,
1363 features: NodeFeatures::from_le_bytes(id_to_feature_flags!(4)),
1364 last_update: Some(1),
1367 addresses: Vec::new(),
1368 announcement_message: None,
1370 network.channels.insert(5, ChannelInfo {
1371 features: ChannelFeatures::from_le_bytes(id_to_feature_flags!(5)),
1372 one_to_two: DirectionalChannelInfo {
1373 src_node_id: node3.clone(),
1376 cltv_expiry_delta: (5 << 8) | 1,
1377 htlc_minimum_msat: 0,
1379 fee_proportional_millionths: 0,
1380 last_update_message: None,
1381 }, two_to_one: DirectionalChannelInfo {
1382 src_node_id: node4.clone(),
1385 cltv_expiry_delta: (5 << 8) | 2,
1386 htlc_minimum_msat: 0,
1388 fee_proportional_millionths: 0,
1389 last_update_message: None,
1391 announcement_message: None,
1393 network.nodes.insert(node5.clone(), NodeInfo {
1394 channels: vec!(6, 11),
1395 lowest_inbound_channel_fee_base_msat: 0,
1396 lowest_inbound_channel_fee_proportional_millionths: 0,
1397 features: NodeFeatures::from_le_bytes(id_to_feature_flags!(5)),
1398 last_update: Some(1),
1401 addresses: Vec::new(),
1402 announcement_message: None,
1404 network.channels.insert(6, ChannelInfo {
1405 features: ChannelFeatures::from_le_bytes(id_to_feature_flags!(6)),
1406 one_to_two: DirectionalChannelInfo {
1407 src_node_id: node3.clone(),
1410 cltv_expiry_delta: (6 << 8) | 1,
1411 htlc_minimum_msat: 0,
1413 fee_proportional_millionths: 0,
1414 last_update_message: None,
1415 }, two_to_one: DirectionalChannelInfo {
1416 src_node_id: node5.clone(),
1419 cltv_expiry_delta: (6 << 8) | 2,
1420 htlc_minimum_msat: 0,
1422 fee_proportional_millionths: 0,
1423 last_update_message: None,
1425 announcement_message: None,
1427 network.channels.insert(11, ChannelInfo {
1428 features: ChannelFeatures::from_le_bytes(id_to_feature_flags!(11)),
1429 one_to_two: DirectionalChannelInfo {
1430 src_node_id: node5.clone(),
1433 cltv_expiry_delta: (11 << 8) | 1,
1434 htlc_minimum_msat: 0,
1436 fee_proportional_millionths: 0,
1437 last_update_message: None,
1438 }, two_to_one: DirectionalChannelInfo {
1439 src_node_id: node4.clone(),
1442 cltv_expiry_delta: (11 << 8) | 2,
1443 htlc_minimum_msat: 0,
1445 fee_proportional_millionths: 0,
1446 last_update_message: None,
1448 announcement_message: None,
1450 network.nodes.insert(node6.clone(), NodeInfo {
1452 lowest_inbound_channel_fee_base_msat: 0,
1453 lowest_inbound_channel_fee_proportional_millionths: 0,
1454 features: NodeFeatures::from_le_bytes(id_to_feature_flags!(6)),
1455 last_update: Some(1),
1458 addresses: Vec::new(),
1459 announcement_message: None,
1461 network.channels.insert(7, ChannelInfo {
1462 features: ChannelFeatures::from_le_bytes(id_to_feature_flags!(7)),
1463 one_to_two: DirectionalChannelInfo {
1464 src_node_id: node3.clone(),
1467 cltv_expiry_delta: (7 << 8) | 1,
1468 htlc_minimum_msat: 0,
1470 fee_proportional_millionths: 1000000,
1471 last_update_message: None,
1472 }, two_to_one: DirectionalChannelInfo {
1473 src_node_id: node6.clone(),
1476 cltv_expiry_delta: (7 << 8) | 2,
1477 htlc_minimum_msat: 0,
1479 fee_proportional_millionths: 0,
1480 last_update_message: None,
1482 announcement_message: None,
1486 { // Simple route to 3 via 2
1487 let route = router.get_route(&node3, None, &Vec::new(), 100, 42).unwrap();
1488 assert_eq!(route.paths[0].len(), 2);
1490 assert_eq!(route.paths[0][0].pubkey, node2);
1491 assert_eq!(route.paths[0][0].short_channel_id, 2);
1492 assert_eq!(route.paths[0][0].fee_msat, 100);
1493 assert_eq!(route.paths[0][0].cltv_expiry_delta, (4 << 8) | 1);
1494 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags!(2));
1495 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags!(2));
1497 assert_eq!(route.paths[0][1].pubkey, node3);
1498 assert_eq!(route.paths[0][1].short_channel_id, 4);
1499 assert_eq!(route.paths[0][1].fee_msat, 100);
1500 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
1501 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags!(3));
1502 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags!(4));
1505 { // Disable channels 4 and 12 by requiring unknown feature bits
1506 let mut network = router.network_map.write().unwrap();
1507 network.channels.get_mut(&4).unwrap().features.set_required_unknown_bits();
1508 network.channels.get_mut(&12).unwrap().features.set_required_unknown_bits();
1511 { // If all the channels require some features we don't understand, route should fail
1512 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = router.get_route(&node3, None, &Vec::new(), 100, 42) {
1513 assert_eq!(err, "Failed to find a path to the given destination");
1514 } else { panic!(); }
1517 { // If we specify a channel to node8, that overrides our local channel view and that gets used
1518 let our_chans = vec![channelmanager::ChannelDetails {
1519 channel_id: [0; 32],
1520 short_channel_id: Some(42),
1521 remote_network_id: node8.clone(),
1522 counterparty_features: InitFeatures::from_le_bytes(vec![0b11]),
1523 channel_value_satoshis: 0,
1525 outbound_capacity_msat: 0,
1526 inbound_capacity_msat: 0,
1529 let route = router.get_route(&node3, Some(&our_chans), &Vec::new(), 100, 42).unwrap();
1530 assert_eq!(route.paths[0].len(), 2);
1532 assert_eq!(route.paths[0][0].pubkey, node8);
1533 assert_eq!(route.paths[0][0].short_channel_id, 42);
1534 assert_eq!(route.paths[0][0].fee_msat, 200);
1535 assert_eq!(route.paths[0][0].cltv_expiry_delta, (13 << 8) | 1);
1536 assert_eq!(route.paths[0][0].node_features.le_flags(), &vec![0b11]); // it should also override our view of their features
1537 assert_eq!(route.paths[0][0].channel_features.le_flags(), &Vec::new()); // No feature flags will meet the relevant-to-channel conversion
1539 assert_eq!(route.paths[0][1].pubkey, node3);
1540 assert_eq!(route.paths[0][1].short_channel_id, 13);
1541 assert_eq!(route.paths[0][1].fee_msat, 100);
1542 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
1543 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags!(3));
1544 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags!(13));
1547 { // Re-enable channels 4 and 12 by wiping the unknown feature bits
1548 let mut network = router.network_map.write().unwrap();
1549 network.channels.get_mut(&4).unwrap().features.clear_unknown_bits();
1550 network.channels.get_mut(&12).unwrap().features.clear_unknown_bits();
1553 { // Disable nodes 1, 2, and 8 by requiring unknown feature bits
1554 let mut network = router.network_map.write().unwrap();
1555 network.nodes.get_mut(&node1).unwrap().features.set_required_unknown_bits();
1556 network.nodes.get_mut(&node2).unwrap().features.set_required_unknown_bits();
1557 network.nodes.get_mut(&node8).unwrap().features.set_required_unknown_bits();
1560 { // If all nodes require some features we don't understand, route should fail
1561 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = router.get_route(&node3, None, &Vec::new(), 100, 42) {
1562 assert_eq!(err, "Failed to find a path to the given destination");
1563 } else { panic!(); }
1566 { // If we specify a channel to node8, that overrides our local channel view and that gets used
1567 let our_chans = vec![channelmanager::ChannelDetails {
1568 channel_id: [0; 32],
1569 short_channel_id: Some(42),
1570 remote_network_id: node8.clone(),
1571 counterparty_features: InitFeatures::from_le_bytes(vec![0b11]),
1572 channel_value_satoshis: 0,
1574 outbound_capacity_msat: 0,
1575 inbound_capacity_msat: 0,
1578 let route = router.get_route(&node3, Some(&our_chans), &Vec::new(), 100, 42).unwrap();
1579 assert_eq!(route.paths[0].len(), 2);
1581 assert_eq!(route.paths[0][0].pubkey, node8);
1582 assert_eq!(route.paths[0][0].short_channel_id, 42);
1583 assert_eq!(route.paths[0][0].fee_msat, 200);
1584 assert_eq!(route.paths[0][0].cltv_expiry_delta, (13 << 8) | 1);
1585 assert_eq!(route.paths[0][0].node_features.le_flags(), &vec![0b11]); // it should also override our view of their features
1586 assert_eq!(route.paths[0][0].channel_features.le_flags(), &Vec::new()); // No feature flags will meet the relevant-to-channel conversion
1588 assert_eq!(route.paths[0][1].pubkey, node3);
1589 assert_eq!(route.paths[0][1].short_channel_id, 13);
1590 assert_eq!(route.paths[0][1].fee_msat, 100);
1591 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
1592 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags!(3));
1593 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags!(13));
1596 { // Re-enable nodes 1, 2, and 8
1597 let mut network = router.network_map.write().unwrap();
1598 network.nodes.get_mut(&node1).unwrap().features.clear_unknown_bits();
1599 network.nodes.get_mut(&node2).unwrap().features.clear_unknown_bits();
1600 network.nodes.get_mut(&node8).unwrap().features.clear_unknown_bits();
1603 // Note that we don't test disabling node 3 and failing to route to it, as we (somewhat
1604 // naively) assume that the user checked the feature bits on the invoice, which override
1605 // the node_announcement.
1607 { // Route to 1 via 2 and 3 because our channel to 1 is disabled
1608 let route = router.get_route(&node1, None, &Vec::new(), 100, 42).unwrap();
1609 assert_eq!(route.paths[0].len(), 3);
1611 assert_eq!(route.paths[0][0].pubkey, node2);
1612 assert_eq!(route.paths[0][0].short_channel_id, 2);
1613 assert_eq!(route.paths[0][0].fee_msat, 200);
1614 assert_eq!(route.paths[0][0].cltv_expiry_delta, (4 << 8) | 1);
1615 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags!(2));
1616 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags!(2));
1618 assert_eq!(route.paths[0][1].pubkey, node3);
1619 assert_eq!(route.paths[0][1].short_channel_id, 4);
1620 assert_eq!(route.paths[0][1].fee_msat, 100);
1621 assert_eq!(route.paths[0][1].cltv_expiry_delta, (3 << 8) | 2);
1622 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags!(3));
1623 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags!(4));
1625 assert_eq!(route.paths[0][2].pubkey, node1);
1626 assert_eq!(route.paths[0][2].short_channel_id, 3);
1627 assert_eq!(route.paths[0][2].fee_msat, 100);
1628 assert_eq!(route.paths[0][2].cltv_expiry_delta, 42);
1629 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags!(1));
1630 assert_eq!(route.paths[0][2].channel_features.le_flags(), &id_to_feature_flags!(3));
1633 { // If we specify a channel to node8, that overrides our local channel view and that gets used
1634 let our_chans = vec![channelmanager::ChannelDetails {
1635 channel_id: [0; 32],
1636 short_channel_id: Some(42),
1637 remote_network_id: node8.clone(),
1638 counterparty_features: InitFeatures::from_le_bytes(vec![0b11]),
1639 channel_value_satoshis: 0,
1641 outbound_capacity_msat: 0,
1642 inbound_capacity_msat: 0,
1645 let route = router.get_route(&node3, Some(&our_chans), &Vec::new(), 100, 42).unwrap();
1646 assert_eq!(route.paths[0].len(), 2);
1648 assert_eq!(route.paths[0][0].pubkey, node8);
1649 assert_eq!(route.paths[0][0].short_channel_id, 42);
1650 assert_eq!(route.paths[0][0].fee_msat, 200);
1651 assert_eq!(route.paths[0][0].cltv_expiry_delta, (13 << 8) | 1);
1652 assert_eq!(route.paths[0][0].node_features.le_flags(), &vec![0b11]);
1653 assert_eq!(route.paths[0][0].channel_features.le_flags(), &Vec::new()); // No feature flags will meet the relevant-to-channel conversion
1655 assert_eq!(route.paths[0][1].pubkey, node3);
1656 assert_eq!(route.paths[0][1].short_channel_id, 13);
1657 assert_eq!(route.paths[0][1].fee_msat, 100);
1658 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
1659 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags!(3));
1660 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags!(13));
1663 let mut last_hops = vec!(RouteHint {
1664 src_node_id: node4.clone(),
1665 short_channel_id: 8,
1667 fee_proportional_millionths: 0,
1668 cltv_expiry_delta: (8 << 8) | 1,
1669 htlc_minimum_msat: 0,
1671 src_node_id: node5.clone(),
1672 short_channel_id: 9,
1673 fee_base_msat: 1001,
1674 fee_proportional_millionths: 0,
1675 cltv_expiry_delta: (9 << 8) | 1,
1676 htlc_minimum_msat: 0,
1678 src_node_id: node6.clone(),
1679 short_channel_id: 10,
1681 fee_proportional_millionths: 0,
1682 cltv_expiry_delta: (10 << 8) | 1,
1683 htlc_minimum_msat: 0,
1686 { // Simple test across 2, 3, 5, and 4 via a last_hop channel
1687 let route = router.get_route(&node7, None, &last_hops, 100, 42).unwrap();
1688 assert_eq!(route.paths[0].len(), 5);
1690 assert_eq!(route.paths[0][0].pubkey, node2);
1691 assert_eq!(route.paths[0][0].short_channel_id, 2);
1692 assert_eq!(route.paths[0][0].fee_msat, 100);
1693 assert_eq!(route.paths[0][0].cltv_expiry_delta, (4 << 8) | 1);
1694 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags!(2));
1695 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags!(2));
1697 assert_eq!(route.paths[0][1].pubkey, node3);
1698 assert_eq!(route.paths[0][1].short_channel_id, 4);
1699 assert_eq!(route.paths[0][1].fee_msat, 0);
1700 assert_eq!(route.paths[0][1].cltv_expiry_delta, (6 << 8) | 1);
1701 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags!(3));
1702 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags!(4));
1704 assert_eq!(route.paths[0][2].pubkey, node5);
1705 assert_eq!(route.paths[0][2].short_channel_id, 6);
1706 assert_eq!(route.paths[0][2].fee_msat, 0);
1707 assert_eq!(route.paths[0][2].cltv_expiry_delta, (11 << 8) | 1);
1708 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags!(5));
1709 assert_eq!(route.paths[0][2].channel_features.le_flags(), &id_to_feature_flags!(6));
1711 assert_eq!(route.paths[0][3].pubkey, node4);
1712 assert_eq!(route.paths[0][3].short_channel_id, 11);
1713 assert_eq!(route.paths[0][3].fee_msat, 0);
1714 assert_eq!(route.paths[0][3].cltv_expiry_delta, (8 << 8) | 1);
1715 // If we have a peer in the node map, we'll use their features here since we don't have
1716 // a way of figuring out their features from the invoice:
1717 assert_eq!(route.paths[0][3].node_features.le_flags(), &id_to_feature_flags!(4));
1718 assert_eq!(route.paths[0][3].channel_features.le_flags(), &id_to_feature_flags!(11));
1720 assert_eq!(route.paths[0][4].pubkey, node7);
1721 assert_eq!(route.paths[0][4].short_channel_id, 8);
1722 assert_eq!(route.paths[0][4].fee_msat, 100);
1723 assert_eq!(route.paths[0][4].cltv_expiry_delta, 42);
1724 assert_eq!(route.paths[0][4].node_features.le_flags(), &Vec::new()); // We dont pass flags in from invoices yet
1725 assert_eq!(route.paths[0][4].channel_features.le_flags(), &Vec::new()); // We can't learn any flags from invoices, sadly
1728 { // Simple test with outbound channel to 4 to test that last_hops and first_hops connect
1729 let our_chans = vec![channelmanager::ChannelDetails {
1730 channel_id: [0; 32],
1731 short_channel_id: Some(42),
1732 remote_network_id: node4.clone(),
1733 counterparty_features: InitFeatures::from_le_bytes(vec![0b11]),
1734 channel_value_satoshis: 0,
1736 outbound_capacity_msat: 0,
1737 inbound_capacity_msat: 0,
1740 let route = router.get_route(&node7, Some(&our_chans), &last_hops, 100, 42).unwrap();
1741 assert_eq!(route.paths[0].len(), 2);
1743 assert_eq!(route.paths[0][0].pubkey, node4);
1744 assert_eq!(route.paths[0][0].short_channel_id, 42);
1745 assert_eq!(route.paths[0][0].fee_msat, 0);
1746 assert_eq!(route.paths[0][0].cltv_expiry_delta, (8 << 8) | 1);
1747 assert_eq!(route.paths[0][0].node_features.le_flags(), &vec![0b11]);
1748 assert_eq!(route.paths[0][0].channel_features.le_flags(), &Vec::new()); // No feature flags will meet the relevant-to-channel conversion
1750 assert_eq!(route.paths[0][1].pubkey, node7);
1751 assert_eq!(route.paths[0][1].short_channel_id, 8);
1752 assert_eq!(route.paths[0][1].fee_msat, 100);
1753 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
1754 assert_eq!(route.paths[0][1].node_features.le_flags(), &Vec::new()); // We dont pass flags in from invoices yet
1755 assert_eq!(route.paths[0][1].channel_features.le_flags(), &Vec::new()); // We can't learn any flags from invoices, sadly
1758 last_hops[0].fee_base_msat = 1000;
1760 { // Revert to via 6 as the fee on 8 goes up
1761 let route = router.get_route(&node7, None, &last_hops, 100, 42).unwrap();
1762 assert_eq!(route.paths[0].len(), 4);
1764 assert_eq!(route.paths[0][0].pubkey, node2);
1765 assert_eq!(route.paths[0][0].short_channel_id, 2);
1766 assert_eq!(route.paths[0][0].fee_msat, 200); // fee increased as its % of value transferred across node
1767 assert_eq!(route.paths[0][0].cltv_expiry_delta, (4 << 8) | 1);
1768 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags!(2));
1769 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags!(2));
1771 assert_eq!(route.paths[0][1].pubkey, node3);
1772 assert_eq!(route.paths[0][1].short_channel_id, 4);
1773 assert_eq!(route.paths[0][1].fee_msat, 100);
1774 assert_eq!(route.paths[0][1].cltv_expiry_delta, (7 << 8) | 1);
1775 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags!(3));
1776 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags!(4));
1778 assert_eq!(route.paths[0][2].pubkey, node6);
1779 assert_eq!(route.paths[0][2].short_channel_id, 7);
1780 assert_eq!(route.paths[0][2].fee_msat, 0);
1781 assert_eq!(route.paths[0][2].cltv_expiry_delta, (10 << 8) | 1);
1782 // If we have a peer in the node map, we'll use their features here since we don't have
1783 // a way of figuring out their features from the invoice:
1784 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags!(6));
1785 assert_eq!(route.paths[0][2].channel_features.le_flags(), &id_to_feature_flags!(7));
1787 assert_eq!(route.paths[0][3].pubkey, node7);
1788 assert_eq!(route.paths[0][3].short_channel_id, 10);
1789 assert_eq!(route.paths[0][3].fee_msat, 100);
1790 assert_eq!(route.paths[0][3].cltv_expiry_delta, 42);
1791 assert_eq!(route.paths[0][3].node_features.le_flags(), &Vec::new()); // We dont pass flags in from invoices yet
1792 assert_eq!(route.paths[0][3].channel_features.le_flags(), &Vec::new()); // We can't learn any flags from invoices, sadly
1795 { // ...but still use 8 for larger payments as 6 has a variable feerate
1796 let route = router.get_route(&node7, None, &last_hops, 2000, 42).unwrap();
1797 assert_eq!(route.paths[0].len(), 5);
1799 assert_eq!(route.paths[0][0].pubkey, node2);
1800 assert_eq!(route.paths[0][0].short_channel_id, 2);
1801 assert_eq!(route.paths[0][0].fee_msat, 3000);
1802 assert_eq!(route.paths[0][0].cltv_expiry_delta, (4 << 8) | 1);
1803 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags!(2));
1804 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags!(2));
1806 assert_eq!(route.paths[0][1].pubkey, node3);
1807 assert_eq!(route.paths[0][1].short_channel_id, 4);
1808 assert_eq!(route.paths[0][1].fee_msat, 0);
1809 assert_eq!(route.paths[0][1].cltv_expiry_delta, (6 << 8) | 1);
1810 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags!(3));
1811 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags!(4));
1813 assert_eq!(route.paths[0][2].pubkey, node5);
1814 assert_eq!(route.paths[0][2].short_channel_id, 6);
1815 assert_eq!(route.paths[0][2].fee_msat, 0);
1816 assert_eq!(route.paths[0][2].cltv_expiry_delta, (11 << 8) | 1);
1817 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags!(5));
1818 assert_eq!(route.paths[0][2].channel_features.le_flags(), &id_to_feature_flags!(6));
1820 assert_eq!(route.paths[0][3].pubkey, node4);
1821 assert_eq!(route.paths[0][3].short_channel_id, 11);
1822 assert_eq!(route.paths[0][3].fee_msat, 1000);
1823 assert_eq!(route.paths[0][3].cltv_expiry_delta, (8 << 8) | 1);
1824 // If we have a peer in the node map, we'll use their features here since we don't have
1825 // a way of figuring out their features from the invoice:
1826 assert_eq!(route.paths[0][3].node_features.le_flags(), &id_to_feature_flags!(4));
1827 assert_eq!(route.paths[0][3].channel_features.le_flags(), &id_to_feature_flags!(11));
1829 assert_eq!(route.paths[0][4].pubkey, node7);
1830 assert_eq!(route.paths[0][4].short_channel_id, 8);
1831 assert_eq!(route.paths[0][4].fee_msat, 2000);
1832 assert_eq!(route.paths[0][4].cltv_expiry_delta, 42);
1833 assert_eq!(route.paths[0][4].node_features.le_flags(), &Vec::new()); // We dont pass flags in from invoices yet
1834 assert_eq!(route.paths[0][4].channel_features.le_flags(), &Vec::new()); // We can't learn any flags from invoices, sadly
1837 { // Test Router serialization/deserialization
1838 let mut w = TestVecWriter(Vec::new());
1839 let network = router.network_map.read().unwrap();
1840 assert!(!network.channels.is_empty());
1841 assert!(!network.nodes.is_empty());
1842 network.write(&mut w).unwrap();
1843 assert!(<NetworkMap>::read(&mut ::std::io::Cursor::new(&w.0)).unwrap() == *network);
1848 fn request_full_sync_finite_times() {
1849 let (secp_ctx, _, router) = create_router();
1850 let node_id = PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&hex::decode("0202020202020202020202020202020202020202020202020202020202020202").unwrap()[..]).unwrap());
1852 assert!(router.should_request_full_sync(&node_id));
1853 assert!(router.should_request_full_sync(&node_id));
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));
1861 fn handling_node_announcements() {
1862 let (secp_ctx, _, router) = create_router();
1864 let node_1_privkey = &SecretKey::from_slice(&[42; 32]).unwrap();
1865 let node_2_privkey = &SecretKey::from_slice(&[41; 32]).unwrap();
1866 let node_id_1 = PublicKey::from_secret_key(&secp_ctx, node_1_privkey);
1867 let node_id_2 = PublicKey::from_secret_key(&secp_ctx, node_2_privkey);
1868 let node_1_btckey = &SecretKey::from_slice(&[40; 32]).unwrap();
1869 let node_2_btckey = &SecretKey::from_slice(&[39; 32]).unwrap();
1870 let zero_hash = Sha256dHash::hash(&[0; 32]);
1871 let first_announcement_time = 500;
1873 let mut unsigned_announcement = UnsignedNodeAnnouncement {
1874 features: NodeFeatures::known(),
1875 timestamp: first_announcement_time,
1879 addresses: Vec::new(),
1880 excess_address_data: Vec::new(),
1881 excess_data: Vec::new(),
1883 let mut msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1884 let valid_announcement = NodeAnnouncement {
1885 signature: secp_ctx.sign(&msghash, node_1_privkey),
1886 contents: unsigned_announcement.clone()
1889 match router.handle_node_announcement(&valid_announcement) {
1891 Err(e) => assert_eq!("No existing channels for node_announcement", e.err)
1895 // Announce a channel to add a corresponding node.
1896 let unsigned_announcement = UnsignedChannelAnnouncement {
1897 features: ChannelFeatures::known(),
1898 chain_hash: genesis_block(Network::Testnet).header.bitcoin_hash(),
1899 short_channel_id: 0,
1902 bitcoin_key_1: PublicKey::from_secret_key(&secp_ctx, node_1_btckey),
1903 bitcoin_key_2: PublicKey::from_secret_key(&secp_ctx, node_2_btckey),
1904 excess_data: Vec::new(),
1907 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1908 let valid_announcement = ChannelAnnouncement {
1909 node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
1910 node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
1911 bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_btckey),
1912 bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_btckey),
1913 contents: unsigned_announcement.clone(),
1915 match router.handle_channel_announcement(&valid_announcement) {
1916 Ok(res) => assert!(res),
1921 match router.handle_node_announcement(&valid_announcement) {
1922 Ok(res) => assert!(res),
1926 let fake_msghash = hash_to_message!(&zero_hash);
1927 match router.handle_node_announcement(
1929 signature: secp_ctx.sign(&fake_msghash, node_1_privkey),
1930 contents: unsigned_announcement.clone()
1933 Err(e) => assert_eq!(e.err, "Invalid signature from remote node")
1936 unsigned_announcement.timestamp += 1000;
1937 unsigned_announcement.excess_data.push(1);
1938 msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1939 let announcement_with_data = NodeAnnouncement {
1940 signature: secp_ctx.sign(&msghash, node_1_privkey),
1941 contents: unsigned_announcement.clone()
1943 // Return false because contains excess data.
1944 match router.handle_node_announcement(&announcement_with_data) {
1945 Ok(res) => assert!(!res),
1948 unsigned_announcement.excess_data = Vec::new();
1950 // Even though previous announcement was not relayed further, we still accepted it,
1951 // so we now won't accept announcements before the previous one.
1952 unsigned_announcement.timestamp -= 10;
1953 msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1954 let outdated_announcement = NodeAnnouncement {
1955 signature: secp_ctx.sign(&msghash, node_1_privkey),
1956 contents: unsigned_announcement.clone()
1958 match router.handle_node_announcement(&outdated_announcement) {
1960 Err(e) => assert_eq!(e.err, "Update older than last processed update")
1965 fn handling_channel_announcements() {
1966 let secp_ctx = Secp256k1::new();
1967 let our_id = PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(
1968 &hex::decode("0101010101010101010101010101010101010101010101010101010101010101").unwrap()[..]).unwrap());
1969 let logger: Arc<Logger> = Arc::new(test_utils::TestLogger::new());
1970 let chain_monitor = Arc::new(test_utils::TestChainWatcher::new());
1971 let router = Router::new(our_id, chain_monitor.clone(), Arc::clone(&logger));
1973 let node_1_privkey = &SecretKey::from_slice(&[42; 32]).unwrap();
1974 let node_2_privkey = &SecretKey::from_slice(&[41; 32]).unwrap();
1975 let node_id_1 = PublicKey::from_secret_key(&secp_ctx, node_1_privkey);
1976 let node_id_2 = PublicKey::from_secret_key(&secp_ctx, node_2_privkey);
1977 let node_1_btckey = &SecretKey::from_slice(&[40; 32]).unwrap();
1978 let node_2_btckey = &SecretKey::from_slice(&[39; 32]).unwrap();
1980 let good_script = Builder::new().push_opcode(opcodes::all::OP_PUSHNUM_2)
1981 .push_slice(&PublicKey::from_secret_key(&secp_ctx, node_1_btckey).serialize())
1982 .push_slice(&PublicKey::from_secret_key(&secp_ctx, node_2_btckey).serialize())
1983 .push_opcode(opcodes::all::OP_PUSHNUM_2)
1984 .push_opcode(opcodes::all::OP_CHECKMULTISIG).into_script().to_v0_p2wsh();
1987 let mut unsigned_announcement = UnsignedChannelAnnouncement {
1988 features: ChannelFeatures::known(),
1989 chain_hash: genesis_block(Network::Testnet).header.bitcoin_hash(),
1990 short_channel_id: 0,
1993 bitcoin_key_1: PublicKey::from_secret_key(&secp_ctx, node_1_btckey),
1994 bitcoin_key_2: PublicKey::from_secret_key(&secp_ctx, node_2_btckey),
1995 excess_data: Vec::new(),
1998 let channel_key = unsigned_announcement.short_channel_id;
2000 let mut msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
2001 let valid_announcement = ChannelAnnouncement {
2002 node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
2003 node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
2004 bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_btckey),
2005 bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_btckey),
2006 contents: unsigned_announcement.clone(),
2009 // Test if the UTXO lookups were not supported
2010 *chain_monitor.utxo_ret.lock().unwrap() = Err(chaininterface::ChainError::NotSupported);
2012 match router.handle_channel_announcement(&valid_announcement) {
2013 Ok(res) => assert!(res),
2017 let network = router.network_map.write().unwrap();
2018 match network.channels.get(&channel_key) {
2024 // If we receive announcement for the same channel (with UTXO lookups disabled),
2025 // drop new one on the floor, since we can't see any changes.
2026 match router.handle_channel_announcement(&valid_announcement) {
2028 Err(e) => assert_eq!(e.err, "Already have knowledge of channel")
2032 // Test if an associated transaction were not on-chain (or not confirmed).
2033 *chain_monitor.utxo_ret.lock().unwrap() = Err(chaininterface::ChainError::UnknownTx);
2034 unsigned_announcement.short_channel_id += 1;
2036 msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
2037 let valid_announcement = ChannelAnnouncement {
2038 node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
2039 node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
2040 bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_btckey),
2041 bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_btckey),
2042 contents: unsigned_announcement.clone(),
2045 match router.handle_channel_announcement(&valid_announcement) {
2047 Err(e) => assert_eq!(e.err, "Channel announced without corresponding UTXO entry")
2051 // Now test if the transaction is found in the UTXO set and the script is correct.
2052 unsigned_announcement.short_channel_id += 1;
2053 *chain_monitor.utxo_ret.lock().unwrap() = Ok((good_script.clone(), 0));
2054 let channel_key = unsigned_announcement.short_channel_id;
2056 msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
2057 let valid_announcement = ChannelAnnouncement {
2058 node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
2059 node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
2060 bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_btckey),
2061 bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_btckey),
2062 contents: unsigned_announcement.clone(),
2064 match router.handle_channel_announcement(&valid_announcement) {
2065 Ok(res) => assert!(res),
2069 let network = router.network_map.write().unwrap();
2070 match network.channels.get(&channel_key) {
2076 // If we receive announcement for the same channel (but TX is not confirmed),
2077 // drop new one on the floor, since we can't see any changes.
2078 *chain_monitor.utxo_ret.lock().unwrap() = Err(chaininterface::ChainError::UnknownTx);
2079 match router.handle_channel_announcement(&valid_announcement) {
2081 Err(e) => assert_eq!(e.err, "Channel announced without corresponding UTXO entry")
2084 // But if it is confirmed, replace the channel
2085 *chain_monitor.utxo_ret.lock().unwrap() = Ok((good_script, 0));
2086 unsigned_announcement.features = ChannelFeatures::empty();
2087 msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
2088 let valid_announcement = ChannelAnnouncement {
2089 node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
2090 node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
2091 bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_btckey),
2092 bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_btckey),
2093 contents: unsigned_announcement.clone(),
2095 match router.handle_channel_announcement(&valid_announcement) {
2096 Ok(res) => assert!(res),
2100 let mut network = router.network_map.write().unwrap();
2101 match network.channels.entry(channel_key) {
2102 BtreeEntry::Occupied(channel_entry) => {
2103 assert_eq!(channel_entry.get().features, ChannelFeatures::empty());
2109 // Don't relay valid channels with excess data
2110 unsigned_announcement.short_channel_id += 1;
2111 unsigned_announcement.excess_data.push(1);
2112 msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
2113 let valid_announcement = ChannelAnnouncement {
2114 node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
2115 node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
2116 bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_btckey),
2117 bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_btckey),
2118 contents: unsigned_announcement.clone(),
2120 match router.handle_channel_announcement(&valid_announcement) {
2121 Ok(res) => assert!(!res),
2125 unsigned_announcement.excess_data = Vec::new();
2126 let invalid_sig_announcement = ChannelAnnouncement {
2127 node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
2128 node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
2129 bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_btckey),
2130 bitcoin_signature_2: secp_ctx.sign(&msghash, node_1_btckey),
2131 contents: unsigned_announcement.clone(),
2133 match router.handle_channel_announcement(&invalid_sig_announcement) {
2135 Err(e) => assert_eq!(e.err, "Invalid signature from remote node")
2138 unsigned_announcement.node_id_1 = PublicKey::from_secret_key(&secp_ctx, node_2_privkey);
2139 msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
2140 let channel_to_itself_announcement = ChannelAnnouncement {
2141 node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
2142 node_signature_2: secp_ctx.sign(&msghash, node_1_privkey),
2143 bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_btckey),
2144 bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_btckey),
2145 contents: unsigned_announcement.clone(),
2147 match router.handle_channel_announcement(&channel_to_itself_announcement) {
2149 Err(e) => assert_eq!(e.err, "Channel announcement node had a channel with itself")
2154 fn handling_channel_update() {
2155 let (secp_ctx, _, router) = create_router();
2156 let node_1_privkey = &SecretKey::from_slice(&[42; 32]).unwrap();
2157 let node_2_privkey = &SecretKey::from_slice(&[41; 32]).unwrap();
2158 let node_id_1 = PublicKey::from_secret_key(&secp_ctx, node_1_privkey);
2159 let node_id_2 = PublicKey::from_secret_key(&secp_ctx, node_2_privkey);
2160 let node_1_btckey = &SecretKey::from_slice(&[40; 32]).unwrap();
2161 let node_2_btckey = &SecretKey::from_slice(&[39; 32]).unwrap();
2163 let zero_hash = Sha256dHash::hash(&[0; 32]);
2164 let short_channel_id = 0;
2165 let chain_hash = genesis_block(Network::Testnet).header.bitcoin_hash();
2166 let channel_key = short_channel_id;
2170 // Announce a channel we will update
2171 let unsigned_announcement = UnsignedChannelAnnouncement {
2172 features: ChannelFeatures::empty(),
2177 bitcoin_key_1: PublicKey::from_secret_key(&secp_ctx, node_1_btckey),
2178 bitcoin_key_2: PublicKey::from_secret_key(&secp_ctx, node_2_btckey),
2179 excess_data: Vec::new(),
2182 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
2183 let valid_channel_announcement = ChannelAnnouncement {
2184 node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
2185 node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
2186 bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_btckey),
2187 bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_btckey),
2188 contents: unsigned_announcement.clone(),
2190 match router.handle_channel_announcement(&valid_channel_announcement) {
2197 let mut unsigned_channel_update = UnsignedChannelUpdate {
2202 cltv_expiry_delta: 144,
2203 htlc_minimum_msat: 1000000,
2204 fee_base_msat: 10000,
2205 fee_proportional_millionths: 20,
2206 excess_data: Vec::new()
2208 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_channel_update.encode()[..])[..]);
2209 let valid_channel_update = ChannelUpdate {
2210 signature: secp_ctx.sign(&msghash, node_1_privkey),
2211 contents: unsigned_channel_update.clone()
2214 match router.handle_channel_update(&valid_channel_update) {
2215 Ok(res) => assert!(res),
2220 let network = router.network_map.write().unwrap();
2221 match network.channels.get(&channel_key) {
2223 Some(channel_info) => {
2224 assert_eq!(channel_info.one_to_two.cltv_expiry_delta, 144);
2225 assert_eq!(channel_info.two_to_one.cltv_expiry_delta, u16::max_value());
2230 unsigned_channel_update.timestamp += 100;
2231 unsigned_channel_update.excess_data.push(1);
2232 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_channel_update.encode()[..])[..]);
2233 let valid_channel_update = ChannelUpdate {
2234 signature: secp_ctx.sign(&msghash, node_1_privkey),
2235 contents: unsigned_channel_update.clone()
2237 // Return false because contains excess data
2238 match router.handle_channel_update(&valid_channel_update) {
2239 Ok(res) => assert!(!res),
2243 unsigned_channel_update.short_channel_id += 1;
2244 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_channel_update.encode()[..])[..]);
2245 let valid_channel_update = ChannelUpdate {
2246 signature: secp_ctx.sign(&msghash, node_1_privkey),
2247 contents: unsigned_channel_update.clone()
2250 match router.handle_channel_update(&valid_channel_update) {
2252 Err(e) => assert_eq!(e.err, "Couldn't find channel for update")
2254 unsigned_channel_update.short_channel_id = short_channel_id;
2257 // Even though previous update was not relayed further, we still accepted it,
2258 // so we now won't accept update before the previous one.
2259 unsigned_channel_update.timestamp -= 10;
2260 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_channel_update.encode()[..])[..]);
2261 let valid_channel_update = ChannelUpdate {
2262 signature: secp_ctx.sign(&msghash, node_1_privkey),
2263 contents: unsigned_channel_update.clone()
2266 match router.handle_channel_update(&valid_channel_update) {
2268 Err(e) => assert_eq!(e.err, "Update older than last processed update")
2270 unsigned_channel_update.timestamp += 500;
2272 let fake_msghash = hash_to_message!(&zero_hash);
2273 let invalid_sig_channel_update = ChannelUpdate {
2274 signature: secp_ctx.sign(&fake_msghash, node_1_privkey),
2275 contents: unsigned_channel_update.clone()
2278 match router.handle_channel_update(&invalid_sig_channel_update) {
2280 Err(e) => assert_eq!(e.err, "Invalid signature from remote node")
2286 fn handling_htlc_fail_channel_update() {
2287 let (secp_ctx, our_id, router) = create_router();
2288 let node_1_privkey = &SecretKey::from_slice(&[42; 32]).unwrap();
2289 let node_2_privkey = &SecretKey::from_slice(&[41; 32]).unwrap();
2290 let node_id_1 = PublicKey::from_secret_key(&secp_ctx, node_1_privkey);
2291 let node_id_2 = PublicKey::from_secret_key(&secp_ctx, node_2_privkey);
2292 let node_1_btckey = &SecretKey::from_slice(&[40; 32]).unwrap();
2293 let node_2_btckey = &SecretKey::from_slice(&[39; 32]).unwrap();
2295 let short_channel_id = 0;
2296 let chain_hash = genesis_block(Network::Testnet).header.bitcoin_hash();
2297 let channel_key = short_channel_id;
2300 // There is only local node in the table at the beginning.
2301 let network = router.network_map.read().unwrap();
2302 assert_eq!(network.nodes.len(), 1);
2303 assert_eq!(network.nodes.contains_key(&our_id), true);
2307 // Announce a channel we will update
2308 let unsigned_announcement = UnsignedChannelAnnouncement {
2309 features: ChannelFeatures::empty(),
2314 bitcoin_key_1: PublicKey::from_secret_key(&secp_ctx, node_1_btckey),
2315 bitcoin_key_2: PublicKey::from_secret_key(&secp_ctx, node_2_btckey),
2316 excess_data: Vec::new(),
2319 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
2320 let valid_channel_announcement = ChannelAnnouncement {
2321 node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
2322 node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
2323 bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_btckey),
2324 bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_btckey),
2325 contents: unsigned_announcement.clone(),
2327 match router.handle_channel_announcement(&valid_channel_announcement) {
2334 let channel_close_msg = HTLCFailChannelUpdate::ChannelClosed {
2339 router.handle_htlc_fail_channel_update(&channel_close_msg);
2342 // Non-permanent closing just disables a channel
2343 let network = router.network_map.write().unwrap();
2344 match network.channels.get(&channel_key) {
2346 Some(channel_info) => {
2347 assert!(!channel_info.one_to_two.enabled);
2348 assert!(!channel_info.two_to_one.enabled);
2353 let channel_close_msg = HTLCFailChannelUpdate::ChannelClosed {
2358 router.handle_htlc_fail_channel_update(&channel_close_msg);
2361 // Permanent closing deletes a channel
2362 let network = router.network_map.read().unwrap();
2363 assert_eq!(network.channels.len(), 0);
2364 // Nodes are also deleted because there are no associated channels anymore
2365 // Only the local node remains in the table.
2366 assert_eq!(network.nodes.len(), 1);
2367 assert_eq!(network.nodes.contains_key(&our_id), true);
2370 // TODO: Test HTLCFailChannelUpdate::NodeFailure, which is not implemented yet.
2374 fn getting_next_channel_announcements() {
2375 let (secp_ctx, _, router) = create_router();
2376 let node_1_privkey = &SecretKey::from_slice(&[42; 32]).unwrap();
2377 let node_2_privkey = &SecretKey::from_slice(&[41; 32]).unwrap();
2378 let node_id_1 = PublicKey::from_secret_key(&secp_ctx, node_1_privkey);
2379 let node_id_2 = PublicKey::from_secret_key(&secp_ctx, node_2_privkey);
2380 let node_1_btckey = &SecretKey::from_slice(&[40; 32]).unwrap();
2381 let node_2_btckey = &SecretKey::from_slice(&[39; 32]).unwrap();
2383 let short_channel_id = 1;
2384 let chain_hash = genesis_block(Network::Testnet).header.bitcoin_hash();
2385 let channel_key = short_channel_id;
2387 // Channels were not announced yet.
2388 let channels_with_announcements = router.get_next_channel_announcements(0, 1);
2389 assert_eq!(channels_with_announcements.len(), 0);
2392 // Announce a channel we will update
2393 let unsigned_announcement = UnsignedChannelAnnouncement {
2394 features: ChannelFeatures::empty(),
2399 bitcoin_key_1: PublicKey::from_secret_key(&secp_ctx, node_1_btckey),
2400 bitcoin_key_2: PublicKey::from_secret_key(&secp_ctx, node_2_btckey),
2401 excess_data: Vec::new(),
2404 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
2405 let valid_channel_announcement = ChannelAnnouncement {
2406 node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
2407 node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
2408 bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_btckey),
2409 bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_btckey),
2410 contents: unsigned_announcement.clone(),
2412 match router.handle_channel_announcement(&valid_channel_announcement) {
2418 // Contains initial channel announcement now.
2419 let channels_with_announcements = router.get_next_channel_announcements(channel_key, 1);
2420 assert_eq!(channels_with_announcements.len(), 1);
2421 if let Some(channel_announcements) = channels_with_announcements.first() {
2422 let &(_, ref update_1, ref update_2) = channel_announcements;
2423 assert_eq!(update_1, &None);
2424 assert_eq!(update_2, &None);
2431 // Valid channel update
2432 let unsigned_channel_update = UnsignedChannelUpdate {
2437 cltv_expiry_delta: 144,
2438 htlc_minimum_msat: 1000000,
2439 fee_base_msat: 10000,
2440 fee_proportional_millionths: 20,
2441 excess_data: Vec::new()
2443 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_channel_update.encode()[..])[..]);
2444 let valid_channel_update = ChannelUpdate {
2445 signature: secp_ctx.sign(&msghash, node_1_privkey),
2446 contents: unsigned_channel_update.clone()
2448 match router.handle_channel_update(&valid_channel_update) {
2454 // Now contains an initial announcement and an update.
2455 let channels_with_announcements = router.get_next_channel_announcements(channel_key, 1);
2456 assert_eq!(channels_with_announcements.len(), 1);
2457 if let Some(channel_announcements) = channels_with_announcements.first() {
2458 let &(_, ref update_1, ref update_2) = channel_announcements;
2459 assert_ne!(update_1, &None);
2460 assert_eq!(update_2, &None);
2467 // Channel update with excess data.
2468 let unsigned_channel_update = UnsignedChannelUpdate {
2473 cltv_expiry_delta: 144,
2474 htlc_minimum_msat: 1000000,
2475 fee_base_msat: 10000,
2476 fee_proportional_millionths: 20,
2477 excess_data: [1; 3].to_vec()
2479 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_channel_update.encode()[..])[..]);
2480 let valid_channel_update = ChannelUpdate {
2481 signature: secp_ctx.sign(&msghash, node_1_privkey),
2482 contents: unsigned_channel_update.clone()
2484 match router.handle_channel_update(&valid_channel_update) {
2490 // Test that announcements with excess data won't be returned
2491 let channels_with_announcements = router.get_next_channel_announcements(channel_key, 1);
2492 assert_eq!(channels_with_announcements.len(), 1);
2493 if let Some(channel_announcements) = channels_with_announcements.first() {
2494 let &(_, ref update_1, ref update_2) = channel_announcements;
2495 assert_eq!(update_1, &None);
2496 assert_eq!(update_2, &None);
2501 // Further starting point have no channels after it
2502 let channels_with_announcements = router.get_next_channel_announcements(channel_key + 1000, 1);
2503 assert_eq!(channels_with_announcements.len(), 0);
2507 fn getting_next_node_announcements() {
2508 let (secp_ctx, _, router) = create_router();
2509 let node_1_privkey = &SecretKey::from_slice(&[42; 32]).unwrap();
2510 let node_2_privkey = &SecretKey::from_slice(&[41; 32]).unwrap();
2511 let node_id_1 = PublicKey::from_secret_key(&secp_ctx, node_1_privkey);
2512 let node_id_2 = PublicKey::from_secret_key(&secp_ctx, node_2_privkey);
2513 let node_1_btckey = &SecretKey::from_slice(&[40; 32]).unwrap();
2514 let node_2_btckey = &SecretKey::from_slice(&[39; 32]).unwrap();
2516 let short_channel_id = 1;
2517 let chain_hash = genesis_block(Network::Testnet).header.bitcoin_hash();
2520 let next_announcements = router.get_next_node_announcements(None, 10);
2521 assert_eq!(next_announcements.len(), 0);
2524 // Announce a channel to add 2 nodes
2525 let unsigned_announcement = UnsignedChannelAnnouncement {
2526 features: ChannelFeatures::empty(),
2531 bitcoin_key_1: PublicKey::from_secret_key(&secp_ctx, node_1_btckey),
2532 bitcoin_key_2: PublicKey::from_secret_key(&secp_ctx, node_2_btckey),
2533 excess_data: Vec::new(),
2536 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
2537 let valid_channel_announcement = ChannelAnnouncement {
2538 node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
2539 node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
2540 bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_btckey),
2541 bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_btckey),
2542 contents: unsigned_announcement.clone(),
2544 match router.handle_channel_announcement(&valid_channel_announcement) {
2551 // Nodes were never announced
2552 let next_announcements = router.get_next_node_announcements(None, 3);
2553 assert_eq!(next_announcements.len(), 0);
2556 let mut unsigned_announcement = UnsignedNodeAnnouncement {
2557 features: NodeFeatures::known(),
2562 addresses: Vec::new(),
2563 excess_address_data: Vec::new(),
2564 excess_data: Vec::new(),
2566 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
2567 let valid_announcement = NodeAnnouncement {
2568 signature: secp_ctx.sign(&msghash, node_1_privkey),
2569 contents: unsigned_announcement.clone()
2571 match router.handle_node_announcement(&valid_announcement) {
2576 unsigned_announcement.node_id = node_id_2;
2577 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
2578 let valid_announcement = NodeAnnouncement {
2579 signature: secp_ctx.sign(&msghash, node_2_privkey),
2580 contents: unsigned_announcement.clone()
2583 match router.handle_node_announcement(&valid_announcement) {
2589 let next_announcements = router.get_next_node_announcements(None, 3);
2590 assert_eq!(next_announcements.len(), 2);
2592 // Skip the first node.
2593 let next_announcements = router.get_next_node_announcements(Some(&node_id_1), 2);
2594 assert_eq!(next_announcements.len(), 1);
2597 // Later announcement which should not be relayed (excess data) prevent us from sharing a node
2598 let unsigned_announcement = UnsignedNodeAnnouncement {
2599 features: NodeFeatures::known(),
2604 addresses: Vec::new(),
2605 excess_address_data: Vec::new(),
2606 excess_data: [1; 3].to_vec(),
2608 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
2609 let valid_announcement = NodeAnnouncement {
2610 signature: secp_ctx.sign(&msghash, node_2_privkey),
2611 contents: unsigned_announcement.clone()
2613 match router.handle_node_announcement(&valid_announcement) {
2614 Ok(res) => assert!(!res),
2619 let next_announcements = router.get_next_node_announcements(Some(&node_id_1), 2);
2620 assert_eq!(next_announcements.len(), 0);