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 class CWallet;
41 fs::path GetWalletDir();
42 std::vector<fs::path> ListWalletDir();
43 std::vector<std::shared_ptr<CWallet>> GetWallets();
44 std::shared_ptr<CWallet> LoadWallet(interfaces::Chain& chain, const std::string& name, std::string& error, std::vector<std::string>& warnings);
45 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);
46 std::unique_ptr<interfaces::Handler> HandleLoadWallet(interfaces::Node::LoadWalletFn load_wallet);
47 
48 namespace interfaces {
49 
50 namespace {
51 
52 class NodeImpl : public Node
53 {
54 public:
55  void initError(const std::string& message) override { InitError(message); }
56  bool parseParameters(int argc, const char* const argv[], std::string& error) override
57  {
58  return gArgs.ParseParameters(argc, argv, error);
59  }
60  bool readConfigFiles(std::string& error) override { return gArgs.ReadConfigFiles(error, true); }
61  void forceSetArg(const std::string& arg, const std::string& value) override { gArgs.ForceSetArg(arg, value); }
62  bool softSetArg(const std::string& arg, const std::string& value) override { return gArgs.SoftSetArg(arg, value); }
63  bool softSetBoolArg(const std::string& arg, bool value) override { return gArgs.SoftSetBoolArg(arg, value); }
64  void selectParams(const std::string& network) override { SelectParams(network); }
65  uint64_t getAssumedBlockchainSize() override { return Params().AssumedBlockchainSize(); }
66  uint64_t getAssumedChainStateSize() override { return Params().AssumedChainStateSize(); }
67  std::string getNetwork() override { return Params().NetworkIDString(); }
68  void initLogging() override { InitLogging(); }
69  void initParameterInteraction() override { InitParameterInteraction(); }
70  std::string getWarnings() override { return GetWarnings(true); }
71  uint32_t getLogCategories() override { return LogInstance().GetCategoryMask(); }
72  bool baseInitialize() override
73  {
76  }
77  bool appInitMain() override
78  {
80  return AppInitMain(m_context);
81  }
82  void appShutdown() override
83  {
86  }
87  void startShutdown() override { StartShutdown(); }
88  bool shutdownRequested() override { return ShutdownRequested(); }
89  void mapPort(bool use_upnp) override
90  {
91  if (use_upnp) {
92  StartMapPort();
93  } else {
95  StopMapPort();
96  }
97  }
98  void setupServerArgs() override { return SetupServerArgs(); }
99  bool getProxy(Network net, proxyType& proxy_info) override { return GetProxy(net, proxy_info); }
100  size_t getNodeCount(CConnman::NumConnections flags) override
101  {
102  return m_context.connman ? m_context.connman->GetNodeCount(flags) : 0;
103  }
104  bool getNodesStats(NodesStats& stats) override
105  {
106  stats.clear();
107 
108  if (m_context.connman) {
109  std::vector<CNodeStats> stats_temp;
110  m_context.connman->GetNodeStats(stats_temp);
111 
112  stats.reserve(stats_temp.size());
113  for (auto& node_stats_temp : stats_temp) {
114  stats.emplace_back(std::move(node_stats_temp), false, CNodeStateStats());
115  }
116 
117  // Try to retrieve the CNodeStateStats for each node.
118  TRY_LOCK(::cs_main, lockMain);
119  if (lockMain) {
120  for (auto& node_stats : stats) {
121  std::get<1>(node_stats) =
122  GetNodeStateStats(std::get<0>(node_stats).nodeid, std::get<2>(node_stats));
123  }
124  }
125  return true;
126  }
127  return false;
128  }
129  bool getBanned(banmap_t& banmap) override
130  {
131  if (m_context.banman) {
132  m_context.banman->GetBanned(banmap);
133  return true;
134  }
135  return false;
136  }
137  bool ban(const CNetAddr& net_addr, BanReason reason, int64_t ban_time_offset) override
138  {
139  if (m_context.banman) {
140  m_context.banman->Ban(net_addr, reason, ban_time_offset);
141  return true;
142  }
143  return false;
144  }
145  bool unban(const CSubNet& ip) override
146  {
147  if (m_context.banman) {
148  m_context.banman->Unban(ip);
149  return true;
150  }
151  return false;
152  }
153  bool disconnect(const CNetAddr& net_addr) override
154  {
155  if (m_context.connman) {
156  return m_context.connman->DisconnectNode(net_addr);
157  }
158  return false;
159  }
160  bool disconnect(NodeId id) override
161  {
162  if (m_context.connman) {
163  return m_context.connman->DisconnectNode(id);
164  }
165  return false;
166  }
167  int64_t getTotalBytesRecv() override { return m_context.connman ? m_context.connman->GetTotalBytesRecv() : 0; }
168  int64_t getTotalBytesSent() override { return m_context.connman ? m_context.connman->GetTotalBytesSent() : 0; }
169  size_t getMempoolSize() override { return m_context.mempool ? m_context.mempool->size() : 0; }
170  size_t getMempoolDynamicUsage() override { return m_context.mempool ? m_context.mempool->DynamicMemoryUsage() : 0; }
171  bool getHeaderTip(int& height, int64_t& block_time) override
172  {
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  {
183  LOCK(::cs_main);
185  }
186  int64_t getLastBlockTime() override
187  {
188  LOCK(::cs_main);
189  if (::ChainActive().Tip()) {
191  }
192  return Params().GenesisBlock().GetBlockTime(); // Genesis block's time of current network
193  }
194  double getVerificationProgress() override
195  {
196  const CBlockIndex* tip;
197  {
198  LOCK(::cs_main);
199  tip = ::ChainActive().Tip();
200  }
201  return GuessVerificationProgress(Params().TxData(), tip);
202  }
203  bool isInitialBlockDownload() override { return ::ChainstateActive().IsInitialBlockDownload(); }
204  bool getReindex() override { return ::fReindex; }
205  bool getImporting() override { return ::fImporting; }
206  void setNetworkActive(bool active) override
207  {
208  if (m_context.connman) {
209  m_context.connman->SetNetworkActive(active);
210  }
211  }
212  bool getNetworkActive() override { return m_context.connman && m_context.connman->GetNetworkActive(); }
213  CFeeRate estimateSmartFee(int num_blocks, bool conservative, int* returned_target = nullptr) override
214  {
215  FeeCalculation fee_calc;
216  CFeeRate result = ::feeEstimator.estimateSmartFee(num_blocks, &fee_calc, conservative);
217  if (returned_target) {
218  *returned_target = fee_calc.returnedTarget;
219  }
220  return result;
221  }
222  CFeeRate getDustRelayFee() override { return ::dustRelayFee; }
223  UniValue executeRpc(const std::string& command, const UniValue& params, const std::string& uri) override
224  {
225  JSONRPCRequest req;
226  req.params = params;
227  req.strMethod = command;
228  req.URI = uri;
230  }
231  std::vector<std::string> listRpcCommands() override { return ::tableRPC.listCommands(); }
232  void rpcSetTimerInterfaceIfUnset(RPCTimerInterface* iface) override { RPCSetTimerInterfaceIfUnset(iface); }
233  void rpcUnsetTimerInterface(RPCTimerInterface* iface) override { RPCUnsetTimerInterface(iface); }
234  bool getUnspentOutput(const COutPoint& output, Coin& coin) override
235  {
236  LOCK(::cs_main);
237  return ::ChainstateActive().CoinsTip().GetCoin(output, coin);
238  }
239  std::string getWalletDir() override
240  {
241  return GetWalletDir().string();
242  }
243  std::vector<std::string> listWalletDir() override
244  {
245  std::vector<std::string> paths;
246  for (auto& path : ListWalletDir()) {
247  paths.push_back(path.string());
248  }
249  return paths;
250  }
251  std::vector<std::unique_ptr<Wallet>> getWallets() override
252  {
253  std::vector<std::unique_ptr<Wallet>> wallets;
254  for (const std::shared_ptr<CWallet>& wallet : GetWallets()) {
255  wallets.emplace_back(MakeWallet(wallet));
256  }
257  return wallets;
258  }
259  std::unique_ptr<Wallet> loadWallet(const std::string& name, std::string& error, std::vector<std::string>& warnings) override
260  {
261  return MakeWallet(LoadWallet(*m_context.chain, name, error, warnings));
262  }
263  WalletCreationStatus createWallet(const SecureString& passphrase, uint64_t wallet_creation_flags, const std::string& name, std::string& error, std::vector<std::string>& warnings, std::unique_ptr<Wallet>& result) override
264  {
265  std::shared_ptr<CWallet> wallet;
266  WalletCreationStatus status = CreateWallet(*m_context.chain, passphrase, wallet_creation_flags, name, error, warnings, wallet);
267  result = MakeWallet(wallet);
268  return status;
269  }
270  std::unique_ptr<Handler> handleInitMessage(InitMessageFn fn) override
271  {
272  return MakeHandler(::uiInterface.InitMessage_connect(fn));
273  }
274  std::unique_ptr<Handler> handleMessageBox(MessageBoxFn fn) override
275  {
276  return MakeHandler(::uiInterface.ThreadSafeMessageBox_connect(fn));
277  }
278  std::unique_ptr<Handler> handleQuestion(QuestionFn fn) override
279  {
280  return MakeHandler(::uiInterface.ThreadSafeQuestion_connect(fn));
281  }
282  std::unique_ptr<Handler> handleShowProgress(ShowProgressFn fn) override
283  {
284  return MakeHandler(::uiInterface.ShowProgress_connect(fn));
285  }
286  std::unique_ptr<Handler> handleLoadWallet(LoadWalletFn fn) override
287  {
288  return HandleLoadWallet(std::move(fn));
289  }
290  std::unique_ptr<Handler> handleNotifyNumConnectionsChanged(NotifyNumConnectionsChangedFn fn) override
291  {
292  return MakeHandler(::uiInterface.NotifyNumConnectionsChanged_connect(fn));
293  }
294  std::unique_ptr<Handler> handleNotifyNetworkActiveChanged(NotifyNetworkActiveChangedFn fn) override
295  {
296  return MakeHandler(::uiInterface.NotifyNetworkActiveChanged_connect(fn));
297  }
298  std::unique_ptr<Handler> handleNotifyAlertChanged(NotifyAlertChangedFn fn) override
299  {
300  return MakeHandler(::uiInterface.NotifyAlertChanged_connect(fn));
301  }
302  std::unique_ptr<Handler> handleBannedListChanged(BannedListChangedFn fn) override
303  {
304  return MakeHandler(::uiInterface.BannedListChanged_connect(fn));
305  }
306  std::unique_ptr<Handler> handleNotifyBlockTip(NotifyBlockTipFn fn) override
307  {
308  return MakeHandler(::uiInterface.NotifyBlockTip_connect([fn](bool initial_download, const CBlockIndex* block) {
309  fn(initial_download, block->nHeight, block->GetBlockTime(),
310  GuessVerificationProgress(Params().TxData(), block));
311  }));
312  }
313  std::unique_ptr<Handler> handleNotifyHeaderTip(NotifyHeaderTipFn fn) override
314  {
315  return MakeHandler(
316  ::uiInterface.NotifyHeaderTip_connect([fn](bool initial_download, const CBlockIndex* block) {
317  fn(initial_download, block->nHeight, block->GetBlockTime(),
318  /* verification progress is unused when a header was received */ 0);
319  }));
320  }
321  NodeContext* context() override { return &m_context; }
323 };
324 
325 } // namespace
326 
327 std::unique_ptr<Node> MakeNode() { return MakeUnique<NodeImpl>(); }
328 
329 } // 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:1196
BCLog::Logger & LogInstance()
Definition: logging.cpp:14
BanReason
Definition: addrdb.h:20
void InitLogging()
Initialize global loggers.
Definition: init.cpp:836
int64_t GetBlockTime() const
Definition: chain.h:247
int returnedTarget
Definition: fees.h:80
#define TRY_LOCK(cs, name)
Definition: sync.h:183
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:177
A UTXO entry.
Definition: coins.h:30
CChain & ChainActive()
Definition: validation.cpp:91
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:915
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:678
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:55
bool AppInitBasicSetup()
Initialize bitcoin core: Basic context setup.
Definition: init.cpp:880
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:378
void RPCUnsetTimerInterface(RPCTimerInterface *iface)
Unset factory function for timers.
Definition: server.cpp:476
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:418
void InitParameterInteraction()
Parameter interaction: change current parameters depending on various rules.
Definition: init.cpp:767
std::string strMethod
Definition: request.h:31
CBlockPolicyEstimator feeEstimator
Definition: validation.cpp:129
std::vector< std::shared_ptr< CWallet > > GetWallets()
Definition: dummywallet.cpp:70
void StopMapPort()
Definition: net.cpp:1554
CRPCTable tableRPC
Definition: server.cpp:499
bool AppInitSanityChecks()
Initialization sanity checks: ecc init, sanity checks, dir lock.
Definition: init.cpp:1163
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:161
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:108
fs::path GetWalletDir()
Definition: dummywallet.cpp:60
#define LOCK(cs)
Definition: sync.h:179
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:106
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:465
bool AppInitParameterInteraction()
Initialization: parameter interaction.
Definition: init.cpp:921
int flags
Definition: bitcoin-tx.cpp:508
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:86
void SetupServerArgs()
Setup the arguments for gArgs.
Definition: init.cpp:350
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:327
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:606
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:1184
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:322
std::vector< std::string > listCommands() const
Returns a list of registered commands.
Definition: server.cpp:458
bool error(const char *fmt, const Args &... args)
Definition: system.h:49
CFeeRate dustRelayFee
Definition: settings.cpp:13
void StartMapPort()
Definition: net.cpp:1546
void InterruptMapPort()
Definition: net.cpp:1550
std::vector< fs::path > ListWalletDir()
Definition: dummywallet.cpp:65
CTxMemPool * mempool
Definition: context.h:33