rpc.rs 11 KB

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