rpc_tx.rs 8.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218
  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. if self.miners_p2p.is_some() {
  109. // Block production participants can directly perform
  110. // the state transition check and append to their
  111. // pending transactions store.
  112. if self.validator.append_tx(&tx, true).await.is_err() {
  113. error!(target: "darkfid::rpc::tx_broadcast", "Failed to append transaction to mempool");
  114. return server_error(RpcError::TxSimulationFail, id, None)
  115. }
  116. } else {
  117. // We'll perform the state transition check here.
  118. let result = self.validator.append_tx(&tx, false).await;
  119. if result.is_err() {
  120. error!(
  121. target: "darkfid::rpc::tx_broadcast", "Failed to validate state transition: {}",
  122. result.err().unwrap()
  123. );
  124. return server_error(RpcError::TxSimulationFail, id, None)
  125. };
  126. }
  127. self.sync_p2p.broadcast(&tx).await;
  128. if self.sync_p2p.channels().await.is_empty() {
  129. error!(target: "darkfid::rpc::tx_broadcast", "Failed broadcasting tx, no connected channels");
  130. return server_error(RpcError::TxBroadcastFail, id, None)
  131. }
  132. let tx_hash = tx.hash().unwrap().to_string();
  133. JsonResponse::new(JsonValue::String(tx_hash), id).into()
  134. }
  135. // RPCAPI:
  136. // Queries the node pending transactions store to retrieve all transactions.
  137. // Returns a vector of hex-encoded transaction hashes.
  138. //
  139. // --> {"jsonrpc": "2.0", "method": "tx.pending", "params": [], "id": 1}
  140. // <-- {"jsonrpc": "2.0", "result": "[TxHash,...]", "id": 1}
  141. pub async fn tx_pending(&self, id: u16, params: JsonValue) -> JsonResult {
  142. let params = params.get::<Vec<JsonValue>>().unwrap();
  143. if !params.is_empty() {
  144. return JsonError::new(InvalidParams, None, id).into()
  145. }
  146. if !*self.validator.synced.read().await {
  147. error!(target: "darkfid::rpc::tx_pending", "Blockchain is not synced");
  148. return server_error(RpcError::NotSynced, id, None)
  149. }
  150. let pending_txs = match self.validator.blockchain.get_pending_txs() {
  151. Ok(v) => v,
  152. Err(e) => {
  153. error!(target: "darkfid::rpc::tx_pending", "Failed fetching pending txs: {}", e);
  154. return JsonError::new(InternalError, None, id).into()
  155. }
  156. };
  157. let pending_txs: Vec<JsonValue> =
  158. pending_txs.iter().map(|x| JsonValue::String(x.hash().unwrap().to_string())).collect();
  159. JsonResponse::new(JsonValue::Array(pending_txs), id).into()
  160. }
  161. // RPCAPI:
  162. // Queries the node pending transactions store to remove all transactions.
  163. // Returns a vector of hex-encoded transaction hashes.
  164. //
  165. // --> {"jsonrpc": "2.0", "method": "tx.clean_pending", "params": [], "id": 1}
  166. // <-- {"jsonrpc": "2.0", "result": "[TxHash,...]", "id": 1}
  167. pub async fn tx_clean_pending(&self, id: u16, params: JsonValue) -> JsonResult {
  168. let params = params.get::<Vec<JsonValue>>().unwrap();
  169. if !params.is_empty() {
  170. return JsonError::new(InvalidParams, None, id).into()
  171. }
  172. if !*self.validator.synced.read().await {
  173. error!(target: "darkfid::rpc::tx_clean_pending", "Blockchain is not synced");
  174. return server_error(RpcError::NotSynced, id, None)
  175. }
  176. let pending_txs = match self.validator.blockchain.get_pending_txs() {
  177. Ok(v) => v,
  178. Err(e) => {
  179. error!(target: "darkfid::rpc::tx_clean_pending", "Failed fetching pending txs: {}", e);
  180. return JsonError::new(InternalError, None, id).into()
  181. }
  182. };
  183. if let Err(e) = self.validator.blockchain.remove_pending_txs(&pending_txs) {
  184. error!(target: "darkfid::rpc::tx_clean_pending", "Failed fetching pending txs: {}", e);
  185. return JsonError::new(InternalError, None, id).into()
  186. };
  187. let pending_txs: Vec<JsonValue> =
  188. pending_txs.iter().map(|x| JsonValue::String(x.hash().unwrap().to_string())).collect();
  189. JsonResponse::new(JsonValue::Array(pending_txs), id).into()
  190. }
  191. }