main.rs 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502
  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.lookup_zkas") => {
  186. return self.blockchain_lookup_zkas(req.id, params).await
  187. }
  188. // ===================
  189. // Transaction methods
  190. // ===================
  191. Some("tx.simulate") => return self.tx_simulate(req.id, params).await,
  192. Some("tx.broadcast") => return self.tx_broadcast(req.id, params).await,
  193. // ==============
  194. // Wallet methods
  195. // ==============
  196. Some("wallet.exec_sql") => return self.wallet_exec_sql(req.id, params).await,
  197. Some("wallet.query_row_single") => {
  198. return self.wallet_query_row_single(req.id, params).await
  199. }
  200. Some("wallet.query_row_multi") => {
  201. return self.wallet_query_row_multi(req.id, params).await
  202. }
  203. // ==============
  204. // Invalid method
  205. // ==============
  206. Some(_) | None => return JsonError::new(MethodNotFound, None, req.id).into(),
  207. }
  208. }
  209. }
  210. impl Darkfid {
  211. pub async fn new(
  212. validator_state: ValidatorStatePtr,
  213. consensus_p2p: Option<P2pPtr>,
  214. sync_p2p: Option<P2pPtr>,
  215. wallet: WalletPtr,
  216. ) -> Self {
  217. Self { synced: Mutex::new(false), consensus_p2p, sync_p2p, wallet, validator_state }
  218. }
  219. }
  220. async_daemonize!(realmain);
  221. async fn realmain(args: Args, ex: Arc<smol::Executor<'_>>) -> Result<()> {
  222. if args.consensus && args.clock_sync {
  223. // We verify that if peer/seed nodes are configured, their rpc config also exists
  224. if ((!args.consensus_p2p_peer.is_empty() && args.consensus_peer_rpc.is_empty()) ||
  225. (args.consensus_p2p_peer.is_empty() && !args.consensus_peer_rpc.is_empty())) ||
  226. ((!args.consensus_p2p_seed.is_empty() && args.consensus_seed_rpc.is_empty()) ||
  227. (args.consensus_p2p_seed.is_empty() && !args.consensus_seed_rpc.is_empty()))
  228. {
  229. error!(
  230. "Consensus peer/seed nodes misconfigured: both p2p and rpc urls must be present"
  231. );
  232. return Err(Error::ConfigInvalid)
  233. }
  234. // We verify that the system clock is valid before initializing
  235. let peers = [&args.consensus_peer_rpc[..], &args.consensus_seed_rpc[..]].concat();
  236. if (check_clock(&peers).await).is_err() {
  237. error!("System clock is invalid, terminating...");
  238. return Err(Error::InvalidClock)
  239. };
  240. }
  241. // We use this handler to block this function after detaching all
  242. // tasks, and to catch a shutdown signal, where we can clean up and
  243. // exit gracefully.
  244. let (signal, shutdown) = smol::channel::bounded::<()>(1);
  245. ctrlc::set_handler(move || {
  246. async_std::task::block_on(signal.send(())).unwrap();
  247. })
  248. .unwrap();
  249. // Initialize or load wallet
  250. let wallet = init_wallet(&args.wallet_path, &args.wallet_pass).await?;
  251. // Initialize or open sled database
  252. let db_path =
  253. Path::new(expand_path(&args.database)?.to_str().unwrap()).join(args.chain.clone());
  254. let sled_db = sled::open(&db_path)?;
  255. // Initialize validator state
  256. let (bootstrap_ts, genesis_ts, genesis_data, initial_distribution) = match args.chain.as_str() {
  257. "mainnet" => (
  258. *MAINNET_BOOTSTRAP_TIMESTAMP,
  259. *MAINNET_GENESIS_TIMESTAMP,
  260. *MAINNET_GENESIS_HASH_BYTES,
  261. *MAINNET_INITIAL_DISTRIBUTION,
  262. ),
  263. "testnet" => (
  264. *TESTNET_BOOTSTRAP_TIMESTAMP,
  265. *TESTNET_GENESIS_TIMESTAMP,
  266. *TESTNET_GENESIS_HASH_BYTES,
  267. *TESTNET_INITIAL_DISTRIBUTION,
  268. ),
  269. x => {
  270. error!("Unsupported chain `{}`", x);
  271. return Err(Error::UnsupportedChain)
  272. }
  273. };
  274. // Parse faucet addresses
  275. let mut faucet_pubkeys = vec![];
  276. for i in args.cashier_pub {
  277. let pk = PublicKey::from_str(&i)?;
  278. faucet_pubkeys.push(pk);
  279. }
  280. for i in args.faucet_pub {
  281. let pk = PublicKey::from_str(&i)?;
  282. faucet_pubkeys.push(pk);
  283. }
  284. if args.single_node {
  285. info!("Node is configured to run in single-node mode!");
  286. }
  287. // Initialize validator state
  288. let state = ValidatorState::new(
  289. &sled_db,
  290. bootstrap_ts,
  291. genesis_ts,
  292. genesis_data,
  293. initial_distribution,
  294. wallet.clone(),
  295. faucet_pubkeys,
  296. args.consensus,
  297. args.single_node,
  298. )
  299. .await?;
  300. let sync_p2p = {
  301. info!("Registering block sync P2P protocols...");
  302. let sync_network_settings = net::Settings {
  303. inbound: args.sync_p2p_accept,
  304. outbound_connections: args.sync_slots,
  305. external_addr: args.sync_p2p_external,
  306. peers: args.sync_p2p_peer.clone(),
  307. seeds: args.sync_p2p_seed.clone(),
  308. outbound_transports: net::settings::get_outbound_transports(args.sync_p2p_transports),
  309. localnet: args.localnet,
  310. channel_log: args.channel_log,
  311. ..Default::default()
  312. };
  313. let p2p = net::P2p::new(sync_network_settings).await;
  314. let registry = p2p.protocol_registry();
  315. let _state = state.clone();
  316. registry
  317. .register(net::SESSION_ALL, move |channel, p2p| {
  318. let state = _state.clone();
  319. async move {
  320. ProtocolSync::init(channel, state, p2p, args.consensus)
  321. .await
  322. .unwrap()
  323. }
  324. })
  325. .await;
  326. let _state = state.clone();
  327. registry
  328. .register(net::SESSION_ALL, move |channel, p2p| {
  329. let state = _state.clone();
  330. async move { ProtocolTx::init(channel, state, p2p).await.unwrap() }
  331. })
  332. .await;
  333. Some(p2p)
  334. };
  335. // P2P network settings for the consensus protocol
  336. let consensus_p2p = {
  337. if !args.consensus {
  338. None
  339. } else {
  340. info!("Registering consensus P2P protocols...");
  341. let consensus_network_settings = net::Settings {
  342. inbound: args.consensus_p2p_accept,
  343. outbound_connections: args.consensus_slots,
  344. external_addr: args.consensus_p2p_external,
  345. peers: args.consensus_p2p_peer.clone(),
  346. seeds: args.consensus_p2p_seed.clone(),
  347. outbound_transports: net::settings::get_outbound_transports(
  348. args.consensus_p2p_transports,
  349. ),
  350. localnet: args.localnet,
  351. channel_log: args.channel_log,
  352. ..Default::default()
  353. };
  354. let p2p = net::P2p::new(consensus_network_settings).await;
  355. let registry = p2p.protocol_registry();
  356. let _state = state.clone();
  357. registry
  358. .register(net::SESSION_ALL, move |channel, p2p| {
  359. let state = _state.clone();
  360. async move { ProtocolProposal::init(channel, state, p2p).await.unwrap() }
  361. })
  362. .await;
  363. let _state = state.clone();
  364. registry
  365. .register(net::SESSION_ALL, move |channel, p2p| {
  366. let state = _state.clone();
  367. async move { ProtocolSyncConsensus::init(channel, state, p2p).await.unwrap() }
  368. })
  369. .await;
  370. Some(p2p)
  371. }
  372. };
  373. // Initialize program state
  374. let darkfid =
  375. Darkfid::new(state.clone(), consensus_p2p.clone(), sync_p2p.clone(), wallet.clone()).await;
  376. let darkfid = Arc::new(darkfid);
  377. // JSON-RPC server
  378. info!("Starting JSON-RPC server");
  379. let _ex = ex.clone();
  380. ex.spawn(listen_and_serve(args.rpc_listen, darkfid.clone(), _ex)).detach();
  381. info!("Starting sync P2P network");
  382. sync_p2p.clone().unwrap().start(ex.clone()).await?;
  383. let _ex = ex.clone();
  384. let _sync_p2p = sync_p2p.clone();
  385. ex.spawn(async move {
  386. if let Err(e) = _sync_p2p.unwrap().run(_ex).await {
  387. error!("Failed starting sync P2P network: {}", e);
  388. }
  389. })
  390. .detach();
  391. info!("Waiting for sync P2P outbound connections");
  392. sync_p2p.clone().unwrap().wait_for_outbound(ex.clone()).await?;
  393. match block_sync_task(sync_p2p.clone().unwrap(), state.clone()).await {
  394. Ok(()) => *darkfid.synced.lock().await = true,
  395. Err(e) => error!("Failed syncing blockchain: {}", e),
  396. }
  397. // Consensus protocol
  398. if args.consensus && *darkfid.synced.lock().await {
  399. info!("Starting consensus P2P network");
  400. consensus_p2p.clone().unwrap().start(ex.clone()).await?;
  401. let _ex = ex.clone();
  402. let _consensus_p2p = consensus_p2p.clone();
  403. ex.spawn(async move {
  404. if let Err(e) = _consensus_p2p.unwrap().run(_ex).await {
  405. error!("Failed starting consensus P2P network: {}", e);
  406. }
  407. })
  408. .detach();
  409. info!("Waiting for consensus P2P outbound connections");
  410. consensus_p2p.clone().unwrap().wait_for_outbound(ex.clone()).await?;
  411. info!("Starting consensus protocol task");
  412. let _ex = ex.clone();
  413. ex.spawn(proposal_task(consensus_p2p.unwrap(), sync_p2p.unwrap(), state, _ex)).detach();
  414. } else {
  415. info!("Not starting consensus P2P network");
  416. }
  417. // Wait for SIGINT
  418. shutdown.recv().await?;
  419. print!("\r");
  420. info!("Caught termination signal, cleaning up and exiting...");
  421. info!("Flushing sled database...");
  422. let flushed_bytes = sled_db.flush_async().await?;
  423. info!("Flushed {} bytes", flushed_bytes);
  424. info!("Closing wallet connection...");
  425. wallet.conn.close().await;
  426. info!("Closed wallet connection");
  427. Ok(())
  428. }