main.rs 22 KB

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