Bitcoin ABC  0.26.3
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 <config.h>
9 #include <interfaces/handler.h>
10 #include <interfaces/node.h>
11 #include <net.h>
12 #include <netbase.h>
13 #include <qt/bantablemodel.h>
14 #include <qt/guiconstants.h>
15 #include <qt/guiutil.h>
16 #include <qt/peertablemodel.h>
17 #include <util/system.h>
18 #include <util/threadnames.h>
19 #include <validation.h>
20 
21 #include <QDebug>
22 #include <QThread>
23 #include <QTimer>
24 
25 #include <cstdint>
26 #include <functional>
27 
30 
32  QObject *parent)
33  : QObject(parent), m_node(node), optionsModel(_optionsModel),
34  peerTableModel(nullptr), banTableModel(nullptr),
35  m_thread(new QThread(this)) {
39  banTableModel = new BanTableModel(m_node, this);
40 
41  QTimer *timer = new QTimer;
42  timer->setInterval(MODEL_UPDATE_DELAY);
43  connect(timer, &QTimer::timeout, [this] {
44  // no locking required at this point
45  // the following calls will acquire the required lock
50  });
51  connect(m_thread, &QThread::finished, timer, &QObject::deleteLater);
52  connect(m_thread, &QThread::started, [timer] { timer->start(); });
53  // move timer to thread so that polling doesn't disturb main event loop
54  timer->moveToThread(m_thread);
55  m_thread->start();
56  QTimer::singleShot(0, timer, []() { util::ThreadRename("qt-clientmodl"); });
57 
59 }
60 
63 
64  m_thread->quit();
65  m_thread->wait();
66 }
67 
70 
71  if (flags == CONNECTIONS_IN) {
72  connections = CConnman::CONNECTIONS_IN;
73  } else if (flags == CONNECTIONS_OUT) {
74  connections = CConnman::CONNECTIONS_OUT;
75  } else if (flags == CONNECTIONS_ALL) {
76  connections = CConnman::CONNECTIONS_ALL;
77  }
78 
79  return m_node.getNodeCount(connections);
80 }
81 
83  if (cachedBestHeaderHeight == -1) {
84  // make sure we initially populate the cache via a cs_main lock
85  // otherwise we need to wait for a tip update
86  int height;
87  int64_t blockTime;
88  if (m_node.getHeaderTip(height, blockTime)) {
89  cachedBestHeaderHeight = height;
90  cachedBestHeaderTime = blockTime;
91  }
92  }
94 }
95 
97  if (cachedBestHeaderTime == -1) {
98  int height;
99  int64_t blockTime;
100  if (m_node.getHeaderTip(height, blockTime)) {
101  cachedBestHeaderHeight = height;
102  cachedBestHeaderTime = blockTime;
103  }
104  }
105  return cachedBestHeaderTime;
106 }
107 
109  if (m_cached_num_blocks == -1) {
111  }
112  return m_cached_num_blocks;
113 }
114 
116  BlockHash tip{WITH_LOCK(m_cached_tip_mutex, return m_cached_tip_blocks)};
117 
118  if (!tip.IsNull()) {
119  return tip;
120  }
121 
122  // Lock order must be: first `cs_main`, then `m_cached_tip_mutex`.
123  // The following will lock `cs_main` (and release it), so we must not
124  // own `m_cached_tip_mutex` here.
125  tip = m_node.getBestBlockHash();
126 
128  // We checked that `m_cached_tip_blocks` is not null above, but then we
129  // released the mutex `m_cached_tip_mutex`, so it could have changed in the
130  // meantime. Thus, check again.
131  if (m_cached_tip_blocks.IsNull()) {
132  m_cached_tip_blocks = tip;
133  }
134  return m_cached_tip_blocks;
135 }
136 
137 void ClientModel::updateNumConnections(int numConnections) {
138  Q_EMIT numConnectionsChanged(numConnections);
139 }
140 
141 void ClientModel::updateNetworkActive(bool networkActive) {
142  Q_EMIT networkActiveChanged(networkActive);
143 }
144 
147 }
148 
150  if (m_node.getReindex()) {
151  return BlockSource::REINDEX;
152  } else if (m_node.getImporting()) {
153  return BlockSource::DISK;
154  } else if (getNumConnections() > 0) {
155  return BlockSource::NETWORK;
156  }
157 
158  return BlockSource::NONE;
159 }
160 
162  return QString::fromStdString(m_node.getWarnings().translated);
163 }
164 
166  return optionsModel;
167 }
168 
170  return peerTableModel;
171 }
172 
174  return banTableModel;
175 }
176 
178  return QString::fromStdString(FormatFullVersion());
179 }
180 
182  return QString::fromStdString(userAgent(GetConfig()));
183 }
184 
186  return CLIENT_VERSION_IS_RELEASE;
187 }
188 
190  return QDateTime::fromTime_t(GetStartupTime()).toString();
191 }
192 
193 QString ClientModel::dataDir() const {
195 }
196 
197 QString ClientModel::blocksDir() const {
199 }
200 
203 }
204 
205 // Handlers for core signals
206 static void ShowProgress(ClientModel *clientmodel, const std::string &title,
207  int nProgress) {
208  // emits signal "showProgress"
209  bool invoked = QMetaObject::invokeMethod(
210  clientmodel, "showProgress", Qt::QueuedConnection,
211  Q_ARG(QString, QString::fromStdString(title)), Q_ARG(int, nProgress));
212  assert(invoked);
213 }
214 
215 static void NotifyNumConnectionsChanged(ClientModel *clientmodel,
216  int newNumConnections) {
217  // Too noisy: qDebug() << "NotifyNumConnectionsChanged: " +
218  // QString::number(newNumConnections);
219  bool invoked = QMetaObject::invokeMethod(
220  clientmodel, "updateNumConnections", Qt::QueuedConnection,
221  Q_ARG(int, newNumConnections));
222  assert(invoked);
223 }
224 
225 static void NotifyNetworkActiveChanged(ClientModel *clientmodel,
226  bool networkActive) {
227  bool invoked = QMetaObject::invokeMethod(clientmodel, "updateNetworkActive",
228  Qt::QueuedConnection,
229  Q_ARG(bool, networkActive));
230  assert(invoked);
231 }
232 
233 static void NotifyAlertChanged(ClientModel *clientmodel) {
234  qDebug() << "NotifyAlertChanged";
235  bool invoked = QMetaObject::invokeMethod(clientmodel, "updateAlert",
236  Qt::QueuedConnection);
237  assert(invoked);
238 }
239 
240 static void BannedListChanged(ClientModel *clientmodel) {
241  qDebug() << QString("%1: Requesting update for peer banlist").arg(__func__);
242  bool invoked = QMetaObject::invokeMethod(clientmodel, "updateBanlist",
243  Qt::QueuedConnection);
244  assert(invoked);
245 }
246 
247 static void BlockTipChanged(ClientModel *clientmodel,
248  SynchronizationState sync_state,
250  double verificationProgress, bool fHeader) {
251  if (fHeader) {
252  // cache best headers time and height to reduce future cs_main locks
253  clientmodel->cachedBestHeaderHeight = tip.block_height;
254  clientmodel->cachedBestHeaderTime = tip.block_time;
255  } else {
256  clientmodel->m_cached_num_blocks = tip.block_height;
257  WITH_LOCK(clientmodel->m_cached_tip_mutex,
258  clientmodel->m_cached_tip_blocks = tip.block_hash;);
259  }
260 
261  // Throttle GUI notifications about (a) blocks during initial sync, and (b)
262  // both blocks and headers during reindex.
263  const bool throttle =
264  (sync_state != SynchronizationState::POST_INIT && !fHeader) ||
266  const int64_t now = throttle ? GetTimeMillis() : 0;
267  int64_t &nLastUpdateNotification = fHeader
270  if (throttle && now < nLastUpdateNotification + MODEL_UPDATE_DELAY) {
271  return;
272  }
273 
274  bool invoked = QMetaObject::invokeMethod(
275  clientmodel, "numBlocksChanged", Qt::QueuedConnection,
276  Q_ARG(int, tip.block_height),
277  Q_ARG(QDateTime, QDateTime::fromTime_t(tip.block_time)),
278  Q_ARG(double, verificationProgress), Q_ARG(bool, fHeader),
279  Q_ARG(SynchronizationState, sync_state));
280  assert(invoked);
281  nLastUpdateNotification = now;
282 }
283 
285  // Connect signals to client
287  ShowProgress, this, std::placeholders::_1, std::placeholders::_2));
290  NotifyNumConnectionsChanged, this, std::placeholders::_1));
293  std::bind(NotifyNetworkActiveChanged, this, std::placeholders::_1));
299  std::bind(BlockTipChanged, this, std::placeholders::_1,
300  std::placeholders::_2, std::placeholders::_3, false));
302  std::bind(BlockTipChanged, this, std::placeholders::_1,
303  std::placeholders::_2, std::placeholders::_3, true));
304 }
305 
307  // Disconnect signals from client
308  m_handler_show_progress->disconnect();
311  m_handler_notify_alert_changed->disconnect();
312  m_handler_banned_list_changed->disconnect();
313  m_handler_notify_block_tip->disconnect();
314  m_handler_notify_header_tip->disconnect();
315 }
316 
317 bool ClientModel::getProxyInfo(std::string &ip_port) const {
318  proxyType ipv4, ipv6;
319  if (m_node.getProxy((Network)1, ipv4) &&
320  m_node.getProxy((Network)2, ipv6)) {
321  ip_port = ipv4.proxy.ToStringIPPort();
322  return true;
323  }
324  return false;
325 }
int flags
Definition: bitcoin-tx.cpp:534
const fs::path & GetBlocksDirPath() const
Get blocks directory path.
Definition: system.cpp:405
const fs::path & GetDataDirNet() const
Get data directory path with appended network identifier.
Definition: system.h:257
Qt model providing information about connected peers, similar to the "getpeerinfo" RPC call.
Definition: bantablemodel.h:42
NumConnections
Definition: net.h:925
@ CONNECTIONS_IN
Definition: net.h:927
@ CONNECTIONS_NONE
Definition: net.h:926
@ CONNECTIONS_ALL
Definition: net.h:929
@ CONNECTIONS_OUT
Definition: net.h:928
std::string ToStringIPPort() const
Model for Bitcoin network client.
Definition: clientmodel.h:36
void updateAlert()
std::unique_ptr< interfaces::Handler > m_handler_banned_list_changed
Definition: clientmodel.h:93
void bytesChanged(quint64 totalBytesIn, quint64 totalBytesOut)
void updateBanlist()
QString blocksDir() const
QString getStatusBarWarnings() const
Return warnings to be displayed in status bar.
int getHeaderTipHeight() const
Definition: clientmodel.cpp:82
std::unique_ptr< interfaces::Handler > m_handler_show_progress
Definition: clientmodel.h:87
std::atomic< int64_t > cachedBestHeaderTime
Definition: clientmodel.h:79
std::unique_ptr< interfaces::Handler > m_handler_notify_alert_changed
Definition: clientmodel.h:92
interfaces::Node & m_node
Definition: clientmodel.h:86
Mutex m_cached_tip_mutex
Definition: clientmodel.h:82
PeerTableModel * getPeerTableModel()
void updateNetworkActive(bool networkActive)
std::atomic< int > cachedBestHeaderHeight
Definition: clientmodel.h:78
void updateNumConnections(int numConnections)
int getNumConnections(NumConnections flags=CONNECTIONS_ALL) const
Return number of connections, default is in- and outbound (total)
Definition: clientmodel.cpp:68
void numConnectionsChanged(int count)
int getNumBlocks() const
int64_t getHeaderTipTime() const
Definition: clientmodel.cpp:96
std::unique_ptr< interfaces::Handler > m_handler_notify_block_tip
Definition: clientmodel.h:94
QString formatClientStartupTime() const
enum BlockSource getBlockSource() const
Returns enum BlockSource of the current importing/syncing state.
ClientModel(interfaces::Node &node, OptionsModel *optionsModel, QObject *parent=nullptr)
Definition: clientmodel.cpp:31
std::unique_ptr< interfaces::Handler > m_handler_notify_num_connections_changed
Definition: clientmodel.h:89
std::unique_ptr< interfaces::Handler > m_handler_notify_network_active_changed
Definition: clientmodel.h:91
OptionsModel * optionsModel
Definition: clientmodel.h:96
BanTableModel * banTableModel
Definition: clientmodel.h:98
QThread *const m_thread
A thread to interact with m_node asynchronously.
Definition: clientmodel.h:101
std::unique_ptr< interfaces::Handler > m_handler_notify_header_tip
Definition: clientmodel.h:95
BanTableModel * getBanTableModel()
void unsubscribeFromCoreSignals()
void alertsChanged(const QString &warnings)
QString dataDir() const
std::atomic< int > m_cached_num_blocks
Definition: clientmodel.h:80
OptionsModel * getOptionsModel()
QString formatFullVersion() const
PeerTableModel * peerTableModel
Definition: clientmodel.h:97
BlockHash getBestBlockHash()
bool getProxyInfo(std::string &ip_port) const
QString formatSubVersion() const
void mempoolSizeChanged(long count, size_t mempoolSizeInBytes)
bool isReleaseVersion() const
void subscribeToCoreSignals()
void networkActiveChanged(bool networkActive)
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:55
virtual std::unique_ptr< Handler > handleNotifyBlockTip(NotifyBlockTipFn fn)=0
virtual std::unique_ptr< Handler > handleNotifyAlertChanged(NotifyAlertChangedFn fn)=0
virtual std::unique_ptr< Handler > handleNotifyHeaderTip(NotifyHeaderTipFn fn)=0
virtual std::unique_ptr< Handler > handleNotifyNetworkActiveChanged(NotifyNetworkActiveChangedFn fn)=0
virtual bool getImporting()=0
Get importing.
virtual bilingual_str getWarnings()=0
Get warnings.
virtual std::unique_ptr< Handler > handleNotifyNumConnectionsChanged(NotifyNumConnectionsChangedFn fn)=0
virtual std::unique_ptr< Handler > handleShowProgress(ShowProgressFn fn)=0
virtual bool getProxy(Network net, proxyType &proxy_info)=0
Get proxy.
virtual bool getReindex()=0
Get reindex.
virtual BlockHash getBestBlockHash()=0
Get best block hash.
virtual size_t getMempoolSize()=0
Get mempool size.
virtual size_t getNodeCount(CConnman::NumConnections 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 int64_t getTotalBytesSent()=0
Get total bytes sent.
virtual size_t getMempoolDynamicUsage()=0
Get mempool dynamic usage.
virtual int getNumBlocks()=0
Get num blocks.
CService proxy
Definition: netbase.h:40
static int64_t nLastHeaderTipUpdateNotification
Definition: clientmodel.cpp:28
static void NotifyAlertChanged(ClientModel *clientmodel)
static void ShowProgress(ClientModel *clientmodel, const std::string &title, int nProgress)
static void BlockTipChanged(ClientModel *clientmodel, SynchronizationState sync_state, interfaces::BlockTip tip, double verificationProgress, bool fHeader)
static void NotifyNetworkActiveChanged(ClientModel *clientmodel, bool networkActive)
static void NotifyNumConnectionsChanged(ClientModel *clientmodel, int newNumConnections)
static int64_t nLastBlockTipUpdateNotification
Definition: clientmodel.cpp:29
static void BannedListChanged(ClientModel *clientmodel)
BlockSource
Definition: clientmodel.h:33
std::string FormatFullVersion()
const Config & GetConfig()
Definition: config.cpp:34
static const int MODEL_UPDATE_DELAY
Definition: guiconstants.h:11
NodeContext & m_node
Definition: chain.cpp:483
QString boostPathToQString(const fs::path &path)
Convert OS specific boost path to QString through UTF-8.
Definition: guiutil.cpp:778
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:3610
Network
A network type.
Definition: netaddress.h:45
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:249
int64_t block_time
Definition: node.h:251
BlockHash block_hash
Definition: node.h:252
#define LOCK(cs)
Definition: sync.h:243
#define WITH_LOCK(cs, code)
Run code while locking a mutex.
Definition: sync.h:276
int64_t GetStartupTime()
Server/client environment: argument handling, config file parsing, thread wrappers,...
Definition: system.cpp:1378
ArgsManager gArgs
Definition: system.cpp:77
int64_t GetTimeMillis()
Returns the system time (not mockable)
Definition: time.cpp:106
assert(!tx.IsCoinBase())
SynchronizationState
Current sync state passed to tip changed callbacks.
Definition: validation.h:127