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