darkfid.rs 11 KB

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