main.rs 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495
  1. /* This file is part of DarkFi (https://dark.fi)
  2. *
  3. * Copyright (C) 2020-2023 Dyne.org foundation
  4. *
  5. * This program is free software: you can redistribute it and/or modify
  6. * it under the terms of the GNU Affero General Public License as
  7. * published by the Free Software Foundation, either version 3 of the
  8. * License, or (at your option) any later version.
  9. *
  10. * This program is distributed in the hope that it will be useful,
  11. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. * GNU Affero General Public License for more details.
  14. *
  15. * You should have received a copy of the GNU Affero General Public License
  16. * along with this program. If not, see <https://www.gnu.org/licenses/>.
  17. */
  18. use std::str::FromStr;
  19. use async_std::sync::{Arc, Mutex};
  20. use async_trait::async_trait;
  21. use darkfi_sdk::crypto::PublicKey;
  22. use log::{error, info};
  23. use structopt_toml::{serde::Deserialize, structopt::StructOpt, StructOptToml};
  24. use url::Url;
  25. use darkfi::{
  26. async_daemonize, cli_desc,
  27. consensus::{
  28. constants::{
  29. MAINNET_BOOTSTRAP_TIMESTAMP, MAINNET_GENESIS_HASH_BYTES, MAINNET_GENESIS_TIMESTAMP,
  30. MAINNET_INITIAL_DISTRIBUTION, TESTNET_BOOTSTRAP_TIMESTAMP, TESTNET_GENESIS_HASH_BYTES,
  31. TESTNET_GENESIS_TIMESTAMP, TESTNET_INITIAL_DISTRIBUTION,
  32. },
  33. proto::{ProtocolProposal, ProtocolSync, ProtocolSyncConsensus, ProtocolTx},
  34. task::{block_sync_task, proposal_task},
  35. validator::ValidatorStatePtr,
  36. ValidatorState,
  37. },
  38. net,
  39. net::P2pPtr,
  40. rpc::{
  41. clock_sync::check_clock,
  42. jsonrpc::{
  43. ErrorCode::{InvalidParams, MethodNotFound},
  44. JsonError, JsonRequest, JsonResult,
  45. },
  46. server::{listen_and_serve, RequestHandler},
  47. },
  48. util::path::expand_path,
  49. wallet::{walletdb::init_wallet, WalletPtr},
  50. Error, Result,
  51. };
  52. mod error;
  53. use error::{server_error, RpcError};
  54. const CONFIG_FILE: &str = "darkfid_config.toml";
  55. const CONFIG_FILE_CONTENTS: &str = include_str!("../darkfid_config.toml");
  56. #[derive(Clone, Debug, Deserialize, StructOpt, StructOptToml)]
  57. #[serde(default)]
  58. #[structopt(name = "darkfid", about = cli_desc!())]
  59. struct Args {
  60. #[structopt(short, long)]
  61. /// Configuration file to use
  62. config: Option<String>,
  63. #[structopt(long, default_value = "testnet")]
  64. /// Chain to use (testnet, mainnet)
  65. chain: String,
  66. #[structopt(long)]
  67. /// Participate in consensus
  68. consensus: bool,
  69. #[structopt(long, default_value = "~/.config/darkfi/darkfid_wallet.db")]
  70. /// Path to wallet database
  71. wallet_path: String,
  72. #[structopt(long, default_value = "changeme")]
  73. /// Password for the wallet database
  74. wallet_pass: String,
  75. #[structopt(long, default_value = "~/.config/darkfi/darkfid_blockchain")]
  76. /// Path to blockchain database
  77. database: String,
  78. #[structopt(long, default_value = "tcp://127.0.0.1:8340")]
  79. /// JSON-RPC listen URL
  80. rpc_listen: Url,
  81. #[structopt(long)]
  82. /// P2P accept addresses for the consensus protocol (repeatable flag)
  83. consensus_p2p_accept: Vec<Url>,
  84. #[structopt(long)]
  85. /// P2P external addresses for the consensus protocol (repeatable flag)
  86. consensus_p2p_external: Vec<Url>,
  87. #[structopt(long, default_value = "8")]
  88. /// Connection slots for the consensus protocol
  89. consensus_slots: u32,
  90. #[structopt(long)]
  91. /// Connect to peer for the consensus protocol (repeatable flag)
  92. consensus_p2p_peer: Vec<Url>,
  93. #[structopt(long)]
  94. /// Peers JSON-RPC listen URL for clock synchronization (repeatable flag)
  95. consensus_peer_rpc: Vec<Url>,
  96. #[structopt(long)]
  97. /// Connect to seed for the consensus protocol (repeatable flag)
  98. consensus_p2p_seed: Vec<Url>,
  99. #[structopt(long)]
  100. /// Seed nodes JSON-RPC listen URL for clock synchronization (repeatable flag)
  101. consensus_seed_rpc: Vec<Url>,
  102. #[structopt(long)]
  103. /// Prefered transports of outbound connections for the consensus protocol (repeatable flag)
  104. consensus_p2p_transports: Vec<String>,
  105. #[structopt(long)]
  106. /// P2P accept addresses for the syncing protocol (repeatable flag)
  107. sync_p2p_accept: Vec<Url>,
  108. #[structopt(long)]
  109. /// P2P external addresses for the syncing protocol (repeatable flag)
  110. sync_p2p_external: Vec<Url>,
  111. #[structopt(long, default_value = "8")]
  112. /// Connection slots for the syncing protocol
  113. sync_slots: u32,
  114. #[structopt(long)]
  115. /// Connect to peer for the syncing protocol (repeatable flag)
  116. sync_p2p_peer: Vec<Url>,
  117. #[structopt(long)]
  118. /// Connect to seed for the syncing protocol (repeatable flag)
  119. sync_p2p_seed: Vec<Url>,
  120. #[structopt(long)]
  121. /// Prefered transports of outbound connections for the syncing protocol (repeatable flag)
  122. sync_p2p_transports: Vec<String>,
  123. #[structopt(long)]
  124. /// Enable localnet hosts
  125. localnet: bool,
  126. #[structopt(long)]
  127. /// Enable channel log
  128. channel_log: bool,
  129. #[structopt(long)]
  130. /// Whitelisted cashier public key (repeatable flag)
  131. cashier_pub: Vec<String>,
  132. #[structopt(long)]
  133. /// Whitelisted faucet public key (repeatable flag)
  134. faucet_pub: Vec<String>,
  135. #[structopt(long)]
  136. /// Verify system clock is correct
  137. clock_sync: bool,
  138. #[structopt(short, parse(from_occurrences))]
  139. /// Increase verbosity (-vvv supported)
  140. verbose: u8,
  141. }
  142. pub struct Darkfid {
  143. synced: Mutex<bool>, // AtomicBool is weird in Arc
  144. consensus_p2p: Option<P2pPtr>,
  145. sync_p2p: Option<P2pPtr>,
  146. wallet: WalletPtr,
  147. validator_state: ValidatorStatePtr,
  148. }
  149. // JSON-RPC methods
  150. mod rpc_blockchain;
  151. mod rpc_misc;
  152. mod rpc_tx;
  153. mod rpc_wallet;
  154. // Internal methods
  155. //mod internal;
  156. #[async_trait]
  157. impl RequestHandler for Darkfid {
  158. async fn handle_request(&self, req: JsonRequest) -> JsonResult {
  159. if !req.params.is_array() {
  160. return JsonError::new(InvalidParams, None, req.id).into()
  161. }
  162. let params = req.params.as_array().unwrap();
  163. match req.method.as_str() {
  164. // =====================
  165. // Miscellaneous methods
  166. // =====================
  167. Some("ping") => return self.misc_pong(req.id, params).await,
  168. Some("clock") => return self.misc_clock(req.id, params).await,
  169. Some("get_info") => return self.misc_get_info(req.id, params).await,
  170. Some("get_consensus_info") => return self.misc_get_consensus_info(req.id, params).await,
  171. // ==================
  172. // Blockchain methods
  173. // ==================
  174. Some("blockchain.get_slot") => return self.blockchain_get_slot(req.id, params).await,
  175. Some("blockchain.last_known_slot") => {
  176. return self.blockchain_last_known_slot(req.id, params).await
  177. }
  178. Some("blockchain.merkle_roots") => {
  179. return self.blockchain_merkle_roots(req.id, params).await
  180. }
  181. Some("blockchain.subscribe_blocks") => {
  182. return self.blockchain_subscribe_blocks(req.id, params).await
  183. }
  184. Some("blockchain.lookup_zkas") => {
  185. return self.blockchain_lookup_zkas(req.id, params).await
  186. }
  187. // ===================
  188. // Transaction methods
  189. // ===================
  190. Some("tx.broadcast") => return self.tx_broadcast(req.id, params).await,
  191. // ==============
  192. // Wallet methods
  193. // ==============
  194. Some("wallet.exec_sql") => return self.wallet_exec_sql(req.id, params).await,
  195. Some("wallet.query_row_single") => {
  196. return self.wallet_query_row_single(req.id, params).await
  197. }
  198. Some("wallet.query_row_multi") => {
  199. return self.wallet_query_row_multi(req.id, params).await
  200. }
  201. // ==============
  202. // Invalid method
  203. // ==============
  204. Some(_) | None => return JsonError::new(MethodNotFound, None, req.id).into(),
  205. }
  206. }
  207. }
  208. impl Darkfid {
  209. pub async fn new(
  210. validator_state: ValidatorStatePtr,
  211. consensus_p2p: Option<P2pPtr>,
  212. sync_p2p: Option<P2pPtr>,
  213. wallet: WalletPtr,
  214. ) -> Self {
  215. Self { synced: Mutex::new(false), consensus_p2p, sync_p2p, wallet, validator_state }
  216. }
  217. }
  218. async_daemonize!(realmain);
  219. async fn realmain(args: Args, ex: Arc<smol::Executor<'_>>) -> Result<()> {
  220. if args.consensus && args.clock_sync {
  221. // We verify that if peer/seed nodes are configured, their rpc config also exists
  222. if ((!args.consensus_p2p_peer.is_empty() && args.consensus_peer_rpc.is_empty()) ||
  223. (args.consensus_p2p_peer.is_empty() && !args.consensus_peer_rpc.is_empty())) ||
  224. ((!args.consensus_p2p_seed.is_empty() && args.consensus_seed_rpc.is_empty()) ||
  225. (args.consensus_p2p_seed.is_empty() && !args.consensus_seed_rpc.is_empty()))
  226. {
  227. error!(
  228. "Consensus peer/seed nodes misconfigured: both p2p and rpc urls must be present"
  229. );
  230. return Err(Error::ConfigInvalid)
  231. }
  232. // We verify that the system clock is valid before initializing
  233. let peers = [&args.consensus_peer_rpc[..], &args.consensus_seed_rpc[..]].concat();
  234. if (check_clock(&peers).await).is_err() {
  235. error!("System clock is invalid, terminating...");
  236. return Err(Error::InvalidClock)
  237. };
  238. }
  239. // We use this handler to block this function after detaching all
  240. // tasks, and to catch a shutdown signal, where we can clean up and
  241. // exit gracefully.
  242. let (signal, shutdown) = smol::channel::bounded::<()>(1);
  243. ctrlc::set_handler(move || {
  244. async_std::task::block_on(signal.send(())).unwrap();
  245. })
  246. .unwrap();
  247. // Initialize or load wallet
  248. let wallet = init_wallet(&args.wallet_path, &args.wallet_pass).await?;
  249. // Initialize or open sled database
  250. // TODO: Use proper OsPath here, not {}/{}
  251. let db_path = format!("{}/{}", expand_path(&args.database)?.to_str().unwrap(), args.chain);
  252. let sled_db = sled::open(&db_path)?;
  253. // Initialize validator state
  254. let (bootstrap_ts, genesis_ts, genesis_data, initial_distribution) = match args.chain.as_str() {
  255. "mainnet" => (
  256. *MAINNET_BOOTSTRAP_TIMESTAMP,
  257. *MAINNET_GENESIS_TIMESTAMP,
  258. *MAINNET_GENESIS_HASH_BYTES,
  259. *MAINNET_INITIAL_DISTRIBUTION,
  260. ),
  261. "testnet" => (
  262. *TESTNET_BOOTSTRAP_TIMESTAMP,
  263. *TESTNET_GENESIS_TIMESTAMP,
  264. *TESTNET_GENESIS_HASH_BYTES,
  265. *TESTNET_INITIAL_DISTRIBUTION,
  266. ),
  267. x => {
  268. error!("Unsupported chain `{}`", x);
  269. return Err(Error::UnsupportedChain)
  270. }
  271. };
  272. // Parse faucet addresses
  273. let mut faucet_pubkeys = vec![];
  274. for i in args.cashier_pub {
  275. let pk = PublicKey::from_str(&i)?;
  276. faucet_pubkeys.push(pk);
  277. }
  278. for i in args.faucet_pub {
  279. let pk = PublicKey::from_str(&i)?;
  280. faucet_pubkeys.push(pk);
  281. }
  282. // Initialize validator state
  283. let state = ValidatorState::new(
  284. &sled_db,
  285. bootstrap_ts,
  286. genesis_ts,
  287. genesis_data,
  288. initial_distribution,
  289. wallet.clone(),
  290. faucet_pubkeys,
  291. args.consensus,
  292. )
  293. .await?;
  294. let sync_p2p = {
  295. info!("Registering block sync P2P protocols...");
  296. let sync_network_settings = net::Settings {
  297. inbound: args.sync_p2p_accept,
  298. outbound_connections: args.sync_slots,
  299. external_addr: args.sync_p2p_external,
  300. peers: args.sync_p2p_peer.clone(),
  301. seeds: args.sync_p2p_seed.clone(),
  302. outbound_transports: net::settings::get_outbound_transports(args.sync_p2p_transports),
  303. localnet: args.localnet,
  304. channel_log: args.channel_log,
  305. ..Default::default()
  306. };
  307. let p2p = net::P2p::new(sync_network_settings).await;
  308. let registry = p2p.protocol_registry();
  309. let _state = state.clone();
  310. registry
  311. .register(net::SESSION_ALL, move |channel, p2p| {
  312. let state = _state.clone();
  313. async move {
  314. ProtocolSync::init(channel, state, p2p, args.consensus)
  315. .await
  316. .unwrap()
  317. }
  318. })
  319. .await;
  320. let _state = state.clone();
  321. registry
  322. .register(net::SESSION_ALL, move |channel, p2p| {
  323. let state = _state.clone();
  324. async move { ProtocolTx::init(channel, state, p2p).await.unwrap() }
  325. })
  326. .await;
  327. Some(p2p)
  328. };
  329. // P2P network settings for the consensus protocol
  330. let consensus_p2p = {
  331. if !args.consensus {
  332. None
  333. } else {
  334. info!("Registering consensus P2P protocols...");
  335. let consensus_network_settings = net::Settings {
  336. inbound: args.consensus_p2p_accept,
  337. outbound_connections: args.consensus_slots,
  338. external_addr: args.consensus_p2p_external,
  339. peers: args.consensus_p2p_peer.clone(),
  340. seeds: args.consensus_p2p_seed.clone(),
  341. outbound_transports: net::settings::get_outbound_transports(
  342. args.consensus_p2p_transports,
  343. ),
  344. localnet: args.localnet,
  345. channel_log: args.channel_log,
  346. ..Default::default()
  347. };
  348. let p2p = net::P2p::new(consensus_network_settings).await;
  349. let registry = p2p.protocol_registry();
  350. let _state = state.clone();
  351. registry
  352. .register(net::SESSION_ALL, move |channel, p2p| {
  353. let state = _state.clone();
  354. async move { ProtocolProposal::init(channel, state, p2p).await.unwrap() }
  355. })
  356. .await;
  357. let _state = state.clone();
  358. registry
  359. .register(net::SESSION_ALL, move |channel, p2p| {
  360. let state = _state.clone();
  361. async move { ProtocolSyncConsensus::init(channel, state, p2p).await.unwrap() }
  362. })
  363. .await;
  364. Some(p2p)
  365. }
  366. };
  367. // Initialize program state
  368. let darkfid =
  369. Darkfid::new(state.clone(), consensus_p2p.clone(), sync_p2p.clone(), wallet.clone()).await;
  370. let darkfid = Arc::new(darkfid);
  371. // JSON-RPC server
  372. info!("Starting JSON-RPC server");
  373. let _ex = ex.clone();
  374. ex.spawn(listen_and_serve(args.rpc_listen, darkfid.clone(), _ex)).detach();
  375. info!("Starting sync P2P network");
  376. sync_p2p.clone().unwrap().start(ex.clone()).await?;
  377. let _ex = ex.clone();
  378. let _sync_p2p = sync_p2p.clone();
  379. ex.spawn(async move {
  380. if let Err(e) = _sync_p2p.unwrap().run(_ex).await {
  381. error!("Failed starting sync P2P network: {}", e);
  382. }
  383. })
  384. .detach();
  385. info!("Waiting for sync P2P outbound connections");
  386. sync_p2p.clone().unwrap().wait_for_outbound(ex.clone()).await?;
  387. match block_sync_task(sync_p2p.clone().unwrap(), state.clone()).await {
  388. Ok(()) => *darkfid.synced.lock().await = true,
  389. Err(e) => error!("Failed syncing blockchain: {}", e),
  390. }
  391. // Consensus protocol
  392. if args.consensus && *darkfid.synced.lock().await {
  393. info!("Starting consensus P2P network");
  394. consensus_p2p.clone().unwrap().start(ex.clone()).await?;
  395. let _ex = ex.clone();
  396. let _consensus_p2p = consensus_p2p.clone();
  397. ex.spawn(async move {
  398. if let Err(e) = _consensus_p2p.unwrap().run(_ex).await {
  399. error!("Failed starting consensus P2P network: {}", e);
  400. }
  401. })
  402. .detach();
  403. info!("Waiting for consensus P2P outbound connections");
  404. consensus_p2p.clone().unwrap().wait_for_outbound(ex.clone()).await?;
  405. info!("Starting consensus protocol task");
  406. let _ex = ex.clone();
  407. ex.spawn(proposal_task(consensus_p2p.unwrap(), sync_p2p.unwrap(), state, _ex)).detach();
  408. } else {
  409. info!("Not starting consensus P2P network");
  410. }
  411. // Wait for SIGINT
  412. shutdown.recv().await?;
  413. print!("\r");
  414. info!("Caught termination signal, cleaning up and exiting...");
  415. info!("Flushing sled database...");
  416. let flushed_bytes = sled_db.flush_async().await?;
  417. info!("Flushed {} bytes", flushed_bytes);
  418. info!("Closing wallet connection...");
  419. wallet.conn.close().await;
  420. info!("Closed wallet connection");
  421. Ok(())
  422. }