main.rs 14 KB

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