Use more appropriate data types for SCIDs, direction, composite_index
[rapid-gossip-sync-server] / src / config.rs
1 use std::convert::TryInto;
2 use std::env;
3 use std::net::SocketAddr;
4 use std::io::Cursor;
5 use bitcoin::secp256k1::PublicKey;
6 use lightning::ln::msgs::ChannelAnnouncement;
7 use lightning::util::ser::Readable;
8 use lightning_block_sync::http::HttpEndpoint;
9 use tokio_postgres::Config;
10 use crate::hex_utils;
11
12 use futures::stream::{FuturesUnordered, StreamExt};
13
14 pub(crate) const SCHEMA_VERSION: i32 = 5;
15 pub(crate) const SNAPSHOT_CALCULATION_INTERVAL: u32 = 3600 * 24; // every 24 hours, in seconds
16 pub(crate) const DOWNLOAD_NEW_GOSSIP: bool = true;
17
18 pub(crate) fn network_graph_cache_path() -> &'static str {
19         "./res/network_graph.bin"
20 }
21
22 pub(crate) fn db_connection_config() -> Config {
23         let mut config = Config::new();
24         let host = env::var("RAPID_GOSSIP_SYNC_SERVER_DB_HOST").unwrap_or("localhost".to_string());
25         let user = env::var("RAPID_GOSSIP_SYNC_SERVER_DB_USER").unwrap_or("alice".to_string());
26         let db = env::var("RAPID_GOSSIP_SYNC_SERVER_DB_NAME").unwrap_or("ln_graph_sync".to_string());
27         config.host(&host);
28         config.user(&user);
29         config.dbname(&db);
30         if let Ok(password) = env::var("RAPID_GOSSIP_SYNC_SERVER_DB_PASSWORD") {
31                 config.password(&password);
32         }
33         config
34 }
35
36 pub(crate) fn bitcoin_rest_endpoint() -> HttpEndpoint {
37         let host = env::var("BITCOIN_REST_DOMAIN").unwrap_or("127.0.0.1".to_string());
38         let port = env::var("BITCOIN_REST_PORT")
39                 .unwrap_or("8332".to_string())
40                 .parse::<u16>()
41                 .expect("BITCOIN_REST_PORT env variable must be a u16.");
42         let path = env::var("BITCOIN_REST_PATH").unwrap_or("/rest/".to_string());
43         HttpEndpoint::for_host(host).with_port(port).with_path(path)
44 }
45
46 pub(crate) fn db_config_table_creation_query() -> &'static str {
47         "CREATE TABLE IF NOT EXISTS config (
48                 id SERIAL PRIMARY KEY,
49                 db_schema integer
50         )"
51 }
52
53 pub(crate) fn db_announcement_table_creation_query() -> &'static str {
54         "CREATE TABLE IF NOT EXISTS channel_announcements (
55                 id SERIAL PRIMARY KEY,
56                 short_channel_id bigint NOT NULL UNIQUE,
57                 block_height integer,
58                 announcement_signed BYTEA,
59                 seen timestamp NOT NULL DEFAULT NOW()
60         )"
61 }
62
63 pub(crate) fn db_channel_update_table_creation_query() -> &'static str {
64         // We'll run out of room in composite index at block 8,388,608 or in the year 2286
65         "CREATE TABLE IF NOT EXISTS channel_updates (
66                 id SERIAL PRIMARY KEY,
67                 composite_index character(29) UNIQUE,
68                 short_channel_id bigint NOT NULL,
69                 timestamp bigint,
70                 channel_flags integer,
71                 direction boolean NOT NULL,
72                 disable boolean,
73                 cltv_expiry_delta integer,
74                 htlc_minimum_msat bigint,
75                 fee_base_msat integer,
76                 fee_proportional_millionths integer,
77                 htlc_maximum_msat bigint,
78                 blob_signed BYTEA,
79                 seen timestamp NOT NULL DEFAULT NOW()
80         )"
81 }
82
83 pub(crate) fn db_index_creation_query() -> &'static str {
84         "
85         CREATE INDEX IF NOT EXISTS channels_seen ON channel_announcements(seen);
86         CREATE INDEX IF NOT EXISTS channel_updates_scid ON channel_updates(short_channel_id);
87         CREATE INDEX IF NOT EXISTS channel_updates_direction ON channel_updates (short_channel_id, direction);
88         CREATE INDEX IF NOT EXISTS channel_updates_seen ON channel_updates(seen);
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("CREATE INDEX channel_updates_scid ON channel_updates(short_channel_id)", &[]).await.unwrap();
130                 tx.execute("CREATE INDEX channel_updates_direction ON channel_updates (short_channel_id, direction)", &[]).await.unwrap();
131                 tx.execute("ALTER TABLE channel_updates ALTER short_channel_id DROP DEFAULT", &[]).await.unwrap();
132                 tx.execute("ALTER TABLE channel_updates ALTER short_channel_id SET NOT NULL", &[]).await.unwrap();
133                 tx.execute("ALTER TABLE channel_updates ALTER direction DROP DEFAULT", &[]).await.unwrap();
134                 tx.execute("ALTER TABLE channel_updates ALTER direction SET NOT NULL", &[]).await.unwrap();
135                 tx.execute("UPDATE config SET db_schema = 3 WHERE id = 1", &[]).await.unwrap();
136                 tx.commit().await.unwrap();
137         }
138         if schema >= 1 && schema <= 3 {
139                 let tx = client.transaction().await.unwrap();
140                 tx.execute("ALTER TABLE channel_announcements DROP COLUMN short_channel_id", &[]).await.unwrap();
141                 tx.execute("ALTER TABLE channel_announcements ADD COLUMN short_channel_id bigint DEFAULT null", &[]).await.unwrap();
142                 loop {
143                         let rows = tx.query("SELECT id, announcement_signed FROM channel_announcements WHERE short_channel_id IS NULL LIMIT 10000", &[]).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 announcement: Vec<u8> = row.get("announcement_signed");
149                                 let tx_ref = &tx;
150                                 updates.push(async move {
151                                         let scid = ChannelAnnouncement::read(&mut Cursor::new(announcement)).unwrap().contents.short_channel_id as i64;
152                                         assert!(scid > 0); // Will roll over in some 150 years or so
153                                         tx_ref.execute("UPDATE channel_announcements SET short_channel_id = $1 WHERE id = $2", &[&scid, &id]).await.unwrap();
154                                 });
155                         }
156                         while let Some(_) = updates.next().await { }
157                 }
158                 tx.execute("ALTER TABLE channel_announcements ADD CONSTRAINT channel_announcements_short_channel_id_key UNIQUE (short_channel_id)", &[]).await.unwrap();
159                 tx.execute("ALTER TABLE channel_announcements ALTER short_channel_id DROP DEFAULT", &[]).await.unwrap();
160                 tx.execute("ALTER TABLE channel_announcements ALTER short_channel_id SET NOT NULL", &[]).await.unwrap();
161                 tx.execute("UPDATE config SET db_schema = 4 WHERE id = 1", &[]).await.unwrap();
162                 tx.commit().await.unwrap();
163         }
164         if schema >= 1 && schema <= 4 {
165                 let tx = client.transaction().await.unwrap();
166                 tx.execute("ALTER TABLE channel_updates ALTER composite_index SET DATA TYPE character(29)", &[]).await.unwrap();
167                 tx.execute("UPDATE config SET db_schema = 5 WHERE id = 1", &[]).await.unwrap();
168                 tx.commit().await.unwrap();
169         }
170         if schema <= 1 || schema > SCHEMA_VERSION {
171                 panic!("Unknown schema in db: {}, we support up to {}", schema, SCHEMA_VERSION);
172         }
173 }
174
175 /// EDIT ME
176 pub(crate) fn ln_peers() -> Vec<(PublicKey, SocketAddr)> {
177         vec![
178                 // Bitfinex
179                 // (hex_utils::to_compressed_pubkey("033d8656219478701227199cbd6f670335c8d408a92ae88b962c49d4dc0e83e025").unwrap(), "34.65.85.39:9735".parse().unwrap()),
180
181                 // Matt Corallo
182                 // (hex_utils::to_compressed_pubkey("03db10aa09ff04d3568b0621750794063df401e6853c79a21a83e1a3f3b5bfb0c8").unwrap(), "69.59.18.80:9735".parse().unwrap())
183
184                 // River Financial
185                 // (hex_utils::to_compressed_pubkey("03037dc08e9ac63b82581f79b662a4d0ceca8a8ca162b1af3551595b8f2d97b70a").unwrap(), "104.196.249.140:9735".parse().unwrap())
186
187                 // Wallet of Satoshi | 035e4ff418fc8b5554c5d9eea66396c227bd429a3251c8cbc711002ba215bfc226@170.75.163.209:9735
188                 (hex_utils::to_compressed_pubkey("035e4ff418fc8b5554c5d9eea66396c227bd429a3251c8cbc711002ba215bfc226").unwrap(), "170.75.163.209:9735".parse().unwrap())
189         ]
190 }