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