rpc.rs 8.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211
  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;
  19. use async_trait::async_trait;
  20. use smol::lock::MutexGuard;
  21. use tinyjson::JsonValue;
  22. use tracing::debug;
  23. use darkfi::{
  24. net::P2pPtr,
  25. rpc::{
  26. jsonrpc::{ErrorCode, JsonError, JsonRequest, JsonResponse, JsonResult},
  27. p2p_method::HandlerP2p,
  28. server::RequestHandler,
  29. },
  30. system::StoppableTaskPtr,
  31. util::time::Timestamp,
  32. };
  33. use crate::DarkfiNode;
  34. /// Default JSON-RPC `RequestHandler`
  35. pub struct DefaultRpcHandler;
  36. /// JSON-RPC `RequestHandler` for Stratum
  37. pub struct StratumRpcHandler;
  38. /// HTTP JSON-RPC `RequestHandler` for p2pool/merge mining
  39. pub struct MmRpcHandler;
  40. #[async_trait]
  41. #[rustfmt::skip]
  42. impl RequestHandler<DefaultRpcHandler> for DarkfiNode {
  43. async fn handle_request(&self, req: JsonRequest) -> JsonResult {
  44. debug!(target: "darkfid::rpc", "--> {}", req.stringify().unwrap());
  45. match req.method.as_str() {
  46. // =====================
  47. // Miscellaneous methods
  48. // =====================
  49. "ping" => <DarkfiNode as RequestHandler<DefaultRpcHandler>>::pong(self, req.id, req.params).await,
  50. "clock" => self.clock(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. "p2p.get_info" => self.p2p_get_info(req.id, req.params).await,
  54. // ==================
  55. // Blockchain methods
  56. // ==================
  57. "blockchain.get_block" => self.blockchain_get_block(req.id, req.params).await,
  58. "blockchain.get_tx" => self.blockchain_get_tx(req.id, req.params).await,
  59. "blockchain.last_confirmed_block" => self.blockchain_last_confirmed_block(req.id, req.params).await,
  60. "blockchain.best_fork_next_block_height" => self.blockchain_best_fork_next_block_height(req.id, req.params).await,
  61. "blockchain.block_target" => self.blockchain_block_target(req.id, req.params).await,
  62. "blockchain.lookup_zkas" => self.blockchain_lookup_zkas(req.id, req.params).await,
  63. "blockchain.get_contract_state" => self.blockchain_get_contract_state(req.id, req.params).await,
  64. "blockchain.get_contract_state_key" => self.blockchain_get_contract_state_key(req.id, req.params).await,
  65. "blockchain.subscribe_blocks" => self.blockchain_subscribe_blocks(req.id, req.params).await,
  66. "blockchain.subscribe_txs" => self.blockchain_subscribe_txs(req.id, req.params).await,
  67. "blockchain.subscribe_proposals" => self.blockchain_subscribe_proposals(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_clean_pending(req.id, req.params).await,
  75. "tx.calculate_fee" => self.tx_calculate_fee(req.id, req.params).await,
  76. // =============
  77. // Miner methods
  78. // =============
  79. /*
  80. "miner.get_current_mining_randomx_key" => self.miner_get_current_mining_randomx_key(req.id, req.params).await,
  81. "miner.get_header" => self.miner_get_header(req.id, req.params).await,
  82. "miner.submit_solution" => self.miner_submit_solution(req.id, req.params).await,
  83. */
  84. // ==============
  85. // Invalid method
  86. // ==============
  87. _ => JsonError::new(ErrorCode::MethodNotFound, None, req.id).into(),
  88. }
  89. }
  90. async fn connections_mut(&self) -> MutexGuard<'life0, HashSet<StoppableTaskPtr>> {
  91. self.rpc_connections.lock().await
  92. }
  93. }
  94. #[async_trait]
  95. #[rustfmt::skip]
  96. impl RequestHandler<StratumRpcHandler> for DarkfiNode {
  97. async fn handle_request(&self, req: JsonRequest) -> JsonResult {
  98. debug!(target: "darkfid::stratum_rpc", "--> {}", req.stringify().unwrap());
  99. match req.method.as_str() {
  100. // ======================
  101. // Stratum mining methods
  102. // ======================
  103. "login" => self.stratum_login(req.id, req.params).await,
  104. "submit" => self.stratum_submit(req.id, req.params).await,
  105. "keepalived" => self.stratum_keepalived(req.id, req.params).await,
  106. _ => JsonError::new(ErrorCode::MethodNotFound, None, req.id).into(),
  107. }
  108. }
  109. async fn connections_mut(&self) -> MutexGuard<'life0, HashSet<StoppableTaskPtr>> {
  110. self.stratum_rpc_connections.lock().await
  111. }
  112. }
  113. #[async_trait]
  114. #[rustfmt::skip]
  115. impl RequestHandler<MmRpcHandler> for DarkfiNode {
  116. async fn handle_request(&self, req: JsonRequest) -> JsonResult {
  117. debug!(target: "darkfid::mm_rpc", "--> {}", req.stringify().unwrap());
  118. match req.method.as_str() {
  119. // ================================================
  120. // P2Pool methods requested for Monero Merge Mining
  121. // ================================================
  122. "merge_mining_get_chain_id" => self.xmr_merge_mining_get_chain_id(req.id, req.params).await,
  123. "merge_mining_get_aux_block" => self.xmr_merge_mining_get_aux_block(req.id, req.params).await,
  124. "merge_mining_submit_solution" => self.xmr_merge_mining_submit_solution(req.id, req.params).await,
  125. // ==============
  126. // Invalid method
  127. // ==============
  128. _ => JsonError::new(ErrorCode::MethodNotFound, None, req.id).into(),
  129. }
  130. }
  131. async fn connections_mut(&self) -> MutexGuard<'life0, HashSet<StoppableTaskPtr>> {
  132. self.mm_rpc_connections.lock().await
  133. }
  134. }
  135. impl DarkfiNode {
  136. // RPCAPI:
  137. // Returns current system clock as `u64` (String) timestamp.
  138. //
  139. // --> {"jsonrpc": "2.0", "method": "clock", "params": [], "id": 1}
  140. // <-- {"jsonrpc": "2.0", "result": "1234", "id": 1}
  141. async fn clock(&self, id: u16, _params: JsonValue) -> JsonResult {
  142. JsonResponse::new(JsonValue::String(Timestamp::current_time().inner().to_string()), id)
  143. .into()
  144. }
  145. // RPCAPI:
  146. // Activate or deactivate dnet in the P2P stack.
  147. // By sending `true`, dnet will be activated, and by sending `false` dnet
  148. // will be deactivated. Returns `true` on success.
  149. //
  150. // --> {"jsonrpc": "2.0", "method": "dnet_switch", "params": [true], "id": 42}
  151. // <-- {"jsonrpc": "2.0", "result": true, "id": 42}
  152. async fn dnet_switch(&self, id: u16, params: JsonValue) -> JsonResult {
  153. let params = params.get::<Vec<JsonValue>>().unwrap();
  154. if params.len() != 1 || !params[0].is_bool() {
  155. return JsonError::new(ErrorCode::InvalidParams, None, id).into()
  156. }
  157. let switch = params[0].get::<bool>().unwrap();
  158. if *switch {
  159. self.p2p_handler.p2p.dnet_enable();
  160. } else {
  161. self.p2p_handler.p2p.dnet_disable();
  162. }
  163. JsonResponse::new(JsonValue::Boolean(true), id).into()
  164. }
  165. // RPCAPI:
  166. // Initializes a subscription to p2p dnet events.
  167. // Once a subscription is established, `darkfid` will send JSON-RPC notifications of
  168. // new network events to the subscriber.
  169. //
  170. // --> {"jsonrpc": "2.0", "method": "dnet.subscribe_events", "params": [], "id": 1}
  171. // <-- {"jsonrpc": "2.0", "method": "dnet.subscribe_events", "params": [`event`]}
  172. pub async fn dnet_subscribe_events(&self, id: u16, params: JsonValue) -> JsonResult {
  173. let params = params.get::<Vec<JsonValue>>().unwrap();
  174. if !params.is_empty() {
  175. return JsonError::new(ErrorCode::InvalidParams, None, id).into()
  176. }
  177. self.subscribers.get("dnet").unwrap().clone().into()
  178. }
  179. }
  180. impl HandlerP2p for DarkfiNode {
  181. fn p2p(&self) -> P2pPtr {
  182. self.p2p_handler.p2p.clone()
  183. }
  184. }