rpc.rs 5.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129
  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, serialize};
  35. use crate::{
  36. error::{server_error, RpcError},
  37. Minerd,
  38. };
  39. #[async_trait]
  40. impl RequestHandler for Minerd {
  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. "mine" => self.mine(req.id, req.params).await,
  46. _ => JsonError::new(ErrorCode::MethodNotFound, None, req.id).into(),
  47. }
  48. }
  49. async fn connections_mut(&self) -> MutexGuard<'_, HashSet<StoppableTaskPtr>> {
  50. self.rpc_connections.lock().await
  51. }
  52. }
  53. impl Minerd {
  54. // RPCAPI:
  55. // Mine provided block for requested mine target, and return the corresponding nonce value.
  56. //
  57. // --> {"jsonrpc": "2.0", "method": "mine", "params": ["target", "block"], "id": 42}
  58. // --> {"jsonrpc": "2.0", "result": "nonce", "id": 42}
  59. async fn mine(&self, id: u16, params: JsonValue) -> JsonResult {
  60. // Verify parameters
  61. if !params.is_array() {
  62. return JsonError::new(ErrorCode::InvalidParams, None, id).into()
  63. }
  64. let params = params.get::<Vec<JsonValue>>().unwrap();
  65. if params.len() != 2 || !params[0].is_string() || !params[1].is_string() {
  66. return JsonError::new(ErrorCode::InvalidParams, None, id).into()
  67. }
  68. // Parse parameters
  69. let Ok(target) = BigUint::from_str_radix(params[0].get::<String>().unwrap(), 10) else {
  70. error!(target: "minerd::rpc", "Failed to parse target");
  71. return server_error(RpcError::TargetParseError, id, None)
  72. };
  73. let Some(block_bytes) = base64::decode(params[1].get::<String>().unwrap()) else {
  74. error!(target: "minerd::rpc", "Failed to parse block bytes");
  75. return server_error(RpcError::BlockParseError, id, None)
  76. };
  77. let Ok(mut block) = deserialize::<BlockInfo>(&block_bytes) else {
  78. error!(target: "minerd::rpc", "Failed to parse block");
  79. return server_error(RpcError::BlockParseError, id, None)
  80. };
  81. // Check if another request is being processed
  82. if self.stop_signal.receiver_count() > 1 {
  83. info!(target: "minerd::rpc", "Another request is in progress, sending stop signal...");
  84. // Send stop signal to other worker
  85. if self.sender.send(()).await.is_err() {
  86. error!(target: "minerd::rpc", "Failed to stop previous request");
  87. return server_error(RpcError::StopFailed, id, None)
  88. }
  89. // Wait for other worker to terminate
  90. info!(target: "minerd::rpc", "Waiting for request to terminate...");
  91. while self.stop_signal.receiver_count() > 1 {
  92. sleep(1).await;
  93. }
  94. info!(target: "minerd::rpc", "Previous request terminated!");
  95. // Consume channel item so its empty again
  96. if self.stop_signal.recv().await.is_err() {
  97. error!(target: "minerd::rpc", "Failed to cleanup stop signal channel");
  98. return server_error(RpcError::StopFailed, id, None)
  99. }
  100. }
  101. // Mine provided block
  102. let Ok(block_hash) = block.hash() else {
  103. error!(target: "minerd::rpc", "Failed to hash block");
  104. return server_error(RpcError::HashingFailed, id, None)
  105. };
  106. info!(target: "minerd::rpc", "Mining block {} for target: {}", block_hash, target);
  107. if let Err(e) = mine_block(&target, &mut block, self.threads, &self.stop_signal.clone()) {
  108. error!(target: "minerd::rpc", "Failed mining block {} with error: {}", block_hash, e);
  109. return server_error(RpcError::MiningFailed, id, None)
  110. }
  111. // Return block nonce
  112. let nonce = base64::encode(&serialize(&block.header.nonce));
  113. JsonResponse::new(JsonValue::String(nonce), id).into()
  114. }
  115. }