darkfid.rs 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406
  1. use async_trait::async_trait;
  2. use clap::clap_app;
  3. use log::debug;
  4. use serde_json::{json, Value};
  5. use async_std::sync::{Arc, Mutex};
  6. use std::path::PathBuf;
  7. //use std::sync::Arc;
  8. use drk::{
  9. blockchain::Rocks,
  10. cli::{Config, DarkfidConfig},
  11. client::Client,
  12. rpc::{
  13. jsonrpc::{error as jsonerr, request as jsonreq, response as jsonresp, send_request},
  14. jsonrpc::{ErrorCode::*, JsonRequest, JsonResult},
  15. rpcserver::{listen_and_serve, RequestHandler, RpcServerConfig},
  16. },
  17. serial::{deserialize, serialize},
  18. util::{expand_path, join_config_path, parse_network, parse_wrapped_token, TokenList},
  19. wallet::WalletDb,
  20. Result,
  21. };
  22. #[derive(Clone)]
  23. struct Darkfid {
  24. config: DarkfidConfig,
  25. wallet: Arc<WalletDb>,
  26. client: Arc<Mutex<Client>>,
  27. tokenlist: TokenList,
  28. }
  29. #[async_trait]
  30. impl RequestHandler for Darkfid {
  31. // TODO: ServerError codes should be part of the lib.
  32. async fn handle_request(&self, req: JsonRequest) -> JsonResult {
  33. if req.params.as_array().is_none() {
  34. return JsonResult::Err(jsonerr(InvalidParams, None, req.id));
  35. }
  36. debug!(target: "RPC", "--> {}", serde_json::to_string(&req).unwrap());
  37. match req.method.as_str() {
  38. Some("say_hello") => return self.say_hello(req.id, req.params).await,
  39. Some("create_wallet") => return self.create_wallet(req.id, req.params).await,
  40. Some("key_gen") => return self.key_gen(req.id, req.params).await,
  41. Some("get_key") => return self.get_key(req.id, req.params).await,
  42. Some("get_token_id") => return self.get_token_id(req.id, req.params).await,
  43. Some("features") => return self.features(req.id, req.params).await,
  44. Some("deposit") => return self.deposit(req.id, req.params).await,
  45. Some("withdraw") => return self.withdraw(req.id, req.params).await,
  46. Some("transfer") => return self.transfer(req.id, req.params).await,
  47. Some(_) | None => return JsonResult::Err(jsonerr(MethodNotFound, None, req.id)),
  48. };
  49. }
  50. }
  51. impl Darkfid {
  52. fn new(config_path: PathBuf) -> Result<Self> {
  53. let config: DarkfidConfig = Config::<DarkfidConfig>::load(config_path)?;
  54. let wallet = WalletDb::new(
  55. expand_path(&config.wallet_path)?.as_path(),
  56. config.wallet_password.clone(),
  57. )?;
  58. debug!(target: "DARKFID", "INIT WALLET WITH PATH {}", config.wallet_path);
  59. let rocks = Rocks::new(expand_path(&config.database_path.clone())?.as_path())?;
  60. let client = Client::new(
  61. rocks,
  62. (
  63. config.gateway_protocol_url.parse()?,
  64. config.gateway_publisher_url.parse()?,
  65. ),
  66. (
  67. expand_path(&config.mint_params_path.clone())?,
  68. expand_path(&config.spend_params_path.clone())?,
  69. ),
  70. wallet.clone(),
  71. )?;
  72. let client = Arc::new(Mutex::new(client));
  73. let tokenlist = TokenList::new()?;
  74. Ok(Self {
  75. config,
  76. wallet,
  77. client,
  78. tokenlist,
  79. })
  80. }
  81. // --> {"method": "say_hello", "params": []}
  82. // <-- {"result": "hello world"}
  83. async fn say_hello(&self, id: Value, _params: Value) -> JsonResult {
  84. JsonResult::Resp(jsonresp(json!("hello world"), id))
  85. }
  86. // --> {"method": "create_wallet", "params": []}
  87. // <-- {"result": true}
  88. async fn create_wallet(&self, id: Value, _params: Value) -> JsonResult {
  89. match self.wallet.init_db().await {
  90. Ok(()) => return JsonResult::Resp(jsonresp(json!(true), id)),
  91. Err(e) => {
  92. return JsonResult::Err(jsonerr(ServerError(-32001), Some(e.to_string()), id))
  93. }
  94. }
  95. }
  96. // --> {"method": "key_gen", "params": []}
  97. // <-- {"result": true}
  98. async fn key_gen(&self, id: Value, _params: Value) -> JsonResult {
  99. match self.wallet.key_gen() {
  100. Ok(()) => return JsonResult::Resp(jsonresp(json!(true), id)),
  101. Err(e) => {
  102. return JsonResult::Err(jsonerr(ServerError(-32002), Some(e.to_string()), id))
  103. }
  104. }
  105. }
  106. // --> {"method": "get_key", "params": []}
  107. // <-- {"result": "vdNS7oBj7KvsMWWmo9r96SV4SqATLrGsH2a3PGpCfJC"}
  108. async fn get_key(&self, id: Value, _params: Value) -> JsonResult {
  109. match self.wallet.get_keypairs() {
  110. Ok(v) => {
  111. let pk = v[0].public;
  112. let b58 = bs58::encode(serialize(&pk)).into_string();
  113. return JsonResult::Resp(jsonresp(json!(b58), id));
  114. }
  115. Err(e) => {
  116. return JsonResult::Err(jsonerr(ServerError(-32003), Some(e.to_string()), id))
  117. }
  118. }
  119. }
  120. // --> {"method": "get_token_id", "params": [token]}
  121. // <-- {"result": "Ht5G1RhkcKnpLVLMhqJc5aqZ4wYUEbxbtZwGCVbgU7DL"}
  122. async fn get_token_id(&self, id: Value, params: Value) -> JsonResult {
  123. let args = params.as_array();
  124. if args.is_none() {
  125. return JsonResult::Err(jsonerr(InvalidParams, None, id));
  126. }
  127. let args = args.unwrap();
  128. let symbol = args[0].as_str();
  129. if symbol.is_none() {
  130. return JsonResult::Err(jsonerr(InvalidParams, None, id));
  131. }
  132. let symbol = symbol.unwrap();
  133. let result: Result<Value> = async {
  134. let token_id = self.tokenlist.clone().search_id(symbol)?;
  135. Ok(json!(token_id))
  136. }
  137. .await;
  138. match result {
  139. Ok(res) => JsonResult::Resp(jsonresp(json!(res), json!(res))),
  140. Err(err) => JsonResult::Err(jsonerr(InternalError, Some(err.to_string()), json!(id))),
  141. }
  142. }
  143. // --> {""method": "features", "params": []}
  144. // <-- {"result": { "network": ["btc", "sol"] } }
  145. async fn features(&self, id: Value, _params: Value) -> JsonResult {
  146. // TODO: return a dictionary of features
  147. let req = jsonreq(json!("features"), json!([]));
  148. let rep: JsonResult;
  149. match send_request(&self.config.cashier_rpc_url, json!(req)).await {
  150. Ok(v) => rep = v,
  151. Err(e) => {
  152. return JsonResult::Err(jsonerr(ServerError(-32004), Some(e.to_string()), id))
  153. }
  154. }
  155. match rep {
  156. JsonResult::Resp(r) => return JsonResult::Resp(r),
  157. JsonResult::Err(e) => return JsonResult::Err(e),
  158. JsonResult::Notif(_) => return JsonResult::Err(jsonerr(InternalError, None, id)),
  159. }
  160. }
  161. // --> {"method": "deposit", "params": [network, token, publickey]}
  162. // The publickey sent here is used so the cashier can know where to send
  163. // assets once the deposit is received.
  164. // <-- {"result": "Ht5G1RhkcKnpLVLMhqJc5aqZ4wYUEbxbtZwGCVbgU7DL"}
  165. async fn deposit(&self, id: Value, params: Value) -> JsonResult {
  166. let args = params.as_array();
  167. if args.is_none() {
  168. return JsonResult::Err(jsonerr(InvalidParams, None, id));
  169. }
  170. let args = args.unwrap();
  171. if args.len() != 2 {
  172. return JsonResult::Err(jsonerr(InvalidParams, None, id));
  173. }
  174. let network = &args[0];
  175. let token = &args[1];
  176. if token.as_str().is_none() {
  177. return JsonResult::Err(jsonerr(InvalidParams, None, id));
  178. }
  179. let token = token.as_str().unwrap();
  180. if network.as_str().is_none() {
  181. return JsonResult::Err(jsonerr(InvalidParams, None, id));
  182. }
  183. let network = network.as_str().unwrap();
  184. let token_id = match parse_network(&network, &token, self.tokenlist.clone()) {
  185. Ok(t) => t,
  186. Err(_e) => {
  187. debug!(target: "DARKFID", "TOKEN ID IS ERR");
  188. // TODO: this should return the relevant drk error
  189. // right now it just flattens it into ParseError
  190. return JsonResult::Err(jsonerr(ParseError, None, id));
  191. }
  192. };
  193. // TODO: Optional sanity checking here, but cashier *must* do so too.
  194. let pubkey: String;
  195. match self.wallet.get_keypairs() {
  196. Ok(v) => {
  197. let pk = v[0].public;
  198. let pk = serialize(&pk);
  199. pubkey = bs58::encode(pk).into_string();
  200. }
  201. Err(e) => {
  202. return JsonResult::Err(jsonerr(ServerError(-32003), Some(e.to_string()), id))
  203. }
  204. }
  205. // Send request to cashier. If the cashier supports the requested network
  206. // (and token), it shall return a valid address where assets can be deposited.
  207. // If not, an error is returned, and forwarded to the method caller.
  208. let req = jsonreq(json!("deposit"), json!([network, token_id, pubkey]));
  209. let rep: JsonResult;
  210. match send_request(&self.config.cashier_rpc_url, json!(req)).await {
  211. Ok(v) => rep = v,
  212. Err(e) => {
  213. debug!(target: "DARKFID", "REQUEST IS ERR");
  214. return JsonResult::Err(jsonerr(ServerError(-32004), Some(e.to_string()), id));
  215. }
  216. }
  217. match rep {
  218. JsonResult::Resp(r) => return JsonResult::Resp(r),
  219. JsonResult::Err(e) => return JsonResult::Err(e),
  220. JsonResult::Notif(_n) => return JsonResult::Err(jsonerr(InternalError, None, id)),
  221. }
  222. }
  223. // --> {"method": "withdraw", "params": [network, token, publickey, amount]}
  224. // The publickey sent here is the address where the caller wants to receive
  225. // the tokens they plan to withdraw.
  226. // On request, send request to cashier to get deposit address, and then transfer
  227. // dark assets to the cashier's wallet. Following that, the cashier should return
  228. // a transaction ID of them sending the funds that are requested for withdrawal.
  229. // <-- {"result": "txID"}
  230. async fn withdraw(&self, id: Value, params: Value) -> JsonResult {
  231. let args = params.as_array();
  232. if args.is_none() {
  233. return JsonResult::Err(jsonerr(InvalidParams, None, id));
  234. }
  235. let args = args.unwrap();
  236. if args.len() != 4 {
  237. return JsonResult::Err(jsonerr(InvalidParams, None, id));
  238. }
  239. let _network = &args[0];
  240. let _token = &args[1];
  241. let _address = &args[2];
  242. let _amount = &args[3];
  243. // 1. Send request to cashier.
  244. // 2. Cashier checks if they support the network, and if so,
  245. // return adeposit address.
  246. // 3. We issue a transfer of $amount to the given address.
  247. return JsonResult::Err(jsonerr(
  248. ServerError(-32005),
  249. Some("failed to withdraw".to_string()),
  250. id,
  251. ));
  252. }
  253. // --> {"method": "transfer", [dToken, address, amount]}
  254. // <-- {"result": "txID"}
  255. async fn transfer(&self, id: Value, params: Value) -> JsonResult {
  256. let args = params.as_array();
  257. if args.is_none() {
  258. return JsonResult::Err(jsonerr(InvalidParams, None, id));
  259. }
  260. let args = args.unwrap();
  261. if args.len() != 3 {
  262. return JsonResult::Err(jsonerr(InvalidParams, None, id));
  263. }
  264. let token = &args[0];
  265. let address = &args[1];
  266. let amount = &args[2];
  267. if token.as_str().is_none() {
  268. return JsonResult::Err(jsonerr(InvalidParams, None, id));
  269. }
  270. let token = address.as_str().unwrap();
  271. if address.as_str().is_none() {
  272. return JsonResult::Err(jsonerr(InvalidParams, None, id));
  273. }
  274. let address = address.as_str().unwrap();
  275. if amount.as_f64().is_none() {
  276. return JsonResult::Err(jsonerr(InvalidParams, None, id));
  277. }
  278. let amount = amount.as_f64().unwrap();
  279. let result: Result<()> = async {
  280. let token_id = parse_wrapped_token(token, self.tokenlist.clone())?;
  281. let address = bs58::decode(&address).into_vec()?;
  282. let address: jubjub::SubgroupPoint = deserialize(&address)?;
  283. self.client
  284. .lock()
  285. .await
  286. .transfer(token_id, address, amount)
  287. .await?;
  288. Ok(())
  289. }
  290. .await;
  291. match result {
  292. Ok(res) => JsonResult::Resp(jsonresp(json!(res), json!(id))),
  293. Err(err) => JsonResult::Err(jsonerr(InternalError, Some(err.to_string()), json!(id))),
  294. }
  295. }
  296. }
  297. #[async_std::main]
  298. async fn main() -> Result<()> {
  299. let args = clap_app!(darkfid =>
  300. (@arg CONFIG: -c --config +takes_value "Sets a custom config file")
  301. (@arg verbose: -v --verbose "Increase verbosity")
  302. )
  303. .get_matches();
  304. let config_path = if args.is_present("CONFIG") {
  305. PathBuf::from(args.value_of("CONFIG").unwrap())
  306. } else {
  307. join_config_path(&PathBuf::from("darkfid.toml"))?
  308. };
  309. let loglevel = if args.is_present("verbose") {
  310. log::Level::Debug
  311. } else {
  312. log::Level::Info
  313. };
  314. simple_logger::init_with_level(loglevel)?;
  315. let darkfid = Darkfid::new(config_path)?;
  316. let server_config = RpcServerConfig {
  317. socket_addr: darkfid.config.rpc_listen_address.clone(),
  318. use_tls: darkfid.config.serve_tls,
  319. identity_path: expand_path(&darkfid.config.tls_identity_path.clone())?,
  320. identity_pass: darkfid.config.tls_identity_password.clone(),
  321. };
  322. listen_and_serve(server_config, darkfid).await
  323. }
  324. mod tests {
  325. //#[test]
  326. //fn test_token_parsing() {
  327. // let token = "usdc";
  328. // let vec: Vec<char> = token.chars().collect();
  329. // let mut counter = 0;
  330. // for c in vec {
  331. // if c.is_alphabetic() {
  332. // counter += 1;
  333. // println!("Found letter: {}", c)
  334. // }
  335. // }
  336. // if counter == token.len() {
  337. // println!("Every character is a letter");
  338. // }
  339. //}
  340. }