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