main.rs 14 KB

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