main.rs 18 KB

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