Bitcoin Core  0.18.99
P2P Digital Currency
chain.cpp
Go to the documentation of this file.
1 // Copyright (c) 2018-2019 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/chain.h>
6 
7 #include <chain.h>
8 #include <chainparams.h>
9 #include <interfaces/handler.h>
10 #include <interfaces/wallet.h>
11 #include <net.h>
12 #include <node/coin.h>
13 #include <policy/fees.h>
14 #include <policy/policy.h>
15 #include <policy/rbf.h>
16 #include <policy/settings.h>
17 #include <primitives/block.h>
18 #include <primitives/transaction.h>
19 #include <protocol.h>
20 #include <rpc/protocol.h>
21 #include <rpc/server.h>
22 #include <shutdown.h>
23 #include <sync.h>
24 #include <threadsafety.h>
25 #include <timedata.h>
26 #include <txmempool.h>
27 #include <ui_interface.h>
28 #include <uint256.h>
29 #include <univalue.h>
30 #include <util/system.h>
31 #include <validation.h>
32 #include <validationinterface.h>
33 
34 #include <memory>
35 #include <utility>
36 
37 namespace interfaces {
38 namespace {
39 
40 class LockImpl : public Chain::Lock, public UniqueLock<CCriticalSection>
41 {
42  Optional<int> getHeight() override
43  {
44  LockAssertion lock(::cs_main);
45  int height = ::ChainActive().Height();
46  if (height >= 0) {
47  return height;
48  }
49  return nullopt;
50  }
51  Optional<int> getBlockHeight(const uint256& hash) override
52  {
53  LockAssertion lock(::cs_main);
54  CBlockIndex* block = LookupBlockIndex(hash);
55  if (block && ::ChainActive().Contains(block)) {
56  return block->nHeight;
57  }
58  return nullopt;
59  }
60  int getBlockDepth(const uint256& hash) override
61  {
62  const Optional<int> tip_height = getHeight();
63  const Optional<int> height = getBlockHeight(hash);
64  return tip_height && height ? *tip_height - *height + 1 : 0;
65  }
66  uint256 getBlockHash(int height) override
67  {
68  LockAssertion lock(::cs_main);
69  CBlockIndex* block = ::ChainActive()[height];
70  assert(block != nullptr);
71  return block->GetBlockHash();
72  }
73  int64_t getBlockTime(int height) override
74  {
75  LockAssertion lock(::cs_main);
76  CBlockIndex* block = ::ChainActive()[height];
77  assert(block != nullptr);
78  return block->GetBlockTime();
79  }
80  int64_t getBlockMedianTimePast(int height) override
81  {
82  LockAssertion lock(::cs_main);
83  CBlockIndex* block = ::ChainActive()[height];
84  assert(block != nullptr);
85  return block->GetMedianTimePast();
86  }
87  bool haveBlockOnDisk(int height) override
88  {
89  LockAssertion lock(::cs_main);
90  CBlockIndex* block = ::ChainActive()[height];
91  return block && ((block->nStatus & BLOCK_HAVE_DATA) != 0) && block->nTx > 0;
92  }
93  Optional<int> findFirstBlockWithTimeAndHeight(int64_t time, int height, uint256* hash) override
94  {
95  LockAssertion lock(::cs_main);
96  CBlockIndex* block = ::ChainActive().FindEarliestAtLeast(time, height);
97  if (block) {
98  if (hash) *hash = block->GetBlockHash();
99  return block->nHeight;
100  }
101  return nullopt;
102  }
103  Optional<int> findPruned(int start_height, Optional<int> stop_height) override
104  {
105  LockAssertion lock(::cs_main);
106  if (::fPruneMode) {
107  CBlockIndex* block = stop_height ? ::ChainActive()[*stop_height] : ::ChainActive().Tip();
108  while (block && block->nHeight >= start_height) {
109  if ((block->nStatus & BLOCK_HAVE_DATA) == 0) {
110  return block->nHeight;
111  }
112  block = block->pprev;
113  }
114  }
115  return nullopt;
116  }
117  Optional<int> findFork(const uint256& hash, Optional<int>* height) override
118  {
119  LockAssertion lock(::cs_main);
120  const CBlockIndex* block = LookupBlockIndex(hash);
121  const CBlockIndex* fork = block ? ::ChainActive().FindFork(block) : nullptr;
122  if (height) {
123  if (block) {
124  *height = block->nHeight;
125  } else {
126  height->reset();
127  }
128  }
129  if (fork) {
130  return fork->nHeight;
131  }
132  return nullopt;
133  }
134  CBlockLocator getTipLocator() override
135  {
136  LockAssertion lock(::cs_main);
138  }
139  Optional<int> findLocatorFork(const CBlockLocator& locator) override
140  {
141  LockAssertion lock(::cs_main);
142  if (CBlockIndex* fork = FindForkInGlobalIndex(::ChainActive(), locator)) {
143  return fork->nHeight;
144  }
145  return nullopt;
146  }
147  bool checkFinalTx(const CTransaction& tx) override
148  {
149  LockAssertion lock(::cs_main);
150  return CheckFinalTx(tx);
151  }
152  bool submitToMemoryPool(const CTransactionRef& tx, CAmount absurd_fee, CValidationState& state) override
153  {
154  LockAssertion lock(::cs_main);
155  return AcceptToMemoryPool(::mempool, state, tx, nullptr /* missing inputs */, nullptr /* txn replaced */,
156  false /* bypass limits */, absurd_fee);
157  }
158 
160 };
161 
162 class NotificationsHandlerImpl : public Handler, CValidationInterface
163 {
164 public:
165  explicit NotificationsHandlerImpl(Chain& chain, Chain::Notifications& notifications)
166  : m_chain(chain), m_notifications(&notifications)
167  {
169  }
170  ~NotificationsHandlerImpl() override { disconnect(); }
171  void disconnect() override
172  {
173  if (m_notifications) {
174  m_notifications = nullptr;
176  }
177  }
178  void TransactionAddedToMempool(const CTransactionRef& tx) override
179  {
180  m_notifications->TransactionAddedToMempool(tx);
181  }
182  void TransactionRemovedFromMempool(const CTransactionRef& tx) override
183  {
184  m_notifications->TransactionRemovedFromMempool(tx);
185  }
186  void BlockConnected(const std::shared_ptr<const CBlock>& block,
187  const CBlockIndex* index,
188  const std::vector<CTransactionRef>& tx_conflicted) override
189  {
190  m_notifications->BlockConnected(*block, tx_conflicted);
191  }
192  void BlockDisconnected(const std::shared_ptr<const CBlock>& block) override
193  {
194  m_notifications->BlockDisconnected(*block);
195  }
196  void UpdatedBlockTip(const CBlockIndex* index, const CBlockIndex* fork_index, bool is_ibd) override
197  {
198  m_notifications->UpdatedBlockTip();
199  }
200  void ChainStateFlushed(const CBlockLocator& locator) override { m_notifications->ChainStateFlushed(locator); }
201  Chain& m_chain;
202  Chain::Notifications* m_notifications;
203 };
204 
205 class RpcHandlerImpl : public Handler
206 {
207 public:
208  RpcHandlerImpl(const CRPCCommand& command) : m_command(command), m_wrapped_command(&command)
209  {
210  m_command.actor = [this](const JSONRPCRequest& request, UniValue& result, bool last_handler) {
211  if (!m_wrapped_command) return false;
212  try {
213  return m_wrapped_command->actor(request, result, last_handler);
214  } catch (const UniValue& e) {
215  // If this is not the last handler and a wallet not found
216  // exception was thrown, return false so the next handler can
217  // try to handle the request. Otherwise, reraise the exception.
218  if (!last_handler) {
219  const UniValue& code = e["code"];
220  if (code.isNum() && code.get_int() == RPC_WALLET_NOT_FOUND) {
221  return false;
222  }
223  }
224  throw;
225  }
226  };
228  }
229 
230  void disconnect() override final
231  {
232  if (m_wrapped_command) {
233  m_wrapped_command = nullptr;
235  }
236  }
237 
238  ~RpcHandlerImpl() override { disconnect(); }
239 
242 };
243 
244 class ChainImpl : public Chain
245 {
246 public:
247  std::unique_ptr<Chain::Lock> lock(bool try_lock) override
248  {
249  auto result = MakeUnique<LockImpl>(::cs_main, "cs_main", __FILE__, __LINE__, try_lock);
250  if (try_lock && result && !*result) return {};
251  // std::move necessary on some compilers due to conversion from
252  // LockImpl to Lock pointer
253  return std::move(result);
254  }
255  bool findBlock(const uint256& hash, CBlock* block, int64_t* time, int64_t* time_max) override
256  {
257  CBlockIndex* index;
258  {
259  LOCK(cs_main);
260  index = LookupBlockIndex(hash);
261  if (!index) {
262  return false;
263  }
264  if (time) {
265  *time = index->GetBlockTime();
266  }
267  if (time_max) {
268  *time_max = index->GetBlockTimeMax();
269  }
270  }
271  if (block && !ReadBlockFromDisk(*block, index, Params().GetConsensus())) {
272  block->SetNull();
273  }
274  return true;
275  }
276  void findCoins(std::map<COutPoint, Coin>& coins) override { return FindCoins(coins); }
277  double guessVerificationProgress(const uint256& block_hash) override
278  {
279  LOCK(cs_main);
280  return GuessVerificationProgress(Params().TxData(), LookupBlockIndex(block_hash));
281  }
282  RBFTransactionState isRBFOptIn(const CTransaction& tx) override
283  {
284  LOCK(::mempool.cs);
285  return IsRBFOptIn(tx, ::mempool);
286  }
287  bool hasDescendantsInMempool(const uint256& txid) override
288  {
289  LOCK(::mempool.cs);
290  auto it = ::mempool.GetIter(txid);
291  return it && (*it)->GetCountWithDescendants() > 1;
292  }
293  void relayTransaction(const uint256& txid) override
294  {
295  CInv inv(MSG_TX, txid);
296  g_connman->ForEachNode([&inv](CNode* node) { node->PushInventory(inv); });
297  }
298  void getTransactionAncestry(const uint256& txid, size_t& ancestors, size_t& descendants) override
299  {
300  ::mempool.GetTransactionAncestry(txid, ancestors, descendants);
301  }
302  bool checkChainLimits(const CTransactionRef& tx) override
303  {
304  LockPoints lp;
305  CTxMemPoolEntry entry(tx, 0, 0, 0, false, 0, lp);
306  CTxMemPool::setEntries ancestors;
307  auto limit_ancestor_count = gArgs.GetArg("-limitancestorcount", DEFAULT_ANCESTOR_LIMIT);
308  auto limit_ancestor_size = gArgs.GetArg("-limitancestorsize", DEFAULT_ANCESTOR_SIZE_LIMIT) * 1000;
309  auto limit_descendant_count = gArgs.GetArg("-limitdescendantcount", DEFAULT_DESCENDANT_LIMIT);
310  auto limit_descendant_size = gArgs.GetArg("-limitdescendantsize", DEFAULT_DESCENDANT_SIZE_LIMIT) * 1000;
311  std::string unused_error_string;
312  LOCK(::mempool.cs);
313  return ::mempool.CalculateMemPoolAncestors(entry, ancestors, limit_ancestor_count, limit_ancestor_size,
314  limit_descendant_count, limit_descendant_size, unused_error_string);
315  }
316  CFeeRate estimateSmartFee(int num_blocks, bool conservative, FeeCalculation* calc) override
317  {
318  return ::feeEstimator.estimateSmartFee(num_blocks, calc, conservative);
319  }
320  unsigned int estimateMaxBlocks() override
321  {
323  }
324  CFeeRate mempoolMinFee() override
325  {
326  return ::mempool.GetMinFee(gArgs.GetArg("-maxmempool", DEFAULT_MAX_MEMPOOL_SIZE) * 1000000);
327  }
328  CFeeRate relayMinFee() override { return ::minRelayTxFee; }
329  CFeeRate relayIncrementalFee() override { return ::incrementalRelayFee; }
330  CFeeRate relayDustFee() override { return ::dustRelayFee; }
331  bool havePruned() override
332  {
333  LOCK(cs_main);
335  }
336  bool p2pEnabled() override { return g_connman != nullptr; }
337  bool isReadyToBroadcast() override { return !::fImporting && !::fReindex && !IsInitialBlockDownload(); }
338  bool isInitialBlockDownload() override { return IsInitialBlockDownload(); }
339  bool shutdownRequested() override { return ShutdownRequested(); }
340  int64_t getAdjustedTime() override { return GetAdjustedTime(); }
341  void initMessage(const std::string& message) override { ::uiInterface.InitMessage(message); }
342  void initWarning(const std::string& message) override { InitWarning(message); }
343  void initError(const std::string& message) override { InitError(message); }
344  void loadWallet(std::unique_ptr<Wallet> wallet) override { ::uiInterface.LoadWallet(wallet); }
345  void showProgress(const std::string& title, int progress, bool resume_possible) override
346  {
347  ::uiInterface.ShowProgress(title, progress, resume_possible);
348  }
349  std::unique_ptr<Handler> handleNotifications(Notifications& notifications) override
350  {
351  return MakeUnique<NotificationsHandlerImpl>(*this, notifications);
352  }
353  void waitForNotificationsIfNewBlocksConnected(const uint256& old_tip) override
354  {
355  if (!old_tip.IsNull()) {
356  LOCK(::cs_main);
357  if (old_tip == ::ChainActive().Tip()->GetBlockHash()) return;
358  CBlockIndex* block = LookupBlockIndex(old_tip);
359  if (block && block->GetAncestor(::ChainActive().Height()) == ::ChainActive().Tip()) return;
360  }
362  }
363  std::unique_ptr<Handler> handleRpc(const CRPCCommand& command) override
364  {
365  return MakeUnique<RpcHandlerImpl>(command);
366  }
367  bool rpcEnableDeprecated(const std::string& method) override { return IsDeprecatedRPCEnabled(method); }
368  void rpcRunLater(const std::string& name, std::function<void()> fn, int64_t seconds) override
369  {
370  RPCRunLater(name, std::move(fn), seconds);
371  }
372  int rpcSerializationFlags() override { return RPCSerializationFlags(); }
373  void requestMempoolTransactions(Notifications& notifications) override
374  {
375  LOCK2(::cs_main, ::mempool.cs);
376  for (const CTxMemPoolEntry& entry : ::mempool.mapTx) {
377  notifications.TransactionAddedToMempool(entry.GetSharedTx());
378  }
379  }
380 };
381 } // namespace
382 
383 std::unique_ptr<Chain> MakeChain() { return MakeUnique<ChainImpl>(); }
384 
385 } // namespace interfaces
std::shared_ptr< const CTransaction > CTransactionRef
Definition: transaction.h:408
CTxMemPool mempool
bool ShutdownRequested()
Definition: shutdown.cpp:20
void SyncWithValidationInterfaceQueue()
This is a synonym for the following, which asserts certain locks are not held: std::promise<void> pro...
bool fPruneMode
True if we&#39;re running in -prune mode.
Definition: validation.cpp:246
int64_t GetBlockTime() const
Definition: chain.h:275
Describes a place in the block chain to another node such that if the other node doesn&#39;t have the sam...
Definition: block.h:126
CBlockIndex * pprev
pointer to the index of the predecessor of this block
Definition: chain.h:146
RBFTransactionState IsRBFOptIn(const CTransaction &tx, const CTxMemPool &pool)
Definition: rbf.cpp:8
uint32_t nStatus
Verification status of this block. See enum BlockStatus.
Definition: chain.h:176
Definition: block.h:72
Actor actor
Definition: server.h:127
CChain & ChainActive()
Definition: validation.cpp:223
bool fHavePruned
Pruning-related variables and constants.
Definition: validation.cpp:245
inv message data
Definition: protocol.h:385
bool ReadBlockFromDisk(CBlock &block, const FlatFilePos &pos, const Consensus::Params &consensusParams)
Functions for disk access for blocks.
CFeeRate dustRelayFee
Definition: settings.cpp:13
int Height() const
Return the maximal height in the chain.
Definition: chain.h:455
bool removeCommand(const std::string &name, const CRPCCommand *pcmd)
Definition: server.cpp:273
std::set< txiter, CompareIteratorByHash > setEntries
Definition: txmempool.h:537
bool isNum() const
Definition: univalue.h:83
void UnregisterValidationInterface(CValidationInterface *pwalletIn)
Unregister a wallet from core.
void RPCRunLater(const std::string &name, std::function< void()> func, int64_t nSeconds)
Run func nSeconds from now.
Definition: server.cpp:520
bool appendCommand(const std::string &name, const CRPCCommand *pcmd)
Appends a CRPCCommand to the dispatch table.
Definition: server.cpp:264
Implement this to subscribe to events generated in validation.
bool IsNull() const
Definition: uint256.h:31
void PushInventory(const CInv &inv)
Definition: net.h:842
RBFTransactionState
Definition: rbf.h:10
bool AcceptToMemoryPool(CTxMemPool &pool, CValidationState &state, const CTransactionRef &tx, bool *pfMissingInputs, std::list< CTransactionRef > *plTxnReplaced, bool bypass_limits, const CAmount nAbsurdFee, bool test_accept)
(try to) add transaction to memory pool plTxnReplaced will be appended to with all transactions repla...
Definition: validation.cpp:999
CTxMemPoolEntry stores data about the corresponding transaction, as well as data about all in-mempool...
Definition: txmempool.h:66
int64_t CAmount
Amount in satoshis (Can be negative)
Definition: amount.h:12
uint256 GetBlockHash() const
Definition: chain.h:261
CBlockPolicyEstimator feeEstimator
Definition: validation.cpp:260
CBlockIndex * FindEarliestAtLeast(int64_t nTime, int height) const
Find the earliest block with timestamp equal or greater than the given time and height equal or great...
Definition: chain.cpp:62
#define LOCK2(cs1, cs2)
Definition: sync.h:183
std::string name
Definition: server.h:126
CRPCTable tableRPC
Definition: server.cpp:537
bool CheckFinalTx(const CTransaction &tx, int flags)
Transaction validation functions.
Definition: validation.cpp:330
CCriticalSection cs_main
Mutex to guard access to validation specific variables, such as reading or changing the chainstate...
Definition: validation.cpp:235
CFeeRate minRelayTxFee
A fee rate smaller than this is considered zero fee (for relaying, mining and transaction creation) ...
Definition: validation.cpp:258
Chain & m_chain
Definition: chain.cpp:201
#define LOCK(cs)
Definition: sync.h:182
const char * name
Definition: rest.cpp:38
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
CTransactionRef GetSharedTx() const
Definition: txmempool.h:100
UniqueLock(Mutex &mutexIn, const char *pszName, const char *pszFile, int nLine, bool fTry=false) EXCLUSIVE_LOCK_FUNCTION(mutexIn)
Definition: sync.h:145
int64_t GetBlockTimeMax() const
Definition: chain.h:280
bool IsInitialBlockDownload()
Check whether we are doing an initial block download (synchronizing from disk or network) ...
const CRPCCommand * m_wrapped_command
Definition: chain.cpp:241
std::atomic_bool fImporting
int get_int() const
bool CalculateMemPoolAncestors(const CTxMemPoolEntry &entry, setEntries &setAncestors, uint64_t limitAncestorCount, uint64_t limitAncestorSize, uint64_t limitDescendantCount, uint64_t limitDescendantSize, std::string &errString, bool fSearchForParents=true) const EXCLUSIVE_LOCKS_REQUIRED(cs)
Try to calculate all in-mempool ancestors of entry.
Definition: txmempool.cpp:150
Invalid wallet specified.
Definition: protocol.h:85
CFeeRate GetMinFee(size_t sizelimit) const
The minimum fee to get into the mempool, which may itself not be enough for larger-sized transactions...
Definition: txmempool.cpp:987
bool IsDeprecatedRPCEnabled(const std::string &method)
Definition: server.cpp:367
int64_t GetMedianTimePast() const
Definition: chain.h:287
CRPCCommand m_command
Definition: chain.cpp:240
void RegisterValidationInterface(CValidationInterface *pwalletIn)
Register a wallet to receive updates from core.
std::atomic_bool fReindex
unsigned int HighestTargetTracked(FeeEstimateHorizon horizon) const
Calculation of highest target that estimates are tracked for.
Definition: fees.cpp:677
Capture information about block/transaction validation.
Definition: validation.h:98
std::unique_ptr< Chain > MakeChain()
Return implementation of Chain interface.
Definition: chain.cpp:383
256-bit opaque blob.
Definition: uint256.h:121
bool InitError(const std::string &str)
Show error message.
void SetNull()
Definition: block.h:100
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.
int RPCSerializationFlags()
Definition: server.cpp:529
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
CBlockIndex * FindForkInGlobalIndex(const CChain &chain, const CBlockLocator &locator)
Find the last common block between the parameter chain and a locator.
Definition: validation.cpp:291
int64_t GetAdjustedTime()
Definition: timedata.cpp:35
boost::optional< txiter > GetIter(const uint256 &txid) const EXCLUSIVE_LOCKS_REQUIRED(cs)
Returns an iterator to the given hash, if found.
Definition: txmempool.cpp:869
CBlockIndex * Tip() const
Returns the index entry for the tip of this chain, or nullptr if none.
Definition: chain.h:424
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
CBlockLocator GetLocator(const CBlockIndex *pindex=nullptr) const
Return a CBlockLocator that refers to a block in this chain (by default the tip). ...
Definition: chain.cpp:23
CBlockIndex * LookupBlockIndex(const uint256 &hash) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
Definition: validation.h:415
Chain::Notifications * m_notifications
Definition: chain.cpp:202
Wrapper around std::unique_lock style lock for Mutex.
Definition: sync.h:119
void InitWarning(const std::string &str)
Show warning message.
CClientUIInterface uiInterface
The basic transaction that is broadcasted on the network and contained in blocks. ...
Definition: transaction.h:270
int nHeight
height of the entry in the chain. The genesis block has height 0
Definition: chain.h:152
boost::optional< T > Optional
Substitute for C++17 std::optional.
Definition: optional.h:14
void FindCoins(std::map< COutPoint, Coin > &coins)
Look up unspent output information.
Definition: coin.cpp:10
Information about a peer.
Definition: net.h:619
CBlockIndex * GetAncestor(int height)
Efficiently find an ancestor of this block.
Definition: chain.cpp:111
full block available in blk*.dat
Definition: chain.h:123
CFeeRate incrementalRelayFee
Definition: settings.cpp:12
const CBlockIndex * FindFork(const CBlockIndex *pindex) const
Find the last common block between this chain and a block index entry.
Definition: chain.cpp:51
unsigned int nTx
Number of transactions in this block.
Definition: chain.h:168
RecursiveMutex cs
This mutex needs to be locked when accessing mapTx or other members that are guarded by it...
Definition: txmempool.h:526
void GetTransactionAncestry(const uint256 &txid, size_t &ancestors, size_t &descendants) const
Calculate the ancestor and descendant count for the given transaction.
Definition: txmempool.cpp:1084
LockPoints lp