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,6 +938,8 @@ bool BlockManager::WriteBlockUndo(const CBlockUndo& blockundo, BlockValidationSt
LogError("FindUndoPos failed");
return false;
}
{
// Open history file to append
AutoFile fileout{OpenUndoFile(pos)};
if (fileout.IsNull()) {
@ -956,6 +958,13 @@ bool BlockManager::WriteBlockUndo(const CBlockUndo& blockundo, BlockValidationSt
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)
// we want to flush the rev (undo) file once we've written the last block, which is indicated by the last height
// in the block file info as below; note that this does not catch the case where the undo writes are keeping up