10#include <chainparams.h>
68 if (
pb ==
nullptr || !
pb->nHeight) {
87 for (
int i = 0; i <
lookup; i++) {
91 maxTime = std::max(time, maxTime);
109 "Returns the estimated network hashes per second based on the last n "
111 "Pass in [blocks] to override # of blocks, -1 specifies since last "
112 "difficulty change.\n"
113 "Pass in [height] to estimate the network speed at the time when a "
114 "certain block was found.\n",
117 "The number of blocks, or -1 for blocks since last difficulty "
120 "To estimate at the time of the given height."},
130 !request.params[0].isNull() ? request.params[0].getInt<
int>()
132 !request.params[1].isNull() ? request.params[1].getInt<
int>()
148 block.
nNonce < std::numeric_limits<uint32_t>::max() &&
157 if (block.
nNonce == std::numeric_limits<uint32_t>::max()) {
162 std::make_shared<const CBlock>(block);
168 "ProcessNewBlock, block not accepted");
182 std::unique_ptr<CBlockTemplate> pblocktemplate(
187 if (!pblocktemplate.get()) {
199 if (!block_hash.
IsNull()) {
217 if (
desc->IsRange()) {
219 "Ranged descriptor not accepted. Maybe pass "
220 "through deriveaddresses first?");
224 std::vector<CScript> scripts;
228 strprintf(
"Cannot derive script without private keys"));
235 if (scripts.size() == 1) {
236 script = scripts.at(0);
239 script = scripts.at(1);
250 "generatetodescriptor",
251 "Mine blocks immediately to a specified descriptor (before the RPC "
255 "How many blocks are generated immediately."},
257 "The descriptor to send the newly generated bitcoin to."},
259 "How many iterations to try."},
263 "hashes of blocks generated",
274 : request.params[2].getInt<
int>()};
295 "has been replaced by the -generate cli option. Refer to "
296 "-help for more information.",
310 "Mine blocks immediately to a specified address before the "
311 "RPC call returns)\n",
314 "How many blocks are generated immediately."},
316 "The address to send the newly generated bitcoin to."},
318 "How many iterations to try."},
322 "hashes of blocks generated",
327 "\nGenerate 11 blocks to myaddress\n" +
329 "If you are using the " PACKAGE_NAME " wallet, you can "
330 "get a new address to send the newly generated bitcoin to with:\n" +
337 : request.params[2].getInt<
int64_t>()};
340 request.params[1].get_str(), config.GetChainParams());
343 "Error: Invalid address");
361 "Mine a block with a set of ordered transactions immediately to a "
362 "specified address or descriptor (before the RPC call returns)\n",
365 "The address or descriptor to send the newly generated bitcoin "
371 "An array of hex strings which are either txids or raw "
373 "Txids must reference transactions currently in the mempool.\n"
374 "All transactions must be valid and in valid order, otherwise "
375 "the block will be rejected.",
390 "\nGenerate a block to myaddress, with txs rawtx and "
393 R
"("myaddress" '["rawtx", "mempool_txid"]')")},
400 const CChainParams &chainparams = config.GetChainParams();
404 const auto destination =
408 "Error: Invalid address or descriptor");
417 std::vector<CTransactionRef>
txs;
425 const auto tx = mempool.
get(
TxId(hash));
429 strprintf(
"Transaction %s not in mempool.", str));
432 txs.emplace_back(tx);
439 strprintf(
"Transaction decode failed for %s", str));
451 node.avalanche.get()}
455 "Couldn't create new block");
463 block.
vtx.insert(block.
vtx.end(),
txs.begin(),
txs.end());
476 .withCheckMerkleRoot(
false))) {
478 strprintf(
"TestBlockValidity failed: %s",
505 "Returns a json object containing mining-related "
515 "The block size of the last assembled block (only present if "
516 "a block was ever assembled)"},
518 "The number of block transactions of the last assembled block "
519 "(only present if a block was ever assembled)"},
522 "The network hashes per second"},
525 "current network name (main, test, regtest)"},
527 "any network and blockchain warnings"},
542 obj.pushKV(
"currentblocksize",
546 obj.pushKV(
"currentblocktx",
550 obj.pushKV(
"networkhashps",
553 obj.pushKV(
"chain", config.GetChainParams().NetworkIDString());
564 "prioritisetransaction",
565 "Accepts the transaction into mined blocks at a higher "
566 "(or lower) priority\n",
569 "The transaction id."},
571 "API-Compatibility for previous API. Must be zero or null.\n"
572 " DEPRECATED. For forward compatibility "
573 "use named arguments and omit this parameter."},
575 "The fee value (in satoshis) to add (or subtract, if negative).\n"
576 " The fee is not actually paid, only the "
577 "algorithm for selecting transactions into a block\n"
578 " considers the transaction as it would "
579 "have paid a higher (or lower) fee."},
592 if (!(request.params[1].isNull() ||
593 request.params[1].get_real() == 0)) {
596 "Priority is no longer supported, dummy argument to "
597 "prioritisetransaction must be 0.");
634 "If the request parameters include a 'mode' key, that is used to "
635 "explicitly select between the default 'template' request or a "
637 "It returns data needed to construct a block to work on.\n"
638 "For full specification, see BIPs 22, 23, 9, and 145:\n"
640 "https://github.com/bitcoin/bips/blob/master/"
641 "bip-0022.mediawiki\n"
643 "https://github.com/bitcoin/bips/blob/master/"
644 "bip-0023.mediawiki\n"
646 "https://github.com/bitcoin/bips/blob/master/"
647 "bip-0009.mediawiki#getblocktemplate_changes\n"
653 "Format of the template",
657 "This must be set to \"template\", \"proposal\" (see BIP "
668 "client side supported feature, 'longpoll', "
669 "'coinbasetxn', 'coinbasevalue', 'proposal', "
670 "'serverlist', 'workid'"},
677 RPCResult{
"If the proposal was accepted with mode=='proposal'",
679 RPCResult{
"If the proposal was not accepted with mode=='proposal'",
688 "The preferred block version"},
690 "The hash of current highest block"},
693 "contents of non-coinbase transactions that should be "
694 "included in the next block",
701 "transaction data encoded in hexadecimal "
704 "transaction id encoded in little-endian "
707 "hash encoded in little-endian hexadecimal"},
713 "transactions before this one (by 1-based "
714 "index in 'transactions' list) that must "
715 "be present in the final block if this one "
719 "difference in value between transaction inputs "
720 "and outputs (in satoshis); for coinbase "
721 "transactions, this is a negative Number of the "
722 "total collected block fees (ie, not including "
723 "the block subsidy); "
724 "if key is not present, fee is unknown and "
725 "clients MUST NOT assume there isn't one"},
727 "total sigChecks, as counted for purposes of "
728 "block limits; if key is not present, sigChecks "
729 "are unknown and clients MUST NOT assume it is "
735 "data that should be included in the coinbase's scriptSig "
741 "maximum allowable input to coinbase transaction, "
742 "including the generation award and transaction fees (in "
746 "information for coinbase transaction",
750 "information related to the coinbase miner fund",
755 "List of valid addresses for the miner fund "
762 "The minimum value the miner fund output must "
768 "information related to the coinbase staking reward "
769 "output, only set after the Nov. 15, 2023 upgrade "
770 "activated and the -avalanchestakingrewards option "
776 "The proof payout script",
779 "Decoded payout script"},
781 "Raw payout script in hex format"},
783 "The output type (e.g. " +
786 "The required signatures"},
796 "The minimum value the staking reward output "
803 "The minimum timestamp appropriate for the next block "
804 "time, expressed in " +
808 "list of ways the block template may be changed",
811 "A way the block template may be changed, e.g. "
812 "'time', 'transactions', 'prevblock'"},
815 "A range of valid nonces"},
817 "limit of sigChecks in blocks"},
822 "compressed target of next block"},
824 "The height of the next block"},
827 "The real-time target parameters. Only present after the "
828 "Nov. 15, 2024 upgrade activated and if -enablertt is set",
832 "The time the preview block headers were received, "
835 ". Contains 4 values for headers at height N-2, "
836 "N-5, N-11 and N-17.",
839 "The time the block header was received, "
844 "The previous block compressed target"},
848 "The real-time target in compact format"},
860 const CChainParams &chainparams = config.GetChainParams();
862 std::string
strMode =
"template";
867 if (!request.params[0].isNull()) {
884 "Missing data String key for proposal");
890 "Block decode failed");
900 if (pindex->nStatus.isInvalid()) {
901 return "duplicate-invalid";
903 return "duplicate-inconclusive";
910 return "inconclusive-not-best-prevblk";
917 .withCheckMerkleRoot(
true));
929 "Bitcoin is not connected!");
935 " is in initial sync and waiting for blocks...");
944 if (!
lpval.isNull()) {
980 std::cv_status::timeout) {
1018 static std::unique_ptr<CBlockTemplate> pblocktemplate;
1035 &mempool,
node.avalanche.get()}
1037 if (!pblocktemplate) {
1056 aCaps.push_back(
"proposal");
1063 for (
const auto &it :
pblock->vtx) {
1070 for (
const auto &
o :
pblock->vtx[0]->vout) {
1118 if (
node.avalanche &&
1120 node.avalanche->getStakingRewardWinners(
1141 aMutable.push_back(
"transactions");
1149 result.
pushKV(
"previousblockhash",
pblock->hashPrevBlock.GetHex());
1154 result.
pushKV(
"longpollid",
1161 result.
pushKV(
"noncerange",
"00000000ffffffff");
1174 (
pblock->GetBlockTime() <=
1187 for (
size_t i = 1; i < 18; i++) {
1202 for (
size_t i : {2, 5, 11, 17}) {
1244 "Attempts to submit new block to network.\n"
1245 "See https://en.bitcoin.it/wiki/BIP_0022 for full specification.\n",
1248 "the hex-encoded block data to submit"},
1250 "dummy value, for compatibility with BIP22. This value is "
1257 "According to BIP22"},
1263 std::shared_ptr<CBlock>
blockptr = std::make_shared<CBlock>();
1265 if (!
DecodeHexBlk(block, request.params[0].get_str())) {
1267 "Block decode failed");
1270 if (block.
vtx.empty() || !block.
vtx[0]->IsCoinBase()) {
1272 "Block does not start with a coinbase");
1286 if (pindex->nStatus.isInvalid()) {
1287 return "duplicate-invalid";
1294 std::make_shared<submitblock_StateCatcher>(block.
GetHash());
1300 node.avalanche.get());
1307 return "inconclusive";
1321 "Decode the given hexdata as a header and submit it as a candidate "
1322 "chain tip if valid."
1323 "\nThrows when the header is invalid.\n",
1326 "the hex-encoded block header data"},
1336 "Block header decode failed");
1343 "Must submit previous header (" +
1344 h.hashPrevBlock.GetHex() +
1366 "Estimates the approximate fee per kilobyte needed for a "
1400 for (
const auto &
c : commands) {
1401 t.appendCommand(
c.name, &
c);
static bool IsAxionEnabled(const Consensus::Params ¶ms, int32_t nHeight)
static constexpr Amount SATOSHI
double GetDifficulty(const CBlockIndex *blockindex)
Calculate the difficulty for a given block index.
@ SCRIPTS
Scripts & signatures ok.
const CChainParams & Params()
Return the currently selected parameters.
#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 BlockValidity nUpTo=BlockValidity::TRANSACTIONS) const EXCLUSIVE_LOCKS_REQUIRED(
Check whether this block index entry is valid up to the passed validity level.
int64_t GetBlockTime() const
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.
CChainParams defines various tweakable parameters of a given instance of the Bitcoin system.
const Consensus::Params & GetConsensus() const
bool MineBlocksOnDemand() const
Whether it is possible to mine blocks on demand (no retargeting)
size_t GetNodeCount(ConnectionDirection) const
Amount GetFeePerK() const
Return the fee in satoshis for a size of 1000 bytes.
A mutable version of CTransaction.
Serialized script, used inside transaction inputs and outputs.
The basic transaction that is broadcasted on the network and contained in blocks.
const TxHash GetHash() const
CTxMemPool stores valid-according-to-the-current-best-chain transactions that may be included in the ...
CFeeRate estimateFee() const
CTransactionRef get(const TxId &txid) const
void PrioritiseTransaction(const TxId &txid, const Amount nFeeDelta)
Affect CreateNewBlock prioritisation of transactions.
unsigned long size() const
unsigned int GetTransactionsUpdated() const
Implement this to subscribe to events generated in validation.
Chainstate stores and provides an API to update our local knowledge of the current best chain.
Provides an interface for creating and interacting with one or two chainstates: an IBD chainstate gen...
const Config & GetConfig() const
bool ProcessNewBlock(const std::shared_ptr< const CBlock > &block, bool force_processing, bool min_pow_checked, bool *new_block, avalanche::Processor *const avalanche=nullptr) LOCKS_EXCLUDED(cs_main)
Process an incoming block.
SnapshotCompletionResult MaybeCompleteSnapshotValidation(std::function< void(bilingual_str)> shutdown_fnc=[](bilingual_str msg) { AbortNode(msg.original, msg);}) EXCLUSIVE_LOCKS_REQUIRED(Chainstate & ActiveChainstate() const
Once the background validation chainstate has reached the height which is the base of the UTXO snapsh...
bool ProcessNewBlockHeaders(const std::vector< CBlockHeader > &block, bool min_pow_checked, BlockValidationState &state, const CBlockIndex **ppindex=nullptr, const std::optional< CCheckpointData > &test_checkpoints=std::nullopt) LOCKS_EXCLUDED(cs_main)
Process incoming block headers.
const Consensus::Params & GetConsensus() const
CChain & ActiveChain() const EXCLUSIVE_LOCKS_REQUIRED(GetMutex())
node::BlockManager m_blockman
A single BlockManager instance is shared across each constructed chainstate to avoid duplicating bloc...
const std::string & get_str() const
const UniValue & find_value(std::string_view key) const
const UniValue & get_obj() const
void pushKVEnd(std::string key, UniValue val)
void pushKV(std::string key, UniValue val)
std::string GetRejectReason() const
std::string ToString() const
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_size
static std::optional< int64_t > m_last_block_num_txs
CBlockIndex * LookupBlockIndex(const BlockHash &hash) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
void BlockChecked(const CBlock &block, const BlockValidationState &stateIn) override
Notifies listeners of a block validation result.
submitblock_StateCatcher(const uint256 &hashIn)
BlockValidationState state
static UniValue Parse(std::string_view raw)
Parse string to UniValue or throw runtime_error if string contains invalid JSON.
static const uint64_t DEFAULT_MAX_BLOCK_SIZE
Default setting for maximum allowed size for a block, in bytes.
uint64_t GetMaxBlockSigChecksCount(uint64_t maxBlockSize)
Compute the maximum number of sigchecks that can be contained in a block given the MAXIMUM block size...
void ScriptPubKeyToUniv(const CScript &scriptPubKey, UniValue &out, bool fIncludeHex)
bool DecodeHexTx(CMutableTransaction &tx, const std::string &strHexTx)
bool DecodeHexBlk(CBlock &, const std::string &strHexBlk)
bool ParseHashStr(const std::string &strHex, uint256 &result)
Parse a hex string into 256 bits.
bool DecodeHexBlockHeader(CBlockHeader &, const std::string &hex_header)
std::string EncodeHexTx(const CTransaction &tx, const int serializeFlags=0)
RecursiveMutex cs_main
Mutex to guard access to validation specific variables, such as reading or changing the chainstate.
std::string EncodeDestination(const CTxDestination &dest, const Config &config)
CTxDestination DecodeDestination(const std::string &addr, const CChainParams ¶ms)
bool error(const char *fmt, const Args &...args)
uint256 BlockMerkleRoot(const CBlock &block, bool *mutated)
Compute the Merkle root of the transactions in a block.
std::unordered_set< CTxDestination, TxDestinationHasher > GetMinerFundWhitelist(const Consensus::Params ¶ms)
Amount GetMinerFundAmount(const Consensus::Params ¶ms, const Amount &coinbaseValue, const CBlockIndex *pprev)
static RPCHelpMan estimatefee()
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 RPCHelpMan generateblock()
static RPCHelpMan generatetodescriptor()
static bool getScriptFromDescriptor(const std::string &descriptor, CScript &script, std::string &error)
static UniValue BIP22ValidationResult(const Config &config, const BlockValidationState &state)
static RPCHelpMan getnetworkhashps()
static RPCHelpMan submitblock()
static RPCHelpMan getblocktemplate()
static RPCHelpMan generate()
static RPCHelpMan submitheader()
static RPCHelpMan prioritisetransaction()
static bool GenerateBlock(ChainstateManager &chainman, avalanche::Processor *const avalanche, CBlock &block, uint64_t &max_tries, BlockHash &block_hash)
static UniValue generateBlocks(ChainstateManager &chainman, const CTxMemPool &mempool, avalanche::Processor *const avalanche, const CScript &coinbase_script, int nGenerate, uint64_t nMaxTries)
static RPCHelpMan getmininginfo()
static RPCHelpMan generatetoaddress()
void RegisterMiningRPCCommands(CRPCTable &t)
static const uint64_t DEFAULT_MAX_TRIES
Default max iterations to try in RPC generatetodescriptor, generatetoaddress, and generateblock.
int64_t UpdateTime(CBlockHeader *pblock, const CChainParams &chainParams, const CBlockIndex *pindexPrev, int64_t adjustedTime)
bool CheckProofOfWork(const BlockHash &hash, uint32_t nBits, const Consensus::Params ¶ms)
Check whether a block hash satisfies the proof-of-work requirement specified by nBits.
static CTransactionRef MakeTransactionRef()
T GetRand(T nMax=std::numeric_limits< T >::max()) noexcept
Generate a uniform random integer of type T in the range [0..nMax) nMax defaults to std::numeric_limi...
UniValue JSONRPCError(int code, const std::string &message)
@ RPC_OUT_OF_MEMORY
Ran out of memory during operation.
@ RPC_MISC_ERROR
General application defined errors std::exception thrown in command handling.
@ RPC_TYPE_ERROR
Unexpected type was passed as parameter.
@ RPC_CLIENT_NOT_CONNECTED
P2P client errors Bitcoin is not connected.
@ 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)
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.
std::string GetAllOutputTypes()
uint256 ParseHashV(const UniValue &v, std::string strName)
Utilities: convert hex-encoded values (throws error if not hex).
std::optional< uint32_t > GetNextRTTWorkRequired(const CBlockIndex *pprev, int64_t now, const Consensus::Params &consensusParams)
Compute the real time block hash target given the previous block parameters.
bool isRTTEnabled(const Consensus::Params ¶ms, const CBlockIndex *pprev)
Whether the RTT feature is enabled.
static std::string ToString(const CService &ip)
bool IsRPCRunning()
Query whether RPC is running.
ChainstateManager & EnsureAnyChainman(const std::any &context)
NodeContext & EnsureAnyNodeContext(const std::any &context)
CTxMemPool & EnsureMemPool(const NodeContext &node)
ChainstateManager & EnsureChainman(const NodeContext &node)
CTxMemPool & EnsureAnyMemPool(const std::any &context)
CConnman & EnsureConnman(const NodeContext &node)
bool ShutdownRequested()
Returns true if a shutdown is requested, false otherwise.
bool IsStakingRewardsActivated(const Consensus::Params ¶ms, const CBlockIndex *pprev)
Amount GetStakingRewardsAmount(const Amount &coinbaseValue)
bool IsValidDestination(const CTxDestination &dest)
Check whether a CTxDestination is a CNoDestination.
CScript GetScriptForDestination(const CTxDestination &dest)
Generate a Bitcoin scriptPubKey for the given CTxDestination.
std::variant< CNoDestination, PKHash, ScriptHash > CTxDestination
A txout script template with a specific destination.
static constexpr Amount zero() noexcept
A BlockHash is a unqiue identifier for a block.
Parameters that influence chain consensus.
int64_t DifficultyAdjustmentInterval() const
@ STR_HEX
Special type that is a STR with only hex chars.
@ OMITTED
The arg is optional for one of two reasons:
std::string oneline_description
Should be empty unless it is supposed to override the auto-generated summary line.
@ ELISION
Special type to denote elision (...)
@ NUM_TIME
Special numeric to denote unix epoch time.
@ STR_HEX
Special string with only hex chars.
@ STR_AMOUNT
Special string to represent a floating point amount.
A TxId is the identifier of a transaction.
NodeContext struct containing references to chain state and connection state.
#define WAIT_LOCK(cs, name)
#define ENTER_CRITICAL_SECTION(cs)
#define LEAVE_CRITICAL_SECTION(cs)
int64_t GetTime()
DEPRECATED Use either ClockType::now() or Now<TimePointType>() if a cast is needed.
NodeClock::time_point GetAdjustedTime()
const UniValue NullUniValue
int64_t atoi64(const std::string &str)
GlobalMutex g_best_block_mutex
std::condition_variable g_best_block_cv
const CBlockIndex * g_best_block
Used to notify getblocktemplate RPC of new tips.
bool ContextualCheckTransactionForCurrentBlock(const CBlockIndex &active_chain_tip, const Consensus::Params ¶ms, const CTransaction &tx, TxValidationState &state) EXCLUSIVE_LOCKS_REQUIRED(bool TestBlockValidity(BlockValidationState &state, const CChainParams ¶ms, Chainstate &chainstate, const CBlock &block, CBlockIndex *pindexPrev, const std::function< NodeClock::time_point()> &adjusted_time_callback, BlockValidationOptions validationOptions) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
This is a variant of ContextualCheckTransaction which computes the contextual check for a transaction...
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.