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::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 network_graph: Arc<NetworkGraph<TestLogger>>,
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);
23 gossip_persistence_receiver,
25 }, gossip_persistence_sender)
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();
33 tokio::spawn(async move {
34 if let Err(e) = connection.await {
35 panic!("connection error: {}", e);
40 // initialize the database
41 let initialization = client
42 .execute(config::db_config_table_creation_query(), &[])
44 if let Err(initialization_error) = initialization {
45 panic!("db init error: {}", initialization_error);
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;
53 let initialization = client
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]
60 if let Err(initialization_error) = initialization {
61 panic!("db init error: {}", initialization_error);
64 let initialization = client
65 .execute(config::db_announcement_table_creation_query(), &[])
67 if let Err(initialization_error) = initialization {
68 panic!("db init error: {}", initialization_error);
71 let initialization = client
73 config::db_channel_update_table_creation_query(),
77 if let Err(initialization_error) = initialization {
78 panic!("db init error: {}", initialization_error);
81 let initialization = client
82 .batch_execute(config::db_index_creation_query())
84 if let Err(initialization_error) = initialization {
85 panic!("db init error: {}", initialization_error);
89 // print log statement every minute
90 let mut latest_persistence_log = Instant::now() - Duration::from_secs(60);
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
96 while let Some(gossip_message) = &self.gossip_persistence_receiver.recv().await {
97 i += 1; // count the persisted gossip messages
99 if latest_persistence_log.elapsed().as_secs() >= 60 {
100 println!("Persisting gossip message #{}", i);
101 latest_persistence_log = Instant::now();
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();
110 match &gossip_message {
111 GossipMessage::ChannelAnnouncement(announcement) => {
112 let scid = announcement.contents.short_channel_id as i64;
114 // block height is the first three bytes
115 // to obtain block height, shift scid right by 5 bytes (40 bits)
116 let block_height = (scid >> 5 * 8) as i32;
118 // start with the type prefix, which is already known a priori
119 let mut announcement_signed = Vec::new();
120 announcement.write(&mut announcement_signed).unwrap();
123 .execute("INSERT INTO channel_announcements (\
126 announcement_signed \
127 ) VALUES ($1, $2, $3) ON CONFLICT (short_channel_id) DO NOTHING", &[
133 panic!("error: {}", result.err().unwrap());
136 GossipMessage::ChannelUpdate(update) => {
137 let scid = update.contents.short_channel_id as i64;
139 let timestamp = update.contents.timestamp as i64;
141 let direction = (update.contents.flags & 1) == 1;
142 let disable = (update.contents.flags & 2) > 0;
144 let composite_index = hex_utils::to_composite_index(scid, timestamp, direction);
146 let cltv_expiry_delta = update.contents.cltv_expiry_delta as i32;
147 let htlc_minimum_msat = update.contents.htlc_minimum_msat as i64;
148 let fee_base_msat = update.contents.fee_base_msat as i32;
149 let fee_proportional_millionths =
150 update.contents.fee_proportional_millionths as i32;
151 let htlc_maximum_msat = update.contents.htlc_maximum_msat as i64;
153 // start with the type prefix, which is already known a priori
154 let mut update_signed = Vec::new();
155 update.write(&mut update_signed).unwrap();
158 .execute("INSERT INTO channel_updates (\
168 fee_proportional_millionths, \
171 ) VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12) ON CONFLICT (composite_index) DO NOTHING", &[
175 &(update.contents.flags as i32),
181 &fee_proportional_millionths,
186 panic!("error: {}", result.err().unwrap());
193 fn persist_network_graph(&self) {
194 println!("Caching network graph…");
195 let cache_path = config::network_graph_cache_path();
196 let file = OpenOptions::new()
202 self.network_graph.remove_stale_channels();
203 let mut writer = BufWriter::new(file);
204 self.network_graph.write(&mut writer).unwrap();
205 writer.flush().unwrap();
206 println!("Cached network graph!");