diff --git a/src/rpc/mining.cpp b/src/rpc/mining.cpp index 75ffb4cc5..ac07ba0ca 100644 --- a/src/rpc/mining.cpp +++ b/src/rpc/mining.cpp @@ -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; }