rpc.rs 6.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154
  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;
  19. use log::{debug, error, info};
  20. use num_bigint::BigUint;
  21. use smol::lock::MutexGuard;
  22. use darkfi::{
  23. blockchain::BlockInfo,
  24. rpc::{
  25. jsonrpc::{ErrorCode, JsonError, JsonRequest, JsonResponse, JsonResult},
  26. server::RequestHandler,
  27. util::JsonValue,
  28. },
  29. system::{sleep, StoppableTaskPtr},
  30. util::encoding::base64,
  31. validator::pow::mine_block,
  32. };
  33. use darkfi_sdk::num_traits::Num;
  34. use darkfi_serial::{async_trait, deserialize_async};
  35. use crate::{
  36. error::{server_error, RpcError},
  37. MinerNode,
  38. };
  39. #[async_trait]
  40. impl RequestHandler for MinerNode {
  41. async fn handle_request(&self, req: JsonRequest) -> JsonResult {
  42. debug!(target: "minerd::rpc", "--> {}", req.stringify().unwrap());
  43. match req.method.as_str() {
  44. "ping" => self.pong(req.id, req.params).await,
  45. "abort" => self.abort(req.id, req.params).await,
  46. "mine" => self.mine(req.id, req.params).await,
  47. _ => JsonError::new(ErrorCode::MethodNotFound, None, req.id).into(),
  48. }
  49. }
  50. async fn connections_mut(&self) -> MutexGuard<'life0, HashSet<StoppableTaskPtr>> {
  51. self.rpc_connections.lock().await
  52. }
  53. }
  54. impl MinerNode {
  55. // RPCAPI:
  56. // Signals miner daemon to abort mining pending request.
  57. // Returns `true` on success.
  58. //
  59. // --> {"jsonrpc": "2.0", "method": "abort", "params": [], "id": 42}
  60. // <-- {"jsonrpc": "2.0", "result": "true", "id": 42}
  61. async fn abort(&self, id: u16, _params: JsonValue) -> JsonResult {
  62. if let Some(e) = self.abort_pending(id).await {
  63. return e
  64. };
  65. JsonResponse::new(JsonValue::Boolean(true), id).into()
  66. }
  67. // RPCAPI:
  68. // Mine provided block for requested mine target, and return the corresponding nonce value.
  69. //
  70. // --> {"jsonrpc": "2.0", "method": "mine", "params": ["target", "block"], "id": 42}
  71. // --> {"jsonrpc": "2.0", "result": "nonce", "id": 42}
  72. async fn mine(&self, id: u16, params: JsonValue) -> JsonResult {
  73. // Verify parameters
  74. if !params.is_array() {
  75. return JsonError::new(ErrorCode::InvalidParams, None, id).into()
  76. }
  77. let params = params.get::<Vec<JsonValue>>().unwrap();
  78. if params.len() != 2 || !params[0].is_string() || !params[1].is_string() {
  79. return JsonError::new(ErrorCode::InvalidParams, None, id).into()
  80. }
  81. // Parse parameters
  82. let Ok(target) = BigUint::from_str_radix(params[0].get::<String>().unwrap(), 10) else {
  83. error!(target: "minerd::rpc", "Failed to parse target");
  84. return server_error(RpcError::TargetParseError, id, None)
  85. };
  86. let Some(block_bytes) = base64::decode(params[1].get::<String>().unwrap()) else {
  87. error!(target: "minerd::rpc", "Failed to parse block bytes");
  88. return server_error(RpcError::BlockParseError, id, None)
  89. };
  90. let Ok(mut block) = deserialize_async::<BlockInfo>(&block_bytes).await else {
  91. error!(target: "minerd::rpc", "Failed to parse block");
  92. return server_error(RpcError::BlockParseError, id, None)
  93. };
  94. let block_hash = block.hash();
  95. info!(target: "minerd::rpc", "Received request to mine block {} for target: {}", block_hash, target);
  96. // Check if another request is being processed
  97. if let Some(e) = self.abort_pending(id).await {
  98. return e
  99. };
  100. // Mine provided block
  101. info!(target: "minerd::rpc", "Mining block {} for target: {}", block_hash, target);
  102. if let Err(e) = mine_block(&target, &mut block, self.threads, &self.stop_signal.clone()) {
  103. error!(target: "minerd::rpc", "Failed mining block {} with error: {}", block_hash, e);
  104. return server_error(RpcError::MiningFailed, id, None)
  105. }
  106. // Return block nonce
  107. JsonResponse::new(JsonValue::Number(block.header.nonce as f64), id).into()
  108. }
  109. /// Auxiliary function to abort pending request.
  110. async fn abort_pending(&self, id: u16) -> Option<JsonResult> {
  111. // Check if a pending request is being processed
  112. info!(target: "minerd::rpc", "Checking if a pending request is being processed...");
  113. if self.stop_signal.receiver_count() == 0 {
  114. info!(target: "minerd::rpc", "No pending requests!");
  115. return None
  116. }
  117. info!(target: "minerd::rpc", "Pending request is in progress, sending stop signal...");
  118. // Send stop signal to worker
  119. if self.sender.send(()).await.is_err() {
  120. error!(target: "minerd::rpc", "Failed to stop pending request");
  121. return Some(server_error(RpcError::StopFailed, id, None))
  122. }
  123. // Wait for worker to terminate
  124. info!(target: "minerd::rpc", "Waiting for request to terminate...");
  125. while self.stop_signal.receiver_count() > 1 {
  126. sleep(1).await;
  127. }
  128. info!(target: "minerd::rpc", "Pending request terminated!");
  129. // Consume channel item so its empty again
  130. if self.stop_signal.recv().await.is_err() {
  131. error!(target: "minerd::rpc", "Failed to cleanup stop signal channel");
  132. return Some(server_error(RpcError::StopFailed, id, None))
  133. }
  134. None
  135. }
  136. }