| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550 |
- /* This file is part of DarkFi (https://dark.fi)
- *
- * Copyright (C) 2020-2026 Dyne.org foundation
- *
- * This program is free software: you can redistribute it and/or modify
- * it under the terms of the GNU Affero General Public License as
- * published by the Free Software Foundation, either version 3 of the
- * License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU Affero General Public License for more details.
- *
- * You should have received a copy of the GNU Affero General Public License
- * along with this program. If not, see <https://www.gnu.org/licenses/>.
- */
- use std::str::FromStr;
- use darkfi_sdk::{
- crypto::contract_id::{ContractId, SMART_CONTRACT_ZKAS_DB_NAME},
- tx::TransactionHash,
- };
- use darkfi_serial::{deserialize_async, serialize_async};
- use tinyjson::JsonValue;
- use tracing::{debug, error};
- use darkfi::{
- rpc::jsonrpc::{
- ErrorCode::{InternalError, InvalidParams, ParseError},
- JsonError, JsonResponse, JsonResult,
- },
- util::encoding::base64,
- };
- use crate::{server_error, DarkfiNode, RpcError};
- impl DarkfiNode {
- // RPCAPI:
- // Queries the blockchain database for a block in the given height.
- // Returns a readable block upon success.
- //
- // **Params:**
- // * `array[0]`: `u32` block height
- //
- // **Returns:**
- // * `BlockInfo` serialized into base64.
- //
- // ```rust,no_run,noplayground
- // {{#include ../../../src/blockchain/block_store.rs:blockinfo}}
- // ```
- //
- // --> {"jsonrpc": "2.0", "method": "blockchain.get_block", "params": [0], "id": 1}
- // <-- {"jsonrpc": "2.0", "result": "base64encodedblock", "id": 1}
- pub async fn blockchain_get_block(&self, id: i64, params: JsonValue) -> JsonResult {
- let Some(params) = params.get::<Vec<JsonValue>>() else {
- return JsonError::new(InvalidParams, None, id).into()
- };
- if params.len() != 1 || !params[0].is_number() {
- return JsonError::new(InvalidParams, None, id).into()
- }
- let block_height = *params[0].get::<f64>().unwrap() as u32;
- let blocks = match self
- .validator
- .read()
- .await
- .blockchain
- .get_blocks_by_heights(&[block_height])
- {
- Ok(v) => v,
- Err(e) => {
- error!(target: "darkfid::rpc::blockchain_get_block", "Failed fetching block by height: {e}");
- return JsonError::new(InternalError, None, id).into()
- }
- };
- if blocks.is_empty() {
- return server_error(RpcError::UnknownBlockHeight, id, None)
- }
- let block = base64::encode(&serialize_async(&blocks[0]).await);
- JsonResponse::new(JsonValue::String(block), id).into()
- }
- // RPCAPI:
- // Queries the blockchain database for a given transaction.
- // Returns a base64 encoded `Transaction` object.
- //
- // **Params:**
- // * `array[0]`: Hex-encoded transaction hash string
- //
- // **Returns:**
- // * `Transaction serialized into base64.
- //
- // ```rust,no_run,noplayground
- // {{#include ../../../src/tx/mod.rs:transaction-struct}}
- // ```
- //
- // --> {"jsonrpc": "2.0", "method": "blockchain.get_tx", "params": ["TxHash"], "id": 1}
- // <-- {"jsonrpc": "2.0", "result": "base64encodedtx", "id": 1}
- pub async fn blockchain_get_tx(&self, id: i64, params: JsonValue) -> JsonResult {
- let Some(params) = params.get::<Vec<JsonValue>>() else {
- return JsonError::new(InvalidParams, None, id).into()
- };
- if params.len() != 1 || !params[0].is_string() {
- return JsonError::new(InvalidParams, None, id).into()
- }
- let tx_hash = params[0].get::<String>().unwrap();
- let tx_hash = match TransactionHash::from_str(tx_hash) {
- Ok(v) => v,
- Err(_) => return JsonError::new(ParseError, None, id).into(),
- };
- let txs = match self.validator.read().await.blockchain.transactions.get(&[tx_hash], true) {
- Ok(txs) => txs,
- Err(e) => {
- error!(target: "darkfid::rpc::blockchain_get_tx", "Failed fetching tx by hash: {e}");
- return JsonError::new(InternalError, None, id).into()
- }
- };
- // This would be an logic error somewhere
- assert_eq!(txs.len(), 1);
- // and strict was used during .get()
- let tx = txs[0].as_ref().unwrap();
- let tx_enc = base64::encode(&serialize_async(tx).await);
- JsonResponse::new(JsonValue::String(tx_enc), id).into()
- }
- // RPCAPI:
- // Queries the blockchain database to fetch the difficulty and cumulative
- // difficulty for a specific block height.
- //
- // **Params:**
- // * `array[0]`: Block height
- //
- // **Returns:**
- // * `difficulty`: Block difficulty as integer
- // * `cumulative_difficulty`: Cumulative block difficulty as integer
- //
- // --> {"jsonrpc": "2.0", "method": "blockchain.get_difficulty", "params": [1], "id": 1}
- // <-- {"jsonrpc": "2.0", "result": [123, 456], "id": 1}
- pub async fn blockchain_get_difficulty(&self, id: i64, params: JsonValue) -> JsonResult {
- let Some(params) = params.get::<Vec<JsonValue>>() else {
- return JsonError::new(InvalidParams, None, id).into()
- };
- if params.len() != 1 || !params[0].is_number() {
- return JsonError::new(InvalidParams, None, id).into()
- }
- let height = *params[0].get::<f64>().unwrap() as u32;
- if height == 0 {
- return JsonResponse::new(JsonValue::Array(vec![1_f64.into(), 1_f64.into()]), id).into()
- }
- let Ok(diff) =
- self.validator.read().await.blockchain.blocks.get_difficulty(&[height], true)
- else {
- return server_error(RpcError::UnknownBlockHeight, id, None)
- };
- let block_diff = diff[0].clone().unwrap();
- let difficulty: f64 = block_diff.difficulty.to_string().parse().unwrap();
- let cumulative: f64 = block_diff.cumulative_difficulty.to_string().parse().unwrap();
- JsonResponse::new(JsonValue::Array(vec![difficulty.into(), cumulative.into()]), id).into()
- }
- // RPCAPI:
- // Queries the blockchain database to find the last confirmed block.
- //
- // **Params:**
- // * Empty
- //
- // **Returns:**
- // * `f64` : Height of the last confirmed block
- // * `String`: Header hash of the last confirmed block
- //
- // --> {"jsonrpc": "2.0", "method": "blockchain.last_confirmed_block", "params": [], "id": 1}
- // <-- {"jsonrpc": "2.0", "result": [1234, "HeaderHash"], "id": 1}
- pub async fn blockchain_last_confirmed_block(&self, id: i64, params: JsonValue) -> JsonResult {
- let Some(params) = params.get::<Vec<JsonValue>>() else {
- return JsonError::new(InvalidParams, None, id).into()
- };
- if !params.is_empty() {
- return JsonError::new(InvalidParams, None, id).into()
- }
- let Ok((height, hash)) = self.validator.read().await.blockchain.last() else {
- return JsonError::new(InternalError, None, id).into()
- };
- JsonResponse::new(
- JsonValue::Array(vec![
- JsonValue::Number(height as f64),
- JsonValue::String(hash.to_string()),
- ]),
- id,
- )
- .into()
- }
- // RPCAPI:
- // Queries the validator to find the current best fork next block height.
- //
- // **Params:**
- // * Empty
- //
- // **Returns:**
- // * `f64`: Current best fork next block height
- //
- // --> {"jsonrpc": "2.0", "method": "blockchain.best_fork_next_block_height", "params": [], "id": 1}
- // <-- {"jsonrpc": "2.0", "result": 1234, "id": 1}
- pub async fn blockchain_best_fork_next_block_height(
- &self,
- id: i64,
- params: JsonValue,
- ) -> JsonResult {
- let Some(params) = params.get::<Vec<JsonValue>>() else {
- return JsonError::new(InvalidParams, None, id).into()
- };
- if !params.is_empty() {
- return JsonError::new(InvalidParams, None, id).into()
- }
- let Ok(next_block_height) = self.validator.read().await.best_fork_next_block_height().await
- else {
- return JsonError::new(InternalError, None, id).into()
- };
- JsonResponse::new(JsonValue::Number(next_block_height as f64), id).into()
- }
- // RPCAPI:
- // Queries the validator to get the currently configured block target time.
- //
- // **Params:**
- // * Empty
- //
- // **Returns:**
- // * `f64`: Current block target time
- //
- // --> {"jsonrpc": "2.0", "method": "blockchain.block_target", "params": [], "id": 1}
- // <-- {"jsonrpc": "2.0", "result": 120, "id": 1}
- pub async fn blockchain_block_target(&self, id: i64, params: JsonValue) -> JsonResult {
- let Some(params) = params.get::<Vec<JsonValue>>() else {
- return JsonError::new(InvalidParams, None, id).into()
- };
- if !params.is_empty() {
- return JsonError::new(InvalidParams, None, id).into()
- }
- let block_target = self.validator.read().await.consensus.module.target;
- JsonResponse::new(JsonValue::Number(block_target as f64), id).into()
- }
- // RPCAPI:
- // Initializes a subscription to new incoming blocks.
- //
- // Once a subscription is established, `darkfid` will send JSON-RPC notifications of
- // new incoming blocks to the subscriber.
- //
- // The notifications contain base64-encoded `BlockInfo` structs.
- //
- // ```rust,no_run,noplayground
- // {{#include ../../../src/blockchain/block_store.rs:blockinfo}}
- // ```
- //
- // --> {"jsonrpc": "2.0", "method": "blockchain.subscribe_blocks", "params": [], "id": 1}
- // <-- {"jsonrpc": "2.0", "method": "blockchain.subscribe_blocks", "params": ["base64encodedblock"]}
- pub async fn blockchain_subscribe_blocks(&self, id: i64, params: JsonValue) -> JsonResult {
- let Some(params) = params.get::<Vec<JsonValue>>() else {
- return JsonError::new(InvalidParams, None, id).into()
- };
- if !params.is_empty() {
- return JsonError::new(InvalidParams, None, id).into()
- }
- self.subscribers.get("blocks").unwrap().clone().into()
- }
- // RPCAPI:
- // Initializes a subscription to new incoming transactions.
- //
- // Once a subscription is established, `darkfid` will send JSON-RPC notifications of
- // new incoming transactions to the subscriber.
- //
- // The notifications contain hex-encoded transaction hashes.
- //
- // --> {"jsonrpc": "2.0", "method": "blockchain.subscribe_txs", "params": [], "id": 1}
- // <-- {"jsonrpc": "2.0", "method": "blockchain.subscribe_txs", "params": ["tx_hash"]}
- pub async fn blockchain_subscribe_txs(&self, id: i64, params: JsonValue) -> JsonResult {
- let Some(params) = params.get::<Vec<JsonValue>>() else {
- return JsonError::new(InvalidParams, None, id).into()
- };
- if !params.is_empty() {
- return JsonError::new(InvalidParams, None, id).into()
- }
- self.subscribers.get("txs").unwrap().clone().into()
- }
- // RPCAPI:
- // Initializes a subscription to new incoming proposals. Once a subscription is established,
- // `darkfid` will send JSON-RPC notifications of new incoming proposals to the subscriber.
- //
- // The notifications contain base64-encoded `BlockInfo` structs.
- //
- // ```rust,no_run,noplayground
- // {{#include ../../../src/blockchain/block_store.rs:blockinfo}}
- // ```
- //
- // --> {"jsonrpc": "2.0", "method": "blockchain.subscribe_proposals", "params": [], "id": 1}
- // <-- {"jsonrpc": "2.0", "method": "blockchain.subscribe_proposals", "params": ["base64encodedblock"]}
- pub async fn blockchain_subscribe_proposals(&self, id: i64, params: JsonValue) -> JsonResult {
- let Some(params) = params.get::<Vec<JsonValue>>() else {
- return JsonError::new(InvalidParams, None, id).into()
- };
- if !params.is_empty() {
- return JsonError::new(InvalidParams, None, id).into()
- }
- self.subscribers.get("proposals").unwrap().clone().into()
- }
- // RPCAPI:
- // Performs a lookup of zkas bincodes for a given contract ID and returns all of
- // them, including their namespace.
- //
- // **Params:**
- // * `array[0]`: base58-encoded contract ID string
- //
- // **Returns:**
- // * `array[n]`: Pairs of: `zkas_namespace` strings and base64-encoded
- // `ZkBinary` objects.
- //
- // ```rust,no_run,noplayground
- // {{#include ../../../src/zkas/decoder.rs:zkbinary-struct}}
- // ```
- //
- // --> {"jsonrpc": "2.0", "method": "blockchain.lookup_zkas", "params": ["BZHKGQ26bzmBithTQYTJtjo2QdCqpkR9tjSBopT4yf4o"], "id": 1}
- // <-- {"jsonrpc": "2.0", "result": [["Foo", "ABCD..."], ["Bar", "EFGH..."]], "id": 1}
- pub async fn blockchain_lookup_zkas(&self, id: i64, params: JsonValue) -> JsonResult {
- let Some(params) = params.get::<Vec<JsonValue>>() else {
- return JsonError::new(InvalidParams, None, id).into()
- };
- if params.len() != 1 || !params[0].is_string() {
- return JsonError::new(InvalidParams, None, id).into()
- }
- let contract_id = params[0].get::<String>().unwrap();
- let contract_id = match ContractId::from_str(contract_id) {
- Ok(v) => v,
- Err(e) => {
- error!(target: "darkfid::rpc::blockchain_lookup_zkas", "Error decoding string to ContractId: {e}");
- return JsonError::new(InvalidParams, None, id).into()
- }
- };
- let validator = self.validator.read().await;
- let Ok(zkas_db) = validator.blockchain.contracts.lookup(
- &validator.blockchain.sled_db,
- &contract_id,
- SMART_CONTRACT_ZKAS_DB_NAME,
- ) else {
- error!(target: "darkfid::rpc::blockchain_lookup_zkas", "Did not find zkas db for ContractId: {contract_id}");
- return server_error(RpcError::ContractZkasDbNotFound, id, None)
- };
- drop(validator);
- let mut ret = vec![];
- for i in zkas_db.iter() {
- debug!(target: "darkfid::rpc::blockchain_lookup_zkas", "Iterating over zkas db");
- let Ok((zkas_ns, zkas_bytes)) = i else {
- error!(target: "darkfid::rpc::blockchain_lookup_zkas", "Internal sled error iterating db");
- return JsonError::new(InternalError, None, id).into()
- };
- let Ok(zkas_ns) = deserialize_async(&zkas_ns).await else {
- return JsonError::new(InternalError, None, id).into()
- };
- let (zkbin, _): (Vec<u8>, Vec<u8>) = match deserialize_async(&zkas_bytes).await {
- Ok(pair) => pair,
- Err(_) => return JsonError::new(InternalError, None, id).into(),
- };
- let zkas_bincode = base64::encode(&zkbin);
- ret.push(JsonValue::Array(vec![
- JsonValue::String(zkas_ns),
- JsonValue::String(zkas_bincode),
- ]));
- }
- JsonResponse::new(JsonValue::Array(ret), id).into()
- }
- // RPCAPI:
- // Perform a lookup of a WASM contract binary deployed on-chain and
- // return the base64-encoded binary.
- //
- // **Params:**
- // * `array[0]`: base58-encoded contract ID string
- //
- // **Returns:**
- // * `String`: base64-encoded WASM binary
- //
- // --> {"jsonrpc": "2.0", "method": "blockchain.lookup_wasm", "params": ["BZHKGQ26bzmBithTQYTJtjo2QdCqpkR9tjSBopT4yf4o"], "id": 1}
- // <-- {"jsonrpc": "2.0", "result": "ABCD...", "id": 1}
- pub async fn blockchain_lookup_wasm(&self, id: i64, params: JsonValue) -> JsonResult {
- let Some(params) = params.get::<Vec<JsonValue>>() else {
- return JsonError::new(InvalidParams, None, id).into()
- };
- if params.len() != 1 || !params[0].is_string() {
- return JsonError::new(InvalidParams, None, id).into()
- }
- let contract_id = params[0].get::<String>().unwrap();
- let Ok(contract_id) = ContractId::from_str(contract_id) else {
- return server_error(RpcError::ParseError, id, None)
- };
- let Ok(bincode) = self.validator.read().await.blockchain.contracts.get(contract_id) else {
- return server_error(RpcError::ContractWasmNotFound, id, None)
- };
- let encoded = base64::encode(&bincode);
- JsonResponse::new(encoded.to_string().into(), id).into()
- }
- // RPCAPI:
- // Queries the blockchain database for a given contract state records.
- // Returns the records value raw bytes as a `BTreeMap`.
- //
- // **Params:**
- // * `array[0]`: base58-encoded contract ID string
- // * `array[1]`: Contract tree name string
- //
- // **Returns:**
- // * Records serialized `BTreeMap` encoded with base64
- //
- // --> {"jsonrpc": "2.0", "method": "blockchain.get_contract_state", "params": ["BZHK...", "tree"], "id": 1}
- // <-- {"jsonrpc": "2.0", "result": "ABCD...", "id": 1}
- pub async fn blockchain_get_contract_state(&self, id: i64, params: JsonValue) -> JsonResult {
- let Some(params) = params.get::<Vec<JsonValue>>() else {
- return JsonError::new(InvalidParams, None, id).into()
- };
- if params.len() != 2 || !params[0].is_string() || !params[1].is_string() {
- return JsonError::new(InvalidParams, None, id).into()
- }
- let contract_id = params[0].get::<String>().unwrap();
- let contract_id = match ContractId::from_str(contract_id) {
- Ok(v) => v,
- Err(e) => {
- error!(target: "darkfid::rpc::blockchain_get_contract_state", "Error decoding string to ContractId: {e}");
- return JsonError::new(InvalidParams, None, id).into()
- }
- };
- let tree_name = params[1].get::<String>().unwrap();
- let validator = self.validator.read().await;
- match validator.blockchain.contracts.get_state_tree_records(
- &validator.blockchain.sled_db,
- &contract_id,
- tree_name,
- ) {
- Ok(records) => JsonResponse::new(
- JsonValue::String(base64::encode(&serialize_async(&records).await)),
- id,
- )
- .into(),
- Err(e) => {
- error!(target: "darkfid::rpc::blockchain_get_contract_state", "Failed fetching contract state records: {e}");
- server_error(RpcError::ContractStateNotFound, id, None)
- }
- }
- }
- // RPCAPI:
- // Queries the blockchain database for a given contract state key raw bytes.
- // Returns the record value raw bytes.
- //
- // **Params:**
- // * `array[0]`: base58-encoded contract ID string
- // * `array[1]`: Contract tree name string
- // * `array[2]`: Key raw bytes, encoded with base64
- //
- // **Returns:**
- // * Record value raw bytes encoded with base64
- //
- // --> {"jsonrpc": "2.0", "method": "blockchain.get_contract_state_key", "params": ["BZHK...", "tree", "ABCD..."], "id": 1}
- // <-- {"jsonrpc": "2.0", "result": "ABCD...", "id": 1}
- pub async fn blockchain_get_contract_state_key(
- &self,
- id: i64,
- params: JsonValue,
- ) -> JsonResult {
- let Some(params) = params.get::<Vec<JsonValue>>() else {
- return JsonError::new(InvalidParams, None, id).into()
- };
- if params.len() != 3 ||
- !params[0].is_string() ||
- !params[1].is_string() ||
- !params[2].is_string()
- {
- return JsonError::new(InvalidParams, None, id).into()
- }
- let contract_id = params[0].get::<String>().unwrap();
- let contract_id = match ContractId::from_str(contract_id) {
- Ok(v) => v,
- Err(e) => {
- error!(target: "darkfid::rpc::blockchain_get_contract_state_key", "Error decoding string to ContractId: {e}");
- return JsonError::new(InvalidParams, None, id).into()
- }
- };
- let tree_name = params[1].get::<String>().unwrap();
- let key_enc = params[2].get::<String>().unwrap().trim();
- let Some(key) = base64::decode(key_enc) else {
- error!(target: "darkfid::rpc::blockchain_get_contract_state_key", "Failed decoding base64 key");
- return server_error(RpcError::ParseError, id, None)
- };
- let validator = self.validator.read().await;
- match validator.blockchain.contracts.get_state_tree_value(
- &validator.blockchain.sled_db,
- &contract_id,
- tree_name,
- &key,
- ) {
- Ok(value) => JsonResponse::new(JsonValue::String(base64::encode(&value)), id).into(),
- Err(e) => {
- error!(target: "darkfid::rpc::blockchain_get_contract_state_key", "Failed fetching contract state key value: {e}");
- server_error(RpcError::ContractStateKeyNotFound, id, None)
- }
- }
- }
- }
|