rpc_tx.rs 6.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159
  1. /* This file is part of DarkFi (https://dark.fi)
  2. *
  3. * Copyright (C) 2020-2023 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 darkfi_serial::deserialize;
  19. use log::{error, warn};
  20. use serde_json::{json, Value};
  21. use darkfi::{
  22. rpc::jsonrpc::{ErrorCode::InvalidParams, JsonError, JsonResponse, JsonResult},
  23. tx::Transaction,
  24. };
  25. use super::Darkfid;
  26. use crate::{server_error, RpcError};
  27. impl Darkfid {
  28. // RPCAPI:
  29. // Simulate a network state transition with the given transaction.
  30. // Returns `true` if the transaction is valid, otherwise, a corresponding
  31. // error.
  32. //
  33. // --> {"jsonrpc": "2.0", "method": "tx.simulate", "params": ["base58encodedTX"], "id": 1}
  34. // <-- {"jsonrpc": "2.0", "result": true, "id": 1}
  35. pub async fn tx_simulate(&self, id: Value, params: &[Value]) -> JsonResult {
  36. if params.len() != 1 || !params[0].is_string() {
  37. return JsonError::new(InvalidParams, None, id).into()
  38. }
  39. if !(*self.synced.lock().await) {
  40. error!("[RPC] tx.simulate: Blockchain is not synced");
  41. return server_error(RpcError::NotSynced, id, None)
  42. }
  43. // Try to deserialize the transaction
  44. let tx_bytes = match bs58::decode(params[0].as_str().unwrap().trim()).into_vec() {
  45. Ok(v) => v,
  46. Err(e) => {
  47. error!("[RPC] tx.simulate: Failed decoding base58 transaction: {}", e);
  48. return server_error(RpcError::ParseError, id, None)
  49. }
  50. };
  51. let tx: Transaction = match deserialize(&tx_bytes) {
  52. Ok(v) => v,
  53. Err(e) => {
  54. error!("[RPC] tx.simulate: Failed deserializing bytes into Transaction: {}", e);
  55. return server_error(RpcError::ParseError, id, None)
  56. }
  57. };
  58. // Simulate state transition
  59. let lock = self.validator_state.read().await;
  60. let current_slot = lock.consensus.time_keeper.current_slot();
  61. match lock.verify_transactions(&[tx], current_slot, false).await {
  62. Ok(erroneous_txs) => {
  63. if !erroneous_txs.is_empty() {
  64. error!("[RPC] tx.simulate: invalid transaction provided");
  65. return server_error(RpcError::TxSimulationFail, id, None)
  66. }
  67. }
  68. Err(e) => {
  69. error!("[RPC] tx.simulate: Failed to validate state transition: {}", e);
  70. return server_error(RpcError::TxSimulationFail, id, None)
  71. }
  72. };
  73. JsonResponse::new(json!(true), id).into()
  74. }
  75. // RPCAPI:
  76. // Broadcast a given transaction to the P2P network.
  77. // The function will first simulate the state transition in order to see
  78. // if the transaction is actually valid, and in turn it will return an
  79. // error if this is the case. Otherwise, a transaction ID will be returned.
  80. //
  81. // --> {"jsonrpc": "2.0", "method": "tx.broadcast", "params": ["base58encodedTX"], "id": 1}
  82. // <-- {"jsonrpc": "2.0", "result": "txID...", "id": 1}
  83. pub async fn tx_broadcast(&self, id: Value, params: &[Value]) -> JsonResult {
  84. if params.len() != 1 || !params[0].is_string() {
  85. return JsonError::new(InvalidParams, None, id).into()
  86. }
  87. if !(*self.synced.lock().await) {
  88. error!("[RPC] tx.transfer: Blockchain is not synced");
  89. return server_error(RpcError::NotSynced, id, None)
  90. }
  91. // Try to deserialize the transaction
  92. let tx_bytes = match bs58::decode(params[0].as_str().unwrap().trim()).into_vec() {
  93. Ok(v) => v,
  94. Err(e) => {
  95. error!("[RPC] tx.broadcast: Failed decoding base58 transaction: {}", e);
  96. return server_error(RpcError::ParseError, id, None)
  97. }
  98. };
  99. let tx: Transaction = match deserialize(&tx_bytes) {
  100. Ok(v) => v,
  101. Err(e) => {
  102. error!("[RPC] tx.broadcast: Failed deserializing bytes into Transaction: {}", e);
  103. return server_error(RpcError::ParseError, id, None)
  104. }
  105. };
  106. if self.consensus_p2p.is_some() {
  107. // Consider we're participating in consensus here?
  108. // The append_tx function performs a state transition check.
  109. if !self.validator_state.write().await.append_tx(tx.clone()).await {
  110. error!("[RPC] tx.broadcast: Failed to append transaction to mempool");
  111. return server_error(RpcError::TxBroadcastFail, id, None)
  112. }
  113. } else {
  114. // We'll perform the state transition check here.
  115. let lock = self.validator_state.read().await;
  116. let current_slot = lock.consensus.time_keeper.current_slot();
  117. match lock.verify_transactions(&[tx.clone()], current_slot, false).await {
  118. Ok(erroneous_txs) => {
  119. if !erroneous_txs.is_empty() {
  120. error!("[RPC] tx.broadcast: invalid transaction provided");
  121. return server_error(RpcError::TxSimulationFail, id, None)
  122. }
  123. }
  124. Err(e) => {
  125. error!("[RPC] tx.broadcast: Failed to validate state transition: {}", e);
  126. return server_error(RpcError::TxSimulationFail, id, None)
  127. }
  128. };
  129. }
  130. if let Some(sync_p2p) = &self.sync_p2p {
  131. sync_p2p.broadcast(&tx).await;
  132. if sync_p2p.channels().lock().await.is_empty() {
  133. error!("[RPC] tx.broadcast: Failed broadcasting tx, no connected channels");
  134. return server_error(RpcError::TxBroadcastFail, id, None)
  135. }
  136. } else {
  137. warn!("[RPC] tx.broadcast: No sync P2P network, not broadcasting transaction.");
  138. return server_error(RpcError::TxBroadcastFail, id, None)
  139. }
  140. let tx_hash = tx.hash().to_string();
  141. JsonResponse::new(json!(tx_hash), id).into()
  142. }
  143. }