main.rs 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488
  1. /* This file is part of DarkFi (https://dark.fi)
  2. *
  3. * Copyright (C) 2020-2022 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_GENESIS_HASH_BYTES, MAINNET_GENESIS_TIMESTAMP, TESTNET_GENESIS_HASH_BYTES,
  30. TESTNET_GENESIS_TIMESTAMP,
  31. },
  32. proto::{ProtocolProposal, ProtocolSync, ProtocolSyncConsensus, ProtocolTx},
  33. state::ValidatorStatePtr,
  34. task::{block_sync_task, proposal_task},
  35. ValidatorState,
  36. },
  37. net,
  38. net::P2pPtr,
  39. rpc::{
  40. clock_sync::check_clock,
  41. jsonrpc::{
  42. ErrorCode::{InvalidParams, MethodNotFound},
  43. JsonError, JsonRequest, JsonResult,
  44. },
  45. server::{listen_and_serve, RequestHandler},
  46. },
  47. util::path::expand_path,
  48. wallet::{walletdb::init_wallet, WalletPtr},
  49. Error, Result,
  50. };
  51. mod error;
  52. use error::{server_error, RpcError};
  53. const CONFIG_FILE: &str = "darkfid_config.toml";
  54. const CONFIG_FILE_CONTENTS: &str = include_str!("../darkfid_config.toml");
  55. #[derive(Clone, Debug, Deserialize, StructOpt, StructOptToml)]
  56. #[serde(default)]
  57. #[structopt(name = "darkfid", about = cli_desc!())]
  58. struct Args {
  59. #[structopt(short, long)]
  60. /// Configuration file to use
  61. config: Option<String>,
  62. #[structopt(long, default_value = "testnet")]
  63. /// Chain to use (testnet, mainnet)
  64. chain: String,
  65. #[structopt(long)]
  66. /// Participate in consensus
  67. consensus: bool,
  68. #[structopt(long, default_value = "~/.config/darkfi/darkfid_wallet.db")]
  69. /// Path to wallet database
  70. wallet_path: String,
  71. #[structopt(long, default_value = "changeme")]
  72. /// Password for the wallet database
  73. wallet_pass: String,
  74. #[structopt(long, default_value = "~/.config/darkfi/darkfid_blockchain")]
  75. /// Path to blockchain database
  76. database: String,
  77. #[structopt(long, default_value = "tcp://127.0.0.1:8340")]
  78. /// JSON-RPC listen URL
  79. rpc_listen: Url,
  80. #[structopt(long)]
  81. /// P2P accept addresses for the consensus protocol (repeatable flag)
  82. consensus_p2p_accept: Vec<Url>,
  83. #[structopt(long)]
  84. /// P2P external addresses for the consensus protocol (repeatable flag)
  85. consensus_p2p_external: Vec<Url>,
  86. #[structopt(long, default_value = "8")]
  87. /// Connection slots for the consensus protocol
  88. consensus_slots: u32,
  89. #[structopt(long)]
  90. /// Connect to peer for the consensus protocol (repeatable flag)
  91. consensus_p2p_peer: Vec<Url>,
  92. #[structopt(long)]
  93. /// Peers JSON-RPC listen URL for clock synchronization (repeatable flag)
  94. consensus_peer_rpc: Vec<Url>,
  95. #[structopt(long)]
  96. /// Connect to seed for the consensus protocol (repeatable flag)
  97. consensus_p2p_seed: Vec<Url>,
  98. #[structopt(long)]
  99. /// Seed nodes JSON-RPC listen URL for clock synchronization (repeatable flag)
  100. consensus_seed_rpc: Vec<Url>,
  101. #[structopt(long)]
  102. /// Prefered transports of outbound connections for the consensus protocol (repeatable flag)
  103. consensus_p2p_transports: Vec<String>,
  104. #[structopt(long)]
  105. /// P2P accept addresses for the syncing protocol (repeatable flag)
  106. sync_p2p_accept: Vec<Url>,
  107. #[structopt(long)]
  108. /// P2P external addresses for the syncing protocol (repeatable flag)
  109. sync_p2p_external: Vec<Url>,
  110. #[structopt(long, default_value = "8")]
  111. /// Connection slots for the syncing protocol
  112. sync_slots: u32,
  113. #[structopt(long)]
  114. /// Connect to peer for the syncing protocol (repeatable flag)
  115. sync_p2p_peer: Vec<Url>,
  116. #[structopt(long)]
  117. /// Connect to seed for the syncing protocol (repeatable flag)
  118. sync_p2p_seed: Vec<Url>,
  119. #[structopt(long)]
  120. /// Prefered transports of outbound connections for the syncing protocol (repeatable flag)
  121. sync_p2p_transports: Vec<String>,
  122. #[structopt(long)]
  123. /// Enable localnet hosts
  124. localnet: bool,
  125. #[structopt(long)]
  126. /// Enable channel log
  127. channel_log: bool,
  128. #[structopt(long)]
  129. /// Whitelisted cashier public key (repeatable flag)
  130. cashier_pub: Vec<String>,
  131. #[structopt(long)]
  132. /// Whitelisted faucet public key (repeatable flag)
  133. faucet_pub: Vec<String>,
  134. #[structopt(long)]
  135. /// Verify system clock is correct
  136. clock_sync: bool,
  137. #[structopt(short, parse(from_occurrences))]
  138. /// Increase verbosity (-vvv supported)
  139. verbose: u8,
  140. }
  141. pub struct Darkfid {
  142. synced: Mutex<bool>, // AtomicBool is weird in Arc
  143. _consensus_p2p: Option<P2pPtr>,
  144. sync_p2p: Option<P2pPtr>,
  145. wallet: WalletPtr,
  146. validator_state: ValidatorStatePtr,
  147. }
  148. // JSON-RPC methods
  149. mod rpc_blockchain;
  150. mod rpc_misc;
  151. //mod rpc_tx;
  152. mod rpc_wallet;
  153. // Internal methods
  154. //mod internal;
  155. #[async_trait]
  156. impl RequestHandler for Darkfid {
  157. async fn handle_request(&self, req: JsonRequest) -> JsonResult {
  158. if !req.params.is_array() {
  159. return JsonError::new(InvalidParams, None, req.id).into()
  160. }
  161. let params = req.params.as_array().unwrap();
  162. match req.method.as_str() {
  163. // =====================
  164. // Miscellaneous methods
  165. // =====================
  166. Some("ping") => return self.misc_pong(req.id, params).await,
  167. Some("clock") => return self.misc_clock(req.id, params).await,
  168. // ==================
  169. // Blockchain methods
  170. // ==================
  171. Some("blockchain.get_slot") => return self.blockchain_get_slot(req.id, params).await,
  172. Some("blockchain.merkle_roots") => {
  173. return self.blockchain_merkle_roots(req.id, params).await
  174. }
  175. // ===================
  176. // Transaction methods
  177. // ===================
  178. /*
  179. Some("tx.transfer") => return self.tx_transfer(req.id, params).await,
  180. Some("tx.broadcast") => return self.tx_broadcast(req.id, params).await,
  181. */
  182. // ==============
  183. // Wallet methods
  184. // ==============
  185. /*
  186. Some("wallet.keygen") => return self.wallet_keygen(req.id, params).await,
  187. Some("wallet.get_addrs") => return self.wallet_get_addrs(req.id, params).await,
  188. Some("wallet.export_keypair") => {
  189. return self.wallet_export_keypair(req.id, params).await
  190. }
  191. Some("wallet.import_keypair") => {
  192. return self.wallet_import_keypair(req.id, params).await
  193. }
  194. Some("wallet.set_default_address") => {
  195. return self.wallet_set_default_address(req.id, params).await
  196. }
  197. Some("wallet.get_balances") => return self.wallet_get_balances(req.id, params).await,
  198. Some("wallet.get_coins_valtok") => {
  199. return self.wallet_get_coins_valtok(req.id, params).await
  200. }
  201. Some("wallet.get_merkle_path") => {
  202. return self.wallet_get_merkle_path(req.id, params).await
  203. }
  204. Some("wallet.decrypt_note") => return self.wallet_decrypt_note(req.id, params).await,
  205. */
  206. // ==============
  207. // Invalid method
  208. // ==============
  209. Some(_) | None => return JsonError::new(MethodNotFound, None, req.id).into(),
  210. }
  211. }
  212. }
  213. impl Darkfid {
  214. pub async fn new(
  215. validator_state: ValidatorStatePtr,
  216. consensus_p2p: Option<P2pPtr>,
  217. sync_p2p: Option<P2pPtr>,
  218. wallet: WalletPtr,
  219. ) -> Self {
  220. Self {
  221. synced: Mutex::new(false),
  222. _consensus_p2p: consensus_p2p,
  223. sync_p2p,
  224. wallet,
  225. validator_state,
  226. }
  227. }
  228. }
  229. async_daemonize!(realmain);
  230. async fn realmain(args: Args, ex: Arc<smol::Executor<'_>>) -> Result<()> {
  231. if args.consensus && args.clock_sync {
  232. // We verify that if peer/seed nodes are configured, their rpc config also exists
  233. if ((!args.consensus_p2p_peer.is_empty() && args.consensus_peer_rpc.is_empty()) ||
  234. (args.consensus_p2p_peer.is_empty() && !args.consensus_peer_rpc.is_empty())) ||
  235. ((!args.consensus_p2p_seed.is_empty() && args.consensus_seed_rpc.is_empty()) ||
  236. (args.consensus_p2p_seed.is_empty() && !args.consensus_seed_rpc.is_empty()))
  237. {
  238. error!(
  239. "Consensus peer/seed nodes misconfigured: both p2p and rpc urls must be present"
  240. );
  241. return Err(Error::ConfigInvalid)
  242. }
  243. // We verify that the system clock is valid before initializing
  244. let peers = [&args.consensus_peer_rpc[..], &args.consensus_seed_rpc[..]].concat();
  245. if (check_clock(&peers).await).is_err() {
  246. error!("System clock is invalid, terminating...");
  247. return Err(Error::InvalidClock)
  248. };
  249. }
  250. // We use this handler to block this function after detaching all
  251. // tasks, and to catch a shutdown signal, where we can clean up and
  252. // exit gracefully.
  253. let (signal, shutdown) = smol::channel::bounded::<()>(1);
  254. ctrlc::set_handler(move || {
  255. async_std::task::block_on(signal.send(())).unwrap();
  256. })
  257. .unwrap();
  258. // Initialize or load wallet
  259. let wallet = init_wallet(&args.wallet_path, &args.wallet_pass).await?;
  260. // Initialize or open sled database
  261. // TODO: Use proper OsPath here, not {}/{}
  262. let db_path = format!("{}/{}", expand_path(&args.database)?.to_str().unwrap(), args.chain);
  263. let sled_db = sled::open(&db_path)?;
  264. // Initialize validator state
  265. let (genesis_ts, genesis_data) = match args.chain.as_str() {
  266. "mainnet" => (*MAINNET_GENESIS_TIMESTAMP, *MAINNET_GENESIS_HASH_BYTES),
  267. "testnet" => (*TESTNET_GENESIS_TIMESTAMP, *TESTNET_GENESIS_HASH_BYTES),
  268. x => {
  269. error!("Unsupported chain `{}`", x);
  270. return Err(Error::UnsupportedChain)
  271. }
  272. };
  273. // Parse cashier addresses
  274. let mut cashier_pubkeys = vec![];
  275. for i in args.cashier_pub {
  276. let pk = PublicKey::from_str(&i)?;
  277. cashier_pubkeys.push(pk);
  278. }
  279. // Parse fauced addresses
  280. let mut faucet_pubkeys = vec![];
  281. for i in args.faucet_pub {
  282. let pk = PublicKey::from_str(&i)?;
  283. faucet_pubkeys.push(pk);
  284. }
  285. // Initialize validator state
  286. let state = ValidatorState::new(
  287. &sled_db,
  288. genesis_ts,
  289. genesis_data,
  290. wallet.clone(),
  291. cashier_pubkeys,
  292. faucet_pubkeys,
  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. ex.spawn(listen_and_serve(args.rpc_listen, darkfid.clone())).detach();
  375. info!("Starting sync P2P network");
  376. sync_p2p.clone().unwrap().start(ex.clone()).await?;
  377. let _ex = ex.clone();
  378. let _sync_p2p = sync_p2p.clone();
  379. ex.spawn(async move {
  380. if let Err(e) = _sync_p2p.unwrap().run(_ex).await {
  381. error!("Failed starting sync P2P network: {}", e);
  382. }
  383. })
  384. .detach();
  385. info!("Waiting for sync P2P outbound connections");
  386. sync_p2p.clone().unwrap().wait_for_outbound(ex.clone()).await?;
  387. match block_sync_task(sync_p2p.clone().unwrap(), state.clone()).await {
  388. Ok(()) => *darkfid.synced.lock().await = true,
  389. Err(e) => error!("Failed syncing blockchain: {}", e),
  390. }
  391. // Consensus protocol
  392. if args.consensus && *darkfid.synced.lock().await {
  393. info!("Starting consensus P2P network");
  394. consensus_p2p.clone().unwrap().start(ex.clone()).await?;
  395. let _ex = ex.clone();
  396. let _consensus_p2p = consensus_p2p.clone();
  397. ex.spawn(async move {
  398. if let Err(e) = _consensus_p2p.unwrap().run(_ex).await {
  399. error!("Failed starting consensus P2P network: {}", e);
  400. }
  401. })
  402. .detach();
  403. info!("Waiting for consensus P2P outbound connections");
  404. consensus_p2p.clone().unwrap().wait_for_outbound(ex.clone()).await?;
  405. info!("Starting consensus protocol task");
  406. ex.spawn(proposal_task(consensus_p2p.unwrap(), sync_p2p.unwrap(), state)).detach();
  407. } else {
  408. info!("Not starting consensus P2P network");
  409. }
  410. // Wait for SIGINT
  411. shutdown.recv().await?;
  412. print!("\r");
  413. info!("Caught termination signal, cleaning up and exiting...");
  414. info!("Flushing database...");
  415. let flushed_bytes = sled_db.flush_async().await?;
  416. info!("Flushed {} bytes", flushed_bytes);
  417. Ok(())
  418. }