main.rs 24 KB

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