main.rs 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427
  1. use std::str::FromStr;
  2. use async_executor::Executor;
  3. use async_std::sync::{Arc, Mutex};
  4. use async_trait::async_trait;
  5. use futures_lite::future;
  6. use log::{debug, error, info};
  7. use serde_derive::Deserialize;
  8. use structopt::StructOpt;
  9. use structopt_toml::StructOptToml;
  10. use url::Url;
  11. use darkfi::{
  12. async_daemonize, cli_desc,
  13. consensus::{
  14. proto::{
  15. ProtocolParticipant, ProtocolProposal, ProtocolSync, ProtocolSyncConsensus, ProtocolTx,
  16. ProtocolVote,
  17. },
  18. state::ValidatorStatePtr,
  19. task::{block_sync_task, proposal_task},
  20. ValidatorState, MAINNET_GENESIS_HASH_BYTES, MAINNET_GENESIS_TIMESTAMP,
  21. TESTNET_GENESIS_HASH_BYTES, TESTNET_GENESIS_TIMESTAMP,
  22. },
  23. crypto::{address::Address, keypair::PublicKey, token_list::DrkTokenList},
  24. net,
  25. net::P2pPtr,
  26. node::Client,
  27. rpc::{
  28. jsonrpc::{
  29. ErrorCode::{InvalidParams, MethodNotFound},
  30. JsonError, JsonRequest, JsonResult,
  31. },
  32. server::{listen_and_serve, RequestHandler},
  33. },
  34. util::{
  35. cli::{get_log_config, get_log_level, spawn_config},
  36. expand_path,
  37. path::get_config_path,
  38. time::check_clock,
  39. },
  40. wallet::walletdb::init_wallet,
  41. Error, Result,
  42. };
  43. mod error;
  44. use error::{server_error, RpcError};
  45. const CONFIG_FILE: &str = "darkfid_config.toml";
  46. const CONFIG_FILE_CONTENTS: &str = include_str!("../darkfid_config.toml");
  47. #[derive(Clone, Debug, Deserialize, StructOpt, StructOptToml)]
  48. #[serde(default)]
  49. #[structopt(name = "darkfid", about = cli_desc!())]
  50. struct Args {
  51. #[structopt(short, long)]
  52. /// Configuration file to use
  53. config: Option<String>,
  54. #[structopt(long, default_value = "testnet")]
  55. /// Chain to use (testnet, mainnet)
  56. chain: String,
  57. #[structopt(long)]
  58. /// Participate in consensus
  59. consensus: bool,
  60. #[structopt(long, default_value = "~/.config/darkfi/darkfid_wallet.db")]
  61. /// Path to wallet database
  62. wallet_path: String,
  63. #[structopt(long, default_value = "changeme")]
  64. /// Password for the wallet database
  65. wallet_pass: String,
  66. #[structopt(long, default_value = "~/.config/darkfi/darkfid_blockchain")]
  67. /// Path to blockchain database
  68. database: String,
  69. #[structopt(long, default_value = "tcp://127.0.0.1:8340")]
  70. /// JSON-RPC listen URL
  71. rpc_listen: Url,
  72. #[structopt(long)]
  73. /// P2P accept address for the consensus protocol
  74. consensus_p2p_accept: Option<Url>,
  75. #[structopt(long)]
  76. /// P2P external address for the consensus protocol
  77. consensus_p2p_external: Option<Url>,
  78. #[structopt(long, default_value = "8")]
  79. /// Connection slots for the consensus protocol
  80. consensus_slots: u32,
  81. #[structopt(long)]
  82. /// Connect to peer for the consensus protocol (repeatable flag)
  83. consensus_p2p_peer: Vec<Url>,
  84. #[structopt(long)]
  85. /// Connect to seed for the consensus protocol (repeatable flag)
  86. consensus_p2p_seed: Vec<Url>,
  87. #[structopt(long)]
  88. /// P2P accept address for the syncing protocol
  89. sync_p2p_accept: Option<Url>,
  90. #[structopt(long)]
  91. /// P2P external address for the syncing protocol
  92. sync_p2p_external: Option<Url>,
  93. #[structopt(long, default_value = "8")]
  94. /// Connection slots for the syncing protocol
  95. sync_slots: u32,
  96. #[structopt(long)]
  97. /// Connect to peer for the syncing protocol (repeatable flag)
  98. sync_p2p_peer: Vec<Url>,
  99. #[structopt(long)]
  100. /// Connect to seed for the syncing protocol (repeatable flag)
  101. sync_p2p_seed: Vec<Url>,
  102. #[structopt(long)]
  103. /// Whitelisted cashier address (repeatable flag)
  104. cashier_pub: Vec<String>,
  105. #[structopt(long)]
  106. /// Whitelisted faucet address (repeatable flag)
  107. faucet_pub: Vec<String>,
  108. #[structopt(long)]
  109. /// Verify system clock is correct
  110. clock_sync: bool,
  111. #[structopt(short, parse(from_occurrences))]
  112. /// Increase verbosity (-vvv supported)
  113. verbose: u8,
  114. }
  115. pub struct Darkfid {
  116. synced: Mutex<bool>, // AtomicBool is weird in Arc
  117. _consensus_p2p: Option<P2pPtr>,
  118. sync_p2p: Option<P2pPtr>,
  119. client: Arc<Client>,
  120. validator_state: ValidatorStatePtr,
  121. }
  122. // JSON-RPC methods
  123. mod rpc_blockchain;
  124. mod rpc_misc;
  125. mod rpc_tx;
  126. mod rpc_wallet;
  127. #[async_trait]
  128. impl RequestHandler for Darkfid {
  129. async fn handle_request(&self, req: JsonRequest) -> JsonResult {
  130. if !req.params.is_array() {
  131. return JsonError::new(InvalidParams, None, req.id).into()
  132. }
  133. let params = req.params.as_array().unwrap();
  134. match req.method.as_str() {
  135. Some("ping") => return self.pong(req.id, params).await,
  136. Some("blockchain.get_slot") => return self.get_slot(req.id, params).await,
  137. Some("blockchain.merkle_roots") => return self.merkle_roots(req.id, params).await,
  138. Some("tx.transfer") => return self.transfer(req.id, params).await,
  139. Some("wallet.keygen") => return self.keygen(req.id, params).await,
  140. Some("wallet.get_key") => return self.get_key(req.id, params).await,
  141. Some("wallet.export_keypair") => return self.export_keypair(req.id, params).await,
  142. Some("wallet.import_keypair") => return self.import_keypair(req.id, params).await,
  143. Some("wallet.set_default_address") => {
  144. return self.set_default_address(req.id, params).await
  145. }
  146. Some("wallet.get_balances") => return self.get_balances(req.id, params).await,
  147. Some(_) | None => return JsonError::new(MethodNotFound, None, req.id).into(),
  148. }
  149. }
  150. }
  151. impl Darkfid {
  152. pub async fn new(
  153. validator_state: ValidatorStatePtr,
  154. consensus_p2p: Option<P2pPtr>,
  155. sync_p2p: Option<P2pPtr>,
  156. ) -> Result<Self> {
  157. debug!("Waiting for validator state lock");
  158. let client = validator_state.read().await.client.clone();
  159. debug!("Released validator state lock");
  160. Ok(Self {
  161. synced: Mutex::new(false),
  162. _consensus_p2p: consensus_p2p,
  163. sync_p2p,
  164. client,
  165. validator_state,
  166. })
  167. }
  168. }
  169. async_daemonize!(realmain);
  170. async fn realmain(args: Args, ex: Arc<Executor<'_>>) -> Result<()> {
  171. if args.clock_sync {
  172. // We verify that the system clock is valid before initializing
  173. if (check_clock().await).is_err() {
  174. error!("System clock is invalid, terminating...");
  175. return Err(Error::InvalidClock)
  176. };
  177. }
  178. // We use this handler to block this function after detaching all
  179. // tasks, and to catch a shutdown signal, where we can clean up and
  180. // exit gracefully.
  181. let (signal, shutdown) = async_channel::bounded::<()>(1);
  182. ctrlc_async::set_async_handler(async move {
  183. signal.send(()).await.unwrap();
  184. })
  185. .unwrap();
  186. // Initialize or load wallet
  187. let wallet = init_wallet(&args.wallet_path, &args.wallet_pass).await?;
  188. // Initialize or open sled database
  189. let db_path = format!("{}/{}", expand_path(&args.database)?.to_str().unwrap(), args.chain);
  190. let sled_db = sled::open(&db_path)?;
  191. // Initialize validator state
  192. let (genesis_ts, genesis_data) = match args.chain.as_str() {
  193. "mainnet" => (*MAINNET_GENESIS_TIMESTAMP, *MAINNET_GENESIS_HASH_BYTES),
  194. "testnet" => (*TESTNET_GENESIS_TIMESTAMP, *TESTNET_GENESIS_HASH_BYTES),
  195. x => {
  196. error!("Unsupported chain `{}`", x);
  197. return Err(Error::UnsupportedChain)
  198. }
  199. };
  200. debug!("Parsing token lists...");
  201. let tokenlist = Arc::new(DrkTokenList::new(&[
  202. ("drk", include_bytes!("../../../contrib/token/darkfi_token_list.min.json")),
  203. ("btc", include_bytes!("../../../contrib/token/bitcoin_token_list.min.json")),
  204. ("eth", include_bytes!("../../../contrib/token/erc20_token_list.min.json")),
  205. ("sol", include_bytes!("../../../contrib/token/solana_token_list.min.json")),
  206. ])?);
  207. debug!("Finished parsing token lists");
  208. // TODO: sqldb init cleanup
  209. // Initialize Client
  210. let client = Arc::new(Client::new(wallet, tokenlist).await?);
  211. // Parse cashier addresses
  212. let mut cashier_pubkeys = vec![];
  213. for i in args.cashier_pub {
  214. let addr = Address::from_str(&i)?;
  215. let pk = PublicKey::try_from(addr)?;
  216. cashier_pubkeys.push(pk);
  217. }
  218. // Parse fauced addresses
  219. let mut faucet_pubkeys = vec![];
  220. for i in args.faucet_pub {
  221. let addr = Address::from_str(&i)?;
  222. let pk = PublicKey::try_from(addr)?;
  223. faucet_pubkeys.push(pk);
  224. }
  225. // Initialize validator state
  226. let state = ValidatorState::new(
  227. &sled_db,
  228. genesis_ts,
  229. genesis_data,
  230. client,
  231. cashier_pubkeys,
  232. faucet_pubkeys,
  233. )
  234. .await?;
  235. let sync_p2p = {
  236. info!("Registering block sync P2P protocols...");
  237. let sync_network_settings = net::Settings {
  238. inbound: args.sync_p2p_accept,
  239. outbound_connections: args.sync_slots,
  240. external_addr: args.sync_p2p_external,
  241. peers: args.sync_p2p_peer.clone(),
  242. seeds: args.sync_p2p_seed.clone(),
  243. ..Default::default()
  244. };
  245. let p2p = net::P2p::new(sync_network_settings).await;
  246. let registry = p2p.protocol_registry();
  247. let _state = state.clone();
  248. registry
  249. .register(net::SESSION_ALL, move |channel, p2p| {
  250. let state = _state.clone();
  251. async move {
  252. ProtocolSync::init(channel, state, p2p, args.consensus)
  253. .await
  254. .unwrap()
  255. }
  256. })
  257. .await;
  258. let _state = state.clone();
  259. registry
  260. .register(net::SESSION_ALL, move |channel, p2p| {
  261. let state = _state.clone();
  262. async move { ProtocolTx::init(channel, state, p2p).await.unwrap() }
  263. })
  264. .await;
  265. Some(p2p)
  266. };
  267. // P2P network settings for the consensus protocol
  268. let consensus_p2p = {
  269. if !args.consensus {
  270. None
  271. } else {
  272. info!("Registering consensus P2P protocols...");
  273. let consensus_network_settings = net::Settings {
  274. inbound: args.consensus_p2p_accept,
  275. outbound_connections: args.consensus_slots,
  276. external_addr: args.consensus_p2p_external,
  277. peers: args.consensus_p2p_peer.clone(),
  278. seeds: args.consensus_p2p_seed.clone(),
  279. ..Default::default()
  280. };
  281. let p2p = net::P2p::new(consensus_network_settings).await;
  282. let registry = p2p.protocol_registry();
  283. let _state = state.clone();
  284. registry
  285. .register(net::SESSION_ALL, move |channel, p2p| {
  286. let state = _state.clone();
  287. async move { ProtocolParticipant::init(channel, state, p2p).await.unwrap() }
  288. })
  289. .await;
  290. let _state = state.clone();
  291. registry
  292. .register(net::SESSION_ALL, move |channel, p2p| {
  293. let state = _state.clone();
  294. async move { ProtocolProposal::init(channel, state, p2p).await.unwrap() }
  295. })
  296. .await;
  297. let _state = state.clone();
  298. let _sync_p2p = sync_p2p.clone().unwrap();
  299. registry
  300. .register(net::SESSION_ALL, move |channel, p2p| {
  301. let state = _state.clone();
  302. let __sync_p2p = _sync_p2p.clone();
  303. async move {
  304. ProtocolVote::init(channel, state, __sync_p2p, p2p)
  305. .await
  306. .unwrap()
  307. }
  308. })
  309. .await;
  310. let _state = state.clone();
  311. registry
  312. .register(net::SESSION_ALL, move |channel, p2p| {
  313. let state = _state.clone();
  314. async move { ProtocolSyncConsensus::init(channel, state, p2p).await.unwrap() }
  315. })
  316. .await;
  317. Some(p2p)
  318. }
  319. };
  320. // Initialize program state
  321. let darkfid = Darkfid::new(state.clone(), consensus_p2p.clone(), sync_p2p.clone()).await?;
  322. let darkfid = Arc::new(darkfid);
  323. // JSON-RPC server
  324. info!("Starting JSON-RPC server");
  325. ex.spawn(listen_and_serve(args.rpc_listen, darkfid.clone())).detach();
  326. info!("Starting sync P2P network");
  327. sync_p2p.clone().unwrap().start(ex.clone()).await?;
  328. let _ex = ex.clone();
  329. let _sync_p2p = sync_p2p.clone();
  330. ex.spawn(async move {
  331. if let Err(e) = _sync_p2p.unwrap().run(_ex).await {
  332. error!("Failed starting sync P2P network: {}", e);
  333. }
  334. })
  335. .detach();
  336. match block_sync_task(sync_p2p.clone().unwrap(), state.clone()).await {
  337. Ok(()) => *darkfid.synced.lock().await = true,
  338. Err(e) => error!("Failed syncing blockchain: {}", e),
  339. }
  340. // Consensus protocol
  341. if args.consensus && *darkfid.synced.lock().await {
  342. info!("Starting consensus P2P network");
  343. consensus_p2p.clone().unwrap().start(ex.clone()).await?;
  344. let _ex = ex.clone();
  345. let _consensus_p2p = consensus_p2p.clone();
  346. ex.spawn(async move {
  347. if let Err(e) = _consensus_p2p.unwrap().run(_ex).await {
  348. error!("Failed starting consensus P2P network: {}", e);
  349. }
  350. })
  351. .detach();
  352. info!("Starting consensus protocol task");
  353. ex.spawn(proposal_task(consensus_p2p.unwrap(), sync_p2p.unwrap(), state)).detach();
  354. } else {
  355. info!("Not starting consensus P2P network");
  356. }
  357. // Wait for SIGINT
  358. shutdown.recv().await?;
  359. print!("\r");
  360. info!("Caught termination signal, cleaning up and exiting...");
  361. info!("Flushing database...");
  362. let flushed_bytes = sled_db.flush_async().await?;
  363. info!("Flushed {} bytes", flushed_bytes);
  364. Ok(())
  365. }