rpc_tx.rs 9.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220
  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_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 current_slot = self.validator.consensus.time_keeper.current_slot();
  66. let result = self.validator.add_transactions(&[tx], current_slot, false).await;
  67. if result.is_err() {
  68. error!(
  69. target: "darkfid::rpc::tx_simulate", "Failed to validate state transition: {}",
  70. result.err().unwrap()
  71. );
  72. return server_error(RpcError::TxSimulationFail, id, None)
  73. };
  74. JsonResponse::new(JsonValue::Boolean(true), id).into()
  75. }
  76. // RPCAPI:
  77. // Broadcast a given transaction to the P2P network.
  78. // The function will first simulate the state transition in order to see
  79. // if the transaction is actually valid, and in turn it will return an
  80. // error if this is the case. Otherwise, a transaction ID will be returned.
  81. //
  82. // --> {"jsonrpc": "2.0", "method": "tx.broadcast", "params": ["base64encodedTX"], "id": 1}
  83. // <-- {"jsonrpc": "2.0", "result": "txID...", "id": 1}
  84. pub async fn tx_broadcast(&self, id: u16, params: JsonValue) -> JsonResult {
  85. let params = params.get::<Vec<JsonValue>>().unwrap();
  86. if params.len() != 1 || !params[0].is_string() {
  87. return JsonError::new(InvalidParams, None, id).into()
  88. }
  89. if !*self.validator.synced.read().await {
  90. error!(target: "darkfid::rpc::tx_broadcast", "Blockchain is not synced");
  91. return server_error(RpcError::NotSynced, id, None)
  92. }
  93. // Try to deserialize the transaction
  94. let tx_enc = params[0].get::<String>().unwrap().trim();
  95. let tx_bytes = match base64::decode(tx_enc) {
  96. Some(v) => v,
  97. None => {
  98. error!(target: "darkfid::rpc::tx_broadcast", "Failed decoding base64 transaction");
  99. return server_error(RpcError::ParseError, id, None)
  100. }
  101. };
  102. let tx: Transaction = match deserialize_async(&tx_bytes).await {
  103. Ok(v) => v,
  104. Err(e) => {
  105. error!(target: "darkfid::rpc::tx_broadcast", "Failed deserializing bytes into Transaction: {}", e);
  106. return server_error(RpcError::ParseError, id, None)
  107. }
  108. };
  109. if self.consensus_p2p.is_some() {
  110. // Consensus participants can directly perform
  111. // the state transition check and append to their
  112. // pending transactions store.
  113. if self.validator.append_tx(&tx).await.is_err() {
  114. error!(target: "darkfid::rpc::tx_broadcast", "Failed to append transaction to mempool");
  115. return server_error(RpcError::TxSimulationFail, id, None)
  116. }
  117. } else {
  118. // We'll perform the state transition check here.
  119. let current_slot = self.validator.consensus.time_keeper.current_slot();
  120. let result = self.validator.add_transactions(&[tx.clone()], current_slot, false).await;
  121. if result.is_err() {
  122. error!(
  123. target: "darkfid::rpc::tx_broadcast", "Failed to validate state transition: {}",
  124. result.err().unwrap()
  125. );
  126. return server_error(RpcError::TxSimulationFail, id, None)
  127. };
  128. }
  129. self.sync_p2p.broadcast(&tx).await;
  130. if self.sync_p2p.channels().await.is_empty() {
  131. error!(target: "darkfid::rpc::tx_broadcast", "Failed broadcasting tx, no connected channels");
  132. return server_error(RpcError::TxBroadcastFail, id, None)
  133. }
  134. let tx_hash = tx.hash().unwrap().to_string();
  135. JsonResponse::new(JsonValue::String(tx_hash), id).into()
  136. }
  137. // RPCAPI:
  138. // Queries the node pending transactions store to retrieve all transactions.
  139. // Returns a vector of hex-encoded transaction hashes.
  140. //
  141. // --> {"jsonrpc": "2.0", "method": "tx.pending", "params": [], "id": 1}
  142. // <-- {"jsonrpc": "2.0", "result": "[TxHash,...]", "id": 1}
  143. pub async fn tx_pending(&self, id: u16, params: JsonValue) -> JsonResult {
  144. let params = params.get::<Vec<JsonValue>>().unwrap();
  145. if !params.is_empty() {
  146. return JsonError::new(InvalidParams, None, id).into()
  147. }
  148. if !*self.validator.synced.read().await {
  149. error!(target: "darkfid::rpc::tx_pending", "Blockchain is not synced");
  150. return server_error(RpcError::NotSynced, id, None)
  151. }
  152. let pending_txs = match self.validator.blockchain.get_pending_txs() {
  153. Ok(v) => v,
  154. Err(e) => {
  155. error!(target: "darkfid::rpc::tx_pending", "Failed fetching pending txs: {}", e);
  156. return JsonError::new(InternalError, None, id).into()
  157. }
  158. };
  159. let pending_txs: Vec<JsonValue> =
  160. pending_txs.iter().map(|x| JsonValue::String(x.hash().unwrap().to_string())).collect();
  161. JsonResponse::new(JsonValue::Array(pending_txs), id).into()
  162. }
  163. // RPCAPI:
  164. // Queries the node pending transactions store to remove all transactions.
  165. // Returns a vector of hex-encoded transaction hashes.
  166. //
  167. // --> {"jsonrpc": "2.0", "method": "tx.clean_pending", "params": [], "id": 1}
  168. // <-- {"jsonrpc": "2.0", "result": "[TxHash,...]", "id": 1}
  169. pub async fn tx_clean_pending(&self, id: u16, params: JsonValue) -> JsonResult {
  170. let params = params.get::<Vec<JsonValue>>().unwrap();
  171. if !params.is_empty() {
  172. return JsonError::new(InvalidParams, None, id).into()
  173. }
  174. if !*self.validator.synced.read().await {
  175. error!(target: "darkfid::rpc::tx_clean_pending", "Blockchain is not synced");
  176. return server_error(RpcError::NotSynced, id, None)
  177. }
  178. let pending_txs = match self.validator.blockchain.get_pending_txs() {
  179. Ok(v) => v,
  180. Err(e) => {
  181. error!(target: "darkfid::rpc::tx_clean_pending", "Failed fetching pending txs: {}", e);
  182. return JsonError::new(InternalError, None, id).into()
  183. }
  184. };
  185. if let Err(e) = self.validator.blockchain.remove_pending_txs(&pending_txs) {
  186. error!(target: "darkfid::rpc::tx_clean_pending", "Failed fetching pending txs: {}", e);
  187. return JsonError::new(InternalError, None, id).into()
  188. };
  189. let pending_txs: Vec<JsonValue> =
  190. pending_txs.iter().map(|x| JsonValue::String(x.hash().unwrap().to_string())).collect();
  191. JsonResponse::new(JsonValue::Array(pending_txs), id).into()
  192. }
  193. }