rpc: build getblocktemplate's block into a local before touching the cached template

getblocktemplate releases cs_main while CreateNewBlockWithKey runs, but it wrote the result
straight into the function-static pblocktemplate from inside that unlocked scope. A second
getblocktemplate call holding cs_main could then delete and NULL it (the "create new block"
branch frees the old template first) just before the first call took cs_main back, so the
first call threw "CreateNewBlock(): create block failed" for a block that had been built
fine, and templates overwritten this way were leaked.

The new block now goes into a local, and the cached template is freed and replaced only
after cs_main is held again. The old template also stays valid while the new one is built.

Seen once on the 3-VPS stress fleet (4 concurrent RPC hammer workers, one of them calling
getblocktemplate). Not reproduced locally: 720 calls (24 concurrent callers per forced
rebuild, 13 wide shielded txs in the mempool, background cs_main load) passed on both the
old and the new binary, so the fix rests on the code path above. The new binary showed no
regressions in that run.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
This commit is contained in:
2026-11-28 21:51:22 -06:00
co-authored by Claude Opus 5.5
parent 0ac7812b11
commit 4538a8cd76
+10 -9
View File
@@ -765,12 +765,10 @@ UniValue getblocktemplate(const UniValue& params, bool fHelp, const CPubKey& myp
CBlockIndex* pindexPrevNew = chainActive.LastTip();
nStart = GetTime();
// Create new block
if(pblocktemplate)
{
delete pblocktemplate;
pblocktemplate = NULL;
}
// Create new block. cs_main is released while it is built, so another getblocktemplate call can
// run this block meanwhile: build into a local and only touch the shared pblocktemplate once cs_main
// is held again, or that call could delete or overwrite it under us.
CBlockTemplate* pblocktemplateNew = NULL;
#ifdef ENABLE_WALLET
CReserveKey reservekey(pwalletMain);
#endif
@@ -778,15 +776,18 @@ UniValue getblocktemplate(const UniValue& params, bool fHelp, const CPubKey& myp
// CreateNewBlockWithKey can throw (keypool/wallet DB errors); cs_main must be held again by then.
CMainUnlockScope unlockMain;
#ifdef ENABLE_WALLET
pblocktemplate = CreateNewBlockWithKey(reservekey,pindexPrevNew->GetHeight()+1,HUSH_MAXGPUCOUNT,false);
pblocktemplateNew = CreateNewBlockWithKey(reservekey,pindexPrevNew->GetHeight()+1,HUSH_MAXGPUCOUNT,false);
#else
pblocktemplate = CreateNewBlockWithKey();
pblocktemplateNew = CreateNewBlockWithKey();
#endif
}
if (!pblocktemplate)
if (!pblocktemplateNew)
throw std::runtime_error("CreateNewBlock(): create block failed");
//throw JSONRPCError(RPC_OUT_OF_MEMORY, "Out of memory or no available utxo for staking");
delete pblocktemplate;
pblocktemplate = pblocktemplateNew;
// Need to update only after we know CreateNewBlockWithKey succeeded
pindexPrev = pindexPrevNew;
}