Bitcoin ABC  0.24.7
P2P Digital Currency
node.cpp
Go to the documentation of this file.
1 // Copyright (c) 2018 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 <interfaces/node.h>
6 
7 #include <addrdb.h>
8 #include <banman.h>
9 #include <chain.h>
10 #include <chainparams.h>
11 #include <config.h>
12 #include <init.h>
13 #include <interfaces/chain.h>
14 #include <interfaces/handler.h>
15 #include <interfaces/wallet.h>
16 #include <net.h>
17 #include <net_processing.h>
18 #include <netaddress.h>
19 #include <netbase.h>
20 #include <node/context.h>
21 #include <node/ui_interface.h>
22 #include <policy/fees.h>
23 #include <policy/settings.h>
24 #include <primitives/block.h>
25 #include <rpc/server.h>
26 #include <shutdown.h>
28 #include <sync.h>
29 #include <txmempool.h>
30 #include <util/check.h>
31 #include <util/ref.h>
32 #include <util/system.h>
33 #include <util/translation.h>
34 #include <validation.h>
35 #include <warnings.h>
36 
37 #if defined(HAVE_CONFIG_H)
38 #include <config/bitcoin-config.h>
39 #endif
40 
41 #include <univalue.h>
42 
43 #include <boost/signals2/signal.hpp>
44 
46 namespace interfaces {
47 namespace {
48 
49  class NodeImpl : public Node {
50  public:
51  NodeImpl(NodeContext *context) { setContext(context); }
52  void initLogging() override { InitLogging(*Assert(m_context->args)); }
53  void initParameterInteraction() override {
55  }
56  bilingual_str getWarnings() override { return GetWarnings(true); }
57  bool baseInitialize(Config &config) override {
58  return AppInitBasicSetup(gArgs) &&
62  }
63  bool appInitMain(Config &config, RPCServer &rpcServer,
64  HTTPRPCRequestProcessor &httpRPCRequestProcessor,
65  interfaces::BlockAndHeaderTipInfo *tip_info) override {
66  return AppInitMain(config, rpcServer, httpRPCRequestProcessor,
67  *m_context, tip_info);
68  }
69  void appShutdown() override {
72  }
73  void startShutdown() override {
74  StartShutdown();
75  // Stop RPC for clean shutdown if any of waitfor* commands is
76  // executed.
77  if (gArgs.GetBoolArg("-server", false)) {
78  InterruptRPC();
79  StopRPC();
80  }
81  }
82  bool shutdownRequested() override { return ShutdownRequested(); }
83  void mapPort(bool use_upnp) override {
84  if (use_upnp) {
85  StartMapPort();
86  } else {
88  StopMapPort();
89  }
90  }
91  bool getProxy(Network net, proxyType &proxy_info) override {
92  return GetProxy(net, proxy_info);
93  }
94  size_t getNodeCount(CConnman::NumConnections flags) override {
95  return m_context->connman ? m_context->connman->GetNodeCount(flags)
96  : 0;
97  }
98  bool getNodesStats(NodesStats &stats) override {
99  stats.clear();
100 
101  if (m_context->connman) {
102  std::vector<CNodeStats> stats_temp;
103  m_context->connman->GetNodeStats(stats_temp);
104 
105  stats.reserve(stats_temp.size());
106  for (auto &node_stats_temp : stats_temp) {
107  stats.emplace_back(std::move(node_stats_temp), false,
108  CNodeStateStats());
109  }
110 
111  // Try to retrieve the CNodeStateStats for each node.
112  TRY_LOCK(::cs_main, lockMain);
113  if (lockMain) {
114  for (auto &node_stats : stats) {
115  std::get<1>(node_stats) =
116  GetNodeStateStats(std::get<0>(node_stats).nodeid,
117  std::get<2>(node_stats));
118  }
119  }
120  return true;
121  }
122  return false;
123  }
124  bool getBanned(banmap_t &banmap) override {
125  if (m_context->banman) {
126  m_context->banman->GetBanned(banmap);
127  return true;
128  }
129  return false;
130  }
131  bool ban(const CNetAddr &net_addr, int64_t ban_time_offset) override {
132  if (m_context->banman) {
133  m_context->banman->Ban(net_addr, ban_time_offset);
134  return true;
135  }
136  return false;
137  }
138  bool unban(const CSubNet &ip) override {
139  if (m_context->banman) {
140  m_context->banman->Unban(ip);
141  return true;
142  }
143  return false;
144  }
145  bool disconnectByAddress(const CNetAddr &net_addr) override {
146  if (m_context->connman) {
147  return m_context->connman->DisconnectNode(net_addr);
148  }
149  return false;
150  }
151  bool disconnectById(NodeId id) override {
152  if (m_context->connman) {
153  return m_context->connman->DisconnectNode(id);
154  }
155  return false;
156  }
157  int64_t getTotalBytesRecv() override {
158  return m_context->connman ? m_context->connman->GetTotalBytesRecv()
159  : 0;
160  }
161  int64_t getTotalBytesSent() override {
162  return m_context->connman ? m_context->connman->GetTotalBytesSent()
163  : 0;
164  }
165  size_t getMempoolSize() override {
166  return m_context->mempool ? m_context->mempool->size() : 0;
167  }
168  size_t getMempoolDynamicUsage() override {
169  return m_context->mempool ? m_context->mempool->DynamicMemoryUsage()
170  : 0;
171  }
172  bool getHeaderTip(int &height, int64_t &block_time) override {
173  LOCK(::cs_main);
174  if (::pindexBestHeader) {
175  height = ::pindexBestHeader->nHeight;
176  block_time = ::pindexBestHeader->GetBlockTime();
177  return true;
178  }
179  return false;
180  }
181  int getNumBlocks() override {
182  LOCK(::cs_main);
184  }
185  BlockHash getBestBlockHash() override {
186  const CBlockIndex *tip =
188  return tip ? tip->GetBlockHash()
189  : Params().GenesisBlock().GetHash();
190  }
191  int64_t getLastBlockTime() override {
192  LOCK(::cs_main);
193  if (::ChainActive().Tip()) {
195  }
196  // Genesis block's time of current network
197  return Params().GenesisBlock().GetBlockTime();
198  }
199  double getVerificationProgress() override {
200  const CBlockIndex *tip;
201  {
202  LOCK(::cs_main);
203  tip = ::ChainActive().Tip();
204  }
205  return GuessVerificationProgress(Params().TxData(), tip);
206  }
207  bool isInitialBlockDownload() override {
209  }
210  bool getReindex() override { return ::fReindex; }
211  bool getImporting() override { return ::fImporting; }
212  void setNetworkActive(bool active) override {
213  if (m_context->connman) {
214  m_context->connman->SetNetworkActive(active);
215  }
216  }
217  bool getNetworkActive() override {
218  return m_context->connman && m_context->connman->GetNetworkActive();
219  }
220  CFeeRate estimateSmartFee() override {
221  return m_context->mempool ? m_context->mempool->estimateFee()
222  : CFeeRate();
223  }
224  CFeeRate getDustRelayFee() override { return ::dustRelayFee; }
225  UniValue executeRpc(Config &config, const std::string &command,
226  const UniValue &params,
227  const std::string &uri) override {
229  req.params = params;
230  req.strMethod = command;
231  req.URI = uri;
232  return ::tableRPC.execute(config, req);
233  }
234  std::vector<std::string> listRpcCommands() override {
236  }
237  void rpcSetTimerInterfaceIfUnset(RPCTimerInterface *iface) override {
239  }
240  void rpcUnsetTimerInterface(RPCTimerInterface *iface) override {
241  RPCUnsetTimerInterface(iface);
242  }
243  bool getUnspentOutput(const COutPoint &output, Coin &coin) override {
244  LOCK(::cs_main);
245  return ::ChainstateActive().CoinsTip().GetCoin(output, coin);
246  }
247  WalletClient &walletClient() override {
248  return *Assert(m_context->wallet_client);
249  }
250  std::unique_ptr<Handler> handleInitMessage(InitMessageFn fn) override {
251  return MakeHandler(::uiInterface.InitMessage_connect(fn));
252  }
253  std::unique_ptr<Handler> handleMessageBox(MessageBoxFn fn) override {
254  return MakeHandler(::uiInterface.ThreadSafeMessageBox_connect(fn));
255  }
256  std::unique_ptr<Handler> handleQuestion(QuestionFn fn) override {
257  return MakeHandler(::uiInterface.ThreadSafeQuestion_connect(fn));
258  }
259  std::unique_ptr<Handler>
260  handleShowProgress(ShowProgressFn fn) override {
261  return MakeHandler(::uiInterface.ShowProgress_connect(fn));
262  }
263  std::unique_ptr<Handler> handleNotifyNumConnectionsChanged(
264  NotifyNumConnectionsChangedFn fn) override {
265  return MakeHandler(
266  ::uiInterface.NotifyNumConnectionsChanged_connect(fn));
267  }
268  std::unique_ptr<Handler> handleNotifyNetworkActiveChanged(
269  NotifyNetworkActiveChangedFn fn) override {
270  return MakeHandler(
271  ::uiInterface.NotifyNetworkActiveChanged_connect(fn));
272  }
273  std::unique_ptr<Handler>
274  handleNotifyAlertChanged(NotifyAlertChangedFn fn) override {
275  return MakeHandler(::uiInterface.NotifyAlertChanged_connect(fn));
276  }
277  std::unique_ptr<Handler>
278  handleBannedListChanged(BannedListChangedFn fn) override {
279  return MakeHandler(::uiInterface.BannedListChanged_connect(fn));
280  }
281  std::unique_ptr<Handler>
282  handleNotifyBlockTip(NotifyBlockTipFn fn) override {
283  return MakeHandler(::uiInterface.NotifyBlockTip_connect(
284  [fn](SynchronizationState sync_state,
285  const CBlockIndex *block) {
286  fn(sync_state,
287  BlockTip{block->nHeight, block->GetBlockTime(),
288  block->GetBlockHash()},
289  GuessVerificationProgress(Params().TxData(), block));
290  }));
291  }
292  std::unique_ptr<Handler>
293  handleNotifyHeaderTip(NotifyHeaderTipFn fn) override {
294  /* verification progress is unused when a header was received */
295  return MakeHandler(::uiInterface.NotifyHeaderTip_connect(
296  [fn](SynchronizationState sync_state,
297  const CBlockIndex *block) {
298  fn(sync_state,
299  BlockTip{block->nHeight, block->GetBlockTime(),
300  block->GetBlockHash()},
301  0);
302  }));
303  }
304  NodeContext *context() override { return m_context; }
305  void setContext(NodeContext *context) override {
306  m_context = context;
307  if (context) {
308  m_context_ref.Set(*context);
309  } else {
311  }
312  }
315  };
316 } // namespace
317 
318 std::unique_ptr<Node> MakeNode(NodeContext *context) {
319  return std::make_unique<NodeImpl>(context);
320 }
321 
322 } // namespace interfaces
CBlockIndex::GetBlockTime
int64_t GetBlockTime() const
Definition: blockindex.h:160
interfaces
Definition: dummywallet.cpp:12
AppInitInterfaces
bool AppInitInterfaces(NodeContext &node)
Initialize node and wallet interface pointers.
Definition: init.cpp:2166
block.h
ShutdownRequested
bool ShutdownRequested()
Definition: shutdown.cpp:18
ArgsManager::GetBoolArg
bool GetBoolArg(const std::string &strArg, bool fDefault) const
Return boolean argument or default value.
Definition: system.cpp:517
ref.h
StopMapPort
void StopMapPort()
Definition: net.cpp:1866
InterruptMapPort
void InterruptMapPort()
Definition: net.cpp:1863
StartMapPort
void StartMapPort()
Definition: net.cpp:1860
check.h
settings.h
ChainActive
CChain & ChainActive()
Please prefer the identical ChainstateManager::ActiveChain.
Definition: validation.cpp:86
InitParameterInteraction
void InitParameterInteraction(ArgsManager &args)
Parameter interaction: change current parameters depending on various rules.
Definition: init.cpp:1562
NodeContext::args
ArgsManager * args
Definition: context.h:44
flags
int flags
Definition: bitcoin-tx.cpp:532
RPCTimerInterface
RPC timer "driver".
Definition: server.h:100
uiInterface
CClientUIInterface uiInterface
Definition: ui_interface.cpp:12
InitLogging
void InitLogging(const ArgsManager &args)
Initialize global loggers.
Definition: init.cpp:1674
NodeContext::mempool
std::unique_ptr< CTxMemPool > mempool
Definition: context.h:38
GetWarnings
bilingual_str GetWarnings(bool verbose)
Format a string that describes several potential problems detected by the core.
Definition: warnings.cpp:41
sync.h
RPCUnsetTimerInterface
void RPCUnsetTimerInterface(RPCTimerInterface *iface)
Unset factory function for timers.
Definition: server.cpp:549
InterruptRPC
void InterruptRPC()
Definition: server.cpp:345
bilingual_str
Bilingual messages:
Definition: translation.h:17
CNetAddr
Network address.
Definition: netaddress.h:117
CBlockIndex::nHeight
int nHeight
height of the entry in the chain. The genesis block has height 0
Definition: blockindex.h:36
util::Ref::Set
void Set(T &value)
Definition: ref.h:29
node.h
handler.h
HTTPRPCRequestProcessor
Definition: httprpc.h:17
WITH_LOCK
#define WITH_LOCK(cs, code)
Run code while locking a mutex.
Definition: sync.h:272
ChainstateActive
CChainState & ChainstateActive()
Please prefer the identical ChainstateManager::ActiveChainstate.
Definition: validation.cpp:80
interfaces::BlockAndHeaderTipInfo
Block and header tip information.
Definition: node.h:46
TRY_LOCK
#define TRY_LOCK(cs, name)
Definition: sync.h:247
chainparams.h
chain.h
Network
Network
A network type.
Definition: netaddress.h:43
CChain::Tip
CBlockIndex * Tip() const
Returns the index entry for the tip of this chain, or nullptr if none.
Definition: chain.h:168
context.h
RPCServer
Class for registering and managing all RPC calls.
Definition: server.h:40
proxyType
Definition: netbase.h:28
Assert
#define Assert(val)
Identity function.
Definition: check.h:56
CFeeRate
Fee rate in satoshis per kilobyte: Amount / kB.
Definition: feerate.h:21
CBlockIndex::GetBlockHash
BlockHash GetBlockHash() const
Definition: blockindex.h:133
UniValue
Definition: univalue.h:23
AppInitMain
bool AppInitMain(Config &config, RPCServer &rpcServer, HTTPRPCRequestProcessor &httpRPCRequestProcessor, NodeContext &node, interfaces::BlockAndHeaderTipInfo *tip_info)
Bitcoin main initialization.
Definition: init.cpp:2176
txmempool.h
shutdown.h
m_context_ref
util::Ref m_context_ref
Definition: node.cpp:314
addrdb.h
Config
Definition: config.h:17
CCoinsViewCache::GetCoin
bool GetCoin(const COutPoint &outpoint, Coin &coin) const override
Retrieve the Coin (unspent transaction output) for a given outpoint.
Definition: coins.cpp:94
util::Ref
Type-safe dynamic reference.
Definition: ref.h:21
banman.h
interfaces::MakeNode
std::unique_ptr< Node > MakeNode(NodeContext *context)
Return implementation of Node interface.
Definition: node.cpp:318
cs_main
RecursiveMutex cs_main
Global state.
Definition: validation.cpp:103
RPCSetTimerInterfaceIfUnset
void RPCSetTimerInterfaceIfUnset(RPCTimerInterface *iface)
Set the factory function for timer, but only, if unset.
Definition: server.cpp:539
CBlockHeader::GetBlockTime
int64_t GetBlockTime() const
Definition: block.h:52
Coin
A UTXO entry.
Definition: coins.h:27
init.h
CConnman::NumConnections
NumConnections
Definition: net.h:223
netaddress.h
univalue.h
tableRPC
CRPCTable tableRPC
Definition: server.cpp:574
pindexBestHeader
CBlockIndex * pindexBestHeader
Best header we've seen so far (used for getheaders queries' starting points).
Definition: validation.cpp:105
CRPCTable::listCommands
std::vector< std::string > listCommands() const
Returns a list of registered commands.
Definition: server.cpp:531
Interrupt
void Interrupt(NodeContext &node)
Interrupt threads.
Definition: init.cpp:164
CSubNet
Definition: netaddress.h:465
CChainParams::GenesisBlock
const CBlock & GenesisBlock() const
Definition: chainparams.h:64
fReindex
std::atomic_bool fReindex
AppInitSanityChecks
bool AppInitSanityChecks()
Initialization sanity checks: ecc init, sanity checks, dir lock.
Definition: init.cpp:2131
net_processing.h
CChain::Height
int Height() const
Return the maximal height in the chain.
Definition: chain.h:204
BlockHash
A BlockHash is a unqiue identifier for a block.
Definition: blockhash.h:13
secure.h
NodeContext::wallet_client
interfaces::WalletClient * wallet_client
Reference to chain client that should used to load or create wallets opened by the gui.
Definition: context.h:51
ui_interface.h
CRPCTable::execute
UniValue execute(const Config &config, const JSONRPCRequest &request) const
Execute a method.
Definition: server.cpp:489
system.h
CChainState::IsInitialBlockDownload
bool IsInitialBlockDownload() const
Check whether we are doing an initial block download (synchronizing from disk or network)
Definition: validation.cpp:897
AppInitLockDataDirectory
bool AppInitLockDataDirectory()
Lock bitcoin data directory.
Definition: init.cpp:2154
NodeContext::banman
std::unique_ptr< BanMan > banman
Definition: context.h:42
AppInitBasicSetup
bool AppInitBasicSetup(ArgsManager &args)
Initialize bitcoin: Basic context setup.
Definition: init.cpp:1723
fees.h
translation.h
m_context
NodeContext * m_context
Definition: node.cpp:313
LOCK
#define LOCK(cs)
Definition: sync.h:241
gArgs
ArgsManager gArgs
Definition: system.cpp:75
GetNodeStateStats
bool GetNodeStateStats(NodeId nodeid, CNodeStateStats &stats)
Get statistics from node state.
Definition: net_processing.cpp:1230
util::Ref::Clear
void Clear()
Definition: ref.h:36
Params
const CChainParams & Params()
Return the currently selected parameters.
Definition: chainparams.cpp:508
GetProxy
bool GetProxy(enum Network net, proxyType &proxyInfoOut)
Definition: netbase.cpp:783
AppInitParameterInteraction
bool AppInitParameterInteraction(Config &config, const ArgsManager &args)
Initialization: parameter interaction.
Definition: init.cpp:1766
fImporting
std::atomic_bool fImporting
wallet.h
config.h
NodeId
int64_t NodeId
Definition: nodeid.h:10
SynchronizationState
SynchronizationState
Current sync state passed to tip changed callbacks.
Definition: validation.h:130
JSONRPCRequest
Definition: request.h:33
banmap_t
std::map< CSubNet, CBanEntry > banmap_t
Definition: net_types.h:13
netbase.h
COutPoint
An outpoint - a combination of a transaction hash and an index n into its vout.
Definition: transaction.h:22
NodeContext::connman
std::unique_ptr< CConnman > connman
Definition: context.h:37
NodeContext
NodeContext struct containing references to chain state and connection state.
Definition: context.h:36
server.h
CNodeStateStats
Definition: net_processing.h:238
net.h
CBlockIndex
The block chain is a tree shaped structure starting with the genesis block at the root,...
Definition: blockindex.h:23
CBlockHeader::GetHash
BlockHash GetHash() const
Definition: block.cpp:11
StopRPC
void StopRPC()
Definition: server.cpp:356
GuessVerificationProgress
double GuessVerificationProgress(const ChainTxData &data, const CBlockIndex *pindex)
Guess how far we are in the verification process at the given block index require cs_main if pindex h...
Definition: validation.cpp:5987
warnings.h
StartShutdown
void StartShutdown()
Definition: shutdown.cpp:12
CChainState::CoinsTip
CCoinsViewCache & CoinsTip() EXCLUSIVE_LOCKS_REQUIRED(cs_main)
Definition: validation.h:837
Shutdown
void Shutdown(NodeContext &node)
Definition: init.cpp:185
dustRelayFee
CFeeRate dustRelayFee
Definition: settings.cpp:11
interfaces::MakeHandler
std::unique_ptr< Handler > MakeHandler(boost::signals2::connection connection)
Return handler wrapping a boost signal connection.
Definition: handler.cpp:48