Inside Bitcoin
Opening the selected file…
Inside Bitcoin
Opening the selected file…
The code behind the network, with room to understand it.
Release published 2026-10-28 · Snapshot fetched 2026-11-01. Latest stable release at fetch time; development branches and Git history are excluded. Only the selected code window and visible folders load here.
751if (modeval.isStr())752strMode = modeval.get_str();753else if (modeval.isNull())754{755/* Do nothing */756}757else758throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid mode");759lpval = oparam.find_value("longpollid");761if (strMode == "proposal")762{763const UniValue& dataval = oparam.find_value("data");764if (!dataval.isStr())765throw JSONRPCError(RPC_TYPE_ERROR, "Missing data String key for proposal");767CBlock block;768if (!DecodeHexBlk(block, dataval.get_str()))769throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "Block decode failed");771uint256 hash = block.GetHash();772LOCK(cs_main);773const CBlockIndex* pindex = chainman.m_blockman.LookupBlockIndex(hash);774if (pindex) {775if (pindex->IsValid(BLOCK_VALID_SCRIPTS))776return "duplicate";777if (pindex->nStatus & BLOCK_FAILED_VALID)778return "duplicate-invalid";779return "duplicate-inconclusive";780}782return BIP22ValidationResult(TestBlockValidity(chainman.ActiveChainstate(), block, /*check_pow=*/false, /*check_merkle_root=*/true));783}785const UniValue& aClientRules = oparam.find_value("rules");786if (aClientRules.isArray()) {787for (unsigned int i = 0; i < aClientRules.size(); ++i) {788const UniValue& v = aClientRules[i];789setClientRules.insert(v.get_str());790}791}792}794if (strMode != "template")795throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid mode");797if (!miner.isTestChain()) {798const CConnman& connman = EnsureConnman(node);799if (connman.GetNodeCount(ConnectionDirection::Both) == 0) {800throw JSONRPCError(RPC_CLIENT_NOT_CONNECTED, CLIENT_NAME " is not connected!");801}803if (miner.isInitialBlockDownload()) {804throw JSONRPCError(RPC_CLIENT_IN_INITIAL_DOWNLOAD, CLIENT_NAME " is in initial sync and waiting for blocks...");805}806}808static unsigned int nTransactionsUpdatedLast;809const CTxMemPool& mempool = EnsureMemPool(node);811WAIT_LOCK(cs_main, cs_main_lock);812uint256 tip{CHECK_NONFATAL(miner.getTip()).value().hash};814// Long Polling (BIP22)815if (!lpval.isNull()) {816/**817* Wait to respond until either the best block changes, OR there are more818* transactions.819*820* The check for new transactions first happens after 1 minute and821* subsequently every 10 seconds. BIP22 does not require this particular interval.822* On mainnet the mempool changes frequently enough that in practice this RPC823* returns after 60 seconds, or sooner if the best block changes.824*825* getblocktemplate is unlikely to be called by bitcoin-cli, so826* -rpcclienttimeout is not a concern. BIP22 recommends a long request timeout.827*828* The longpollid is assumed to be a tip hash if it has the right format.829*/830uint256 hashWatchedChain;831unsigned int nTransactionsUpdatedLastLP;833if (lpval.isStr())834{835// Format: <hashBestChain><nTransactionsUpdatedLast>836const std::string& lpstr = lpval.get_str();838// Assume the longpollid is a block hash. If it's not then we return839// early below.840hashWatchedChain = ParseHashV(lpstr.substr(0, 64), "longpollid");841nTransactionsUpdatedLastLP = LocaleIndependentAtoi<int64_t>(lpstr.substr(64));842}843else844{845// NOTE: Spec does not specify behaviour for non-string longpollid, but this makes testing easier846hashWatchedChain = tip;847nTransactionsUpdatedLastLP = nTransactionsUpdatedLast;848}850// Release lock while waiting851{852REVERSE_LOCK(cs_main_lock, cs_main);853MillisecondsDouble checktxtime{std::chrono::minutes(1)};854while (IsRPCRunning()) {855// If hashWatchedChain is not a real block hash, this will856// return immediately.857std::optional<BlockRef> maybe_tip{miner.waitTipChanged(hashWatchedChain, checktxtime)};858// Node is shutting down859if (!maybe_tip) break;860tip = maybe_tip->hash;861if (tip != hashWatchedChain) break;863// Check transactions for update without holding the mempool864// lock to avoid deadlocks.865if (mempool.GetTransactionsUpdated() != nTransactionsUpdatedLastLP) {866break;867}868checktxtime = std::chrono::seconds(10);869}870}871tip = CHECK_NONFATAL(miner.getTip()).value().hash;873if (!IsRPCRunning())874throw JSONRPCError(RPC_CLIENT_NOT_CONNECTED, "Shutting down");875// TODO: Maybe recheck connections/IBD and (if something wrong) send an expires-immediately template to stop miners?876}878const Consensus::Params& consensusParams = chainman.GetParams().GetConsensus();880// GBT must be called with 'signet' set in the rules for signet chains881if (consensusParams.signet_blocks && !setClientRules.contains("signet")) {882throw JSONRPCError(RPC_INVALID_PARAMETER, "getblocktemplate must be called with the signet rule set (call with {\"rules\": [\"segwit\", \"signet\"]})");883}885// GBT must be called with 'segwit' set in the rules886if (!setClientRules.contains("segwit")) {887throw JSONRPCError(RPC_INVALID_PARAMETER, "getblocktemplate must be called with the segwit rule set (call with {\"rules\": [\"segwit\"]})");888}890// Update block891static CBlockIndex* pindexPrev;892static int64_t time_start;893static std::unique_ptr<BlockTemplate> block_template;894if (!pindexPrev || pindexPrev->GetBlockHash() != tip ||895(mempool.GetTransactionsUpdated() != nTransactionsUpdatedLast && GetTime() - time_start > 5))896{897// Clear pindexPrev so future calls make a new block, despite any failures from here on898pindexPrev = nullptr;900// Store the pindexBest used before createNewBlock, to avoid races901nTransactionsUpdatedLast = mempool.GetTransactionsUpdated();902CBlockIndex* pindexPrevNew = chainman.m_blockman.LookupBlockIndex(tip);903time_start = GetTime();905// Create new block. Opt-out of cooldown mechanism, because it would add906// a delay to each getblocktemplate call. This differs from typical907// long-lived IPC usage, where the overhead is paid only when creating908// the initial template.909block_template = miner.createNewBlock({}, /*cooldown=*/false);910CHECK_NONFATAL(block_template);913// Need to update only after we know createNewBlock succeeded914pindexPrev = pindexPrevNew;915}916CHECK_NONFATAL(pindexPrev);917CBlock block{block_template->getBlock()};919// Update nTime920UpdateTime(&block, consensusParams, pindexPrev);921block.nNonce = 0;923// NOTE: If at some point we support pre-segwit miners post-segwit-activation, this needs to take segwit support into consideration924const bool fPreSegWit = !DeploymentActiveAfter(pindexPrev, chainman, Consensus::DEPLOYMENT_SEGWIT);926UniValue aCaps(UniValue::VARR); aCaps.push_back("proposal");928UniValue transactions(UniValue::VARR);929std::map<Txid, int64_t> setTxIndex;930std::vector<CAmount> tx_fees{block_template->getTxFees()};931std::vector<int64_t> tx_sigops{block_template->getTxSigops()};933int i = 0;934for (const auto& it : block.vtx) {935const CTransaction& tx = *it;936Txid txHash = tx.GetHash();937setTxIndex[txHash] = i++;939if (tx.IsCoinBase())940continue;942UniValue entry(UniValue::VOBJ);944entry.pushKV("data", EncodeHexTx(tx));945entry.pushKV("txid", txHash.GetHex());946entry.pushKV("hash", tx.GetWitnessHash().GetHex());948UniValue deps(UniValue::VARR);949for (const CTxIn &in : tx.vin)950{951if (setTxIndex.contains(in.prevout.hash))952deps.push_back(setTxIndex[in.prevout.hash]);953}954entry.pushKV("depends", std::move(deps));956int index_in_template = i - 2;957entry.pushKV("fee", tx_fees.at(index_in_template));958int64_t nTxSigOps{tx_sigops.at(index_in_template)};959if (fPreSegWit) {960CHECK_NONFATAL(nTxSigOps % WITNESS_SCALE_FACTOR == 0);961nTxSigOps /= WITNESS_SCALE_FACTOR;962}963entry.pushKV("sigops", nTxSigOps);964entry.pushKV("weight", GetTransactionWeight(tx));966transactions.push_back(std::move(entry));967}969UniValue aux(UniValue::VOBJ);971arith_uint256 hashTarget = arith_uint256().SetCompact(block.nBits);973UniValue aMutable(UniValue::VARR);974aMutable.push_back("time");975aMutable.push_back("transactions");976aMutable.push_back("prevblock");978UniValue result(UniValue::VOBJ);979result.pushKV("capabilities", std::move(aCaps));981UniValue aRules(UniValue::VARR);982// See getblocktemplate changes in BIP 9:983// ! indicates a more subtle change to the block structure or generation transaction984// Otherwise clients may assume the rule will not impact usage of the template as-is.985aRules.push_back("csv");986if (!fPreSegWit) {987aRules.push_back("!segwit");988aRules.push_back("taproot");989}990if (consensusParams.signet_blocks) {991// indicate to miner that they must understand signet rules992// when attempting to mine with this template993aRules.push_back("!signet");994}996UniValue vbavailable(UniValue::VOBJ);997const auto gbtstatus = chainman.m_versionbitscache.GBTStatus(*pindexPrev, consensusParams);999for (const auto& [name, info] : gbtstatus.signalling) {1000vbavailable.pushKV(gbt_rule_value(name, info.gbt_optional_rule), info.bit);