1 // This file is Copyright its original authors, visible in version control
4 // This file is licensed under the Apache License, Version 2.0 <LICENSE-APACHE
5 // or http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
6 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your option.
7 // You may not use this file except in accordance with one or both of these
10 //! The top-level network map tracking logic lives here.
12 use bitcoin::secp256k1::key::PublicKey;
13 use bitcoin::secp256k1::Secp256k1;
14 use bitcoin::secp256k1;
16 use bitcoin::hashes::sha256d::Hash as Sha256dHash;
17 use bitcoin::hashes::Hash;
18 use bitcoin::blockdata::script::Builder;
19 use bitcoin::blockdata::transaction::TxOut;
20 use bitcoin::blockdata::opcodes;
21 use bitcoin::hash_types::BlockHash;
25 use ln::features::{ChannelFeatures, NodeFeatures};
26 use ln::msgs::{DecodeError, ErrorAction, Init, LightningError, RoutingMessageHandler, NetAddress, MAX_VALUE_MSAT};
27 use ln::msgs::{ChannelAnnouncement, ChannelUpdate, NodeAnnouncement, OptionalField};
28 use ln::msgs::{QueryChannelRange, ReplyChannelRange, QueryShortChannelIds, ReplyShortChannelIdsEnd};
30 use util::ser::{Writeable, Readable, Writer};
31 use util::logger::{Logger, Level};
32 use util::events::{MessageSendEvent, MessageSendEventsProvider};
33 use util::scid_utils::{block_from_scid, scid_from_parts, MAX_SCID_BLOCK};
36 use alloc::collections::{BTreeMap, btree_map::Entry as BtreeEntry};
38 use sync::{RwLock, RwLockReadGuard};
39 use core::sync::atomic::{AtomicUsize, Ordering};
42 use bitcoin::hashes::hex::ToHex;
44 /// The maximum number of extra bytes which we do not understand in a gossip message before we will
45 /// refuse to relay the message.
46 const MAX_EXCESS_BYTES_FOR_RELAY: usize = 1024;
48 /// Maximum number of short_channel_ids that will be encoded in one gossip reply message.
49 /// This value ensures a reply fits within the 65k payload limit and is consistent with other implementations.
50 const MAX_SCIDS_PER_REPLY: usize = 8000;
52 /// Represents the network as nodes and channels between them
53 #[derive(Clone, PartialEq)]
54 pub struct NetworkGraph {
55 genesis_hash: BlockHash,
56 channels: BTreeMap<u64, ChannelInfo>,
57 nodes: BTreeMap<PublicKey, NodeInfo>,
60 /// A simple newtype for RwLockReadGuard<'a, NetworkGraph>.
61 /// This exists only to make accessing a RwLock<NetworkGraph> possible from
62 /// the C bindings, as it can be done directly in Rust code.
63 pub struct LockedNetworkGraph<'a>(pub RwLockReadGuard<'a, NetworkGraph>);
65 /// Receives and validates network updates from peers,
66 /// stores authentic and relevant data as a network graph.
67 /// This network graph is then used for routing payments.
68 /// Provides interface to help with initial routing sync by
69 /// serving historical announcements.
70 pub struct NetGraphMsgHandler<C: Deref, L: Deref> where C::Target: chain::Access, L::Target: Logger {
71 secp_ctx: Secp256k1<secp256k1::VerifyOnly>,
72 /// Representation of the payment channel network
73 pub network_graph: RwLock<NetworkGraph>,
74 chain_access: Option<C>,
75 full_syncs_requested: AtomicUsize,
76 pending_events: Mutex<Vec<MessageSendEvent>>,
80 impl<C: Deref, L: Deref> NetGraphMsgHandler<C, L> where C::Target: chain::Access, L::Target: Logger {
81 /// Creates a new tracker of the actual state of the network of channels and nodes,
82 /// assuming a fresh network graph.
83 /// Chain monitor is used to make sure announced channels exist on-chain,
84 /// channel data is correct, and that the announcement is signed with
85 /// channel owners' keys.
86 pub fn new(genesis_hash: BlockHash, chain_access: Option<C>, logger: L) -> Self {
88 secp_ctx: Secp256k1::verification_only(),
89 network_graph: RwLock::new(NetworkGraph::new(genesis_hash)),
90 full_syncs_requested: AtomicUsize::new(0),
92 pending_events: Mutex::new(vec![]),
97 /// Creates a new tracker of the actual state of the network of channels and nodes,
98 /// assuming an existing Network Graph.
99 pub fn from_net_graph(chain_access: Option<C>, logger: L, network_graph: NetworkGraph) -> Self {
101 secp_ctx: Secp256k1::verification_only(),
102 network_graph: RwLock::new(network_graph),
103 full_syncs_requested: AtomicUsize::new(0),
105 pending_events: Mutex::new(vec![]),
110 /// Adds a provider used to check new announcements. Does not affect
111 /// existing announcements unless they are updated.
112 /// Add, update or remove the provider would replace the current one.
113 pub fn add_chain_access(&mut self, chain_access: Option<C>) {
114 self.chain_access = chain_access;
117 /// Take a read lock on the network_graph and return it in the C-bindings
118 /// newtype helper. This is likely only useful when called via the C
119 /// bindings as you can call `self.network_graph.read().unwrap()` in Rust
121 pub fn read_locked_graph<'a>(&'a self) -> LockedNetworkGraph<'a> {
122 LockedNetworkGraph(self.network_graph.read().unwrap())
125 /// Returns true when a full routing table sync should be performed with a peer.
126 fn should_request_full_sync(&self, _node_id: &PublicKey) -> bool {
127 //TODO: Determine whether to request a full sync based on the network map.
128 const FULL_SYNCS_TO_REQUEST: usize = 5;
129 if self.full_syncs_requested.load(Ordering::Acquire) < FULL_SYNCS_TO_REQUEST {
130 self.full_syncs_requested.fetch_add(1, Ordering::AcqRel);
138 impl<'a> LockedNetworkGraph<'a> {
139 /// Get a reference to the NetworkGraph which this read-lock contains.
140 pub fn graph(&self) -> &NetworkGraph {
146 macro_rules! secp_verify_sig {
147 ( $secp_ctx: expr, $msg: expr, $sig: expr, $pubkey: expr ) => {
148 match $secp_ctx.verify($msg, $sig, $pubkey) {
150 Err(_) => return Err(LightningError{err: "Invalid signature from remote node".to_owned(), action: ErrorAction::IgnoreError}),
155 impl<C: Deref , L: Deref > RoutingMessageHandler for NetGraphMsgHandler<C, L> where C::Target: chain::Access, L::Target: Logger {
156 fn handle_node_announcement(&self, msg: &msgs::NodeAnnouncement) -> Result<bool, LightningError> {
157 self.network_graph.write().unwrap().update_node_from_announcement(msg, &self.secp_ctx)?;
158 Ok(msg.contents.excess_data.len() <= MAX_EXCESS_BYTES_FOR_RELAY &&
159 msg.contents.excess_address_data.len() <= MAX_EXCESS_BYTES_FOR_RELAY &&
160 msg.contents.excess_data.len() + msg.contents.excess_address_data.len() <= MAX_EXCESS_BYTES_FOR_RELAY)
163 fn handle_channel_announcement(&self, msg: &msgs::ChannelAnnouncement) -> Result<bool, LightningError> {
164 self.network_graph.write().unwrap().update_channel_from_announcement(msg, &self.chain_access, &self.secp_ctx)?;
165 log_trace!(self.logger, "Added channel_announcement for {}{}", msg.contents.short_channel_id, if !msg.contents.excess_data.is_empty() { " with excess uninterpreted data!" } else { "" });
166 Ok(msg.contents.excess_data.len() <= MAX_EXCESS_BYTES_FOR_RELAY)
169 fn handle_htlc_fail_channel_update(&self, update: &msgs::HTLCFailChannelUpdate) {
171 &msgs::HTLCFailChannelUpdate::ChannelUpdateMessage { ref msg } => {
172 let chan_enabled = msg.contents.flags & (1 << 1) != (1 << 1);
173 log_debug!(self.logger, "Updating channel with channel_update from a payment failure. Channel {} is {}abled.", msg.contents.short_channel_id, if chan_enabled { "en" } else { "dis" });
174 let _ = self.network_graph.write().unwrap().update_channel(msg, &self.secp_ctx);
176 &msgs::HTLCFailChannelUpdate::ChannelClosed { short_channel_id, is_permanent } => {
177 log_debug!(self.logger, "{} channel graph entry for {} due to a payment failure.", if is_permanent { "Removing" } else { "Disabling" }, short_channel_id);
178 self.network_graph.write().unwrap().close_channel_from_update(short_channel_id, is_permanent);
180 &msgs::HTLCFailChannelUpdate::NodeFailure { ref node_id, is_permanent } => {
181 log_debug!(self.logger, "{} node graph entry for {} due to a payment failure.", if is_permanent { "Removing" } else { "Disabling" }, node_id);
182 self.network_graph.write().unwrap().fail_node(node_id, is_permanent);
187 fn handle_channel_update(&self, msg: &msgs::ChannelUpdate) -> Result<bool, LightningError> {
188 self.network_graph.write().unwrap().update_channel(msg, &self.secp_ctx)?;
189 Ok(msg.contents.excess_data.len() <= MAX_EXCESS_BYTES_FOR_RELAY)
192 fn get_next_channel_announcements(&self, starting_point: u64, batch_amount: u8) -> Vec<(ChannelAnnouncement, Option<ChannelUpdate>, Option<ChannelUpdate>)> {
193 let network_graph = self.network_graph.read().unwrap();
194 let mut result = Vec::with_capacity(batch_amount as usize);
195 let mut iter = network_graph.get_channels().range(starting_point..);
196 while result.len() < batch_amount as usize {
197 if let Some((_, ref chan)) = iter.next() {
198 if chan.announcement_message.is_some() {
199 let chan_announcement = chan.announcement_message.clone().unwrap();
200 let mut one_to_two_announcement: Option<msgs::ChannelUpdate> = None;
201 let mut two_to_one_announcement: Option<msgs::ChannelUpdate> = None;
202 if let Some(one_to_two) = chan.one_to_two.as_ref() {
203 one_to_two_announcement = one_to_two.last_update_message.clone();
205 if let Some(two_to_one) = chan.two_to_one.as_ref() {
206 two_to_one_announcement = two_to_one.last_update_message.clone();
208 result.push((chan_announcement, one_to_two_announcement, two_to_one_announcement));
210 // TODO: We may end up sending un-announced channel_updates if we are sending
211 // initial sync data while receiving announce/updates for this channel.
220 fn get_next_node_announcements(&self, starting_point: Option<&PublicKey>, batch_amount: u8) -> Vec<NodeAnnouncement> {
221 let network_graph = self.network_graph.read().unwrap();
222 let mut result = Vec::with_capacity(batch_amount as usize);
223 let mut iter = if let Some(pubkey) = starting_point {
224 let mut iter = network_graph.get_nodes().range((*pubkey)..);
228 network_graph.get_nodes().range(..)
230 while result.len() < batch_amount as usize {
231 if let Some((_, ref node)) = iter.next() {
232 if let Some(node_info) = node.announcement_info.as_ref() {
233 if node_info.announcement_message.is_some() {
234 result.push(node_info.announcement_message.clone().unwrap());
244 /// Initiates a stateless sync of routing gossip information with a peer
245 /// using gossip_queries. The default strategy used by this implementation
246 /// is to sync the full block range with several peers.
248 /// We should expect one or more reply_channel_range messages in response
249 /// to our query_channel_range. Each reply will enqueue a query_scid message
250 /// to request gossip messages for each channel. The sync is considered complete
251 /// when the final reply_scids_end message is received, though we are not
252 /// tracking this directly.
253 fn sync_routing_table(&self, their_node_id: &PublicKey, init_msg: &Init) {
255 // We will only perform a sync with peers that support gossip_queries.
256 if !init_msg.features.supports_gossip_queries() {
260 // Check if we need to perform a full synchronization with this peer
261 if !self.should_request_full_sync(their_node_id) {
265 let first_blocknum = 0;
266 let number_of_blocks = 0xffffffff;
267 log_debug!(self.logger, "Sending query_channel_range peer={}, first_blocknum={}, number_of_blocks={}", log_pubkey!(their_node_id), first_blocknum, number_of_blocks);
268 let mut pending_events = self.pending_events.lock().unwrap();
269 pending_events.push(MessageSendEvent::SendChannelRangeQuery {
270 node_id: their_node_id.clone(),
271 msg: QueryChannelRange {
272 chain_hash: self.network_graph.read().unwrap().genesis_hash,
279 /// Statelessly processes a reply to a channel range query by immediately
280 /// sending an SCID query with SCIDs in the reply. To keep this handler
281 /// stateless, it does not validate the sequencing of replies for multi-
282 /// reply ranges. It does not validate whether the reply(ies) cover the
283 /// queried range. It also does not filter SCIDs to only those in the
284 /// original query range. We also do not validate that the chain_hash
285 /// matches the chain_hash of the NetworkGraph. Any chan_ann message that
286 /// does not match our chain_hash will be rejected when the announcement is
288 fn handle_reply_channel_range(&self, their_node_id: &PublicKey, msg: ReplyChannelRange) -> Result<(), LightningError> {
289 log_debug!(self.logger, "Handling reply_channel_range peer={}, first_blocknum={}, number_of_blocks={}, sync_complete={}, scids={}", log_pubkey!(their_node_id), msg.first_blocknum, msg.number_of_blocks, msg.sync_complete, msg.short_channel_ids.len(),);
291 log_debug!(self.logger, "Sending query_short_channel_ids peer={}, batch_size={}", log_pubkey!(their_node_id), msg.short_channel_ids.len());
292 let mut pending_events = self.pending_events.lock().unwrap();
293 pending_events.push(MessageSendEvent::SendShortIdsQuery {
294 node_id: their_node_id.clone(),
295 msg: QueryShortChannelIds {
296 chain_hash: msg.chain_hash,
297 short_channel_ids: msg.short_channel_ids,
304 /// When an SCID query is initiated the remote peer will begin streaming
305 /// gossip messages. In the event of a failure, we may have received
306 /// some channel information. Before trying with another peer, the
307 /// caller should update its set of SCIDs that need to be queried.
308 fn handle_reply_short_channel_ids_end(&self, their_node_id: &PublicKey, msg: ReplyShortChannelIdsEnd) -> Result<(), LightningError> {
309 log_debug!(self.logger, "Handling reply_short_channel_ids_end peer={}, full_information={}", log_pubkey!(their_node_id), msg.full_information);
311 // If the remote node does not have up-to-date information for the
312 // chain_hash they will set full_information=false. We can fail
313 // the result and try again with a different peer.
314 if !msg.full_information {
315 return Err(LightningError {
316 err: String::from("Received reply_short_channel_ids_end with no information"),
317 action: ErrorAction::IgnoreError
324 /// Processes a query from a peer by finding announced/public channels whose funding UTXOs
325 /// are in the specified block range. Due to message size limits, large range
326 /// queries may result in several reply messages. This implementation enqueues
327 /// all reply messages into pending events. Each message will allocate just under 65KiB. A full
328 /// sync of the public routing table with 128k channels will generated 16 messages and allocate ~1MB.
329 /// Logic can be changed to reduce allocation if/when a full sync of the routing table impacts
330 /// memory constrained systems.
331 fn handle_query_channel_range(&self, their_node_id: &PublicKey, msg: QueryChannelRange) -> Result<(), LightningError> {
332 log_debug!(self.logger, "Handling query_channel_range peer={}, first_blocknum={}, number_of_blocks={}", log_pubkey!(their_node_id), msg.first_blocknum, msg.number_of_blocks);
334 let network_graph = self.network_graph.read().unwrap();
336 let inclusive_start_scid = scid_from_parts(msg.first_blocknum as u64, 0, 0);
338 // We might receive valid queries with end_blocknum that would overflow SCID conversion.
339 // If so, we manually cap the ending block to avoid this overflow.
340 let exclusive_end_scid = scid_from_parts(cmp::min(msg.end_blocknum() as u64, MAX_SCID_BLOCK), 0, 0);
342 // Per spec, we must reply to a query. Send an empty message when things are invalid.
343 if msg.chain_hash != network_graph.genesis_hash || inclusive_start_scid.is_err() || exclusive_end_scid.is_err() || msg.number_of_blocks == 0 {
344 let mut pending_events = self.pending_events.lock().unwrap();
345 pending_events.push(MessageSendEvent::SendReplyChannelRange {
346 node_id: their_node_id.clone(),
347 msg: ReplyChannelRange {
348 chain_hash: msg.chain_hash.clone(),
349 first_blocknum: msg.first_blocknum,
350 number_of_blocks: msg.number_of_blocks,
352 short_channel_ids: vec![],
355 return Err(LightningError {
356 err: String::from("query_channel_range could not be processed"),
357 action: ErrorAction::IgnoreError,
361 // Creates channel batches. We are not checking if the channel is routable
362 // (has at least one update). A peer may still want to know the channel
363 // exists even if its not yet routable.
364 let mut batches: Vec<Vec<u64>> = vec![Vec::with_capacity(MAX_SCIDS_PER_REPLY)];
365 for (_, ref chan) in network_graph.get_channels().range(inclusive_start_scid.unwrap()..exclusive_end_scid.unwrap()) {
366 if let Some(chan_announcement) = &chan.announcement_message {
367 // Construct a new batch if last one is full
368 if batches.last().unwrap().len() == batches.last().unwrap().capacity() {
369 batches.push(Vec::with_capacity(MAX_SCIDS_PER_REPLY));
372 let batch = batches.last_mut().unwrap();
373 batch.push(chan_announcement.contents.short_channel_id);
378 let mut pending_events = self.pending_events.lock().unwrap();
379 let batch_count = batches.len();
380 let mut prev_batch_endblock = msg.first_blocknum;
381 for (batch_index, batch) in batches.into_iter().enumerate() {
382 // Per spec, the initial `first_blocknum` needs to be <= the query's `first_blocknum`
383 // and subsequent `first_blocknum`s must be >= the prior reply's `first_blocknum`.
385 // Additionally, c-lightning versions < 0.10 require that the `first_blocknum` of each
386 // reply is >= the previous reply's `first_blocknum` and either exactly the previous
387 // reply's `first_blocknum + number_of_blocks` or exactly one greater. This is a
388 // significant diversion from the requirements set by the spec, and, in case of blocks
389 // with no channel opens (e.g. empty blocks), requires that we use the previous value
390 // and *not* derive the first_blocknum from the actual first block of the reply.
391 let first_blocknum = prev_batch_endblock;
393 // Each message carries the number of blocks (from the `first_blocknum`) its contents
394 // fit in. Though there is no requirement that we use exactly the number of blocks its
395 // contents are from, except for the bogus requirements c-lightning enforces, above.
397 // Per spec, the last end block (ie `first_blocknum + number_of_blocks`) needs to be
398 // >= the query's end block. Thus, for the last reply, we calculate the difference
399 // between the query's end block and the start of the reply.
401 // Overflow safe since end_blocknum=msg.first_block_num+msg.number_of_blocks and
402 // first_blocknum will be either msg.first_blocknum or a higher block height.
403 let (sync_complete, number_of_blocks) = if batch_index == batch_count-1 {
404 (true, msg.end_blocknum() - first_blocknum)
406 // Prior replies should use the number of blocks that fit into the reply. Overflow
407 // safe since first_blocknum is always <= last SCID's block.
409 (false, block_from_scid(batch.last().unwrap()) - first_blocknum)
412 prev_batch_endblock = first_blocknum + number_of_blocks;
414 pending_events.push(MessageSendEvent::SendReplyChannelRange {
415 node_id: their_node_id.clone(),
416 msg: ReplyChannelRange {
417 chain_hash: msg.chain_hash.clone(),
421 short_channel_ids: batch,
429 fn handle_query_short_channel_ids(&self, _their_node_id: &PublicKey, _msg: QueryShortChannelIds) -> Result<(), LightningError> {
432 err: String::from("Not implemented"),
433 action: ErrorAction::IgnoreError,
438 impl<C: Deref, L: Deref> MessageSendEventsProvider for NetGraphMsgHandler<C, L>
440 C::Target: chain::Access,
443 fn get_and_clear_pending_msg_events(&self) -> Vec<MessageSendEvent> {
444 let mut ret = Vec::new();
445 let mut pending_events = self.pending_events.lock().unwrap();
446 core::mem::swap(&mut ret, &mut pending_events);
451 #[derive(Clone, Debug, PartialEq)]
452 /// Details about one direction of a channel. Received
453 /// within a channel update.
454 pub struct DirectionalChannelInfo {
455 /// When the last update to the channel direction was issued.
456 /// Value is opaque, as set in the announcement.
457 pub last_update: u32,
458 /// Whether the channel can be currently used for payments (in this one direction).
460 /// The difference in CLTV values that you must have when routing through this channel.
461 pub cltv_expiry_delta: u16,
462 /// The minimum value, which must be relayed to the next hop via the channel
463 pub htlc_minimum_msat: u64,
464 /// The maximum value which may be relayed to the next hop via the channel.
465 pub htlc_maximum_msat: Option<u64>,
466 /// Fees charged when the channel is used for routing
467 pub fees: RoutingFees,
468 /// Most recent update for the channel received from the network
469 /// Mostly redundant with the data we store in fields explicitly.
470 /// Everything else is useful only for sending out for initial routing sync.
471 /// Not stored if contains excess data to prevent DoS.
472 pub last_update_message: Option<ChannelUpdate>,
475 impl fmt::Display for DirectionalChannelInfo {
476 fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
477 write!(f, "last_update {}, enabled {}, cltv_expiry_delta {}, htlc_minimum_msat {}, fees {:?}", self.last_update, self.enabled, self.cltv_expiry_delta, self.htlc_minimum_msat, self.fees)?;
482 impl_writeable_tlv_based!(DirectionalChannelInfo, {
483 (0, last_update, required),
484 (2, enabled, required),
485 (4, cltv_expiry_delta, required),
486 (6, htlc_minimum_msat, required),
487 (8, htlc_maximum_msat, required),
488 (10, fees, required),
489 (12, last_update_message, required),
492 #[derive(Clone, Debug, PartialEq)]
493 /// Details about a channel (both directions).
494 /// Received within a channel announcement.
495 pub struct ChannelInfo {
496 /// Protocol features of a channel communicated during its announcement
497 pub features: ChannelFeatures,
498 /// Source node of the first direction of a channel
499 pub node_one: PublicKey,
500 /// Details about the first direction of a channel
501 pub one_to_two: Option<DirectionalChannelInfo>,
502 /// Source node of the second direction of a channel
503 pub node_two: PublicKey,
504 /// Details about the second direction of a channel
505 pub two_to_one: Option<DirectionalChannelInfo>,
506 /// The channel capacity as seen on-chain, if chain lookup is available.
507 pub capacity_sats: Option<u64>,
508 /// An initial announcement of the channel
509 /// Mostly redundant with the data we store in fields explicitly.
510 /// Everything else is useful only for sending out for initial routing sync.
511 /// Not stored if contains excess data to prevent DoS.
512 pub announcement_message: Option<ChannelAnnouncement>,
515 impl fmt::Display for ChannelInfo {
516 fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
517 write!(f, "features: {}, node_one: {}, one_to_two: {:?}, node_two: {}, two_to_one: {:?}",
518 log_bytes!(self.features.encode()), log_pubkey!(self.node_one), self.one_to_two, log_pubkey!(self.node_two), self.two_to_one)?;
523 impl_writeable_tlv_based!(ChannelInfo, {
524 (0, features, required),
525 (2, node_one, required),
526 (4, one_to_two, required),
527 (6, node_two, required),
528 (8, two_to_one, required),
529 (10, capacity_sats, required),
530 (12, announcement_message, required),
534 /// Fees for routing via a given channel or a node
535 #[derive(Eq, PartialEq, Copy, Clone, Debug)]
536 pub struct RoutingFees {
537 /// Flat routing fee in satoshis
539 /// Liquidity-based routing fee in millionths of a routed amount.
540 /// In other words, 10000 is 1%.
541 pub proportional_millionths: u32,
544 impl_writeable_tlv_based!(RoutingFees, {
545 (0, base_msat, required),
546 (2, proportional_millionths, required)
549 #[derive(Clone, Debug, PartialEq)]
550 /// Information received in the latest node_announcement from this node.
551 pub struct NodeAnnouncementInfo {
552 /// Protocol features the node announced support for
553 pub features: NodeFeatures,
554 /// When the last known update to the node state was issued.
555 /// Value is opaque, as set in the announcement.
556 pub last_update: u32,
557 /// Color assigned to the node
559 /// Moniker assigned to the node.
560 /// May be invalid or malicious (eg control chars),
561 /// should not be exposed to the user.
563 /// Internet-level addresses via which one can connect to the node
564 pub addresses: Vec<NetAddress>,
565 /// An initial announcement of the node
566 /// Mostly redundant with the data we store in fields explicitly.
567 /// Everything else is useful only for sending out for initial routing sync.
568 /// Not stored if contains excess data to prevent DoS.
569 pub announcement_message: Option<NodeAnnouncement>
572 impl_writeable_tlv_based!(NodeAnnouncementInfo, {
573 (0, features, required),
574 (2, last_update, required),
576 (6, alias, required),
577 (8, announcement_message, option),
578 (10, addresses, vec_type),
581 #[derive(Clone, Debug, PartialEq)]
582 /// Details about a node in the network, known from the network announcement.
583 pub struct NodeInfo {
584 /// All valid channels a node has announced
585 pub channels: Vec<u64>,
586 /// Lowest fees enabling routing via any of the enabled, known channels to a node.
587 /// The two fields (flat and proportional fee) are independent,
588 /// meaning they don't have to refer to the same channel.
589 pub lowest_inbound_channel_fees: Option<RoutingFees>,
590 /// More information about a node from node_announcement.
591 /// Optional because we store a Node entry after learning about it from
592 /// a channel announcement, but before receiving a node announcement.
593 pub announcement_info: Option<NodeAnnouncementInfo>
596 impl fmt::Display for NodeInfo {
597 fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
598 write!(f, "lowest_inbound_channel_fees: {:?}, channels: {:?}, announcement_info: {:?}",
599 self.lowest_inbound_channel_fees, &self.channels[..], self.announcement_info)?;
604 impl_writeable_tlv_based!(NodeInfo, {
605 (0, lowest_inbound_channel_fees, option),
606 (2, announcement_info, option),
607 (4, channels, vec_type),
610 const SERIALIZATION_VERSION: u8 = 1;
611 const MIN_SERIALIZATION_VERSION: u8 = 1;
613 impl Writeable for NetworkGraph {
614 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
615 write_ver_prefix!(writer, SERIALIZATION_VERSION, MIN_SERIALIZATION_VERSION);
617 self.genesis_hash.write(writer)?;
618 (self.channels.len() as u64).write(writer)?;
619 for (ref chan_id, ref chan_info) in self.channels.iter() {
620 (*chan_id).write(writer)?;
621 chan_info.write(writer)?;
623 (self.nodes.len() as u64).write(writer)?;
624 for (ref node_id, ref node_info) in self.nodes.iter() {
625 node_id.write(writer)?;
626 node_info.write(writer)?;
629 write_tlv_fields!(writer, {});
634 impl Readable for NetworkGraph {
635 fn read<R: ::std::io::Read>(reader: &mut R) -> Result<NetworkGraph, DecodeError> {
636 let _ver = read_ver_prefix!(reader, SERIALIZATION_VERSION);
638 let genesis_hash: BlockHash = Readable::read(reader)?;
639 let channels_count: u64 = Readable::read(reader)?;
640 let mut channels = BTreeMap::new();
641 for _ in 0..channels_count {
642 let chan_id: u64 = Readable::read(reader)?;
643 let chan_info = Readable::read(reader)?;
644 channels.insert(chan_id, chan_info);
646 let nodes_count: u64 = Readable::read(reader)?;
647 let mut nodes = BTreeMap::new();
648 for _ in 0..nodes_count {
649 let node_id = Readable::read(reader)?;
650 let node_info = Readable::read(reader)?;
651 nodes.insert(node_id, node_info);
653 read_tlv_fields!(reader, {});
663 impl fmt::Display for NetworkGraph {
664 fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
665 writeln!(f, "Network map\n[Channels]")?;
666 for (key, val) in self.channels.iter() {
667 writeln!(f, " {}: {}", key, val)?;
669 writeln!(f, "[Nodes]")?;
670 for (key, val) in self.nodes.iter() {
671 writeln!(f, " {}: {}", log_pubkey!(key), val)?;
678 /// Returns all known valid channels' short ids along with announced channel info.
680 /// (C-not exported) because we have no mapping for `BTreeMap`s
681 pub fn get_channels<'a>(&'a self) -> &'a BTreeMap<u64, ChannelInfo> { &self.channels }
682 /// Returns all known nodes' public keys along with announced node info.
684 /// (C-not exported) because we have no mapping for `BTreeMap`s
685 pub fn get_nodes<'a>(&'a self) -> &'a BTreeMap<PublicKey, NodeInfo> { &self.nodes }
687 /// Get network addresses by node id.
688 /// Returns None if the requested node is completely unknown,
689 /// or if node announcement for the node was never received.
691 /// (C-not exported) as there is no practical way to track lifetimes of returned values.
692 pub fn get_addresses<'a>(&'a self, pubkey: &PublicKey) -> Option<&'a Vec<NetAddress>> {
693 if let Some(node) = self.nodes.get(pubkey) {
694 if let Some(node_info) = node.announcement_info.as_ref() {
695 return Some(&node_info.addresses)
701 /// Creates a new, empty, network graph.
702 pub fn new(genesis_hash: BlockHash) -> NetworkGraph {
705 channels: BTreeMap::new(),
706 nodes: BTreeMap::new(),
710 /// For an already known node (from channel announcements), update its stored properties from a
711 /// given node announcement.
713 /// You probably don't want to call this directly, instead relying on a NetGraphMsgHandler's
714 /// RoutingMessageHandler implementation to call it indirectly. This may be useful to accept
715 /// routing messages from a source using a protocol other than the lightning P2P protocol.
716 pub fn update_node_from_announcement<T: secp256k1::Verification>(&mut self, msg: &msgs::NodeAnnouncement, secp_ctx: &Secp256k1<T>) -> Result<(), LightningError> {
717 let msg_hash = hash_to_message!(&Sha256dHash::hash(&msg.contents.encode()[..])[..]);
718 secp_verify_sig!(secp_ctx, &msg_hash, &msg.signature, &msg.contents.node_id);
719 self.update_node_from_announcement_intern(&msg.contents, Some(&msg))
722 /// For an already known node (from channel announcements), update its stored properties from a
723 /// given node announcement without verifying the associated signatures. Because we aren't
724 /// given the associated signatures here we cannot relay the node announcement to any of our
726 pub fn update_node_from_unsigned_announcement(&mut self, msg: &msgs::UnsignedNodeAnnouncement) -> Result<(), LightningError> {
727 self.update_node_from_announcement_intern(msg, None)
730 fn update_node_from_announcement_intern(&mut self, msg: &msgs::UnsignedNodeAnnouncement, full_msg: Option<&msgs::NodeAnnouncement>) -> Result<(), LightningError> {
731 match self.nodes.get_mut(&msg.node_id) {
732 None => Err(LightningError{err: "No existing channels for node_announcement".to_owned(), action: ErrorAction::IgnoreError}),
734 if let Some(node_info) = node.announcement_info.as_ref() {
735 if node_info.last_update >= msg.timestamp {
736 return Err(LightningError{err: "Update older than last processed update".to_owned(), action: ErrorAction::IgnoreAndLog(Level::Trace)});
741 msg.excess_data.len() <= MAX_EXCESS_BYTES_FOR_RELAY &&
742 msg.excess_address_data.len() <= MAX_EXCESS_BYTES_FOR_RELAY &&
743 msg.excess_data.len() + msg.excess_address_data.len() <= MAX_EXCESS_BYTES_FOR_RELAY;
744 node.announcement_info = Some(NodeAnnouncementInfo {
745 features: msg.features.clone(),
746 last_update: msg.timestamp,
749 addresses: msg.addresses.clone(),
750 announcement_message: if should_relay { full_msg.cloned() } else { None },
758 /// Store or update channel info from a channel announcement.
760 /// You probably don't want to call this directly, instead relying on a NetGraphMsgHandler's
761 /// RoutingMessageHandler implementation to call it indirectly. This may be useful to accept
762 /// routing messages from a source using a protocol other than the lightning P2P protocol.
764 /// If a `chain::Access` object is provided via `chain_access`, it will be called to verify
765 /// the corresponding UTXO exists on chain and is correctly-formatted.
766 pub fn update_channel_from_announcement<T: secp256k1::Verification, C: Deref>
767 (&mut self, msg: &msgs::ChannelAnnouncement, chain_access: &Option<C>, secp_ctx: &Secp256k1<T>)
768 -> Result<(), LightningError>
769 where C::Target: chain::Access {
770 let msg_hash = hash_to_message!(&Sha256dHash::hash(&msg.contents.encode()[..])[..]);
771 secp_verify_sig!(secp_ctx, &msg_hash, &msg.node_signature_1, &msg.contents.node_id_1);
772 secp_verify_sig!(secp_ctx, &msg_hash, &msg.node_signature_2, &msg.contents.node_id_2);
773 secp_verify_sig!(secp_ctx, &msg_hash, &msg.bitcoin_signature_1, &msg.contents.bitcoin_key_1);
774 secp_verify_sig!(secp_ctx, &msg_hash, &msg.bitcoin_signature_2, &msg.contents.bitcoin_key_2);
775 self.update_channel_from_unsigned_announcement_intern(&msg.contents, Some(msg), chain_access)
778 /// Store or update channel info from a channel announcement without verifying the associated
779 /// signatures. Because we aren't given the associated signatures here we cannot relay the
780 /// channel announcement to any of our peers.
782 /// If a `chain::Access` object is provided via `chain_access`, it will be called to verify
783 /// the corresponding UTXO exists on chain and is correctly-formatted.
784 pub fn update_channel_from_unsigned_announcement<C: Deref>
785 (&mut self, msg: &msgs::UnsignedChannelAnnouncement, chain_access: &Option<C>)
786 -> Result<(), LightningError>
787 where C::Target: chain::Access {
788 self.update_channel_from_unsigned_announcement_intern(msg, None, chain_access)
791 fn update_channel_from_unsigned_announcement_intern<C: Deref>
792 (&mut self, msg: &msgs::UnsignedChannelAnnouncement, full_msg: Option<&msgs::ChannelAnnouncement>, chain_access: &Option<C>)
793 -> Result<(), LightningError>
794 where C::Target: chain::Access {
795 if msg.node_id_1 == msg.node_id_2 || msg.bitcoin_key_1 == msg.bitcoin_key_2 {
796 return Err(LightningError{err: "Channel announcement node had a channel with itself".to_owned(), action: ErrorAction::IgnoreError});
799 let utxo_value = match &chain_access {
801 // Tentatively accept, potentially exposing us to DoS attacks
804 &Some(ref chain_access) => {
805 match chain_access.get_utxo(&msg.chain_hash, msg.short_channel_id) {
806 Ok(TxOut { value, script_pubkey }) => {
807 let expected_script = Builder::new().push_opcode(opcodes::all::OP_PUSHNUM_2)
808 .push_slice(&msg.bitcoin_key_1.serialize())
809 .push_slice(&msg.bitcoin_key_2.serialize())
810 .push_opcode(opcodes::all::OP_PUSHNUM_2)
811 .push_opcode(opcodes::all::OP_CHECKMULTISIG).into_script().to_v0_p2wsh();
812 if script_pubkey != expected_script {
813 return Err(LightningError{err: format!("Channel announcement key ({}) didn't match on-chain script ({})", script_pubkey.to_hex(), expected_script.to_hex()), action: ErrorAction::IgnoreError});
815 //TODO: Check if value is worth storing, use it to inform routing, and compare it
816 //to the new HTLC max field in channel_update
819 Err(chain::AccessError::UnknownChain) => {
820 return Err(LightningError{err: format!("Channel announced on an unknown chain ({})", msg.chain_hash.encode().to_hex()), action: ErrorAction::IgnoreError});
822 Err(chain::AccessError::UnknownTx) => {
823 return Err(LightningError{err: "Channel announced without corresponding UTXO entry".to_owned(), action: ErrorAction::IgnoreError});
829 let chan_info = ChannelInfo {
830 features: msg.features.clone(),
831 node_one: msg.node_id_1.clone(),
833 node_two: msg.node_id_2.clone(),
835 capacity_sats: utxo_value,
836 announcement_message: if msg.excess_data.len() <= MAX_EXCESS_BYTES_FOR_RELAY
837 { full_msg.cloned() } else { None },
840 match self.channels.entry(msg.short_channel_id) {
841 BtreeEntry::Occupied(mut entry) => {
842 //TODO: because asking the blockchain if short_channel_id is valid is only optional
843 //in the blockchain API, we need to handle it smartly here, though it's unclear
845 if utxo_value.is_some() {
846 // Either our UTXO provider is busted, there was a reorg, or the UTXO provider
847 // only sometimes returns results. In any case remove the previous entry. Note
848 // that the spec expects us to "blacklist" the node_ids involved, but we can't
850 // a) we don't *require* a UTXO provider that always returns results.
851 // b) we don't track UTXOs of channels we know about and remove them if they
853 // c) it's unclear how to do so without exposing ourselves to massive DoS risk.
854 Self::remove_channel_in_nodes(&mut self.nodes, &entry.get(), msg.short_channel_id);
855 *entry.get_mut() = chan_info;
857 return Err(LightningError{err: "Already have knowledge of channel".to_owned(), action: ErrorAction::IgnoreAndLog(Level::Trace)})
860 BtreeEntry::Vacant(entry) => {
861 entry.insert(chan_info);
865 macro_rules! add_channel_to_node {
866 ( $node_id: expr ) => {
867 match self.nodes.entry($node_id) {
868 BtreeEntry::Occupied(node_entry) => {
869 node_entry.into_mut().channels.push(msg.short_channel_id);
871 BtreeEntry::Vacant(node_entry) => {
872 node_entry.insert(NodeInfo {
873 channels: vec!(msg.short_channel_id),
874 lowest_inbound_channel_fees: None,
875 announcement_info: None,
882 add_channel_to_node!(msg.node_id_1);
883 add_channel_to_node!(msg.node_id_2);
888 /// Close a channel if a corresponding HTLC fail was sent.
889 /// If permanent, removes a channel from the local storage.
890 /// May cause the removal of nodes too, if this was their last channel.
891 /// If not permanent, makes channels unavailable for routing.
892 pub fn close_channel_from_update(&mut self, short_channel_id: u64, is_permanent: bool) {
894 if let Some(chan) = self.channels.remove(&short_channel_id) {
895 Self::remove_channel_in_nodes(&mut self.nodes, &chan, short_channel_id);
898 if let Some(chan) = self.channels.get_mut(&short_channel_id) {
899 if let Some(one_to_two) = chan.one_to_two.as_mut() {
900 one_to_two.enabled = false;
902 if let Some(two_to_one) = chan.two_to_one.as_mut() {
903 two_to_one.enabled = false;
909 fn fail_node(&mut self, _node_id: &PublicKey, is_permanent: bool) {
911 // TODO: Wholly remove the node
913 // TODO: downgrade the node
917 /// For an already known (from announcement) channel, update info about one of the directions
920 /// You probably don't want to call this directly, instead relying on a NetGraphMsgHandler's
921 /// RoutingMessageHandler implementation to call it indirectly. This may be useful to accept
922 /// routing messages from a source using a protocol other than the lightning P2P protocol.
923 pub fn update_channel<T: secp256k1::Verification>(&mut self, msg: &msgs::ChannelUpdate, secp_ctx: &Secp256k1<T>) -> Result<(), LightningError> {
924 self.update_channel_intern(&msg.contents, Some(&msg), Some((&msg.signature, secp_ctx)))
927 /// For an already known (from announcement) channel, update info about one of the directions
928 /// of the channel without verifying the associated signatures. Because we aren't given the
929 /// associated signatures here we cannot relay the channel update to any of our peers.
930 pub fn update_channel_unsigned(&mut self, msg: &msgs::UnsignedChannelUpdate) -> Result<(), LightningError> {
931 self.update_channel_intern(msg, None, None::<(&secp256k1::Signature, &Secp256k1<secp256k1::VerifyOnly>)>)
934 fn update_channel_intern<T: secp256k1::Verification>(&mut self, msg: &msgs::UnsignedChannelUpdate, full_msg: Option<&msgs::ChannelUpdate>, sig_info: Option<(&secp256k1::Signature, &Secp256k1<T>)>) -> Result<(), LightningError> {
936 let chan_enabled = msg.flags & (1 << 1) != (1 << 1);
937 let chan_was_enabled;
939 match self.channels.get_mut(&msg.short_channel_id) {
940 None => return Err(LightningError{err: "Couldn't find channel for update".to_owned(), action: ErrorAction::IgnoreError}),
942 if let OptionalField::Present(htlc_maximum_msat) = msg.htlc_maximum_msat {
943 if htlc_maximum_msat > MAX_VALUE_MSAT {
944 return Err(LightningError{err: "htlc_maximum_msat is larger than maximum possible msats".to_owned(), action: ErrorAction::IgnoreError});
947 if let Some(capacity_sats) = channel.capacity_sats {
948 // It's possible channel capacity is available now, although it wasn't available at announcement (so the field is None).
949 // Don't query UTXO set here to reduce DoS risks.
950 if capacity_sats > MAX_VALUE_MSAT / 1000 || htlc_maximum_msat > capacity_sats * 1000 {
951 return Err(LightningError{err: "htlc_maximum_msat is larger than channel capacity or capacity is bogus".to_owned(), action: ErrorAction::IgnoreError});
955 macro_rules! maybe_update_channel_info {
956 ( $target: expr, $src_node: expr) => {
957 if let Some(existing_chan_info) = $target.as_ref() {
958 if existing_chan_info.last_update >= msg.timestamp {
959 return Err(LightningError{err: "Update older than last processed update".to_owned(), action: ErrorAction::IgnoreAndLog(Level::Trace)});
961 chan_was_enabled = existing_chan_info.enabled;
963 chan_was_enabled = false;
966 let last_update_message = if msg.excess_data.len() <= MAX_EXCESS_BYTES_FOR_RELAY
967 { full_msg.cloned() } else { None };
969 let updated_channel_dir_info = DirectionalChannelInfo {
970 enabled: chan_enabled,
971 last_update: msg.timestamp,
972 cltv_expiry_delta: msg.cltv_expiry_delta,
973 htlc_minimum_msat: msg.htlc_minimum_msat,
974 htlc_maximum_msat: if let OptionalField::Present(max_value) = msg.htlc_maximum_msat { Some(max_value) } else { None },
976 base_msat: msg.fee_base_msat,
977 proportional_millionths: msg.fee_proportional_millionths,
981 $target = Some(updated_channel_dir_info);
985 let msg_hash = hash_to_message!(&Sha256dHash::hash(&msg.encode()[..])[..]);
986 if msg.flags & 1 == 1 {
987 dest_node_id = channel.node_one.clone();
988 if let Some((sig, ctx)) = sig_info {
989 secp_verify_sig!(ctx, &msg_hash, &sig, &channel.node_two);
991 maybe_update_channel_info!(channel.two_to_one, channel.node_two);
993 dest_node_id = channel.node_two.clone();
994 if let Some((sig, ctx)) = sig_info {
995 secp_verify_sig!(ctx, &msg_hash, &sig, &channel.node_one);
997 maybe_update_channel_info!(channel.one_to_two, channel.node_one);
1003 let node = self.nodes.get_mut(&dest_node_id).unwrap();
1004 let mut base_msat = msg.fee_base_msat;
1005 let mut proportional_millionths = msg.fee_proportional_millionths;
1006 if let Some(fees) = node.lowest_inbound_channel_fees {
1007 base_msat = cmp::min(base_msat, fees.base_msat);
1008 proportional_millionths = cmp::min(proportional_millionths, fees.proportional_millionths);
1010 node.lowest_inbound_channel_fees = Some(RoutingFees {
1012 proportional_millionths
1014 } else if chan_was_enabled {
1015 let node = self.nodes.get_mut(&dest_node_id).unwrap();
1016 let mut lowest_inbound_channel_fees = None;
1018 for chan_id in node.channels.iter() {
1019 let chan = self.channels.get(chan_id).unwrap();
1021 if chan.node_one == dest_node_id {
1022 chan_info_opt = chan.two_to_one.as_ref();
1024 chan_info_opt = chan.one_to_two.as_ref();
1026 if let Some(chan_info) = chan_info_opt {
1027 if chan_info.enabled {
1028 let fees = lowest_inbound_channel_fees.get_or_insert(RoutingFees {
1029 base_msat: u32::max_value(), proportional_millionths: u32::max_value() });
1030 fees.base_msat = cmp::min(fees.base_msat, chan_info.fees.base_msat);
1031 fees.proportional_millionths = cmp::min(fees.proportional_millionths, chan_info.fees.proportional_millionths);
1036 node.lowest_inbound_channel_fees = lowest_inbound_channel_fees;
1042 fn remove_channel_in_nodes(nodes: &mut BTreeMap<PublicKey, NodeInfo>, chan: &ChannelInfo, short_channel_id: u64) {
1043 macro_rules! remove_from_node {
1044 ($node_id: expr) => {
1045 if let BtreeEntry::Occupied(mut entry) = nodes.entry($node_id) {
1046 entry.get_mut().channels.retain(|chan_id| {
1047 short_channel_id != *chan_id
1049 if entry.get().channels.is_empty() {
1050 entry.remove_entry();
1053 panic!("Had channel that pointed to unknown node (ie inconsistent network map)!");
1058 remove_from_node!(chan.node_one);
1059 remove_from_node!(chan.node_two);
1066 use ln::features::{ChannelFeatures, InitFeatures, NodeFeatures};
1067 use routing::network_graph::{NetGraphMsgHandler, NetworkGraph, MAX_EXCESS_BYTES_FOR_RELAY};
1068 use ln::msgs::{Init, OptionalField, RoutingMessageHandler, UnsignedNodeAnnouncement, NodeAnnouncement,
1069 UnsignedChannelAnnouncement, ChannelAnnouncement, UnsignedChannelUpdate, ChannelUpdate, HTLCFailChannelUpdate,
1070 ReplyChannelRange, ReplyShortChannelIdsEnd, QueryChannelRange, QueryShortChannelIds, MAX_VALUE_MSAT};
1071 use util::test_utils;
1072 use util::logger::Logger;
1073 use util::ser::{Readable, Writeable};
1074 use util::events::{MessageSendEvent, MessageSendEventsProvider};
1075 use util::scid_utils::scid_from_parts;
1077 use bitcoin::hashes::sha256d::Hash as Sha256dHash;
1078 use bitcoin::hashes::Hash;
1079 use bitcoin::network::constants::Network;
1080 use bitcoin::blockdata::constants::genesis_block;
1081 use bitcoin::blockdata::script::Builder;
1082 use bitcoin::blockdata::transaction::TxOut;
1083 use bitcoin::blockdata::opcodes;
1087 use bitcoin::secp256k1::key::{PublicKey, SecretKey};
1088 use bitcoin::secp256k1::{All, Secp256k1};
1093 fn create_net_graph_msg_handler() -> (Secp256k1<All>, NetGraphMsgHandler<Arc<test_utils::TestChainSource>, Arc<test_utils::TestLogger>>) {
1094 let secp_ctx = Secp256k1::new();
1095 let logger = Arc::new(test_utils::TestLogger::new());
1096 let genesis_hash = genesis_block(Network::Testnet).header.block_hash();
1097 let net_graph_msg_handler = NetGraphMsgHandler::new(genesis_hash, None, Arc::clone(&logger));
1098 (secp_ctx, net_graph_msg_handler)
1102 fn request_full_sync_finite_times() {
1103 let (secp_ctx, net_graph_msg_handler) = create_net_graph_msg_handler();
1104 let node_id = PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&hex::decode("0202020202020202020202020202020202020202020202020202020202020202").unwrap()[..]).unwrap());
1106 assert!(net_graph_msg_handler.should_request_full_sync(&node_id));
1107 assert!(net_graph_msg_handler.should_request_full_sync(&node_id));
1108 assert!(net_graph_msg_handler.should_request_full_sync(&node_id));
1109 assert!(net_graph_msg_handler.should_request_full_sync(&node_id));
1110 assert!(net_graph_msg_handler.should_request_full_sync(&node_id));
1111 assert!(!net_graph_msg_handler.should_request_full_sync(&node_id));
1115 fn handling_node_announcements() {
1116 let (secp_ctx, net_graph_msg_handler) = create_net_graph_msg_handler();
1118 let node_1_privkey = &SecretKey::from_slice(&[42; 32]).unwrap();
1119 let node_2_privkey = &SecretKey::from_slice(&[41; 32]).unwrap();
1120 let node_id_1 = PublicKey::from_secret_key(&secp_ctx, node_1_privkey);
1121 let node_id_2 = PublicKey::from_secret_key(&secp_ctx, node_2_privkey);
1122 let node_1_btckey = &SecretKey::from_slice(&[40; 32]).unwrap();
1123 let node_2_btckey = &SecretKey::from_slice(&[39; 32]).unwrap();
1124 let zero_hash = Sha256dHash::hash(&[0; 32]);
1125 let first_announcement_time = 500;
1127 let mut unsigned_announcement = UnsignedNodeAnnouncement {
1128 features: NodeFeatures::known(),
1129 timestamp: first_announcement_time,
1133 addresses: Vec::new(),
1134 excess_address_data: Vec::new(),
1135 excess_data: Vec::new(),
1137 let mut msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1138 let valid_announcement = NodeAnnouncement {
1139 signature: secp_ctx.sign(&msghash, node_1_privkey),
1140 contents: unsigned_announcement.clone()
1143 match net_graph_msg_handler.handle_node_announcement(&valid_announcement) {
1145 Err(e) => assert_eq!("No existing channels for node_announcement", e.err)
1149 // Announce a channel to add a corresponding node.
1150 let unsigned_announcement = UnsignedChannelAnnouncement {
1151 features: ChannelFeatures::known(),
1152 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1153 short_channel_id: 0,
1156 bitcoin_key_1: PublicKey::from_secret_key(&secp_ctx, node_1_btckey),
1157 bitcoin_key_2: PublicKey::from_secret_key(&secp_ctx, node_2_btckey),
1158 excess_data: Vec::new(),
1161 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1162 let valid_announcement = ChannelAnnouncement {
1163 node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
1164 node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
1165 bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_btckey),
1166 bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_btckey),
1167 contents: unsigned_announcement.clone(),
1169 match net_graph_msg_handler.handle_channel_announcement(&valid_announcement) {
1170 Ok(res) => assert!(res),
1175 match net_graph_msg_handler.handle_node_announcement(&valid_announcement) {
1176 Ok(res) => assert!(res),
1180 let fake_msghash = hash_to_message!(&zero_hash);
1181 match net_graph_msg_handler.handle_node_announcement(
1183 signature: secp_ctx.sign(&fake_msghash, node_1_privkey),
1184 contents: unsigned_announcement.clone()
1187 Err(e) => assert_eq!(e.err, "Invalid signature from remote node")
1190 unsigned_announcement.timestamp += 1000;
1191 unsigned_announcement.excess_data.resize(MAX_EXCESS_BYTES_FOR_RELAY + 1, 0);
1192 msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1193 let announcement_with_data = NodeAnnouncement {
1194 signature: secp_ctx.sign(&msghash, node_1_privkey),
1195 contents: unsigned_announcement.clone()
1197 // Return false because contains excess data.
1198 match net_graph_msg_handler.handle_node_announcement(&announcement_with_data) {
1199 Ok(res) => assert!(!res),
1202 unsigned_announcement.excess_data = Vec::new();
1204 // Even though previous announcement was not relayed further, we still accepted it,
1205 // so we now won't accept announcements before the previous one.
1206 unsigned_announcement.timestamp -= 10;
1207 msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1208 let outdated_announcement = NodeAnnouncement {
1209 signature: secp_ctx.sign(&msghash, node_1_privkey),
1210 contents: unsigned_announcement.clone()
1212 match net_graph_msg_handler.handle_node_announcement(&outdated_announcement) {
1214 Err(e) => assert_eq!(e.err, "Update older than last processed update")
1219 fn handling_channel_announcements() {
1220 let secp_ctx = Secp256k1::new();
1221 let logger: Arc<Logger> = Arc::new(test_utils::TestLogger::new());
1223 let node_1_privkey = &SecretKey::from_slice(&[42; 32]).unwrap();
1224 let node_2_privkey = &SecretKey::from_slice(&[41; 32]).unwrap();
1225 let node_id_1 = PublicKey::from_secret_key(&secp_ctx, node_1_privkey);
1226 let node_id_2 = PublicKey::from_secret_key(&secp_ctx, node_2_privkey);
1227 let node_1_btckey = &SecretKey::from_slice(&[40; 32]).unwrap();
1228 let node_2_btckey = &SecretKey::from_slice(&[39; 32]).unwrap();
1230 let good_script = Builder::new().push_opcode(opcodes::all::OP_PUSHNUM_2)
1231 .push_slice(&PublicKey::from_secret_key(&secp_ctx, node_1_btckey).serialize())
1232 .push_slice(&PublicKey::from_secret_key(&secp_ctx, node_2_btckey).serialize())
1233 .push_opcode(opcodes::all::OP_PUSHNUM_2)
1234 .push_opcode(opcodes::all::OP_CHECKMULTISIG).into_script().to_v0_p2wsh();
1237 let mut unsigned_announcement = UnsignedChannelAnnouncement {
1238 features: ChannelFeatures::known(),
1239 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1240 short_channel_id: 0,
1243 bitcoin_key_1: PublicKey::from_secret_key(&secp_ctx, node_1_btckey),
1244 bitcoin_key_2: PublicKey::from_secret_key(&secp_ctx, node_2_btckey),
1245 excess_data: Vec::new(),
1248 let mut msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1249 let valid_announcement = ChannelAnnouncement {
1250 node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
1251 node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
1252 bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_btckey),
1253 bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_btckey),
1254 contents: unsigned_announcement.clone(),
1257 // Test if the UTXO lookups were not supported
1258 let mut net_graph_msg_handler = NetGraphMsgHandler::new(genesis_block(Network::Testnet).header.block_hash(), None, Arc::clone(&logger));
1259 match net_graph_msg_handler.handle_channel_announcement(&valid_announcement) {
1260 Ok(res) => assert!(res),
1265 let network = net_graph_msg_handler.network_graph.read().unwrap();
1266 match network.get_channels().get(&unsigned_announcement.short_channel_id) {
1272 // If we receive announcement for the same channel (with UTXO lookups disabled),
1273 // drop new one on the floor, since we can't see any changes.
1274 match net_graph_msg_handler.handle_channel_announcement(&valid_announcement) {
1276 Err(e) => assert_eq!(e.err, "Already have knowledge of channel")
1279 // Test if an associated transaction were not on-chain (or not confirmed).
1280 let chain_source = Arc::new(test_utils::TestChainSource::new(Network::Testnet));
1281 *chain_source.utxo_ret.lock().unwrap() = Err(chain::AccessError::UnknownTx);
1282 net_graph_msg_handler = NetGraphMsgHandler::new(chain_source.clone().genesis_hash, Some(chain_source.clone()), Arc::clone(&logger));
1283 unsigned_announcement.short_channel_id += 1;
1285 msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1286 let valid_announcement = ChannelAnnouncement {
1287 node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
1288 node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
1289 bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_btckey),
1290 bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_btckey),
1291 contents: unsigned_announcement.clone(),
1294 match net_graph_msg_handler.handle_channel_announcement(&valid_announcement) {
1296 Err(e) => assert_eq!(e.err, "Channel announced without corresponding UTXO entry")
1299 // Now test if the transaction is found in the UTXO set and the script is correct.
1300 unsigned_announcement.short_channel_id += 1;
1301 *chain_source.utxo_ret.lock().unwrap() = Ok(TxOut { value: 0, script_pubkey: good_script.clone() });
1303 msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1304 let valid_announcement = ChannelAnnouncement {
1305 node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
1306 node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
1307 bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_btckey),
1308 bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_btckey),
1309 contents: unsigned_announcement.clone(),
1311 match net_graph_msg_handler.handle_channel_announcement(&valid_announcement) {
1312 Ok(res) => assert!(res),
1317 let network = net_graph_msg_handler.network_graph.read().unwrap();
1318 match network.get_channels().get(&unsigned_announcement.short_channel_id) {
1324 // If we receive announcement for the same channel (but TX is not confirmed),
1325 // drop new one on the floor, since we can't see any changes.
1326 *chain_source.utxo_ret.lock().unwrap() = Err(chain::AccessError::UnknownTx);
1327 match net_graph_msg_handler.handle_channel_announcement(&valid_announcement) {
1329 Err(e) => assert_eq!(e.err, "Channel announced without corresponding UTXO entry")
1332 // But if it is confirmed, replace the channel
1333 *chain_source.utxo_ret.lock().unwrap() = Ok(TxOut { value: 0, script_pubkey: good_script });
1334 unsigned_announcement.features = ChannelFeatures::empty();
1335 msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1336 let valid_announcement = ChannelAnnouncement {
1337 node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
1338 node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
1339 bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_btckey),
1340 bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_btckey),
1341 contents: unsigned_announcement.clone(),
1343 match net_graph_msg_handler.handle_channel_announcement(&valid_announcement) {
1344 Ok(res) => assert!(res),
1348 let network = net_graph_msg_handler.network_graph.read().unwrap();
1349 match network.get_channels().get(&unsigned_announcement.short_channel_id) {
1350 Some(channel_entry) => {
1351 assert_eq!(channel_entry.features, ChannelFeatures::empty());
1357 // Don't relay valid channels with excess data
1358 unsigned_announcement.short_channel_id += 1;
1359 unsigned_announcement.excess_data.resize(MAX_EXCESS_BYTES_FOR_RELAY + 1, 0);
1360 msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1361 let valid_announcement = ChannelAnnouncement {
1362 node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
1363 node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
1364 bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_btckey),
1365 bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_btckey),
1366 contents: unsigned_announcement.clone(),
1368 match net_graph_msg_handler.handle_channel_announcement(&valid_announcement) {
1369 Ok(res) => assert!(!res),
1373 unsigned_announcement.excess_data = Vec::new();
1374 let invalid_sig_announcement = ChannelAnnouncement {
1375 node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
1376 node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
1377 bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_btckey),
1378 bitcoin_signature_2: secp_ctx.sign(&msghash, node_1_btckey),
1379 contents: unsigned_announcement.clone(),
1381 match net_graph_msg_handler.handle_channel_announcement(&invalid_sig_announcement) {
1383 Err(e) => assert_eq!(e.err, "Invalid signature from remote node")
1386 unsigned_announcement.node_id_1 = PublicKey::from_secret_key(&secp_ctx, node_2_privkey);
1387 msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1388 let channel_to_itself_announcement = ChannelAnnouncement {
1389 node_signature_1: secp_ctx.sign(&msghash, node_2_privkey),
1390 node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
1391 bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_btckey),
1392 bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_btckey),
1393 contents: unsigned_announcement.clone(),
1395 match net_graph_msg_handler.handle_channel_announcement(&channel_to_itself_announcement) {
1397 Err(e) => assert_eq!(e.err, "Channel announcement node had a channel with itself")
1402 fn handling_channel_update() {
1403 let secp_ctx = Secp256k1::new();
1404 let logger: Arc<Logger> = Arc::new(test_utils::TestLogger::new());
1405 let chain_source = Arc::new(test_utils::TestChainSource::new(Network::Testnet));
1406 let net_graph_msg_handler = NetGraphMsgHandler::new(genesis_block(Network::Testnet).header.block_hash(), Some(chain_source.clone()), Arc::clone(&logger));
1408 let node_1_privkey = &SecretKey::from_slice(&[42; 32]).unwrap();
1409 let node_2_privkey = &SecretKey::from_slice(&[41; 32]).unwrap();
1410 let node_id_1 = PublicKey::from_secret_key(&secp_ctx, node_1_privkey);
1411 let node_id_2 = PublicKey::from_secret_key(&secp_ctx, node_2_privkey);
1412 let node_1_btckey = &SecretKey::from_slice(&[40; 32]).unwrap();
1413 let node_2_btckey = &SecretKey::from_slice(&[39; 32]).unwrap();
1415 let zero_hash = Sha256dHash::hash(&[0; 32]);
1416 let short_channel_id = 0;
1417 let chain_hash = genesis_block(Network::Testnet).header.block_hash();
1418 let amount_sats = 1000_000;
1421 // Announce a channel we will update
1422 let good_script = Builder::new().push_opcode(opcodes::all::OP_PUSHNUM_2)
1423 .push_slice(&PublicKey::from_secret_key(&secp_ctx, node_1_btckey).serialize())
1424 .push_slice(&PublicKey::from_secret_key(&secp_ctx, node_2_btckey).serialize())
1425 .push_opcode(opcodes::all::OP_PUSHNUM_2)
1426 .push_opcode(opcodes::all::OP_CHECKMULTISIG).into_script().to_v0_p2wsh();
1427 *chain_source.utxo_ret.lock().unwrap() = Ok(TxOut { value: amount_sats, script_pubkey: good_script.clone() });
1428 let unsigned_announcement = UnsignedChannelAnnouncement {
1429 features: ChannelFeatures::empty(),
1434 bitcoin_key_1: PublicKey::from_secret_key(&secp_ctx, node_1_btckey),
1435 bitcoin_key_2: PublicKey::from_secret_key(&secp_ctx, node_2_btckey),
1436 excess_data: Vec::new(),
1439 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1440 let valid_channel_announcement = ChannelAnnouncement {
1441 node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
1442 node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
1443 bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_btckey),
1444 bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_btckey),
1445 contents: unsigned_announcement.clone(),
1447 match net_graph_msg_handler.handle_channel_announcement(&valid_channel_announcement) {
1454 let mut unsigned_channel_update = UnsignedChannelUpdate {
1459 cltv_expiry_delta: 144,
1460 htlc_minimum_msat: 1000000,
1461 htlc_maximum_msat: OptionalField::Absent,
1462 fee_base_msat: 10000,
1463 fee_proportional_millionths: 20,
1464 excess_data: Vec::new()
1466 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_channel_update.encode()[..])[..]);
1467 let valid_channel_update = ChannelUpdate {
1468 signature: secp_ctx.sign(&msghash, node_1_privkey),
1469 contents: unsigned_channel_update.clone()
1472 match net_graph_msg_handler.handle_channel_update(&valid_channel_update) {
1473 Ok(res) => assert!(res),
1478 let network = net_graph_msg_handler.network_graph.read().unwrap();
1479 match network.get_channels().get(&short_channel_id) {
1481 Some(channel_info) => {
1482 assert_eq!(channel_info.one_to_two.as_ref().unwrap().cltv_expiry_delta, 144);
1483 assert!(channel_info.two_to_one.is_none());
1488 unsigned_channel_update.timestamp += 100;
1489 unsigned_channel_update.excess_data.resize(MAX_EXCESS_BYTES_FOR_RELAY + 1, 0);
1490 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_channel_update.encode()[..])[..]);
1491 let valid_channel_update = ChannelUpdate {
1492 signature: secp_ctx.sign(&msghash, node_1_privkey),
1493 contents: unsigned_channel_update.clone()
1495 // Return false because contains excess data
1496 match net_graph_msg_handler.handle_channel_update(&valid_channel_update) {
1497 Ok(res) => assert!(!res),
1500 unsigned_channel_update.timestamp += 10;
1502 unsigned_channel_update.short_channel_id += 1;
1503 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_channel_update.encode()[..])[..]);
1504 let valid_channel_update = ChannelUpdate {
1505 signature: secp_ctx.sign(&msghash, node_1_privkey),
1506 contents: unsigned_channel_update.clone()
1509 match net_graph_msg_handler.handle_channel_update(&valid_channel_update) {
1511 Err(e) => assert_eq!(e.err, "Couldn't find channel for update")
1513 unsigned_channel_update.short_channel_id = short_channel_id;
1515 unsigned_channel_update.htlc_maximum_msat = OptionalField::Present(MAX_VALUE_MSAT + 1);
1516 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_channel_update.encode()[..])[..]);
1517 let valid_channel_update = ChannelUpdate {
1518 signature: secp_ctx.sign(&msghash, node_1_privkey),
1519 contents: unsigned_channel_update.clone()
1522 match net_graph_msg_handler.handle_channel_update(&valid_channel_update) {
1524 Err(e) => assert_eq!(e.err, "htlc_maximum_msat is larger than maximum possible msats")
1526 unsigned_channel_update.htlc_maximum_msat = OptionalField::Absent;
1528 unsigned_channel_update.htlc_maximum_msat = OptionalField::Present(amount_sats * 1000 + 1);
1529 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_channel_update.encode()[..])[..]);
1530 let valid_channel_update = ChannelUpdate {
1531 signature: secp_ctx.sign(&msghash, node_1_privkey),
1532 contents: unsigned_channel_update.clone()
1535 match net_graph_msg_handler.handle_channel_update(&valid_channel_update) {
1537 Err(e) => assert_eq!(e.err, "htlc_maximum_msat is larger than channel capacity or capacity is bogus")
1539 unsigned_channel_update.htlc_maximum_msat = OptionalField::Absent;
1541 // Even though previous update was not relayed further, we still accepted it,
1542 // so we now won't accept update before the previous one.
1543 unsigned_channel_update.timestamp -= 10;
1544 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_channel_update.encode()[..])[..]);
1545 let valid_channel_update = ChannelUpdate {
1546 signature: secp_ctx.sign(&msghash, node_1_privkey),
1547 contents: unsigned_channel_update.clone()
1550 match net_graph_msg_handler.handle_channel_update(&valid_channel_update) {
1552 Err(e) => assert_eq!(e.err, "Update older than last processed update")
1554 unsigned_channel_update.timestamp += 500;
1556 let fake_msghash = hash_to_message!(&zero_hash);
1557 let invalid_sig_channel_update = ChannelUpdate {
1558 signature: secp_ctx.sign(&fake_msghash, node_1_privkey),
1559 contents: unsigned_channel_update.clone()
1562 match net_graph_msg_handler.handle_channel_update(&invalid_sig_channel_update) {
1564 Err(e) => assert_eq!(e.err, "Invalid signature from remote node")
1570 fn handling_htlc_fail_channel_update() {
1571 let (secp_ctx, net_graph_msg_handler) = create_net_graph_msg_handler();
1572 let node_1_privkey = &SecretKey::from_slice(&[42; 32]).unwrap();
1573 let node_2_privkey = &SecretKey::from_slice(&[41; 32]).unwrap();
1574 let node_id_1 = PublicKey::from_secret_key(&secp_ctx, node_1_privkey);
1575 let node_id_2 = PublicKey::from_secret_key(&secp_ctx, node_2_privkey);
1576 let node_1_btckey = &SecretKey::from_slice(&[40; 32]).unwrap();
1577 let node_2_btckey = &SecretKey::from_slice(&[39; 32]).unwrap();
1579 let short_channel_id = 0;
1580 let chain_hash = genesis_block(Network::Testnet).header.block_hash();
1583 // There is no nodes in the table at the beginning.
1584 let network = net_graph_msg_handler.network_graph.read().unwrap();
1585 assert_eq!(network.get_nodes().len(), 0);
1589 // Announce a channel we will update
1590 let unsigned_announcement = UnsignedChannelAnnouncement {
1591 features: ChannelFeatures::empty(),
1596 bitcoin_key_1: PublicKey::from_secret_key(&secp_ctx, node_1_btckey),
1597 bitcoin_key_2: PublicKey::from_secret_key(&secp_ctx, node_2_btckey),
1598 excess_data: Vec::new(),
1601 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1602 let valid_channel_announcement = ChannelAnnouncement {
1603 node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
1604 node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
1605 bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_btckey),
1606 bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_btckey),
1607 contents: unsigned_announcement.clone(),
1609 match net_graph_msg_handler.handle_channel_announcement(&valid_channel_announcement) {
1614 let unsigned_channel_update = UnsignedChannelUpdate {
1619 cltv_expiry_delta: 144,
1620 htlc_minimum_msat: 1000000,
1621 htlc_maximum_msat: OptionalField::Absent,
1622 fee_base_msat: 10000,
1623 fee_proportional_millionths: 20,
1624 excess_data: Vec::new()
1626 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_channel_update.encode()[..])[..]);
1627 let valid_channel_update = ChannelUpdate {
1628 signature: secp_ctx.sign(&msghash, node_1_privkey),
1629 contents: unsigned_channel_update.clone()
1632 match net_graph_msg_handler.handle_channel_update(&valid_channel_update) {
1633 Ok(res) => assert!(res),
1638 // Non-permanent closing just disables a channel
1640 let network = net_graph_msg_handler.network_graph.read().unwrap();
1641 match network.get_channels().get(&short_channel_id) {
1643 Some(channel_info) => {
1644 assert!(channel_info.one_to_two.is_some());
1649 let channel_close_msg = HTLCFailChannelUpdate::ChannelClosed {
1654 net_graph_msg_handler.handle_htlc_fail_channel_update(&channel_close_msg);
1656 // Non-permanent closing just disables a channel
1658 let network = net_graph_msg_handler.network_graph.read().unwrap();
1659 match network.get_channels().get(&short_channel_id) {
1661 Some(channel_info) => {
1662 assert!(!channel_info.one_to_two.as_ref().unwrap().enabled);
1667 let channel_close_msg = HTLCFailChannelUpdate::ChannelClosed {
1672 net_graph_msg_handler.handle_htlc_fail_channel_update(&channel_close_msg);
1674 // Permanent closing deletes a channel
1676 let network = net_graph_msg_handler.network_graph.read().unwrap();
1677 assert_eq!(network.get_channels().len(), 0);
1678 // Nodes are also deleted because there are no associated channels anymore
1679 assert_eq!(network.get_nodes().len(), 0);
1681 // TODO: Test HTLCFailChannelUpdate::NodeFailure, which is not implemented yet.
1685 fn getting_next_channel_announcements() {
1686 let (secp_ctx, net_graph_msg_handler) = create_net_graph_msg_handler();
1687 let node_1_privkey = &SecretKey::from_slice(&[42; 32]).unwrap();
1688 let node_2_privkey = &SecretKey::from_slice(&[41; 32]).unwrap();
1689 let node_id_1 = PublicKey::from_secret_key(&secp_ctx, node_1_privkey);
1690 let node_id_2 = PublicKey::from_secret_key(&secp_ctx, node_2_privkey);
1691 let node_1_btckey = &SecretKey::from_slice(&[40; 32]).unwrap();
1692 let node_2_btckey = &SecretKey::from_slice(&[39; 32]).unwrap();
1694 let short_channel_id = 1;
1695 let chain_hash = genesis_block(Network::Testnet).header.block_hash();
1697 // Channels were not announced yet.
1698 let channels_with_announcements = net_graph_msg_handler.get_next_channel_announcements(0, 1);
1699 assert_eq!(channels_with_announcements.len(), 0);
1702 // Announce a channel we will update
1703 let unsigned_announcement = UnsignedChannelAnnouncement {
1704 features: ChannelFeatures::empty(),
1709 bitcoin_key_1: PublicKey::from_secret_key(&secp_ctx, node_1_btckey),
1710 bitcoin_key_2: PublicKey::from_secret_key(&secp_ctx, node_2_btckey),
1711 excess_data: Vec::new(),
1714 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1715 let valid_channel_announcement = ChannelAnnouncement {
1716 node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
1717 node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
1718 bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_btckey),
1719 bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_btckey),
1720 contents: unsigned_announcement.clone(),
1722 match net_graph_msg_handler.handle_channel_announcement(&valid_channel_announcement) {
1728 // Contains initial channel announcement now.
1729 let channels_with_announcements = net_graph_msg_handler.get_next_channel_announcements(short_channel_id, 1);
1730 assert_eq!(channels_with_announcements.len(), 1);
1731 if let Some(channel_announcements) = channels_with_announcements.first() {
1732 let &(_, ref update_1, ref update_2) = channel_announcements;
1733 assert_eq!(update_1, &None);
1734 assert_eq!(update_2, &None);
1741 // Valid channel update
1742 let unsigned_channel_update = UnsignedChannelUpdate {
1747 cltv_expiry_delta: 144,
1748 htlc_minimum_msat: 1000000,
1749 htlc_maximum_msat: OptionalField::Absent,
1750 fee_base_msat: 10000,
1751 fee_proportional_millionths: 20,
1752 excess_data: Vec::new()
1754 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_channel_update.encode()[..])[..]);
1755 let valid_channel_update = ChannelUpdate {
1756 signature: secp_ctx.sign(&msghash, node_1_privkey),
1757 contents: unsigned_channel_update.clone()
1759 match net_graph_msg_handler.handle_channel_update(&valid_channel_update) {
1765 // Now contains an initial announcement and an update.
1766 let channels_with_announcements = net_graph_msg_handler.get_next_channel_announcements(short_channel_id, 1);
1767 assert_eq!(channels_with_announcements.len(), 1);
1768 if let Some(channel_announcements) = channels_with_announcements.first() {
1769 let &(_, ref update_1, ref update_2) = channel_announcements;
1770 assert_ne!(update_1, &None);
1771 assert_eq!(update_2, &None);
1778 // Channel update with excess data.
1779 let unsigned_channel_update = UnsignedChannelUpdate {
1784 cltv_expiry_delta: 144,
1785 htlc_minimum_msat: 1000000,
1786 htlc_maximum_msat: OptionalField::Absent,
1787 fee_base_msat: 10000,
1788 fee_proportional_millionths: 20,
1789 excess_data: [1; MAX_EXCESS_BYTES_FOR_RELAY + 1].to_vec()
1791 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_channel_update.encode()[..])[..]);
1792 let valid_channel_update = ChannelUpdate {
1793 signature: secp_ctx.sign(&msghash, node_1_privkey),
1794 contents: unsigned_channel_update.clone()
1796 match net_graph_msg_handler.handle_channel_update(&valid_channel_update) {
1802 // Test that announcements with excess data won't be returned
1803 let channels_with_announcements = net_graph_msg_handler.get_next_channel_announcements(short_channel_id, 1);
1804 assert_eq!(channels_with_announcements.len(), 1);
1805 if let Some(channel_announcements) = channels_with_announcements.first() {
1806 let &(_, ref update_1, ref update_2) = channel_announcements;
1807 assert_eq!(update_1, &None);
1808 assert_eq!(update_2, &None);
1813 // Further starting point have no channels after it
1814 let channels_with_announcements = net_graph_msg_handler.get_next_channel_announcements(short_channel_id + 1000, 1);
1815 assert_eq!(channels_with_announcements.len(), 0);
1819 fn getting_next_node_announcements() {
1820 let (secp_ctx, net_graph_msg_handler) = create_net_graph_msg_handler();
1821 let node_1_privkey = &SecretKey::from_slice(&[42; 32]).unwrap();
1822 let node_2_privkey = &SecretKey::from_slice(&[41; 32]).unwrap();
1823 let node_id_1 = PublicKey::from_secret_key(&secp_ctx, node_1_privkey);
1824 let node_id_2 = PublicKey::from_secret_key(&secp_ctx, node_2_privkey);
1825 let node_1_btckey = &SecretKey::from_slice(&[40; 32]).unwrap();
1826 let node_2_btckey = &SecretKey::from_slice(&[39; 32]).unwrap();
1828 let short_channel_id = 1;
1829 let chain_hash = genesis_block(Network::Testnet).header.block_hash();
1832 let next_announcements = net_graph_msg_handler.get_next_node_announcements(None, 10);
1833 assert_eq!(next_announcements.len(), 0);
1836 // Announce a channel to add 2 nodes
1837 let unsigned_announcement = UnsignedChannelAnnouncement {
1838 features: ChannelFeatures::empty(),
1843 bitcoin_key_1: PublicKey::from_secret_key(&secp_ctx, node_1_btckey),
1844 bitcoin_key_2: PublicKey::from_secret_key(&secp_ctx, node_2_btckey),
1845 excess_data: Vec::new(),
1848 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1849 let valid_channel_announcement = ChannelAnnouncement {
1850 node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
1851 node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
1852 bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_btckey),
1853 bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_btckey),
1854 contents: unsigned_announcement.clone(),
1856 match net_graph_msg_handler.handle_channel_announcement(&valid_channel_announcement) {
1863 // Nodes were never announced
1864 let next_announcements = net_graph_msg_handler.get_next_node_announcements(None, 3);
1865 assert_eq!(next_announcements.len(), 0);
1868 let mut unsigned_announcement = UnsignedNodeAnnouncement {
1869 features: NodeFeatures::known(),
1874 addresses: Vec::new(),
1875 excess_address_data: Vec::new(),
1876 excess_data: Vec::new(),
1878 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1879 let valid_announcement = NodeAnnouncement {
1880 signature: secp_ctx.sign(&msghash, node_1_privkey),
1881 contents: unsigned_announcement.clone()
1883 match net_graph_msg_handler.handle_node_announcement(&valid_announcement) {
1888 unsigned_announcement.node_id = node_id_2;
1889 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1890 let valid_announcement = NodeAnnouncement {
1891 signature: secp_ctx.sign(&msghash, node_2_privkey),
1892 contents: unsigned_announcement.clone()
1895 match net_graph_msg_handler.handle_node_announcement(&valid_announcement) {
1901 let next_announcements = net_graph_msg_handler.get_next_node_announcements(None, 3);
1902 assert_eq!(next_announcements.len(), 2);
1904 // Skip the first node.
1905 let next_announcements = net_graph_msg_handler.get_next_node_announcements(Some(&node_id_1), 2);
1906 assert_eq!(next_announcements.len(), 1);
1909 // Later announcement which should not be relayed (excess data) prevent us from sharing a node
1910 let unsigned_announcement = UnsignedNodeAnnouncement {
1911 features: NodeFeatures::known(),
1916 addresses: Vec::new(),
1917 excess_address_data: Vec::new(),
1918 excess_data: [1; MAX_EXCESS_BYTES_FOR_RELAY + 1].to_vec(),
1920 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1921 let valid_announcement = NodeAnnouncement {
1922 signature: secp_ctx.sign(&msghash, node_2_privkey),
1923 contents: unsigned_announcement.clone()
1925 match net_graph_msg_handler.handle_node_announcement(&valid_announcement) {
1926 Ok(res) => assert!(!res),
1931 let next_announcements = net_graph_msg_handler.get_next_node_announcements(Some(&node_id_1), 2);
1932 assert_eq!(next_announcements.len(), 0);
1936 fn network_graph_serialization() {
1937 let (secp_ctx, net_graph_msg_handler) = create_net_graph_msg_handler();
1939 let node_1_privkey = &SecretKey::from_slice(&[42; 32]).unwrap();
1940 let node_2_privkey = &SecretKey::from_slice(&[41; 32]).unwrap();
1941 let node_1_btckey = &SecretKey::from_slice(&[40; 32]).unwrap();
1942 let node_2_btckey = &SecretKey::from_slice(&[39; 32]).unwrap();
1944 // Announce a channel to add a corresponding node.
1945 let node_id_1 = PublicKey::from_secret_key(&secp_ctx, node_1_privkey);
1946 let node_id_2 = PublicKey::from_secret_key(&secp_ctx, node_2_privkey);
1947 let unsigned_announcement = UnsignedChannelAnnouncement {
1948 features: ChannelFeatures::known(),
1949 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1950 short_channel_id: 0,
1953 bitcoin_key_1: PublicKey::from_secret_key(&secp_ctx, node_1_btckey),
1954 bitcoin_key_2: PublicKey::from_secret_key(&secp_ctx, node_2_btckey),
1955 excess_data: Vec::new(),
1958 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1959 let valid_announcement = ChannelAnnouncement {
1960 node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
1961 node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
1962 bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_btckey),
1963 bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_btckey),
1964 contents: unsigned_announcement.clone(),
1966 match net_graph_msg_handler.handle_channel_announcement(&valid_announcement) {
1967 Ok(res) => assert!(res),
1972 let node_id = PublicKey::from_secret_key(&secp_ctx, node_1_privkey);
1973 let unsigned_announcement = UnsignedNodeAnnouncement {
1974 features: NodeFeatures::known(),
1979 addresses: Vec::new(),
1980 excess_address_data: Vec::new(),
1981 excess_data: Vec::new(),
1983 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1984 let valid_announcement = NodeAnnouncement {
1985 signature: secp_ctx.sign(&msghash, node_1_privkey),
1986 contents: unsigned_announcement.clone()
1989 match net_graph_msg_handler.handle_node_announcement(&valid_announcement) {
1994 let network = net_graph_msg_handler.network_graph.write().unwrap();
1995 let mut w = test_utils::TestVecWriter(Vec::new());
1996 assert!(!network.get_nodes().is_empty());
1997 assert!(!network.get_channels().is_empty());
1998 network.write(&mut w).unwrap();
1999 assert!(<NetworkGraph>::read(&mut ::std::io::Cursor::new(&w.0)).unwrap() == *network);
2003 fn calling_sync_routing_table() {
2004 let (secp_ctx, net_graph_msg_handler) = create_net_graph_msg_handler();
2005 let node_privkey_1 = &SecretKey::from_slice(&[42; 32]).unwrap();
2006 let node_id_1 = PublicKey::from_secret_key(&secp_ctx, node_privkey_1);
2008 let chain_hash = genesis_block(Network::Testnet).header.block_hash();
2009 let first_blocknum = 0;
2010 let number_of_blocks = 0xffff_ffff;
2012 // It should ignore if gossip_queries feature is not enabled
2014 let init_msg = Init { features: InitFeatures::known().clear_gossip_queries() };
2015 net_graph_msg_handler.sync_routing_table(&node_id_1, &init_msg);
2016 let events = net_graph_msg_handler.get_and_clear_pending_msg_events();
2017 assert_eq!(events.len(), 0);
2020 // It should send a query_channel_message with the correct information
2022 let init_msg = Init { features: InitFeatures::known() };
2023 net_graph_msg_handler.sync_routing_table(&node_id_1, &init_msg);
2024 let events = net_graph_msg_handler.get_and_clear_pending_msg_events();
2025 assert_eq!(events.len(), 1);
2027 MessageSendEvent::SendChannelRangeQuery{ node_id, msg } => {
2028 assert_eq!(node_id, &node_id_1);
2029 assert_eq!(msg.chain_hash, chain_hash);
2030 assert_eq!(msg.first_blocknum, first_blocknum);
2031 assert_eq!(msg.number_of_blocks, number_of_blocks);
2033 _ => panic!("Expected MessageSendEvent::SendChannelRangeQuery")
2037 // It should not enqueue a query when should_request_full_sync return false.
2038 // The initial implementation allows syncing with the first 5 peers after
2039 // which should_request_full_sync will return false
2041 let (secp_ctx, net_graph_msg_handler) = create_net_graph_msg_handler();
2042 let init_msg = Init { features: InitFeatures::known() };
2044 let node_privkey = &SecretKey::from_slice(&[n; 32]).unwrap();
2045 let node_id = PublicKey::from_secret_key(&secp_ctx, node_privkey);
2046 net_graph_msg_handler.sync_routing_table(&node_id, &init_msg);
2047 let events = net_graph_msg_handler.get_and_clear_pending_msg_events();
2049 assert_eq!(events.len(), 1);
2051 assert_eq!(events.len(), 0);
2059 fn handling_reply_channel_range() {
2060 let (secp_ctx, net_graph_msg_handler) = create_net_graph_msg_handler();
2061 let node_privkey_1 = &SecretKey::from_slice(&[42; 32]).unwrap();
2062 let node_id_1 = PublicKey::from_secret_key(&secp_ctx, node_privkey_1);
2064 let chain_hash = genesis_block(Network::Testnet).header.block_hash();
2066 // Test receipt of a single reply that should enqueue an SCID query
2067 // matching the SCIDs in the reply
2069 let result = net_graph_msg_handler.handle_reply_channel_range(&node_id_1, ReplyChannelRange {
2071 sync_complete: true,
2073 number_of_blocks: 2000,
2074 short_channel_ids: vec![
2075 0x0003e0_000000_0000, // 992x0x0
2076 0x0003e8_000000_0000, // 1000x0x0
2077 0x0003e9_000000_0000, // 1001x0x0
2078 0x0003f0_000000_0000, // 1008x0x0
2079 0x00044c_000000_0000, // 1100x0x0
2080 0x0006e0_000000_0000, // 1760x0x0
2083 assert!(result.is_ok());
2085 // We expect to emit a query_short_channel_ids message with the received scids
2086 let events = net_graph_msg_handler.get_and_clear_pending_msg_events();
2087 assert_eq!(events.len(), 1);
2089 MessageSendEvent::SendShortIdsQuery { node_id, msg } => {
2090 assert_eq!(node_id, &node_id_1);
2091 assert_eq!(msg.chain_hash, chain_hash);
2092 assert_eq!(msg.short_channel_ids, vec![
2093 0x0003e0_000000_0000, // 992x0x0
2094 0x0003e8_000000_0000, // 1000x0x0
2095 0x0003e9_000000_0000, // 1001x0x0
2096 0x0003f0_000000_0000, // 1008x0x0
2097 0x00044c_000000_0000, // 1100x0x0
2098 0x0006e0_000000_0000, // 1760x0x0
2101 _ => panic!("expected MessageSendEvent::SendShortIdsQuery"),
2107 fn handling_reply_short_channel_ids() {
2108 let (secp_ctx, net_graph_msg_handler) = create_net_graph_msg_handler();
2109 let node_privkey = &SecretKey::from_slice(&[41; 32]).unwrap();
2110 let node_id = PublicKey::from_secret_key(&secp_ctx, node_privkey);
2112 let chain_hash = genesis_block(Network::Testnet).header.block_hash();
2114 // Test receipt of a successful reply
2116 let result = net_graph_msg_handler.handle_reply_short_channel_ids_end(&node_id, ReplyShortChannelIdsEnd {
2118 full_information: true,
2120 assert!(result.is_ok());
2123 // Test receipt of a reply that indicates the peer does not maintain up-to-date information
2124 // for the chain_hash requested in the query.
2126 let result = net_graph_msg_handler.handle_reply_short_channel_ids_end(&node_id, ReplyShortChannelIdsEnd {
2128 full_information: false,
2130 assert!(result.is_err());
2131 assert_eq!(result.err().unwrap().err, "Received reply_short_channel_ids_end with no information");
2136 fn handling_query_channel_range() {
2137 let (secp_ctx, net_graph_msg_handler) = create_net_graph_msg_handler();
2139 let chain_hash = genesis_block(Network::Testnet).header.block_hash();
2140 let node_1_privkey = &SecretKey::from_slice(&[42; 32]).unwrap();
2141 let node_2_privkey = &SecretKey::from_slice(&[41; 32]).unwrap();
2142 let node_1_btckey = &SecretKey::from_slice(&[40; 32]).unwrap();
2143 let node_2_btckey = &SecretKey::from_slice(&[39; 32]).unwrap();
2144 let node_id_1 = PublicKey::from_secret_key(&secp_ctx, node_1_privkey);
2145 let node_id_2 = PublicKey::from_secret_key(&secp_ctx, node_2_privkey);
2146 let bitcoin_key_1 = PublicKey::from_secret_key(&secp_ctx, node_1_btckey);
2147 let bitcoin_key_2 = PublicKey::from_secret_key(&secp_ctx, node_2_btckey);
2149 let mut scids: Vec<u64> = vec![
2150 scid_from_parts(0xfffffe, 0xffffff, 0xffff).unwrap(), // max
2151 scid_from_parts(0xffffff, 0xffffff, 0xffff).unwrap(), // never
2154 // used for testing multipart reply across blocks
2155 for block in 100000..=108001 {
2156 scids.push(scid_from_parts(block, 0, 0).unwrap());
2159 // used for testing resumption on same block
2160 scids.push(scid_from_parts(108001, 1, 0).unwrap());
2163 let unsigned_announcement = UnsignedChannelAnnouncement {
2164 features: ChannelFeatures::known(),
2165 chain_hash: chain_hash.clone(),
2166 short_channel_id: scid,
2171 excess_data: Vec::new(),
2174 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
2175 let valid_announcement = ChannelAnnouncement {
2176 node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
2177 node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
2178 bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_btckey),
2179 bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_btckey),
2180 contents: unsigned_announcement.clone(),
2182 match net_graph_msg_handler.handle_channel_announcement(&valid_announcement) {
2188 // Error when number_of_blocks=0
2189 do_handling_query_channel_range(
2190 &net_graph_msg_handler,
2193 chain_hash: chain_hash.clone(),
2195 number_of_blocks: 0,
2198 vec![ReplyChannelRange {
2199 chain_hash: chain_hash.clone(),
2201 number_of_blocks: 0,
2202 sync_complete: true,
2203 short_channel_ids: vec![]
2207 // Error when wrong chain
2208 do_handling_query_channel_range(
2209 &net_graph_msg_handler,
2212 chain_hash: genesis_block(Network::Bitcoin).header.block_hash(),
2214 number_of_blocks: 0xffff_ffff,
2217 vec![ReplyChannelRange {
2218 chain_hash: genesis_block(Network::Bitcoin).header.block_hash(),
2220 number_of_blocks: 0xffff_ffff,
2221 sync_complete: true,
2222 short_channel_ids: vec![],
2226 // Error when first_blocknum > 0xffffff
2227 do_handling_query_channel_range(
2228 &net_graph_msg_handler,
2231 chain_hash: chain_hash.clone(),
2232 first_blocknum: 0x01000000,
2233 number_of_blocks: 0xffff_ffff,
2236 vec![ReplyChannelRange {
2237 chain_hash: chain_hash.clone(),
2238 first_blocknum: 0x01000000,
2239 number_of_blocks: 0xffff_ffff,
2240 sync_complete: true,
2241 short_channel_ids: vec![]
2245 // Empty reply when max valid SCID block num
2246 do_handling_query_channel_range(
2247 &net_graph_msg_handler,
2250 chain_hash: chain_hash.clone(),
2251 first_blocknum: 0xffffff,
2252 number_of_blocks: 1,
2257 chain_hash: chain_hash.clone(),
2258 first_blocknum: 0xffffff,
2259 number_of_blocks: 1,
2260 sync_complete: true,
2261 short_channel_ids: vec![]
2266 // No results in valid query range
2267 do_handling_query_channel_range(
2268 &net_graph_msg_handler,
2271 chain_hash: chain_hash.clone(),
2272 first_blocknum: 1000,
2273 number_of_blocks: 1000,
2278 chain_hash: chain_hash.clone(),
2279 first_blocknum: 1000,
2280 number_of_blocks: 1000,
2281 sync_complete: true,
2282 short_channel_ids: vec![],
2287 // Overflow first_blocknum + number_of_blocks
2288 do_handling_query_channel_range(
2289 &net_graph_msg_handler,
2292 chain_hash: chain_hash.clone(),
2293 first_blocknum: 0xfe0000,
2294 number_of_blocks: 0xffffffff,
2299 chain_hash: chain_hash.clone(),
2300 first_blocknum: 0xfe0000,
2301 number_of_blocks: 0xffffffff - 0xfe0000,
2302 sync_complete: true,
2303 short_channel_ids: vec![
2304 0xfffffe_ffffff_ffff, // max
2310 // Single block exactly full
2311 do_handling_query_channel_range(
2312 &net_graph_msg_handler,
2315 chain_hash: chain_hash.clone(),
2316 first_blocknum: 100000,
2317 number_of_blocks: 8000,
2322 chain_hash: chain_hash.clone(),
2323 first_blocknum: 100000,
2324 number_of_blocks: 8000,
2325 sync_complete: true,
2326 short_channel_ids: (100000..=107999)
2327 .map(|block| scid_from_parts(block, 0, 0).unwrap())
2333 // Multiple split on new block
2334 do_handling_query_channel_range(
2335 &net_graph_msg_handler,
2338 chain_hash: chain_hash.clone(),
2339 first_blocknum: 100000,
2340 number_of_blocks: 8001,
2345 chain_hash: chain_hash.clone(),
2346 first_blocknum: 100000,
2347 number_of_blocks: 7999,
2348 sync_complete: false,
2349 short_channel_ids: (100000..=107999)
2350 .map(|block| scid_from_parts(block, 0, 0).unwrap())
2354 chain_hash: chain_hash.clone(),
2355 first_blocknum: 107999,
2356 number_of_blocks: 2,
2357 sync_complete: true,
2358 short_channel_ids: vec![
2359 scid_from_parts(108000, 0, 0).unwrap(),
2365 // Multiple split on same block
2366 do_handling_query_channel_range(
2367 &net_graph_msg_handler,
2370 chain_hash: chain_hash.clone(),
2371 first_blocknum: 100002,
2372 number_of_blocks: 8000,
2377 chain_hash: chain_hash.clone(),
2378 first_blocknum: 100002,
2379 number_of_blocks: 7999,
2380 sync_complete: false,
2381 short_channel_ids: (100002..=108001)
2382 .map(|block| scid_from_parts(block, 0, 0).unwrap())
2386 chain_hash: chain_hash.clone(),
2387 first_blocknum: 108001,
2388 number_of_blocks: 1,
2389 sync_complete: true,
2390 short_channel_ids: vec![
2391 scid_from_parts(108001, 1, 0).unwrap(),
2398 fn do_handling_query_channel_range(
2399 net_graph_msg_handler: &NetGraphMsgHandler<Arc<test_utils::TestChainSource>, Arc<test_utils::TestLogger>>,
2400 test_node_id: &PublicKey,
2401 msg: QueryChannelRange,
2403 expected_replies: Vec<ReplyChannelRange>
2405 let mut max_firstblocknum = msg.first_blocknum.saturating_sub(1);
2406 let mut c_lightning_0_9_prev_end_blocknum = max_firstblocknum;
2407 let query_end_blocknum = msg.end_blocknum();
2408 let result = net_graph_msg_handler.handle_query_channel_range(test_node_id, msg);
2411 assert!(result.is_ok());
2413 assert!(result.is_err());
2416 let events = net_graph_msg_handler.get_and_clear_pending_msg_events();
2417 assert_eq!(events.len(), expected_replies.len());
2419 for i in 0..events.len() {
2420 let expected_reply = &expected_replies[i];
2422 MessageSendEvent::SendReplyChannelRange { node_id, msg } => {
2423 assert_eq!(node_id, test_node_id);
2424 assert_eq!(msg.chain_hash, expected_reply.chain_hash);
2425 assert_eq!(msg.first_blocknum, expected_reply.first_blocknum);
2426 assert_eq!(msg.number_of_blocks, expected_reply.number_of_blocks);
2427 assert_eq!(msg.sync_complete, expected_reply.sync_complete);
2428 assert_eq!(msg.short_channel_ids, expected_reply.short_channel_ids);
2430 // Enforce exactly the sequencing requirements present on c-lightning v0.9.3
2431 assert!(msg.first_blocknum == c_lightning_0_9_prev_end_blocknum || msg.first_blocknum == c_lightning_0_9_prev_end_blocknum.saturating_add(1));
2432 assert!(msg.first_blocknum >= max_firstblocknum);
2433 max_firstblocknum = msg.first_blocknum;
2434 c_lightning_0_9_prev_end_blocknum = msg.first_blocknum.saturating_add(msg.number_of_blocks);
2436 // Check that the last block count is >= the query's end_blocknum
2437 if i == events.len() - 1 {
2438 assert!(msg.first_blocknum.saturating_add(msg.number_of_blocks) >= query_end_blocknum);
2441 _ => panic!("expected MessageSendEvent::SendReplyChannelRange"),
2447 fn handling_query_short_channel_ids() {
2448 let (secp_ctx, net_graph_msg_handler) = create_net_graph_msg_handler();
2449 let node_privkey = &SecretKey::from_slice(&[41; 32]).unwrap();
2450 let node_id = PublicKey::from_secret_key(&secp_ctx, node_privkey);
2452 let chain_hash = genesis_block(Network::Testnet).header.block_hash();
2454 let result = net_graph_msg_handler.handle_query_short_channel_ids(&node_id, QueryShortChannelIds {
2456 short_channel_ids: vec![0x0003e8_000000_0000],
2458 assert!(result.is_err());
2462 #[cfg(all(test, feature = "unstable"))]
2470 fn read_network_graph(bench: &mut Bencher) {
2471 let mut d = ::routing::router::test_utils::get_route_file().unwrap();
2472 let mut v = Vec::new();
2473 d.read_to_end(&mut v).unwrap();
2475 let _ = NetworkGraph::read(&mut std::io::Cursor::new(&v)).unwrap();
2480 fn write_network_graph(bench: &mut Bencher) {
2481 let mut d = ::routing::router::test_utils::get_route_file().unwrap();
2482 let net_graph = NetworkGraph::read(&mut d).unwrap();
2484 let _ = net_graph.encode();