main.rs 6.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178
  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::sync::Arc;
  19. use darkfi::{async_daemonize, cli_desc, rpc::util::JsonValue, Error, Result};
  20. use log::{debug, error, info};
  21. use serde::Deserialize;
  22. use smol::{net::TcpStream, stream::StreamExt, Executor};
  23. use structopt::StructOpt;
  24. use structopt_toml::StructOptToml;
  25. use surf::StatusCode;
  26. use url::Url;
  27. const CONFIG_FILE: &str = "darkfi_mmproxy.toml";
  28. const CONFIG_FILE_CONTENTS: &str = include_str!("../darkfi_mmproxy.toml");
  29. /// Monero RPC functions
  30. mod monerod;
  31. #[derive(Clone, Debug, Deserialize, StructOpt, StructOptToml)]
  32. #[serde(default)]
  33. #[structopt(name = "darkfi-mmproxy", about = cli_desc!())]
  34. struct Args {
  35. #[structopt(short, parse(from_occurrences))]
  36. /// Increase verbosity (-vvv supported)
  37. verbose: u8,
  38. #[structopt(short, long)]
  39. /// Configuration file to use
  40. config: Option<String>,
  41. #[structopt(long, default_value = "http://127.0.0.1:3333")]
  42. // mmproxy daemon listen URL
  43. listen: Url,
  44. #[structopt(long)]
  45. /// Set log file output
  46. log: Option<String>,
  47. #[structopt(flatten)]
  48. monerod: MonerodArgs,
  49. }
  50. #[derive(Clone, Debug, Deserialize, StructOpt, StructOptToml)]
  51. #[structopt()]
  52. struct MonerodArgs {
  53. #[structopt(long, default_value = "mainnet")]
  54. /// Monero network type (mainnet/testnet)
  55. network: String,
  56. #[structopt(long, default_value = "http://127.0.0.1:18081")]
  57. /// monerod JSON-RPC server listen URL
  58. rpc: Url,
  59. }
  60. /// Mining proxy state
  61. struct MiningProxy {
  62. /// monerod network type
  63. monerod_network: monero::Network,
  64. /// monerod RPC address
  65. monerod_rpc: Url,
  66. }
  67. impl MiningProxy {
  68. /// Instantiate `MiningProxy` state
  69. async fn new(monerod: MonerodArgs) -> Result<Self> {
  70. let monerod_network = match monerod.network.to_lowercase().as_str() {
  71. "mainnet" => monero::Network::Mainnet,
  72. "testnet" => monero::Network::Testnet,
  73. _ => {
  74. error!("Invalid Monero network \"{}\"", monerod.network);
  75. return Err(Error::Custom(format!("Invalid Monero network \"{}\"", monerod.network)))
  76. }
  77. };
  78. // Test that monerod RPC is reachable
  79. if let Err(e) = TcpStream::connect(monerod.rpc.socket_addrs(|| None)?[0]).await {
  80. error!("Failed connecting to monerod RPC: {}", e);
  81. return Err(e.into())
  82. }
  83. Ok(Self { monerod_network, monerod_rpc: monerod.rpc })
  84. }
  85. }
  86. async_daemonize!(realmain);
  87. async fn realmain(args: Args, ex: Arc<Executor<'static>>) -> Result<()> {
  88. info!("Starting DarkFi x Monero merge mining proxy");
  89. let mmproxy = Arc::new(MiningProxy::new(args.monerod).await?);
  90. let mut app = tide::with_state(mmproxy);
  91. // monerod `/getheight` endpoint proxy
  92. app.at("/getheight").get(|req: tide::Request<Arc<MiningProxy>>| async move {
  93. let mmproxy = req.state();
  94. let return_data = mmproxy.monerod_get_height().await?;
  95. let return_data = return_data.stringify()?;
  96. debug!(target: "monerod::getheight", "<-- {}", return_data);
  97. Ok(return_data)
  98. });
  99. // monerod `/getinfo` endpoint proxy
  100. app.at("/getinfo").get(|req: tide::Request<Arc<MiningProxy>>| async move {
  101. let mmproxy = req.state();
  102. let return_data = mmproxy.monerod_get_info().await?;
  103. let return_data = return_data.stringify()?;
  104. debug!(target: "monerod::getinfo", "<-- {}", return_data);
  105. Ok(return_data)
  106. });
  107. // monerod `/json_rpc` endpoint proxy
  108. app.at("/json_rpc").post(|mut req: tide::Request<Arc<MiningProxy>>| async move {
  109. let json_str: JsonValue = match req.body_string().await {
  110. Ok(v) => v.parse()?,
  111. Err(e) => return Err(e),
  112. };
  113. let JsonValue::Object(ref request) = json_str else {
  114. return Err(surf::Error::new(
  115. StatusCode::BadRequest,
  116. Error::Custom("Invalid JSONRPC request".to_string()),
  117. ))
  118. };
  119. if !request.contains_key("method") || !request["method"].is_string() {
  120. return Err(surf::Error::new(
  121. StatusCode::BadRequest,
  122. Error::Custom("Invalid JSONRPC request".to_string()),
  123. ))
  124. }
  125. let mmproxy = req.state();
  126. let method = request["method"].get::<String>().unwrap();
  127. // For XMRig we only have to handle 2 methods:
  128. let return_data = match method.as_str() {
  129. "getblocktemplate" => mmproxy.monerod_getblocktemplate(&json_str).await?,
  130. "submitblock" => mmproxy.monerod_submit_block(&json_str).await?,
  131. _ => {
  132. return Err(surf::Error::new(
  133. StatusCode::BadRequest,
  134. Error::Custom("Invalid JSONRPC request".to_string()),
  135. ))
  136. }
  137. };
  138. let return_data = return_data.stringify()?;
  139. let log_tgt = format!("monerod::{}", method);
  140. debug!(target: &log_tgt, "<-- {}", return_data);
  141. Ok(return_data)
  142. });
  143. ex.spawn(async move { app.listen(args.listen).await.unwrap() }).detach();
  144. info!("Merge mining proxy ready, waiting for connections");
  145. // Signal handling for graceful termination.
  146. let (signals_handler, signals_task) = SignalHandler::new(ex)?;
  147. signals_handler.wait_termination(signals_task).await?;
  148. info!("Caught termination signal, cleaning up and exiting");
  149. Ok(())
  150. }