Drop spurious comments
[rapid-gossip-sync-server] / src / persistence.rs
1 use std::fs::OpenOptions;
2 use std::io::{BufWriter, Write};
3 use std::sync::Arc;
4 use std::time::{Duration, 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         network_graph: Arc<NetworkGraph<TestLogger>>,
16 }
17
18 impl GossipPersister {
19         pub fn new(network_graph: Arc<NetworkGraph<TestLogger>>) -> (Self, mpsc::Sender<GossipMessage>) {
20                 let (gossip_persistence_sender, gossip_persistence_receiver) =
21                         mpsc::channel::<GossipMessage>(100);
22                 (GossipPersister {
23                         gossip_persistence_receiver,
24                         network_graph
25                 }, gossip_persistence_sender)
26         }
27
28         pub(crate) async fn persist_gossip(&mut self) {
29                 let connection_config = config::db_connection_config();
30                 let (client, connection) =
31                         connection_config.connect(NoTls).await.unwrap();
32
33                 tokio::spawn(async move {
34                         if let Err(e) = connection.await {
35                                 panic!("connection error: {}", e);
36                         }
37                 });
38
39                 {
40                         // initialize the database
41                         let initialization = client
42                                 .execute(config::db_config_table_creation_query(), &[])
43                                 .await;
44                         if let Err(initialization_error) = initialization {
45                                 panic!("db init error: {}", initialization_error);
46                         }
47
48                         let initialization = client
49                                 .execute(
50                                         // TODO: figure out a way to fix the id value without Postgres complaining about
51                                         // its value not being default
52                                         "INSERT INTO config (id, db_schema) VALUES ($1, $2) ON CONFLICT (id) DO NOTHING",
53                                         &[&1, &config::SCHEMA_VERSION]
54                                 ).await;
55                         if let Err(initialization_error) = initialization {
56                                 panic!("db init error: {}", initialization_error);
57                         }
58
59                         let initialization = client
60                                 .execute(config::db_announcement_table_creation_query(), &[])
61                                 .await;
62                         if let Err(initialization_error) = initialization {
63                                 panic!("db init error: {}", initialization_error);
64                         }
65
66                         let initialization = client
67                                 .execute(
68                                         config::db_channel_update_table_creation_query(),
69                                         &[],
70                                 )
71                                 .await;
72                         if let Err(initialization_error) = initialization {
73                                 panic!("db init error: {}", initialization_error);
74                         }
75
76                         let initialization = client
77                                 .batch_execute(config::db_index_creation_query())
78                                 .await;
79                         if let Err(initialization_error) = initialization {
80                                 panic!("db init error: {}", initialization_error);
81                         }
82                 }
83
84                 // print log statement every minute
85                 let mut latest_persistence_log = Instant::now() - Duration::from_secs(60);
86                 let mut i = 0u32;
87                 let mut latest_graph_cache_time = Instant::now();
88                 // TODO: it would be nice to have some sort of timeout here so after 10 seconds of
89                 // inactivity, some sort of message could be broadcast signaling the activation of request
90                 // processing
91                 while let Some(gossip_message) = &self.gossip_persistence_receiver.recv().await {
92                         i += 1; // count the persisted gossip messages
93
94                         if latest_persistence_log.elapsed().as_secs() >= 60 {
95                                 println!("Persisting gossip message #{}", i);
96                                 latest_persistence_log = Instant::now();
97                         }
98
99                         // has it been ten minutes? Just cache it
100                         if latest_graph_cache_time.elapsed().as_secs() >= 600 {
101                                 self.persist_network_graph();
102                                 latest_graph_cache_time = Instant::now();
103                         }
104
105                         match &gossip_message {
106                                 GossipMessage::ChannelAnnouncement(announcement) => {
107                                         let scid = announcement.contents.short_channel_id;
108                                         let scid_hex = hex_utils::hex_str(&scid.to_be_bytes());
109                                         // scid is 8 bytes
110                                         // block height is the first three bytes
111                                         // to obtain block height, shift scid right by 5 bytes (40 bits)
112                                         let block_height = (scid >> 5 * 8) as i32;
113                                         let chain_hash = announcement.contents.chain_hash.as_ref();
114                                         let chain_hash_hex = hex_utils::hex_str(chain_hash);
115
116                                         // start with the type prefix, which is already known a priori
117                                         let mut announcement_signed = Vec::new();
118                                         announcement.write(&mut announcement_signed).unwrap();
119
120                                         let result = client
121                                                 .execute("INSERT INTO channel_announcements (\
122                                                         short_channel_id, \
123                                                         block_height, \
124                                                         chain_hash, \
125                                                         announcement_signed \
126                                                 ) VALUES ($1, $2, $3, $4) ON CONFLICT (short_channel_id) DO NOTHING", &[
127                                                         &scid_hex,
128                                                         &block_height,
129                                                         &chain_hash_hex,
130                                                         &announcement_signed
131                                                 ]).await;
132                                         if result.is_err() {
133                                                 panic!("error: {}", result.err().unwrap());
134                                         }
135                                 }
136                                 GossipMessage::ChannelUpdate(update) => {
137                                         let scid = update.contents.short_channel_id;
138                                         let scid_hex = hex_utils::hex_str(&scid.to_be_bytes());
139
140                                         let chain_hash = update.contents.chain_hash.as_ref();
141                                         let chain_hash_hex = hex_utils::hex_str(chain_hash);
142
143                                         let timestamp = update.contents.timestamp as i64;
144
145                                         let channel_flags = update.contents.flags as i32;
146                                         let direction = channel_flags & 1;
147                                         let disable = (channel_flags & 2) > 0;
148
149                                         let composite_index = format!("{}:{}:{}", scid_hex, timestamp, direction);
150
151                                         let cltv_expiry_delta = update.contents.cltv_expiry_delta as i32;
152                                         let htlc_minimum_msat = update.contents.htlc_minimum_msat as i64;
153                                         let fee_base_msat = update.contents.fee_base_msat as i32;
154                                         let fee_proportional_millionths =
155                                                 update.contents.fee_proportional_millionths as i32;
156                                         let htlc_maximum_msat = update.contents.htlc_maximum_msat as i64;
157
158                                         // start with the type prefix, which is already known a priori
159                                         let mut update_signed = Vec::new();
160                                         update.write(&mut update_signed).unwrap();
161
162                                         let result = client
163                                                 .execute("INSERT INTO channel_updates (\
164                                                         composite_index, \
165                                                         chain_hash, \
166                                                         short_channel_id, \
167                                                         timestamp, \
168                                                         channel_flags, \
169                                                         direction, \
170                                                         disable, \
171                                                         cltv_expiry_delta, \
172                                                         htlc_minimum_msat, \
173                                                         fee_base_msat, \
174                                                         fee_proportional_millionths, \
175                                                         htlc_maximum_msat, \
176                                                         blob_signed \
177                                                 ) VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13)  ON CONFLICT (composite_index) DO NOTHING", &[
178                                                         &composite_index,
179                                                         &chain_hash_hex,
180                                                         &scid_hex,
181                                                         &timestamp,
182                                                         &channel_flags,
183                                                         &direction,
184                                                         &disable,
185                                                         &cltv_expiry_delta,
186                                                         &htlc_minimum_msat,
187                                                         &fee_base_msat,
188                                                         &fee_proportional_millionths,
189                                                         &htlc_maximum_msat,
190                                                         &update_signed
191                                                 ]).await;
192                                         if result.is_err() {
193                                                 panic!("error: {}", result.err().unwrap());
194                                         }
195                                 }
196                         }
197                 }
198         }
199
200         fn persist_network_graph(&self) {
201                 println!("Caching network graph…");
202                 let cache_path = config::network_graph_cache_path();
203                 let file = OpenOptions::new()
204                         .create(true)
205                         .write(true)
206                         .truncate(true)
207                         .open(&cache_path)
208                         .unwrap();
209                 self.network_graph.remove_stale_channels();
210                 let mut writer = BufWriter::new(file);
211                 self.network_graph.write(&mut writer).unwrap();
212                 writer.flush().unwrap();
213                 println!("Cached network graph!");
214         }
215 }