Bitcoin Core  27.99.0
P2P Digital Currency
clientmodel.cpp
Go to the documentation of this file.
1 // Copyright (c) 2011-2022 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 #if defined(HAVE_CONFIG_H)
7 #endif
8 
9 #include <qt/clientmodel.h>
10 
11 #include <qt/bantablemodel.h>
12 #include <qt/guiconstants.h>
13 #include <qt/guiutil.h>
14 #include <qt/peertablemodel.h>
15 #include <qt/peertablesortproxy.h>
16 
17 #include <clientversion.h>
18 #include <common/args.h>
19 #include <common/system.h>
20 #include <interfaces/handler.h>
21 #include <interfaces/node.h>
22 #include <net.h>
23 #include <netbase.h>
24 #include <util/threadnames.h>
25 #include <util/time.h>
26 #include <validation.h>
27 
28 #include <stdint.h>
29 
30 #include <QDebug>
31 #include <QMetaObject>
32 #include <QThread>
33 #include <QTimer>
34 
35 static SteadyClock::time_point g_last_header_tip_update_notification{};
36 static SteadyClock::time_point g_last_block_tip_update_notification{};
37 
38 ClientModel::ClientModel(interfaces::Node& node, OptionsModel *_optionsModel, QObject *parent) :
39  QObject(parent),
40  m_node(node),
41  optionsModel(_optionsModel),
42  m_thread(new QThread(this))
43 {
46 
49  m_peer_table_sort_proxy->setSourceModel(peerTableModel);
50 
51  banTableModel = new BanTableModel(m_node, this);
52 
53  QTimer* timer = new QTimer;
54  timer->setInterval(MODEL_UPDATE_DELAY);
55  connect(timer, &QTimer::timeout, [this] {
56  // no locking required at this point
57  // the following calls will acquire the required lock
60  });
61  connect(m_thread, &QThread::finished, timer, &QObject::deleteLater);
62  connect(m_thread, &QThread::started, [timer] { timer->start(); });
63  // move timer to thread so that polling doesn't disturb main event loop
64  timer->moveToThread(m_thread);
65  m_thread->start();
66  QTimer::singleShot(0, timer, []() {
67  util::ThreadRename("qt-clientmodl");
68  });
69 
71 }
72 
74 {
76 
77  m_thread->quit();
78  m_thread->wait();
79 }
80 
82 {
83  stop();
84 }
85 
86 int ClientModel::getNumConnections(unsigned int flags) const
87 {
89 
90  if(flags == CONNECTIONS_IN)
91  connections = ConnectionDirection::In;
92  else if (flags == CONNECTIONS_OUT)
93  connections = ConnectionDirection::Out;
94  else if (flags == CONNECTIONS_ALL)
95  connections = ConnectionDirection::Both;
96 
97  return m_node.getNodeCount(connections);
98 }
99 
101 {
102  if (cachedBestHeaderHeight == -1) {
103  // make sure we initially populate the cache via a cs_main lock
104  // otherwise we need to wait for a tip update
105  int height;
106  int64_t blockTime;
107  if (m_node.getHeaderTip(height, blockTime)) {
108  cachedBestHeaderHeight = height;
109  cachedBestHeaderTime = blockTime;
110  }
111  }
112  return cachedBestHeaderHeight;
113 }
114 
116 {
117  if (cachedBestHeaderTime == -1) {
118  int height;
119  int64_t blockTime;
120  if (m_node.getHeaderTip(height, blockTime)) {
121  cachedBestHeaderHeight = height;
122  cachedBestHeaderTime = blockTime;
123  }
124  }
125  return cachedBestHeaderTime;
126 }
127 
129 {
130  if (m_cached_num_blocks == -1) {
132  }
133  return m_cached_num_blocks;
134 }
135 
137 {
138  uint256 tip{WITH_LOCK(m_cached_tip_mutex, return m_cached_tip_blocks)};
139 
140  if (!tip.IsNull()) {
141  return tip;
142  }
143 
144  // Lock order must be: first `cs_main`, then `m_cached_tip_mutex`.
145  // The following will lock `cs_main` (and release it), so we must not
146  // own `m_cached_tip_mutex` here.
147  tip = m_node.getBestBlockHash();
148 
150  // We checked that `m_cached_tip_blocks` is not null above, but then we
151  // released the mutex `m_cached_tip_mutex`, so it could have changed in the
152  // meantime. Thus, check again.
153  if (m_cached_tip_blocks.IsNull()) {
154  m_cached_tip_blocks = tip;
155  }
156  return m_cached_tip_blocks;
157 }
158 
160 {
162  if (getNumConnections() > 0) return BlockSource::NETWORK;
163  return BlockSource::NONE;
164 }
165 
167 {
168  return QString::fromStdString(m_node.getWarnings().translated);
169 }
170 
172 {
173  return optionsModel;
174 }
175 
177 {
178  return peerTableModel;
179 }
180 
182 {
184 }
185 
187 {
188  return banTableModel;
189 }
190 
192 {
193  return QString::fromStdString(FormatFullVersion());
194 }
195 
197 {
198  return QString::fromStdString(strSubVersion);
199 }
200 
202 {
204 }
205 
207 {
208  return QDateTime::fromSecsSinceEpoch(GetStartupTime()).toString();
209 }
210 
211 QString ClientModel::dataDir() const
212 {
214 }
215 
216 QString ClientModel::blocksDir() const
217 {
219 }
220 
221 void ClientModel::TipChanged(SynchronizationState sync_state, interfaces::BlockTip tip, double verification_progress, SyncType synctype)
222 {
223  if (synctype == SyncType::HEADER_SYNC) {
224  // cache best headers time and height to reduce future cs_main locks
227  } else if (synctype == SyncType::BLOCK_SYNC) {
229  WITH_LOCK(m_cached_tip_mutex, m_cached_tip_blocks = tip.block_hash;);
230  }
231 
232  // Throttle GUI notifications about (a) blocks during initial sync, and (b) both blocks and headers during reindex.
233  const bool throttle = (sync_state != SynchronizationState::POST_INIT && synctype == SyncType::BLOCK_SYNC) || sync_state == SynchronizationState::INIT_REINDEX;
234  const auto now{throttle ? SteadyClock::now() : SteadyClock::time_point{}};
236  if (throttle && now < nLastUpdateNotification + MODEL_UPDATE_DELAY) {
237  return;
238  }
239 
240  Q_EMIT numBlocksChanged(tip.block_height, QDateTime::fromSecsSinceEpoch(tip.block_time), verification_progress, synctype, sync_state);
241  nLastUpdateNotification = now;
242 }
243 
245 {
247  [this](const std::string& title, int progress, [[maybe_unused]] bool resume_possible) {
248  Q_EMIT showProgress(QString::fromStdString(title), progress);
249  }));
251  [this](int new_num_connections) {
252  Q_EMIT numConnectionsChanged(new_num_connections);
253  }));
255  [this](bool network_active) {
256  Q_EMIT networkActiveChanged(network_active);
257  }));
259  [this]() {
260  qDebug() << "ClientModel: NotifyAlertChanged";
261  Q_EMIT alertsChanged(getStatusBarWarnings());
262  }));
264  [this]() {
265  qDebug() << "ClienModel: Requesting update for peer banlist";
266  QMetaObject::invokeMethod(banTableModel, [this] { banTableModel->refresh(); });
267  }));
268  m_event_handlers.emplace_back(m_node.handleNotifyBlockTip(
269  [this](SynchronizationState sync_state, interfaces::BlockTip tip, double verification_progress) {
270  TipChanged(sync_state, tip, verification_progress, SyncType::BLOCK_SYNC);
271  }));
272  m_event_handlers.emplace_back(m_node.handleNotifyHeaderTip(
273  [this](SynchronizationState sync_state, interfaces::BlockTip tip, bool presync) {
274  TipChanged(sync_state, tip, /*verification_progress=*/0.0, presync ? SyncType::HEADER_PRESYNC : SyncType::HEADER_SYNC);
275  }));
276 }
277 
279 {
280  m_event_handlers.clear();
281 }
282 
283 bool ClientModel::getProxyInfo(std::string& ip_port) const
284 {
285  Proxy ipv4, ipv6;
286  if (m_node.getProxy((Network) 1, ipv4) && m_node.getProxy((Network) 2, ipv6)) {
287  ip_port = ipv4.proxy.ToStringAddrPort();
288  return true;
289  }
290  return false;
291 }
ArgsManager gArgs
Definition: args.cpp:41
#define CLIENT_VERSION_IS_RELEASE
node::NodeContext m_node
Definition: bitcoin-gui.cpp:37
int flags
Definition: bitcoin-tx.cpp:530
fs::path GetDataDirNet() const
Get data directory path with appended network identifier.
Definition: args.h:232
fs::path GetBlocksDirPath() const
Get blocks directory path.
Definition: args.cpp:280
Qt model providing information about banned peers, similar to the "getpeerinfo" RPC call.
Definition: bantablemodel.h:44
std::string ToStringAddrPort() const
Definition: netaddress.cpp:902
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:100
int getHeaderTipHeight() const
std::atomic< int64_t > cachedBestHeaderTime
Definition: clientmodel.h:92
interfaces::Node & m_node
Definition: clientmodel.h:96
Mutex m_cached_tip_mutex
Definition: clientmodel.h:95
PeerTableModel * getPeerTableModel()
PeerTableSortProxy * peerTableSortProxy()
std::atomic< int > cachedBestHeaderHeight
Definition: clientmodel.h:91
uint256 getBestBlockHash() EXCLUSIVE_LOCKS_REQUIRED(!m_cached_tip_mutex)
BlockSource getBlockSource() const
Returns the block source of the current importing/syncing state.
int getNumBlocks() const
int64_t getHeaderTipTime() const
QString formatClientStartupTime() const
int getNumConnections(unsigned int flags=CONNECTIONS_ALL) const
Return number of connections, default is in- and outbound (total)
Definition: clientmodel.cpp:86
ClientModel(interfaces::Node &node, OptionsModel *optionsModel, QObject *parent=nullptr)
Definition: clientmodel.cpp:38
OptionsModel * optionsModel
Definition: clientmodel.h:101
BanTableModel * banTableModel
Definition: clientmodel.h:104
QThread *const m_thread
A thread to interact with m_node asynchronously.
Definition: clientmodel.h:107
BanTableModel * getBanTableModel()
void unsubscribeFromCoreSignals()
void numBlocksChanged(int count, const QDateTime &blockDate, double nVerificationProgress, SyncType header, SynchronizationState sync_state)
void TipChanged(SynchronizationState sync_state, interfaces::BlockTip tip, double verification_progress, SyncType synctype) EXCLUSIVE_LOCKS_REQUIRED(!m_cached_tip_mutex)
QString dataDir() const
std::atomic< int > m_cached_num_blocks
Definition: clientmodel.h:93
OptionsModel * getOptionsModel()
QString formatFullVersion() const
PeerTableModel * peerTableModel
Definition: clientmodel.h:102
PeerTableSortProxy * m_peer_table_sort_proxy
Definition: clientmodel.h:103
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:43
Qt model providing information about connected peers, similar to the "getpeerinfo" RPC call.
Definition: netbase.h:59
CService proxy
Definition: netbase.h:65
Top-level interface for a bitcoin node (bitcoind process).
Definition: node.h:70
virtual std::unique_ptr< Handler > handleNotifyAlertChanged(NotifyAlertChangedFn fn)=0
virtual std::unique_ptr< Handler > handleNotifyNetworkActiveChanged(NotifyNetworkActiveChangedFn fn)=0
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 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 uint256 getBestBlockHash()=0
Get best block hash.
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 bool getProxy(Network net, Proxy &proxy_info)=0
Get proxy.
virtual int getNumBlocks()=0
Get num blocks.
256-bit opaque blob.
Definition: uint256.h:106
static SteadyClock::time_point g_last_block_tip_update_notification
Definition: clientmodel.cpp:36
static SteadyClock::time_point g_last_header_tip_update_notification
Definition: clientmodel.cpp:35
SyncType
Definition: clientmodel.h:39
@ CONNECTIONS_IN
Definition: clientmodel.h:47
@ CONNECTIONS_OUT
Definition: clientmodel.h:48
@ CONNECTIONS_ALL
Definition: clientmodel.h:49
BlockSource
Definition: clientmodel.h:33
std::string FormatFullVersion()
int64_t GetStartupTime()
Definition: system.cpp:109
static constexpr auto MODEL_UPDATE_DELAY
Definition: guiconstants.h:14
QString PathToQString(const fs::path &path)
Convert OS specific boost path to QString through UTF-8.
Definition: guiutil.cpp:674
Definition: init.h:25
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:59
std::string strSubVersion
Subversion as sent to the P2P network in version messages.
Definition: net.cpp:119
Network
A network type.
Definition: netaddress.h:32
ConnectionDirection
Definition: netbase.h:33
std::string translated
Definition: translation.h:20
Block tip (could be a header or not, depends on the subscribed signal).
Definition: node.h:276
uint256 block_hash
Definition: node.h:279
int64_t block_time
Definition: node.h:278
#define LOCK(cs)
Definition: sync.h:257
#define WITH_LOCK(cs, code)
Run code while locking a mutex.
Definition: sync.h:301
SynchronizationState
Current sync state passed to tip changed callbacks.
Definition: validation.h:80