main.rs 5.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179
  1. /* This file is part of DarkFi (https://dark.fi)
  2. *
  3. * Copyright (C) 2020-2023 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::{
  19. collections::{HashMap, HashSet},
  20. sync::Arc,
  21. };
  22. use darkfi::{
  23. async_daemonize, cli_desc,
  24. rpc::{
  25. jsonrpc::{ErrorCode, JsonError, JsonRequest, JsonResult},
  26. server::{listen_and_serve, RequestHandler},
  27. },
  28. system::{StoppableTask, StoppableTaskPtr},
  29. Error, Result,
  30. };
  31. use darkfi_serial::async_trait;
  32. use log::{error, info};
  33. use serde::Deserialize;
  34. use smol::{
  35. lock::{Mutex, MutexGuard, RwLock},
  36. net::TcpStream,
  37. stream::StreamExt,
  38. Executor,
  39. };
  40. use structopt::StructOpt;
  41. use structopt_toml::StructOptToml;
  42. use url::Url;
  43. use uuid::Uuid;
  44. mod error;
  45. mod stratum;
  46. const CONFIG_FILE: &str = "darkfi_mmproxy.toml";
  47. const CONFIG_FILE_CONTENTS: &str = include_str!("../darkfi_mmproxy.toml");
  48. #[derive(Clone, Debug, Deserialize, StructOpt, StructOptToml)]
  49. #[serde(default)]
  50. #[structopt(name = "darkfi-mmproxy", about = cli_desc!())]
  51. struct Args {
  52. #[structopt(short, parse(from_occurrences))]
  53. /// Increase verbosity (-vvv supported)
  54. verbose: u8,
  55. #[structopt(short, long)]
  56. /// Configuration file to use
  57. config: Option<String>,
  58. #[structopt(long, default_value = "tcp://127.0.0.1:3333")]
  59. /// mmproxy JSON-RPC server listen URL
  60. rpc_listen: Url,
  61. #[structopt(long)]
  62. /// List of worker logins
  63. workers: Vec<String>,
  64. #[structopt(long)]
  65. /// Set log file output
  66. log: Option<String>,
  67. #[structopt(flatten)]
  68. monerod: MonerodArgs,
  69. }
  70. #[derive(Clone, Debug, Deserialize, StructOpt, StructOptToml)]
  71. #[structopt()]
  72. struct MonerodArgs {
  73. #[structopt(long, default_value = "mainnet")]
  74. /// Mining reward wallet address
  75. network: String,
  76. #[structopt(long, default_value = "http://127.0.0.1:28081/json_rpc")]
  77. /// monerod JSON-RPC server listen URL
  78. rpc: Url,
  79. }
  80. struct MiningProxy {
  81. /// monerod network type
  82. monerod_network: monero::Network,
  83. /// monerod RPC address
  84. monerod_rpc: Url,
  85. /// Workers UUIDs
  86. workers: Arc<RwLock<HashMap<Uuid, stratum::Worker>>>,
  87. /// JSON-RPC connection tracker
  88. rpc_connections: Mutex<HashSet<StoppableTaskPtr>>,
  89. /// Main async executor reference
  90. executor: Arc<Executor<'static>>,
  91. }
  92. impl MiningProxy {
  93. async fn new(monerod: MonerodArgs, executor: Arc<Executor<'static>>) -> Result<Self> {
  94. let monerod_network = match monerod.network.as_str() {
  95. "mainnet" => monero::Network::Mainnet,
  96. "testnet" => monero::Network::Testnet,
  97. _ => {
  98. error!("Invalid Monero network \"{}\"", monerod.network);
  99. return Err(Error::Custom("Invalid Monero network".to_string()))
  100. }
  101. };
  102. // Test that monerod RPC is reachable
  103. if let Err(e) = TcpStream::connect(monerod.rpc.socket_addrs(|| None)?[0]).await {
  104. error!("Failed connecting to monerod RPC: {}", e);
  105. return Err(e.into())
  106. }
  107. let workers = Arc::new(RwLock::new(HashMap::new()));
  108. let rpc_connections = Mutex::new(HashSet::new());
  109. Ok(Self { monerod_network, monerod_rpc: monerod.rpc, workers, rpc_connections, executor })
  110. }
  111. }
  112. #[async_trait]
  113. #[rustfmt::skip]
  114. impl RequestHandler for MiningProxy {
  115. async fn handle_request(&self, req: JsonRequest) -> JsonResult {
  116. match req.method.as_str() {
  117. "ping" => self.pong(req.id, req.params).await,
  118. // Stratum methods
  119. "login" => self.stratum_login(req.id, req.params).await,
  120. "submit" => self.stratum_submit(req.id, req.params).await,
  121. "keepalived" => self.stratum_keepalived(req.id, req.params).await,
  122. _ => JsonError::new(ErrorCode::MethodNotFound, None, req.id).into(),
  123. }
  124. }
  125. async fn connections_mut(&self) -> MutexGuard<'_, HashSet<StoppableTaskPtr>> {
  126. self.rpc_connections.lock().await
  127. }
  128. }
  129. async_daemonize!(realmain);
  130. async fn realmain(args: Args, ex: Arc<Executor<'static>>) -> Result<()> {
  131. info!("Starting DarkFi x Monero merge mining proxy...");
  132. let mmproxy = Arc::new(MiningProxy::new(args.monerod, ex.clone()).await?);
  133. info!("Starting JSON-RPC server");
  134. let rpc_task = StoppableTask::new();
  135. rpc_task.clone().start(
  136. listen_and_serve(args.rpc_listen, mmproxy.clone(), None, ex.clone()),
  137. |res| async move {
  138. match res {
  139. Ok(()) | Err(Error::RpcServerStopped) => mmproxy.stop_connections().await,
  140. Err(e) => error!("Failed stopping JSON-RPC server: {}", e),
  141. }
  142. },
  143. Error::RpcServerStopped,
  144. ex.clone(),
  145. );
  146. info!("Merge mining proxy ready, waiting for connections...");
  147. // Signal handling for graceful termination.
  148. let (signals_handler, signals_task) = SignalHandler::new(ex)?;
  149. signals_handler.wait_termination(signals_task).await?;
  150. info!("Caught termination signal, cleaning up and exiting...");
  151. Ok(())
  152. }