rpc.rs 11 KB

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