rpc_tx.rs 9.1 KB

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