main.rs 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410
  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::{
  19. collections::{HashMap, HashSet},
  20. sync::Arc,
  21. };
  22. use log::{error, info};
  23. use smol::{lock::Mutex, stream::StreamExt};
  24. use structopt_toml::{serde::Deserialize, structopt::StructOpt, StructOptToml};
  25. use url::Url;
  26. use darkfi::{
  27. async_daemonize,
  28. blockchain::BlockInfo,
  29. cli_desc,
  30. net::{settings::SettingsOpt, P2pPtr},
  31. rpc::{
  32. client::RpcChadClient,
  33. jsonrpc::JsonSubscriber,
  34. server::{listen_and_serve, RequestHandler},
  35. },
  36. system::{StoppableTask, StoppableTaskPtr},
  37. util::{encoding::base64, path::expand_path},
  38. validator::{Validator, ValidatorConfig, ValidatorPtr},
  39. Error, Result,
  40. };
  41. use darkfi_serial::deserialize_async;
  42. #[cfg(test)]
  43. mod tests;
  44. mod error;
  45. use error::{server_error, RpcError};
  46. /// JSON-RPC requests handler and methods
  47. mod rpc;
  48. mod rpc_blockchain;
  49. mod rpc_tx;
  50. /// Validator async tasks
  51. mod task;
  52. use task::{consensus::ConsensusInitTaskConfig, consensus_init_task};
  53. /// P2P net protocols
  54. mod proto;
  55. /// Utility functions
  56. mod utils;
  57. use utils::{parse_blockchain_config, spawn_p2p};
  58. const CONFIG_FILE: &str = "darkfid_config.toml";
  59. const CONFIG_FILE_CONTENTS: &str = include_str!("../darkfid_config.toml");
  60. /// Note:
  61. /// If you change these don't forget to remove their corresponding database folder,
  62. /// since if it already has a genesis block, provided one is ignored.
  63. const GENESIS_BLOCK_LOCALNET: &str = include_str!("../genesis_block_localnet");
  64. const GENESIS_BLOCK_TESTNET: &str = include_str!("../genesis_block_testnet");
  65. const GENESIS_BLOCK_MAINNET: &str = include_str!("../genesis_block_mainnet");
  66. #[derive(Clone, Debug, Deserialize, StructOpt, StructOptToml)]
  67. #[serde(default)]
  68. #[structopt(name = "darkfid", about = cli_desc!())]
  69. struct Args {
  70. #[structopt(short, long)]
  71. /// Configuration file to use
  72. config: Option<String>,
  73. #[structopt(short, long, default_value = "testnet")]
  74. /// Blockchain network to use
  75. network: String,
  76. #[structopt(short, long)]
  77. /// Set log file to ouput into
  78. log: Option<String>,
  79. #[structopt(short, parse(from_occurrences))]
  80. /// Increase verbosity (-vvv supported)
  81. verbose: u8,
  82. }
  83. /// Defines a blockchain network configuration.
  84. /// Default values correspond to a local network.
  85. #[derive(Clone, Debug, serde::Deserialize, structopt::StructOpt, structopt_toml::StructOptToml)]
  86. #[structopt()]
  87. pub struct BlockchainNetwork {
  88. #[structopt(short, long, default_value = "tcp://127.0.0.1:8240")]
  89. /// JSON-RPC listen URL
  90. pub rpc_listen: Url,
  91. #[structopt(long, default_value = "~/.local/darkfi/darkfid/localnet")]
  92. /// Path to blockchain database
  93. pub database: String,
  94. #[structopt(long, default_value = "3")]
  95. /// Finalization threshold, denominated by number of blocks
  96. pub threshold: usize,
  97. #[structopt(long, default_value = "tcp://127.0.0.1:28467")]
  98. /// minerd JSON-RPC endpoint
  99. pub minerd_endpoint: Url,
  100. #[structopt(long, default_value = "10")]
  101. /// PoW block production target, in seconds
  102. pub pow_target: u32,
  103. #[structopt(long)]
  104. /// Optional fixed PoW difficulty, used for testing
  105. pub pow_fixed_difficulty: Option<usize>,
  106. #[structopt(long)]
  107. /// Participate in block production
  108. pub miner: bool,
  109. #[structopt(long)]
  110. /// Wallet address to receive mining rewards
  111. pub recipient: Option<String>,
  112. #[structopt(long)]
  113. /// Optional contract spend hook to use in the mining reward
  114. pub spend_hook: Option<String>,
  115. #[structopt(long)]
  116. /// Optional user data to use in the mining reward
  117. pub user_data: Option<String>,
  118. #[structopt(long)]
  119. /// Skip syncing process and start node right away
  120. pub skip_sync: bool,
  121. #[structopt(long)]
  122. /// Disable transaction's fee verification, used for testing
  123. pub skip_fees: bool,
  124. #[structopt(long)]
  125. /// Optional sync checkpoint height
  126. pub checkpoint_height: Option<u32>,
  127. #[structopt(long)]
  128. /// Optional sync checkpoint hash
  129. pub checkpoint: Option<String>,
  130. #[structopt(long)]
  131. /// Optional bootstrap timestamp
  132. pub bootstrap: Option<u64>,
  133. #[structopt(long)]
  134. /// Garbage collection task transactions batch size
  135. pub txs_batch_size: Option<usize>,
  136. /// P2P network settings
  137. #[structopt(flatten)]
  138. pub net: SettingsOpt,
  139. }
  140. /// Structure to hold a JSON-RPC client and its config,
  141. /// so we can recreate it in case of an error.
  142. pub struct MinerRpcCLient {
  143. endpoint: Url,
  144. ex: Arc<smol::Executor<'static>>,
  145. client: RpcChadClient,
  146. }
  147. impl MinerRpcCLient {
  148. pub async fn new(endpoint: Url, ex: Arc<smol::Executor<'static>>) -> Result<Self> {
  149. let client = RpcChadClient::new(endpoint.clone(), ex.clone()).await?;
  150. Ok(Self { endpoint, ex, client })
  151. }
  152. }
  153. /// Daemon structure
  154. pub struct Darkfid {
  155. /// P2P network pointer
  156. p2p: P2pPtr,
  157. /// Validator(node) pointer
  158. validator: ValidatorPtr,
  159. /// Flag to specify node is a miner
  160. miner: bool,
  161. /// Garbage collection task transactions batch size
  162. txs_batch_size: usize,
  163. /// A map of various subscribers exporting live info from the blockchain
  164. subscribers: HashMap<&'static str, JsonSubscriber>,
  165. /// JSON-RPC connection tracker
  166. rpc_connections: Mutex<HashSet<StoppableTaskPtr>>,
  167. /// JSON-RPC client to execute requests to the miner daemon
  168. rpc_client: Option<Mutex<MinerRpcCLient>>,
  169. }
  170. impl Darkfid {
  171. pub async fn new(
  172. p2p: P2pPtr,
  173. validator: ValidatorPtr,
  174. miner: bool,
  175. txs_batch_size: usize,
  176. subscribers: HashMap<&'static str, JsonSubscriber>,
  177. rpc_client: Option<Mutex<MinerRpcCLient>>,
  178. ) -> Self {
  179. Self {
  180. p2p,
  181. validator,
  182. miner,
  183. txs_batch_size,
  184. subscribers,
  185. rpc_connections: Mutex::new(HashSet::new()),
  186. rpc_client,
  187. }
  188. }
  189. }
  190. async_daemonize!(realmain);
  191. async fn realmain(args: Args, ex: Arc<smol::Executor<'static>>) -> Result<()> {
  192. info!(target: "darkfid", "Initializing DarkFi node...");
  193. // Grab blockchain network configuration
  194. let (blockchain_config, genesis_block) = match args.network.as_str() {
  195. "localnet" => {
  196. (parse_blockchain_config(args.config, "localnet").await?, GENESIS_BLOCK_LOCALNET)
  197. }
  198. "testnet" => {
  199. (parse_blockchain_config(args.config, "testnet").await?, GENESIS_BLOCK_TESTNET)
  200. }
  201. "mainnet" => {
  202. (parse_blockchain_config(args.config, "mainnet").await?, GENESIS_BLOCK_MAINNET)
  203. }
  204. _ => {
  205. error!("Unsupported chain `{}`", args.network);
  206. return Err(Error::UnsupportedChain)
  207. }
  208. };
  209. // Parse the genesis block
  210. let bytes = base64::decode(genesis_block.trim()).unwrap();
  211. let genesis_block: BlockInfo = deserialize_async(&bytes).await?;
  212. // Compute the bootstrap timestamp
  213. let bootstrap = match blockchain_config.bootstrap {
  214. Some(b) => b,
  215. None => genesis_block.header.timestamp.inner(),
  216. };
  217. // Initialize or open sled database
  218. let db_path = expand_path(&blockchain_config.database)?;
  219. let sled_db = sled::open(&db_path)?;
  220. // Initialize validator configuration
  221. let pow_fixed_difficulty = if let Some(diff) = blockchain_config.pow_fixed_difficulty {
  222. info!(target: "darkfid", "Node is configured to run with fixed PoW difficulty: {}", diff);
  223. Some(diff.into())
  224. } else {
  225. None
  226. };
  227. let config = ValidatorConfig {
  228. finalization_threshold: blockchain_config.threshold,
  229. pow_target: blockchain_config.pow_target,
  230. pow_fixed_difficulty,
  231. genesis_block,
  232. verify_fees: !blockchain_config.skip_fees,
  233. };
  234. // Initialize validator
  235. let validator = Validator::new(&sled_db, config).await?;
  236. // Here we initialize various subscribers that can export live blockchain/consensus data.
  237. let mut subscribers = HashMap::new();
  238. subscribers.insert("blocks", JsonSubscriber::new("blockchain.subscribe_blocks"));
  239. subscribers.insert("txs", JsonSubscriber::new("blockchain.subscribe_txs"));
  240. subscribers.insert("proposals", JsonSubscriber::new("blockchain.subscribe_proposals"));
  241. // Initialize P2P network
  242. let p2p = spawn_p2p(&blockchain_config.net.into(), &validator, &subscribers, ex.clone()).await;
  243. // Initialize JSON-RPC client to perform requests to minerd
  244. let rpc_client = if blockchain_config.miner {
  245. let Ok(rpc_client) =
  246. MinerRpcCLient::new(blockchain_config.minerd_endpoint, ex.clone()).await
  247. else {
  248. error!(target: "darkfid", "Failed to initialize miner daemon rpc client, check if minerd is running");
  249. return Err(Error::RpcClientStopped)
  250. };
  251. Some(Mutex::new(rpc_client))
  252. } else {
  253. None
  254. };
  255. // Grab blockchain network configured transactions batch size for garbage collection
  256. let txs_batch_size = match blockchain_config.txs_batch_size {
  257. Some(b) => {
  258. if b > 0 {
  259. b
  260. } else {
  261. 50
  262. }
  263. }
  264. None => 50,
  265. };
  266. // Initialize node
  267. let darkfid = Darkfid::new(
  268. p2p.clone(),
  269. validator,
  270. blockchain_config.miner,
  271. txs_batch_size,
  272. subscribers,
  273. rpc_client,
  274. )
  275. .await;
  276. let darkfid = Arc::new(darkfid);
  277. info!(target: "darkfid", "Node initialized successfully!");
  278. // Pinging minerd daemon to verify it listens
  279. if blockchain_config.miner {
  280. if let Err(e) = darkfid.ping_miner_daemon().await {
  281. error!(target: "darkfid", "Failed to ping miner daemon: {}", e);
  282. return Err(Error::RpcClientStopped)
  283. }
  284. }
  285. // JSON-RPC server
  286. info!(target: "darkfid", "Starting JSON-RPC server");
  287. // Here we create a task variable so we can manually close the
  288. // task later. P2P tasks don't need this since it has its own
  289. // stop() function to shut down, also terminating the task we
  290. // created for it.
  291. let rpc_task = StoppableTask::new();
  292. let darkfid_ = darkfid.clone();
  293. rpc_task.clone().start(
  294. listen_and_serve(blockchain_config.rpc_listen, darkfid.clone(), None, ex.clone()),
  295. |res| async move {
  296. match res {
  297. Ok(()) | Err(Error::RpcServerStopped) => darkfid_.stop_connections().await,
  298. Err(e) => error!(target: "darkfid", "Failed starting sync JSON-RPC server: {}", e),
  299. }
  300. },
  301. Error::RpcServerStopped,
  302. ex.clone(),
  303. );
  304. info!(target: "darkfid", "Starting P2P network");
  305. p2p.clone().start().await?;
  306. // Consensus protocol
  307. info!(target: "darkfid", "Starting consensus protocol task");
  308. let consensus_task = StoppableTask::new();
  309. consensus_task.clone().start(
  310. consensus_init_task(
  311. darkfid.clone(),
  312. ConsensusInitTaskConfig {
  313. skip_sync: blockchain_config.skip_sync,
  314. checkpoint_height: blockchain_config.checkpoint_height,
  315. checkpoint: blockchain_config.checkpoint,
  316. miner: blockchain_config.miner,
  317. recipient: blockchain_config.recipient,
  318. spend_hook: blockchain_config.spend_hook,
  319. user_data: blockchain_config.user_data,
  320. bootstrap,
  321. },
  322. ex.clone(),
  323. ),
  324. |res| async move {
  325. match res {
  326. Ok(()) | Err(Error::ConsensusTaskStopped) | Err(Error::MinerTaskStopped) => { /* Do nothing */ }
  327. Err(e) => error!(target: "darkfid", "Failed starting consensus initialization task: {}", e),
  328. }
  329. },
  330. Error::ConsensusTaskStopped,
  331. ex.clone(),
  332. );
  333. // Signal handling for graceful termination.
  334. let (signals_handler, signals_task) = SignalHandler::new(ex)?;
  335. signals_handler.wait_termination(signals_task).await?;
  336. info!(target: "darkfid", "Caught termination signal, cleaning up and exiting...");
  337. info!(target: "darkfid", "Stopping JSON-RPC server...");
  338. rpc_task.stop().await;
  339. info!(target: "darkfid", "Stopping P2P network...");
  340. p2p.stop().await;
  341. info!(target: "darkfid", "Stopping consensus task...");
  342. consensus_task.stop().await;
  343. info!(target: "darkfid", "Flushing sled database...");
  344. let flushed_bytes = sled_db.flush_async().await?;
  345. info!(target: "darkfid", "Flushed {} bytes", flushed_bytes);
  346. if let Some(ref rpc_client) = darkfid.rpc_client {
  347. info!(target: "darkfid", "Stopping JSON-RPC client...");
  348. rpc_client.lock().await.client.stop().await;
  349. };
  350. Ok(())
  351. }