Bitcoin Core  0.21.1
P2P Digital Currency
 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Properties Friends Macros Modules
chain.h
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 #ifndef BITCOIN_INTERFACES_CHAIN_H
6 #define BITCOIN_INTERFACES_CHAIN_H
7 
8 #include <optional.h> // For Optional and nullopt
9 #include <primitives/transaction.h> // For CTransactionRef
10 #include <util/settings.h> // For util::SettingsValue
11 
12 #include <functional>
13 #include <memory>
14 #include <stddef.h>
15 #include <stdint.h>
16 #include <string>
17 #include <vector>
18 
19 class ArgsManager;
20 class CBlock;
21 class CFeeRate;
22 class CRPCCommand;
23 class CScheduler;
24 class Coin;
25 class uint256;
26 enum class MemPoolRemovalReason;
27 enum class RBFTransactionState;
28 struct bilingual_str;
29 struct CBlockLocator;
30 struct FeeCalculation;
31 struct NodeContext;
32 
33 namespace interfaces {
34 
35 class Handler;
36 class Wallet;
37 
40 {
41 public:
42  FoundBlock& hash(uint256& hash) { m_hash = &hash; return *this; }
43  FoundBlock& height(int& height) { m_height = &height; return *this; }
44  FoundBlock& time(int64_t& time) { m_time = &time; return *this; }
45  FoundBlock& maxTime(int64_t& max_time) { m_max_time = &max_time; return *this; }
46  FoundBlock& mtpTime(int64_t& mtp_time) { m_mtp_time = &mtp_time; return *this; }
49  FoundBlock& data(CBlock& data) { m_data = &data; return *this; }
50 
51  uint256* m_hash = nullptr;
52  int* m_height = nullptr;
53  int64_t* m_time = nullptr;
54  int64_t* m_max_time = nullptr;
55  int64_t* m_mtp_time = nullptr;
56  CBlock* m_data = nullptr;
57 };
58 
83 class Chain
84 {
85 public:
86  virtual ~Chain() {}
87 
91  virtual Optional<int> getHeight() = 0;
92 
96  virtual Optional<int> getBlockHeight(const uint256& hash) = 0;
97 
99  virtual uint256 getBlockHash(int height) = 0;
100 
103  virtual bool haveBlockOnDisk(int height) = 0;
104 
110  virtual Optional<int> findFirstBlockWithTimeAndHeight(int64_t time, int height, uint256* hash) = 0;
111 
113  virtual CBlockLocator getTipLocator() = 0;
114 
118  virtual Optional<int> findLocatorFork(const CBlockLocator& locator) = 0;
119 
121  virtual bool checkFinalTx(const CTransaction& tx) = 0;
122 
125  virtual bool findBlock(const uint256& hash, const FoundBlock& block={}) = 0;
126 
131  virtual bool findFirstBlockWithTimeAndHeight(int64_t min_time, int min_height, const FoundBlock& block={}) = 0;
132 
136  virtual bool findNextBlock(const uint256& block_hash, int block_height, const FoundBlock& next={}, bool* reorg=nullptr) = 0;
137 
140  virtual bool findAncestorByHeight(const uint256& block_hash, int ancestor_height, const FoundBlock& ancestor_out={}) = 0;
141 
144  virtual bool findAncestorByHash(const uint256& block_hash,
145  const uint256& ancestor_hash,
146  const FoundBlock& ancestor_out={}) = 0;
147 
150  virtual bool findCommonAncestor(const uint256& block_hash1,
151  const uint256& block_hash2,
152  const FoundBlock& ancestor_out={},
153  const FoundBlock& block1_out={},
154  const FoundBlock& block2_out={}) = 0;
155 
159  virtual void findCoins(std::map<COutPoint, Coin>& coins) = 0;
160 
163  virtual double guessVerificationProgress(const uint256& block_hash) = 0;
164 
168  virtual bool hasBlocks(const uint256& block_hash, int min_height = 0, Optional<int> max_height = {}) = 0;
169 
171  virtual RBFTransactionState isRBFOptIn(const CTransaction& tx) = 0;
172 
174  virtual bool hasDescendantsInMempool(const uint256& txid) = 0;
175 
179  virtual bool broadcastTransaction(const CTransactionRef& tx,
180  const CAmount& max_tx_fee,
181  bool relay,
182  std::string& err_string) = 0;
183 
185  virtual void getTransactionAncestry(const uint256& txid, size_t& ancestors, size_t& descendants) = 0;
186 
190  virtual void getPackageLimits(unsigned int& limit_ancestor_count, unsigned int& limit_descendant_count) = 0;
191 
193  virtual bool checkChainLimits(const CTransactionRef& tx) = 0;
194 
196  virtual CFeeRate estimateSmartFee(int num_blocks, bool conservative, FeeCalculation* calc = nullptr) = 0;
197 
199  virtual unsigned int estimateMaxBlocks() = 0;
200 
202  virtual CFeeRate mempoolMinFee() = 0;
203 
205  virtual CFeeRate relayMinFee() = 0;
206 
208  virtual CFeeRate relayIncrementalFee() = 0;
209 
211  virtual CFeeRate relayDustFee() = 0;
212 
214  virtual bool havePruned() = 0;
215 
217  virtual bool isReadyToBroadcast() = 0;
218 
220  virtual bool isInitialBlockDownload() = 0;
221 
223  virtual bool shutdownRequested() = 0;
224 
226  virtual int64_t getAdjustedTime() = 0;
227 
229  virtual void initMessage(const std::string& message) = 0;
230 
232  virtual void initWarning(const bilingual_str& message) = 0;
233 
235  virtual void initError(const bilingual_str& message) = 0;
236 
238  virtual void showProgress(const std::string& title, int progress, bool resume_possible) = 0;
239 
242  {
243  public:
244  virtual ~Notifications() {}
245  virtual void transactionAddedToMempool(const CTransactionRef& tx, uint64_t mempool_sequence) {}
246  virtual void transactionRemovedFromMempool(const CTransactionRef& tx, MemPoolRemovalReason reason, uint64_t mempool_sequence) {}
247  virtual void blockConnected(const CBlock& block, int height) {}
248  virtual void blockDisconnected(const CBlock& block, int height) {}
249  virtual void updatedBlockTip() {}
250  virtual void chainStateFlushed(const CBlockLocator& locator) {}
251  };
252 
254  virtual std::unique_ptr<Handler> handleNotifications(std::shared_ptr<Notifications> notifications) = 0;
255 
258  virtual void waitForNotificationsIfTipChanged(const uint256& old_tip) = 0;
259 
262  virtual std::unique_ptr<Handler> handleRpc(const CRPCCommand& command) = 0;
263 
265  virtual bool rpcEnableDeprecated(const std::string& method) = 0;
266 
268  virtual void rpcRunLater(const std::string& name, std::function<void()> fn, int64_t seconds) = 0;
269 
271  virtual int rpcSerializationFlags() = 0;
272 
274  virtual util::SettingsValue getRwSetting(const std::string& name) = 0;
275 
277  virtual bool updateRwSetting(const std::string& name, const util::SettingsValue& value) = 0;
278 
287  virtual void requestMempoolTransactions(Notifications& notifications) = 0;
288 };
289 
293 {
294 public:
295  virtual ~ChainClient() {}
296 
298  virtual void registerRpcs() = 0;
299 
301  virtual bool verify() = 0;
302 
304  virtual bool load() = 0;
305 
307  virtual void start(CScheduler& scheduler) = 0;
308 
310  virtual void flush() = 0;
311 
313  virtual void stop() = 0;
314 
316  virtual void setMockTime(int64_t time) = 0;
317 };
318 
320 std::unique_ptr<Chain> MakeChain(NodeContext& node);
321 
322 } // namespace interfaces
323 
324 #endif // BITCOIN_INTERFACES_CHAIN_H
std::shared_ptr< const CTransaction > CTransactionRef
Definition: transaction.h:395
virtual bool haveBlockOnDisk(int height)=0
Check that the block is available on disk (i.e.
Helper for findBlock to selectively return pieces of block data.
Definition: chain.h:39
virtual bool findCommonAncestor(const uint256 &block_hash1, const uint256 &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.
virtual Optional< int > getHeight()=0
Get current chain height, not including genesis block (returns 0 if chain only contains genesis block...
virtual void findCoins(std::map< COutPoint, Coin > &coins)=0
Look up unspent output information.
virtual void getPackageLimits(unsigned int &limit_ancestor_count, unsigned int &limit_descendant_count)=0
Get the node's package limits.
virtual int rpcSerializationFlags()=0
Current RPC serialization flags.
virtual bool updateRwSetting(const std::string &name, const util::SettingsValue &value)=0
Write a setting to /settings.json.
virtual void transactionRemovedFromMempool(const CTransactionRef &tx, MemPoolRemovalReason reason, uint64_t mempool_sequence)
Definition: chain.h:246
Describes a place in the block chain to another node such that if the other node doesn't have the sam...
Definition: block.h:114
virtual 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...
virtual std::unique_ptr< Handler > handleNotifications(std::shared_ptr< Notifications > notifications)=0
Register handler for notifications.
virtual void registerRpcs()=0
Register rpcs.
A UTXO entry.
Definition: coins.h:30
Bilingual messages:
Definition: translation.h:16
Definition: block.h:62
virtual uint256 getBlockHash(int height)=0
Get block hash. Height must be valid or this function will abort.
virtual CFeeRate mempoolMinFee()=0
Mempool minimum fee.
virtual void rpcRunLater(const std::string &name, std::function< void()> fn, int64_t seconds)=0
Run function after given number of seconds. Cancel any previous calls with same name.
int64_t * m_max_time
Definition: chain.h:54
virtual Optional< int > findFirstBlockWithTimeAndHeight(int64_t time, int height, uint256 *hash)=0
Return height of the first block in the chain with timestamp equal or greater than the given time and...
virtual CFeeRate relayDustFee()=0
Relay dust fee setting (-dustrelayfee), reflecting lowest rate it's economical to spend...
virtual int64_t getAdjustedTime()=0
Get adjusted time.
virtual bool isInitialBlockDownload()=0
Check if in IBD.
virtual void transactionAddedToMempool(const CTransactionRef &tx, uint64_t mempool_sequence)
Definition: chain.h:245
virtual void stop()=0
Shut down client.
virtual void updatedBlockTip()
Definition: chain.h:249
MemPoolRemovalReason
Reason why a transaction was removed from the mempool, this is passed to the notification signal...
Definition: txmempool.h:392
virtual double guessVerificationProgress(const uint256 &block_hash)=0
Estimate fraction of total transactions verified if blocks up to the specified block hash are verifie...
virtual bool load()=0
Load saved state.
int64_t * m_mtp_time
Definition: chain.h:55
virtual bool checkFinalTx(const CTransaction &tx)=0
Check if transaction will be final given chain height current time.
std::unique_ptr< Chain > MakeChain(NodeContext &node)
Return implementation of Chain interface.
Definition: chain.cpp:415
RBFTransactionState
The rbf state of unconfirmed transactions.
Definition: rbf.h:11
uint256 * m_hash
Definition: chain.h:51
int64_t CAmount
Amount in satoshis (Can be negative)
Definition: amount.h:12
FoundBlock & data(CBlock &data)
Read block data from disk.
Definition: chain.h:49
virtual bool hasDescendantsInMempool(const uint256 &txid)=0
Check if transaction has descendants in mempool.
virtual bool hasBlocks(const uint256 &block_hash, int min_height=0, Optional< int > max_height={})=0
Return true if data is available for all blocks in the specified range of blocks. ...
virtual void blockDisconnected(const CBlock &block, int height)
Definition: chain.h:248
virtual void blockConnected(const CBlock &block, int height)
Definition: chain.h:247
virtual void setMockTime(int64_t time)=0
Set mock time.
NodeContext struct containing references to chain state and connection state.
Definition: context.h:36
virtual ~Chain()
Definition: chain.h:86
virtual bool findAncestorByHeight(const uint256 &block_hash, int ancestor_height, const FoundBlock &ancestor_out={})=0
Find ancestor of block at specified height and optionally return ancestor information.
virtual CFeeRate estimateSmartFee(int num_blocks, bool conservative, FeeCalculation *calc=nullptr)=0
Estimate smart fee.
CBlock * m_data
Definition: chain.h:56
const char * name
Definition: rest.cpp:41
Chain notifications.
Definition: chain.h:241
FoundBlock & maxTime(int64_t &max_time)
Definition: chain.h:45
virtual std::unique_ptr< Handler > handleRpc(const CRPCCommand &command)=0
Register handler for RPC.
virtual ~ChainClient()
Definition: chain.h:295
virtual void start(CScheduler &scheduler)=0
Start client execution and provide a scheduler.
virtual bool findBlock(const uint256 &hash, const FoundBlock &block={})=0
Return whether node has the block and optionally return block metadata or contents.
virtual void waitForNotificationsIfTipChanged(const uint256 &old_tip)=0
Wait for pending notifications to be processed unless block hash points to the current chain tip...
virtual void requestMempoolTransactions(Notifications &notifications)=0
Synchronously send transactionAddedToMempool notifications about all current mempool transactions to ...
virtual void flush()=0
Save state to disk.
virtual void getTransactionAncestry(const uint256 &txid, size_t &ancestors, size_t &descendants)=0
Calculate mempool ancestor and descendant counts for the given transaction.
virtual bool verify()=0
Check for errors before loading.
virtual void initWarning(const bilingual_str &message)=0
Send init warning.
256-bit opaque blob.
Definition: uint256.h:124
virtual bool isReadyToBroadcast()=0
Check if the node is ready to broadcast transactions.
virtual bool checkChainLimits(const CTransactionRef &tx)=0
Check if transaction will pass the mempool's chain limits.
virtual util::SettingsValue getRwSetting(const std::string &name)=0
Return /settings.json setting value.
virtual bool findAncestorByHash(const uint256 &block_hash, const uint256 &ancestor_hash, const FoundBlock &ancestor_out={})=0
Return whether block descends from a specified ancestor, and optionally return ancestor information...
Interface to let node manage chain clients (wallets, or maybe tools for monitoring and analysis in th...
Definition: chain.h:292
Interface giving clients (wallet processes, maybe other analysis tools in the future) ability to acce...
Definition: chain.h:83
virtual void chainStateFlushed(const CBlockLocator &locator)
Definition: chain.h:250
int64_t * m_time
Definition: chain.h:53
virtual void initMessage(const std::string &message)=0
Send init message.
Fee rate in satoshis per kilobyte: CAmount / kB.
Definition: feerate.h:29
FoundBlock & hash(uint256 &hash)
Definition: chain.h:42
virtual RBFTransactionState isRBFOptIn(const CTransaction &tx)=0
Check if transaction is RBF opt in.
virtual void showProgress(const std::string &title, int progress, bool resume_possible)=0
Send progress indicator.
virtual Optional< int > getBlockHeight(const uint256 &hash)=0
Get block height above genesis block.
virtual unsigned int estimateMaxBlocks()=0
Fee estimator max target.
virtual bool shutdownRequested()=0
Check if shutdown requested.
FoundBlock & height(int &height)
Definition: chain.h:43
virtual bool broadcastTransaction(const CTransactionRef &tx, const CAmount &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...
The basic transaction that is broadcasted on the network and contained in blocks. ...
Definition: transaction.h:259
FoundBlock & mtpTime(int64_t &mtp_time)
Definition: chain.h:46
boost::optional< T > Optional
Substitute for C++17 std::optional.
Definition: optional.h:14
Simple class for background tasks that should be run periodically or once "after a while"...
Definition: scheduler.h:32
virtual CBlockLocator getTipLocator()=0
Get locator for the current chain tip.
virtual bool rpcEnableDeprecated(const std::string &method)=0
Check if deprecated RPC is enabled.
virtual void initError(const bilingual_str &message)=0
Send init error.
virtual CFeeRate relayIncrementalFee()=0
Relay incremental fee setting (-incrementalrelayfee), reflecting cost of relay.
virtual CFeeRate relayMinFee()=0
Relay current minimum fee (from -minrelaytxfee and -incrementalrelayfee settings).
virtual bool findNextBlock(const uint256 &block_hash, int block_height, const FoundBlock &next={}, bool *reorg=nullptr)=0
Find next block if block is part of current chain.
FoundBlock & time(int64_t &time)
Definition: chain.h:44
virtual bool havePruned()=0
Check if any block has been pruned.