main.rs 14 KB

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