diff --git a/src/validation.cpp b/src/validation.cpp --- a/src/validation.cpp +++ b/src/validation.cpp @@ -3705,6 +3705,30 @@ return true; } +/** Store block on disk. If dbp is non-nullptr, the file is known to already + * reside on disk */ +static CDiskBlockPos SaveBlockToDisk(CValidationState &state, + const CBlock &block, int nHeight, + const CChainParams &chainparams, + const CDiskBlockPos *dbp) { + unsigned int nBlockSize = + ::GetSerializeSize(block, SER_DISK, CLIENT_VERSION); + CDiskBlockPos blockPos; + if (dbp != nullptr) blockPos = *dbp; + if (!FindBlockPos(state, blockPos, nBlockSize + 8, nHeight, + block.GetBlockTime(), dbp != nullptr)) { + error("%s: FindBlockPos failed", __func__); + return CDiskBlockPos(); + } + if (dbp == nullptr) { + if (!WriteBlockToDisk(block, blockPos, chainparams.DiskMagic())) { + AbortNode("Failed to write block"); + return CDiskBlockPos(); + } + } + return blockPos; +} + /** * Store a block on disk. * @@ -3843,29 +3867,17 @@ GetMainSignals().NewPoWValidBlock(pindex, pblock); } - int nHeight = pindex->nHeight; const CChainParams &chainparams = config.GetChainParams(); // Write block to history file try { - unsigned int nBlockSize = - ::GetSerializeSize(block, SER_DISK, CLIENT_VERSION); - CDiskBlockPos blockPos; - if (dbp != nullptr) { - blockPos = *dbp; - } - - if (!FindBlockPos(state, blockPos, nBlockSize + 8, nHeight, - block.GetBlockTime(), dbp != nullptr)) { - return error("AcceptBlock(): FindBlockPos failed"); + CDiskBlockPos blockPos = + SaveBlockToDisk(state, block, pindex->nHeight, chainparams, dbp); + if (blockPos.IsNull()) { + return state.Error(strprintf( + "%s: Failed to find position to write new block to disk", + __func__)); } - - if (dbp == nullptr) { - if (!WriteBlockToDisk(block, blockPos, chainparams.DiskMagic())) { - AbortNode(state, "Failed to write block"); - } - } - if (!ReceivedBlockTransactions(block, state, pindex, blockPos)) { return error("AcceptBlock(): ReceivedBlockTransactions failed"); } @@ -4800,16 +4812,10 @@ // one already on disk) try { CBlock &block = const_cast(chainparams.GenesisBlock()); - // Start new block file - unsigned int nBlockSize = - ::GetSerializeSize(block, SER_DISK, CLIENT_VERSION); - CDiskBlockPos blockPos; CValidationState state; - if (!FindBlockPos(state, blockPos, nBlockSize + 8, 0, - block.GetBlockTime())) { - return error("%s: FindBlockPos failed", __func__); - } - if (!WriteBlockToDisk(block, blockPos, chainparams.DiskMagic())) { + CDiskBlockPos blockPos = + SaveBlockToDisk(state, block, 0, chainparams, nullptr); + if (blockPos.IsNull()) { return error("%s: writing genesis block to disk failed", __func__); } CBlockIndex *pindex = AddToBlockIndex(block);