rpc.rs 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288
  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, warn};
  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: 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_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. // ==============
  127. // Invalid method
  128. // ==============
  129. _ => JsonError::new(ErrorCode::MethodNotFound, None, req.id).into(),
  130. }
  131. }
  132. async fn connections_mut(&self) -> MutexGuard<'life0, HashSet<StoppableTaskPtr>> {
  133. self.mm_rpc_connections.lock().await
  134. }
  135. }
  136. impl DarkfiNode {
  137. // RPCAPI:
  138. // Returns current system clock as `u64` (String) timestamp.
  139. //
  140. // --> {"jsonrpc": "2.0", "method": "clock", "params": [], "id": 1}
  141. // <-- {"jsonrpc": "2.0", "result": "1234", "id": 1}
  142. async fn clock(&self, id: u16, _params: JsonValue) -> JsonResult {
  143. JsonResponse::new(JsonValue::String(Timestamp::current_time().inner().to_string()), id)
  144. .into()
  145. }
  146. // RPCAPI:
  147. // Activate or deactivate dnet in the P2P stack.
  148. // By sending `true`, dnet will be activated, and by sending `false` dnet
  149. // will be deactivated. Returns `true` on success.
  150. //
  151. // --> {"jsonrpc": "2.0", "method": "dnet_switch", "params": [true], "id": 42}
  152. // <-- {"jsonrpc": "2.0", "result": true, "id": 42}
  153. async fn dnet_switch(&self, id: u16, params: JsonValue) -> JsonResult {
  154. let params = params.get::<Vec<JsonValue>>().unwrap();
  155. if params.len() != 1 || !params[0].is_bool() {
  156. return JsonError::new(ErrorCode::InvalidParams, None, id).into()
  157. }
  158. let switch = params[0].get::<bool>().unwrap();
  159. if *switch {
  160. self.p2p_handler.p2p.dnet_enable();
  161. } else {
  162. self.p2p_handler.p2p.dnet_disable();
  163. }
  164. JsonResponse::new(JsonValue::Boolean(true), id).into()
  165. }
  166. // RPCAPI:
  167. // Initializes a subscription to p2p dnet events.
  168. // Once a subscription is established, `darkfid` will send JSON-RPC notifications of
  169. // new network events to the subscriber.
  170. //
  171. // --> {"jsonrpc": "2.0", "method": "dnet.subscribe_events", "params": [], "id": 1}
  172. // <-- {"jsonrpc": "2.0", "method": "dnet.subscribe_events", "params": [`event`]}
  173. pub async fn dnet_subscribe_events(&self, id: u16, params: JsonValue) -> JsonResult {
  174. let params = params.get::<Vec<JsonValue>>().unwrap();
  175. if !params.is_empty() {
  176. return JsonError::new(ErrorCode::InvalidParams, None, id).into()
  177. }
  178. self.subscribers.get("dnet").unwrap().clone().into()
  179. }
  180. // RPCAPI:
  181. // Pings configured miner daemon for liveness.
  182. // Returns `true` on success.
  183. //
  184. // --> {"jsonrpc": "2.0", "method": "ping_miner", "params": [], "id": 1}
  185. // <-- {"jsonrpc": "2.0", "result": "true", "id": 1}
  186. async fn ping_miner(&self, id: u16, _params: JsonValue) -> JsonResult {
  187. if let Err(e) = self.ping_miner_daemon().await {
  188. error!(target: "darkfid::rpc::ping_miner", "Failed to ping miner daemon: {}", e);
  189. return server_error(RpcError::PingFailed, id, None)
  190. }
  191. JsonResponse::new(JsonValue::Boolean(true), id).into()
  192. }
  193. /// Ping configured miner daemon JSON-RPC endpoint.
  194. pub async fn ping_miner_daemon(&self) -> Result<()> {
  195. debug!(target: "darkfid::ping_miner_daemon", "Pinging miner daemon...");
  196. self.miner_daemon_request("ping", &JsonValue::Array(vec![])).await?;
  197. Ok(())
  198. }
  199. /// Auxiliary function to execute a request towards the configured miner daemon JSON-RPC endpoint.
  200. pub async fn miner_daemon_request(
  201. &self,
  202. method: &str,
  203. params: &JsonValue,
  204. ) -> Result<JsonValue> {
  205. let Some(ref rpc_client) = self.rpc_client else { return Err(Error::RpcClientStopped) };
  206. debug!(target: "darkfid::rpc::miner_daemon_request", "Executing request {} with params: {:?}", method, params);
  207. let latency = Instant::now();
  208. let req = JsonRequest::new(method, params.clone());
  209. let lock = rpc_client.lock().await;
  210. let Some(ref client) = lock.client else { return Err(Error::RpcClientStopped) };
  211. let rep = client.request(req).await?;
  212. drop(lock);
  213. let latency = latency.elapsed();
  214. debug!(target: "darkfid::rpc::miner_daemon_request", "Got reply: {:?}", rep);
  215. debug!(target: "darkfid::rpc::miner_daemon_request", "Latency: {:?}", latency);
  216. Ok(rep)
  217. }
  218. /// Auxiliary function to execute a request towards the configured miner daemon JSON-RPC endpoint,
  219. /// but in case of failure, sleep and retry until connection is re-established.
  220. pub async fn miner_daemon_request_with_retry(
  221. &self,
  222. method: &str,
  223. params: &JsonValue,
  224. ) -> JsonValue {
  225. loop {
  226. // Try to execute the request using current client
  227. match self.miner_daemon_request(method, params).await {
  228. Ok(v) => return v,
  229. Err(e) => {
  230. error!(target: "darkfid::rpc::miner_daemon_request_with_retry", "Failed to execute miner daemon request: {}", e);
  231. }
  232. }
  233. loop {
  234. // Sleep a bit before retrying
  235. info!(target: "darkfid::rpc::miner_daemon_request_with_retry", "Sleeping so we can retry later");
  236. sleep(10).await;
  237. // Create a new client
  238. let mut rpc_client = self.rpc_client.as_ref().unwrap().lock().await;
  239. let Ok(client) =
  240. RpcChadClient::new(rpc_client.endpoint.clone(), rpc_client.ex.clone()).await
  241. else {
  242. error!(target: "darkfid::rpc::miner_daemon_request_with_retry", "Failed to initialize miner daemon rpc client, check if minerd is running");
  243. drop(rpc_client);
  244. continue
  245. };
  246. info!(target: "darkfid::rpc::miner_daemon_request_with_retry", "Connection re-established!");
  247. // Set the new client as the daemon one
  248. rpc_client.client = Some(client);
  249. break;
  250. }
  251. }
  252. }
  253. }
  254. impl HandlerP2p for DarkfiNode {
  255. fn p2p(&self) -> P2pPtr {
  256. self.p2p_handler.p2p.clone()
  257. }
  258. }