1 use std::fs::OpenOptions;
2 use std::io::{BufWriter, Write};
4 use std::time::{Duration, Instant};
5 use lightning::routing::gossip::NetworkGraph;
6 use lightning::util::logger::Logger;
7 use lightning::util::ser::Writeable;
9 use tokio_postgres::NoTls;
12 use crate::types::GossipMessage;
14 const POSTGRES_INSERT_TIMEOUT: Duration = Duration::from_secs(15);
16 pub(crate) struct GossipPersister<L: Logger> {
17 gossip_persistence_receiver: mpsc::Receiver<GossipMessage>,
18 network_graph: Arc<NetworkGraph<Arc<L>>>,
21 impl<L: Logger> GossipPersister<L> {
22 pub fn new(network_graph: Arc<NetworkGraph<Arc<L>>>) -> (Self, mpsc::Sender<GossipMessage>) {
23 let (gossip_persistence_sender, gossip_persistence_receiver) =
24 mpsc::channel::<GossipMessage>(100);
26 gossip_persistence_receiver,
28 }, gossip_persistence_sender)
31 pub(crate) async fn persist_gossip(&mut self) {
32 let connection_config = config::db_connection_config();
33 let (mut client, connection) =
34 connection_config.connect(NoTls).await.unwrap();
36 tokio::spawn(async move {
37 if let Err(e) = connection.await {
38 panic!("connection error: {}", e);
43 // initialize the database
44 let initialization = client
45 .execute(config::db_config_table_creation_query(), &[])
47 if let Err(initialization_error) = initialization {
48 panic!("db init error: {}", initialization_error);
51 let cur_schema = client.query("SELECT db_schema FROM config WHERE id = $1", &[&1]).await.unwrap();
52 if !cur_schema.is_empty() {
53 config::upgrade_db(cur_schema[0].get(0), &mut client).await;
56 let initialization = client
58 // TODO: figure out a way to fix the id value without Postgres complaining about
59 // its value not being default
60 "INSERT INTO config (id, db_schema) VALUES ($1, $2) ON CONFLICT (id) DO NOTHING",
61 &[&1, &config::SCHEMA_VERSION]
63 if let Err(initialization_error) = initialization {
64 panic!("db init error: {}", initialization_error);
67 let initialization = client
68 .execute(config::db_announcement_table_creation_query(), &[])
70 if let Err(initialization_error) = initialization {
71 panic!("db init error: {}", initialization_error);
74 let initialization = client
76 config::db_channel_update_table_creation_query(),
80 if let Err(initialization_error) = initialization {
81 panic!("db init error: {}", initialization_error);
84 let initialization = client
85 .batch_execute(config::db_index_creation_query())
87 if let Err(initialization_error) = initialization {
88 panic!("db init error: {}", initialization_error);
92 // print log statement every minute
93 let mut latest_persistence_log = Instant::now() - Duration::from_secs(60);
95 let mut latest_graph_cache_time = Instant::now();
96 // TODO: it would be nice to have some sort of timeout here so after 10 seconds of
97 // inactivity, some sort of message could be broadcast signaling the activation of request
99 while let Some(gossip_message) = &self.gossip_persistence_receiver.recv().await {
100 i += 1; // count the persisted gossip messages
102 if latest_persistence_log.elapsed().as_secs() >= 60 {
103 println!("Persisting gossip message #{}", i);
104 latest_persistence_log = Instant::now();
107 // has it been ten minutes? Just cache it
108 if latest_graph_cache_time.elapsed().as_secs() >= 600 {
109 self.persist_network_graph();
110 latest_graph_cache_time = Instant::now();
113 match &gossip_message {
114 GossipMessage::ChannelAnnouncement(announcement) => {
115 let scid = announcement.contents.short_channel_id as i64;
117 // start with the type prefix, which is already known a priori
118 let mut announcement_signed = Vec::new();
119 announcement.write(&mut announcement_signed).unwrap();
121 tokio::time::timeout(POSTGRES_INSERT_TIMEOUT, client
122 .execute("INSERT INTO channel_announcements (\
124 announcement_signed \
125 ) VALUES ($1, $2) ON CONFLICT (short_channel_id) DO NOTHING", &[
128 ])).await.unwrap().unwrap();
130 GossipMessage::ChannelUpdate(update) => {
131 let scid = update.contents.short_channel_id as i64;
133 let timestamp = update.contents.timestamp as i64;
135 let direction = (update.contents.flags & 1) == 1;
136 let disable = (update.contents.flags & 2) > 0;
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;
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();
149 tokio::time::timeout(POSTGRES_INSERT_TIMEOUT, client
150 .execute("INSERT INTO channel_updates (\
159 fee_proportional_millionths, \
162 ) VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11) ON CONFLICT DO NOTHING", &[
165 &(update.contents.flags as i16),
171 &fee_proportional_millionths,
174 ])).await.unwrap().unwrap();
180 fn persist_network_graph(&self) {
181 println!("Caching network graph…");
182 let cache_path = config::network_graph_cache_path();
183 let file = OpenOptions::new()
189 self.network_graph.remove_stale_channels_and_tracking();
190 let mut writer = BufWriter::new(file);
191 self.network_graph.write(&mut writer).unwrap();
192 writer.flush().unwrap();
193 println!("Cached network graph!");