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 <scheduler.h>
27 #include <shutdown.h>
28 #include <sync.h>
29 #include <txmempool.h>
30 #include <ui_interface.h>
31 #include <util/system.h>
32 #include <validation.h>
33 #include <warnings.h>
34 
35 #if defined(HAVE_CONFIG_H)
36 #include <config/bitcoin-config.h>
37 #endif
38 
39 #include <atomic>
40 #include <univalue.h>
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::string& warning);
47 
48 namespace interfaces {
49 
50 class Wallet;
51 
52 namespace {
53 
54 class NodeImpl : public Node
55 {
56 public:
57  NodeImpl() { m_interfaces.chain = MakeChain(); }
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 IsInitialBlockDownload(); }
201  bool getReindex() override { return ::fReindex; }
202  bool getImporting() override { return ::fImporting; }
203  void setNetworkActive(bool active) override
204  {
205  if (g_connman) {
206  g_connman->SetNetworkActive(active);
207  }
208  }
209  bool getNetworkActive() override { return g_connman && g_connman->GetNetworkActive(); }
210  CFeeRate estimateSmartFee(int num_blocks, bool conservative, int* returned_target = nullptr) override
211  {
212  FeeCalculation fee_calc;
213  CFeeRate result = ::feeEstimator.estimateSmartFee(num_blocks, &fee_calc, conservative);
214  if (returned_target) {
215  *returned_target = fee_calc.returnedTarget;
216  }
217  return result;
218  }
219  CFeeRate getDustRelayFee() override { return ::dustRelayFee; }
220  UniValue executeRpc(const std::string& command, const UniValue& params, const std::string& uri) override
221  {
222  JSONRPCRequest req;
223  req.params = params;
224  req.strMethod = command;
225  req.URI = uri;
227  }
228  std::vector<std::string> listRpcCommands() override { return ::tableRPC.listCommands(); }
229  void rpcSetTimerInterfaceIfUnset(RPCTimerInterface* iface) override { RPCSetTimerInterfaceIfUnset(iface); }
230  void rpcUnsetTimerInterface(RPCTimerInterface* iface) override { RPCUnsetTimerInterface(iface); }
231  bool getUnspentOutput(const COutPoint& output, Coin& coin) override
232  {
233  LOCK(::cs_main);
234  return ::pcoinsTip->GetCoin(output, coin);
235  }
236  std::string getWalletDir() override
237  {
238  return GetWalletDir().string();
239  }
240  std::vector<std::string> listWalletDir() override
241  {
242  std::vector<std::string> paths;
243  for (auto& path : ListWalletDir()) {
244  paths.push_back(path.string());
245  }
246  return paths;
247  }
248  std::vector<std::unique_ptr<Wallet>> getWallets() override
249  {
250  std::vector<std::unique_ptr<Wallet>> wallets;
251  for (const std::shared_ptr<CWallet>& wallet : GetWallets()) {
252  wallets.emplace_back(MakeWallet(wallet));
253  }
254  return wallets;
255  }
256  std::unique_ptr<Wallet> loadWallet(const std::string& name, std::string& error, std::string& warning) override
257  {
258  return MakeWallet(LoadWallet(*m_interfaces.chain, name, error, warning));
259  }
260  std::unique_ptr<Handler> handleInitMessage(InitMessageFn fn) override
261  {
262  return MakeHandler(::uiInterface.InitMessage_connect(fn));
263  }
264  std::unique_ptr<Handler> handleMessageBox(MessageBoxFn fn) override
265  {
266  return MakeHandler(::uiInterface.ThreadSafeMessageBox_connect(fn));
267  }
268  std::unique_ptr<Handler> handleQuestion(QuestionFn fn) override
269  {
270  return MakeHandler(::uiInterface.ThreadSafeQuestion_connect(fn));
271  }
272  std::unique_ptr<Handler> handleShowProgress(ShowProgressFn fn) override
273  {
274  return MakeHandler(::uiInterface.ShowProgress_connect(fn));
275  }
276  std::unique_ptr<Handler> handleLoadWallet(LoadWalletFn fn) override
277  {
278  return MakeHandler(::uiInterface.LoadWallet_connect([fn](std::unique_ptr<Wallet>& wallet) { fn(std::move(wallet)); }));
279  }
280  std::unique_ptr<Handler> handleNotifyNumConnectionsChanged(NotifyNumConnectionsChangedFn fn) override
281  {
282  return MakeHandler(::uiInterface.NotifyNumConnectionsChanged_connect(fn));
283  }
284  std::unique_ptr<Handler> handleNotifyNetworkActiveChanged(NotifyNetworkActiveChangedFn fn) override
285  {
286  return MakeHandler(::uiInterface.NotifyNetworkActiveChanged_connect(fn));
287  }
288  std::unique_ptr<Handler> handleNotifyAlertChanged(NotifyAlertChangedFn fn) override
289  {
290  return MakeHandler(::uiInterface.NotifyAlertChanged_connect(fn));
291  }
292  std::unique_ptr<Handler> handleBannedListChanged(BannedListChangedFn fn) override
293  {
294  return MakeHandler(::uiInterface.BannedListChanged_connect(fn));
295  }
296  std::unique_ptr<Handler> handleNotifyBlockTip(NotifyBlockTipFn fn) override
297  {
298  return MakeHandler(::uiInterface.NotifyBlockTip_connect([fn](bool initial_download, const CBlockIndex* block) {
299  fn(initial_download, block->nHeight, block->GetBlockTime(),
300  GuessVerificationProgress(Params().TxData(), block));
301  }));
302  }
303  std::unique_ptr<Handler> handleNotifyHeaderTip(NotifyHeaderTipFn fn) override
304  {
305  return MakeHandler(
306  ::uiInterface.NotifyHeaderTip_connect([fn](bool initial_download, const CBlockIndex* block) {
307  fn(initial_download, block->nHeight, block->GetBlockTime(),
308  GuessVerificationProgress(Params().TxData(), block));
309  }));
310  }
312 };
313 
314 } // namespace
315 
316 std::unique_ptr<Node> MakeNode() { return MakeUnique<NodeImpl>(); }
317 
318 } // namespace interfaces
NODISCARD bool ReadConfigFiles(std::string &error, bool ignore_invalid_keys=false)
Definition: system.cpp:871
CTxMemPool mempool
std::string NetworkIDString() const
Return the BIP70 network string (main, test or regtest)
Definition: chainparams.h:77
bool ShutdownRequested()
Definition: shutdown.cpp:20
RPC timer "driver".
Definition: server.h:72
BCLog::Logger & LogInstance()
Definition: logging.cpp:14
BanReason
Definition: addrdb.h:19
void InitLogging()
Initialize global loggers.
Definition: init.cpp:854
int64_t GetBlockTime() const
Definition: chain.h:275
int returnedTarget
Definition: fees.h:81
#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:29
CChain & ChainActive()
Definition: validation.cpp:223
uint64_t AssumedChainStateSize() const
Minimum free space (in GB) needed for data directory when pruned; Does not include prune target...
Definition: chainparams.h:73
bool GetNodeStateStats(NodeId nodeid, CNodeStateStats &stats)
Get statistics from node state.
size_t DynamicMemoryUsage() const
Definition: txmempool.cpp:912
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:683
void Interrupt()
Interrupt threads.
Definition: init.cpp:182
const CBlock & GenesisBlock() const
Definition: chainparams.h:64
NODISCARD bool ParseParameters(int argc, const char *const argv[], std::string &error)
Definition: system.cpp:381
bool AppInitMain(InitInterfaces &interfaces)
Bitcoin core main initialization.
Definition: init.cpp:1238
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:40
bool AppInitBasicSetup()
Initialize bitcoin core: Basic context setup.
Definition: init.cpp:904
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:514
std::unique_ptr< CCoinsViewCache > pcoinsTip
Global variable that points to the active CCoinsView (protected by cs_main)
Definition: validation.cpp:311
interfaces::Chain & chain() const
Interface for accessing chain state.
Definition: wallet.h:877
UniValue execute(const JSONRPCRequest &request) const
Execute a method.
Definition: server.cpp:456
void InitParameterInteraction()
Parameter interaction: change current parameters depending on various rules.
Definition: init.cpp:780
std::string strMethod
Definition: server.h:34
CBlockPolicyEstimator feeEstimator
Definition: validation.cpp:260
std::vector< std::shared_ptr< CWallet > > GetWallets()
Definition: dummywallet.cpp:67
void StopMapPort()
Definition: net.cpp:1511
CRPCTable tableRPC
Definition: server.cpp:537
bool AppInitSanityChecks()
Initialization sanity checks: ecc init, sanity checks, dir lock.
Definition: init.cpp:1205
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:235
virtual std::unique_ptr< Handler > handleShowProgress(ShowProgressFn fn)=0
UniValue params
Definition: server.h:35
CBlockIndex * pindexBestHeader
Best header we&#39;ve seen so far (used for getheaders queries&#39; starting points).
Definition: validation.cpp:238
fs::path GetWalletDir()
Definition: dummywallet.cpp:57
#define LOCK(cs)
Definition: sync.h:182
const char * name
Definition: rest.cpp:38
std::unique_ptr< BanMan > g_banman
Definition: init.cpp:87
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:787
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:99
bool IsInitialBlockDownload()
Check whether we are doing an initial block download (synchronizing from disk or network) ...
Network
Definition: netaddress.h:20
int64_t NodeId
Definition: net.h:85
NumConnections
Definition: net.h:117
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:311
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:503
bool AppInitParameterInteraction()
Initialization: parameter interaction.
Definition: init.cpp:945
int flags
Definition: bitcoin-tx.cpp:507
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:383
std::shared_ptr< CWallet > LoadWallet(interfaces::Chain &chain, const std::string &name, std::string &error, std::string &warning)
Definition: dummywallet.cpp:72
void SetupServerArgs()
Setup the arguments for gArgs.
Definition: init.cpp:362
uint64_t AssumedBlockchainSize() const
Minimum free space (in GB) needed for data directory.
Definition: chainparams.h:71
Interface giving clients (wallet processes, maybe other analysis tools in the future) ability to acce...
Definition: chain.h:58
std::unique_ptr< Node > MakeNode()
Return implementation of Node interface.
Definition: node.cpp:316
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 URI
Definition: server.h:37
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:261
A CWallet is an extension of a keystore, which also maintains a set of transactions and balances...
Definition: wallet.h:692
ArgsManager gArgs
Definition: system.cpp:74
Fee rate in satoshis per kilobyte: CAmount / kB.
Definition: feerate.h:19
std::unique_ptr< CConnman > g_connman
Definition: init.cpp:85
void StartShutdown()
Definition: shutdown.cpp:12
bool GetProxy(enum Network net, proxyType &proxyInfoOut)
Definition: netbase.cpp:566
std::unique_ptr< interfaces::Chain > chain
Definition: init.h:21
void Shutdown(InitInterfaces &interfaces)
Definition: init.cpp:198
bool AppInitLockDataDirectory()
Lock bitcoin core data directory.
Definition: init.cpp:1226
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:496
bool error(const char *fmt, const Args &... args)
Definition: system.h:61
void StartMapPort()
Definition: net.cpp:1503
void InterruptMapPort()
Definition: net.cpp:1507
std::vector< fs::path > ListWalletDir()
Definition: dummywallet.cpp:62