main.rs 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505
  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::{path::Path, 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)]
  70. /// Enable single-node mode for local testing
  71. single_node: bool,
  72. #[structopt(long, default_value = "~/.config/darkfi/darkfid_wallet.db")]
  73. /// Path to wallet database
  74. wallet_path: String,
  75. #[structopt(long, default_value = "changeme")]
  76. /// Password for the wallet database
  77. wallet_pass: String,
  78. #[structopt(long, default_value = "~/.config/darkfi/darkfid_blockchain")]
  79. /// Path to blockchain database
  80. database: String,
  81. #[structopt(long, default_value = "tcp://127.0.0.1:8340")]
  82. /// JSON-RPC listen URL
  83. rpc_listen: Url,
  84. #[structopt(long)]
  85. /// P2P accept addresses for the consensus protocol (repeatable flag)
  86. consensus_p2p_accept: Vec<Url>,
  87. #[structopt(long)]
  88. /// P2P external addresses for the consensus protocol (repeatable flag)
  89. consensus_p2p_external: Vec<Url>,
  90. #[structopt(long, default_value = "8")]
  91. /// Connection slots for the consensus protocol
  92. consensus_slots: u32,
  93. #[structopt(long)]
  94. /// Connect to peer for the consensus protocol (repeatable flag)
  95. consensus_p2p_peer: Vec<Url>,
  96. #[structopt(long)]
  97. /// Peers JSON-RPC listen URL for clock synchronization (repeatable flag)
  98. consensus_peer_rpc: Vec<Url>,
  99. #[structopt(long)]
  100. /// Connect to seed for the consensus protocol (repeatable flag)
  101. consensus_p2p_seed: Vec<Url>,
  102. #[structopt(long)]
  103. /// Seed nodes JSON-RPC listen URL for clock synchronization (repeatable flag)
  104. consensus_seed_rpc: Vec<Url>,
  105. #[structopt(long)]
  106. /// Prefered transports of outbound connections for the consensus protocol (repeatable flag)
  107. consensus_p2p_transports: Vec<String>,
  108. #[structopt(long)]
  109. /// P2P accept addresses for the syncing protocol (repeatable flag)
  110. sync_p2p_accept: Vec<Url>,
  111. #[structopt(long)]
  112. /// P2P external addresses for the syncing protocol (repeatable flag)
  113. sync_p2p_external: Vec<Url>,
  114. #[structopt(long, default_value = "8")]
  115. /// Connection slots for the syncing protocol
  116. sync_slots: u32,
  117. #[structopt(long)]
  118. /// Connect to peer for the syncing protocol (repeatable flag)
  119. sync_p2p_peer: Vec<Url>,
  120. #[structopt(long)]
  121. /// Connect to seed for the syncing protocol (repeatable flag)
  122. sync_p2p_seed: Vec<Url>,
  123. #[structopt(long)]
  124. /// Prefered transports of outbound connections for the syncing protocol (repeatable flag)
  125. sync_p2p_transports: Vec<String>,
  126. #[structopt(long)]
  127. /// Enable localnet hosts
  128. localnet: bool,
  129. #[structopt(long)]
  130. /// Enable channel log
  131. channel_log: bool,
  132. #[structopt(long)]
  133. /// Whitelisted cashier public key (repeatable flag)
  134. cashier_pub: Vec<String>,
  135. #[structopt(long)]
  136. /// Whitelisted faucet public key (repeatable flag)
  137. faucet_pub: Vec<String>,
  138. #[structopt(long)]
  139. /// Verify system clock is correct
  140. clock_sync: bool,
  141. #[structopt(short, parse(from_occurrences))]
  142. /// Increase verbosity (-vvv supported)
  143. verbose: u8,
  144. }
  145. pub struct Darkfid {
  146. synced: Mutex<bool>, // AtomicBool is weird in Arc
  147. consensus_p2p: Option<P2pPtr>,
  148. sync_p2p: Option<P2pPtr>,
  149. wallet: WalletPtr,
  150. validator_state: ValidatorStatePtr,
  151. }
  152. // JSON-RPC methods
  153. mod rpc_blockchain;
  154. mod rpc_misc;
  155. mod rpc_tx;
  156. mod rpc_wallet;
  157. // Internal methods
  158. //mod internal;
  159. #[async_trait]
  160. impl RequestHandler for Darkfid {
  161. async fn handle_request(&self, req: JsonRequest) -> JsonResult {
  162. if !req.params.is_array() {
  163. return JsonError::new(InvalidParams, None, req.id).into()
  164. }
  165. let params = req.params.as_array().unwrap();
  166. match req.method.as_str() {
  167. // =====================
  168. // Miscellaneous methods
  169. // =====================
  170. Some("ping") => return self.misc_pong(req.id, params).await,
  171. Some("clock") => return self.misc_clock(req.id, params).await,
  172. Some("get_info") => return self.misc_get_info(req.id, params).await,
  173. Some("get_consensus_info") => return self.misc_get_consensus_info(req.id, params).await,
  174. // ==================
  175. // Blockchain methods
  176. // ==================
  177. Some("blockchain.get_slot") => return self.blockchain_get_slot(req.id, params).await,
  178. Some("blockchain.get_tx") => return self.blockchain_get_tx(req.id, params).await,
  179. Some("blockchain.last_known_slot") => {
  180. return self.blockchain_last_known_slot(req.id, params).await
  181. }
  182. Some("blockchain.subscribe_blocks") => {
  183. return self.blockchain_subscribe_blocks(req.id, params).await
  184. }
  185. Some("blockchain.subscribe_err_txs") => {
  186. return self.blockchain_subscribe_err_txs(req.id, params).await
  187. }
  188. Some("blockchain.lookup_zkas") => {
  189. return self.blockchain_lookup_zkas(req.id, params).await
  190. }
  191. // ===================
  192. // Transaction methods
  193. // ===================
  194. Some("tx.simulate") => return self.tx_simulate(req.id, params).await,
  195. Some("tx.broadcast") => return self.tx_broadcast(req.id, params).await,
  196. // ==============
  197. // Wallet methods
  198. // ==============
  199. Some("wallet.exec_sql") => return self.wallet_exec_sql(req.id, params).await,
  200. Some("wallet.query_row_single") => {
  201. return self.wallet_query_row_single(req.id, params).await
  202. }
  203. Some("wallet.query_row_multi") => {
  204. return self.wallet_query_row_multi(req.id, params).await
  205. }
  206. // ==============
  207. // Invalid method
  208. // ==============
  209. Some(_) | None => return JsonError::new(MethodNotFound, None, req.id).into(),
  210. }
  211. }
  212. }
  213. impl Darkfid {
  214. pub async fn new(
  215. validator_state: ValidatorStatePtr,
  216. consensus_p2p: Option<P2pPtr>,
  217. sync_p2p: Option<P2pPtr>,
  218. wallet: WalletPtr,
  219. ) -> Self {
  220. Self { synced: Mutex::new(false), consensus_p2p, sync_p2p, wallet, validator_state }
  221. }
  222. }
  223. async_daemonize!(realmain);
  224. async fn realmain(args: Args, ex: Arc<smol::Executor<'_>>) -> Result<()> {
  225. if args.consensus && args.clock_sync {
  226. // We verify that if peer/seed nodes are configured, their rpc config also exists
  227. if ((!args.consensus_p2p_peer.is_empty() && args.consensus_peer_rpc.is_empty()) ||
  228. (args.consensus_p2p_peer.is_empty() && !args.consensus_peer_rpc.is_empty())) ||
  229. ((!args.consensus_p2p_seed.is_empty() && args.consensus_seed_rpc.is_empty()) ||
  230. (args.consensus_p2p_seed.is_empty() && !args.consensus_seed_rpc.is_empty()))
  231. {
  232. error!(
  233. "Consensus peer/seed nodes misconfigured: both p2p and rpc urls must be present"
  234. );
  235. return Err(Error::ConfigInvalid)
  236. }
  237. // We verify that the system clock is valid before initializing
  238. let peers = [&args.consensus_peer_rpc[..], &args.consensus_seed_rpc[..]].concat();
  239. if (check_clock(&peers).await).is_err() {
  240. error!("System clock is invalid, terminating...");
  241. return Err(Error::InvalidClock)
  242. };
  243. }
  244. // We use this handler to block this function after detaching all
  245. // tasks, and to catch a shutdown signal, where we can clean up and
  246. // exit gracefully.
  247. let (signal, shutdown) = smol::channel::bounded::<()>(1);
  248. ctrlc::set_handler(move || {
  249. async_std::task::block_on(signal.send(())).unwrap();
  250. })
  251. .unwrap();
  252. // Initialize or load wallet
  253. let wallet = init_wallet(&args.wallet_path, &args.wallet_pass).await?;
  254. // Initialize or open sled database
  255. let db_path =
  256. Path::new(expand_path(&args.database)?.to_str().unwrap()).join(args.chain.clone());
  257. let sled_db = sled::open(&db_path)?;
  258. // Initialize validator state
  259. let (bootstrap_ts, genesis_ts, genesis_data, initial_distribution) = match args.chain.as_str() {
  260. "mainnet" => (
  261. *MAINNET_BOOTSTRAP_TIMESTAMP,
  262. *MAINNET_GENESIS_TIMESTAMP,
  263. *MAINNET_GENESIS_HASH_BYTES,
  264. *MAINNET_INITIAL_DISTRIBUTION,
  265. ),
  266. "testnet" => (
  267. *TESTNET_BOOTSTRAP_TIMESTAMP,
  268. *TESTNET_GENESIS_TIMESTAMP,
  269. *TESTNET_GENESIS_HASH_BYTES,
  270. *TESTNET_INITIAL_DISTRIBUTION,
  271. ),
  272. x => {
  273. error!("Unsupported chain `{}`", x);
  274. return Err(Error::UnsupportedChain)
  275. }
  276. };
  277. // Parse faucet addresses
  278. let mut faucet_pubkeys = vec![];
  279. for i in args.cashier_pub {
  280. let pk = PublicKey::from_str(&i)?;
  281. faucet_pubkeys.push(pk);
  282. }
  283. for i in args.faucet_pub {
  284. let pk = PublicKey::from_str(&i)?;
  285. faucet_pubkeys.push(pk);
  286. }
  287. if args.single_node {
  288. info!("Node is configured to run in single-node mode!");
  289. }
  290. // Initialize validator state
  291. let state = ValidatorState::new(
  292. &sled_db,
  293. bootstrap_ts,
  294. genesis_ts,
  295. genesis_data,
  296. initial_distribution,
  297. wallet.clone(),
  298. faucet_pubkeys,
  299. args.consensus,
  300. args.single_node,
  301. )
  302. .await?;
  303. let sync_p2p = {
  304. info!("Registering block sync P2P protocols...");
  305. let sync_network_settings = net::Settings {
  306. inbound: args.sync_p2p_accept,
  307. outbound_connections: args.sync_slots,
  308. external_addr: args.sync_p2p_external,
  309. peers: args.sync_p2p_peer.clone(),
  310. seeds: args.sync_p2p_seed.clone(),
  311. outbound_transports: net::settings::get_outbound_transports(args.sync_p2p_transports),
  312. localnet: args.localnet,
  313. channel_log: args.channel_log,
  314. ..Default::default()
  315. };
  316. let p2p = net::P2p::new(sync_network_settings).await;
  317. let registry = p2p.protocol_registry();
  318. let _state = state.clone();
  319. registry
  320. .register(net::SESSION_ALL, move |channel, p2p| {
  321. let state = _state.clone();
  322. async move {
  323. ProtocolSync::init(channel, state, p2p, args.consensus)
  324. .await
  325. .unwrap()
  326. }
  327. })
  328. .await;
  329. let _state = state.clone();
  330. registry
  331. .register(net::SESSION_ALL, move |channel, p2p| {
  332. let state = _state.clone();
  333. async move { ProtocolTx::init(channel, state, p2p).await.unwrap() }
  334. })
  335. .await;
  336. Some(p2p)
  337. };
  338. // P2P network settings for the consensus protocol
  339. let consensus_p2p = {
  340. if !args.consensus {
  341. None
  342. } else {
  343. info!("Registering consensus P2P protocols...");
  344. let consensus_network_settings = net::Settings {
  345. inbound: args.consensus_p2p_accept,
  346. outbound_connections: args.consensus_slots,
  347. external_addr: args.consensus_p2p_external,
  348. peers: args.consensus_p2p_peer.clone(),
  349. seeds: args.consensus_p2p_seed.clone(),
  350. outbound_transports: net::settings::get_outbound_transports(
  351. args.consensus_p2p_transports,
  352. ),
  353. localnet: args.localnet,
  354. channel_log: args.channel_log,
  355. ..Default::default()
  356. };
  357. let p2p = net::P2p::new(consensus_network_settings).await;
  358. let registry = p2p.protocol_registry();
  359. let _state = state.clone();
  360. registry
  361. .register(net::SESSION_ALL, move |channel, p2p| {
  362. let state = _state.clone();
  363. async move { ProtocolProposal::init(channel, state, p2p).await.unwrap() }
  364. })
  365. .await;
  366. let _state = state.clone();
  367. registry
  368. .register(net::SESSION_ALL, move |channel, p2p| {
  369. let state = _state.clone();
  370. async move { ProtocolSyncConsensus::init(channel, state, p2p).await.unwrap() }
  371. })
  372. .await;
  373. Some(p2p)
  374. }
  375. };
  376. // Initialize program state
  377. let darkfid =
  378. Darkfid::new(state.clone(), consensus_p2p.clone(), sync_p2p.clone(), wallet.clone()).await;
  379. let darkfid = Arc::new(darkfid);
  380. // JSON-RPC server
  381. info!("Starting JSON-RPC server");
  382. let _ex = ex.clone();
  383. ex.spawn(listen_and_serve(args.rpc_listen, darkfid.clone(), _ex)).detach();
  384. info!("Starting sync P2P network");
  385. sync_p2p.clone().unwrap().start(ex.clone()).await?;
  386. let _ex = ex.clone();
  387. let _sync_p2p = sync_p2p.clone();
  388. ex.spawn(async move {
  389. if let Err(e) = _sync_p2p.unwrap().run(_ex).await {
  390. error!("Failed starting sync P2P network: {}", e);
  391. }
  392. })
  393. .detach();
  394. info!("Waiting for sync P2P outbound connections");
  395. sync_p2p.clone().unwrap().wait_for_outbound(ex.clone()).await?;
  396. match block_sync_task(sync_p2p.clone().unwrap(), state.clone()).await {
  397. Ok(()) => *darkfid.synced.lock().await = true,
  398. Err(e) => error!("Failed syncing blockchain: {}", e),
  399. }
  400. // Consensus protocol
  401. if args.consensus && *darkfid.synced.lock().await {
  402. info!("Starting consensus P2P network");
  403. consensus_p2p.clone().unwrap().start(ex.clone()).await?;
  404. let _ex = ex.clone();
  405. let _consensus_p2p = consensus_p2p.clone();
  406. ex.spawn(async move {
  407. if let Err(e) = _consensus_p2p.unwrap().run(_ex).await {
  408. error!("Failed starting consensus P2P network: {}", e);
  409. }
  410. })
  411. .detach();
  412. info!("Waiting for consensus P2P outbound connections");
  413. consensus_p2p.clone().unwrap().wait_for_outbound(ex.clone()).await?;
  414. info!("Starting consensus protocol task");
  415. let _ex = ex.clone();
  416. ex.spawn(proposal_task(consensus_p2p.unwrap(), sync_p2p.unwrap(), state, _ex)).detach();
  417. } else {
  418. info!("Not starting consensus P2P network");
  419. }
  420. // Wait for SIGINT
  421. shutdown.recv().await?;
  422. print!("\r");
  423. info!("Caught termination signal, cleaning up and exiting...");
  424. info!("Flushing sled database...");
  425. let flushed_bytes = sled_db.flush_async().await?;
  426. info!("Flushed {} bytes", flushed_bytes);
  427. info!("Closing wallet connection...");
  428. wallet.conn.close().await;
  429. info!("Closed wallet connection");
  430. Ok(())
  431. }