main.rs 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935
  1. use std::{path::PathBuf, str::FromStr};
  2. use async_executor::Executor;
  3. use async_std::sync::{Arc, Mutex};
  4. use async_trait::async_trait;
  5. use clap::{IntoApp, Parser};
  6. use easy_parallel::Parallel;
  7. use fxhash::FxHashMap;
  8. use log::{debug, info};
  9. use num_bigint::BigUint;
  10. use serde::{Deserialize, Serialize};
  11. use serde_json::{json, Value};
  12. use simplelog::{ColorChoice, TermLogger, TerminalMode};
  13. use url::Url;
  14. use darkfi::{
  15. blockchain::{rocks::columns, Rocks, RocksColumn},
  16. crypto::{
  17. address::Address,
  18. keypair::{Keypair, PublicKey, SecretKey},
  19. proof::VerifyingKey,
  20. token_list::{assign_id, DrkTokenList, TokenList},
  21. types::DrkTokenId,
  22. },
  23. node::{
  24. client::Client,
  25. state::{ProgramState, State},
  26. },
  27. rpc::{
  28. jsonrpc::{
  29. error as jsonerr, request as jsonreq, response as jsonresp, send_request, ErrorCode::*,
  30. JsonRequest, JsonResult,
  31. },
  32. rpcserver::{listen_and_serve, RequestHandler, RpcServerConfig},
  33. },
  34. util::{
  35. cli::{log_config, spawn_config, Config, UrlConfig},
  36. decode_base10, encode_base10, expand_path, join_config_path, NetworkName,
  37. },
  38. wallet::walletdb::WalletDb,
  39. zk::circuit::{MintContract, SpendContract},
  40. Error, Result,
  41. };
  42. #[derive(Clone, Debug, Serialize, Deserialize)]
  43. pub struct CashierC {
  44. /// Cashier name
  45. pub name: String,
  46. /// The selected cashier public key
  47. pub public_key: String,
  48. /// The RPC endpoint for a selected cashier
  49. pub rpc_url: UrlConfig,
  50. }
  51. /// The configuration for darkfid
  52. #[derive(Clone, Serialize, Deserialize, Debug)]
  53. pub struct DarkfidConfig {
  54. /// Path to the client database
  55. pub database_path: String,
  56. /// Path to the wallet database
  57. pub wallet_path: String,
  58. /// The wallet password
  59. pub wallet_password: String,
  60. /// Path to DER-formatted PKCS#12 archive. (used only with tls listener url)
  61. pub tls_identity_path: String,
  62. /// Socks5 server url. eg. `socks5://127.0.0.1:9050` used for tor and nym protocols
  63. pub socks_url: UrlConfig,
  64. /// The address where darkfid should bind its RPC socket
  65. pub rpc_listener_url: UrlConfig,
  66. /// The endpoint to a gatewayd protocol API
  67. pub gateway_url: UrlConfig,
  68. /// The endpoint to a gatewayd publisher API
  69. pub gateway_pub_url: UrlConfig,
  70. /// The configured cashiers to use
  71. pub cashiers: Vec<CashierC>,
  72. }
  73. /// Darkfid cli
  74. #[derive(Parser)]
  75. #[clap(name = "darkfid")]
  76. pub struct CliDarkfid {
  77. /// Sets a custom config file
  78. #[clap(short, long)]
  79. pub config: Option<String>,
  80. /// Local cashier public key
  81. #[clap(long)]
  82. pub cashier: Option<String>,
  83. /// Increase verbosity
  84. #[clap(short, parse(from_occurrences))]
  85. pub verbose: u8,
  86. /// Refresh the wallet and slabstore
  87. #[clap(short, long)]
  88. pub refresh: bool,
  89. }
  90. const CONFIG_FILE_CONTENTS: &[u8] = include_bytes!("../darkfid_config.toml");
  91. pub const ETH_NATIVE_TOKEN_ID: &str = "0x0000000000000000000000000000000000000000";
  92. #[derive(Clone, Debug)]
  93. pub struct Cashier {
  94. pub name: String,
  95. pub rpc_url: Url,
  96. pub public_key: PublicKey,
  97. }
  98. struct Darkfid {
  99. client: Arc<Mutex<Client>>,
  100. state: Arc<Mutex<State>>,
  101. sol_tokenlist: TokenList,
  102. eth_tokenlist: TokenList,
  103. btc_tokenlist: TokenList,
  104. drk_tokenlist: DrkTokenList,
  105. cashiers: Vec<Cashier>,
  106. socks_url: Url,
  107. }
  108. #[async_trait]
  109. impl RequestHandler for Darkfid {
  110. async fn handle_request(&self, req: JsonRequest, _executor: Arc<Executor<'_>>) -> JsonResult {
  111. if req.params.as_array().is_none() {
  112. return JsonResult::Err(jsonerr(InvalidParams, None, req.id))
  113. }
  114. debug!(target: "RPC", "--> {}", serde_json::to_string(&req).unwrap());
  115. if self.update_balances().await.is_err() {
  116. return JsonResult::Err(jsonerr(
  117. InternalError,
  118. Some("Unable to update balances".into()),
  119. req.id,
  120. ))
  121. }
  122. match req.method.as_str() {
  123. Some("say_hello") => return self.say_hello(req.id, req.params).await,
  124. Some("create_wallet") => return self.create_wallet(req.id, req.params).await,
  125. Some("key_gen") => return self.key_gen(req.id, req.params).await,
  126. Some("get_key") => return self.get_key(req.id, req.params).await,
  127. Some("get_keys") => return self.get_keys(req.id, req.params).await,
  128. Some("export_keypair") => return self.export_keypair(req.id, req.params).await,
  129. Some("import_keypair") => return self.import_keypair(req.id, req.params).await,
  130. Some("set_default_address") => {
  131. return self.set_default_address(req.id, req.params).await
  132. }
  133. Some("get_balances") => return self.get_balances(req.id, req.params).await,
  134. Some("get_token_id") => return self.get_token_id(req.id, req.params).await,
  135. Some("features") => return self.features(req.id, req.params).await,
  136. Some("deposit") => return self.deposit(req.id, req.params).await,
  137. Some("withdraw") => return self.withdraw(req.id, req.params).await,
  138. Some("transfer") => return self.transfer(req.id, req.params).await,
  139. Some(_) | None => return JsonResult::Err(jsonerr(MethodNotFound, None, req.id)),
  140. };
  141. }
  142. }
  143. impl Darkfid {
  144. async fn new(
  145. client: Arc<Mutex<Client>>,
  146. state: Arc<Mutex<State>>,
  147. cashiers: Vec<Cashier>,
  148. socks_url: Url,
  149. ) -> Result<Self> {
  150. let sol_tokenlist =
  151. TokenList::new(include_bytes!("../../../contrib/token/solana_token_list.json"))?;
  152. let eth_tokenlist =
  153. TokenList::new(include_bytes!("../../../contrib/token/erc20_token_list.json"))?;
  154. let btc_tokenlist =
  155. TokenList::new(include_bytes!("../../../contrib/token/bitcoin_token_list.json"))?;
  156. let drk_tokenlist = DrkTokenList::new(&sol_tokenlist, &eth_tokenlist, &btc_tokenlist)?;
  157. Ok(Self {
  158. client,
  159. state,
  160. sol_tokenlist,
  161. eth_tokenlist,
  162. btc_tokenlist,
  163. drk_tokenlist,
  164. cashiers,
  165. socks_url,
  166. })
  167. }
  168. async fn start(&mut self, executor: Arc<Executor<'_>>) -> Result<()> {
  169. self.client.lock().await.start().await?;
  170. self.client.lock().await.connect_to_subscriber(self.state.clone(), executor).await?;
  171. Ok(())
  172. }
  173. async fn update_balances(&self) -> Result<()> {
  174. let own_coins = self.client.lock().await.get_own_coins().await?;
  175. for own_coin in own_coins.iter() {
  176. let nullifier_exists = self.state.lock().await.nullifier_exists(&own_coin.nullifier);
  177. if nullifier_exists {
  178. self.client.lock().await.confirm_spend_coin(&own_coin.coin).await?;
  179. }
  180. }
  181. Ok(())
  182. }
  183. // RPCAPI:
  184. // Returns a `helloworld` string.
  185. // --> {"jsonrpc": "2.0", "method": "say_hello", "params": [], "id": 1}
  186. // <-- {"jsonrpc": "2.0", "result": "hello world", "id": 1}
  187. async fn say_hello(&self, id: Value, _params: Value) -> JsonResult {
  188. JsonResult::Resp(jsonresp(json!("hello world"), id))
  189. }
  190. // RPCAPI:
  191. // Attempts to initialize a wallet, and returns `true` upon success.
  192. // --> {"jsonrpc": "2.0", "method": "create_wallet", "params": [], "id": 1}
  193. // <-- {"jsonrpc": "2.0", "result": true, "id": 1}
  194. async fn create_wallet(&self, id: Value, _params: Value) -> JsonResult {
  195. match self.client.lock().await.init_db().await {
  196. Ok(()) => JsonResult::Resp(jsonresp(json!(true), id)),
  197. Err(e) => JsonResult::Err(jsonerr(ServerError(-32001), Some(e.to_string()), id)),
  198. }
  199. }
  200. // RPCAPI:
  201. // Attempts to generate a new keypair and returns `true` upon success.
  202. // --> {"jsonrpc": "2.0", "method": "key_gen", "params": [], "id": 1}
  203. // <-- {"jsonrpc": "2.0", "result": true, "id": 1}
  204. async fn key_gen(&self, id: Value, _params: Value) -> JsonResult {
  205. let client = self.client.lock().await;
  206. match client.keygen().await {
  207. Ok(()) => JsonResult::Resp(jsonresp(json!(true), id)),
  208. Err(e) => JsonResult::Err(jsonerr(ServerError(-32002), Some(e.to_string()), id)),
  209. }
  210. }
  211. // RPCAPI:
  212. // Fetches the main keypair from the wallet and returns it
  213. // in an encoded format.
  214. // --> {"jsonrpc": "2.0", "method": "get_key", "params": [], "id": 1}
  215. // <-- {"jsonrpc": "2.0", "result": "vdNS7oBj7KvsMWWmo9r96SV4SqATLrGsH2a3PGpCfJC", "id": 1}
  216. async fn get_key(&self, id: Value, _params: Value) -> JsonResult {
  217. let pk = self.client.lock().await.main_keypair.public;
  218. let addr = Address::from(pk).to_string();
  219. JsonResult::Resp(jsonresp(json!(addr), id))
  220. }
  221. // RPCAPI:
  222. // Fetches all keypairs from the wallet and returns a list of them
  223. // in an encoded format.
  224. // The first one in the list is the default selected keypair.
  225. // --> {"jsonrpc": "2.0", "method": "get_keys", "params": [], "id": 1}
  226. // <-- {"jsonrpc": "2.0", "result": ["vdNS7oBj7KvsMWWmo9r96SV4SqATLrGsH2a3PGpCfJC", "..."], "id": 1}
  227. async fn get_keys(&self, id: Value, _params: Value) -> JsonResult {
  228. let result: Result<Vec<String>> = async {
  229. let keypairs = self.client.lock().await.get_keypairs().await?;
  230. let default_keypair = self.client.lock().await.main_keypair;
  231. let mut addresses: Vec<String> = keypairs
  232. .iter()
  233. .filter_map(|k| {
  234. if *k == default_keypair {
  235. return None
  236. }
  237. Some(Address::from(k.public).to_string())
  238. })
  239. .collect();
  240. addresses.insert(0, Address::from(default_keypair.public).to_string());
  241. Ok(addresses)
  242. }
  243. .await;
  244. match result {
  245. Ok(addresses) => JsonResult::Resp(jsonresp(json!(addresses), id)),
  246. Err(err) => JsonResult::Err(jsonerr(ServerError(-32003), Some(err.to_string()), id)),
  247. }
  248. }
  249. // RPCAPI:
  250. // Imports a keypair into the wallet with a given path on the filesystem.
  251. // Returns `true` upon success.
  252. // --> {"jsonrpc": "2.0", "method": "import_keypair", "params": ["/path"], "id": 1}
  253. // <-- {"jsonrpc:" "2.0", "result": true, "id": 1}
  254. async fn import_keypair(&self, id: Value, params: Value) -> JsonResult {
  255. let args = params.as_array();
  256. if args.is_none() {
  257. return JsonResult::Err(jsonerr(InvalidParams, None, id))
  258. }
  259. let arg = args.unwrap()[0].clone();
  260. if arg.as_str().is_none() &&
  261. expand_path(arg.as_str().unwrap()).is_ok() &&
  262. expand_path(arg.as_str().unwrap()).unwrap().to_str().is_some()
  263. {
  264. return JsonResult::Err(jsonerr(InvalidParams, Some("invalid path".into()), id))
  265. }
  266. let path = expand_path(arg.as_str().unwrap()).unwrap();
  267. let path = path.to_str().unwrap();
  268. let result: Result<()> = async {
  269. let keypair_str: String = std::fs::read_to_string(path)?;
  270. let mut bytes = [0u8; 32];
  271. let bytes_vec: Vec<u8> = serde_json::from_str(&keypair_str)?;
  272. bytes.copy_from_slice(bytes_vec.as_slice());
  273. let secret: SecretKey = SecretKey::from_bytes(bytes)?;
  274. let public: PublicKey = PublicKey::from_secret(secret);
  275. self.client.lock().await.put_keypair(&Keypair { secret, public }).await?;
  276. Ok(())
  277. }
  278. .await;
  279. match result {
  280. Ok(_) => JsonResult::Resp(jsonresp(json!(true), id)),
  281. Err(err) => JsonResult::Err(jsonerr(ServerError(-32004), Some(err.to_string()), id)),
  282. }
  283. }
  284. // RPCAPI:
  285. // Exports the default selected keypair to a given path on the filesystem.
  286. // Returns `true` upon success.
  287. // --> {"jsonrpc": "2.0", "method": "export_keypair", "params": ["/path"], "id": 1}
  288. // <-- {"jsonrpc": "2.0", "result": true, "id": 1}
  289. async fn export_keypair(&self, id: Value, params: Value) -> JsonResult {
  290. let args = params.as_array();
  291. if args.is_none() {
  292. return JsonResult::Err(jsonerr(InvalidParams, None, id))
  293. }
  294. let arg = args.unwrap()[0].clone();
  295. if arg.as_str().is_none() &&
  296. expand_path(arg.as_str().unwrap()).is_ok() &&
  297. expand_path(arg.as_str().unwrap()).unwrap().to_str().is_some()
  298. {
  299. return JsonResult::Err(jsonerr(InvalidParams, Some("invalid path".into()), id))
  300. }
  301. let path = expand_path(arg.as_str().unwrap()).unwrap();
  302. let path = path.to_str().unwrap();
  303. let result: Result<()> = async {
  304. let keypair: String =
  305. serde_json::to_string(&self.client.lock().await.main_keypair.secret.to_bytes())?;
  306. std::fs::write(path, &keypair)?;
  307. Ok(())
  308. }
  309. .await;
  310. match result {
  311. Ok(_) => JsonResult::Resp(jsonresp(json!(true), id)),
  312. Err(err) => JsonResult::Err(jsonerr(ServerError(-32004), Some(err.to_string()), id)),
  313. }
  314. }
  315. // RPCAPI:
  316. // Sets the default wallet address to the given parameter.
  317. // Returns true upon success.
  318. // --> {"jsonrpc": "2.0", "method": "set_default_address", "params": ["vdNS7oBj7KvsMWWmo9r96SV4SqATLrGsH2a3PGpCfJC"], "id": 1}
  319. // <-- {"jsonrpc": "2.0", "result": true, "id": 1}
  320. async fn set_default_address(&self, id: Value, params: Value) -> JsonResult {
  321. let args = params.as_array();
  322. if args.is_none() && args.unwrap()[0].as_str().is_none() {
  323. return JsonResult::Err(jsonerr(InvalidParams, None, id))
  324. }
  325. let addr_str = args.unwrap()[0].as_str().unwrap();
  326. let result: Result<()> = async {
  327. let public = PublicKey::try_from(Address::from_str(addr_str)?)?;
  328. self.client.lock().await.set_default_keypair(&public).await?;
  329. Ok(())
  330. }
  331. .await;
  332. match result {
  333. Ok(_) => JsonResult::Resp(jsonresp(json!(true), id)),
  334. Err(err) => JsonResult::Err(jsonerr(ServerError(-32005), Some(err.to_string()), id)),
  335. }
  336. }
  337. // RPCAPI:
  338. // Fetches the known balances from the wallet.
  339. // Returns a map of balances, indexed by `network`, and token ID.
  340. // --> {"jsonrpc": "2.0", "method": "get_balances", "params": [], "id": 1}
  341. // <-- {"jsonrpc": "2.0", "result": [{"btc": [100, "Bitcoin"]}, {...}], "id": 1}
  342. async fn get_balances(&self, id: Value, _params: Value) -> JsonResult {
  343. let result: Result<FxHashMap<String, (String, String)>> = async {
  344. let balances = self.client.lock().await.get_balances().await?;
  345. let mut symbols: FxHashMap<String, (String, String)> = FxHashMap::default();
  346. for b in balances.list.iter() {
  347. let network: String;
  348. let symbol: String;
  349. let mut amount = BigUint::from(b.value);
  350. if let Some((net, sym)) = self.drk_tokenlist.symbol_from_id(&b.token_id)? {
  351. network = net.to_string();
  352. symbol = sym;
  353. } else {
  354. // TODO: SQL needs to have the mint address for show, not the internal hash.
  355. // TODO: SQL needs to have the nework name
  356. network = String::from("UNKNOWN");
  357. symbol = format!("{:?}", b.token_id);
  358. }
  359. if let Some(prev) = symbols.get(&symbol) {
  360. let prev_amnt = decode_base10(&prev.0, 8, true)?;
  361. amount += prev_amnt;
  362. }
  363. let amount = encode_base10(amount, 8);
  364. symbols.insert(symbol, (amount, network));
  365. }
  366. Ok(symbols)
  367. }
  368. .await;
  369. match result {
  370. Ok(res) => JsonResult::Resp(jsonresp(json!(res), id)),
  371. Err(err) => JsonResult::Err(jsonerr(InternalError, Some(err.to_string()), json!(id))),
  372. }
  373. }
  374. // RPCAPI:
  375. // Generates the internal token ID for a given `network` and token ticker or address.
  376. // Returns the internal representation of the token ID.
  377. // --> {"jsonrpc": "2.0", "method": "get_token_id", "params": ["network", "token"], "id": 1}
  378. // <-- {"jsonrpc": "2.0", "result": "Ht5G1RhkcKnpLVLMhqJc5aqZ4wYUEbxbtZwGCVbgU7DL", "id": 1}
  379. async fn get_token_id(&self, id: Value, params: Value) -> JsonResult {
  380. let args = params.as_array();
  381. if args.is_none() {
  382. return JsonResult::Err(jsonerr(InvalidParams, None, id))
  383. }
  384. let args = args.unwrap();
  385. if args.len() != 2 {
  386. return JsonResult::Err(jsonerr(InvalidParams, None, id))
  387. }
  388. let network: &str;
  389. let symbol: &str;
  390. match (args[0].as_str(), args[1].as_str()) {
  391. (Some(net), Some(sym)) => {
  392. network = net;
  393. symbol = sym;
  394. }
  395. (None, _) => return JsonResult::Err(jsonerr(InvalidNetworkParam, None, id)),
  396. (_, None) => return JsonResult::Err(jsonerr(InvalidSymbolParam, None, id)),
  397. }
  398. let result: Result<Value> = async {
  399. let network = NetworkName::from_str(network)?;
  400. match network {
  401. NetworkName::Solana => {
  402. if let Some(tkn) = self.sol_tokenlist.search_id(symbol)? {
  403. Ok(json!(tkn))
  404. } else {
  405. Err(Error::NotSupportedToken)
  406. }
  407. }
  408. NetworkName::Bitcoin => {
  409. if let Some(tkn) = self.btc_tokenlist.search_id(symbol)? {
  410. Ok(json!(tkn))
  411. } else {
  412. Err(Error::NotSupportedToken)
  413. }
  414. }
  415. NetworkName::Ethereum => {
  416. if symbol.to_lowercase() == "eth" {
  417. Ok(json!(ETH_NATIVE_TOKEN_ID.to_string()))
  418. } else if let Some(tkn) = self.eth_tokenlist.search_id(symbol)? {
  419. Ok(json!(tkn))
  420. } else {
  421. Err(Error::NotSupportedToken)
  422. }
  423. }
  424. _ => Err(Error::NotSupportedNetwork),
  425. }
  426. }
  427. .await;
  428. match result {
  429. Ok(res) => JsonResult::Resp(jsonresp(json!(res), id)),
  430. Err(err) => JsonResult::Err(jsonerr(InternalError, Some(err.to_string()), json!(id))),
  431. }
  432. }
  433. // RPCAPI:
  434. // Asks the configured cashier for their supported features.
  435. // Returns a map of features received from the requested cashier.
  436. // --> {"jsonrpc": "2.0", "method": "features", "params": [], "id": 1}
  437. // <-- {"jsonrpc": "2.0", "result": {"network": ["btc", "sol"]}, "id": 1}
  438. async fn features(&self, id: Value, _params: Value) -> JsonResult {
  439. let req = jsonreq(json!("features"), json!([]));
  440. let rep: JsonResult =
  441. // NOTE: this just selects the first cashier in the list
  442. match send_request(&self.cashiers[0].rpc_url, json!(req), Some(self.socks_url.clone())).await {
  443. Ok(v) => v,
  444. Err(e) => return JsonResult::Err(jsonerr(ServerError(-32004), Some(e.to_string()), id)),
  445. };
  446. match rep {
  447. JsonResult::Resp(r) => JsonResult::Resp(r),
  448. JsonResult::Err(e) => JsonResult::Err(e),
  449. JsonResult::Notif(_) => JsonResult::Err(jsonerr(InternalError, None, id)),
  450. }
  451. }
  452. // RPCAPI:
  453. // Initializes a DarkFi deposit request for a given `network`, `token`,
  454. // and `publickey`.
  455. // The public key send here is used so the cashier can know where to send
  456. // the newly minted tokens once the deposit is received.
  457. // Returns an address to which the caller is supposed to deposit funds.
  458. // --> {"jsonrpc": "2.0", "method": "deposit", "params": ["network", "token", "publickey"], "id": 1}
  459. // <-- {"jsonrpc": "2.0", "result": "Ht5G1RhkcKnpLVLMhqJc5aqZ4wYUEbxbtZwGCVbgU7DL", "id": 1}
  460. async fn deposit(&self, id: Value, params: Value) -> JsonResult {
  461. let args = params.as_array();
  462. if args.is_none() {
  463. return JsonResult::Err(jsonerr(InvalidParams, None, id))
  464. }
  465. let args = args.unwrap();
  466. if args.len() != 2 {
  467. return JsonResult::Err(jsonerr(InvalidParams, None, id))
  468. }
  469. let network: NetworkName;
  470. let token: &str;
  471. match (args[0].as_str(), args[1].as_str()) {
  472. (Some(net), Some(tkn)) => {
  473. if NetworkName::from_str(net).is_err() {
  474. return JsonResult::Err(jsonerr(InvalidNetworkParam, None, id))
  475. }
  476. network = NetworkName::from_str(net).unwrap();
  477. token = tkn;
  478. }
  479. (None, _) => return JsonResult::Err(jsonerr(InvalidNetworkParam, None, id)),
  480. (_, None) => return JsonResult::Err(jsonerr(InvalidTokenIdParam, None, id)),
  481. }
  482. let token_id = match assign_id(
  483. &network,
  484. token,
  485. &self.sol_tokenlist,
  486. &self.eth_tokenlist,
  487. &self.btc_tokenlist,
  488. ) {
  489. Ok(t) => t,
  490. Err(e) => return JsonResult::Err(jsonerr(InternalError, Some(e.to_string()), id)),
  491. };
  492. let pk = self.client.lock().await.main_keypair.public;
  493. let pubkey = Address::from(pk).to_string();
  494. // Send request to cashier. If the cashier supports the requested network
  495. // (and token), it shall return a valid address where tokens can be deposited.
  496. // If not, an error is returned, and forwarded to the method caller.
  497. let req = jsonreq(json!("deposit"), json!([network, token_id, pubkey]));
  498. let rep: JsonResult =
  499. match send_request(&self.cashiers[0].rpc_url, json!(req), Some(self.socks_url.clone()))
  500. .await
  501. {
  502. Ok(v) => v,
  503. Err(e) => {
  504. debug!(target: "DARKFID", "REQUEST IS ERR");
  505. return JsonResult::Err(jsonerr(ServerError(-32004), Some(e.to_string()), id))
  506. }
  507. };
  508. match rep {
  509. JsonResult::Resp(r) => JsonResult::Resp(r),
  510. JsonResult::Err(e) => JsonResult::Err(e),
  511. JsonResult::Notif(_n) => JsonResult::Err(jsonerr(InternalError, None, id)),
  512. }
  513. }
  514. // RPCAPI:
  515. // Initializes a withdraw request for a given `network`, `token`, `publickey`,
  516. // and `amount`.
  517. // The publickey send here is the address where the caller wants to receive
  518. // the tokens they plan to withdraw.
  519. // On request, sends a request to a cashier to get a deposit address, and
  520. // then transfers wrapped DarkFitokens to the cashier's wallet. Following that,
  521. // the cashier should return a transaction ID of them sending the funds that
  522. // are requested for withdrawal.
  523. // --> {"jsonrpc": "2.0", "method": "withdraw", "params": ["network", "token", "publickey", "amount"], "id": 1}
  524. // <-- {"jsonrpc": "2.0", "result": "txID", "id": 1}
  525. async fn withdraw(&self, id: Value, params: Value) -> JsonResult {
  526. let args = params.as_array();
  527. if args.is_none() {
  528. return JsonResult::Err(jsonerr(InvalidParams, None, id))
  529. }
  530. let args = args.unwrap();
  531. if args.len() != 4 {
  532. return JsonResult::Err(jsonerr(InvalidParams, None, id))
  533. }
  534. let network: NetworkName;
  535. let token: &str;
  536. let address: &str;
  537. let amount: &str;
  538. match (args[0].as_str(), args[1].as_str(), args[2].as_str(), args[3].as_str()) {
  539. (Some(net), Some(tkn), Some(addr), Some(val)) => {
  540. if NetworkName::from_str(net).is_err() {
  541. return JsonResult::Err(jsonerr(InvalidNetworkParam, None, id))
  542. }
  543. network = NetworkName::from_str(net).unwrap();
  544. token = tkn;
  545. address = addr;
  546. amount = val;
  547. }
  548. (None, _, _, _) => return JsonResult::Err(jsonerr(InvalidNetworkParam, None, id)),
  549. (_, None, _, _) => return JsonResult::Err(jsonerr(InvalidTokenIdParam, None, id)),
  550. (_, _, None, _) => return JsonResult::Err(jsonerr(InvalidAddressParam, None, id)),
  551. (_, _, _, None) => return JsonResult::Err(jsonerr(InvalidAmountParam, None, id)),
  552. }
  553. let amount_in_apo = match decode_base10(amount, 8, true) {
  554. Ok(a) => a,
  555. Err(e) => return JsonResult::Err(jsonerr(InvalidAmountParam, Some(e.to_string()), id)),
  556. };
  557. let token_id = match assign_id(
  558. &network,
  559. token,
  560. &self.sol_tokenlist,
  561. &self.eth_tokenlist,
  562. &self.btc_tokenlist,
  563. ) {
  564. Ok(t) => t,
  565. Err(e) => return JsonResult::Err(jsonerr(InternalError, Some(e.to_string()), id)),
  566. };
  567. let req = jsonreq(json!("withdraw"), json!([network, token_id, address, amount_in_apo]));
  568. let mut rep: JsonResult =
  569. match send_request(&self.cashiers[0].rpc_url, json!(req), Some(self.socks_url.clone()))
  570. .await
  571. {
  572. Ok(v) => v,
  573. Err(e) => {
  574. return JsonResult::Err(jsonerr(ServerError(-32004), Some(e.to_string()), id))
  575. }
  576. };
  577. let token_id: &DrkTokenId;
  578. if let Some(tk_id) = self.drk_tokenlist.tokens[&network].get(&token.to_uppercase()) {
  579. token_id = tk_id;
  580. } else {
  581. return JsonResult::Err(jsonerr(InvalidTokenIdParam, None, id))
  582. }
  583. // send drk to cashier_public
  584. if let JsonResult::Resp(cashier_public) = &rep {
  585. let result: Result<()> = async {
  586. let cashier_public = cashier_public.result.as_str().unwrap();
  587. let cashier_public: PublicKey =
  588. PublicKey::try_from(Address::from_str(cashier_public)?)?;
  589. self.client
  590. .lock()
  591. .await
  592. .transfer(
  593. *token_id,
  594. cashier_public,
  595. amount_in_apo.try_into()?,
  596. self.state.clone(),
  597. )
  598. .await?;
  599. Ok(())
  600. }
  601. .await;
  602. match result {
  603. Err(e) => {
  604. rep = JsonResult::Err(jsonerr(InternalError, Some(e.to_string()), id.clone()))
  605. }
  606. Ok(_) => {
  607. rep = JsonResult::Resp(jsonresp(
  608. json!(format!(
  609. "Sent request to withdraw {} amount of {:?}",
  610. amount, token_id
  611. )),
  612. id.clone(),
  613. ))
  614. }
  615. }
  616. };
  617. match rep {
  618. JsonResult::Resp(r) => JsonResult::Resp(r),
  619. JsonResult::Err(e) => JsonResult::Err(e),
  620. JsonResult::Notif(_n) => JsonResult::Err(jsonerr(InternalError, None, id)),
  621. }
  622. }
  623. // RPCAPI:
  624. // Transfer a given wrapped DarkFi token amount to the given address.
  625. // Returns the transaction ID of the transfer.
  626. // --> {"jsonrpc": "2.0", "method": "transfer", "params": ["network", "dToken", "address", "amount"], "id": 1}
  627. // <-- {"jsonrpc": "2.0", "result": "txID", "id": 1}
  628. async fn transfer(&self, id: Value, params: Value) -> JsonResult {
  629. let args = params.as_array();
  630. if args.is_none() {
  631. return JsonResult::Err(jsonerr(InvalidParams, None, id))
  632. }
  633. let args = args.unwrap();
  634. if args.len() != 4 {
  635. return JsonResult::Err(jsonerr(InvalidParams, None, id))
  636. }
  637. let network: NetworkName;
  638. let token: &str;
  639. let address: &str;
  640. let amount: &str;
  641. match (args[0].as_str(), args[1].as_str(), args[2].as_str(), args[3].as_str()) {
  642. (Some(net), Some(tkn), Some(addr), Some(val)) => {
  643. if NetworkName::from_str(net).is_err() {
  644. return JsonResult::Err(jsonerr(InvalidNetworkParam, None, id))
  645. }
  646. network = NetworkName::from_str(net).unwrap();
  647. token = tkn;
  648. address = addr;
  649. amount = val;
  650. }
  651. (None, _, _, _) => return JsonResult::Err(jsonerr(InvalidNetworkParam, None, id)),
  652. (_, None, _, _) => return JsonResult::Err(jsonerr(InvalidTokenIdParam, None, id)),
  653. (_, _, None, _) => return JsonResult::Err(jsonerr(InvalidAddressParam, None, id)),
  654. (_, _, _, None) => return JsonResult::Err(jsonerr(InvalidAmountParam, None, id)),
  655. }
  656. let token_id: &DrkTokenId;
  657. // get the id for the token
  658. if let Some(tk_id) = self.drk_tokenlist.tokens[&network].get(&token.to_uppercase()) {
  659. token_id = tk_id;
  660. } else {
  661. return JsonResult::Err(jsonerr(InvalidTokenIdParam, None, id))
  662. }
  663. let result: Result<()> = async {
  664. let drk_address: PublicKey = PublicKey::try_from(Address::from_str(address)?)?;
  665. let decimals: usize = 8;
  666. let amount = decode_base10(amount, decimals, true)?;
  667. self.client
  668. .lock()
  669. .await
  670. .transfer(*token_id, drk_address, amount.try_into()?, self.state.clone())
  671. .await?;
  672. Ok(())
  673. }
  674. .await;
  675. match result {
  676. Ok(_) => JsonResult::Resp(jsonresp(json!("Success"), id)),
  677. Err(err) => JsonResult::Err(jsonerr(InternalError, Some(err.to_string()), json!(id))),
  678. }
  679. }
  680. }
  681. async fn start(
  682. executor: Arc<Executor<'_>>,
  683. local_cashier: Option<String>,
  684. config: &DarkfidConfig,
  685. ) -> Result<()> {
  686. let wallet_path = format!("sqlite://{}", expand_path(&config.wallet_path)?.to_str().unwrap());
  687. let wallet = WalletDb::new(&wallet_path, &config.wallet_password).await?;
  688. let rocks = Rocks::new(expand_path(&config.database_path.clone())?.as_path())?;
  689. let mut cashiers = Vec::new();
  690. let mut cashier_keys = Vec::new();
  691. if let Some(cpub) = local_cashier {
  692. let cashier_public: PublicKey = PublicKey::try_from(Address::from_str(&cpub)?)?;
  693. cashiers.push(Cashier {
  694. name: "localCashier".into(),
  695. rpc_url: Url::parse("tcp://127.0.0.1:9000")?,
  696. public_key: cashier_public,
  697. });
  698. cashier_keys.push(cashier_public);
  699. } else {
  700. for cashier in config.clone().cashiers {
  701. if cashier.public_key.is_empty() {
  702. return Err(Error::CashierKeysNotFound)
  703. }
  704. let cashier_public: PublicKey =
  705. PublicKey::try_from(Address::from_str(&cashier.public_key)?)?;
  706. cashiers.push(Cashier {
  707. name: cashier.name,
  708. rpc_url: Url::try_from(cashier.rpc_url)?,
  709. public_key: cashier_public,
  710. });
  711. cashier_keys.push(cashier_public);
  712. }
  713. }
  714. let client = Client::new(
  715. rocks.clone(),
  716. (
  717. Url::try_from(config.gateway_url.clone())?,
  718. Url::try_from(config.gateway_pub_url.clone())?,
  719. ),
  720. wallet.clone(),
  721. )
  722. .await?;
  723. let client = Arc::new(Mutex::new(client));
  724. let tree = client.lock().await.get_tree().await?;
  725. let merkle_roots = RocksColumn::<columns::MerkleRoots>::new(rocks.clone());
  726. let nullifiers = RocksColumn::<columns::Nullifiers>::new(rocks);
  727. info!("Building verifying key for the mint contract...");
  728. let mint_vk = VerifyingKey::build(11, &MintContract::default());
  729. info!("Building verifying key for the spend contract...");
  730. let spend_vk = VerifyingKey::build(11, &SpendContract::default());
  731. let state = Arc::new(Mutex::new(State {
  732. tree,
  733. merkle_roots,
  734. nullifiers,
  735. mint_vk,
  736. spend_vk,
  737. public_keys: cashier_keys,
  738. }));
  739. let mut darkfid =
  740. Darkfid::new(client, state, cashiers, Url::try_from(config.socks_url.clone())?).await?;
  741. // TODO fix this
  742. let server_config = RpcServerConfig {
  743. socket_addr: config.rpc_listener_url.url.parse()?,
  744. use_tls: false,
  745. identity_path: expand_path(&config.tls_identity_path.clone())?,
  746. identity_pass: config.rpc_listener_url.password.clone().unwrap(),
  747. };
  748. darkfid.start(executor.clone()).await?;
  749. listen_and_serve(server_config, Arc::new(darkfid), executor).await
  750. }
  751. #[async_std::main]
  752. async fn main() -> Result<()> {
  753. let args = CliDarkfid::parse();
  754. let matches = CliDarkfid::command().get_matches();
  755. let config_path = if args.config.is_some() {
  756. expand_path(&args.config.unwrap())?
  757. } else {
  758. join_config_path(&PathBuf::from("darkfid.toml"))?
  759. };
  760. // Spawn config file if it's not in place already.
  761. spawn_config(&config_path, CONFIG_FILE_CONTENTS)?;
  762. let verbosity_level = matches.occurrences_of("verbose");
  763. let (lvl, conf) = log_config(verbosity_level)?;
  764. TermLogger::init(lvl, conf, TerminalMode::Mixed, ColorChoice::Auto)?;
  765. let config: DarkfidConfig = Config::<DarkfidConfig>::load(config_path)?;
  766. if args.refresh {
  767. info!(target: "DARKFI DAEMON", "Refresh the wallet and the database");
  768. let wallet_path =
  769. format!("sqlite://{}", expand_path(&config.wallet_path)?.to_str().unwrap());
  770. let wallet = WalletDb::new(&wallet_path, &config.wallet_password).await?;
  771. wallet.remove_own_coins().await?;
  772. if let Some(path) = expand_path(&config.database_path)?.to_str() {
  773. info!(target: "DARKFI DAEMON", "Remove database: {}", path);
  774. std::fs::remove_dir_all(path)?;
  775. }
  776. info!("Wallet updated successfully.");
  777. return Ok(())
  778. }
  779. let ex = Arc::new(Executor::new());
  780. let (signal, shutdown) = async_channel::unbounded::<()>();
  781. let ex2 = ex.clone();
  782. let nthreads = num_cpus::get();
  783. debug!(target: "DARKFI DAEMON", "Run {} executor threads", nthreads);
  784. let (_, result) = Parallel::new()
  785. .each(0..nthreads, |_| smol::future::block_on(ex.run(shutdown.recv())))
  786. // Run the main future on the current thread.
  787. .finish(|| {
  788. smol::future::block_on(async move {
  789. start(ex2, args.cashier, &config).await?;
  790. drop(signal);
  791. Ok::<(), darkfi::Error>(())
  792. })
  793. });
  794. result
  795. }