main.rs 22 KB

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