Bitcoin Core  0.18.99
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 <amount.h>
9 #include <banman.h>
10 #include <chain.h>
11 #include <chainparams.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 <policy/feerate.h>
21 #include <policy/fees.h>
22 #include <policy/policy.h>
23 #include <policy/settings.h>
24 #include <primitives/block.h>
25 #include <rpc/server.h>
26 #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 <atomic>
39 #include <univalue.h>
40 
41 class CWallet;
42 fs::path GetWalletDir();
43 std::vector<fs::path> ListWalletDir();
44 std::vector<std::shared_ptr<CWallet>> GetWallets();
45 std::shared_ptr<CWallet> LoadWallet(interfaces::Chain& chain, const std::string& name, std::string& error, std::string& warning);
46 
47 namespace interfaces {
48 
49 class Wallet;
50 
51 namespace {
52 
53 class NodeImpl : public Node
54 {
55 public:
56  NodeImpl() { m_interfaces.chain = MakeChain(); }
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  bool softSetArg(const std::string& arg, const std::string& value) override { return gArgs.SoftSetArg(arg, value); }
64  bool softSetBoolArg(const std::string& arg, bool value) override { return gArgs.SoftSetBoolArg(arg, value); }
65  void selectParams(const std::string& network) override { SelectParams(network); }
66  uint64_t getAssumedBlockchainSize() override { return Params().AssumedBlockchainSize(); }
67  uint64_t getAssumedChainStateSize() override { return Params().AssumedChainStateSize(); }
68  std::string getNetwork() override { return Params().NetworkIDString(); }
69  void initLogging() override { InitLogging(); }
70  void initParameterInteraction() override { InitParameterInteraction(); }
71  std::string getWarnings(const std::string& type) override { return GetWarnings(type); }
72  uint32_t getLogCategories() override { return LogInstance().GetCategoryMask(); }
73  bool baseInitialize() override
74  {
77  }
78  bool appInitMain() override { return AppInitMain(m_interfaces); }
79  void appShutdown() override
80  {
81  Interrupt();
83  }
84  void startShutdown() override { StartShutdown(); }
85  bool shutdownRequested() override { return ShutdownRequested(); }
86  void mapPort(bool use_upnp) override
87  {
88  if (use_upnp) {
89  StartMapPort();
90  } else {
92  StopMapPort();
93  }
94  }
95  void setupServerArgs() override { return SetupServerArgs(); }
96  bool getProxy(Network net, proxyType& proxy_info) override { return GetProxy(net, proxy_info); }
97  size_t getNodeCount(CConnman::NumConnections flags) override
98  {
99  return g_connman ? g_connman->GetNodeCount(flags) : 0;
100  }
101  bool getNodesStats(NodesStats& stats) override
102  {
103  stats.clear();
104 
105  if (g_connman) {
106  std::vector<CNodeStats> stats_temp;
107  g_connman->GetNodeStats(stats_temp);
108 
109  stats.reserve(stats_temp.size());
110  for (auto& node_stats_temp : stats_temp) {
111  stats.emplace_back(std::move(node_stats_temp), false, CNodeStateStats());
112  }
113 
114  // Try to retrieve the CNodeStateStats for each node.
115  TRY_LOCK(::cs_main, lockMain);
116  if (lockMain) {
117  for (auto& node_stats : stats) {
118  std::get<1>(node_stats) =
119  GetNodeStateStats(std::get<0>(node_stats).nodeid, std::get<2>(node_stats));
120  }
121  }
122  return true;
123  }
124  return false;
125  }
126  bool getBanned(banmap_t& banmap) override
127  {
128  if (g_banman) {
129  g_banman->GetBanned(banmap);
130  return true;
131  }
132  return false;
133  }
134  bool ban(const CNetAddr& net_addr, BanReason reason, int64_t ban_time_offset) override
135  {
136  if (g_banman) {
137  g_banman->Ban(net_addr, reason, ban_time_offset);
138  return true;
139  }
140  return false;
141  }
142  bool unban(const CSubNet& ip) override
143  {
144  if (g_banman) {
145  g_banman->Unban(ip);
146  return true;
147  }
148  return false;
149  }
150  bool disconnect(const CNetAddr& net_addr) override
151  {
152  if (g_connman) {
153  return g_connman->DisconnectNode(net_addr);
154  }
155  return false;
156  }
157  bool disconnect(NodeId id) override
158  {
159  if (g_connman) {
160  return g_connman->DisconnectNode(id);
161  }
162  return false;
163  }
164  int64_t getTotalBytesRecv() override { return g_connman ? g_connman->GetTotalBytesRecv() : 0; }
165  int64_t getTotalBytesSent() override { return g_connman ? g_connman->GetTotalBytesSent() : 0; }
166  size_t getMempoolSize() override { return ::mempool.size(); }
167  size_t getMempoolDynamicUsage() override { return ::mempool.DynamicMemoryUsage(); }
168  bool getHeaderTip(int& height, int64_t& block_time) override
169  {
170  LOCK(::cs_main);
171  if (::pindexBestHeader) {
172  height = ::pindexBestHeader->nHeight;
173  block_time = ::pindexBestHeader->GetBlockTime();
174  return true;
175  }
176  return false;
177  }
178  int getNumBlocks() override
179  {
180  LOCK(::cs_main);
182  }
183  int64_t getLastBlockTime() override
184  {
185  LOCK(::cs_main);
186  if (::ChainActive().Tip()) {
188  }
189  return Params().GenesisBlock().GetBlockTime(); // Genesis block's time of current network
190  }
191  double getVerificationProgress() override
192  {
193  const CBlockIndex* tip;
194  {
195  LOCK(::cs_main);
196  tip = ::ChainActive().Tip();
197  }
198  return GuessVerificationProgress(Params().TxData(), tip);
199  }
200  bool isInitialBlockDownload() override { return ::ChainstateActive().IsInitialBlockDownload(); }
201  bool isAddressTypeSet() override { return !::gArgs.GetArg("-addresstype", "").empty(); }
202  bool getReindex() override { return ::fReindex; }
203  bool getImporting() override { return ::fImporting; }
204  void setNetworkActive(bool active) override
205  {
206  if (g_connman) {
207  g_connman->SetNetworkActive(active);
208  }
209  }
210  bool getNetworkActive() override { return g_connman && g_connman->GetNetworkActive(); }
211  CFeeRate estimateSmartFee(int num_blocks, bool conservative, int* returned_target = nullptr) override
212  {
213  FeeCalculation fee_calc;
214  CFeeRate result = ::feeEstimator.estimateSmartFee(num_blocks, &fee_calc, conservative);
215  if (returned_target) {
216  *returned_target = fee_calc.returnedTarget;
217  }
218  return result;
219  }
220  CFeeRate getDustRelayFee() override { return ::dustRelayFee; }
221  UniValue executeRpc(const std::string& command, const UniValue& params, const std::string& uri) override
222  {
223  JSONRPCRequest req;
224  req.params = params;
225  req.strMethod = command;
226  req.URI = uri;
228  }
229  std::vector<std::string> listRpcCommands() override { return ::tableRPC.listCommands(); }
230  void rpcSetTimerInterfaceIfUnset(RPCTimerInterface* iface) override { RPCSetTimerInterfaceIfUnset(iface); }
231  void rpcUnsetTimerInterface(RPCTimerInterface* iface) override { RPCUnsetTimerInterface(iface); }
232  bool getUnspentOutput(const COutPoint& output, Coin& coin) override
233  {
234  LOCK(::cs_main);
235  return ::ChainstateActive().CoinsTip().GetCoin(output, coin);
236  }
237  std::string getWalletDir() override
238  {
239  return GetWalletDir().string();
240  }
241  std::vector<std::string> listWalletDir() override
242  {
243  std::vector<std::string> paths;
244  for (auto& path : ListWalletDir()) {
245  paths.push_back(path.string());
246  }
247  return paths;
248  }
249  std::vector<std::unique_ptr<Wallet>> getWallets() override
250  {
251  std::vector<std::unique_ptr<Wallet>> wallets;
252  for (const std::shared_ptr<CWallet>& wallet : GetWallets()) {
253  wallets.emplace_back(MakeWallet(wallet));
254  }
255  return wallets;
256  }
257  std::unique_ptr<Wallet> loadWallet(const std::string& name, std::string& error, std::string& warning) override
258  {
259  return MakeWallet(LoadWallet(*m_interfaces.chain, name, error, warning));
260  }
261  std::unique_ptr<Handler> handleInitMessage(InitMessageFn fn) override
262  {
263  return MakeHandler(::uiInterface.InitMessage_connect(fn));
264  }
265  std::unique_ptr<Handler> handleMessageBox(MessageBoxFn fn) override
266  {
267  return MakeHandler(::uiInterface.ThreadSafeMessageBox_connect(fn));
268  }
269  std::unique_ptr<Handler> handleQuestion(QuestionFn fn) override
270  {
271  return MakeHandler(::uiInterface.ThreadSafeQuestion_connect(fn));
272  }
273  std::unique_ptr<Handler> handleShowProgress(ShowProgressFn fn) override
274  {
275  return MakeHandler(::uiInterface.ShowProgress_connect(fn));
276  }
277  std::unique_ptr<Handler> handleLoadWallet(LoadWalletFn fn) override
278  {
279  return MakeHandler(::uiInterface.LoadWallet_connect([fn](std::unique_ptr<Wallet>& wallet) { fn(std::move(wallet)); }));
280  }
281  std::unique_ptr<Handler> handleNotifyNumConnectionsChanged(NotifyNumConnectionsChangedFn fn) override
282  {
283  return MakeHandler(::uiInterface.NotifyNumConnectionsChanged_connect(fn));
284  }
285  std::unique_ptr<Handler> handleNotifyNetworkActiveChanged(NotifyNetworkActiveChangedFn fn) override
286  {
287  return MakeHandler(::uiInterface.NotifyNetworkActiveChanged_connect(fn));
288  }
289  std::unique_ptr<Handler> handleNotifyAlertChanged(NotifyAlertChangedFn fn) override
290  {
291  return MakeHandler(::uiInterface.NotifyAlertChanged_connect(fn));
292  }
293  std::unique_ptr<Handler> handleBannedListChanged(BannedListChangedFn fn) override
294  {
295  return MakeHandler(::uiInterface.BannedListChanged_connect(fn));
296  }
297  std::unique_ptr<Handler> handleNotifyBlockTip(NotifyBlockTipFn fn) override
298  {
299  return MakeHandler(::uiInterface.NotifyBlockTip_connect([fn](bool initial_download, const CBlockIndex* block) {
300  fn(initial_download, block->nHeight, block->GetBlockTime(),
301  GuessVerificationProgress(Params().TxData(), block));
302  }));
303  }
304  std::unique_ptr<Handler> handleNotifyHeaderTip(NotifyHeaderTipFn fn) override
305  {
306  return MakeHandler(
307  ::uiInterface.NotifyHeaderTip_connect([fn](bool initial_download, const CBlockIndex* block) {
308  fn(initial_download, block->nHeight, block->GetBlockTime(),
309  GuessVerificationProgress(Params().TxData(), block));
310  }));
311  }
313 };
314 
315 } // namespace
316 
317 std::unique_ptr<Node> MakeNode() { return MakeUnique<NodeImpl>(); }
318 
319 } // namespace interfaces
NODISCARD bool ReadConfigFiles(std::string &error, bool ignore_invalid_keys=false)
Definition: system.cpp:873
CTxMemPool mempool
std::string NetworkIDString() const
Return the BIP70 network string (main, test or regtest)
Definition: chainparams.h:79
bool ShutdownRequested()
Definition: shutdown.cpp:20
RPC timer "driver".
Definition: server.h:58
BCLog::Logger & LogInstance()
Definition: logging.cpp:14
BanReason
Definition: addrdb.h:19
void InitLogging()
Initialize global loggers.
Definition: init.cpp:833
int64_t GetBlockTime() const
Definition: chain.h:275
int returnedTarget
Definition: fees.h:80
#define TRY_LOCK(cs, name)
Definition: sync.h:186
bool SoftSetBoolArg(const std::string &strArg, bool fValue)
Set a boolean argument if it doesn&#39;t already have a value.
Definition: system.cpp:528
A UTXO entry.
Definition: coins.h:30
CChain & ChainActive()
Definition: validation.cpp:92
uint64_t AssumedChainStateSize() const
Minimum free space (in GB) needed for data directory when pruned; Does not include prune target...
Definition: chainparams.h:75
bool GetNodeStateStats(NodeId nodeid, CNodeStateStats &stats)
Get statistics from node state.
size_t DynamicMemoryUsage() const
Definition: txmempool.cpp:906
CFeeRate dustRelayFee
Definition: settings.cpp:13
int Height() const
Return the maximal height in the chain.
Definition: chain.h:455
unsigned long size() const
Definition: txmempool.h:674
void Interrupt()
Interrupt threads.
Definition: init.cpp:157
const CBlock & GenesisBlock() const
Definition: chainparams.h:64
NODISCARD bool ParseParameters(int argc, const char *const argv[], std::string &error)
Definition: system.cpp:376
bool AppInitMain(InitInterfaces &interfaces)
Bitcoin core main initialization.
Definition: init.cpp:1203
std::unique_ptr< Handler > MakeHandler(boost::signals2::connection connection)
Return handler wrapping a boost signal connection.
Definition: handler.cpp:27
std::string GetWarnings(const std::string &strFor)
Format a string that describes several potential problems detected by the core.
Definition: warnings.cpp:41
bool AppInitBasicSetup()
Initialize bitcoin core: Basic context setup.
Definition: init.cpp:877
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:520
void RPCUnsetTimerInterface(RPCTimerInterface *iface)
Unset factory function for timers.
Definition: server.cpp:478
interfaces::Chain & chain() const
Interface for accessing chain state.
Definition: wallet.h:919
UniValue execute(const JSONRPCRequest &request) const
Execute a method.
Definition: server.cpp:420
void InitParameterInteraction()
Parameter interaction: change current parameters depending on various rules.
Definition: init.cpp:764
std::string strMethod
Definition: request.h:31
CBlockPolicyEstimator feeEstimator
Definition: validation.cpp:130
std::vector< std::shared_ptr< CWallet > > GetWallets()
Definition: dummywallet.cpp:67
void StopMapPort()
Definition: net.cpp:1515
CRPCTable tableRPC
Definition: server.cpp:501
bool AppInitSanityChecks()
Initialization sanity checks: ecc init, sanity checks, dir lock.
Definition: init.cpp:1170
std::map< CSubNet, CBanEntry > banmap_t
Definition: addrdb.h:82
CCriticalSection cs_main
Mutex to guard access to validation specific variables, such as reading or changing the chainstate...
Definition: validation.cpp:107
virtual std::unique_ptr< Handler > handleShowProgress(ShowProgressFn fn)=0
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:109
fs::path GetWalletDir()
Definition: dummywallet.cpp:57
#define LOCK(cs)
Definition: sync.h:182
const char * name
Definition: rest.cpp:39
std::unique_ptr< BanMan > g_banman
Definition: init.cpp:89
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:786
void SelectParams(const std::string &network)
Sets the params returned by Params() to those for the given BIP70 chain name.
uint32_t GetCategoryMask() const
Definition: logging.h:108
Network
Definition: netaddress.h:20
int64_t NodeId
Definition: net.h:91
NumConnections
Definition: net.h:123
std::atomic_bool fImporting
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
InitInterfaces m_interfaces
Definition: node.cpp:312
std::unique_ptr< Wallet > MakeWallet(const std::shared_ptr< CWallet > &wallet)
Return implementation of Wallet interface.
Definition: dummywallet.cpp:81
void RPCSetTimerInterfaceIfUnset(RPCTimerInterface *iface)
Set the factory function for timer, but only, if unset.
Definition: server.cpp:467
bool AppInitParameterInteraction()
Initialization: parameter interaction.
Definition: init.cpp:918
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:32
std::unique_ptr< Chain > MakeChain()
Return implementation of Chain interface.
Definition: chain.cpp:381
std::shared_ptr< CWallet > LoadWallet(interfaces::Chain &chain, const std::string &name, std::string &error, std::string &warning)
Definition: dummywallet.cpp:72
CChainState & ChainstateActive()
Definition: validation.cpp:87
void SetupServerArgs()
Setup the arguments for gArgs.
Definition: init.cpp:341
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:73
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:317
The block chain is a tree shaped structure starting with the genesis block at the root...
Definition: chain.h:139
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 GetArg(const std::string &strArg, const std::string &strDefault) const
Return string argument or default value.
Definition: system.cpp:496
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:424
std::function< void(const std::string &title, int progress)> ShowProgressFn
Register handler for show progress messages.
Definition: wallet.h:268
bool IsInitialBlockDownload() const
Check whether we are doing an initial block download (synchronizing from disk or network) ...
A CWallet is an extension of a keystore, which also maintains a set of transactions and balances...
Definition: wallet.h:680
ArgsManager gArgs
Definition: system.cpp:73
Fee rate in satoshis per kilobyte: CAmount / kB.
Definition: feerate.h:19
std::unique_ptr< CConnman > g_connman
Definition: init.cpp:87
void StartShutdown()
Definition: shutdown.cpp:12
CCoinsViewCache & CoinsTip() EXCLUSIVE_LOCKS_REQUIRED(cs_main)
Definition: validation.h:626
bool GetProxy(enum Network net, proxyType &proxyInfoOut)
Definition: netbase.cpp:701
std::unique_ptr< interfaces::Chain > chain
Definition: init.h:21
void Shutdown(InitInterfaces &interfaces)
Definition: init.cpp:173
bool AppInitLockDataDirectory()
Lock bitcoin core data directory.
Definition: init.cpp:1191
CClientUIInterface uiInterface
int nHeight
height of the entry in the chain. The genesis block has height 0
Definition: chain.h:152
Pointers to interfaces used during init and destroyed on shutdown.
Definition: init.h:19
std::vector< std::string > listCommands() const
Returns a list of registered commands.
Definition: server.cpp:460
bool error(const char *fmt, const Args &... args)
Definition: system.h:47
void StartMapPort()
Definition: net.cpp:1507
void InterruptMapPort()
Definition: net.cpp:1511
std::vector< fs::path > ListWalletDir()
Definition: dummywallet.cpp:62