rpc_blockchain.rs 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422
  1. /* This file is part of DarkFi (https://dark.fi)
  2. *
  3. * Copyright (C) 2020-2025 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, tx::TransactionHash};
  20. use darkfi_serial::{deserialize_async, serialize_async};
  21. use log::{debug, error};
  22. use tinyjson::JsonValue;
  23. use darkfi::{
  24. blockchain::contract_store::SMART_CONTRACT_ZKAS_DB_NAME,
  25. rpc::jsonrpc::{
  26. ErrorCode::{InternalError, InvalidParams, ParseError},
  27. JsonError, JsonResponse, JsonResult,
  28. },
  29. util::encoding::base64,
  30. };
  31. use crate::{server_error, DarkfiNode, RpcError};
  32. impl DarkfiNode {
  33. // RPCAPI:
  34. // Queries the blockchain database for a block in the given height.
  35. // Returns a readable block upon success.
  36. //
  37. // **Params:**
  38. // * `array[0]`: `u64` Block height (as string)
  39. //
  40. // **Returns:**
  41. // * [`BlockInfo`](https://darkrenaissance.github.io/darkfi/dev/darkfi/blockchain/block_store/struct.BlockInfo.html)
  42. // struct serialized into base64.
  43. //
  44. // --> {"jsonrpc": "2.0", "method": "blockchain.get_block", "params": ["0"], "id": 1}
  45. // <-- {"jsonrpc": "2.0", "result": {...}, "id": 1}
  46. pub async fn blockchain_get_block(&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 block_height = match params[0].get::<String>().unwrap().parse::<u32>() {
  52. Ok(v) => v,
  53. Err(_) => return JsonError::new(ParseError, None, id).into(),
  54. };
  55. let blocks = match self.validator.blockchain.get_blocks_by_heights(&[block_height]) {
  56. Ok(v) => v,
  57. Err(e) => {
  58. error!(target: "darkfid::rpc::blockchain_get_block", "Failed fetching block by height: {}", e);
  59. return JsonError::new(InternalError, None, id).into()
  60. }
  61. };
  62. if blocks.is_empty() {
  63. return server_error(RpcError::UnknownBlockHeight, id, None)
  64. }
  65. let block = base64::encode(&serialize_async(&blocks[0]).await);
  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/dev/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 || !params[0].is_string() {
  84. return JsonError::new(InvalidParams, None, id).into()
  85. }
  86. let tx_hash = params[0].get::<String>().unwrap();
  87. let tx_hash = match TransactionHash::from_str(tx_hash) {
  88. Ok(v) => v,
  89. Err(_) => return JsonError::new(ParseError, None, id).into(),
  90. };
  91. let txs = match self.validator.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_async(tx).await);
  103. JsonResponse::new(JsonValue::String(tx_enc), id).into()
  104. }
  105. // RPCAPI:
  106. // Queries the blockchain database to find the last confirmed block.
  107. //
  108. // **Params:**
  109. // * `None`
  110. //
  111. // **Returns:**
  112. // * `f64` : Height of the last confirmed block
  113. // * `String`: Header hash of the last confirmed block
  114. //
  115. // --> {"jsonrpc": "2.0", "method": "blockchain.last_confirmed_block", "params": [], "id": 1}
  116. // <-- {"jsonrpc": "2.0", "result": [1234, "HeaderHash"], "id": 1}
  117. pub async fn blockchain_last_confirmed_block(&self, id: u16, params: JsonValue) -> JsonResult {
  118. let params = params.get::<Vec<JsonValue>>().unwrap();
  119. if !params.is_empty() {
  120. return JsonError::new(InvalidParams, None, id).into()
  121. }
  122. let Ok((height, hash)) = self.validator.blockchain.last() else {
  123. return JsonError::new(InternalError, None, id).into()
  124. };
  125. JsonResponse::new(
  126. JsonValue::Array(vec![
  127. JsonValue::Number(height as f64),
  128. JsonValue::String(hash.to_string()),
  129. ]),
  130. id,
  131. )
  132. .into()
  133. }
  134. // RPCAPI:
  135. // Queries the validator to find the current best fork next block height.
  136. //
  137. // **Params:**
  138. // * `None`
  139. //
  140. // **Returns:**
  141. // * `f64`: Current best fork next block height
  142. //
  143. // --> {"jsonrpc": "2.0", "method": "blockchain.best_fork_next_block_height", "params": [], "id": 1}
  144. // <-- {"jsonrpc": "2.0", "result": 1234, "id": 1}
  145. pub async fn blockchain_best_fork_next_block_height(
  146. &self,
  147. id: u16,
  148. params: JsonValue,
  149. ) -> JsonResult {
  150. let params = params.get::<Vec<JsonValue>>().unwrap();
  151. if !params.is_empty() {
  152. return JsonError::new(InvalidParams, None, id).into()
  153. }
  154. let Ok(next_block_height) = self.validator.best_fork_next_block_height().await else {
  155. return JsonError::new(InternalError, None, id).into()
  156. };
  157. JsonResponse::new(JsonValue::Number(next_block_height as f64), id).into()
  158. }
  159. // RPCAPI:
  160. // Queries the validator to get the currently configured block target time.
  161. //
  162. // **Params:**
  163. // * `None`
  164. //
  165. // **Returns:**
  166. // * `f64`: Current block target time
  167. //
  168. // --> {"jsonrpc": "2.0", "method": "blockchain.block_target", "params": [], "id": 1}
  169. // <-- {"jsonrpc": "2.0", "result": 1234, "id": 1}
  170. pub async fn blockchain_block_target(&self, id: u16, params: JsonValue) -> JsonResult {
  171. let params = params.get::<Vec<JsonValue>>().unwrap();
  172. if !params.is_empty() {
  173. return JsonError::new(InvalidParams, None, id).into()
  174. }
  175. let block_target = self.validator.consensus.module.read().await.target;
  176. JsonResponse::new(JsonValue::Number(block_target as f64), id).into()
  177. }
  178. // RPCAPI:
  179. // Initializes a subscription to new incoming blocks.
  180. // Once a subscription is established, `darkfid` will send JSON-RPC notifications of
  181. // new incoming blocks to the subscriber.
  182. //
  183. // --> {"jsonrpc": "2.0", "method": "blockchain.subscribe_blocks", "params": [], "id": 1}
  184. // <-- {"jsonrpc": "2.0", "method": "blockchain.subscribe_blocks", "params": [`blockinfo`]}
  185. pub async fn blockchain_subscribe_blocks(&self, id: u16, params: JsonValue) -> JsonResult {
  186. let params = params.get::<Vec<JsonValue>>().unwrap();
  187. if !params.is_empty() {
  188. return JsonError::new(InvalidParams, None, id).into()
  189. }
  190. self.subscribers.get("blocks").unwrap().clone().into()
  191. }
  192. // RPCAPI:
  193. // Initializes a subscription to new incoming transactions.
  194. // Once a subscription is established, `darkfid` will send JSON-RPC notifications of
  195. // new incoming transactions to the subscriber.
  196. //
  197. // --> {"jsonrpc": "2.0", "method": "blockchain.subscribe_txs", "params": [], "id": 1}
  198. // <-- {"jsonrpc": "2.0", "method": "blockchain.subscribe_txs", "params": [`tx_hash`]}
  199. pub async fn blockchain_subscribe_txs(&self, id: u16, params: JsonValue) -> JsonResult {
  200. let params = params.get::<Vec<JsonValue>>().unwrap();
  201. if !params.is_empty() {
  202. return JsonError::new(InvalidParams, None, id).into()
  203. }
  204. self.subscribers.get("txs").unwrap().clone().into()
  205. }
  206. // RPCAPI:
  207. // Initializes a subscription to new incoming proposals. Once a subscription is established,
  208. // `darkfid` will send JSON-RPC notifications of new incoming proposals to the subscriber.
  209. //
  210. // --> {"jsonrpc": "2.0", "method": "blockchain.subscribe_proposals", "params": [], "id": 1}
  211. // <-- {"jsonrpc": "2.0", "method": "blockchain.subscribe_proposals", "params": [`blockinfo`]}
  212. pub async fn blockchain_subscribe_proposals(&self, id: u16, params: JsonValue) -> JsonResult {
  213. let params = params.get::<Vec<JsonValue>>().unwrap();
  214. if !params.is_empty() {
  215. return JsonError::new(InvalidParams, None, id).into()
  216. }
  217. self.subscribers.get("proposals").unwrap().clone().into()
  218. }
  219. // RPCAPI:
  220. // Performs a lookup of zkas bincodes for a given contract ID and returns all of
  221. // them, including their namespace.
  222. //
  223. // **Params:**
  224. // * `array[0]`: base58-encoded contract ID string
  225. //
  226. // **Returns:**
  227. // * `array[n]`: Pairs of: `zkas_namespace` string, serialized
  228. // [`ZkBinary`](https://darkrenaissance.github.io/darkfi/dev/darkfi/zkas/decoder/struct.ZkBinary.html)
  229. // object
  230. //
  231. // --> {"jsonrpc": "2.0", "method": "blockchain.lookup_zkas", "params": ["BZHKGQ26bzmBithTQYTJtjo2QdCqpkR9tjSBopT4yf4o"], "id": 1}
  232. // <-- {"jsonrpc": "2.0", "result": [["Foo", "ABCD..."], ["Bar", "EFGH..."]], "id": 1}
  233. pub async fn blockchain_lookup_zkas(&self, id: u16, params: JsonValue) -> JsonResult {
  234. let params = params.get::<Vec<JsonValue>>().unwrap();
  235. if params.len() != 1 || !params[0].is_string() {
  236. return JsonError::new(InvalidParams, None, id).into()
  237. }
  238. let contract_id = params[0].get::<String>().unwrap();
  239. let contract_id = match ContractId::from_str(contract_id) {
  240. Ok(v) => v,
  241. Err(e) => {
  242. error!(target: "darkfid::rpc::blockchain_lookup_zkas", "Error decoding string to ContractId: {}", e);
  243. return JsonError::new(InvalidParams, None, id).into()
  244. }
  245. };
  246. let Ok(zkas_db) = self.validator.blockchain.contracts.lookup(
  247. &self.validator.blockchain.sled_db,
  248. &contract_id,
  249. SMART_CONTRACT_ZKAS_DB_NAME,
  250. ) else {
  251. error!(
  252. target: "darkfid::rpc::blockchain_lookup_zkas", "Did not find zkas db for ContractId: {}",
  253. contract_id
  254. );
  255. return server_error(RpcError::ContractZkasDbNotFound, id, None)
  256. };
  257. let mut ret = vec![];
  258. for i in zkas_db.iter() {
  259. debug!(target: "darkfid::rpc::blockchain_lookup_zkas", "Iterating over zkas db");
  260. let Ok((zkas_ns, zkas_bytes)) = i else {
  261. error!(target: "darkfid::rpc::blockchain_lookup_zkas", "Internal sled error iterating db");
  262. return JsonError::new(InternalError, None, id).into()
  263. };
  264. let Ok(zkas_ns) = deserialize_async(&zkas_ns).await else {
  265. return JsonError::new(InternalError, None, id).into()
  266. };
  267. let (zkbin, _): (Vec<u8>, Vec<u8>) = match deserialize_async(&zkas_bytes).await {
  268. Ok(pair) => pair,
  269. Err(_) => return JsonError::new(InternalError, None, id).into(),
  270. };
  271. let zkas_bincode = base64::encode(&zkbin);
  272. ret.push(JsonValue::Array(vec![
  273. JsonValue::String(zkas_ns),
  274. JsonValue::String(zkas_bincode),
  275. ]));
  276. }
  277. JsonResponse::new(JsonValue::Array(ret), id).into()
  278. }
  279. // RPCAPI:
  280. // Queries the blockchain database for a given contract state records.
  281. // Returns the records value raw bytes as a `BTreeMap`.
  282. //
  283. // **Params:**
  284. // * `array[0]`: base58-encoded contract ID string
  285. // * `array[1]`: Contract tree name string
  286. //
  287. // **Returns:**
  288. // * Records serialized `BTreeMap` encoded with base64
  289. //
  290. // --> {"jsonrpc": "2.0", "method": "blockchain.get_contract_state", "params": ["BZHK...", "tree"], "id": 1}
  291. // <-- {"jsonrpc": "2.0", "result": "ABCD...", "id": 1}
  292. pub async fn blockchain_get_contract_state(&self, id: u16, params: JsonValue) -> JsonResult {
  293. let params = params.get::<Vec<JsonValue>>().unwrap();
  294. if params.len() != 2 || !params[0].is_string() || !params[1].is_string() {
  295. return JsonError::new(InvalidParams, None, id).into()
  296. }
  297. let contract_id = params[0].get::<String>().unwrap();
  298. let contract_id = match ContractId::from_str(contract_id) {
  299. Ok(v) => v,
  300. Err(e) => {
  301. error!(target: "darkfid::rpc::blockchain_get_contract_state", "Error decoding string to ContractId: {}", e);
  302. return JsonError::new(InvalidParams, None, id).into()
  303. }
  304. };
  305. let tree_name = params[1].get::<String>().unwrap();
  306. match self.validator.blockchain.contracts.get_state_tree_records(
  307. &self.validator.blockchain.sled_db,
  308. &contract_id,
  309. tree_name,
  310. ) {
  311. Ok(records) => JsonResponse::new(
  312. JsonValue::String(base64::encode(&serialize_async(&records).await)),
  313. id,
  314. )
  315. .into(),
  316. Err(e) => {
  317. error!(target: "darkfid::rpc::blockchain_get_contract_state", "Failed fetching contract state records: {}", e);
  318. server_error(RpcError::ContractStateNotFound, id, None)
  319. }
  320. }
  321. }
  322. // RPCAPI:
  323. // Queries the blockchain database for a given contract state key raw bytes.
  324. // Returns the record value raw bytes.
  325. //
  326. // **Params:**
  327. // * `array[0]`: base58-encoded contract ID string
  328. // * `array[1]`: Contract tree name string
  329. // * `array[2]`: Key raw bytes, encoded with base64
  330. //
  331. // **Returns:**
  332. // * Record value raw bytes encoded with base64
  333. //
  334. // --> {"jsonrpc": "2.0", "method": "blockchain.get_contract_state_key", "params": ["BZHK...", "tree", "ABCD..."], "id": 1}
  335. // <-- {"jsonrpc": "2.0", "result": "ABCD...", "id": 1}
  336. pub async fn blockchain_get_contract_state_key(
  337. &self,
  338. id: u16,
  339. params: JsonValue,
  340. ) -> JsonResult {
  341. let params = params.get::<Vec<JsonValue>>().unwrap();
  342. if params.len() != 3 ||
  343. !params[0].is_string() ||
  344. !params[1].is_string() ||
  345. !params[2].is_string()
  346. {
  347. return JsonError::new(InvalidParams, None, id).into()
  348. }
  349. let contract_id = params[0].get::<String>().unwrap();
  350. let contract_id = match ContractId::from_str(contract_id) {
  351. Ok(v) => v,
  352. Err(e) => {
  353. error!(target: "darkfid::rpc::blockchain_get_contract_state_key", "Error decoding string to ContractId: {}", e);
  354. return JsonError::new(InvalidParams, None, id).into()
  355. }
  356. };
  357. let tree_name = params[1].get::<String>().unwrap();
  358. let key_enc = params[2].get::<String>().unwrap().trim();
  359. let Some(key) = base64::decode(key_enc) else {
  360. error!(target: "darkfid::rpc::blockchain_get_contract_state_key", "Failed decoding base64 key");
  361. return server_error(RpcError::ParseError, id, None)
  362. };
  363. match self.validator.blockchain.contracts.get_state_tree_value(
  364. &self.validator.blockchain.sled_db,
  365. &contract_id,
  366. tree_name,
  367. &key,
  368. ) {
  369. Ok(value) => JsonResponse::new(JsonValue::String(base64::encode(&value)), id).into(),
  370. Err(e) => {
  371. error!(target: "darkfid::rpc::blockchain_get_contract_state_key", "Failed fetching contract state key value: {}", e);
  372. server_error(RpcError::ContractStateKeyNotFound, id, None)
  373. }
  374. }
  375. }
  376. }