main.rs 27 KB

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