rpc.rs 7.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185
  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` type
  35. pub struct DefaultRpcHandler;
  36. /// HTTP JSON-RPC `RequestHandler` type for p2pool
  37. pub struct MmRpcHandler;
  38. #[async_trait]
  39. #[rustfmt::skip]
  40. impl RequestHandler<DefaultRpcHandler> for DarkfiNode {
  41. async fn handle_request(&self, req: JsonRequest) -> JsonResult {
  42. debug!(target: "darkfid::rpc", "--> {}", req.stringify().unwrap());
  43. match req.method.as_str() {
  44. // =====================
  45. // Miscellaneous methods
  46. // =====================
  47. "ping" => <DarkfiNode as RequestHandler<DefaultRpcHandler>>::pong(self, req.id, req.params).await,
  48. "clock" => self.clock(req.id, req.params).await,
  49. "dnet.switch" => self.dnet_switch(req.id, req.params).await,
  50. "dnet.subscribe_events" => self.dnet_subscribe_events(req.id, req.params).await,
  51. "p2p.get_info" => self.p2p_get_info(req.id, req.params).await,
  52. // ==================
  53. // Blockchain methods
  54. // ==================
  55. "blockchain.get_block" => self.blockchain_get_block(req.id, req.params).await,
  56. "blockchain.get_tx" => self.blockchain_get_tx(req.id, req.params).await,
  57. "blockchain.last_confirmed_block" => self.blockchain_last_confirmed_block(req.id, req.params).await,
  58. "blockchain.best_fork_next_block_height" => self.blockchain_best_fork_next_block_height(req.id, req.params).await,
  59. "blockchain.block_target" => self.blockchain_block_target(req.id, req.params).await,
  60. "blockchain.lookup_zkas" => self.blockchain_lookup_zkas(req.id, req.params).await,
  61. "blockchain.get_contract_state" => self.blockchain_get_contract_state(req.id, req.params).await,
  62. "blockchain.get_contract_state_key" => self.blockchain_get_contract_state_key(req.id, req.params).await,
  63. "blockchain.subscribe_blocks" => self.blockchain_subscribe_blocks(req.id, req.params).await,
  64. "blockchain.subscribe_txs" => self.blockchain_subscribe_txs(req.id, req.params).await,
  65. "blockchain.subscribe_proposals" => self.blockchain_subscribe_proposals(req.id, req.params).await,
  66. // ===================
  67. // Transaction methods
  68. // ===================
  69. "tx.simulate" => self.tx_simulate(req.id, req.params).await,
  70. "tx.broadcast" => self.tx_broadcast(req.id, req.params).await,
  71. "tx.pending" => self.tx_pending(req.id, req.params).await,
  72. "tx.clean_pending" => self.tx_clean_pending(req.id, req.params).await,
  73. "tx.calculate_fee" => self.tx_calculate_fee(req.id, req.params).await,
  74. // =============
  75. // Miner methods
  76. // =============
  77. "miner.get_current_randomx_keys" => self.miner_get_current_randomx_keys(req.id, req.params).await,
  78. "miner.get_header" => self.miner_get_header(req.id, req.params).await,
  79. "miner.submit_solution" => self.miner_submit_solution(req.id, req.params).await,
  80. // ==============
  81. // Invalid method
  82. // ==============
  83. _ => JsonError::new(ErrorCode::MethodNotFound, None, req.id).into(),
  84. }
  85. }
  86. async fn connections_mut(&self) -> MutexGuard<'life0, HashSet<StoppableTaskPtr>> {
  87. self.rpc_connections.lock().await
  88. }
  89. }
  90. #[async_trait]
  91. #[rustfmt::skip]
  92. impl RequestHandler<MmRpcHandler> for DarkfiNode {
  93. async fn handle_request(&self, req: JsonRequest) -> JsonResult {
  94. debug!(target: "darkfid::mm_rpc", "--> {}", req.stringify().unwrap());
  95. match req.method.as_str() {
  96. // ================================================
  97. // P2Pool methods requested for Monero Merge Mining
  98. // ================================================
  99. "merge_mining_get_chain_id" => self.xmr_merge_mining_get_chain_id(req.id, req.params).await,
  100. "merge_mining_get_aux_block" => self.xmr_merge_mining_get_aux_block(req.id, req.params).await,
  101. "merge_mining_submit_solution" => self.xmr_merge_mining_submit_solution(req.id, req.params).await,
  102. // ==============
  103. // Invalid method
  104. // ==============
  105. _ => JsonError::new(ErrorCode::MethodNotFound, None, req.id).into(),
  106. }
  107. }
  108. async fn connections_mut(&self) -> MutexGuard<'life0, HashSet<StoppableTaskPtr>> {
  109. self.mm_rpc_connections.lock().await
  110. }
  111. }
  112. impl DarkfiNode {
  113. // RPCAPI:
  114. // Returns current system clock as `u64` (String) timestamp.
  115. //
  116. // --> {"jsonrpc": "2.0", "method": "clock", "params": [], "id": 1}
  117. // <-- {"jsonrpc": "2.0", "result": "1234", "id": 1}
  118. async fn clock(&self, id: u16, _params: JsonValue) -> JsonResult {
  119. JsonResponse::new(JsonValue::String(Timestamp::current_time().inner().to_string()), id)
  120. .into()
  121. }
  122. // RPCAPI:
  123. // Activate or deactivate dnet in the P2P stack.
  124. // By sending `true`, dnet will be activated, and by sending `false` dnet
  125. // will be deactivated. Returns `true` on success.
  126. //
  127. // --> {"jsonrpc": "2.0", "method": "dnet_switch", "params": [true], "id": 42}
  128. // <-- {"jsonrpc": "2.0", "result": true, "id": 42}
  129. async fn dnet_switch(&self, id: u16, params: JsonValue) -> JsonResult {
  130. let params = params.get::<Vec<JsonValue>>().unwrap();
  131. if params.len() != 1 || !params[0].is_bool() {
  132. return JsonError::new(ErrorCode::InvalidParams, None, id).into()
  133. }
  134. let switch = params[0].get::<bool>().unwrap();
  135. if *switch {
  136. self.p2p_handler.p2p.dnet_enable();
  137. } else {
  138. self.p2p_handler.p2p.dnet_disable();
  139. }
  140. JsonResponse::new(JsonValue::Boolean(true), id).into()
  141. }
  142. // RPCAPI:
  143. // Initializes a subscription to p2p dnet events.
  144. // Once a subscription is established, `darkfid` will send JSON-RPC notifications of
  145. // new network events to the subscriber.
  146. //
  147. // --> {"jsonrpc": "2.0", "method": "dnet.subscribe_events", "params": [], "id": 1}
  148. // <-- {"jsonrpc": "2.0", "method": "dnet.subscribe_events", "params": [`event`]}
  149. pub async fn dnet_subscribe_events(&self, id: u16, params: JsonValue) -> JsonResult {
  150. let params = params.get::<Vec<JsonValue>>().unwrap();
  151. if !params.is_empty() {
  152. return JsonError::new(ErrorCode::InvalidParams, None, id).into()
  153. }
  154. self.subscribers.get("dnet").unwrap().clone().into()
  155. }
  156. }
  157. impl HandlerP2p for DarkfiNode {
  158. fn p2p(&self) -> P2pPtr {
  159. self.p2p_handler.p2p.clone()
  160. }
  161. }