rpc.rs 8.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199
  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, info};
  21. use smol::lock::MutexGuard;
  22. use tinyjson::JsonValue;
  23. use darkfi::{
  24. rpc::{
  25. client::RpcChadClient,
  26. jsonrpc::{ErrorCode, JsonError, JsonRequest, JsonResponse, JsonResult},
  27. server::RequestHandler,
  28. },
  29. system::{sleep, StoppableTaskPtr},
  30. util::time::Timestamp,
  31. Error, Result,
  32. };
  33. use crate::{
  34. error::{server_error, RpcError},
  35. Darkfid,
  36. };
  37. #[async_trait]
  38. #[rustfmt::skip]
  39. impl RequestHandler for Darkfid {
  40. async fn handle_request(&self, req: JsonRequest) -> JsonResult {
  41. debug!(target: "darkfid::rpc", "--> {}", req.stringify().unwrap());
  42. match req.method.as_str() {
  43. // =====================
  44. // Miscellaneous methods
  45. // =====================
  46. "ping" => self.pong(req.id, req.params).await,
  47. "clock" => self.clock(req.id, req.params).await,
  48. "dnet_switch" => self.dnet_switch(req.id, req.params).await,
  49. "ping_miner" => self.ping_miner(req.id, req.params).await,
  50. // ==================
  51. // Blockchain methods
  52. // ==================
  53. "blockchain.get_block" => self.blockchain_get_block(req.id, req.params).await,
  54. "blockchain.get_tx" => self.blockchain_get_tx(req.id, req.params).await,
  55. "blockchain.last_known_block" => self.blockchain_last_known_block(req.id, req.params).await,
  56. "blockchain.lookup_zkas" => self.blockchain_lookup_zkas(req.id, req.params).await,
  57. "blockchain.subscribe_blocks" => self.blockchain_subscribe_blocks(req.id, req.params).await,
  58. "blockchain.subscribe_txs" => self.blockchain_subscribe_txs(req.id, req.params).await,
  59. "blockchain.subscribe_proposals" => self.blockchain_subscribe_proposals(req.id, req.params).await,
  60. "merge_mining_get_chain_id" => self.merge_mining_get_chain_id(req.id, req.params).await,
  61. // ===================
  62. // Transaction methods
  63. // ===================
  64. "tx.simulate" => self.tx_simulate(req.id, req.params).await,
  65. "tx.broadcast" => self.tx_broadcast(req.id, req.params).await,
  66. "tx.pending" => self.tx_pending(req.id, req.params).await,
  67. "tx.clean_pending" => self.tx_pending(req.id, req.params).await,
  68. // ==============
  69. // Invalid method
  70. // ==============
  71. _ => JsonError::new(ErrorCode::MethodNotFound, None, req.id).into(),
  72. }
  73. }
  74. async fn connections_mut(&self) -> MutexGuard<'_, HashSet<StoppableTaskPtr>> {
  75. self.rpc_connections.lock().await
  76. }
  77. }
  78. impl Darkfid {
  79. // RPCAPI:
  80. // Returns current system clock as `u64` (String) timestamp.
  81. //
  82. // --> {"jsonrpc": "2.0", "method": "clock", "params": [], "id": 1}
  83. // <-- {"jsonrpc": "2.0", "result": "1234", "id": 1}
  84. async fn clock(&self, id: u16, _params: JsonValue) -> JsonResult {
  85. JsonResponse::new(JsonValue::String(Timestamp::current_time().inner().to_string()), id)
  86. .into()
  87. }
  88. // RPCAPI:
  89. // Activate or deactivate dnet in the P2P stack.
  90. // By sending `true`, dnet will be activated, and by sending `false` dnet
  91. // will be deactivated. Returns `true` on success.
  92. //
  93. // --> {"jsonrpc": "2.0", "method": "dnet_switch", "params": [true], "id": 42}
  94. // <-- {"jsonrpc": "2.0", "result": true, "id": 42}
  95. async fn dnet_switch(&self, id: u16, params: JsonValue) -> JsonResult {
  96. let params = params.get::<Vec<JsonValue>>().unwrap();
  97. if params.len() != 1 || !params[0].is_bool() {
  98. return JsonError::new(ErrorCode::InvalidParams, None, id).into()
  99. }
  100. let switch = params[0].get::<bool>().unwrap();
  101. if *switch {
  102. self.p2p.dnet_enable().await;
  103. } else {
  104. self.p2p.dnet_disable().await;
  105. }
  106. JsonResponse::new(JsonValue::Boolean(true), id).into()
  107. }
  108. // RPCAPI:
  109. // Pings configured miner daemon for liveness.
  110. // Returns `true` on success.
  111. //
  112. // --> {"jsonrpc": "2.0", "method": "ping_miner", "params": [], "id": 1}
  113. // <-- {"jsonrpc": "2.0", "result": "true", "id": 1}
  114. async fn ping_miner(&self, id: u16, _params: JsonValue) -> JsonResult {
  115. if let Err(e) = self.ping_miner_daemon().await {
  116. error!(target: "darkfid::rpc::ping_miner", "Failed to ping miner daemon: {}", e);
  117. return server_error(RpcError::PingFailed, id, None)
  118. }
  119. JsonResponse::new(JsonValue::Boolean(true), id).into()
  120. }
  121. /// Ping configured miner daemon JSON-RPC endpoint.
  122. pub async fn ping_miner_daemon(&self) -> Result<()> {
  123. debug!(target: "darkfid::ping_miner_daemon", "Pinging miner daemon...");
  124. self.miner_daemon_request("ping", &JsonValue::Array(vec![])).await?;
  125. Ok(())
  126. }
  127. /// Auxiliary function to execute a request towards the configured miner daemon JSON-RPC endpoint.
  128. pub async fn miner_daemon_request(
  129. &self,
  130. method: &str,
  131. params: &JsonValue,
  132. ) -> Result<JsonValue> {
  133. let Some(ref rpc_client) = self.rpc_client else { return Err(Error::RpcClientStopped) };
  134. debug!(target: "darkfid::rpc::miner_daemon_request", "Executing request {} with params: {:?}", method, params);
  135. let latency = Instant::now();
  136. let req = JsonRequest::new(method, params.clone());
  137. let lock = rpc_client.lock().await;
  138. let rep = lock.client.request(req).await?;
  139. drop(lock);
  140. let latency = latency.elapsed();
  141. debug!(target: "darkfid::rpc::miner_daemon_request", "Got reply: {:?}", rep);
  142. debug!(target: "darkfid::rpc::miner_daemon_request", "Latency: {:?}", latency);
  143. Ok(rep)
  144. }
  145. /// Auxiliary function to execute a request towards the configured miner daemon JSON-RPC endpoint,
  146. /// but in case of failure, sleep and retry until connection is re-established.
  147. pub async fn miner_daemon_request_with_retry(
  148. &self,
  149. method: &str,
  150. params: &JsonValue,
  151. ) -> JsonValue {
  152. loop {
  153. // Try to execute the request using current client
  154. match self.miner_daemon_request(method, params).await {
  155. Ok(v) => return v,
  156. Err(e) => {
  157. error!(target: "darkfid::rpc::miner_daemon_request_with_retry", "Failed to execute miner daemon request: {}", e);
  158. }
  159. }
  160. loop {
  161. // Sleep a bit before retrying
  162. info!(target: "darkfid::rpc::miner_daemon_request_with_retry", "Sleeping so we can retry later");
  163. sleep(10).await;
  164. // Create a new client
  165. let mut rpc_client = self.rpc_client.as_ref().unwrap().lock().await;
  166. let Ok(client) =
  167. RpcChadClient::new(rpc_client.endpoint.clone(), rpc_client.ex.clone()).await
  168. else {
  169. error!(target: "darkfid::rpc::miner_daemon_request_with_retry", "Failed to initialize miner daemon rpc client, check if minerd is running");
  170. drop(rpc_client);
  171. continue
  172. };
  173. info!(target: "darkfid::rpc::miner_daemon_request_with_retry", "Connection re-established!");
  174. // Set the new client as the daemon one
  175. rpc_client.client = client;
  176. break;
  177. }
  178. }
  179. }
  180. }