main.rs 14 KB

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