6#include <bitcoin-build-config.h>
13#include <chainparams.h>
64#include <versionbits.h>
110 if (
pb ==
nullptr || !
pb->nHeight)
124 for (
int i = 0; i <
lookup; i++) {
128 maxTime = std::max(time, maxTime);
145 "Returns the estimated network hashes per second based on the last n blocks.\n"
146 "Pass in [blocks] to override # of blocks, -1 specifies since last difficulty change.\n"
147 "Pass in [height] to estimate the network speed at the time when a certain block was found.\n",
149 {
"nblocks",
RPCArg::Type::NUM,
RPCArg::Default{120},
"The number of previous blocks to calculate estimate from, or -1 for blocks since last difficulty change."},
179 if (block.nNonce == std::numeric_limits<uint32_t>::max()) {
183 block_out = std::make_shared<const CBlock>(std::move(block));
218 if (
descs.empty())
return false;
219 if (
descs.size() > 1) {
222 const auto& desc =
descs.at(0);
223 if (desc->IsRange()) {
228 std::vector<CScript> scripts;
236 if (scripts.size() == 1) {
238 }
else if (scripts.size() == 4) {
252 "generatetodescriptor",
253 "Mine to a specified descriptor and return the block hashes.",
266 "\nGenerate 11 blocks to mydesc\n" +
HelpExampleCli(
"generatetodescriptor",
"11 \"mydesc\"")},
272 CScript coinbase_output_script;
297 "Mine to a specified address and return the block hashes.",
309 "\nGenerate 11 blocks to myaddress\n"
311 +
"If you are using the " CLIENT_NAME " wallet, you can get a new address to send the newly generated bitcoin to with:\n"
338 "Mine a set of ordered transactions to a specified address or descriptor and return the block hash.\n"
339 "Transaction fees are not collected in the block reward.",
343 "Txids must reference transactions currently in the mempool.\n"
344 "All transactions must be valid and in valid order, otherwise the block will be rejected.",
359 "\nGenerate a block to myaddress, with txs rawtx and mempool_txid\n"
360 +
HelpExampleCli(
"generateblock", R
"("myaddress" '["rawtx", "mempool_txid"]')")
365 CScript coinbase_output_script;
381 std::vector<CTransactionRef>
txs;
388 const auto tx{mempool.
get(*txid)};
393 txs.emplace_back(tx);
410 std::unique_ptr<node::CBlockTemplate>
block_template{block_template_manager.
CreateNewTemplate({.use_mempool =
false, .coinbase_output_script = coinbase_output_script})};
419 block.
vtx.insert(block.
vtx.end(),
txs.begin(),
txs.end());
420 RegenerateCommitments(block, chainman);
450 "Returns a json object containing mining-related information.",
457 {
RPCResult::Type::NUM,
"currentblockweight",
true,
"The block weight (including reserved weight for block header, txs count and coinbase tx) of the last assembled block (only present if a block was ever assembled)"},
458 {
RPCResult::Type::NUM,
"currentblocktx",
true,
"The number of block transactions (excluding coinbase) of the last assembled block (only present if a block was ever assembled)"},
466 {
RPCResult::Type::STR_HEX,
"signet_challenge",
true,
"The block challenge (aka. block script), in hexadecimal (only present if the current network is a signet)"},
476 RPCResult{
RPCResult::Type::ARR,
"warnings",
"any network and blockchain warnings (run with `-deprecatedrpc=warnings` to return the latest warning as a single string)",
498 obj.pushKV(
"bestblockhash",
tip.GetBlockHash().GetHex());
505 obj.pushKV(
"pooledtx", mempool.
size());
518 obj.pushKV(
"next", next);
521 const std::vector<uint8_t>& signet_challenge =
523 obj.pushKV(
"signet_challenge",
HexStr(signet_challenge));
535 return RPCMethod{
"prioritisetransaction",
536 "Accepts the transaction into mined blocks at a higher (or lower) priority\n",
540 " DEPRECATED. For forward compatibility use named arguments and omit this parameter.",
543 " Note, that this value is not a fee rate. It is a value to modify absolute fee of the TX.\n"
544 " The fee is not actually paid, only the algorithm for selecting transactions into a block\n"
545 " considers the transaction as it would have paid a higher (or lower) fee."},
558 const auto dummy{
self.MaybeArg<
double>(
"dummy")};
561 if (dummy && *dummy != 0) {
568 const auto& tx = mempool.
get(txid);
581 return RPCMethod{
"getprioritisedtransactions",
582 "Returns a map of all user-created (see prioritisetransaction) fee deltas by txid, and whether the tx is present in mempool.",
590 {
RPCResult::Type::NUM,
"modified_fee",
true,
"modified fee in satoshis. Only returned if in_mempool=true"},
606 result_inner.pushKV(
"in_mempool", delta_info.in_mempool);
607 if (delta_info.in_mempool) {
608 result_inner.pushKV(
"modified_fee", *delta_info.modified_fee);
641 if (!gbt_optional_rule) {
642 s.insert(s.begin(),
'!');
651 "If the request parameters include a 'mode' key, that is used to explicitly select between the default 'template' request or a 'proposal'.\n"
652 "It returns data needed to construct a block to work on.\n"
653 "For full specification, see BIPs 22, 23, 9, and 145:\n"
654 " https://github.com/bitcoin/bips/blob/master/bip-0022.mediawiki\n"
655 " https://github.com/bitcoin/bips/blob/master/bip-0023.mediawiki\n"
656 " https://github.com/bitcoin/bips/blob/master/bip-0009.mediawiki#getblocktemplate_changes\n"
657 " https://github.com/bitcoin/bips/blob/master/bip-0145.mediawiki\n",
684 {
RPCResult::Type::STR,
"",
"name of a rule the client must understand to some extent; see BIP 9 for format"},
688 {
RPCResult::Type::NUM,
"rulename",
"identifies the bit number as indicating acceptance and readiness for the named softfork rule"},
694 {
RPCResult::Type::NUM,
"vbrequired",
"bit mask of versionbits the server requires set in submissions"},
696 {
RPCResult::Type::ARR,
"transactions",
"contents of non-coinbase transactions that should be included in the next block",
705 {
RPCResult::Type::NUM,
"",
"transactions before this one (by 1-based index in 'transactions' list) that must be present in the final block if this one is"},
707 {
RPCResult::Type::NUM,
"fee",
"difference in value between transaction inputs and outputs (in satoshis); for coinbase transactions, this is a negative Number of the total collected block fees (ie, not including the block subsidy); if key is not present, fee is unknown and clients MUST NOT assume there isn't one"},
708 {
RPCResult::Type::NUM,
"sigops",
"total SigOps cost, as counted for purposes of block limits; if key is not present, sigop cost is unknown and clients MUST NOT assume it is zero"},
709 {
RPCResult::Type::NUM,
"weight",
"total transaction weight, as counted for purposes of block limits"},
716 {
RPCResult::Type::NUM,
"coinbasevalue",
"maximum allowable input to coinbase transaction, including the generation award and transaction fees (in satoshis)"},
717 {
RPCResult::Type::STR,
"longpollid",
"an id to include with a request to longpoll on an update to this template"},
722 {
RPCResult::Type::STR,
"value",
"A way the block template may be changed, e.g. 'time', 'transactions', 'prevblock'"},
732 {
RPCResult::Type::STR_HEX,
"default_witness_commitment",
true,
"a valid witness commitment for the unmodified block template"},
745 std::string
strMode =
"template";
748 if (!request.params[0].isNull())
779 return "duplicate-invalid";
780 return "duplicate-inconclusive";
788 for (
unsigned int i = 0; i <
aClientRules.size(); ++i) {
816 if (!
lpval.isNull()) {
967 transactions.
push_back(std::move(entry));
988 aRules.push_back(
"!segwit");
989 aRules.push_back(
"taproot");
994 aRules.push_back(
"!signet");
1028 result.
pushKV(
"vbrequired", 0);
1031 result.
pushKV(
"transactions", std::move(transactions));
1032 result.
pushKV(
"coinbaseaux", std::move(aux));
1038 result.
pushKV(
"noncerange",
"00000000ffffffff");
1062 result.
pushKV(
"default_witness_commitment",
HexStr(
coinbase.required_outputs[0].scriptPubKey));
1075 "Attempts to submit new block to network.\n"
1076 "See https://en.bitcoin.it/wiki/BIP_0022 for full specification.\n",
1092 std::shared_ptr<CBlock>
blockptr = std::make_shared<CBlock>();
1094 if (!
DecodeHexBlk(block, request.params[0].get_str())) {
1108 auto sc = std::make_shared<node::BlockValidationStateCatcher>(block.
GetHash());
1116 return "inconclusive";
1127 "Decode the given hexdata as a header and submit it as a candidate chain tip if valid."
1128 "\nThrows when the header is invalid.\n",
1180 t.appendCommand(
c.name, &
c);
bool IsValidDestination(const CTxDestination &dest)
Check whether a CTxDestination corresponds to one with an address.
CScript GetScriptForDestination(const CTxDestination &dest)
Generate a Bitcoin scriptPubKey for the given CTxDestination.
std::variant< CNoDestination, PubKeyDestination, PKHash, ScriptHash, WitnessV0ScriptHash, WitnessV0KeyHash, WitnessV1Taproot, PayToAnchor, WitnessUnknown > CTxDestination
A txout script categorized into standard templates.
int64_t CAmount
Amount in satoshis (Can be negative)
double GetDifficulty(const CBlockIndex &blockindex)
Get the difficulty of the net wrt to the given block index.
@ BLOCK_VALID_SCRIPTS
Scripts & signatures ok.
@ BLOCK_FAILED_VALID
stage after last reached validness failed
const CChainParams & Params()
Return the currently selected parameters.
#define LIST_CHAIN_NAMES
List of possible chain / network names
#define CHECK_NONFATAL(condition)
Identity function.
std::vector< CTransactionRef > vtx
The block chain is a tree shaped structure starting with the genesis block at the root,...
bool IsValid(enum BlockStatus nUpTo) const EXCLUSIVE_LOCKS_REQUIRED(
Check whether this block index entry is valid up to the passed validity level.
int64_t GetBlockTime() const
int nHeight
height of the entry in the chain. The genesis block has height 0
An in-memory indexed chain of blocks.
std::string GetChainTypeString() const
Return the chain type string.
const Consensus::Params & GetConsensus() const
bool IsTestChain() const
If this chain is exclusively used for testing.
ChainType GetChainType() const
Return the chain type.
size_t GetNodeCount(ConnectionDirection) const EXCLUSIVE_LOCKS_REQUIRED(!m_nodes_mutex)
Serialized script, used inside transaction inputs and outputs.
The basic transaction that is broadcasted on the network and contained in blocks.
const Wtxid & GetWitnessHash() const LIFETIMEBOUND
const Txid & GetHash() const LIFETIMEBOUND
const std::vector< CTxIn > vin
An input of a transaction.
CTxMemPool stores valid-according-to-the-current-best-chain transactions that may be included in the ...
void PrioritiseTransaction(const Txid &hash, const CAmount &nFeeDelta)
Affect CreateNewBlock prioritisation of transactions.
CTransactionRef get(const Txid &hash) const
Return a mempool transaction with a given hash.
std::vector< delta_info > GetPrioritisedTransactions() const EXCLUSIVE_LOCKS_REQUIRED(!cs)
Return a vector of all entries in mapDeltas with their corresponding delta_info.
unsigned long size() const
unsigned int GetTransactionsUpdated() const
Interface for managing multiple Chainstate objects, where each chainstate is associated with chainsta...
bool IsInitialBlockDownload() const noexcept
Check whether we are doing an initial block download (synchronizing from disk or network)
RecursiveMutex & GetMutex() const LOCK_RETURNED(
Alias for cs_main.
Chainstate & ActiveChainstate() const
Alternatives to CurrentChainstate() used by older code to query latest chainstate information without...
bool ProcessNewBlock(const std::shared_ptr< const CBlock > &block, bool force_processing, bool min_pow_checked, bool *new_block) LOCKS_EXCLUDED(cs_main)
Process an incoming block.
const util::SignalInterrupt & m_interrupt
VersionBitsCache m_versionbitscache
Track versionbit status.
const CChainParams & GetParams() const
bool ProcessNewBlockHeaders(std::span< const CBlockHeader > headers, bool min_pow_checked, BlockValidationState &state, const CBlockIndex **ppindex=nullptr) LOCKS_EXCLUDED(cs_main)
Process incoming block headers.
const Consensus::Params & GetConsensus() const
CChain & ActiveChain() const EXCLUSIVE_LOCKS_REQUIRED(GetMutex())
void MaybeRebalanceCaches() EXCLUSIVE_LOCKS_REQUIRED(void UpdateUncommittedBlockStructures(CBlock &block, const CBlockIndex *pindexPrev) const
Check to see if caches are out of balance and if so, call ResizeCoinsCaches() as needed.
node::BlockManager m_blockman
A single BlockManager instance is shared across each constructed chainstate to avoid duplicating bloc...
Double ended buffer combining vector and stream-like interfaces.
void push_back(UniValue val)
const std::string & get_str() const
const UniValue & find_value(std::string_view key) const
const UniValue & get_obj() const
void pushKV(std::string key, UniValue val)
std::string GetRejectReason() const
std::string ToString() const
BIP9GBTStatus GBTStatus(const CBlockIndex &block_index, const Consensus::Params ¶ms) EXCLUSIVE_LOCKS_REQUIRED(!m_mutex)
256-bit unsigned big integer.
arith_uint256 & SetCompact(uint32_t nCompact, bool *pfNegative=nullptr, bool *pfOverflow=nullptr)
The "compact" format is a representation of a whole number N using an unsigned 32bit number similar t...
std::string GetHex() const
Generate a new block, without valid proof-of-work.
static std::optional< int64_t > m_last_block_num_txs
The number of transactions in the last assembled block (excluding coinbase transaction)
static std::optional< int64_t > m_last_block_weight
The weight of the last assembled block (including reserved weight for block header,...
CBlockIndex * LookupBlockIndex(const uint256 &hash) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
Creates block templates, submits solved blocks, and provides tip-waiting helpers for mining code.
std::optional< interfaces::BlockRef > WaitTipChanged(const uint256 ¤t_tip, MillisecondsDouble &timeout, bool &interrupt)
Wait for the tip to differ from current_tip or timeout.
std::unique_ptr< CBlockTemplate > CreateNewTemplate(const BlockCreateOptions &options)
Create a fresh block template, applying init-time defaults to any unset options.
std::optional< interfaces::BlockRef > GetTip()
Locks cs_main.
std::string GetHex() const
static transaction_identifier FromUint256(const uint256 &id)
static std::optional< transaction_identifier > FromHex(std::string_view hex)
static UniValue Parse(std::string_view raw, ParamFormat format=ParamFormat::JSON)
Parse string to UniValue or throw runtime_error if string contains invalid JSON.
auto lookup
Helper lookup function in the simulated cache stack.
uint256 BlockMerkleRoot(const CBlock &block, bool *mutated)
static int32_t GetTransactionWeight(const CTransaction &tx)
constexpr int64_t MAX_BLOCK_SIGOPS_COST
The maximum allowed number of signature check operations in a block (network rule)
constexpr unsigned int MAX_BLOCK_SERIALIZED_SIZE
The maximum allowed size for a serialized block, in bytes (only for buffer size limits)
constexpr unsigned int MAX_BLOCK_WEIGHT
The maximum allowed weight for a block, see BIP 141 (network rule)
constexpr int WITNESS_SCALE_FACTOR
std::string EncodeHexTx(const CTransaction &tx)
bool DecodeHexTx(CMutableTransaction &tx, const std::string &hex_tx, bool try_no_witness, bool try_witness)
bool DecodeHexBlockHeader(CBlockHeader &header, const std::string &hex_header)
bool DecodeHexBlk(CBlock &block, const std::string &strHexBlk)
UniValue ValueFromAmount(const CAmount amount)
RecursiveMutex cs_main
Mutex to guard access to validation specific variables, such as reading or changing the chainstate.
bool DeploymentActiveAfter(const CBlockIndex *pindexPrev, const Consensus::Params ¶ms, Consensus::BuriedDeployment dep, VersionBitsCache &versionbitscache)
Determine if a deployment is active for the next block.
const std::string CURRENCY_UNIT
std::string HexStr(const std::span< const uint8_t > s)
Convert a span of bytes to a lower-case hexadecimal string.
CTxDestination DecodeDestination(const std::string &str, std::string &error_msg, std::vector< int > *error_locations)
is used externally by mining IPC clients, so it should only declare simple data definitions.
void RegenerateCommitments(CBlock &block, ChainstateManager &chainman)
Update an old GenerateCoinbaseCommitment from CreateNewBlock after the block txs have changed.
int64_t UpdateTime(CBlockHeader *pblock, const Consensus::Params &consensusParams, const CBlockIndex *pindexPrev)
BlockCreateOptions FlattenMiningOptions(BlockCreateOptions options)
Replace null optional values with their hardcoded defaults.
int64_t GetMinimumTime(const CBlockIndex *pindexPrev, const int64_t difficulty_adjustment_interval)
Get the minimum time a miner should use in the next block.
UniValue GetWarningsForRpc(const Warnings &warnings, bool use_deprecated)
RPC helper function that wraps warnings.GetMessages().
std::string ToString(const T &t)
Locale-independent version of std::to_string.
std::vector< uint32_t > GetDust(const CTransaction &tx, CFeeRate dust_relay_rate)
Get the vout index numbers of all dust outputs.
bool CheckProofOfWork(uint256 hash, unsigned int nBits, const Consensus::Params ¶ms)
Check whether a block hash satisfies the proof-of-work requirement specified by nBits.
constexpr TransactionSerParams TX_WITH_WITNESS
static CTransactionRef MakeTransactionRef(Tx &&txIn)
UniValue JSONRPCError(int code, const std::string &message)
static RPCMethod getblocktemplate()
static UniValue GetNetworkHashPS(int lookup, int height, const CChain &active_chain)
Return average network hashes per second based on the last 'lookup' blocks, or from the last difficul...
static RPCMethod getmininginfo()
static bool getScriptFromDescriptor(std::string_view descriptor, CScript &script, std::string &error)
static std::string gbt_rule_value(const std::string &name, bool gbt_optional_rule)
static RPCMethod submitblock()
static UniValue BIP22ValidationResult(const BlockValidationState &state)
static RPCMethod getprioritisedtransactions()
static RPCMethod generatetodescriptor()
static RPCMethod generate()
static UniValue generateBlocks(ChainstateManager &chainman, node::BlockTemplateManager &block_template_manager, const CScript &coinbase_output_script, int nGenerate, uint64_t nMaxTries)
static RPCMethod generateblock()
static RPCMethod prioritisetransaction()
static bool GenerateBlock(ChainstateManager &chainman, CBlock &&block, uint64_t &max_tries, std::shared_ptr< const CBlock > &block_out, bool process_new_block)
static RPCMethod generatetoaddress()
static RPCMethod getnetworkhashps()
void RegisterMiningRPCCommands(CRPCTable &t)
static RPCMethod submitheader()
constexpr uint64_t DEFAULT_MAX_TRIES
Default max iterations to try in RPC generatetodescriptor, generatetoaddress, and generateblock.
@ RPC_MISC_ERROR
General application defined errors.
@ RPC_TYPE_ERROR
Unexpected type was passed as parameter.
@ RPC_CLIENT_NOT_CONNECTED
P2P client errors.
@ RPC_INVALID_PARAMETER
Invalid, missing or duplicate parameter.
@ RPC_VERIFY_ERROR
General error during transaction or block submission.
@ RPC_CLIENT_IN_INITIAL_DOWNLOAD
Still downloading initial blocks.
@ RPC_DESERIALIZATION_ERROR
Error parsing or validating structure in raw format.
@ RPC_INVALID_ADDRESS_OR_KEY
Invalid address or key.
std::string HelpExampleCli(const std::string &methodname, const std::string &args)
uint256 GetTarget(const CBlockIndex &blockindex, const uint256 pow_limit)
std::string HelpExampleRpc(const std::string &methodname, const std::string &args)
const std::string UNIX_EPOCH_TIME
String used to describe UNIX epoch time in documentation, factored out to a constant for consistency.
uint256 ParseHashV(const UniValue &v, std::string_view name)
Utilities: convert hex-encoded Values (throws error if not hex).
bool IsDeprecatedRPCEnabled(const std::string &method)
bool IsRPCRunning()
Query whether RPC is running.
ChainstateManager & EnsureAnyChainman(const std::any &context)
void NextEmptyBlockIndex(CBlockIndex &tip, const Consensus::Params &consensusParams, CBlockIndex &next_index)
Return an empty block index on top of the tip, with height, time and nBits set.
NodeContext & EnsureAnyNodeContext(const std::any &context)
CTxMemPool & EnsureMemPool(const NodeContext &node)
ChainstateManager & EnsureChainman(const NodeContext &node)
node::BlockTemplateManager & EnsureBlockTemplateManager(const NodeContext &node)
CTxMemPool & EnsureAnyMemPool(const std::any &context)
CConnman & EnsureConnman(const NodeContext &node)
A mutable version of CTransaction.
Parameters that influence chain consensus.
std::vector< uint8_t > signet_challenge
int64_t DifficultyAdjustmentInterval() const
uint256 powLimit
Proof of work parameters.
@ STR_HEX
Special type that is a STR with only hex chars.
std::string DefaultHint
Hint for default value.
@ OMITTED
Optional argument for which the default value is omitted from help text for one of two reasons:
bool placeholder
If set, the argument is retained only for compatibility and should generally be omitted.
@ NUM_TIME
Special numeric to denote unix epoch time.
@ OBJ_DYN
Special dictionary with keys that are not literals.
@ STR_HEX
Special string with only hex chars.
@ STR_AMOUNT
Special string to represent a floating point amount.
Hash/height pair to help track and identify blocks.
ValidationSignals * signals
CFeeRate dust_relay_feerate
NodeContext struct containing references to chain state and connection state.
#define WAIT_LOCK(cs, name)
#define REVERSE_LOCK(g, cs)
FuzzedDataProvider provider
const UniValue NullUniValue
int64_t GetTime()
DEPRECATED Use either ClockType::now() or Now<TimePointType>() if a cast is needed.
std::chrono::duration< double, std::chrono::milliseconds::period > MillisecondsDouble
constexpr auto Ticks(Dur2 d)
Helper to count the seconds of a duration/time_point.
BlockValidationState TestBlockValidity(Chainstate &chainstate, const CBlock &block, const bool check_pow, const bool check_merkle_root)
Verify a block, including transactions.