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