Bitcoin Core  22.99.0
P2P Digital Currency
clientmodel.cpp
Go to the documentation of this file.
1 // Copyright (c) 2011-2021 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 <qt/bantablemodel.h>
8 #include <qt/guiconstants.h>
9 #include <qt/guiutil.h>
10 #include <qt/peertablemodel.h>
11 #include <qt/peertablesortproxy.h>
12 
13 #include <clientversion.h>
14 #include <interfaces/handler.h>
15 #include <interfaces/node.h>
16 #include <net.h>
17 #include <netbase.h>
18 #include <util/system.h>
19 #include <util/threadnames.h>
20 #include <util/time.h>
21 #include <validation.h>
22 
23 #include <stdint.h>
24 #include <functional>
25 
26 #include <QDebug>
27 #include <QThread>
28 #include <QTimer>
29 
32 
33 ClientModel::ClientModel(interfaces::Node& node, OptionsModel *_optionsModel, QObject *parent) :
34  QObject(parent),
35  m_node(node),
36  optionsModel(_optionsModel),
37  peerTableModel(nullptr),
38  banTableModel(nullptr),
39  m_thread(new QThread(this))
40 {
43 
46  m_peer_table_sort_proxy->setSourceModel(peerTableModel);
47 
48  banTableModel = new BanTableModel(m_node, this);
49 
50  QTimer* timer = new QTimer;
51  timer->setInterval(MODEL_UPDATE_DELAY);
52  connect(timer, &QTimer::timeout, [this] {
53  // no locking required at this point
54  // the following calls will acquire the required lock
57  });
58  connect(m_thread, &QThread::finished, timer, &QObject::deleteLater);
59  connect(m_thread, &QThread::started, [timer] { timer->start(); });
60  // move timer to thread so that polling doesn't disturb main event loop
61  timer->moveToThread(m_thread);
62  m_thread->start();
63  QTimer::singleShot(0, timer, []() {
64  util::ThreadRename("qt-clientmodl");
65  });
66 
68 }
69 
71 {
73 
74  m_thread->quit();
75  m_thread->wait();
76 }
77 
78 int ClientModel::getNumConnections(unsigned int flags) const
79 {
81 
82  if(flags == CONNECTIONS_IN)
83  connections = ConnectionDirection::In;
84  else if (flags == CONNECTIONS_OUT)
85  connections = ConnectionDirection::Out;
86  else if (flags == CONNECTIONS_ALL)
87  connections = ConnectionDirection::Both;
88 
89  return m_node.getNodeCount(connections);
90 }
91 
93 {
94  if (cachedBestHeaderHeight == -1) {
95  // make sure we initially populate the cache via a cs_main lock
96  // otherwise we need to wait for a tip update
97  int height;
98  int64_t blockTime;
99  if (m_node.getHeaderTip(height, blockTime)) {
100  cachedBestHeaderHeight = height;
101  cachedBestHeaderTime = blockTime;
102  }
103  }
104  return cachedBestHeaderHeight;
105 }
106 
108 {
109  if (cachedBestHeaderTime == -1) {
110  int height;
111  int64_t blockTime;
112  if (m_node.getHeaderTip(height, blockTime)) {
113  cachedBestHeaderHeight = height;
114  cachedBestHeaderTime = blockTime;
115  }
116  }
117  return cachedBestHeaderTime;
118 }
119 
121 {
122  if (m_cached_num_blocks == -1) {
124  }
125  return m_cached_num_blocks;
126 }
127 
129 {
130  uint256 tip{WITH_LOCK(m_cached_tip_mutex, return m_cached_tip_blocks)};
131 
132  if (!tip.IsNull()) {
133  return tip;
134  }
135 
136  // Lock order must be: first `cs_main`, then `m_cached_tip_mutex`.
137  // The following will lock `cs_main` (and release it), so we must not
138  // own `m_cached_tip_mutex` here.
139  tip = m_node.getBestBlockHash();
140 
142  // We checked that `m_cached_tip_blocks` is not null above, but then we
143  // released the mutex `m_cached_tip_mutex`, so it could have changed in the
144  // meantime. Thus, check again.
145  if (m_cached_tip_blocks.IsNull()) {
146  m_cached_tip_blocks = tip;
147  }
148  return m_cached_tip_blocks;
149 }
150 
151 void ClientModel::updateNumConnections(int numConnections)
152 {
153  Q_EMIT numConnectionsChanged(numConnections);
154 }
155 
156 void ClientModel::updateNetworkActive(bool networkActive)
157 {
158  Q_EMIT networkActiveChanged(networkActive);
159 }
160 
162 {
164 }
165 
167 {
168  if (m_node.getReindex())
169  return BlockSource::REINDEX;
170  else if (m_node.getImporting())
171  return BlockSource::DISK;
172  else if (getNumConnections() > 0)
173  return BlockSource::NETWORK;
174 
175  return BlockSource::NONE;
176 }
177 
179 {
180  return QString::fromStdString(m_node.getWarnings().translated);
181 }
182 
184 {
185  return optionsModel;
186 }
187 
189 {
190  return peerTableModel;
191 }
192 
194 {
196 }
197 
199 {
200  return banTableModel;
201 }
202 
204 {
205  return QString::fromStdString(FormatFullVersion());
206 }
207 
209 {
210  return QString::fromStdString(strSubVersion);
211 }
212 
214 {
216 }
217 
219 {
220  return QDateTime::fromSecsSinceEpoch(GetStartupTime()).toString();
221 }
222 
223 QString ClientModel::dataDir() const
224 {
226 }
227 
228 QString ClientModel::blocksDir() const
229 {
231 }
232 
234 {
236 }
237 
238 // Handlers for core signals
239 static void ShowProgress(ClientModel *clientmodel, const std::string &title, int nProgress)
240 {
241  // emits signal "showProgress"
242  bool invoked = QMetaObject::invokeMethod(clientmodel, "showProgress", Qt::QueuedConnection,
243  Q_ARG(QString, QString::fromStdString(title)),
244  Q_ARG(int, nProgress));
245  assert(invoked);
246 }
247 
248 static void NotifyNumConnectionsChanged(ClientModel *clientmodel, int newNumConnections)
249 {
250  // Too noisy: qDebug() << "NotifyNumConnectionsChanged: " + QString::number(newNumConnections);
251  bool invoked = QMetaObject::invokeMethod(clientmodel, "updateNumConnections", Qt::QueuedConnection,
252  Q_ARG(int, newNumConnections));
253  assert(invoked);
254 }
255 
256 static void NotifyNetworkActiveChanged(ClientModel *clientmodel, bool networkActive)
257 {
258  bool invoked = QMetaObject::invokeMethod(clientmodel, "updateNetworkActive", Qt::QueuedConnection,
259  Q_ARG(bool, networkActive));
260  assert(invoked);
261 }
262 
263 static void NotifyAlertChanged(ClientModel *clientmodel)
264 {
265  qDebug() << "NotifyAlertChanged";
266  bool invoked = QMetaObject::invokeMethod(clientmodel, "updateAlert", Qt::QueuedConnection);
267  assert(invoked);
268 }
269 
270 static void BannedListChanged(ClientModel *clientmodel)
271 {
272  qDebug() << QString("%1: Requesting update for peer banlist").arg(__func__);
273  bool invoked = QMetaObject::invokeMethod(clientmodel, "updateBanlist", Qt::QueuedConnection);
274  assert(invoked);
275 }
276 
277 static void BlockTipChanged(ClientModel* clientmodel, SynchronizationState sync_state, interfaces::BlockTip tip, double verificationProgress, bool fHeader)
278 {
279  if (fHeader) {
280  // cache best headers time and height to reduce future cs_main locks
281  clientmodel->cachedBestHeaderHeight = tip.block_height;
282  clientmodel->cachedBestHeaderTime = tip.block_time;
283  } else {
284  clientmodel->m_cached_num_blocks = tip.block_height;
285  WITH_LOCK(clientmodel->m_cached_tip_mutex, clientmodel->m_cached_tip_blocks = tip.block_hash;);
286  }
287 
288  // Throttle GUI notifications about (a) blocks during initial sync, and (b) both blocks and headers during reindex.
289  const bool throttle = (sync_state != SynchronizationState::POST_INIT && !fHeader) || sync_state == SynchronizationState::INIT_REINDEX;
290  const int64_t now = throttle ? GetTimeMillis() : 0;
291  int64_t& nLastUpdateNotification = fHeader ? nLastHeaderTipUpdateNotification : nLastBlockTipUpdateNotification;
292  if (throttle && now < nLastUpdateNotification + count_milliseconds(MODEL_UPDATE_DELAY)) {
293  return;
294  }
295 
296  bool invoked = QMetaObject::invokeMethod(clientmodel, "numBlocksChanged", Qt::QueuedConnection,
297  Q_ARG(int, tip.block_height),
298  Q_ARG(QDateTime, QDateTime::fromSecsSinceEpoch(tip.block_time)),
299  Q_ARG(double, verificationProgress),
300  Q_ARG(bool, fHeader),
301  Q_ARG(SynchronizationState, sync_state));
302  assert(invoked);
303  nLastUpdateNotification = now;
304 }
305 
307 {
308  // Connect signals to client
309  m_handler_show_progress = m_node.handleShowProgress(std::bind(ShowProgress, this, std::placeholders::_1, std::placeholders::_2));
314  m_handler_notify_block_tip = m_node.handleNotifyBlockTip(std::bind(BlockTipChanged, this, std::placeholders::_1, std::placeholders::_2, std::placeholders::_3, false));
315  m_handler_notify_header_tip = m_node.handleNotifyHeaderTip(std::bind(BlockTipChanged, this, std::placeholders::_1, std::placeholders::_2, std::placeholders::_3, true));
316 }
317 
319 {
320  // Disconnect signals from client
321  m_handler_show_progress->disconnect();
324  m_handler_notify_alert_changed->disconnect();
325  m_handler_banned_list_changed->disconnect();
326  m_handler_notify_block_tip->disconnect();
327  m_handler_notify_header_tip->disconnect();
328 }
329 
330 bool ClientModel::getProxyInfo(std::string& ip_port) const
331 {
332  proxyType ipv4, ipv6;
333  if (m_node.getProxy((Network) 1, ipv4) && m_node.getProxy((Network) 2, ipv6)) {
334  ip_port = ipv4.proxy.ToStringIPPort();
335  return true;
336  }
337  return false;
338 }
ClientModel::alertsChanged
void alertsChanged(const QString &warnings)
interfaces::BlockTip::block_hash
uint256 block_hash
Definition: node.h:260
GUIUtil::PathToQString
QString PathToQString(const fs::path &path)
Convert OS specific boost path to QString through UTF-8.
Definition: guiutil.cpp:665
ClientModel::subscribeToCoreSignals
void subscribeToCoreSignals()
Definition: clientmodel.cpp:306
interfaces::Node::handleShowProgress
virtual std::unique_ptr< Handler > handleShowProgress(ShowProgressFn fn)=0
CONNECTIONS_IN
@ CONNECTIONS_IN
Definition: clientmodel.h:41
ClientModel::m_handler_notify_alert_changed
std::unique_ptr< interfaces::Handler > m_handler_notify_alert_changed
Definition: clientmodel.h:95
interfaces::Node::getNumBlocks
virtual int getNumBlocks()=0
Get num blocks.
assert
assert(!tx.IsCoinBase())
ClientModel::numConnectionsChanged
void numConnectionsChanged(int count)
CONNECTIONS_OUT
@ CONNECTIONS_OUT
Definition: clientmodel.h:42
ClientModel::mempoolSizeChanged
void mempoolSizeChanged(long count, size_t mempoolSizeInBytes)
ConnectionDirection::Out
@ Out
interfaces::Node::getProxy
virtual bool getProxy(Network net, proxyType &proxy_info)=0
Get proxy.
NotifyAlertChanged
static void NotifyAlertChanged(ClientModel *clientmodel)
Definition: clientmodel.cpp:263
interfaces::Node::handleNotifyNetworkActiveChanged
virtual std::unique_ptr< Handler > handleNotifyNetworkActiveChanged(NotifyNetworkActiveChangedFn fn)=0
ClientModel::getNumConnections
int getNumConnections(unsigned int flags=CONNECTIONS_ALL) const
Return number of connections, default is in- and outbound (total)
Definition: clientmodel.cpp:78
flags
int flags
Definition: bitcoin-tx.cpp:529
ArgsManager::GetDataDirNet
const fs::path & GetDataDirNet() const
Get data directory path with appended network identifier.
Definition: system.h:304
ArgsManager::GetBlocksDirPath
const fs::path & GetBlocksDirPath() const
Get blocks directory path.
Definition: system.cpp:397
ClientModel::isReleaseVersion
bool isReleaseVersion() const
Definition: clientmodel.cpp:213
ShowProgress
static void ShowProgress(ClientModel *clientmodel, const std::string &title, int nProgress)
Definition: clientmodel.cpp:239
interfaces::Node::handleNotifyHeaderTip
virtual std::unique_ptr< Handler > handleNotifyHeaderTip(NotifyHeaderTipFn fn)=0
CLIENT_VERSION_IS_RELEASE
#define CLIENT_VERSION_IS_RELEASE
Definition: bitcoin-config.h:18
interfaces::Node::handleNotifyBlockTip
virtual std::unique_ptr< Handler > handleNotifyBlockTip(NotifyBlockTipFn fn)=0
m_node
node::NodeContext m_node
Definition: bitcoin-gui.cpp:36
interfaces::Node::getReindex
virtual bool getReindex()=0
Get reindex.
ConnectionDirection::Both
@ Both
ClientModel::getBlockSource
enum BlockSource getBlockSource() const
Returns enum BlockSource of the current importing/syncing state.
Definition: clientmodel.cpp:166
handler.h
ClientModel::peerTableSortProxy
PeerTableSortProxy * peerTableSortProxy()
Definition: clientmodel.cpp:193
ClientModel::blocksDir
QString blocksDir() const
Definition: clientmodel.cpp:228
ClientModel::m_handler_notify_num_connections_changed
std::unique_ptr< interfaces::Handler > m_handler_notify_num_connections_changed
Definition: clientmodel.h:93
BlockSource::DISK
@ DISK
WITH_LOCK
#define WITH_LOCK(cs, code)
Run code while locking a mutex.
Definition: sync.h:270
peertablesortproxy.h
interfaces::Node::handleNotifyAlertChanged
virtual std::unique_ptr< Handler > handleNotifyAlertChanged(NotifyAlertChangedFn fn)=0
clientversion.h
GetStartupTime
int64_t GetStartupTime()
Definition: system.cpp:1358
interfaces::Node::getNodeCount
virtual size_t getNodeCount(ConnectionDirection flags)=0
Get number of connections.
CONNECTIONS_ALL
@ CONNECTIONS_ALL
Definition: clientmodel.h:43
ClientModel::getStatusBarWarnings
QString getStatusBarWarnings() const
Return warnings to be displayed in status bar.
Definition: clientmodel.cpp:178
Network
Network
A network type.
Definition: netaddress.h:45
BanTableModel
Qt model providing information about connected peers, similar to the "getpeerinfo" RPC call.
Definition: bantablemodel.h:43
ClientModel::banTableModel
BanTableModel * banTableModel
Definition: clientmodel.h:102
interfaces::Node::handleBannedListChanged
virtual std::unique_ptr< Handler > handleBannedListChanged(BannedListChangedFn fn)=0
proxyType
Definition: netbase.h:48
CService::ToStringIPPort
std::string ToStringIPPort() const
Definition: netaddress.cpp:1039
ClientModel::updateNetworkActive
void updateNetworkActive(bool networkActive)
Definition: clientmodel.cpp:156
ClientModel::m_handler_notify_block_tip
std::unique_ptr< interfaces::Handler > m_handler_notify_block_tip
Definition: clientmodel.h:97
interfaces::BlockTip::block_time
int64_t block_time
Definition: node.h:259
nLastHeaderTipUpdateNotification
static int64_t nLastHeaderTipUpdateNotification
Definition: clientmodel.cpp:30
OptionsModel
Interface from Qt to configuration data structure for Bitcoin client.
Definition: optionsmodel.h:38
ClientModel::getOptionsModel
OptionsModel * getOptionsModel()
Definition: clientmodel.cpp:183
ConnectionDirection::In
@ In
interfaces::Node::getHeaderTip
virtual bool getHeaderTip(int &height, int64_t &block_time)=0
Get header tip height and time.
ClientModel::unsubscribeFromCoreSignals
void unsubscribeFromCoreSignals()
Definition: clientmodel.cpp:318
ClientModel::m_handler_notify_network_active_changed
std::unique_ptr< interfaces::Handler > m_handler_notify_network_active_changed
Definition: clientmodel.h:94
ClientModel::getPeerTableModel
PeerTableModel * getPeerTableModel()
Definition: clientmodel.cpp:188
BlockSource::REINDEX
@ REINDEX
interfaces::BlockTip::block_height
int block_height
Definition: node.h:258
ClientModel::getHeaderTipHeight
int getHeaderTipHeight() const
Definition: clientmodel.cpp:92
ClientModel::getProxyInfo
bool getProxyInfo(std::string &ip_port) const
Definition: clientmodel.cpp:330
node.h
ClientModel::bytesChanged
void bytesChanged(quint64 totalBytesIn, quint64 totalBytesOut)
util::ThreadRename
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:57
BlockSource::NETWORK
@ NETWORK
MODEL_UPDATE_DELAY
static constexpr auto MODEL_UPDATE_DELAY
Definition: guiconstants.h:14
time.h
ClientModel::ClientModel
ClientModel(interfaces::Node &node, OptionsModel *optionsModel, QObject *parent=nullptr)
Definition: clientmodel.cpp:33
BannedListChanged
static void BannedListChanged(ClientModel *clientmodel)
Definition: clientmodel.cpp:270
SynchronizationState::INIT_REINDEX
@ INIT_REINDEX
ClientModel::getNumBlocks
int getNumBlocks() const
Definition: clientmodel.cpp:120
guiutil.h
ClientModel::formatFullVersion
QString formatFullVersion() const
Definition: clientmodel.cpp:203
ClientModel::cachedBestHeaderTime
std::atomic< int64_t > cachedBestHeaderTime
Definition: clientmodel.h:84
interfaces::Node::handleNotifyNumConnectionsChanged
virtual std::unique_ptr< Handler > handleNotifyNumConnectionsChanged(NotifyNumConnectionsChangedFn fn)=0
bilingual_str::translated
std::string translated
Definition: translation.h:18
uint256
256-bit opaque blob.
Definition: uint256.h:126
ClientModel::peerTableModel
PeerTableModel * peerTableModel
Definition: clientmodel.h:100
ClientModel::optionsModel
OptionsModel * optionsModel
Definition: clientmodel.h:99
BlockSource::NONE
@ NONE
ClientModel::m_node
interfaces::Node & m_node
Definition: clientmodel.h:88
PeerTableModel
Qt model providing information about connected peers, similar to the "getpeerinfo" RPC call.
Definition: peertablemodel.h:38
ClientModel::updateNumConnections
void updateNumConnections(int numConnections)
Definition: clientmodel.cpp:151
gArgs
ArgsManager gArgs
Definition: system.cpp:87
interfaces::Node
Top-level interface for a bitcoin node (bitcoind process).
Definition: node.h:68
ClientModel::updateBanlist
void updateBanlist()
Definition: clientmodel.cpp:233
system.h
ClientModel
Model for Bitcoin network client.
Definition: clientmodel.h:47
BlockTipChanged
static void BlockTipChanged(ClientModel *clientmodel, SynchronizationState sync_state, interfaces::BlockTip tip, double verificationProgress, bool fHeader)
Definition: clientmodel.cpp:277
strSubVersion
std::string strSubVersion
Subversion as sent to the P2P network in version messages.
Definition: net.cpp:119
guiconstants.h
nLastBlockTipUpdateNotification
static int64_t nLastBlockTipUpdateNotification
Definition: clientmodel.cpp:31
ClientModel::formatSubVersion
QString formatSubVersion() const
Definition: clientmodel.cpp:208
ClientModel::m_handler_show_progress
std::unique_ptr< interfaces::Handler > m_handler_show_progress
Definition: clientmodel.h:92
ClientModel::m_peer_table_sort_proxy
PeerTableSortProxy * m_peer_table_sort_proxy
Definition: clientmodel.h:101
LOCK
#define LOCK(cs)
Definition: sync.h:226
ClientModel::m_handler_notify_header_tip
std::unique_ptr< interfaces::Handler > m_handler_notify_header_tip
Definition: clientmodel.h:98
interfaces::Node::getMempoolDynamicUsage
virtual size_t getMempoolDynamicUsage()=0
Get mempool dynamic usage.
ClientModel::cachedBestHeaderHeight
std::atomic< int > cachedBestHeaderHeight
Definition: clientmodel.h:83
ClientModel::formatClientStartupTime
QString formatClientStartupTime() const
Definition: clientmodel.cpp:218
PeerTableSortProxy
Definition: peertablesortproxy.h:14
count_milliseconds
constexpr int64_t count_milliseconds(std::chrono::milliseconds t)
Definition: time.h:30
NotifyNumConnectionsChanged
static void NotifyNumConnectionsChanged(ClientModel *clientmodel, int newNumConnections)
Definition: clientmodel.cpp:248
ClientModel::~ClientModel
~ClientModel()
Definition: clientmodel.cpp:70
ClientModel::m_cached_num_blocks
std::atomic< int > m_cached_num_blocks
Definition: clientmodel.h:85
interfaces::Node::getWarnings
virtual bilingual_str getWarnings()=0
Get warnings.
ClientModel::dataDir
QString dataDir() const
Definition: clientmodel.cpp:223
node
Definition: init.h:22
SynchronizationState
SynchronizationState
Current sync state passed to tip changed callbacks.
Definition: validation.h:105
bantablemodel.h
netbase.h
interfaces::Node::getImporting
virtual bool getImporting()=0
Get importing.
BlockSource
BlockSource
Definition: clientmodel.h:32
FormatFullVersion
std::string FormatFullVersion()
Definition: clientversion.cpp:50
ConnectionDirection::None
@ None
ConnectionDirection
ConnectionDirection
Definition: netbase.h:32
peertablemodel.h
interfaces::Node::getTotalBytesRecv
virtual int64_t getTotalBytesRecv()=0
Get total bytes recv.
interfaces::Node::getBestBlockHash
virtual uint256 getBestBlockHash()=0
Get best block hash.
interfaces::Node::getMempoolSize
virtual size_t getMempoolSize()=0
Get mempool size.
ClientModel::m_thread
QThread *const m_thread
A thread to interact with m_node asynchronously.
Definition: clientmodel.h:105
ClientModel::getBestBlockHash
uint256 getBestBlockHash()
Definition: clientmodel.cpp:128
threadnames.h
ClientModel::m_cached_tip_mutex
Mutex m_cached_tip_mutex
Definition: clientmodel.h:87
ClientModel::m_handler_banned_list_changed
std::unique_ptr< interfaces::Handler > m_handler_banned_list_changed
Definition: clientmodel.h:96
NotifyNetworkActiveChanged
static void NotifyNetworkActiveChanged(ClientModel *clientmodel, bool networkActive)
Definition: clientmodel.cpp:256
interfaces::BlockTip
Block tip (could be a header or not, depends on the subscribed signal).
Definition: node.h:257
interfaces::Node::getTotalBytesSent
virtual int64_t getTotalBytesSent()=0
Get total bytes sent.
BanTableModel::refresh
void refresh()
Definition: bantablemodel.cpp:166
GetTimeMillis
int64_t GetTimeMillis()
Returns the system time (not mockable)
Definition: time.cpp:117
SynchronizationState::POST_INIT
@ POST_INIT
ClientModel::networkActiveChanged
void networkActiveChanged(bool networkActive)
clientmodel.h
ClientModel::updateAlert
void updateAlert()
Definition: clientmodel.cpp:161
proxyType::proxy
CService proxy
Definition: netbase.h:56
ClientModel::getHeaderTipTime
int64_t getHeaderTipTime() const
Definition: clientmodel.cpp:107
ClientModel::getBanTableModel
BanTableModel * getBanTableModel()
Definition: clientmodel.cpp:198