Bitcoin ABC  0.24.11
P2P Digital Currency
chain.h
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 #ifndef BITCOIN_INTERFACES_CHAIN_H
6 #define BITCOIN_INTERFACES_CHAIN_H
7 
9 #include <primitives/txid.h>
10 #include <util/settings.h> // For util::SettingsValue
11 
12 #include <cstddef>
13 #include <cstdint>
14 #include <functional>
15 #include <memory>
16 #include <optional>
17 #include <string>
18 #include <vector>
19 
20 class ArgsManager;
21 class CBlock;
22 class CChainParams;
23 class Coin;
24 class Config;
25 class CRPCCommand;
26 class CScheduler;
27 class TxValidationState;
28 
29 enum class MemPoolRemovalReason;
30 
31 struct BlockHash;
32 struct bilingual_str;
33 struct CBlockLocator;
34 struct NodeContext;
35 
36 namespace Consensus {
37 struct Params;
38 }
39 
40 namespace interfaces {
41 
42 class Handler;
43 class Wallet;
44 
46 class FoundBlock {
47 public:
49  m_hash = &hash;
50  return *this;
51  }
53  m_height = &height;
54  return *this;
55  }
56  FoundBlock &time(int64_t &time) {
57  m_time = &time;
58  return *this;
59  }
60  FoundBlock &maxTime(int64_t &max_time) {
61  m_max_time = &max_time;
62  return *this;
63  }
64  FoundBlock &mtpTime(int64_t &mtp_time) {
65  m_mtp_time = &mtp_time;
66  return *this;
67  }
71  m_data = &data;
72  return *this;
73  }
74 
75  BlockHash *m_hash = nullptr;
76  int *m_height = nullptr;
77  int64_t *m_time = nullptr;
78  int64_t *m_max_time = nullptr;
79  int64_t *m_mtp_time = nullptr;
80  CBlock *m_data = nullptr;
81 };
82 
108 class Chain {
109 public:
110  virtual ~Chain() {}
111 
115  virtual std::optional<int> getHeight() = 0;
116 
120  virtual std::optional<int> getBlockHeight(const BlockHash &hash) = 0;
121 
123  virtual BlockHash getBlockHash(int height) = 0;
124 
127  virtual bool haveBlockOnDisk(int height) = 0;
128 
135  virtual std::optional<int>
136  findFirstBlockWithTimeAndHeight(int64_t time, int height,
137  BlockHash *hash) = 0;
138 
140  virtual CBlockLocator getTipLocator() = 0;
141 
145  virtual std::optional<int>
146  findLocatorFork(const CBlockLocator &locator) = 0;
147 
149  virtual bool
151  TxValidationState &state) = 0;
152 
155  virtual bool findBlock(const BlockHash &hash,
156  const FoundBlock &block = {}) = 0;
157 
162  virtual bool
163  findFirstBlockWithTimeAndHeight(int64_t min_time, int min_height,
164  const FoundBlock &block = {}) = 0;
165 
169  virtual bool findNextBlock(const BlockHash &block_hash, int block_height,
170  const FoundBlock &next = {},
171  bool *reorg = nullptr) = 0;
172 
175  virtual bool findAncestorByHeight(const BlockHash &block_hash,
176  int ancestor_height,
177  const FoundBlock &ancestor_out = {}) = 0;
178 
181  virtual bool findAncestorByHash(const BlockHash &block_hash,
182  const BlockHash &ancestor_hash,
183  const FoundBlock &ancestor_out = {}) = 0;
184 
187  virtual bool findCommonAncestor(const BlockHash &block_hash1,
188  const BlockHash &block_hash2,
189  const FoundBlock &ancestor_out = {},
190  const FoundBlock &block1_out = {},
191  const FoundBlock &block2_out = {}) = 0;
192 
196  virtual void findCoins(std::map<COutPoint, Coin> &coins) = 0;
197 
200  virtual double guessVerificationProgress(const BlockHash &block_hash) = 0;
201 
205  virtual bool hasBlocks(const BlockHash &block_hash, int min_height = 0,
206  std::optional<int> max_height = {}) = 0;
207 
209  virtual bool hasDescendantsInMempool(const TxId &txid) = 0;
210 
215  virtual bool broadcastTransaction(const Config &config,
216  const CTransactionRef &tx,
217  const Amount &max_tx_fee, bool relay,
218  std::string &err_string) = 0;
219 
222  virtual void getTransactionAncestry(const TxId &txid, size_t &ancestors,
223  size_t &descendants) = 0;
224 
228  virtual void getPackageLimits(size_t &limit_ancestor_count,
229  size_t &limit_descendant_count) = 0;
230 
232  virtual bool checkChainLimits(const CTransactionRef &tx) = 0;
233 
235  virtual CFeeRate estimateFee() const = 0;
236 
238  virtual CFeeRate relayMinFee() = 0;
239 
242  virtual CFeeRate relayDustFee() = 0;
243 
245  virtual bool havePruned() = 0;
246 
248  virtual bool isReadyToBroadcast() = 0;
249 
251  virtual bool isInitialBlockDownload() = 0;
252 
254  virtual bool shutdownRequested() = 0;
255 
257  virtual int64_t getAdjustedTime() = 0;
258 
260  virtual void initMessage(const std::string &message) = 0;
261 
263  virtual void initWarning(const bilingual_str &message) = 0;
264 
266  virtual void initError(const bilingual_str &message) = 0;
267 
269  virtual void showProgress(const std::string &title, int progress,
270  bool resume_possible) = 0;
271 
274  public:
275  virtual ~Notifications() {}
277  uint64_t mempool_sequence) {}
279  MemPoolRemovalReason reason,
280  uint64_t mempool_sequence) {}
281  virtual void blockConnected(const CBlock &block, int height) {}
282  virtual void blockDisconnected(const CBlock &block, int height) {}
283  virtual void updatedBlockTip() {}
284  virtual void chainStateFlushed(const CBlockLocator &locator) {}
285  };
286 
288  virtual std::unique_ptr<Handler>
289  handleNotifications(std::shared_ptr<Notifications> notifications) = 0;
290 
293  virtual void waitForNotificationsIfTipChanged(const BlockHash &old_tip) = 0;
294 
297  virtual std::unique_ptr<Handler> handleRpc(const CRPCCommand &command) = 0;
298 
300  virtual bool rpcEnableDeprecated(const std::string &method) = 0;
301 
304  virtual void rpcRunLater(const std::string &name, std::function<void()> fn,
305  int64_t seconds) = 0;
306 
308  virtual int rpcSerializationFlags() = 0;
309 
311  virtual util::SettingsValue getRwSetting(const std::string &name) = 0;
312 
314  virtual bool updateRwSetting(const std::string &name,
315  const util::SettingsValue &value) = 0;
316 
325  virtual void requestMempoolTransactions(Notifications &notifications) = 0;
326 
328  virtual const CChainParams &params() const = 0;
329 };
330 
333 class ChainClient {
334 public:
335  virtual ~ChainClient() {}
336 
338  virtual void registerRpcs() = 0;
339 
341  virtual bool verify() = 0;
342 
344  virtual bool load() = 0;
345 
347  virtual void start(CScheduler &scheduler) = 0;
348 
350  virtual void flush() = 0;
351 
353  virtual void stop() = 0;
354 
356  virtual void setMockTime(int64_t time) = 0;
357 };
358 
360 std::unique_ptr<Chain> MakeChain(NodeContext &node, const CChainParams &params);
361 
362 } // namespace interfaces
363 
364 #endif // BITCOIN_INTERFACES_CHAIN_H
interfaces
Definition: dummywallet.cpp:12
interfaces::ChainClient::registerRpcs
virtual void registerRpcs()=0
Register rpcs.
CScheduler
Simple class for background tasks that should be run periodically or once "after a while".
Definition: scheduler.h:35
interfaces::Chain::updateRwSetting
virtual bool updateRwSetting(const std::string &name, const util::SettingsValue &value)=0
Write a setting to <datadir>/settings.json.
interfaces::Chain::hasBlocks
virtual bool hasBlocks(const BlockHash &block_hash, int min_height=0, std::optional< int > max_height={})=0
Return true if data is available for all blocks in the specified range of blocks.
interfaces::Chain::rpcSerializationFlags
virtual int rpcSerializationFlags()=0
Current RPC serialization flags.
interfaces::FoundBlock::data
FoundBlock & data(CBlock &data)
Read block data from disk.
Definition: chain.h:70
interfaces::Chain::Notifications::~Notifications
virtual ~Notifications()
Definition: chain.h:275
interfaces::Chain::findAncestorByHash
virtual bool findAncestorByHash(const BlockHash &block_hash, const BlockHash &ancestor_hash, const FoundBlock &ancestor_out={})=0
Return whether block descends from a specified ancestor, and optionally return ancestor information.
interfaces::FoundBlock::m_data
CBlock * m_data
Definition: chain.h:80
interfaces::Chain::findCoins
virtual void findCoins(std::map< COutPoint, Coin > &coins)=0
Look up unspent output information.
interfaces::Chain::findNextBlock
virtual bool findNextBlock(const BlockHash &block_hash, int block_height, const FoundBlock &next={}, bool *reorg=nullptr)=0
Find next block if block is part of current chain.
interfaces::FoundBlock::mtpTime
FoundBlock & mtpTime(int64_t &mtp_time)
Definition: chain.h:64
transaction.h
bilingual_str
Bilingual messages:
Definition: translation.h:17
interfaces::Chain::isInitialBlockDownload
virtual bool isInitialBlockDownload()=0
Check if in IBD.
interfaces::Chain::Notifications::chainStateFlushed
virtual void chainStateFlushed(const CBlockLocator &locator)
Definition: chain.h:284
interfaces::Chain::~Chain
virtual ~Chain()
Definition: chain.h:110
interfaces::Chain::hasDescendantsInMempool
virtual bool hasDescendantsInMempool(const TxId &txid)=0
Check if transaction has descendants in mempool.
CChainParams
CChainParams defines various tweakable parameters of a given instance of the Bitcoin system.
Definition: chainparams.h:47
interfaces::Chain::handleNotifications
virtual std::unique_ptr< Handler > handleNotifications(std::shared_ptr< Notifications > notifications)=0
Register handler for notifications.
interfaces::Chain::findFirstBlockWithTimeAndHeight
virtual std::optional< int > findFirstBlockWithTimeAndHeight(int64_t time, int height, BlockHash *hash)=0
Return height of the first block in the chain with timestamp equal or greater than the given time and...
interfaces::ChainClient::flush
virtual void flush()=0
Save state to disk.
interfaces::Chain::getHeight
virtual std::optional< int > getHeight()=0
Get current chain height, not including genesis block (returns 0 if chain only contains genesis block...
interfaces::Chain::getBlockHash
virtual BlockHash getBlockHash(int height)=0
Get block hash. Height must be valid or this function will abort.
interfaces::FoundBlock::hash
FoundBlock & hash(BlockHash &hash)
Definition: chain.h:48
interfaces::ChainClient::start
virtual void start(CScheduler &scheduler)=0
Start client execution and provide a scheduler.
interfaces::Chain::guessVerificationProgress
virtual double guessVerificationProgress(const BlockHash &block_hash)=0
Estimate fraction of total transactions verified if blocks up to the specified block hash are verifie...
interfaces::Chain::getRwSetting
virtual util::SettingsValue getRwSetting(const std::string &name)=0
Return <datadir>/settings.json setting value.
CFeeRate
Fee rate in satoshis per kilobyte: Amount / kB.
Definition: feerate.h:21
interfaces::FoundBlock::time
FoundBlock & time(int64_t &time)
Definition: chain.h:56
UniValue
Definition: univalue.h:23
CTransaction
The basic transaction that is broadcasted on the network and contained in blocks.
Definition: transaction.h:194
interfaces::ChainClient::~ChainClient
virtual ~ChainClient()
Definition: chain.h:335
TxValidationState
Definition: validation.h:137
Config
Definition: config.h:17
interfaces::Chain::isReadyToBroadcast
virtual bool isReadyToBroadcast()=0
Check if the node is ready to broadcast transactions.
interfaces::Chain::havePruned
virtual bool havePruned()=0
Check if any block has been pruned.
interfaces::Chain
Interface giving clients (wallet processes, maybe other analysis tools in the future) ability to acce...
Definition: chain.h:108
interfaces::Chain::Notifications::updatedBlockTip
virtual void updatedBlockTip()
Definition: chain.h:283
settings.h
interfaces::FoundBlock::m_time
int64_t * m_time
Definition: chain.h:77
interfaces::ChainClient::load
virtual bool load()=0
Load saved state.
Consensus
Definition: blockdb.h:10
CRPCCommand
Definition: server.h:147
Coin
A UTXO entry.
Definition: coins.h:27
interfaces::FoundBlock::maxTime
FoundBlock & maxTime(int64_t &max_time)
Definition: chain.h:60
interfaces::Chain::params
virtual const CChainParams & params() const =0
This Chain's parameters.
interfaces::Chain::Notifications::blockDisconnected
virtual void blockDisconnected(const CBlock &block, int height)
Definition: chain.h:282
interfaces::Chain::findLocatorFork
virtual std::optional< int > findLocatorFork(const CBlockLocator &locator)=0
Return height of the highest block on chain in common with the locator, which will either be the orig...
interfaces::Chain::broadcastTransaction
virtual bool broadcastTransaction(const Config &config, const CTransactionRef &tx, const Amount &max_tx_fee, bool relay, std::string &err_string)=0
Transaction is added to memory pool, if the transaction fee is below the amount specified by max_tx_f...
interfaces::Chain::relayMinFee
virtual CFeeRate relayMinFee()=0
Relay current minimum fee (from -minrelaytxfee settings).
interfaces::Chain::shutdownRequested
virtual bool shutdownRequested()=0
Check if shutdown requested.
interfaces::FoundBlock
Helper for findBlock to selectively return pieces of block data.
Definition: chain.h:46
interfaces::Chain::rpcRunLater
virtual void rpcRunLater(const std::string &name, std::function< void()> fn, int64_t seconds)=0
Run function after given number of seconds.
TxId
A TxId is the identifier of a transaction.
Definition: txid.h:14
interfaces::Chain::getAdjustedTime
virtual int64_t getAdjustedTime()=0
Get adjusted time.
Amount
Definition: amount.h:19
interfaces::Chain::Notifications::transactionRemovedFromMempool
virtual void transactionRemovedFromMempool(const CTransactionRef &ptx, MemPoolRemovalReason reason, uint64_t mempool_sequence)
Definition: chain.h:278
interfaces::FoundBlock::m_hash
BlockHash * m_hash
Definition: chain.h:75
BlockHash
A BlockHash is a unqiue identifier for a block.
Definition: blockhash.h:13
interfaces::Chain::rpcEnableDeprecated
virtual bool rpcEnableDeprecated(const std::string &method)=0
Check if deprecated RPC is enabled.
interfaces::Chain::Notifications::transactionAddedToMempool
virtual void transactionAddedToMempool(const CTransactionRef &tx, uint64_t mempool_sequence)
Definition: chain.h:276
name
const char * name
Definition: rest.cpp:43
interfaces::FoundBlock::height
FoundBlock & height(int &height)
Definition: chain.h:52
interfaces::Chain::initWarning
virtual void initWarning(const bilingual_str &message)=0
Send init warning.
CBlock
Definition: block.h:55
interfaces::Chain::waitForNotificationsIfTipChanged
virtual void waitForNotificationsIfTipChanged(const BlockHash &old_tip)=0
Wait for pending notifications to be processed unless block hash points to the current chain tip.
interfaces::Chain::getTransactionAncestry
virtual void getTransactionAncestry(const TxId &txid, size_t &ancestors, size_t &descendants)=0
Calculate mempool ancestor and descendant counts for the given transaction.
interfaces::Chain::estimateFee
virtual CFeeRate estimateFee() const =0
Estimate fee.
interfaces::ChainClient
Interface to let node manage chain clients (wallets, or maybe tools for monitoring and analysis in th...
Definition: chain.h:333
ArgsManager
Definition: system.h:148
MemPoolRemovalReason
MemPoolRemovalReason
Reason why a transaction was removed from the mempool, this is passed to the notification signal.
Definition: txmempool.h:400
interfaces::Chain::Notifications
Chain notifications.
Definition: chain.h:273
interfaces::FoundBlock::m_max_time
int64_t * m_max_time
Definition: chain.h:78
interfaces::Chain::relayDustFee
virtual CFeeRate relayDustFee()=0
Relay dust fee setting (-dustrelayfee), reflecting lowest rate it's economical to spend.
interfaces::FoundBlock::m_mtp_time
int64_t * m_mtp_time
Definition: chain.h:79
interfaces::Chain::initMessage
virtual void initMessage(const std::string &message)=0
Send init message.
interfaces::ChainClient::stop
virtual void stop()=0
Shut down client.
interfaces::Chain::contextualCheckTransactionForCurrentBlock
virtual bool contextualCheckTransactionForCurrentBlock(const CTransaction &tx, TxValidationState &state)=0
Check if transaction will be final given chain height current time.
interfaces::Chain::checkChainLimits
virtual bool checkChainLimits(const CTransactionRef &tx)=0
Check if transaction will pass the mempool's chain limits.
interfaces::ChainClient::verify
virtual bool verify()=0
Check for errors before loading.
Params
const CChainParams & Params()
Return the currently selected parameters.
Definition: chainparams.cpp:508
CTransactionRef
std::shared_ptr< const CTransaction > CTransactionRef
Definition: transaction.h:319
interfaces::MakeChain
std::unique_ptr< Chain > MakeChain(NodeContext &node, const CChainParams &params)
Return implementation of Chain interface.
Definition: chain.cpp:492
interfaces::Chain::haveBlockOnDisk
virtual bool haveBlockOnDisk(int height)=0
Check that the block is available on disk (i.e.
interfaces::Chain::initError
virtual void initError(const bilingual_str &message)=0
Send init error.
txid.h
interfaces::Chain::getTipLocator
virtual CBlockLocator getTipLocator()=0
Get locator for the current chain tip.
interfaces::Chain::requestMempoolTransactions
virtual void requestMempoolTransactions(Notifications &notifications)=0
Synchronously send transactionAddedToMempool notifications about all current mempool transactions to ...
CBlockLocator
Describes a place in the block chain to another node such that if the other node doesn't have the sam...
Definition: block.h:100
NodeContext
NodeContext struct containing references to chain state and connection state.
Definition: context.h:36
interfaces::Chain::findCommonAncestor
virtual bool findCommonAncestor(const BlockHash &block_hash1, const BlockHash &block_hash2, const FoundBlock &ancestor_out={}, const FoundBlock &block1_out={}, const FoundBlock &block2_out={})=0
Find most recent common ancestor between two blocks and optionally return block information.
interfaces::Chain::getBlockHeight
virtual std::optional< int > getBlockHeight(const BlockHash &hash)=0
Get block height above genesis block.
interfaces::Chain::showProgress
virtual void showProgress(const std::string &title, int progress, bool resume_possible)=0
Send progress indicator.
interfaces::Chain::findAncestorByHeight
virtual bool findAncestorByHeight(const BlockHash &block_hash, int ancestor_height, const FoundBlock &ancestor_out={})=0
Find ancestor of block at specified height and optionally return ancestor information.
interfaces::Chain::findBlock
virtual bool findBlock(const BlockHash &hash, const FoundBlock &block={})=0
Return whether node has the block and optionally return block metadata or contents.
interfaces::Chain::handleRpc
virtual std::unique_ptr< Handler > handleRpc(const CRPCCommand &command)=0
Register handler for RPC.
interfaces::Chain::getPackageLimits
virtual void getPackageLimits(size_t &limit_ancestor_count, size_t &limit_descendant_count)=0
Get the node's package limits.
interfaces::ChainClient::setMockTime
virtual void setMockTime(int64_t time)=0
Set mock time.
interfaces::Chain::Notifications::blockConnected
virtual void blockConnected(const CBlock &block, int height)
Definition: chain.h:281
interfaces::FoundBlock::m_height
int * m_height
Definition: chain.h:76