rpc_blockchain.rs 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265
  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 tinyjson::JsonValue;
  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. util::encoding::base64,
  30. };
  31. use crate::{server_error, Darkfid, 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 (as string)
  39. //
  40. // **Returns:**
  41. // * [`BlockInfo`](https://darkrenaissance.github.io/darkfi/development/darkfi/consensus/block/struct.BlockInfo.html)
  42. // struct serialized into base64.
  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: u16, params: JsonValue) -> JsonResult {
  47. let params = params.get::<Vec<JsonValue>>().unwrap();
  48. if params.len() != 1 || !params[0].is_string() {
  49. return JsonError::new(InvalidParams, None, id).into()
  50. }
  51. let slot = match params[0].get::<String>().unwrap().parse::<u64>() {
  52. Ok(v) => v,
  53. Err(_) => return JsonError::new(ParseError, None, id).into(),
  54. };
  55. let blocks = match self.validator.read().await.blockchain.get_blocks_by_slot(&[slot]) {
  56. Ok(v) => v,
  57. Err(e) => {
  58. error!(target: "darkfid::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. let block = base64::encode(&serialize(&blocks[0]));
  66. JsonResponse::new(JsonValue::String(block), id).into()
  67. }
  68. // RPCAPI:
  69. // Queries the blockchain database for a given transaction.
  70. // Returns a serialized `Transaction` object.
  71. //
  72. // **Params:**
  73. // * `array[0]`: Hex-encoded transaction hash string
  74. //
  75. // **Returns:**
  76. // * Serialized [`Transaction`](https://darkrenaissance.github.io/darkfi/development/darkfi/tx/struct.Transaction.html)
  77. // object encoded with base64
  78. //
  79. // --> {"jsonrpc": "2.0", "method": "blockchain.get_tx", "params": ["TxHash"], "id": 1}
  80. // <-- {"jsonrpc": "2.0", "result": "ABCD...", "id": 1}
  81. pub async fn blockchain_get_tx(&self, id: u16, params: JsonValue) -> JsonResult {
  82. let params = params.get::<Vec<JsonValue>>().unwrap();
  83. if params.len() != 1 {
  84. return JsonError::new(InvalidParams, None, id).into()
  85. }
  86. let tx_hash = params[0].get::<String>().unwrap();
  87. let tx_hash = match blake3::Hash::from_hex(tx_hash) {
  88. Ok(v) => v,
  89. Err(_) => return JsonError::new(ParseError, None, id).into(),
  90. };
  91. let txs = match self.validator.read().await.blockchain.transactions.get(&[tx_hash], true) {
  92. Ok(txs) => txs,
  93. Err(e) => {
  94. error!(target: "darkfid::rpc::blockchain_get_tx", "Failed fetching tx by hash: {}", e);
  95. return JsonError::new(InternalError, None, id).into()
  96. }
  97. };
  98. // This would be an logic error somewhere
  99. assert_eq!(txs.len(), 1);
  100. // and strict was used during .get()
  101. let tx = txs[0].as_ref().unwrap();
  102. let tx_enc = base64::encode(&serialize(tx));
  103. JsonResponse::new(JsonValue::String(tx_enc), id).into()
  104. }
  105. // RPCAPI:
  106. // Queries the blockchain database to find the last known slot
  107. //
  108. // **Params:**
  109. // * `None`
  110. //
  111. // **Returns:**
  112. // * `u64` ID of the last known slot, as string
  113. //
  114. // --> {"jsonrpc": "2.0", "method": "blockchain.last_known_slot", "params": [], "id": 1}
  115. // <-- {"jsonrpc": "2.0", "result": "1234", "id": 1}
  116. pub async fn blockchain_last_known_slot(&self, id: u16, params: JsonValue) -> JsonResult {
  117. let params = params.get::<Vec<JsonValue>>().unwrap();
  118. if !params.is_empty() {
  119. return JsonError::new(InvalidParams, None, id).into()
  120. }
  121. let blockchain = { self.validator.read().await.blockchain.clone() };
  122. let Ok(last_slot) = blockchain.last() else {
  123. return JsonError::new(InternalError, None, id).into()
  124. };
  125. JsonResponse::new(JsonValue::String(last_slot.0.to_string()), id).into()
  126. }
  127. // RPCAPI:
  128. // Initializes a subscription to new incoming blocks.
  129. // Once a subscription is established, `darkfid` will send JSON-RPC notifications of
  130. // new incoming blocks to the subscriber.
  131. //
  132. // --> {"jsonrpc": "2.0", "method": "blockchain.subscribe_blocks", "params": [], "id": 1}
  133. // <-- {"jsonrpc": "2.0", "method": "blockchain.subscribe_blocks", "params": [`blockinfo`]}
  134. pub async fn blockchain_subscribe_blocks(&self, id: u16, params: JsonValue) -> JsonResult {
  135. let params = params.get::<Vec<JsonValue>>().unwrap();
  136. if !params.is_empty() {
  137. return JsonError::new(InvalidParams, None, id).into()
  138. }
  139. self.subscribers.get("blocks").unwrap().clone().into()
  140. }
  141. // RPCAPI:
  142. // Initializes a subscription to new incoming transactions.
  143. // Once a subscription is established, `darkfid` will send JSON-RPC notifications of
  144. // new incoming transactions to the subscriber.
  145. //
  146. // --> {"jsonrpc": "2.0", "method": "blockchain.subscribe_txs", "params": [], "id": 1}
  147. // <-- {"jsonrpc": "2.0", "method": "blockchain.subscribe_txs", "params": [`tx_hash`]}
  148. pub async fn blockchain_subscribe_txs(&self, id: u16, params: JsonValue) -> JsonResult {
  149. let params = params.get::<Vec<JsonValue>>().unwrap();
  150. if !params.is_empty() {
  151. return JsonError::new(InvalidParams, None, id).into()
  152. }
  153. self.subscribers.get("txs").unwrap().clone().into()
  154. }
  155. // RPCAPI:
  156. // Initializes a subscription to new incoming proposals, asuming node participates
  157. // in consensus. Once a subscription is established, `darkfid` will send JSON-RPC
  158. // notifications of new incoming proposals to the subscriber.
  159. //
  160. // --> {"jsonrpc": "2.0", "method": "blockchain.subscribe_proposals", "params": [], "id": 1}
  161. // <-- {"jsonrpc": "2.0", "method": "blockchain.subscribe_proposals", "params": [`blockinfo`]}
  162. pub async fn blockchain_subscribe_proposals(&self, id: u16, params: JsonValue) -> JsonResult {
  163. let params = params.get::<Vec<JsonValue>>().unwrap();
  164. if !params.is_empty() {
  165. return JsonError::new(InvalidParams, None, id).into()
  166. }
  167. // Since proposals subscriber is only active if we participate to consensus,
  168. // we have to check if it actually exists in the subscribers map.
  169. let proposals_subscriber = self.subscribers.get("proposals");
  170. if proposals_subscriber.is_none() {
  171. error!(target: "darkfid::rpc::blockchain_subscribe_proposals", "Proposals subscriber not found");
  172. return JsonError::new(InternalError, None, id).into()
  173. }
  174. proposals_subscriber.unwrap().clone().into()
  175. }
  176. // RPCAPI:
  177. // Performs a lookup of zkas bincodes for a given contract ID and returns all of
  178. // them, including their namespace.
  179. //
  180. // **Params:**
  181. // * `array[0]`: base58-encoded contract ID string
  182. //
  183. // **Returns:**
  184. // * `array[n]`: Pairs of: `zkas_namespace` string, serialized
  185. // [`ZkBinary`](https://darkrenaissance.github.io/darkfi/development/darkfi/zkas/decoder/struct.ZkBinary.html)
  186. // object
  187. //
  188. // --> {"jsonrpc": "2.0", "method": "blockchain.lookup_zkas", "params": ["6Ef42L1KLZXBoxBuCDto7coi9DA2D2SRtegNqNU4sd74"], "id": 1}
  189. // <-- {"jsonrpc": "2.0", "result": [["Foo", "ABCD..."], ["Bar", "EFGH..."]], "id": 1}
  190. pub async fn blockchain_lookup_zkas(&self, id: u16, params: JsonValue) -> JsonResult {
  191. let params = params.get::<Vec<JsonValue>>().unwrap();
  192. if params.len() != 1 || !params[0].is_string() {
  193. return JsonError::new(InvalidParams, None, id).into()
  194. }
  195. let contract_id = params[0].get::<String>().unwrap();
  196. let contract_id = match ContractId::from_str(contract_id) {
  197. Ok(v) => v,
  198. Err(e) => {
  199. error!(target: "darkfid::rpc::blockchain_lookup_zkas", "Error decoding string to ContractId: {}", e);
  200. return JsonError::new(InvalidParams, None, id).into()
  201. }
  202. };
  203. let blockchain = { self.validator.read().await.blockchain.clone() };
  204. let Ok(zkas_db) = blockchain.contracts.lookup(
  205. &blockchain.sled_db,
  206. &contract_id,
  207. SMART_CONTRACT_ZKAS_DB_NAME,
  208. ) else {
  209. error!(
  210. target: "darkfid::rpc::blockchain_lookup_zkas", "Did not find zkas db for ContractId: {}",
  211. contract_id
  212. );
  213. return server_error(RpcError::ContractZkasDbNotFound, id, None)
  214. };
  215. let mut ret = vec![];
  216. for i in zkas_db.iter() {
  217. debug!(target: "darkfid::rpc::blockchain_lookup_zkas", "Iterating over zkas db");
  218. let Ok((zkas_ns, zkas_bytes)) = i else {
  219. error!(target: "darkfid::rpc::blockchain_lookup_zkas", "Internal sled error iterating db");
  220. return JsonError::new(InternalError, None, id).into()
  221. };
  222. let Ok(zkas_ns) = deserialize(&zkas_ns) else {
  223. return JsonError::new(InternalError, None, id).into()
  224. };
  225. let zkas_bincode = base64::encode(&zkas_bytes);
  226. ret.push(JsonValue::Array(vec![
  227. JsonValue::String(zkas_ns),
  228. JsonValue::String(zkas_bincode),
  229. ]));
  230. }
  231. JsonResponse::new(JsonValue::Array(ret), id).into()
  232. }
  233. }