Bitcoin Core  25.99.0
P2P Digital Currency
chain.h
Go to the documentation of this file.
1 // Copyright (c) 2018-2022 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 <blockfilter.h>
9 #include <primitives/transaction.h> // For CTransactionRef
10 #include <util/settings.h> // For util::SettingsValue
11 
12 #include <functional>
13 #include <memory>
14 #include <optional>
15 #include <stddef.h>
16 #include <stdint.h>
17 #include <string>
18 #include <vector>
19 
20 class ArgsManager;
21 class CBlock;
22 class CBlockUndo;
23 class CFeeRate;
24 class CRPCCommand;
25 class CScheduler;
26 class Coin;
27 class uint256;
28 enum class MemPoolRemovalReason;
29 enum class RBFTransactionState;
30 struct bilingual_str;
31 struct CBlockLocator;
32 struct FeeCalculation;
33 namespace node {
34 struct NodeContext;
35 } // namespace node
36 
37 namespace interfaces {
38 
39 class Handler;
40 class Wallet;
41 
43 struct BlockKey {
45  int height = -1;
46 };
47 
52 {
53 public:
54  FoundBlock& hash(uint256& hash) { m_hash = &hash; return *this; }
55  FoundBlock& height(int& height) { m_height = &height; return *this; }
56  FoundBlock& time(int64_t& time) { m_time = &time; return *this; }
57  FoundBlock& maxTime(int64_t& max_time) { m_max_time = &max_time; return *this; }
58  FoundBlock& mtpTime(int64_t& mtp_time) { m_mtp_time = &mtp_time; return *this; }
60  FoundBlock& inActiveChain(bool& in_active_chain) { m_in_active_chain = &in_active_chain; return *this; }
64  FoundBlock& nextBlock(const FoundBlock& next_block) { m_next_block = &next_block; return *this; }
67  FoundBlock& data(CBlock& data) { m_data = &data; return *this; }
68 
69  uint256* m_hash = nullptr;
70  int* m_height = nullptr;
71  int64_t* m_time = nullptr;
72  int64_t* m_max_time = nullptr;
73  int64_t* m_mtp_time = nullptr;
74  bool* m_in_active_chain = nullptr;
76  const FoundBlock* m_next_block = nullptr;
77  CBlock* m_data = nullptr;
78  mutable bool found = false;
79 };
80 
82 struct BlockInfo {
83  const uint256& hash;
84  const uint256* prev_hash = nullptr;
85  int height = -1;
86  int file_number = -1;
87  unsigned data_pos = 0;
88  const CBlock* data = nullptr;
89  const CBlockUndo* undo_data = nullptr;
90  // The maximum time in the chain up to and including this block.
91  // A timestamp that can only move forward.
92  unsigned int chain_time_max{0};
93 
95 };
96 
121 class Chain
122 {
123 public:
124  virtual ~Chain() {}
125 
129  virtual std::optional<int> getHeight() = 0;
130 
132  virtual uint256 getBlockHash(int height) = 0;
133 
136  virtual bool haveBlockOnDisk(int height) = 0;
137 
140 
143  virtual CBlockLocator getActiveChainLocator(const uint256& block_hash) = 0;
144 
148  virtual std::optional<int> findLocatorFork(const CBlockLocator& locator) = 0;
149 
151  virtual bool hasBlockFilterIndex(BlockFilterType filter_type) = 0;
152 
155  virtual std::optional<bool> blockFilterMatchesAny(BlockFilterType filter_type, const uint256& block_hash, const GCSFilter::ElementSet& filter_set) = 0;
156 
159  virtual bool findBlock(const uint256& hash, const FoundBlock& block={}) = 0;
160 
165  virtual bool findFirstBlockWithTimeAndHeight(int64_t min_time, int min_height, const FoundBlock& block={}) = 0;
166 
169  virtual bool findAncestorByHeight(const uint256& block_hash, int ancestor_height, const FoundBlock& ancestor_out={}) = 0;
170 
173  virtual bool findAncestorByHash(const uint256& block_hash,
174  const uint256& ancestor_hash,
175  const FoundBlock& ancestor_out={}) = 0;
176 
179  virtual bool findCommonAncestor(const uint256& block_hash1,
180  const uint256& block_hash2,
181  const FoundBlock& ancestor_out={},
182  const FoundBlock& block1_out={},
183  const FoundBlock& block2_out={}) = 0;
184 
188  virtual void findCoins(std::map<COutPoint, Coin>& coins) = 0;
189 
192  virtual double guessVerificationProgress(const uint256& block_hash) = 0;
193 
197  virtual bool hasBlocks(const uint256& block_hash, int min_height = 0, std::optional<int> max_height = {}) = 0;
198 
201 
203  virtual bool isInMempool(const uint256& txid) = 0;
204 
206  virtual bool hasDescendantsInMempool(const uint256& txid) = 0;
207 
211  virtual bool broadcastTransaction(const CTransactionRef& tx,
212  const CAmount& max_tx_fee,
213  bool relay,
214  std::string& err_string) = 0;
215 
217  virtual void getTransactionAncestry(const uint256& txid, size_t& ancestors, size_t& descendants, size_t* ancestorsize = nullptr, CAmount* ancestorfees = nullptr) = 0;
218 
222  virtual void getPackageLimits(unsigned int& limit_ancestor_count, unsigned int& limit_descendant_count) = 0;
223 
225  virtual bool checkChainLimits(const CTransactionRef& tx) = 0;
226 
228  virtual CFeeRate estimateSmartFee(int num_blocks, bool conservative, FeeCalculation* calc = nullptr) = 0;
229 
231  virtual unsigned int estimateMaxBlocks() = 0;
232 
234  virtual CFeeRate mempoolMinFee() = 0;
235 
237  virtual CFeeRate relayMinFee() = 0;
238 
241 
243  virtual CFeeRate relayDustFee() = 0;
244 
246  virtual bool havePruned() = 0;
247 
249  virtual bool isReadyToBroadcast() = 0;
250 
252  virtual bool isInitialBlockDownload() = 0;
253 
255  virtual bool shutdownRequested() = 0;
256 
258  virtual void initMessage(const std::string& message) = 0;
259 
261  virtual void initWarning(const bilingual_str& message) = 0;
262 
264  virtual void initError(const bilingual_str& message) = 0;
265 
267  virtual void showProgress(const std::string& title, int progress, bool resume_possible) = 0;
268 
271  {
272  public:
273  virtual ~Notifications() {}
274  virtual void transactionAddedToMempool(const CTransactionRef& tx) {}
276  virtual void blockConnected(const BlockInfo& block) {}
277  virtual void blockDisconnected(const BlockInfo& block) {}
278  virtual void updatedBlockTip() {}
279  virtual void chainStateFlushed(const CBlockLocator& locator) {}
280  };
281 
283  virtual std::unique_ptr<Handler> handleNotifications(std::shared_ptr<Notifications> notifications) = 0;
284 
287  virtual void waitForNotificationsIfTipChanged(const uint256& old_tip) = 0;
288 
291  virtual std::unique_ptr<Handler> handleRpc(const CRPCCommand& command) = 0;
292 
294  virtual bool rpcEnableDeprecated(const std::string& method) = 0;
295 
297  virtual void rpcRunLater(const std::string& name, std::function<void()> fn, int64_t seconds) = 0;
298 
300  virtual int rpcSerializationFlags() = 0;
301 
303  virtual util::SettingsValue getSetting(const std::string& arg) = 0;
304 
306  virtual std::vector<util::SettingsValue> getSettingsList(const std::string& arg) = 0;
307 
309  virtual util::SettingsValue getRwSetting(const std::string& name) = 0;
310 
313  virtual bool updateRwSetting(const std::string& name, const util::SettingsValue& value, bool write=true) = 0;
314 
323  virtual void requestMempoolTransactions(Notifications& notifications) = 0;
324 
326  virtual bool hasAssumedValidChain() = 0;
327 
330  virtual node::NodeContext* context() { return nullptr; }
331 };
332 
336 {
337 public:
338  virtual ~ChainClient() {}
339 
341  virtual void registerRpcs() = 0;
342 
344  virtual bool verify() = 0;
345 
347  virtual bool load() = 0;
348 
350  virtual void start(CScheduler& scheduler) = 0;
351 
353  virtual void flush() = 0;
354 
356  virtual void stop() = 0;
357 
359  virtual void setMockTime(int64_t time) = 0;
360 };
361 
363 std::unique_ptr<Chain> MakeChain(node::NodeContext& node);
364 
365 } // namespace interfaces
366 
367 #endif // BITCOIN_INTERFACES_CHAIN_H
int64_t CAmount
Amount in satoshis (Can be negative)
Definition: amount.h:12
#define LIFETIMEBOUND
Definition: attributes.h:16
const auto command
BlockFilterType
Definition: blockfilter.h:90
Definition: block.h:69
Undo information for a CBlock.
Definition: undo.h:64
Fee rate in satoshis per kilovirtualbyte: CAmount / kvB.
Definition: feerate.h:33
Simple class for background tasks that should be run periodically or once "after a while".
Definition: scheduler.h:39
The basic transaction that is broadcasted on the network and contained in blocks.
Definition: transaction.h:295
A UTXO entry.
Definition: coins.h:32
std::unordered_set< Element, ByteVectorHash > ElementSet
Definition: blockfilter.h:29
Chain notifications.
Definition: chain.h:271
virtual void transactionRemovedFromMempool(const CTransactionRef &tx, MemPoolRemovalReason reason)
Definition: chain.h:275
virtual void chainStateFlushed(const CBlockLocator &locator)
Definition: chain.h:279
virtual void blockDisconnected(const BlockInfo &block)
Definition: chain.h:277
virtual void blockConnected(const BlockInfo &block)
Definition: chain.h:276
virtual void updatedBlockTip()
Definition: chain.h:278
virtual void transactionAddedToMempool(const CTransactionRef &tx)
Definition: chain.h:274
Interface to let node manage chain clients (wallets, or maybe tools for monitoring and analysis in th...
Definition: chain.h:336
virtual void stop()=0
Shut down client.
virtual void flush()=0
Save state to disk.
virtual bool load()=0
Load saved state.
virtual void registerRpcs()=0
Register rpcs.
virtual void start(CScheduler &scheduler)=0
Start client execution and provide a scheduler.
virtual bool verify()=0
Check for errors before loading.
virtual ~ChainClient()
Definition: chain.h:338
virtual void setMockTime(int64_t time)=0
Set mock time.
Interface giving clients (wallet processes, maybe other analysis tools in the future) ability to acce...
Definition: chain.h:122
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.
virtual CBlockLocator getTipLocator()=0
Get locator for the current chain tip.
virtual bool isInitialBlockDownload()=0
Check if in IBD.
virtual bool hasDescendantsInMempool(const uint256 &txid)=0
Check if transaction has descendants in mempool.
virtual CBlockLocator getActiveChainLocator(const uint256 &block_hash)=0
Return a locator that refers to a block in the active chain.
virtual bool rpcEnableDeprecated(const std::string &method)=0
Check if deprecated RPC is enabled.
virtual int rpcSerializationFlags()=0
Current RPC serialization flags.
virtual bool hasBlocks(const uint256 &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.
virtual node::NodeContext * context()
Get internal node context.
Definition: chain.h:330
virtual RBFTransactionState isRBFOptIn(const CTransaction &tx)=0
Check if transaction is RBF opt in.
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 bool updateRwSetting(const std::string &name, const util::SettingsValue &value, bool write=true)=0
Write a setting to <datadir>/settings.json.
virtual uint256 getBlockHash(int height)=0
Get block hash. Height must be valid or this function will abort.
virtual bool findFirstBlockWithTimeAndHeight(int64_t min_time, int min_height, const FoundBlock &block={})=0
Find first block in the chain with timestamp >= the given time and height >= than the given height,...
virtual util::SettingsValue getRwSetting(const std::string &name)=0
Return <datadir>/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.
virtual void showProgress(const std::string &title, int progress, bool resume_possible)=0
Send progress indicator.
virtual bool havePruned()=0
Check if any block has been pruned.
virtual void findCoins(std::map< COutPoint, Coin > &coins)=0
Look up unspent output information.
virtual bool shutdownRequested()=0
Check if shutdown requested.
virtual bool hasBlockFilterIndex(BlockFilterType filter_type)=0
Returns whether a block filter index is available.
virtual std::optional< int > getHeight()=0
Get current chain height, not including genesis block (returns 0 if chain only contains genesis block...
virtual std::optional< bool > blockFilterMatchesAny(BlockFilterType filter_type, const uint256 &block_hash, const GCSFilter::ElementSet &filter_set)=0
Returns whether any of the elements match the block via a BIP 157 block filter or std::nullopt if the...
virtual void getTransactionAncestry(const uint256 &txid, size_t &ancestors, size_t &descendants, size_t *ancestorsize=nullptr, CAmount *ancestorfees=nullptr)=0
Calculate mempool ancestor and descendant counts for the given transaction.
virtual bool isReadyToBroadcast()=0
Check if the node is ready to broadcast transactions.
virtual bool hasAssumedValidChain()=0
Return true if an assumed-valid chain is in use.
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 util::SettingsValue getSetting(const std::string &arg)=0
Get settings value.
virtual bool findBlock(const uint256 &hash, const FoundBlock &block={})=0
Return whether node has the block and optionally return block metadata or contents.
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 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...
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 CFeeRate mempoolMinFee()=0
Mempool minimum fee.
virtual void initMessage(const std::string &message)=0
Send init message.
virtual bool isInMempool(const uint256 &txid)=0
Check if transaction is in mempool.
virtual unsigned int estimateMaxBlocks()=0
Fee estimator max target.
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...
virtual void getPackageLimits(unsigned int &limit_ancestor_count, unsigned int &limit_descendant_count)=0
Get the node's package limits.
virtual bool checkChainLimits(const CTransactionRef &tx)=0
Check if transaction will pass the mempool's chain limits.
virtual std::unique_ptr< Handler > handleNotifications(std::shared_ptr< Notifications > notifications)=0
Register handler for notifications.
virtual bool haveBlockOnDisk(int height)=0
Check that the block is available on disk (i.e.
virtual ~Chain()
Definition: chain.h:124
virtual std::unique_ptr< Handler > handleRpc(const CRPCCommand &command)=0
Register handler for RPC.
virtual CFeeRate relayDustFee()=0
Relay dust fee setting (-dustrelayfee), reflecting lowest rate it's economical to spend.
virtual void requestMempoolTransactions(Notifications &notifications)=0
Synchronously send transactionAddedToMempool notifications about all current mempool transactions to ...
virtual void initError(const bilingual_str &message)=0
Send init error.
virtual void initWarning(const bilingual_str &message)=0
Send init warning.
virtual CFeeRate estimateSmartFee(int num_blocks, bool conservative, FeeCalculation *calc=nullptr)=0
Estimate smart fee.
virtual CFeeRate relayMinFee()=0
Relay current minimum fee (from -minrelaytxfee and -incrementalrelayfee settings).
virtual CFeeRate relayIncrementalFee()=0
Relay incremental fee setting (-incrementalrelayfee), reflecting cost of relay.
virtual std::vector< util::SettingsValue > getSettingsList(const std::string &arg)=0
Get list of settings values.
Helper for findBlock to selectively return pieces of block data.
Definition: chain.h:52
CBlock * m_data
Definition: chain.h:77
const FoundBlock * m_next_block
Definition: chain.h:76
FoundBlock & height(int &height)
Definition: chain.h:55
FoundBlock & locator(CBlockLocator &locator)
Return locator if block is in the active chain.
Definition: chain.h:62
FoundBlock & hash(uint256 &hash)
Definition: chain.h:54
FoundBlock & mtpTime(int64_t &mtp_time)
Definition: chain.h:58
FoundBlock & nextBlock(const FoundBlock &next_block)
Return next block in the active chain if current block is in the active chain.
Definition: chain.h:64
FoundBlock & data(CBlock &data)
Read block data from disk.
Definition: chain.h:67
FoundBlock & inActiveChain(bool &in_active_chain)
Return whether block is in the active (most-work) chain.
Definition: chain.h:60
FoundBlock & maxTime(int64_t &max_time)
Definition: chain.h:57
int64_t * m_max_time
Definition: chain.h:72
int64_t * m_time
Definition: chain.h:71
bool * m_in_active_chain
Definition: chain.h:74
uint256 * m_hash
Definition: chain.h:69
int64_t * m_mtp_time
Definition: chain.h:73
FoundBlock & time(int64_t &time)
Definition: chain.h:56
CBlockLocator * m_locator
Definition: chain.h:75
256-bit opaque blob.
Definition: uint256.h:105
std::unique_ptr< Chain > MakeChain(node::NodeContext &node)
Return implementation of Chain interface.
Definition: interfaces.cpp:799
Definition: init.h:25
RBFTransactionState
The rbf state of unconfirmed transactions.
Definition: rbf.h:27
std::shared_ptr< const CTransaction > CTransactionRef
Definition: transaction.h:421
const char * name
Definition: rest.cpp:45
Describes a place in the block chain to another node such that if the other node doesn't have the sam...
Definition: block.h:121
Bilingual messages:
Definition: translation.h:18
Block data sent with blockConnected, blockDisconnected notifications.
Definition: chain.h:82
unsigned data_pos
Definition: chain.h:87
const uint256 * prev_hash
Definition: chain.h:84
const CBlock * data
Definition: chain.h:88
const uint256 & hash
Definition: chain.h:83
BlockInfo(const uint256 &hash LIFETIMEBOUND)
Definition: chain.h:94
const CBlockUndo * undo_data
Definition: chain.h:89
unsigned int chain_time_max
Definition: chain.h:92
Hash/height pair to help track and identify blocks.
Definition: chain.h:43
uint256 hash
Definition: chain.h:44
NodeContext struct containing references to chain state and connection state.
Definition: context.h:45
MemPoolRemovalReason
Reason why a transaction was removed from the mempool, this is passed to the notification signal.
Definition: txmempool.h:231