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