main.rs 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433
  1. use std::{collections::HashMap, net::SocketAddr, str::FromStr};
  2. use async_executor::Executor;
  3. use async_std::sync::{Arc, Mutex};
  4. use async_trait::async_trait;
  5. use chrono::Utc;
  6. use easy_parallel::Parallel;
  7. use futures_lite::future;
  8. use log::{debug, error, info};
  9. use num_bigint::BigUint;
  10. use serde_derive::Deserialize;
  11. use serde_json::{json, Value};
  12. use simplelog::{ColorChoice, TermLogger, TerminalMode};
  13. use structopt::StructOpt;
  14. use structopt_toml::StructOptToml;
  15. use url::Url;
  16. use darkfi::{
  17. async_daemonize, cli_desc,
  18. consensus::{
  19. proto::{ProtocolSync, ProtocolTx},
  20. task::block_sync_task,
  21. Timestamp, Tx, ValidatorState, ValidatorStatePtr, MAINNET_GENESIS_HASH_BYTES,
  22. TESTNET_GENESIS_HASH_BYTES,
  23. },
  24. crypto::{address::Address, keypair::PublicKey, types::DrkTokenId},
  25. net,
  26. net::P2pPtr,
  27. node::Client,
  28. rpc::{
  29. jsonrpc,
  30. jsonrpc::{
  31. ErrorCode::{InternalError, InvalidParams, MethodNotFound},
  32. JsonRequest, JsonResult,
  33. },
  34. rpcserver2::{listen_and_serve, RequestHandler},
  35. },
  36. util::{
  37. cli::{log_config, spawn_config},
  38. decode_base10, expand_path,
  39. path::get_config_path,
  40. serial::serialize,
  41. sleep,
  42. },
  43. wallet::walletdb::init_wallet,
  44. Error, Result,
  45. };
  46. mod error;
  47. use error::{server_error, RpcError};
  48. const CONFIG_FILE: &str = "faucetd_config.toml";
  49. const CONFIG_FILE_CONTENTS: &str = include_str!("../faucetd_config.toml");
  50. #[derive(Clone, Debug, Deserialize, StructOpt, StructOptToml)]
  51. #[serde(default)]
  52. #[structopt(name = "faucetd", about = cli_desc!())]
  53. struct Args {
  54. #[structopt(short, long)]
  55. /// Configuration file to use
  56. config: Option<String>,
  57. #[structopt(long, default_value = "testnet")]
  58. /// Chain to use (testnet, mainnet)
  59. chain: String,
  60. #[structopt(long, default_value = "~/.config/darkfi/faucetd_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/faucetd_blockchain")]
  67. /// Path to blockchain database
  68. database: String,
  69. #[structopt(long, default_value = "tcp://127.0.0.1:5381")]
  70. /// JSON-RPC listen URL
  71. rpc_listen: Url,
  72. #[structopt(long)]
  73. /// P2P accept address for the syncing protocol
  74. sync_p2p_accept: Option<SocketAddr>,
  75. #[structopt(long)]
  76. /// P2P external address for the syncing protocol
  77. sync_p2p_external: Option<SocketAddr>,
  78. #[structopt(long, default_value = "8")]
  79. /// Connection slots for the syncing protocol
  80. sync_slots: u32,
  81. #[structopt(long)]
  82. /// Connect to seed for the syncing protocol (repeatable flag)
  83. sync_seed: Vec<SocketAddr>,
  84. #[structopt(long)]
  85. /// Connect to peer for the syncing protocol (repeatable flag)
  86. sync_peer: Vec<SocketAddr>,
  87. #[structopt(long)]
  88. /// Whitelisted cashier address (repeatable flag)
  89. cashier_pub: Vec<String>,
  90. #[structopt(long)]
  91. /// Whitelisted faucet address (repeatable flag)
  92. faucet_pub: Vec<String>,
  93. #[structopt(long, default_value = "600")]
  94. /// Airdrop timeout limit in seconds
  95. airdrop_timeout: i64,
  96. #[structopt(long, default_value = "10")]
  97. /// Airdrop amount limit
  98. airdrop_limit: String, // We convert this to biguint with decode_base10
  99. #[structopt(short, parse(from_occurrences))]
  100. /// Increase verbosity (-vvv supported)
  101. verbose: u8,
  102. #[structopt(short)]
  103. /// Genesis time
  104. genesis_time: i64,
  105. }
  106. pub struct Faucetd {
  107. synced: Mutex<bool>, // AtomicBool is weird in Arc
  108. sync_p2p: P2pPtr,
  109. client: Arc<Client>,
  110. validator_state: ValidatorStatePtr,
  111. airdrop_timeout: i64,
  112. airdrop_limit: BigUint,
  113. airdrop_map: Arc<Mutex<HashMap<Address, i64>>>,
  114. }
  115. #[async_trait]
  116. impl RequestHandler for Faucetd {
  117. async fn handle_request(&self, req: JsonRequest) -> JsonResult {
  118. if !req.params.is_array() {
  119. return jsonrpc::error(InvalidParams, None, req.id).into()
  120. }
  121. let params = req.params.as_array().unwrap();
  122. match req.method.as_str() {
  123. Some("airdrop") => return self.airdrop(req.id, params).await,
  124. Some(_) | None => return jsonrpc::error(MethodNotFound, None, req.id).into(),
  125. }
  126. }
  127. }
  128. impl Faucetd {
  129. pub async fn new(
  130. validator_state: ValidatorStatePtr,
  131. sync_p2p: P2pPtr,
  132. timeout: i64,
  133. limit: BigUint,
  134. ) -> Result<Self> {
  135. let client = validator_state.read().await.client.clone();
  136. Ok(Self {
  137. synced: Mutex::new(false),
  138. sync_p2p,
  139. client,
  140. validator_state,
  141. airdrop_timeout: timeout,
  142. airdrop_limit: limit,
  143. airdrop_map: Arc::new(Mutex::new(HashMap::new())),
  144. })
  145. }
  146. // RPCAPI:
  147. // Processes an airdrop request and airdrops requested amount to address.
  148. // Returns the transaction ID upon success.
  149. // --> {"jsonrpc": "2.0", "method": "airdrop", "params": ["1DarkFi...", 1.42], "id": 1}
  150. // <-- {"jsonrpc": "2.0", "result": "txID", "id": 1}
  151. async fn airdrop(&self, id: Value, params: &[Value]) -> JsonResult {
  152. if params.len() != 2 || !params[0].is_string() || !params[1].is_f64() {
  153. return jsonrpc::error(InvalidParams, None, id).into()
  154. }
  155. if *self.synced.lock().await == false {
  156. error!("airdrop(): Blockchain is not yet synced");
  157. return jsonrpc::error(InternalError, None, id).into()
  158. }
  159. let address = match Address::from_str(params[0].as_str().unwrap()) {
  160. Ok(v) => v,
  161. Err(_) => {
  162. error!("airdrop(): Failed parsing address from string");
  163. return server_error(RpcError::ParseError, id)
  164. }
  165. };
  166. let pubkey = match PublicKey::try_from(address) {
  167. Ok(v) => v,
  168. Err(_) => {
  169. error!("airdrop(): Failed parsing PublicKey from Address");
  170. return server_error(RpcError::ParseError, id)
  171. }
  172. };
  173. let amount = params[1].as_f64().unwrap().to_string();
  174. let amount = match decode_base10(&amount, 8, true) {
  175. Ok(v) => v,
  176. Err(_) => {
  177. error!("airdrop(): Failed parsing amount from string");
  178. return server_error(RpcError::ParseError, id)
  179. }
  180. };
  181. if amount > self.airdrop_limit {
  182. return server_error(RpcError::AmountExceedsLimit, id)
  183. }
  184. // Check if there as a previous airdrop and the timeout has passed.
  185. let now = Utc::now().timestamp();
  186. let map = self.airdrop_map.lock().await;
  187. if let Some(last_airdrop) = map.get(&address) {
  188. if now - last_airdrop <= self.airdrop_timeout {
  189. return server_error(RpcError::TimeLimitReached, id)
  190. }
  191. };
  192. drop(map);
  193. // TODO: Token ID decision
  194. let token_id = DrkTokenId::from(1);
  195. let amnt: u64 = match amount.try_into() {
  196. Ok(v) => v,
  197. Err(e) => {
  198. error!("airdrop(): Failed converting biguint to u64: {}", e);
  199. return jsonrpc::error(InternalError, None, id).into()
  200. }
  201. };
  202. let tx = match self
  203. .client
  204. .build_transaction(
  205. pubkey,
  206. amnt,
  207. token_id,
  208. true,
  209. self.validator_state.read().await.state_machine.clone(),
  210. )
  211. .await
  212. {
  213. Ok(v) => v,
  214. Err(e) => {
  215. error!("airdrop(): Failed building transaction: {}", e);
  216. return jsonrpc::error(InternalError, None, id).into()
  217. }
  218. };
  219. // Broadcast transaction to the network.
  220. match self.sync_p2p.broadcast(Tx(tx.clone())).await {
  221. Ok(()) => {}
  222. Err(e) => {
  223. error!("airdrop(): Failed broadcasting transaction: {}", e);
  224. return jsonrpc::error(InternalError, None, id).into()
  225. }
  226. }
  227. // Add/Update this airdrop into the hashmap
  228. let mut map = self.airdrop_map.lock().await;
  229. map.insert(address, now);
  230. drop(map);
  231. let tx_hash = blake3::hash(&serialize(&tx)).to_hex().as_str().to_string();
  232. jsonrpc::response(json!(tx_hash), id).into()
  233. }
  234. }
  235. async fn prune_airdrop_map(map: Arc<Mutex<HashMap<Address, i64>>>, timeout: i64) {
  236. loop {
  237. sleep(timeout as u64).await;
  238. debug!("Pruning airdrop map");
  239. let now = Utc::now().timestamp();
  240. let mut prune = vec![];
  241. let im_map = map.lock().await;
  242. for (k, v) in im_map.iter() {
  243. if now - *v > timeout {
  244. prune.push(k.clone());
  245. }
  246. }
  247. drop(im_map);
  248. let mut mut_map = map.lock().await;
  249. for i in prune {
  250. mut_map.remove(&i);
  251. }
  252. drop(mut_map);
  253. }
  254. }
  255. async_daemonize!(realmain);
  256. async fn realmain(args: Args, ex: Arc<Executor<'_>>) -> Result<()> {
  257. // We use this handler to block this function after detaching all
  258. // tasks, and to catch a shutdown signal, where we can clean up and
  259. // exit gracefully.
  260. let (signal, shutdown) = async_channel::bounded::<()>(1);
  261. ctrlc_async::set_async_handler(async move {
  262. signal.send(()).await.unwrap();
  263. })
  264. .unwrap();
  265. // Initialize or load wallet
  266. let wallet = init_wallet(&args.wallet_path, &args.wallet_pass).await?;
  267. // Initialize or open sled database
  268. let db_path = format!("{}/{}", expand_path(&args.database)?.to_str().unwrap(), args.chain);
  269. let sled_db = sled::open(&db_path)?;
  270. // Initialize validator state
  271. // TODO: genesis_ts should be some hardcoded constant
  272. let genesis_ts = Timestamp(args.genesis_time);
  273. let genesis_data = match args.chain.as_str() {
  274. "mainnet" => *MAINNET_GENESIS_HASH_BYTES,
  275. "testnet" => *TESTNET_GENESIS_HASH_BYTES,
  276. x => {
  277. error!("Unsupported chain `{}`", x);
  278. return Err(Error::UnsupportedChain)
  279. }
  280. };
  281. // TODO: sqldb init cleanup
  282. // Initialize client
  283. let client = Arc::new(Client::new(wallet.clone()).await?);
  284. // Parse cashier addresses
  285. let mut cashier_pubkeys = vec![];
  286. for i in args.cashier_pub {
  287. let addr = Address::from_str(&i)?;
  288. let pk = PublicKey::try_from(addr)?;
  289. cashier_pubkeys.push(pk);
  290. }
  291. // Parse faucet addresses
  292. let mut faucet_pubkeys = vec![wallet.get_default_keypair().await?.public];
  293. for i in args.faucet_pub {
  294. let addr = Address::from_str(&i)?;
  295. let pk = PublicKey::try_from(addr)?;
  296. faucet_pubkeys.push(pk);
  297. }
  298. // Initialize validator state
  299. let state = ValidatorState::new(
  300. &sled_db,
  301. genesis_ts,
  302. genesis_data,
  303. client,
  304. cashier_pubkeys,
  305. faucet_pubkeys,
  306. )
  307. .await?;
  308. // P2P network. The faucet doesn't participate in consensus, so we only
  309. // build the sync protocol.
  310. let network_settings = net::Settings {
  311. inbound: args.sync_p2p_accept,
  312. outbound_connections: args.sync_slots,
  313. external_addr: args.sync_p2p_external,
  314. peers: args.sync_peer.clone(),
  315. seeds: args.sync_seed.clone(),
  316. ..Default::default()
  317. };
  318. let sync_p2p = net::P2p::new(network_settings).await;
  319. let registry = sync_p2p.protocol_registry();
  320. info!("Registering block sync P2P protocols...");
  321. let _state = state.clone();
  322. registry
  323. .register(net::SESSION_ALL, move |channel, p2p| {
  324. let state = _state.clone();
  325. async move { ProtocolSync::init(channel, state, p2p, false).await.unwrap() }
  326. })
  327. .await;
  328. let _state = state.clone();
  329. registry
  330. .register(net::SESSION_ALL, move |channel, p2p| {
  331. let state = _state.clone();
  332. async move { ProtocolTx::init(channel, state, p2p).await.unwrap() }
  333. })
  334. .await;
  335. let airdrop_timeout = args.airdrop_timeout;
  336. let airdrop_limit = decode_base10(&args.airdrop_limit, 8, true)?;
  337. // Initialize program state
  338. let faucetd =
  339. Faucetd::new(state.clone(), sync_p2p.clone(), airdrop_timeout, airdrop_limit).await?;
  340. let faucetd = Arc::new(faucetd);
  341. // Task to periodically clean up the hashmap of airdrops.
  342. ex.spawn(prune_airdrop_map(faucetd.airdrop_map.clone(), airdrop_timeout)).detach();
  343. // JSON-RPC server
  344. info!("Starting JSON-RPC server");
  345. ex.spawn(listen_and_serve(args.rpc_listen, faucetd.clone())).detach();
  346. info!("Starting sync P2P network");
  347. sync_p2p.clone().start(ex.clone()).await?;
  348. let _ex = ex.clone();
  349. let _sync_p2p = sync_p2p.clone();
  350. ex.spawn(async move {
  351. if let Err(e) = _sync_p2p.run(_ex).await {
  352. error!("Failed starting sync P2P network: {}", e);
  353. }
  354. })
  355. .detach();
  356. match block_sync_task(sync_p2p.clone(), state.clone()).await {
  357. Ok(()) => *faucetd.synced.lock().await = true,
  358. Err(e) => error!("Failed syncing blockchain: {}", e),
  359. }
  360. // Wait for SIGINT
  361. shutdown.recv().await?;
  362. print!("\r");
  363. info!("Caught termination signal, cleaning up and exiting...");
  364. info!("Flushing database...");
  365. let flushed_bytes = sled_db.flush_async().await?;
  366. info!("Flushed {} bytes", flushed_bytes);
  367. Ok(())
  368. }