Bitcoin Core  0.19.99
P2P Digital Currency
node.cpp
Go to the documentation of this file.
1 // Copyright (c) 2018-2020 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 <init.h>
12 #include <interfaces/chain.h>
13 #include <interfaces/handler.h>
14 #include <interfaces/wallet.h>
15 #include <net.h>
16 #include <net_processing.h>
17 #include <netaddress.h>
18 #include <netbase.h>
19 #include <node/context.h>
20 #include <policy/feerate.h>
21 #include <policy/fees.h>
22 #include <policy/settings.h>
23 #include <primitives/block.h>
24 #include <rpc/server.h>
25 #include <shutdown.h>
27 #include <sync.h>
28 #include <txmempool.h>
29 #include <ui_interface.h>
30 #include <util/system.h>
31 #include <validation.h>
32 #include <warnings.h>
33 
34 #if defined(HAVE_CONFIG_H)
35 #include <config/bitcoin-config.h>
36 #endif
37 
38 #include <univalue.h>
39 
40 #include <boost/signals2/signal.hpp>
41 
42 class CWallet;
43 fs::path GetWalletDir();
44 std::vector<fs::path> ListWalletDir();
45 std::vector<std::shared_ptr<CWallet>> GetWallets();
46 std::shared_ptr<CWallet> LoadWallet(interfaces::Chain& chain, const std::string& name, std::string& error, std::vector<std::string>& warnings);
47 WalletCreationStatus CreateWallet(interfaces::Chain& chain, const SecureString& passphrase, uint64_t wallet_creation_flags, const std::string& name, std::string& error, std::vector<std::string>& warnings, std::shared_ptr<CWallet>& result);
48 std::unique_ptr<interfaces::Handler> HandleLoadWallet(interfaces::Node::LoadWalletFn load_wallet);
49 
50 namespace interfaces {
51 
52 namespace {
53 
54 class NodeImpl : public Node
55 {
56 public:
57  void initError(const std::string& message) override { InitError(message); }
58  bool parseParameters(int argc, const char* const argv[], std::string& error) override
59  {
60  return gArgs.ParseParameters(argc, argv, error);
61  }
62  bool readConfigFiles(std::string& error) override { return gArgs.ReadConfigFiles(error, true); }
63  void forceSetArg(const std::string& arg, const std::string& value) override { gArgs.ForceSetArg(arg, value); }
64  bool softSetArg(const std::string& arg, const std::string& value) override { return gArgs.SoftSetArg(arg, value); }
65  bool softSetBoolArg(const std::string& arg, bool value) override { return gArgs.SoftSetBoolArg(arg, value); }
66  void selectParams(const std::string& network) override { SelectParams(network); }
67  uint64_t getAssumedBlockchainSize() override { return Params().AssumedBlockchainSize(); }
68  uint64_t getAssumedChainStateSize() override { return Params().AssumedChainStateSize(); }
69  std::string getNetwork() override { return Params().NetworkIDString(); }
70  void initLogging() override { InitLogging(); }
71  void initParameterInteraction() override { InitParameterInteraction(); }
72  std::string getWarnings() override { return GetWarnings(true); }
73  uint32_t getLogCategories() override { return LogInstance().GetCategoryMask(); }
74  bool baseInitialize() override
75  {
78  }
79  bool appInitMain() override
80  {
82  return AppInitMain(m_context);
83  }
84  void appShutdown() override
85  {
88  }
89  void startShutdown() override { StartShutdown(); }
90  bool shutdownRequested() override { return ShutdownRequested(); }
91  void mapPort(bool use_upnp) override
92  {
93  if (use_upnp) {
94  StartMapPort();
95  } else {
97  StopMapPort();
98  }
99  }
100  void setupServerArgs() override { return SetupServerArgs(); }
101  bool getProxy(Network net, proxyType& proxy_info) override { return GetProxy(net, proxy_info); }
102  size_t getNodeCount(CConnman::NumConnections flags) override
103  {
104  return m_context.connman ? m_context.connman->GetNodeCount(flags) : 0;
105  }
106  bool getNodesStats(NodesStats& stats) override
107  {
108  stats.clear();
109 
110  if (m_context.connman) {
111  std::vector<CNodeStats> stats_temp;
112  m_context.connman->GetNodeStats(stats_temp);
113 
114  stats.reserve(stats_temp.size());
115  for (auto& node_stats_temp : stats_temp) {
116  stats.emplace_back(std::move(node_stats_temp), false, CNodeStateStats());
117  }
118 
119  // Try to retrieve the CNodeStateStats for each node.
120  TRY_LOCK(::cs_main, lockMain);
121  if (lockMain) {
122  for (auto& node_stats : stats) {
123  std::get<1>(node_stats) =
124  GetNodeStateStats(std::get<0>(node_stats).nodeid, std::get<2>(node_stats));
125  }
126  }
127  return true;
128  }
129  return false;
130  }
131  bool getBanned(banmap_t& banmap) override
132  {
133  if (m_context.banman) {
134  m_context.banman->GetBanned(banmap);
135  return true;
136  }
137  return false;
138  }
139  bool ban(const CNetAddr& net_addr, BanReason reason, int64_t ban_time_offset) override
140  {
141  if (m_context.banman) {
142  m_context.banman->Ban(net_addr, reason, ban_time_offset);
143  return true;
144  }
145  return false;
146  }
147  bool unban(const CSubNet& ip) override
148  {
149  if (m_context.banman) {
150  m_context.banman->Unban(ip);
151  return true;
152  }
153  return false;
154  }
155  bool disconnectByAddress(const CNetAddr& net_addr) override
156  {
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  {
164  if (m_context.connman) {
165  return m_context.connman->DisconnectNode(id);
166  }
167  return false;
168  }
169  int64_t getTotalBytesRecv() override { return m_context.connman ? m_context.connman->GetTotalBytesRecv() : 0; }
170  int64_t getTotalBytesSent() override { return m_context.connman ? m_context.connman->GetTotalBytesSent() : 0; }
171  size_t getMempoolSize() override { return m_context.mempool ? m_context.mempool->size() : 0; }
172  size_t getMempoolDynamicUsage() override { return m_context.mempool ? m_context.mempool->DynamicMemoryUsage() : 0; }
173  bool getHeaderTip(int& height, int64_t& block_time) override
174  {
175  LOCK(::cs_main);
176  if (::pindexBestHeader) {
177  height = ::pindexBestHeader->nHeight;
178  block_time = ::pindexBestHeader->GetBlockTime();
179  return true;
180  }
181  return false;
182  }
183  int getNumBlocks() override
184  {
185  LOCK(::cs_main);
187  }
188  int64_t getLastBlockTime() override
189  {
190  LOCK(::cs_main);
191  if (::ChainActive().Tip()) {
193  }
194  return Params().GenesisBlock().GetBlockTime(); // Genesis block's time of current network
195  }
196  double getVerificationProgress() override
197  {
198  const CBlockIndex* tip;
199  {
200  LOCK(::cs_main);
201  tip = ::ChainActive().Tip();
202  }
203  return GuessVerificationProgress(Params().TxData(), tip);
204  }
205  bool isInitialBlockDownload() override { return ::ChainstateActive().IsInitialBlockDownload(); }
206  bool getReindex() override { return ::fReindex; }
207  bool getImporting() override { return ::fImporting; }
208  void setNetworkActive(bool active) override
209  {
210  if (m_context.connman) {
211  m_context.connman->SetNetworkActive(active);
212  }
213  }
214  bool getNetworkActive() override { return m_context.connman && m_context.connman->GetNetworkActive(); }
215  CFeeRate estimateSmartFee(int num_blocks, bool conservative, int* returned_target = nullptr) override
216  {
217  FeeCalculation fee_calc;
218  CFeeRate result = ::feeEstimator.estimateSmartFee(num_blocks, &fee_calc, conservative);
219  if (returned_target) {
220  *returned_target = fee_calc.returnedTarget;
221  }
222  return result;
223  }
224  CFeeRate getDustRelayFee() override { return ::dustRelayFee; }
225  UniValue executeRpc(const std::string& command, const UniValue& params, const std::string& uri) override
226  {
227  JSONRPCRequest req;
228  req.params = params;
229  req.strMethod = command;
230  req.URI = uri;
232  }
233  std::vector<std::string> listRpcCommands() override { return ::tableRPC.listCommands(); }
234  void rpcSetTimerInterfaceIfUnset(RPCTimerInterface* iface) override { RPCSetTimerInterfaceIfUnset(iface); }
235  void rpcUnsetTimerInterface(RPCTimerInterface* iface) override { RPCUnsetTimerInterface(iface); }
236  bool getUnspentOutput(const COutPoint& output, Coin& coin) override
237  {
238  LOCK(::cs_main);
239  return ::ChainstateActive().CoinsTip().GetCoin(output, coin);
240  }
241  std::string getWalletDir() override
242  {
243  return GetWalletDir().string();
244  }
245  std::vector<std::string> listWalletDir() override
246  {
247  std::vector<std::string> paths;
248  for (auto& path : ListWalletDir()) {
249  paths.push_back(path.string());
250  }
251  return paths;
252  }
253  std::vector<std::unique_ptr<Wallet>> getWallets() override
254  {
255  std::vector<std::unique_ptr<Wallet>> wallets;
256  for (const std::shared_ptr<CWallet>& wallet : GetWallets()) {
257  wallets.emplace_back(MakeWallet(wallet));
258  }
259  return wallets;
260  }
261  std::unique_ptr<Wallet> loadWallet(const std::string& name, std::string& error, std::vector<std::string>& warnings) override
262  {
263  return MakeWallet(LoadWallet(*m_context.chain, name, error, warnings));
264  }
265  std::unique_ptr<Wallet> createWallet(const SecureString& passphrase, uint64_t wallet_creation_flags, const std::string& name, std::string& error, std::vector<std::string>& warnings, WalletCreationStatus& status) override
266  {
267  std::shared_ptr<CWallet> wallet;
268  status = CreateWallet(*m_context.chain, passphrase, wallet_creation_flags, name, error, warnings, wallet);
269  return MakeWallet(wallet);
270  }
271  std::unique_ptr<Handler> handleInitMessage(InitMessageFn fn) override
272  {
273  return MakeHandler(::uiInterface.InitMessage_connect(fn));
274  }
275  std::unique_ptr<Handler> handleMessageBox(MessageBoxFn fn) override
276  {
277  return MakeHandler(::uiInterface.ThreadSafeMessageBox_connect(fn));
278  }
279  std::unique_ptr<Handler> handleQuestion(QuestionFn fn) override
280  {
281  return MakeHandler(::uiInterface.ThreadSafeQuestion_connect(fn));
282  }
283  std::unique_ptr<Handler> handleShowProgress(ShowProgressFn fn) override
284  {
285  return MakeHandler(::uiInterface.ShowProgress_connect(fn));
286  }
287  std::unique_ptr<Handler> handleLoadWallet(LoadWalletFn fn) override
288  {
289  return HandleLoadWallet(std::move(fn));
290  }
291  std::unique_ptr<Handler> handleNotifyNumConnectionsChanged(NotifyNumConnectionsChangedFn fn) override
292  {
293  return MakeHandler(::uiInterface.NotifyNumConnectionsChanged_connect(fn));
294  }
295  std::unique_ptr<Handler> handleNotifyNetworkActiveChanged(NotifyNetworkActiveChangedFn fn) override
296  {
297  return MakeHandler(::uiInterface.NotifyNetworkActiveChanged_connect(fn));
298  }
299  std::unique_ptr<Handler> handleNotifyAlertChanged(NotifyAlertChangedFn fn) override
300  {
301  return MakeHandler(::uiInterface.NotifyAlertChanged_connect(fn));
302  }
303  std::unique_ptr<Handler> handleBannedListChanged(BannedListChangedFn fn) override
304  {
305  return MakeHandler(::uiInterface.BannedListChanged_connect(fn));
306  }
307  std::unique_ptr<Handler> handleNotifyBlockTip(NotifyBlockTipFn fn) override
308  {
309  return MakeHandler(::uiInterface.NotifyBlockTip_connect([fn](bool initial_download, const CBlockIndex* block) {
310  fn(initial_download, block->nHeight, block->GetBlockTime(),
311  GuessVerificationProgress(Params().TxData(), block));
312  }));
313  }
314  std::unique_ptr<Handler> handleNotifyHeaderTip(NotifyHeaderTipFn fn) override
315  {
316  return MakeHandler(
317  ::uiInterface.NotifyHeaderTip_connect([fn](bool initial_download, const CBlockIndex* block) {
318  fn(initial_download, block->nHeight, block->GetBlockTime(),
319  /* verification progress is unused when a header was received */ 0);
320  }));
321  }
322  NodeContext* context() override { return &m_context; }
324 };
325 
326 } // namespace
327 
328 std::unique_ptr<Node> MakeNode() { return MakeUnique<NodeImpl>(); }
329 
330 } // namespace interfaces
NODISCARD bool ReadConfigFiles(std::string &error, bool ignore_invalid_keys=false)
Definition: system.cpp:736
std::string NetworkIDString() const
Return the network string.
Definition: chainparams.h:81
bool ShutdownRequested()
Definition: shutdown.cpp:20
RPC timer "driver".
Definition: server.h:56
bool AppInitMain(NodeContext &node)
Bitcoin core main initialization.
Definition: init.cpp:1192
BCLog::Logger & LogInstance()
Definition: logging.cpp:14
BanReason
Definition: addrdb.h:20
void InitLogging()
Initialize global loggers.
Definition: init.cpp:832
int64_t GetBlockTime() const
Definition: chain.h:247
int returnedTarget
Definition: fees.h:80
#define TRY_LOCK(cs, name)
Definition: sync.h:222
bool SoftSetBoolArg(const std::string &strArg, bool fValue)
Set a boolean argument if it doesn&#39;t already have a value.
Definition: system.cpp:398
void Shutdown(NodeContext &node)
Definition: init.cpp:173
A UTXO entry.
Definition: coins.h:30
CChain & ChainActive()
Definition: validation.cpp:90
std::unique_ptr< BanMan > banman
Definition: context.h:35
uint64_t AssumedChainStateSize() const
Minimum free space (in GB) needed for data directory when pruned; Does not include prune target...
Definition: chainparams.h:77
bool GetNodeStateStats(NodeId nodeid, CNodeStateStats &stats)
Get statistics from node state.
size_t DynamicMemoryUsage() const
Definition: txmempool.cpp:916
std::shared_ptr< CWallet > LoadWallet(interfaces::Chain &chain, const std::string &name, std::string &error, std::vector< std::string > &warnings)
Definition: dummywallet.cpp:75
int Height() const
Return the maximal height in the chain.
Definition: chain.h:421
std::basic_string< char, std::char_traits< char >, secure_allocator< char > > SecureString
Definition: secure.h:60
std::unique_ptr< interfaces::Chain > chain
Definition: context.h:36
WalletCreationStatus CreateWallet(interfaces::Chain &chain, const SecureString &passphrase, uint64_t wallet_creation_flags, const std::string &name, std::string &error, std::vector< std::string > &warnings, std::shared_ptr< CWallet > &result)
Definition: dummywallet.cpp:80
unsigned long size() const
Definition: txmempool.h:677
const CBlock & GenesisBlock() const
Definition: chainparams.h:64
NODISCARD bool ParseParameters(int argc, const char *const argv[], std::string &error)
Definition: system.cpp:275
std::unique_ptr< Handler > MakeHandler(boost::signals2::connection connection)
Return handler wrapping a boost signal connection.
Definition: handler.cpp:36
void ForceSetArg(const std::string &strArg, const std::string &strValue)
Definition: system.cpp:406
WalletCreationStatus
Definition: wallet.h:58
bool AppInitBasicSetup()
Initialize bitcoin core: Basic context setup.
Definition: init.cpp:876
bool SoftSetArg(const std::string &strArg, const std::string &strValue)
Set an argument if it doesn&#39;t already have a value.
Definition: system.cpp:390
std::unique_ptr< Chain > MakeChain(NodeContext &node)
Return implementation of Chain interface.
Definition: chain.cpp:386
void RPCUnsetTimerInterface(RPCTimerInterface *iface)
Unset factory function for timers.
Definition: server.cpp:479
interfaces::Chain & chain() const
Interface for accessing chain state.
Definition: wallet.h:786
UniValue execute(const JSONRPCRequest &request) const
Execute a method.
Definition: server.cpp:421
void InitParameterInteraction()
Parameter interaction: change current parameters depending on various rules.
Definition: init.cpp:763
std::string strMethod
Definition: request.h:31
CBlockPolicyEstimator feeEstimator
Definition: validation.cpp:128
std::vector< std::shared_ptr< CWallet > > GetWallets()
Definition: dummywallet.cpp:70
void StopMapPort()
Definition: net.cpp:1567
CRPCTable tableRPC
Definition: server.cpp:502
bool AppInitSanityChecks()
Initialization sanity checks: ecc init, sanity checks, dir lock.
Definition: init.cpp:1159
NodeContext struct containing references to chain state and connection state.
Definition: context.h:31
std::unique_ptr< CConnman > connman
Definition: context.h:32
void Interrupt(NodeContext &node)
Interrupt threads.
Definition: init.cpp:157
UniValue params
Definition: request.h:32
CBlockIndex * pindexBestHeader
Best header we&#39;ve seen so far (used for getheaders queries&#39; starting points).
Definition: validation.cpp:107
fs::path GetWalletDir()
Definition: dummywallet.cpp:60
#define LOCK(cs)
Definition: sync.h:218
const char * name
Definition: rest.cpp:40
CFeeRate estimateSmartFee(int confTarget, FeeCalculation *feeCalc, bool conservative) const
Estimate feerate needed to get be included in a block within confTarget blocks.
Definition: fees.cpp:785
void SelectParams(const std::string &network)
Sets the params returned by Params() to those for the given chain name.
RecursiveMutex cs_main
Mutex to guard access to validation specific variables, such as reading or changing the chainstate...
Definition: validation.cpp:105
uint32_t GetCategoryMask() const
Definition: logging.h:127
std::unique_ptr< interfaces::Handler > HandleLoadWallet(interfaces::Node::LoadWalletFn load_wallet)
Network
Definition: netaddress.h:19
int64_t NodeId
Definition: net.h:93
NumConnections
Definition: net.h:125
std::atomic_bool fImporting
std::function< void(std::unique_ptr< interfaces::Wallet > wallet)> LoadWalletFn
Definition: dummywallet.cpp:85
std::function< void(std::unique_ptr< Wallet > wallet)> LoadWalletFn
Register handler for load wallet messages.
Definition: node.h:230
An outpoint - a combination of a transaction hash and an index n into its vout.
Definition: transaction.h:18
int64_t GetBlockTime() const
Definition: block.h:65
std::unique_ptr< Wallet > MakeWallet(const std::shared_ptr< CWallet > &wallet)
Return implementation of Wallet interface.
Definition: dummywallet.cpp:93
void RPCSetTimerInterfaceIfUnset(RPCTimerInterface *iface)
Set the factory function for timer, but only, if unset.
Definition: server.cpp:468
bool AppInitParameterInteraction()
Initialization: parameter interaction.
Definition: init.cpp:917
int flags
Definition: bitcoin-tx.cpp:509
std::atomic_bool fReindex
IP address (IPv6, or IPv4 using mapped IPv6 range (::FFFF:0:0/96))
Definition: netaddress.h:31
CChainState & ChainstateActive()
Definition: validation.cpp:85
void SetupServerArgs()
Setup the arguments for gArgs.
Definition: init.cpp:347
bool InitError(const std::string &str)
Show error message.
bool GetCoin(const COutPoint &outpoint, Coin &coin) const override
Retrieve the Coin (unspent transaction output) for a given outpoint.
Definition: coins.cpp:59
uint64_t AssumedBlockchainSize() const
Minimum free space (in GB) needed for data directory.
Definition: chainparams.h:75
Interface giving clients (wallet processes, maybe other analysis tools in the future) ability to acce...
Definition: chain.h:54
std::unique_ptr< Node > MakeNode()
Return implementation of Node interface.
Definition: node.cpp:328
The block chain is a tree shaped structure starting with the genesis block at the root...
Definition: chain.h:137
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...
std::string URI
Definition: request.h:34
CBlockIndex * Tip() const
Returns the index entry for the tip of this chain, or nullptr if none.
Definition: chain.h:390
bool IsInitialBlockDownload() const
Check whether we are doing an initial block download (synchronizing from disk or network) ...
A CWallet maintains a set of transactions and balances, and provides the ability to create new transa...
Definition: wallet.h:609
ArgsManager gArgs
Definition: system.cpp:76
Fee rate in satoshis per kilobyte: CAmount / kB.
Definition: feerate.h:19
std::string GetWarnings(bool verbose)
Format a string that describes several potential problems detected by the core.
Definition: warnings.cpp:41
void StartShutdown()
Definition: shutdown.cpp:12
CCoinsViewCache & CoinsTip() EXCLUSIVE_LOCKS_REQUIRED(cs_main)
Definition: validation.h:631
std::map< CSubNet, CBanEntry > banmap_t
Definition: net_types.h:13
bool GetProxy(enum Network net, proxyType &proxyInfoOut)
Definition: netbase.cpp:719
bool AppInitLockDataDirectory()
Lock bitcoin core data directory.
Definition: init.cpp:1180
CClientUIInterface uiInterface
int nHeight
height of the entry in the chain. The genesis block has height 0
Definition: chain.h:150
NodeContext m_context
Definition: node.cpp:323
std::vector< std::string > listCommands() const
Returns a list of registered commands.
Definition: server.cpp:461
bool error(const char *fmt, const Args &... args)
Definition: system.h:49
CFeeRate dustRelayFee
Definition: settings.cpp:13
void StartMapPort()
Definition: net.cpp:1559
void InterruptMapPort()
Definition: net.cpp:1563
std::vector< fs::path > ListWalletDir()
Definition: dummywallet.cpp:65
CTxMemPool * mempool
Definition: context.h:33