main.rs 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436
  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 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. ValidatorState, ValidatorStatePtr, MAINNET_GENESIS_HASH_BYTES, MAINNET_GENESIS_TIMESTAMP,
  22. TESTNET_GENESIS_HASH_BYTES, TESTNET_GENESIS_TIMESTAMP,
  23. },
  24. crypto::{address::Address, keypair::PublicKey, token_list::DrkTokenList},
  25. net,
  26. net::P2pPtr,
  27. node::Client,
  28. rpc::{
  29. jsonrpc::{
  30. ErrorCode::{InternalError, InvalidParams, MethodNotFound},
  31. JsonError, JsonRequest, JsonResponse, JsonResult,
  32. },
  33. server::{listen_and_serve, RequestHandler},
  34. },
  35. util::{
  36. cli::{log_config, spawn_config},
  37. decode_base10, expand_path,
  38. path::get_config_path,
  39. serial::serialize,
  40. sleep, 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(short, parse(from_occurrences))]
  99. /// Increase verbosity (-vvv supported)
  100. verbose: u8,
  101. }
  102. pub struct Faucetd {
  103. synced: Mutex<bool>, // AtomicBool is weird in Arc
  104. sync_p2p: P2pPtr,
  105. client: Arc<Client>,
  106. validator_state: ValidatorStatePtr,
  107. airdrop_timeout: i64,
  108. airdrop_limit: BigUint,
  109. airdrop_map: Arc<Mutex<HashMap<Address, i64>>>,
  110. }
  111. #[async_trait]
  112. impl RequestHandler for Faucetd {
  113. async fn handle_request(&self, req: JsonRequest) -> JsonResult {
  114. if !req.params.is_array() {
  115. return JsonError::new(InvalidParams, None, req.id).into()
  116. }
  117. let params = req.params.as_array().unwrap();
  118. match req.method.as_str() {
  119. Some("airdrop") => return self.airdrop(req.id, params).await,
  120. Some(_) | None => return JsonError::new(MethodNotFound, None, req.id).into(),
  121. }
  122. }
  123. }
  124. impl Faucetd {
  125. pub async fn new(
  126. validator_state: ValidatorStatePtr,
  127. sync_p2p: P2pPtr,
  128. timeout: i64,
  129. limit: BigUint,
  130. ) -> Result<Self> {
  131. let client = validator_state.read().await.client.clone();
  132. Ok(Self {
  133. synced: Mutex::new(false),
  134. sync_p2p,
  135. client,
  136. validator_state,
  137. airdrop_timeout: timeout,
  138. airdrop_limit: limit,
  139. airdrop_map: Arc::new(Mutex::new(HashMap::new())),
  140. })
  141. }
  142. // RPCAPI:
  143. // Processes an airdrop request and airdrops requested amount to address.
  144. // Returns the transaction ID upon success.
  145. // --> {"jsonrpc": "2.0", "method": "airdrop", "params": ["1DarkFi...", 1.42], "id": 1}
  146. // <-- {"jsonrpc": "2.0", "result": "txID", "id": 1}
  147. async fn airdrop(&self, id: Value, params: &[Value]) -> JsonResult {
  148. if params.len() != 2 || !params[0].is_string() || !params[1].is_f64() {
  149. return JsonError::new(InvalidParams, None, id).into()
  150. }
  151. if !(*self.synced.lock().await) {
  152. error!("airdrop(): Blockchain is not yet synced");
  153. return JsonError::new(InternalError, None, id).into()
  154. }
  155. let address = match Address::from_str(params[0].as_str().unwrap()) {
  156. Ok(v) => v,
  157. Err(_) => {
  158. error!("airdrop(): Failed parsing address from string");
  159. return server_error(RpcError::ParseError, id)
  160. }
  161. };
  162. let pubkey = match PublicKey::try_from(address) {
  163. Ok(v) => v,
  164. Err(_) => {
  165. error!("airdrop(): Failed parsing PublicKey from Address");
  166. return server_error(RpcError::ParseError, id)
  167. }
  168. };
  169. let amount = params[1].as_f64().unwrap().to_string();
  170. let amount = match decode_base10(&amount, 8, true) {
  171. Ok(v) => v,
  172. Err(_) => {
  173. error!("airdrop(): Failed parsing amount from string");
  174. return server_error(RpcError::ParseError, id)
  175. }
  176. };
  177. if amount > self.airdrop_limit {
  178. return server_error(RpcError::AmountExceedsLimit, id)
  179. }
  180. // Check if there as a previous airdrop and the timeout has passed.
  181. let now = Utc::now().timestamp();
  182. let map = self.airdrop_map.lock().await;
  183. if let Some(last_airdrop) = map.get(&address) {
  184. if now - last_airdrop <= self.airdrop_timeout {
  185. return server_error(RpcError::TimeLimitReached, id)
  186. }
  187. };
  188. drop(map);
  189. let token_id = self.client.tokenlist.by_net[&NetworkName::DarkFi]
  190. .get("DRK".to_string())
  191. .unwrap()
  192. .drk_address;
  193. let amnt: u64 = match amount.try_into() {
  194. Ok(v) => v,
  195. Err(e) => {
  196. error!("airdrop(): Failed converting biguint to u64: {}", e);
  197. return JsonError::new(InternalError, None, id).into()
  198. }
  199. };
  200. let tx = match self
  201. .client
  202. .build_transaction(
  203. pubkey,
  204. amnt,
  205. token_id,
  206. true,
  207. self.validator_state.read().await.state_machine.clone(),
  208. )
  209. .await
  210. {
  211. Ok(v) => v,
  212. Err(e) => {
  213. error!("airdrop(): Failed building transaction: {}", e);
  214. return JsonError::new(InternalError, None, id).into()
  215. }
  216. };
  217. // Broadcast transaction to the network.
  218. match self.sync_p2p.broadcast(tx.clone()).await {
  219. Ok(()) => {}
  220. Err(e) => {
  221. error!("airdrop(): Failed broadcasting transaction: {}", e);
  222. return JsonError::new(InternalError, None, id).into()
  223. }
  224. }
  225. // Add/Update this airdrop into the hashmap
  226. let mut map = self.airdrop_map.lock().await;
  227. map.insert(address, now);
  228. drop(map);
  229. let tx_hash = blake3::hash(&serialize(&tx)).to_hex().as_str().to_string();
  230. JsonResponse::new(json!(tx_hash), id).into()
  231. }
  232. }
  233. async fn prune_airdrop_map(map: Arc<Mutex<HashMap<Address, i64>>>, timeout: i64) {
  234. loop {
  235. sleep(timeout as u64).await;
  236. debug!("Pruning airdrop map");
  237. let now = Utc::now().timestamp();
  238. let mut prune = vec![];
  239. let im_map = map.lock().await;
  240. for (k, v) in im_map.iter() {
  241. if now - *v > timeout {
  242. prune.push(*k);
  243. }
  244. }
  245. drop(im_map);
  246. let mut mut_map = map.lock().await;
  247. for i in prune {
  248. mut_map.remove(&i);
  249. }
  250. drop(mut_map);
  251. }
  252. }
  253. async_daemonize!(realmain);
  254. async fn realmain(args: Args, ex: Arc<Executor<'_>>) -> Result<()> {
  255. // We use this handler to block this function after detaching all
  256. // tasks, and to catch a shutdown signal, where we can clean up and
  257. // exit gracefully.
  258. let (signal, shutdown) = async_channel::bounded::<()>(1);
  259. ctrlc_async::set_async_handler(async move {
  260. signal.send(()).await.unwrap();
  261. })
  262. .unwrap();
  263. // Initialize or load wallet
  264. let wallet = init_wallet(&args.wallet_path, &args.wallet_pass).await?;
  265. // Initialize or open sled database
  266. let db_path = format!("{}/{}", expand_path(&args.database)?.to_str().unwrap(), args.chain);
  267. let sled_db = sled::open(&db_path)?;
  268. // Initialize validator state
  269. let (genesis_ts, genesis_data) = match args.chain.as_str() {
  270. "mainnet" => (*MAINNET_GENESIS_TIMESTAMP, *MAINNET_GENESIS_HASH_BYTES),
  271. "testnet" => (*TESTNET_GENESIS_TIMESTAMP, *TESTNET_GENESIS_HASH_BYTES),
  272. x => {
  273. error!("Unsupported chain `{}`", x);
  274. return Err(Error::UnsupportedChain)
  275. }
  276. };
  277. let tokenlist = Arc::new(DrkTokenList::new(&[
  278. ("drk", include_bytes!("../../../contrib/token/darkfi_token_list.min.json")),
  279. ("btc", include_bytes!("../../../contrib/token/bitcoin_token_list.min.json")),
  280. ("eth", include_bytes!("../../../contrib/token/erc20_token_list.min.json")),
  281. ("sol", include_bytes!("../../../contrib/token/solana_token_list.min.json")),
  282. ])?);
  283. // TODO: sqldb init cleanup
  284. // Initialize client
  285. let client = Arc::new(Client::new(wallet.clone(), tokenlist).await?);
  286. // Parse cashier addresses
  287. let mut cashier_pubkeys = vec![];
  288. for i in args.cashier_pub {
  289. let addr = Address::from_str(&i)?;
  290. let pk = PublicKey::try_from(addr)?;
  291. cashier_pubkeys.push(pk);
  292. }
  293. // Parse faucet addresses
  294. let mut faucet_pubkeys = vec![wallet.get_default_keypair().await?.public];
  295. for i in args.faucet_pub {
  296. let addr = Address::from_str(&i)?;
  297. let pk = PublicKey::try_from(addr)?;
  298. faucet_pubkeys.push(pk);
  299. }
  300. // Initialize validator state
  301. let state = ValidatorState::new(
  302. &sled_db,
  303. genesis_ts,
  304. genesis_data,
  305. client,
  306. cashier_pubkeys,
  307. faucet_pubkeys,
  308. )
  309. .await?;
  310. // P2P network. The faucet doesn't participate in consensus, so we only
  311. // build the sync protocol.
  312. let network_settings = net::Settings {
  313. inbound: args.sync_p2p_accept,
  314. outbound_connections: args.sync_slots,
  315. external_addr: args.sync_p2p_external,
  316. peers: args.sync_p2p_peer.clone(),
  317. seeds: args.sync_p2p_seed.clone(),
  318. ..Default::default()
  319. };
  320. let sync_p2p = net::P2p::new(network_settings).await;
  321. let registry = sync_p2p.protocol_registry();
  322. info!("Registering block sync P2P protocols...");
  323. let _state = state.clone();
  324. registry
  325. .register(net::SESSION_ALL, move |channel, p2p| {
  326. let state = _state.clone();
  327. async move { ProtocolSync::init(channel, state, p2p, false).await.unwrap() }
  328. })
  329. .await;
  330. let _state = state.clone();
  331. registry
  332. .register(net::SESSION_ALL, move |channel, p2p| {
  333. let state = _state.clone();
  334. async move { ProtocolTx::init(channel, state, p2p).await.unwrap() }
  335. })
  336. .await;
  337. let airdrop_timeout = args.airdrop_timeout;
  338. let airdrop_limit = decode_base10(&args.airdrop_limit, 8, true)?;
  339. // Initialize program state
  340. let faucetd =
  341. Faucetd::new(state.clone(), sync_p2p.clone(), airdrop_timeout, airdrop_limit).await?;
  342. let faucetd = Arc::new(faucetd);
  343. // Task to periodically clean up the hashmap of airdrops.
  344. ex.spawn(prune_airdrop_map(faucetd.airdrop_map.clone(), airdrop_timeout)).detach();
  345. // JSON-RPC server
  346. info!("Starting JSON-RPC server");
  347. ex.spawn(listen_and_serve(args.rpc_listen, faucetd.clone())).detach();
  348. info!("Starting sync P2P network");
  349. sync_p2p.clone().start(ex.clone()).await?;
  350. let _ex = ex.clone();
  351. let _sync_p2p = sync_p2p.clone();
  352. ex.spawn(async move {
  353. if let Err(e) = _sync_p2p.run(_ex).await {
  354. error!("Failed starting sync P2P network: {}", e);
  355. }
  356. })
  357. .detach();
  358. match block_sync_task(sync_p2p.clone(), state.clone()).await {
  359. Ok(()) => *faucetd.synced.lock().await = true,
  360. Err(e) => error!("Failed syncing blockchain: {}", e),
  361. }
  362. // Wait for SIGINT
  363. shutdown.recv().await?;
  364. print!("\r");
  365. info!("Caught termination signal, cleaning up and exiting...");
  366. info!("Flushing database...");
  367. let flushed_bytes = sled_db.flush_async().await?;
  368. info!("Flushed {} bytes", flushed_bytes);
  369. Ok(())
  370. }