main.rs 13 KB

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