Bitcoin Core  25.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 #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 <common/args.h>
15 #include <common/system.h>
16 #include <interfaces/handler.h>
17 #include <interfaces/node.h>
18 #include <net.h>
19 #include <netbase.h>
20 #include <util/threadnames.h>
21 #include <util/time.h>
22 #include <validation.h>
23 
24 #include <stdint.h>
25 
26 #include <QDebug>
27 #include <QMetaObject>
28 #include <QThread>
29 #include <QTimer>
30 
31 static SteadyClock::time_point g_last_header_tip_update_notification{};
32 static SteadyClock::time_point g_last_block_tip_update_notification{};
33 
34 ClientModel::ClientModel(interfaces::Node& node, OptionsModel *_optionsModel, QObject *parent) :
35  QObject(parent),
36  m_node(node),
37  optionsModel(_optionsModel),
38  m_thread(new QThread(this))
39 {
42 
45  m_peer_table_sort_proxy->setSourceModel(peerTableModel);
46 
47  banTableModel = new BanTableModel(m_node, this);
48 
49  QTimer* timer = new QTimer;
50  timer->setInterval(MODEL_UPDATE_DELAY);
51  connect(timer, &QTimer::timeout, [this] {
52  // no locking required at this point
53  // the following calls will acquire the required lock
56  });
57  connect(m_thread, &QThread::finished, timer, &QObject::deleteLater);
58  connect(m_thread, &QThread::started, [timer] { timer->start(); });
59  // move timer to thread so that polling doesn't disturb main event loop
60  timer->moveToThread(m_thread);
61  m_thread->start();
62  QTimer::singleShot(0, timer, []() {
63  util::ThreadRename("qt-clientmodl");
64  });
65 
67 }
68 
70 {
72 
73  m_thread->quit();
74  m_thread->wait();
75 }
76 
77 int ClientModel::getNumConnections(unsigned int flags) const
78 {
80 
81  if(flags == CONNECTIONS_IN)
82  connections = ConnectionDirection::In;
83  else if (flags == CONNECTIONS_OUT)
84  connections = ConnectionDirection::Out;
85  else if (flags == CONNECTIONS_ALL)
86  connections = ConnectionDirection::Both;
87 
88  return m_node.getNodeCount(connections);
89 }
90 
92 {
93  if (cachedBestHeaderHeight == -1) {
94  // make sure we initially populate the cache via a cs_main lock
95  // otherwise we need to wait for a tip update
96  int height;
97  int64_t blockTime;
98  if (m_node.getHeaderTip(height, blockTime)) {
99  cachedBestHeaderHeight = height;
100  cachedBestHeaderTime = blockTime;
101  }
102  }
103  return cachedBestHeaderHeight;
104 }
105 
107 {
108  if (cachedBestHeaderTime == -1) {
109  int height;
110  int64_t blockTime;
111  if (m_node.getHeaderTip(height, blockTime)) {
112  cachedBestHeaderHeight = height;
113  cachedBestHeaderTime = blockTime;
114  }
115  }
116  return cachedBestHeaderTime;
117 }
118 
120 {
121  if (m_cached_num_blocks == -1) {
123  }
124  return m_cached_num_blocks;
125 }
126 
128 {
129  uint256 tip{WITH_LOCK(m_cached_tip_mutex, return m_cached_tip_blocks)};
130 
131  if (!tip.IsNull()) {
132  return tip;
133  }
134 
135  // Lock order must be: first `cs_main`, then `m_cached_tip_mutex`.
136  // The following will lock `cs_main` (and release it), so we must not
137  // own `m_cached_tip_mutex` here.
138  tip = m_node.getBestBlockHash();
139 
141  // We checked that `m_cached_tip_blocks` is not null above, but then we
142  // released the mutex `m_cached_tip_mutex`, so it could have changed in the
143  // meantime. Thus, check again.
144  if (m_cached_tip_blocks.IsNull()) {
145  m_cached_tip_blocks = tip;
146  }
147  return m_cached_tip_blocks;
148 }
149 
151 {
153  if (getNumConnections() > 0) return BlockSource::NETWORK;
154  return BlockSource::NONE;
155 }
156 
158 {
159  return QString::fromStdString(m_node.getWarnings().translated);
160 }
161 
163 {
164  return optionsModel;
165 }
166 
168 {
169  return peerTableModel;
170 }
171 
173 {
175 }
176 
178 {
179  return banTableModel;
180 }
181 
183 {
184  return QString::fromStdString(FormatFullVersion());
185 }
186 
188 {
189  return QString::fromStdString(strSubVersion);
190 }
191 
193 {
195 }
196 
198 {
199  return QDateTime::fromSecsSinceEpoch(GetStartupTime()).toString();
200 }
201 
202 QString ClientModel::dataDir() const
203 {
205 }
206 
207 QString ClientModel::blocksDir() const
208 {
210 }
211 
212 void ClientModel::TipChanged(SynchronizationState sync_state, interfaces::BlockTip tip, double verification_progress, SyncType synctype)
213 {
214  if (synctype == SyncType::HEADER_SYNC) {
215  // cache best headers time and height to reduce future cs_main locks
218  } else if (synctype == SyncType::BLOCK_SYNC) {
220  WITH_LOCK(m_cached_tip_mutex, m_cached_tip_blocks = tip.block_hash;);
221  }
222 
223  // Throttle GUI notifications about (a) blocks during initial sync, and (b) both blocks and headers during reindex.
224  const bool throttle = (sync_state != SynchronizationState::POST_INIT && synctype == SyncType::BLOCK_SYNC) || sync_state == SynchronizationState::INIT_REINDEX;
225  const auto now{throttle ? SteadyClock::now() : SteadyClock::time_point{}};
227  if (throttle && now < nLastUpdateNotification + MODEL_UPDATE_DELAY) {
228  return;
229  }
230 
231  Q_EMIT numBlocksChanged(tip.block_height, QDateTime::fromSecsSinceEpoch(tip.block_time), verification_progress, synctype, sync_state);
232  nLastUpdateNotification = now;
233 }
234 
236 {
238  [this](const std::string& title, int progress, [[maybe_unused]] bool resume_possible) {
239  Q_EMIT showProgress(QString::fromStdString(title), progress);
240  });
242  [this](int new_num_connections) {
243  Q_EMIT numConnectionsChanged(new_num_connections);
244  });
246  [this](bool network_active) {
247  Q_EMIT networkActiveChanged(network_active);
248  });
250  [this]() {
251  qDebug() << "ClientModel: NotifyAlertChanged";
253  });
255  [this]() {
256  qDebug() << "ClienModel: Requesting update for peer banlist";
257  QMetaObject::invokeMethod(banTableModel, [this] { banTableModel->refresh(); });
258  });
260  [this](SynchronizationState sync_state, interfaces::BlockTip tip, double verification_progress) {
261  TipChanged(sync_state, tip, verification_progress, SyncType::BLOCK_SYNC);
262  });
264  [this](SynchronizationState sync_state, interfaces::BlockTip tip, bool presync) {
265  TipChanged(sync_state, tip, /*verification_progress=*/0.0, presync ? SyncType::HEADER_PRESYNC : SyncType::HEADER_SYNC);
266  });
267 }
268 
270 {
271  m_handler_show_progress->disconnect();
274  m_handler_notify_alert_changed->disconnect();
275  m_handler_banned_list_changed->disconnect();
276  m_handler_notify_block_tip->disconnect();
277  m_handler_notify_header_tip->disconnect();
278 }
279 
280 bool ClientModel::getProxyInfo(std::string& ip_port) const
281 {
282  Proxy ipv4, ipv6;
283  if (m_node.getProxy((Network) 1, ipv4) && m_node.getProxy((Network) 2, ipv6)) {
284  ip_port = ipv4.proxy.ToStringAddrPort();
285  return true;
286  }
287  return false;
288 }
ArgsManager gArgs
Definition: args.cpp:42
#define CLIENT_VERSION_IS_RELEASE
node::NodeContext m_node
Definition: bitcoin-gui.cpp:37
int flags
Definition: bitcoin-tx.cpp:528
const fs::path & GetBlocksDirPath() const
Get blocks directory path.
Definition: args.cpp:281
const fs::path & GetDataDirNet() const
Get data directory path with appended network identifier.
Definition: args.h:231
Qt model providing information about banned peers, similar to the "getpeerinfo" RPC call.
Definition: bantablemodel.h:44
std::string ToStringAddrPort() const
Definition: netaddress.cpp:914
std::unique_ptr< interfaces::Handler > m_handler_banned_list_changed
Definition: clientmodel.h:102
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:91
std::unique_ptr< interfaces::Handler > m_handler_show_progress
Definition: clientmodel.h:98
std::atomic< int64_t > cachedBestHeaderTime
Definition: clientmodel.h:90
std::unique_ptr< interfaces::Handler > m_handler_notify_alert_changed
Definition: clientmodel.h:101
interfaces::Node & m_node
Definition: clientmodel.h:94
Mutex m_cached_tip_mutex
Definition: clientmodel.h:93
PeerTableModel * getPeerTableModel()
PeerTableSortProxy * peerTableSortProxy()
std::atomic< int > cachedBestHeaderHeight
Definition: clientmodel.h:89
uint256 getBestBlockHash() EXCLUSIVE_LOCKS_REQUIRED(!m_cached_tip_mutex)
void numConnectionsChanged(int count)
BlockSource getBlockSource() const
Returns the block source of the current importing/syncing state.
int getNumBlocks() const
int64_t getHeaderTipTime() const
std::unique_ptr< interfaces::Handler > m_handler_notify_block_tip
Definition: clientmodel.h:103
QString formatClientStartupTime() const
int getNumConnections(unsigned int flags=CONNECTIONS_ALL) const
Return number of connections, default is in- and outbound (total)
Definition: clientmodel.cpp:77
ClientModel(interfaces::Node &node, OptionsModel *optionsModel, QObject *parent=nullptr)
Definition: clientmodel.cpp:34
std::unique_ptr< interfaces::Handler > m_handler_notify_num_connections_changed
Definition: clientmodel.h:99
std::unique_ptr< interfaces::Handler > m_handler_notify_network_active_changed
Definition: clientmodel.h:100
OptionsModel * optionsModel
Definition: clientmodel.h:105
BanTableModel * banTableModel
Definition: clientmodel.h:108
QThread *const m_thread
A thread to interact with m_node asynchronously.
Definition: clientmodel.h:111
std::unique_ptr< interfaces::Handler > m_handler_notify_header_tip
Definition: clientmodel.h:104
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)
void alertsChanged(const QString &warnings)
QString dataDir() const
std::atomic< int > m_cached_num_blocks
Definition: clientmodel.h:91
OptionsModel * getOptionsModel()
QString formatFullVersion() const
PeerTableModel * peerTableModel
Definition: clientmodel.h:106
PeerTableSortProxy * m_peer_table_sort_proxy
Definition: clientmodel.h:107
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:41
Qt model providing information about connected peers, similar to the "getpeerinfo" RPC call.
Definition: netbase.h:49
CService proxy
Definition: netbase.h:56
Top-level interface for a bitcoin node (bitcoind process).
Definition: node.h:70
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 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:105
static SteadyClock::time_point g_last_block_tip_update_notification
Definition: clientmodel.cpp:32
static SteadyClock::time_point g_last_header_tip_update_notification
Definition: clientmodel.cpp:31
SyncType
Definition: clientmodel.h:39
@ HEADER_PRESYNC
@ 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:104
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:670
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:121
Network
A network type.
Definition: netaddress.h:44
ConnectionDirection
Definition: netbase.h:32
std::string translated
Definition: translation.h:20
Block tip (could be a header or not, depends on the subscribed signal).
Definition: node.h:273
uint256 block_hash
Definition: node.h:276
int64_t block_time
Definition: node.h:275
#define LOCK(cs)
Definition: sync.h:258
#define WITH_LOCK(cs, code)
Run code while locking a mutex.
Definition: sync.h:302
SynchronizationState
Current sync state passed to tip changed callbacks.
Definition: validation.h:85