main.rs 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808
  1. /* This file is part of DarkFi (https://dark.fi)
  2. *
  3. * Copyright (C) 2020-2023 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, path::Path, str::FromStr, sync::Arc};
  19. use async_trait::async_trait;
  20. use chrono::Utc;
  21. use darkfi_money_contract::{
  22. client::{
  23. transfer_v1::TransferCallBuilder, MONEY_KEYS_COL_IS_DEFAULT, MONEY_KEYS_COL_PUBLIC,
  24. MONEY_KEYS_COL_SECRET, MONEY_KEYS_TABLE, MONEY_TREE_COL_TREE, MONEY_TREE_TABLE,
  25. },
  26. MoneyFunction::TransferV1 as MoneyTransfer,
  27. MONEY_CONTRACT_ZKAS_BURN_NS_V1, MONEY_CONTRACT_ZKAS_MINT_NS_V1,
  28. };
  29. use darkfi_sdk::{
  30. crypto::{
  31. contract_id::MONEY_CONTRACT_ID, mimc_vdf, pasta_prelude::Field, Keypair, MerkleNode,
  32. MerkleTree, PublicKey, DARK_TOKEN_ID,
  33. },
  34. num_bigint::BigUint,
  35. num_traits::Num,
  36. pasta::{group::ff::PrimeField, pallas},
  37. tx::ContractCall,
  38. };
  39. use darkfi_serial::{deserialize, serialize, Encodable};
  40. use log::{debug, error, info};
  41. use rand::rngs::OsRng;
  42. use smol::{
  43. lock::{Mutex, RwLock},
  44. stream::StreamExt,
  45. };
  46. use structopt_toml::{serde::Deserialize, structopt::StructOpt, StructOptToml};
  47. use tinyjson::JsonValue;
  48. use url::Url;
  49. use darkfi::{
  50. async_daemonize, cli_desc,
  51. consensus::{
  52. constants::{
  53. MAINNET_BOOTSTRAP_TIMESTAMP, MAINNET_GENESIS_HASH_BYTES, MAINNET_GENESIS_TIMESTAMP,
  54. MAINNET_INITIAL_DISTRIBUTION, TESTNET_BOOTSTRAP_TIMESTAMP, TESTNET_GENESIS_HASH_BYTES,
  55. TESTNET_GENESIS_TIMESTAMP, TESTNET_INITIAL_DISTRIBUTION,
  56. },
  57. proto::{ProtocolSync, ProtocolTx},
  58. task::block_sync_task,
  59. ValidatorState, ValidatorStatePtr,
  60. },
  61. net,
  62. net::P2pPtr,
  63. rpc::{
  64. jsonrpc::{
  65. ErrorCode::{InternalError, InvalidParams, MethodNotFound},
  66. JsonError, JsonRequest, JsonResponse, JsonResult,
  67. },
  68. server::{listen_and_serve, RequestHandler},
  69. },
  70. runtime::vm_runtime::SMART_CONTRACT_ZKAS_DB_NAME,
  71. system::{sleep, StoppableTask},
  72. tx::Transaction,
  73. util::{parse::decode_base10, path::expand_path},
  74. wallet::{WalletDb, WalletPtr},
  75. zk::{proof::ProvingKey, vm::ZkCircuit, vm_heap::empty_witnesses},
  76. zkas::ZkBinary,
  77. Error, Result,
  78. };
  79. mod error;
  80. use error::{server_error, RpcError};
  81. const CONFIG_FILE: &str = "faucetd_config.toml";
  82. const CONFIG_FILE_CONTENTS: &str = include_str!("../faucetd_config.toml");
  83. #[derive(Clone, Debug, Deserialize, StructOpt, StructOptToml)]
  84. #[serde(default)]
  85. #[structopt(name = "faucetd", about = cli_desc!())]
  86. struct Args {
  87. #[structopt(short, long)]
  88. /// Configuration file to use
  89. config: Option<String>,
  90. #[structopt(long, default_value = "testnet")]
  91. /// Chain to use (testnet, mainnet)
  92. chain: String,
  93. #[structopt(long, default_value = "~/.config/darkfi/faucetd_wallet.db")]
  94. /// Path to wallet database
  95. wallet_path: String,
  96. #[structopt(long, default_value = "changeme")]
  97. /// Password for the wallet database
  98. wallet_pass: String,
  99. #[structopt(long, default_value = "~/.config/darkfi/faucetd_blockchain")]
  100. /// Path to blockchain database
  101. database: String,
  102. #[structopt(long, default_value = "tcp://127.0.0.1:9340")]
  103. /// JSON-RPC listen URL
  104. rpc_listen: Url,
  105. #[structopt(long)]
  106. /// P2P accept addresses for the syncing protocol
  107. sync_p2p_accept: Vec<Url>,
  108. #[structopt(long)]
  109. /// P2P external addresses for the syncing protocol
  110. sync_p2p_external: Vec<Url>,
  111. #[structopt(long, default_value = "8")]
  112. /// Connection slots for the syncing protocol
  113. sync_slots: usize,
  114. #[structopt(long)]
  115. /// Connect to seed for the syncing protocol (repeatable flag)
  116. sync_p2p_seed: Vec<Url>,
  117. #[structopt(long)]
  118. /// Connect to peer for the syncing protocol (repeatable flag)
  119. sync_p2p_peer: Vec<Url>,
  120. #[structopt(long)]
  121. /// Prefered transports of outbound connections for the syncing protocol (repeatable flag)
  122. sync_p2p_transports: Vec<String>,
  123. #[structopt(long)]
  124. /// Enable localnet hosts
  125. localnet: bool,
  126. #[structopt(long)]
  127. /// Whitelisted cashier address (repeatable flag)
  128. cashier_pub: Vec<String>,
  129. #[structopt(long)]
  130. /// Whitelisted faucet address (repeatable flag)
  131. faucet_pub: Vec<String>,
  132. #[structopt(long, default_value = "600")]
  133. /// Airdrop timeout limit in seconds
  134. airdrop_timeout: i64,
  135. #[structopt(long, default_value = "10")]
  136. /// Airdrop amount limit
  137. airdrop_limit: String, // We convert this to u64 with decode_base10
  138. #[structopt(short, long)]
  139. /// Set log file to ouput into
  140. log: Option<String>,
  141. #[structopt(short, parse(from_occurrences))]
  142. /// Increase verbosity (-vvv supported)
  143. verbose: u8,
  144. }
  145. type ProvingKeyMap = Arc<RwLock<HashMap<[u8; 32], Vec<(String, ProvingKey, ZkBinary)>>>>;
  146. type AirdropMap = Arc<Mutex<HashMap<[u8; 32], i64>>>;
  147. type ChallengeMap = Arc<Mutex<HashMap<[u8; 32], (BigUint, u64)>>>;
  148. pub struct Faucetd {
  149. synced: Mutex<bool>, // AtomicBool is weird in Arc
  150. sync_p2p: P2pPtr,
  151. validator_state: ValidatorStatePtr,
  152. keypair: Keypair,
  153. _wallet: WalletPtr,
  154. merkle_tree: MerkleTree,
  155. airdrop_timeout: i64,
  156. airdrop_limit: u64,
  157. airdrop_map: AirdropMap,
  158. challenge_map: ChallengeMap,
  159. proving_keys: ProvingKeyMap,
  160. }
  161. #[async_trait]
  162. impl RequestHandler for Faucetd {
  163. async fn handle_request(&self, req: JsonRequest) -> JsonResult {
  164. match req.method.as_str() {
  165. "challenge" => return self.challenge(req.id, req.params).await,
  166. "airdrop" => return self.airdrop(req.id, req.params).await,
  167. _ => return JsonError::new(MethodNotFound, None, req.id).into(),
  168. }
  169. }
  170. }
  171. impl Faucetd {
  172. pub async fn new(
  173. validator_state: ValidatorStatePtr,
  174. sync_p2p: P2pPtr,
  175. wallet: WalletPtr,
  176. timeout: i64,
  177. limit: u64,
  178. ) -> Result<Self> {
  179. // Here we initialize the wallet for the money contract.
  180. let merkle_tree = Self::initialize_wallet(wallet.clone()).await?;
  181. // This is kinda bad, but whatever. The hashmaps hold proving keys for
  182. // the money contract. We keep it under RwLock in case we want to add
  183. // other proving keys to it later.
  184. let proving_keys = Arc::new(RwLock::new(HashMap::new()));
  185. // For now we'll create the keys for the money contract
  186. let cid = *MONEY_CONTRACT_ID;
  187. // Do a lookup for the money contract's zkas database and fetch the circuits.
  188. let blockchain = { validator_state.read().await.blockchain.clone() };
  189. let db_handle =
  190. blockchain.contracts.lookup(&blockchain.sled_db, &cid, SMART_CONTRACT_ZKAS_DB_NAME)?;
  191. let Some(mint_zkbytes) = db_handle.get(serialize(&MONEY_CONTRACT_ZKAS_MINT_NS_V1))? else {
  192. error!(target: "faucetd", "{} zkas bincode not found in sled database", MONEY_CONTRACT_ZKAS_MINT_NS_V1);
  193. return Err(Error::ZkasBincodeNotFound)
  194. };
  195. let Some(burn_zkbytes) = db_handle.get(serialize(&MONEY_CONTRACT_ZKAS_BURN_NS_V1))? else {
  196. error!(target: "faucetd", "{} zkas bincode not found in sled database", MONEY_CONTRACT_ZKAS_BURN_NS_V1);
  197. return Err(Error::ZkasBincodeNotFound)
  198. };
  199. let (mint_zkbin, _): (Vec<u8>, Vec<u8>) = deserialize(&mint_zkbytes)?;
  200. let (burn_zkbin, _): (Vec<u8>, Vec<u8>) = deserialize(&burn_zkbytes)?;
  201. let mint_zkbin = ZkBinary::decode(&mint_zkbin)?;
  202. let mint_circuit = ZkCircuit::new(empty_witnesses(&mint_zkbin)?, &mint_zkbin);
  203. let burn_zkbin = ZkBinary::decode(&burn_zkbin)?;
  204. let burn_circuit = ZkCircuit::new(empty_witnesses(&burn_zkbin)?, &burn_zkbin);
  205. info!(target: "faucetd", "Creating mint circuit proving key");
  206. let mint_provingkey = ProvingKey::build(mint_zkbin.k, &mint_circuit);
  207. info!(target: "faucetd", "Creating burn circuit proving key");
  208. let burn_provingkey = ProvingKey::build(burn_zkbin.k, &burn_circuit);
  209. {
  210. let provingkeys = vec![
  211. (MONEY_CONTRACT_ZKAS_MINT_NS_V1.to_string(), mint_provingkey, mint_zkbin),
  212. (MONEY_CONTRACT_ZKAS_BURN_NS_V1.to_string(), burn_provingkey, burn_zkbin),
  213. ];
  214. let mut proving_keys_w = proving_keys.write().await;
  215. proving_keys_w.insert(cid.inner().to_repr(), provingkeys);
  216. }
  217. // Get or create an initial keypair for signing transactions
  218. let keypair = Self::initialize_keypair(wallet.clone()).await?;
  219. info!(target: "faucetd", "Faucet pubkey: {}", keypair.public);
  220. let faucetd = Self {
  221. synced: Mutex::new(false),
  222. sync_p2p,
  223. validator_state,
  224. keypair,
  225. _wallet: wallet,
  226. merkle_tree,
  227. airdrop_timeout: timeout,
  228. airdrop_limit: limit,
  229. airdrop_map: Arc::new(Mutex::new(HashMap::new())),
  230. challenge_map: Arc::new(Mutex::new(HashMap::new())),
  231. proving_keys,
  232. };
  233. Ok(faucetd)
  234. }
  235. async fn initialize_wallet(wallet: WalletPtr) -> Result<MerkleTree> {
  236. // Perform wallet initialization for the money contract
  237. let wallet_schema = include_str!("../../../src/contract/money/wallet.sql");
  238. // Get a wallet connection
  239. info!(target: "faucetd", "Acquiring wallet connection");
  240. let conn = wallet.conn.lock().await;
  241. info!(target: "faucetd", "Initializing wallet schema");
  242. conn.execute(wallet_schema, rusqlite::params![])?;
  243. let query = format!("SELECT * FROM {}", MONEY_TREE_COL_TREE);
  244. let merkle_tree = conn.query_row(&query, [], |row| {
  245. let tree_bytes: Vec<u8> = row.get(MONEY_TREE_COL_TREE)?;
  246. Ok(deserialize(&tree_bytes).unwrap())
  247. });
  248. let merkle_tree = match merkle_tree {
  249. Ok(v) => {
  250. info!(target: "faucetd", "Merkle tree already exists");
  251. v
  252. }
  253. Err(_) => {
  254. let mut tree = MerkleTree::new(100);
  255. tree.append(MerkleNode::from(pallas::Base::ZERO));
  256. let tree_bytes = serialize(&tree);
  257. let query = format!(
  258. "DELETE FROM {}; INSERT INTO {} ({}) VALUES (?1)",
  259. MONEY_TREE_TABLE, MONEY_TREE_TABLE, MONEY_TREE_COL_TREE
  260. );
  261. conn.execute(&query, rusqlite::params![tree_bytes])?;
  262. info!(target: "faucetd", "Successfully initialized Merkle tree");
  263. tree
  264. }
  265. };
  266. Ok(merkle_tree)
  267. }
  268. async fn initialize_keypair(wallet: WalletPtr) -> Result<Keypair> {
  269. let conn = wallet.conn.lock().await;
  270. let query = format!(
  271. "SELECT {}, {} FROM {};",
  272. MONEY_KEYS_COL_PUBLIC, MONEY_KEYS_COL_SECRET, MONEY_KEYS_TABLE
  273. );
  274. let keypair = conn.query_row(&query, [], |row| {
  275. let public_bytes: Vec<u8> = row.get("public")?;
  276. let secret_bytes: Vec<u8> = row.get("secret")?;
  277. let public = deserialize(&public_bytes).unwrap();
  278. let secret = deserialize(&secret_bytes).unwrap();
  279. Ok(Keypair { public, secret })
  280. });
  281. let keypair = match keypair {
  282. Ok(k) => k,
  283. Err(_) => {
  284. let keypair = Keypair::random(&mut OsRng);
  285. let is_default = 0;
  286. let public_bytes = serialize(&keypair.public);
  287. let secret_bytes = serialize(&keypair.secret);
  288. let query = format!(
  289. "INSERT INTO {} ({}, {}, {}) VALUES (?1, ?2, ?3)",
  290. MONEY_KEYS_TABLE,
  291. MONEY_KEYS_COL_IS_DEFAULT,
  292. MONEY_KEYS_COL_PUBLIC,
  293. MONEY_KEYS_COL_SECRET
  294. );
  295. conn.execute(&query, rusqlite::params![is_default, public_bytes, secret_bytes])?;
  296. info!(target: "faucetd", "Wrote keypair to wallet");
  297. keypair
  298. }
  299. };
  300. Ok(keypair)
  301. }
  302. // RPCAPI:
  303. // Request a VDF challenge in order to become eligible for an airdrop. It is then
  304. // necessary to execute the VDF with the challenge as input and pass it to the
  305. // `airdrop` call, which the faucet will then verify.
  306. //
  307. // **Params:**
  308. // * `array[0]`: base58 encoded address string of the recipient
  309. //
  310. // **Returns:**
  311. // * `array[0]`: hex-encoded challenge string
  312. // * `array[1]`: n steps (`u64`) needed for VDF evaluation
  313. //
  314. // --> {"jsonrpc": "2.0", "method": "challenge", "params": ["1DarkFi..."], "id": 1}
  315. // <-- {"jsonrpc": "2.0", "result": ["0x123...", 10000], "id": 1}
  316. async fn challenge(&self, id: u16, params: JsonValue) -> JsonResult {
  317. const N_STEPS: u64 = 2_000_000;
  318. let params = params.get::<Vec<JsonValue>>().unwrap();
  319. if params.len() != 1 || !params[0].is_string() {
  320. return JsonError::new(InvalidParams, None, id).into()
  321. }
  322. if !(*self.synced.lock().await) {
  323. error!(target: "faucetd", "challenge(): Blockchain is not yet synced");
  324. return JsonError::new(InternalError, None, id).into()
  325. }
  326. let pubkey = params[0].get::<String>().unwrap();
  327. let pubkey = match PublicKey::from_str(pubkey) {
  328. Ok(v) => v,
  329. Err(e) => {
  330. error!(target: "faucetd", "challenge(): Failed parsing PublicKey from String: {}", e);
  331. return server_error(RpcError::ParseError, id)
  332. }
  333. };
  334. let map = self.challenge_map.lock().await;
  335. if map.contains_key(&pubkey.to_bytes()) {
  336. return server_error(RpcError::RateLimitReached, id)
  337. }
  338. drop(map);
  339. // Create a random challenge
  340. let mut hasher = blake3::Hasher::new();
  341. hasher.update(&pubkey.to_bytes());
  342. hasher.update(&pallas::Base::random(&mut OsRng).to_repr());
  343. let h = hasher.finalize();
  344. let c = BigUint::from_str_radix(&h.to_hex(), 16).unwrap();
  345. // Add/Update this airdrop into the hashmap
  346. let mut map = self.challenge_map.lock().await;
  347. map.insert(pubkey.to_bytes(), (c.clone(), N_STEPS));
  348. drop(map);
  349. let chall = JsonValue::from(c.to_str_radix(16));
  350. let steps = JsonValue::from(N_STEPS as f64);
  351. JsonResponse::new(JsonValue::Array(vec![chall, steps]), id).into()
  352. }
  353. // RPCAPI:
  354. // Processes a native token airdrop request and airdrops requested amount to address.
  355. // Returns the transaction ID upon success.
  356. //
  357. // **Params:**
  358. // * `array[0]`: base58 encoded address string of the recipient
  359. // * `array[1]`: Amount to airdrop in form of f64
  360. // * `array[2]`: VDF evaluation witness as hex-encoded BigUint string
  361. //
  362. // **Returns:**
  363. // * hex-encoded transaction ID string
  364. //
  365. // --> {"jsonrpc": "2.0", "method": "airdrop", "params": ["1DarkFi...", 1.42, "0x123..."], "id": 1}
  366. // <-- {"jsonrpc": "2.0", "result": "txID", "id": 1}
  367. async fn airdrop(&self, id: u16, params: JsonValue) -> JsonResult {
  368. let params = params.get::<Vec<JsonValue>>().unwrap();
  369. if params.len() != 3 ||
  370. !params[0].is_string() ||
  371. !params[1].is_number() ||
  372. !params[2].is_string()
  373. {
  374. return JsonError::new(InvalidParams, None, id).into()
  375. }
  376. if !(*self.synced.lock().await) {
  377. error!(target: "faucetd", "airdrop(): Blockchain is not yet synced");
  378. return JsonError::new(InternalError, None, id).into()
  379. }
  380. // Decode public key
  381. let pubkey = params[0].get::<String>().unwrap();
  382. let pubkey = match PublicKey::from_str(pubkey) {
  383. Ok(v) => v,
  384. Err(e) => {
  385. error!(target: "faucetd", "airdrop(): Failed parsing PublicKey from String: {}", e);
  386. return server_error(RpcError::ParseError, id)
  387. }
  388. };
  389. // Decode requested airdrop amount
  390. let amount = params[1].get::<f64>().unwrap().to_string();
  391. let amount = match decode_base10(&amount, 8, true) {
  392. Ok(v) => v,
  393. Err(_) => {
  394. error!(target: "faucetd", "airdrop(): Failed parsing amount from string");
  395. return server_error(RpcError::ParseError, id)
  396. }
  397. };
  398. if amount > self.airdrop_limit {
  399. return server_error(RpcError::AmountExceedsLimit, id)
  400. }
  401. // Decode VDF witness
  402. let witness = params[2].get::<String>().unwrap();
  403. let Ok(witness) = BigUint::from_str_radix(witness, 16) else {
  404. error!(target: "faucetd", "airdrop(): Failed parsing VDF witness from string");
  405. return server_error(RpcError::ParseError, id)
  406. };
  407. // Check if there as a previous airdrop and the timeout has passed.
  408. let now = Utc::now().timestamp();
  409. let map = self.airdrop_map.lock().await;
  410. if let Some(last_airdrop) = map.get(&pubkey.to_bytes()) {
  411. if now - last_airdrop <= self.airdrop_timeout {
  412. error!(target: "faucetd", "airdrop(): Time limit reached for {}", pubkey);
  413. return server_error(RpcError::TimeLimitReached, id)
  414. }
  415. };
  416. drop(map);
  417. // Check if a VDF challenge exists
  418. let map = self.challenge_map.lock().await;
  419. let Some((challenge, n_steps)) = map.get(&pubkey.to_bytes()).cloned() else {
  420. error!(target: "faucetd", "airdrop(): No VDF challenge found for {}", pubkey);
  421. return server_error(RpcError::NoVdfChallenge, id)
  422. };
  423. drop(map);
  424. // Verify the VDF
  425. info!(target: "faucetd", "airdrop(): Verifying VDF for {}...", pubkey);
  426. if !mimc_vdf::verify(&challenge, n_steps, &witness) {
  427. error!(target: "faucetd", "airdrop(): VDF verification failed for {}", pubkey);
  428. return server_error(RpcError::VdfVerifyFailed, id)
  429. }
  430. // Remove the challenge from the map at this point. Latter stuff might
  431. // fail, but we want clients to be able to request things again.
  432. let mut mut_map = self.challenge_map.lock().await;
  433. mut_map.remove(&pubkey.to_bytes());
  434. drop(mut_map);
  435. let cid = *MONEY_CONTRACT_ID;
  436. let (mint_zkbin, mint_pk, burn_zkbin, burn_pk) = {
  437. let proving_keys_r = self.proving_keys.read().await;
  438. let Some(arr) = proving_keys_r.get(&cid.to_bytes()) else {
  439. error!(target: "faucetd", "Contract ID {} not found in proving keys hashmap", cid);
  440. return server_error(RpcError::InternalError, id)
  441. };
  442. let Some(mint_data) = arr.iter().find(|x| x.0 == MONEY_CONTRACT_ZKAS_MINT_NS_V1) else {
  443. error!(target: "faucetd", "{} proof data not found in vector", MONEY_CONTRACT_ZKAS_MINT_NS_V1);
  444. return server_error(RpcError::InternalError, id)
  445. };
  446. let Some(burn_data) = arr.iter().find(|x| x.0 == MONEY_CONTRACT_ZKAS_BURN_NS_V1) else {
  447. error!(target: "faucetd", "{} proof data not found in vector", MONEY_CONTRACT_ZKAS_BURN_NS_V1);
  448. return server_error(RpcError::InternalError, id)
  449. };
  450. (mint_data.2.clone(), mint_data.1.clone(), burn_data.2.clone(), burn_data.1.clone())
  451. };
  452. // Create money contract transfer params and proofs
  453. let builder = TransferCallBuilder {
  454. keypair: self.keypair,
  455. recipient: pubkey,
  456. value: amount,
  457. token_id: *DARK_TOKEN_ID,
  458. rcpt_spend_hook: pallas::Base::zero(),
  459. rcpt_user_data: pallas::Base::zero(),
  460. rcpt_user_data_blind: pallas::Base::random(&mut OsRng),
  461. change_spend_hook: pallas::Base::zero(),
  462. change_user_data: pallas::Base::zero(),
  463. change_user_data_blind: pallas::Base::random(&mut OsRng),
  464. coins: vec![],
  465. tree: self.merkle_tree.clone(),
  466. mint_zkbin,
  467. mint_pk,
  468. burn_zkbin,
  469. burn_pk,
  470. clear_input: true,
  471. };
  472. let debris = match builder.build() {
  473. Ok(v) => v,
  474. Err(e) => {
  475. error!(target: "faucetd", "Failed to build transfer tx params: {}", e);
  476. return server_error(RpcError::InternalError, id)
  477. }
  478. };
  479. // Build transaction
  480. let mut data = vec![MoneyTransfer as u8];
  481. debris.params.encode(&mut data).unwrap();
  482. let calls = vec![ContractCall { contract_id: cid, data }];
  483. let proofs = vec![debris.proofs];
  484. let mut tx = Transaction { calls, proofs, signatures: vec![] };
  485. let sigs = tx.create_sigs(&mut OsRng, &debris.signature_secrets).unwrap();
  486. tx.signatures = vec![sigs];
  487. // Safety check to see if the transaction is actually valid.
  488. let lock = self.validator_state.read().await;
  489. let current_slot = lock.consensus.time_keeper.current_slot();
  490. if let Err(e) = lock.verify_transactions(&[tx.clone()], current_slot, false).await {
  491. error!(target: "faucetd", "airdrop(): Failed to verify transaction before broadcasting: {}", e);
  492. return JsonError::new(InternalError, None, id).into()
  493. }
  494. // Broadcast transaction to the network.
  495. self.sync_p2p.broadcast(&tx).await;
  496. // Add/Update this airdrop into the hashmap
  497. let mut map = self.airdrop_map.lock().await;
  498. map.insert(pubkey.to_bytes(), now);
  499. drop(map);
  500. let tx_hash = blake3::hash(&serialize(&tx)).to_hex().as_str().to_string();
  501. JsonResponse::new(JsonValue::String(tx_hash), id).into()
  502. }
  503. }
  504. async fn prune_airdrop_maps(
  505. rate_map: AirdropMap,
  506. challenge_map: ChallengeMap,
  507. timeout: i64,
  508. ) -> Result<()> {
  509. loop {
  510. sleep(timeout as u64).await;
  511. debug!(target: "faucetd", "Pruning airdrop maps");
  512. let now = Utc::now().timestamp();
  513. let mut prune = vec![];
  514. let im_map = rate_map.lock().await;
  515. for (k, v) in im_map.iter() {
  516. if now - *v > timeout {
  517. prune.push(*k);
  518. }
  519. }
  520. drop(im_map);
  521. let mut mut_rate_map = rate_map.lock().await;
  522. let mut mut_challenge_map = challenge_map.lock().await;
  523. for i in prune {
  524. mut_rate_map.remove(&i);
  525. mut_challenge_map.remove(&i);
  526. }
  527. drop(mut_rate_map);
  528. drop(mut_challenge_map);
  529. }
  530. }
  531. async_daemonize!(realmain);
  532. async fn realmain(args: Args, ex: Arc<smol::Executor<'static>>) -> Result<()> {
  533. // Initialize or load wallet
  534. let wallet = WalletDb::new(Some(expand_path(&args.wallet_path)?), Some(&args.wallet_pass))?;
  535. // Initialize or open sled database
  536. let db_path =
  537. Path::new(expand_path(&args.database)?.to_str().unwrap()).join(args.chain.clone());
  538. let sled_db = sled::open(&db_path)?;
  539. // Initialize validator state
  540. let (bootstrap_ts, genesis_ts, genesis_data, initial_distribution) = match args.chain.as_str() {
  541. "mainnet" => (
  542. *MAINNET_BOOTSTRAP_TIMESTAMP,
  543. *MAINNET_GENESIS_TIMESTAMP,
  544. *MAINNET_GENESIS_HASH_BYTES,
  545. *MAINNET_INITIAL_DISTRIBUTION,
  546. ),
  547. "testnet" => (
  548. *TESTNET_BOOTSTRAP_TIMESTAMP,
  549. *TESTNET_GENESIS_TIMESTAMP,
  550. *TESTNET_GENESIS_HASH_BYTES,
  551. *TESTNET_INITIAL_DISTRIBUTION,
  552. ),
  553. x => {
  554. error!(target: "faucetd", "Unsupported chain `{}`", x);
  555. return Err(Error::UnsupportedChain)
  556. }
  557. };
  558. // Parse faucet addresses
  559. let mut faucet_pubkeys = vec![];
  560. for i in args.cashier_pub {
  561. let pk = PublicKey::from_str(&i)?;
  562. faucet_pubkeys.push(pk);
  563. }
  564. for i in args.faucet_pub {
  565. let pk = PublicKey::from_str(&i)?;
  566. faucet_pubkeys.push(pk);
  567. }
  568. // Initialize validator state
  569. let state = ValidatorState::new(
  570. &sled_db,
  571. bootstrap_ts,
  572. genesis_ts,
  573. genesis_data,
  574. initial_distribution,
  575. wallet.clone(),
  576. faucet_pubkeys,
  577. false,
  578. false,
  579. )
  580. .await?;
  581. // P2P network. The faucet doesn't participate in consensus, so we only
  582. // build the sync protocol.
  583. let network_settings = net::Settings {
  584. inbound_addrs: args.sync_p2p_accept,
  585. outbound_connections: args.sync_slots,
  586. external_addrs: args.sync_p2p_external,
  587. peers: args.sync_p2p_peer.clone(),
  588. seeds: args.sync_p2p_seed.clone(),
  589. allowed_transports: args.sync_p2p_transports,
  590. localnet: args.localnet,
  591. ..Default::default()
  592. };
  593. let sync_p2p = net::P2p::new(network_settings, ex.clone()).await;
  594. let registry = sync_p2p.protocol_registry();
  595. info!(target: "faucetd", "Registering block sync P2P protocols...");
  596. let _state = state.clone();
  597. registry
  598. .register(net::SESSION_ALL, move |channel, p2p| {
  599. let state = _state.clone();
  600. async move { ProtocolSync::init(channel, state, p2p, false).await.unwrap() }
  601. })
  602. .await;
  603. let _state = state.clone();
  604. registry
  605. .register(net::SESSION_ALL, move |channel, p2p| {
  606. let state = _state.clone();
  607. async move { ProtocolTx::init(channel, state, p2p).await.unwrap() }
  608. })
  609. .await;
  610. let airdrop_timeout = args.airdrop_timeout;
  611. let airdrop_limit = decode_base10(&args.airdrop_limit, 8, true)?;
  612. // Initialize program state
  613. let faucetd = Faucetd::new(
  614. state.clone(),
  615. sync_p2p.clone(),
  616. wallet.clone(),
  617. airdrop_timeout,
  618. airdrop_limit,
  619. )
  620. .await?;
  621. let faucetd = Arc::new(faucetd);
  622. // Task to periodically clean up the airdrop rate/challenge hashmaps
  623. let airdrop_task = StoppableTask::new();
  624. airdrop_task.clone().start(
  625. prune_airdrop_maps(
  626. faucetd.airdrop_map.clone(),
  627. faucetd.challenge_map.clone(),
  628. airdrop_timeout,
  629. ),
  630. |res| async {
  631. match res {
  632. Ok(()) | Err(Error::DetachedTaskStopped) => { /* Do nothing */ }
  633. Err(e) => error!(target: "faucetd", "Failed starting airdrop prune task: {}", e),
  634. }
  635. },
  636. Error::DetachedTaskStopped,
  637. ex.clone(),
  638. );
  639. // JSON-RPC server
  640. info!(target: "faucetd", "Starting JSON-RPC server");
  641. let rpc_task = StoppableTask::new();
  642. rpc_task.clone().start(
  643. listen_and_serve(args.rpc_listen, faucetd.clone(), ex.clone()),
  644. |res| async {
  645. match res {
  646. Ok(()) | Err(Error::RPCServerStopped) => { /* Do nothing */ }
  647. Err(e) => error!(target: "faucetd", "Failed starting JSON-RPC server: {}", e),
  648. }
  649. },
  650. Error::RPCServerStopped,
  651. ex.clone(),
  652. );
  653. info!(target: "faucetd", "Starting sync P2P network");
  654. sync_p2p.clone().start().await?;
  655. StoppableTask::new().start(
  656. sync_p2p.clone().run(),
  657. |res| async {
  658. match res {
  659. Ok(()) | Err(Error::P2PNetworkStopped) => { /* Do nothing */ }
  660. Err(e) => error!(target: "faucetd", "Failed starting sync P2P network: {}", e),
  661. }
  662. },
  663. Error::P2PNetworkStopped,
  664. ex.clone(),
  665. );
  666. // TODO: I think this is not needed anymore
  667. //info!("Waiting for sync P2P outbound connections");
  668. //sync_p2p.clone().wait_for_outbound(ex).await?;
  669. match block_sync_task(sync_p2p.clone(), state.clone()).await {
  670. Ok(()) => *faucetd.synced.lock().await = true,
  671. Err(e) => error!(target: "faucetd", "Failed syncing blockchain: {}", e),
  672. }
  673. // Signal handling for graceful termination.
  674. let (signals_handler, signals_task) = SignalHandler::new(ex)?;
  675. signals_handler.wait_termination(signals_task).await?;
  676. info!(target: "faucetd", "Caught termination signal, cleaning up and exiting...");
  677. info!(target: "faucetd", "Stopping JSON-RPC server...");
  678. rpc_task.stop().await;
  679. info!(target: "faucetd", "Stopping airdrop prune task...");
  680. airdrop_task.stop().await;
  681. info!(target: "faucetd", "Stopping syncing P2P network...");
  682. sync_p2p.stop().await;
  683. info!(target: "faucetd", "Flushing database...");
  684. let flushed_bytes = sled_db.flush_async().await?;
  685. info!(target: "faucetd", "Flushed {} bytes", flushed_bytes);
  686. Ok(())
  687. }