Bitcoin ABC  0.28.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 <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 <QMetaObject>
23 #include <QThread>
24 #include <QTimer>
25 
26 #include <cstdint>
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 
138  if (m_node.getReindex()) {
139  return BlockSource::REINDEX;
140  } else if (m_node.getImporting()) {
141  return BlockSource::DISK;
142  } else if (getNumConnections() > 0) {
143  return BlockSource::NETWORK;
144  }
145 
146  return BlockSource::NONE;
147 }
148 
150  return QString::fromStdString(m_node.getWarnings().translated);
151 }
152 
154  return optionsModel;
155 }
156 
158  return peerTableModel;
159 }
160 
162  return banTableModel;
163 }
164 
166  return QString::fromStdString(FormatFullVersion());
167 }
168 
170  return QString::fromStdString(userAgent(GetConfig()));
171 }
172 
174  return CLIENT_VERSION_IS_RELEASE;
175 }
176 
178  return QDateTime::fromTime_t(GetStartupTime()).toString();
179 }
180 
181 QString ClientModel::dataDir() const {
183 }
184 
185 QString ClientModel::blocksDir() const {
187 }
188 
191  double verification_progress, SyncType synctype)
192  EXCLUSIVE_LOCKS_REQUIRED(!m_cached_tip_mutex) {
193  if (synctype == SyncType::HEADER_SYNC) {
194  // cache best headers time and height to reduce future cs_main locks
195  cachedBestHeaderHeight = tip.block_height;
196  cachedBestHeaderTime = tip.block_time;
197  } else if (synctype == SyncType::BLOCK_SYNC) {
198  m_cached_num_blocks = tip.block_height;
199  WITH_LOCK(m_cached_tip_mutex, m_cached_tip_blocks = tip.block_hash;);
200  }
201 
202  // Throttle GUI notifications about (a) blocks during initial sync, and (b)
203  // both blocks and headers during reindex.
204  const bool throttle = (sync_state != SynchronizationState::POST_INIT &&
205  synctype == SyncType::BLOCK_SYNC) ||
207  const int64_t now = throttle ? GetTimeMillis() : 0;
208  int64_t &nLastUpdateNotification = synctype != SyncType::BLOCK_SYNC
211  if (throttle && now < nLastUpdateNotification + MODEL_UPDATE_DELAY) {
212  return;
213  }
214 
215  Q_EMIT numBlocksChanged(tip.block_height,
216  QDateTime::fromSecsSinceEpoch(tip.block_time),
217  verification_progress, synctype, sync_state);
218  nLastUpdateNotification = now;
219 }
220 
223  [this](const std::string &title, int progress,
224  [[maybe_unused]] bool resume_possible) {
225  Q_EMIT showProgress(QString::fromStdString(title), progress);
226  });
229  [this](int new_num_connections) {
230  Q_EMIT numConnectionsChanged(new_num_connections);
231  });
233  m_node.handleNotifyNetworkActiveChanged([this](bool network_active) {
234  Q_EMIT networkActiveChanged(network_active);
235  });
237  qDebug() << "ClientModel: NotifyAlertChanged";
239  });
241  qDebug() << "ClienModel: Requesting update for peer banlist";
242  QMetaObject::invokeMethod(banTableModel,
243  [this] { banTableModel->refresh(); });
244  });
246  [this](SynchronizationState sync_state, interfaces::BlockTip tip,
247  double verification_progress) {
248  TipChanged(sync_state, tip, verification_progress,
250  });
252  [this](SynchronizationState sync_state, interfaces::BlockTip tip,
253  bool presync) {
254  TipChanged(sync_state, tip, /*verification_progress=*/0.0,
255  presync ? SyncType::HEADER_PRESYNC
257  });
258 }
259 
261  m_handler_show_progress->disconnect();
264  m_handler_notify_alert_changed->disconnect();
265  m_handler_banned_list_changed->disconnect();
266  m_handler_notify_block_tip->disconnect();
267  m_handler_notify_header_tip->disconnect();
268 }
269 
270 bool ClientModel::getProxyInfo(std::string &ip_port) const {
271  proxyType ipv4, ipv6;
272  if (m_node.getProxy((Network)1, ipv4) &&
273  m_node.getProxy((Network)2, ipv6)) {
274  ip_port = ipv4.proxy.ToStringIPPort();
275  return true;
276  }
277  return false;
278 }
int flags
Definition: bitcoin-tx.cpp:533
const fs::path & GetBlocksDirPath() const
Get blocks directory path.
Definition: system.cpp:410
const fs::path & GetDataDirNet() const
Get data directory path with appended network identifier.
Definition: system.h:268
Qt model providing information about connected peers, similar to the "getpeerinfo" RPC call.
Definition: bantablemodel.h:42
NumConnections
Definition: net.h:847
@ CONNECTIONS_IN
Definition: net.h:849
@ CONNECTIONS_NONE
Definition: net.h:848
@ CONNECTIONS_ALL
Definition: net.h:851
@ CONNECTIONS_OUT
Definition: net.h:850
std::string ToStringIPPort() const
std::unique_ptr< interfaces::Handler > m_handler_banned_list_changed
Definition: clientmodel.h:96
void bytesChanged(quint64 totalBytesIn, quint64 totalBytesOut)
void showProgress(const QString &title, int nProgress)
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:90
std::atomic< int64_t > cachedBestHeaderTime
Definition: clientmodel.h:82
std::unique_ptr< interfaces::Handler > m_handler_notify_alert_changed
Definition: clientmodel.h:95
interfaces::Node & m_node
Definition: clientmodel.h:89
Mutex m_cached_tip_mutex
Definition: clientmodel.h:85
PeerTableModel * getPeerTableModel()
std::atomic< int > cachedBestHeaderHeight
Definition: clientmodel.h:81
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: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:97
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
void TipChanged(SynchronizationState sync_state, interfaces::BlockTip tip, double verification_progress, SyncType synctype)
std::unique_ptr< interfaces::Handler > m_handler_notify_num_connections_changed
Definition: clientmodel.h:92
std::unique_ptr< interfaces::Handler > m_handler_notify_network_active_changed
Definition: clientmodel.h:94
OptionsModel * optionsModel
Definition: clientmodel.h:99
BanTableModel * banTableModel
Definition: clientmodel.h:101
QThread *const m_thread
A thread to interact with m_node asynchronously.
Definition: clientmodel.h:104
std::unique_ptr< interfaces::Handler > m_handler_notify_header_tip
Definition: clientmodel.h:98
BanTableModel * getBanTableModel()
void unsubscribeFromCoreSignals()
void alertsChanged(const QString &warnings)
QString dataDir() const
std::atomic< int > m_cached_num_blocks
Definition: clientmodel.h:83
OptionsModel * getOptionsModel()
QString formatFullVersion() const
PeerTableModel * peerTableModel
Definition: clientmodel.h:100
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:58
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 int64_t nLastBlockTipUpdateNotification
Definition: clientmodel.cpp:29
SyncType
Definition: clientmodel.h:36
@ HEADER_PRESYNC
BlockSource
Definition: clientmodel.h:34
std::string FormatFullVersion()
const Config & GetConfig()
Definition: config.cpp:34
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:783
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:3591
Network
A network type.
Definition: netaddress.h:44
NodeContext & m_node
Definition: interfaces.cpp:778
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:272
#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()
Server/client environment: argument handling, config file parsing, thread wrappers,...
Definition: system.cpp:1449
ArgsManager gArgs
Definition: system.cpp:80
#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:117