main.rs 28 KB

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