Prune the network graph immediately prior to generating updates
[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_mut)]
8 #![deny(unused_variables)]
9 #![deny(unused_imports)]
10
11 extern crate core;
12
13 use std::collections::{HashMap, HashSet};
14 use std::fs::File;
15 use std::io::BufReader;
16 use std::sync::Arc;
17
18 use bitcoin::blockdata::constants::genesis_block;
19 use bitcoin::Network;
20 use bitcoin::secp256k1::PublicKey;
21 use lightning::routing::gossip::NetworkGraph;
22 use lightning::util::ser::{ReadableArgs, Writeable};
23 use tokio::sync::mpsc;
24 use crate::lookup::DeltaSet;
25
26 use crate::persistence::GossipPersister;
27 use crate::serialization::UpdateSerializationMechanism;
28 use crate::snapshot::Snapshotter;
29 use crate::types::TestLogger;
30
31 mod downloader;
32 mod types;
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 struct RapidSyncProcessor {
43         network_graph: Arc<NetworkGraph<TestLogger>>,
44 }
45
46 pub struct SerializedResponse {
47         pub data: Vec<u8>,
48         pub message_count: u32,
49         pub announcement_count: u32,
50         pub update_count: u32,
51         pub update_count_full: u32,
52         pub update_count_incremental: u32,
53 }
54
55 impl RapidSyncProcessor {
56         pub fn new() -> Self {
57                 let logger = TestLogger::new();
58                 let network_graph = if let Ok(file) = File::open(&config::network_graph_cache_path()) {
59                         println!("Initializing from cached network graph…");
60                         let mut buffered_reader = BufReader::new(file);
61                         let network_graph_result = NetworkGraph::read(&mut buffered_reader, logger);
62                         if let Ok(network_graph) = network_graph_result {
63                                 network_graph.remove_stale_channels_and_tracking();
64                                 println!("Initialized from cached network graph!");
65                                 network_graph
66                         } else {
67                                 println!("Initialization from cached network graph failed: {}", network_graph_result.err().unwrap());
68                                 NetworkGraph::new(genesis_block(Network::Bitcoin).header.block_hash(), logger)
69                         }
70                 } else {
71                         NetworkGraph::new(genesis_block(Network::Bitcoin).header.block_hash(), logger)
72                 };
73                 let arc_network_graph = Arc::new(network_graph);
74                 Self {
75                         network_graph: arc_network_graph,
76                 }
77         }
78
79         pub async fn start_sync(&self) {
80                 // means to indicate sync completion status within this module
81                 let (sync_completion_sender, mut sync_completion_receiver) = mpsc::channel::<()>(1);
82
83                 if config::DOWNLOAD_NEW_GOSSIP {
84                         let (mut persister, persistence_sender) = GossipPersister::new(Arc::clone(&self.network_graph));
85
86                         println!("Starting gossip download");
87                         tokio::spawn(tracking::download_gossip(persistence_sender, sync_completion_sender,
88                                 Arc::clone(&self.network_graph)));
89                         println!("Starting gossip db persistence listener");
90                         tokio::spawn(async move { persister.persist_gossip().await; });
91                 } else {
92                         sync_completion_sender.send(()).await.unwrap();
93                 }
94
95                 let sync_completion = sync_completion_receiver.recv().await;
96                 if sync_completion.is_none() {
97                         panic!("Sync failed!");
98                 }
99                 println!("Initial sync complete!");
100
101                 // start the gossip snapshotting service
102                 Snapshotter::new(Arc::clone(&self.network_graph)).snapshot_gossip().await;
103         }
104 }
105
106 async fn serialize_delta(network_graph: Arc<NetworkGraph<TestLogger>>, last_sync_timestamp: u32, consider_intermediate_updates: bool) -> SerializedResponse {
107         let (client, connection) = lookup::connect_to_db().await;
108
109         network_graph.remove_stale_channels_and_tracking();
110
111         tokio::spawn(async move {
112                 if let Err(e) = connection.await {
113                         panic!("connection error: {}", e);
114                 }
115         });
116
117         let mut output: Vec<u8> = vec![];
118
119         // set a flag if the chain hash is prepended
120         // chain hash only necessary if either channel announcements or non-incremental updates are present
121         // for announcement-free incremental-only updates, chain hash can be skipped
122
123         let mut node_id_set: HashSet<[u8; 33]> = HashSet::new();
124         let mut node_id_indices: HashMap<[u8; 33], usize> = HashMap::new();
125         let mut node_ids: Vec<PublicKey> = Vec::new();
126         let mut duplicate_node_ids: i32 = 0;
127
128         let mut get_node_id_index = |node_id: PublicKey| {
129                 let serialized_node_id = node_id.serialize();
130                 if node_id_set.insert(serialized_node_id) {
131                         node_ids.push(node_id);
132                         let index = node_ids.len() - 1;
133                         node_id_indices.insert(serialized_node_id, index);
134                         return index;
135                 }
136                 duplicate_node_ids += 1;
137                 node_id_indices[&serialized_node_id]
138         };
139
140         let mut delta_set = DeltaSet::new();
141         lookup::fetch_channel_announcements(&mut delta_set, network_graph, &client, last_sync_timestamp).await;
142         println!("announcement channel count: {}", delta_set.len());
143         lookup::fetch_channel_updates(&mut delta_set, &client, last_sync_timestamp, consider_intermediate_updates).await;
144         println!("update-fetched channel count: {}", delta_set.len());
145         lookup::filter_delta_set(&mut delta_set);
146         println!("update-filtered channel count: {}", delta_set.len());
147         let serialization_details = serialization::serialize_delta_set(delta_set, last_sync_timestamp);
148
149         // process announcements
150         // write the number of channel announcements to the output
151         let announcement_count = serialization_details.announcements.len() as u32;
152         announcement_count.write(&mut output).unwrap();
153         let mut previous_announcement_scid = 0;
154         for current_announcement in serialization_details.announcements {
155                 let id_index_1 = get_node_id_index(current_announcement.node_id_1);
156                 let id_index_2 = get_node_id_index(current_announcement.node_id_2);
157                 let mut stripped_announcement = serialization::serialize_stripped_channel_announcement(&current_announcement, id_index_1, id_index_2, previous_announcement_scid);
158                 output.append(&mut stripped_announcement);
159
160                 previous_announcement_scid = current_announcement.short_channel_id;
161         }
162
163         // process updates
164         let mut previous_update_scid = 0;
165         let update_count = serialization_details.updates.len() as u32;
166         update_count.write(&mut output).unwrap();
167
168         let default_update_values = serialization_details.full_update_defaults;
169         if update_count > 0 {
170                 default_update_values.cltv_expiry_delta.write(&mut output).unwrap();
171                 default_update_values.htlc_minimum_msat.write(&mut output).unwrap();
172                 default_update_values.fee_base_msat.write(&mut output).unwrap();
173                 default_update_values.fee_proportional_millionths.write(&mut output).unwrap();
174                 default_update_values.htlc_maximum_msat.write(&mut output).unwrap();
175         }
176
177         let mut update_count_full = 0;
178         let mut update_count_incremental = 0;
179         for current_update in serialization_details.updates {
180                 match &current_update.mechanism {
181                         UpdateSerializationMechanism::Full => {
182                                 update_count_full += 1;
183                         }
184                         UpdateSerializationMechanism::Incremental(_) => {
185                                 update_count_incremental += 1;
186                         }
187                 };
188
189                 let mut stripped_update = serialization::serialize_stripped_channel_update(&current_update, &default_update_values, previous_update_scid);
190                 output.append(&mut stripped_update);
191
192                 previous_update_scid = current_update.update.short_channel_id;
193         }
194
195         // some stats
196         let message_count = announcement_count + update_count;
197
198         let mut prefixed_output = vec![76, 68, 75, 1];
199
200         // always write the chain hash
201         serialization_details.chain_hash.write(&mut prefixed_output).unwrap();
202         // always write the latest seen timestamp
203         let latest_seen_timestamp = serialization_details.latest_seen;
204         let overflow_seconds = latest_seen_timestamp % config::SNAPSHOT_CALCULATION_INTERVAL;
205         let serialized_seen_timestamp = latest_seen_timestamp.saturating_sub(overflow_seconds);
206         serialized_seen_timestamp.write(&mut prefixed_output).unwrap();
207
208         let node_id_count = node_ids.len() as u32;
209         node_id_count.write(&mut prefixed_output).unwrap();
210
211         for current_node_id in node_ids {
212                 current_node_id.write(&mut prefixed_output).unwrap();
213         }
214
215         prefixed_output.append(&mut output);
216
217         println!("duplicated node ids: {}", duplicate_node_ids);
218         println!("latest seen timestamp: {:?}", serialization_details.latest_seen);
219
220         SerializedResponse {
221                 data: prefixed_output,
222                 message_count,
223                 announcement_count,
224                 update_count,
225                 update_count_full,
226                 update_count_incremental,
227         }
228 }