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