From 2994d88fe3410405b4579f5cdc80e736b8a66e7a Mon Sep 17 00:00:00 2001 From: furszy Date: Wed, 27 Jan 2021 18:27:46 -0300 Subject: [PATCH] blockassembler: do not lock cs_main and mempool cs for the entire block, only where are needed. --- src/blockassembler.cpp | 24 ++++++++++++++++-------- 1 file changed, 16 insertions(+), 8 deletions(-) diff --git a/src/blockassembler.cpp b/src/blockassembler.cpp index 42f5fc219b2c0a..483d7c3621c4bf 100644 --- a/src/blockassembler.cpp +++ b/src/blockassembler.cpp @@ -160,8 +160,7 @@ std::unique_ptr BlockAssembler::CreateNewBlock(const CScript& sc pblocktemplate->vTxFees.push_back(-1); // updated at end pblocktemplate->vTxSigOps.push_back(-1); // updated at end - LOCK2(cs_main, mempool.cs); - CBlockIndex* pindexPrev = chainActive.Tip(); + CBlockIndex* pindexPrev = WITH_LOCK(cs_main, return chainActive.Tip()); nHeight = pindexPrev->nHeight + 1; pblock->nVersion = ComputeBlockVersion(chainparams.GetConsensus(), nHeight); @@ -177,9 +176,12 @@ std::unique_ptr BlockAssembler::CreateNewBlock(const CScript& sc return nullptr; } - // Add transactions - addPriorityTxs(); - addScoreTxs(); + { + // Add transactions from mempool + LOCK2(cs_main,mempool.cs); + addPriorityTxs(); + addScoreTxs(); + } if (!fProofOfStake) { // Coinbase can get the fees. @@ -211,9 +213,15 @@ std::unique_ptr BlockAssembler::CreateNewBlock(const CScript& sc } } - CValidationState state; - if (!TestBlockValidity(state, *pblock, pindexPrev, false, false)) { - throw std::runtime_error(strprintf("%s: TestBlockValidity failed: %s", __func__, FormatStateMessage(state))); + { + LOCK(cs_main); + if (chainActive.Tip() != pindexPrev) return nullptr; // new block came in, move on + + CValidationState state; + if (!TestBlockValidity(state, *pblock, pindexPrev, false, false)) { + throw std::runtime_error( + strprintf("%s: TestBlockValidity failed: %s", __func__, FormatStateMessage(state))); + } } return std::move(pblocktemplate);