1 use std::fs::OpenOptions;
2 use std::io::BufWriter;
4 use std::time::Instant;
5 use lightning::routing::gossip::NetworkGraph;
6 use lightning::util::ser::Writeable;
8 use tokio_postgres::NoTls;
10 use crate::{config, hex_utils, TestLogger};
11 use crate::types::GossipMessage;
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>>>,
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);
24 gossip_persistence_receiver,
25 server_sync_completion_sender,
27 }, gossip_persistence_sender)
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();
35 tokio::spawn(async move {
36 if let Err(e) = connection.await {
37 panic!("connection error: {}", e);
42 // initialize the database
43 let initialization = client
44 .execute(config::db_config_table_creation_query(), &[])
46 if let Err(initialization_error) = initialization {
47 panic!("db init error: {}", initialization_error);
50 let initialization = client
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]
57 if let Err(initialization_error) = initialization {
58 panic!("db init error: {}", initialization_error);
61 let initialization = client
62 .execute(config::db_announcement_table_creation_query(), &[])
64 if let Err(initialization_error) = initialization {
65 panic!("db init error: {}", initialization_error);
68 let initialization = client
70 config::db_channel_update_table_creation_query(),
74 if let Err(initialization_error) = initialization {
75 panic!("db init error: {}", initialization_error);
78 let initialization = client
79 .batch_execute(config::db_index_creation_query())
81 if let Err(initialization_error) = initialization {
82 panic!("db init error: {}", initialization_error);
86 // print log statement every 10,000 messages
87 let mut persistence_log_threshold = 10000;
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
94 while let Some(gossip_message) = &self.gossip_persistence_receiver.recv().await {
95 i += 1; // count the persisted gossip messages
97 if i == 1 || i % persistence_log_threshold == 0 {
98 println!("Persisting gossip message #{}", i);
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());
108 // initialize graph cache timer
109 latest_graph_cache_time = Some(Instant::now());
112 match &gossip_message {
113 GossipMessage::InitialSyncComplete => {
114 // signal to the server that it may now serve dynamic responses and calculate
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.");
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;
136 println!("Network graph has been cached too recently.");
138 latest_graph_cache_time = Some(Instant::now());
139 self.persist_network_graph();
142 GossipMessage::ChannelAnnouncement(announcement) => {
144 let scid = announcement.contents.short_channel_id;
145 let scid_hex = hex_utils::hex_str(&scid.to_be_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);
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();
158 .execute("INSERT INTO channel_announcements (\
162 announcement_signed \
163 ) VALUES ($1, $2, $3, $4) ON CONFLICT (short_channel_id) DO NOTHING", &[
170 panic!("error: {}", result.err().unwrap());
173 GossipMessage::ChannelUpdate(update) => {
174 let scid = update.contents.short_channel_id;
175 let scid_hex = hex_utils::hex_str(&scid.to_be_bytes());
177 let chain_hash = update.contents.chain_hash.as_ref();
178 let chain_hash_hex = hex_utils::hex_str(chain_hash);
180 let timestamp = update.contents.timestamp as i64;
182 let channel_flags = update.contents.flags as i32;
183 let direction = channel_flags & 1;
184 let disable = (channel_flags & 2) > 0;
186 let composite_index = format!("{}:{}:{}", scid_hex, timestamp, direction);
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;
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();
200 .execute("INSERT INTO channel_updates (\
211 fee_proportional_millionths, \
214 ) VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13) ON CONFLICT (composite_index) DO NOTHING", &[
225 &fee_proportional_millionths,
230 panic!("error: {}", result.err().unwrap());
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()
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!");