rpc_blockchain.rs 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263
  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 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. // Initializes a subscription to new incoming blocks.
  125. // Once a subscription is established, `darkfid` will send JSON-RPC notifications of
  126. // new incoming blocks to the subscriber.
  127. //
  128. // --> {"jsonrpc": "2.0", "method": "blockchain.subscribe_blocks", "params": [], "id": 1}
  129. // <-- {"jsonrpc": "2.0", "method": "blockchain.subscribe_blocks", "params": [`blockinfo`]}
  130. pub async fn blockchain_subscribe_blocks(&self, id: Value, params: &[Value]) -> JsonResult {
  131. if !params.is_empty() {
  132. return JsonError::new(InvalidParams, None, id).into()
  133. }
  134. let blocks_subscriber = self.subscribers.get("blocks").unwrap().clone();
  135. JsonSubscriber::new(blocks_subscriber).into()
  136. }
  137. // RPCAPI:
  138. // Initializes a subscription to new incoming transactions.
  139. // Once a subscription is established, `darkfid` will send JSON-RPC notifications of
  140. // new incoming transactions to the subscriber.
  141. //
  142. // --> {"jsonrpc": "2.0", "method": "blockchain.subscribe_txs", "params": [], "id": 1}
  143. // <-- {"jsonrpc": "2.0", "method": "blockchain.subscribe_txs", "params": [`tx_hash`]}
  144. pub async fn blockchain_subscribe_txs(&self, id: Value, params: &[Value]) -> JsonResult {
  145. if !params.is_empty() {
  146. return JsonError::new(InvalidParams, None, id).into()
  147. }
  148. let txs_subscriber = self.subscribers.get("txs").unwrap().clone();
  149. JsonSubscriber::new(txs_subscriber).into()
  150. }
  151. // RPCAPI:
  152. // Initializes a subscription to new incoming proposals, asuming node participates
  153. // in consensus. Once a subscription is established, `darkfid` will send JSON-RPC
  154. // notifications of new incoming proposals to the subscriber.
  155. //
  156. // --> {"jsonrpc": "2.0", "method": "blockchain.subscribe_proposals", "params": [], "id": 1}
  157. // <-- {"jsonrpc": "2.0", "method": "blockchain.subscribe_proposals", "params": [`blockinfo`]}
  158. pub async fn blockchain_subscribe_proposals(&self, id: Value, params: &[Value]) -> JsonResult {
  159. if !params.is_empty() {
  160. return JsonError::new(InvalidParams, None, id).into()
  161. }
  162. // Since proposals subscriber is only active if we participate to consensus,
  163. // we have to check if it actually exists in the subscribers map.
  164. let proposals_subscriber = self.subscribers.get("proposals");
  165. if proposals_subscriber.is_none() {
  166. error!(target: "darkfid::rpc::blockchain_subscribe_proposals", "Proposals subscriber not found");
  167. return JsonError::new(InternalError, None, id).into()
  168. }
  169. JsonSubscriber::new(proposals_subscriber.unwrap().clone()).into()
  170. }
  171. // RPCAPI:
  172. // Performs a lookup of zkas bincodes for a given contract ID and returns all of
  173. // them, including their namespace.
  174. //
  175. // **Params:**
  176. // * `array[0]`: base58-encoded contract ID string
  177. //
  178. // **Returns:**
  179. // * `array[n]`: Pairs of: `zkas_namespace` string, serialized
  180. // [`ZkBinary`](https://darkrenaissance.github.io/darkfi/development/darkfi/zkas/decoder/struct.ZkBinary.html)
  181. // object
  182. //
  183. // --> {"jsonrpc": "2.0", "method": "blockchain.lookup_zkas", "params": ["6Ef42L1KLZXBoxBuCDto7coi9DA2D2SRtegNqNU4sd74"], "id": 1}
  184. // <-- {"jsonrpc": "2.0", "result": [["Foo", [...]], ["Bar", [...]]], "id": 1}
  185. pub async fn blockchain_lookup_zkas(&self, id: Value, params: &[Value]) -> JsonResult {
  186. if params.len() != 1 || !params[0].is_string() {
  187. return JsonError::new(InvalidParams, None, id).into()
  188. }
  189. let contract_id = match ContractId::from_str(params[0].as_str().unwrap()) {
  190. Ok(v) => v,
  191. Err(e) => {
  192. error!(target: "darkfid::rpc::blockchain_lookup_zkas", "Error decoding string to ContractId: {}", e);
  193. return JsonError::new(InvalidParams, None, id).into()
  194. }
  195. };
  196. let blockchain = { self.validator.read().await.blockchain.clone() };
  197. let Ok(zkas_db) = blockchain.contracts.lookup(
  198. &blockchain.sled_db,
  199. &contract_id,
  200. SMART_CONTRACT_ZKAS_DB_NAME,
  201. ) else {
  202. error!(
  203. target: "darkfid::rpc::blockchain_lookup_zkas", "Did not find zkas db for ContractId: {}",
  204. contract_id
  205. );
  206. return server_error(RpcError::ContractZkasDbNotFound, id, None)
  207. };
  208. let mut ret: Vec<(String, Vec<u8>)> = vec![];
  209. for i in zkas_db.iter() {
  210. debug!(target: "darkfid::rpc::blockchain_lookup_zkas", "Iterating over zkas db");
  211. let Ok((zkas_ns, zkas_bytes)) = i else {
  212. error!(target: "darkfid::rpc::blockchain_lookup_zkas", "Internal sled error iterating db");
  213. return JsonError::new(InternalError, None, id).into()
  214. };
  215. let Ok(zkas_ns) = deserialize(&zkas_ns) else {
  216. return JsonError::new(InternalError, None, id).into()
  217. };
  218. let Ok((zkas_bincode, _)): Result<(Vec<u8>, Vec<u8>), std::io::Error> =
  219. deserialize(&zkas_bytes)
  220. else {
  221. return JsonError::new(InternalError, None, id).into()
  222. };
  223. ret.push((zkas_ns, zkas_bincode.to_vec()));
  224. }
  225. JsonResponse::new(json!(ret), id).into()
  226. }
  227. }