rpc_tx.rs 6.7 KB

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