rpc_blockchain.rs 8.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208
  1. /* This file is part of DarkFi (https://dark.fi)
  2. *
  3. * Copyright (C) 2020-2023 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::ContractId, db::SMART_CONTRACT_ZKAS_DB_NAME};
  19. use darkfi_serial::{deserialize, serialize};
  20. use log::{debug, error};
  21. use serde_json::{json, Value};
  22. use darkfi::rpc::jsonrpc::{
  23. ErrorCode::{InternalError, InvalidParams, ParseError},
  24. JsonError, JsonResponse, JsonResult, JsonSubscriber,
  25. };
  26. use super::Darkfid;
  27. use crate::{server_error, RpcError};
  28. impl Darkfid {
  29. // RPCAPI:
  30. // Queries the blockchain database for a block in the given slot.
  31. // Returns a readable block upon success.
  32. //
  33. // --> {"jsonrpc": "2.0", "method": "blockchain.get_slot", "params": [0], "id": 1}
  34. // <-- {"jsonrpc": "2.0", "result": {...}, "id": 1}
  35. pub async fn blockchain_get_slot(&self, id: Value, params: &[Value]) -> JsonResult {
  36. if params.len() != 1 || !params[0].is_u64() {
  37. return JsonError::new(InvalidParams, None, id).into()
  38. }
  39. let slot = params[0].as_u64().unwrap();
  40. let validator_state = self.validator_state.read().await;
  41. let blocks = match validator_state.blockchain.get_blocks_by_slot(&[slot]) {
  42. Ok(v) => {
  43. drop(validator_state);
  44. v
  45. }
  46. Err(e) => {
  47. error!("[RPC] blockchain.get_slot: Failed fetching block by slot: {}", e);
  48. return JsonError::new(InternalError, None, id).into()
  49. }
  50. };
  51. if blocks.is_empty() {
  52. return server_error(RpcError::UnknownSlot, id, None)
  53. }
  54. JsonResponse::new(json!(serialize(&blocks[0])), id).into()
  55. }
  56. // RPCAPI:
  57. // Queries the blockchain database for a block in the given slot.
  58. // Returns a readable block upon success.
  59. //
  60. // --> {"jsonrpc": "2.0", "method": "blockchain.get_tx", "params": ["TxHash"], "id": 1}
  61. // <-- {"jsonrpc": "2.0", "result": {...}, "id": 1}
  62. pub async fn blockchain_get_tx(&self, id: Value, params: &[Value]) -> JsonResult {
  63. if params.len() != 1 {
  64. return JsonError::new(InvalidParams, None, id).into()
  65. }
  66. let tx_hash_str = if let Some(tx_hash_str) = params[0].as_str() {
  67. tx_hash_str
  68. } else {
  69. return JsonError::new(InvalidParams, None, id).into()
  70. };
  71. let tx_hash = if let Ok(tx_hash) = blake3::Hash::from_hex(tx_hash_str) {
  72. tx_hash
  73. } else {
  74. return JsonError::new(ParseError, None, id).into()
  75. };
  76. let validator_state = self.validator_state.read().await;
  77. let txs = match validator_state.blockchain.transactions.get(&[tx_hash], true) {
  78. Ok(txs) => {
  79. drop(validator_state);
  80. txs
  81. }
  82. Err(e) => {
  83. error!("[RPC] blockchain.get_tx: Failed fetching tx by hash: {}", e);
  84. return JsonError::new(InternalError, None, id).into()
  85. }
  86. };
  87. // This would be an logic error somewhere
  88. assert_eq!(txs.len(), 1);
  89. // and strict was used during .get()
  90. let tx = txs[0].as_ref().unwrap();
  91. JsonResponse::new(json!(serialize(tx)), id).into()
  92. }
  93. // RPCAPI:
  94. // Queries the blockchain database to find the last known slot
  95. //
  96. // --> {"jsonrpc": "2.0", "method": "blockchain.last_known_slot", "params": [], "id": 1}
  97. // <-- {"jsonrpc": "2.0", "result": 1234, "id": 1}
  98. pub async fn blockchain_last_known_slot(&self, id: Value, params: &[Value]) -> JsonResult {
  99. if !params.is_empty() {
  100. return JsonError::new(InvalidParams, None, id).into()
  101. }
  102. let blockchain = { self.validator_state.read().await.blockchain.clone() };
  103. let Ok(last_slot) = blockchain.last() else {
  104. return JsonError::new(InternalError, None, id).into()
  105. };
  106. JsonResponse::new(json!(last_slot.0), id).into()
  107. }
  108. // RPCAPI:
  109. // Initializes a subscription to new incoming blocks.
  110. // Once a subscription is established, `darkfid` will send JSON-RPC notifications of
  111. // new incoming blocks to the subscriber.
  112. //
  113. // --> {"jsonrpc": "2.0", "method": "blockchain.subscribe_blocks", "params": [], "id": 1}
  114. // <-- {"jsonrpc": "2.0", "method": "blockchain.subscribe_blocks", "params": [`blockinfo`]}
  115. pub async fn blockchain_subscribe_blocks(&self, id: Value, params: &[Value]) -> JsonResult {
  116. if !params.is_empty() {
  117. return JsonError::new(InvalidParams, None, id).into()
  118. }
  119. let blocks_subscriber =
  120. self.validator_state.read().await.subscribers.get("blocks").unwrap().clone();
  121. JsonSubscriber::new(blocks_subscriber).into()
  122. }
  123. // RPCAPI:
  124. // Performs a lookup of zkas bincodes for a given contract ID and returns all of
  125. // them, including their namespace.
  126. //
  127. // --> {"jsonrpc": "2.0", "method": "blockchain.lookup_zkas", "params": ["6Ef42L1KLZXBoxBuCDto7coi9DA2D2SRtegNqNU4sd74"], "id": 1}
  128. // <-- {"jsonrpc": "2.0", "result": [["Foo", [...]], ["Bar", [...]]], "id": 1}
  129. pub async fn blockchain_lookup_zkas(&self, id: Value, params: &[Value]) -> JsonResult {
  130. if params.len() != 1 || !params[0].is_string() {
  131. return JsonError::new(InvalidParams, None, id).into()
  132. }
  133. let contract_id = match ContractId::try_from(params[0].as_str().unwrap()) {
  134. Ok(v) => v,
  135. Err(e) => {
  136. error!("[RPC] blockchain.lookup_zkas: Error decoding string to ContractId: {}", e);
  137. return JsonError::new(InvalidParams, None, id).into()
  138. }
  139. };
  140. let blockchain = { self.validator_state.read().await.blockchain.clone() };
  141. let Ok(zkas_db) = blockchain.contracts.lookup(&blockchain.sled_db, &contract_id, SMART_CONTRACT_ZKAS_DB_NAME) else {
  142. error!("[RPC] blockchain.lookup_zkas: Did not find zkas db for ContractId: {}", contract_id);
  143. return server_error(RpcError::ContractZkasDbNotFound, id, None)
  144. };
  145. let mut ret: Vec<(String, Vec<u8>)> = vec![];
  146. for i in zkas_db.iter() {
  147. debug!("Iterating over zkas db");
  148. let Ok((zkas_ns, zkas_bincode)) = i else {
  149. error!("Internal sled error iterating db");
  150. return JsonError::new(InternalError, None, id).into()
  151. };
  152. let Ok(zkas_ns) = deserialize(&zkas_ns) else {
  153. return JsonError::new(InternalError, None, id).into()
  154. };
  155. ret.push((zkas_ns, zkas_bincode.to_vec()));
  156. }
  157. JsonResponse::new(json!(ret), id).into()
  158. }
  159. // RPCAPI:
  160. // Queries the blockchain database to check if the provided transaction hash exists
  161. // in the erroneous transactions set.
  162. //
  163. // --> {"jsonrpc": "2.0", "method": "blockchain.was_erroneous_tx", "params": [[tx_hash bytes]], "id": 1}
  164. // <-- {"jsonrpc": "2.0", "result": bool, "id": 1}
  165. pub async fn blockchain_was_erroneous_tx(&self, id: Value, params: &[Value]) -> JsonResult {
  166. if params.len() != 1 || !params[0].is_array() {
  167. return JsonError::new(InvalidParams, None, id).into()
  168. }
  169. let hash_bytes: [u8; 32] = serde_json::from_value(params[0].clone()).unwrap();
  170. let tx_hash = blake3::Hash::try_from(hash_bytes).unwrap();
  171. let blockchain = { self.validator_state.read().await.blockchain.clone() };
  172. let Ok(result) = blockchain.was_erroneous_tx(&tx_hash) else {
  173. return JsonError::new(InternalError, None, id).into()
  174. };
  175. JsonResponse::new(json!(result), id).into()
  176. }
  177. }