rpc.rs 9.5 KB

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