main.rs 23 KB

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