99fab327c932c101157f2eec3ee21fe1aeed87e8
[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, 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 (mut 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 cur_schema = client.query("SELECT db_schema FROM config WHERE id = $1", &[&1]).await.unwrap();
49                         if !cur_schema.is_empty() {
50                                 config::upgrade_db(cur_schema[0].get(0), &mut client).await;
51                         }
52
53                         let initialization = client
54                                 .execute(
55                                         // TODO: figure out a way to fix the id value without Postgres complaining about
56                                         // its value not being default
57                                         "INSERT INTO config (id, db_schema) VALUES ($1, $2) ON CONFLICT (id) DO NOTHING",
58                                         &[&1, &config::SCHEMA_VERSION]
59                                 ).await;
60                         if let Err(initialization_error) = initialization {
61                                 panic!("db init error: {}", initialization_error);
62                         }
63
64                         let initialization = client
65                                 .execute(config::db_announcement_table_creation_query(), &[])
66                                 .await;
67                         if let Err(initialization_error) = initialization {
68                                 panic!("db init error: {}", initialization_error);
69                         }
70
71                         let initialization = client
72                                 .execute(
73                                         config::db_channel_update_table_creation_query(),
74                                         &[],
75                                 )
76                                 .await;
77                         if let Err(initialization_error) = initialization {
78                                 panic!("db init error: {}", initialization_error);
79                         }
80
81                         let initialization = client
82                                 .batch_execute(config::db_index_creation_query())
83                                 .await;
84                         if let Err(initialization_error) = initialization {
85                                 panic!("db init error: {}", initialization_error);
86                         }
87                 }
88
89                 // print log statement every minute
90                 let mut latest_persistence_log = Instant::now() - Duration::from_secs(60);
91                 let mut i = 0u32;
92                 let mut latest_graph_cache_time = Instant::now();
93                 // TODO: it would be nice to have some sort of timeout here so after 10 seconds of
94                 // inactivity, some sort of message could be broadcast signaling the activation of request
95                 // processing
96                 while let Some(gossip_message) = &self.gossip_persistence_receiver.recv().await {
97                         i += 1; // count the persisted gossip messages
98
99                         if latest_persistence_log.elapsed().as_secs() >= 60 {
100                                 println!("Persisting gossip message #{}", i);
101                                 latest_persistence_log = Instant::now();
102                         }
103
104                         // has it been ten minutes? Just cache it
105                         if latest_graph_cache_time.elapsed().as_secs() >= 600 {
106                                 self.persist_network_graph();
107                                 latest_graph_cache_time = Instant::now();
108                         }
109
110                         match &gossip_message {
111                                 GossipMessage::ChannelAnnouncement(announcement) => {
112                                         let scid = announcement.contents.short_channel_id as i64;
113
114                                         // start with the type prefix, which is already known a priori
115                                         let mut announcement_signed = Vec::new();
116                                         announcement.write(&mut announcement_signed).unwrap();
117
118                                         let result = client
119                                                 .execute("INSERT INTO channel_announcements (\
120                                                         short_channel_id, \
121                                                         announcement_signed \
122                                                 ) VALUES ($1, $2) ON CONFLICT (short_channel_id) DO NOTHING", &[
123                                                         &scid,
124                                                         &announcement_signed
125                                                 ]).await;
126                                         if result.is_err() {
127                                                 panic!("error: {}", result.err().unwrap());
128                                         }
129                                 }
130                                 GossipMessage::ChannelUpdate(update) => {
131                                         let scid = update.contents.short_channel_id as i64;
132
133                                         let timestamp = update.contents.timestamp as i64;
134
135                                         let direction = (update.contents.flags & 1) == 1;
136                                         let disable = (update.contents.flags & 2) > 0;
137
138                                         let cltv_expiry_delta = update.contents.cltv_expiry_delta as i32;
139                                         let htlc_minimum_msat = update.contents.htlc_minimum_msat as i64;
140                                         let fee_base_msat = update.contents.fee_base_msat as i32;
141                                         let fee_proportional_millionths =
142                                                 update.contents.fee_proportional_millionths as i32;
143                                         let htlc_maximum_msat = update.contents.htlc_maximum_msat as i64;
144
145                                         // start with the type prefix, which is already known a priori
146                                         let mut update_signed = Vec::new();
147                                         update.write(&mut update_signed).unwrap();
148
149                                         let result = client
150                                                 .execute("INSERT INTO channel_updates (\
151                                                         short_channel_id, \
152                                                         timestamp, \
153                                                         channel_flags, \
154                                                         direction, \
155                                                         disable, \
156                                                         cltv_expiry_delta, \
157                                                         htlc_minimum_msat, \
158                                                         fee_base_msat, \
159                                                         fee_proportional_millionths, \
160                                                         htlc_maximum_msat, \
161                                                         blob_signed \
162                                                 ) VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11)  ON CONFLICT DO NOTHING", &[
163                                                         &scid,
164                                                         &timestamp,
165                                                         &(update.contents.flags as i16),
166                                                         &direction,
167                                                         &disable,
168                                                         &cltv_expiry_delta,
169                                                         &htlc_minimum_msat,
170                                                         &fee_base_msat,
171                                                         &fee_proportional_millionths,
172                                                         &htlc_maximum_msat,
173                                                         &update_signed
174                                                 ]).await;
175                                         if result.is_err() {
176                                                 panic!("error: {}", result.err().unwrap());
177                                         }
178                                 }
179                         }
180                 }
181         }
182
183         fn persist_network_graph(&self) {
184                 println!("Caching network graph…");
185                 let cache_path = config::network_graph_cache_path();
186                 let file = OpenOptions::new()
187                         .create(true)
188                         .write(true)
189                         .truncate(true)
190                         .open(&cache_path)
191                         .unwrap();
192                 self.network_graph.remove_stale_channels_and_tracking();
193                 let mut writer = BufWriter::new(file);
194                 self.network_graph.write(&mut writer).unwrap();
195                 writer.flush().unwrap();
196                 println!("Cached network graph!");
197         }
198 }