main.rs 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500
  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)]
  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.last_known_slot") => {
  179. return self.blockchain_last_known_slot(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. if args.single_node {
  283. info!("Node is configured to run in single-node mode!");
  284. }
  285. // Initialize validator state
  286. let state = ValidatorState::new(
  287. &sled_db,
  288. bootstrap_ts,
  289. genesis_ts,
  290. genesis_data,
  291. initial_distribution,
  292. wallet.clone(),
  293. faucet_pubkeys,
  294. args.consensus,
  295. args.single_node,
  296. )
  297. .await?;
  298. let sync_p2p = {
  299. info!("Registering block sync P2P protocols...");
  300. let sync_network_settings = net::Settings {
  301. inbound: args.sync_p2p_accept,
  302. outbound_connections: args.sync_slots,
  303. external_addr: args.sync_p2p_external,
  304. peers: args.sync_p2p_peer.clone(),
  305. seeds: args.sync_p2p_seed.clone(),
  306. outbound_transports: net::settings::get_outbound_transports(args.sync_p2p_transports),
  307. localnet: args.localnet,
  308. channel_log: args.channel_log,
  309. ..Default::default()
  310. };
  311. let p2p = net::P2p::new(sync_network_settings).await;
  312. let registry = p2p.protocol_registry();
  313. let _state = state.clone();
  314. registry
  315. .register(net::SESSION_ALL, move |channel, p2p| {
  316. let state = _state.clone();
  317. async move {
  318. ProtocolSync::init(channel, state, p2p, args.consensus)
  319. .await
  320. .unwrap()
  321. }
  322. })
  323. .await;
  324. let _state = state.clone();
  325. registry
  326. .register(net::SESSION_ALL, move |channel, p2p| {
  327. let state = _state.clone();
  328. async move { ProtocolTx::init(channel, state, p2p).await.unwrap() }
  329. })
  330. .await;
  331. Some(p2p)
  332. };
  333. // P2P network settings for the consensus protocol
  334. let consensus_p2p = {
  335. if !args.consensus {
  336. None
  337. } else {
  338. info!("Registering consensus P2P protocols...");
  339. let consensus_network_settings = net::Settings {
  340. inbound: args.consensus_p2p_accept,
  341. outbound_connections: args.consensus_slots,
  342. external_addr: args.consensus_p2p_external,
  343. peers: args.consensus_p2p_peer.clone(),
  344. seeds: args.consensus_p2p_seed.clone(),
  345. outbound_transports: net::settings::get_outbound_transports(
  346. args.consensus_p2p_transports,
  347. ),
  348. localnet: args.localnet,
  349. channel_log: args.channel_log,
  350. ..Default::default()
  351. };
  352. let p2p = net::P2p::new(consensus_network_settings).await;
  353. let registry = p2p.protocol_registry();
  354. let _state = state.clone();
  355. registry
  356. .register(net::SESSION_ALL, move |channel, p2p| {
  357. let state = _state.clone();
  358. async move { ProtocolProposal::init(channel, state, p2p).await.unwrap() }
  359. })
  360. .await;
  361. let _state = state.clone();
  362. registry
  363. .register(net::SESSION_ALL, move |channel, p2p| {
  364. let state = _state.clone();
  365. async move { ProtocolSyncConsensus::init(channel, state, p2p).await.unwrap() }
  366. })
  367. .await;
  368. Some(p2p)
  369. }
  370. };
  371. // Initialize program state
  372. let darkfid =
  373. Darkfid::new(state.clone(), consensus_p2p.clone(), sync_p2p.clone(), wallet.clone()).await;
  374. let darkfid = Arc::new(darkfid);
  375. // JSON-RPC server
  376. info!("Starting JSON-RPC server");
  377. let _ex = ex.clone();
  378. ex.spawn(listen_and_serve(args.rpc_listen, darkfid.clone(), _ex)).detach();
  379. info!("Starting sync P2P network");
  380. sync_p2p.clone().unwrap().start(ex.clone()).await?;
  381. let _ex = ex.clone();
  382. let _sync_p2p = sync_p2p.clone();
  383. ex.spawn(async move {
  384. if let Err(e) = _sync_p2p.unwrap().run(_ex).await {
  385. error!("Failed starting sync P2P network: {}", e);
  386. }
  387. })
  388. .detach();
  389. info!("Waiting for sync P2P outbound connections");
  390. sync_p2p.clone().unwrap().wait_for_outbound(ex.clone()).await?;
  391. match block_sync_task(sync_p2p.clone().unwrap(), state.clone()).await {
  392. Ok(()) => *darkfid.synced.lock().await = true,
  393. Err(e) => error!("Failed syncing blockchain: {}", e),
  394. }
  395. // Consensus protocol
  396. if args.consensus && *darkfid.synced.lock().await {
  397. info!("Starting consensus P2P network");
  398. consensus_p2p.clone().unwrap().start(ex.clone()).await?;
  399. let _ex = ex.clone();
  400. let _consensus_p2p = consensus_p2p.clone();
  401. ex.spawn(async move {
  402. if let Err(e) = _consensus_p2p.unwrap().run(_ex).await {
  403. error!("Failed starting consensus P2P network: {}", e);
  404. }
  405. })
  406. .detach();
  407. info!("Waiting for consensus P2P outbound connections");
  408. consensus_p2p.clone().unwrap().wait_for_outbound(ex.clone()).await?;
  409. info!("Starting consensus protocol task");
  410. let _ex = ex.clone();
  411. ex.spawn(proposal_task(consensus_p2p.unwrap(), sync_p2p.unwrap(), state, _ex)).detach();
  412. } else {
  413. info!("Not starting consensus P2P network");
  414. }
  415. // Wait for SIGINT
  416. shutdown.recv().await?;
  417. print!("\r");
  418. info!("Caught termination signal, cleaning up and exiting...");
  419. info!("Flushing sled database...");
  420. let flushed_bytes = sled_db.flush_async().await?;
  421. info!("Flushed {} bytes", flushed_bytes);
  422. info!("Closing wallet connection...");
  423. wallet.conn.close().await;
  424. info!("Closed wallet connection");
  425. Ok(())
  426. }