rpc_tx.rs 8.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212
  1. /* This file is part of DarkFi (https://dark.fi)
  2. *
  3. * Copyright (C) 2020-2024 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_async;
  19. use log::error;
  20. use tinyjson::JsonValue;
  21. use darkfi::{
  22. rpc::jsonrpc::{
  23. ErrorCode::{InternalError, InvalidParams},
  24. JsonError, JsonResponse, JsonResult,
  25. },
  26. tx::Transaction,
  27. util::encoding::base64,
  28. };
  29. use super::Darkfid;
  30. use crate::{server_error, RpcError};
  31. impl Darkfid {
  32. // RPCAPI:
  33. // Simulate a network state transition with the given transaction.
  34. // Returns `true` if the transaction is valid, otherwise, a corresponding
  35. // error.
  36. //
  37. // --> {"jsonrpc": "2.0", "method": "tx.simulate", "params": ["base64encodedTX"], "id": 1}
  38. // <-- {"jsonrpc": "2.0", "result": true, "id": 1}
  39. pub async fn tx_simulate(&self, id: u16, params: JsonValue) -> JsonResult {
  40. let params = params.get::<Vec<JsonValue>>().unwrap();
  41. if params.len() != 1 || !params[0].is_string() {
  42. return JsonError::new(InvalidParams, None, id).into()
  43. }
  44. if !*self.validator.synced.read().await {
  45. error!(target: "darkfid::rpc::tx_simulate", "Blockchain is not synced");
  46. return server_error(RpcError::NotSynced, id, None)
  47. }
  48. // Try to deserialize the transaction
  49. let tx_enc = params[0].get::<String>().unwrap().trim();
  50. let tx_bytes = match base64::decode(tx_enc) {
  51. Some(v) => v,
  52. None => {
  53. error!(target: "darkfid::rpc::tx_simulate", "Failed decoding base64 transaction");
  54. return server_error(RpcError::ParseError, id, None)
  55. }
  56. };
  57. let tx: Transaction = match deserialize_async(&tx_bytes).await {
  58. Ok(v) => v,
  59. Err(e) => {
  60. error!(target: "darkfid::rpc::tx_simulate", "Failed deserializing bytes into Transaction: {}", e);
  61. return server_error(RpcError::ParseError, id, None)
  62. }
  63. };
  64. // Simulate state transition
  65. let result = self.validator.append_tx(&tx, false).await;
  66. if result.is_err() {
  67. error!(
  68. target: "darkfid::rpc::tx_simulate", "Failed to validate state transition: {}",
  69. result.err().unwrap()
  70. );
  71. return server_error(RpcError::TxSimulationFail, id, None)
  72. };
  73. JsonResponse::new(JsonValue::Boolean(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": ["base64encodedTX"], "id": 1}
  82. // <-- {"jsonrpc": "2.0", "result": "txID...", "id": 1}
  83. pub async fn tx_broadcast(&self, id: u16, params: JsonValue) -> JsonResult {
  84. let params = params.get::<Vec<JsonValue>>().unwrap();
  85. if params.len() != 1 || !params[0].is_string() {
  86. return JsonError::new(InvalidParams, None, id).into()
  87. }
  88. if !*self.validator.synced.read().await {
  89. error!(target: "darkfid::rpc::tx_broadcast", "Blockchain is not synced");
  90. return server_error(RpcError::NotSynced, id, None)
  91. }
  92. // Try to deserialize the transaction
  93. let tx_enc = params[0].get::<String>().unwrap().trim();
  94. let tx_bytes = match base64::decode(tx_enc) {
  95. Some(v) => v,
  96. None => {
  97. error!(target: "darkfid::rpc::tx_broadcast", "Failed decoding base64 transaction");
  98. return server_error(RpcError::ParseError, id, None)
  99. }
  100. };
  101. let tx: Transaction = match deserialize_async(&tx_bytes).await {
  102. Ok(v) => v,
  103. Err(e) => {
  104. error!(target: "darkfid::rpc::tx_broadcast", "Failed deserializing bytes into Transaction: {}", e);
  105. return server_error(RpcError::ParseError, id, None)
  106. }
  107. };
  108. // Block production participants can directly perform
  109. // the state transition check and append to their
  110. // pending transactions store.
  111. let error_message = if self.miner {
  112. "Failed to append transaction to mempool"
  113. } else {
  114. "Failed to validate state transition"
  115. };
  116. // We'll perform the state transition check here.
  117. if let Err(e) = self.validator.append_tx(&tx, self.miner).await {
  118. error!(target: "darkfid::rpc::tx_broadcast", "{}: {}", error_message, e);
  119. return server_error(RpcError::TxSimulationFail, id, None)
  120. };
  121. self.p2p.broadcast(&tx).await;
  122. if self.p2p.hosts().channels().await.is_empty() {
  123. error!(target: "darkfid::rpc::tx_broadcast", "Failed broadcasting tx, no connected channels");
  124. return server_error(RpcError::TxBroadcastFail, id, None)
  125. }
  126. let tx_hash = tx.hash().to_string();
  127. JsonResponse::new(JsonValue::String(tx_hash), id).into()
  128. }
  129. // RPCAPI:
  130. // Queries the node pending transactions store to retrieve all transactions.
  131. // Returns a vector of hex-encoded transaction hashes.
  132. //
  133. // --> {"jsonrpc": "2.0", "method": "tx.pending", "params": [], "id": 1}
  134. // <-- {"jsonrpc": "2.0", "result": "[TxHash,...]", "id": 1}
  135. pub async fn tx_pending(&self, id: u16, params: JsonValue) -> JsonResult {
  136. let params = params.get::<Vec<JsonValue>>().unwrap();
  137. if !params.is_empty() {
  138. return JsonError::new(InvalidParams, None, id).into()
  139. }
  140. if !*self.validator.synced.read().await {
  141. error!(target: "darkfid::rpc::tx_pending", "Blockchain is not synced");
  142. return server_error(RpcError::NotSynced, id, None)
  143. }
  144. let pending_txs = match self.validator.blockchain.get_pending_txs() {
  145. Ok(v) => v,
  146. Err(e) => {
  147. error!(target: "darkfid::rpc::tx_pending", "Failed fetching pending txs: {}", e);
  148. return JsonError::new(InternalError, None, id).into()
  149. }
  150. };
  151. let pending_txs: Vec<JsonValue> =
  152. pending_txs.iter().map(|x| JsonValue::String(x.hash().to_string())).collect();
  153. JsonResponse::new(JsonValue::Array(pending_txs), id).into()
  154. }
  155. // RPCAPI:
  156. // Queries the node pending transactions store to remove all transactions.
  157. // Returns a vector of hex-encoded transaction hashes.
  158. //
  159. // --> {"jsonrpc": "2.0", "method": "tx.clean_pending", "params": [], "id": 1}
  160. // <-- {"jsonrpc": "2.0", "result": "[TxHash,...]", "id": 1}
  161. pub async fn tx_clean_pending(&self, id: u16, params: JsonValue) -> JsonResult {
  162. let params = params.get::<Vec<JsonValue>>().unwrap();
  163. if !params.is_empty() {
  164. return JsonError::new(InvalidParams, None, id).into()
  165. }
  166. if !*self.validator.synced.read().await {
  167. error!(target: "darkfid::rpc::tx_clean_pending", "Blockchain is not synced");
  168. return server_error(RpcError::NotSynced, id, None)
  169. }
  170. let pending_txs = match self.validator.blockchain.get_pending_txs() {
  171. Ok(v) => v,
  172. Err(e) => {
  173. error!(target: "darkfid::rpc::tx_clean_pending", "Failed fetching pending txs: {}", e);
  174. return JsonError::new(InternalError, None, id).into()
  175. }
  176. };
  177. if let Err(e) = self.validator.blockchain.remove_pending_txs(&pending_txs) {
  178. error!(target: "darkfid::rpc::tx_clean_pending", "Failed fetching pending txs: {}", e);
  179. return JsonError::new(InternalError, None, id).into()
  180. };
  181. let pending_txs: Vec<JsonValue> =
  182. pending_txs.iter().map(|x| JsonValue::String(x.hash().to_string())).collect();
  183. JsonResponse::new(JsonValue::Array(pending_txs), id).into()
  184. }
  185. }