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, const CBlockIndex* index) override
176  {
177  m_notifications->blockConnected(*block, index->nHeight);
178  }
179  void BlockDisconnected(const std::shared_ptr<const CBlock>& block, const CBlockIndex* index) override
180  {
181  m_notifications->blockDisconnected(*block, index->nHeight);
182  }
183  void UpdatedBlockTip(const CBlockIndex* index, const CBlockIndex* fork_index, bool is_ibd) override
184  {
185  m_notifications->updatedBlockTip();
186  }
187  void ChainStateFlushed(const CBlockLocator& locator) override { m_notifications->chainStateFlushed(locator); }
188  Chain& m_chain;
189  Chain::Notifications* m_notifications;
190 };
191 
192 class RpcHandlerImpl : public Handler
193 {
194 public:
195  explicit RpcHandlerImpl(const CRPCCommand& command) : m_command(command), m_wrapped_command(&command)
196  {
197  m_command.actor = [this](const JSONRPCRequest& request, UniValue& result, bool last_handler) {
198  if (!m_wrapped_command) return false;
199  try {
200  return m_wrapped_command->actor(request, result, last_handler);
201  } catch (const UniValue& e) {
202  // If this is not the last handler and a wallet not found
203  // exception was thrown, return false so the next handler can
204  // try to handle the request. Otherwise, reraise the exception.
205  if (!last_handler) {
206  const UniValue& code = e["code"];
207  if (code.isNum() && code.get_int() == RPC_WALLET_NOT_FOUND) {
208  return false;
209  }
210  }
211  throw;
212  }
213  };
215  }
216 
217  void disconnect() override final
218  {
219  if (m_wrapped_command) {
220  m_wrapped_command = nullptr;
222  }
223  }
224 
225  ~RpcHandlerImpl() override { disconnect(); }
226 
229 };
230 
231 class ChainImpl : public Chain
232 {
233 public:
234  explicit ChainImpl(NodeContext& node) : m_node(node) {}
235  std::unique_ptr<Chain::Lock> lock(bool try_lock) override
236  {
237  auto lock = MakeUnique<LockImpl>(::cs_main, "cs_main", __FILE__, __LINE__, try_lock);
238  if (try_lock && lock && !*lock) return {};
239  std::unique_ptr<Chain::Lock> result = std::move(lock); // Temporary to avoid CWG 1579
240  return result;
241  }
242  bool findBlock(const uint256& hash, CBlock* block, int64_t* time, int64_t* time_max) override
243  {
244  CBlockIndex* index;
245  {
246  LOCK(cs_main);
247  index = LookupBlockIndex(hash);
248  if (!index) {
249  return false;
250  }
251  if (time) {
252  *time = index->GetBlockTime();
253  }
254  if (time_max) {
255  *time_max = index->GetBlockTimeMax();
256  }
257  }
258  if (block && !ReadBlockFromDisk(*block, index, Params().GetConsensus())) {
259  block->SetNull();
260  }
261  return true;
262  }
263  void findCoins(std::map<COutPoint, Coin>& coins) override { return FindCoins(m_node, coins); }
264  double guessVerificationProgress(const uint256& block_hash) override
265  {
266  LOCK(cs_main);
267  return GuessVerificationProgress(Params().TxData(), LookupBlockIndex(block_hash));
268  }
269  RBFTransactionState isRBFOptIn(const CTransaction& tx) override
270  {
271  LOCK(::mempool.cs);
272  return IsRBFOptIn(tx, ::mempool);
273  }
274  bool hasDescendantsInMempool(const uint256& txid) override
275  {
276  LOCK(::mempool.cs);
277  auto it = ::mempool.GetIter(txid);
278  return it && (*it)->GetCountWithDescendants() > 1;
279  }
280  bool broadcastTransaction(const CTransactionRef& tx,
281  const CAmount& max_tx_fee,
282  bool relay,
283  std::string& err_string) 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:873
bool fPruneMode
True if we&#39;re running in -prune mode.
Definition: validation.cpp:115
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:90
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:114
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:271
std::set< txiter, CompareIteratorByHash > setEntries
Definition: txmempool.h:531
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:485
bool appendCommand(const std::string &name, const CRPCCommand *pcmd)
Appends a CRPCCommand to the dispatch table.
Definition: server.cpp:262
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:64
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:128
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:219
std::string name
Definition: server.h:110
CRPCTable tableRPC
Definition: server.cpp:502
bool CheckFinalTx(const CTransaction &tx, int flags)
Transaction validation functions.
Definition: validation.cpp:187
NodeContext struct containing references to chain state and connection state.
Definition: context.h:31
CFeeRate minRelayTxFee
A fee rate smaller than this is considered zero fee (for relaying, mining and transaction creation) ...
Definition: validation.cpp:126
Chain & m_chain
Definition: chain.cpp:188
#define LOCK(cs)
Definition: sync.h:218
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:98
RecursiveMutex cs_main
Mutex to guard access to validation specific variables, such as reading or changing the chainstate...
Definition: validation.cpp:105
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:228
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:992
bool IsDeprecatedRPCEnabled(const std::string &method)
Definition: server.cpp:332
int64_t GetMedianTimePast() const
Definition: chain.h:259
CFeeRate incrementalRelayFee
Definition: settings.cpp:12
CRPCCommand m_command
Definition: chain.cpp:227
void RegisterValidationInterface(CValidationInterface *pwalletIn)
Register a wallet to receive updates from core.
std::atomic_bool fReindex
CBlockIndex * LookupBlockIndex(const uint256 &hash)
Definition: validation.cpp:151
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:16
CChainState & ChainstateActive()
Definition: validation.cpp:85
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:494
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:158
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
UniqueLock()
Definition: sync.h:179
Chain::Notifications * m_notifications
Definition: chain.cpp:189
Wrapper around std::unique_lock style lock for Mutex.
Definition: sync.h:121
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:361
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:520
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:1089
LockPoints lp