| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263 |
- /* This file is part of DarkFi (https://dark.fi)
- *
- * Copyright (C) 2020-2024 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 darkfi_serial::deserialize_async;
- use log::{error, warn};
- use tinyjson::JsonValue;
- use darkfi::{
- rpc::jsonrpc::{
- ErrorCode::{InternalError, InvalidParams},
- JsonError, JsonResponse, JsonResult,
- },
- tx::Transaction,
- util::encoding::base64,
- };
- use super::Darkfid;
- use crate::{server_error, RpcError};
- impl Darkfid {
- // RPCAPI:
- // Simulate a network state transition with the given transaction.
- // Returns `true` if the transaction is valid, otherwise, a corresponding
- // error.
- //
- // --> {"jsonrpc": "2.0", "method": "tx.simulate", "params": ["base64encodedTX"], "id": 1}
- // <-- {"jsonrpc": "2.0", "result": true, "id": 1}
- pub async fn tx_simulate(&self, id: u16, params: JsonValue) -> JsonResult {
- let params = params.get::<Vec<JsonValue>>().unwrap();
- if params.len() != 1 || !params[0].is_string() {
- return JsonError::new(InvalidParams, None, id).into()
- }
- if !*self.validator.synced.read().await {
- error!(target: "darkfid::rpc::tx_simulate", "Blockchain is not synced");
- return server_error(RpcError::NotSynced, id, None)
- }
- // Try to deserialize the transaction
- let tx_enc = params[0].get::<String>().unwrap().trim();
- let tx_bytes = match base64::decode(tx_enc) {
- Some(v) => v,
- None => {
- error!(target: "darkfid::rpc::tx_simulate", "Failed decoding base64 transaction");
- return server_error(RpcError::ParseError, id, None)
- }
- };
- let tx: Transaction = match deserialize_async(&tx_bytes).await {
- Ok(v) => v,
- Err(e) => {
- error!(target: "darkfid::rpc::tx_simulate", "Failed deserializing bytes into Transaction: {}", e);
- return server_error(RpcError::ParseError, id, None)
- }
- };
- // Simulate state transition
- let result = self.validator.append_tx(&tx, false).await;
- if result.is_err() {
- error!(
- target: "darkfid::rpc::tx_simulate", "Failed to validate state transition: {}",
- result.err().unwrap()
- );
- return server_error(RpcError::TxSimulationFail, id, None)
- };
- JsonResponse::new(JsonValue::Boolean(true), id).into()
- }
- // RPCAPI:
- // Broadcast a given transaction to the P2P network.
- // The function will first simulate the state transition in order to see
- // if the transaction is actually valid, and in turn it will return an
- // error if this is the case. Otherwise, a transaction ID will be returned.
- //
- // --> {"jsonrpc": "2.0", "method": "tx.broadcast", "params": ["base64encodedTX"], "id": 1}
- // <-- {"jsonrpc": "2.0", "result": "txID...", "id": 1}
- pub async fn tx_broadcast(&self, id: u16, params: JsonValue) -> JsonResult {
- let params = params.get::<Vec<JsonValue>>().unwrap();
- if params.len() != 1 || !params[0].is_string() {
- return JsonError::new(InvalidParams, None, id).into()
- }
- if !*self.validator.synced.read().await {
- error!(target: "darkfid::rpc::tx_broadcast", "Blockchain is not synced");
- return server_error(RpcError::NotSynced, id, None)
- }
- // Try to deserialize the transaction
- let tx_enc = params[0].get::<String>().unwrap().trim();
- let tx_bytes = match base64::decode(tx_enc) {
- Some(v) => v,
- None => {
- error!(target: "darkfid::rpc::tx_broadcast", "Failed decoding base64 transaction");
- return server_error(RpcError::ParseError, id, None)
- }
- };
- let tx: Transaction = match deserialize_async(&tx_bytes).await {
- Ok(v) => v,
- Err(e) => {
- error!(target: "darkfid::rpc::tx_broadcast", "Failed deserializing bytes into Transaction: {}", e);
- return server_error(RpcError::ParseError, id, None)
- }
- };
- // Block production participants can directly perform
- // the state transition check and append to their
- // pending transactions store.
- let error_message = if self.miner {
- "Failed to append transaction to mempool"
- } else {
- "Failed to validate state transition"
- };
- // We'll perform the state transition check here.
- if let Err(e) = self.validator.append_tx(&tx, self.miner).await {
- error!(target: "darkfid::rpc::tx_broadcast", "{}: {}", error_message, e);
- return server_error(RpcError::TxSimulationFail, id, None)
- };
- self.p2p.broadcast(&tx).await;
- if !self.p2p.is_connected() {
- warn!(target: "darkfid::rpc::tx_broadcast", "No connected channels to broadcast tx");
- }
- let tx_hash = tx.hash().to_string();
- JsonResponse::new(JsonValue::String(tx_hash), id).into()
- }
- // RPCAPI:
- // Queries the node pending transactions store to retrieve all transactions.
- // Returns a vector of hex-encoded transaction hashes.
- //
- // --> {"jsonrpc": "2.0", "method": "tx.pending", "params": [], "id": 1}
- // <-- {"jsonrpc": "2.0", "result": "[TxHash,...]", "id": 1}
- pub async fn tx_pending(&self, id: u16, params: JsonValue) -> JsonResult {
- let params = params.get::<Vec<JsonValue>>().unwrap();
- if !params.is_empty() {
- return JsonError::new(InvalidParams, None, id).into()
- }
- if !*self.validator.synced.read().await {
- error!(target: "darkfid::rpc::tx_pending", "Blockchain is not synced");
- return server_error(RpcError::NotSynced, id, None)
- }
- let pending_txs = match self.validator.blockchain.get_pending_txs() {
- Ok(v) => v,
- Err(e) => {
- error!(target: "darkfid::rpc::tx_pending", "Failed fetching pending txs: {}", e);
- return JsonError::new(InternalError, None, id).into()
- }
- };
- let pending_txs: Vec<JsonValue> =
- pending_txs.iter().map(|x| JsonValue::String(x.hash().to_string())).collect();
- JsonResponse::new(JsonValue::Array(pending_txs), id).into()
- }
- // RPCAPI:
- // Queries the node pending transactions store to remove all transactions.
- // Returns a vector of hex-encoded transaction hashes.
- //
- // --> {"jsonrpc": "2.0", "method": "tx.clean_pending", "params": [], "id": 1}
- // <-- {"jsonrpc": "2.0", "result": "[TxHash,...]", "id": 1}
- pub async fn tx_clean_pending(&self, id: u16, params: JsonValue) -> JsonResult {
- let params = params.get::<Vec<JsonValue>>().unwrap();
- if !params.is_empty() {
- return JsonError::new(InvalidParams, None, id).into()
- }
- if !*self.validator.synced.read().await {
- error!(target: "darkfid::rpc::tx_clean_pending", "Blockchain is not synced");
- return server_error(RpcError::NotSynced, id, None)
- }
- let pending_txs = match self.validator.blockchain.get_pending_txs() {
- Ok(v) => v,
- Err(e) => {
- error!(target: "darkfid::rpc::tx_clean_pending", "Failed fetching pending txs: {}", e);
- return JsonError::new(InternalError, None, id).into()
- }
- };
- if let Err(e) = self.validator.blockchain.remove_pending_txs(&pending_txs) {
- error!(target: "darkfid::rpc::tx_clean_pending", "Failed fetching pending txs: {}", e);
- return JsonError::new(InternalError, None, id).into()
- };
- let pending_txs: Vec<JsonValue> =
- pending_txs.iter().map(|x| JsonValue::String(x.hash().to_string())).collect();
- JsonResponse::new(JsonValue::Array(pending_txs), id).into()
- }
- // RPCAPI:
- // Compute provided transaction's total gas, against current best fork.
- // Returns the gas value if the transaction is valid, otherwise, a corresponding
- // error.
- //
- // --> {"jsonrpc": "2.0", "method": "tx.calculate_gas", "params": ["base64encodedTX", "include_fee"], "id": 1}
- // <-- {"jsonrpc": "2.0", "result": true, "id": 1}
- pub async fn tx_calculate_gas(&self, id: u16, params: JsonValue) -> JsonResult {
- let params = params.get::<Vec<JsonValue>>().unwrap();
- if params.len() != 2 || !params[0].is_string() || !params[1].is_bool() {
- return JsonError::new(InvalidParams, None, id).into()
- }
- if !*self.validator.synced.read().await {
- error!(target: "darkfid::rpc::tx_calculate_gas", "Blockchain is not synced");
- return server_error(RpcError::NotSynced, id, None)
- }
- // Try to deserialize the transaction
- let tx_enc = params[0].get::<String>().unwrap().trim();
- let tx_bytes = match base64::decode(tx_enc) {
- Some(v) => v,
- None => {
- error!(target: "darkfid::rpc::tx_calculate_gas", "Failed decoding base64 transaction");
- return server_error(RpcError::ParseError, id, None)
- }
- };
- let tx: Transaction = match deserialize_async(&tx_bytes).await {
- Ok(v) => v,
- Err(e) => {
- error!(target: "darkfid::rpc::tx_calculate_gas", "Failed deserializing bytes into Transaction: {}", e);
- return server_error(RpcError::ParseError, id, None)
- }
- };
- // Parse the include fee flag
- let include_fee = params[1].get::<bool>().unwrap();
- // Simulate state transition
- let result = self.validator.calculate_gas(&tx, *include_fee).await;
- if result.is_err() {
- error!(
- target: "darkfid::rpc::tx_calculate_gas", "Failed to validate state transition: {}",
- result.err().unwrap()
- );
- return server_error(RpcError::TxGasCalculationFail, id, None)
- };
- JsonResponse::new(JsonValue::Number(result.unwrap() as f64), id).into()
- }
- }
|