rpc_blockchain.rs 7.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206
  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 std::str::FromStr;
  19. use darkfi_sdk::crypto::ContractId;
  20. use darkfi_serial::{deserialize, serialize};
  21. use log::{debug, error};
  22. use serde_json::{json, Value};
  23. use darkfi::{
  24. rpc::jsonrpc::{
  25. ErrorCode::{InternalError, InvalidParams, ParseError},
  26. JsonError, JsonResponse, JsonResult,
  27. },
  28. runtime::vm_runtime::SMART_CONTRACT_ZKAS_DB_NAME,
  29. };
  30. use crate::{server_error, Darkfid, RpcError};
  31. impl Darkfid {
  32. // RPCAPI:
  33. // Queries the blockchain database for a block in the given slot.
  34. // Returns a readable block upon success.
  35. //
  36. // **Params:**
  37. // * `array[0]`: `u64` slot ID
  38. //
  39. // **Returns:**
  40. // * [`BlockInfo`](https://darkrenaissance.github.io/darkfi/development/darkfi/consensus/block/struct.BlockInfo.html)
  41. // struct as a JSON object
  42. //
  43. // --> {"jsonrpc": "2.0", "method": "blockchain.get_slot", "params": [0], "id": 1}
  44. // <-- {"jsonrpc": "2.0", "result": {...}, "id": 1}
  45. pub async fn blockchain_get_slot(&self, id: Value, params: &[Value]) -> JsonResult {
  46. if params.len() != 1 || !params[0].is_u64() {
  47. return JsonError::new(InvalidParams, None, id).into()
  48. }
  49. let slot = params[0].as_u64().unwrap();
  50. let blocks = match self.validator.read().await.blockchain.get_blocks_by_slot(&[slot]) {
  51. Ok(v) => v,
  52. Err(e) => {
  53. error!(target: "darkfid::rpc::blockchain_get_slot", "Failed fetching block by slot: {}", e);
  54. return JsonError::new(InternalError, None, id).into()
  55. }
  56. };
  57. if blocks.is_empty() {
  58. return server_error(RpcError::UnknownSlot, id, None)
  59. }
  60. JsonResponse::new(json!(serialize(&blocks[0])), id).into()
  61. }
  62. // RPCAPI:
  63. // Queries the blockchain database for a given transaction.
  64. // Returns a serialized `Transaction` object.
  65. //
  66. // **Params:**
  67. // * `array[0]`: Hex-encoded transaction hash string
  68. //
  69. // **Returns:**
  70. // * Serialized [`Transaction`](https://darkrenaissance.github.io/darkfi/development/darkfi/tx/struct.Transaction.html)
  71. // object
  72. //
  73. // --> {"jsonrpc": "2.0", "method": "blockchain.get_tx", "params": ["TxHash"], "id": 1}
  74. // <-- {"jsonrpc": "2.0", "result": {...}, "id": 1}
  75. pub async fn blockchain_get_tx(&self, id: Value, params: &[Value]) -> JsonResult {
  76. if params.len() != 1 {
  77. return JsonError::new(InvalidParams, None, id).into()
  78. }
  79. let tx_hash_str = if let Some(tx_hash_str) = params[0].as_str() {
  80. tx_hash_str
  81. } else {
  82. return JsonError::new(InvalidParams, None, id).into()
  83. };
  84. let tx_hash = if let Ok(tx_hash) = blake3::Hash::from_hex(tx_hash_str) {
  85. tx_hash
  86. } else {
  87. return JsonError::new(ParseError, None, id).into()
  88. };
  89. let txs = match self.validator.read().await.blockchain.transactions.get(&[tx_hash], true) {
  90. Ok(txs) => txs,
  91. Err(e) => {
  92. error!(target: "darkfid::rpc::blockchain_get_tx", "Failed fetching tx by hash: {}", e);
  93. return JsonError::new(InternalError, None, id).into()
  94. }
  95. };
  96. // This would be an logic error somewhere
  97. assert_eq!(txs.len(), 1);
  98. // and strict was used during .get()
  99. let tx = txs[0].as_ref().unwrap();
  100. JsonResponse::new(json!(serialize(tx)), id).into()
  101. }
  102. // RPCAPI:
  103. // Queries the blockchain database to find the last known slot
  104. //
  105. // **Params:**
  106. // * `None`
  107. //
  108. // **Returns:**
  109. // * `u64` ID of the last known slot
  110. //
  111. // --> {"jsonrpc": "2.0", "method": "blockchain.last_known_slot", "params": [], "id": 1}
  112. // <-- {"jsonrpc": "2.0", "result": 1234, "id": 1}
  113. pub async fn blockchain_last_known_slot(&self, id: Value, params: &[Value]) -> JsonResult {
  114. if !params.is_empty() {
  115. return JsonError::new(InvalidParams, None, id).into()
  116. }
  117. let blockchain = { self.validator.read().await.blockchain.clone() };
  118. let Ok(last_slot) = blockchain.last() else {
  119. return JsonError::new(InternalError, None, id).into()
  120. };
  121. JsonResponse::new(json!(last_slot.0), id).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. // **Params:**
  128. // * `array[0]`: base58-encoded contract ID string
  129. //
  130. // **Returns:**
  131. // * `array[n]`: Pairs of: `zkas_namespace` string, serialized
  132. // [`ZkBinary`](https://darkrenaissance.github.io/darkfi/development/darkfi/zkas/decoder/struct.ZkBinary.html)
  133. // object
  134. //
  135. // --> {"jsonrpc": "2.0", "method": "blockchain.lookup_zkas", "params": ["6Ef42L1KLZXBoxBuCDto7coi9DA2D2SRtegNqNU4sd74"], "id": 1}
  136. // <-- {"jsonrpc": "2.0", "result": [["Foo", [...]], ["Bar", [...]]], "id": 1}
  137. pub async fn blockchain_lookup_zkas(&self, id: Value, params: &[Value]) -> JsonResult {
  138. if params.len() != 1 || !params[0].is_string() {
  139. return JsonError::new(InvalidParams, None, id).into()
  140. }
  141. let contract_id = match ContractId::from_str(params[0].as_str().unwrap()) {
  142. Ok(v) => v,
  143. Err(e) => {
  144. error!(target: "darkfid::rpc::blockchain_lookup_zkas", "Error decoding string to ContractId: {}", e);
  145. return JsonError::new(InvalidParams, None, id).into()
  146. }
  147. };
  148. let blockchain = { self.validator.read().await.blockchain.clone() };
  149. let Ok(zkas_db) = blockchain.contracts.lookup(
  150. &blockchain.sled_db,
  151. &contract_id,
  152. SMART_CONTRACT_ZKAS_DB_NAME,
  153. ) else {
  154. error!(
  155. target: "darkfid::rpc::blockchain_lookup_zkas", "Did not find zkas db for ContractId: {}",
  156. contract_id
  157. );
  158. return server_error(RpcError::ContractZkasDbNotFound, id, None)
  159. };
  160. let mut ret: Vec<(String, Vec<u8>)> = vec![];
  161. for i in zkas_db.iter() {
  162. debug!(target: "darkfid::rpc::blockchain_lookup_zkas", "Iterating over zkas db");
  163. let Ok((zkas_ns, zkas_bytes)) = i else {
  164. error!(target: "darkfid::rpc::blockchain_lookup_zkas", "Internal sled error iterating db");
  165. return JsonError::new(InternalError, None, id).into()
  166. };
  167. let Ok(zkas_ns) = deserialize(&zkas_ns) else {
  168. return JsonError::new(InternalError, None, id).into()
  169. };
  170. let Ok((zkas_bincode, _)): Result<(Vec<u8>, Vec<u8>), std::io::Error> =
  171. deserialize(&zkas_bytes)
  172. else {
  173. return JsonError::new(InternalError, None, id).into()
  174. };
  175. ret.push((zkas_ns, zkas_bincode.to_vec()));
  176. }
  177. JsonResponse::new(json!(ret), id).into()
  178. }
  179. }