main.rs 14 KB

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