rpc_wallet.rs 9.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258
  1. use fxhash::FxHashMap;
  2. use log::{error, warn};
  3. use num_bigint::BigUint;
  4. use pasta_curves::group::ff::PrimeField;
  5. use serde_json::{json, Value};
  6. use darkfi::{
  7. crypto::{
  8. address::Address,
  9. keypair::{Keypair, PublicKey, SecretKey},
  10. },
  11. rpc::{
  12. jsonrpc,
  13. jsonrpc::{
  14. ErrorCode::{InternalError, InvalidParams},
  15. JsonResult,
  16. },
  17. },
  18. util::{decode_base10, encode_base10, NetworkName},
  19. };
  20. use super::Darkfid;
  21. use crate::{server_error, RpcError};
  22. impl Darkfid {
  23. // RPCAPI:
  24. // Attempts to generate a new keypair and returns its address upon success.
  25. // --> {"jsonrpc": "2.0", "method": "wallet.keygen", "params": [], "id": 1}
  26. // <-- {"jsonrpc": "2.0", "result": "1DarkFi...", "id": 1}
  27. pub async fn keygen(&self, id: Value, _params: &[Value]) -> JsonResult {
  28. match self.client.keygen().await {
  29. Ok(a) => jsonrpc::response(json!(a.to_string()), id).into(),
  30. Err(e) => {
  31. error!("Failed creating keypair: {}", e);
  32. server_error(RpcError::Keygen, id)
  33. }
  34. }
  35. }
  36. // RPCAPI:
  37. // Fetches public keys by given indexes from the wallet and returns it in an
  38. // encoded format. `-1` is supported to fetch all available keys.
  39. // --> {"jsonrpc": "2.0", "method": "wallet.get_key", "params": [1, 2], "id": 1}
  40. // <-- {"jsonrpc": "2.0", "result": ["foo", "bar"], "id": 1}
  41. pub async fn get_key(&self, id: Value, params: &[Value]) -> JsonResult {
  42. if params.is_empty() {
  43. return jsonrpc::error(InvalidParams, None, id).into()
  44. }
  45. let mut fetch_all = false;
  46. for i in params {
  47. if !i.is_i64() {
  48. return server_error(RpcError::Nan, id)
  49. }
  50. if i.as_i64() == Some(-1) {
  51. fetch_all = true;
  52. break
  53. }
  54. if i.as_i64() < Some(-1) {
  55. return server_error(RpcError::LessThanNegOne, id)
  56. }
  57. }
  58. let keypairs = match self.client.get_keypairs().await {
  59. Ok(v) => v,
  60. Err(e) => {
  61. error!("Failed fetching keypairs: {}", e);
  62. return server_error(RpcError::KeypairFetch, id)
  63. }
  64. };
  65. let mut ret = vec![];
  66. if fetch_all {
  67. ret = keypairs.iter().map(|x| Some(Address::from(x.public).to_string())).collect()
  68. } else {
  69. for i in params {
  70. // This cast is safe on 64bit since we've already sorted out
  71. // all negative cases above.
  72. let idx = i.as_i64().unwrap() as usize;
  73. if let Some(kp) = keypairs.get(idx) {
  74. ret.push(Some(Address::from(kp.public).to_string()));
  75. } else {
  76. ret.push(None)
  77. }
  78. }
  79. }
  80. jsonrpc::response(json!(ret), id).into()
  81. }
  82. // RPCAPI:
  83. // Exports the given keypair index.
  84. // Returns the encoded secret key upon success.
  85. // --> {"jsonrpc": "2.0", "method": "wallet.export_keypair", "params": [0], "id": 1}
  86. // <-- {"jsonrpc": "2.0", "result": "foobar", "id": 1}
  87. pub async fn export_keypair(&self, id: Value, params: &[Value]) -> JsonResult {
  88. if params.len() != 1 || !params[0].is_u64() {
  89. return jsonrpc::error(InvalidParams, None, id).into()
  90. }
  91. let keypairs = match self.client.get_keypairs().await {
  92. Ok(v) => v,
  93. Err(e) => {
  94. error!("Failed fetching keypairs: {}", e);
  95. return server_error(RpcError::KeypairFetch, id)
  96. }
  97. };
  98. if let Some(kp) = keypairs.get(params[0].as_u64().unwrap() as usize) {
  99. return jsonrpc::response(json!(kp.secret.to_bytes()), id).into()
  100. }
  101. server_error(RpcError::KeypairNotFound, id)
  102. }
  103. // RPCAPI:
  104. // Imports a given secret key into the wallet as a keypair.
  105. // Returns the public counterpart as the result upon success.
  106. // --> {"jsonrpc": "2.0", "method": "wallet.import_keypair", "params": ["foobar"], "id": 1}
  107. // <-- {"jsonrpc": "2.0", "result": "pubfoobar", "id": 1}
  108. pub async fn import_keypair(&self, id: Value, params: &[Value]) -> JsonResult {
  109. if params.len() != 1 || !params[0].is_string() {
  110. return jsonrpc::error(InvalidParams, None, id).into()
  111. }
  112. let bytes: [u8; 32] = match serde_json::from_str(params[0].as_str().unwrap()) {
  113. Ok(v) => v,
  114. Err(e) => {
  115. error!("Failed parsing secret key from string: {}", e);
  116. return server_error(RpcError::InvalidKeypair, id)
  117. }
  118. };
  119. let secret = match SecretKey::from_bytes(bytes) {
  120. Ok(v) => v,
  121. Err(e) => {
  122. error!("Failed parsing secret key from string: {}", e);
  123. return server_error(RpcError::InvalidKeypair, id)
  124. }
  125. };
  126. let public = PublicKey::from_secret(secret);
  127. let keypair = Keypair { secret, public };
  128. let address = Address::from(public).to_string();
  129. match self.client.put_keypair(&keypair).await {
  130. Ok(()) => {}
  131. Err(e) => {
  132. error!("Failed inserting keypair into wallet: {}", e);
  133. return jsonrpc::error(InternalError, None, id).into()
  134. }
  135. };
  136. jsonrpc::response(json!(address), id).into()
  137. }
  138. // RPCAPI:
  139. // Sets the default wallet address to the given index.
  140. // Returns `true` upon success.
  141. // --> {"jsonrpc": "2.0", "method": "wallet.set_default_address", "params": [2], "id": 1}
  142. // <-- {"jsonrpc": "2.0", "result": true, "id": 1}
  143. pub async fn set_default_address(&self, id: Value, params: &[Value]) -> JsonResult {
  144. if params.len() != 1 || !params[0].is_u64() {
  145. return jsonrpc::error(InvalidParams, None, id).into()
  146. }
  147. let idx = params[0].as_u64().unwrap();
  148. let keypairs = match self.client.get_keypairs().await {
  149. Ok(v) => v,
  150. Err(e) => {
  151. error!("Failed fetching keypairs: {}", e);
  152. return server_error(RpcError::KeypairFetch, id)
  153. }
  154. };
  155. if keypairs.len() as u64 != idx - 1 {
  156. return server_error(RpcError::KeypairNotFound, id)
  157. }
  158. let kp = keypairs[idx as usize];
  159. match self.client.set_default_keypair(&kp.public).await {
  160. Ok(()) => {}
  161. Err(e) => {
  162. error!("Failed setting default keypair: {}", e);
  163. return jsonrpc::error(InternalError, None, id).into()
  164. }
  165. };
  166. jsonrpc::response(json!(true), id).into()
  167. }
  168. // RPCAPI:
  169. // Queries the wallet for known balances.
  170. // Returns a map of balances, indexed by `network`, and token ID.
  171. // --> {"jsonrpc": "2.0", "method": "wallet.get_balances", "params": [], "id": 1}
  172. // <-- {"jsonrpc": "2.0", "result": [{"btc": [100, "Bitcoin"]}, {...}], "id": 1}
  173. pub async fn get_balances(&self, id: Value, _params: &[Value]) -> JsonResult {
  174. let balances = match self.client.get_balances().await {
  175. Ok(v) => v,
  176. Err(e) => {
  177. error!("Failed fetching balances from wallet: {}", e);
  178. return jsonrpc::error(InternalError, None, id).into()
  179. }
  180. };
  181. // k: ticker/drk_addr, v: (amount, network, net_addr, drk_addr)
  182. let mut ret: FxHashMap<String, (String, String, String, String)> = FxHashMap::default();
  183. for balance in balances.list {
  184. let drk_addr = bs58::encode(balance.token_id.to_repr()).into_string();
  185. let mut amount = BigUint::from(balance.value);
  186. let (net_name, net_addr) =
  187. if let Some((net, tok)) = self.client.tokenlist.by_addr.get(&drk_addr) {
  188. (net, tok.net_address.clone())
  189. } else {
  190. warn!("Could not find network name and token info for {}", drk_addr);
  191. (&NetworkName::DarkFi, "unknown".to_string())
  192. };
  193. let mut ticker = None;
  194. for (k, v) in self.client.tokenlist.by_net[net_name].0.iter() {
  195. if v.net_address == net_addr {
  196. ticker = Some(k.clone());
  197. break
  198. }
  199. }
  200. if ticker.is_none() {
  201. ticker = Some(drk_addr.clone())
  202. }
  203. let ticker = ticker.unwrap();
  204. if let Some(prev) = ret.get(&ticker) {
  205. // TODO: We shouldn't be hardcoding everything to 8 decimals.
  206. let prev_amnt = match decode_base10(&prev.0, 8, false) {
  207. Ok(v) => v,
  208. Err(e) => {
  209. error!("Failed to decode_base10(): {}", e);
  210. return jsonrpc::error(InternalError, None, id).into()
  211. }
  212. };
  213. amount += prev_amnt;
  214. }
  215. let amount = encode_base10(amount, 8);
  216. ret.insert(ticker, (amount, net_name.to_string(), net_addr, drk_addr));
  217. }
  218. jsonrpc::response(json!(ret), id).into()
  219. }
  220. }