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)]
12 use std::collections::{HashMap, HashSet};
14 use std::io::BufReader;
17 use lightning::routing::gossip::{NetworkGraph, NodeId};
18 use lightning::util::ser::{ReadableArgs, Writeable};
19 use tokio::sync::mpsc;
20 use crate::lookup::DeltaSet;
22 use crate::persistence::GossipPersister;
23 use crate::serialization::UpdateSerialization;
24 use crate::snapshot::Snapshotter;
25 use crate::types::TestLogger;
38 /// The purpose of this prefix is to identify the serialization format, should other rapid gossip
39 /// sync formats arise in the future.
41 /// The fourth byte is the protocol version in case our format gets updated.
42 const GOSSIP_PREFIX: [u8; 4] = [76, 68, 75, 1];
44 pub struct RapidSyncProcessor {
45 network_graph: Arc<NetworkGraph<TestLogger>>,
48 pub struct SerializedResponse {
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,
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!");
69 println!("Initialization from cached network graph failed: {}", network_graph_result.err().unwrap());
70 NetworkGraph::new(network, logger)
73 NetworkGraph::new(network, logger)
75 let arc_network_graph = Arc::new(network_graph);
77 network_graph: arc_network_graph,
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);
85 if config::DOWNLOAD_NEW_GOSSIP {
86 let (mut persister, persistence_sender) = GossipPersister::new(Arc::clone(&self.network_graph));
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; });
94 sync_completion_sender.send(()).await.unwrap();
97 let sync_completion = sync_completion_receiver.recv().await;
98 if sync_completion.is_none() {
99 panic!("Sync failed!");
101 println!("Initial sync complete!");
103 // start the gossip snapshotting service
104 Snapshotter::new(Arc::clone(&self.network_graph)).snapshot_gossip().await;
108 /// This method generates a no-op blob that can be used as a delta where none exists.
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.
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();
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();
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();
132 0u32.write(&mut blob).unwrap(); // node count
133 0u32.write(&mut blob).unwrap(); // announcement count
134 0u32.write(&mut blob).unwrap(); // update count
139 async fn serialize_delta(network_graph: Arc<NetworkGraph<TestLogger>>, last_sync_timestamp: u32) -> SerializedResponse {
140 let (client, connection) = lookup::connect_to_db().await;
142 network_graph.remove_stale_channels_and_tracking();
144 tokio::spawn(async move {
145 if let Err(e) = connection.await {
146 panic!("connection error: {}", e);
150 let mut output: Vec<u8> = vec![];
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
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;
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);
168 duplicate_node_ids += 1;
169 node_id_indices[&node_id]
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);
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(¤t_announcement, id_index_1, id_index_2, previous_announcement_scid);
190 output.append(&mut stripped_announcement);
192 previous_announcement_scid = current_announcement.short_channel_id;
196 let mut previous_update_scid = 0;
197 let update_count = serialization_details.updates.len() as u32;
198 update_count.write(&mut output).unwrap();
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();
209 let mut update_count_full = 0;
210 let mut update_count_incremental = 0;
211 for current_update in serialization_details.updates {
212 match ¤t_update {
213 UpdateSerialization::Full(_) => {
214 update_count_full += 1;
216 UpdateSerialization::Incremental(_, _) | UpdateSerialization::Reminder(_, _) => {
217 update_count_incremental += 1;
221 let mut stripped_update = serialization::serialize_stripped_channel_update(¤t_update, &default_update_values, previous_update_scid);
222 output.append(&mut stripped_update);
224 previous_update_scid = current_update.scid();
228 let message_count = announcement_count + update_count;
230 let mut prefixed_output = GOSSIP_PREFIX.to_vec();
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();
240 let node_id_count = node_ids.len() as u32;
241 node_id_count.write(&mut prefixed_output).unwrap();
243 for current_node_id in node_ids {
244 current_node_id.write(&mut prefixed_output).unwrap();
247 prefixed_output.append(&mut output);
249 println!("duplicated node ids: {}", duplicate_node_ids);
250 println!("latest seen timestamp: {:?}", serialization_details.latest_seen);
253 data: prefixed_output,
258 update_count_incremental,