Skip to content

Commit 6640dd5

Browse files
l0rinchodlinatormaflcko
committed
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 <[email protected]> Co-authored-by: maflcko <[email protected]>
1 parent 3197155 commit 6640dd5

File tree

1 file changed

+23
-14
lines changed

1 file changed

+23
-14
lines changed

src/node/blockstorage.cpp

Lines changed: 23 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -938,22 +938,31 @@ bool BlockManager::WriteBlockUndo(const CBlockUndo& blockundo, BlockValidationSt
938938
LogError("FindUndoPos failed");
939939
return false;
940940
}
941-
// Open history file to append
942-
AutoFile fileout{OpenUndoFile(pos)};
943-
if (fileout.IsNull()) {
944-
LogError("OpenUndoFile failed");
945-
return FatalError(m_opts.notifications, state, _("Failed to write undo data."));
946-
}
947941

948-
// Write index header
949-
fileout << GetParams().MessageStart() << blockundo_size;
950-
pos.nPos += BLOCK_SERIALIZATION_HEADER_SIZE;
951942
{
952-
// Calculate checksum
953-
HashWriter hasher{};
954-
hasher << block.pprev->GetBlockHash() << blockundo;
955-
// Write undo data & checksum
956-
fileout << blockundo << hasher.GetHash();
943+
// Open history file to append
944+
AutoFile fileout{OpenUndoFile(pos)};
945+
if (fileout.IsNull()) {
946+
LogError("OpenUndoFile failed");
947+
return FatalError(m_opts.notifications, state, _("Failed to write undo data."));
948+
}
949+
950+
// Write index header
951+
fileout << GetParams().MessageStart() << blockundo_size;
952+
pos.nPos += BLOCK_SERIALIZATION_HEADER_SIZE;
953+
{
954+
// Calculate checksum
955+
HashWriter hasher{};
956+
hasher << block.pprev->GetBlockHash() << blockundo;
957+
// Write undo data & checksum
958+
fileout << blockundo << hasher.GetHash();
959+
}
960+
961+
// Make sure `AutoFile` goes out of scope before we call `FlushUndoFile`
962+
if (fileout.fclose()) {
963+
LogError("WriteBlockUndo: fclose failed");
964+
return false;
965+
}
957966
}
958967

959968
// rev files are written in block height order, whereas blk files are written as blocks come in (often out of order)

0 commit comments

Comments
 (0)