rpc_wallet_old.rs 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362
  1. /* This file is part of DarkFi (https://dark.fi)
  2. *
  3. * Copyright (C) 2020-2022 Dyne.org foundation
  4. *
  5. * This program is free software: you can redistribute it and/or modify
  6. * it under the terms of the GNU Affero General Public License as
  7. * published by the Free Software Foundation, either version 3 of the
  8. * License, or (at your option) any later version.
  9. *
  10. * This program is distributed in the hope that it will be useful,
  11. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. * GNU Affero General Public License for more details.
  14. *
  15. * You should have received a copy of the GNU Affero General Public License
  16. * along with this program. If not, see <https://www.gnu.org/licenses/>.
  17. */
  18. use darkfi_sdk::crypto::{Address, Keypair, PublicKey, SecretKey, TokenId};
  19. use darkfi_serial::{deserialize, serialize};
  20. use fxhash::FxHashMap;
  21. use incrementalmerkletree::Tree;
  22. use log::error;
  23. use serde_json::{json, Value};
  24. use darkfi::{
  25. node::State,
  26. rpc::jsonrpc::{
  27. ErrorCode::{InternalError, InvalidParams, ParseError},
  28. JsonError, JsonResponse, JsonResult,
  29. },
  30. };
  31. use super::Darkfid;
  32. use crate::{server_error, RpcError};
  33. impl Darkfid {
  34. // RPCAPI:
  35. // Attempts to generate a new keypair and returns its address upon success.
  36. //
  37. // --> {"jsonrpc": "2.0", "method": "wallet.keygen", "params": [], "id": 1}
  38. // <-- {"jsonrpc": "2.0", "result": "1DarkFi...", "id": 1}
  39. pub async fn wallet_keygen(&self, id: Value, params: &[Value]) -> JsonResult {
  40. if !params.is_empty() {
  41. return JsonError::new(InvalidParams, None, id).into()
  42. }
  43. match self.client.keygen().await {
  44. Ok(a) => JsonResponse::new(json!(a.to_string()), id).into(),
  45. Err(e) => {
  46. error!("[RPC] wallet.keygen: Failed creating keypair: {}", e);
  47. server_error(RpcError::Keygen, id, None)
  48. }
  49. }
  50. }
  51. // RPCAPI:
  52. // Fetches public keys by given indexes from the wallet and returns it in an
  53. // encoded format. `-1` is supported to fetch all available keys.
  54. //
  55. // --> {"jsonrpc": "2.0", "method": "wallet.get_addrs", "params": [1, 2], "id": 1}
  56. // <-- {"jsonrpc": "2.0", "result": ["foo", "bar"], "id": 1}
  57. pub async fn wallet_get_addrs(&self, id: Value, params: &[Value]) -> JsonResult {
  58. if params.is_empty() {
  59. return JsonError::new(InvalidParams, None, id).into()
  60. }
  61. let mut fetch_all = false;
  62. for (i, elem) in params.iter().enumerate() {
  63. if !elem.is_i64() {
  64. error!("[RPC] wallet.get_addrs: Param {} is not i64", i);
  65. return server_error(RpcError::NaN, id, Some(&format!("Param {} is not i64", i)))
  66. }
  67. if elem.as_i64() == Some(-1) {
  68. if params.len() != 1 {
  69. return server_error(
  70. RpcError::ParseError,
  71. id,
  72. Some("-1 can only be used as a single param"),
  73. )
  74. }
  75. fetch_all = true;
  76. break
  77. }
  78. if elem.as_i64() < Some(-1) {
  79. return server_error(RpcError::LessThanNegOne, id, None)
  80. }
  81. }
  82. let keypairs = match self.client.get_keypairs().await {
  83. Ok(v) => v,
  84. Err(e) => {
  85. error!("[RPC] wallet.get_addrs: Failed fetching keypairs: {}", e);
  86. return server_error(RpcError::KeypairFetch, id, None)
  87. }
  88. };
  89. if fetch_all {
  90. let ret: Vec<String> =
  91. keypairs.iter().map(|x| Address::from(x.public).to_string()).collect();
  92. return JsonResponse::new(json!(ret), id).into()
  93. }
  94. let mut ret = vec![];
  95. for i in params {
  96. // This cast is safe on 64bit since we've already sorted out
  97. // all negative cases above.
  98. let idx = i.as_i64().unwrap() as usize;
  99. if let Some(kp) = keypairs.get(idx) {
  100. ret.push(Some(Address::from(kp.public).to_string()));
  101. } else {
  102. ret.push(None)
  103. }
  104. }
  105. JsonResponse::new(json!(ret), id).into()
  106. }
  107. // RPCAPI:
  108. // Exports the given keypair index.
  109. // Returns the encoded secret key upon success.
  110. //
  111. // --> {"jsonrpc": "2.0", "method": "wallet.export_keypair", "params": [0], "id": 1}
  112. // <-- {"jsonrpc": "2.0", "result": "foobar", "id": 1}
  113. pub async fn wallet_export_keypair(&self, id: Value, params: &[Value]) -> JsonResult {
  114. if params.len() != 1 || !params[0].is_u64() {
  115. return JsonError::new(InvalidParams, None, id).into()
  116. }
  117. let keypairs = match self.client.get_keypairs().await {
  118. Ok(v) => v,
  119. Err(e) => {
  120. error!("[RPC] wallet.export_keypair: Failed fetching keypairs: {}", e);
  121. return server_error(RpcError::KeypairFetch, id, None)
  122. }
  123. };
  124. if let Some(kp) = keypairs.get(params[0].as_u64().unwrap() as usize) {
  125. return JsonResponse::new(json!(serialize(&kp.secret)), id).into()
  126. }
  127. server_error(RpcError::KeypairNotFound, id, None)
  128. }
  129. // RPCAPI:
  130. // Imports a given secret key into the wallet as a keypair.
  131. // Returns the public counterpart as the result upon success.
  132. //
  133. // --> {"jsonrpc": "2.0", "method": "wallet.import_keypair", "params": ["foobar"], "id": 1}
  134. // <-- {"jsonrpc": "2.0", "result": "pubfoobar", "id": 1}
  135. pub async fn wallet_import_keypair(&self, id: Value, params: &[Value]) -> JsonResult {
  136. if params.len() != 1 || !params[0].is_string() {
  137. return JsonError::new(InvalidParams, None, id).into()
  138. }
  139. let bytes: [u8; 32] = match serde_json::from_str(params[0].as_str().unwrap()) {
  140. Ok(v) => v,
  141. Err(e) => {
  142. error!("[RPC] wallet.import_keypair: Failed parsing secret key from string: {}", e);
  143. return server_error(RpcError::InvalidKeypair, id, None)
  144. }
  145. };
  146. let secret = match SecretKey::from_bytes(bytes) {
  147. Ok(v) => v,
  148. Err(e) => {
  149. error!("[RPC] wallet.import_keypair: Failed parsing secret key from string: {}", e);
  150. return server_error(RpcError::InvalidKeypair, id, None)
  151. }
  152. };
  153. let public = PublicKey::from_secret(secret);
  154. let keypair = Keypair { secret, public };
  155. let address = Address::from(public).to_string();
  156. if let Err(e) = self.client.put_keypair(&keypair).await {
  157. error!("[RPC] wallet.import_keypair: Failed inserting keypair into wallet: {}", e);
  158. return JsonError::new(InternalError, None, id).into()
  159. }
  160. JsonResponse::new(json!(address), id).into()
  161. }
  162. // RPCAPI:
  163. // Sets the default wallet address to the given index.
  164. // Returns `true` upon success.
  165. //
  166. // --> {"jsonrpc": "2.0", "method": "wallet.set_default_address", "params": [2], "id": 1}
  167. // <-- {"jsonrpc": "2.0", "result": true, "id": 1}
  168. pub async fn wallet_set_default_address(&self, id: Value, params: &[Value]) -> JsonResult {
  169. if params.len() != 1 || !params[0].is_u64() {
  170. return JsonError::new(InvalidParams, None, id).into()
  171. }
  172. let idx = params[0].as_u64().unwrap();
  173. let keypairs = match self.client.get_keypairs().await {
  174. Ok(v) => v,
  175. Err(e) => {
  176. error!("[RPC] wallet.set_default_address: Failed fetching keypairs: {}", e);
  177. return server_error(RpcError::KeypairFetch, id, None)
  178. }
  179. };
  180. if keypairs.len() as u64 != idx - 1 {
  181. return server_error(RpcError::KeypairNotFound, id, None)
  182. }
  183. let kp = keypairs[idx as usize];
  184. if let Err(e) = self.client.set_default_keypair(&kp.public).await {
  185. error!("[RPC] wallet.set_default_address: Failed setting default keypair: {}", e);
  186. return JsonError::new(InternalError, None, id).into()
  187. }
  188. JsonResponse::new(json!(true), id).into()
  189. }
  190. // RPCAPI:
  191. // Queries the wallet for known tokens with active balances.
  192. // Returns a map of balances, indexed by the token ID.
  193. //
  194. // --> {"jsonrpc": "2.0", "method": "wallet.get_balances", "params": [], "id": 1}
  195. // <-- {"jsonrpc": "2.0", "result": [{"1Foobar...": 100}, {...}]", "id": 1}
  196. pub async fn wallet_get_balances(&self, id: Value, _params: &[Value]) -> JsonResult {
  197. let balances = match self.client.get_balances().await {
  198. Ok(v) => v,
  199. Err(e) => {
  200. error!("[RPC] wallet.get_balances: Failed fetching balances from wallet: {}", e);
  201. return JsonError::new(InternalError, None, id).into()
  202. }
  203. };
  204. // k: token_id, v: [amount]
  205. let mut ret: FxHashMap<String, u64> = FxHashMap::default();
  206. for balance in balances.list {
  207. let token_id = format!("{}", TokenId::from(balance.token_id));
  208. let mut amount = balance.value;
  209. if let Some(prev) = ret.get(&token_id) {
  210. amount += prev;
  211. }
  212. ret.insert(token_id, amount);
  213. }
  214. JsonResponse::new(json!(ret), id).into()
  215. }
  216. // RPCAPI:
  217. // Queries the wallet for a coin containing given parameters (value, token_id, unspent),
  218. // and returns the entire row with the coin's data:
  219. //
  220. // --> {"jsonrpc": "2.0", "method": "wallet.get_coins_valtok", "params": [1234, "F00b4r...", true], "id": 1}
  221. // <-- {"jsonrpc": "2.0", "result": ["coin", "data", ...], "id": 1}
  222. pub async fn wallet_get_coins_valtok(&self, id: Value, params: &[Value]) -> JsonResult {
  223. if params.len() != 3 ||
  224. !params[0].is_u64() ||
  225. !params[1].is_string() ||
  226. !params[2].is_boolean()
  227. {
  228. return JsonError::new(InvalidParams, None, id).into()
  229. }
  230. let value = params[0].as_u64().unwrap();
  231. let unspent = params[2].as_bool().unwrap();
  232. let token_id = match TokenId::try_from(params[1].as_str().unwrap()) {
  233. Ok(v) => v,
  234. Err(e) => {
  235. error!("[RPC] wallet.get_coins_valtok: Failed parsing token_id from base58: {}", e);
  236. return JsonError::new(ParseError, None, id).into()
  237. }
  238. };
  239. let coins = match self.client.get_coins_valtok(value, token_id, unspent).await {
  240. Ok(v) => v,
  241. Err(e) => {
  242. error!("[RPC] wallet.get_coins_valtok: Failed fetching from wallet: {}", e);
  243. return JsonError::new(InternalError, None, id).into()
  244. }
  245. };
  246. let ret: Vec<String> =
  247. coins.iter().map(|x| bs58::encode(serialize(x)).into_string()).collect();
  248. JsonResponse::new(json!(ret), id).into()
  249. }
  250. // RPCAPI:
  251. // Query the state merkle tree for the merkle path of a given leaf position.
  252. //
  253. // --> {"jsonrpc": "2.0", "method": "wallet.get_merkle_path", "params": [3], "id": 1}
  254. // <-- {"jsonrpc": "2.0", "result": ["f091uf1...", "081ff0h10w1h0...", ...], "id": 1}
  255. pub async fn wallet_get_merkle_path(&self, id: Value, params: &[Value]) -> JsonResult {
  256. if params.len() != 1 || !params[0].is_u64() {
  257. return JsonError::new(InvalidParams, None, id).into()
  258. }
  259. let leaf_pos: incrementalmerkletree::Position =
  260. ((params[0].as_u64().unwrap() as u64) as usize).into();
  261. let validator_state = self.validator_state.read().await;
  262. let state = validator_state.state_machine.lock().await;
  263. let root = state.tree.root(0).unwrap();
  264. let merkle_path = state.tree.authentication_path(leaf_pos, &root).unwrap();
  265. drop(state);
  266. drop(validator_state);
  267. let ret: Vec<String> =
  268. merkle_path.iter().map(|x| bs58::encode(serialize(x)).into_string()).collect();
  269. JsonResponse::new(json!(ret), id).into()
  270. }
  271. // RPCAPI:
  272. // Try to decrypt a given encrypted note with the secret keys
  273. // found in the wallet.
  274. //
  275. // --> {"jsonrpc": "2.0", "method": "wallet.decrypt_note", params": [ciphertext], "id": 1}
  276. // <-- {"jsonrpc": "2.0", "result": "base58_encoded_plain_note", "id": 1}
  277. pub async fn wallet_decrypt_note(&self, id: Value, params: &[Value]) -> JsonResult {
  278. if params.len() != 1 || !params[0].is_string() {
  279. return JsonError::new(InvalidParams, None, id).into()
  280. }
  281. let bytes = match bs58::decode(params[0].as_str().unwrap()).into_vec() {
  282. Ok(v) => v,
  283. Err(e) => {
  284. error!("[RPC] wallet.decrypt_note: Failed decoding base58 string: {}", e);
  285. return JsonError::new(ParseError, None, id).into()
  286. }
  287. };
  288. let enc_note = match deserialize(&bytes) {
  289. Ok(v) => v,
  290. Err(e) => {
  291. error!("[RPC] wallet.decrypt_note: Failed deserializing into EncryptedNote: {}", e);
  292. return JsonError::new(InternalError, None, id).into()
  293. }
  294. };
  295. let keypairs = match self.client.get_keypairs().await {
  296. Ok(v) => v,
  297. Err(e) => {
  298. error!("[RPC] wallet.decrypt_note: Failed fetching keypairs: {}", e);
  299. return JsonError::new(InternalError, None, id).into()
  300. }
  301. };
  302. for kp in keypairs {
  303. if let Some(note) = State::try_decrypt_note(&enc_note, kp.secret) {
  304. let s = bs58::encode(&serialize(&note)).into_string();
  305. return JsonResponse::new(json!(s), id).into()
  306. }
  307. }
  308. server_error(RpcError::DecryptionFailed, id, None)
  309. }
  310. }