rpc_blockchain.rs 16 KB

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