Bitcoin ABC 0.30.12
P2P Digital Currency
clientmodel.cpp
Go to the documentation of this file.
1// Copyright (c) 2011-2016 The Bitcoin Core developers
2// Distributed under the MIT software license, see the accompanying
3// file COPYING or http://www.opensource.org/licenses/mit-license.php.
4
5#include <qt/clientmodel.h>
6
7#include <clientversion.h>
8#include <common/args.h>
9#include <common/system.h>
10#include <config.h>
11#include <interfaces/handler.h>
12#include <interfaces/node.h>
13#include <net.h>
14#include <netbase.h>
15#include <qt/bantablemodel.h>
16#include <qt/guiconstants.h>
17#include <qt/guiutil.h>
18#include <qt/peertablemodel.h>
19#include <util/threadnames.h>
20#include <validation.h>
21
22#include <QDebug>
23#include <QMetaObject>
24#include <QThread>
25#include <QTimer>
26
27#include <cstdint>
28
31
33 QObject *parent)
34 : QObject(parent), m_node(node), optionsModel(_optionsModel),
35 peerTableModel(nullptr), banTableModel(nullptr),
36 m_thread(new QThread(this)) {
41
42 QTimer *timer = new QTimer;
43 timer->setInterval(MODEL_UPDATE_DELAY);
44 connect(timer, &QTimer::timeout, [this] {
45 // no locking required at this point
46 // the following calls will acquire the required lock
51 });
52 connect(m_thread, &QThread::finished, timer, &QObject::deleteLater);
53 connect(m_thread, &QThread::started, [timer] { timer->start(); });
54 // move timer to thread so that polling doesn't disturb main event loop
55 timer->moveToThread(m_thread);
56 m_thread->start();
57 QTimer::singleShot(0, timer, []() { util::ThreadRename("qt-clientmodl"); });
58
60}
61
64
65 m_thread->quit();
66 m_thread->wait();
67}
68
70 stop();
71}
72
75
76 if (flags == CONNECTIONS_IN) {
77 connections = ConnectionDirection::In;
78 } else if (flags == CONNECTIONS_OUT) {
79 connections = ConnectionDirection::Out;
80 } else if (flags == CONNECTIONS_ALL) {
81 connections = ConnectionDirection::Both;
82 }
83
84 return m_node.getNodeCount(connections);
85}
86
88 if (cachedBestHeaderHeight == -1) {
89 // make sure we initially populate the cache via a cs_main lock
90 // otherwise we need to wait for a tip update
91 int height;
92 int64_t blockTime;
93 if (m_node.getHeaderTip(height, blockTime)) {
95 cachedBestHeaderTime = blockTime;
96 }
97 }
99}
100
102 if (cachedBestHeaderTime == -1) {
103 int height;
104 int64_t blockTime;
105 if (m_node.getHeaderTip(height, blockTime)) {
106 cachedBestHeaderHeight = height;
107 cachedBestHeaderTime = blockTime;
108 }
109 }
111}
112
114 if (m_cached_num_blocks == -1) {
116 }
117 return m_cached_num_blocks;
118}
119
121 BlockHash tip{WITH_LOCK(m_cached_tip_mutex, return m_cached_tip_blocks)};
122
123 if (!tip.IsNull()) {
124 return tip;
125 }
126
127 // Lock order must be: first `cs_main`, then `m_cached_tip_mutex`.
128 // The following will lock `cs_main` (and release it), so we must not
129 // own `m_cached_tip_mutex` here.
130 tip = m_node.getBestBlockHash();
131
133 // We checked that `m_cached_tip_blocks` is not null above, but then we
134 // released the mutex `m_cached_tip_mutex`, so it could have changed in the
135 // meantime. Thus, check again.
136 if (m_cached_tip_blocks.IsNull()) {
137 m_cached_tip_blocks = tip;
138 }
139 return m_cached_tip_blocks;
140}
141
143 if (m_node.isLoadingBlocks()) {
144 return BlockSource::DISK;
145 }
146 if (getNumConnections() > 0) {
148 }
149 return BlockSource::NONE;
150}
151
153 return QString::fromStdString(m_node.getWarnings().translated);
154}
155
157 return optionsModel;
158}
159
161 return peerTableModel;
162}
163
165 return banTableModel;
166}
167
169 return QString::fromStdString(FormatFullVersion());
170}
171
173 return QString::fromStdString(userAgent(GetConfig()));
174}
175
177 return CLIENT_VERSION_IS_RELEASE;
178}
179
181 return QDateTime::fromTime_t(GetStartupTime()).toString();
182}
183
184QString ClientModel::dataDir() const {
186}
187
188QString ClientModel::blocksDir() const {
190}
191
194 double verification_progress, SyncType synctype)
195 EXCLUSIVE_LOCKS_REQUIRED(!m_cached_tip_mutex) {
196 if (synctype == SyncType::HEADER_SYNC) {
197 // cache best headers time and height to reduce future cs_main locks
198 cachedBestHeaderHeight = tip.block_height;
199 cachedBestHeaderTime = tip.block_time;
200 } else if (synctype == SyncType::BLOCK_SYNC) {
201 m_cached_num_blocks = tip.block_height;
202 WITH_LOCK(m_cached_tip_mutex, m_cached_tip_blocks = tip.block_hash;);
203 }
204
205 // Throttle GUI notifications about (a) blocks during initial sync, and (b)
206 // both blocks and headers during reindex.
207 const bool throttle = (sync_state != SynchronizationState::POST_INIT &&
208 synctype == SyncType::BLOCK_SYNC) ||
210 const int64_t now = throttle ? GetTimeMillis() : 0;
211 int64_t &nLastUpdateNotification = synctype != SyncType::BLOCK_SYNC
214 if (throttle && now < nLastUpdateNotification + MODEL_UPDATE_DELAY) {
215 return;
216 }
217
218 Q_EMIT numBlocksChanged(tip.block_height,
219 QDateTime::fromSecsSinceEpoch(tip.block_time),
220 verification_progress, synctype, sync_state);
221 nLastUpdateNotification = now;
222}
223
226 [this](const std::string &title, int progress,
227 [[maybe_unused]] bool resume_possible) {
228 Q_EMIT showProgress(QString::fromStdString(title), progress);
229 }));
231 [this](int new_num_connections) {
232 Q_EMIT numConnectionsChanged(new_num_connections);
233 }));
234 m_event_handlers.emplace_back(
235 m_node.handleNotifyNetworkActiveChanged([this](bool network_active) {
236 Q_EMIT networkActiveChanged(network_active);
237 }));
238 m_event_handlers.emplace_back(m_node.handleNotifyAlertChanged([this]() {
239 qDebug() << "ClientModel: NotifyAlertChanged";
240 Q_EMIT alertsChanged(getStatusBarWarnings());
241 }));
242 m_event_handlers.emplace_back(m_node.handleBannedListChanged([this]() {
243 qDebug() << "ClienModel: Requesting update for peer banlist";
244 QMetaObject::invokeMethod(banTableModel,
245 [this] { banTableModel->refresh(); });
246 }));
247 m_event_handlers.emplace_back(m_node.handleNotifyBlockTip(
248 [this](SynchronizationState sync_state, interfaces::BlockTip tip,
249 double verification_progress) {
250 TipChanged(sync_state, tip, verification_progress,
251 SyncType::BLOCK_SYNC);
252 }));
253 m_event_handlers.emplace_back(m_node.handleNotifyHeaderTip(
254 [this](SynchronizationState sync_state, interfaces::BlockTip tip,
255 bool presync) {
256 TipChanged(sync_state, tip, /*verification_progress=*/0.0,
257 presync ? SyncType::HEADER_PRESYNC
258 : SyncType::HEADER_SYNC);
259 }));
260}
261
263 m_event_handlers.clear();
264}
265
266bool ClientModel::getProxyInfo(std::string &ip_port) const {
267 proxyType ipv4, ipv6;
268 if (m_node.getProxy((Network)1, ipv4) &&
269 m_node.getProxy((Network)2, ipv6)) {
270 ip_port = ipv4.proxy.ToStringIPPort();
271 return true;
272 }
273 return false;
274}
ArgsManager gArgs
Definition: args.cpp:38
int flags
Definition: bitcoin-tx.cpp:541
fs::path GetDataDirNet() const
Get data directory path with appended network identifier.
Definition: args.h:215
fs::path GetBlocksDirPath() const
Get blocks directory path.
Definition: args.cpp:289
Qt model providing information about connected peers, similar to the "getpeerinfo" RPC call.
Definition: bantablemodel.h:42
std::string ToStringIPPort() const
void bytesChanged(quint64 totalBytesIn, quint64 totalBytesOut)
QString blocksDir() const
QString getStatusBarWarnings() const
Return warnings to be displayed in status bar.
std::vector< std::unique_ptr< interfaces::Handler > > m_event_handlers
Definition: clientmodel.h:96
int getHeaderTipHeight() const
Definition: clientmodel.cpp:87
std::atomic< int64_t > cachedBestHeaderTime
Definition: clientmodel.h:88
interfaces::Node & m_node
Definition: clientmodel.h:95
Mutex m_cached_tip_mutex
Definition: clientmodel.h:91
PeerTableModel * getPeerTableModel()
std::atomic< int > cachedBestHeaderHeight
Definition: clientmodel.h:87
BlockHash getBestBlockHash() EXCLUSIVE_LOCKS_REQUIRED(!m_cached_tip_mutex)
int getNumConnections(NumConnections flags=CONNECTIONS_ALL) const
Return number of connections, default is in- and outbound (total)
Definition: clientmodel.cpp:73
BlockSource getBlockSource() const
Returns the block source of the current importing/syncing state.
int getNumBlocks() const
int64_t getHeaderTipTime() const
QString formatClientStartupTime() const
ClientModel(interfaces::Node &node, OptionsModel *optionsModel, QObject *parent=nullptr)
Definition: clientmodel.cpp:32
void TipChanged(SynchronizationState sync_state, interfaces::BlockTip tip, double verification_progress, SyncType synctype)
OptionsModel * optionsModel
Definition: clientmodel.h:97
BanTableModel * banTableModel
Definition: clientmodel.h:99
QThread *const m_thread
A thread to interact with m_node asynchronously.
Definition: clientmodel.h:102
BanTableModel * getBanTableModel()
void unsubscribeFromCoreSignals()
QString dataDir() const
std::atomic< int > m_cached_num_blocks
Definition: clientmodel.h:89
OptionsModel * getOptionsModel()
QString formatFullVersion() const
PeerTableModel * peerTableModel
Definition: clientmodel.h:98
bool getProxyInfo(std::string &ip_port) const
QString formatSubVersion() const
void mempoolSizeChanged(long count, size_t mempoolSizeInBytes)
bool isReleaseVersion() const
void subscribeToCoreSignals()
Interface from Qt to configuration data structure for Bitcoin client.
Definition: optionsmodel.h:48
Qt model providing information about connected peers, similar to the "getpeerinfo" RPC call.
Top-level interface for a bitcoin node (bitcoind process).
Definition: node.h:59
virtual std::unique_ptr< Handler > handleShowProgress(ShowProgressFn fn)=0
virtual bilingual_str getWarnings()=0
Get warnings.
virtual std::unique_ptr< Handler > handleNotifyAlertChanged(NotifyAlertChangedFn fn)=0
virtual bool getProxy(Network net, proxyType &proxy_info)=0
Get proxy.
virtual BlockHash getBestBlockHash()=0
Get best block hash.
virtual size_t getMempoolSize()=0
Get mempool size.
virtual bool isLoadingBlocks()=0
Is loading blocks.
virtual size_t getNodeCount(ConnectionDirection flags)=0
Get number of connections.
virtual bool getHeaderTip(int &height, int64_t &block_time)=0
Get header tip height and time.
virtual int64_t getTotalBytesRecv()=0
Get total bytes recv.
virtual std::unique_ptr< Handler > handleBannedListChanged(BannedListChangedFn fn)=0
virtual std::unique_ptr< Handler > handleNotifyNetworkActiveChanged(NotifyNetworkActiveChangedFn fn)=0
virtual int64_t getTotalBytesSent()=0
Get total bytes sent.
virtual size_t getMempoolDynamicUsage()=0
Get mempool dynamic usage.
virtual int getNumBlocks()=0
Get num blocks.
virtual std::unique_ptr< Handler > handleNotifyNumConnectionsChanged(NotifyNumConnectionsChangedFn fn)=0
CService proxy
Definition: netbase.h:60
static int64_t nLastHeaderTipUpdateNotification
Definition: clientmodel.cpp:29
static int64_t nLastBlockTipUpdateNotification
Definition: clientmodel.cpp:30
SyncType
Definition: clientmodel.h:40
BlockSource
Definition: clientmodel.h:34
std::string FormatFullVersion()
const Config & GetConfig()
Definition: config.cpp:40
static const int MODEL_UPDATE_DELAY
Definition: guiconstants.h:11
QString boostPathToQString(const fs::path &path)
Convert OS specific boost path to QString through UTF-8.
Definition: guiutil.cpp:785
Definition: init.h:28
void ThreadRename(std::string &&)
Rename a thread both in terms of an internal (in-memory) name as well as its system thread name.
Definition: threadnames.cpp:48
std::string userAgent(const Config &config)
Definition: net.cpp:3455
Network
A network type.
Definition: netaddress.h:44
ConnectionDirection
Definition: netbase.h:32
NodeContext & m_node
Definition: interfaces.cpp:788
A BlockHash is a unqiue identifier for a block.
Definition: blockhash.h:13
std::string translated
Definition: translation.h:19
Block tip (could be a header or not, depends on the subscribed signal).
Definition: node.h:270
#define LOCK(cs)
Definition: sync.h:306
#define WITH_LOCK(cs, code)
Run code while locking a mutex.
Definition: sync.h:357
int64_t GetStartupTime()
Definition: system.cpp:116
#define EXCLUSIVE_LOCKS_REQUIRED(...)
Definition: threadsafety.h:56
int64_t GetTimeMillis()
Returns the system time (not mockable)
Definition: time.cpp:101
SynchronizationState
Current sync state passed to tip changed callbacks.
Definition: validation.h:114