Bitcoin ABC  0.22.13
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/ref.h>
31 #include <util/system.h>
32 #include <util/translation.h>
33 #include <validation.h>
34 #include <warnings.h>
35 
36 #if defined(HAVE_CONFIG_H)
37 #include <config/bitcoin-config.h>
38 #endif
39 
40 #include <univalue.h>
41 
42 #include <boost/signals2/signal.hpp>
43 
45 class CWallet;
46 fs::path GetWalletDir();
47 std::vector<fs::path> ListWalletDir();
48 std::vector<std::shared_ptr<CWallet>> GetWallets();
49 std::shared_ptr<CWallet> LoadWallet(const CChainParams &chainParams,
51  const std::string &name,
53  std::vector<bilingual_str> &warnings);
56  const SecureString &passphrase,
57  uint64_t wallet_creation_flags,
58  const std::string &name, bilingual_str &error,
59  std::vector<bilingual_str> &warnings,
60  std::shared_ptr<CWallet> &result);
61 std::unique_ptr<interfaces::Handler>
63 
64 namespace interfaces {
65 
66 namespace {
67 
68  class NodeImpl : public Node {
69  public:
70  NodeImpl(NodeContext *context) { setContext(context); }
71  void initLogging() override { InitLogging(*Assert(m_context->args)); }
72  void initParameterInteraction() override {
74  }
75  std::string getWarnings() override { return GetWarnings(true); }
76  bool baseInitialize(Config &config) override {
77  return AppInitBasicSetup(gArgs) &&
80  }
81  bool
82  appInitMain(Config &config, RPCServer &rpcServer,
83  HTTPRPCRequestProcessor &httpRPCRequestProcessor) override {
85  return AppInitMain(config, rpcServer, httpRPCRequestProcessor,
86  *m_context);
87  }
88  void appShutdown() override {
91  }
92  void startShutdown() override { StartShutdown(); }
93  bool shutdownRequested() override { return ShutdownRequested(); }
94  void mapPort(bool use_upnp) override {
95  if (use_upnp) {
96  StartMapPort();
97  } else {
99  StopMapPort();
100  }
101  }
102  bool getProxy(Network net, proxyType &proxy_info) override {
103  return GetProxy(net, proxy_info);
104  }
105  size_t getNodeCount(CConnman::NumConnections flags) override {
106  return m_context->connman ? m_context->connman->GetNodeCount(flags)
107  : 0;
108  }
109  bool getNodesStats(NodesStats &stats) override {
110  stats.clear();
111 
112  if (m_context->connman) {
113  std::vector<CNodeStats> stats_temp;
114  m_context->connman->GetNodeStats(stats_temp);
115 
116  stats.reserve(stats_temp.size());
117  for (auto &node_stats_temp : stats_temp) {
118  stats.emplace_back(std::move(node_stats_temp), false,
119  CNodeStateStats());
120  }
121 
122  // Try to retrieve the CNodeStateStats for each node.
123  TRY_LOCK(::cs_main, lockMain);
124  if (lockMain) {
125  for (auto &node_stats : stats) {
126  std::get<1>(node_stats) =
127  GetNodeStateStats(std::get<0>(node_stats).nodeid,
128  std::get<2>(node_stats));
129  }
130  }
131  return true;
132  }
133  return false;
134  }
135  bool getBanned(banmap_t &banmap) override {
136  if (m_context->banman) {
137  m_context->banman->GetBanned(banmap);
138  return true;
139  }
140  return false;
141  }
142  bool ban(const CNetAddr &net_addr, int64_t ban_time_offset) override {
143  if (m_context->banman) {
144  m_context->banman->Ban(net_addr, ban_time_offset);
145  return true;
146  }
147  return false;
148  }
149  bool unban(const CSubNet &ip) override {
150  if (m_context->banman) {
151  m_context->banman->Unban(ip);
152  return true;
153  }
154  return false;
155  }
156  bool disconnectByAddress(const CNetAddr &net_addr) override {
157  if (m_context->connman) {
158  return m_context->connman->DisconnectNode(net_addr);
159  }
160  return false;
161  }
162  bool disconnectById(NodeId id) override {
163  if (m_context->connman) {
164  return m_context->connman->DisconnectNode(id);
165  }
166  return false;
167  }
168  int64_t getTotalBytesRecv() override {
169  return m_context->connman ? m_context->connman->GetTotalBytesRecv()
170  : 0;
171  }
172  int64_t getTotalBytesSent() override {
173  return m_context->connman ? m_context->connman->GetTotalBytesSent()
174  : 0;
175  }
176  size_t getMempoolSize() override {
177  return m_context->mempool ? m_context->mempool->size() : 0;
178  }
179  size_t getMempoolDynamicUsage() override {
181  : 0;
182  }
183  bool getHeaderTip(int &height, int64_t &block_time) override {
184  LOCK(::cs_main);
185  if (::pindexBestHeader) {
186  height = ::pindexBestHeader->nHeight;
187  block_time = ::pindexBestHeader->GetBlockTime();
188  return true;
189  }
190  return false;
191  }
192  int getNumBlocks() override {
193  LOCK(::cs_main);
195  }
196  int64_t getLastBlockTime() override {
197  LOCK(::cs_main);
198  if (::ChainActive().Tip()) {
200  }
201  // Genesis block's time of current network
202  return Params().GenesisBlock().GetBlockTime();
203  }
204  double getVerificationProgress() override {
205  const CBlockIndex *tip;
206  {
207  LOCK(::cs_main);
208  tip = ::ChainActive().Tip();
209  }
210  return GuessVerificationProgress(Params().TxData(), tip);
211  }
212  bool isInitialBlockDownload() override {
214  }
215  bool getReindex() override { return ::fReindex; }
216  bool getImporting() override { return ::fImporting; }
217  void setNetworkActive(bool active) override {
218  if (m_context->connman) {
219  m_context->connman->SetNetworkActive(active);
220  }
221  }
222  bool getNetworkActive() override {
223  return m_context->connman && m_context->connman->GetNetworkActive();
224  }
225  CFeeRate estimateSmartFee() override {
227  : CFeeRate();
228  }
229  CFeeRate getDustRelayFee() override { return ::dustRelayFee; }
230  UniValue executeRpc(Config &config, const std::string &command,
231  const UniValue &params,
232  const std::string &uri) override {
234  req.params = params;
235  req.strMethod = command;
236  req.URI = uri;
237  return ::tableRPC.execute(config, req);
238  }
239  std::vector<std::string> listRpcCommands() override {
241  }
242  void rpcSetTimerInterfaceIfUnset(RPCTimerInterface *iface) override {
244  }
245  void rpcUnsetTimerInterface(RPCTimerInterface *iface) override {
246  RPCUnsetTimerInterface(iface);
247  }
248  bool getUnspentOutput(const COutPoint &output, Coin &coin) override {
249  LOCK(::cs_main);
250  return ::ChainstateActive().CoinsTip().GetCoin(output, coin);
251  }
252  std::string getWalletDir() override { return GetWalletDir().string(); }
253  std::vector<std::string> listWalletDir() override {
254  std::vector<std::string> paths;
255  for (auto &path : ListWalletDir()) {
256  paths.push_back(path.string());
257  }
258  return paths;
259  }
260  std::vector<std::unique_ptr<Wallet>> getWallets() override {
261  std::vector<std::unique_ptr<Wallet>> wallets;
262  for (auto &client : m_context->chain_clients) {
263  auto client_wallets = client->getWallets();
264  std::move(client_wallets.begin(), client_wallets.end(),
265  std::back_inserter(wallets));
266  }
267  return wallets;
268  }
269  std::unique_ptr<Wallet>
270  loadWallet(const CChainParams &params, const std::string &name,
272  std::vector<bilingual_str> &warnings) const override {
273  return MakeWallet(
274  LoadWallet(params, *m_context->chain, name, error, warnings));
275  }
276  std::unique_ptr<Wallet>
277  createWallet(const CChainParams &params, const SecureString &passphrase,
278  uint64_t wallet_creation_flags, const std::string &name,
279  bilingual_str &error, std::vector<bilingual_str> &warnings,
280  WalletCreationStatus &status) override {
281  std::shared_ptr<CWallet> wallet;
282  status = CreateWallet(params, *m_context->chain, passphrase,
283  wallet_creation_flags, name, error, warnings,
284  wallet);
285  return MakeWallet(wallet);
286  }
287  std::unique_ptr<Handler> handleInitMessage(InitMessageFn fn) override {
288  return MakeHandler(::uiInterface.InitMessage_connect(fn));
289  }
290  std::unique_ptr<Handler> handleMessageBox(MessageBoxFn fn) override {
291  return MakeHandler(::uiInterface.ThreadSafeMessageBox_connect(fn));
292  }
293  std::unique_ptr<Handler> handleQuestion(QuestionFn fn) override {
294  return MakeHandler(::uiInterface.ThreadSafeQuestion_connect(fn));
295  }
296  std::unique_ptr<Handler>
297  handleShowProgress(ShowProgressFn fn) override {
298  return MakeHandler(::uiInterface.ShowProgress_connect(fn));
299  }
300  std::unique_ptr<Handler> handleLoadWallet(LoadWalletFn fn) override {
301  return HandleLoadWallet(std::move(fn));
302  }
303  std::unique_ptr<Handler> handleNotifyNumConnectionsChanged(
304  NotifyNumConnectionsChangedFn fn) override {
305  return MakeHandler(
306  ::uiInterface.NotifyNumConnectionsChanged_connect(fn));
307  }
308  std::unique_ptr<Handler> handleNotifyNetworkActiveChanged(
309  NotifyNetworkActiveChangedFn fn) override {
310  return MakeHandler(
311  ::uiInterface.NotifyNetworkActiveChanged_connect(fn));
312  }
313  std::unique_ptr<Handler>
314  handleNotifyAlertChanged(NotifyAlertChangedFn fn) override {
315  return MakeHandler(::uiInterface.NotifyAlertChanged_connect(fn));
316  }
317  std::unique_ptr<Handler>
318  handleBannedListChanged(BannedListChangedFn fn) override {
319  return MakeHandler(::uiInterface.BannedListChanged_connect(fn));
320  }
321  std::unique_ptr<Handler>
322  handleNotifyBlockTip(NotifyBlockTipFn fn) override {
323  return MakeHandler(::uiInterface.NotifyBlockTip_connect(
324  [fn](SynchronizationState sync_state,
325  const CBlockIndex *block) {
326  fn(sync_state, block->nHeight, block->GetBlockTime(),
327  GuessVerificationProgress(Params().TxData(), block));
328  }));
329  }
330  std::unique_ptr<Handler>
331  handleNotifyHeaderTip(NotifyHeaderTipFn fn) override {
332  /* verification progress is unused when a header was received */
333  return MakeHandler(::uiInterface.NotifyHeaderTip_connect(
334  [fn](SynchronizationState sync_state,
335  const CBlockIndex *block) {
336  fn(sync_state, block->nHeight, block->GetBlockTime(), 0);
337  }));
338  }
339  NodeContext *context() override { return m_context; }
340  void setContext(NodeContext *context) override {
341  m_context = context;
342  if (context) {
343  m_context_ref.Set(*context);
344  } else {
346  }
347  }
350  };
351 } // namespace
352 
353 std::unique_ptr<Node> MakeNode(NodeContext *context) {
354  return std::make_unique<NodeImpl>(context);
355 }
356 
357 } // namespace interfaces
std::vector< std::unique_ptr< interfaces::ChainClient > > chain_clients
Definition: context.h:46
bool ShutdownRequested()
Definition: shutdown.cpp:18
RPC timer "driver".
Definition: server.h:98
void InitLogging(const ArgsManager &args)
Initialize global loggers.
Definition: init.cpp:1601
SynchronizationState
Current sync state passed to tip changed callbacks.
Definition: validation.h:128
int64_t GetBlockTime() const
Definition: blockindex.h:160
#define TRY_LOCK(cs, name)
Definition: sync.h:236
void Shutdown(NodeContext &node)
Definition: init.cpp:178
A UTXO entry.
Definition: coins.h:27
Bilingual messages:
Definition: translation.h:17
CChain & ChainActive()
Definition: validation.cpp:78
std::unique_ptr< BanMan > banman
Definition: context.h:42
bool GetNodeStateStats(NodeId nodeid, CNodeStateStats &stats)
Get statistics from node state.
size_t DynamicMemoryUsage() const
Definition: txmempool.cpp:1058
util::Ref m_context_ref
Definition: node.cpp:349
int Height() const
Return the maximal height in the chain.
Definition: chain.h:210
std::basic_string< char, std::char_traits< char >, secure_allocator< char > > SecureString
Definition: secure.h:56
std::unique_ptr< interfaces::Chain > chain
Definition: context.h:45
unsigned long size() const
Definition: txmempool.h:763
CFeeRate estimateFee() const
Definition: txmempool.cpp:941
std::shared_ptr< CWallet > LoadWallet(const CChainParams &chainParams, interfaces::Chain &chain, const std::string &name, bilingual_str &error, std::vector< bilingual_str > &warnings)
Definition: dummywallet.cpp:57
const CBlock & GenesisBlock() const
Definition: chainparams.h:64
CChainParams defines various tweakable parameters of a given instance of the Bitcoin system...
Definition: chainparams.h:47
std::unique_ptr< Handler > MakeHandler(boost::signals2::connection connection)
Return handler wrapping a boost signal connection.
Definition: handler.cpp:48
WalletCreationStatus
Definition: wallet.h:68
virtual const CChainParams & GetChainParams() const =0
void RPCUnsetTimerInterface(RPCTimerInterface *iface)
Unset factory function for timers.
Definition: server.cpp:538
CChainState & ChainstateActive()
Definition: validation.cpp:72
interfaces::Chain & chain() const
Interface for accessing chain state.
Definition: wallet.h:896
void Set(T &value)
Definition: ref.h:29
std::vector< std::shared_ptr< CWallet > > GetWallets()
Definition: dummywallet.cpp:53
void StopMapPort()
Definition: net.cpp:1738
CRPCTable tableRPC
Definition: server.cpp:563
bool AppInitSanityChecks()
Initialization sanity checks: ecc init, sanity checks, dir lock.
Definition: init.cpp:2057
Definition: config.h:19
NodeContext struct containing references to chain state and connection state.
Definition: context.h:35
std::unique_ptr< CConnman > connman
Definition: context.h:36
void Interrupt(NodeContext &node)
Interrupt threads.
Definition: init.cpp:157
CBlockIndex * pindexBestHeader
Best header we&#39;ve seen so far (used for getheaders queries&#39; starting points).
Definition: validation.cpp:97
fs::path GetWalletDir()
Definition: dummywallet.cpp:45
#define LOCK(cs)
Definition: sync.h:230
const char * name
Definition: rest.cpp:43
RecursiveMutex cs_main
Global state.
Definition: validation.cpp:95
std::unique_ptr< interfaces::Handler > HandleLoadWallet(interfaces::Node::LoadWalletFn load_wallet)
Network
Definition: netaddress.h:19
Class for registering and managing all RPC calls.
Definition: server.h:41
int64_t NodeId
Definition: net.h:99
NumConnections
Definition: net.h:167
std::atomic_bool fImporting
std::function< void(std::unique_ptr< interfaces::Wallet > wallet)> LoadWalletFn
Definition: dummywallet.cpp:76
std::function< void(std::unique_ptr< Wallet > wallet)> LoadWalletFn
Register handler for load wallet messages.
Definition: node.h:213
An outpoint - a combination of a transaction hash and an index n into its vout.
Definition: transaction.h:22
int64_t GetBlockTime() const
Definition: block.h:59
WalletCreationStatus CreateWallet(const CChainParams &params, interfaces::Chain &chain, const SecureString &passphrase, uint64_t wallet_creation_flags, const std::string &name, bilingual_str &error, std::vector< bilingual_str > &warnings, std::shared_ptr< CWallet > &result)
Definition: dummywallet.cpp:65
std::unique_ptr< Wallet > MakeWallet(const std::shared_ptr< CWallet > &wallet)
Return implementation of Wallet interface.
Definition: dummywallet.cpp:84
Type-safe dynamic reference.
Definition: ref.h:21
void RPCSetTimerInterfaceIfUnset(RPCTimerInterface *iface)
Set the factory function for timer, but only, if unset.
Definition: server.cpp:528
int flags
Definition: bitcoin-tx.cpp:529
std::atomic_bool fReindex
IP address (IPv6, or IPv4 using mapped IPv6 range (::FFFF:0:0/96))
Definition: netaddress.h:30
ArgsManager * args
Definition: context.h:44
bool GetCoin(const COutPoint &outpoint, Coin &coin) const override
Retrieve the Coin (unspent transaction output) for a given outpoint.
Definition: coins.cpp:94
Interface giving clients (wallet processes, maybe other analysis tools in the future) ability to acce...
Definition: chain.h:105
The block chain is a tree shaped structure starting with the genesis block at the root...
Definition: blockindex.h:23
const CChainParams & Params()
Return the currently selected parameters.
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...
bool AppInitBasicSetup(ArgsManager &args)
Initialize bitcoin: Basic context setup.
Definition: init.cpp:1648
CBlockIndex * Tip() const
Returns the index entry for the tip of this chain, or nullptr if none.
Definition: chain.h:168
bool IsInitialBlockDownload() const
Check whether we are doing an initial block download (synchronizing from disk or network) ...
Definition: validation.cpp:901
A CWallet maintains a set of transactions and balances, and provides the ability to create new transa...
Definition: wallet.h:679
ArgsManager gArgs
Definition: system.cpp:76
Fee rate in satoshis per kilobyte: Amount / kB.
Definition: feerate.h:21
NodeContext * m_context
Definition: node.cpp:348
std::string GetWarnings(bool verbose)
Format a string that describes several potential problems detected by the core.
Definition: warnings.cpp:38
void StartShutdown()
Definition: shutdown.cpp:12
CCoinsViewCache & CoinsTip() EXCLUSIVE_LOCKS_REQUIRED(cs_main)
Definition: validation.h:775
std::map< CSubNet, CBanEntry > banmap_t
Definition: net_types.h:13
bool GetProxy(enum Network net, proxyType &proxyInfoOut)
Definition: netbase.cpp:782
bool AppInitLockDataDirectory()
Lock bitcoin data directory.
Definition: init.cpp:2080
UniValue execute(Config &config, const JSONRPCRequest &request) const
Execute a method.
Definition: server.cpp:478
CClientUIInterface uiInterface
int nHeight
height of the entry in the chain. The genesis block has height 0
Definition: blockindex.h:36
std::vector< std::string > listCommands() const
Returns a list of registered commands.
Definition: server.cpp:520
std::unique_ptr< Node > MakeNode(NodeContext *context)
Return implementation of Node interface.
Definition: node.cpp:353
void Clear()
Definition: ref.h:36
bool error(const char *fmt, const Args &... args)
Definition: system.h:47
CFeeRate dustRelayFee
Definition: settings.cpp:11
void StartMapPort()
Definition: net.cpp:1732
void InitParameterInteraction(ArgsManager &args)
Parameter interaction: change current parameters depending on various rules.
Definition: init.cpp:1489
bool AppInitMain(Config &config, RPCServer &rpcServer, HTTPRPCRequestProcessor &httpRPCRequestProcessor, NodeContext &node)
Bitcoin main initialization.
Definition: init.cpp:2092
void InterruptMapPort()
Definition: net.cpp:1735
std::vector< fs::path > ListWalletDir()
Definition: dummywallet.cpp:49
#define Assert(val)
Identity function.
Definition: check.h:57
bool AppInitParameterInteraction(Config &config, const ArgsManager &args)
Initialization: parameter interaction.
Definition: init.cpp:1691
std::unique_ptr< Chain > MakeChain(NodeContext &node, const CChainParams &params)
Return implementation of Chain interface.
Definition: chain.cpp:448
CTxMemPool * mempool
Definition: context.h:38