Allow passing a timestamp override to snapshot calculation.
[rapid-gossip-sync-server] / src / lib.rs
1 #![deny(unsafe_code)]
2 #![deny(broken_intra_doc_links)]
3 #![deny(private_intra_doc_links)]
4 #![deny(non_upper_case_globals)]
5 #![deny(non_camel_case_types)]
6 #![deny(non_snake_case)]
7 #![deny(unused_variables)]
8 #![deny(unused_imports)]
9
10 extern crate core;
11
12 use std::collections::{HashMap, HashSet};
13 use std::fs::File;
14 use std::io::BufReader;
15 use std::ops::Deref;
16 use std::sync::Arc;
17 use std::time::SystemTime;
18 use bitcoin::blockdata::constants::ChainHash;
19 use lightning::log_info;
20
21 use lightning::routing::gossip::{NetworkGraph, NodeId};
22 use lightning::util::logger::Logger;
23 use lightning::util::ser::{ReadableArgs, Writeable};
24 use tokio::sync::mpsc;
25 use tokio_postgres::{Client, NoTls};
26 use crate::config::SYMLINK_GRANULARITY_INTERVAL;
27 use crate::lookup::DeltaSet;
28
29 use crate::persistence::GossipPersister;
30 use crate::serialization::UpdateSerialization;
31 use crate::snapshot::Snapshotter;
32 use crate::types::RGSSLogger;
33
34 mod downloader;
35 mod tracking;
36 mod lookup;
37 mod persistence;
38 mod serialization;
39 mod snapshot;
40 mod config;
41 mod hex_utils;
42 mod verifier;
43
44 pub mod types;
45
46 #[cfg(test)]
47 mod tests;
48
49 /// The purpose of this prefix is to identify the serialization format, should other rapid gossip
50 /// sync formats arise in the future.
51 ///
52 /// The fourth byte is the protocol version in case our format gets updated.
53 const GOSSIP_PREFIX: [u8; 4] = [76, 68, 75, 1];
54
55 pub struct RapidSyncProcessor<L: Deref> where L::Target: Logger {
56         network_graph: Arc<NetworkGraph<L>>,
57         logger: L
58 }
59
60 pub struct SerializedResponse {
61         pub data: Vec<u8>,
62         pub message_count: u32,
63         pub announcement_count: u32,
64         pub update_count: u32,
65         pub update_count_full: u32,
66         pub update_count_incremental: u32,
67 }
68
69 impl<L: Deref + Clone + Send + Sync + 'static> RapidSyncProcessor<L> where L::Target: Logger {
70         pub fn new(logger: L) -> Self {
71                 let network = config::network();
72                 let network_graph = if let Ok(file) = File::open(&config::network_graph_cache_path()) {
73                         log_info!(logger, "Initializing from cached network graph…");
74                         let mut buffered_reader = BufReader::new(file);
75                         let network_graph_result = NetworkGraph::read(&mut buffered_reader, logger.clone());
76                         if let Ok(network_graph) = network_graph_result {
77                                 log_info!(logger, "Initialized from cached network graph!");
78                                 network_graph
79                         } else {
80                                 log_info!(logger, "Initialization from cached network graph failed: {}", network_graph_result.err().unwrap());
81                                 NetworkGraph::new(network, logger.clone())
82                         }
83                 } else {
84                         NetworkGraph::new(network, logger.clone())
85                 };
86                 let arc_network_graph = Arc::new(network_graph);
87                 Self {
88                         network_graph: arc_network_graph,
89                         logger
90                 }
91         }
92
93         pub async fn start_sync(&self) {
94                 log_info!(self.logger, "Starting Rapid Gossip Sync Server");
95                 log_info!(self.logger, "Snapshot interval: {} seconds", config::snapshot_generation_interval());
96
97                 // means to indicate sync completion status within this module
98                 let (sync_completion_sender, mut sync_completion_receiver) = mpsc::channel::<()>(1);
99
100                 if config::DOWNLOAD_NEW_GOSSIP {
101                         let (mut persister, persistence_sender) = GossipPersister::new(self.network_graph.clone(), self.logger.clone());
102
103                         log_info!(self.logger, "Starting gossip download");
104                         tokio::spawn(tracking::download_gossip(persistence_sender, sync_completion_sender,
105                                 Arc::clone(&self.network_graph), self.logger.clone()));
106                         log_info!(self.logger, "Starting gossip db persistence listener");
107                         tokio::spawn(async move { persister.persist_gossip().await; });
108                 } else {
109                         sync_completion_sender.send(()).await.unwrap();
110                 }
111
112                 let sync_completion = sync_completion_receiver.recv().await;
113                 if sync_completion.is_none() {
114                         panic!("Sync failed!");
115                 }
116                 log_info!(self.logger, "Initial sync complete!");
117
118                 // start the gossip snapshotting service
119                 Snapshotter::new(Arc::clone(&self.network_graph), self.logger.clone()).snapshot_gossip().await;
120         }
121 }
122
123 pub(crate) async fn connect_to_db() -> Client {
124         let connection_config = config::db_connection_config();
125         let (client, connection) = connection_config.connect(NoTls).await.unwrap();
126
127         tokio::spawn(async move {
128                 if let Err(e) = connection.await {
129                         panic!("connection error: {}", e);
130                 }
131         });
132
133         #[cfg(test)]
134         {
135                 let schema_name = tests::db_test_schema();
136                 let schema_creation_command = format!("CREATE SCHEMA IF NOT EXISTS {}", schema_name);
137                 client.execute(&schema_creation_command, &[]).await.unwrap();
138                 client.execute(&format!("SET search_path TO {}", schema_name), &[]).await.unwrap();
139         }
140
141         client.execute("set time zone UTC", &[]).await.unwrap();
142         client
143 }
144
145 /// This method generates a no-op blob that can be used as a delta where none exists.
146 ///
147 /// The primary purpose of this method is the scenario of a client retrieving and processing a
148 /// given snapshot, and then immediately retrieving the would-be next snapshot at the timestamp
149 /// indicated by the one that was just processed.
150 /// Previously, there would not be a new snapshot to be processed for that particular timestamp yet,
151 /// and the server would return a 404 error.
152 ///
153 /// In principle, this method could also be used to address another unfortunately all too common
154 /// pitfall: requesting snapshots from intermediate timestamps, i. e. those that are not multiples
155 /// of our granularity constant. Note that for that purpose, this method could be very dangerous,
156 /// because if consumed, the `timestamp` value calculated here will overwrite the timestamp that
157 /// the client previously had, which could result in duplicated or omitted gossip down the line.
158 fn serialize_empty_blob(current_timestamp: u64) -> Vec<u8> {
159         let mut blob = GOSSIP_PREFIX.to_vec();
160
161         let network = config::network();
162         let chain_hash = ChainHash::using_genesis_block(network);
163         chain_hash.write(&mut blob).unwrap();
164
165         let blob_timestamp = Snapshotter::<Arc<RGSSLogger>>::round_down_to_nearest_multiple(current_timestamp, SYMLINK_GRANULARITY_INTERVAL as u64) as u32;
166         blob_timestamp.write(&mut blob).unwrap();
167
168         0u32.write(&mut blob).unwrap(); // node count
169         0u32.write(&mut blob).unwrap(); // announcement count
170         0u32.write(&mut blob).unwrap(); // update count
171
172         blob
173 }
174
175 async fn serialize_delta<L: Deref + Clone>(network_graph: Arc<NetworkGraph<L>>, last_sync_timestamp: u32, snapshot_calculation_time: Option<SystemTime>, logger: L) -> SerializedResponse where L::Target: Logger {
176         let client = connect_to_db().await;
177
178         network_graph.remove_stale_channels_and_tracking();
179
180         let mut output: Vec<u8> = vec![];
181         let snapshot_interval = config::snapshot_generation_interval();
182
183         // set a flag if the chain hash is prepended
184         // chain hash only necessary if either channel announcements or non-incremental updates are present
185         // for announcement-free incremental-only updates, chain hash can be skipped
186
187         let mut node_id_set: HashSet<NodeId> = HashSet::new();
188         let mut node_id_indices: HashMap<NodeId, usize> = HashMap::new();
189         let mut node_ids: Vec<NodeId> = Vec::new();
190         let mut duplicate_node_ids: i32 = 0;
191
192         let mut get_node_id_index = |node_id: NodeId| {
193                 if node_id_set.insert(node_id) {
194                         node_ids.push(node_id);
195                         let index = node_ids.len() - 1;
196                         node_id_indices.insert(node_id, index);
197                         return index;
198                 }
199                 duplicate_node_ids += 1;
200                 node_id_indices[&node_id]
201         };
202
203         let mut delta_set = DeltaSet::new();
204         lookup::fetch_channel_announcements(&mut delta_set, network_graph, &client, last_sync_timestamp, snapshot_calculation_time, logger.clone()).await;
205         log_info!(logger, "announcement channel count: {}", delta_set.len());
206         lookup::fetch_channel_updates(&mut delta_set, &client, last_sync_timestamp, logger.clone()).await;
207         log_info!(logger, "update-fetched channel count: {}", delta_set.len());
208         lookup::filter_delta_set(&mut delta_set, logger.clone());
209         log_info!(logger, "update-filtered channel count: {}", delta_set.len());
210         let serialization_details = serialization::serialize_delta_set(delta_set, last_sync_timestamp);
211
212         // process announcements
213         // write the number of channel announcements to the output
214         let announcement_count = serialization_details.announcements.len() as u32;
215         announcement_count.write(&mut output).unwrap();
216         let mut previous_announcement_scid = 0;
217         for current_announcement in serialization_details.announcements {
218                 let id_index_1 = get_node_id_index(current_announcement.node_id_1);
219                 let id_index_2 = get_node_id_index(current_announcement.node_id_2);
220                 let mut stripped_announcement = serialization::serialize_stripped_channel_announcement(&current_announcement, id_index_1, id_index_2, previous_announcement_scid);
221                 output.append(&mut stripped_announcement);
222
223                 previous_announcement_scid = current_announcement.short_channel_id;
224         }
225
226         // process updates
227         let mut previous_update_scid = 0;
228         let update_count = serialization_details.updates.len() as u32;
229         update_count.write(&mut output).unwrap();
230
231         let default_update_values = serialization_details.full_update_defaults;
232         if update_count > 0 {
233                 default_update_values.cltv_expiry_delta.write(&mut output).unwrap();
234                 default_update_values.htlc_minimum_msat.write(&mut output).unwrap();
235                 default_update_values.fee_base_msat.write(&mut output).unwrap();
236                 default_update_values.fee_proportional_millionths.write(&mut output).unwrap();
237                 default_update_values.htlc_maximum_msat.write(&mut output).unwrap();
238         }
239
240         let mut update_count_full = 0;
241         let mut update_count_incremental = 0;
242         for current_update in serialization_details.updates {
243                 match &current_update {
244                         UpdateSerialization::Full(_) => {
245                                 update_count_full += 1;
246                         }
247                         UpdateSerialization::Incremental(_, _) | UpdateSerialization::Reminder(_, _) => {
248                                 update_count_incremental += 1;
249                         }
250                 };
251
252                 let mut stripped_update = serialization::serialize_stripped_channel_update(&current_update, &default_update_values, previous_update_scid);
253                 output.append(&mut stripped_update);
254
255                 previous_update_scid = current_update.scid();
256         }
257
258         // some stats
259         let message_count = announcement_count + update_count;
260
261         let mut prefixed_output = GOSSIP_PREFIX.to_vec();
262
263         // always write the chain hash
264         serialization_details.chain_hash.write(&mut prefixed_output).unwrap();
265         // always write the latest seen timestamp
266         let latest_seen_timestamp = serialization_details.latest_seen;
267         let overflow_seconds = latest_seen_timestamp % snapshot_interval;
268         let serialized_seen_timestamp = latest_seen_timestamp.saturating_sub(overflow_seconds);
269         serialized_seen_timestamp.write(&mut prefixed_output).unwrap();
270
271         let node_id_count = node_ids.len() as u32;
272         node_id_count.write(&mut prefixed_output).unwrap();
273
274         for current_node_id in node_ids {
275                 current_node_id.write(&mut prefixed_output).unwrap();
276         }
277
278         prefixed_output.append(&mut output);
279
280         log_info!(logger, "duplicated node ids: {}", duplicate_node_ids);
281         log_info!(logger, "latest seen timestamp: {:?}", serialization_details.latest_seen);
282
283         SerializedResponse {
284                 data: prefixed_output,
285                 message_count,
286                 announcement_count,
287                 update_count,
288                 update_count_full,
289                 update_count_incremental,
290         }
291 }