BSHA3  0.17.99
P2P Blockchain, based on Bitcoin
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 <chain.h>
10 #include <chainparams.h>
11 #include <init.h>
12 #include <interfaces/handler.h>
13 #include <interfaces/wallet.h>
14 #include <net.h>
15 #include <net_processing.h>
16 #include <netaddress.h>
17 #include <netbase.h>
18 #include <policy/feerate.h>
19 #include <policy/fees.h>
20 #include <policy/policy.h>
21 #include <primitives/block.h>
22 #include <rpc/server.h>
23 #include <scheduler.h>
24 #include <shutdown.h>
25 #include <sync.h>
26 #include <txmempool.h>
27 #include <ui_interface.h>
28 #include <util.h>
29 #include <validation.h>
30 #include <warnings.h>
31 
32 #if defined(HAVE_CONFIG_H)
33 #include <config/bitcoin-config.h>
34 #endif
35 
36 #include <atomic>
37 #include <boost/thread/thread.hpp>
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 
45 namespace interfaces {
46 
47 class Wallet;
48 
49 namespace {
50 
51 class NodeImpl : public Node
52 {
53  bool parseParameters(int argc, const char* const argv[], std::string& error) override
54  {
55  return gArgs.ParseParameters(argc, argv, error);
56  }
57  bool readConfigFiles(std::string& error) override { return gArgs.ReadConfigFiles(error, true); }
58  bool softSetArg(const std::string& arg, const std::string& value) override { return gArgs.SoftSetArg(arg, value); }
59  bool softSetBoolArg(const std::string& arg, bool value) override { return gArgs.SoftSetBoolArg(arg, value); }
60  void selectParams(const std::string& network) override { SelectParams(network); }
61  std::string getNetwork() override { return Params().NetworkIDString(); }
62  void initLogging() override { InitLogging(); }
63  void initParameterInteraction() override { InitParameterInteraction(); }
64  std::string getWarnings(const std::string& type) override { return GetWarnings(type); }
65  uint32_t getLogCategories() override { return g_logger->GetCategoryMask(); }
66  bool baseInitialize() override
67  {
70  }
71  bool appInitMain() override { return AppInitMain(); }
72  void appShutdown() override
73  {
74  Interrupt();
75  Shutdown();
76  }
77  void startShutdown() override { StartShutdown(); }
78  bool shutdownRequested() override { return ShutdownRequested(); }
79  void mapPort(bool use_upnp) override
80  {
81  if (use_upnp) {
82  StartMapPort();
83  } else {
85  StopMapPort();
86  }
87  }
88  void setupServerArgs() override { return SetupServerArgs(); }
89  bool getProxy(Network net, proxyType& proxy_info) override { return GetProxy(net, proxy_info); }
90  size_t getNodeCount(CConnman::NumConnections flags) override
91  {
92  return g_connman ? g_connman->GetNodeCount(flags) : 0;
93  }
94  bool getNodesStats(NodesStats& stats) override
95  {
96  stats.clear();
97 
98  if (g_connman) {
99  std::vector<CNodeStats> stats_temp;
100  g_connman->GetNodeStats(stats_temp);
101 
102  stats.reserve(stats_temp.size());
103  for (auto& node_stats_temp : stats_temp) {
104  stats.emplace_back(std::move(node_stats_temp), false, CNodeStateStats());
105  }
106 
107  // Try to retrieve the CNodeStateStats for each node.
108  TRY_LOCK(::cs_main, lockMain);
109  if (lockMain) {
110  for (auto& node_stats : stats) {
111  std::get<1>(node_stats) =
112  GetNodeStateStats(std::get<0>(node_stats).nodeid, std::get<2>(node_stats));
113  }
114  }
115  return true;
116  }
117  return false;
118  }
119  bool getBanned(banmap_t& banmap) override
120  {
121  if (g_connman) {
122  g_connman->GetBanned(banmap);
123  return true;
124  }
125  return false;
126  }
127  bool ban(const CNetAddr& net_addr, BanReason reason, int64_t ban_time_offset) override
128  {
129  if (g_connman) {
130  g_connman->Ban(net_addr, reason, ban_time_offset);
131  return true;
132  }
133  return false;
134  }
135  bool unban(const CSubNet& ip) override
136  {
137  if (g_connman) {
138  g_connman->Unban(ip);
139  return true;
140  }
141  return false;
142  }
143  bool disconnect(NodeId id) override
144  {
145  if (g_connman) {
146  return g_connman->DisconnectNode(id);
147  }
148  return false;
149  }
150  int64_t getTotalBytesRecv() override { return g_connman ? g_connman->GetTotalBytesRecv() : 0; }
151  int64_t getTotalBytesSent() override { return g_connman ? g_connman->GetTotalBytesSent() : 0; }
152  size_t getMempoolSize() override { return ::mempool.size(); }
153  size_t getMempoolDynamicUsage() override { return ::mempool.DynamicMemoryUsage(); }
154  bool getHeaderTip(int& height, int64_t& block_time) override
155  {
156  LOCK(::cs_main);
157  if (::pindexBestHeader) {
158  height = ::pindexBestHeader->nHeight;
159  block_time = ::pindexBestHeader->GetBlockTime();
160  return true;
161  }
162  return false;
163  }
164  int getNumBlocks() override
165  {
166  LOCK(::cs_main);
168  }
169  int64_t getLastBlockTime() override
170  {
171  LOCK(::cs_main);
172  if (::chainActive.Tip()) {
174  }
175  return Params().GenesisBlock().GetBlockTime(); // Genesis block's time of current network
176  }
177  double getVerificationProgress() override
178  {
179  const CBlockIndex* tip;
180  {
181  LOCK(::cs_main);
182  tip = ::chainActive.Tip();
183  }
184  return GuessVerificationProgress(Params().TxData(), tip);
185  }
186  bool isInitialBlockDownload() override { return IsInitialBlockDownload(); }
187  bool getReindex() override { return ::fReindex; }
188  bool getImporting() override { return ::fImporting; }
189  void setNetworkActive(bool active) override
190  {
191  if (g_connman) {
192  g_connman->SetNetworkActive(active);
193  }
194  }
195  bool getNetworkActive() override { return g_connman && g_connman->GetNetworkActive(); }
196  CAmount getMaxTxFee() override { return ::maxTxFee; }
197  CFeeRate estimateSmartFee(int num_blocks, bool conservative, int* returned_target = nullptr) override
198  {
199  FeeCalculation fee_calc;
200  CFeeRate result = ::feeEstimator.estimateSmartFee(num_blocks, &fee_calc, conservative);
201  if (returned_target) {
202  *returned_target = fee_calc.returnedTarget;
203  }
204  return result;
205  }
206  CFeeRate getDustRelayFee() override { return ::dustRelayFee; }
207  UniValue executeRpc(const std::string& command, const UniValue& params, const std::string& uri) override
208  {
209  JSONRPCRequest req;
210  req.params = params;
211  req.strMethod = command;
212  req.URI = uri;
214  }
215  std::vector<std::string> listRpcCommands() override { return ::tableRPC.listCommands(); }
216  void rpcSetTimerInterfaceIfUnset(RPCTimerInterface* iface) override { RPCSetTimerInterfaceIfUnset(iface); }
217  void rpcUnsetTimerInterface(RPCTimerInterface* iface) override { RPCUnsetTimerInterface(iface); }
218  bool getUnspentOutput(const COutPoint& output, Coin& coin) override
219  {
220  LOCK(::cs_main);
221  return ::pcoinsTip->GetCoin(output, coin);
222  }
223  std::string getWalletDir() override
224  {
225  return GetWalletDir().string();
226  }
227  std::vector<std::string> listWalletDir() override
228  {
229  std::vector<std::string> paths;
230  for (auto& path : ListWalletDir()) {
231  paths.push_back(path.string());
232  }
233  return paths;
234  }
235  std::vector<std::unique_ptr<Wallet>> getWallets() override
236  {
237  std::vector<std::unique_ptr<Wallet>> wallets;
238  for (const std::shared_ptr<CWallet>& wallet : GetWallets()) {
239  wallets.emplace_back(MakeWallet(wallet));
240  }
241  return wallets;
242  }
243  std::unique_ptr<Handler> handleInitMessage(InitMessageFn fn) override
244  {
245  return MakeHandler(::uiInterface.InitMessage_connect(fn));
246  }
247  std::unique_ptr<Handler> handleMessageBox(MessageBoxFn fn) override
248  {
249  return MakeHandler(::uiInterface.ThreadSafeMessageBox_connect(fn));
250  }
251  std::unique_ptr<Handler> handleQuestion(QuestionFn fn) override
252  {
253  return MakeHandler(::uiInterface.ThreadSafeQuestion_connect(fn));
254  }
255  std::unique_ptr<Handler> handleShowProgress(ShowProgressFn fn) override
256  {
257  return MakeHandler(::uiInterface.ShowProgress_connect(fn));
258  }
259  std::unique_ptr<Handler> handleLoadWallet(LoadWalletFn fn) override
260  {
261  return MakeHandler(::uiInterface.LoadWallet_connect([fn](std::shared_ptr<CWallet> wallet) { fn(MakeWallet(wallet)); }));
262  }
263  std::unique_ptr<Handler> handleNotifyNumConnectionsChanged(NotifyNumConnectionsChangedFn fn) override
264  {
265  return MakeHandler(::uiInterface.NotifyNumConnectionsChanged_connect(fn));
266  }
267  std::unique_ptr<Handler> handleNotifyNetworkActiveChanged(NotifyNetworkActiveChangedFn fn) override
268  {
269  return MakeHandler(::uiInterface.NotifyNetworkActiveChanged_connect(fn));
270  }
271  std::unique_ptr<Handler> handleNotifyAlertChanged(NotifyAlertChangedFn fn) override
272  {
273  return MakeHandler(::uiInterface.NotifyAlertChanged_connect(fn));
274  }
275  std::unique_ptr<Handler> handleBannedListChanged(BannedListChangedFn fn) override
276  {
277  return MakeHandler(::uiInterface.BannedListChanged_connect(fn));
278  }
279  std::unique_ptr<Handler> handleNotifyBlockTip(NotifyBlockTipFn fn) override
280  {
281  return MakeHandler(::uiInterface.NotifyBlockTip_connect([fn](bool initial_download, const CBlockIndex* block) {
282  fn(initial_download, block->nHeight, block->GetBlockTime(),
283  GuessVerificationProgress(Params().TxData(), block));
284  }));
285  }
286  std::unique_ptr<Handler> handleNotifyHeaderTip(NotifyHeaderTipFn fn) override
287  {
288  return MakeHandler(
289  ::uiInterface.NotifyHeaderTip_connect([fn](bool initial_download, const CBlockIndex* block) {
290  fn(initial_download, block->nHeight, block->GetBlockTime(),
291  GuessVerificationProgress(Params().TxData(), block));
292  }));
293  }
294 };
295 
296 } // namespace
297 
298 std::unique_ptr<Node> MakeNode() { return MakeUnique<NodeImpl>(); }
299 
300 } // namespace interfaces
bool ReadConfigFiles(std::string &error, bool ignore_invalid_keys=false)
Definition: util.cpp:887
CTxMemPool mempool
std::string NetworkIDString() const
Return the BIP70 network string (main, test or regtest)
Definition: chainparams.h:74
bool ShutdownRequested()
Definition: shutdown.cpp:20
RPC timer "driver".
Definition: server.h:101
BanReason
Definition: addrdb.h:19
void InitLogging()
Initialize global loggers.
Definition: init.cpp:805
int64_t GetBlockTime() const
Definition: chain.h:297
int returnedTarget
Definition: fees.h:85
#define TRY_LOCK(cs, name)
Definition: sync.h:185
bool SoftSetBoolArg(const std::string &strArg, bool fValue)
Set a boolean argument if it doesn&#39;t already have a value.
Definition: util.cpp:558
A UTXO entry.
Definition: coins.h:29
bool AppInitMain()
Bitcoin core main initialization.
Definition: init.cpp:1152
bool GetNodeStateStats(NodeId nodeid, CNodeStateStats &stats)
Get statistics from node state.
CAmount maxTxFee
Absolute maximum transaction fee (in satoshis) used by wallet and mempool (rejects high fee in sendra...
Definition: validation.cpp:242
size_t DynamicMemoryUsage() const
Definition: txmempool.cpp:911
int Height() const
Return the maximal height in the chain.
Definition: chain.h:476
void Interrupt()
Interrupt threads.
Definition: init.cpp:144
const CBlock & GenesisBlock() const
Definition: chainparams.h:65
bool ParseParameters(int argc, const char *const argv[], std::string &error)
Definition: util.cpp:411
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:852
bool SoftSetArg(const std::string &strArg, const std::string &strValue)
Set an argument if it doesn&#39;t already have a value.
Definition: util.cpp:550
void RPCUnsetTimerInterface(RPCTimerInterface *iface)
Unset factory function for timers.
Definition: server.cpp:533
std::unique_ptr< CCoinsViewCache > pcoinsTip
Global variable that points to the active CCoinsView (protected by cs_main)
Definition: validation.cpp:298
int64_t CAmount
Amount in satoshis (Can be negative)
Definition: amount.h:12
UniValue execute(const JSONRPCRequest &request) const
Execute a method.
Definition: server.cpp:469
void InitParameterInteraction()
Parameter interaction: change current parameters depending on various rules.
Definition: init.cpp:726
std::string strMethod
Definition: server.h:43
CBlockPolicyEstimator feeEstimator
Definition: validation.cpp:244
std::vector< std::shared_ptr< CWallet > > GetWallets()
Definition: dummywallet.cpp:47
void StopMapPort()
Definition: net.cpp:1607
CRPCTable tableRPC
Definition: server.cpp:556
bool AppInitSanityChecks()
Initialization sanity checks: ecc init, sanity checks, dir lock.
Definition: init.cpp:1119
std::map< CSubNet, CBanEntry > banmap_t
Definition: addrdb.h:77
CCriticalSection cs_main
Definition: validation.cpp:216
virtual std::unique_ptr< Handler > handleShowProgress(ShowProgressFn fn)=0
unsigned long size()
Definition: txmempool.h:638
UniValue params
Definition: server.h:44
CBlockIndex * pindexBestHeader
Best header we&#39;ve seen so far (used for getheaders queries&#39; starting points).
Definition: validation.cpp:220
fs::path GetWalletDir()
Definition: dummywallet.cpp:37
#define LOCK(cs)
Definition: sync.h:181
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:820
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:97
bool IsInitialBlockDownload()
Check whether we are doing an initial block download (synchronizing from disk or network) ...
void Shutdown()
Definition: init.cpp:159
Network
Definition: netaddress.h:20
int64_t NodeId
Definition: net.h:88
NumConnections
Definition: net.h:119
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:67
std::unique_ptr< Wallet > MakeWallet(const std::shared_ptr< CWallet > &wallet)
Return implementation of Wallet interface.
Definition: dummywallet.cpp:56
void RPCSetTimerInterfaceIfUnset(RPCTimerInterface *iface)
Set the factory function for timer, but only, if unset.
Definition: server.cpp:522
bool AppInitParameterInteraction()
Initialization: parameter interaction.
Definition: init.cpp:902
std::atomic_bool fReindex
IP address (IPv6, or IPv4 using mapped IPv6 range (::FFFF:0:0/96))
Definition: netaddress.h:32
ArgsManager gArgs
Definition: util.cpp:88
void SetupServerArgs()
Setup the arguments for gArgs.
Definition: init.cpp:315
std::unique_ptr< Node > MakeNode()
Return implementation of Node interface.
Definition: node.cpp:298
The block chain is a tree shaped structure starting with the genesis block at the root...
Definition: chain.h:170
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:46
CBlockIndex * Tip() const
Returns the index entry for the tip of this chain, or nullptr if none.
Definition: chain.h:445
std::function< void(const std::string &title, int progress)> ShowProgressFn
Register handler for show progress messages.
Definition: wallet.h:253
A CWallet is an extension of a keystore, which also maintains a set of transactions and balances...
Definition: wallet.h:599
Fee rate in satoshis per kilobyte: CAmount / kB.
Definition: feerate.h:19
std::unique_ptr< CConnman > g_connman
Definition: init.cpp:74
bool error(const char *fmt, const Args &... args)
Definition: util.h:59
void StartShutdown()
Definition: shutdown.cpp:12
bool GetProxy(enum Network net, proxyType &proxyInfoOut)
Definition: netbase.cpp:551
int flags
Definition: bsha3-tx.cpp:509
bool AppInitLockDataDirectory()
Lock bitcoin core data directory.
Definition: init.cpp:1140
CClientUIInterface uiInterface
int nHeight
height of the entry in the chain. The genesis block has height 0
Definition: chain.h:183
CChain & chainActive
The currently-connected chain of blocks (protected by cs_main).
Definition: validation.cpp:219
std::vector< std::string > listCommands() const
Returns a list of registered commands.
Definition: server.cpp:500
BCLog::Logger *const g_logger
NOTE: the logger instances is leaked on exit.
Definition: logging.cpp:24
void StartMapPort()
Definition: net.cpp:1599
void InterruptMapPort()
Definition: net.cpp:1603
std::vector< fs::path > ListWalletDir()
Definition: dummywallet.cpp:42
CFeeRate dustRelayFee
Definition: policy.cpp:243