darkfid.rs 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718
  1. use async_std::sync::{Arc, Mutex};
  2. use std::collections::HashMap;
  3. use std::convert::TryInto;
  4. use std::path::PathBuf;
  5. use std::str::FromStr;
  6. use async_executor::Executor;
  7. use async_trait::async_trait;
  8. use clap::clap_app;
  9. use easy_parallel::Parallel;
  10. use log::debug;
  11. use num_bigint::BigUint;
  12. use serde_json::{json, Value};
  13. use url::Url;
  14. use drk::{
  15. blockchain::{rocks::columns, Rocks, RocksColumn},
  16. cli::{Config, DarkfidConfig},
  17. client::{Client, State},
  18. crypto::{
  19. load_params, merkle::CommitmentTree, save_params, setup_mint_prover, setup_spend_prover,
  20. },
  21. rpc::{
  22. jsonrpc::{error as jsonerr, request as jsonreq, response as jsonresp, send_raw_request},
  23. jsonrpc::{ErrorCode::*, JsonRequest, JsonResult},
  24. rpcserver::{listen_and_serve, RequestHandler, RpcServerConfig},
  25. },
  26. serial::{deserialize, serialize},
  27. state::ProgramState,
  28. util::{
  29. assign_id, decode_base10, encode_base10, expand_path, join_config_path, DrkTokenList,
  30. NetworkName, TokenList,
  31. },
  32. wallet::WalletDb,
  33. Error, Result,
  34. };
  35. #[derive(Clone, Debug)]
  36. pub struct Cashier {
  37. pub name: String,
  38. pub rpc_url: String,
  39. pub public_key: jubjub::SubgroupPoint,
  40. }
  41. #[async_trait]
  42. impl RequestHandler for Darkfid {
  43. async fn handle_request(&self, req: JsonRequest, _executor: Arc<Executor<'_>>) -> JsonResult {
  44. if req.params.as_array().is_none() {
  45. return JsonResult::Err(jsonerr(InvalidParams, None, req.id));
  46. }
  47. debug!(target: "RPC", "--> {}", serde_json::to_string(&req).unwrap());
  48. match req.method.as_str() {
  49. Some("say_hello") => return self.say_hello(req.id, req.params).await,
  50. Some("create_wallet") => return self.create_wallet(req.id, req.params).await,
  51. Some("key_gen") => return self.key_gen(req.id, req.params).await,
  52. Some("get_key") => return self.get_key(req.id, req.params).await,
  53. Some("get_balances") => return self.get_balances(req.id, req.params).await,
  54. Some("get_token_id") => return self.get_token_id(req.id, req.params).await,
  55. Some("features") => return self.features(req.id, req.params).await,
  56. Some("deposit") => return self.deposit(req.id, req.params).await,
  57. Some("withdraw") => return self.withdraw(req.id, req.params).await,
  58. Some("transfer") => return self.transfer(req.id, req.params).await,
  59. Some(_) | None => return JsonResult::Err(jsonerr(MethodNotFound, None, req.id)),
  60. };
  61. }
  62. }
  63. struct Darkfid {
  64. client: Arc<Mutex<Client>>,
  65. state: Arc<Mutex<State>>,
  66. sol_tokenlist: TokenList,
  67. drk_tokenlist: DrkTokenList,
  68. cashiers: Vec<Cashier>,
  69. }
  70. impl Darkfid {
  71. async fn new(
  72. client: Arc<Mutex<Client>>,
  73. state: Arc<Mutex<State>>,
  74. cashiers: Vec<Cashier>,
  75. ) -> Result<Self> {
  76. let sol_tokenlist = TokenList::new(include_bytes!("../../token/solana_token_list.json"))?;
  77. let drk_tokenlist = DrkTokenList::new(sol_tokenlist.clone())?;
  78. Ok(Self {
  79. client,
  80. state,
  81. sol_tokenlist,
  82. drk_tokenlist,
  83. cashiers,
  84. })
  85. }
  86. async fn start(&mut self, executor: Arc<Executor<'_>>) -> Result<()> {
  87. self.client.lock().await.start().await?;
  88. self.client
  89. .lock()
  90. .await
  91. .connect_to_subscriber(self.state.clone(), executor)
  92. .await?;
  93. Ok(())
  94. }
  95. async fn update_balances(&self) -> Result<()> {
  96. let own_coins = self.client.lock().await.get_own_coins()?;
  97. for own_coin in own_coins.iter() {
  98. let nullifier_exists = self
  99. .state
  100. .lock()
  101. .await
  102. .nullifier_exists(&own_coin.nullifier);
  103. if nullifier_exists {
  104. self.client
  105. .lock()
  106. .await
  107. .confirm_spend_coin(&own_coin.coin)?;
  108. }
  109. }
  110. Ok(())
  111. }
  112. // --> {"method": "say_hello", "params": []}
  113. // <-- {"result": "hello world"}
  114. async fn say_hello(&self, id: Value, _params: Value) -> JsonResult {
  115. JsonResult::Resp(jsonresp(json!("hello world"), id))
  116. }
  117. // --> {"method": "create_wallet", "params": []}
  118. // <-- {"result": true}
  119. async fn create_wallet(&self, id: Value, _params: Value) -> JsonResult {
  120. match self.client.lock().await.init_db().await {
  121. Ok(()) => JsonResult::Resp(jsonresp(json!(true), id)),
  122. Err(e) => JsonResult::Err(jsonerr(ServerError(-32001), Some(e.to_string()), id)),
  123. }
  124. }
  125. // --> {"method": "key_gen", "params": []}
  126. // <-- {"result": true}
  127. async fn key_gen(&self, id: Value, _params: Value) -> JsonResult {
  128. match self.client.lock().await.key_gen() {
  129. Ok(()) => JsonResult::Resp(jsonresp(json!(true), id)),
  130. Err(e) => JsonResult::Err(jsonerr(ServerError(-32002), Some(e.to_string()), id)),
  131. }
  132. }
  133. // --> {"method": "get_key", "params": []}
  134. // <-- {"result": "vdNS7oBj7KvsMWWmo9r96SV4SqATLrGsH2a3PGpCfJC"}
  135. async fn get_key(&self, id: Value, _params: Value) -> JsonResult {
  136. let pk = self.client.lock().await.main_keypair.public;
  137. let b58 = bs58::encode(serialize(&pk)).into_string();
  138. JsonResult::Resp(jsonresp(json!(b58), id))
  139. }
  140. // --> {"method": "get_balances", "params": []}
  141. // <-- {"result": "get_balances": "[ {"btc": (value, network)}, .. ]"}
  142. async fn get_balances(&self, id: Value, _params: Value) -> JsonResult {
  143. let result: Result<HashMap<String, (String, String)>> = async {
  144. self.update_balances().await?;
  145. let balances = self.client.lock().await.get_balances()?;
  146. let mut symbols: HashMap<String, (String, String)> = HashMap::new();
  147. for balance in balances.list.iter() {
  148. // XXX: this must be changed once cashierd
  149. // supports more than two networks
  150. let mut network = "solana";
  151. if balance.token_id.to_string()
  152. == "0x01300f9bce0f9ba7168dc001a67bcbda3a5bf4bdb4c56ae900fe4698cee9a7bd"
  153. {
  154. network = "bitcoin"
  155. }
  156. if let Some(symbol) = self.drk_tokenlist.symbol_from_id(balance.token_id)? {
  157. let amount = encode_base10(BigUint::from(balance.value), 8);
  158. symbols.insert(symbol, (amount, network.to_string()));
  159. }
  160. }
  161. Ok(symbols)
  162. }
  163. .await;
  164. match result {
  165. Ok(res) => JsonResult::Resp(jsonresp(json!(res), id)),
  166. Err(err) => JsonResult::Err(jsonerr(InternalError, Some(err.to_string()), json!(id))),
  167. }
  168. }
  169. // --> {"method": "get_token_id", "params": [network, token]}
  170. // <-- {"result": "Ht5G1RhkcKnpLVLMhqJc5aqZ4wYUEbxbtZwGCVbgU7DL"}
  171. async fn get_token_id(&self, id: Value, params: Value) -> JsonResult {
  172. let args = params.as_array();
  173. if args.is_none() {
  174. return JsonResult::Err(jsonerr(InvalidParams, None, id));
  175. }
  176. let args = args.unwrap();
  177. if args.len() != 2 {
  178. return JsonResult::Err(jsonerr(InvalidParams, None, id));
  179. }
  180. let network: &str;
  181. let symbol: &str;
  182. match (args[0].as_str(), args[1].as_str()) {
  183. (Some(net), Some(sym)) => {
  184. network = net;
  185. symbol = sym;
  186. }
  187. (None, _) => {
  188. return JsonResult::Err(jsonerr(InvalidNetworkParam, None, id));
  189. }
  190. (_, None) => {
  191. return JsonResult::Err(jsonerr(InvalidSymbolParam, None, id));
  192. }
  193. }
  194. let result: Result<Value> = async {
  195. let network = NetworkName::from_str(network)?;
  196. match network {
  197. #[cfg(feature = "sol")]
  198. NetworkName::Solana => {
  199. let token_id = self.sol_tokenlist.search_id(symbol)?;
  200. Ok(json!(token_id))
  201. }
  202. #[cfg(feature = "btc")]
  203. NetworkName::Bitcoin => {
  204. //hardcoded genesis coinbase address
  205. let token_id = "1A1zP1eP5QGefi2DMPTfTL5SLmv7DivfNa".to_string();
  206. Ok(json!(token_id))
  207. }
  208. _ => Err(Error::NotSupportedNetwork),
  209. }
  210. }
  211. .await;
  212. match result {
  213. Ok(res) => JsonResult::Resp(jsonresp(json!(res), id)),
  214. Err(err) => JsonResult::Err(jsonerr(InternalError, Some(err.to_string()), json!(id))),
  215. }
  216. }
  217. // --> {""method": "features", "params": []}
  218. // <-- {"result": { "network": ["btc", "sol"] } }
  219. async fn features(&self, id: Value, _params: Value) -> JsonResult {
  220. let req = jsonreq(json!("features"), json!([]));
  221. let rep: JsonResult;
  222. // NOTE: this just selects the first cashier in the list
  223. match send_raw_request(&self.cashiers[0].rpc_url, json!(req)).await {
  224. Ok(v) => rep = v,
  225. Err(e) => {
  226. return JsonResult::Err(jsonerr(ServerError(-32004), Some(e.to_string()), id))
  227. }
  228. }
  229. match rep {
  230. JsonResult::Resp(r) => JsonResult::Resp(r),
  231. JsonResult::Err(e) => JsonResult::Err(e),
  232. JsonResult::Notif(_) => JsonResult::Err(jsonerr(InternalError, None, id)),
  233. }
  234. }
  235. // --> {"method": "deposit", "params": [network, token, publickey]}
  236. // The publickey sent here is used so the cashier can know where to send
  237. // tokens once the deposit is received.
  238. // <-- {"result": "Ht5G1RhkcKnpLVLMhqJc5aqZ4wYUEbxbtZwGCVbgU7DL"}
  239. async fn deposit(&self, id: Value, params: Value) -> JsonResult {
  240. let args = params.as_array();
  241. if args.is_none() {
  242. return JsonResult::Err(jsonerr(InvalidParams, None, id));
  243. }
  244. let args = args.unwrap();
  245. if args.len() != 2 {
  246. return JsonResult::Err(jsonerr(InvalidParams, None, id));
  247. }
  248. let network: &str;
  249. let token: &str;
  250. match (args[0].as_str(), args[1].as_str()) {
  251. (Some(net), Some(tkn)) => {
  252. network = net;
  253. token = tkn;
  254. }
  255. (None, _) => {
  256. return JsonResult::Err(jsonerr(InvalidNetworkParam, None, id));
  257. }
  258. (_, None) => {
  259. return JsonResult::Err(jsonerr(InvalidTokenIdParam, None, id));
  260. }
  261. }
  262. let token_id = match assign_id(network, token, &self.sol_tokenlist) {
  263. Ok(t) => t,
  264. Err(e) => {
  265. return JsonResult::Err(jsonerr(InternalError, Some(e.to_string()), id));
  266. }
  267. };
  268. // TODO: Optional sanity checking here, but cashier *must* do so too.
  269. let pk = self.client.lock().await.main_keypair.public;
  270. let pubkey = bs58::encode(serialize(&pk)).into_string();
  271. // Send request to cashier. If the cashier supports the requested network
  272. // (and token), it shall return a valid address where tokens can be deposited.
  273. // If not, an error is returned, and forwarded to the method caller.
  274. let req = jsonreq(json!("deposit"), json!([network, token_id, pubkey]));
  275. let rep: JsonResult;
  276. match send_raw_request(&self.cashiers[0].rpc_url, json!(req)).await {
  277. Ok(v) => rep = v,
  278. Err(e) => {
  279. debug!(target: "DARKFID", "REQUEST IS ERR");
  280. return JsonResult::Err(jsonerr(ServerError(-32004), Some(e.to_string()), id));
  281. }
  282. }
  283. match rep {
  284. JsonResult::Resp(r) => JsonResult::Resp(r),
  285. JsonResult::Err(e) => JsonResult::Err(e),
  286. JsonResult::Notif(_n) => JsonResult::Err(jsonerr(InternalError, None, id)),
  287. }
  288. }
  289. // --> {"method": "withdraw", "params": [network, token, publickey, amount]}
  290. // The publickey sent here is the address where the caller wants to receive
  291. // the tokens they plan to withdraw.
  292. // On request, send request to cashier to get deposit address, and then transfer
  293. // dark tokens to the cashier's wallet. Following that, the cashier should return
  294. // a transaction ID of them sending the funds that are requested for withdrawal.
  295. // <-- {"result": "txID"}
  296. async fn withdraw(&self, id: Value, params: Value) -> JsonResult {
  297. let args = params.as_array();
  298. if args.is_none() {
  299. return JsonResult::Err(jsonerr(InvalidParams, None, id));
  300. }
  301. let args = args.unwrap();
  302. if args.len() != 4 {
  303. return JsonResult::Err(jsonerr(InvalidParams, None, id));
  304. }
  305. let network: &str;
  306. let token: &str;
  307. let address: &str;
  308. let amount: &str;
  309. match (
  310. args[0].as_str(),
  311. args[1].as_str(),
  312. args[2].as_str(),
  313. args[3].as_str(),
  314. ) {
  315. (Some(net), Some(tkn), Some(addr), Some(val)) => {
  316. network = net;
  317. token = tkn;
  318. address = addr;
  319. amount = val;
  320. }
  321. (None, _, _, _) => {
  322. return JsonResult::Err(jsonerr(InvalidNetworkParam, None, id));
  323. }
  324. (_, None, _, _) => {
  325. return JsonResult::Err(jsonerr(InvalidTokenIdParam, None, id));
  326. }
  327. (_, _, None, _) => {
  328. return JsonResult::Err(jsonerr(InvalidAddressParam, None, id));
  329. }
  330. (_, _, _, None) => {
  331. return JsonResult::Err(jsonerr(InvalidAmountParam, None, id));
  332. }
  333. }
  334. let amount_in_apo = match decode_base10(amount, 8, true) {
  335. Ok(a) => a,
  336. Err(e) => {
  337. return JsonResult::Err(jsonerr(InvalidAmountParam, Some(e.to_string()), id));
  338. }
  339. };
  340. let token_id = match assign_id(network, token, &self.sol_tokenlist) {
  341. Ok(t) => t,
  342. Err(e) => {
  343. return JsonResult::Err(jsonerr(InternalError, Some(e.to_string()), id));
  344. }
  345. };
  346. let req = jsonreq(
  347. json!("withdraw"),
  348. json!([network, token_id, address, amount_in_apo]),
  349. );
  350. let mut rep: JsonResult;
  351. match send_raw_request(&self.cashiers[0].rpc_url, json!(req)).await {
  352. Ok(v) => rep = v,
  353. Err(e) => {
  354. return JsonResult::Err(jsonerr(ServerError(-32004), Some(e.to_string()), id));
  355. }
  356. }
  357. let token_id: &jubjub::Fr;
  358. // get the id for the token
  359. if let Some(tk_id) = self.drk_tokenlist.tokens.get(&token.to_uppercase()) {
  360. token_id = tk_id;
  361. } else {
  362. return JsonResult::Err(jsonerr(InvalidParams, None, id));
  363. }
  364. // send drk to cashier_public
  365. if let JsonResult::Resp(cashier_public) = &rep {
  366. let result: Result<()> = async {
  367. let cashier_public = cashier_public.result.as_str().unwrap();
  368. let cashier_public: jubjub::SubgroupPoint =
  369. deserialize(&bs58::decode(cashier_public).into_vec()?)?;
  370. self.client
  371. .lock()
  372. .await
  373. .transfer(
  374. *token_id,
  375. cashier_public,
  376. amount_in_apo.try_into()?,
  377. self.state.clone(),
  378. )
  379. .await?;
  380. Ok(())
  381. }
  382. .await;
  383. match result {
  384. Err(e) => {
  385. rep = JsonResult::Err(jsonerr(InternalError, Some(e.to_string()), id.clone()))
  386. }
  387. Ok(_) => {
  388. rep = JsonResult::Resp(jsonresp(
  389. json!(format!(
  390. "Sent request to withdraw {} amount of {}",
  391. amount, token_id
  392. )),
  393. id.clone(),
  394. ))
  395. }
  396. }
  397. };
  398. match rep {
  399. JsonResult::Resp(r) => JsonResult::Resp(r),
  400. JsonResult::Err(e) => JsonResult::Err(e),
  401. JsonResult::Notif(_n) => JsonResult::Err(jsonerr(InternalError, None, id)),
  402. }
  403. }
  404. // --> {"method": "transfer", [dToken, address, amount]}
  405. // <-- {"result": "txID"}
  406. async fn transfer(&self, id: Value, params: Value) -> JsonResult {
  407. let args = params.as_array();
  408. if args.is_none() {
  409. return JsonResult::Err(jsonerr(InvalidParams, None, id));
  410. }
  411. let args = args.unwrap();
  412. if args.len() != 3 {
  413. return JsonResult::Err(jsonerr(InvalidParams, None, id));
  414. }
  415. let token: &str;
  416. let address: &str;
  417. let amount: &str;
  418. match (args[0].as_str(), args[1].as_str(), args[2].as_str()) {
  419. (Some(tkn), Some(addr), Some(val)) => {
  420. token = tkn;
  421. address = addr;
  422. amount = val;
  423. }
  424. (None, _, _) => {
  425. return JsonResult::Err(jsonerr(InvalidTokenIdParam, None, id));
  426. }
  427. (_, None, _) => {
  428. return JsonResult::Err(jsonerr(InvalidAddressParam, None, id));
  429. }
  430. (_, _, None) => {
  431. return JsonResult::Err(jsonerr(InvalidAmountParam, None, id));
  432. }
  433. }
  434. let token_id: &jubjub::Fr;
  435. // get the id for the token
  436. if let Some(tk_id) = self.drk_tokenlist.tokens.get(&token.to_uppercase()) {
  437. token_id = tk_id;
  438. } else {
  439. return JsonResult::Err(jsonerr(InvalidParams, None, id));
  440. }
  441. let result: Result<()> = async {
  442. let drk_address = bs58::decode(&address).into_vec()?;
  443. let drk_address: jubjub::SubgroupPoint = deserialize(&drk_address)?;
  444. let decimals: usize = 8;
  445. let amount = decode_base10(amount, decimals, true)?;
  446. self.update_balances().await?;
  447. self.client
  448. .lock()
  449. .await
  450. .transfer(
  451. *token_id,
  452. drk_address,
  453. amount.try_into()?,
  454. self.state.clone(),
  455. )
  456. .await?;
  457. Ok(())
  458. }
  459. .await;
  460. match result {
  461. Ok(_) => JsonResult::Resp(jsonresp(json!("Success"), id)),
  462. Err(err) => JsonResult::Err(jsonerr(InternalError, Some(err.to_string()), json!(id))),
  463. }
  464. }
  465. }
  466. async fn start(
  467. executor: Arc<Executor<'_>>,
  468. local_cashier: Option<&str>,
  469. config: &DarkfidConfig,
  470. ) -> Result<()> {
  471. let wallet = WalletDb::new(
  472. expand_path(&config.wallet_path)?.as_path(),
  473. config.wallet_password.clone(),
  474. )?;
  475. let rocks = Rocks::new(expand_path(&config.database_path.clone())?.as_path())?;
  476. let mut cashiers = Vec::new();
  477. let mut cashier_keys = Vec::new();
  478. if let Some(cpub) = local_cashier {
  479. let cashier_public: jubjub::SubgroupPoint = deserialize(&bs58::decode(cpub).into_vec()?)?;
  480. cashiers.push(Cashier {
  481. name: "localCashier".into(),
  482. rpc_url: "tcp://127.0.0.1:9000".into(),
  483. public_key: cashier_public,
  484. });
  485. cashier_keys.push(cashier_public);
  486. } else {
  487. for cashier in config.clone().cashiers {
  488. if cashier.public_key.is_empty() {
  489. return Err(Error::CashierKeysNotFound);
  490. }
  491. let cashier_public: jubjub::SubgroupPoint =
  492. deserialize(&bs58::decode(cashier.public_key).into_vec()?)?;
  493. cashiers.push(Cashier {
  494. name: cashier.name,
  495. rpc_url: cashier.rpc_url,
  496. public_key: cashier_public,
  497. });
  498. cashier_keys.push(cashier_public);
  499. }
  500. }
  501. // Load trusted setup parameters
  502. let params_paths = (
  503. expand_path(&config.mint_params_path.clone())?,
  504. expand_path(&config.spend_params_path.clone())?,
  505. );
  506. let mint_params_path = params_paths.0.to_str().unwrap_or("mint.params");
  507. let spend_params_path = params_paths.1.to_str().unwrap_or("spend.params");
  508. // Auto create trusted ceremony parameters if they don't exist
  509. if !params_paths.0.exists() {
  510. let params = setup_mint_prover();
  511. save_params(mint_params_path, &params)?;
  512. }
  513. if !params_paths.1.exists() {
  514. let params = setup_spend_prover();
  515. save_params(spend_params_path, &params)?;
  516. }
  517. let (mint_params, mint_pvk) = load_params(mint_params_path)?;
  518. let (spend_params, spend_pvk) = load_params(spend_params_path)?;
  519. let client = Client::new(
  520. rocks.clone(),
  521. (
  522. Url::parse(&config.gateway_protocol_url)?,
  523. Url::parse(&config.gateway_publisher_url)?,
  524. ),
  525. wallet.clone(),
  526. mint_params,
  527. spend_params,
  528. )
  529. .await?;
  530. let client = Arc::new(Mutex::new(client));
  531. let merkle_roots = RocksColumn::<columns::MerkleRoots>::new(rocks.clone());
  532. let nullifiers = RocksColumn::<columns::Nullifiers>::new(rocks);
  533. let state = Arc::new(Mutex::new(State {
  534. tree: CommitmentTree::empty(),
  535. merkle_roots,
  536. nullifiers,
  537. mint_pvk,
  538. spend_pvk,
  539. public_keys: cashier_keys,
  540. }));
  541. let mut darkfid = Darkfid::new(client, state, cashiers).await?;
  542. let server_config = RpcServerConfig {
  543. socket_addr: config.rpc_listen_address,
  544. use_tls: config.serve_tls,
  545. identity_path: expand_path(&config.tls_identity_path.clone())?,
  546. identity_pass: config.tls_identity_password.clone(),
  547. };
  548. darkfid.start(executor.clone()).await?;
  549. listen_and_serve(server_config, Arc::new(darkfid), executor).await
  550. }
  551. #[async_std::main]
  552. async fn main() -> Result<()> {
  553. let args = clap_app!(darkfid =>
  554. (@arg CONFIG: -c --config +takes_value "Sets a custom config file")
  555. (@arg verbose: -v --verbose "Increase verbosity")
  556. (@arg refresh: -r --refresh "Refresh the wallet and slabstore")
  557. (@arg cashier: --cashier +takes_value "Local cashier public key")
  558. )
  559. .get_matches();
  560. let config_path = if args.is_present("CONFIG") {
  561. expand_path(args.value_of("CONFIG").unwrap())?
  562. } else {
  563. join_config_path(&PathBuf::from("darkfid.toml"))?
  564. };
  565. let loglevel = if args.is_present("verbose") {
  566. log::Level::Debug
  567. } else {
  568. log::Level::Info
  569. };
  570. simple_logger::init_with_level(loglevel)?;
  571. let config: DarkfidConfig = Config::<DarkfidConfig>::load(config_path)?;
  572. if args.is_present("refresh") {
  573. debug!(target: "DARKFI DAEMON", "Refresh the wallet and the database");
  574. let wallet = WalletDb::new(
  575. expand_path(&config.wallet_path)?.as_path(),
  576. config.wallet_password.clone(),
  577. )?;
  578. wallet.remove_own_coins()?;
  579. if let Some(path) = expand_path(&config.database_path)?.to_str() {
  580. debug!(target: "DARKFI DAEMON", "Remove database: {}", path);
  581. std::fs::remove_dir_all(path)?;
  582. }
  583. println!("Wallet got updated successfully.");
  584. return Ok(());
  585. }
  586. let mut local_cashier: Option<&str> = None;
  587. if args.is_present("cashier") {
  588. local_cashier = Some(args.value_of("cashier").unwrap())
  589. }
  590. let ex = Arc::new(Executor::new());
  591. let (signal, shutdown) = async_channel::unbounded::<()>();
  592. let ex2 = ex.clone();
  593. let nthreads = num_cpus::get();
  594. debug!(target: "DARKFI DAEMON", "Run {} executor threads", nthreads);
  595. let (_, result) = Parallel::new()
  596. .each(0..nthreads, |_| {
  597. smol::future::block_on(ex.run(shutdown.recv()))
  598. })
  599. // Run the main future on the current thread.
  600. .finish(|| {
  601. smol::future::block_on(async move {
  602. start(ex2, local_cashier, &config).await?;
  603. drop(signal);
  604. Ok::<(), drk::Error>(())
  605. })
  606. });
  607. result
  608. }