Add some further indexes on channel_updates to match queries
[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 = 6;
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                 announcement_signed BYTEA,
58                 seen timestamp NOT NULL DEFAULT NOW()
59         )"
60 }
61
62 pub(crate) fn db_channel_update_table_creation_query() -> &'static str {
63         // We'll run out of room in composite index at block 8,388,608 or in the year 2286
64         "CREATE TABLE IF NOT EXISTS channel_updates (
65                 id SERIAL PRIMARY KEY,
66                 composite_index character(29) UNIQUE,
67                 short_channel_id bigint NOT NULL,
68                 timestamp bigint,
69                 channel_flags smallint,
70                 direction boolean NOT NULL,
71                 disable boolean,
72                 cltv_expiry_delta integer,
73                 htlc_minimum_msat bigint,
74                 fee_base_msat integer,
75                 fee_proportional_millionths integer,
76                 htlc_maximum_msat bigint,
77                 blob_signed BYTEA,
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 channels_seen ON channel_announcements(seen);
85         CREATE INDEX IF NOT EXISTS channel_updates_scid ON channel_updates(short_channel_id);
86         CREATE INDEX IF NOT EXISTS channel_updates_direction ON channel_updates (short_channel_id, direction);
87         CREATE INDEX IF NOT EXISTS channel_updates_seen ON channel_updates(seen);
88         CREATE INDEX IF NOT EXISTS channel_updates_scid_seen ON channel_updates(short_channel_id, seen);
89         CREATE INDEX IF NOT EXISTS channel_updates_scid_dir_seen ON channel_updates(short_channel_id ASC, direction ASC, seen DESC);
90         "
91 }
92
93 pub(crate) async fn upgrade_db(schema: i32, client: &mut tokio_postgres::Client) {
94         if schema == 1 {
95                 let tx = client.transaction().await.unwrap();
96                 tx.execute("ALTER TABLE channel_updates DROP COLUMN chain_hash", &[]).await.unwrap();
97                 tx.execute("ALTER TABLE channel_announcements DROP COLUMN chain_hash", &[]).await.unwrap();
98                 tx.execute("UPDATE config SET db_schema = 2 WHERE id = 1", &[]).await.unwrap();
99                 tx.commit().await.unwrap();
100         }
101         if schema == 1 || schema == 2 {
102                 let tx = client.transaction().await.unwrap();
103                 tx.execute("ALTER TABLE channel_updates DROP COLUMN short_channel_id", &[]).await.unwrap();
104                 tx.execute("ALTER TABLE channel_updates ADD COLUMN short_channel_id bigint DEFAULT null", &[]).await.unwrap();
105                 tx.execute("ALTER TABLE channel_updates DROP COLUMN direction", &[]).await.unwrap();
106                 tx.execute("ALTER TABLE channel_updates ADD COLUMN direction boolean DEFAULT null", &[]).await.unwrap();
107                 loop {
108                         let rows = tx.query("SELECT id, composite_index FROM channel_updates WHERE short_channel_id IS NULL LIMIT 50000", &[]).await.unwrap();
109                         if rows.is_empty() { break; }
110                         let mut updates = FuturesUnordered::new();
111                         for row in rows {
112                                 let id: i32 = row.get("id");
113                                 let index: String = row.get("composite_index");
114                                 let tx_ref = &tx;
115                                 updates.push(async move {
116                                         let mut index_iter = index.split(":");
117                                         let scid_hex = index_iter.next().unwrap();
118                                         index_iter.next().unwrap();
119                                         let direction_str = index_iter.next().unwrap();
120                                         assert!(direction_str == "1" || direction_str == "0");
121                                         let direction = direction_str == "1";
122                                         let scid_be_bytes = hex_utils::to_vec(scid_hex).unwrap();
123                                         let scid = i64::from_be_bytes(scid_be_bytes.try_into().unwrap());
124                                         assert!(scid > 0); // Will roll over in some 150 years or so
125                                         tx_ref.execute("UPDATE channel_updates SET short_channel_id = $1, direction = $2 WHERE id = $3", &[&scid, &direction, &id]).await.unwrap();
126                                 });
127                         }
128                         while let Some(_) = updates.next().await { }
129                 }
130                 tx.execute("CREATE INDEX channel_updates_scid ON channel_updates(short_channel_id)", &[]).await.unwrap();
131                 tx.execute("CREATE INDEX channel_updates_direction ON channel_updates (short_channel_id, direction)", &[]).await.unwrap();
132                 tx.execute("ALTER TABLE channel_updates ALTER short_channel_id DROP DEFAULT", &[]).await.unwrap();
133                 tx.execute("ALTER TABLE channel_updates ALTER short_channel_id SET NOT NULL", &[]).await.unwrap();
134                 tx.execute("ALTER TABLE channel_updates ALTER direction DROP DEFAULT", &[]).await.unwrap();
135                 tx.execute("ALTER TABLE channel_updates ALTER direction SET NOT NULL", &[]).await.unwrap();
136                 tx.execute("UPDATE config SET db_schema = 3 WHERE id = 1", &[]).await.unwrap();
137                 tx.commit().await.unwrap();
138         }
139         if schema >= 1 && schema <= 3 {
140                 let tx = client.transaction().await.unwrap();
141                 tx.execute("ALTER TABLE channel_announcements DROP COLUMN short_channel_id", &[]).await.unwrap();
142                 tx.execute("ALTER TABLE channel_announcements ADD COLUMN short_channel_id bigint DEFAULT null", &[]).await.unwrap();
143                 loop {
144                         let rows = tx.query("SELECT id, announcement_signed FROM channel_announcements WHERE short_channel_id IS NULL LIMIT 10000", &[]).await.unwrap();
145                         if rows.is_empty() { break; }
146                         let mut updates = FuturesUnordered::new();
147                         for row in rows {
148                                 let id: i32 = row.get("id");
149                                 let announcement: Vec<u8> = row.get("announcement_signed");
150                                 let tx_ref = &tx;
151                                 updates.push(async move {
152                                         let scid = ChannelAnnouncement::read(&mut Cursor::new(announcement)).unwrap().contents.short_channel_id as i64;
153                                         assert!(scid > 0); // Will roll over in some 150 years or so
154                                         tx_ref.execute("UPDATE channel_announcements SET short_channel_id = $1 WHERE id = $2", &[&scid, &id]).await.unwrap();
155                                 });
156                         }
157                         while let Some(_) = updates.next().await { }
158                 }
159                 tx.execute("ALTER TABLE channel_announcements ADD CONSTRAINT channel_announcements_short_channel_id_key UNIQUE (short_channel_id)", &[]).await.unwrap();
160                 tx.execute("ALTER TABLE channel_announcements ALTER short_channel_id DROP DEFAULT", &[]).await.unwrap();
161                 tx.execute("ALTER TABLE channel_announcements ALTER short_channel_id SET NOT NULL", &[]).await.unwrap();
162                 tx.execute("UPDATE config SET db_schema = 4 WHERE id = 1", &[]).await.unwrap();
163                 tx.commit().await.unwrap();
164         }
165         if schema >= 1 && schema <= 4 {
166                 let tx = client.transaction().await.unwrap();
167                 tx.execute("ALTER TABLE channel_updates ALTER composite_index SET DATA TYPE character(29)", &[]).await.unwrap();
168                 tx.execute("UPDATE config SET db_schema = 5 WHERE id = 1", &[]).await.unwrap();
169                 tx.commit().await.unwrap();
170         }
171         if schema >= 1 && schema <= 5 {
172                 let tx = client.transaction().await.unwrap();
173                 tx.execute("ALTER TABLE channel_updates ALTER channel_flags SET DATA TYPE smallint", &[]).await.unwrap();
174                 tx.execute("ALTER TABLE channel_announcements DROP COLUMN block_height", &[]).await.unwrap();
175                 tx.execute("UPDATE config SET db_schema = 6 WHERE id = 1", &[]).await.unwrap();
176                 tx.commit().await.unwrap();
177         }
178         if schema <= 1 || schema > SCHEMA_VERSION {
179                 panic!("Unknown schema in db: {}, we support up to {}", schema, SCHEMA_VERSION);
180         }
181 }
182
183 /// EDIT ME
184 pub(crate) fn ln_peers() -> Vec<(PublicKey, SocketAddr)> {
185         vec![
186                 // Bitfinex
187                 // (hex_utils::to_compressed_pubkey("033d8656219478701227199cbd6f670335c8d408a92ae88b962c49d4dc0e83e025").unwrap(), "34.65.85.39:9735".parse().unwrap()),
188
189                 // Matt Corallo
190                 // (hex_utils::to_compressed_pubkey("03db10aa09ff04d3568b0621750794063df401e6853c79a21a83e1a3f3b5bfb0c8").unwrap(), "69.59.18.80:9735".parse().unwrap())
191
192                 // River Financial
193                 // (hex_utils::to_compressed_pubkey("03037dc08e9ac63b82581f79b662a4d0ceca8a8ca162b1af3551595b8f2d97b70a").unwrap(), "104.196.249.140:9735".parse().unwrap())
194
195                 // Wallet of Satoshi | 035e4ff418fc8b5554c5d9eea66396c227bd429a3251c8cbc711002ba215bfc226@170.75.163.209:9735
196                 (hex_utils::to_compressed_pubkey("035e4ff418fc8b5554c5d9eea66396c227bd429a3251c8cbc711002ba215bfc226").unwrap(), "170.75.163.209:9735".parse().unwrap())
197         ]
198 }