blockchain.rs 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550
  1. /* This file is part of DarkFi (https://dark.fi)
  2. *
  3. * Copyright (C) 2020-2026 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]`: `u32` block height
  41. //
  42. // **Returns:**
  43. // * `BlockInfo` serialized into base64.
  44. //
  45. // ```rust,no_run,noplayground
  46. // {{#include ../../../src/blockchain/block_store.rs:blockinfo}}
  47. // ```
  48. //
  49. // --> {"jsonrpc": "2.0", "method": "blockchain.get_block", "params": [0], "id": 1}
  50. // <-- {"jsonrpc": "2.0", "result": "base64encodedblock", "id": 1}
  51. pub async fn blockchain_get_block(&self, id: i64, params: JsonValue) -> JsonResult {
  52. let Some(params) = params.get::<Vec<JsonValue>>() else {
  53. return JsonError::new(InvalidParams, None, id).into()
  54. };
  55. if params.len() != 1 || !params[0].is_number() {
  56. return JsonError::new(InvalidParams, None, id).into()
  57. }
  58. let block_height = *params[0].get::<f64>().unwrap() as u32;
  59. let blocks = match self
  60. .validator
  61. .read()
  62. .await
  63. .blockchain
  64. .get_blocks_by_heights(&[block_height])
  65. {
  66. Ok(v) => v,
  67. Err(e) => {
  68. error!(target: "darkfid::rpc::blockchain_get_block", "Failed fetching block by height: {e}");
  69. return JsonError::new(InternalError, None, id).into()
  70. }
  71. };
  72. if blocks.is_empty() {
  73. return server_error(RpcError::UnknownBlockHeight, id, None)
  74. }
  75. let block = base64::encode(&serialize_async(&blocks[0]).await);
  76. JsonResponse::new(JsonValue::String(block), id).into()
  77. }
  78. // RPCAPI:
  79. // Queries the blockchain database for a given transaction.
  80. // Returns a base64 encoded `Transaction` object.
  81. //
  82. // **Params:**
  83. // * `array[0]`: Hex-encoded transaction hash string
  84. //
  85. // **Returns:**
  86. // * `Transaction serialized into base64.
  87. //
  88. // ```rust,no_run,noplayground
  89. // {{#include ../../../src/tx/mod.rs:transaction-struct}}
  90. // ```
  91. //
  92. // --> {"jsonrpc": "2.0", "method": "blockchain.get_tx", "params": ["TxHash"], "id": 1}
  93. // <-- {"jsonrpc": "2.0", "result": "base64encodedtx", "id": 1}
  94. pub async fn blockchain_get_tx(&self, id: i64, params: JsonValue) -> JsonResult {
  95. let Some(params) = params.get::<Vec<JsonValue>>() else {
  96. return JsonError::new(InvalidParams, None, id).into()
  97. };
  98. if params.len() != 1 || !params[0].is_string() {
  99. return JsonError::new(InvalidParams, None, id).into()
  100. }
  101. let tx_hash = params[0].get::<String>().unwrap();
  102. let tx_hash = match TransactionHash::from_str(tx_hash) {
  103. Ok(v) => v,
  104. Err(_) => return JsonError::new(ParseError, None, id).into(),
  105. };
  106. let txs = match self.validator.read().await.blockchain.transactions.get(&[tx_hash], true) {
  107. Ok(txs) => txs,
  108. Err(e) => {
  109. error!(target: "darkfid::rpc::blockchain_get_tx", "Failed fetching tx by hash: {e}");
  110. return JsonError::new(InternalError, None, id).into()
  111. }
  112. };
  113. // This would be an logic error somewhere
  114. assert_eq!(txs.len(), 1);
  115. // and strict was used during .get()
  116. let tx = txs[0].as_ref().unwrap();
  117. let tx_enc = base64::encode(&serialize_async(tx).await);
  118. JsonResponse::new(JsonValue::String(tx_enc), id).into()
  119. }
  120. // RPCAPI:
  121. // Queries the blockchain database to fetch the difficulty and cumulative
  122. // difficulty for a specific block height.
  123. //
  124. // **Params:**
  125. // * `array[0]`: Block height
  126. //
  127. // **Returns:**
  128. // * `difficulty`: Block difficulty as integer
  129. // * `cumulative_difficulty`: Cumulative block difficulty as integer
  130. //
  131. // --> {"jsonrpc": "2.0", "method": "blockchain.get_difficulty", "params": [1], "id": 1}
  132. // <-- {"jsonrpc": "2.0", "result": [123, 456], "id": 1}
  133. pub async fn blockchain_get_difficulty(&self, id: i64, params: JsonValue) -> JsonResult {
  134. let Some(params) = params.get::<Vec<JsonValue>>() else {
  135. return JsonError::new(InvalidParams, None, id).into()
  136. };
  137. if params.len() != 1 || !params[0].is_number() {
  138. return JsonError::new(InvalidParams, None, id).into()
  139. }
  140. let height = *params[0].get::<f64>().unwrap() as u32;
  141. if height == 0 {
  142. return JsonResponse::new(JsonValue::Array(vec![1_f64.into(), 1_f64.into()]), id).into()
  143. }
  144. let Ok(diff) =
  145. self.validator.read().await.blockchain.blocks.get_difficulty(&[height], true)
  146. else {
  147. return server_error(RpcError::UnknownBlockHeight, id, None)
  148. };
  149. let block_diff = diff[0].clone().unwrap();
  150. let difficulty: f64 = block_diff.difficulty.to_string().parse().unwrap();
  151. let cumulative: f64 = block_diff.cumulative_difficulty.to_string().parse().unwrap();
  152. JsonResponse::new(JsonValue::Array(vec![difficulty.into(), cumulative.into()]), id).into()
  153. }
  154. // RPCAPI:
  155. // Queries the blockchain database to find the last confirmed block.
  156. //
  157. // **Params:**
  158. // * Empty
  159. //
  160. // **Returns:**
  161. // * `f64` : Height of the last confirmed block
  162. // * `String`: Header hash of the last confirmed block
  163. //
  164. // --> {"jsonrpc": "2.0", "method": "blockchain.last_confirmed_block", "params": [], "id": 1}
  165. // <-- {"jsonrpc": "2.0", "result": [1234, "HeaderHash"], "id": 1}
  166. pub async fn blockchain_last_confirmed_block(&self, id: i64, params: JsonValue) -> JsonResult {
  167. let Some(params) = params.get::<Vec<JsonValue>>() else {
  168. return JsonError::new(InvalidParams, None, id).into()
  169. };
  170. if !params.is_empty() {
  171. return JsonError::new(InvalidParams, None, id).into()
  172. }
  173. let Ok((height, hash)) = self.validator.read().await.blockchain.last() else {
  174. return JsonError::new(InternalError, None, id).into()
  175. };
  176. JsonResponse::new(
  177. JsonValue::Array(vec![
  178. JsonValue::Number(height as f64),
  179. JsonValue::String(hash.to_string()),
  180. ]),
  181. id,
  182. )
  183. .into()
  184. }
  185. // RPCAPI:
  186. // Queries the validator to find the current best fork next block height.
  187. //
  188. // **Params:**
  189. // * Empty
  190. //
  191. // **Returns:**
  192. // * `f64`: Current best fork next block height
  193. //
  194. // --> {"jsonrpc": "2.0", "method": "blockchain.best_fork_next_block_height", "params": [], "id": 1}
  195. // <-- {"jsonrpc": "2.0", "result": 1234, "id": 1}
  196. pub async fn blockchain_best_fork_next_block_height(
  197. &self,
  198. id: i64,
  199. params: JsonValue,
  200. ) -> JsonResult {
  201. let Some(params) = params.get::<Vec<JsonValue>>() else {
  202. return JsonError::new(InvalidParams, None, id).into()
  203. };
  204. if !params.is_empty() {
  205. return JsonError::new(InvalidParams, None, id).into()
  206. }
  207. let Ok(next_block_height) = self.validator.read().await.best_fork_next_block_height().await
  208. else {
  209. return JsonError::new(InternalError, None, id).into()
  210. };
  211. JsonResponse::new(JsonValue::Number(next_block_height as f64), id).into()
  212. }
  213. // RPCAPI:
  214. // Queries the validator to get the currently configured block target time.
  215. //
  216. // **Params:**
  217. // * Empty
  218. //
  219. // **Returns:**
  220. // * `f64`: Current block target time
  221. //
  222. // --> {"jsonrpc": "2.0", "method": "blockchain.block_target", "params": [], "id": 1}
  223. // <-- {"jsonrpc": "2.0", "result": 120, "id": 1}
  224. pub async fn blockchain_block_target(&self, id: i64, params: JsonValue) -> JsonResult {
  225. let Some(params) = params.get::<Vec<JsonValue>>() else {
  226. return JsonError::new(InvalidParams, None, id).into()
  227. };
  228. if !params.is_empty() {
  229. return JsonError::new(InvalidParams, None, id).into()
  230. }
  231. let block_target = self.validator.read().await.consensus.module.target;
  232. JsonResponse::new(JsonValue::Number(block_target as f64), id).into()
  233. }
  234. // RPCAPI:
  235. // Initializes a subscription to new incoming blocks.
  236. //
  237. // Once a subscription is established, `darkfid` will send JSON-RPC notifications of
  238. // new incoming blocks to the subscriber.
  239. //
  240. // The notifications contain base64-encoded `BlockInfo` structs.
  241. //
  242. // ```rust,no_run,noplayground
  243. // {{#include ../../../src/blockchain/block_store.rs:blockinfo}}
  244. // ```
  245. //
  246. // --> {"jsonrpc": "2.0", "method": "blockchain.subscribe_blocks", "params": [], "id": 1}
  247. // <-- {"jsonrpc": "2.0", "method": "blockchain.subscribe_blocks", "params": ["base64encodedblock"]}
  248. pub async fn blockchain_subscribe_blocks(&self, id: i64, params: JsonValue) -> JsonResult {
  249. let Some(params) = params.get::<Vec<JsonValue>>() else {
  250. return JsonError::new(InvalidParams, None, id).into()
  251. };
  252. if !params.is_empty() {
  253. return JsonError::new(InvalidParams, None, id).into()
  254. }
  255. self.subscribers.get("blocks").unwrap().clone().into()
  256. }
  257. // RPCAPI:
  258. // Initializes a subscription to new incoming transactions.
  259. //
  260. // Once a subscription is established, `darkfid` will send JSON-RPC notifications of
  261. // new incoming transactions to the subscriber.
  262. //
  263. // The notifications contain hex-encoded transaction hashes.
  264. //
  265. // --> {"jsonrpc": "2.0", "method": "blockchain.subscribe_txs", "params": [], "id": 1}
  266. // <-- {"jsonrpc": "2.0", "method": "blockchain.subscribe_txs", "params": ["tx_hash"]}
  267. pub async fn blockchain_subscribe_txs(&self, id: i64, params: JsonValue) -> JsonResult {
  268. let Some(params) = params.get::<Vec<JsonValue>>() else {
  269. return JsonError::new(InvalidParams, None, id).into()
  270. };
  271. if !params.is_empty() {
  272. return JsonError::new(InvalidParams, None, id).into()
  273. }
  274. self.subscribers.get("txs").unwrap().clone().into()
  275. }
  276. // RPCAPI:
  277. // Initializes a subscription to new incoming proposals. Once a subscription is established,
  278. // `darkfid` will send JSON-RPC notifications of new incoming proposals to the subscriber.
  279. //
  280. // The notifications contain base64-encoded `BlockInfo` structs.
  281. //
  282. // ```rust,no_run,noplayground
  283. // {{#include ../../../src/blockchain/block_store.rs:blockinfo}}
  284. // ```
  285. //
  286. // --> {"jsonrpc": "2.0", "method": "blockchain.subscribe_proposals", "params": [], "id": 1}
  287. // <-- {"jsonrpc": "2.0", "method": "blockchain.subscribe_proposals", "params": ["base64encodedblock"]}
  288. pub async fn blockchain_subscribe_proposals(&self, id: i64, params: JsonValue) -> JsonResult {
  289. let Some(params) = params.get::<Vec<JsonValue>>() else {
  290. return JsonError::new(InvalidParams, None, id).into()
  291. };
  292. if !params.is_empty() {
  293. return JsonError::new(InvalidParams, None, id).into()
  294. }
  295. self.subscribers.get("proposals").unwrap().clone().into()
  296. }
  297. // RPCAPI:
  298. // Performs a lookup of zkas bincodes for a given contract ID and returns all of
  299. // them, including their namespace.
  300. //
  301. // **Params:**
  302. // * `array[0]`: base58-encoded contract ID string
  303. //
  304. // **Returns:**
  305. // * `array[n]`: Pairs of: `zkas_namespace` strings and base64-encoded
  306. // `ZkBinary` objects.
  307. //
  308. // ```rust,no_run,noplayground
  309. // {{#include ../../../src/zkas/decoder.rs:zkbinary-struct}}
  310. // ```
  311. //
  312. // --> {"jsonrpc": "2.0", "method": "blockchain.lookup_zkas", "params": ["BZHKGQ26bzmBithTQYTJtjo2QdCqpkR9tjSBopT4yf4o"], "id": 1}
  313. // <-- {"jsonrpc": "2.0", "result": [["Foo", "ABCD..."], ["Bar", "EFGH..."]], "id": 1}
  314. pub async fn blockchain_lookup_zkas(&self, id: i64, params: JsonValue) -> JsonResult {
  315. let Some(params) = params.get::<Vec<JsonValue>>() else {
  316. return JsonError::new(InvalidParams, None, id).into()
  317. };
  318. if params.len() != 1 || !params[0].is_string() {
  319. return JsonError::new(InvalidParams, None, id).into()
  320. }
  321. let contract_id = params[0].get::<String>().unwrap();
  322. let contract_id = match ContractId::from_str(contract_id) {
  323. Ok(v) => v,
  324. Err(e) => {
  325. error!(target: "darkfid::rpc::blockchain_lookup_zkas", "Error decoding string to ContractId: {e}");
  326. return JsonError::new(InvalidParams, None, id).into()
  327. }
  328. };
  329. let validator = self.validator.read().await;
  330. let Ok(zkas_db) = validator.blockchain.contracts.lookup(
  331. &validator.blockchain.sled_db,
  332. &contract_id,
  333. SMART_CONTRACT_ZKAS_DB_NAME,
  334. ) else {
  335. error!(target: "darkfid::rpc::blockchain_lookup_zkas", "Did not find zkas db for ContractId: {contract_id}");
  336. return server_error(RpcError::ContractZkasDbNotFound, id, None)
  337. };
  338. drop(validator);
  339. let mut ret = vec![];
  340. for i in zkas_db.iter() {
  341. debug!(target: "darkfid::rpc::blockchain_lookup_zkas", "Iterating over zkas db");
  342. let Ok((zkas_ns, zkas_bytes)) = i else {
  343. error!(target: "darkfid::rpc::blockchain_lookup_zkas", "Internal sled error iterating db");
  344. return JsonError::new(InternalError, None, id).into()
  345. };
  346. let Ok(zkas_ns) = deserialize_async(&zkas_ns).await else {
  347. return JsonError::new(InternalError, None, id).into()
  348. };
  349. let (zkbin, _): (Vec<u8>, Vec<u8>) = match deserialize_async(&zkas_bytes).await {
  350. Ok(pair) => pair,
  351. Err(_) => return JsonError::new(InternalError, None, id).into(),
  352. };
  353. let zkas_bincode = base64::encode(&zkbin);
  354. ret.push(JsonValue::Array(vec![
  355. JsonValue::String(zkas_ns),
  356. JsonValue::String(zkas_bincode),
  357. ]));
  358. }
  359. JsonResponse::new(JsonValue::Array(ret), id).into()
  360. }
  361. // RPCAPI:
  362. // Perform a lookup of a WASM contract binary deployed on-chain and
  363. // return the base64-encoded binary.
  364. //
  365. // **Params:**
  366. // * `array[0]`: base58-encoded contract ID string
  367. //
  368. // **Returns:**
  369. // * `String`: base64-encoded WASM binary
  370. //
  371. // --> {"jsonrpc": "2.0", "method": "blockchain.lookup_wasm", "params": ["BZHKGQ26bzmBithTQYTJtjo2QdCqpkR9tjSBopT4yf4o"], "id": 1}
  372. // <-- {"jsonrpc": "2.0", "result": "ABCD...", "id": 1}
  373. pub async fn blockchain_lookup_wasm(&self, id: i64, params: JsonValue) -> JsonResult {
  374. let Some(params) = params.get::<Vec<JsonValue>>() else {
  375. return JsonError::new(InvalidParams, None, id).into()
  376. };
  377. if params.len() != 1 || !params[0].is_string() {
  378. return JsonError::new(InvalidParams, None, id).into()
  379. }
  380. let contract_id = params[0].get::<String>().unwrap();
  381. let Ok(contract_id) = ContractId::from_str(contract_id) else {
  382. return server_error(RpcError::ParseError, id, None)
  383. };
  384. let Ok(bincode) = self.validator.read().await.blockchain.contracts.get(contract_id) else {
  385. return server_error(RpcError::ContractWasmNotFound, id, None)
  386. };
  387. let encoded = base64::encode(&bincode);
  388. JsonResponse::new(encoded.to_string().into(), id).into()
  389. }
  390. // RPCAPI:
  391. // Queries the blockchain database for a given contract state records.
  392. // Returns the records value raw bytes as a `BTreeMap`.
  393. //
  394. // **Params:**
  395. // * `array[0]`: base58-encoded contract ID string
  396. // * `array[1]`: Contract tree name string
  397. //
  398. // **Returns:**
  399. // * Records serialized `BTreeMap` encoded with base64
  400. //
  401. // --> {"jsonrpc": "2.0", "method": "blockchain.get_contract_state", "params": ["BZHK...", "tree"], "id": 1}
  402. // <-- {"jsonrpc": "2.0", "result": "ABCD...", "id": 1}
  403. pub async fn blockchain_get_contract_state(&self, id: i64, params: JsonValue) -> JsonResult {
  404. let Some(params) = params.get::<Vec<JsonValue>>() else {
  405. return JsonError::new(InvalidParams, None, id).into()
  406. };
  407. if params.len() != 2 || !params[0].is_string() || !params[1].is_string() {
  408. return JsonError::new(InvalidParams, None, id).into()
  409. }
  410. let contract_id = params[0].get::<String>().unwrap();
  411. let contract_id = match ContractId::from_str(contract_id) {
  412. Ok(v) => v,
  413. Err(e) => {
  414. error!(target: "darkfid::rpc::blockchain_get_contract_state", "Error decoding string to ContractId: {e}");
  415. return JsonError::new(InvalidParams, None, id).into()
  416. }
  417. };
  418. let tree_name = params[1].get::<String>().unwrap();
  419. let validator = self.validator.read().await;
  420. match validator.blockchain.contracts.get_state_tree_records(
  421. &validator.blockchain.sled_db,
  422. &contract_id,
  423. tree_name,
  424. ) {
  425. Ok(records) => JsonResponse::new(
  426. JsonValue::String(base64::encode(&serialize_async(&records).await)),
  427. id,
  428. )
  429. .into(),
  430. Err(e) => {
  431. error!(target: "darkfid::rpc::blockchain_get_contract_state", "Failed fetching contract state records: {e}");
  432. server_error(RpcError::ContractStateNotFound, id, None)
  433. }
  434. }
  435. }
  436. // RPCAPI:
  437. // Queries the blockchain database for a given contract state key raw bytes.
  438. // Returns the record value raw bytes.
  439. //
  440. // **Params:**
  441. // * `array[0]`: base58-encoded contract ID string
  442. // * `array[1]`: Contract tree name string
  443. // * `array[2]`: Key raw bytes, encoded with base64
  444. //
  445. // **Returns:**
  446. // * Record value raw bytes encoded with base64
  447. //
  448. // --> {"jsonrpc": "2.0", "method": "blockchain.get_contract_state_key", "params": ["BZHK...", "tree", "ABCD..."], "id": 1}
  449. // <-- {"jsonrpc": "2.0", "result": "ABCD...", "id": 1}
  450. pub async fn blockchain_get_contract_state_key(
  451. &self,
  452. id: i64,
  453. params: JsonValue,
  454. ) -> JsonResult {
  455. let Some(params) = params.get::<Vec<JsonValue>>() else {
  456. return JsonError::new(InvalidParams, None, id).into()
  457. };
  458. if params.len() != 3 ||
  459. !params[0].is_string() ||
  460. !params[1].is_string() ||
  461. !params[2].is_string()
  462. {
  463. return JsonError::new(InvalidParams, None, id).into()
  464. }
  465. let contract_id = params[0].get::<String>().unwrap();
  466. let contract_id = match ContractId::from_str(contract_id) {
  467. Ok(v) => v,
  468. Err(e) => {
  469. error!(target: "darkfid::rpc::blockchain_get_contract_state_key", "Error decoding string to ContractId: {e}");
  470. return JsonError::new(InvalidParams, None, id).into()
  471. }
  472. };
  473. let tree_name = params[1].get::<String>().unwrap();
  474. let key_enc = params[2].get::<String>().unwrap().trim();
  475. let Some(key) = base64::decode(key_enc) else {
  476. error!(target: "darkfid::rpc::blockchain_get_contract_state_key", "Failed decoding base64 key");
  477. return server_error(RpcError::ParseError, id, None)
  478. };
  479. let validator = self.validator.read().await;
  480. match validator.blockchain.contracts.get_state_tree_value(
  481. &validator.blockchain.sled_db,
  482. &contract_id,
  483. tree_name,
  484. &key,
  485. ) {
  486. Ok(value) => JsonResponse::new(JsonValue::String(base64::encode(&value)), id).into(),
  487. Err(e) => {
  488. error!(target: "darkfid::rpc::blockchain_get_contract_state_key", "Failed fetching contract state key value: {e}");
  489. server_error(RpcError::ContractStateKeyNotFound, id, None)
  490. }
  491. }
  492. }
  493. }