Clean up the flow and variables in lib.rs and main.rs
[rapid-gossip-sync-server] / src / persistence.rs
1 use std::fs::OpenOptions;
2 use std::io::BufWriter;
3 use std::sync::Arc;
4 use std::time::Instant;
5 use lightning::routing::gossip::NetworkGraph;
6 use lightning::util::ser::Writeable;
7 use tokio::sync::mpsc;
8 use tokio_postgres::NoTls;
9
10 use crate::{config, hex_utils, TestLogger};
11 use crate::types::GossipMessage;
12
13 pub(crate) struct GossipPersister {
14         gossip_persistence_receiver: mpsc::Receiver<GossipMessage>,
15         server_sync_completion_sender: mpsc::Sender<()>,
16         network_graph: Arc<NetworkGraph<Arc<TestLogger>>>,
17 }
18
19 impl GossipPersister {
20         pub fn new(server_sync_completion_sender: mpsc::Sender<()>, network_graph: Arc<NetworkGraph<Arc<TestLogger>>>) -> (Self, mpsc::Sender<GossipMessage>) {
21                 let (gossip_persistence_sender, gossip_persistence_receiver) =
22                         mpsc::channel::<GossipMessage>(100);
23                 (GossipPersister {
24                         gossip_persistence_receiver,
25                         server_sync_completion_sender,
26                         network_graph
27                 }, gossip_persistence_sender)
28         }
29
30         pub(crate) async fn persist_gossip(&mut self) {
31                 let connection_config = config::db_connection_config();
32                 let (client, connection) =
33                         connection_config.connect(NoTls).await.unwrap();
34
35                 tokio::spawn(async move {
36                         if let Err(e) = connection.await {
37                                 panic!("connection error: {}", e);
38                         }
39                 });
40
41                 {
42                         // initialize the database
43                         let initialization = client
44                                 .execute(config::db_config_table_creation_query(), &[])
45                                 .await;
46                         if let Err(initialization_error) = initialization {
47                                 panic!("db init error: {}", initialization_error);
48                         }
49
50                         let initialization = client
51                                 .execute(
52                                         // TODO: figure out a way to fix the id value without Postgres complaining about
53                                         // its value not being default
54                                         "INSERT INTO config (id, db_schema) VALUES ($1, $2) ON CONFLICT (id) DO NOTHING",
55                                         &[&1, &config::SCHEMA_VERSION]
56                                 ).await;
57                         if let Err(initialization_error) = initialization {
58                                 panic!("db init error: {}", initialization_error);
59                         }
60
61                         let initialization = client
62                                 .execute(config::db_announcement_table_creation_query(), &[])
63                                 .await;
64                         if let Err(initialization_error) = initialization {
65                                 panic!("db init error: {}", initialization_error);
66                         }
67
68                         let initialization = client
69                                 .execute(
70                                         config::db_channel_update_table_creation_query(),
71                                         &[],
72                                 )
73                                 .await;
74                         if let Err(initialization_error) = initialization {
75                                 panic!("db init error: {}", initialization_error);
76                         }
77
78                         let initialization = client
79                                 .batch_execute(config::db_index_creation_query())
80                                 .await;
81                         if let Err(initialization_error) = initialization {
82                                 panic!("db init error: {}", initialization_error);
83                         }
84                 }
85
86                 // print log statement every 10,000 messages
87                 let mut persistence_log_threshold = 10000;
88                 let mut i = 0u32;
89                 let mut server_sync_completion_sent = false;
90                 let mut latest_graph_cache_time: Option<Instant> = None;
91                 // TODO: it would be nice to have some sort of timeout here so after 10 seconds of
92                 // inactivity, some sort of message could be broadcast signaling the activation of request
93                 // processing
94                 while let Some(gossip_message) = &self.gossip_persistence_receiver.recv().await {
95                         i += 1; // count the persisted gossip messages
96
97                         if i == 1 || i % persistence_log_threshold == 0 {
98                                 println!("Persisting gossip message #{}", i);
99                         }
100
101                         if let Some(last_cache_time) = latest_graph_cache_time {
102                                 // has it been ten minutes? Just cache it
103                                 if last_cache_time.elapsed().as_secs() >= 600 {
104                                         self.persist_network_graph();
105                                         latest_graph_cache_time = Some(Instant::now());
106                                 }
107                         } else {
108                                 // initialize graph cache timer
109                                 latest_graph_cache_time = Some(Instant::now());
110                         }
111
112                         match &gossip_message {
113                                 GossipMessage::InitialSyncComplete => {
114                                         // signal to the server that it may now serve dynamic responses and calculate
115                                         // snapshots
116                                         // we take this detour through the persister to ensure that all previous
117                                         // messages have already been persisted to the database
118                                         println!("Persister caught up with gossip!");
119                                         i -= 1; // this wasn't an actual gossip message that needed persisting
120                                         persistence_log_threshold = 50;
121                                         if !server_sync_completion_sent {
122                                                 server_sync_completion_sent = true;
123                                                 self.server_sync_completion_sender.send(()).await.unwrap();
124                                                 println!("Server has been notified of persistence completion.");
125                                         }
126
127                                         // now, cache the persisted network graph
128                                         // also persist the network graph here
129                                         let mut too_soon = false;
130                                         if let Some(latest_graph_cache_time) = latest_graph_cache_time {
131                                                 let time_since_last_cached = latest_graph_cache_time.elapsed().as_secs();
132                                                 // don't cache more frequently than every 2 minutes
133                                                 too_soon = time_since_last_cached < 120;
134                                         }
135                                         if too_soon {
136                                                 println!("Network graph has been cached too recently.");
137                                         }else {
138                                                 latest_graph_cache_time = Some(Instant::now());
139                                                 self.persist_network_graph();
140                                         }
141                                 }
142                                 GossipMessage::ChannelAnnouncement(announcement) => {
143
144                                         let scid = announcement.contents.short_channel_id;
145                                         let scid_hex = hex_utils::hex_str(&scid.to_be_bytes());
146                                         // scid is 8 bytes
147                                         // block height is the first three bytes
148                                         // to obtain block height, shift scid right by 5 bytes (40 bits)
149                                         let block_height = (scid >> 5 * 8) as i32;
150                                         let chain_hash = announcement.contents.chain_hash.as_ref();
151                                         let chain_hash_hex = hex_utils::hex_str(chain_hash);
152
153                                         // start with the type prefix, which is already known a priori
154                                         let mut announcement_signed = Vec::new(); // vec![1, 0];
155                                         announcement.write(&mut announcement_signed).unwrap();
156
157                                         let result = client
158                                                 .execute("INSERT INTO channel_announcements (\
159                                                         short_channel_id, \
160                                                         block_height, \
161                                                         chain_hash, \
162                                                         announcement_signed \
163                                                 ) VALUES ($1, $2, $3, $4) ON CONFLICT (short_channel_id) DO NOTHING", &[
164                                                         &scid_hex,
165                                                         &block_height,
166                                                         &chain_hash_hex,
167                                                         &announcement_signed
168                                                 ]).await;
169                                         if result.is_err() {
170                                                 panic!("error: {}", result.err().unwrap());
171                                         }
172                                 }
173                                 GossipMessage::ChannelUpdate(update) => {
174                                         let scid = update.contents.short_channel_id;
175                                         let scid_hex = hex_utils::hex_str(&scid.to_be_bytes());
176
177                                         let chain_hash = update.contents.chain_hash.as_ref();
178                                         let chain_hash_hex = hex_utils::hex_str(chain_hash);
179
180                                         let timestamp = update.contents.timestamp as i64;
181
182                                         let channel_flags = update.contents.flags as i32;
183                                         let direction = channel_flags & 1;
184                                         let disable = (channel_flags & 2) > 0;
185
186                                         let composite_index = format!("{}:{}:{}", scid_hex, timestamp, direction);
187
188                                         let cltv_expiry_delta = update.contents.cltv_expiry_delta as i32;
189                                         let htlc_minimum_msat = update.contents.htlc_minimum_msat as i64;
190                                         let fee_base_msat = update.contents.fee_base_msat as i32;
191                                         let fee_proportional_millionths =
192                                                 update.contents.fee_proportional_millionths as i32;
193                                         let htlc_maximum_msat = update.contents.htlc_maximum_msat as i64;
194
195                                         // start with the type prefix, which is already known a priori
196                                         let mut update_signed = Vec::new(); // vec![1, 2];
197                                         update.write(&mut update_signed).unwrap();
198
199                                         let result = client
200                                                 .execute("INSERT INTO channel_updates (\
201                                                         composite_index, \
202                                                         chain_hash, \
203                                                         short_channel_id, \
204                                                         timestamp, \
205                                                         channel_flags, \
206                                                         direction, \
207                                                         disable, \
208                                                         cltv_expiry_delta, \
209                                                         htlc_minimum_msat, \
210                                                         fee_base_msat, \
211                                                         fee_proportional_millionths, \
212                                                         htlc_maximum_msat, \
213                                                         blob_signed \
214                                                 ) VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13)  ON CONFLICT (composite_index) DO NOTHING", &[
215                                                         &composite_index,
216                                                         &chain_hash_hex,
217                                                         &scid_hex,
218                                                         &timestamp,
219                                                         &channel_flags,
220                                                         &direction,
221                                                         &disable,
222                                                         &cltv_expiry_delta,
223                                                         &htlc_minimum_msat,
224                                                         &fee_base_msat,
225                                                         &fee_proportional_millionths,
226                                                         &htlc_maximum_msat,
227                                                         &update_signed
228                                                 ]).await;
229                                         if result.is_err() {
230                                                 panic!("error: {}", result.err().unwrap());
231                                         }
232                                 }
233                         }
234                 }
235         }
236
237         fn persist_network_graph(&self) {
238                 println!("Caching network graph…");
239                 let cache_path = config::network_graph_cache_path();
240                 let file = OpenOptions::new()
241                         .create(true)
242                         .write(true)
243                         .truncate(true)
244                         .open(&cache_path)
245                         .unwrap();
246                 self.network_graph.remove_stale_channels();
247                 let mut writer = BufWriter::new(file);
248                 self.network_graph.write(&mut writer).unwrap();
249                 println!("Cached network graph!");
250         }
251 }