rpc_wallet.rs 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331
  1. use fxhash::FxHashMap;
  2. use incrementalmerkletree::Tree;
  3. use log::error;
  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. token_id,
  11. },
  12. node::State,
  13. rpc::jsonrpc::{
  14. ErrorCode::{InternalError, InvalidParams, ParseError},
  15. JsonError, JsonResponse, JsonResult,
  16. },
  17. util::serial::{deserialize, serialize},
  18. };
  19. use super::Darkfid;
  20. use crate::{server_error, RpcError};
  21. impl Darkfid {
  22. // RPCAPI:
  23. // Attempts to generate a new keypair and returns its address upon success.
  24. // --> {"jsonrpc": "2.0", "method": "wallet.keygen", "params": [], "id": 1}
  25. // <-- {"jsonrpc": "2.0", "result": "1DarkFi...", "id": 1}
  26. pub async fn keygen(&self, id: Value, _params: &[Value]) -> JsonResult {
  27. match self.client.keygen().await {
  28. Ok(a) => JsonResponse::new(json!(a.to_string()), id).into(),
  29. Err(e) => {
  30. error!("Failed creating keypair: {}", e);
  31. server_error(RpcError::Keygen, id)
  32. }
  33. }
  34. }
  35. // RPCAPI:
  36. // Fetches public keys by given indexes from the wallet and returns it in an
  37. // encoded format. `-1` is supported to fetch all available keys.
  38. // --> {"jsonrpc": "2.0", "method": "wallet.get_addrs", "params": [1, 2], "id": 1}
  39. // <-- {"jsonrpc": "2.0", "result": ["foo", "bar"], "id": 1}
  40. pub async fn get_addrs(&self, id: Value, params: &[Value]) -> JsonResult {
  41. if params.is_empty() {
  42. return JsonError::new(InvalidParams, None, id).into()
  43. }
  44. let mut fetch_all = false;
  45. for i in params {
  46. if !i.is_i64() {
  47. return server_error(RpcError::Nan, id)
  48. }
  49. if i.as_i64() == Some(-1) {
  50. fetch_all = true;
  51. break
  52. }
  53. if i.as_i64() < Some(-1) {
  54. return server_error(RpcError::LessThanNegOne, id)
  55. }
  56. }
  57. let keypairs = match self.client.get_keypairs().await {
  58. Ok(v) => v,
  59. Err(e) => {
  60. error!("Failed fetching keypairs: {}", e);
  61. return server_error(RpcError::KeypairFetch, id)
  62. }
  63. };
  64. let mut ret = vec![];
  65. if fetch_all {
  66. ret = keypairs.iter().map(|x| Some(Address::from(x.public).to_string())).collect()
  67. } else {
  68. for i in params {
  69. // This cast is safe on 64bit since we've already sorted out
  70. // all negative cases above.
  71. let idx = i.as_i64().unwrap() as usize;
  72. if let Some(kp) = keypairs.get(idx) {
  73. ret.push(Some(Address::from(kp.public).to_string()));
  74. } else {
  75. ret.push(None)
  76. }
  77. }
  78. }
  79. JsonResponse::new(json!(ret), id).into()
  80. }
  81. // RPCAPI:
  82. // Exports the given keypair index.
  83. // Returns the encoded secret key upon success.
  84. // --> {"jsonrpc": "2.0", "method": "wallet.export_keypair", "params": [0], "id": 1}
  85. // <-- {"jsonrpc": "2.0", "result": "foobar", "id": 1}
  86. pub async fn export_keypair(&self, id: Value, params: &[Value]) -> JsonResult {
  87. if params.len() != 1 || !params[0].is_u64() {
  88. return JsonError::new(InvalidParams, None, id).into()
  89. }
  90. let keypairs = match self.client.get_keypairs().await {
  91. Ok(v) => v,
  92. Err(e) => {
  93. error!("Failed fetching keypairs: {}", e);
  94. return server_error(RpcError::KeypairFetch, id)
  95. }
  96. };
  97. if let Some(kp) = keypairs.get(params[0].as_u64().unwrap() as usize) {
  98. return JsonResponse::new(json!(kp.secret.to_bytes()), id).into()
  99. }
  100. server_error(RpcError::KeypairNotFound, id)
  101. }
  102. // RPCAPI:
  103. // Imports a given secret key into the wallet as a keypair.
  104. // Returns the public counterpart as the result upon success.
  105. // --> {"jsonrpc": "2.0", "method": "wallet.import_keypair", "params": ["foobar"], "id": 1}
  106. // <-- {"jsonrpc": "2.0", "result": "pubfoobar", "id": 1}
  107. pub async fn import_keypair(&self, id: Value, params: &[Value]) -> JsonResult {
  108. if params.len() != 1 || !params[0].is_string() {
  109. return JsonError::new(InvalidParams, None, id).into()
  110. }
  111. let bytes: [u8; 32] = match serde_json::from_str(params[0].as_str().unwrap()) {
  112. Ok(v) => v,
  113. Err(e) => {
  114. error!("Failed parsing secret key from string: {}", e);
  115. return server_error(RpcError::InvalidKeypair, id)
  116. }
  117. };
  118. let secret = match SecretKey::from_bytes(bytes) {
  119. Ok(v) => v,
  120. Err(e) => {
  121. error!("Failed parsing secret key from string: {}", e);
  122. return server_error(RpcError::InvalidKeypair, id)
  123. }
  124. };
  125. let public = PublicKey::from_secret(secret);
  126. let keypair = Keypair { secret, public };
  127. let address = Address::from(public).to_string();
  128. match self.client.put_keypair(&keypair).await {
  129. Ok(()) => {}
  130. Err(e) => {
  131. error!("Failed inserting keypair into wallet: {}", e);
  132. return JsonError::new(InternalError, None, id).into()
  133. }
  134. };
  135. JsonResponse::new(json!(address), id).into()
  136. }
  137. // RPCAPI:
  138. // Sets the default wallet address to the given index.
  139. // Returns `true` upon success.
  140. // --> {"jsonrpc": "2.0", "method": "wallet.set_default_address", "params": [2], "id": 1}
  141. // <-- {"jsonrpc": "2.0", "result": true, "id": 1}
  142. pub async fn set_default_address(&self, id: Value, params: &[Value]) -> JsonResult {
  143. if params.len() != 1 || !params[0].is_u64() {
  144. return JsonError::new(InvalidParams, None, id).into()
  145. }
  146. let idx = params[0].as_u64().unwrap();
  147. let keypairs = match self.client.get_keypairs().await {
  148. Ok(v) => v,
  149. Err(e) => {
  150. error!("Failed fetching keypairs: {}", e);
  151. return server_error(RpcError::KeypairFetch, id)
  152. }
  153. };
  154. if keypairs.len() as u64 != idx - 1 {
  155. return server_error(RpcError::KeypairNotFound, id)
  156. }
  157. let kp = keypairs[idx as usize];
  158. match self.client.set_default_keypair(&kp.public).await {
  159. Ok(()) => {}
  160. Err(e) => {
  161. error!("Failed setting default keypair: {}", e);
  162. return JsonError::new(InternalError, None, id).into()
  163. }
  164. };
  165. JsonResponse::new(json!(true), id).into()
  166. }
  167. // RPCAPI:
  168. // Queries the wallet for known tokens with active balances.
  169. // Returns a map of balances, indexed by the token ID.
  170. // --> {"jsonrpc": "2.0", "method": "wallet.get_balances", "params": [], "id": 1}
  171. // <-- {"jsonrpc": "2.0", "result": [{"1Foobar...": 100}, {...}]", "id": 1}
  172. pub async fn get_balances(&self, id: Value, _params: &[Value]) -> JsonResult {
  173. let balances = match self.client.get_balances().await {
  174. Ok(v) => v,
  175. Err(e) => {
  176. error!("Failed fetching balances from wallet: {}", e);
  177. return JsonError::new(InternalError, None, id).into()
  178. }
  179. };
  180. // k: token_id, v: [amount]
  181. let mut ret: FxHashMap<String, u64> = FxHashMap::default();
  182. for balance in balances.list {
  183. let token_id = bs58::encode(balance.token_id.to_repr()).into_string();
  184. let mut amount = balance.value;
  185. if let Some(prev) = ret.get(&token_id) {
  186. amount += prev;
  187. }
  188. ret.insert(token_id, amount);
  189. }
  190. JsonResponse::new(json!(ret), id).into()
  191. }
  192. // RPCAPI:
  193. // Queries the wallet for a coin containing given parameters (value, token_id, unspent),
  194. // and returns the entire row with the coin's data:
  195. //
  196. // --> {"jsonrpc": "2.0", "method": "wallet.get_coins_valtok", "params": [1234, "F00b4r...", true], "id": 1}
  197. // <-- {"jsonrpc": "2.0", "result": ["coin", "data", ...], "id": 1}
  198. pub async fn get_coins_valtok(&self, id: Value, params: &[Value]) -> JsonResult {
  199. if params.len() != 3 ||
  200. !params[0].is_u64() ||
  201. !params[1].is_string() ||
  202. !params[2].is_boolean()
  203. {
  204. return JsonError::new(InvalidParams, None, id).into()
  205. }
  206. let value = params[0].as_u64().unwrap();
  207. let unspent = params[2].as_bool().unwrap();
  208. let token_id = match token_id::parse_b58(params[1].as_str().unwrap()) {
  209. Ok(v) => v,
  210. Err(e) => {
  211. error!("Failed parsing token_id from base58 string: {}", e);
  212. return JsonError::new(ParseError, None, id).into()
  213. }
  214. };
  215. let coins = match self.client.get_coins_valtok(value, token_id, unspent).await {
  216. Ok(v) => v,
  217. Err(e) => {
  218. error!("Failed fetching coins by valtok from wallet: {}", e);
  219. return JsonError::new(InternalError, None, id).into()
  220. }
  221. };
  222. let ret: Vec<String> =
  223. coins.iter().map(|x| bs58::encode(serialize(x)).into_string()).collect();
  224. JsonResponse::new(json!(ret), id).into()
  225. }
  226. // RPCAPI:
  227. // Query the state merkle tree for the merkle path of a given leaf position.
  228. // --> {"jsonrpc": "2.0", "method": "wallet.get_merkle_path", "params": [3], "id": 1}
  229. // <-- {"jsonrpc": "2.0", "result": ["f091uf1...", "081ff0h10w1h0...", ...], "id": 1}
  230. pub async fn get_merkle_path(&self, id: Value, params: &[Value]) -> JsonResult {
  231. if params.len() != 1 || !params[0].is_u64() {
  232. return JsonError::new(InvalidParams, None, id).into()
  233. }
  234. let leaf_pos: incrementalmerkletree::Position =
  235. ((params[0].as_u64().unwrap() as u64) as usize).into();
  236. let validator_state = self.validator_state.read().await;
  237. let state = validator_state.state_machine.lock().await;
  238. let root = state.tree.root(0).unwrap();
  239. let merkle_path = state.tree.authentication_path(leaf_pos, &root).unwrap();
  240. drop(state);
  241. drop(validator_state);
  242. let ret: Vec<String> =
  243. merkle_path.iter().map(|x| bs58::encode(serialize(x)).into_string()).collect();
  244. JsonResponse::new(json!(ret), id).into()
  245. }
  246. // RPCAPI:
  247. // Try to decrypt a given encrypted note with the secret keys
  248. // found in the wallet.
  249. // --> {"jsonrpc": "2.0", "method": "wallet.decrypt_note", params": [ciphertext], "id": 1}
  250. // <-- {"jsonrpc": "2.0", "result": "base58_encoded_plain_note", "id": 1}
  251. pub async fn decrypt_note(&self, id: Value, params: &[Value]) -> JsonResult {
  252. if params.len() != 1 || !params[0].is_string() {
  253. return JsonError::new(InvalidParams, None, id).into()
  254. }
  255. let bytes = match bs58::decode(params[0].as_str().unwrap()).into_vec() {
  256. Ok(v) => v,
  257. Err(e) => {
  258. error!("decrypt_note(): Failed decoding base58 string: {}", e);
  259. return JsonError::new(ParseError, None, id).into()
  260. }
  261. };
  262. let enc_note = match deserialize(&bytes) {
  263. Ok(v) => v,
  264. Err(e) => {
  265. error!("decrypt_note(): Failed deserializing bytes into EncryptedNote: {}", e);
  266. return JsonError::new(InternalError, None, id).into()
  267. }
  268. };
  269. let keypairs = match self.client.get_keypairs().await {
  270. Ok(v) => v,
  271. Err(e) => {
  272. error!("decrypt_note(): Failed fetching keypairs: {}", e);
  273. return JsonError::new(InternalError, None, id).into()
  274. }
  275. };
  276. for kp in keypairs {
  277. if let Some(note) = State::try_decrypt_note(&enc_note, kp.secret) {
  278. let s = bs58::encode(&serialize(&note)).into_string();
  279. return JsonResponse::new(json!(s), id).into()
  280. }
  281. }
  282. server_error(RpcError::DecryptionFailed, id)
  283. }
  284. }