rpc.rs 4.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123
  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 std::{collections::HashSet, time::Instant};
  19. use async_trait::async_trait;
  20. use log::{debug, error};
  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. BlockchainExplorer,
  34. };
  35. #[async_trait]
  36. impl RequestHandler for BlockchainExplorer {
  37. async fn handle_request(&self, req: JsonRequest) -> JsonResult {
  38. debug!(target: "blockchain-explorer::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. // Transactions methods
  55. // =====================
  56. "transactions.get_transactions_by_header_hash" => {
  57. self.transactions_get_transactions_by_header_hash(req.id, req.params).await
  58. }
  59. "transactions.get_transaction_by_hash" => {
  60. self.transactions_get_transaction_by_hash(req.id, req.params).await
  61. }
  62. // =====================
  63. // Statistics methods
  64. // =====================
  65. "statistics.get_basic_statistics" => {
  66. self.statistics_get_basic_statistics(req.id, req.params).await
  67. }
  68. // TODO: add any other usefull methods
  69. // ==============
  70. // Invalid method
  71. // ==============
  72. _ => JsonError::new(ErrorCode::MethodNotFound, None, req.id).into(),
  73. }
  74. }
  75. async fn connections_mut(&self) -> MutexGuard<'_, HashSet<StoppableTaskPtr>> {
  76. self.rpc_connections.lock().await
  77. }
  78. }
  79. impl BlockchainExplorer {
  80. // RPCAPI:
  81. // Pings configured darkfid daemon for liveness.
  82. // Returns `true` on success.
  83. //
  84. // --> {"jsonrpc": "2.0", "method": "ping_darkfid", "params": [], "id": 1}
  85. // <-- {"jsonrpc": "2.0", "result": "true", "id": 1}
  86. async fn ping_darkfid(&self, id: u16, _params: JsonValue) -> JsonResult {
  87. debug!(target: "blockchain-explorer::rpc::ping_darkfid", "Pinging darkfid daemon...");
  88. if let Err(e) = self.darkfid_daemon_request("ping", &JsonValue::Array(vec![])).await {
  89. error!(target: "blockchain-explorer::rpc::ping_darkfid", "Failed to ping darkfid daemon: {}", e);
  90. return server_error(RpcError::PingFailed, id, None)
  91. }
  92. JsonResponse::new(JsonValue::Boolean(true), id).into()
  93. }
  94. /// Auxiliary function to execute a request towards the configured darkfid daemon JSON-RPC endpoint.
  95. pub async fn darkfid_daemon_request(
  96. &self,
  97. method: &str,
  98. params: &JsonValue,
  99. ) -> Result<JsonValue> {
  100. debug!(target: "blockchain-explorer::rpc::darkfid_daemon_request", "Executing request {} with params: {:?}", method, params);
  101. let latency = Instant::now();
  102. let req = JsonRequest::new(method, params.clone());
  103. let rep = self.rpc_client.request(req).await?;
  104. let latency = latency.elapsed();
  105. debug!(target: "blockchain-explorer::rpc::darkfid_daemon_request", "Got reply: {:?}", rep);
  106. debug!(target: "blockchain-explorer::rpc::darkfid_daemon_request", "Latency: {:?}", latency);
  107. Ok(rep)
  108. }
  109. }