Narrow scope of undofile write to avoid possible resource management issue

`AutoFile{OpenUndoFile(pos)}` was still in scope when `FlushUndoFile(pos.nFile)` was called, which could lead to file handle conflicts or other unexpected behavior.

Co-authored-by: Hodlinator <172445034+hodlinator@users.noreply.github.com>
Co-authored-by: maflcko <6399679+maflcko@users.noreply.github.com>
This commit is contained in:
Lőrinc 2025-04-07 17:47:57 +02:00
parent 3197155f91
commit 6640dd52c9

View File

@ -938,22 +938,31 @@ bool BlockManager::WriteBlockUndo(const CBlockUndo& blockundo, BlockValidationSt
LogError("FindUndoPos failed"); LogError("FindUndoPos failed");
return false; return false;
} }
// Open history file to append
AutoFile fileout{OpenUndoFile(pos)};
if (fileout.IsNull()) {
LogError("OpenUndoFile failed");
return FatalError(m_opts.notifications, state, _("Failed to write undo data."));
}
// Write index header
fileout << GetParams().MessageStart() << blockundo_size;
pos.nPos += BLOCK_SERIALIZATION_HEADER_SIZE;
{ {
// Calculate checksum // Open history file to append
HashWriter hasher{}; AutoFile fileout{OpenUndoFile(pos)};
hasher << block.pprev->GetBlockHash() << blockundo; if (fileout.IsNull()) {
// Write undo data & checksum LogError("OpenUndoFile failed");
fileout << blockundo << hasher.GetHash(); return FatalError(m_opts.notifications, state, _("Failed to write undo data."));
}
// Write index header
fileout << GetParams().MessageStart() << blockundo_size;
pos.nPos += BLOCK_SERIALIZATION_HEADER_SIZE;
{
// Calculate checksum
HashWriter hasher{};
hasher << block.pprev->GetBlockHash() << blockundo;
// Write undo data & checksum
fileout << blockundo << hasher.GetHash();
}
// Make sure `AutoFile` goes out of scope before we call `FlushUndoFile`
if (fileout.fclose()) {
LogError("WriteBlockUndo: fclose failed");
return false;
}
} }
// rev files are written in block height order, whereas blk files are written as blocks come in (often out of order) // rev files are written in block height order, whereas blk files are written as blocks come in (often out of order)