tx.rs 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257
  1. /* This file is part of DarkFi (https://dark.fi)
  2. *
  3. * Copyright (C) 2020-2026 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 tinyjson::JsonValue;
  20. use tracing::{error, warn};
  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::DarkfiNode;
  30. use crate::{server_error, RpcError};
  31. impl DarkfiNode {
  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 Some(params) = params.get::<Vec<JsonValue>>() else {
  41. return JsonError::new(InvalidParams, None, id).into()
  42. };
  43. if params.len() != 1 || !params[0].is_string() {
  44. return JsonError::new(InvalidParams, None, id).into()
  45. }
  46. if !*self.validator.synced.read().await {
  47. error!(target: "darkfid::rpc::tx_simulate", "Blockchain is not synced");
  48. return server_error(RpcError::NotSynced, id, None)
  49. }
  50. // Try to deserialize the transaction
  51. let tx_enc = params[0].get::<String>().unwrap().trim();
  52. let tx_bytes = match base64::decode(tx_enc) {
  53. Some(v) => v,
  54. None => {
  55. error!(target: "darkfid::rpc::tx_simulate", "Failed decoding base64 transaction");
  56. return server_error(RpcError::ParseError, id, None)
  57. }
  58. };
  59. let tx: Transaction = match deserialize_async(&tx_bytes).await {
  60. Ok(v) => v,
  61. Err(e) => {
  62. error!(target: "darkfid::rpc::tx_simulate", "Failed deserializing bytes into Transaction: {e}");
  63. return server_error(RpcError::ParseError, id, None)
  64. }
  65. };
  66. // Simulate state transition
  67. let result = self.validator.append_tx(&tx, false).await;
  68. if result.is_err() {
  69. error!(
  70. target: "darkfid::rpc::tx_simulate", "Failed to validate state transition: {}",
  71. result.err().unwrap()
  72. );
  73. return server_error(RpcError::TxSimulationFail, id, None)
  74. };
  75. JsonResponse::new(JsonValue::Boolean(true), id).into()
  76. }
  77. // RPCAPI:
  78. // Append a given transaction to the mempool and broadcast it to
  79. // the P2P network. The function will first simulate the state
  80. // transition in order to see if the transaction is actually valid,
  81. // and in turn it will return an error if this is the case.
  82. // Otherwise, a transaction ID will be returned.
  83. //
  84. // --> {"jsonrpc": "2.0", "method": "tx.broadcast", "params": ["base64encodedTX"], "id": 1}
  85. // <-- {"jsonrpc": "2.0", "result": "txID...", "id": 1}
  86. pub async fn tx_broadcast(&self, id: u16, params: JsonValue) -> JsonResult {
  87. let Some(params) = params.get::<Vec<JsonValue>>() else {
  88. return JsonError::new(InvalidParams, None, id).into()
  89. };
  90. if params.len() != 1 || !params[0].is_string() {
  91. return JsonError::new(InvalidParams, None, id).into()
  92. }
  93. if !*self.validator.synced.read().await {
  94. error!(target: "darkfid::rpc::tx_broadcast", "Blockchain is not synced");
  95. return server_error(RpcError::NotSynced, id, None)
  96. }
  97. // Try to deserialize the transaction
  98. let tx_enc = params[0].get::<String>().unwrap().trim();
  99. let tx_bytes = match base64::decode(tx_enc) {
  100. Some(v) => v,
  101. None => {
  102. error!(target: "darkfid::rpc::tx_broadcast", "Failed decoding base64 transaction");
  103. return server_error(RpcError::ParseError, id, None)
  104. }
  105. };
  106. let tx: Transaction = match deserialize_async(&tx_bytes).await {
  107. Ok(v) => v,
  108. Err(e) => {
  109. error!(target: "darkfid::rpc::tx_broadcast", "Failed deserializing bytes into Transaction: {e}");
  110. return server_error(RpcError::ParseError, id, None)
  111. }
  112. };
  113. // We'll perform the state transition check here.
  114. if let Err(e) = self.validator.append_tx(&tx, true).await {
  115. error!(target: "darkfid::rpc::tx_broadcast", "Failed to append transaction to mempool: {e}");
  116. return server_error(RpcError::TxSimulationFail, id, None)
  117. };
  118. self.p2p_handler.p2p.broadcast(&tx).await;
  119. if !self.p2p_handler.p2p.is_connected() {
  120. warn!(target: "darkfid::rpc::tx_broadcast", "No connected channels to broadcast tx");
  121. }
  122. let tx_hash = tx.hash().to_string();
  123. JsonResponse::new(JsonValue::String(tx_hash), id).into()
  124. }
  125. // RPCAPI:
  126. // Queries the node pending transactions store to retrieve all transactions.
  127. // Returns a vector of hex-encoded transaction hashes.
  128. //
  129. // --> {"jsonrpc": "2.0", "method": "tx.pending", "params": [], "id": 1}
  130. // <-- {"jsonrpc": "2.0", "result": ["TxHash" , "..."], "id": 1}
  131. pub async fn tx_pending(&self, id: u16, params: JsonValue) -> JsonResult {
  132. let Some(params) = params.get::<Vec<JsonValue>>() else {
  133. return JsonError::new(InvalidParams, None, id).into()
  134. };
  135. if !params.is_empty() {
  136. return JsonError::new(InvalidParams, None, id).into()
  137. }
  138. if !*self.validator.synced.read().await {
  139. error!(target: "darkfid::rpc::tx_pending", "Blockchain is not synced");
  140. return server_error(RpcError::NotSynced, id, None)
  141. }
  142. let pending_txs = match self.validator.blockchain.get_pending_txs() {
  143. Ok(v) => v,
  144. Err(e) => {
  145. error!(target: "darkfid::rpc::tx_pending", "Failed fetching pending txs: {e}");
  146. return JsonError::new(InternalError, None, id).into()
  147. }
  148. };
  149. let pending_txs: Vec<JsonValue> =
  150. pending_txs.iter().map(|x| JsonValue::String(x.hash().to_string())).collect();
  151. JsonResponse::new(JsonValue::Array(pending_txs), id).into()
  152. }
  153. // RPCAPI:
  154. // Queries the node pending transactions store to reset all
  155. // transactions. Unproposed transactions are removed.
  156. // Returns `true` if the operation was successful, otherwise, a
  157. // corresponding error.
  158. //
  159. // --> {"jsonrpc": "2.0", "method": "tx.clean_pending", "params": [], "id": 1}
  160. // <-- {"jsonrpc": "2.0", "result": true, "id": 1}
  161. pub async fn tx_clean_pending(&self, id: u16, params: JsonValue) -> JsonResult {
  162. let Some(params) = params.get::<Vec<JsonValue>>() else {
  163. return JsonError::new(InvalidParams, None, id).into()
  164. };
  165. if !params.is_empty() {
  166. return JsonError::new(InvalidParams, None, id).into()
  167. }
  168. if !*self.validator.synced.read().await {
  169. error!(target: "darkfid::rpc::tx_clean_pending", "Blockchain is not synced");
  170. return server_error(RpcError::NotSynced, id, None)
  171. }
  172. if let Err(e) = self.validator.consensus.purge_unproposed_pending_txs().await {
  173. error!(target: "darkfid::rpc::tx_clean_pending", "Failed removing pending txs: {e}");
  174. return JsonError::new(InternalError, None, id).into()
  175. };
  176. JsonResponse::new(JsonValue::Boolean(true), id).into()
  177. }
  178. // RPCAPI:
  179. // Compute provided transaction's total gas, against current best fork.
  180. // Returns the gas value if the transaction is valid, otherwise, a corresponding
  181. // error.
  182. //
  183. // --> {"jsonrpc": "2.0", "method": "tx.calculate_fee", "params": ["base64encodedTX", "include_fee"], "id": 1}
  184. // <-- {"jsonrpc": "2.0", "result": true, "id": 1}
  185. pub async fn tx_calculate_fee(&self, id: u16, params: JsonValue) -> JsonResult {
  186. let Some(params) = params.get::<Vec<JsonValue>>() else {
  187. return JsonError::new(InvalidParams, None, id).into()
  188. };
  189. if params.len() != 2 || !params[0].is_string() || !params[1].is_bool() {
  190. return JsonError::new(InvalidParams, None, id).into()
  191. }
  192. if !*self.validator.synced.read().await {
  193. error!(target: "darkfid::rpc::tx_calculate_fee", "Blockchain is not synced");
  194. return server_error(RpcError::NotSynced, id, None)
  195. }
  196. // Try to deserialize the transaction
  197. let tx_enc = params[0].get::<String>().unwrap().trim();
  198. let tx_bytes = match base64::decode(tx_enc) {
  199. Some(v) => v,
  200. None => {
  201. error!(target: "darkfid::rpc::tx_calculate_fee", "Failed decoding base64 transaction");
  202. return server_error(RpcError::ParseError, id, None)
  203. }
  204. };
  205. let tx: Transaction = match deserialize_async(&tx_bytes).await {
  206. Ok(v) => v,
  207. Err(e) => {
  208. error!(target: "darkfid::rpc::tx_calculate_fee", "Failed deserializing bytes into Transaction: {e}");
  209. return server_error(RpcError::ParseError, id, None)
  210. }
  211. };
  212. // Parse the include fee flag
  213. let include_fee = params[1].get::<bool>().unwrap();
  214. // Simulate state transition
  215. let result = self.validator.calculate_fee(&tx, *include_fee).await;
  216. if result.is_err() {
  217. error!(
  218. target: "darkfid::rpc::tx_calculate_fee", "Failed to validate state transition: {}",
  219. result.err().unwrap()
  220. );
  221. return server_error(RpcError::TxGasCalculationFail, id, None)
  222. };
  223. JsonResponse::new(JsonValue::Number(result.unwrap() as f64), id).into()
  224. }
  225. }