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::{
  20. stream::StreamExt,
  21. sync::{Arc, Mutex},
  22. };
  23. use async_trait::async_trait;
  24. use darkfi_sdk::crypto::PublicKey;
  25. use log::{error, info};
  26. use structopt_toml::{serde::Deserialize, structopt::StructOpt, StructOptToml};
  27. use url::Url;
  28. use darkfi::{
  29. async_daemonize, cli_desc,
  30. consensus::{
  31. constants::{
  32. MAINNET_BOOTSTRAP_TIMESTAMP, MAINNET_GENESIS_HASH_BYTES, MAINNET_GENESIS_TIMESTAMP,
  33. MAINNET_INITIAL_DISTRIBUTION, TESTNET_BOOTSTRAP_TIMESTAMP, TESTNET_GENESIS_HASH_BYTES,
  34. TESTNET_GENESIS_TIMESTAMP, TESTNET_INITIAL_DISTRIBUTION,
  35. },
  36. proto::{ProtocolProposal, ProtocolSync, ProtocolSyncConsensus, ProtocolTx},
  37. task::{block_sync_task, proposal_task},
  38. validator::ValidatorStatePtr,
  39. ValidatorState,
  40. },
  41. net,
  42. net::P2pPtr,
  43. rpc::{
  44. clock_sync::check_clock,
  45. jsonrpc::{
  46. ErrorCode::{InvalidParams, MethodNotFound},
  47. JsonError, JsonRequest, JsonResult,
  48. },
  49. server::{listen_and_serve, RequestHandler},
  50. },
  51. util::path::expand_path,
  52. wallet::{WalletDb, WalletPtr},
  53. Error, Result,
  54. };
  55. mod error;
  56. use error::{server_error, RpcError};
  57. const CONFIG_FILE: &str = "darkfid_config.toml";
  58. const CONFIG_FILE_CONTENTS: &str = include_str!("../darkfid_config.toml");
  59. #[derive(Clone, Debug, Deserialize, StructOpt, StructOptToml)]
  60. #[serde(default)]
  61. #[structopt(name = "darkfid", about = cli_desc!())]
  62. struct Args {
  63. #[structopt(short, long)]
  64. /// Configuration file to use
  65. config: Option<String>,
  66. #[structopt(long, default_value = "testnet")]
  67. /// Chain to use (testnet, mainnet)
  68. chain: String,
  69. #[structopt(long)]
  70. /// Participate in consensus
  71. consensus: bool,
  72. #[structopt(long)]
  73. /// Enable single-node mode for local testing
  74. single_node: bool,
  75. #[structopt(long, default_value = "~/.config/darkfi/darkfid_wallet.db")]
  76. /// Path to wallet database
  77. wallet_path: String,
  78. #[structopt(long, default_value = "changeme")]
  79. /// Password for the wallet database
  80. wallet_pass: String,
  81. #[structopt(long, default_value = "~/.config/darkfi/darkfid_blockchain")]
  82. /// Path to blockchain database
  83. database: String,
  84. #[structopt(long, default_value = "tcp://127.0.0.1:8340")]
  85. /// JSON-RPC listen URL
  86. rpc_listen: Url,
  87. #[structopt(long)]
  88. /// P2P accept addresses for the consensus protocol (repeatable flag)
  89. consensus_p2p_accept: Vec<Url>,
  90. #[structopt(long)]
  91. /// P2P external addresses for the consensus protocol (repeatable flag)
  92. consensus_p2p_external: Vec<Url>,
  93. #[structopt(long, default_value = "8")]
  94. /// Connection slots for the consensus protocol
  95. consensus_slots: usize,
  96. #[structopt(long)]
  97. /// Connect to peer for the consensus protocol (repeatable flag)
  98. consensus_p2p_peer: Vec<Url>,
  99. #[structopt(long)]
  100. /// Peers JSON-RPC listen URL for clock synchronization (repeatable flag)
  101. consensus_peer_rpc: Vec<Url>,
  102. #[structopt(long)]
  103. /// Connect to seed for the consensus protocol (repeatable flag)
  104. consensus_p2p_seed: Vec<Url>,
  105. #[structopt(long)]
  106. /// Seed nodes JSON-RPC listen URL for clock synchronization (repeatable flag)
  107. consensus_seed_rpc: Vec<Url>,
  108. #[structopt(long)]
  109. /// Prefered transports of outbound connections for the consensus protocol (repeatable flag)
  110. consensus_p2p_transports: Vec<String>,
  111. #[structopt(long)]
  112. /// P2P accept addresses for the syncing protocol (repeatable flag)
  113. sync_p2p_accept: Vec<Url>,
  114. #[structopt(long)]
  115. /// P2P external addresses for the syncing protocol (repeatable flag)
  116. sync_p2p_external: Vec<Url>,
  117. #[structopt(long, default_value = "8")]
  118. /// Connection slots for the syncing protocol
  119. sync_slots: usize,
  120. #[structopt(long)]
  121. /// Connect to peer for the syncing protocol (repeatable flag)
  122. sync_p2p_peer: Vec<Url>,
  123. #[structopt(long)]
  124. /// Connect to seed for the syncing protocol (repeatable flag)
  125. sync_p2p_seed: Vec<Url>,
  126. #[structopt(long)]
  127. /// Prefered transports of outbound connections for the syncing protocol (repeatable flag)
  128. sync_p2p_transports: Vec<String>,
  129. #[structopt(long)]
  130. /// Enable localnet hosts
  131. localnet: bool,
  132. #[structopt(long)]
  133. /// Enable channel log
  134. channel_log: bool,
  135. #[structopt(long)]
  136. /// Whitelisted cashier public key (repeatable flag)
  137. cashier_pub: Vec<String>,
  138. #[structopt(long)]
  139. /// Whitelisted faucet public key (repeatable flag)
  140. faucet_pub: Vec<String>,
  141. #[structopt(long)]
  142. /// Verify system clock is correct
  143. clock_sync: bool,
  144. #[structopt(short, long)]
  145. /// Set log file to ouput into
  146. log: Option<String>,
  147. #[structopt(short, parse(from_occurrences))]
  148. /// Increase verbosity (-vvv supported)
  149. verbose: u8,
  150. }
  151. pub struct Darkfid {
  152. synced: Mutex<bool>, // AtomicBool is weird in Arc
  153. consensus_p2p: Option<P2pPtr>,
  154. sync_p2p: Option<P2pPtr>,
  155. _wallet: WalletPtr,
  156. validator_state: ValidatorStatePtr,
  157. }
  158. // JSON-RPC methods
  159. mod rpc_blockchain;
  160. mod rpc_misc;
  161. mod rpc_tx;
  162. mod rpc_wallet;
  163. // Internal methods
  164. //mod internal;
  165. #[async_trait]
  166. impl RequestHandler for Darkfid {
  167. async fn handle_request(&self, req: JsonRequest) -> JsonResult {
  168. if !req.params.is_array() {
  169. return JsonError::new(InvalidParams, None, req.id).into()
  170. }
  171. let params = req.params.as_array().unwrap();
  172. match req.method.as_str() {
  173. // =====================
  174. // Miscellaneous methods
  175. // =====================
  176. Some("ping") => return self.misc_pong(req.id, params).await,
  177. Some("clock") => return self.misc_clock(req.id, params).await,
  178. Some("sync_dnet_switch") => return self.misc_sync_dnet_switch(req.id, params).await,
  179. Some("sync_dnet_info") => return self.misc_sync_dnet_info(req.id, params).await,
  180. Some("consensus_dnet_switch") => {
  181. return self.misc_consensus_dnet_switch(req.id, params).await
  182. }
  183. Some("consensus_dnet_info") => {
  184. return self.misc_consensus_dnet_info(req.id, params).await
  185. }
  186. // ==================
  187. // Blockchain methods
  188. // ==================
  189. Some("blockchain.get_slot") => return self.blockchain_get_slot(req.id, params).await,
  190. Some("blockchain.get_tx") => return self.blockchain_get_tx(req.id, params).await,
  191. Some("blockchain.last_known_slot") => {
  192. return self.blockchain_last_known_slot(req.id, params).await
  193. }
  194. Some("blockchain.subscribe_blocks") => {
  195. return self.blockchain_subscribe_blocks(req.id, params).await
  196. }
  197. Some("blockchain.subscribe_err_txs") => {
  198. return self.blockchain_subscribe_err_txs(req.id, params).await
  199. }
  200. Some("blockchain.lookup_zkas") => {
  201. return self.blockchain_lookup_zkas(req.id, params).await
  202. }
  203. // ===================
  204. // Transaction methods
  205. // ===================
  206. Some("tx.simulate") => return self.tx_simulate(req.id, params).await,
  207. Some("tx.broadcast") => return self.tx_broadcast(req.id, params).await,
  208. // ==============
  209. // Wallet methods
  210. // ==============
  211. Some("wallet.exec_sql") => return self.wallet_exec_sql(req.id, params).await,
  212. Some("wallet.query_row_single") => {
  213. return self.wallet_query_row_single(req.id, params).await
  214. }
  215. Some("wallet.query_row_multi") => {
  216. return self.wallet_query_row_multi(req.id, params).await
  217. }
  218. // ==============
  219. // Invalid method
  220. // ==============
  221. Some(_) | None => return JsonError::new(MethodNotFound, None, req.id).into(),
  222. }
  223. }
  224. }
  225. impl Darkfid {
  226. pub async fn new(
  227. validator_state: ValidatorStatePtr,
  228. consensus_p2p: Option<P2pPtr>,
  229. sync_p2p: Option<P2pPtr>,
  230. _wallet: WalletPtr,
  231. ) -> Self {
  232. Self { synced: Mutex::new(false), consensus_p2p, sync_p2p, _wallet, validator_state }
  233. }
  234. }
  235. async_daemonize!(realmain);
  236. async fn realmain(args: Args, ex: Arc<smol::Executor<'_>>) -> Result<()> {
  237. if args.consensus && args.clock_sync {
  238. // We verify that if peer/seed nodes are configured, their rpc config also exists
  239. if ((!args.consensus_p2p_peer.is_empty() && args.consensus_peer_rpc.is_empty()) ||
  240. (args.consensus_p2p_peer.is_empty() && !args.consensus_peer_rpc.is_empty())) ||
  241. ((!args.consensus_p2p_seed.is_empty() && args.consensus_seed_rpc.is_empty()) ||
  242. (args.consensus_p2p_seed.is_empty() && !args.consensus_seed_rpc.is_empty()))
  243. {
  244. error!(
  245. "Consensus peer/seed nodes misconfigured: both p2p and rpc urls must be present"
  246. );
  247. return Err(Error::ConfigInvalid)
  248. }
  249. // We verify that the system clock is valid before initializing
  250. let peers = [&args.consensus_peer_rpc[..], &args.consensus_seed_rpc[..]].concat();
  251. if (check_clock(&peers).await).is_err() {
  252. error!("System clock is invalid, terminating...");
  253. return Err(Error::InvalidClock)
  254. };
  255. }
  256. // Initialize or load wallet
  257. let wallet = WalletDb::new(Some(expand_path(&args.wallet_path)?), Some(&args.wallet_pass))?;
  258. // Initialize or open sled database
  259. let db_path =
  260. Path::new(expand_path(&args.database)?.to_str().unwrap()).join(args.chain.clone());
  261. let sled_db = sled::open(&db_path)?;
  262. // Initialize validator state
  263. let (bootstrap_ts, genesis_ts, genesis_data, initial_distribution) = match args.chain.as_str() {
  264. "mainnet" => (
  265. *MAINNET_BOOTSTRAP_TIMESTAMP,
  266. *MAINNET_GENESIS_TIMESTAMP,
  267. *MAINNET_GENESIS_HASH_BYTES,
  268. *MAINNET_INITIAL_DISTRIBUTION,
  269. ),
  270. "testnet" => (
  271. *TESTNET_BOOTSTRAP_TIMESTAMP,
  272. *TESTNET_GENESIS_TIMESTAMP,
  273. *TESTNET_GENESIS_HASH_BYTES,
  274. *TESTNET_INITIAL_DISTRIBUTION,
  275. ),
  276. x => {
  277. error!("Unsupported chain `{}`", x);
  278. return Err(Error::UnsupportedChain)
  279. }
  280. };
  281. // Parse faucet addresses
  282. let mut faucet_pubkeys = vec![];
  283. for i in args.cashier_pub {
  284. let pk = PublicKey::from_str(&i)?;
  285. faucet_pubkeys.push(pk);
  286. }
  287. for i in args.faucet_pub {
  288. let pk = PublicKey::from_str(&i)?;
  289. faucet_pubkeys.push(pk);
  290. }
  291. if args.single_node {
  292. info!("Node is configured to run in single-node mode!");
  293. }
  294. // Initialize validator state
  295. let state = ValidatorState::new(
  296. &sled_db,
  297. bootstrap_ts,
  298. genesis_ts,
  299. genesis_data,
  300. initial_distribution,
  301. wallet.clone(),
  302. faucet_pubkeys,
  303. args.consensus,
  304. args.single_node,
  305. )
  306. .await?;
  307. let sync_p2p = {
  308. info!("Registering block sync P2P protocols...");
  309. let sync_network_settings = net::Settings {
  310. inbound_addrs: args.sync_p2p_accept,
  311. outbound_connections: args.sync_slots,
  312. external_addrs: args.sync_p2p_external,
  313. peers: args.sync_p2p_peer.clone(),
  314. seeds: args.sync_p2p_seed.clone(),
  315. allowed_transports: args.sync_p2p_transports,
  316. localnet: args.localnet,
  317. ..Default::default()
  318. };
  319. let p2p = net::P2p::new(sync_network_settings).await;
  320. let registry = p2p.protocol_registry();
  321. let _state = state.clone();
  322. registry
  323. .register(net::SESSION_ALL, move |channel, p2p| {
  324. let state = _state.clone();
  325. async move {
  326. ProtocolSync::init(channel, state, p2p, args.consensus)
  327. .await
  328. .unwrap()
  329. }
  330. })
  331. .await;
  332. let _state = state.clone();
  333. registry
  334. .register(net::SESSION_ALL, move |channel, p2p| {
  335. let state = _state.clone();
  336. async move { ProtocolTx::init(channel, state, p2p).await.unwrap() }
  337. })
  338. .await;
  339. Some(p2p)
  340. };
  341. // P2P network settings for the consensus protocol
  342. let consensus_p2p = {
  343. if !args.consensus {
  344. None
  345. } else {
  346. info!("Registering consensus P2P protocols...");
  347. let consensus_network_settings = net::Settings {
  348. inbound_addrs: args.consensus_p2p_accept,
  349. outbound_connections: args.consensus_slots,
  350. external_addrs: args.consensus_p2p_external,
  351. peers: args.consensus_p2p_peer.clone(),
  352. seeds: args.consensus_p2p_seed.clone(),
  353. allowed_transports: args.consensus_p2p_transports,
  354. localnet: args.localnet,
  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. // TODO: I think this is not necessary anymore
  395. //info!("Waiting for sync P2P outbound connections");
  396. //sync_p2p.clone().unwrap().wait_for_outbound(ex.clone()).await?;
  397. match block_sync_task(sync_p2p.clone().unwrap(), state.clone()).await {
  398. Ok(()) => *darkfid.synced.lock().await = true,
  399. Err(e) => error!("Failed syncing blockchain: {}", e),
  400. }
  401. // Consensus protocol
  402. if args.consensus && *darkfid.synced.lock().await {
  403. info!("Starting consensus P2P network");
  404. consensus_p2p.clone().unwrap().start(ex.clone()).await?;
  405. let _ex = ex.clone();
  406. let _consensus_p2p = consensus_p2p.clone();
  407. ex.spawn(async move {
  408. if let Err(e) = _consensus_p2p.unwrap().run(_ex).await {
  409. error!("Failed starting consensus P2P network: {}", e);
  410. }
  411. })
  412. .detach();
  413. // TODO: I think this is not necessary anymore
  414. //info!("Waiting for consensus P2P outbound connections");
  415. //consensus_p2p.clone().unwrap().wait_for_outbound(ex.clone()).await?;
  416. info!("Starting consensus protocol task");
  417. let _ex = ex.clone();
  418. ex.spawn(proposal_task(consensus_p2p.unwrap(), sync_p2p.unwrap(), state, _ex)).detach();
  419. } else {
  420. info!("Not starting consensus P2P network");
  421. }
  422. // Signal handling for graceful termination.
  423. let (signals_handler, signals_task) = SignalHandler::new()?;
  424. signals_handler.wait_termination(signals_task).await?;
  425. info!("Caught termination signal, cleaning up and exiting...");
  426. // TODO: STOP P2P NETS
  427. info!("Flushing sled database...");
  428. let flushed_bytes = sled_db.flush_async().await?;
  429. info!("Flushed {} bytes", flushed_bytes);
  430. Ok(())
  431. }