main.rs 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443
  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::{debug, 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. /// dnet JSON-RPC subscriber
  170. dnet_sub: JsonSubscriber,
  171. }
  172. impl Darkfid {
  173. pub async fn new(
  174. p2p: P2pPtr,
  175. validator: ValidatorPtr,
  176. miner: bool,
  177. txs_batch_size: usize,
  178. subscribers: HashMap<&'static str, JsonSubscriber>,
  179. rpc_client: Option<Mutex<MinerRpcCLient>>,
  180. dnet_sub: JsonSubscriber,
  181. ) -> Self {
  182. Self {
  183. p2p,
  184. validator,
  185. miner,
  186. txs_batch_size,
  187. subscribers,
  188. rpc_connections: Mutex::new(HashSet::new()),
  189. rpc_client,
  190. dnet_sub,
  191. }
  192. }
  193. }
  194. async_daemonize!(realmain);
  195. async fn realmain(args: Args, ex: Arc<smol::Executor<'static>>) -> Result<()> {
  196. info!(target: "darkfid", "Initializing DarkFi node...");
  197. // Grab blockchain network configuration
  198. let (blockchain_config, genesis_block) = match args.network.as_str() {
  199. "localnet" => {
  200. (parse_blockchain_config(args.config, "localnet").await?, GENESIS_BLOCK_LOCALNET)
  201. }
  202. "testnet" => {
  203. (parse_blockchain_config(args.config, "testnet").await?, GENESIS_BLOCK_TESTNET)
  204. }
  205. "mainnet" => {
  206. (parse_blockchain_config(args.config, "mainnet").await?, GENESIS_BLOCK_MAINNET)
  207. }
  208. _ => {
  209. error!("Unsupported chain `{}`", args.network);
  210. return Err(Error::UnsupportedChain)
  211. }
  212. };
  213. // Parse the genesis block
  214. let bytes = base64::decode(genesis_block.trim()).unwrap();
  215. let genesis_block: BlockInfo = deserialize_async(&bytes).await?;
  216. // Compute the bootstrap timestamp
  217. let bootstrap = match blockchain_config.bootstrap {
  218. Some(b) => b,
  219. None => genesis_block.header.timestamp.inner(),
  220. };
  221. // Initialize or open sled database
  222. let db_path = expand_path(&blockchain_config.database)?;
  223. let sled_db = sled_overlay::sled::open(&db_path)?;
  224. // Initialize validator configuration
  225. let pow_fixed_difficulty = if let Some(diff) = blockchain_config.pow_fixed_difficulty {
  226. info!(target: "darkfid", "Node is configured to run with fixed PoW difficulty: {}", diff);
  227. Some(diff.into())
  228. } else {
  229. None
  230. };
  231. let config = ValidatorConfig {
  232. finalization_threshold: blockchain_config.threshold,
  233. pow_target: blockchain_config.pow_target,
  234. pow_fixed_difficulty,
  235. genesis_block,
  236. verify_fees: !blockchain_config.skip_fees,
  237. };
  238. // Initialize validator
  239. let validator = Validator::new(&sled_db, config).await?;
  240. // Here we initialize various subscribers that can export live blockchain/consensus data.
  241. let mut subscribers = HashMap::new();
  242. subscribers.insert("blocks", JsonSubscriber::new("blockchain.subscribe_blocks"));
  243. subscribers.insert("txs", JsonSubscriber::new("blockchain.subscribe_txs"));
  244. subscribers.insert("proposals", JsonSubscriber::new("blockchain.subscribe_proposals"));
  245. // Initialize P2P network
  246. let p2p =
  247. spawn_p2p(&blockchain_config.net.into(), &validator, &subscribers, ex.clone()).await?;
  248. // Initialize JSON-RPC client to perform requests to minerd
  249. let rpc_client = if blockchain_config.miner {
  250. let Ok(rpc_client) =
  251. MinerRpcCLient::new(blockchain_config.minerd_endpoint, ex.clone()).await
  252. else {
  253. error!(target: "darkfid", "Failed to initialize miner daemon rpc client, check if minerd is running");
  254. return Err(Error::RpcClientStopped)
  255. };
  256. Some(Mutex::new(rpc_client))
  257. } else {
  258. None
  259. };
  260. // Grab blockchain network configured transactions batch size for garbage collection
  261. let txs_batch_size = match blockchain_config.txs_batch_size {
  262. Some(b) => {
  263. if b > 0 {
  264. b
  265. } else {
  266. 50
  267. }
  268. }
  269. None => 50,
  270. };
  271. info!(target: "darkfid", "Starting dnet subs task");
  272. let dnet_sub = JsonSubscriber::new("dnet.subscribe_events");
  273. let dnet_sub_ = dnet_sub.clone();
  274. let p2p_ = p2p.clone();
  275. let dnet_task = StoppableTask::new();
  276. dnet_task.clone().start(
  277. async move {
  278. let dnet_sub = p2p_.dnet_subscribe().await;
  279. loop {
  280. let event = dnet_sub.receive().await;
  281. debug!(target: "darkfid", "Got dnet event: {:?}", event);
  282. dnet_sub_.notify(vec![event.into()].into()).await;
  283. }
  284. },
  285. |res| async {
  286. match res {
  287. Ok(()) | Err(Error::DetachedTaskStopped) => { /* Do nothing */ }
  288. Err(e) => error!(target: "darkfid", "Failed starting dnet subs task: {}", e),
  289. }
  290. },
  291. Error::DetachedTaskStopped,
  292. ex.clone(),
  293. );
  294. // Initialize node
  295. let darkfid = Darkfid::new(
  296. p2p.clone(),
  297. validator,
  298. blockchain_config.miner,
  299. txs_batch_size,
  300. subscribers,
  301. rpc_client,
  302. dnet_sub,
  303. )
  304. .await;
  305. let darkfid = Arc::new(darkfid);
  306. info!(target: "darkfid", "Node initialized successfully!");
  307. // Pinging minerd daemon to verify it listens
  308. if blockchain_config.miner {
  309. if let Err(e) = darkfid.ping_miner_daemon().await {
  310. error!(target: "darkfid", "Failed to ping miner daemon: {}", e);
  311. return Err(Error::RpcClientStopped)
  312. }
  313. }
  314. // JSON-RPC server
  315. info!(target: "darkfid", "Starting JSON-RPC server");
  316. // Here we create a task variable so we can manually close the
  317. // task later. P2P tasks don't need this since it has its own
  318. // stop() function to shut down, also terminating the task we
  319. // created for it.
  320. let rpc_task = StoppableTask::new();
  321. let darkfid_ = darkfid.clone();
  322. rpc_task.clone().start(
  323. listen_and_serve(blockchain_config.rpc_listen, darkfid.clone(), None, ex.clone()),
  324. |res| async move {
  325. match res {
  326. Ok(()) | Err(Error::RpcServerStopped) => darkfid_.stop_connections().await,
  327. Err(e) => error!(target: "darkfid", "Failed starting sync JSON-RPC server: {}", e),
  328. }
  329. },
  330. Error::RpcServerStopped,
  331. ex.clone(),
  332. );
  333. info!(target: "darkfid", "Starting P2P network");
  334. p2p.clone().start().await?;
  335. // Consensus protocol
  336. info!(target: "darkfid", "Starting consensus protocol task");
  337. let consensus_task = StoppableTask::new();
  338. consensus_task.clone().start(
  339. consensus_init_task(
  340. darkfid.clone(),
  341. ConsensusInitTaskConfig {
  342. skip_sync: blockchain_config.skip_sync,
  343. checkpoint_height: blockchain_config.checkpoint_height,
  344. checkpoint: blockchain_config.checkpoint,
  345. miner: blockchain_config.miner,
  346. recipient: blockchain_config.recipient,
  347. spend_hook: blockchain_config.spend_hook,
  348. user_data: blockchain_config.user_data,
  349. bootstrap,
  350. },
  351. ex.clone(),
  352. ),
  353. |res| async move {
  354. match res {
  355. Ok(()) | Err(Error::ConsensusTaskStopped) | Err(Error::MinerTaskStopped) => { /* Do nothing */ }
  356. Err(e) => error!(target: "darkfid", "Failed starting consensus initialization task: {}", e),
  357. }
  358. },
  359. Error::ConsensusTaskStopped,
  360. ex.clone(),
  361. );
  362. // Signal handling for graceful termination.
  363. let (signals_handler, signals_task) = SignalHandler::new(ex)?;
  364. signals_handler.wait_termination(signals_task).await?;
  365. info!(target: "darkfid", "Caught termination signal, cleaning up and exiting...");
  366. info!(target: "darkfid", "Stopping dnet subs task...");
  367. dnet_task.stop().await;
  368. info!(target: "darkfid", "Stopping JSON-RPC server...");
  369. rpc_task.stop().await;
  370. info!(target: "darkfid", "Stopping P2P network...");
  371. p2p.stop().await;
  372. info!(target: "darkfid", "Stopping consensus task...");
  373. consensus_task.stop().await;
  374. info!(target: "darkfid", "Flushing sled database...");
  375. let flushed_bytes = sled_db.flush_async().await?;
  376. info!(target: "darkfid", "Flushed {} bytes", flushed_bytes);
  377. if let Some(ref rpc_client) = darkfid.rpc_client {
  378. info!(target: "darkfid", "Stopping JSON-RPC client...");
  379. rpc_client.lock().await.client.stop().await;
  380. };
  381. Ok(())
  382. }