Bitcoin Core  22.99.0
P2P Digital Currency
chain.h
Go to the documentation of this file.
1 // Copyright (c) 2018-2021 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 <primitives/transaction.h> // For CTransactionRef
9 #include <util/settings.h> // For util::SettingsValue
10 
11 #include <functional>
12 #include <memory>
13 #include <optional>
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 namespace node {
32 struct NodeContext;
33 } // namespace node
34 
35 namespace interfaces {
36 
37 class Handler;
38 class Wallet;
39 
44 {
45 public:
46  FoundBlock& hash(uint256& hash) { m_hash = &hash; return *this; }
47  FoundBlock& height(int& height) { m_height = &height; return *this; }
48  FoundBlock& time(int64_t& time) { m_time = &time; return *this; }
49  FoundBlock& maxTime(int64_t& max_time) { m_max_time = &max_time; return *this; }
50  FoundBlock& mtpTime(int64_t& mtp_time) { m_mtp_time = &mtp_time; return *this; }
52  FoundBlock& inActiveChain(bool& in_active_chain) { m_in_active_chain = &in_active_chain; return *this; }
54  FoundBlock& nextBlock(const FoundBlock& next_block) { m_next_block = &next_block; return *this; }
57  FoundBlock& data(CBlock& data) { m_data = &data; return *this; }
58 
59  uint256* m_hash = nullptr;
60  int* m_height = nullptr;
61  int64_t* m_time = nullptr;
62  int64_t* m_max_time = nullptr;
63  int64_t* m_mtp_time = nullptr;
64  bool* m_in_active_chain = nullptr;
65  const FoundBlock* m_next_block = nullptr;
66  CBlock* m_data = nullptr;
67  mutable bool found = false;
68 };
69 
94 class Chain
95 {
96 public:
97  virtual ~Chain() {}
98 
102  virtual std::optional<int> getHeight() = 0;
103 
105  virtual uint256 getBlockHash(int height) = 0;
106 
109  virtual bool haveBlockOnDisk(int height) = 0;
110 
112  virtual CBlockLocator getTipLocator() = 0;
113 
117  virtual std::optional<int> findLocatorFork(const CBlockLocator& locator) = 0;
118 
121  virtual bool findBlock(const uint256& hash, const FoundBlock& block={}) = 0;
122 
127  virtual bool findFirstBlockWithTimeAndHeight(int64_t min_time, int min_height, const FoundBlock& block={}) = 0;
128 
131  virtual bool findAncestorByHeight(const uint256& block_hash, int ancestor_height, const FoundBlock& ancestor_out={}) = 0;
132 
135  virtual bool findAncestorByHash(const uint256& block_hash,
136  const uint256& ancestor_hash,
137  const FoundBlock& ancestor_out={}) = 0;
138 
141  virtual bool findCommonAncestor(const uint256& block_hash1,
142  const uint256& block_hash2,
143  const FoundBlock& ancestor_out={},
144  const FoundBlock& block1_out={},
145  const FoundBlock& block2_out={}) = 0;
146 
150  virtual void findCoins(std::map<COutPoint, Coin>& coins) = 0;
151 
154  virtual double guessVerificationProgress(const uint256& block_hash) = 0;
155 
159  virtual bool hasBlocks(const uint256& block_hash, int min_height = 0, std::optional<int> max_height = {}) = 0;
160 
162  virtual RBFTransactionState isRBFOptIn(const CTransaction& tx) = 0;
163 
165  virtual bool isInMempool(const uint256& txid) = 0;
166 
168  virtual bool hasDescendantsInMempool(const uint256& txid) = 0;
169 
173  virtual bool broadcastTransaction(const CTransactionRef& tx,
174  const CAmount& max_tx_fee,
175  bool relay,
176  std::string& err_string) = 0;
177 
179  virtual void getTransactionAncestry(const uint256& txid, size_t& ancestors, size_t& descendants, size_t* ancestorsize = nullptr, CAmount* ancestorfees = nullptr) = 0;
180 
184  virtual void getPackageLimits(unsigned int& limit_ancestor_count, unsigned int& limit_descendant_count) = 0;
185 
187  virtual bool checkChainLimits(const CTransactionRef& tx) = 0;
188 
190  virtual CFeeRate estimateSmartFee(int num_blocks, bool conservative, FeeCalculation* calc = nullptr) = 0;
191 
193  virtual unsigned int estimateMaxBlocks() = 0;
194 
196  virtual CFeeRate mempoolMinFee() = 0;
197 
199  virtual CFeeRate relayMinFee() = 0;
200 
202  virtual CFeeRate relayIncrementalFee() = 0;
203 
205  virtual CFeeRate relayDustFee() = 0;
206 
208  virtual bool havePruned() = 0;
209 
211  virtual bool isReadyToBroadcast() = 0;
212 
214  virtual bool isInitialBlockDownload() = 0;
215 
217  virtual bool shutdownRequested() = 0;
218 
220  virtual void initMessage(const std::string& message) = 0;
221 
223  virtual void initWarning(const bilingual_str& message) = 0;
224 
226  virtual void initError(const bilingual_str& message) = 0;
227 
229  virtual void showProgress(const std::string& title, int progress, bool resume_possible) = 0;
230 
233  {
234  public:
235  virtual ~Notifications() {}
236  virtual void transactionAddedToMempool(const CTransactionRef& tx, uint64_t mempool_sequence) {}
237  virtual void transactionRemovedFromMempool(const CTransactionRef& tx, MemPoolRemovalReason reason, uint64_t mempool_sequence) {}
238  virtual void blockConnected(const CBlock& block, int height) {}
239  virtual void blockDisconnected(const CBlock& block, int height) {}
240  virtual void updatedBlockTip() {}
241  virtual void chainStateFlushed(const CBlockLocator& locator) {}
242  };
243 
245  virtual std::unique_ptr<Handler> handleNotifications(std::shared_ptr<Notifications> notifications) = 0;
246 
249  virtual void waitForNotificationsIfTipChanged(const uint256& old_tip) = 0;
250 
253  virtual std::unique_ptr<Handler> handleRpc(const CRPCCommand& command) = 0;
254 
256  virtual bool rpcEnableDeprecated(const std::string& method) = 0;
257 
259  virtual void rpcRunLater(const std::string& name, std::function<void()> fn, int64_t seconds) = 0;
260 
262  virtual int rpcSerializationFlags() = 0;
263 
265  virtual util::SettingsValue getSetting(const std::string& arg) = 0;
266 
268  virtual std::vector<util::SettingsValue> getSettingsList(const std::string& arg) = 0;
269 
271  virtual util::SettingsValue getRwSetting(const std::string& name) = 0;
272 
275  virtual bool updateRwSetting(const std::string& name, const util::SettingsValue& value, bool write=true) = 0;
276 
285  virtual void requestMempoolTransactions(Notifications& notifications) = 0;
286 };
287 
291 {
292 public:
293  virtual ~ChainClient() {}
294 
296  virtual void registerRpcs() = 0;
297 
299  virtual bool verify() = 0;
300 
302  virtual bool load() = 0;
303 
305  virtual void start(CScheduler& scheduler) = 0;
306 
308  virtual void flush() = 0;
309 
311  virtual void stop() = 0;
312 
314  virtual void setMockTime(int64_t time) = 0;
315 };
316 
318 std::unique_ptr<Chain> MakeChain(node::NodeContext& node);
319 
320 } // namespace interfaces
321 
322 #endif // BITCOIN_INTERFACES_CHAIN_H
interfaces::MakeChain
std::unique_ptr< Chain > MakeChain(node::NodeContext &node)
Return implementation of Chain interface.
Definition: interfaces.cpp:728
interfaces
Definition: dummywallet.cpp:10
interfaces::Chain::findAncestorByHash
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.
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:33
interfaces::Chain::guessVerificationProgress
virtual double guessVerificationProgress(const uint256 &block_hash)=0
Estimate fraction of total transactions verified if blocks up to the specified block hash are verifie...
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:57
interfaces::Chain::Notifications::~Notifications
virtual ~Notifications()
Definition: chain.h:235
interfaces::FoundBlock::m_data
CBlock * m_data
Definition: chain.h:66
interfaces::Chain::findCoins
virtual void findCoins(std::map< COutPoint, Coin > &coins)=0
Look up unspent output information.
interfaces::Chain::Notifications::transactionRemovedFromMempool
virtual void transactionRemovedFromMempool(const CTransactionRef &tx, MemPoolRemovalReason reason, uint64_t mempool_sequence)
Definition: chain.h:237
interfaces::FoundBlock::mtpTime
FoundBlock & mtpTime(int64_t &mtp_time)
Definition: chain.h:50
transaction.h
RBFTransactionState
RBFTransactionState
The rbf state of unconfirmed transactions.
Definition: rbf.h:20
bilingual_str
Bilingual messages:
Definition: translation.h:16
interfaces::Chain::isInitialBlockDownload
virtual bool isInitialBlockDownload()=0
Check if in IBD.
interfaces::FoundBlock::nextBlock
FoundBlock & nextBlock(const FoundBlock &next_block)
Return next block in the active chain if current block is in the active chain.
Definition: chain.h:54
interfaces::Chain::Notifications::chainStateFlushed
virtual void chainStateFlushed(const CBlockLocator &locator)
Definition: chain.h:241
interfaces::Chain::~Chain
virtual ~Chain()
Definition: chain.h:97
interfaces::FoundBlock::m_in_active_chain
bool * m_in_active_chain
Definition: chain.h:64
node::NodeContext
NodeContext struct containing references to chain state and connection state.
Definition: context.h:40
interfaces::Chain::handleNotifications
virtual std::unique_ptr< Handler > handleNotifications(std::shared_ptr< Notifications > notifications)=0
Register handler for notifications.
interfaces::Chain::getSettingsList
virtual std::vector< util::SettingsValue > getSettingsList(const std::string &arg)=0
Get list of settings values.
interfaces::Chain::hasDescendantsInMempool
virtual bool hasDescendantsInMempool(const uint256 &txid)=0
Check if transaction has descendants in mempool.
interfaces::FoundBlock::found
bool found
Definition: chain.h:67
interfaces::ChainClient::flush
virtual void flush()=0
Save state to disk.
interfaces::FoundBlock::m_next_block
const FoundBlock * m_next_block
Definition: chain.h:65
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::findBlock
virtual bool findBlock(const uint256 &hash, const FoundBlock &block={})=0
Return whether node has the block and optionally return block metadata or contents.
interfaces::ChainClient::start
virtual void start(CScheduler &scheduler)=0
Start client execution and provide a scheduler.
CTransactionRef
std::shared_ptr< const CTransaction > CTransactionRef
Definition: transaction.h:406
interfaces::Chain::findAncestorByHeight
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.
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: CAmount / kB.
Definition: feerate.h:29
interfaces::FoundBlock::time
FoundBlock & time(int64_t &time)
Definition: chain.h:48
interfaces::Chain::getPackageLimits
virtual void getPackageLimits(unsigned int &limit_ancestor_count, unsigned int &limit_descendant_count)=0
Get the node's package limits.
UniValue
Definition: univalue.h:17
CTransaction
The basic transaction that is broadcasted on the network and contained in blocks.
Definition: transaction.h:279
interfaces::ChainClient::~ChainClient
virtual ~ChainClient()
Definition: chain.h:293
interfaces::Chain::relayIncrementalFee
virtual CFeeRate relayIncrementalFee()=0
Relay incremental fee setting (-incrementalrelayfee), reflecting cost of relay.
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:94
interfaces::Chain::Notifications::updatedBlockTip
virtual void updatedBlockTip()
Definition: chain.h:240
FeeCalculation
Definition: fees.h:75
settings.h
interfaces::FoundBlock::m_time
int64_t * m_time
Definition: chain.h:61
interfaces::ChainClient::load
virtual bool load()=0
Load saved state.
CRPCCommand
Definition: server.h:89
Coin
A UTXO entry.
Definition: coins.h:30
interfaces::Chain::getBlockHash
virtual uint256 getBlockHash(int height)=0
Get block hash. Height must be valid or this function will abort.
interfaces::Chain::mempoolMinFee
virtual CFeeRate mempoolMinFee()=0
Mempool minimum fee.
interfaces::FoundBlock::maxTime
FoundBlock & maxTime(int64_t &max_time)
Definition: chain.h:49
interfaces::Chain::waitForNotificationsIfTipChanged
virtual void waitForNotificationsIfTipChanged(const uint256 &old_tip)=0
Wait for pending notifications to be processed unless block hash points to the current chain tip.
interfaces::Chain::Notifications::blockDisconnected
virtual void blockDisconnected(const CBlock &block, int height)
Definition: chain.h:239
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...
CAmount
int64_t CAmount
Amount in satoshis (Can be negative)
Definition: amount.h:12
interfaces::Chain::relayMinFee
virtual CFeeRate relayMinFee()=0
Relay current minimum fee (from -minrelaytxfee and -incrementalrelayfee settings).
interfaces::Chain::shutdownRequested
virtual bool shutdownRequested()=0
Check if shutdown requested.
interfaces::Chain::broadcastTransaction
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...
interfaces::Chain::updateRwSetting
virtual bool updateRwSetting(const std::string &name, const util::SettingsValue &value, bool write=true)=0
Write a setting to <datadir>/settings.json.
interfaces::FoundBlock
Helper for findBlock to selectively return pieces of block data.
Definition: chain.h:43
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. Cancel any previous calls with same name.
uint256
256-bit opaque blob.
Definition: uint256.h:126
interfaces::Chain::isRBFOptIn
virtual RBFTransactionState isRBFOptIn(const CTransaction &tx)=0
Check if transaction is RBF opt in.
interfaces::Chain::findCommonAncestor
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.
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:236
name
const char * name
Definition: rest.cpp:52
interfaces::Chain::estimateSmartFee
virtual CFeeRate estimateSmartFee(int num_blocks, bool conservative, FeeCalculation *calc=nullptr)=0
Estimate smart fee.
interfaces::FoundBlock::height
FoundBlock & height(int &height)
Definition: chain.h:47
interfaces::Chain::initWarning
virtual void initWarning(const bilingual_str &message)=0
Send init warning.
CBlock
Definition: block.h:62
interfaces::FoundBlock::m_hash
uint256 * m_hash
Definition: chain.h:59
interfaces::ChainClient
Interface to let node manage chain clients (wallets, or maybe tools for monitoring and analysis in th...
Definition: chain.h:290
ArgsManager
Definition: system.h:164
interfaces::Chain::isInMempool
virtual bool isInMempool(const uint256 &txid)=0
Check if transaction is in mempool.
MemPoolRemovalReason
MemPoolRemovalReason
Reason why a transaction was removed from the mempool, this is passed to the notification signal.
Definition: txmempool.h:347
interfaces::Chain::Notifications
Chain notifications.
Definition: chain.h:232
interfaces::FoundBlock::m_max_time
int64_t * m_max_time
Definition: chain.h:62
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:63
interfaces::Chain::initMessage
virtual void initMessage(const std::string &message)=0
Send init message.
interfaces::Chain::getSetting
virtual util::SettingsValue getSetting(const std::string &arg)=0
Get settings value.
interfaces::ChainClient::stop
virtual void stop()=0
Shut down client.
interfaces::Chain::getTransactionAncestry
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.
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.
node
Definition: init.h:22
interfaces::FoundBlock::hash
FoundBlock & hash(uint256 &hash)
Definition: chain.h:46
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.
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:114
interfaces::Chain::showProgress
virtual void showProgress(const std::string &title, int progress, bool resume_possible)=0
Send progress indicator.
interfaces::FoundBlock::inActiveChain
FoundBlock & inActiveChain(bool &in_active_chain)
Return whether block is in the active (most-work) chain.
Definition: chain.h:52
interfaces::Chain::estimateMaxBlocks
virtual unsigned int estimateMaxBlocks()=0
Fee estimator max target.
interfaces::Chain::handleRpc
virtual std::unique_ptr< Handler > handleRpc(const CRPCCommand &command)=0
Register handler for RPC.
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:238
interfaces::Chain::findFirstBlockWithTimeAndHeight
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,...
interfaces::FoundBlock::m_height
int * m_height
Definition: chain.h:60
interfaces::Chain::hasBlocks
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.