38 #include <validation.h>
42 #if defined(HAVE_CONFIG_H)
43 #include <config/bitcoin-config.h>
48 #include <boost/signals2/signal.hpp>
66 class NodeImpl :
public Node {
71 explicit NodeImpl(NodeContext *context) { setContext(context); }
73 void initParameterInteraction()
override {
77 bool baseInitialize(
Config &config)
override {
86 return AppInitMain(config, rpcServer, httpRPCRequestProcessor,
89 void appShutdown()
override {
93 void startShutdown()
override {
103 void mapPort(
bool use_upnp,
bool use_natpmp)
override {
113 bool getNodesStats(NodesStats &stats)
override {
117 std::vector<CNodeStats> stats_temp;
118 m_context->connman->GetNodeStats(stats_temp);
120 stats.reserve(stats_temp.size());
121 for (
auto &node_stats_temp : stats_temp) {
122 stats.emplace_back(std::move(node_stats_temp),
false,
130 for (
auto &node_stats : stats) {
131 std::get<1>(node_stats) =
133 std::get<0>(node_stats).nodeid,
134 std::get<2>(node_stats));
142 bool getBanned(
banmap_t &banmap)
override {
149 bool ban(
const CNetAddr &net_addr, int64_t ban_time_offset)
override {
151 m_context->banman->Ban(net_addr, ban_time_offset);
156 bool unban(
const CSubNet &ip)
override {
163 bool disconnectByAddress(
const CNetAddr &net_addr)
override {
165 return m_context->connman->DisconnectNode(net_addr);
169 bool disconnectById(
NodeId id)
override {
171 return m_context->connman->DisconnectNode(
id);
175 int64_t getTotalBytesRecv()
override {
179 int64_t getTotalBytesSent()
override {
183 size_t getMempoolSize()
override {
186 size_t getMempoolDynamicUsage()
override {
190 bool getHeaderTip(
int &height, int64_t &block_time)
override {
192 auto best_header = chainman().m_best_header;
194 height = best_header->nHeight;
195 block_time = best_header->GetBlockTime();
200 int getNumBlocks()
override {
202 return chainman().ActiveChain().Height();
210 int64_t getLastBlockTime()
override {
212 if (chainman().ActiveChain().Tip()) {
213 return chainman().ActiveChain().Tip()->GetBlockTime();
218 double getVerificationProgress()
override {
222 tip = chainman().ActiveChain().Tip();
226 bool isInitialBlockDownload()
override {
227 return chainman().ActiveChainstate().IsInitialBlockDownload();
231 void setNetworkActive(
bool active)
override {
233 m_context->connman->SetNetworkActive(active);
236 bool getNetworkActive()
override {
240 UniValue executeRpc(
const Config &config,
const std::string &command,
242 const std::string &uri)
override {
250 std::vector<std::string> listRpcCommands()
override {
259 bool getUnspentOutput(
const COutPoint &output,
Coin &coin)
override {
261 return chainman().ActiveChainstate().CoinsTip().GetCoin(output,
267 std::unique_ptr<Handler> handleInitMessage(InitMessageFn fn)
override {
270 std::unique_ptr<Handler> handleMessageBox(MessageBoxFn fn)
override {
273 std::unique_ptr<Handler> handleQuestion(QuestionFn fn)
override {
276 std::unique_ptr<Handler>
277 handleShowProgress(ShowProgressFn fn)
override {
280 std::unique_ptr<Handler> handleNotifyNumConnectionsChanged(
281 NotifyNumConnectionsChangedFn fn)
override {
283 ::
uiInterface.NotifyNumConnectionsChanged_connect(fn));
285 std::unique_ptr<Handler> handleNotifyNetworkActiveChanged(
286 NotifyNetworkActiveChangedFn fn)
override {
288 ::
uiInterface.NotifyNetworkActiveChanged_connect(fn));
290 std::unique_ptr<Handler>
291 handleNotifyAlertChanged(NotifyAlertChangedFn fn)
override {
294 std::unique_ptr<Handler>
295 handleBannedListChanged(BannedListChangedFn fn)
override {
298 std::unique_ptr<Handler>
299 handleNotifyBlockTip(NotifyBlockTipFn fn)
override {
304 BlockTip{block->nHeight, block->GetBlockTime(),
305 block->GetBlockHash()},
309 std::unique_ptr<Handler>
310 handleNotifyHeaderTip(NotifyHeaderTipFn fn)
override {
316 BlockTip{block->nHeight, block->GetBlockTime(),
317 block->GetBlockHash()},
321 NodeContext *context()
override {
return m_context; }
322 void setContext(NodeContext *context)
override {
m_context = context; }
350 FillBlock(active[index->
nHeight] == index
358 Params().GetConsensus())) {
367 explicit NotificationsProxy(
368 std::shared_ptr<Chain::Notifications> notifications)
370 virtual ~NotificationsProxy() =
default;
372 uint64_t mempool_sequence)
override {
377 uint64_t mempool_sequence)
override {
391 bool is_ibd)
override {
400 class NotificationsHandlerImpl :
public Handler {
402 explicit NotificationsHandlerImpl(
403 std::shared_ptr<Chain::Notifications> notifications)
404 :
m_proxy(std::make_shared<NotificationsProxy>(
405 std::move(notifications))) {
408 ~NotificationsHandlerImpl()
override {
disconnect(); }
418 class RpcHandlerImpl :
public Handler {
420 explicit RpcHandlerImpl(
const CRPCCommand &command)
424 UniValue &result,
bool last_handler) {
462 class ChainImpl :
public Chain {
469 std::optional<int>
getHeight()
override {
472 int height = active.
Height();
489 return block && (block->nStatus.hasData() != 0) && block->
nTx > 0;
503 return fork->nHeight;
511 return FillBlock(
m_node.chainman->m_blockman.LookupBlockIndex(hash),
512 block, lock, active);
519 block, lock, active);
527 m_node.chainman->m_blockman.LookupBlockIndex(block_hash)) {
529 block->GetAncestor(ancestor_height)) {
530 return FillBlock(ancestor, ancestor_out, lock, active);
533 return FillBlock(
nullptr, ancestor_out, lock, active);
541 m_node.chainman->m_blockman.LookupBlockIndex(block_hash);
543 m_node.chainman->m_blockman.LookupBlockIndex(ancestor_hash);
544 if (block && ancestor &&
548 return FillBlock(ancestor, ancestor_out, lock, active);
558 m_node.chainman->m_blockman.LookupBlockIndex(block_hash1);
560 m_node.chainman->m_blockman.LookupBlockIndex(block_hash2);
566 return int{FillBlock(ancestor, ancestor_out, lock, active)} &
567 int{FillBlock(block1, block1_out, lock, active)} &
568 int{FillBlock(block2, block2_out, lock, active)};
570 void findCoins(std::map<COutPoint, Coin> &coins)
override {
577 chainman().m_blockman.LookupBlockIndex(block_hash));
580 std::optional<int> max_height)
override {
590 chainman().m_blockman.LookupBlockIndex(block_hash)) {
591 if (max_height && block->
nHeight >= *max_height) {
594 for (; block->nStatus.hasData(); block = block->
pprev) {
605 const Amount &max_tx_fee,
bool relay,
606 std::string &err_string)
override {
621 return m_node.mempool->estimateFee();
627 return m_node.chainman->m_blockman.m_have_pruned;
634 return chainman().ActiveChainstate().IsInitialBlockDownload();
638 void initMessage(
const std::string &message)
override {
647 void showProgress(
const std::string &title,
int progress,
648 bool resume_possible)
override {
649 ::uiInterface.ShowProgress(title, progress, resume_possible);
652 std::shared_ptr<Notifications> notifications)
override {
653 return std::make_unique<NotificationsHandlerImpl>(
654 std::move(notifications));
668 std::unique_ptr<Handler>
670 return std::make_unique<RpcHandlerImpl>(command);
676 int64_t seconds)
override {
694 settings.rw_settings.erase(name);
696 settings.rw_settings[name] = value;
707 notifications.transactionAddedToMempool(entry.
GetSharedTx(),
720 return std::make_unique<node::NodeImpl>(context);
724 return std::make_unique<node::ChainImpl>(
node, params);
RecursiveMutex cs_main
Global state.
const CBlockIndex * LastCommonAncestor(const CBlockIndex *pa, const CBlockIndex *pb)
Find the last common ancestor two blocks have.
const CChainParams & Params()
Return the currently selected parameters.
#define Assert(val)
Identity function.
bool WriteSettingsFile(std::vector< std::string > *errors=nullptr) const
Write settings file.
void LockSettings(Fn &&fn)
Access settings with lock held.
bool GetBoolArg(const std::string &strArg, bool fDefault) const
Return boolean argument or default value.
The block chain is a tree shaped structure starting with the genesis block at the root,...
CBlockIndex * pprev
pointer to the index of the predecessor of this block
int64_t GetBlockTime() const
int64_t GetMedianTimePast() const
int64_t GetBlockTimeMax() const
unsigned int nTx
Number of transactions in this block.
CBlockIndex * GetAncestor(int height)
Efficiently find an ancestor of this block.
BlockHash GetBlockHash() const
int nHeight
height of the entry in the chain. The genesis block has height 0
An in-memory indexed chain of blocks.
CBlockIndex * Tip() const
Returns the index entry for the tip of this chain, or nullptr if none.
CBlockLocator GetLocator(const CBlockIndex *pindex=nullptr) const
Return a CBlockLocator that refers to a block in this chain (by default the tip).
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...
int Height() const
Return the maximal height in the chain.
CChainParams defines various tweakable parameters of a given instance of the Bitcoin system.
const CBlock & GenesisBlock() const
Fee rate in satoshis per kilobyte: Amount / kB.
An outpoint - a combination of a transaction hash and an index n into its vout.
bool removeCommand(const std::string &name, const CRPCCommand *pcmd)
std::vector< std::string > listCommands() const
Returns a list of registered commands.
UniValue execute(const Config &config, const JSONRPCRequest &request) const
Execute a method.
void appendCommand(const std::string &name, const CRPCCommand *pcmd)
Appends a CRPCCommand to the dispatch table.
CTxMemPoolEntry stores data about the corresponding transaction, as well as data about all in-mempool...
CTransactionRef GetSharedTx() const
Implement this to subscribe to events generated in validation.
virtual void TransactionAddedToMempool(const CTransactionRef &tx, uint64_t mempool_sequence)
Notifies listeners of a transaction having been added to mempool.
virtual void ChainStateFlushed(const CBlockLocator &locator)
Notifies listeners of the new active block chain on-disk.
virtual void TransactionRemovedFromMempool(const CTransactionRef &tx, MemPoolRemovalReason reason, uint64_t mempool_sequence)
Notifies listeners of a transaction leaving mempool.
virtual void UpdatedBlockTip(const CBlockIndex *pindexNew, const CBlockIndex *pindexFork, bool fInitialDownload)
Notifies listeners when the block chain tip advances.
virtual void BlockConnected(const std::shared_ptr< const CBlock > &block, const CBlockIndex *pindex)
Notifies listeners of a block being connected.
virtual void BlockDisconnected(const std::shared_ptr< const CBlock > &block, const CBlockIndex *pindex)
Notifies listeners of a block being disconnected.
Chainstate stores and provides an API to update our local knowledge of the current best chain.
const CBlockIndex * FindForkInGlobalIndex(const CBlockLocator &locator) const EXCLUSIVE_LOCKS_REQUIRED(cs_main)
Find the last common block of this chain and a locator.
Provides an interface for creating and interacting with one or two chainstates: an IBD chainstate gen...
Class for registering and managing all RPC calls.
Wrapper around std::unique_lock style lock for Mutex.
Interface giving clients (wallet processes, maybe other analysis tools in the future) ability to acce...
virtual void rpcRunLater(const std::string &name, std::function< void()> fn, int64_t seconds)=0
Run function after given number of seconds.
virtual CBlockLocator getTipLocator()=0
Get locator for the current chain tip.
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.
virtual bool isInitialBlockDownload()=0
Check if in IBD.
virtual BlockHash getBlockHash(int height)=0
Get block hash. Height must be valid or this function will abort.
virtual bool rpcEnableDeprecated(const std::string &method)=0
Check if deprecated RPC is enabled.
virtual int rpcSerializationFlags()=0
Current RPC serialization flags.
virtual bool findBlock(const BlockHash &hash, const FoundBlock &block={})=0
Return whether node has the block and optionally return block metadata or contents.
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.
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 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...
virtual util::SettingsValue getRwSetting(const std::string &name)=0
Return <datadir>/settings.json setting value.
virtual double guessVerificationProgress(const BlockHash &block_hash)=0
Estimate fraction of total transactions verified if blocks up to the specified block hash are verifie...
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 std::optional< int > getHeight()=0
Get current chain height, not including genesis block (returns 0 if chain only contains genesis block...
virtual bool updateRwSetting(const std::string &name, const util::SettingsValue &value)=0
Write a setting to <datadir>/settings.json.
virtual bool isReadyToBroadcast()=0
Check if the node is ready to broadcast transactions.
virtual int64_t getAdjustedTime()=0
Get adjusted time.
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.
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 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.
virtual void initMessage(const std::string &message)=0
Send init message.
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 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 CFeeRate estimateFee() const =0
Estimate fee.
virtual void requestMempoolTransactions(Notifications ¬ifications)=0
Synchronously send transactionAddedToMempool notifications about all current mempool transactions to ...
virtual void initError(const bilingual_str &message)=0
Send init error.
virtual void waitForNotificationsIfTipChanged(const BlockHash &old_tip)=0
Wait for pending notifications to be processed unless block hash points to the current chain tip.
virtual void initWarning(const bilingual_str &message)=0
Send init warning.
virtual CFeeRate relayMinFee()=0
Relay current minimum fee (from -minrelaytxfee settings).
virtual const CChainParams & params() const =0
This Chain's parameters.
Helper for findBlock to selectively return pieces of block data.
const FoundBlock * m_next_block
Generic interface for managing an event handler or callback function registered with another interfac...
virtual void disconnect()=0
Disconnect the handler.
Top-level interface for a bitcoin node (bitcoind process).
Wallet chain client that in addition to having chain client methods for starting up,...
void Interrupt(NodeContext &node)
Interrupt threads.
void InitLogging(const ArgsManager &args)
Initialize global loggers.
bool AppInitLockDataDirectory()
Lock bitcoin data directory.
void Shutdown(NodeContext &node)
bool AppInitMain(Config &config, RPCServer &rpcServer, HTTPRPCRequestProcessor &httpRPCRequestProcessor, NodeContext &node, interfaces::BlockAndHeaderTipInfo *tip_info)
Bitcoin main initialization.
bool AppInitBasicSetup(const ArgsManager &args)
Initialize bitcoin: Basic context setup.
bool AppInitSanityChecks()
Initialization sanity checks: ecc init, sanity checks, dir lock.
bool AppInitInterfaces(NodeContext &node)
Initialize node and wallet interface pointers.
void InitParameterInteraction(ArgsManager &args)
Parameter interaction: change current parameters depending on various rules.
bool AppInitParameterInteraction(Config &config, const ArgsManager &args)
Initialization: parameter interaction.
void StartMapPort(bool use_upnp, bool use_natpmp)
std::unique_ptr< Handler > MakeHandler(boost::signals2::connection connection)
Return handler wrapping a boost signal connection.
std::unique_ptr< Chain > MakeChain(node::NodeContext &node, const CChainParams ¶ms)
Return implementation of Chain interface.
std::unique_ptr< Node > MakeNode(node::NodeContext *context=nullptr)
Return implementation of Node interface.
TransactionError BroadcastTransaction(const NodeContext &node, const CTransactionRef tx, std::string &err_string, const Amount max_tx_fee, bool relay, bool wait_callback)
Submit a transaction to the mempool and (optionally) relay it to all P2P peers.
std::atomic_bool fImporting
bool ReadBlockFromDisk(CBlock &block, const FlatFilePos &pos, const Consensus::Params ¶ms)
Functions for disk access for blocks.
void FindCoins(const NodeContext &node, std::map< COutPoint, Coin > &coins)
Look up unspent output information.
std::atomic_bool fReindex
auto FindKey(Map &&map, Key &&key) -> decltype(&map.at(key))
Map lookup helper.
std::map< CSubNet, CBanEntry > banmap_t
bool GetProxy(enum Network net, proxyType &proxyInfoOut)
std::shared_ptr< Chain::Notifications > m_notifications
const CChainParams & m_params
const CRPCCommand * m_wrapped_command
std::shared_ptr< NotificationsProxy > m_proxy
std::shared_ptr< const CTransaction > CTransactionRef
@ RPC_WALLET_NOT_FOUND
Invalid wallet specified.
void RPCSetTimerInterfaceIfUnset(RPCTimerInterface *iface)
Set the factory function for timer, but only, if unset.
bool IsDeprecatedRPCEnabled(const ArgsManager &args, const std::string &method)
void RPCUnsetTimerInterface(RPCTimerInterface *iface)
Unset factory function for timers.
void RPCRunLater(const std::string &name, std::function< void()> func, int64_t nSeconds)
Run func nSeconds from now.
int RPCSerializationFlags()
Retrieves any serialization flags requested in command line argument.
bool ShutdownRequested()
Returns true if a shutdown is requested, false otherwise.
void StartShutdown()
Request shutdown of the application.
A BlockHash is a unqiue identifier for a block.
Describes a place in the block chain to another node such that if the other node doesn't have the sam...
Block and header tip information.
Block tip (could be a header or not, depends on the subscribed signal).
NodeContext struct containing references to chain state and connection state.
std::map< std::string, SettingsValue > rw_settings
Map of setting name to read-write file setting value.
#define WAIT_LOCK(cs, name)
#define WITH_LOCK(cs, code)
Run code while locking a mutex.
#define TRY_LOCK(cs, name)
int64_t GetAdjustedTime()
MemPoolRemovalReason
Reason why a transaction was removed from the mempool, this is passed to the notification signal.
CClientUIInterface uiInterface
void InitWarning(const bilingual_str &str)
Show warning message.
bool InitError(const bilingual_str &str)
Show error message.
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...
CFeeRate minRelayTxFee
A fee rate smaller than this is considered zero fee (for relaying, mining and transaction creation)
SynchronizationState
Current sync state passed to tip changed callbacks.
void UnregisterSharedValidationInterface(std::shared_ptr< CValidationInterface > callbacks)
Unregister subscriber.
void SyncWithValidationInterfaceQueue()
This is a synonym for the following, which asserts certain locks are not held: std::promise<void> pro...
void RegisterSharedValidationInterface(std::shared_ptr< CValidationInterface > callbacks)
Register subscriber.
bilingual_str GetWarnings(bool verbose)
Format a string that describes several potential problems detected by the core.