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::constants::PUBLIC_KEY_SIZE;
13 use bitcoin::secp256k1::PublicKey;
14 use bitcoin::secp256k1::Secp256k1;
15 use bitcoin::secp256k1;
17 use bitcoin::hashes::sha256d::Hash as Sha256dHash;
18 use bitcoin::hashes::Hash;
19 use bitcoin::blockdata::script::Builder;
20 use bitcoin::blockdata::transaction::TxOut;
21 use bitcoin::blockdata::opcodes;
22 use bitcoin::hash_types::BlockHash;
26 use ln::features::{ChannelFeatures, NodeFeatures};
27 use ln::msgs::{DecodeError, ErrorAction, Init, LightningError, RoutingMessageHandler, NetAddress, MAX_VALUE_MSAT};
28 use ln::msgs::{ChannelAnnouncement, ChannelUpdate, NodeAnnouncement, OptionalField, GossipTimestampFilter};
29 use ln::msgs::{QueryChannelRange, ReplyChannelRange, QueryShortChannelIds, ReplyShortChannelIdsEnd};
31 use util::ser::{Writeable, Readable, Writer};
32 use util::logger::{Logger, Level};
33 use util::events::{Event, EventHandler, MessageSendEvent, MessageSendEventsProvider};
34 use util::scid_utils::{block_from_scid, scid_from_parts, MAX_SCID_BLOCK};
38 use alloc::collections::{BTreeMap, btree_map::Entry as BtreeEntry};
40 use sync::{RwLock, RwLockReadGuard};
41 use core::sync::atomic::{AtomicUsize, Ordering};
44 use bitcoin::hashes::hex::ToHex;
46 #[cfg(feature = "std")]
47 use std::time::{SystemTime, UNIX_EPOCH};
49 /// We remove stale channel directional info two weeks after the last update, per BOLT 7's
51 const STALE_CHANNEL_UPDATE_AGE_LIMIT_SECS: u64 = 60 * 60 * 24 * 14;
53 /// The maximum number of extra bytes which we do not understand in a gossip message before we will
54 /// refuse to relay the message.
55 const MAX_EXCESS_BYTES_FOR_RELAY: usize = 1024;
57 /// Maximum number of short_channel_ids that will be encoded in one gossip reply message.
58 /// This value ensures a reply fits within the 65k payload limit and is consistent with other implementations.
59 const MAX_SCIDS_PER_REPLY: usize = 8000;
61 /// Represents the compressed public key of a node
62 #[derive(Clone, Copy)]
63 pub struct NodeId([u8; PUBLIC_KEY_SIZE]);
66 /// Create a new NodeId from a public key
67 pub fn from_pubkey(pubkey: &PublicKey) -> Self {
68 NodeId(pubkey.serialize())
71 /// Get the public key slice from this NodeId
72 pub fn as_slice(&self) -> &[u8] {
77 impl fmt::Debug for NodeId {
78 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
79 write!(f, "NodeId({})", log_bytes!(self.0))
83 impl core::hash::Hash for NodeId {
84 fn hash<H: core::hash::Hasher>(&self, hasher: &mut H) {
91 impl PartialEq for NodeId {
92 fn eq(&self, other: &Self) -> bool {
93 self.0[..] == other.0[..]
97 impl cmp::PartialOrd for NodeId {
98 fn partial_cmp(&self, other: &Self) -> Option<cmp::Ordering> {
103 impl Ord for NodeId {
104 fn cmp(&self, other: &Self) -> cmp::Ordering {
105 self.0[..].cmp(&other.0[..])
109 impl Writeable for NodeId {
110 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
111 writer.write_all(&self.0)?;
116 impl Readable for NodeId {
117 fn read<R: io::Read>(reader: &mut R) -> Result<Self, DecodeError> {
118 let mut buf = [0; PUBLIC_KEY_SIZE];
119 reader.read_exact(&mut buf)?;
124 /// Represents the network as nodes and channels between them
125 pub struct NetworkGraph {
126 genesis_hash: BlockHash,
127 // Lock order: channels -> nodes
128 channels: RwLock<BTreeMap<u64, ChannelInfo>>,
129 nodes: RwLock<BTreeMap<NodeId, NodeInfo>>,
132 impl Clone for NetworkGraph {
133 fn clone(&self) -> Self {
134 let channels = self.channels.read().unwrap();
135 let nodes = self.nodes.read().unwrap();
137 genesis_hash: self.genesis_hash.clone(),
138 channels: RwLock::new(channels.clone()),
139 nodes: RwLock::new(nodes.clone()),
144 /// A read-only view of [`NetworkGraph`].
145 pub struct ReadOnlyNetworkGraph<'a> {
146 channels: RwLockReadGuard<'a, BTreeMap<u64, ChannelInfo>>,
147 nodes: RwLockReadGuard<'a, BTreeMap<NodeId, NodeInfo>>,
150 /// Update to the [`NetworkGraph`] based on payment failure information conveyed via the Onion
151 /// return packet by a node along the route. See [BOLT #4] for details.
153 /// [BOLT #4]: https://github.com/lightning/bolts/blob/master/04-onion-routing.md
154 #[derive(Clone, Debug, PartialEq)]
155 pub enum NetworkUpdate {
156 /// An error indicating a `channel_update` messages should be applied via
157 /// [`NetworkGraph::update_channel`].
158 ChannelUpdateMessage {
159 /// The update to apply via [`NetworkGraph::update_channel`].
162 /// An error indicating only that a channel has been closed, which should be applied via
163 /// [`NetworkGraph::close_channel_from_update`].
165 /// The short channel id of the closed channel.
166 short_channel_id: u64,
167 /// Whether the channel should be permanently removed or temporarily disabled until a new
168 /// `channel_update` message is received.
171 /// An error indicating only that a node has failed, which should be applied via
172 /// [`NetworkGraph::fail_node`].
174 /// The node id of the failed node.
176 /// Whether the node should be permanently removed from consideration or can be restored
177 /// when a new `channel_update` message is received.
182 impl_writeable_tlv_based_enum_upgradable!(NetworkUpdate,
183 (0, ChannelUpdateMessage) => {
186 (2, ChannelClosed) => {
187 (0, short_channel_id, required),
188 (2, is_permanent, required),
190 (4, NodeFailure) => {
191 (0, node_id, required),
192 (2, is_permanent, required),
196 impl<G: Deref<Target=NetworkGraph>, C: Deref, L: Deref> EventHandler for NetGraphMsgHandler<G, C, L>
197 where C::Target: chain::Access, L::Target: Logger {
198 fn handle_event(&self, event: &Event) {
199 if let Event::PaymentPathFailed { payment_hash: _, rejected_by_dest: _, network_update, .. } = event {
200 if let Some(network_update) = network_update {
201 self.handle_network_update(network_update);
207 /// Receives and validates network updates from peers,
208 /// stores authentic and relevant data as a network graph.
209 /// This network graph is then used for routing payments.
210 /// Provides interface to help with initial routing sync by
211 /// serving historical announcements.
213 /// Serves as an [`EventHandler`] for applying updates from [`Event::PaymentPathFailed`] to the
214 /// [`NetworkGraph`].
215 pub struct NetGraphMsgHandler<G: Deref<Target=NetworkGraph>, C: Deref, L: Deref>
216 where C::Target: chain::Access, L::Target: Logger
218 secp_ctx: Secp256k1<secp256k1::VerifyOnly>,
220 chain_access: Option<C>,
221 full_syncs_requested: AtomicUsize,
222 pending_events: Mutex<Vec<MessageSendEvent>>,
226 impl<G: Deref<Target=NetworkGraph>, C: Deref, L: Deref> NetGraphMsgHandler<G, C, L>
227 where C::Target: chain::Access, L::Target: Logger
229 /// Creates a new tracker of the actual state of the network of channels and nodes,
230 /// assuming an existing Network Graph.
231 /// Chain monitor is used to make sure announced channels exist on-chain,
232 /// channel data is correct, and that the announcement is signed with
233 /// channel owners' keys.
234 pub fn new(network_graph: G, chain_access: Option<C>, logger: L) -> Self {
236 secp_ctx: Secp256k1::verification_only(),
238 full_syncs_requested: AtomicUsize::new(0),
240 pending_events: Mutex::new(vec![]),
245 /// Adds a provider used to check new announcements. Does not affect
246 /// existing announcements unless they are updated.
247 /// Add, update or remove the provider would replace the current one.
248 pub fn add_chain_access(&mut self, chain_access: Option<C>) {
249 self.chain_access = chain_access;
252 /// Gets a reference to the underlying [`NetworkGraph`] which was provided in
253 /// [`NetGraphMsgHandler::new`].
255 /// (C-not exported) as bindings don't support a reference-to-a-reference yet
256 pub fn network_graph(&self) -> &G {
260 /// Returns true when a full routing table sync should be performed with a peer.
261 fn should_request_full_sync(&self, _node_id: &PublicKey) -> bool {
262 //TODO: Determine whether to request a full sync based on the network map.
263 const FULL_SYNCS_TO_REQUEST: usize = 5;
264 if self.full_syncs_requested.load(Ordering::Acquire) < FULL_SYNCS_TO_REQUEST {
265 self.full_syncs_requested.fetch_add(1, Ordering::AcqRel);
272 /// Applies changes to the [`NetworkGraph`] from the given update.
273 fn handle_network_update(&self, update: &NetworkUpdate) {
275 NetworkUpdate::ChannelUpdateMessage { ref msg } => {
276 let short_channel_id = msg.contents.short_channel_id;
277 let is_enabled = msg.contents.flags & (1 << 1) != (1 << 1);
278 let status = if is_enabled { "enabled" } else { "disabled" };
279 log_debug!(self.logger, "Updating channel with channel_update from a payment failure. Channel {} is {}.", short_channel_id, status);
280 let _ = self.network_graph.update_channel(msg, &self.secp_ctx);
282 NetworkUpdate::ChannelClosed { short_channel_id, is_permanent } => {
283 let action = if is_permanent { "Removing" } else { "Disabling" };
284 log_debug!(self.logger, "{} channel graph entry for {} due to a payment failure.", action, short_channel_id);
285 self.network_graph.close_channel_from_update(short_channel_id, is_permanent);
287 NetworkUpdate::NodeFailure { ref node_id, is_permanent } => {
288 let action = if is_permanent { "Removing" } else { "Disabling" };
289 log_debug!(self.logger, "{} node graph entry for {} due to a payment failure.", action, node_id);
290 self.network_graph.fail_node(node_id, is_permanent);
296 macro_rules! secp_verify_sig {
297 ( $secp_ctx: expr, $msg: expr, $sig: expr, $pubkey: expr, $msg_type: expr ) => {
298 match $secp_ctx.verify_ecdsa($msg, $sig, $pubkey) {
301 return Err(LightningError {
302 err: format!("Invalid signature on {} message", $msg_type),
303 action: ErrorAction::SendWarningMessage {
304 msg: msgs::WarningMessage {
306 data: format!("Invalid signature on {} message", $msg_type),
308 log_level: Level::Trace,
316 impl<G: Deref<Target=NetworkGraph>, C: Deref, L: Deref> RoutingMessageHandler for NetGraphMsgHandler<G, C, L>
317 where C::Target: chain::Access, L::Target: Logger
319 fn handle_node_announcement(&self, msg: &msgs::NodeAnnouncement) -> Result<bool, LightningError> {
320 self.network_graph.update_node_from_announcement(msg, &self.secp_ctx)?;
321 Ok(msg.contents.excess_data.len() <= MAX_EXCESS_BYTES_FOR_RELAY &&
322 msg.contents.excess_address_data.len() <= MAX_EXCESS_BYTES_FOR_RELAY &&
323 msg.contents.excess_data.len() + msg.contents.excess_address_data.len() <= MAX_EXCESS_BYTES_FOR_RELAY)
326 fn handle_channel_announcement(&self, msg: &msgs::ChannelAnnouncement) -> Result<bool, LightningError> {
327 self.network_graph.update_channel_from_announcement(msg, &self.chain_access, &self.secp_ctx)?;
328 log_gossip!(self.logger, "Added channel_announcement for {}{}", msg.contents.short_channel_id, if !msg.contents.excess_data.is_empty() { " with excess uninterpreted data!" } else { "" });
329 Ok(msg.contents.excess_data.len() <= MAX_EXCESS_BYTES_FOR_RELAY)
332 fn handle_channel_update(&self, msg: &msgs::ChannelUpdate) -> Result<bool, LightningError> {
333 self.network_graph.update_channel(msg, &self.secp_ctx)?;
334 Ok(msg.contents.excess_data.len() <= MAX_EXCESS_BYTES_FOR_RELAY)
337 fn get_next_channel_announcements(&self, starting_point: u64, batch_amount: u8) -> Vec<(ChannelAnnouncement, Option<ChannelUpdate>, Option<ChannelUpdate>)> {
338 let mut result = Vec::with_capacity(batch_amount as usize);
339 let channels = self.network_graph.channels.read().unwrap();
340 let mut iter = channels.range(starting_point..);
341 while result.len() < batch_amount as usize {
342 if let Some((_, ref chan)) = iter.next() {
343 if chan.announcement_message.is_some() {
344 let chan_announcement = chan.announcement_message.clone().unwrap();
345 let mut one_to_two_announcement: Option<msgs::ChannelUpdate> = None;
346 let mut two_to_one_announcement: Option<msgs::ChannelUpdate> = None;
347 if let Some(one_to_two) = chan.one_to_two.as_ref() {
348 one_to_two_announcement = one_to_two.last_update_message.clone();
350 if let Some(two_to_one) = chan.two_to_one.as_ref() {
351 two_to_one_announcement = two_to_one.last_update_message.clone();
353 result.push((chan_announcement, one_to_two_announcement, two_to_one_announcement));
355 // TODO: We may end up sending un-announced channel_updates if we are sending
356 // initial sync data while receiving announce/updates for this channel.
365 fn get_next_node_announcements(&self, starting_point: Option<&PublicKey>, batch_amount: u8) -> Vec<NodeAnnouncement> {
366 let mut result = Vec::with_capacity(batch_amount as usize);
367 let nodes = self.network_graph.nodes.read().unwrap();
368 let mut iter = if let Some(pubkey) = starting_point {
369 let mut iter = nodes.range(NodeId::from_pubkey(pubkey)..);
373 nodes.range::<NodeId, _>(..)
375 while result.len() < batch_amount as usize {
376 if let Some((_, ref node)) = iter.next() {
377 if let Some(node_info) = node.announcement_info.as_ref() {
378 if node_info.announcement_message.is_some() {
379 result.push(node_info.announcement_message.clone().unwrap());
389 /// Initiates a stateless sync of routing gossip information with a peer
390 /// using gossip_queries. The default strategy used by this implementation
391 /// is to sync the full block range with several peers.
393 /// We should expect one or more reply_channel_range messages in response
394 /// to our query_channel_range. Each reply will enqueue a query_scid message
395 /// to request gossip messages for each channel. The sync is considered complete
396 /// when the final reply_scids_end message is received, though we are not
397 /// tracking this directly.
398 fn peer_connected(&self, their_node_id: &PublicKey, init_msg: &Init) {
399 // We will only perform a sync with peers that support gossip_queries.
400 if !init_msg.features.supports_gossip_queries() {
404 // The lightning network's gossip sync system is completely broken in numerous ways.
406 // Given no broadly-available set-reconciliation protocol, the only reasonable approach is
407 // to do a full sync from the first few peers we connect to, and then receive gossip
408 // updates from all our peers normally.
410 // Originally, we could simply tell a peer to dump us the entire gossip table on startup,
411 // wasting lots of bandwidth but ensuring we have the full network graph. After the initial
412 // dump peers would always send gossip and we'd stay up-to-date with whatever our peer has
415 // In order to reduce the bandwidth waste, "gossip queries" were introduced, allowing you
416 // to ask for the SCIDs of all channels in your peer's routing graph, and then only request
417 // channel data which you are missing. Except there was no way at all to identify which
418 // `channel_update`s you were missing, so you still had to request everything, just in a
419 // very complicated way with some queries instead of just getting the dump.
421 // Later, an option was added to fetch the latest timestamps of the `channel_update`s to
422 // make efficient sync possible, however it has yet to be implemented in lnd, which makes
423 // relying on it useless.
425 // After gossip queries were introduced, support for receiving a full gossip table dump on
426 // connection was removed from several nodes, making it impossible to get a full sync
427 // without using the "gossip queries" messages.
429 // Once you opt into "gossip queries" the only way to receive any gossip updates that a
430 // peer receives after you connect, you must send a `gossip_timestamp_filter` message. This
431 // message, as the name implies, tells the peer to not forward any gossip messages with a
432 // timestamp older than a given value (not the time the peer received the filter, but the
433 // timestamp in the update message, which is often hours behind when the peer received the
436 // Obnoxiously, `gossip_timestamp_filter` isn't *just* a filter, but its also a request for
437 // your peer to send you the full routing graph (subject to the filter). Thus, in order to
438 // tell a peer to send you any updates as it sees them, you have to also ask for the full
439 // routing graph to be synced. If you set a timestamp filter near the current time, peers
440 // will simply not forward any new updates they see to you which were generated some time
441 // ago (which is not uncommon). If you instead set a timestamp filter near 0 (or two weeks
442 // ago), you will always get the full routing graph from all your peers.
444 // Most lightning nodes today opt to simply turn off receiving gossip data which only
445 // propagated some time after it was generated, and, worse, often disable gossiping with
446 // several peers after their first connection. The second behavior can cause gossip to not
447 // propagate fully if there are cuts in the gossiping subgraph.
449 // In an attempt to cut a middle ground between always fetching the full graph from all of
450 // our peers and never receiving gossip from peers at all, we send all of our peers a
451 // `gossip_timestamp_filter`, with the filter time set either two weeks ago or an hour ago.
453 // For no-std builds, we bury our head in the sand and do a full sync on each connection.
454 let should_request_full_sync = self.should_request_full_sync(&their_node_id);
455 #[allow(unused_mut, unused_assignments)]
456 let mut gossip_start_time = 0;
457 #[cfg(feature = "std")]
459 gossip_start_time = SystemTime::now().duration_since(UNIX_EPOCH).expect("Time must be > 1970").as_secs();
460 if should_request_full_sync {
461 gossip_start_time -= 60 * 60 * 24 * 7 * 2; // 2 weeks ago
463 gossip_start_time -= 60 * 60; // an hour ago
467 let mut pending_events = self.pending_events.lock().unwrap();
468 pending_events.push(MessageSendEvent::SendGossipTimestampFilter {
469 node_id: their_node_id.clone(),
470 msg: GossipTimestampFilter {
471 chain_hash: self.network_graph.genesis_hash,
472 first_timestamp: gossip_start_time as u32, // 2106 issue!
473 timestamp_range: u32::max_value(),
478 fn handle_reply_channel_range(&self, _their_node_id: &PublicKey, _msg: ReplyChannelRange) -> Result<(), LightningError> {
479 // We don't make queries, so should never receive replies. If, in the future, the set
480 // reconciliation extensions to gossip queries become broadly supported, we should revert
481 // this code to its state pre-0.0.106.
485 fn handle_reply_short_channel_ids_end(&self, _their_node_id: &PublicKey, _msg: ReplyShortChannelIdsEnd) -> Result<(), LightningError> {
486 // We don't make queries, so should never receive replies. If, in the future, the set
487 // reconciliation extensions to gossip queries become broadly supported, we should revert
488 // this code to its state pre-0.0.106.
492 /// Processes a query from a peer by finding announced/public channels whose funding UTXOs
493 /// are in the specified block range. Due to message size limits, large range
494 /// queries may result in several reply messages. This implementation enqueues
495 /// all reply messages into pending events. Each message will allocate just under 65KiB. A full
496 /// sync of the public routing table with 128k channels will generated 16 messages and allocate ~1MB.
497 /// Logic can be changed to reduce allocation if/when a full sync of the routing table impacts
498 /// memory constrained systems.
499 fn handle_query_channel_range(&self, their_node_id: &PublicKey, msg: QueryChannelRange) -> Result<(), LightningError> {
500 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);
502 let inclusive_start_scid = scid_from_parts(msg.first_blocknum as u64, 0, 0);
504 // We might receive valid queries with end_blocknum that would overflow SCID conversion.
505 // If so, we manually cap the ending block to avoid this overflow.
506 let exclusive_end_scid = scid_from_parts(cmp::min(msg.end_blocknum() as u64, MAX_SCID_BLOCK), 0, 0);
508 // Per spec, we must reply to a query. Send an empty message when things are invalid.
509 if msg.chain_hash != self.network_graph.genesis_hash || inclusive_start_scid.is_err() || exclusive_end_scid.is_err() || msg.number_of_blocks == 0 {
510 let mut pending_events = self.pending_events.lock().unwrap();
511 pending_events.push(MessageSendEvent::SendReplyChannelRange {
512 node_id: their_node_id.clone(),
513 msg: ReplyChannelRange {
514 chain_hash: msg.chain_hash.clone(),
515 first_blocknum: msg.first_blocknum,
516 number_of_blocks: msg.number_of_blocks,
518 short_channel_ids: vec![],
521 return Err(LightningError {
522 err: String::from("query_channel_range could not be processed"),
523 action: ErrorAction::IgnoreError,
527 // Creates channel batches. We are not checking if the channel is routable
528 // (has at least one update). A peer may still want to know the channel
529 // exists even if its not yet routable.
530 let mut batches: Vec<Vec<u64>> = vec![Vec::with_capacity(MAX_SCIDS_PER_REPLY)];
531 let channels = self.network_graph.channels.read().unwrap();
532 for (_, ref chan) in channels.range(inclusive_start_scid.unwrap()..exclusive_end_scid.unwrap()) {
533 if let Some(chan_announcement) = &chan.announcement_message {
534 // Construct a new batch if last one is full
535 if batches.last().unwrap().len() == batches.last().unwrap().capacity() {
536 batches.push(Vec::with_capacity(MAX_SCIDS_PER_REPLY));
539 let batch = batches.last_mut().unwrap();
540 batch.push(chan_announcement.contents.short_channel_id);
545 let mut pending_events = self.pending_events.lock().unwrap();
546 let batch_count = batches.len();
547 let mut prev_batch_endblock = msg.first_blocknum;
548 for (batch_index, batch) in batches.into_iter().enumerate() {
549 // Per spec, the initial `first_blocknum` needs to be <= the query's `first_blocknum`
550 // and subsequent `first_blocknum`s must be >= the prior reply's `first_blocknum`.
552 // Additionally, c-lightning versions < 0.10 require that the `first_blocknum` of each
553 // reply is >= the previous reply's `first_blocknum` and either exactly the previous
554 // reply's `first_blocknum + number_of_blocks` or exactly one greater. This is a
555 // significant diversion from the requirements set by the spec, and, in case of blocks
556 // with no channel opens (e.g. empty blocks), requires that we use the previous value
557 // and *not* derive the first_blocknum from the actual first block of the reply.
558 let first_blocknum = prev_batch_endblock;
560 // Each message carries the number of blocks (from the `first_blocknum`) its contents
561 // fit in. Though there is no requirement that we use exactly the number of blocks its
562 // contents are from, except for the bogus requirements c-lightning enforces, above.
564 // Per spec, the last end block (ie `first_blocknum + number_of_blocks`) needs to be
565 // >= the query's end block. Thus, for the last reply, we calculate the difference
566 // between the query's end block and the start of the reply.
568 // Overflow safe since end_blocknum=msg.first_block_num+msg.number_of_blocks and
569 // first_blocknum will be either msg.first_blocknum or a higher block height.
570 let (sync_complete, number_of_blocks) = if batch_index == batch_count-1 {
571 (true, msg.end_blocknum() - first_blocknum)
573 // Prior replies should use the number of blocks that fit into the reply. Overflow
574 // safe since first_blocknum is always <= last SCID's block.
576 (false, block_from_scid(batch.last().unwrap()) - first_blocknum)
579 prev_batch_endblock = first_blocknum + number_of_blocks;
581 pending_events.push(MessageSendEvent::SendReplyChannelRange {
582 node_id: their_node_id.clone(),
583 msg: ReplyChannelRange {
584 chain_hash: msg.chain_hash.clone(),
588 short_channel_ids: batch,
596 fn handle_query_short_channel_ids(&self, _their_node_id: &PublicKey, _msg: QueryShortChannelIds) -> Result<(), LightningError> {
599 err: String::from("Not implemented"),
600 action: ErrorAction::IgnoreError,
605 impl<G: Deref<Target=NetworkGraph>, C: Deref, L: Deref> MessageSendEventsProvider for NetGraphMsgHandler<G, C, L>
607 C::Target: chain::Access,
610 fn get_and_clear_pending_msg_events(&self) -> Vec<MessageSendEvent> {
611 let mut ret = Vec::new();
612 let mut pending_events = self.pending_events.lock().unwrap();
613 core::mem::swap(&mut ret, &mut pending_events);
618 #[derive(Clone, Debug, PartialEq)]
619 /// Details about one direction of a channel as received within a [`ChannelUpdate`].
620 pub struct ChannelUpdateInfo {
621 /// When the last update to the channel direction was issued.
622 /// Value is opaque, as set in the announcement.
623 pub last_update: u32,
624 /// Whether the channel can be currently used for payments (in this one direction).
626 /// The difference in CLTV values that you must have when routing through this channel.
627 pub cltv_expiry_delta: u16,
628 /// The minimum value, which must be relayed to the next hop via the channel
629 pub htlc_minimum_msat: u64,
630 /// The maximum value which may be relayed to the next hop via the channel.
631 pub htlc_maximum_msat: Option<u64>,
632 /// Fees charged when the channel is used for routing
633 pub fees: RoutingFees,
634 /// Most recent update for the channel received from the network
635 /// Mostly redundant with the data we store in fields explicitly.
636 /// Everything else is useful only for sending out for initial routing sync.
637 /// Not stored if contains excess data to prevent DoS.
638 pub last_update_message: Option<ChannelUpdate>,
641 impl fmt::Display for ChannelUpdateInfo {
642 fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
643 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)?;
648 impl_writeable_tlv_based!(ChannelUpdateInfo, {
649 (0, last_update, required),
650 (2, enabled, required),
651 (4, cltv_expiry_delta, required),
652 (6, htlc_minimum_msat, required),
653 (8, htlc_maximum_msat, required),
654 (10, fees, required),
655 (12, last_update_message, required),
658 #[derive(Clone, Debug, PartialEq)]
659 /// Details about a channel (both directions).
660 /// Received within a channel announcement.
661 pub struct ChannelInfo {
662 /// Protocol features of a channel communicated during its announcement
663 pub features: ChannelFeatures,
664 /// Source node of the first direction of a channel
665 pub node_one: NodeId,
666 /// Details about the first direction of a channel
667 pub one_to_two: Option<ChannelUpdateInfo>,
668 /// Source node of the second direction of a channel
669 pub node_two: NodeId,
670 /// Details about the second direction of a channel
671 pub two_to_one: Option<ChannelUpdateInfo>,
672 /// The channel capacity as seen on-chain, if chain lookup is available.
673 pub capacity_sats: Option<u64>,
674 /// An initial announcement of the channel
675 /// Mostly redundant with the data we store in fields explicitly.
676 /// Everything else is useful only for sending out for initial routing sync.
677 /// Not stored if contains excess data to prevent DoS.
678 pub announcement_message: Option<ChannelAnnouncement>,
679 /// The timestamp when we received the announcement, if we are running with feature = "std"
680 /// (which we can probably assume we are - no-std environments probably won't have a full
681 /// network graph in memory!).
682 announcement_received_time: u64,
686 /// Returns a [`DirectedChannelInfo`] for the channel directed to the given `target` from a
687 /// returned `source`, or `None` if `target` is not one of the channel's counterparties.
688 pub fn as_directed_to(&self, target: &NodeId) -> Option<(DirectedChannelInfo, &NodeId)> {
689 let (direction, source) = {
690 if target == &self.node_one {
691 (self.two_to_one.as_ref(), &self.node_two)
692 } else if target == &self.node_two {
693 (self.one_to_two.as_ref(), &self.node_one)
698 Some((DirectedChannelInfo::new(self, direction), source))
701 /// Returns a [`DirectedChannelInfo`] for the channel directed from the given `source` to a
702 /// returned `target`, or `None` if `source` is not one of the channel's counterparties.
703 pub fn as_directed_from(&self, source: &NodeId) -> Option<(DirectedChannelInfo, &NodeId)> {
704 let (direction, target) = {
705 if source == &self.node_one {
706 (self.one_to_two.as_ref(), &self.node_two)
707 } else if source == &self.node_two {
708 (self.two_to_one.as_ref(), &self.node_one)
713 Some((DirectedChannelInfo::new(self, direction), target))
716 /// Returns a [`ChannelUpdateInfo`] based on the direction implied by the channel_flag.
717 pub fn get_directional_info(&self, channel_flags: u8) -> Option<&ChannelUpdateInfo> {
718 let direction = channel_flags & 1u8;
720 self.one_to_two.as_ref()
722 self.two_to_one.as_ref()
727 impl fmt::Display for ChannelInfo {
728 fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
729 write!(f, "features: {}, node_one: {}, one_to_two: {:?}, node_two: {}, two_to_one: {:?}",
730 log_bytes!(self.features.encode()), log_bytes!(self.node_one.as_slice()), self.one_to_two, log_bytes!(self.node_two.as_slice()), self.two_to_one)?;
735 impl_writeable_tlv_based!(ChannelInfo, {
736 (0, features, required),
737 (1, announcement_received_time, (default_value, 0)),
738 (2, node_one, required),
739 (4, one_to_two, required),
740 (6, node_two, required),
741 (8, two_to_one, required),
742 (10, capacity_sats, required),
743 (12, announcement_message, required),
746 /// A wrapper around [`ChannelInfo`] representing information about the channel as directed from a
747 /// source node to a target node.
749 pub struct DirectedChannelInfo<'a> {
750 channel: &'a ChannelInfo,
751 direction: Option<&'a ChannelUpdateInfo>,
752 htlc_maximum_msat: u64,
753 effective_capacity: EffectiveCapacity,
756 impl<'a> DirectedChannelInfo<'a> {
758 fn new(channel: &'a ChannelInfo, direction: Option<&'a ChannelUpdateInfo>) -> Self {
759 let htlc_maximum_msat = direction.and_then(|direction| direction.htlc_maximum_msat);
760 let capacity_msat = channel.capacity_sats.map(|capacity_sats| capacity_sats * 1000);
762 let (htlc_maximum_msat, effective_capacity) = match (htlc_maximum_msat, capacity_msat) {
763 (Some(amount_msat), Some(capacity_msat)) => {
764 let htlc_maximum_msat = cmp::min(amount_msat, capacity_msat);
765 (htlc_maximum_msat, EffectiveCapacity::Total { capacity_msat })
767 (Some(amount_msat), None) => {
768 (amount_msat, EffectiveCapacity::MaximumHTLC { amount_msat })
770 (None, Some(capacity_msat)) => {
771 (capacity_msat, EffectiveCapacity::Total { capacity_msat })
773 (None, None) => (EffectiveCapacity::Unknown.as_msat(), EffectiveCapacity::Unknown),
777 channel, direction, htlc_maximum_msat, effective_capacity
781 /// Returns information for the channel.
782 pub fn channel(&self) -> &'a ChannelInfo { self.channel }
784 /// Returns information for the direction.
785 pub fn direction(&self) -> Option<&'a ChannelUpdateInfo> { self.direction }
787 /// Returns the maximum HTLC amount allowed over the channel in the direction.
788 pub fn htlc_maximum_msat(&self) -> u64 {
789 self.htlc_maximum_msat
792 /// Returns the [`EffectiveCapacity`] of the channel in the direction.
794 /// This is either the total capacity from the funding transaction, if known, or the
795 /// `htlc_maximum_msat` for the direction as advertised by the gossip network, if known,
797 pub fn effective_capacity(&self) -> EffectiveCapacity {
798 self.effective_capacity
801 /// Returns `Some` if [`ChannelUpdateInfo`] is available in the direction.
802 pub(super) fn with_update(self) -> Option<DirectedChannelInfoWithUpdate<'a>> {
803 match self.direction {
804 Some(_) => Some(DirectedChannelInfoWithUpdate { inner: self }),
810 impl<'a> fmt::Debug for DirectedChannelInfo<'a> {
811 fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
812 f.debug_struct("DirectedChannelInfo")
813 .field("channel", &self.channel)
818 /// A [`DirectedChannelInfo`] with [`ChannelUpdateInfo`] available in its direction.
820 pub(super) struct DirectedChannelInfoWithUpdate<'a> {
821 inner: DirectedChannelInfo<'a>,
824 impl<'a> DirectedChannelInfoWithUpdate<'a> {
825 /// Returns information for the channel.
827 pub(super) fn channel(&self) -> &'a ChannelInfo { &self.inner.channel }
829 /// Returns information for the direction.
831 pub(super) fn direction(&self) -> &'a ChannelUpdateInfo { self.inner.direction.unwrap() }
833 /// Returns the [`EffectiveCapacity`] of the channel in the direction.
835 pub(super) fn effective_capacity(&self) -> EffectiveCapacity { self.inner.effective_capacity() }
837 /// Returns the maximum HTLC amount allowed over the channel in the direction.
839 pub(super) fn htlc_maximum_msat(&self) -> u64 { self.inner.htlc_maximum_msat() }
842 impl<'a> fmt::Debug for DirectedChannelInfoWithUpdate<'a> {
843 fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
848 /// The effective capacity of a channel for routing purposes.
850 /// While this may be smaller than the actual channel capacity, amounts greater than
851 /// [`Self::as_msat`] should not be routed through the channel.
852 #[derive(Clone, Copy)]
853 pub enum EffectiveCapacity {
854 /// The available liquidity in the channel known from being a channel counterparty, and thus a
857 /// Either the inbound or outbound liquidity depending on the direction, denominated in
861 /// The maximum HTLC amount in one direction as advertised on the gossip network.
863 /// The maximum HTLC amount denominated in millisatoshi.
866 /// The total capacity of the channel as determined by the funding transaction.
868 /// The funding amount denominated in millisatoshi.
871 /// A capacity sufficient to route any payment, typically used for private channels provided by
874 /// A capacity that is unknown possibly because either the chain state is unavailable to know
875 /// the total capacity or the `htlc_maximum_msat` was not advertised on the gossip network.
879 /// The presumed channel capacity denominated in millisatoshi for [`EffectiveCapacity::Unknown`] to
880 /// use when making routing decisions.
881 pub const UNKNOWN_CHANNEL_CAPACITY_MSAT: u64 = 250_000 * 1000;
883 impl EffectiveCapacity {
884 /// Returns the effective capacity denominated in millisatoshi.
885 pub fn as_msat(&self) -> u64 {
887 EffectiveCapacity::ExactLiquidity { liquidity_msat } => *liquidity_msat,
888 EffectiveCapacity::MaximumHTLC { amount_msat } => *amount_msat,
889 EffectiveCapacity::Total { capacity_msat } => *capacity_msat,
890 EffectiveCapacity::Infinite => u64::max_value(),
891 EffectiveCapacity::Unknown => UNKNOWN_CHANNEL_CAPACITY_MSAT,
896 /// Fees for routing via a given channel or a node
897 #[derive(Eq, PartialEq, Copy, Clone, Debug, Hash)]
898 pub struct RoutingFees {
899 /// Flat routing fee in satoshis
901 /// Liquidity-based routing fee in millionths of a routed amount.
902 /// In other words, 10000 is 1%.
903 pub proportional_millionths: u32,
906 impl_writeable_tlv_based!(RoutingFees, {
907 (0, base_msat, required),
908 (2, proportional_millionths, required)
911 #[derive(Clone, Debug, PartialEq)]
912 /// Information received in the latest node_announcement from this node.
913 pub struct NodeAnnouncementInfo {
914 /// Protocol features the node announced support for
915 pub features: NodeFeatures,
916 /// When the last known update to the node state was issued.
917 /// Value is opaque, as set in the announcement.
918 pub last_update: u32,
919 /// Color assigned to the node
921 /// Moniker assigned to the node.
922 /// May be invalid or malicious (eg control chars),
923 /// should not be exposed to the user.
925 /// Internet-level addresses via which one can connect to the node
926 pub addresses: Vec<NetAddress>,
927 /// An initial announcement of the node
928 /// Mostly redundant with the data we store in fields explicitly.
929 /// Everything else is useful only for sending out for initial routing sync.
930 /// Not stored if contains excess data to prevent DoS.
931 pub announcement_message: Option<NodeAnnouncement>
934 impl_writeable_tlv_based!(NodeAnnouncementInfo, {
935 (0, features, required),
936 (2, last_update, required),
938 (6, alias, required),
939 (8, announcement_message, option),
940 (10, addresses, vec_type),
943 #[derive(Clone, Debug, PartialEq)]
944 /// Details about a node in the network, known from the network announcement.
945 pub struct NodeInfo {
946 /// All valid channels a node has announced
947 pub channels: Vec<u64>,
948 /// Lowest fees enabling routing via any of the enabled, known channels to a node.
949 /// The two fields (flat and proportional fee) are independent,
950 /// meaning they don't have to refer to the same channel.
951 pub lowest_inbound_channel_fees: Option<RoutingFees>,
952 /// More information about a node from node_announcement.
953 /// Optional because we store a Node entry after learning about it from
954 /// a channel announcement, but before receiving a node announcement.
955 pub announcement_info: Option<NodeAnnouncementInfo>
958 impl fmt::Display for NodeInfo {
959 fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
960 write!(f, "lowest_inbound_channel_fees: {:?}, channels: {:?}, announcement_info: {:?}",
961 self.lowest_inbound_channel_fees, &self.channels[..], self.announcement_info)?;
966 impl_writeable_tlv_based!(NodeInfo, {
967 (0, lowest_inbound_channel_fees, option),
968 (2, announcement_info, option),
969 (4, channels, vec_type),
972 const SERIALIZATION_VERSION: u8 = 1;
973 const MIN_SERIALIZATION_VERSION: u8 = 1;
975 impl Writeable for NetworkGraph {
976 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
977 write_ver_prefix!(writer, SERIALIZATION_VERSION, MIN_SERIALIZATION_VERSION);
979 self.genesis_hash.write(writer)?;
980 let channels = self.channels.read().unwrap();
981 (channels.len() as u64).write(writer)?;
982 for (ref chan_id, ref chan_info) in channels.iter() {
983 (*chan_id).write(writer)?;
984 chan_info.write(writer)?;
986 let nodes = self.nodes.read().unwrap();
987 (nodes.len() as u64).write(writer)?;
988 for (ref node_id, ref node_info) in nodes.iter() {
989 node_id.write(writer)?;
990 node_info.write(writer)?;
993 write_tlv_fields!(writer, {});
998 impl Readable for NetworkGraph {
999 fn read<R: io::Read>(reader: &mut R) -> Result<NetworkGraph, DecodeError> {
1000 let _ver = read_ver_prefix!(reader, SERIALIZATION_VERSION);
1002 let genesis_hash: BlockHash = Readable::read(reader)?;
1003 let channels_count: u64 = Readable::read(reader)?;
1004 let mut channels = BTreeMap::new();
1005 for _ in 0..channels_count {
1006 let chan_id: u64 = Readable::read(reader)?;
1007 let chan_info = Readable::read(reader)?;
1008 channels.insert(chan_id, chan_info);
1010 let nodes_count: u64 = Readable::read(reader)?;
1011 let mut nodes = BTreeMap::new();
1012 for _ in 0..nodes_count {
1013 let node_id = Readable::read(reader)?;
1014 let node_info = Readable::read(reader)?;
1015 nodes.insert(node_id, node_info);
1017 read_tlv_fields!(reader, {});
1021 channels: RwLock::new(channels),
1022 nodes: RwLock::new(nodes),
1027 impl fmt::Display for NetworkGraph {
1028 fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
1029 writeln!(f, "Network map\n[Channels]")?;
1030 for (key, val) in self.channels.read().unwrap().iter() {
1031 writeln!(f, " {}: {}", key, val)?;
1033 writeln!(f, "[Nodes]")?;
1034 for (&node_id, val) in self.nodes.read().unwrap().iter() {
1035 writeln!(f, " {}: {}", log_bytes!(node_id.as_slice()), val)?;
1041 impl PartialEq for NetworkGraph {
1042 fn eq(&self, other: &Self) -> bool {
1043 self.genesis_hash == other.genesis_hash &&
1044 *self.channels.read().unwrap() == *other.channels.read().unwrap() &&
1045 *self.nodes.read().unwrap() == *other.nodes.read().unwrap()
1050 /// Creates a new, empty, network graph.
1051 pub fn new(genesis_hash: BlockHash) -> NetworkGraph {
1054 channels: RwLock::new(BTreeMap::new()),
1055 nodes: RwLock::new(BTreeMap::new()),
1059 /// Returns a read-only view of the network graph.
1060 pub fn read_only(&'_ self) -> ReadOnlyNetworkGraph<'_> {
1061 let channels = self.channels.read().unwrap();
1062 let nodes = self.nodes.read().unwrap();
1063 ReadOnlyNetworkGraph {
1069 /// Clears the `NodeAnnouncementInfo` field for all nodes in the `NetworkGraph` for testing
1072 pub fn clear_nodes_announcement_info(&self) {
1073 for node in self.nodes.write().unwrap().iter_mut() {
1074 node.1.announcement_info = None;
1078 /// For an already known node (from channel announcements), update its stored properties from a
1079 /// given node announcement.
1081 /// You probably don't want to call this directly, instead relying on a NetGraphMsgHandler's
1082 /// RoutingMessageHandler implementation to call it indirectly. This may be useful to accept
1083 /// routing messages from a source using a protocol other than the lightning P2P protocol.
1084 pub fn update_node_from_announcement<T: secp256k1::Verification>(&self, msg: &msgs::NodeAnnouncement, secp_ctx: &Secp256k1<T>) -> Result<(), LightningError> {
1085 let msg_hash = hash_to_message!(&Sha256dHash::hash(&msg.contents.encode()[..])[..]);
1086 secp_verify_sig!(secp_ctx, &msg_hash, &msg.signature, &msg.contents.node_id, "node_announcement");
1087 self.update_node_from_announcement_intern(&msg.contents, Some(&msg))
1090 /// For an already known node (from channel announcements), update its stored properties from a
1091 /// given node announcement without verifying the associated signatures. Because we aren't
1092 /// given the associated signatures here we cannot relay the node announcement to any of our
1094 pub fn update_node_from_unsigned_announcement(&self, msg: &msgs::UnsignedNodeAnnouncement) -> Result<(), LightningError> {
1095 self.update_node_from_announcement_intern(msg, None)
1098 fn update_node_from_announcement_intern(&self, msg: &msgs::UnsignedNodeAnnouncement, full_msg: Option<&msgs::NodeAnnouncement>) -> Result<(), LightningError> {
1099 match self.nodes.write().unwrap().get_mut(&NodeId::from_pubkey(&msg.node_id)) {
1100 None => Err(LightningError{err: "No existing channels for node_announcement".to_owned(), action: ErrorAction::IgnoreError}),
1102 if let Some(node_info) = node.announcement_info.as_ref() {
1103 // The timestamp field is somewhat of a misnomer - the BOLTs use it to order
1104 // updates to ensure you always have the latest one, only vaguely suggesting
1105 // that it be at least the current time.
1106 if node_info.last_update > msg.timestamp {
1107 return Err(LightningError{err: "Update older than last processed update".to_owned(), action: ErrorAction::IgnoreAndLog(Level::Gossip)});
1108 } else if node_info.last_update == msg.timestamp {
1109 return Err(LightningError{err: "Update had the same timestamp as last processed update".to_owned(), action: ErrorAction::IgnoreDuplicateGossip});
1114 msg.excess_data.len() <= MAX_EXCESS_BYTES_FOR_RELAY &&
1115 msg.excess_address_data.len() <= MAX_EXCESS_BYTES_FOR_RELAY &&
1116 msg.excess_data.len() + msg.excess_address_data.len() <= MAX_EXCESS_BYTES_FOR_RELAY;
1117 node.announcement_info = Some(NodeAnnouncementInfo {
1118 features: msg.features.clone(),
1119 last_update: msg.timestamp,
1122 addresses: msg.addresses.clone(),
1123 announcement_message: if should_relay { full_msg.cloned() } else { None },
1131 /// Store or update channel info from a channel announcement.
1133 /// You probably don't want to call this directly, instead relying on a NetGraphMsgHandler's
1134 /// RoutingMessageHandler implementation to call it indirectly. This may be useful to accept
1135 /// routing messages from a source using a protocol other than the lightning P2P protocol.
1137 /// If a `chain::Access` object is provided via `chain_access`, it will be called to verify
1138 /// the corresponding UTXO exists on chain and is correctly-formatted.
1139 pub fn update_channel_from_announcement<T: secp256k1::Verification, C: Deref>(
1140 &self, msg: &msgs::ChannelAnnouncement, chain_access: &Option<C>, secp_ctx: &Secp256k1<T>
1141 ) -> Result<(), LightningError>
1143 C::Target: chain::Access,
1145 let msg_hash = hash_to_message!(&Sha256dHash::hash(&msg.contents.encode()[..])[..]);
1146 secp_verify_sig!(secp_ctx, &msg_hash, &msg.node_signature_1, &msg.contents.node_id_1, "channel_announcement");
1147 secp_verify_sig!(secp_ctx, &msg_hash, &msg.node_signature_2, &msg.contents.node_id_2, "channel_announcement");
1148 secp_verify_sig!(secp_ctx, &msg_hash, &msg.bitcoin_signature_1, &msg.contents.bitcoin_key_1, "channel_announcement");
1149 secp_verify_sig!(secp_ctx, &msg_hash, &msg.bitcoin_signature_2, &msg.contents.bitcoin_key_2, "channel_announcement");
1150 self.update_channel_from_unsigned_announcement_intern(&msg.contents, Some(msg), chain_access)
1153 /// Store or update channel info from a channel announcement without verifying the associated
1154 /// signatures. Because we aren't given the associated signatures here we cannot relay the
1155 /// channel announcement to any of our peers.
1157 /// If a `chain::Access` object is provided via `chain_access`, it will be called to verify
1158 /// the corresponding UTXO exists on chain and is correctly-formatted.
1159 pub fn update_channel_from_unsigned_announcement<C: Deref>(
1160 &self, msg: &msgs::UnsignedChannelAnnouncement, chain_access: &Option<C>
1161 ) -> Result<(), LightningError>
1163 C::Target: chain::Access,
1165 self.update_channel_from_unsigned_announcement_intern(msg, None, chain_access)
1168 /// Update channel from partial announcement data received via rapid gossip sync
1170 /// `timestamp: u64`: Timestamp emulating the backdated original announcement receipt (by the
1171 /// rapid gossip sync server)
1173 /// All other parameters as used in [`msgs::UnsignedChannelAnnouncement`] fields.
1174 pub fn add_channel_from_partial_announcement(&self, short_channel_id: u64, timestamp: u64, features: ChannelFeatures, node_id_1: PublicKey, node_id_2: PublicKey) -> Result<(), LightningError> {
1175 if node_id_1 == node_id_2 {
1176 return Err(LightningError{err: "Channel announcement node had a channel with itself".to_owned(), action: ErrorAction::IgnoreError});
1179 let node_1 = NodeId::from_pubkey(&node_id_1);
1180 let node_2 = NodeId::from_pubkey(&node_id_2);
1181 let channel_info = ChannelInfo {
1183 node_one: node_1.clone(),
1185 node_two: node_2.clone(),
1187 capacity_sats: None,
1188 announcement_message: None,
1189 announcement_received_time: timestamp,
1192 self.add_channel_between_nodes(short_channel_id, channel_info, None)
1195 fn add_channel_between_nodes(&self, short_channel_id: u64, channel_info: ChannelInfo, utxo_value: Option<u64>) -> Result<(), LightningError> {
1196 let mut channels = self.channels.write().unwrap();
1197 let mut nodes = self.nodes.write().unwrap();
1199 let node_id_a = channel_info.node_one.clone();
1200 let node_id_b = channel_info.node_two.clone();
1202 match channels.entry(short_channel_id) {
1203 BtreeEntry::Occupied(mut entry) => {
1204 //TODO: because asking the blockchain if short_channel_id is valid is only optional
1205 //in the blockchain API, we need to handle it smartly here, though it's unclear
1207 if utxo_value.is_some() {
1208 // Either our UTXO provider is busted, there was a reorg, or the UTXO provider
1209 // only sometimes returns results. In any case remove the previous entry. Note
1210 // that the spec expects us to "blacklist" the node_ids involved, but we can't
1212 // a) we don't *require* a UTXO provider that always returns results.
1213 // b) we don't track UTXOs of channels we know about and remove them if they
1215 // c) it's unclear how to do so without exposing ourselves to massive DoS risk.
1216 Self::remove_channel_in_nodes(&mut nodes, &entry.get(), short_channel_id);
1217 *entry.get_mut() = channel_info;
1219 return Err(LightningError{err: "Already have knowledge of channel".to_owned(), action: ErrorAction::IgnoreDuplicateGossip});
1222 BtreeEntry::Vacant(entry) => {
1223 entry.insert(channel_info);
1227 for current_node_id in [node_id_a, node_id_b].iter() {
1228 match nodes.entry(current_node_id.clone()) {
1229 BtreeEntry::Occupied(node_entry) => {
1230 node_entry.into_mut().channels.push(short_channel_id);
1232 BtreeEntry::Vacant(node_entry) => {
1233 node_entry.insert(NodeInfo {
1234 channels: vec!(short_channel_id),
1235 lowest_inbound_channel_fees: None,
1236 announcement_info: None,
1245 fn update_channel_from_unsigned_announcement_intern<C: Deref>(
1246 &self, msg: &msgs::UnsignedChannelAnnouncement, full_msg: Option<&msgs::ChannelAnnouncement>, chain_access: &Option<C>
1247 ) -> Result<(), LightningError>
1249 C::Target: chain::Access,
1251 if msg.node_id_1 == msg.node_id_2 || msg.bitcoin_key_1 == msg.bitcoin_key_2 {
1252 return Err(LightningError{err: "Channel announcement node had a channel with itself".to_owned(), action: ErrorAction::IgnoreError});
1255 let utxo_value = match &chain_access {
1257 // Tentatively accept, potentially exposing us to DoS attacks
1260 &Some(ref chain_access) => {
1261 match chain_access.get_utxo(&msg.chain_hash, msg.short_channel_id) {
1262 Ok(TxOut { value, script_pubkey }) => {
1263 let expected_script = Builder::new().push_opcode(opcodes::all::OP_PUSHNUM_2)
1264 .push_slice(&msg.bitcoin_key_1.serialize())
1265 .push_slice(&msg.bitcoin_key_2.serialize())
1266 .push_opcode(opcodes::all::OP_PUSHNUM_2)
1267 .push_opcode(opcodes::all::OP_CHECKMULTISIG).into_script().to_v0_p2wsh();
1268 if script_pubkey != expected_script {
1269 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});
1271 //TODO: Check if value is worth storing, use it to inform routing, and compare it
1272 //to the new HTLC max field in channel_update
1275 Err(chain::AccessError::UnknownChain) => {
1276 return Err(LightningError{err: format!("Channel announced on an unknown chain ({})", msg.chain_hash.encode().to_hex()), action: ErrorAction::IgnoreError});
1278 Err(chain::AccessError::UnknownTx) => {
1279 return Err(LightningError{err: "Channel announced without corresponding UTXO entry".to_owned(), action: ErrorAction::IgnoreError});
1285 #[allow(unused_mut, unused_assignments)]
1286 let mut announcement_received_time = 0;
1287 #[cfg(feature = "std")]
1289 announcement_received_time = SystemTime::now().duration_since(UNIX_EPOCH).expect("Time must be > 1970").as_secs();
1292 let chan_info = ChannelInfo {
1293 features: msg.features.clone(),
1294 node_one: NodeId::from_pubkey(&msg.node_id_1),
1296 node_two: NodeId::from_pubkey(&msg.node_id_2),
1298 capacity_sats: utxo_value,
1299 announcement_message: if msg.excess_data.len() <= MAX_EXCESS_BYTES_FOR_RELAY
1300 { full_msg.cloned() } else { None },
1301 announcement_received_time,
1304 self.add_channel_between_nodes(msg.short_channel_id, chan_info, utxo_value)
1307 /// Close a channel if a corresponding HTLC fail was sent.
1308 /// If permanent, removes a channel from the local storage.
1309 /// May cause the removal of nodes too, if this was their last channel.
1310 /// If not permanent, makes channels unavailable for routing.
1311 pub fn close_channel_from_update(&self, short_channel_id: u64, is_permanent: bool) {
1312 let mut channels = self.channels.write().unwrap();
1314 if let Some(chan) = channels.remove(&short_channel_id) {
1315 let mut nodes = self.nodes.write().unwrap();
1316 Self::remove_channel_in_nodes(&mut nodes, &chan, short_channel_id);
1319 if let Some(chan) = channels.get_mut(&short_channel_id) {
1320 if let Some(one_to_two) = chan.one_to_two.as_mut() {
1321 one_to_two.enabled = false;
1323 if let Some(two_to_one) = chan.two_to_one.as_mut() {
1324 two_to_one.enabled = false;
1330 /// Marks a node in the graph as failed.
1331 pub fn fail_node(&self, _node_id: &PublicKey, is_permanent: bool) {
1333 // TODO: Wholly remove the node
1335 // TODO: downgrade the node
1339 #[cfg(feature = "std")]
1340 /// Removes information about channels that we haven't heard any updates about in some time.
1341 /// This can be used regularly to prune the network graph of channels that likely no longer
1344 /// While there is no formal requirement that nodes regularly re-broadcast their channel
1345 /// updates every two weeks, the non-normative section of BOLT 7 currently suggests that
1346 /// pruning occur for updates which are at least two weeks old, which we implement here.
1348 /// Note that for users of the `lightning-background-processor` crate this method may be
1349 /// automatically called regularly for you.
1351 /// This method is only available with the `std` feature. See
1352 /// [`NetworkGraph::remove_stale_channels_with_time`] for `no-std` use.
1353 pub fn remove_stale_channels(&self) {
1354 let time = SystemTime::now().duration_since(UNIX_EPOCH).expect("Time must be > 1970").as_secs();
1355 self.remove_stale_channels_with_time(time);
1358 /// Removes information about channels that we haven't heard any updates about in some time.
1359 /// This can be used regularly to prune the network graph of channels that likely no longer
1362 /// While there is no formal requirement that nodes regularly re-broadcast their channel
1363 /// updates every two weeks, the non-normative section of BOLT 7 currently suggests that
1364 /// pruning occur for updates which are at least two weeks old, which we implement here.
1366 /// This function takes the current unix time as an argument. For users with the `std` feature
1367 /// enabled, [`NetworkGraph::remove_stale_channels`] may be preferable.
1368 pub fn remove_stale_channels_with_time(&self, current_time_unix: u64) {
1369 let mut channels = self.channels.write().unwrap();
1370 // Time out if we haven't received an update in at least 14 days.
1371 if current_time_unix > u32::max_value() as u64 { return; } // Remove by 2106
1372 if current_time_unix < STALE_CHANNEL_UPDATE_AGE_LIMIT_SECS { return; }
1373 let min_time_unix: u32 = (current_time_unix - STALE_CHANNEL_UPDATE_AGE_LIMIT_SECS) as u32;
1374 // Sadly BTreeMap::retain was only stabilized in 1.53 so we can't switch to it for some
1376 let mut scids_to_remove = Vec::new();
1377 for (scid, info) in channels.iter_mut() {
1378 if info.one_to_two.is_some() && info.one_to_two.as_ref().unwrap().last_update < min_time_unix {
1379 info.one_to_two = None;
1381 if info.two_to_one.is_some() && info.two_to_one.as_ref().unwrap().last_update < min_time_unix {
1382 info.two_to_one = None;
1384 if info.one_to_two.is_none() && info.two_to_one.is_none() {
1385 // We check the announcement_received_time here to ensure we don't drop
1386 // announcements that we just received and are just waiting for our peer to send a
1387 // channel_update for.
1388 if info.announcement_received_time < min_time_unix as u64 {
1389 scids_to_remove.push(*scid);
1393 if !scids_to_remove.is_empty() {
1394 let mut nodes = self.nodes.write().unwrap();
1395 for scid in scids_to_remove {
1396 let info = channels.remove(&scid).expect("We just accessed this scid, it should be present");
1397 Self::remove_channel_in_nodes(&mut nodes, &info, scid);
1402 /// For an already known (from announcement) channel, update info about one of the directions
1405 /// You probably don't want to call this directly, instead relying on a NetGraphMsgHandler's
1406 /// RoutingMessageHandler implementation to call it indirectly. This may be useful to accept
1407 /// routing messages from a source using a protocol other than the lightning P2P protocol.
1409 /// If built with `no-std`, any updates with a timestamp more than two weeks in the past or
1410 /// materially in the future will be rejected.
1411 pub fn update_channel<T: secp256k1::Verification>(&self, msg: &msgs::ChannelUpdate, secp_ctx: &Secp256k1<T>) -> Result<(), LightningError> {
1412 self.update_channel_intern(&msg.contents, Some(&msg), Some((&msg.signature, secp_ctx)))
1415 /// For an already known (from announcement) channel, update info about one of the directions
1416 /// of the channel without verifying the associated signatures. Because we aren't given the
1417 /// associated signatures here we cannot relay the channel update to any of our peers.
1419 /// If built with `no-std`, any updates with a timestamp more than two weeks in the past or
1420 /// materially in the future will be rejected.
1421 pub fn update_channel_unsigned(&self, msg: &msgs::UnsignedChannelUpdate) -> Result<(), LightningError> {
1422 self.update_channel_intern(msg, None, None::<(&secp256k1::ecdsa::Signature, &Secp256k1<secp256k1::VerifyOnly>)>)
1425 fn update_channel_intern<T: secp256k1::Verification>(&self, msg: &msgs::UnsignedChannelUpdate, full_msg: Option<&msgs::ChannelUpdate>, sig_info: Option<(&secp256k1::ecdsa::Signature, &Secp256k1<T>)>) -> Result<(), LightningError> {
1427 let chan_enabled = msg.flags & (1 << 1) != (1 << 1);
1428 let chan_was_enabled;
1430 #[cfg(all(feature = "std", not(test), not(feature = "_test_utils")))]
1432 // Note that many tests rely on being able to set arbitrarily old timestamps, thus we
1433 // disable this check during tests!
1434 let time = SystemTime::now().duration_since(UNIX_EPOCH).expect("Time must be > 1970").as_secs();
1435 if (msg.timestamp as u64) < time - STALE_CHANNEL_UPDATE_AGE_LIMIT_SECS {
1436 return Err(LightningError{err: "channel_update is older than two weeks old".to_owned(), action: ErrorAction::IgnoreAndLog(Level::Gossip)});
1438 if msg.timestamp as u64 > time + 60 * 60 * 24 {
1439 return Err(LightningError{err: "channel_update has a timestamp more than a day in the future".to_owned(), action: ErrorAction::IgnoreAndLog(Level::Gossip)});
1443 let mut channels = self.channels.write().unwrap();
1444 match channels.get_mut(&msg.short_channel_id) {
1445 None => return Err(LightningError{err: "Couldn't find channel for update".to_owned(), action: ErrorAction::IgnoreError}),
1447 if let OptionalField::Present(htlc_maximum_msat) = msg.htlc_maximum_msat {
1448 if htlc_maximum_msat > MAX_VALUE_MSAT {
1449 return Err(LightningError{err: "htlc_maximum_msat is larger than maximum possible msats".to_owned(), action: ErrorAction::IgnoreError});
1452 if let Some(capacity_sats) = channel.capacity_sats {
1453 // It's possible channel capacity is available now, although it wasn't available at announcement (so the field is None).
1454 // Don't query UTXO set here to reduce DoS risks.
1455 if capacity_sats > MAX_VALUE_MSAT / 1000 || htlc_maximum_msat > capacity_sats * 1000 {
1456 return Err(LightningError{err: "htlc_maximum_msat is larger than channel capacity or capacity is bogus".to_owned(), action: ErrorAction::IgnoreError});
1460 macro_rules! check_update_latest {
1461 ($target: expr) => {
1462 if let Some(existing_chan_info) = $target.as_ref() {
1463 // The timestamp field is somewhat of a misnomer - the BOLTs use it to
1464 // order updates to ensure you always have the latest one, only
1465 // suggesting that it be at least the current time. For
1466 // channel_updates specifically, the BOLTs discuss the possibility of
1467 // pruning based on the timestamp field being more than two weeks old,
1468 // but only in the non-normative section.
1469 if existing_chan_info.last_update > msg.timestamp {
1470 return Err(LightningError{err: "Update older than last processed update".to_owned(), action: ErrorAction::IgnoreAndLog(Level::Gossip)});
1471 } else if existing_chan_info.last_update == msg.timestamp {
1472 return Err(LightningError{err: "Update had same timestamp as last processed update".to_owned(), action: ErrorAction::IgnoreDuplicateGossip});
1474 chan_was_enabled = existing_chan_info.enabled;
1476 chan_was_enabled = false;
1481 macro_rules! get_new_channel_info {
1483 let last_update_message = if msg.excess_data.len() <= MAX_EXCESS_BYTES_FOR_RELAY
1484 { full_msg.cloned() } else { None };
1486 let updated_channel_update_info = ChannelUpdateInfo {
1487 enabled: chan_enabled,
1488 last_update: msg.timestamp,
1489 cltv_expiry_delta: msg.cltv_expiry_delta,
1490 htlc_minimum_msat: msg.htlc_minimum_msat,
1491 htlc_maximum_msat: if let OptionalField::Present(max_value) = msg.htlc_maximum_msat { Some(max_value) } else { None },
1493 base_msat: msg.fee_base_msat,
1494 proportional_millionths: msg.fee_proportional_millionths,
1498 Some(updated_channel_update_info)
1502 let msg_hash = hash_to_message!(&Sha256dHash::hash(&msg.encode()[..])[..]);
1503 if msg.flags & 1 == 1 {
1504 dest_node_id = channel.node_one.clone();
1505 check_update_latest!(channel.two_to_one);
1506 if let Some((sig, ctx)) = sig_info {
1507 secp_verify_sig!(ctx, &msg_hash, &sig, &PublicKey::from_slice(channel.node_two.as_slice()).map_err(|_| LightningError{
1508 err: "Couldn't parse source node pubkey".to_owned(),
1509 action: ErrorAction::IgnoreAndLog(Level::Debug)
1510 })?, "channel_update");
1512 channel.two_to_one = get_new_channel_info!();
1514 dest_node_id = channel.node_two.clone();
1515 check_update_latest!(channel.one_to_two);
1516 if let Some((sig, ctx)) = sig_info {
1517 secp_verify_sig!(ctx, &msg_hash, &sig, &PublicKey::from_slice(channel.node_one.as_slice()).map_err(|_| LightningError{
1518 err: "Couldn't parse destination node pubkey".to_owned(),
1519 action: ErrorAction::IgnoreAndLog(Level::Debug)
1520 })?, "channel_update");
1522 channel.one_to_two = get_new_channel_info!();
1527 let mut nodes = self.nodes.write().unwrap();
1529 let node = nodes.get_mut(&dest_node_id).unwrap();
1530 let mut base_msat = msg.fee_base_msat;
1531 let mut proportional_millionths = msg.fee_proportional_millionths;
1532 if let Some(fees) = node.lowest_inbound_channel_fees {
1533 base_msat = cmp::min(base_msat, fees.base_msat);
1534 proportional_millionths = cmp::min(proportional_millionths, fees.proportional_millionths);
1536 node.lowest_inbound_channel_fees = Some(RoutingFees {
1538 proportional_millionths
1540 } else if chan_was_enabled {
1541 let node = nodes.get_mut(&dest_node_id).unwrap();
1542 let mut lowest_inbound_channel_fees = None;
1544 for chan_id in node.channels.iter() {
1545 let chan = channels.get(chan_id).unwrap();
1547 if chan.node_one == dest_node_id {
1548 chan_info_opt = chan.two_to_one.as_ref();
1550 chan_info_opt = chan.one_to_two.as_ref();
1552 if let Some(chan_info) = chan_info_opt {
1553 if chan_info.enabled {
1554 let fees = lowest_inbound_channel_fees.get_or_insert(RoutingFees {
1555 base_msat: u32::max_value(), proportional_millionths: u32::max_value() });
1556 fees.base_msat = cmp::min(fees.base_msat, chan_info.fees.base_msat);
1557 fees.proportional_millionths = cmp::min(fees.proportional_millionths, chan_info.fees.proportional_millionths);
1562 node.lowest_inbound_channel_fees = lowest_inbound_channel_fees;
1568 fn remove_channel_in_nodes(nodes: &mut BTreeMap<NodeId, NodeInfo>, chan: &ChannelInfo, short_channel_id: u64) {
1569 macro_rules! remove_from_node {
1570 ($node_id: expr) => {
1571 if let BtreeEntry::Occupied(mut entry) = nodes.entry($node_id) {
1572 entry.get_mut().channels.retain(|chan_id| {
1573 short_channel_id != *chan_id
1575 if entry.get().channels.is_empty() {
1576 entry.remove_entry();
1579 panic!("Had channel that pointed to unknown node (ie inconsistent network map)!");
1584 remove_from_node!(chan.node_one);
1585 remove_from_node!(chan.node_two);
1589 impl ReadOnlyNetworkGraph<'_> {
1590 /// Returns all known valid channels' short ids along with announced channel info.
1592 /// (C-not exported) because we have no mapping for `BTreeMap`s
1593 pub fn channels(&self) -> &BTreeMap<u64, ChannelInfo> {
1597 /// Returns all known nodes' public keys along with announced node info.
1599 /// (C-not exported) because we have no mapping for `BTreeMap`s
1600 pub fn nodes(&self) -> &BTreeMap<NodeId, NodeInfo> {
1604 /// Get network addresses by node id.
1605 /// Returns None if the requested node is completely unknown,
1606 /// or if node announcement for the node was never received.
1607 pub fn get_addresses(&self, pubkey: &PublicKey) -> Option<Vec<NetAddress>> {
1608 if let Some(node) = self.nodes.get(&NodeId::from_pubkey(&pubkey)) {
1609 if let Some(node_info) = node.announcement_info.as_ref() {
1610 return Some(node_info.addresses.clone())
1620 use ln::PaymentHash;
1621 use ln::features::{ChannelFeatures, InitFeatures, NodeFeatures};
1622 use routing::network_graph::{NetGraphMsgHandler, NetworkGraph, NetworkUpdate, MAX_EXCESS_BYTES_FOR_RELAY};
1623 use ln::msgs::{Init, OptionalField, RoutingMessageHandler, UnsignedNodeAnnouncement, NodeAnnouncement,
1624 UnsignedChannelAnnouncement, ChannelAnnouncement, UnsignedChannelUpdate, ChannelUpdate,
1625 ReplyChannelRange, QueryChannelRange, QueryShortChannelIds, MAX_VALUE_MSAT};
1626 use util::test_utils;
1627 use util::logger::Logger;
1628 use util::ser::{Readable, Writeable};
1629 use util::events::{Event, EventHandler, MessageSendEvent, MessageSendEventsProvider};
1630 use util::scid_utils::scid_from_parts;
1632 use super::STALE_CHANNEL_UPDATE_AGE_LIMIT_SECS;
1634 use bitcoin::hashes::sha256d::Hash as Sha256dHash;
1635 use bitcoin::hashes::Hash;
1636 use bitcoin::network::constants::Network;
1637 use bitcoin::blockdata::constants::genesis_block;
1638 use bitcoin::blockdata::script::{Builder, Script};
1639 use bitcoin::blockdata::transaction::TxOut;
1640 use bitcoin::blockdata::opcodes;
1644 use bitcoin::secp256k1::{PublicKey, SecretKey};
1645 use bitcoin::secp256k1::{All, Secp256k1};
1648 use bitcoin::secp256k1;
1652 fn create_network_graph() -> NetworkGraph {
1653 let genesis_hash = genesis_block(Network::Testnet).header.block_hash();
1654 NetworkGraph::new(genesis_hash)
1657 fn create_net_graph_msg_handler(network_graph: &NetworkGraph) -> (
1658 Secp256k1<All>, NetGraphMsgHandler<&NetworkGraph, Arc<test_utils::TestChainSource>, Arc<test_utils::TestLogger>>
1660 let secp_ctx = Secp256k1::new();
1661 let logger = Arc::new(test_utils::TestLogger::new());
1662 let net_graph_msg_handler = NetGraphMsgHandler::new(network_graph, None, Arc::clone(&logger));
1663 (secp_ctx, net_graph_msg_handler)
1667 fn request_full_sync_finite_times() {
1668 let network_graph = create_network_graph();
1669 let (secp_ctx, net_graph_msg_handler) = create_net_graph_msg_handler(&network_graph);
1670 let node_id = PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&hex::decode("0202020202020202020202020202020202020202020202020202020202020202").unwrap()[..]).unwrap());
1672 assert!(net_graph_msg_handler.should_request_full_sync(&node_id));
1673 assert!(net_graph_msg_handler.should_request_full_sync(&node_id));
1674 assert!(net_graph_msg_handler.should_request_full_sync(&node_id));
1675 assert!(net_graph_msg_handler.should_request_full_sync(&node_id));
1676 assert!(net_graph_msg_handler.should_request_full_sync(&node_id));
1677 assert!(!net_graph_msg_handler.should_request_full_sync(&node_id));
1680 fn get_signed_node_announcement<F: Fn(&mut UnsignedNodeAnnouncement)>(f: F, node_key: &SecretKey, secp_ctx: &Secp256k1<secp256k1::All>) -> NodeAnnouncement {
1681 let node_id = PublicKey::from_secret_key(&secp_ctx, node_key);
1682 let mut unsigned_announcement = UnsignedNodeAnnouncement {
1683 features: NodeFeatures::known(),
1688 addresses: Vec::new(),
1689 excess_address_data: Vec::new(),
1690 excess_data: Vec::new(),
1692 f(&mut unsigned_announcement);
1693 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1695 signature: secp_ctx.sign_ecdsa(&msghash, node_key),
1696 contents: unsigned_announcement
1700 fn get_signed_channel_announcement<F: Fn(&mut UnsignedChannelAnnouncement)>(f: F, node_1_key: &SecretKey, node_2_key: &SecretKey, secp_ctx: &Secp256k1<secp256k1::All>) -> ChannelAnnouncement {
1701 let node_id_1 = PublicKey::from_secret_key(&secp_ctx, node_1_key);
1702 let node_id_2 = PublicKey::from_secret_key(&secp_ctx, node_2_key);
1703 let node_1_btckey = &SecretKey::from_slice(&[40; 32]).unwrap();
1704 let node_2_btckey = &SecretKey::from_slice(&[39; 32]).unwrap();
1706 let mut unsigned_announcement = UnsignedChannelAnnouncement {
1707 features: ChannelFeatures::known(),
1708 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1709 short_channel_id: 0,
1712 bitcoin_key_1: PublicKey::from_secret_key(&secp_ctx, node_1_btckey),
1713 bitcoin_key_2: PublicKey::from_secret_key(&secp_ctx, node_2_btckey),
1714 excess_data: Vec::new(),
1716 f(&mut unsigned_announcement);
1717 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1718 ChannelAnnouncement {
1719 node_signature_1: secp_ctx.sign_ecdsa(&msghash, node_1_key),
1720 node_signature_2: secp_ctx.sign_ecdsa(&msghash, node_2_key),
1721 bitcoin_signature_1: secp_ctx.sign_ecdsa(&msghash, node_1_btckey),
1722 bitcoin_signature_2: secp_ctx.sign_ecdsa(&msghash, node_2_btckey),
1723 contents: unsigned_announcement,
1727 fn get_channel_script(secp_ctx: &Secp256k1<secp256k1::All>) -> Script {
1728 let node_1_btckey = &SecretKey::from_slice(&[40; 32]).unwrap();
1729 let node_2_btckey = &SecretKey::from_slice(&[39; 32]).unwrap();
1730 Builder::new().push_opcode(opcodes::all::OP_PUSHNUM_2)
1731 .push_slice(&PublicKey::from_secret_key(&secp_ctx, node_1_btckey).serialize())
1732 .push_slice(&PublicKey::from_secret_key(&secp_ctx, node_2_btckey).serialize())
1733 .push_opcode(opcodes::all::OP_PUSHNUM_2)
1734 .push_opcode(opcodes::all::OP_CHECKMULTISIG).into_script()
1738 fn get_signed_channel_update<F: Fn(&mut UnsignedChannelUpdate)>(f: F, node_key: &SecretKey, secp_ctx: &Secp256k1<secp256k1::All>) -> ChannelUpdate {
1739 let mut unsigned_channel_update = UnsignedChannelUpdate {
1740 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1741 short_channel_id: 0,
1744 cltv_expiry_delta: 144,
1745 htlc_minimum_msat: 1_000_000,
1746 htlc_maximum_msat: OptionalField::Absent,
1747 fee_base_msat: 10_000,
1748 fee_proportional_millionths: 20,
1749 excess_data: Vec::new()
1751 f(&mut unsigned_channel_update);
1752 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_channel_update.encode()[..])[..]);
1754 signature: secp_ctx.sign_ecdsa(&msghash, node_key),
1755 contents: unsigned_channel_update
1760 fn handling_node_announcements() {
1761 let network_graph = create_network_graph();
1762 let (secp_ctx, net_graph_msg_handler) = create_net_graph_msg_handler(&network_graph);
1764 let node_1_privkey = &SecretKey::from_slice(&[42; 32]).unwrap();
1765 let node_2_privkey = &SecretKey::from_slice(&[41; 32]).unwrap();
1766 let zero_hash = Sha256dHash::hash(&[0; 32]);
1768 let valid_announcement = get_signed_node_announcement(|_| {}, node_1_privkey, &secp_ctx);
1769 match net_graph_msg_handler.handle_node_announcement(&valid_announcement) {
1771 Err(e) => assert_eq!("No existing channels for node_announcement", e.err)
1775 // Announce a channel to add a corresponding node.
1776 let valid_announcement = get_signed_channel_announcement(|_| {}, node_1_privkey, node_2_privkey, &secp_ctx);
1777 match net_graph_msg_handler.handle_channel_announcement(&valid_announcement) {
1778 Ok(res) => assert!(res),
1783 match net_graph_msg_handler.handle_node_announcement(&valid_announcement) {
1784 Ok(res) => assert!(res),
1788 let fake_msghash = hash_to_message!(&zero_hash);
1789 match net_graph_msg_handler.handle_node_announcement(
1791 signature: secp_ctx.sign_ecdsa(&fake_msghash, node_1_privkey),
1792 contents: valid_announcement.contents.clone()
1795 Err(e) => assert_eq!(e.err, "Invalid signature on node_announcement message")
1798 let announcement_with_data = get_signed_node_announcement(|unsigned_announcement| {
1799 unsigned_announcement.timestamp += 1000;
1800 unsigned_announcement.excess_data.resize(MAX_EXCESS_BYTES_FOR_RELAY + 1, 0);
1801 }, node_1_privkey, &secp_ctx);
1802 // Return false because contains excess data.
1803 match net_graph_msg_handler.handle_node_announcement(&announcement_with_data) {
1804 Ok(res) => assert!(!res),
1808 // Even though previous announcement was not relayed further, we still accepted it,
1809 // so we now won't accept announcements before the previous one.
1810 let outdated_announcement = get_signed_node_announcement(|unsigned_announcement| {
1811 unsigned_announcement.timestamp += 1000 - 10;
1812 }, node_1_privkey, &secp_ctx);
1813 match net_graph_msg_handler.handle_node_announcement(&outdated_announcement) {
1815 Err(e) => assert_eq!(e.err, "Update older than last processed update")
1820 fn handling_channel_announcements() {
1821 let secp_ctx = Secp256k1::new();
1822 let logger: Arc<Logger> = Arc::new(test_utils::TestLogger::new());
1824 let node_1_privkey = &SecretKey::from_slice(&[42; 32]).unwrap();
1825 let node_2_privkey = &SecretKey::from_slice(&[41; 32]).unwrap();
1827 let good_script = get_channel_script(&secp_ctx);
1828 let valid_announcement = get_signed_channel_announcement(|_| {}, node_1_privkey, node_2_privkey, &secp_ctx);
1830 // Test if the UTXO lookups were not supported
1831 let network_graph = NetworkGraph::new(genesis_block(Network::Testnet).header.block_hash());
1832 let mut net_graph_msg_handler = NetGraphMsgHandler::new(&network_graph, None, Arc::clone(&logger));
1833 match net_graph_msg_handler.handle_channel_announcement(&valid_announcement) {
1834 Ok(res) => assert!(res),
1839 match network_graph.read_only().channels().get(&valid_announcement.contents.short_channel_id) {
1845 // If we receive announcement for the same channel (with UTXO lookups disabled),
1846 // drop new one on the floor, since we can't see any changes.
1847 match net_graph_msg_handler.handle_channel_announcement(&valid_announcement) {
1849 Err(e) => assert_eq!(e.err, "Already have knowledge of channel")
1852 // Test if an associated transaction were not on-chain (or not confirmed).
1853 let chain_source = Arc::new(test_utils::TestChainSource::new(Network::Testnet));
1854 *chain_source.utxo_ret.lock().unwrap() = Err(chain::AccessError::UnknownTx);
1855 let network_graph = NetworkGraph::new(genesis_block(Network::Testnet).header.block_hash());
1856 net_graph_msg_handler = NetGraphMsgHandler::new(&network_graph, Some(chain_source.clone()), Arc::clone(&logger));
1858 let valid_announcement = get_signed_channel_announcement(|unsigned_announcement| {
1859 unsigned_announcement.short_channel_id += 1;
1860 }, node_1_privkey, node_2_privkey, &secp_ctx);
1861 match net_graph_msg_handler.handle_channel_announcement(&valid_announcement) {
1863 Err(e) => assert_eq!(e.err, "Channel announced without corresponding UTXO entry")
1866 // Now test if the transaction is found in the UTXO set and the script is correct.
1867 *chain_source.utxo_ret.lock().unwrap() = Ok(TxOut { value: 0, script_pubkey: good_script.clone() });
1868 let valid_announcement = get_signed_channel_announcement(|unsigned_announcement| {
1869 unsigned_announcement.short_channel_id += 2;
1870 }, node_1_privkey, node_2_privkey, &secp_ctx);
1871 match net_graph_msg_handler.handle_channel_announcement(&valid_announcement) {
1872 Ok(res) => assert!(res),
1877 match network_graph.read_only().channels().get(&valid_announcement.contents.short_channel_id) {
1883 // If we receive announcement for the same channel (but TX is not confirmed),
1884 // drop new one on the floor, since we can't see any changes.
1885 *chain_source.utxo_ret.lock().unwrap() = Err(chain::AccessError::UnknownTx);
1886 match net_graph_msg_handler.handle_channel_announcement(&valid_announcement) {
1888 Err(e) => assert_eq!(e.err, "Channel announced without corresponding UTXO entry")
1891 // But if it is confirmed, replace the channel
1892 *chain_source.utxo_ret.lock().unwrap() = Ok(TxOut { value: 0, script_pubkey: good_script });
1893 let valid_announcement = get_signed_channel_announcement(|unsigned_announcement| {
1894 unsigned_announcement.features = ChannelFeatures::empty();
1895 unsigned_announcement.short_channel_id += 2;
1896 }, node_1_privkey, node_2_privkey, &secp_ctx);
1897 match net_graph_msg_handler.handle_channel_announcement(&valid_announcement) {
1898 Ok(res) => assert!(res),
1902 match network_graph.read_only().channels().get(&valid_announcement.contents.short_channel_id) {
1903 Some(channel_entry) => {
1904 assert_eq!(channel_entry.features, ChannelFeatures::empty());
1910 // Don't relay valid channels with excess data
1911 let valid_announcement = get_signed_channel_announcement(|unsigned_announcement| {
1912 unsigned_announcement.short_channel_id += 3;
1913 unsigned_announcement.excess_data.resize(MAX_EXCESS_BYTES_FOR_RELAY + 1, 0);
1914 }, node_1_privkey, node_2_privkey, &secp_ctx);
1915 match net_graph_msg_handler.handle_channel_announcement(&valid_announcement) {
1916 Ok(res) => assert!(!res),
1920 let mut invalid_sig_announcement = valid_announcement.clone();
1921 invalid_sig_announcement.contents.excess_data = Vec::new();
1922 match net_graph_msg_handler.handle_channel_announcement(&invalid_sig_announcement) {
1924 Err(e) => assert_eq!(e.err, "Invalid signature on channel_announcement message")
1927 let channel_to_itself_announcement = get_signed_channel_announcement(|_| {}, node_1_privkey, node_1_privkey, &secp_ctx);
1928 match net_graph_msg_handler.handle_channel_announcement(&channel_to_itself_announcement) {
1930 Err(e) => assert_eq!(e.err, "Channel announcement node had a channel with itself")
1935 fn handling_channel_update() {
1936 let secp_ctx = Secp256k1::new();
1937 let logger: Arc<Logger> = Arc::new(test_utils::TestLogger::new());
1938 let chain_source = Arc::new(test_utils::TestChainSource::new(Network::Testnet));
1939 let network_graph = NetworkGraph::new(genesis_block(Network::Testnet).header.block_hash());
1940 let net_graph_msg_handler = NetGraphMsgHandler::new(&network_graph, Some(chain_source.clone()), Arc::clone(&logger));
1942 let node_1_privkey = &SecretKey::from_slice(&[42; 32]).unwrap();
1943 let node_2_privkey = &SecretKey::from_slice(&[41; 32]).unwrap();
1945 let amount_sats = 1000_000;
1946 let short_channel_id;
1949 // Announce a channel we will update
1950 let good_script = get_channel_script(&secp_ctx);
1951 *chain_source.utxo_ret.lock().unwrap() = Ok(TxOut { value: amount_sats, script_pubkey: good_script.clone() });
1953 let valid_channel_announcement = get_signed_channel_announcement(|_| {}, node_1_privkey, node_2_privkey, &secp_ctx);
1954 short_channel_id = valid_channel_announcement.contents.short_channel_id;
1955 match net_graph_msg_handler.handle_channel_announcement(&valid_channel_announcement) {
1962 let valid_channel_update = get_signed_channel_update(|_| {}, node_1_privkey, &secp_ctx);
1963 match net_graph_msg_handler.handle_channel_update(&valid_channel_update) {
1964 Ok(res) => assert!(res),
1969 match network_graph.read_only().channels().get(&short_channel_id) {
1971 Some(channel_info) => {
1972 assert_eq!(channel_info.one_to_two.as_ref().unwrap().cltv_expiry_delta, 144);
1973 assert!(channel_info.two_to_one.is_none());
1978 let valid_channel_update = get_signed_channel_update(|unsigned_channel_update| {
1979 unsigned_channel_update.timestamp += 100;
1980 unsigned_channel_update.excess_data.resize(MAX_EXCESS_BYTES_FOR_RELAY + 1, 0);
1981 }, node_1_privkey, &secp_ctx);
1982 // Return false because contains excess data
1983 match net_graph_msg_handler.handle_channel_update(&valid_channel_update) {
1984 Ok(res) => assert!(!res),
1988 let valid_channel_update = get_signed_channel_update(|unsigned_channel_update| {
1989 unsigned_channel_update.timestamp += 110;
1990 unsigned_channel_update.short_channel_id += 1;
1991 }, node_1_privkey, &secp_ctx);
1992 match net_graph_msg_handler.handle_channel_update(&valid_channel_update) {
1994 Err(e) => assert_eq!(e.err, "Couldn't find channel for update")
1997 let valid_channel_update = get_signed_channel_update(|unsigned_channel_update| {
1998 unsigned_channel_update.htlc_maximum_msat = OptionalField::Present(MAX_VALUE_MSAT + 1);
1999 unsigned_channel_update.timestamp += 110;
2000 }, node_1_privkey, &secp_ctx);
2001 match net_graph_msg_handler.handle_channel_update(&valid_channel_update) {
2003 Err(e) => assert_eq!(e.err, "htlc_maximum_msat is larger than maximum possible msats")
2006 let valid_channel_update = get_signed_channel_update(|unsigned_channel_update| {
2007 unsigned_channel_update.htlc_maximum_msat = OptionalField::Present(amount_sats * 1000 + 1);
2008 unsigned_channel_update.timestamp += 110;
2009 }, node_1_privkey, &secp_ctx);
2010 match net_graph_msg_handler.handle_channel_update(&valid_channel_update) {
2012 Err(e) => assert_eq!(e.err, "htlc_maximum_msat is larger than channel capacity or capacity is bogus")
2015 // Even though previous update was not relayed further, we still accepted it,
2016 // so we now won't accept update before the previous one.
2017 let valid_channel_update = get_signed_channel_update(|unsigned_channel_update| {
2018 unsigned_channel_update.timestamp += 100;
2019 }, node_1_privkey, &secp_ctx);
2020 match net_graph_msg_handler.handle_channel_update(&valid_channel_update) {
2022 Err(e) => assert_eq!(e.err, "Update had same timestamp as last processed update")
2025 let mut invalid_sig_channel_update = get_signed_channel_update(|unsigned_channel_update| {
2026 unsigned_channel_update.timestamp += 500;
2027 }, node_1_privkey, &secp_ctx);
2028 let zero_hash = Sha256dHash::hash(&[0; 32]);
2029 let fake_msghash = hash_to_message!(&zero_hash);
2030 invalid_sig_channel_update.signature = secp_ctx.sign_ecdsa(&fake_msghash, node_1_privkey);
2031 match net_graph_msg_handler.handle_channel_update(&invalid_sig_channel_update) {
2033 Err(e) => assert_eq!(e.err, "Invalid signature on channel_update message")
2038 fn handling_network_update() {
2039 let logger = test_utils::TestLogger::new();
2040 let chain_source = Arc::new(test_utils::TestChainSource::new(Network::Testnet));
2041 let genesis_hash = genesis_block(Network::Testnet).header.block_hash();
2042 let network_graph = NetworkGraph::new(genesis_hash);
2043 let net_graph_msg_handler = NetGraphMsgHandler::new(&network_graph, Some(chain_source.clone()), &logger);
2044 let secp_ctx = Secp256k1::new();
2046 let node_1_privkey = &SecretKey::from_slice(&[42; 32]).unwrap();
2047 let node_2_privkey = &SecretKey::from_slice(&[41; 32]).unwrap();
2050 // There is no nodes in the table at the beginning.
2051 assert_eq!(network_graph.read_only().nodes().len(), 0);
2054 let short_channel_id;
2056 // Announce a channel we will update
2057 let valid_channel_announcement = get_signed_channel_announcement(|_| {}, node_1_privkey, node_2_privkey, &secp_ctx);
2058 short_channel_id = valid_channel_announcement.contents.short_channel_id;
2059 let chain_source: Option<&test_utils::TestChainSource> = None;
2060 assert!(network_graph.update_channel_from_announcement(&valid_channel_announcement, &chain_source, &secp_ctx).is_ok());
2061 assert!(network_graph.read_only().channels().get(&short_channel_id).is_some());
2063 let valid_channel_update = get_signed_channel_update(|_| {}, node_1_privkey, &secp_ctx);
2064 assert!(network_graph.read_only().channels().get(&short_channel_id).unwrap().one_to_two.is_none());
2066 net_graph_msg_handler.handle_event(&Event::PaymentPathFailed {
2068 payment_hash: PaymentHash([0; 32]),
2069 rejected_by_dest: false,
2070 all_paths_failed: true,
2072 network_update: Some(NetworkUpdate::ChannelUpdateMessage {
2073 msg: valid_channel_update,
2075 short_channel_id: None,
2081 assert!(network_graph.read_only().channels().get(&short_channel_id).unwrap().one_to_two.is_some());
2084 // Non-permanent closing just disables a channel
2086 match network_graph.read_only().channels().get(&short_channel_id) {
2088 Some(channel_info) => {
2089 assert!(channel_info.one_to_two.as_ref().unwrap().enabled);
2093 net_graph_msg_handler.handle_event(&Event::PaymentPathFailed {
2095 payment_hash: PaymentHash([0; 32]),
2096 rejected_by_dest: false,
2097 all_paths_failed: true,
2099 network_update: Some(NetworkUpdate::ChannelClosed {
2101 is_permanent: false,
2103 short_channel_id: None,
2109 match network_graph.read_only().channels().get(&short_channel_id) {
2111 Some(channel_info) => {
2112 assert!(!channel_info.one_to_two.as_ref().unwrap().enabled);
2117 // Permanent closing deletes a channel
2118 net_graph_msg_handler.handle_event(&Event::PaymentPathFailed {
2120 payment_hash: PaymentHash([0; 32]),
2121 rejected_by_dest: false,
2122 all_paths_failed: true,
2124 network_update: Some(NetworkUpdate::ChannelClosed {
2128 short_channel_id: None,
2134 assert_eq!(network_graph.read_only().channels().len(), 0);
2135 // Nodes are also deleted because there are no associated channels anymore
2136 assert_eq!(network_graph.read_only().nodes().len(), 0);
2137 // TODO: Test NetworkUpdate::NodeFailure, which is not implemented yet.
2141 fn test_channel_timeouts() {
2142 // Test the removal of channels with `remove_stale_channels`.
2143 let logger = test_utils::TestLogger::new();
2144 let chain_source = Arc::new(test_utils::TestChainSource::new(Network::Testnet));
2145 let genesis_hash = genesis_block(Network::Testnet).header.block_hash();
2146 let network_graph = NetworkGraph::new(genesis_hash);
2147 let net_graph_msg_handler = NetGraphMsgHandler::new(&network_graph, Some(chain_source.clone()), &logger);
2148 let secp_ctx = Secp256k1::new();
2150 let node_1_privkey = &SecretKey::from_slice(&[42; 32]).unwrap();
2151 let node_2_privkey = &SecretKey::from_slice(&[41; 32]).unwrap();
2153 let valid_channel_announcement = get_signed_channel_announcement(|_| {}, node_1_privkey, node_2_privkey, &secp_ctx);
2154 let short_channel_id = valid_channel_announcement.contents.short_channel_id;
2155 let chain_source: Option<&test_utils::TestChainSource> = None;
2156 assert!(network_graph.update_channel_from_announcement(&valid_channel_announcement, &chain_source, &secp_ctx).is_ok());
2157 assert!(network_graph.read_only().channels().get(&short_channel_id).is_some());
2159 let valid_channel_update = get_signed_channel_update(|_| {}, node_1_privkey, &secp_ctx);
2160 assert!(net_graph_msg_handler.handle_channel_update(&valid_channel_update).is_ok());
2161 assert!(network_graph.read_only().channels().get(&short_channel_id).unwrap().one_to_two.is_some());
2163 network_graph.remove_stale_channels_with_time(100 + STALE_CHANNEL_UPDATE_AGE_LIMIT_SECS);
2164 assert_eq!(network_graph.read_only().channels().len(), 1);
2165 assert_eq!(network_graph.read_only().nodes().len(), 2);
2167 network_graph.remove_stale_channels_with_time(101 + STALE_CHANNEL_UPDATE_AGE_LIMIT_SECS);
2168 #[cfg(feature = "std")]
2170 // In std mode, a further check is performed before fully removing the channel -
2171 // the channel_announcement must have been received at least two weeks ago. We
2172 // fudge that here by indicating the time has jumped two weeks. Note that the
2173 // directional channel information will have been removed already..
2174 assert_eq!(network_graph.read_only().channels().len(), 1);
2175 assert_eq!(network_graph.read_only().nodes().len(), 2);
2176 assert!(network_graph.read_only().channels().get(&short_channel_id).unwrap().one_to_two.is_none());
2178 use std::time::{SystemTime, UNIX_EPOCH};
2179 let announcement_time = SystemTime::now().duration_since(UNIX_EPOCH).expect("Time must be > 1970").as_secs();
2180 network_graph.remove_stale_channels_with_time(announcement_time + 1 + STALE_CHANNEL_UPDATE_AGE_LIMIT_SECS);
2183 assert_eq!(network_graph.read_only().channels().len(), 0);
2184 assert_eq!(network_graph.read_only().nodes().len(), 0);
2188 fn getting_next_channel_announcements() {
2189 let network_graph = create_network_graph();
2190 let (secp_ctx, net_graph_msg_handler) = create_net_graph_msg_handler(&network_graph);
2191 let node_1_privkey = &SecretKey::from_slice(&[42; 32]).unwrap();
2192 let node_2_privkey = &SecretKey::from_slice(&[41; 32]).unwrap();
2194 // Channels were not announced yet.
2195 let channels_with_announcements = net_graph_msg_handler.get_next_channel_announcements(0, 1);
2196 assert_eq!(channels_with_announcements.len(), 0);
2198 let short_channel_id;
2200 // Announce a channel we will update
2201 let valid_channel_announcement = get_signed_channel_announcement(|_| {}, node_1_privkey, node_2_privkey, &secp_ctx);
2202 short_channel_id = valid_channel_announcement.contents.short_channel_id;
2203 match net_graph_msg_handler.handle_channel_announcement(&valid_channel_announcement) {
2209 // Contains initial channel announcement now.
2210 let channels_with_announcements = net_graph_msg_handler.get_next_channel_announcements(short_channel_id, 1);
2211 assert_eq!(channels_with_announcements.len(), 1);
2212 if let Some(channel_announcements) = channels_with_announcements.first() {
2213 let &(_, ref update_1, ref update_2) = channel_announcements;
2214 assert_eq!(update_1, &None);
2215 assert_eq!(update_2, &None);
2222 // Valid channel update
2223 let valid_channel_update = get_signed_channel_update(|unsigned_channel_update| {
2224 unsigned_channel_update.timestamp = 101;
2225 }, node_1_privkey, &secp_ctx);
2226 match net_graph_msg_handler.handle_channel_update(&valid_channel_update) {
2232 // Now contains an initial announcement and an update.
2233 let channels_with_announcements = net_graph_msg_handler.get_next_channel_announcements(short_channel_id, 1);
2234 assert_eq!(channels_with_announcements.len(), 1);
2235 if let Some(channel_announcements) = channels_with_announcements.first() {
2236 let &(_, ref update_1, ref update_2) = channel_announcements;
2237 assert_ne!(update_1, &None);
2238 assert_eq!(update_2, &None);
2244 // Channel update with excess data.
2245 let valid_channel_update = get_signed_channel_update(|unsigned_channel_update| {
2246 unsigned_channel_update.timestamp = 102;
2247 unsigned_channel_update.excess_data = [1; MAX_EXCESS_BYTES_FOR_RELAY + 1].to_vec();
2248 }, node_1_privkey, &secp_ctx);
2249 match net_graph_msg_handler.handle_channel_update(&valid_channel_update) {
2255 // Test that announcements with excess data won't be returned
2256 let channels_with_announcements = net_graph_msg_handler.get_next_channel_announcements(short_channel_id, 1);
2257 assert_eq!(channels_with_announcements.len(), 1);
2258 if let Some(channel_announcements) = channels_with_announcements.first() {
2259 let &(_, ref update_1, ref update_2) = channel_announcements;
2260 assert_eq!(update_1, &None);
2261 assert_eq!(update_2, &None);
2266 // Further starting point have no channels after it
2267 let channels_with_announcements = net_graph_msg_handler.get_next_channel_announcements(short_channel_id + 1000, 1);
2268 assert_eq!(channels_with_announcements.len(), 0);
2272 fn getting_next_node_announcements() {
2273 let network_graph = create_network_graph();
2274 let (secp_ctx, net_graph_msg_handler) = create_net_graph_msg_handler(&network_graph);
2275 let node_1_privkey = &SecretKey::from_slice(&[42; 32]).unwrap();
2276 let node_2_privkey = &SecretKey::from_slice(&[41; 32]).unwrap();
2277 let node_id_1 = PublicKey::from_secret_key(&secp_ctx, node_1_privkey);
2280 let next_announcements = net_graph_msg_handler.get_next_node_announcements(None, 10);
2281 assert_eq!(next_announcements.len(), 0);
2284 // Announce a channel to add 2 nodes
2285 let valid_channel_announcement = get_signed_channel_announcement(|_| {}, node_1_privkey, node_2_privkey, &secp_ctx);
2286 match net_graph_msg_handler.handle_channel_announcement(&valid_channel_announcement) {
2293 // Nodes were never announced
2294 let next_announcements = net_graph_msg_handler.get_next_node_announcements(None, 3);
2295 assert_eq!(next_announcements.len(), 0);
2298 let valid_announcement = get_signed_node_announcement(|_| {}, node_1_privkey, &secp_ctx);
2299 match net_graph_msg_handler.handle_node_announcement(&valid_announcement) {
2304 let valid_announcement = get_signed_node_announcement(|_| {}, node_2_privkey, &secp_ctx);
2305 match net_graph_msg_handler.handle_node_announcement(&valid_announcement) {
2311 let next_announcements = net_graph_msg_handler.get_next_node_announcements(None, 3);
2312 assert_eq!(next_announcements.len(), 2);
2314 // Skip the first node.
2315 let next_announcements = net_graph_msg_handler.get_next_node_announcements(Some(&node_id_1), 2);
2316 assert_eq!(next_announcements.len(), 1);
2319 // Later announcement which should not be relayed (excess data) prevent us from sharing a node
2320 let valid_announcement = get_signed_node_announcement(|unsigned_announcement| {
2321 unsigned_announcement.timestamp += 10;
2322 unsigned_announcement.excess_data = [1; MAX_EXCESS_BYTES_FOR_RELAY + 1].to_vec();
2323 }, node_2_privkey, &secp_ctx);
2324 match net_graph_msg_handler.handle_node_announcement(&valid_announcement) {
2325 Ok(res) => assert!(!res),
2330 let next_announcements = net_graph_msg_handler.get_next_node_announcements(Some(&node_id_1), 2);
2331 assert_eq!(next_announcements.len(), 0);
2335 fn network_graph_serialization() {
2336 let network_graph = create_network_graph();
2337 let (secp_ctx, net_graph_msg_handler) = create_net_graph_msg_handler(&network_graph);
2339 let node_1_privkey = &SecretKey::from_slice(&[42; 32]).unwrap();
2340 let node_2_privkey = &SecretKey::from_slice(&[41; 32]).unwrap();
2342 // Announce a channel to add a corresponding node.
2343 let valid_announcement = get_signed_channel_announcement(|_| {}, node_1_privkey, node_2_privkey, &secp_ctx);
2344 match net_graph_msg_handler.handle_channel_announcement(&valid_announcement) {
2345 Ok(res) => assert!(res),
2349 let valid_announcement = get_signed_node_announcement(|_| {}, node_1_privkey, &secp_ctx);
2350 match net_graph_msg_handler.handle_node_announcement(&valid_announcement) {
2355 let mut w = test_utils::TestVecWriter(Vec::new());
2356 assert!(!network_graph.read_only().nodes().is_empty());
2357 assert!(!network_graph.read_only().channels().is_empty());
2358 network_graph.write(&mut w).unwrap();
2359 assert!(<NetworkGraph>::read(&mut io::Cursor::new(&w.0)).unwrap() == network_graph);
2363 #[cfg(feature = "std")]
2364 fn calling_sync_routing_table() {
2365 use std::time::{SystemTime, UNIX_EPOCH};
2367 let network_graph = create_network_graph();
2368 let (secp_ctx, net_graph_msg_handler) = create_net_graph_msg_handler(&network_graph);
2369 let node_privkey_1 = &SecretKey::from_slice(&[42; 32]).unwrap();
2370 let node_id_1 = PublicKey::from_secret_key(&secp_ctx, node_privkey_1);
2372 let chain_hash = genesis_block(Network::Testnet).header.block_hash();
2374 // It should ignore if gossip_queries feature is not enabled
2376 let init_msg = Init { features: InitFeatures::known().clear_gossip_queries(), remote_network_address: None };
2377 net_graph_msg_handler.peer_connected(&node_id_1, &init_msg);
2378 let events = net_graph_msg_handler.get_and_clear_pending_msg_events();
2379 assert_eq!(events.len(), 0);
2382 // It should send a gossip_timestamp_filter with the correct information
2384 let init_msg = Init { features: InitFeatures::known(), remote_network_address: None };
2385 net_graph_msg_handler.peer_connected(&node_id_1, &init_msg);
2386 let events = net_graph_msg_handler.get_and_clear_pending_msg_events();
2387 assert_eq!(events.len(), 1);
2389 MessageSendEvent::SendGossipTimestampFilter{ node_id, msg } => {
2390 assert_eq!(node_id, &node_id_1);
2391 assert_eq!(msg.chain_hash, chain_hash);
2392 let expected_timestamp = SystemTime::now().duration_since(UNIX_EPOCH).expect("Time must be > 1970").as_secs();
2393 assert!((msg.first_timestamp as u64) >= expected_timestamp - 60*60*24*7*2);
2394 assert!((msg.first_timestamp as u64) < expected_timestamp - 60*60*24*7*2 + 10);
2395 assert_eq!(msg.timestamp_range, u32::max_value());
2397 _ => panic!("Expected MessageSendEvent::SendChannelRangeQuery")
2403 fn handling_query_channel_range() {
2404 let network_graph = create_network_graph();
2405 let (secp_ctx, net_graph_msg_handler) = create_net_graph_msg_handler(&network_graph);
2407 let chain_hash = genesis_block(Network::Testnet).header.block_hash();
2408 let node_1_privkey = &SecretKey::from_slice(&[42; 32]).unwrap();
2409 let node_2_privkey = &SecretKey::from_slice(&[41; 32]).unwrap();
2410 let node_id_2 = PublicKey::from_secret_key(&secp_ctx, node_2_privkey);
2412 let mut scids: Vec<u64> = vec![
2413 scid_from_parts(0xfffffe, 0xffffff, 0xffff).unwrap(), // max
2414 scid_from_parts(0xffffff, 0xffffff, 0xffff).unwrap(), // never
2417 // used for testing multipart reply across blocks
2418 for block in 100000..=108001 {
2419 scids.push(scid_from_parts(block, 0, 0).unwrap());
2422 // used for testing resumption on same block
2423 scids.push(scid_from_parts(108001, 1, 0).unwrap());
2426 let valid_announcement = get_signed_channel_announcement(|unsigned_announcement| {
2427 unsigned_announcement.short_channel_id = scid;
2428 }, node_1_privkey, node_2_privkey, &secp_ctx);
2429 match net_graph_msg_handler.handle_channel_announcement(&valid_announcement) {
2435 // Error when number_of_blocks=0
2436 do_handling_query_channel_range(
2437 &net_graph_msg_handler,
2440 chain_hash: chain_hash.clone(),
2442 number_of_blocks: 0,
2445 vec![ReplyChannelRange {
2446 chain_hash: chain_hash.clone(),
2448 number_of_blocks: 0,
2449 sync_complete: true,
2450 short_channel_ids: vec![]
2454 // Error when wrong chain
2455 do_handling_query_channel_range(
2456 &net_graph_msg_handler,
2459 chain_hash: genesis_block(Network::Bitcoin).header.block_hash(),
2461 number_of_blocks: 0xffff_ffff,
2464 vec![ReplyChannelRange {
2465 chain_hash: genesis_block(Network::Bitcoin).header.block_hash(),
2467 number_of_blocks: 0xffff_ffff,
2468 sync_complete: true,
2469 short_channel_ids: vec![],
2473 // Error when first_blocknum > 0xffffff
2474 do_handling_query_channel_range(
2475 &net_graph_msg_handler,
2478 chain_hash: chain_hash.clone(),
2479 first_blocknum: 0x01000000,
2480 number_of_blocks: 0xffff_ffff,
2483 vec![ReplyChannelRange {
2484 chain_hash: chain_hash.clone(),
2485 first_blocknum: 0x01000000,
2486 number_of_blocks: 0xffff_ffff,
2487 sync_complete: true,
2488 short_channel_ids: vec![]
2492 // Empty reply when max valid SCID block num
2493 do_handling_query_channel_range(
2494 &net_graph_msg_handler,
2497 chain_hash: chain_hash.clone(),
2498 first_blocknum: 0xffffff,
2499 number_of_blocks: 1,
2504 chain_hash: chain_hash.clone(),
2505 first_blocknum: 0xffffff,
2506 number_of_blocks: 1,
2507 sync_complete: true,
2508 short_channel_ids: vec![]
2513 // No results in valid query range
2514 do_handling_query_channel_range(
2515 &net_graph_msg_handler,
2518 chain_hash: chain_hash.clone(),
2519 first_blocknum: 1000,
2520 number_of_blocks: 1000,
2525 chain_hash: chain_hash.clone(),
2526 first_blocknum: 1000,
2527 number_of_blocks: 1000,
2528 sync_complete: true,
2529 short_channel_ids: vec![],
2534 // Overflow first_blocknum + number_of_blocks
2535 do_handling_query_channel_range(
2536 &net_graph_msg_handler,
2539 chain_hash: chain_hash.clone(),
2540 first_blocknum: 0xfe0000,
2541 number_of_blocks: 0xffffffff,
2546 chain_hash: chain_hash.clone(),
2547 first_blocknum: 0xfe0000,
2548 number_of_blocks: 0xffffffff - 0xfe0000,
2549 sync_complete: true,
2550 short_channel_ids: vec![
2551 0xfffffe_ffffff_ffff, // max
2557 // Single block exactly full
2558 do_handling_query_channel_range(
2559 &net_graph_msg_handler,
2562 chain_hash: chain_hash.clone(),
2563 first_blocknum: 100000,
2564 number_of_blocks: 8000,
2569 chain_hash: chain_hash.clone(),
2570 first_blocknum: 100000,
2571 number_of_blocks: 8000,
2572 sync_complete: true,
2573 short_channel_ids: (100000..=107999)
2574 .map(|block| scid_from_parts(block, 0, 0).unwrap())
2580 // Multiple split on new block
2581 do_handling_query_channel_range(
2582 &net_graph_msg_handler,
2585 chain_hash: chain_hash.clone(),
2586 first_blocknum: 100000,
2587 number_of_blocks: 8001,
2592 chain_hash: chain_hash.clone(),
2593 first_blocknum: 100000,
2594 number_of_blocks: 7999,
2595 sync_complete: false,
2596 short_channel_ids: (100000..=107999)
2597 .map(|block| scid_from_parts(block, 0, 0).unwrap())
2601 chain_hash: chain_hash.clone(),
2602 first_blocknum: 107999,
2603 number_of_blocks: 2,
2604 sync_complete: true,
2605 short_channel_ids: vec![
2606 scid_from_parts(108000, 0, 0).unwrap(),
2612 // Multiple split on same block
2613 do_handling_query_channel_range(
2614 &net_graph_msg_handler,
2617 chain_hash: chain_hash.clone(),
2618 first_blocknum: 100002,
2619 number_of_blocks: 8000,
2624 chain_hash: chain_hash.clone(),
2625 first_blocknum: 100002,
2626 number_of_blocks: 7999,
2627 sync_complete: false,
2628 short_channel_ids: (100002..=108001)
2629 .map(|block| scid_from_parts(block, 0, 0).unwrap())
2633 chain_hash: chain_hash.clone(),
2634 first_blocknum: 108001,
2635 number_of_blocks: 1,
2636 sync_complete: true,
2637 short_channel_ids: vec![
2638 scid_from_parts(108001, 1, 0).unwrap(),
2645 fn do_handling_query_channel_range(
2646 net_graph_msg_handler: &NetGraphMsgHandler<&NetworkGraph, Arc<test_utils::TestChainSource>, Arc<test_utils::TestLogger>>,
2647 test_node_id: &PublicKey,
2648 msg: QueryChannelRange,
2650 expected_replies: Vec<ReplyChannelRange>
2652 let mut max_firstblocknum = msg.first_blocknum.saturating_sub(1);
2653 let mut c_lightning_0_9_prev_end_blocknum = max_firstblocknum;
2654 let query_end_blocknum = msg.end_blocknum();
2655 let result = net_graph_msg_handler.handle_query_channel_range(test_node_id, msg);
2658 assert!(result.is_ok());
2660 assert!(result.is_err());
2663 let events = net_graph_msg_handler.get_and_clear_pending_msg_events();
2664 assert_eq!(events.len(), expected_replies.len());
2666 for i in 0..events.len() {
2667 let expected_reply = &expected_replies[i];
2669 MessageSendEvent::SendReplyChannelRange { node_id, msg } => {
2670 assert_eq!(node_id, test_node_id);
2671 assert_eq!(msg.chain_hash, expected_reply.chain_hash);
2672 assert_eq!(msg.first_blocknum, expected_reply.first_blocknum);
2673 assert_eq!(msg.number_of_blocks, expected_reply.number_of_blocks);
2674 assert_eq!(msg.sync_complete, expected_reply.sync_complete);
2675 assert_eq!(msg.short_channel_ids, expected_reply.short_channel_ids);
2677 // Enforce exactly the sequencing requirements present on c-lightning v0.9.3
2678 assert!(msg.first_blocknum == c_lightning_0_9_prev_end_blocknum || msg.first_blocknum == c_lightning_0_9_prev_end_blocknum.saturating_add(1));
2679 assert!(msg.first_blocknum >= max_firstblocknum);
2680 max_firstblocknum = msg.first_blocknum;
2681 c_lightning_0_9_prev_end_blocknum = msg.first_blocknum.saturating_add(msg.number_of_blocks);
2683 // Check that the last block count is >= the query's end_blocknum
2684 if i == events.len() - 1 {
2685 assert!(msg.first_blocknum.saturating_add(msg.number_of_blocks) >= query_end_blocknum);
2688 _ => panic!("expected MessageSendEvent::SendReplyChannelRange"),
2694 fn handling_query_short_channel_ids() {
2695 let network_graph = create_network_graph();
2696 let (secp_ctx, net_graph_msg_handler) = create_net_graph_msg_handler(&network_graph);
2697 let node_privkey = &SecretKey::from_slice(&[41; 32]).unwrap();
2698 let node_id = PublicKey::from_secret_key(&secp_ctx, node_privkey);
2700 let chain_hash = genesis_block(Network::Testnet).header.block_hash();
2702 let result = net_graph_msg_handler.handle_query_short_channel_ids(&node_id, QueryShortChannelIds {
2704 short_channel_ids: vec![0x0003e8_000000_0000],
2706 assert!(result.is_err());
2710 #[cfg(all(test, feature = "_bench_unstable"))]
2718 fn read_network_graph(bench: &mut Bencher) {
2719 let mut d = ::routing::router::test_utils::get_route_file().unwrap();
2720 let mut v = Vec::new();
2721 d.read_to_end(&mut v).unwrap();
2723 let _ = NetworkGraph::read(&mut std::io::Cursor::new(&v)).unwrap();
2728 fn write_network_graph(bench: &mut Bencher) {
2729 let mut d = ::routing::router::test_utils::get_route_file().unwrap();
2730 let net_graph = NetworkGraph::read(&mut d).unwrap();
2732 let _ = net_graph.encode();