rpc_tx.rs 6.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166
  1. use std::str::FromStr;
  2. use log::{error, warn};
  3. use serde_json::{json, Value};
  4. use darkfi::{
  5. consensus::ValidatorState,
  6. crypto::{address::Address, keypair::PublicKey, token_id},
  7. node::MemoryState,
  8. rpc::jsonrpc::{ErrorCode::InvalidParams, JsonError, JsonResponse, JsonResult},
  9. tx::Transaction,
  10. util::serial::{deserialize, serialize},
  11. };
  12. use super::Darkfid;
  13. use crate::{server_error, RpcError};
  14. impl Darkfid {
  15. // RPCAPI:
  16. // Transfer a given amount of some token to the given address.
  17. // Returns a transaction ID upon success.
  18. //
  19. // * `dest_addr` -> Recipient's DarkFi address
  20. // * `token_id` -> ID of the token to send
  21. // * `12345` -> Amount in `u64` of the funds to send
  22. //
  23. // --> {"jsonrpc": "2.0", "method": "tx.transfer", "params": ["dest_addr", "token_id", 12345], "id": 1}
  24. // <-- {"jsonrpc": "2.0", "result": "txID...", "id": 1}
  25. pub async fn tx_transfer(&self, id: Value, params: &[Value]) -> JsonResult {
  26. if params.len() != 3 ||
  27. !params[0].is_string() ||
  28. !params[1].is_string() ||
  29. !params[2].is_u64()
  30. {
  31. return JsonError::new(InvalidParams, None, id).into()
  32. }
  33. if !(*self.synced.lock().await) {
  34. error!("[RPC] tx.transfer: Blockchain is not synced");
  35. return server_error(RpcError::NotSynced, id, None)
  36. }
  37. let address = params[0].as_str().unwrap();
  38. let token = params[1].as_str().unwrap();
  39. let amount = params[2].as_u64().unwrap();
  40. let address = match Address::from_str(address) {
  41. Ok(v) => v,
  42. Err(e) => {
  43. error!("[RPC] tx.transfer: Failed parsing address from string: {}", e);
  44. return server_error(RpcError::InvalidAddressParam, id, None)
  45. }
  46. };
  47. let pubkey = match PublicKey::try_from(address) {
  48. Ok(v) => v,
  49. Err(e) => {
  50. error!("[RPC] tx.transfer: Failed parsing PublicKey from Address: {}", e);
  51. return server_error(RpcError::ParseError, id, None)
  52. }
  53. };
  54. let token_id = match token_id::parse_b58(token) {
  55. Ok(v) => v,
  56. Err(e) => {
  57. error!("[RPC] tx.transfer: Failed parsing Token ID from string: {}", e);
  58. return server_error(RpcError::ParseError, id, None)
  59. }
  60. };
  61. let tx = match self
  62. .client
  63. .build_transaction(
  64. pubkey,
  65. amount,
  66. token_id,
  67. false,
  68. self.validator_state.read().await.state_machine.clone(),
  69. )
  70. .await
  71. {
  72. Ok(v) => v,
  73. Err(e) => {
  74. error!("tx.transfer: Failed building transaction: {}", e);
  75. return server_error(RpcError::TxBuildFail, id, None)
  76. }
  77. };
  78. if let Some(sync_p2p) = &self.sync_p2p {
  79. if let Err(e) = sync_p2p.broadcast(tx.clone()).await {
  80. error!("[RPC] tx.transfer: Failed broadcasting transaction: {}", e);
  81. return server_error(RpcError::TxBroadcastFail, id, None)
  82. }
  83. } else {
  84. warn!("[RPC] tx.transfer: No sync P2P network, not broadcasting transaction.");
  85. return server_error(RpcError::TxBroadcastFail, id, None)
  86. }
  87. let tx_hash = blake3::hash(&serialize(&tx)).to_hex().as_str().to_string();
  88. JsonResponse::new(json!(tx_hash), id).into()
  89. }
  90. // RPCAPI:
  91. // Broadcast a given transaction to the P2P network.
  92. // The function will first simulate the state transition in order to see
  93. // if the transaction is actually valid, and in turn it will return an
  94. // error if this is the case. Otherwise, a transaction ID will be returned.
  95. //
  96. // --> {"jsonrpc": "2.0", "method": "tx.broadcast", "params": ["base58encodedTX"], "id": 1}
  97. // <-- {"jsonrpc": "2.0", "result": "txID...", "id": 1}
  98. pub async fn tx_broadcast(&self, id: Value, params: &[Value]) -> JsonResult {
  99. if params.len() != 1 || !params[0].is_string() {
  100. return JsonError::new(InvalidParams, None, id).into()
  101. }
  102. if !(*self.synced.lock().await) {
  103. error!("[RPC] tx.transfer: Blockchain is not synced");
  104. return server_error(RpcError::NotSynced, id, None)
  105. }
  106. // Try to deserialize the transaction
  107. let tx_bytes = match bs58::decode(params[0].as_str().unwrap().trim()).into_vec() {
  108. Ok(v) => v,
  109. Err(e) => {
  110. error!("[RPC] tx.broadcast: Failed decoding base58 transaction: {}", e);
  111. return server_error(RpcError::ParseError, id, None)
  112. }
  113. };
  114. let tx: Transaction = match deserialize(&tx_bytes) {
  115. Ok(v) => v,
  116. Err(e) => {
  117. error!("[RPC] tx.broadcast: Failed deserializing bytes into Transaction: {}", e);
  118. return server_error(RpcError::ParseError, id, None)
  119. }
  120. };
  121. // Grab the current state and apply a new MemoryState
  122. let validator_state = self.validator_state.read().await;
  123. let state = validator_state.state_machine.lock().await;
  124. let mem_state = MemoryState::new(state.clone());
  125. drop(state);
  126. drop(validator_state);
  127. // Simulate state transition
  128. if let Err(e) = ValidatorState::validate_state_transitions(mem_state, &[tx.clone()]) {
  129. error!("[RPC] tx.broadcast: Failed to validate state transition: {}", e);
  130. return server_error(RpcError::TxSimulationFail, id, None)
  131. }
  132. if let Some(sync_p2p) = &self.sync_p2p {
  133. if let Err(e) = sync_p2p.broadcast(tx.clone()).await {
  134. error!("[RPC] tx.broadcast: Failed broadcasting transaction: {}", e);
  135. return server_error(RpcError::TxBroadcastFail, id, None)
  136. }
  137. // TODO: Mark coin as spent in the wallet
  138. } else {
  139. warn!("[RPC] tx.broadcast: No sync P2P network, not broadcasting transaction.");
  140. return server_error(RpcError::TxBroadcastFail, id, None)
  141. }
  142. let tx_hash = blake3::hash(&serialize(&tx)).to_hex().as_str().to_string();
  143. JsonResponse::new(json!(tx_hash), id).into()
  144. }
  145. }