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