main.rs 16 KB

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