main.rs 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434
  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, NetworkName,
  39. },
  40. wallet::walletdb::init_wallet,
  41. Error, Result,
  42. };
  43. mod error;
  44. use error::{server_error, RpcError};
  45. const CONFIG_FILE: &str = "faucetd_config.toml";
  46. const CONFIG_FILE_CONTENTS: &str = include_str!("../faucetd_config.toml");
  47. #[derive(Clone, Debug, Deserialize, StructOpt, StructOptToml)]
  48. #[serde(default)]
  49. #[structopt(name = "faucetd", 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, default_value = "~/.config/darkfi/faucetd_wallet.db")]
  58. /// Path to wallet database
  59. wallet_path: String,
  60. #[structopt(long, default_value = "changeme")]
  61. /// Password for the wallet database
  62. wallet_pass: String,
  63. #[structopt(long, default_value = "~/.config/darkfi/faucetd_blockchain")]
  64. /// Path to blockchain database
  65. database: String,
  66. #[structopt(long, default_value = "tcp://127.0.0.1:9340")]
  67. /// JSON-RPC listen URL
  68. rpc_listen: Url,
  69. #[structopt(long)]
  70. /// P2P accept address for the syncing protocol
  71. sync_p2p_accept: Option<Url>,
  72. #[structopt(long)]
  73. /// P2P external address for the syncing protocol
  74. sync_p2p_external: Option<Url>,
  75. #[structopt(long, default_value = "8")]
  76. /// Connection slots for the syncing protocol
  77. sync_slots: u32,
  78. #[structopt(long)]
  79. /// Connect to seed for the syncing protocol (repeatable flag)
  80. sync_p2p_seed: Vec<Url>,
  81. #[structopt(long)]
  82. /// Connect to peer for the syncing protocol (repeatable flag)
  83. sync_p2p_peer: Vec<Url>,
  84. #[structopt(long)]
  85. /// Whitelisted cashier address (repeatable flag)
  86. cashier_pub: Vec<String>,
  87. #[structopt(long)]
  88. /// Whitelisted faucet address (repeatable flag)
  89. faucet_pub: Vec<String>,
  90. #[structopt(long, default_value = "600")]
  91. /// Airdrop timeout limit in seconds
  92. airdrop_timeout: i64,
  93. #[structopt(long, default_value = "10")]
  94. /// Airdrop amount limit
  95. airdrop_limit: String, // We convert this to biguint with decode_base10
  96. #[structopt(short, parse(from_occurrences))]
  97. /// Increase verbosity (-vvv supported)
  98. verbose: u8,
  99. }
  100. pub struct Faucetd {
  101. synced: Mutex<bool>, // AtomicBool is weird in Arc
  102. sync_p2p: P2pPtr,
  103. client: Arc<Client>,
  104. validator_state: ValidatorStatePtr,
  105. airdrop_timeout: i64,
  106. airdrop_limit: BigUint,
  107. airdrop_map: Arc<Mutex<HashMap<Address, i64>>>,
  108. }
  109. #[async_trait]
  110. impl RequestHandler for Faucetd {
  111. async fn handle_request(&self, req: JsonRequest) -> JsonResult {
  112. if !req.params.is_array() {
  113. return JsonError::new(InvalidParams, None, req.id).into()
  114. }
  115. let params = req.params.as_array().unwrap();
  116. match req.method.as_str() {
  117. Some("airdrop") => return self.airdrop(req.id, params).await,
  118. Some(_) | None => return JsonError::new(MethodNotFound, None, req.id).into(),
  119. }
  120. }
  121. }
  122. impl Faucetd {
  123. pub async fn new(
  124. validator_state: ValidatorStatePtr,
  125. sync_p2p: P2pPtr,
  126. timeout: i64,
  127. limit: BigUint,
  128. ) -> Result<Self> {
  129. let client = validator_state.read().await.client.clone();
  130. Ok(Self {
  131. synced: Mutex::new(false),
  132. sync_p2p,
  133. client,
  134. validator_state,
  135. airdrop_timeout: timeout,
  136. airdrop_limit: limit,
  137. airdrop_map: Arc::new(Mutex::new(HashMap::new())),
  138. })
  139. }
  140. // RPCAPI:
  141. // Processes an airdrop request and airdrops requested amount to address.
  142. // Returns the transaction ID upon success.
  143. // --> {"jsonrpc": "2.0", "method": "airdrop", "params": ["1DarkFi...", 1.42], "id": 1}
  144. // <-- {"jsonrpc": "2.0", "result": "txID", "id": 1}
  145. async fn airdrop(&self, id: Value, params: &[Value]) -> JsonResult {
  146. if params.len() != 2 || !params[0].is_string() || !params[1].is_f64() {
  147. return JsonError::new(InvalidParams, None, id).into()
  148. }
  149. if !(*self.synced.lock().await) {
  150. error!("airdrop(): Blockchain is not yet synced");
  151. return JsonError::new(InternalError, None, id).into()
  152. }
  153. let address = match Address::from_str(params[0].as_str().unwrap()) {
  154. Ok(v) => v,
  155. Err(_) => {
  156. error!("airdrop(): Failed parsing address from string");
  157. return server_error(RpcError::ParseError, id)
  158. }
  159. };
  160. let pubkey = match PublicKey::try_from(address) {
  161. Ok(v) => v,
  162. Err(_) => {
  163. error!("airdrop(): Failed parsing PublicKey from Address");
  164. return server_error(RpcError::ParseError, id)
  165. }
  166. };
  167. let amount = params[1].as_f64().unwrap().to_string();
  168. let amount = match decode_base10(&amount, 8, true) {
  169. Ok(v) => v,
  170. Err(_) => {
  171. error!("airdrop(): Failed parsing amount from string");
  172. return server_error(RpcError::ParseError, id)
  173. }
  174. };
  175. if amount > self.airdrop_limit {
  176. return server_error(RpcError::AmountExceedsLimit, id)
  177. }
  178. // Check if there as a previous airdrop and the timeout has passed.
  179. let now = Utc::now().timestamp();
  180. let map = self.airdrop_map.lock().await;
  181. if let Some(last_airdrop) = map.get(&address) {
  182. if now - last_airdrop <= self.airdrop_timeout {
  183. return server_error(RpcError::TimeLimitReached, id)
  184. }
  185. };
  186. drop(map);
  187. let token_id = self.client.tokenlist.by_net[&NetworkName::DarkFi]
  188. .get("DRK".to_string())
  189. .unwrap()
  190. .drk_address;
  191. let amnt: u64 = match amount.try_into() {
  192. Ok(v) => v,
  193. Err(e) => {
  194. error!("airdrop(): Failed converting biguint to u64: {}", e);
  195. return JsonError::new(InternalError, None, id).into()
  196. }
  197. };
  198. let tx = match self
  199. .client
  200. .build_transaction(
  201. pubkey,
  202. amnt,
  203. token_id,
  204. true,
  205. self.validator_state.read().await.state_machine.clone(),
  206. )
  207. .await
  208. {
  209. Ok(v) => v,
  210. Err(e) => {
  211. error!("airdrop(): Failed building transaction: {}", e);
  212. return JsonError::new(InternalError, None, id).into()
  213. }
  214. };
  215. // Broadcast transaction to the network.
  216. match self.sync_p2p.broadcast(tx.clone()).await {
  217. Ok(()) => {}
  218. Err(e) => {
  219. error!("airdrop(): Failed broadcasting transaction: {}", e);
  220. return JsonError::new(InternalError, None, id).into()
  221. }
  222. }
  223. // Add/Update this airdrop into the hashmap
  224. let mut map = self.airdrop_map.lock().await;
  225. map.insert(address, now);
  226. drop(map);
  227. let tx_hash = blake3::hash(&serialize(&tx)).to_hex().as_str().to_string();
  228. JsonResponse::new(json!(tx_hash), id).into()
  229. }
  230. }
  231. async fn prune_airdrop_map(map: Arc<Mutex<HashMap<Address, i64>>>, timeout: i64) {
  232. loop {
  233. sleep(timeout as u64).await;
  234. debug!("Pruning airdrop map");
  235. let now = Utc::now().timestamp();
  236. let mut prune = vec![];
  237. let im_map = map.lock().await;
  238. for (k, v) in im_map.iter() {
  239. if now - *v > timeout {
  240. prune.push(*k);
  241. }
  242. }
  243. drop(im_map);
  244. let mut mut_map = map.lock().await;
  245. for i in prune {
  246. mut_map.remove(&i);
  247. }
  248. drop(mut_map);
  249. }
  250. }
  251. async_daemonize!(realmain);
  252. async fn realmain(args: Args, ex: Arc<Executor<'_>>) -> Result<()> {
  253. // We use this handler to block this function after detaching all
  254. // tasks, and to catch a shutdown signal, where we can clean up and
  255. // exit gracefully.
  256. let (signal, shutdown) = async_channel::bounded::<()>(1);
  257. ctrlc_async::set_async_handler(async move {
  258. signal.send(()).await.unwrap();
  259. })
  260. .unwrap();
  261. // Initialize or load wallet
  262. let wallet = init_wallet(&args.wallet_path, &args.wallet_pass).await?;
  263. // Initialize or open sled database
  264. let db_path = format!("{}/{}", expand_path(&args.database)?.to_str().unwrap(), args.chain);
  265. let sled_db = sled::open(&db_path)?;
  266. // Initialize validator state
  267. let (genesis_ts, genesis_data) = match args.chain.as_str() {
  268. "mainnet" => (*MAINNET_GENESIS_TIMESTAMP, *MAINNET_GENESIS_HASH_BYTES),
  269. "testnet" => (*TESTNET_GENESIS_TIMESTAMP, *TESTNET_GENESIS_HASH_BYTES),
  270. x => {
  271. error!("Unsupported chain `{}`", x);
  272. return Err(Error::UnsupportedChain)
  273. }
  274. };
  275. let tokenlist = Arc::new(DrkTokenList::new(&[
  276. ("drk", include_bytes!("../../../contrib/token/darkfi_token_list.min.json")),
  277. ("btc", include_bytes!("../../../contrib/token/bitcoin_token_list.min.json")),
  278. ("eth", include_bytes!("../../../contrib/token/erc20_token_list.min.json")),
  279. ("sol", include_bytes!("../../../contrib/token/solana_token_list.min.json")),
  280. ])?);
  281. // TODO: sqldb init cleanup
  282. // Initialize client
  283. let client = Arc::new(Client::new(wallet.clone(), tokenlist).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_p2p_peer.clone(),
  315. seeds: args.sync_p2p_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. }