main.rs 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501
  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 log::{debug, error, info};
  22. use structopt_toml::{serde::Deserialize, structopt::StructOpt, StructOptToml};
  23. use url::Url;
  24. use darkfi::{
  25. async_daemonize, cli_desc,
  26. consensus::{
  27. proto::{
  28. ProtocolParticipant, ProtocolProposal, ProtocolSync, ProtocolSyncConsensus, ProtocolTx,
  29. },
  30. state::ValidatorStatePtr,
  31. task::{block_sync_task, proposal_task},
  32. ValidatorState, MAINNET_GENESIS_HASH_BYTES, MAINNET_GENESIS_TIMESTAMP,
  33. TESTNET_GENESIS_HASH_BYTES, TESTNET_GENESIS_TIMESTAMP,
  34. },
  35. crypto::{address::Address, keypair::PublicKey},
  36. net,
  37. net::P2pPtr,
  38. node::Client,
  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,
  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 address (repeatable flag)
  130. cashier_pub: Vec<String>,
  131. #[structopt(long)]
  132. /// Whitelisted faucet address (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. client: Arc<Client>,
  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. Some("tx.transfer") => return self.tx_transfer(req.id, params).await,
  179. Some("tx.broadcast") => return self.tx_broadcast(req.id, params).await,
  180. // ==============
  181. // Wallet methods
  182. // ==============
  183. Some("wallet.keygen") => return self.wallet_keygen(req.id, params).await,
  184. Some("wallet.get_addrs") => return self.wallet_get_addrs(req.id, params).await,
  185. Some("wallet.export_keypair") => {
  186. return self.wallet_export_keypair(req.id, params).await
  187. }
  188. Some("wallet.import_keypair") => {
  189. return self.wallet_import_keypair(req.id, params).await
  190. }
  191. Some("wallet.set_default_address") => {
  192. return self.wallet_set_default_address(req.id, params).await
  193. }
  194. Some("wallet.get_balances") => return self.wallet_get_balances(req.id, params).await,
  195. Some("wallet.get_coins_valtok") => {
  196. return self.wallet_get_coins_valtok(req.id, params).await
  197. }
  198. Some("wallet.get_merkle_path") => {
  199. return self.wallet_get_merkle_path(req.id, params).await
  200. }
  201. Some("wallet.decrypt_note") => return self.wallet_decrypt_note(req.id, params).await,
  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. ) -> Result<Self> {
  215. debug!("Waiting for validator state lock");
  216. let client = validator_state.read().await.client.clone();
  217. debug!("Released validator state lock");
  218. Ok(Self {
  219. synced: Mutex::new(false),
  220. _consensus_p2p: consensus_p2p,
  221. sync_p2p,
  222. client,
  223. validator_state,
  224. })
  225. }
  226. }
  227. async_daemonize!(realmain);
  228. async fn realmain(args: Args, ex: Arc<smol::Executor<'_>>) -> Result<()> {
  229. if args.consensus && args.clock_sync {
  230. // We verify that if peer/seed nodes are configured, their rpc config also exists
  231. if ((!args.consensus_p2p_peer.is_empty() && args.consensus_peer_rpc.is_empty()) ||
  232. (args.consensus_p2p_peer.is_empty() && !args.consensus_peer_rpc.is_empty())) ||
  233. ((!args.consensus_p2p_seed.is_empty() && args.consensus_seed_rpc.is_empty()) ||
  234. (args.consensus_p2p_seed.is_empty() && !args.consensus_seed_rpc.is_empty()))
  235. {
  236. error!(
  237. "Consensus peer/seed nodes misconfigured: both p2p and rpc urls must be present"
  238. );
  239. return Err(Error::ConfigInvalid)
  240. }
  241. // We verify that the system clock is valid before initializing
  242. let peers = [&args.consensus_peer_rpc[..], &args.consensus_seed_rpc[..]].concat();
  243. if (check_clock(&peers).await).is_err() {
  244. error!("System clock is invalid, terminating...");
  245. return Err(Error::InvalidClock)
  246. };
  247. }
  248. // We use this handler to block this function after detaching all
  249. // tasks, and to catch a shutdown signal, where we can clean up and
  250. // exit gracefully.
  251. let (signal, shutdown) = smol::channel::bounded::<()>(1);
  252. ctrlc::set_handler(move || {
  253. async_std::task::block_on(signal.send(())).unwrap();
  254. })
  255. .unwrap();
  256. // Initialize or load wallet
  257. let wallet = init_wallet(&args.wallet_path, &args.wallet_pass).await?;
  258. // Initialize or open sled database
  259. // TODO: Use proper OsPath here, not {}/{}
  260. let db_path = format!("{}/{}", expand_path(&args.database)?.to_str().unwrap(), args.chain);
  261. let sled_db = sled::open(&db_path)?;
  262. // Initialize validator state
  263. let (genesis_ts, genesis_data) = match args.chain.as_str() {
  264. "mainnet" => (*MAINNET_GENESIS_TIMESTAMP, *MAINNET_GENESIS_HASH_BYTES),
  265. "testnet" => (*TESTNET_GENESIS_TIMESTAMP, *TESTNET_GENESIS_HASH_BYTES),
  266. x => {
  267. error!("Unsupported chain `{}`", x);
  268. return Err(Error::UnsupportedChain)
  269. }
  270. };
  271. // TODO: sqldb init cleanup
  272. // Initialize Client
  273. let client = Arc::new(Client::new(wallet).await?);
  274. // Parse cashier addresses
  275. let mut cashier_pubkeys = vec![];
  276. for i in args.cashier_pub {
  277. let addr = Address::from_str(&i)?;
  278. let pk = PublicKey::try_from(addr)?;
  279. cashier_pubkeys.push(pk);
  280. }
  281. // Parse fauced addresses
  282. let mut faucet_pubkeys = vec![];
  283. for i in args.faucet_pub {
  284. let addr = Address::from_str(&i)?;
  285. let pk = PublicKey::try_from(addr)?;
  286. faucet_pubkeys.push(pk);
  287. }
  288. // Initialize validator state
  289. let state = ValidatorState::new(
  290. &sled_db,
  291. genesis_ts,
  292. genesis_data,
  293. client,
  294. cashier_pubkeys,
  295. faucet_pubkeys,
  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 { ProtocolParticipant::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 { ProtocolProposal::init(channel, state, p2p).await.unwrap() }
  366. })
  367. .await;
  368. let _state = state.clone();
  369. registry
  370. .register(net::SESSION_ALL, move |channel, p2p| {
  371. let state = _state.clone();
  372. async move { ProtocolSyncConsensus::init(channel, state, p2p).await.unwrap() }
  373. })
  374. .await;
  375. Some(p2p)
  376. }
  377. };
  378. // Initialize program state
  379. let darkfid = Darkfid::new(state.clone(), consensus_p2p.clone(), sync_p2p.clone()).await?;
  380. let darkfid = Arc::new(darkfid);
  381. // JSON-RPC server
  382. info!("Starting JSON-RPC server");
  383. ex.spawn(listen_and_serve(args.rpc_listen, darkfid.clone())).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. info!("Waiting for sync P2P outbound connections");
  395. sync_p2p.clone().unwrap().wait_for_outbound(ex.clone()).await?;
  396. match block_sync_task(sync_p2p.clone().unwrap(), state.clone()).await {
  397. Ok(()) => *darkfid.synced.lock().await = true,
  398. Err(e) => error!("Failed syncing blockchain: {}", e),
  399. }
  400. // Consensus protocol
  401. if args.consensus && *darkfid.synced.lock().await {
  402. info!("Starting consensus P2P network");
  403. consensus_p2p.clone().unwrap().start(ex.clone()).await?;
  404. let _ex = ex.clone();
  405. let _consensus_p2p = consensus_p2p.clone();
  406. ex.spawn(async move {
  407. if let Err(e) = _consensus_p2p.unwrap().run(_ex).await {
  408. error!("Failed starting consensus P2P network: {}", e);
  409. }
  410. })
  411. .detach();
  412. info!("Waiting for consensus P2P outbound connections");
  413. consensus_p2p.clone().unwrap().wait_for_outbound(ex.clone()).await?;
  414. info!("Starting consensus protocol task");
  415. ex.spawn(proposal_task(consensus_p2p.unwrap(), sync_p2p.unwrap(), state)).detach();
  416. } else {
  417. info!("Not starting consensus P2P network");
  418. }
  419. // Wait for SIGINT
  420. shutdown.recv().await?;
  421. print!("\r");
  422. info!("Caught termination signal, cleaning up and exiting...");
  423. info!("Flushing database...");
  424. let flushed_bytes = sled_db.flush_async().await?;
  425. info!("Flushed {} bytes", flushed_bytes);
  426. Ok(())
  427. }