rpc_blockchain.rs 8.2 KB

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