main.rs 29 KB

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