Let postgres filter timestamps rather than doing it in Rust
[rapid-gossip-sync-server] / src / config.rs
1 use crate::hex_utils;
2
3 use std::convert::TryInto;
4 use std::env;
5 use std::io::Cursor;
6 use std::net::{SocketAddr, ToSocketAddrs};
7 use std::time::Duration;
8
9 use bitcoin::Network;
10 use bitcoin::hashes::hex::FromHex;
11 use bitcoin::secp256k1::PublicKey;
12 use futures::stream::{FuturesUnordered, StreamExt};
13 use lightning::ln::msgs::ChannelAnnouncement;
14 use lightning::util::ser::Readable;
15 use lightning_block_sync::http::HttpEndpoint;
16 use tokio_postgres::Config;
17
18 pub(crate) const SCHEMA_VERSION: i32 = 8;
19 pub(crate) const SNAPSHOT_CALCULATION_INTERVAL: u32 = 3600 * 24; // every 24 hours, in seconds
20 /// If the last update in either direction was more than six days ago, we send a reminder
21 /// That reminder may be either in the form of a channel announcement, or in the form of empty
22 /// updates in both directions.
23 pub(crate) const CHANNEL_REMINDER_AGE: Duration = Duration::from_secs(6 * 24 * 60 * 60);
24 pub(crate) const DOWNLOAD_NEW_GOSSIP: bool = true;
25
26 pub(crate) fn network() -> Network {
27         let network = env::var("RAPID_GOSSIP_SYNC_SERVER_NETWORK").unwrap_or("bitcoin".to_string()).to_lowercase();
28         match network.as_str() {
29                 "mainnet" => Network::Bitcoin,
30                 "bitcoin" => Network::Bitcoin,
31                 "testnet" => Network::Testnet,
32                 "signet" => Network::Signet,
33                 "regtest" => Network::Regtest,
34                 _ => panic!("Invalid network"),
35         }
36 }
37
38 pub(crate) fn network_graph_cache_path() -> String {
39         format!("{}/network_graph.bin", cache_path())
40 }
41
42 pub(crate) fn cache_path() -> String {
43         let path = env::var("RAPID_GOSSIP_SYNC_SERVER_CACHES_PATH").unwrap_or("./res".to_string()).to_lowercase();
44         path
45 }
46
47 pub(crate) fn db_connection_config() -> Config {
48         let mut config = Config::new();
49         let host = env::var("RAPID_GOSSIP_SYNC_SERVER_DB_HOST").unwrap_or("localhost".to_string());
50         let user = env::var("RAPID_GOSSIP_SYNC_SERVER_DB_USER").unwrap_or("alice".to_string());
51         let db = env::var("RAPID_GOSSIP_SYNC_SERVER_DB_NAME").unwrap_or("ln_graph_sync".to_string());
52         config.host(&host);
53         config.user(&user);
54         config.dbname(&db);
55         if let Ok(password) = env::var("RAPID_GOSSIP_SYNC_SERVER_DB_PASSWORD") {
56                 config.password(&password);
57         }
58         config
59 }
60
61 pub(crate) fn bitcoin_rest_endpoint() -> HttpEndpoint {
62         let host = env::var("BITCOIN_REST_DOMAIN").unwrap_or("127.0.0.1".to_string());
63         let port = env::var("BITCOIN_REST_PORT")
64                 .unwrap_or("8332".to_string())
65                 .parse::<u16>()
66                 .expect("BITCOIN_REST_PORT env variable must be a u16.");
67         let path = env::var("BITCOIN_REST_PATH").unwrap_or("/rest/".to_string());
68         HttpEndpoint::for_host(host).with_port(port).with_path(path)
69 }
70
71 pub(crate) fn db_config_table_creation_query() -> &'static str {
72         "CREATE TABLE IF NOT EXISTS config (
73                 id SERIAL PRIMARY KEY,
74                 db_schema integer
75         )"
76 }
77
78 pub(crate) fn db_announcement_table_creation_query() -> &'static str {
79         "CREATE TABLE IF NOT EXISTS channel_announcements (
80                 id SERIAL PRIMARY KEY,
81                 short_channel_id bigint NOT NULL UNIQUE,
82                 announcement_signed BYTEA,
83                 seen timestamp NOT NULL DEFAULT NOW()
84         )"
85 }
86
87 pub(crate) fn db_channel_update_table_creation_query() -> &'static str {
88         "CREATE TABLE IF NOT EXISTS channel_updates (
89                 id SERIAL PRIMARY KEY,
90                 short_channel_id bigint NOT NULL,
91                 timestamp bigint NOT NULL,
92                 channel_flags smallint NOT NULL,
93                 direction boolean NOT NULL,
94                 disable boolean NOT NULL,
95                 cltv_expiry_delta integer NOT NULL,
96                 htlc_minimum_msat bigint NOT NULL,
97                 fee_base_msat integer NOT NULL,
98                 fee_proportional_millionths integer NOT NULL,
99                 htlc_maximum_msat bigint NOT NULL,
100                 blob_signed BYTEA NOT NULL,
101                 seen timestamp NOT NULL DEFAULT NOW()
102         )"
103 }
104
105 pub(crate) fn db_index_creation_query() -> &'static str {
106         "
107         CREATE INDEX IF NOT EXISTS channel_updates_seen ON channel_updates(seen, short_channel_id, direction) INCLUDE (id, blob_signed);
108         CREATE INDEX IF NOT EXISTS channel_updates_scid_seen ON channel_updates(short_channel_id, seen) INCLUDE (blob_signed);
109         CREATE INDEX IF NOT EXISTS channel_updates_seen_scid ON channel_updates(seen, short_channel_id);
110         CREATE INDEX IF NOT EXISTS channel_updates_scid_dir_seen ON channel_updates(short_channel_id ASC, direction ASC, seen DESC) INCLUDE (id, blob_signed);
111         CREATE UNIQUE INDEX IF NOT EXISTS channel_updates_key ON channel_updates (short_channel_id, direction, timestamp);
112         "
113 }
114
115 pub(crate) async fn upgrade_db(schema: i32, client: &mut tokio_postgres::Client) {
116         if schema == 1 {
117                 let tx = client.transaction().await.unwrap();
118                 tx.execute("ALTER TABLE channel_updates DROP COLUMN chain_hash", &[]).await.unwrap();
119                 tx.execute("ALTER TABLE channel_announcements DROP COLUMN chain_hash", &[]).await.unwrap();
120                 tx.execute("UPDATE config SET db_schema = 2 WHERE id = 1", &[]).await.unwrap();
121                 tx.commit().await.unwrap();
122         }
123         if schema == 1 || schema == 2 {
124                 let tx = client.transaction().await.unwrap();
125                 tx.execute("ALTER TABLE channel_updates DROP COLUMN short_channel_id", &[]).await.unwrap();
126                 tx.execute("ALTER TABLE channel_updates ADD COLUMN short_channel_id bigint DEFAULT null", &[]).await.unwrap();
127                 tx.execute("ALTER TABLE channel_updates DROP COLUMN direction", &[]).await.unwrap();
128                 tx.execute("ALTER TABLE channel_updates ADD COLUMN direction boolean DEFAULT null", &[]).await.unwrap();
129                 loop {
130                         let rows = tx.query("SELECT id, composite_index FROM channel_updates WHERE short_channel_id IS NULL LIMIT 50000", &[]).await.unwrap();
131                         if rows.is_empty() { break; }
132                         let mut updates = FuturesUnordered::new();
133                         for row in rows {
134                                 let id: i32 = row.get("id");
135                                 let index: String = row.get("composite_index");
136                                 let tx_ref = &tx;
137                                 updates.push(async move {
138                                         let mut index_iter = index.split(":");
139                                         let scid_hex = index_iter.next().unwrap();
140                                         index_iter.next().unwrap();
141                                         let direction_str = index_iter.next().unwrap();
142                                         assert!(direction_str == "1" || direction_str == "0");
143                                         let direction = direction_str == "1";
144                                         let scid_be_bytes = hex_utils::to_vec(scid_hex).unwrap();
145                                         let scid = i64::from_be_bytes(scid_be_bytes.try_into().unwrap());
146                                         assert!(scid > 0); // Will roll over in some 150 years or so
147                                         tx_ref.execute("UPDATE channel_updates SET short_channel_id = $1, direction = $2 WHERE id = $3", &[&scid, &direction, &id]).await.unwrap();
148                                 });
149                         }
150                         while let Some(_) = updates.next().await { }
151                 }
152                 tx.execute("ALTER TABLE channel_updates ALTER short_channel_id DROP DEFAULT", &[]).await.unwrap();
153                 tx.execute("ALTER TABLE channel_updates ALTER short_channel_id SET NOT NULL", &[]).await.unwrap();
154                 tx.execute("ALTER TABLE channel_updates ALTER direction DROP DEFAULT", &[]).await.unwrap();
155                 tx.execute("ALTER TABLE channel_updates ALTER direction SET NOT NULL", &[]).await.unwrap();
156                 tx.execute("UPDATE config SET db_schema = 3 WHERE id = 1", &[]).await.unwrap();
157                 tx.commit().await.unwrap();
158         }
159         if schema >= 1 && schema <= 3 {
160                 let tx = client.transaction().await.unwrap();
161                 tx.execute("ALTER TABLE channel_announcements DROP COLUMN short_channel_id", &[]).await.unwrap();
162                 tx.execute("ALTER TABLE channel_announcements ADD COLUMN short_channel_id bigint DEFAULT null", &[]).await.unwrap();
163                 loop {
164                         let rows = tx.query("SELECT id, announcement_signed FROM channel_announcements WHERE short_channel_id IS NULL LIMIT 10000", &[]).await.unwrap();
165                         if rows.is_empty() { break; }
166                         let mut updates = FuturesUnordered::new();
167                         for row in rows {
168                                 let id: i32 = row.get("id");
169                                 let announcement: Vec<u8> = row.get("announcement_signed");
170                                 let tx_ref = &tx;
171                                 updates.push(async move {
172                                         let scid = ChannelAnnouncement::read(&mut Cursor::new(announcement)).unwrap().contents.short_channel_id as i64;
173                                         assert!(scid > 0); // Will roll over in some 150 years or so
174                                         tx_ref.execute("UPDATE channel_announcements SET short_channel_id = $1 WHERE id = $2", &[&scid, &id]).await.unwrap();
175                                 });
176                         }
177                         while let Some(_) = updates.next().await { }
178                 }
179                 tx.execute("ALTER TABLE channel_announcements ADD CONSTRAINT channel_announcements_short_channel_id_key UNIQUE (short_channel_id)", &[]).await.unwrap();
180                 tx.execute("ALTER TABLE channel_announcements ALTER short_channel_id DROP DEFAULT", &[]).await.unwrap();
181                 tx.execute("ALTER TABLE channel_announcements ALTER short_channel_id SET NOT NULL", &[]).await.unwrap();
182                 tx.execute("UPDATE config SET db_schema = 4 WHERE id = 1", &[]).await.unwrap();
183                 tx.commit().await.unwrap();
184         }
185         if schema >= 1 && schema <= 4 {
186                 let tx = client.transaction().await.unwrap();
187                 tx.execute("ALTER TABLE channel_updates ALTER composite_index SET DATA TYPE character(29)", &[]).await.unwrap();
188                 tx.execute("UPDATE config SET db_schema = 5 WHERE id = 1", &[]).await.unwrap();
189                 tx.commit().await.unwrap();
190         }
191         if schema >= 1 && schema <= 5 {
192                 let tx = client.transaction().await.unwrap();
193                 tx.execute("ALTER TABLE channel_updates ALTER channel_flags SET DATA TYPE smallint", &[]).await.unwrap();
194                 tx.execute("ALTER TABLE channel_announcements DROP COLUMN block_height", &[]).await.unwrap();
195                 tx.execute("UPDATE config SET db_schema = 6 WHERE id = 1", &[]).await.unwrap();
196                 tx.commit().await.unwrap();
197         }
198         if schema >= 1 && schema <= 6 {
199                 let tx = client.transaction().await.unwrap();
200                 tx.execute("ALTER TABLE channel_updates DROP COLUMN composite_index", &[]).await.unwrap();
201                 tx.execute("ALTER TABLE channel_updates ALTER timestamp SET NOT NULL", &[]).await.unwrap();
202                 tx.execute("ALTER TABLE channel_updates ALTER channel_flags SET NOT NULL", &[]).await.unwrap();
203                 tx.execute("ALTER TABLE channel_updates ALTER disable SET NOT NULL", &[]).await.unwrap();
204                 tx.execute("ALTER TABLE channel_updates ALTER cltv_expiry_delta SET NOT NULL", &[]).await.unwrap();
205                 tx.execute("ALTER TABLE channel_updates ALTER htlc_minimum_msat SET NOT NULL", &[]).await.unwrap();
206                 tx.execute("ALTER TABLE channel_updates ALTER fee_base_msat SET NOT NULL", &[]).await.unwrap();
207                 tx.execute("ALTER TABLE channel_updates ALTER fee_proportional_millionths SET NOT NULL", &[]).await.unwrap();
208                 tx.execute("ALTER TABLE channel_updates ALTER htlc_maximum_msat SET NOT NULL", &[]).await.unwrap();
209                 tx.execute("ALTER TABLE channel_updates ALTER blob_signed SET NOT NULL", &[]).await.unwrap();
210                 tx.execute("CREATE UNIQUE INDEX channel_updates_key ON channel_updates (short_channel_id, direction, timestamp)", &[]).await.unwrap();
211                 tx.execute("UPDATE config SET db_schema = 7 WHERE id = 1", &[]).await.unwrap();
212                 tx.commit().await.unwrap();
213         }
214         if schema >= 1 && schema <= 7 {
215                 let tx = client.transaction().await.unwrap();
216                 tx.execute("DROP INDEX channels_seen", &[]).await.unwrap();
217                 tx.execute("DROP INDEX channel_updates_scid", &[]).await.unwrap();
218                 tx.execute("DROP INDEX channel_updates_direction", &[]).await.unwrap();
219                 tx.execute("DROP INDEX channel_updates_seen", &[]).await.unwrap();
220                 tx.execute("DROP INDEX channel_updates_scid_seen", &[]).await.unwrap();
221                 tx.execute("DROP INDEX channel_updates_scid_dir_seen", &[]).await.unwrap();
222                 tx.execute("UPDATE config SET db_schema = 8 WHERE id = 1", &[]).await.unwrap();
223                 tx.commit().await.unwrap();
224         }
225         if schema <= 1 || schema > SCHEMA_VERSION {
226                 panic!("Unknown schema in db: {}, we support up to {}", schema, SCHEMA_VERSION);
227         }
228         // PostgreSQL (at least v13, but likely later versions as well) handles insert-only tables
229         // *very* poorly. After some number of inserts, it refuses to rely on indexes, assuming them to
230         // be possibly-stale, until a VACUUM happens. Thus, we set the vacuum factor really low here,
231         // pushing PostgreSQL to vacuum often.
232         // See https://www.cybertec-postgresql.com/en/postgresql-autovacuum-insert-only-tables/
233         let _ = client.execute("ALTER TABLE channel_updates SET ( autovacuum_vacuum_insert_scale_factor = 0.005 );", &[]).await;
234         let _ = client.execute("ALTER TABLE channel_announcements SET ( autovacuum_vacuum_insert_scale_factor = 0.005 );", &[]).await;
235 }
236
237 pub(crate) fn ln_peers() -> Vec<(PublicKey, SocketAddr)> {
238         const WALLET_OF_SATOSHI: &str = "035e4ff418fc8b5554c5d9eea66396c227bd429a3251c8cbc711002ba215bfc226@170.75.163.209:9735";
239         let list = env::var("LN_PEERS").unwrap_or(WALLET_OF_SATOSHI.to_string());
240         let mut peers = Vec::new();
241         for peer_info in list.split(',') {
242                 peers.push(resolve_peer_info(peer_info).expect("Invalid peer info in LN_PEERS"));
243         }
244         peers
245 }
246
247 fn resolve_peer_info(peer_info: &str) -> Result<(PublicKey, SocketAddr), &str> {
248         let mut peer_info = peer_info.splitn(2, '@');
249
250         let pubkey = peer_info.next().ok_or("Invalid peer info. Should be formatted as: `pubkey@host:port`")?;
251         let pubkey = Vec::from_hex(pubkey).map_err(|_| "Invalid node pubkey")?;
252         let pubkey = PublicKey::from_slice(&pubkey).map_err(|_| "Invalid node pubkey")?;
253
254         let socket_address = peer_info.next().ok_or("Invalid peer info. Should be formatted as: `pubkey@host:port`")?;
255         let socket_address = socket_address
256                 .to_socket_addrs()
257                 .map_err(|_| "Cannot resolve node address")?
258                 .next()
259                 .ok_or("Cannot resolve node address")?;
260
261         Ok((pubkey, socket_address))
262 }
263
264 #[cfg(test)]
265 mod tests {
266         use super::resolve_peer_info;
267         use bitcoin::hashes::hex::ToHex;
268
269         #[test]
270         fn test_resolve_peer_info() {
271                 let wallet_of_satoshi = "035e4ff418fc8b5554c5d9eea66396c227bd429a3251c8cbc711002ba215bfc226@170.75.163.209:9735";
272                 let (pubkey, socket_address) = resolve_peer_info(wallet_of_satoshi).unwrap();
273                 assert_eq!(pubkey.serialize().to_hex(), "035e4ff418fc8b5554c5d9eea66396c227bd429a3251c8cbc711002ba215bfc226");
274                 assert_eq!(socket_address.to_string(), "170.75.163.209:9735");
275
276                 let ipv6 = "033d8656219478701227199cbd6f670335c8d408a92ae88b962c49d4dc0e83e025@[2001:db8::1]:80";
277                 let (pubkey, socket_address) = resolve_peer_info(ipv6).unwrap();
278                 assert_eq!(pubkey.serialize().to_hex(), "033d8656219478701227199cbd6f670335c8d408a92ae88b962c49d4dc0e83e025");
279                 assert_eq!(socket_address.to_string(), "[2001:db8::1]:80");
280
281                 let localhost = "033d8656219478701227199cbd6f670335c8d408a92ae88b962c49d4dc0e83e025@localhost:9735";
282                 let (pubkey, socket_address) = resolve_peer_info(localhost).unwrap();
283                 assert_eq!(pubkey.serialize().to_hex(), "033d8656219478701227199cbd6f670335c8d408a92ae88b962c49d4dc0e83e025");
284                 let socket_address = socket_address.to_string();
285                 assert!(socket_address == "127.0.0.1:9735" || socket_address == "[::1]:9735");
286         }
287 }