rpc.rs 12 KB

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