main.rs 14 KB

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