1 // Copyright (c) 2016 The Zcash developers
2 // Distributed under the MIT software license, see the accompanying
3 // file COPYING or http://www.opensource.org/licenses/mit-license.php.
7 #include "chainparams.h"
8 #include "checkpoints.h"
10 #include "ui_interface.h"
13 #include "utilmoneystr.h"
14 #include "utilstrencodings.h"
16 #include <boost/thread.hpp>
17 #include <boost/thread/synchronized_value.hpp>
22 #include <sys/ioctl.h>
26 void AtomicTimer::start()
28 std::unique_lock<std::mutex> lock(mtx);
30 start_time = GetTime();
35 void AtomicTimer::stop()
37 std::unique_lock<std::mutex> lock(mtx);
38 // Ignore excess calls to stop()
42 int64_t time_span = GetTime() - start_time;
43 total_time += time_span;
48 bool AtomicTimer::running()
50 std::unique_lock<std::mutex> lock(mtx);
54 uint64_t AtomicTimer::threadCount()
56 std::unique_lock<std::mutex> lock(mtx);
60 double AtomicTimer::rate(const AtomicCounter& count)
62 std::unique_lock<std::mutex> lock(mtx);
63 int64_t duration = total_time;
65 // Timer is running, so get the latest count
66 duration += GetTime() - start_time;
68 return duration > 0 ? (double)count.get() / duration : 0;
71 static CCriticalSection cs_metrics;
73 static boost::synchronized_value<int64_t> nNodeStartTime;
74 static boost::synchronized_value<int64_t> nNextRefresh;
75 AtomicCounter transactionsValidated;
76 AtomicCounter ehSolverRuns;
77 AtomicCounter solutionTargetChecks;
78 static AtomicCounter minedBlocks;
79 AtomicTimer miningTimer;
81 static boost::synchronized_value<std::list<uint256>> trackedBlocks;
83 static boost::synchronized_value<std::list<std::string>> messageBox;
84 static boost::synchronized_value<std::string> initMessage;
85 static bool loaded = false;
87 extern int64_t GetNetworkHashPS(int lookup, int height);
89 void TrackMinedBlock(uint256 hash)
92 minedBlocks.increment();
93 trackedBlocks->push_back(hash);
98 *nNodeStartTime = GetTime();
103 return GetTime() - *nNodeStartTime;
106 double GetLocalSolPS()
108 return miningTimer.rate(solutionTargetChecks);
111 int EstimateNetHeightInner(int height, int64_t tipmediantime,
112 int heightLastCheckpoint, int64_t timeLastCheckpoint,
113 int64_t genesisTime, int64_t targetSpacing)
115 // We average the target spacing with the observed spacing to the last
116 // checkpoint (either from below or above depending on the current height),
117 // and use that to estimate the current network height.
118 int medianHeight = height > CBlockIndex::nMedianTimeSpan ?
119 height - (1 + ((CBlockIndex::nMedianTimeSpan - 1) / 2)) :
121 double checkpointSpacing = medianHeight > heightLastCheckpoint ?
122 (double (tipmediantime - timeLastCheckpoint)) / (medianHeight - heightLastCheckpoint) :
123 (double (timeLastCheckpoint - genesisTime)) / heightLastCheckpoint;
124 double averageSpacing = (targetSpacing + checkpointSpacing) / 2;
125 int netheight = medianHeight + ((GetTime() - tipmediantime) / averageSpacing);
126 // Round to nearest ten to reduce noise
127 return ((netheight + 5) / 10) * 10;
130 int EstimateNetHeight(int height, int64_t tipmediantime, CChainParams chainParams)
132 auto checkpointData = chainParams.Checkpoints();
133 return EstimateNetHeightInner(
134 height, tipmediantime,
135 Checkpoints::GetTotalBlocksEstimate(checkpointData),
136 checkpointData.nTimeLastCheckpoint,
137 chainParams.GenesisBlock().nTime,
138 chainParams.GetConsensus().nPowTargetSpacing);
141 void TriggerRefresh()
143 *nNextRefresh = GetTime();
144 // Ensure that the refresh has started before we return
148 static bool metrics_ThreadSafeMessageBox(const std::string& message,
149 const std::string& caption,
152 // The SECURE flag has no effect in the metrics UI.
153 style &= ~CClientUIInterface::SECURE;
155 std::string strCaption;
156 // Check for usage of predefined caption
158 case CClientUIInterface::MSG_ERROR:
159 strCaption += _("Error");
161 case CClientUIInterface::MSG_WARNING:
162 strCaption += _("Warning");
164 case CClientUIInterface::MSG_INFORMATION:
165 strCaption += _("Information");
168 strCaption += caption; // Use supplied caption (can be empty)
171 boost::strict_lock_ptr<std::list<std::string>> u = messageBox.synchronize();
172 u->push_back(strCaption + ": " + message);
181 static bool metrics_ThreadSafeQuestion(const std::string& /* ignored interactive message */, const std::string& message, const std::string& caption, unsigned int style)
183 return metrics_ThreadSafeMessageBox(message, caption, style);
186 static void metrics_InitMessage(const std::string& message)
188 *initMessage = message;
191 void ConnectMetricsScreen()
193 uiInterface.ThreadSafeMessageBox.disconnect_all_slots();
194 uiInterface.ThreadSafeMessageBox.connect(metrics_ThreadSafeMessageBox);
195 uiInterface.ThreadSafeQuestion.disconnect_all_slots();
196 uiInterface.ThreadSafeQuestion.connect(metrics_ThreadSafeQuestion);
197 uiInterface.InitMessage.disconnect_all_slots();
198 uiInterface.InitMessage.connect(metrics_InitMessage);
201 int printStats(bool mining)
203 // Number of lines that are always displayed
207 int64_t tipmediantime;
211 LOCK2(cs_main, cs_vNodes);
212 height = chainActive.Height();
213 tipmediantime = chainActive.Tip()->GetMedianTimePast();
214 connections = vNodes.size();
215 netsolps = GetNetworkHashPS(120, -1);
217 auto localsolps = GetLocalSolPS();
219 if (IsInitialBlockDownload(Params())) {
220 int netheight = EstimateNetHeight(height, tipmediantime, Params());
221 int downloadPercent = height * 100 / netheight;
222 std::cout << " " << _("Downloading blocks") << " | " << height << " / ~" << netheight << " (" << downloadPercent << "%)" << std::endl;
224 std::cout << " " << _("Block height") << " | " << height << std::endl;
226 std::cout << " " << _("Connections") << " | " << connections << std::endl;
227 std::cout << " " << _("Network solution rate") << " | " << netsolps << " Sol/s" << std::endl;
228 if (mining && miningTimer.running()) {
229 std::cout << " " << _("Local solution rate") << " | " << strprintf("%.4f Sol/s", localsolps) << std::endl;
232 std::cout << std::endl;
237 int printMiningStatus(bool mining)
240 // Number of lines that are always displayed
244 auto nThreads = miningTimer.threadCount();
246 std::cout << strprintf(_("You are mining with the %s solver on %d threads."),
247 GetArg("-equihashsolver", "default"), nThreads) << std::endl;
252 fvNodesEmpty = vNodes.empty();
255 std::cout << _("Mining is paused while waiting for connections.") << std::endl;
256 } else if (IsInitialBlockDownload(Params())) {
257 std::cout << _("Mining is paused while downloading blocks.") << std::endl;
259 std::cout << _("Mining is paused (a JoinSplit may be in progress).") << std::endl;
264 std::cout << _("You are currently not mining.") << std::endl;
265 std::cout << _("To enable mining, add 'gen=1' to your zcash.conf and restart.") << std::endl;
268 std::cout << std::endl;
271 #else // ENABLE_MINING
273 #endif // !ENABLE_MINING
276 int printMetrics(size_t cols, bool mining)
278 // Number of lines that are always displayed
282 int64_t uptime = GetUptime();
283 int days = uptime / (24 * 60 * 60);
284 int hours = (uptime - (days * 24 * 60 * 60)) / (60 * 60);
285 int minutes = (uptime - (((days * 24) + hours) * 60 * 60)) / 60;
286 int seconds = uptime - (((((days * 24) + hours) * 60) + minutes) * 60);
289 std::string duration;
291 duration = strprintf(_("%d days, %d hours, %d minutes, %d seconds"), days, hours, minutes, seconds);
292 } else if (hours > 0) {
293 duration = strprintf(_("%d hours, %d minutes, %d seconds"), hours, minutes, seconds);
294 } else if (minutes > 0) {
295 duration = strprintf(_("%d minutes, %d seconds"), minutes, seconds);
297 duration = strprintf(_("%d seconds"), seconds);
299 std::string strDuration = strprintf(_("Since starting this node %s ago:"), duration);
300 std::cout << strDuration << std::endl;
301 lines += (strDuration.size() / cols);
303 int validatedCount = transactionsValidated.get();
304 if (validatedCount > 1) {
305 std::cout << "- " << strprintf(_("You have validated %d transactions!"), validatedCount) << std::endl;
306 } else if (validatedCount == 1) {
307 std::cout << "- " << _("You have validated a transaction!") << std::endl;
309 std::cout << "- " << _("You have validated no transactions.") << std::endl;
312 if (mining && loaded) {
313 std::cout << "- " << strprintf(_("You have completed %d Equihash solver runs."), ehSolverRuns.get()) << std::endl;
318 CAmount immature {0};
321 LOCK2(cs_main, cs_metrics);
322 boost::strict_lock_ptr<std::list<uint256>> u = trackedBlocks.synchronize();
323 auto consensusParams = Params().GetConsensus();
324 auto tipHeight = chainActive.Height();
326 // Update orphans and calculate subsidies
327 std::list<uint256>::iterator it = u->begin();
328 while (it != u->end()) {
330 if (mapBlockIndex.count(hash) > 0 &&
331 chainActive.Contains(mapBlockIndex[hash])) {
332 int height = mapBlockIndex[hash]->nHeight;
333 CAmount subsidy = GetBlockSubsidy(height, consensusParams);
334 if ((height > 0) && (height <= consensusParams.GetLastFoundersRewardBlockHeight())) {
335 subsidy -= subsidy/5;
337 if (std::max(0, COINBASE_MATURITY - (tipHeight - height)) > 0) {
348 mined = minedBlocks.get();
349 orphaned = mined - u->size();
353 std::string units = Params().CurrencyUnits();
354 std::cout << "- " << strprintf(_("You have mined %d blocks!"), mined) << std::endl;
356 << strprintf(_("Orphaned: %d blocks, Immature: %u %s, Mature: %u %s"),
358 FormatMoney(immature), units,
359 FormatMoney(mature), units)
364 std::cout << std::endl;
369 int printMessageBox(size_t cols)
371 boost::strict_lock_ptr<std::list<std::string>> u = messageBox.synchronize();
373 if (u->size() == 0) {
377 int lines = 2 + u->size();
378 std::cout << _("Messages:") << std::endl;
379 for (auto it = u->cbegin(); it != u->cend(); ++it) {
380 auto msg = FormatParagraph(*it, cols, 2);
381 std::cout << "- " << msg << std::endl;
382 // Handle newlines and wrapped lines
385 while (j < msg.size()) {
386 i = msg.find('\n', j);
387 if (i == std::string::npos) {
396 std::cout << std::endl;
400 int printInitMessage()
406 std::string msg = *initMessage;
407 std::cout << _("Init message:") << " " << msg << std::endl;
408 std::cout << std::endl;
410 if (msg == _("Done loading")) {
418 #define ENABLE_VIRTUAL_TERMINAL_PROCESSING 0x0004
422 // Set output mode to handle virtual terminal sequences
423 HANDLE hOut = GetStdHandle(STD_OUTPUT_HANDLE);
424 if (hOut == INVALID_HANDLE_VALUE) {
429 if (!GetConsoleMode(hOut, &dwMode)) {
433 dwMode |= ENABLE_VIRTUAL_TERMINAL_PROCESSING;
434 if (!SetConsoleMode(hOut, dwMode)) {
441 void ThreadShowMetricsScreen()
443 // Make this thread recognisable as the metrics screen thread
444 RenameThread("zcash-metrics-screen");
446 // Determine whether we should render a persistent UI or rolling metrics
447 bool isTTY = isatty(STDOUT_FILENO);
448 bool isScreen = GetBoolArg("-metricsui", isTTY);
449 int64_t nRefresh = GetArg("-metricsrefreshtime", isTTY ? 1 : 600);
457 std::cout << "\e[2J";
460 std::cout << METRICS_ART << std::endl;
461 std::cout << std::endl;
464 std::cout << _("Thank you for running a Zcash node!") << std::endl;
465 std::cout << _("You're helping to strengthen the network and contributing to a social good :)") << std::endl;
467 // Privacy notice text
468 std::cout << PrivacyInfo();
469 std::cout << std::endl;
473 // Number of lines that are always displayed
477 // Get current window size
480 CONSOLE_SCREEN_BUFFER_INFO csbi;
481 if (GetConsoleScreenBufferInfo(GetStdHandle(STD_OUTPUT_HANDLE), &csbi) != 0) {
482 cols = csbi.srWindow.Right - csbi.srWindow.Left + 1;
487 if (ioctl(STDOUT_FILENO, TIOCGWINSZ, &w) != -1 && w.ws_col != 0) {
494 // Erase below current position
500 bool mining = GetBoolArg("-gen", false);
506 lines += printStats(mining);
507 lines += printMiningStatus(mining);
509 lines += printMetrics(cols, mining);
510 lines += printMessageBox(cols);
511 lines += printInitMessage();
514 // Explain how to exit
517 std::cout << _("'zcash-cli.exe stop' to exit");
519 std::cout << _("Press Ctrl+C to exit");
521 std::cout << "] [" << _("Set 'showmetrics=0' to hide") << "]" << std::endl;
524 std::cout << "----------------------------------------" << std::endl;
527 *nNextRefresh = GetTime() + nRefresh;
528 while (GetTime() < *nNextRefresh) {
529 boost::this_thread::interruption_point();
534 // Return to the top of the updating section
535 std::cout << "\e[" << lines << "A";