From 6640dd52c9fcb85d77f081780c02ee37b8089091 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?L=C5=91rinc?= Date: Mon, 7 Apr 2025 17:47:57 +0200 Subject: [PATCH] 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> --- src/node/blockstorage.cpp | 37 +++++++++++++++++++++++-------------- 1 file changed, 23 insertions(+), 14 deletions(-) diff --git a/src/node/blockstorage.cpp b/src/node/blockstorage.cpp index 2e49443b569..e65d461b906 100644 --- a/src/node/blockstorage.cpp +++ b/src/node/blockstorage.cpp @@ -938,22 +938,31 @@ bool BlockManager::WriteBlockUndo(const CBlockUndo& blockundo, BlockValidationSt LogError("FindUndoPos failed"); 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 - HashWriter hasher{}; - hasher << block.pprev->GetBlockHash() << blockundo; - // Write undo data & checksum - fileout << blockundo << hasher.GetHash(); + // 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 + 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)