main.rs 8.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242
  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::HashMap, sync::Arc};
  19. use darkfi::{
  20. async_daemonize, cli_desc,
  21. rpc::{
  22. jsonrpc::{JsonRequest, JsonResponse},
  23. util::JsonValue,
  24. },
  25. Error, Result,
  26. };
  27. use log::{debug, error, info};
  28. use serde::Deserialize;
  29. use smol::{stream::StreamExt, Executor};
  30. use structopt::StructOpt;
  31. use structopt_toml::StructOptToml;
  32. use surf::StatusCode;
  33. use url::Url;
  34. const CONFIG_FILE: &str = "darkfi_mmproxy.toml";
  35. const CONFIG_FILE_CONTENTS: &str = include_str!("../darkfi_mmproxy.toml");
  36. /// Monero RPC functions
  37. mod monerod;
  38. use monerod::MonerodRequest;
  39. #[derive(Clone, Debug, Deserialize, StructOpt, StructOptToml)]
  40. #[serde(default)]
  41. #[structopt(name = "darkfi-mmproxy", about = cli_desc!())]
  42. struct Args {
  43. #[structopt(short, parse(from_occurrences))]
  44. /// Increase verbosity (-vvv supported)
  45. verbose: u8,
  46. #[structopt(short, long)]
  47. /// Configuration file to use
  48. config: Option<String>,
  49. #[structopt(long)]
  50. /// Set log file output
  51. log: Option<String>,
  52. #[structopt(flatten)]
  53. mmproxy: MmproxyArgs,
  54. #[structopt(flatten)]
  55. monerod: MonerodArgs,
  56. }
  57. #[derive(Clone, Debug, Deserialize, StructOpt, StructOptToml)]
  58. #[structopt()]
  59. struct MmproxyArgs {
  60. #[structopt(long, default_value = "http://127.0.0.1:3333")]
  61. /// darkfi-mmproxy JSON-RPC server listen URL
  62. mmproxy_rpc: Url,
  63. }
  64. #[derive(Clone, Debug, Deserialize, StructOpt, StructOptToml)]
  65. #[structopt()]
  66. struct MonerodArgs {
  67. #[structopt(long, default_value = "mainnet")]
  68. /// Monero network type (mainnet/testnet)
  69. monero_network: String,
  70. #[structopt(long, default_value = "http://127.0.0.1:18081")]
  71. /// monerod JSON-RPC server listen URL
  72. monero_rpc: Url,
  73. }
  74. /// Mining proxy state
  75. struct MiningProxy {
  76. /// Monero network type
  77. monero_network: monero::Network,
  78. /// Monero RPC address
  79. monero_rpc: Url,
  80. }
  81. impl MiningProxy {
  82. /// Instantiate `MiningProxy` state
  83. async fn new(monerod: MonerodArgs) -> Result<Self> {
  84. let monero_network = match monerod.monero_network.to_lowercase().as_str() {
  85. "mainnet" => monero::Network::Mainnet,
  86. "testnet" => monero::Network::Testnet,
  87. _ => {
  88. error!("Invalid Monero network \"{}\"", monerod.monero_network);
  89. return Err(Error::Custom(format!(
  90. "Invalid Monero network \"{}\"",
  91. monerod.monero_network
  92. )))
  93. }
  94. };
  95. // Test that monerod RPC is reachable and is configured
  96. // with the matching network
  97. let self_ = Self { monero_network, monero_rpc: monerod.monero_rpc };
  98. let req = JsonRequest::new("getinfo", vec![].into());
  99. let rep: JsonResponse = match self_.monero_request(MonerodRequest::Post(req)).await {
  100. Ok(v) => JsonResponse::try_from(&v)?,
  101. Err(e) => {
  102. error!("Failed connecting to monerod RPC: {}", e);
  103. return Err(e)
  104. }
  105. };
  106. let Some(result) = rep.result.get::<HashMap<String, JsonValue>>() else {
  107. error!("Invalid response from monerod RPC");
  108. return Err(Error::Custom("Invalid response from monerod RPC".to_string()))
  109. };
  110. let nettype = result.get("nettype").unwrap().get::<String>().unwrap();
  111. let mut xmr_is_mainnet = false;
  112. let mut xmr_is_testnet = false;
  113. match nettype.as_str() {
  114. // Here we allow fakechain, which we get with monerod --regtest
  115. "mainnet" | "fakechain" => xmr_is_mainnet = true,
  116. "testnet" => xmr_is_testnet = true,
  117. _ => unimplemented!("Missing handler for network {}", nettype),
  118. }
  119. if xmr_is_mainnet && !(monero_network == monero::Network::Mainnet) {
  120. error!("mmproxy requested testnet, but monerod is mainnet");
  121. return Err(Error::Custom("Monero network mismatch".to_string()))
  122. }
  123. if xmr_is_testnet && !(monero_network == monero::Network::Testnet) {
  124. error!("mmproxy requested mainnet, but monerod is testnet");
  125. return Err(Error::Custom("Monero network mismatch".to_string()))
  126. }
  127. Ok(self_)
  128. }
  129. }
  130. async_daemonize!(realmain);
  131. async fn realmain(args: Args, ex: Arc<Executor<'static>>) -> Result<()> {
  132. info!("Starting DarkFi x Monero merge mining proxy");
  133. let mmproxy = Arc::new(MiningProxy::new(args.monerod).await?);
  134. let mut app = tide::with_state(mmproxy);
  135. // monerod `/getheight` endpoint proxy [HTTP GET]
  136. app.at("/getheight").get(|req: tide::Request<Arc<MiningProxy>>| async move {
  137. debug!(target: "monerod::getheight", "--> /getheight");
  138. let mmproxy = req.state();
  139. let return_data = mmproxy.monerod_get_height().await?;
  140. let return_data = return_data.stringify()?;
  141. debug!(target: "monerod::getheight", "<-- {}", return_data);
  142. Ok(return_data)
  143. });
  144. // monerod `/getinfo` endpoint proxy [HTTP GET]
  145. app.at("/getinfo").get(|req: tide::Request<Arc<MiningProxy>>| async move {
  146. debug!(target: "monerod::getinfo", "--> /getinfo");
  147. let mmproxy = req.state();
  148. let return_data = mmproxy.monerod_get_info().await?;
  149. let return_data = return_data.stringify()?;
  150. debug!(target: "monerod::getinfo", "<-- {}", return_data);
  151. Ok(return_data)
  152. });
  153. // monerod `/json_rpc` endpoint proxy [HTTP POST]
  154. app.at("/json_rpc").post(|mut req: tide::Request<Arc<MiningProxy>>| async move {
  155. let body_string = match req.body_string().await {
  156. Ok(v) => v,
  157. Err(e) => {
  158. error!(target: "monerod::json_rpc", "Failed reading request body: {}", e);
  159. return Err(surf::Error::new(StatusCode::BadRequest, Error::Custom(e.to_string())))
  160. }
  161. };
  162. debug!(target: "monerod::json_rpc", "--> {}", body_string);
  163. let json_str: JsonValue = match body_string.parse() {
  164. Ok(v) => v,
  165. Err(e) => {
  166. error!(target: "monerod::json_rpc", "Failed parsing JSON body: {}", e);
  167. return Err(surf::Error::new(StatusCode::BadRequest, Error::Custom(e.to_string())))
  168. }
  169. };
  170. let JsonValue::Object(ref request) = json_str else {
  171. return Err(surf::Error::new(
  172. StatusCode::BadRequest,
  173. Error::Custom("Invalid JSONRPC request".to_string()),
  174. ))
  175. };
  176. if !request.contains_key("method") || !request["method"].is_string() {
  177. return Err(surf::Error::new(
  178. StatusCode::BadRequest,
  179. Error::Custom("Invalid JSONRPC request".to_string()),
  180. ))
  181. }
  182. let mmproxy = req.state();
  183. // For XMRig we only have to handle 2 methods:
  184. let return_data: JsonValue = match request["method"].get::<String>().unwrap().as_str() {
  185. "getblocktemplate" => mmproxy.monerod_getblocktemplate(&json_str).await?,
  186. "submitblock" => mmproxy.monerod_submit_block(&json_str).await?,
  187. _ => {
  188. return Err(surf::Error::new(
  189. StatusCode::BadRequest,
  190. Error::Custom("Invalid JSONRPC request".to_string()),
  191. ))
  192. }
  193. };
  194. let return_data = return_data.stringify()?;
  195. debug!(target: "monerod::json_rpc", "<-- {}", return_data);
  196. Ok(return_data)
  197. });
  198. ex.spawn(async move { app.listen(args.mmproxy.mmproxy_rpc).await.unwrap() }).detach();
  199. info!("Merge mining proxy ready, waiting for connections");
  200. // Signal handling for graceful termination.
  201. let (signals_handler, signals_task) = SignalHandler::new(ex)?;
  202. signals_handler.wait_termination(signals_task).await?;
  203. info!("Caught termination signal, cleaning up and exiting");
  204. Ok(())
  205. }