804b0f8ff8a66262b7273702239b3ac645d24fae
[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 = 11;
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 log_level() -> lightning::util::logger::Level {
39         let level = env::var("RAPID_GOSSIP_SYNC_SERVER_LOG_LEVEL").unwrap_or("info".to_string()).to_lowercase();
40         match level.as_str() {
41                 "gossip" => lightning::util::logger::Level::Gossip,
42                 "trace" => lightning::util::logger::Level::Trace,
43                 "debug" => lightning::util::logger::Level::Debug,
44                 "info" => lightning::util::logger::Level::Info,
45                 "warn" => lightning::util::logger::Level::Warn,
46                 "error" => lightning::util::logger::Level::Error,
47                 _ => panic!("Invalid log level"),
48         }
49 }
50
51 pub(crate) fn network_graph_cache_path() -> String {
52         format!("{}/network_graph.bin", cache_path())
53 }
54
55 pub(crate) fn cache_path() -> String {
56         let path = env::var("RAPID_GOSSIP_SYNC_SERVER_CACHES_PATH").unwrap_or("./res".to_string()).to_lowercase();
57         path
58 }
59
60 pub(crate) fn db_connection_config() -> Config {
61         let mut config = Config::new();
62         let host = env::var("RAPID_GOSSIP_SYNC_SERVER_DB_HOST").unwrap_or("localhost".to_string());
63         let user = env::var("RAPID_GOSSIP_SYNC_SERVER_DB_USER").unwrap_or("alice".to_string());
64         let db = env::var("RAPID_GOSSIP_SYNC_SERVER_DB_NAME").unwrap_or("ln_graph_sync".to_string());
65         config.host(&host);
66         config.user(&user);
67         config.dbname(&db);
68         if let Ok(password) = env::var("RAPID_GOSSIP_SYNC_SERVER_DB_PASSWORD") {
69                 config.password(&password);
70         }
71         config
72 }
73
74 pub(crate) fn bitcoin_rest_endpoint() -> HttpEndpoint {
75         let host = env::var("BITCOIN_REST_DOMAIN").unwrap_or("127.0.0.1".to_string());
76         let port = env::var("BITCOIN_REST_PORT")
77                 .unwrap_or("8332".to_string())
78                 .parse::<u16>()
79                 .expect("BITCOIN_REST_PORT env variable must be a u16.");
80         let path = env::var("BITCOIN_REST_PATH").unwrap_or("/rest/".to_string());
81         HttpEndpoint::for_host(host).with_port(port).with_path(path)
82 }
83
84 pub(crate) fn db_config_table_creation_query() -> &'static str {
85         "CREATE TABLE IF NOT EXISTS config (
86                 id SERIAL PRIMARY KEY,
87                 db_schema integer
88         )"
89 }
90
91 pub(crate) fn db_announcement_table_creation_query() -> &'static str {
92         "CREATE TABLE IF NOT EXISTS channel_announcements (
93                 id SERIAL PRIMARY KEY,
94                 short_channel_id bigint NOT NULL UNIQUE,
95                 announcement_signed BYTEA,
96                 seen timestamp NOT NULL DEFAULT NOW()
97         )"
98 }
99
100 pub(crate) fn db_channel_update_table_creation_query() -> &'static str {
101         "CREATE TABLE IF NOT EXISTS channel_updates (
102                 id SERIAL PRIMARY KEY,
103                 short_channel_id bigint NOT NULL,
104                 timestamp bigint NOT NULL,
105                 channel_flags smallint NOT NULL,
106                 direction boolean NOT NULL,
107                 disable boolean NOT NULL,
108                 cltv_expiry_delta integer NOT NULL,
109                 htlc_minimum_msat bigint NOT NULL,
110                 fee_base_msat integer NOT NULL,
111                 fee_proportional_millionths integer NOT NULL,
112                 htlc_maximum_msat bigint NOT NULL,
113                 blob_signed BYTEA NOT NULL,
114                 seen timestamp NOT NULL DEFAULT NOW()
115         )"
116 }
117
118 pub(crate) fn db_index_creation_query() -> &'static str {
119         "
120         CREATE INDEX IF NOT EXISTS channel_updates_seen_with_id_direction_blob ON channel_updates(seen) INCLUDE (id, direction, blob_signed);
121         CREATE INDEX IF NOT EXISTS channel_updates_seen_scid ON channel_updates(seen, short_channel_id);
122         CREATE INDEX IF NOT EXISTS channel_updates_scid_dir_seen_asc ON channel_updates(short_channel_id, direction, seen);
123         CREATE INDEX IF NOT EXISTS channel_updates_scid_dir_seen_desc_with_id ON channel_updates(short_channel_id ASC, direction ASC, seen DESC) INCLUDE (id);
124         CREATE UNIQUE INDEX IF NOT EXISTS channel_updates_key ON channel_updates (short_channel_id, direction, timestamp);
125         "
126 }
127
128 pub(crate) async fn upgrade_db(schema: i32, client: &mut tokio_postgres::Client) {
129         if schema == 1 {
130                 let tx = client.transaction().await.unwrap();
131                 tx.execute("ALTER TABLE channel_updates DROP COLUMN chain_hash", &[]).await.unwrap();
132                 tx.execute("ALTER TABLE channel_announcements DROP COLUMN chain_hash", &[]).await.unwrap();
133                 tx.execute("UPDATE config SET db_schema = 2 WHERE id = 1", &[]).await.unwrap();
134                 tx.commit().await.unwrap();
135         }
136         if schema == 1 || schema == 2 {
137                 let tx = client.transaction().await.unwrap();
138                 tx.execute("ALTER TABLE channel_updates DROP COLUMN short_channel_id", &[]).await.unwrap();
139                 tx.execute("ALTER TABLE channel_updates ADD COLUMN short_channel_id bigint DEFAULT null", &[]).await.unwrap();
140                 tx.execute("ALTER TABLE channel_updates DROP COLUMN direction", &[]).await.unwrap();
141                 tx.execute("ALTER TABLE channel_updates ADD COLUMN direction boolean DEFAULT null", &[]).await.unwrap();
142                 loop {
143                         let rows = tx.query("SELECT id, composite_index FROM channel_updates WHERE short_channel_id IS NULL LIMIT 50000", &[]).await.unwrap();
144                         if rows.is_empty() { break; }
145                         let mut updates = FuturesUnordered::new();
146                         for row in rows {
147                                 let id: i32 = row.get("id");
148                                 let index: String = row.get("composite_index");
149                                 let tx_ref = &tx;
150                                 updates.push(async move {
151                                         let mut index_iter = index.split(":");
152                                         let scid_hex = index_iter.next().unwrap();
153                                         index_iter.next().unwrap();
154                                         let direction_str = index_iter.next().unwrap();
155                                         assert!(direction_str == "1" || direction_str == "0");
156                                         let direction = direction_str == "1";
157                                         let scid_be_bytes = hex_utils::to_vec(scid_hex).unwrap();
158                                         let scid = i64::from_be_bytes(scid_be_bytes.try_into().unwrap());
159                                         assert!(scid > 0); // Will roll over in some 150 years or so
160                                         tx_ref.execute("UPDATE channel_updates SET short_channel_id = $1, direction = $2 WHERE id = $3", &[&scid, &direction, &id]).await.unwrap();
161                                 });
162                         }
163                         while let Some(_) = updates.next().await { }
164                 }
165                 tx.execute("ALTER TABLE channel_updates ALTER short_channel_id DROP DEFAULT", &[]).await.unwrap();
166                 tx.execute("ALTER TABLE channel_updates ALTER short_channel_id SET NOT NULL", &[]).await.unwrap();
167                 tx.execute("ALTER TABLE channel_updates ALTER direction DROP DEFAULT", &[]).await.unwrap();
168                 tx.execute("ALTER TABLE channel_updates ALTER direction SET NOT NULL", &[]).await.unwrap();
169                 tx.execute("UPDATE config SET db_schema = 3 WHERE id = 1", &[]).await.unwrap();
170                 tx.commit().await.unwrap();
171         }
172         if schema >= 1 && schema <= 3 {
173                 let tx = client.transaction().await.unwrap();
174                 tx.execute("ALTER TABLE channel_announcements DROP COLUMN short_channel_id", &[]).await.unwrap();
175                 tx.execute("ALTER TABLE channel_announcements ADD COLUMN short_channel_id bigint DEFAULT null", &[]).await.unwrap();
176                 loop {
177                         let rows = tx.query("SELECT id, announcement_signed FROM channel_announcements WHERE short_channel_id IS NULL LIMIT 10000", &[]).await.unwrap();
178                         if rows.is_empty() { break; }
179                         let mut updates = FuturesUnordered::new();
180                         for row in rows {
181                                 let id: i32 = row.get("id");
182                                 let announcement: Vec<u8> = row.get("announcement_signed");
183                                 let tx_ref = &tx;
184                                 updates.push(async move {
185                                         let scid = ChannelAnnouncement::read(&mut Cursor::new(announcement)).unwrap().contents.short_channel_id as i64;
186                                         assert!(scid > 0); // Will roll over in some 150 years or so
187                                         tx_ref.execute("UPDATE channel_announcements SET short_channel_id = $1 WHERE id = $2", &[&scid, &id]).await.unwrap();
188                                 });
189                         }
190                         while let Some(_) = updates.next().await { }
191                 }
192                 tx.execute("ALTER TABLE channel_announcements ADD CONSTRAINT channel_announcements_short_channel_id_key UNIQUE (short_channel_id)", &[]).await.unwrap();
193                 tx.execute("ALTER TABLE channel_announcements ALTER short_channel_id DROP DEFAULT", &[]).await.unwrap();
194                 tx.execute("ALTER TABLE channel_announcements ALTER short_channel_id SET NOT NULL", &[]).await.unwrap();
195                 tx.execute("UPDATE config SET db_schema = 4 WHERE id = 1", &[]).await.unwrap();
196                 tx.commit().await.unwrap();
197         }
198         if schema >= 1 && schema <= 4 {
199                 let tx = client.transaction().await.unwrap();
200                 tx.execute("ALTER TABLE channel_updates ALTER composite_index SET DATA TYPE character(29)", &[]).await.unwrap();
201                 tx.execute("UPDATE config SET db_schema = 5 WHERE id = 1", &[]).await.unwrap();
202                 tx.commit().await.unwrap();
203         }
204         if schema >= 1 && schema <= 5 {
205                 let tx = client.transaction().await.unwrap();
206                 tx.execute("ALTER TABLE channel_updates ALTER channel_flags SET DATA TYPE smallint", &[]).await.unwrap();
207                 tx.execute("ALTER TABLE channel_announcements DROP COLUMN block_height", &[]).await.unwrap();
208                 tx.execute("UPDATE config SET db_schema = 6 WHERE id = 1", &[]).await.unwrap();
209                 tx.commit().await.unwrap();
210         }
211         if schema >= 1 && schema <= 6 {
212                 let tx = client.transaction().await.unwrap();
213                 tx.execute("ALTER TABLE channel_updates DROP COLUMN composite_index", &[]).await.unwrap();
214                 tx.execute("ALTER TABLE channel_updates ALTER timestamp SET NOT NULL", &[]).await.unwrap();
215                 tx.execute("ALTER TABLE channel_updates ALTER channel_flags SET NOT NULL", &[]).await.unwrap();
216                 tx.execute("ALTER TABLE channel_updates ALTER disable SET NOT NULL", &[]).await.unwrap();
217                 tx.execute("ALTER TABLE channel_updates ALTER cltv_expiry_delta SET NOT NULL", &[]).await.unwrap();
218                 tx.execute("ALTER TABLE channel_updates ALTER htlc_minimum_msat SET NOT NULL", &[]).await.unwrap();
219                 tx.execute("ALTER TABLE channel_updates ALTER fee_base_msat SET NOT NULL", &[]).await.unwrap();
220                 tx.execute("ALTER TABLE channel_updates ALTER fee_proportional_millionths SET NOT NULL", &[]).await.unwrap();
221                 tx.execute("ALTER TABLE channel_updates ALTER htlc_maximum_msat SET NOT NULL", &[]).await.unwrap();
222                 tx.execute("ALTER TABLE channel_updates ALTER blob_signed SET NOT NULL", &[]).await.unwrap();
223                 tx.execute("CREATE UNIQUE INDEX channel_updates_key ON channel_updates (short_channel_id, direction, timestamp)", &[]).await.unwrap();
224                 tx.execute("UPDATE config SET db_schema = 7 WHERE id = 1", &[]).await.unwrap();
225                 tx.commit().await.unwrap();
226         }
227         if schema >= 1 && schema <= 7 {
228                 let tx = client.transaction().await.unwrap();
229                 tx.execute("DROP INDEX IF EXISTS channels_seen", &[]).await.unwrap();
230                 tx.execute("DROP INDEX IF EXISTS channel_updates_scid", &[]).await.unwrap();
231                 tx.execute("DROP INDEX IF EXISTS channel_updates_direction", &[]).await.unwrap();
232                 tx.execute("DROP INDEX IF EXISTS channel_updates_seen", &[]).await.unwrap();
233                 tx.execute("DROP INDEX IF EXISTS channel_updates_scid_seen", &[]).await.unwrap();
234                 tx.execute("DROP INDEX IF EXISTS channel_updates_scid_dir_seen", &[]).await.unwrap();
235                 tx.execute("UPDATE config SET db_schema = 8 WHERE id = 1", &[]).await.unwrap();
236                 tx.commit().await.unwrap();
237         }
238         if schema >= 1 && schema <= 8 {
239                 let tx = client.transaction().await.unwrap();
240                 tx.execute("DROP INDEX IF EXISTS channel_updates_seen", &[]).await.unwrap();
241                 tx.execute("DROP INDEX IF EXISTS channel_updates_scid_seen", &[]).await.unwrap();
242                 tx.execute("UPDATE config SET db_schema = 9 WHERE id = 1", &[]).await.unwrap();
243                 tx.commit().await.unwrap();
244         }
245         if schema >= 1 && schema <= 9 {
246                 let tx = client.transaction().await.unwrap();
247                 tx.execute("DROP INDEX IF EXISTS channel_updates_scid_dir_seen", &[]).await.unwrap();
248                 tx.execute("UPDATE config SET db_schema = 10 WHERE id = 1", &[]).await.unwrap();
249                 tx.commit().await.unwrap();
250         }
251         if schema >= 1 && schema <= 10 {
252                 let tx = client.transaction().await.unwrap();
253                 tx.execute("DROP INDEX IF EXISTS channel_updates_id_with_scid_dir_blob", &[]).await.unwrap();
254                 tx.execute("UPDATE config SET db_schema = 11 WHERE id = 1", &[]).await.unwrap();
255                 tx.commit().await.unwrap();
256         }
257         if schema <= 1 || schema > SCHEMA_VERSION {
258                 panic!("Unknown schema in db: {}, we support up to {}", schema, SCHEMA_VERSION);
259         }
260         // PostgreSQL (at least v13, but likely later versions as well) handles insert-only tables
261         // *very* poorly. After some number of inserts, it refuses to rely on indexes, assuming them to
262         // be possibly-stale, until a VACUUM happens. Thus, we set the vacuum factor really low here,
263         // pushing PostgreSQL to vacuum often.
264         // See https://www.cybertec-postgresql.com/en/postgresql-autovacuum-insert-only-tables/
265         let _ = client.execute("ALTER TABLE channel_updates SET ( autovacuum_vacuum_insert_scale_factor = 0.005 );", &[]).await;
266         let _ = client.execute("ALTER TABLE channel_announcements SET ( autovacuum_vacuum_insert_scale_factor = 0.005 );", &[]).await;
267 }
268
269 pub(crate) fn ln_peers() -> Vec<(PublicKey, SocketAddr)> {
270         const WALLET_OF_SATOSHI: &str = "035e4ff418fc8b5554c5d9eea66396c227bd429a3251c8cbc711002ba215bfc226@170.75.163.209:9735";
271         let list = env::var("LN_PEERS").unwrap_or(WALLET_OF_SATOSHI.to_string());
272         let mut peers = Vec::new();
273         for peer_info in list.split(',') {
274                 peers.push(resolve_peer_info(peer_info).expect("Invalid peer info in LN_PEERS"));
275         }
276         peers
277 }
278
279 fn resolve_peer_info(peer_info: &str) -> Result<(PublicKey, SocketAddr), &str> {
280         let mut peer_info = peer_info.splitn(2, '@');
281
282         let pubkey = peer_info.next().ok_or("Invalid peer info. Should be formatted as: `pubkey@host:port`")?;
283         let pubkey = Vec::from_hex(pubkey).map_err(|_| "Invalid node pubkey")?;
284         let pubkey = PublicKey::from_slice(&pubkey).map_err(|_| "Invalid node pubkey")?;
285
286         let socket_address = peer_info.next().ok_or("Invalid peer info. Should be formatted as: `pubkey@host:port`")?;
287         let socket_address = socket_address
288                 .to_socket_addrs()
289                 .map_err(|_| "Cannot resolve node address")?
290                 .next()
291                 .ok_or("Cannot resolve node address")?;
292
293         Ok((pubkey, socket_address))
294 }
295
296 #[cfg(test)]
297 mod tests {
298         use super::resolve_peer_info;
299         use bitcoin::hashes::hex::ToHex;
300
301         #[test]
302         fn test_resolve_peer_info() {
303                 let wallet_of_satoshi = "035e4ff418fc8b5554c5d9eea66396c227bd429a3251c8cbc711002ba215bfc226@170.75.163.209:9735";
304                 let (pubkey, socket_address) = resolve_peer_info(wallet_of_satoshi).unwrap();
305                 assert_eq!(pubkey.serialize().to_hex(), "035e4ff418fc8b5554c5d9eea66396c227bd429a3251c8cbc711002ba215bfc226");
306                 assert_eq!(socket_address.to_string(), "170.75.163.209:9735");
307
308                 let ipv6 = "033d8656219478701227199cbd6f670335c8d408a92ae88b962c49d4dc0e83e025@[2001:db8::1]:80";
309                 let (pubkey, socket_address) = resolve_peer_info(ipv6).unwrap();
310                 assert_eq!(pubkey.serialize().to_hex(), "033d8656219478701227199cbd6f670335c8d408a92ae88b962c49d4dc0e83e025");
311                 assert_eq!(socket_address.to_string(), "[2001:db8::1]:80");
312
313                 let localhost = "033d8656219478701227199cbd6f670335c8d408a92ae88b962c49d4dc0e83e025@localhost:9735";
314                 let (pubkey, socket_address) = resolve_peer_info(localhost).unwrap();
315                 assert_eq!(pubkey.serialize().to_hex(), "033d8656219478701227199cbd6f670335c8d408a92ae88b962c49d4dc0e83e025");
316                 let socket_address = socket_address.to_string();
317                 assert!(socket_address == "127.0.0.1:9735" || socket_address == "[::1]:9735");
318         }
319 }