Bitcoin Core 31.0.0
P2P Digital Currency
Loading...
Searching...
No Matches
clientmodel.cpp
Go to the documentation of this file.
1// Copyright (c) 2011-present 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 <bitcoin-build-config.h> // IWYU pragma: keep
6
7#include <qt/clientmodel.h>
8
9#include <qt/bantablemodel.h>
10#include <qt/guiconstants.h>
11#include <qt/guiutil.h>
12#include <qt/peertablemodel.h>
14
15#include <clientversion.h>
16#include <common/args.h>
17#include <common/system.h>
18#include <interfaces/handler.h>
19#include <interfaces/node.h>
20#include <net.h>
21#include <netbase.h>
22#include <util/threadnames.h>
23#include <util/time.h>
24#include <validation.h>
25
26#include <cstdint>
27
28#include <QDebug>
29#include <QMetaObject>
30#include <QThread>
31#include <QTimer>
32
33static SteadyClock::time_point g_last_header_tip_update_notification{};
34static SteadyClock::time_point g_last_block_tip_update_notification{};
35
37 QObject(parent),
38 m_node(node),
39 optionsModel(_optionsModel),
40 m_thread(new QThread(this))
41{
44
48
50
51 QTimer* timer = new QTimer;
52 timer->setInterval(MODEL_UPDATE_DELAY);
53 connect(timer, &QTimer::timeout, [this] {
54 // no locking required at this point
55 // the following calls will acquire the required lock
58 });
59 connect(m_thread, &QThread::finished, timer, &QObject::deleteLater);
60 connect(m_thread, &QThread::started, [timer] { timer->start(); });
61 // move timer to thread so that polling doesn't disturb main event loop
62 timer->moveToThread(m_thread);
63 m_thread->start();
64 QTimer::singleShot(0, timer, []() {
65 util::ThreadRename("qt-clientmodl");
66 });
67
69}
70
72{
74
75 m_thread->quit();
76 m_thread->wait();
77}
78
83
97
99{
100 if (cachedBestHeaderHeight == -1) {
101 // make sure we initially populate the cache via a cs_main lock
102 // otherwise we need to wait for a tip update
103 int height;
105 if (m_node.getHeaderTip(height, blockTime)) {
106 cachedBestHeaderHeight = height;
108 }
109 }
111}
112
114{
115 if (cachedBestHeaderTime == -1) {
116 int height;
118 if (m_node.getHeaderTip(height, blockTime)) {
119 cachedBestHeaderHeight = height;
121 }
122 }
124}
125
126
127std::map<CNetAddr, LocalServiceInfo> ClientModel::getNetLocalAddresses() const
128{
130}
131
132
134{
135 if (m_cached_num_blocks == -1) {
137 }
138 return m_cached_num_blocks;
139}
140
142{
144
145 if (!tip.IsNull()) {
146 return tip;
147 }
148
149 // Lock order must be: first `cs_main`, then `m_cached_tip_mutex`.
150 // The following will lock `cs_main` (and release it), so we must not
151 // own `m_cached_tip_mutex` here.
153
155 // We checked that `m_cached_tip_blocks` is not null above, but then we
156 // released the mutex `m_cached_tip_mutex`, so it could have changed in the
157 // meantime. Thus, check again.
158 if (m_cached_tip_blocks.IsNull()) {
160 }
161 return m_cached_tip_blocks;
162}
163
170
172{
173 return QString::fromStdString(m_node.getWarnings().translated);
174}
175
180
185
190
195
197{
198 return QString::fromStdString(FormatFullVersion());
199}
200
202{
203 return QString::fromStdString(strSubVersion);
204}
205
210
212{
213 return QDateTime::currentDateTime().addSecs(-TicksSeconds(GetUptime())).toString();
214}
215
220
225
227{
229 // cache best headers time and height to reduce future cs_main locks
230 cachedBestHeaderHeight = tip.block_height;
231 cachedBestHeaderTime = tip.block_time;
232 } else if (synctype == SyncType::BLOCK_SYNC) {
233 m_cached_num_blocks = tip.block_height;
235 }
236
237 // Throttle GUI notifications about (a) blocks during initial sync, and (b) both blocks and headers during reindex.
239 const auto now{throttle ? SteadyClock::now() : SteadyClock::time_point{}};
242 return;
243 }
244
245 Q_EMIT numBlocksChanged(tip.block_height, QDateTime::fromSecsSinceEpoch(tip.block_time), verification_progress, synctype, sync_state);
247}
248
250{
252 [this](const std::string& title, int progress, [[maybe_unused]] bool resume_possible) {
253 Q_EMIT showProgress(QString::fromStdString(title), progress);
254 }));
256 [this](int new_num_connections) {
257 Q_EMIT numConnectionsChanged(new_num_connections);
258 }));
260 [this](bool network_active) {
261 Q_EMIT networkActiveChanged(network_active);
262 }));
264 [this]() {
265 qDebug() << "ClientModel: NotifyAlertChanged";
266 Q_EMIT alertsChanged(getStatusBarWarnings());
267 }));
269 [this]() {
270 qDebug() << "ClienModel: Requesting update for peer banlist";
271 QMetaObject::invokeMethod(banTableModel, [this] { banTableModel->refresh(); });
272 }));
273 m_event_handlers.emplace_back(m_node.handleNotifyBlockTip(
274 [this](SynchronizationState sync_state, interfaces::BlockTip tip, double verification_progress) {
275 TipChanged(sync_state, tip, verification_progress, SyncType::BLOCK_SYNC);
276 }));
277 m_event_handlers.emplace_back(m_node.handleNotifyHeaderTip(
279 TipChanged(sync_state, tip, /*verification_progress=*/0.0, presync ? SyncType::HEADER_PRESYNC : SyncType::HEADER_SYNC);
280 }));
281}
282
287
288bool ClientModel::getProxyInfo(std::string& ip_port) const
289{
290 Proxy ipv4, ipv6;
291 if (m_node.getProxy((Network) 1, ipv4) && m_node.getProxy((Network) 2, ipv6)) {
293 return true;
294 }
295 return false;
296}
ArgsManager gArgs
Definition args.cpp:40
node::NodeContext m_node
int flags
fs::path GetDataDirNet() const
Get data directory path with appended network identifier.
Definition args.h:239
fs::path GetBlocksDirPath() const
Get blocks directory path.
Definition args.cpp:286
Qt model providing information about banned peers, similar to the "getpeerinfo" RPC call.
std::string ToStringAddrPort() const
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
std::map< CNetAddr, LocalServiceInfo > getNetLocalAddresses() const
int getHeaderTipHeight() const
std::atomic< int64_t > cachedBestHeaderTime
Definition clientmodel.h:96
interfaces::Node & m_node
Mutex m_cached_tip_mutex
Definition clientmodel.h:99
PeerTableModel * getPeerTableModel()
PeerTableSortProxy * peerTableSortProxy()
std::atomic< int > cachedBestHeaderHeight
Definition clientmodel.h:95
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)
ClientModel(interfaces::Node &node, OptionsModel *optionsModel, QObject *parent=nullptr)
OptionsModel * optionsModel
BanTableModel * banTableModel
QThread *const m_thread
A thread to interact with m_node asynchronously.
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 mempoolSizeChanged(long count, size_t mempoolSizeInBytes, size_t mempoolMaxSizeInBytes)
QString dataDir() const
std::atomic< int > m_cached_num_blocks
Definition clientmodel.h:97
OptionsModel * getOptionsModel()
QString formatFullVersion() const
PeerTableModel * peerTableModel
PeerTableSortProxy * m_peer_table_sort_proxy
bool getProxyInfo(std::string &ip_port) const
QString formatSubVersion() const
bool isReleaseVersion() const
void subscribeToCoreSignals()
Interface from Qt to configuration data structure for Bitcoin client.
Qt model providing information about connected peers, similar to the "getpeerinfo" RPC call.
CService proxy
Definition netbase.h:66
Top-level interface for a bitcoin node (bitcoind process).
Definition node.h:70
virtual std::map< CNetAddr, LocalServiceInfo > getNetLocalAddresses()=0
Get network local addresses.
virtual std::unique_ptr< Handler > handleShowProgress(ShowProgressFn fn)=0
virtual bilingual_str getWarnings()=0
Get warnings.
virtual size_t getMempoolMaxUsage()=0
Get mempool maximum memory usage.
virtual std::unique_ptr< Handler > handleNotifyAlertChanged(NotifyAlertChangedFn 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 std::unique_ptr< Handler > handleNotifyNetworkActiveChanged(NotifyNetworkActiveChangedFn 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.
virtual std::unique_ptr< Handler > handleNotifyNumConnectionsChanged(NotifyNumConnectionsChangedFn fn)=0
256-bit opaque blob.
Definition uint256.h:195
static SteadyClock::time_point g_last_block_tip_update_notification
static SteadyClock::time_point g_last_header_tip_update_notification
SyncType
Definition clientmodel.h:42
@ HEADER_PRESYNC
@ CONNECTIONS_IN
Definition clientmodel.h:50
@ CONNECTIONS_OUT
Definition clientmodel.h:51
@ CONNECTIONS_ALL
Definition clientmodel.h:52
BlockSource
Definition clientmodel.h:36
std::string FormatFullVersion()
SteadyClock::duration GetUptime()
Monotonic uptime (not affected by system time changes).
Definition system.cpp:134
static constexpr auto MODEL_UPDATE_DELAY
QString PathToQString(const fs::path &path)
Convert OS specific boost path to QString through UTF-8.
Definition guiutil.cpp:675
void ThreadRename(const std::string &)
Rename a thread both in terms of an internal (in-memory) name as well as its system thread name.
std::string strSubVersion
Subversion as sent to the P2P network in version messages.
Definition net.cpp:120
Network
A network type.
Definition netaddress.h:33
ConnectionDirection
Definition netbase.h:33
std::string translated
Definition translation.h:26
Block tip (could be a header or not, depends on the subscribed signal).
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:289
constexpr int64_t TicksSeconds(Duration d)
Definition time.h:79
constexpr auto Ticks(Dur2 d)
Helper to count the seconds of a duration/time_point.
Definition time.h:73
SynchronizationState
Current sync state passed to tip changed callbacks.
Definition validation.h:93