main.rs 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440
  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. /// Prefered transports of outbound connections for the syncing protocol (repeatable flag)
  85. sync_p2p_transports: Vec<String>,
  86. #[structopt(long)]
  87. /// Enable localnet hosts
  88. localnet: bool,
  89. #[structopt(long)]
  90. /// Whitelisted cashier address (repeatable flag)
  91. cashier_pub: Vec<String>,
  92. #[structopt(long)]
  93. /// Whitelisted faucet address (repeatable flag)
  94. faucet_pub: Vec<String>,
  95. #[structopt(long, default_value = "600")]
  96. /// Airdrop timeout limit in seconds
  97. airdrop_timeout: i64,
  98. #[structopt(long, default_value = "10")]
  99. /// Airdrop amount limit
  100. airdrop_limit: String, // We convert this to u64 with decode_base10
  101. #[structopt(short, parse(from_occurrences))]
  102. /// Increase verbosity (-vvv supported)
  103. verbose: u8,
  104. }
  105. pub struct Faucetd {
  106. synced: Mutex<bool>, // AtomicBool is weird in Arc
  107. sync_p2p: P2pPtr,
  108. client: Arc<Client>,
  109. validator_state: ValidatorStatePtr,
  110. airdrop_timeout: i64,
  111. airdrop_limit: u64,
  112. airdrop_map: Arc<Mutex<HashMap<Address, i64>>>,
  113. }
  114. #[async_trait]
  115. impl RequestHandler for Faucetd {
  116. async fn handle_request(&self, req: JsonRequest) -> JsonResult {
  117. if !req.params.is_array() {
  118. return JsonError::new(InvalidParams, None, req.id).into()
  119. }
  120. let params = req.params.as_array().unwrap();
  121. match req.method.as_str() {
  122. Some("airdrop") => return self.airdrop(req.id, params).await,
  123. Some(_) | None => return JsonError::new(MethodNotFound, None, req.id).into(),
  124. }
  125. }
  126. }
  127. impl Faucetd {
  128. pub async fn new(
  129. validator_state: ValidatorStatePtr,
  130. sync_p2p: P2pPtr,
  131. timeout: i64,
  132. limit: u64,
  133. ) -> Result<Self> {
  134. let client = validator_state.read().await.client.clone();
  135. Ok(Self {
  136. synced: Mutex::new(false),
  137. sync_p2p,
  138. client,
  139. validator_state,
  140. airdrop_timeout: timeout,
  141. airdrop_limit: limit,
  142. airdrop_map: Arc::new(Mutex::new(HashMap::new())),
  143. })
  144. }
  145. // RPCAPI:
  146. // Processes an airdrop request and airdrops requested token and amount to address.
  147. // Returns the transaction ID upon success.
  148. // --> {"jsonrpc": "2.0", "method": "airdrop", "params": ["1DarkFi...", 1.42, "1F00b4r..."], "id": 1}
  149. // <-- {"jsonrpc": "2.0", "result": "txID", "id": 1}
  150. async fn airdrop(&self, id: Value, params: &[Value]) -> JsonResult {
  151. if params.len() != 3 ||
  152. !params[0].is_string() ||
  153. !params[1].is_f64() ||
  154. !params[2].is_string()
  155. {
  156. return JsonError::new(InvalidParams, None, id).into()
  157. }
  158. if !(*self.synced.lock().await) {
  159. error!("airdrop(): Blockchain is not yet synced");
  160. return JsonError::new(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. // Here we allow the faucet to mint arbitrary token IDs.
  188. // TODO: Revert this to native token when we have contracts for minting tokens.
  189. let token_id = match token_id::parse_b58(params[2].as_str().unwrap()) {
  190. Ok(v) => v,
  191. Err(_) => {
  192. error!("airdrop(): Failed parsing token id from string");
  193. return server_error(RpcError::ParseError, id)
  194. }
  195. };
  196. // Check if there as a previous airdrop and the timeout has passed.
  197. let now = Utc::now().timestamp();
  198. let map = self.airdrop_map.lock().await;
  199. if let Some(last_airdrop) = map.get(&address) {
  200. if now - last_airdrop <= self.airdrop_timeout {
  201. return server_error(RpcError::TimeLimitReached, id)
  202. }
  203. };
  204. drop(map);
  205. let tx = match self
  206. .client
  207. .build_transaction(
  208. pubkey,
  209. amount,
  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 JsonError::new(InternalError, None, id).into()
  220. }
  221. };
  222. // Broadcast transaction to the network.
  223. match self.sync_p2p.broadcast(tx.clone()).await {
  224. Ok(()) => {}
  225. Err(e) => {
  226. error!("airdrop(): Failed broadcasting transaction: {}", e);
  227. return JsonError::new(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. JsonResponse::new(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::set_handler(move || {
  265. async_std::task::block_on(signal.send(())).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. let (genesis_ts, genesis_data) = match args.chain.as_str() {
  275. "mainnet" => (*MAINNET_GENESIS_TIMESTAMP, *MAINNET_GENESIS_HASH_BYTES),
  276. "testnet" => (*TESTNET_GENESIS_TIMESTAMP, *TESTNET_GENESIS_HASH_BYTES),
  277. x => {
  278. error!("Unsupported chain `{}`", x);
  279. return Err(Error::UnsupportedChain)
  280. }
  281. };
  282. // TODO: sqldb init cleanup
  283. // Initialize client
  284. let client = Arc::new(Client::new(wallet.clone()).await?);
  285. // Parse cashier addresses
  286. let mut cashier_pubkeys = vec![];
  287. for i in args.cashier_pub {
  288. let addr = Address::from_str(&i)?;
  289. let pk = PublicKey::try_from(addr)?;
  290. cashier_pubkeys.push(pk);
  291. }
  292. // Parse faucet addresses
  293. let mut faucet_pubkeys = vec![wallet.get_default_keypair().await?.public];
  294. for i in args.faucet_pub {
  295. let addr = Address::from_str(&i)?;
  296. let pk = PublicKey::try_from(addr)?;
  297. faucet_pubkeys.push(pk);
  298. }
  299. // Initialize validator state
  300. let state = ValidatorState::new(
  301. &sled_db,
  302. genesis_ts,
  303. genesis_data,
  304. client,
  305. cashier_pubkeys,
  306. faucet_pubkeys,
  307. )
  308. .await?;
  309. // P2P network. The faucet doesn't participate in consensus, so we only
  310. // build the sync protocol.
  311. let network_settings = net::Settings {
  312. inbound: args.sync_p2p_accept,
  313. outbound_connections: args.sync_slots,
  314. external_addr: args.sync_p2p_external,
  315. peers: args.sync_p2p_peer.clone(),
  316. seeds: args.sync_p2p_seed.clone(),
  317. outbound_transports: net::settings::get_outbound_transports(args.sync_p2p_transports),
  318. localnet: args.localnet,
  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. info!("Waiting for sync P2P outbound connections");
  360. sync_p2p.clone().wait_for_outbound(ex).await?;
  361. match block_sync_task(sync_p2p, state.clone()).await {
  362. Ok(()) => *faucetd.synced.lock().await = true,
  363. Err(e) => error!("Failed syncing blockchain: {}", e),
  364. }
  365. // Wait for SIGINT
  366. shutdown.recv().await?;
  367. print!("\r");
  368. info!("Caught termination signal, cleaning up and exiting...");
  369. info!("Flushing database...");
  370. let flushed_bytes = sled_db.flush_async().await?;
  371. info!("Flushed {} bytes", flushed_bytes);
  372. Ok(())
  373. }