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 <net_processing.h>
13 #include <node/coin.h>
14 #include <node/transaction.h>
15 #include <policy/fees.h>
16 #include <policy/policy.h>
17 #include <policy/rbf.h>
18 #include <policy/settings.h>
19 #include <primitives/block.h>
20 #include <primitives/transaction.h>
21 #include <protocol.h>
22 #include <rpc/protocol.h>
23 #include <rpc/server.h>
24 #include <shutdown.h>
25 #include <sync.h>
26 #include <threadsafety.h>
27 #include <timedata.h>
28 #include <txmempool.h>
29 #include <ui_interface.h>
30 #include <uint256.h>
31 #include <univalue.h>
32 #include <util/system.h>
33 #include <validation.h>
34 #include <validationinterface.h>
35 
36 #include <memory>
37 #include <utility>
38 
39 namespace interfaces {
40 namespace {
41 
42 class LockImpl : public Chain::Lock, public UniqueLock<CCriticalSection>
43 {
44  Optional<int> getHeight() override
45  {
46  LockAssertion lock(::cs_main);
47  int height = ::ChainActive().Height();
48  if (height >= 0) {
49  return height;
50  }
51  return nullopt;
52  }
53  Optional<int> getBlockHeight(const uint256& hash) override
54  {
55  LockAssertion lock(::cs_main);
56  CBlockIndex* block = LookupBlockIndex(hash);
57  if (block && ::ChainActive().Contains(block)) {
58  return block->nHeight;
59  }
60  return nullopt;
61  }
62  int getBlockDepth(const uint256& hash) override
63  {
64  const Optional<int> tip_height = getHeight();
65  const Optional<int> height = getBlockHeight(hash);
66  return tip_height && height ? *tip_height - *height + 1 : 0;
67  }
68  uint256 getBlockHash(int height) override
69  {
70  LockAssertion lock(::cs_main);
71  CBlockIndex* block = ::ChainActive()[height];
72  assert(block != nullptr);
73  return block->GetBlockHash();
74  }
75  int64_t getBlockTime(int height) override
76  {
77  LockAssertion lock(::cs_main);
78  CBlockIndex* block = ::ChainActive()[height];
79  assert(block != nullptr);
80  return block->GetBlockTime();
81  }
82  int64_t getBlockMedianTimePast(int height) override
83  {
84  LockAssertion lock(::cs_main);
85  CBlockIndex* block = ::ChainActive()[height];
86  assert(block != nullptr);
87  return block->GetMedianTimePast();
88  }
89  bool haveBlockOnDisk(int height) override
90  {
91  LockAssertion lock(::cs_main);
92  CBlockIndex* block = ::ChainActive()[height];
93  return block && ((block->nStatus & BLOCK_HAVE_DATA) != 0) && block->nTx > 0;
94  }
95  Optional<int> findFirstBlockWithTimeAndHeight(int64_t time, int height, uint256* hash) override
96  {
97  LockAssertion lock(::cs_main);
98  CBlockIndex* block = ::ChainActive().FindEarliestAtLeast(time, height);
99  if (block) {
100  if (hash) *hash = block->GetBlockHash();
101  return block->nHeight;
102  }
103  return nullopt;
104  }
105  Optional<int> findPruned(int start_height, Optional<int> stop_height) override
106  {
107  LockAssertion lock(::cs_main);
108  if (::fPruneMode) {
109  CBlockIndex* block = stop_height ? ::ChainActive()[*stop_height] : ::ChainActive().Tip();
110  while (block && block->nHeight >= start_height) {
111  if ((block->nStatus & BLOCK_HAVE_DATA) == 0) {
112  return block->nHeight;
113  }
114  block = block->pprev;
115  }
116  }
117  return nullopt;
118  }
119  Optional<int> findFork(const uint256& hash, Optional<int>* height) override
120  {
121  LockAssertion lock(::cs_main);
122  const CBlockIndex* block = LookupBlockIndex(hash);
123  const CBlockIndex* fork = block ? ::ChainActive().FindFork(block) : nullptr;
124  if (height) {
125  if (block) {
126  *height = block->nHeight;
127  } else {
128  height->reset();
129  }
130  }
131  if (fork) {
132  return fork->nHeight;
133  }
134  return nullopt;
135  }
136  CBlockLocator getTipLocator() override
137  {
138  LockAssertion lock(::cs_main);
140  }
141  Optional<int> findLocatorFork(const CBlockLocator& locator) override
142  {
143  LockAssertion lock(::cs_main);
144  if (CBlockIndex* fork = FindForkInGlobalIndex(::ChainActive(), locator)) {
145  return fork->nHeight;
146  }
147  return nullopt;
148  }
149  bool checkFinalTx(const CTransaction& tx) override
150  {
151  LockAssertion lock(::cs_main);
152  return CheckFinalTx(tx);
153  }
154 
156 };
157 
158 class NotificationsHandlerImpl : public Handler, CValidationInterface
159 {
160 public:
161  explicit NotificationsHandlerImpl(Chain& chain, Chain::Notifications& notifications)
162  : m_chain(chain), m_notifications(&notifications)
163  {
165  }
166  ~NotificationsHandlerImpl() override { disconnect(); }
167  void disconnect() override
168  {
169  if (m_notifications) {
170  m_notifications = nullptr;
172  }
173  }
174  void TransactionAddedToMempool(const CTransactionRef& tx) override
175  {
176  m_notifications->TransactionAddedToMempool(tx);
177  }
178  void TransactionRemovedFromMempool(const CTransactionRef& tx) override
179  {
180  m_notifications->TransactionRemovedFromMempool(tx);
181  }
182  void BlockConnected(const std::shared_ptr<const CBlock>& block,
183  const CBlockIndex* index,
184  const std::vector<CTransactionRef>& tx_conflicted) override
185  {
186  m_notifications->BlockConnected(*block, tx_conflicted);
187  }
188  void BlockDisconnected(const std::shared_ptr<const CBlock>& block) override
189  {
190  m_notifications->BlockDisconnected(*block);
191  }
192  void UpdatedBlockTip(const CBlockIndex* index, const CBlockIndex* fork_index, bool is_ibd) override
193  {
194  m_notifications->UpdatedBlockTip();
195  }
196  void ChainStateFlushed(const CBlockLocator& locator) override { m_notifications->ChainStateFlushed(locator); }
197  Chain& m_chain;
198  Chain::Notifications* m_notifications;
199 };
200 
201 class RpcHandlerImpl : public Handler
202 {
203 public:
204  explicit RpcHandlerImpl(const CRPCCommand& command) : m_command(command), m_wrapped_command(&command)
205  {
206  m_command.actor = [this](const JSONRPCRequest& request, UniValue& result, bool last_handler) {
207  if (!m_wrapped_command) return false;
208  try {
209  return m_wrapped_command->actor(request, result, last_handler);
210  } catch (const UniValue& e) {
211  // If this is not the last handler and a wallet not found
212  // exception was thrown, return false so the next handler can
213  // try to handle the request. Otherwise, reraise the exception.
214  if (!last_handler) {
215  const UniValue& code = e["code"];
216  if (code.isNum() && code.get_int() == RPC_WALLET_NOT_FOUND) {
217  return false;
218  }
219  }
220  throw;
221  }
222  };
224  }
225 
226  void disconnect() override final
227  {
228  if (m_wrapped_command) {
229  m_wrapped_command = nullptr;
231  }
232  }
233 
234  ~RpcHandlerImpl() override { disconnect(); }
235 
238 };
239 
240 class ChainImpl : public Chain
241 {
242 public:
243  std::unique_ptr<Chain::Lock> lock(bool try_lock) override
244  {
245  auto result = MakeUnique<LockImpl>(::cs_main, "cs_main", __FILE__, __LINE__, try_lock);
246  if (try_lock && result && !*result) return {};
247  // std::move necessary on some compilers due to conversion from
248  // LockImpl to Lock pointer
249  return std::move(result);
250  }
251  bool findBlock(const uint256& hash, CBlock* block, int64_t* time, int64_t* time_max) override
252  {
253  CBlockIndex* index;
254  {
255  LOCK(cs_main);
256  index = LookupBlockIndex(hash);
257  if (!index) {
258  return false;
259  }
260  if (time) {
261  *time = index->GetBlockTime();
262  }
263  if (time_max) {
264  *time_max = index->GetBlockTimeMax();
265  }
266  }
267  if (block && !ReadBlockFromDisk(*block, index, Params().GetConsensus())) {
268  block->SetNull();
269  }
270  return true;
271  }
272  void findCoins(std::map<COutPoint, Coin>& coins) override { return FindCoins(coins); }
273  double guessVerificationProgress(const uint256& block_hash) override
274  {
275  LOCK(cs_main);
276  return GuessVerificationProgress(Params().TxData(), LookupBlockIndex(block_hash));
277  }
278  RBFTransactionState isRBFOptIn(const CTransaction& tx) override
279  {
280  LOCK(::mempool.cs);
281  return IsRBFOptIn(tx, ::mempool);
282  }
283  bool hasDescendantsInMempool(const uint256& txid) override
284  {
285  LOCK(::mempool.cs);
286  auto it = ::mempool.GetIter(txid);
287  return it && (*it)->GetCountWithDescendants() > 1;
288  }
289  bool broadcastTransaction(const CTransactionRef& tx, std::string& err_string, const CAmount& max_tx_fee, bool relay) override
290  {
291  const TransactionError err = BroadcastTransaction(tx, err_string, max_tx_fee, relay, /*wait_callback*/ false);
292  // Chain clients only care about failures to accept the tx to the mempool. Disregard non-mempool related failures.
293  // Note: this will need to be updated if BroadcastTransactions() is updated to return other non-mempool failures
294  // that Chain clients do not need to know about.
295  return TransactionError::OK == err;
296  }
297  void getTransactionAncestry(const uint256& txid, size_t& ancestors, size_t& descendants) override
298  {
299  ::mempool.GetTransactionAncestry(txid, ancestors, descendants);
300  }
301  bool checkChainLimits(const CTransactionRef& tx) override
302  {
303  LockPoints lp;
304  CTxMemPoolEntry entry(tx, 0, 0, 0, false, 0, lp);
305  CTxMemPool::setEntries ancestors;
306  auto limit_ancestor_count = gArgs.GetArg("-limitancestorcount", DEFAULT_ANCESTOR_LIMIT);
307  auto limit_ancestor_size = gArgs.GetArg("-limitancestorsize", DEFAULT_ANCESTOR_SIZE_LIMIT) * 1000;
308  auto limit_descendant_count = gArgs.GetArg("-limitdescendantcount", DEFAULT_DESCENDANT_LIMIT);
309  auto limit_descendant_size = gArgs.GetArg("-limitdescendantsize", DEFAULT_DESCENDANT_SIZE_LIMIT) * 1000;
310  std::string unused_error_string;
311  LOCK(::mempool.cs);
312  return ::mempool.CalculateMemPoolAncestors(entry, ancestors, limit_ancestor_count, limit_ancestor_size,
313  limit_descendant_count, limit_descendant_size, unused_error_string);
314  }
315  CFeeRate estimateSmartFee(int num_blocks, bool conservative, FeeCalculation* calc) override
316  {
317  return ::feeEstimator.estimateSmartFee(num_blocks, calc, conservative);
318  }
319  unsigned int estimateMaxBlocks() override
320  {
322  }
323  CFeeRate mempoolMinFee() override
324  {
326  }
327  CFeeRate relayMinFee() override { return ::minRelayTxFee; }
328  CFeeRate relayIncrementalFee() override { return ::incrementalRelayFee; }
329  CFeeRate relayDustFee() override { return ::dustRelayFee; }
330  bool havePruned() override
331  {
332  LOCK(cs_main);
334  }
335  bool isReadyToBroadcast() override { return !::fImporting && !::fReindex && !isInitialBlockDownload(); }
336  bool isInitialBlockDownload() override { return ::ChainstateActive().IsInitialBlockDownload(); }
337  bool shutdownRequested() override { return ShutdownRequested(); }
338  int64_t getAdjustedTime() override { return GetAdjustedTime(); }
339  void initMessage(const std::string& message) override { ::uiInterface.InitMessage(message); }
340  void initWarning(const std::string& message) override { InitWarning(message); }
341  void initError(const std::string& message) override { InitError(message); }
342  void loadWallet(std::unique_ptr<Wallet> wallet) override { ::uiInterface.LoadWallet(wallet); }
343  void showProgress(const std::string& title, int progress, bool resume_possible) override
344  {
345  ::uiInterface.ShowProgress(title, progress, resume_possible);
346  }
347  std::unique_ptr<Handler> handleNotifications(Notifications& notifications) override
348  {
349  return MakeUnique<NotificationsHandlerImpl>(*this, notifications);
350  }
351  void waitForNotificationsIfNewBlocksConnected(const uint256& old_tip) override
352  {
353  if (!old_tip.IsNull()) {
354  LOCK(::cs_main);
355  if (old_tip == ::ChainActive().Tip()->GetBlockHash()) return;
356  CBlockIndex* block = LookupBlockIndex(old_tip);
357  if (block && block->GetAncestor(::ChainActive().Height()) == ::ChainActive().Tip()) return;
358  }
360  }
361  std::unique_ptr<Handler> handleRpc(const CRPCCommand& command) override
362  {
363  return MakeUnique<RpcHandlerImpl>(command);
364  }
365  bool rpcEnableDeprecated(const std::string& method) override { return IsDeprecatedRPCEnabled(method); }
366  void rpcRunLater(const std::string& name, std::function<void()> fn, int64_t seconds) override
367  {
368  RPCRunLater(name, std::move(fn), seconds);
369  }
370  int rpcSerializationFlags() override { return RPCSerializationFlags(); }
371  void requestMempoolTransactions(Notifications& notifications) override
372  {
373  LOCK2(::cs_main, ::mempool.cs);
374  for (const CTxMemPoolEntry& entry : ::mempool.mapTx) {
375  notifications.TransactionAddedToMempool(entry.GetSharedTx());
376  }
377  }
378 };
379 } // namespace
380 
381 std::unique_ptr<Chain> MakeChain() { return MakeUnique<ChainImpl>(); }
382 
383 } // namespace interfaces
std::shared_ptr< const CTransaction > CTransactionRef
Definition: transaction.h:408
static const unsigned int DEFAULT_ANCESTOR_SIZE_LIMIT
Default for -limitancestorsize, maximum kilobytes of tx + all in-mempool ancestors.
Definition: validation.h:58
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...
static const unsigned int DEFAULT_DESCENDANT_LIMIT
Default for -limitdescendantcount, max number of in-mempool descendants.
Definition: validation.h:60
bool fPruneMode
True if we&#39;re running in -prune mode.
Definition: validation.cpp:117
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:113
CChain & ChainActive()
Definition: validation.cpp:92
static const unsigned int DEFAULT_MAX_MEMPOOL_SIZE
Default for -maxmempool, maximum megabytes of mempool memory usage.
Definition: policy.h:32
bool fHavePruned
Pruning-related variables and constants.
Definition: validation.cpp:116
bool ReadBlockFromDisk(CBlock &block, const FlatFilePos &pos, const Consensus::Params &consensusParams)
Functions for disk access for blocks.
Definition: validation.cpp:950
static const unsigned int DEFAULT_ANCESTOR_LIMIT
Default for -limitancestorcount, max number of in-mempool ancestors.
Definition: validation.h:56
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:270
std::set< txiter, CompareIteratorByHash > setEntries
Definition: txmempool.h:528
static auto & nullopt
Substitute for C++17 std::nullopt.
Definition: optional.h:24
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:484
bool appendCommand(const std::string &name, const CRPCCommand *pcmd)
Appends a CRPCCommand to the dispatch table.
Definition: server.cpp:261
Implement this to subscribe to events generated in validation.
bool IsNull() const
Definition: uint256.h:31
RBFTransactionState
Definition: rbf.h:10
CTxMemPoolEntry stores data about the corresponding transaction, as well as data about all in-mempool...
Definition: txmempool.h:67
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:130
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:112
CRPCTable tableRPC
Definition: server.cpp:501
bool CheckFinalTx(const CTransaction &tx, int flags)
Transaction validation functions.
Definition: validation.cpp:192
CCriticalSection cs_main
Mutex to guard access to validation specific variables, such as reading or changing the chainstate...
Definition: validation.cpp:107
CFeeRate minRelayTxFee
A fee rate smaller than this is considered zero fee (for relaying, mining and transaction creation) ...
Definition: validation.cpp:128
Chain & m_chain
Definition: chain.cpp:197
#define LOCK(cs)
Definition: sync.h:182
const char * name
Definition: rest.cpp:39
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
CTransactionRef GetSharedTx() const
Definition: txmempool.h:101
UniqueLock(Mutex &mutexIn, const char *pszName, const char *pszFile, int nLine, bool fTry=false) EXCLUSIVE_LOCK_FUNCTION(mutexIn)
Definition: sync.h:145
static const unsigned int DEFAULT_DESCENDANT_SIZE_LIMIT
Default for -limitdescendantsize, maximum kilobytes of in-mempool descendants.
Definition: validation.h:62
int64_t GetBlockTimeMax() const
Definition: chain.h:280
const CRPCCommand * m_wrapped_command
Definition: chain.cpp:237
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:148
Invalid wallet specified.
Definition: protocol.h:76
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:981
bool IsDeprecatedRPCEnabled(const std::string &method)
Definition: server.cpp:331
int64_t GetMedianTimePast() const
Definition: chain.h:287
CRPCCommand m_command
Definition: chain.cpp:236
void RegisterValidationInterface(CValidationInterface *pwalletIn)
Register a wallet to receive updates from core.
std::atomic_bool fReindex
CBlockIndex * LookupBlockIndex(const uint256 &hash)
Definition: validation.cpp:156
unsigned int HighestTargetTracked(FeeEstimateHorizon horizon) const
Calculation of highest target that estimates are tracked for.
Definition: fees.cpp:676
std::unique_ptr< Chain > MakeChain()
Return implementation of Chain interface.
Definition: chain.cpp:381
256-bit opaque blob.
Definition: uint256.h:121
CChainState & ChainstateActive()
Definition: validation.cpp:87
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:493
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:163
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:863
CBlockIndex * Tip() const
Returns the index entry for the tip of this chain, or nullptr if none.
Definition: chain.h:424
bool IsInitialBlockDownload() const
Check whether we are doing an initial block download (synchronizing from disk or network) ...
ArgsManager gArgs
Definition: system.cpp:73
TransactionError
util/error.h is a common place for definitions of simple error types and string functions.
Definition: error.h:20
Fee rate in satoshis per kilobyte: CAmount / kB.
Definition: feerate.h:19
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
Chain::Notifications * m_notifications
Definition: chain.cpp:198
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
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
auto it
Definition: validation.cpp:366
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:517
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:1078
LockPoints lp
TransactionError BroadcastTransaction(const CTransactionRef tx, std::string &err_string, const CAmount &max_tx_fee, bool relay, bool wait_callback)
Submit a transaction to the mempool and (optionally) relay it to all P2P peers.
Definition: transaction.cpp:17