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