1 // This file is Copyright its original authors, visible in version control
4 // This file is licensed under the Apache License, Version 2.0 <LICENSE-APACHE
5 // or http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
6 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your option.
7 // You may not use this file except in accordance with one or both of these
10 //! The top-level network map tracking logic lives here.
12 use bitcoin::secp256k1::key::PublicKey;
13 use bitcoin::secp256k1::Secp256k1;
14 use bitcoin::secp256k1;
16 use bitcoin::hashes::sha256d::Hash as Sha256dHash;
17 use bitcoin::hashes::Hash;
18 use bitcoin::blockdata::script::Builder;
19 use bitcoin::blockdata::transaction::TxOut;
20 use bitcoin::blockdata::opcodes;
21 use bitcoin::hash_types::BlockHash;
25 use ln::features::{ChannelFeatures, NodeFeatures};
26 use ln::msgs::{DecodeError, ErrorAction, Init, LightningError, RoutingMessageHandler, NetAddress, MAX_VALUE_MSAT};
27 use ln::msgs::{ChannelAnnouncement, ChannelUpdate, NodeAnnouncement, OptionalField};
28 use ln::msgs::{QueryChannelRange, ReplyChannelRange, QueryShortChannelIds, ReplyShortChannelIdsEnd};
30 use util::ser::{Writeable, Readable, Writer};
31 use util::logger::Logger;
32 use util::events::{MessageSendEvent, MessageSendEventsProvider};
33 use util::scid_utils::{block_from_scid, scid_from_parts, MAX_SCID_BLOCK};
36 use std::sync::{RwLock, RwLockReadGuard};
37 use std::sync::atomic::{AtomicUsize, Ordering};
39 use std::collections::BTreeMap;
40 use std::collections::btree_map::Entry as BtreeEntry;
42 use bitcoin::hashes::hex::ToHex;
44 /// The maximum number of extra bytes which we do not understand in a gossip message before we will
45 /// refuse to relay the message.
46 const MAX_EXCESS_BYTES_FOR_RELAY: usize = 1024;
48 /// Represents the network as nodes and channels between them
49 #[derive(Clone, PartialEq)]
50 pub struct NetworkGraph {
51 genesis_hash: BlockHash,
52 channels: BTreeMap<u64, ChannelInfo>,
53 nodes: BTreeMap<PublicKey, NodeInfo>,
56 /// A simple newtype for RwLockReadGuard<'a, NetworkGraph>.
57 /// This exists only to make accessing a RwLock<NetworkGraph> possible from
58 /// the C bindings, as it can be done directly in Rust code.
59 pub struct LockedNetworkGraph<'a>(pub RwLockReadGuard<'a, NetworkGraph>);
61 /// Receives and validates network updates from peers,
62 /// stores authentic and relevant data as a network graph.
63 /// This network graph is then used for routing payments.
64 /// Provides interface to help with initial routing sync by
65 /// serving historical announcements.
66 pub struct NetGraphMsgHandler<C: Deref, L: Deref> where C::Target: chain::Access, L::Target: Logger {
67 secp_ctx: Secp256k1<secp256k1::VerifyOnly>,
68 /// Representation of the payment channel network
69 pub network_graph: RwLock<NetworkGraph>,
70 chain_access: Option<C>,
71 full_syncs_requested: AtomicUsize,
72 pending_events: Mutex<Vec<MessageSendEvent>>,
75 /// Maximum number of short_channel_ids that will be encoded in one gossip reply message.
76 /// Default is 8000 which ensures a reply fits within the 65k payload limit and is
77 /// consistent with other implementations.
78 max_reply_scids: usize,
81 impl<C: Deref, L: Deref> NetGraphMsgHandler<C, L> where C::Target: chain::Access, L::Target: Logger {
82 /// Creates a new tracker of the actual state of the network of channels and nodes,
83 /// assuming a fresh network graph.
84 /// Chain monitor is used to make sure announced channels exist on-chain,
85 /// channel data is correct, and that the announcement is signed with
86 /// channel owners' keys.
87 pub fn new(genesis_hash: BlockHash, chain_access: Option<C>, logger: L) -> Self {
89 secp_ctx: Secp256k1::verification_only(),
90 network_graph: RwLock::new(NetworkGraph::new(genesis_hash)),
91 full_syncs_requested: AtomicUsize::new(0),
93 pending_events: Mutex::new(vec![]),
95 max_reply_scids: 8000,
99 /// Creates a new tracker of the actual state of the network of channels and nodes,
100 /// assuming an existing Network Graph.
101 pub fn from_net_graph(chain_access: Option<C>, logger: L, network_graph: NetworkGraph) -> Self {
103 secp_ctx: Secp256k1::verification_only(),
104 network_graph: RwLock::new(network_graph),
105 full_syncs_requested: AtomicUsize::new(0),
107 pending_events: Mutex::new(vec![]),
109 max_reply_scids: 8000,
113 /// Adds a provider used to check new announcements. Does not affect
114 /// existing announcements unless they are updated.
115 /// Add, update or remove the provider would replace the current one.
116 pub fn add_chain_access(&mut self, chain_access: Option<C>) {
117 self.chain_access = chain_access;
120 /// Take a read lock on the network_graph and return it in the C-bindings
121 /// newtype helper. This is likely only useful when called via the C
122 /// bindings as you can call `self.network_graph.read().unwrap()` in Rust
124 pub fn read_locked_graph<'a>(&'a self) -> LockedNetworkGraph<'a> {
125 LockedNetworkGraph(self.network_graph.read().unwrap())
128 /// Returns true when a full routing table sync should be performed with a peer.
129 fn should_request_full_sync(&self, _node_id: &PublicKey) -> bool {
130 //TODO: Determine whether to request a full sync based on the network map.
131 const FULL_SYNCS_TO_REQUEST: usize = 5;
132 if self.full_syncs_requested.load(Ordering::Acquire) < FULL_SYNCS_TO_REQUEST {
133 self.full_syncs_requested.fetch_add(1, Ordering::AcqRel);
141 impl<'a> LockedNetworkGraph<'a> {
142 /// Get a reference to the NetworkGraph which this read-lock contains.
143 pub fn graph(&self) -> &NetworkGraph {
149 macro_rules! secp_verify_sig {
150 ( $secp_ctx: expr, $msg: expr, $sig: expr, $pubkey: expr ) => {
151 match $secp_ctx.verify($msg, $sig, $pubkey) {
153 Err(_) => return Err(LightningError{err: "Invalid signature from remote node".to_owned(), action: ErrorAction::IgnoreError}),
158 impl<C: Deref + Sync + Send, L: Deref + Sync + Send> RoutingMessageHandler for NetGraphMsgHandler<C, L> where C::Target: chain::Access, L::Target: Logger {
159 fn handle_node_announcement(&self, msg: &msgs::NodeAnnouncement) -> Result<bool, LightningError> {
160 self.network_graph.write().unwrap().update_node_from_announcement(msg, &self.secp_ctx)?;
161 Ok(msg.contents.excess_data.len() <= MAX_EXCESS_BYTES_FOR_RELAY &&
162 msg.contents.excess_address_data.len() <= MAX_EXCESS_BYTES_FOR_RELAY &&
163 msg.contents.excess_data.len() + msg.contents.excess_address_data.len() <= MAX_EXCESS_BYTES_FOR_RELAY)
166 fn handle_channel_announcement(&self, msg: &msgs::ChannelAnnouncement) -> Result<bool, LightningError> {
167 self.network_graph.write().unwrap().update_channel_from_announcement(msg, &self.chain_access, &self.secp_ctx)?;
168 log_trace!(self.logger, "Added channel_announcement for {}{}", msg.contents.short_channel_id, if !msg.contents.excess_data.is_empty() { " with excess uninterpreted data!" } else { "" });
169 Ok(msg.contents.excess_data.len() <= MAX_EXCESS_BYTES_FOR_RELAY)
172 fn handle_htlc_fail_channel_update(&self, update: &msgs::HTLCFailChannelUpdate) {
174 &msgs::HTLCFailChannelUpdate::ChannelUpdateMessage { ref msg } => {
175 let _ = self.network_graph.write().unwrap().update_channel(msg, &self.secp_ctx);
177 &msgs::HTLCFailChannelUpdate::ChannelClosed { short_channel_id, is_permanent } => {
178 self.network_graph.write().unwrap().close_channel_from_update(short_channel_id, is_permanent);
180 &msgs::HTLCFailChannelUpdate::NodeFailure { ref node_id, is_permanent } => {
181 self.network_graph.write().unwrap().fail_node(node_id, is_permanent);
186 fn handle_channel_update(&self, msg: &msgs::ChannelUpdate) -> Result<bool, LightningError> {
187 self.network_graph.write().unwrap().update_channel(msg, &self.secp_ctx)?;
188 Ok(msg.contents.excess_data.len() <= MAX_EXCESS_BYTES_FOR_RELAY)
191 fn get_next_channel_announcements(&self, starting_point: u64, batch_amount: u8) -> Vec<(ChannelAnnouncement, Option<ChannelUpdate>, Option<ChannelUpdate>)> {
192 let network_graph = self.network_graph.read().unwrap();
193 let mut result = Vec::with_capacity(batch_amount as usize);
194 let mut iter = network_graph.get_channels().range(starting_point..);
195 while result.len() < batch_amount as usize {
196 if let Some((_, ref chan)) = iter.next() {
197 if chan.announcement_message.is_some() {
198 let chan_announcement = chan.announcement_message.clone().unwrap();
199 let mut one_to_two_announcement: Option<msgs::ChannelUpdate> = None;
200 let mut two_to_one_announcement: Option<msgs::ChannelUpdate> = None;
201 if let Some(one_to_two) = chan.one_to_two.as_ref() {
202 one_to_two_announcement = one_to_two.last_update_message.clone();
204 if let Some(two_to_one) = chan.two_to_one.as_ref() {
205 two_to_one_announcement = two_to_one.last_update_message.clone();
207 result.push((chan_announcement, one_to_two_announcement, two_to_one_announcement));
209 // TODO: We may end up sending un-announced channel_updates if we are sending
210 // initial sync data while receiving announce/updates for this channel.
219 fn get_next_node_announcements(&self, starting_point: Option<&PublicKey>, batch_amount: u8) -> Vec<NodeAnnouncement> {
220 let network_graph = self.network_graph.read().unwrap();
221 let mut result = Vec::with_capacity(batch_amount as usize);
222 let mut iter = if let Some(pubkey) = starting_point {
223 let mut iter = network_graph.get_nodes().range((*pubkey)..);
227 network_graph.get_nodes().range(..)
229 while result.len() < batch_amount as usize {
230 if let Some((_, ref node)) = iter.next() {
231 if let Some(node_info) = node.announcement_info.as_ref() {
232 if node_info.announcement_message.is_some() {
233 result.push(node_info.announcement_message.clone().unwrap());
243 /// Initiates a stateless sync of routing gossip information with a peer
244 /// using gossip_queries. The default strategy used by this implementation
245 /// is to sync the full block range with several peers.
247 /// We should expect one or more reply_channel_range messages in response
248 /// to our query_channel_range. Each reply will enqueue a query_scid message
249 /// to request gossip messages for each channel. The sync is considered complete
250 /// when the final reply_scids_end message is received, though we are not
251 /// tracking this directly.
252 fn sync_routing_table(&self, their_node_id: &PublicKey, init_msg: &Init) {
254 // We will only perform a sync with peers that support gossip_queries.
255 if !init_msg.features.supports_gossip_queries() {
259 // Check if we need to perform a full synchronization with this peer
260 if !self.should_request_full_sync(their_node_id) {
264 let first_blocknum = 0;
265 let number_of_blocks = 0xffffffff;
266 log_debug!(self.logger, "Sending query_channel_range peer={}, first_blocknum={}, number_of_blocks={}", log_pubkey!(their_node_id), first_blocknum, number_of_blocks);
267 let mut pending_events = self.pending_events.lock().unwrap();
268 pending_events.push(MessageSendEvent::SendChannelRangeQuery {
269 node_id: their_node_id.clone(),
270 msg: QueryChannelRange {
271 chain_hash: self.network_graph.read().unwrap().genesis_hash,
278 /// Statelessly processes a reply to a channel range query by immediately
279 /// sending an SCID query with SCIDs in the reply. To keep this handler
280 /// stateless, it does not validate the sequencing of replies for multi-
281 /// reply ranges. It does not validate whether the reply(ies) cover the
282 /// queried range. It also does not filter SCIDs to only those in the
283 /// original query range. We also do not validate that the chain_hash
284 /// matches the chain_hash of the NetworkGraph. Any chan_ann message that
285 /// does not match our chain_hash will be rejected when the announcement is
287 fn handle_reply_channel_range(&self, their_node_id: &PublicKey, msg: ReplyChannelRange) -> Result<(), LightningError> {
288 log_debug!(self.logger, "Handling reply_channel_range peer={}, first_blocknum={}, number_of_blocks={}, sync_complete={}, scids={}", log_pubkey!(their_node_id), msg.first_blocknum, msg.number_of_blocks, msg.sync_complete, msg.short_channel_ids.len(),);
290 log_debug!(self.logger, "Sending query_short_channel_ids peer={}, batch_size={}", log_pubkey!(their_node_id), msg.short_channel_ids.len());
291 let mut pending_events = self.pending_events.lock().unwrap();
292 pending_events.push(MessageSendEvent::SendShortIdsQuery {
293 node_id: their_node_id.clone(),
294 msg: QueryShortChannelIds {
295 chain_hash: msg.chain_hash,
296 short_channel_ids: msg.short_channel_ids,
303 /// When an SCID query is initiated the remote peer will begin streaming
304 /// gossip messages. In the event of a failure, we may have received
305 /// some channel information. Before trying with another peer, the
306 /// caller should update its set of SCIDs that need to be queried.
307 fn handle_reply_short_channel_ids_end(&self, their_node_id: &PublicKey, msg: ReplyShortChannelIdsEnd) -> Result<(), LightningError> {
308 log_debug!(self.logger, "Handling reply_short_channel_ids_end peer={}, full_information={}", log_pubkey!(their_node_id), msg.full_information);
310 // If the remote node does not have up-to-date information for the
311 // chain_hash they will set full_information=false. We can fail
312 // the result and try again with a different peer.
313 if !msg.full_information {
314 return Err(LightningError {
315 err: String::from("Received reply_short_channel_ids_end with no information"),
316 action: ErrorAction::IgnoreError
323 /// Processes a query from a peer by finding channels whose funding UTXOs
324 /// are in the specified block range. Due to message size limits, large range
325 /// queries may result in several reply messages. This implementation enqueues
326 /// all reply messages into pending events.
327 fn handle_query_channel_range(&self, their_node_id: &PublicKey, msg: QueryChannelRange) -> Result<(), LightningError> {
328 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);
330 let network_graph = self.network_graph.read().unwrap();
332 let start_scid = scid_from_parts(msg.first_blocknum as u64, 0, 0);
334 // We receive valid queries with end_blocknum that would overflow SCID conversion.
335 // Manually cap the ending block to avoid this overflow.
336 let exclusive_end_scid = scid_from_parts(cmp::min(msg.end_blocknum() as u64, MAX_SCID_BLOCK), 0, 0);
338 // Per spec, we must reply to a query. Send an empty message when things are invalid.
339 if msg.chain_hash != network_graph.genesis_hash || start_scid.is_err() || exclusive_end_scid.is_err() {
340 let mut pending_events = self.pending_events.lock().unwrap();
341 pending_events.push(MessageSendEvent::SendReplyChannelRange {
342 node_id: their_node_id.clone(),
343 msg: ReplyChannelRange {
344 chain_hash: msg.chain_hash.clone(),
345 first_blocknum: msg.first_blocknum,
346 number_of_blocks: msg.number_of_blocks,
348 short_channel_ids: vec![],
354 // Creates channel batches. We are not checking if the channel is routable
355 // (has at least one update). A peer may still want to know the channel
356 // exists even if its not yet routable.
357 let mut batches: Vec<Vec<u64>> = vec![Vec::with_capacity(self.max_reply_scids)];
358 for (_, ref chan) in network_graph.get_channels().range(start_scid.unwrap()..exclusive_end_scid.unwrap()) {
359 if let Some(chan_announcement) = &chan.announcement_message {
360 // Construct a new batch if last one is full
361 if batches.last().unwrap().len() == batches.last().unwrap().capacity() {
362 batches.push(Vec::with_capacity(self.max_reply_scids));
365 let batch = batches.last_mut().unwrap();
366 batch.push(chan_announcement.contents.short_channel_id);
371 let mut pending_events = self.pending_events.lock().unwrap();
372 let batch_count = batches.len();
373 for (batch_index, batch) in batches.into_iter().enumerate() {
374 // Per spec, the initial first_blocknum needs to be <= the query's first_blocknum.
375 // Use the query's values since we don't use pre-processed reply ranges.
376 let first_blocknum = if batch_index == 0 {
379 // Subsequent replies must be >= the last sent first_blocknum. Use the first block
382 block_from_scid(batch.first().unwrap())
385 // Per spec, the last end_block needs to be >= the query's end_block. Last
386 // reply calculates difference between the query's end_blocknum and the start of the reply.
387 // Overflow safe since end_blocknum=msg.first_block_num+msg.number_of_blocks and first_blocknum
388 // will be either msg.first_blocknum or a higher block height.
389 let number_of_blocks = if batch_index == batch_count-1 {
390 msg.end_blocknum() - first_blocknum
392 // Prior replies should use the number of blocks that fit into the reply. Overflow
393 // safe since first_blocknum is always <= last SCID's block.
395 block_from_scid(batch.last().unwrap()) - first_blocknum + 1
398 // Only true for the last message in a sequence
399 let sync_complete = batch_index == batch_count - 1;
401 pending_events.push(MessageSendEvent::SendReplyChannelRange {
402 node_id: their_node_id.clone(),
403 msg: ReplyChannelRange {
404 chain_hash: msg.chain_hash.clone(),
408 short_channel_ids: batch,
416 fn handle_query_short_channel_ids(&self, _their_node_id: &PublicKey, _msg: QueryShortChannelIds) -> Result<(), LightningError> {
419 err: String::from("Not implemented"),
420 action: ErrorAction::IgnoreError,
425 impl<C: Deref, L: Deref> MessageSendEventsProvider for NetGraphMsgHandler<C, L>
427 C::Target: chain::Access,
430 fn get_and_clear_pending_msg_events(&self) -> Vec<MessageSendEvent> {
431 let mut ret = Vec::new();
432 let mut pending_events = self.pending_events.lock().unwrap();
433 std::mem::swap(&mut ret, &mut pending_events);
438 #[derive(Clone, Debug, PartialEq)]
439 /// Details about one direction of a channel. Received
440 /// within a channel update.
441 pub struct DirectionalChannelInfo {
442 /// When the last update to the channel direction was issued.
443 /// Value is opaque, as set in the announcement.
444 pub last_update: u32,
445 /// Whether the channel can be currently used for payments (in this one direction).
447 /// The difference in CLTV values that you must have when routing through this channel.
448 pub cltv_expiry_delta: u16,
449 /// The minimum value, which must be relayed to the next hop via the channel
450 pub htlc_minimum_msat: u64,
451 /// The maximum value which may be relayed to the next hop via the channel.
452 pub htlc_maximum_msat: Option<u64>,
453 /// Fees charged when the channel is used for routing
454 pub fees: RoutingFees,
455 /// Most recent update for the channel received from the network
456 /// Mostly redundant with the data we store in fields explicitly.
457 /// Everything else is useful only for sending out for initial routing sync.
458 /// Not stored if contains excess data to prevent DoS.
459 pub last_update_message: Option<ChannelUpdate>,
462 impl fmt::Display for DirectionalChannelInfo {
463 fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
464 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)?;
469 impl_writeable!(DirectionalChannelInfo, 0, {
479 #[derive(Clone, Debug, PartialEq)]
480 /// Details about a channel (both directions).
481 /// Received within a channel announcement.
482 pub struct ChannelInfo {
483 /// Protocol features of a channel communicated during its announcement
484 pub features: ChannelFeatures,
485 /// Source node of the first direction of a channel
486 pub node_one: PublicKey,
487 /// Details about the first direction of a channel
488 pub one_to_two: Option<DirectionalChannelInfo>,
489 /// Source node of the second direction of a channel
490 pub node_two: PublicKey,
491 /// Details about the second direction of a channel
492 pub two_to_one: Option<DirectionalChannelInfo>,
493 /// The channel capacity as seen on-chain, if chain lookup is available.
494 pub capacity_sats: Option<u64>,
495 /// An initial announcement of the channel
496 /// Mostly redundant with the data we store in fields explicitly.
497 /// Everything else is useful only for sending out for initial routing sync.
498 /// Not stored if contains excess data to prevent DoS.
499 pub announcement_message: Option<ChannelAnnouncement>,
502 impl fmt::Display for ChannelInfo {
503 fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
504 write!(f, "features: {}, node_one: {}, one_to_two: {:?}, node_two: {}, two_to_one: {:?}",
505 log_bytes!(self.features.encode()), log_pubkey!(self.node_one), self.one_to_two, log_pubkey!(self.node_two), self.two_to_one)?;
510 impl_writeable!(ChannelInfo, 0, {
521 /// Fees for routing via a given channel or a node
522 #[derive(Eq, PartialEq, Copy, Clone, Debug)]
523 pub struct RoutingFees {
524 /// Flat routing fee in satoshis
526 /// Liquidity-based routing fee in millionths of a routed amount.
527 /// In other words, 10000 is 1%.
528 pub proportional_millionths: u32,
531 impl Readable for RoutingFees{
532 fn read<R: ::std::io::Read>(reader: &mut R) -> Result<RoutingFees, DecodeError> {
533 let base_msat: u32 = Readable::read(reader)?;
534 let proportional_millionths: u32 = Readable::read(reader)?;
537 proportional_millionths,
542 impl Writeable for RoutingFees {
543 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
544 self.base_msat.write(writer)?;
545 self.proportional_millionths.write(writer)?;
550 #[derive(Clone, Debug, PartialEq)]
551 /// Information received in the latest node_announcement from this node.
552 pub struct NodeAnnouncementInfo {
553 /// Protocol features the node announced support for
554 pub features: NodeFeatures,
555 /// When the last known update to the node state was issued.
556 /// Value is opaque, as set in the announcement.
557 pub last_update: u32,
558 /// Color assigned to the node
560 /// Moniker assigned to the node.
561 /// May be invalid or malicious (eg control chars),
562 /// should not be exposed to the user.
564 /// Internet-level addresses via which one can connect to the node
565 pub addresses: Vec<NetAddress>,
566 /// An initial announcement of the node
567 /// Mostly redundant with the data we store in fields explicitly.
568 /// Everything else is useful only for sending out for initial routing sync.
569 /// Not stored if contains excess data to prevent DoS.
570 pub announcement_message: Option<NodeAnnouncement>
573 impl Writeable for NodeAnnouncementInfo {
574 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
575 self.features.write(writer)?;
576 self.last_update.write(writer)?;
577 self.rgb.write(writer)?;
578 self.alias.write(writer)?;
579 (self.addresses.len() as u64).write(writer)?;
580 for ref addr in &self.addresses {
583 self.announcement_message.write(writer)?;
588 impl Readable for NodeAnnouncementInfo {
589 fn read<R: ::std::io::Read>(reader: &mut R) -> Result<NodeAnnouncementInfo, DecodeError> {
590 let features = Readable::read(reader)?;
591 let last_update = Readable::read(reader)?;
592 let rgb = Readable::read(reader)?;
593 let alias = Readable::read(reader)?;
594 let addresses_count: u64 = Readable::read(reader)?;
595 let mut addresses = Vec::with_capacity(cmp::min(addresses_count, MAX_ALLOC_SIZE / 40) as usize);
596 for _ in 0..addresses_count {
597 match Readable::read(reader) {
598 Ok(Ok(addr)) => { addresses.push(addr); },
599 Ok(Err(_)) => return Err(DecodeError::InvalidValue),
600 Err(DecodeError::ShortRead) => return Err(DecodeError::BadLengthDescriptor),
604 let announcement_message = Readable::read(reader)?;
605 Ok(NodeAnnouncementInfo {
616 #[derive(Clone, Debug, PartialEq)]
617 /// Details about a node in the network, known from the network announcement.
618 pub struct NodeInfo {
619 /// All valid channels a node has announced
620 pub channels: Vec<u64>,
621 /// Lowest fees enabling routing via any of the enabled, known channels to a node.
622 /// The two fields (flat and proportional fee) are independent,
623 /// meaning they don't have to refer to the same channel.
624 pub lowest_inbound_channel_fees: Option<RoutingFees>,
625 /// More information about a node from node_announcement.
626 /// Optional because we store a Node entry after learning about it from
627 /// a channel announcement, but before receiving a node announcement.
628 pub announcement_info: Option<NodeAnnouncementInfo>
631 impl fmt::Display for NodeInfo {
632 fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
633 write!(f, "lowest_inbound_channel_fees: {:?}, channels: {:?}, announcement_info: {:?}",
634 self.lowest_inbound_channel_fees, &self.channels[..], self.announcement_info)?;
639 impl Writeable for NodeInfo {
640 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
641 (self.channels.len() as u64).write(writer)?;
642 for ref chan in self.channels.iter() {
645 self.lowest_inbound_channel_fees.write(writer)?;
646 self.announcement_info.write(writer)?;
651 const MAX_ALLOC_SIZE: u64 = 64*1024;
653 impl Readable for NodeInfo {
654 fn read<R: ::std::io::Read>(reader: &mut R) -> Result<NodeInfo, DecodeError> {
655 let channels_count: u64 = Readable::read(reader)?;
656 let mut channels = Vec::with_capacity(cmp::min(channels_count, MAX_ALLOC_SIZE / 8) as usize);
657 for _ in 0..channels_count {
658 channels.push(Readable::read(reader)?);
660 let lowest_inbound_channel_fees = Readable::read(reader)?;
661 let announcement_info = Readable::read(reader)?;
664 lowest_inbound_channel_fees,
670 impl Writeable for NetworkGraph {
671 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
672 self.genesis_hash.write(writer)?;
673 (self.channels.len() as u64).write(writer)?;
674 for (ref chan_id, ref chan_info) in self.channels.iter() {
675 (*chan_id).write(writer)?;
676 chan_info.write(writer)?;
678 (self.nodes.len() as u64).write(writer)?;
679 for (ref node_id, ref node_info) in self.nodes.iter() {
680 node_id.write(writer)?;
681 node_info.write(writer)?;
687 impl Readable for NetworkGraph {
688 fn read<R: ::std::io::Read>(reader: &mut R) -> Result<NetworkGraph, DecodeError> {
689 let genesis_hash: BlockHash = Readable::read(reader)?;
690 let channels_count: u64 = Readable::read(reader)?;
691 let mut channels = BTreeMap::new();
692 for _ in 0..channels_count {
693 let chan_id: u64 = Readable::read(reader)?;
694 let chan_info = Readable::read(reader)?;
695 channels.insert(chan_id, chan_info);
697 let nodes_count: u64 = Readable::read(reader)?;
698 let mut nodes = BTreeMap::new();
699 for _ in 0..nodes_count {
700 let node_id = Readable::read(reader)?;
701 let node_info = Readable::read(reader)?;
702 nodes.insert(node_id, node_info);
712 impl fmt::Display for NetworkGraph {
713 fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
714 writeln!(f, "Network map\n[Channels]")?;
715 for (key, val) in self.channels.iter() {
716 writeln!(f, " {}: {}", key, val)?;
718 writeln!(f, "[Nodes]")?;
719 for (key, val) in self.nodes.iter() {
720 writeln!(f, " {}: {}", log_pubkey!(key), val)?;
727 /// Returns all known valid channels' short ids along with announced channel info.
729 /// (C-not exported) because we have no mapping for `BTreeMap`s
730 pub fn get_channels<'a>(&'a self) -> &'a BTreeMap<u64, ChannelInfo> { &self.channels }
731 /// Returns all known nodes' public keys along with announced node info.
733 /// (C-not exported) because we have no mapping for `BTreeMap`s
734 pub fn get_nodes<'a>(&'a self) -> &'a BTreeMap<PublicKey, NodeInfo> { &self.nodes }
736 /// Get network addresses by node id.
737 /// Returns None if the requested node is completely unknown,
738 /// or if node announcement for the node was never received.
740 /// (C-not exported) as there is no practical way to track lifetimes of returned values.
741 pub fn get_addresses<'a>(&'a self, pubkey: &PublicKey) -> Option<&'a Vec<NetAddress>> {
742 if let Some(node) = self.nodes.get(pubkey) {
743 if let Some(node_info) = node.announcement_info.as_ref() {
744 return Some(&node_info.addresses)
750 /// Creates a new, empty, network graph.
751 pub fn new(genesis_hash: BlockHash) -> NetworkGraph {
754 channels: BTreeMap::new(),
755 nodes: BTreeMap::new(),
759 /// For an already known node (from channel announcements), update its stored properties from a
760 /// given node announcement.
762 /// You probably don't want to call this directly, instead relying on a NetGraphMsgHandler's
763 /// RoutingMessageHandler implementation to call it indirectly. This may be useful to accept
764 /// routing messages from a source using a protocol other than the lightning P2P protocol.
765 pub fn update_node_from_announcement<T: secp256k1::Verification>(&mut self, msg: &msgs::NodeAnnouncement, secp_ctx: &Secp256k1<T>) -> Result<(), LightningError> {
766 let msg_hash = hash_to_message!(&Sha256dHash::hash(&msg.contents.encode()[..])[..]);
767 secp_verify_sig!(secp_ctx, &msg_hash, &msg.signature, &msg.contents.node_id);
768 self.update_node_from_announcement_intern(&msg.contents, Some(&msg))
771 /// For an already known node (from channel announcements), update its stored properties from a
772 /// given node announcement without verifying the associated signatures. Because we aren't
773 /// given the associated signatures here we cannot relay the node announcement to any of our
775 pub fn update_node_from_unsigned_announcement(&mut self, msg: &msgs::UnsignedNodeAnnouncement) -> Result<(), LightningError> {
776 self.update_node_from_announcement_intern(msg, None)
779 fn update_node_from_announcement_intern(&mut self, msg: &msgs::UnsignedNodeAnnouncement, full_msg: Option<&msgs::NodeAnnouncement>) -> Result<(), LightningError> {
780 match self.nodes.get_mut(&msg.node_id) {
781 None => Err(LightningError{err: "No existing channels for node_announcement".to_owned(), action: ErrorAction::IgnoreError}),
783 if let Some(node_info) = node.announcement_info.as_ref() {
784 if node_info.last_update >= msg.timestamp {
785 return Err(LightningError{err: "Update older than last processed update".to_owned(), action: ErrorAction::IgnoreError});
790 msg.excess_data.len() <= MAX_EXCESS_BYTES_FOR_RELAY &&
791 msg.excess_address_data.len() <= MAX_EXCESS_BYTES_FOR_RELAY &&
792 msg.excess_data.len() + msg.excess_address_data.len() <= MAX_EXCESS_BYTES_FOR_RELAY;
793 node.announcement_info = Some(NodeAnnouncementInfo {
794 features: msg.features.clone(),
795 last_update: msg.timestamp,
798 addresses: msg.addresses.clone(),
799 announcement_message: if should_relay { full_msg.cloned() } else { None },
807 /// Store or update channel info from a channel announcement.
809 /// You probably don't want to call this directly, instead relying on a NetGraphMsgHandler's
810 /// RoutingMessageHandler implementation to call it indirectly. This may be useful to accept
811 /// routing messages from a source using a protocol other than the lightning P2P protocol.
813 /// If a `chain::Access` object is provided via `chain_access`, it will be called to verify
814 /// the corresponding UTXO exists on chain and is correctly-formatted.
815 pub fn update_channel_from_announcement<T: secp256k1::Verification, C: Deref>
816 (&mut self, msg: &msgs::ChannelAnnouncement, chain_access: &Option<C>, secp_ctx: &Secp256k1<T>)
817 -> Result<(), LightningError>
818 where C::Target: chain::Access {
819 let msg_hash = hash_to_message!(&Sha256dHash::hash(&msg.contents.encode()[..])[..]);
820 secp_verify_sig!(secp_ctx, &msg_hash, &msg.node_signature_1, &msg.contents.node_id_1);
821 secp_verify_sig!(secp_ctx, &msg_hash, &msg.node_signature_2, &msg.contents.node_id_2);
822 secp_verify_sig!(secp_ctx, &msg_hash, &msg.bitcoin_signature_1, &msg.contents.bitcoin_key_1);
823 secp_verify_sig!(secp_ctx, &msg_hash, &msg.bitcoin_signature_2, &msg.contents.bitcoin_key_2);
824 self.update_channel_from_unsigned_announcement_intern(&msg.contents, Some(msg), chain_access)
827 /// Store or update channel info from a channel announcement without verifying the associated
828 /// signatures. Because we aren't given the associated signatures here we cannot relay the
829 /// channel announcement to any of our peers.
831 /// If a `chain::Access` object is provided via `chain_access`, it will be called to verify
832 /// the corresponding UTXO exists on chain and is correctly-formatted.
833 pub fn update_channel_from_unsigned_announcement<C: Deref>
834 (&mut self, msg: &msgs::UnsignedChannelAnnouncement, chain_access: &Option<C>)
835 -> Result<(), LightningError>
836 where C::Target: chain::Access {
837 self.update_channel_from_unsigned_announcement_intern(msg, None, chain_access)
840 fn update_channel_from_unsigned_announcement_intern<C: Deref>
841 (&mut self, msg: &msgs::UnsignedChannelAnnouncement, full_msg: Option<&msgs::ChannelAnnouncement>, chain_access: &Option<C>)
842 -> Result<(), LightningError>
843 where C::Target: chain::Access {
844 if msg.node_id_1 == msg.node_id_2 || msg.bitcoin_key_1 == msg.bitcoin_key_2 {
845 return Err(LightningError{err: "Channel announcement node had a channel with itself".to_owned(), action: ErrorAction::IgnoreError});
848 let utxo_value = match &chain_access {
850 // Tentatively accept, potentially exposing us to DoS attacks
853 &Some(ref chain_access) => {
854 match chain_access.get_utxo(&msg.chain_hash, msg.short_channel_id) {
855 Ok(TxOut { value, script_pubkey }) => {
856 let expected_script = Builder::new().push_opcode(opcodes::all::OP_PUSHNUM_2)
857 .push_slice(&msg.bitcoin_key_1.serialize())
858 .push_slice(&msg.bitcoin_key_2.serialize())
859 .push_opcode(opcodes::all::OP_PUSHNUM_2)
860 .push_opcode(opcodes::all::OP_CHECKMULTISIG).into_script().to_v0_p2wsh();
861 if script_pubkey != expected_script {
862 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});
864 //TODO: Check if value is worth storing, use it to inform routing, and compare it
865 //to the new HTLC max field in channel_update
868 Err(chain::AccessError::UnknownChain) => {
869 return Err(LightningError{err: format!("Channel announced on an unknown chain ({})", msg.chain_hash.encode().to_hex()), action: ErrorAction::IgnoreError});
871 Err(chain::AccessError::UnknownTx) => {
872 return Err(LightningError{err: "Channel announced without corresponding UTXO entry".to_owned(), action: ErrorAction::IgnoreError});
878 let chan_info = ChannelInfo {
879 features: msg.features.clone(),
880 node_one: msg.node_id_1.clone(),
882 node_two: msg.node_id_2.clone(),
884 capacity_sats: utxo_value,
885 announcement_message: if msg.excess_data.len() <= MAX_EXCESS_BYTES_FOR_RELAY
886 { full_msg.cloned() } else { None },
889 match self.channels.entry(msg.short_channel_id) {
890 BtreeEntry::Occupied(mut entry) => {
891 //TODO: because asking the blockchain if short_channel_id is valid is only optional
892 //in the blockchain API, we need to handle it smartly here, though it's unclear
894 if utxo_value.is_some() {
895 // Either our UTXO provider is busted, there was a reorg, or the UTXO provider
896 // only sometimes returns results. In any case remove the previous entry. Note
897 // that the spec expects us to "blacklist" the node_ids involved, but we can't
899 // a) we don't *require* a UTXO provider that always returns results.
900 // b) we don't track UTXOs of channels we know about and remove them if they
902 // c) it's unclear how to do so without exposing ourselves to massive DoS risk.
903 Self::remove_channel_in_nodes(&mut self.nodes, &entry.get(), msg.short_channel_id);
904 *entry.get_mut() = chan_info;
906 return Err(LightningError{err: "Already have knowledge of channel".to_owned(), action: ErrorAction::IgnoreError})
909 BtreeEntry::Vacant(entry) => {
910 entry.insert(chan_info);
914 macro_rules! add_channel_to_node {
915 ( $node_id: expr ) => {
916 match self.nodes.entry($node_id) {
917 BtreeEntry::Occupied(node_entry) => {
918 node_entry.into_mut().channels.push(msg.short_channel_id);
920 BtreeEntry::Vacant(node_entry) => {
921 node_entry.insert(NodeInfo {
922 channels: vec!(msg.short_channel_id),
923 lowest_inbound_channel_fees: None,
924 announcement_info: None,
931 add_channel_to_node!(msg.node_id_1);
932 add_channel_to_node!(msg.node_id_2);
937 /// Close a channel if a corresponding HTLC fail was sent.
938 /// If permanent, removes a channel from the local storage.
939 /// May cause the removal of nodes too, if this was their last channel.
940 /// If not permanent, makes channels unavailable for routing.
941 pub fn close_channel_from_update(&mut self, short_channel_id: u64, is_permanent: bool) {
943 if let Some(chan) = self.channels.remove(&short_channel_id) {
944 Self::remove_channel_in_nodes(&mut self.nodes, &chan, short_channel_id);
947 if let Some(chan) = self.channels.get_mut(&short_channel_id) {
948 if let Some(one_to_two) = chan.one_to_two.as_mut() {
949 one_to_two.enabled = false;
951 if let Some(two_to_one) = chan.two_to_one.as_mut() {
952 two_to_one.enabled = false;
958 fn fail_node(&mut self, _node_id: &PublicKey, is_permanent: bool) {
960 // TODO: Wholly remove the node
962 // TODO: downgrade the node
966 /// For an already known (from announcement) channel, update info about one of the directions
969 /// You probably don't want to call this directly, instead relying on a NetGraphMsgHandler's
970 /// RoutingMessageHandler implementation to call it indirectly. This may be useful to accept
971 /// routing messages from a source using a protocol other than the lightning P2P protocol.
972 pub fn update_channel<T: secp256k1::Verification>(&mut self, msg: &msgs::ChannelUpdate, secp_ctx: &Secp256k1<T>) -> Result<(), LightningError> {
973 self.update_channel_intern(&msg.contents, Some(&msg), Some((&msg.signature, secp_ctx)))
976 /// For an already known (from announcement) channel, update info about one of the directions
977 /// of the channel without verifying the associated signatures. Because we aren't given the
978 /// associated signatures here we cannot relay the channel update to any of our peers.
979 pub fn update_channel_unsigned(&mut self, msg: &msgs::UnsignedChannelUpdate) -> Result<(), LightningError> {
980 self.update_channel_intern(msg, None, None::<(&secp256k1::Signature, &Secp256k1<secp256k1::VerifyOnly>)>)
983 fn update_channel_intern<T: secp256k1::Verification>(&mut self, msg: &msgs::UnsignedChannelUpdate, full_msg: Option<&msgs::ChannelUpdate>, sig_info: Option<(&secp256k1::Signature, &Secp256k1<T>)>) -> Result<(), LightningError> {
985 let chan_enabled = msg.flags & (1 << 1) != (1 << 1);
986 let chan_was_enabled;
988 match self.channels.get_mut(&msg.short_channel_id) {
989 None => return Err(LightningError{err: "Couldn't find channel for update".to_owned(), action: ErrorAction::IgnoreError}),
991 if let OptionalField::Present(htlc_maximum_msat) = msg.htlc_maximum_msat {
992 if htlc_maximum_msat > MAX_VALUE_MSAT {
993 return Err(LightningError{err: "htlc_maximum_msat is larger than maximum possible msats".to_owned(), action: ErrorAction::IgnoreError});
996 if let Some(capacity_sats) = channel.capacity_sats {
997 // It's possible channel capacity is available now, although it wasn't available at announcement (so the field is None).
998 // Don't query UTXO set here to reduce DoS risks.
999 if capacity_sats > MAX_VALUE_MSAT / 1000 || htlc_maximum_msat > capacity_sats * 1000 {
1000 return Err(LightningError{err: "htlc_maximum_msat is larger than channel capacity or capacity is bogus".to_owned(), action: ErrorAction::IgnoreError});
1004 macro_rules! maybe_update_channel_info {
1005 ( $target: expr, $src_node: expr) => {
1006 if let Some(existing_chan_info) = $target.as_ref() {
1007 if existing_chan_info.last_update >= msg.timestamp {
1008 return Err(LightningError{err: "Update older than last processed update".to_owned(), action: ErrorAction::IgnoreError});
1010 chan_was_enabled = existing_chan_info.enabled;
1012 chan_was_enabled = false;
1015 let last_update_message = if msg.excess_data.len() <= MAX_EXCESS_BYTES_FOR_RELAY
1016 { full_msg.cloned() } else { None };
1018 let updated_channel_dir_info = DirectionalChannelInfo {
1019 enabled: chan_enabled,
1020 last_update: msg.timestamp,
1021 cltv_expiry_delta: msg.cltv_expiry_delta,
1022 htlc_minimum_msat: msg.htlc_minimum_msat,
1023 htlc_maximum_msat: if let OptionalField::Present(max_value) = msg.htlc_maximum_msat { Some(max_value) } else { None },
1025 base_msat: msg.fee_base_msat,
1026 proportional_millionths: msg.fee_proportional_millionths,
1030 $target = Some(updated_channel_dir_info);
1034 let msg_hash = hash_to_message!(&Sha256dHash::hash(&msg.encode()[..])[..]);
1035 if msg.flags & 1 == 1 {
1036 dest_node_id = channel.node_one.clone();
1037 if let Some((sig, ctx)) = sig_info {
1038 secp_verify_sig!(ctx, &msg_hash, &sig, &channel.node_two);
1040 maybe_update_channel_info!(channel.two_to_one, channel.node_two);
1042 dest_node_id = channel.node_two.clone();
1043 if let Some((sig, ctx)) = sig_info {
1044 secp_verify_sig!(ctx, &msg_hash, &sig, &channel.node_one);
1046 maybe_update_channel_info!(channel.one_to_two, channel.node_one);
1052 let node = self.nodes.get_mut(&dest_node_id).unwrap();
1053 let mut base_msat = msg.fee_base_msat;
1054 let mut proportional_millionths = msg.fee_proportional_millionths;
1055 if let Some(fees) = node.lowest_inbound_channel_fees {
1056 base_msat = cmp::min(base_msat, fees.base_msat);
1057 proportional_millionths = cmp::min(proportional_millionths, fees.proportional_millionths);
1059 node.lowest_inbound_channel_fees = Some(RoutingFees {
1061 proportional_millionths
1063 } else if chan_was_enabled {
1064 let node = self.nodes.get_mut(&dest_node_id).unwrap();
1065 let mut lowest_inbound_channel_fees = None;
1067 for chan_id in node.channels.iter() {
1068 let chan = self.channels.get(chan_id).unwrap();
1070 if chan.node_one == dest_node_id {
1071 chan_info_opt = chan.two_to_one.as_ref();
1073 chan_info_opt = chan.one_to_two.as_ref();
1075 if let Some(chan_info) = chan_info_opt {
1076 if chan_info.enabled {
1077 let fees = lowest_inbound_channel_fees.get_or_insert(RoutingFees {
1078 base_msat: u32::max_value(), proportional_millionths: u32::max_value() });
1079 fees.base_msat = cmp::min(fees.base_msat, chan_info.fees.base_msat);
1080 fees.proportional_millionths = cmp::min(fees.proportional_millionths, chan_info.fees.proportional_millionths);
1085 node.lowest_inbound_channel_fees = lowest_inbound_channel_fees;
1091 fn remove_channel_in_nodes(nodes: &mut BTreeMap<PublicKey, NodeInfo>, chan: &ChannelInfo, short_channel_id: u64) {
1092 macro_rules! remove_from_node {
1093 ($node_id: expr) => {
1094 if let BtreeEntry::Occupied(mut entry) = nodes.entry($node_id) {
1095 entry.get_mut().channels.retain(|chan_id| {
1096 short_channel_id != *chan_id
1098 if entry.get().channels.is_empty() {
1099 entry.remove_entry();
1102 panic!("Had channel that pointed to unknown node (ie inconsistent network map)!");
1107 remove_from_node!(chan.node_one);
1108 remove_from_node!(chan.node_two);
1115 use ln::features::{ChannelFeatures, InitFeatures, NodeFeatures};
1116 use routing::network_graph::{NetGraphMsgHandler, NetworkGraph, MAX_EXCESS_BYTES_FOR_RELAY};
1117 use ln::msgs::{Init, OptionalField, RoutingMessageHandler, UnsignedNodeAnnouncement, NodeAnnouncement,
1118 UnsignedChannelAnnouncement, ChannelAnnouncement, UnsignedChannelUpdate, ChannelUpdate, HTLCFailChannelUpdate,
1119 ReplyChannelRange, ReplyShortChannelIdsEnd, QueryChannelRange, QueryShortChannelIds, MAX_VALUE_MSAT};
1120 use util::test_utils;
1121 use util::logger::Logger;
1122 use util::ser::{Readable, Writeable};
1123 use util::events::{MessageSendEvent, MessageSendEventsProvider};
1125 use bitcoin::hashes::sha256d::Hash as Sha256dHash;
1126 use bitcoin::hashes::Hash;
1127 use bitcoin::network::constants::Network;
1128 use bitcoin::blockdata::constants::genesis_block;
1129 use bitcoin::blockdata::script::Builder;
1130 use bitcoin::blockdata::transaction::TxOut;
1131 use bitcoin::blockdata::opcodes;
1135 use bitcoin::secp256k1::key::{PublicKey, SecretKey};
1136 use bitcoin::secp256k1::{All, Secp256k1};
1140 fn create_net_graph_msg_handler() -> (Secp256k1<All>, NetGraphMsgHandler<Arc<test_utils::TestChainSource>, Arc<test_utils::TestLogger>>) {
1141 let secp_ctx = Secp256k1::new();
1142 let logger = Arc::new(test_utils::TestLogger::new());
1143 let genesis_hash = genesis_block(Network::Testnet).header.block_hash();
1144 let net_graph_msg_handler = NetGraphMsgHandler::new(genesis_hash, None, Arc::clone(&logger));
1145 (secp_ctx, net_graph_msg_handler)
1149 fn request_full_sync_finite_times() {
1150 let (secp_ctx, net_graph_msg_handler) = create_net_graph_msg_handler();
1151 let node_id = PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&hex::decode("0202020202020202020202020202020202020202020202020202020202020202").unwrap()[..]).unwrap());
1153 assert!(net_graph_msg_handler.should_request_full_sync(&node_id));
1154 assert!(net_graph_msg_handler.should_request_full_sync(&node_id));
1155 assert!(net_graph_msg_handler.should_request_full_sync(&node_id));
1156 assert!(net_graph_msg_handler.should_request_full_sync(&node_id));
1157 assert!(net_graph_msg_handler.should_request_full_sync(&node_id));
1158 assert!(!net_graph_msg_handler.should_request_full_sync(&node_id));
1162 fn handling_node_announcements() {
1163 let (secp_ctx, net_graph_msg_handler) = create_net_graph_msg_handler();
1165 let node_1_privkey = &SecretKey::from_slice(&[42; 32]).unwrap();
1166 let node_2_privkey = &SecretKey::from_slice(&[41; 32]).unwrap();
1167 let node_id_1 = PublicKey::from_secret_key(&secp_ctx, node_1_privkey);
1168 let node_id_2 = PublicKey::from_secret_key(&secp_ctx, node_2_privkey);
1169 let node_1_btckey = &SecretKey::from_slice(&[40; 32]).unwrap();
1170 let node_2_btckey = &SecretKey::from_slice(&[39; 32]).unwrap();
1171 let zero_hash = Sha256dHash::hash(&[0; 32]);
1172 let first_announcement_time = 500;
1174 let mut unsigned_announcement = UnsignedNodeAnnouncement {
1175 features: NodeFeatures::known(),
1176 timestamp: first_announcement_time,
1180 addresses: Vec::new(),
1181 excess_address_data: Vec::new(),
1182 excess_data: Vec::new(),
1184 let mut msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1185 let valid_announcement = NodeAnnouncement {
1186 signature: secp_ctx.sign(&msghash, node_1_privkey),
1187 contents: unsigned_announcement.clone()
1190 match net_graph_msg_handler.handle_node_announcement(&valid_announcement) {
1192 Err(e) => assert_eq!("No existing channels for node_announcement", e.err)
1196 // Announce a channel to add a corresponding node.
1197 let unsigned_announcement = UnsignedChannelAnnouncement {
1198 features: ChannelFeatures::known(),
1199 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1200 short_channel_id: 0,
1203 bitcoin_key_1: PublicKey::from_secret_key(&secp_ctx, node_1_btckey),
1204 bitcoin_key_2: PublicKey::from_secret_key(&secp_ctx, node_2_btckey),
1205 excess_data: Vec::new(),
1208 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1209 let valid_announcement = ChannelAnnouncement {
1210 node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
1211 node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
1212 bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_btckey),
1213 bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_btckey),
1214 contents: unsigned_announcement.clone(),
1216 match net_graph_msg_handler.handle_channel_announcement(&valid_announcement) {
1217 Ok(res) => assert!(res),
1222 match net_graph_msg_handler.handle_node_announcement(&valid_announcement) {
1223 Ok(res) => assert!(res),
1227 let fake_msghash = hash_to_message!(&zero_hash);
1228 match net_graph_msg_handler.handle_node_announcement(
1230 signature: secp_ctx.sign(&fake_msghash, node_1_privkey),
1231 contents: unsigned_announcement.clone()
1234 Err(e) => assert_eq!(e.err, "Invalid signature from remote node")
1237 unsigned_announcement.timestamp += 1000;
1238 unsigned_announcement.excess_data.resize(MAX_EXCESS_BYTES_FOR_RELAY + 1, 0);
1239 msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1240 let announcement_with_data = NodeAnnouncement {
1241 signature: secp_ctx.sign(&msghash, node_1_privkey),
1242 contents: unsigned_announcement.clone()
1244 // Return false because contains excess data.
1245 match net_graph_msg_handler.handle_node_announcement(&announcement_with_data) {
1246 Ok(res) => assert!(!res),
1249 unsigned_announcement.excess_data = Vec::new();
1251 // Even though previous announcement was not relayed further, we still accepted it,
1252 // so we now won't accept announcements before the previous one.
1253 unsigned_announcement.timestamp -= 10;
1254 msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1255 let outdated_announcement = NodeAnnouncement {
1256 signature: secp_ctx.sign(&msghash, node_1_privkey),
1257 contents: unsigned_announcement.clone()
1259 match net_graph_msg_handler.handle_node_announcement(&outdated_announcement) {
1261 Err(e) => assert_eq!(e.err, "Update older than last processed update")
1266 fn handling_channel_announcements() {
1267 let secp_ctx = Secp256k1::new();
1268 let logger: Arc<Logger> = Arc::new(test_utils::TestLogger::new());
1270 let node_1_privkey = &SecretKey::from_slice(&[42; 32]).unwrap();
1271 let node_2_privkey = &SecretKey::from_slice(&[41; 32]).unwrap();
1272 let node_id_1 = PublicKey::from_secret_key(&secp_ctx, node_1_privkey);
1273 let node_id_2 = PublicKey::from_secret_key(&secp_ctx, node_2_privkey);
1274 let node_1_btckey = &SecretKey::from_slice(&[40; 32]).unwrap();
1275 let node_2_btckey = &SecretKey::from_slice(&[39; 32]).unwrap();
1277 let good_script = Builder::new().push_opcode(opcodes::all::OP_PUSHNUM_2)
1278 .push_slice(&PublicKey::from_secret_key(&secp_ctx, node_1_btckey).serialize())
1279 .push_slice(&PublicKey::from_secret_key(&secp_ctx, node_2_btckey).serialize())
1280 .push_opcode(opcodes::all::OP_PUSHNUM_2)
1281 .push_opcode(opcodes::all::OP_CHECKMULTISIG).into_script().to_v0_p2wsh();
1284 let mut unsigned_announcement = UnsignedChannelAnnouncement {
1285 features: ChannelFeatures::known(),
1286 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1287 short_channel_id: 0,
1290 bitcoin_key_1: PublicKey::from_secret_key(&secp_ctx, node_1_btckey),
1291 bitcoin_key_2: PublicKey::from_secret_key(&secp_ctx, node_2_btckey),
1292 excess_data: Vec::new(),
1295 let mut msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1296 let valid_announcement = ChannelAnnouncement {
1297 node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
1298 node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
1299 bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_btckey),
1300 bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_btckey),
1301 contents: unsigned_announcement.clone(),
1304 // Test if the UTXO lookups were not supported
1305 let mut net_graph_msg_handler = NetGraphMsgHandler::new(genesis_block(Network::Testnet).header.block_hash(), None, Arc::clone(&logger));
1306 match net_graph_msg_handler.handle_channel_announcement(&valid_announcement) {
1307 Ok(res) => assert!(res),
1312 let network = net_graph_msg_handler.network_graph.read().unwrap();
1313 match network.get_channels().get(&unsigned_announcement.short_channel_id) {
1319 // If we receive announcement for the same channel (with UTXO lookups disabled),
1320 // drop new one on the floor, since we can't see any changes.
1321 match net_graph_msg_handler.handle_channel_announcement(&valid_announcement) {
1323 Err(e) => assert_eq!(e.err, "Already have knowledge of channel")
1326 // Test if an associated transaction were not on-chain (or not confirmed).
1327 let chain_source = Arc::new(test_utils::TestChainSource::new(Network::Testnet));
1328 *chain_source.utxo_ret.lock().unwrap() = Err(chain::AccessError::UnknownTx);
1329 net_graph_msg_handler = NetGraphMsgHandler::new(chain_source.clone().genesis_hash, Some(chain_source.clone()), Arc::clone(&logger));
1330 unsigned_announcement.short_channel_id += 1;
1332 msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1333 let valid_announcement = ChannelAnnouncement {
1334 node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
1335 node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
1336 bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_btckey),
1337 bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_btckey),
1338 contents: unsigned_announcement.clone(),
1341 match net_graph_msg_handler.handle_channel_announcement(&valid_announcement) {
1343 Err(e) => assert_eq!(e.err, "Channel announced without corresponding UTXO entry")
1346 // Now test if the transaction is found in the UTXO set and the script is correct.
1347 unsigned_announcement.short_channel_id += 1;
1348 *chain_source.utxo_ret.lock().unwrap() = Ok(TxOut { value: 0, script_pubkey: good_script.clone() });
1350 msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1351 let valid_announcement = ChannelAnnouncement {
1352 node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
1353 node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
1354 bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_btckey),
1355 bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_btckey),
1356 contents: unsigned_announcement.clone(),
1358 match net_graph_msg_handler.handle_channel_announcement(&valid_announcement) {
1359 Ok(res) => assert!(res),
1364 let network = net_graph_msg_handler.network_graph.read().unwrap();
1365 match network.get_channels().get(&unsigned_announcement.short_channel_id) {
1371 // If we receive announcement for the same channel (but TX is not confirmed),
1372 // drop new one on the floor, since we can't see any changes.
1373 *chain_source.utxo_ret.lock().unwrap() = Err(chain::AccessError::UnknownTx);
1374 match net_graph_msg_handler.handle_channel_announcement(&valid_announcement) {
1376 Err(e) => assert_eq!(e.err, "Channel announced without corresponding UTXO entry")
1379 // But if it is confirmed, replace the channel
1380 *chain_source.utxo_ret.lock().unwrap() = Ok(TxOut { value: 0, script_pubkey: good_script });
1381 unsigned_announcement.features = ChannelFeatures::empty();
1382 msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1383 let valid_announcement = ChannelAnnouncement {
1384 node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
1385 node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
1386 bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_btckey),
1387 bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_btckey),
1388 contents: unsigned_announcement.clone(),
1390 match net_graph_msg_handler.handle_channel_announcement(&valid_announcement) {
1391 Ok(res) => assert!(res),
1395 let network = net_graph_msg_handler.network_graph.read().unwrap();
1396 match network.get_channels().get(&unsigned_announcement.short_channel_id) {
1397 Some(channel_entry) => {
1398 assert_eq!(channel_entry.features, ChannelFeatures::empty());
1404 // Don't relay valid channels with excess data
1405 unsigned_announcement.short_channel_id += 1;
1406 unsigned_announcement.excess_data.resize(MAX_EXCESS_BYTES_FOR_RELAY + 1, 0);
1407 msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1408 let valid_announcement = ChannelAnnouncement {
1409 node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
1410 node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
1411 bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_btckey),
1412 bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_btckey),
1413 contents: unsigned_announcement.clone(),
1415 match net_graph_msg_handler.handle_channel_announcement(&valid_announcement) {
1416 Ok(res) => assert!(!res),
1420 unsigned_announcement.excess_data = Vec::new();
1421 let invalid_sig_announcement = ChannelAnnouncement {
1422 node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
1423 node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
1424 bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_btckey),
1425 bitcoin_signature_2: secp_ctx.sign(&msghash, node_1_btckey),
1426 contents: unsigned_announcement.clone(),
1428 match net_graph_msg_handler.handle_channel_announcement(&invalid_sig_announcement) {
1430 Err(e) => assert_eq!(e.err, "Invalid signature from remote node")
1433 unsigned_announcement.node_id_1 = PublicKey::from_secret_key(&secp_ctx, node_2_privkey);
1434 msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1435 let channel_to_itself_announcement = ChannelAnnouncement {
1436 node_signature_1: secp_ctx.sign(&msghash, node_2_privkey),
1437 node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
1438 bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_btckey),
1439 bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_btckey),
1440 contents: unsigned_announcement.clone(),
1442 match net_graph_msg_handler.handle_channel_announcement(&channel_to_itself_announcement) {
1444 Err(e) => assert_eq!(e.err, "Channel announcement node had a channel with itself")
1449 fn handling_channel_update() {
1450 let secp_ctx = Secp256k1::new();
1451 let logger: Arc<Logger> = Arc::new(test_utils::TestLogger::new());
1452 let chain_source = Arc::new(test_utils::TestChainSource::new(Network::Testnet));
1453 let net_graph_msg_handler = NetGraphMsgHandler::new(genesis_block(Network::Testnet).header.block_hash(), Some(chain_source.clone()), Arc::clone(&logger));
1455 let node_1_privkey = &SecretKey::from_slice(&[42; 32]).unwrap();
1456 let node_2_privkey = &SecretKey::from_slice(&[41; 32]).unwrap();
1457 let node_id_1 = PublicKey::from_secret_key(&secp_ctx, node_1_privkey);
1458 let node_id_2 = PublicKey::from_secret_key(&secp_ctx, node_2_privkey);
1459 let node_1_btckey = &SecretKey::from_slice(&[40; 32]).unwrap();
1460 let node_2_btckey = &SecretKey::from_slice(&[39; 32]).unwrap();
1462 let zero_hash = Sha256dHash::hash(&[0; 32]);
1463 let short_channel_id = 0;
1464 let chain_hash = genesis_block(Network::Testnet).header.block_hash();
1465 let amount_sats = 1000_000;
1468 // Announce a channel we will update
1469 let good_script = Builder::new().push_opcode(opcodes::all::OP_PUSHNUM_2)
1470 .push_slice(&PublicKey::from_secret_key(&secp_ctx, node_1_btckey).serialize())
1471 .push_slice(&PublicKey::from_secret_key(&secp_ctx, node_2_btckey).serialize())
1472 .push_opcode(opcodes::all::OP_PUSHNUM_2)
1473 .push_opcode(opcodes::all::OP_CHECKMULTISIG).into_script().to_v0_p2wsh();
1474 *chain_source.utxo_ret.lock().unwrap() = Ok(TxOut { value: amount_sats, script_pubkey: good_script.clone() });
1475 let unsigned_announcement = UnsignedChannelAnnouncement {
1476 features: ChannelFeatures::empty(),
1481 bitcoin_key_1: PublicKey::from_secret_key(&secp_ctx, node_1_btckey),
1482 bitcoin_key_2: PublicKey::from_secret_key(&secp_ctx, node_2_btckey),
1483 excess_data: Vec::new(),
1486 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1487 let valid_channel_announcement = ChannelAnnouncement {
1488 node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
1489 node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
1490 bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_btckey),
1491 bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_btckey),
1492 contents: unsigned_announcement.clone(),
1494 match net_graph_msg_handler.handle_channel_announcement(&valid_channel_announcement) {
1501 let mut unsigned_channel_update = UnsignedChannelUpdate {
1506 cltv_expiry_delta: 144,
1507 htlc_minimum_msat: 1000000,
1508 htlc_maximum_msat: OptionalField::Absent,
1509 fee_base_msat: 10000,
1510 fee_proportional_millionths: 20,
1511 excess_data: Vec::new()
1513 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_channel_update.encode()[..])[..]);
1514 let valid_channel_update = ChannelUpdate {
1515 signature: secp_ctx.sign(&msghash, node_1_privkey),
1516 contents: unsigned_channel_update.clone()
1519 match net_graph_msg_handler.handle_channel_update(&valid_channel_update) {
1520 Ok(res) => assert!(res),
1525 let network = net_graph_msg_handler.network_graph.read().unwrap();
1526 match network.get_channels().get(&short_channel_id) {
1528 Some(channel_info) => {
1529 assert_eq!(channel_info.one_to_two.as_ref().unwrap().cltv_expiry_delta, 144);
1530 assert!(channel_info.two_to_one.is_none());
1535 unsigned_channel_update.timestamp += 100;
1536 unsigned_channel_update.excess_data.resize(MAX_EXCESS_BYTES_FOR_RELAY + 1, 0);
1537 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_channel_update.encode()[..])[..]);
1538 let valid_channel_update = ChannelUpdate {
1539 signature: secp_ctx.sign(&msghash, node_1_privkey),
1540 contents: unsigned_channel_update.clone()
1542 // Return false because contains excess data
1543 match net_graph_msg_handler.handle_channel_update(&valid_channel_update) {
1544 Ok(res) => assert!(!res),
1547 unsigned_channel_update.timestamp += 10;
1549 unsigned_channel_update.short_channel_id += 1;
1550 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_channel_update.encode()[..])[..]);
1551 let valid_channel_update = ChannelUpdate {
1552 signature: secp_ctx.sign(&msghash, node_1_privkey),
1553 contents: unsigned_channel_update.clone()
1556 match net_graph_msg_handler.handle_channel_update(&valid_channel_update) {
1558 Err(e) => assert_eq!(e.err, "Couldn't find channel for update")
1560 unsigned_channel_update.short_channel_id = short_channel_id;
1562 unsigned_channel_update.htlc_maximum_msat = OptionalField::Present(MAX_VALUE_MSAT + 1);
1563 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_channel_update.encode()[..])[..]);
1564 let valid_channel_update = ChannelUpdate {
1565 signature: secp_ctx.sign(&msghash, node_1_privkey),
1566 contents: unsigned_channel_update.clone()
1569 match net_graph_msg_handler.handle_channel_update(&valid_channel_update) {
1571 Err(e) => assert_eq!(e.err, "htlc_maximum_msat is larger than maximum possible msats")
1573 unsigned_channel_update.htlc_maximum_msat = OptionalField::Absent;
1575 unsigned_channel_update.htlc_maximum_msat = OptionalField::Present(amount_sats * 1000 + 1);
1576 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_channel_update.encode()[..])[..]);
1577 let valid_channel_update = ChannelUpdate {
1578 signature: secp_ctx.sign(&msghash, node_1_privkey),
1579 contents: unsigned_channel_update.clone()
1582 match net_graph_msg_handler.handle_channel_update(&valid_channel_update) {
1584 Err(e) => assert_eq!(e.err, "htlc_maximum_msat is larger than channel capacity or capacity is bogus")
1586 unsigned_channel_update.htlc_maximum_msat = OptionalField::Absent;
1588 // Even though previous update was not relayed further, we still accepted it,
1589 // so we now won't accept update before the previous one.
1590 unsigned_channel_update.timestamp -= 10;
1591 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_channel_update.encode()[..])[..]);
1592 let valid_channel_update = ChannelUpdate {
1593 signature: secp_ctx.sign(&msghash, node_1_privkey),
1594 contents: unsigned_channel_update.clone()
1597 match net_graph_msg_handler.handle_channel_update(&valid_channel_update) {
1599 Err(e) => assert_eq!(e.err, "Update older than last processed update")
1601 unsigned_channel_update.timestamp += 500;
1603 let fake_msghash = hash_to_message!(&zero_hash);
1604 let invalid_sig_channel_update = ChannelUpdate {
1605 signature: secp_ctx.sign(&fake_msghash, node_1_privkey),
1606 contents: unsigned_channel_update.clone()
1609 match net_graph_msg_handler.handle_channel_update(&invalid_sig_channel_update) {
1611 Err(e) => assert_eq!(e.err, "Invalid signature from remote node")
1617 fn handling_htlc_fail_channel_update() {
1618 let (secp_ctx, net_graph_msg_handler) = create_net_graph_msg_handler();
1619 let node_1_privkey = &SecretKey::from_slice(&[42; 32]).unwrap();
1620 let node_2_privkey = &SecretKey::from_slice(&[41; 32]).unwrap();
1621 let node_id_1 = PublicKey::from_secret_key(&secp_ctx, node_1_privkey);
1622 let node_id_2 = PublicKey::from_secret_key(&secp_ctx, node_2_privkey);
1623 let node_1_btckey = &SecretKey::from_slice(&[40; 32]).unwrap();
1624 let node_2_btckey = &SecretKey::from_slice(&[39; 32]).unwrap();
1626 let short_channel_id = 0;
1627 let chain_hash = genesis_block(Network::Testnet).header.block_hash();
1630 // There is no nodes in the table at the beginning.
1631 let network = net_graph_msg_handler.network_graph.read().unwrap();
1632 assert_eq!(network.get_nodes().len(), 0);
1636 // Announce a channel we will update
1637 let unsigned_announcement = UnsignedChannelAnnouncement {
1638 features: ChannelFeatures::empty(),
1643 bitcoin_key_1: PublicKey::from_secret_key(&secp_ctx, node_1_btckey),
1644 bitcoin_key_2: PublicKey::from_secret_key(&secp_ctx, node_2_btckey),
1645 excess_data: Vec::new(),
1648 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1649 let valid_channel_announcement = ChannelAnnouncement {
1650 node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
1651 node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
1652 bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_btckey),
1653 bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_btckey),
1654 contents: unsigned_announcement.clone(),
1656 match net_graph_msg_handler.handle_channel_announcement(&valid_channel_announcement) {
1661 let unsigned_channel_update = UnsignedChannelUpdate {
1666 cltv_expiry_delta: 144,
1667 htlc_minimum_msat: 1000000,
1668 htlc_maximum_msat: OptionalField::Absent,
1669 fee_base_msat: 10000,
1670 fee_proportional_millionths: 20,
1671 excess_data: Vec::new()
1673 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_channel_update.encode()[..])[..]);
1674 let valid_channel_update = ChannelUpdate {
1675 signature: secp_ctx.sign(&msghash, node_1_privkey),
1676 contents: unsigned_channel_update.clone()
1679 match net_graph_msg_handler.handle_channel_update(&valid_channel_update) {
1680 Ok(res) => assert!(res),
1685 // Non-permanent closing just disables a channel
1687 let network = net_graph_msg_handler.network_graph.read().unwrap();
1688 match network.get_channels().get(&short_channel_id) {
1690 Some(channel_info) => {
1691 assert!(channel_info.one_to_two.is_some());
1696 let channel_close_msg = HTLCFailChannelUpdate::ChannelClosed {
1701 net_graph_msg_handler.handle_htlc_fail_channel_update(&channel_close_msg);
1703 // Non-permanent closing just disables a channel
1705 let network = net_graph_msg_handler.network_graph.read().unwrap();
1706 match network.get_channels().get(&short_channel_id) {
1708 Some(channel_info) => {
1709 assert!(!channel_info.one_to_two.as_ref().unwrap().enabled);
1714 let channel_close_msg = HTLCFailChannelUpdate::ChannelClosed {
1719 net_graph_msg_handler.handle_htlc_fail_channel_update(&channel_close_msg);
1721 // Permanent closing deletes a channel
1723 let network = net_graph_msg_handler.network_graph.read().unwrap();
1724 assert_eq!(network.get_channels().len(), 0);
1725 // Nodes are also deleted because there are no associated channels anymore
1726 assert_eq!(network.get_nodes().len(), 0);
1728 // TODO: Test HTLCFailChannelUpdate::NodeFailure, which is not implemented yet.
1732 fn getting_next_channel_announcements() {
1733 let (secp_ctx, net_graph_msg_handler) = create_net_graph_msg_handler();
1734 let node_1_privkey = &SecretKey::from_slice(&[42; 32]).unwrap();
1735 let node_2_privkey = &SecretKey::from_slice(&[41; 32]).unwrap();
1736 let node_id_1 = PublicKey::from_secret_key(&secp_ctx, node_1_privkey);
1737 let node_id_2 = PublicKey::from_secret_key(&secp_ctx, node_2_privkey);
1738 let node_1_btckey = &SecretKey::from_slice(&[40; 32]).unwrap();
1739 let node_2_btckey = &SecretKey::from_slice(&[39; 32]).unwrap();
1741 let short_channel_id = 1;
1742 let chain_hash = genesis_block(Network::Testnet).header.block_hash();
1744 // Channels were not announced yet.
1745 let channels_with_announcements = net_graph_msg_handler.get_next_channel_announcements(0, 1);
1746 assert_eq!(channels_with_announcements.len(), 0);
1749 // Announce a channel we will update
1750 let unsigned_announcement = UnsignedChannelAnnouncement {
1751 features: ChannelFeatures::empty(),
1756 bitcoin_key_1: PublicKey::from_secret_key(&secp_ctx, node_1_btckey),
1757 bitcoin_key_2: PublicKey::from_secret_key(&secp_ctx, node_2_btckey),
1758 excess_data: Vec::new(),
1761 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1762 let valid_channel_announcement = ChannelAnnouncement {
1763 node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
1764 node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
1765 bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_btckey),
1766 bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_btckey),
1767 contents: unsigned_announcement.clone(),
1769 match net_graph_msg_handler.handle_channel_announcement(&valid_channel_announcement) {
1775 // Contains initial channel announcement now.
1776 let channels_with_announcements = net_graph_msg_handler.get_next_channel_announcements(short_channel_id, 1);
1777 assert_eq!(channels_with_announcements.len(), 1);
1778 if let Some(channel_announcements) = channels_with_announcements.first() {
1779 let &(_, ref update_1, ref update_2) = channel_announcements;
1780 assert_eq!(update_1, &None);
1781 assert_eq!(update_2, &None);
1788 // Valid channel update
1789 let unsigned_channel_update = UnsignedChannelUpdate {
1794 cltv_expiry_delta: 144,
1795 htlc_minimum_msat: 1000000,
1796 htlc_maximum_msat: OptionalField::Absent,
1797 fee_base_msat: 10000,
1798 fee_proportional_millionths: 20,
1799 excess_data: Vec::new()
1801 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_channel_update.encode()[..])[..]);
1802 let valid_channel_update = ChannelUpdate {
1803 signature: secp_ctx.sign(&msghash, node_1_privkey),
1804 contents: unsigned_channel_update.clone()
1806 match net_graph_msg_handler.handle_channel_update(&valid_channel_update) {
1812 // Now contains an initial announcement and an update.
1813 let channels_with_announcements = net_graph_msg_handler.get_next_channel_announcements(short_channel_id, 1);
1814 assert_eq!(channels_with_announcements.len(), 1);
1815 if let Some(channel_announcements) = channels_with_announcements.first() {
1816 let &(_, ref update_1, ref update_2) = channel_announcements;
1817 assert_ne!(update_1, &None);
1818 assert_eq!(update_2, &None);
1825 // Channel update with excess data.
1826 let unsigned_channel_update = UnsignedChannelUpdate {
1831 cltv_expiry_delta: 144,
1832 htlc_minimum_msat: 1000000,
1833 htlc_maximum_msat: OptionalField::Absent,
1834 fee_base_msat: 10000,
1835 fee_proportional_millionths: 20,
1836 excess_data: [1; MAX_EXCESS_BYTES_FOR_RELAY + 1].to_vec()
1838 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_channel_update.encode()[..])[..]);
1839 let valid_channel_update = ChannelUpdate {
1840 signature: secp_ctx.sign(&msghash, node_1_privkey),
1841 contents: unsigned_channel_update.clone()
1843 match net_graph_msg_handler.handle_channel_update(&valid_channel_update) {
1849 // Test that announcements with excess data won't be returned
1850 let channels_with_announcements = net_graph_msg_handler.get_next_channel_announcements(short_channel_id, 1);
1851 assert_eq!(channels_with_announcements.len(), 1);
1852 if let Some(channel_announcements) = channels_with_announcements.first() {
1853 let &(_, ref update_1, ref update_2) = channel_announcements;
1854 assert_eq!(update_1, &None);
1855 assert_eq!(update_2, &None);
1860 // Further starting point have no channels after it
1861 let channels_with_announcements = net_graph_msg_handler.get_next_channel_announcements(short_channel_id + 1000, 1);
1862 assert_eq!(channels_with_announcements.len(), 0);
1866 fn getting_next_node_announcements() {
1867 let (secp_ctx, net_graph_msg_handler) = create_net_graph_msg_handler();
1868 let node_1_privkey = &SecretKey::from_slice(&[42; 32]).unwrap();
1869 let node_2_privkey = &SecretKey::from_slice(&[41; 32]).unwrap();
1870 let node_id_1 = PublicKey::from_secret_key(&secp_ctx, node_1_privkey);
1871 let node_id_2 = PublicKey::from_secret_key(&secp_ctx, node_2_privkey);
1872 let node_1_btckey = &SecretKey::from_slice(&[40; 32]).unwrap();
1873 let node_2_btckey = &SecretKey::from_slice(&[39; 32]).unwrap();
1875 let short_channel_id = 1;
1876 let chain_hash = genesis_block(Network::Testnet).header.block_hash();
1879 let next_announcements = net_graph_msg_handler.get_next_node_announcements(None, 10);
1880 assert_eq!(next_announcements.len(), 0);
1883 // Announce a channel to add 2 nodes
1884 let unsigned_announcement = UnsignedChannelAnnouncement {
1885 features: ChannelFeatures::empty(),
1890 bitcoin_key_1: PublicKey::from_secret_key(&secp_ctx, node_1_btckey),
1891 bitcoin_key_2: PublicKey::from_secret_key(&secp_ctx, node_2_btckey),
1892 excess_data: Vec::new(),
1895 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1896 let valid_channel_announcement = ChannelAnnouncement {
1897 node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
1898 node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
1899 bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_btckey),
1900 bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_btckey),
1901 contents: unsigned_announcement.clone(),
1903 match net_graph_msg_handler.handle_channel_announcement(&valid_channel_announcement) {
1910 // Nodes were never announced
1911 let next_announcements = net_graph_msg_handler.get_next_node_announcements(None, 3);
1912 assert_eq!(next_announcements.len(), 0);
1915 let mut unsigned_announcement = UnsignedNodeAnnouncement {
1916 features: NodeFeatures::known(),
1921 addresses: Vec::new(),
1922 excess_address_data: Vec::new(),
1923 excess_data: Vec::new(),
1925 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1926 let valid_announcement = NodeAnnouncement {
1927 signature: secp_ctx.sign(&msghash, node_1_privkey),
1928 contents: unsigned_announcement.clone()
1930 match net_graph_msg_handler.handle_node_announcement(&valid_announcement) {
1935 unsigned_announcement.node_id = node_id_2;
1936 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1937 let valid_announcement = NodeAnnouncement {
1938 signature: secp_ctx.sign(&msghash, node_2_privkey),
1939 contents: unsigned_announcement.clone()
1942 match net_graph_msg_handler.handle_node_announcement(&valid_announcement) {
1948 let next_announcements = net_graph_msg_handler.get_next_node_announcements(None, 3);
1949 assert_eq!(next_announcements.len(), 2);
1951 // Skip the first node.
1952 let next_announcements = net_graph_msg_handler.get_next_node_announcements(Some(&node_id_1), 2);
1953 assert_eq!(next_announcements.len(), 1);
1956 // Later announcement which should not be relayed (excess data) prevent us from sharing a node
1957 let unsigned_announcement = UnsignedNodeAnnouncement {
1958 features: NodeFeatures::known(),
1963 addresses: Vec::new(),
1964 excess_address_data: Vec::new(),
1965 excess_data: [1; MAX_EXCESS_BYTES_FOR_RELAY + 1].to_vec(),
1967 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1968 let valid_announcement = NodeAnnouncement {
1969 signature: secp_ctx.sign(&msghash, node_2_privkey),
1970 contents: unsigned_announcement.clone()
1972 match net_graph_msg_handler.handle_node_announcement(&valid_announcement) {
1973 Ok(res) => assert!(!res),
1978 let next_announcements = net_graph_msg_handler.get_next_node_announcements(Some(&node_id_1), 2);
1979 assert_eq!(next_announcements.len(), 0);
1983 fn network_graph_serialization() {
1984 let (secp_ctx, net_graph_msg_handler) = create_net_graph_msg_handler();
1986 let node_1_privkey = &SecretKey::from_slice(&[42; 32]).unwrap();
1987 let node_2_privkey = &SecretKey::from_slice(&[41; 32]).unwrap();
1988 let node_1_btckey = &SecretKey::from_slice(&[40; 32]).unwrap();
1989 let node_2_btckey = &SecretKey::from_slice(&[39; 32]).unwrap();
1991 // Announce a channel to add a corresponding node.
1992 let node_id_1 = PublicKey::from_secret_key(&secp_ctx, node_1_privkey);
1993 let node_id_2 = PublicKey::from_secret_key(&secp_ctx, node_2_privkey);
1994 let unsigned_announcement = UnsignedChannelAnnouncement {
1995 features: ChannelFeatures::known(),
1996 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1997 short_channel_id: 0,
2000 bitcoin_key_1: PublicKey::from_secret_key(&secp_ctx, node_1_btckey),
2001 bitcoin_key_2: PublicKey::from_secret_key(&secp_ctx, node_2_btckey),
2002 excess_data: Vec::new(),
2005 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
2006 let valid_announcement = ChannelAnnouncement {
2007 node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
2008 node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
2009 bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_btckey),
2010 bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_btckey),
2011 contents: unsigned_announcement.clone(),
2013 match net_graph_msg_handler.handle_channel_announcement(&valid_announcement) {
2014 Ok(res) => assert!(res),
2019 let node_id = PublicKey::from_secret_key(&secp_ctx, node_1_privkey);
2020 let unsigned_announcement = UnsignedNodeAnnouncement {
2021 features: NodeFeatures::known(),
2026 addresses: Vec::new(),
2027 excess_address_data: Vec::new(),
2028 excess_data: Vec::new(),
2030 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
2031 let valid_announcement = NodeAnnouncement {
2032 signature: secp_ctx.sign(&msghash, node_1_privkey),
2033 contents: unsigned_announcement.clone()
2036 match net_graph_msg_handler.handle_node_announcement(&valid_announcement) {
2041 let network = net_graph_msg_handler.network_graph.write().unwrap();
2042 let mut w = test_utils::TestVecWriter(Vec::new());
2043 assert!(!network.get_nodes().is_empty());
2044 assert!(!network.get_channels().is_empty());
2045 network.write(&mut w).unwrap();
2046 assert!(<NetworkGraph>::read(&mut ::std::io::Cursor::new(&w.0)).unwrap() == *network);
2050 fn calling_sync_routing_table() {
2051 let (secp_ctx, net_graph_msg_handler) = create_net_graph_msg_handler();
2052 let node_privkey_1 = &SecretKey::from_slice(&[42; 32]).unwrap();
2053 let node_id_1 = PublicKey::from_secret_key(&secp_ctx, node_privkey_1);
2055 let chain_hash = genesis_block(Network::Testnet).header.block_hash();
2056 let first_blocknum = 0;
2057 let number_of_blocks = 0xffff_ffff;
2059 // It should ignore if gossip_queries feature is not enabled
2061 let init_msg = Init { features: InitFeatures::known().clear_gossip_queries() };
2062 net_graph_msg_handler.sync_routing_table(&node_id_1, &init_msg);
2063 let events = net_graph_msg_handler.get_and_clear_pending_msg_events();
2064 assert_eq!(events.len(), 0);
2067 // It should send a query_channel_message with the correct information
2069 let init_msg = Init { features: InitFeatures::known() };
2070 net_graph_msg_handler.sync_routing_table(&node_id_1, &init_msg);
2071 let events = net_graph_msg_handler.get_and_clear_pending_msg_events();
2072 assert_eq!(events.len(), 1);
2074 MessageSendEvent::SendChannelRangeQuery{ node_id, msg } => {
2075 assert_eq!(node_id, &node_id_1);
2076 assert_eq!(msg.chain_hash, chain_hash);
2077 assert_eq!(msg.first_blocknum, first_blocknum);
2078 assert_eq!(msg.number_of_blocks, number_of_blocks);
2080 _ => panic!("Expected MessageSendEvent::SendChannelRangeQuery")
2084 // It should not enqueue a query when should_request_full_sync return false.
2085 // The initial implementation allows syncing with the first 5 peers after
2086 // which should_request_full_sync will return false
2088 let (secp_ctx, net_graph_msg_handler) = create_net_graph_msg_handler();
2089 let init_msg = Init { features: InitFeatures::known() };
2091 let node_privkey = &SecretKey::from_slice(&[n; 32]).unwrap();
2092 let node_id = PublicKey::from_secret_key(&secp_ctx, node_privkey);
2093 net_graph_msg_handler.sync_routing_table(&node_id, &init_msg);
2094 let events = net_graph_msg_handler.get_and_clear_pending_msg_events();
2096 assert_eq!(events.len(), 1);
2098 assert_eq!(events.len(), 0);
2106 fn handling_reply_channel_range() {
2107 let (secp_ctx, net_graph_msg_handler) = create_net_graph_msg_handler();
2108 let node_privkey_1 = &SecretKey::from_slice(&[42; 32]).unwrap();
2109 let node_id_1 = PublicKey::from_secret_key(&secp_ctx, node_privkey_1);
2111 let chain_hash = genesis_block(Network::Testnet).header.block_hash();
2113 // Test receipt of a single reply that should enqueue an SCID query
2114 // matching the SCIDs in the reply
2116 let result = net_graph_msg_handler.handle_reply_channel_range(&node_id_1, ReplyChannelRange {
2118 sync_complete: true,
2120 number_of_blocks: 2000,
2121 short_channel_ids: vec![
2122 0x0003e0_000000_0000, // 992x0x0
2123 0x0003e8_000000_0000, // 1000x0x0
2124 0x0003e9_000000_0000, // 1001x0x0
2125 0x0003f0_000000_0000, // 1008x0x0
2126 0x00044c_000000_0000, // 1100x0x0
2127 0x0006e0_000000_0000, // 1760x0x0
2130 assert!(result.is_ok());
2132 // We expect to emit a query_short_channel_ids message with the received scids
2133 let events = net_graph_msg_handler.get_and_clear_pending_msg_events();
2134 assert_eq!(events.len(), 1);
2136 MessageSendEvent::SendShortIdsQuery { node_id, msg } => {
2137 assert_eq!(node_id, &node_id_1);
2138 assert_eq!(msg.chain_hash, chain_hash);
2139 assert_eq!(msg.short_channel_ids, vec![
2140 0x0003e0_000000_0000, // 992x0x0
2141 0x0003e8_000000_0000, // 1000x0x0
2142 0x0003e9_000000_0000, // 1001x0x0
2143 0x0003f0_000000_0000, // 1008x0x0
2144 0x00044c_000000_0000, // 1100x0x0
2145 0x0006e0_000000_0000, // 1760x0x0
2148 _ => panic!("expected MessageSendEvent::SendShortIdsQuery"),
2154 fn handling_reply_short_channel_ids() {
2155 let (secp_ctx, net_graph_msg_handler) = create_net_graph_msg_handler();
2156 let node_privkey = &SecretKey::from_slice(&[41; 32]).unwrap();
2157 let node_id = PublicKey::from_secret_key(&secp_ctx, node_privkey);
2159 let chain_hash = genesis_block(Network::Testnet).header.block_hash();
2161 // Test receipt of a successful reply
2163 let result = net_graph_msg_handler.handle_reply_short_channel_ids_end(&node_id, ReplyShortChannelIdsEnd {
2165 full_information: true,
2167 assert!(result.is_ok());
2170 // Test receipt of a reply that indicates the peer does not maintain up-to-date information
2171 // for the chain_hash requested in the query.
2173 let result = net_graph_msg_handler.handle_reply_short_channel_ids_end(&node_id, ReplyShortChannelIdsEnd {
2175 full_information: false,
2177 assert!(result.is_err());
2178 assert_eq!(result.err().unwrap().err, "Received reply_short_channel_ids_end with no information");
2183 fn handling_query_channel_range() {
2184 let (secp_ctx, mut net_graph_msg_handler) = create_net_graph_msg_handler();
2186 let chain_hash = genesis_block(Network::Testnet).header.block_hash();
2187 let node_1_privkey = &SecretKey::from_slice(&[42; 32]).unwrap();
2188 let node_2_privkey = &SecretKey::from_slice(&[41; 32]).unwrap();
2189 let node_1_btckey = &SecretKey::from_slice(&[40; 32]).unwrap();
2190 let node_2_btckey = &SecretKey::from_slice(&[39; 32]).unwrap();
2191 let node_id_1 = PublicKey::from_secret_key(&secp_ctx, node_1_privkey);
2192 let node_id_2 = PublicKey::from_secret_key(&secp_ctx, node_2_privkey);
2193 let bitcoin_key_1 = PublicKey::from_secret_key(&secp_ctx, node_1_btckey);
2194 let bitcoin_key_2 = PublicKey::from_secret_key(&secp_ctx, node_2_btckey);
2196 let scids: Vec<u64> = vec![
2197 0x000000_000000_0000, // 0x0x0
2198 0x000001_000000_0000, // 1x0x0
2199 0x000002_000000_0000, // 2x0x0
2200 0x000002_000001_0000, // 2x1x0
2201 0x000100_000000_0000, // 256x0x0
2202 0x000101_000000_0000, // 257x0x0
2203 0xfffffe_ffffff_ffff, // max
2204 0xffffff_ffffff_ffff, // never
2208 let unsigned_announcement = UnsignedChannelAnnouncement {
2209 features: ChannelFeatures::known(),
2210 chain_hash: chain_hash.clone(),
2211 short_channel_id: scid,
2216 excess_data: Vec::new(),
2219 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
2220 let valid_announcement = ChannelAnnouncement {
2221 node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
2222 node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
2223 bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_btckey),
2224 bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_btckey),
2225 contents: unsigned_announcement.clone(),
2227 match net_graph_msg_handler.handle_channel_announcement(&valid_announcement) {
2233 // Empty reply when number_of_blocks=0
2234 test_handling_query_channel_range(
2235 &net_graph_msg_handler,
2238 chain_hash: chain_hash.clone(),
2240 number_of_blocks: 0,
2242 vec![ReplyChannelRange {
2243 chain_hash: chain_hash.clone(),
2245 number_of_blocks: 0,
2246 sync_complete: true,
2247 short_channel_ids: vec![]
2251 // Empty when wrong chain
2252 test_handling_query_channel_range(
2253 &net_graph_msg_handler,
2256 chain_hash: genesis_block(Network::Bitcoin).header.block_hash(),
2258 number_of_blocks: 0xffff_ffff,
2260 vec![ReplyChannelRange {
2261 chain_hash: genesis_block(Network::Bitcoin).header.block_hash(),
2263 number_of_blocks: 0xffff_ffff,
2264 sync_complete: true,
2265 short_channel_ids: vec![],
2269 // Empty reply when first_blocknum > 0xffffff
2270 test_handling_query_channel_range(
2271 &net_graph_msg_handler,
2274 chain_hash: chain_hash.clone(),
2275 first_blocknum: 0x01000000,
2276 number_of_blocks: 0xffffffff,
2278 vec![ReplyChannelRange {
2279 chain_hash: chain_hash.clone(),
2280 first_blocknum: 0x01000000,
2281 number_of_blocks: 0xffffffff,
2282 sync_complete: true,
2283 short_channel_ids: vec![]
2287 // Empty reply when max valid SCID block num.
2288 // Unlike prior test this is a valid but no results are found
2289 test_handling_query_channel_range(
2290 &net_graph_msg_handler,
2293 chain_hash: chain_hash.clone(),
2294 first_blocknum: 0xffffff,
2295 number_of_blocks: 1,
2299 chain_hash: chain_hash.clone(),
2300 first_blocknum: 0xffffff,
2301 number_of_blocks: 1,
2302 sync_complete: true,
2303 short_channel_ids: vec![]
2308 // No results in valid query range
2309 test_handling_query_channel_range(
2310 &net_graph_msg_handler,
2313 chain_hash: chain_hash.clone(),
2314 first_blocknum: 0x00100000,
2315 number_of_blocks: 1000,
2319 chain_hash: chain_hash.clone(),
2320 first_blocknum: 0x00100000,
2321 number_of_blocks: 1000,
2322 sync_complete: true,
2323 short_channel_ids: vec![],
2328 // Single reply - all blocks
2329 test_handling_query_channel_range(
2330 &net_graph_msg_handler,
2333 chain_hash: chain_hash.clone(),
2335 number_of_blocks: 0xffffffff,
2339 chain_hash: chain_hash.clone(),
2341 number_of_blocks: 0xffffffff,
2342 sync_complete: true,
2343 short_channel_ids: vec![
2344 0x000000_000000_0000, // 0x0x0
2345 0x000001_000000_0000, // 1x0x0
2346 0x000002_000000_0000, // 2x0x0
2347 0x000002_000001_0000, // 2x1x0
2348 0x000100_000000_0000, // 256x0x0
2349 0x000101_000000_0000, // 257x0x0
2350 0xfffffe_ffffff_ffff, // max
2356 // Single reply - overflow of first_blocknum + number_of_blocks
2357 test_handling_query_channel_range(
2358 &net_graph_msg_handler,
2361 chain_hash: chain_hash.clone(),
2363 number_of_blocks: 0xffffffff,
2367 chain_hash: chain_hash.clone(),
2369 number_of_blocks: 0xfffffffe,
2370 sync_complete: true,
2371 short_channel_ids: vec![
2372 0x000001_000000_0000, // 1x0x0
2373 0x000002_000000_0000, // 2x0x0
2374 0x000002_000001_0000, // 2x1x0
2375 0x000100_000000_0000, // 256x0x0
2376 0x000101_000000_0000, // 257x0x0
2377 0xfffffe_ffffff_ffff, // max
2383 // Single reply - query larger than found results
2384 test_handling_query_channel_range(
2385 &net_graph_msg_handler,
2388 chain_hash: chain_hash.clone(),
2389 first_blocknum: 100,
2390 number_of_blocks: 1000,
2394 chain_hash: chain_hash.clone(),
2395 first_blocknum: 100,
2396 number_of_blocks: 1000,
2397 sync_complete: true,
2398 short_channel_ids: vec![
2399 0x000100_000000_0000, // 256x0x0
2400 0x000101_000000_0000, // 257x0x0
2406 // Tests below here will chunk replies
2407 net_graph_msg_handler.max_reply_scids = 1;
2409 // Multipart - new block per messages
2410 test_handling_query_channel_range(
2411 &net_graph_msg_handler,
2414 chain_hash: chain_hash.clone(),
2416 number_of_blocks: 2,
2420 chain_hash: chain_hash.clone(),
2422 number_of_blocks: 1,
2423 sync_complete: false,
2424 short_channel_ids: vec![
2425 0x000000_000000_0000, // 0x0x0
2429 chain_hash: chain_hash.clone(),
2431 number_of_blocks: 1,
2432 sync_complete: true,
2433 short_channel_ids: vec![
2434 0x000001_000000_0000, // 1x0x0
2440 // Multiplart - resumption of same block
2441 test_handling_query_channel_range(
2442 &net_graph_msg_handler,
2445 chain_hash: chain_hash.clone(),
2447 number_of_blocks: 1,
2451 chain_hash: chain_hash.clone(),
2453 number_of_blocks: 1,
2454 sync_complete: false,
2455 short_channel_ids: vec![
2456 0x000002_000000_0000, // 2x0x0
2460 chain_hash: chain_hash.clone(),
2462 number_of_blocks: 1,
2463 sync_complete: true,
2464 short_channel_ids: vec![
2465 0x000002_000001_0000, // 2x1x0
2471 // Multipart - query larger than found results, similar to single reply
2472 test_handling_query_channel_range(
2473 &net_graph_msg_handler,
2476 chain_hash: chain_hash.clone(),
2477 first_blocknum: 100,
2478 number_of_blocks: 1000,
2482 chain_hash: chain_hash.clone(),
2483 first_blocknum: 100, // <= query first_blocknum
2484 number_of_blocks: 157,
2485 sync_complete: false,
2486 short_channel_ids: vec![
2487 0x000100_000000_0000, // 256x0x0
2491 chain_hash: chain_hash.clone(),
2492 first_blocknum: 257,
2493 number_of_blocks: 843, // >= query first_blocknum+number_of_blocks
2494 sync_complete: true,
2495 short_channel_ids: vec![
2496 0x000101_000000_0000, // 257x0x0
2503 fn test_handling_query_channel_range(
2504 net_graph_msg_handler: &NetGraphMsgHandler<Arc<test_utils::TestChainSource>, Arc<test_utils::TestLogger>>,
2505 test_node_id: &PublicKey,
2506 msg: QueryChannelRange,
2507 expected_replies: Vec<ReplyChannelRange>
2509 let result = net_graph_msg_handler.handle_query_channel_range(test_node_id, msg);
2510 assert!(result.is_ok());
2512 let events = net_graph_msg_handler.get_and_clear_pending_msg_events();
2513 assert_eq!(events.len(), expected_replies.len());
2515 for i in 0..events.len() {
2516 let expected_reply = &expected_replies[i];
2518 MessageSendEvent::SendReplyChannelRange { node_id, msg } => {
2519 assert_eq!(node_id, test_node_id);
2520 assert_eq!(msg.chain_hash, expected_reply.chain_hash);
2521 assert_eq!(msg.first_blocknum, expected_reply.first_blocknum);
2522 assert_eq!(msg.number_of_blocks, expected_reply.number_of_blocks);
2523 assert_eq!(msg.sync_complete, expected_reply.sync_complete);
2524 assert_eq!(msg.short_channel_ids, expected_reply.short_channel_ids);
2526 _ => panic!("expected MessageSendEvent::SendReplyChannelRange"),
2532 fn handling_query_short_channel_ids() {
2533 let (secp_ctx, net_graph_msg_handler) = create_net_graph_msg_handler();
2534 let node_privkey = &SecretKey::from_slice(&[41; 32]).unwrap();
2535 let node_id = PublicKey::from_secret_key(&secp_ctx, node_privkey);
2537 let chain_hash = genesis_block(Network::Testnet).header.block_hash();
2539 let result = net_graph_msg_handler.handle_query_short_channel_ids(&node_id, QueryShortChannelIds {
2541 short_channel_ids: vec![0x0003e8_000000_0000],
2543 assert!(result.is_err());