rpc.rs 5.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139
  1. /* This file is part of DarkFi (https://dark.fi)
  2. *
  3. * Copyright (C) 2020-2025 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 std::{collections::HashSet, time::Instant};
  19. use async_trait::async_trait;
  20. use log::{debug, error, trace};
  21. use smol::lock::MutexGuard;
  22. use tinyjson::JsonValue;
  23. use darkfi::{
  24. rpc::{
  25. jsonrpc::{ErrorCode, JsonError, JsonRequest, JsonResponse, JsonResult},
  26. server::RequestHandler,
  27. },
  28. system::StoppableTaskPtr,
  29. Result,
  30. };
  31. use crate::{
  32. error::{server_error, RpcError},
  33. Explorerd,
  34. };
  35. #[async_trait]
  36. impl RequestHandler<()> for Explorerd {
  37. async fn handle_request(&self, req: JsonRequest) -> JsonResult {
  38. debug!(target: "explorerd::rpc", "--> {}", req.stringify().unwrap());
  39. match req.method.as_str() {
  40. // =====================
  41. // Miscellaneous methods
  42. // =====================
  43. "ping" => self.pong(req.id, req.params).await,
  44. "ping_darkfid" => self.ping_darkfid(req.id, req.params).await,
  45. // =====================
  46. // Blocks methods
  47. // =====================
  48. "blocks.get_last_n_blocks" => self.blocks_get_last_n_blocks(req.id, req.params).await,
  49. "blocks.get_blocks_in_heights_range" => {
  50. self.blocks_get_blocks_in_heights_range(req.id, req.params).await
  51. }
  52. "blocks.get_block_by_hash" => self.blocks_get_block_by_hash(req.id, req.params).await,
  53. // =====================
  54. // Contract methods
  55. // =====================
  56. "contracts.get_native_contracts" => {
  57. self.contracts_get_native_contracts(req.id, req.params).await
  58. }
  59. "contracts.get_contract_source_code_paths" => {
  60. self.contracts_get_contract_source_code_paths(req.id, req.params).await
  61. }
  62. "contracts.get_contract_source" => {
  63. self.contracts_get_contract_source(req.id, req.params).await
  64. }
  65. // =====================
  66. // Transactions methods
  67. // =====================
  68. "transactions.get_transactions_by_header_hash" => {
  69. self.transactions_get_transactions_by_header_hash(req.id, req.params).await
  70. }
  71. "transactions.get_transaction_by_hash" => {
  72. self.transactions_get_transaction_by_hash(req.id, req.params).await
  73. }
  74. // =====================
  75. // Statistics methods
  76. // =====================
  77. "statistics.get_basic_statistics" => {
  78. self.statistics_get_basic_statistics(req.id, req.params).await
  79. }
  80. "statistics.get_metric_statistics" => {
  81. self.statistics_get_metric_statistics(req.id, req.params).await
  82. }
  83. // TODO: add any other useful methods
  84. // ==============
  85. // Invalid method
  86. // ==============
  87. _ => JsonError::new(ErrorCode::MethodNotFound, None, req.id).into(),
  88. }
  89. }
  90. async fn connections_mut(&self) -> MutexGuard<'_, HashSet<StoppableTaskPtr>> {
  91. self.rpc_connections.lock().await
  92. }
  93. }
  94. impl Explorerd {
  95. // RPCAPI:
  96. // Pings configured darkfid daemon for liveness.
  97. // Returns `true` on success.
  98. //
  99. // --> {"jsonrpc": "2.0", "method": "ping_darkfid", "params": [], "id": 1}
  100. // <-- {"jsonrpc": "2.0", "result": "true", "id": 1}
  101. async fn ping_darkfid(&self, id: u16, _params: JsonValue) -> JsonResult {
  102. debug!(target: "explorerd::rpc::ping_darkfid", "Pinging darkfid daemon...");
  103. if let Err(e) = self.darkfid_daemon_request("ping", &JsonValue::Array(vec![])).await {
  104. error!(target: "explorerd::rpc::ping_darkfid", "Failed to ping darkfid daemon: {}", e);
  105. return server_error(RpcError::PingFailed, id, None)
  106. }
  107. JsonResponse::new(JsonValue::Boolean(true), id).into()
  108. }
  109. /// Auxiliary function to execute a request towards the configured darkfid daemon JSON-RPC endpoint.
  110. pub async fn darkfid_daemon_request(
  111. &self,
  112. method: &str,
  113. params: &JsonValue,
  114. ) -> Result<JsonValue> {
  115. debug!(target: "explorerd::rpc::darkfid_daemon_request", "Executing request {} with params: {:?}", method, params);
  116. let latency = Instant::now();
  117. let req = JsonRequest::new(method, params.clone());
  118. let rep = self.rpc_client.request(req).await?;
  119. let latency = latency.elapsed();
  120. trace!(target: "explorerd::rpc::darkfid_daemon_request", "Got reply: {:?}", rep);
  121. debug!(target: "explorerd::rpc::darkfid_daemon_request", "Latency: {:?}", latency);
  122. Ok(rep)
  123. }
  124. }