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"
9 #include "ui_interface.h"
12 #include "utilmoneystr.h"
14 #include <boost/thread.hpp>
15 #include <boost/thread/synchronized_value.hpp>
17 #include <sys/ioctl.h>
20 void AtomicTimer::start()
22 std::unique_lock<std::mutex> lock(mtx);
24 start_time = GetTime();
29 void AtomicTimer::stop()
31 std::unique_lock<std::mutex> lock(mtx);
32 // Ignore excess calls to stop()
36 int64_t time_span = GetTime() - start_time;
37 total_time += time_span;
42 bool AtomicTimer::running()
44 std::unique_lock<std::mutex> lock(mtx);
48 double AtomicTimer::rate(const AtomicCounter& count)
50 std::unique_lock<std::mutex> lock(mtx);
51 int64_t duration = total_time;
53 // Timer is running, so get the latest count
54 duration += GetTime() - start_time;
56 return duration > 0 ? (double)count.get() / duration : 0;
59 CCriticalSection cs_metrics;
61 boost::synchronized_value<int64_t> nNodeStartTime;
62 boost::synchronized_value<int64_t> nNextRefresh;
63 AtomicCounter transactionsValidated;
64 AtomicCounter ehSolverRuns;
65 AtomicCounter solutionTargetChecks;
66 AtomicCounter minedBlocks;
67 AtomicTimer miningTimer;
69 boost::synchronized_value<std::list<uint256>> trackedBlocks;
71 boost::synchronized_value<std::list<std::string>> messageBox;
72 boost::synchronized_value<std::string> initMessage;
75 extern int64_t GetNetworkHashPS(int lookup, int height);
77 void TrackMinedBlock(uint256 hash)
80 minedBlocks.increment();
81 trackedBlocks->push_back(hash);
86 *nNodeStartTime = GetTime();
91 return GetTime() - *nNodeStartTime;
94 double GetLocalSolPS()
96 return miningTimer.rate(solutionTargetChecks);
101 *nNextRefresh = GetTime();
102 // Ensure that the refresh has started before we return
106 static bool metrics_ThreadSafeMessageBox(const std::string& message,
107 const std::string& caption,
110 // The SECURE flag has no effect in the metrics UI.
111 style &= ~CClientUIInterface::SECURE;
113 std::string strCaption;
114 // Check for usage of predefined caption
116 case CClientUIInterface::MSG_ERROR:
117 strCaption += _("Error");
119 case CClientUIInterface::MSG_WARNING:
120 strCaption += _("Warning");
122 case CClientUIInterface::MSG_INFORMATION:
123 strCaption += _("Information");
126 strCaption += caption; // Use supplied caption (can be empty)
129 boost::strict_lock_ptr<std::list<std::string>> u = messageBox.synchronize();
130 u->push_back(strCaption + ": " + message);
139 static bool metrics_ThreadSafeQuestion(const std::string& /* ignored interactive message */, const std::string& message, const std::string& caption, unsigned int style)
141 return metrics_ThreadSafeMessageBox(message, caption, style);
144 static void metrics_InitMessage(const std::string& message)
146 *initMessage = message;
149 void ConnectMetricsScreen()
151 uiInterface.ThreadSafeMessageBox.disconnect_all_slots();
152 uiInterface.ThreadSafeMessageBox.connect(metrics_ThreadSafeMessageBox);
153 uiInterface.ThreadSafeQuestion.disconnect_all_slots();
154 uiInterface.ThreadSafeQuestion.connect(metrics_ThreadSafeQuestion);
155 uiInterface.InitMessage.disconnect_all_slots();
156 uiInterface.InitMessage.connect(metrics_InitMessage);
159 int printStats(bool mining)
161 // Number of lines that are always displayed
168 LOCK2(cs_main, cs_vNodes);
169 height = chainActive.Height();
170 connections = vNodes.size();
171 netsolps = GetNetworkHashPS(120, -1);
173 auto localsolps = GetLocalSolPS();
175 std::cout << " " << _("Block height") << " | " << height << std::endl;
176 std::cout << " " << _("Connections") << " | " << connections << std::endl;
177 std::cout << " " << _("Network solution rate") << " | " << netsolps << " Sol/s" << std::endl;
178 if (mining && miningTimer.running()) {
179 std::cout << " " << _("Local solution rate") << " | " << strprintf("%.4f Sol/s", localsolps) << std::endl;
182 std::cout << std::endl;
187 int printMiningStatus(bool mining)
190 // Number of lines that are always displayed
194 int nThreads = GetArg("-genproclimit", 1);
196 // In regtest threads defaults to 1
197 if (Params().DefaultMinerThreads())
198 nThreads = Params().DefaultMinerThreads();
200 nThreads = boost::thread::hardware_concurrency();
202 if (miningTimer.running()) {
203 std::cout << strprintf(_("You are mining with the %s solver on %d threads."),
204 GetArg("-equihashsolver", "default"), nThreads) << std::endl;
206 std::cout << _("Mining is paused.") << std::endl;
210 std::cout << _("You are currently not mining.") << std::endl;
211 std::cout << _("To enable mining, add 'gen=1' to your zcash.conf and restart.") << std::endl;
214 std::cout << std::endl;
217 #else // ENABLE_MINING
219 #endif // !ENABLE_MINING
222 int printMetrics(size_t cols, bool mining)
224 // Number of lines that are always displayed
228 int64_t uptime = GetUptime();
229 int days = uptime / (24 * 60 * 60);
230 int hours = (uptime - (days * 24 * 60 * 60)) / (60 * 60);
231 int minutes = (uptime - (((days * 24) + hours) * 60 * 60)) / 60;
232 int seconds = uptime - (((((days * 24) + hours) * 60) + minutes) * 60);
235 std::string duration;
237 duration = strprintf(_("%d days, %d hours, %d minutes, %d seconds"), days, hours, minutes, seconds);
238 } else if (hours > 0) {
239 duration = strprintf(_("%d hours, %d minutes, %d seconds"), hours, minutes, seconds);
240 } else if (minutes > 0) {
241 duration = strprintf(_("%d minutes, %d seconds"), minutes, seconds);
243 duration = strprintf(_("%d seconds"), seconds);
245 std::string strDuration = strprintf(_("Since starting this node %s ago:"), duration);
246 std::cout << strDuration << std::endl;
247 lines += (strDuration.size() / cols);
249 int validatedCount = transactionsValidated.get();
250 if (validatedCount > 1) {
251 std::cout << "- " << strprintf(_("You have validated %d transactions!"), validatedCount) << std::endl;
252 } else if (validatedCount == 1) {
253 std::cout << "- " << _("You have validated a transaction!") << std::endl;
255 std::cout << "- " << _("You have validated no transactions.") << std::endl;
258 if (mining && loaded) {
259 std::cout << "- " << strprintf(_("You have completed %d Equihash solver runs."), ehSolverRuns.get()) << std::endl;
264 CAmount immature {0};
267 LOCK2(cs_main, cs_metrics);
268 boost::strict_lock_ptr<std::list<uint256>> u = trackedBlocks.synchronize();
269 auto consensusParams = Params().GetConsensus();
270 auto tipHeight = chainActive.Height();
272 // Update orphans and calculate subsidies
273 std::list<uint256>::iterator it = u->begin();
274 while (it != u->end()) {
276 if (mapBlockIndex.count(hash) > 0 &&
277 chainActive.Contains(mapBlockIndex[hash])) {
278 int height = mapBlockIndex[hash]->nHeight;
279 CAmount subsidy = GetBlockSubsidy(height, consensusParams);
280 if ((height > 0) && (height <= consensusParams.GetLastFoundersRewardBlockHeight())) {
281 subsidy -= subsidy/5;
283 if (std::max(0, COINBASE_MATURITY - (tipHeight - height)) > 0) {
294 mined = minedBlocks.get();
295 orphaned = mined - u->size();
299 std::string units = Params().CurrencyUnits();
300 std::cout << "- " << strprintf(_("You have mined %d blocks!"), mined) << std::endl;
302 << strprintf(_("Orphaned: %d blocks, Immature: %u %s, Mature: %u %s"),
304 FormatMoney(immature), units,
305 FormatMoney(mature), units)
310 std::cout << std::endl;
315 int printMessageBox(size_t cols)
317 boost::strict_lock_ptr<std::list<std::string>> u = messageBox.synchronize();
319 if (u->size() == 0) {
323 int lines = 2 + u->size();
324 std::cout << _("Messages:") << std::endl;
325 for (auto it = u->cbegin(); it != u->cend(); ++it) {
326 std::cout << *it << std::endl;
327 // Handle newlines and wrapped lines
330 while (j < it->size()) {
331 i = it->find('\n', j);
332 if (i == std::string::npos) {
339 lines += ((i-j) / cols);
343 std::cout << std::endl;
347 int printInitMessage()
353 std::string msg = *initMessage;
354 std::cout << _("Init message:") << " " << msg << std::endl;
355 std::cout << std::endl;
357 if (msg == _("Done loading")) {
364 void ThreadShowMetricsScreen()
366 // Make this thread recognisable as the metrics screen thread
367 RenameThread("zcash-metrics-screen");
369 // Determine whether we should render a persistent UI or rolling metrics
370 bool isTTY = isatty(STDOUT_FILENO);
371 bool isScreen = GetBoolArg("-metricsui", isTTY);
372 int64_t nRefresh = GetArg("-metricsrefreshtime", isTTY ? 1 : 600);
376 std::cout << "\e[2J";
379 std::cout << METRICS_ART << std::endl;
380 std::cout << std::endl;
383 std::cout << _("Thank you for running a Zcash node!") << std::endl;
384 std::cout << _("You're helping to strengthen the network and contributing to a social good :)") << std::endl;
385 std::cout << std::endl;
389 // Number of lines that are always displayed
393 // Get current window size
397 if (ioctl(STDOUT_FILENO, TIOCGWINSZ, &w) != -1 && w.ws_col != 0) {
403 // Erase below current position
409 bool mining = GetBoolArg("-gen", false);
415 lines += printStats(mining);
416 lines += printMiningStatus(mining);
418 lines += printMetrics(cols, mining);
419 lines += printMessageBox(cols);
420 lines += printInitMessage();
423 // Explain how to exit
424 std::cout << "[" << _("Press Ctrl+C to exit") << "] [" << _("Set 'showmetrics=0' to hide") << "]" << std::endl;
427 std::cout << "----------------------------------------" << std::endl;
430 *nNextRefresh = GetTime() + nRefresh;
431 while (GetTime() < *nNextRefresh) {
432 boost::this_thread::interruption_point();
437 // Return to the top of the updating section
438 std::cout << "\e[" << lines << "A";