rpc_tx.rs 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263
  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, warn};
  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.is_connected() {
  123. warn!(target: "darkfid::rpc::tx_broadcast", "No connected channels to broadcast tx");
  124. }
  125. let tx_hash = tx.hash().to_string();
  126. JsonResponse::new(JsonValue::String(tx_hash), id).into()
  127. }
  128. // RPCAPI:
  129. // Queries the node pending transactions store to retrieve all transactions.
  130. // Returns a vector of hex-encoded transaction hashes.
  131. //
  132. // --> {"jsonrpc": "2.0", "method": "tx.pending", "params": [], "id": 1}
  133. // <-- {"jsonrpc": "2.0", "result": "[TxHash,...]", "id": 1}
  134. pub async fn tx_pending(&self, id: u16, params: JsonValue) -> JsonResult {
  135. let params = params.get::<Vec<JsonValue>>().unwrap();
  136. if !params.is_empty() {
  137. return JsonError::new(InvalidParams, None, id).into()
  138. }
  139. if !*self.validator.synced.read().await {
  140. error!(target: "darkfid::rpc::tx_pending", "Blockchain is not synced");
  141. return server_error(RpcError::NotSynced, id, None)
  142. }
  143. let pending_txs = match self.validator.blockchain.get_pending_txs() {
  144. Ok(v) => v,
  145. Err(e) => {
  146. error!(target: "darkfid::rpc::tx_pending", "Failed fetching pending txs: {}", e);
  147. return JsonError::new(InternalError, None, id).into()
  148. }
  149. };
  150. let pending_txs: Vec<JsonValue> =
  151. pending_txs.iter().map(|x| JsonValue::String(x.hash().to_string())).collect();
  152. JsonResponse::new(JsonValue::Array(pending_txs), id).into()
  153. }
  154. // RPCAPI:
  155. // Queries the node pending transactions store to remove all transactions.
  156. // Returns a vector of hex-encoded transaction hashes.
  157. //
  158. // --> {"jsonrpc": "2.0", "method": "tx.clean_pending", "params": [], "id": 1}
  159. // <-- {"jsonrpc": "2.0", "result": "[TxHash,...]", "id": 1}
  160. pub async fn tx_clean_pending(&self, id: u16, params: JsonValue) -> JsonResult {
  161. let params = params.get::<Vec<JsonValue>>().unwrap();
  162. if !params.is_empty() {
  163. return JsonError::new(InvalidParams, None, id).into()
  164. }
  165. if !*self.validator.synced.read().await {
  166. error!(target: "darkfid::rpc::tx_clean_pending", "Blockchain is not synced");
  167. return server_error(RpcError::NotSynced, id, None)
  168. }
  169. let pending_txs = match self.validator.blockchain.get_pending_txs() {
  170. Ok(v) => v,
  171. Err(e) => {
  172. error!(target: "darkfid::rpc::tx_clean_pending", "Failed fetching pending txs: {}", e);
  173. return JsonError::new(InternalError, None, id).into()
  174. }
  175. };
  176. if let Err(e) = self.validator.blockchain.remove_pending_txs(&pending_txs) {
  177. error!(target: "darkfid::rpc::tx_clean_pending", "Failed fetching pending txs: {}", e);
  178. return JsonError::new(InternalError, None, id).into()
  179. };
  180. let pending_txs: Vec<JsonValue> =
  181. pending_txs.iter().map(|x| JsonValue::String(x.hash().to_string())).collect();
  182. JsonResponse::new(JsonValue::Array(pending_txs), id).into()
  183. }
  184. // RPCAPI:
  185. // Compute provided transaction's total gas, against current best fork.
  186. // Returns the gas value if the transaction is valid, otherwise, a corresponding
  187. // error.
  188. //
  189. // --> {"jsonrpc": "2.0", "method": "tx.calculate_gas", "params": ["base64encodedTX", "include_fee"], "id": 1}
  190. // <-- {"jsonrpc": "2.0", "result": true, "id": 1}
  191. pub async fn tx_calculate_gas(&self, id: u16, params: JsonValue) -> JsonResult {
  192. let params = params.get::<Vec<JsonValue>>().unwrap();
  193. if params.len() != 2 || !params[0].is_string() || !params[1].is_bool() {
  194. return JsonError::new(InvalidParams, None, id).into()
  195. }
  196. if !*self.validator.synced.read().await {
  197. error!(target: "darkfid::rpc::tx_calculate_gas", "Blockchain is not synced");
  198. return server_error(RpcError::NotSynced, id, None)
  199. }
  200. // Try to deserialize the transaction
  201. let tx_enc = params[0].get::<String>().unwrap().trim();
  202. let tx_bytes = match base64::decode(tx_enc) {
  203. Some(v) => v,
  204. None => {
  205. error!(target: "darkfid::rpc::tx_calculate_gas", "Failed decoding base64 transaction");
  206. return server_error(RpcError::ParseError, id, None)
  207. }
  208. };
  209. let tx: Transaction = match deserialize_async(&tx_bytes).await {
  210. Ok(v) => v,
  211. Err(e) => {
  212. error!(target: "darkfid::rpc::tx_calculate_gas", "Failed deserializing bytes into Transaction: {}", e);
  213. return server_error(RpcError::ParseError, id, None)
  214. }
  215. };
  216. // Parse the include fee flag
  217. let include_fee = params[1].get::<bool>().unwrap();
  218. // Simulate state transition
  219. let result = self.validator.calculate_gas(&tx, *include_fee).await;
  220. if result.is_err() {
  221. error!(
  222. target: "darkfid::rpc::tx_calculate_gas", "Failed to validate state transition: {}",
  223. result.err().unwrap()
  224. );
  225. return server_error(RpcError::TxGasCalculationFail, id, None)
  226. };
  227. JsonResponse::new(JsonValue::Number(result.unwrap() as f64), id).into()
  228. }
  229. }