rpc_blockchain.rs 9.1 KB

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