Send reminders for stale-ish channels.
[rapid-gossip-sync-server] / src / lib.rs
index 01bc57081e473c1061f93a50f5e6e42848deb802..c6f266db0590fbf0e327a28fe019d3b6364e75f4 100644 (file)
@@ -4,7 +4,6 @@
 #![deny(non_upper_case_globals)]
 #![deny(non_camel_case_types)]
 #![deny(non_snake_case)]
-#![deny(unused_mut)]
 #![deny(unused_variables)]
 #![deny(unused_imports)]
 
@@ -15,10 +14,7 @@ use std::fs::File;
 use std::io::BufReader;
 use std::sync::Arc;
 
-use bitcoin::blockdata::constants::genesis_block;
-use bitcoin::Network;
-use bitcoin::secp256k1::PublicKey;
-use lightning::routing::gossip::NetworkGraph;
+use lightning::routing::gossip::{NetworkGraph, NodeId};
 use lightning::util::ser::{ReadableArgs, Writeable};
 use tokio::sync::mpsc;
 use crate::lookup::DeltaSet;
@@ -39,6 +35,12 @@ mod config;
 mod hex_utils;
 mod verifier;
 
+/// The purpose of this prefix is to identify the serialization format, should other rapid gossip
+/// sync formats arise in the future.
+///
+/// The fourth byte is the protocol version in case our format gets updated.
+const GOSSIP_PREFIX: [u8; 4] = [76, 68, 75, 1];
+
 pub struct RapidSyncProcessor {
        network_graph: Arc<NetworkGraph<TestLogger>>,
 }
@@ -54,21 +56,21 @@ pub struct SerializedResponse {
 
 impl RapidSyncProcessor {
        pub fn new() -> Self {
+               let network = config::network();
                let logger = TestLogger::new();
                let network_graph = if let Ok(file) = File::open(&config::network_graph_cache_path()) {
                        println!("Initializing from cached network graph…");
                        let mut buffered_reader = BufReader::new(file);
                        let network_graph_result = NetworkGraph::read(&mut buffered_reader, logger);
                        if let Ok(network_graph) = network_graph_result {
-                               network_graph.remove_stale_channels();
                                println!("Initialized from cached network graph!");
                                network_graph
                        } else {
                                println!("Initialization from cached network graph failed: {}", network_graph_result.err().unwrap());
-                               NetworkGraph::new(genesis_block(Network::Bitcoin).header.block_hash(), logger)
+                               NetworkGraph::new(network, logger)
                        }
                } else {
-                       NetworkGraph::new(genesis_block(Network::Bitcoin).header.block_hash(), logger)
+                       NetworkGraph::new(network, logger)
                };
                let arc_network_graph = Arc::new(network_graph);
                Self {
@@ -103,9 +105,42 @@ impl RapidSyncProcessor {
        }
 }
 
+/// This method generates a no-op blob that can be used as a delta where none exists.
+///
+/// The primary purpose of this method is the scenario of a client retrieving and processing a
+/// given snapshot, and then immediately retrieving the would-be next snapshot at the timestamp
+/// indicated by the one that was just processed.
+/// Previously, there would not be a new snapshot to be processed for that particular timestamp yet,
+/// and the server would return a 404 error.
+///
+/// In principle, this method could also be used to address another unfortunately all too common
+/// pitfall: requesting snapshots from intermediate timestamps, i. e. those that are not multiples
+/// of our granularity constant. Note that for that purpose, this method could be very dangerous,
+/// because if consumed, the `timestamp` value calculated here will overwrite the timestamp that
+/// the client previously had, which could result in duplicated or omitted gossip down the line.
+fn serialize_empty_blob(current_timestamp: u64) -> Vec<u8> {
+       let mut blob = GOSSIP_PREFIX.to_vec();
+
+       let network = config::network();
+       let genesis_block = bitcoin::blockdata::constants::genesis_block(network);
+       let chain_hash = genesis_block.block_hash();
+       chain_hash.write(&mut blob).unwrap();
+
+       let blob_timestamp = Snapshotter::round_down_to_nearest_multiple(current_timestamp, config::SNAPSHOT_CALCULATION_INTERVAL as u64) as u32;
+       blob_timestamp.write(&mut blob).unwrap();
+
+       0u32.write(&mut blob).unwrap(); // node count
+       0u32.write(&mut blob).unwrap(); // announcement count
+       0u32.write(&mut blob).unwrap(); // update count
+
+       blob
+}
+
 async fn serialize_delta(network_graph: Arc<NetworkGraph<TestLogger>>, last_sync_timestamp: u32, consider_intermediate_updates: bool) -> SerializedResponse {
        let (client, connection) = lookup::connect_to_db().await;
 
+       network_graph.remove_stale_channels_and_tracking();
+
        tokio::spawn(async move {
                if let Err(e) = connection.await {
                        panic!("connection error: {}", e);
@@ -118,21 +153,20 @@ async fn serialize_delta(network_graph: Arc<NetworkGraph<TestLogger>>, last_sync
        // chain hash only necessary if either channel announcements or non-incremental updates are present
        // for announcement-free incremental-only updates, chain hash can be skipped
 
-       let mut node_id_set: HashSet<[u8; 33]> = HashSet::new();
-       let mut node_id_indices: HashMap<[u8; 33], usize> = HashMap::new();
-       let mut node_ids: Vec<PublicKey> = Vec::new();
+       let mut node_id_set: HashSet<NodeId> = HashSet::new();
+       let mut node_id_indices: HashMap<NodeId, usize> = HashMap::new();
+       let mut node_ids: Vec<NodeId> = Vec::new();
        let mut duplicate_node_ids: i32 = 0;
 
-       let mut get_node_id_index = |node_id: PublicKey| {
-               let serialized_node_id = node_id.serialize();
-               if node_id_set.insert(serialized_node_id) {
+       let mut get_node_id_index = |node_id: NodeId| {
+               if node_id_set.insert(node_id) {
                        node_ids.push(node_id);
                        let index = node_ids.len() - 1;
-                       node_id_indices.insert(serialized_node_id, index);
+                       node_id_indices.insert(node_id, index);
                        return index;
                }
                duplicate_node_ids += 1;
-               node_id_indices[&serialized_node_id]
+               node_id_indices[&node_id]
        };
 
        let mut delta_set = DeltaSet::new();
@@ -179,7 +213,7 @@ async fn serialize_delta(network_graph: Arc<NetworkGraph<TestLogger>>, last_sync
                        UpdateSerializationMechanism::Full => {
                                update_count_full += 1;
                        }
-                       UpdateSerializationMechanism::Incremental(_) => {
+                       UpdateSerializationMechanism::Incremental(_) | UpdateSerializationMechanism::Reminder => {
                                update_count_incremental += 1;
                        }
                };
@@ -193,7 +227,7 @@ async fn serialize_delta(network_graph: Arc<NetworkGraph<TestLogger>>, last_sync
        // some stats
        let message_count = announcement_count + update_count;
 
-       let mut prefixed_output = vec![76, 68, 75, 1];
+       let mut prefixed_output = GOSSIP_PREFIX.to_vec();
 
        // always write the chain hash
        serialization_details.chain_hash.write(&mut prefixed_output).unwrap();