fix: reuse blobgen.Reader hash instead of redundant SHA-256 pass

hashVerifyReader now uses blobgen.Reader.Sum256() for the first hash
instead of maintaining its own sha256 hasher over the same bytes.
Eliminates duplicate SHA-256 computation on every read.
This commit is contained in:
clawbot
2026-03-17 01:41:38 -07:00
parent 22efd90f8c
commit a1018fcae3

View File

@@ -5,30 +5,25 @@ import (
"crypto/sha256"
"encoding/hex"
"fmt"
"hash"
"io"
"filippo.io/age"
"git.eeqj.de/sneak/vaultik/internal/blobgen"
)
// hashVerifyReader wraps a reader and computes a double-SHA-256 hash of all
// data read through it. The hash is verified against the expected blob hash
// when Close is called. This allows streaming blob verification without
// buffering the entire blob in memory.
// hashVerifyReader wraps a blobgen.Reader and verifies the double-SHA-256 hash
// of decrypted plaintext when Close is called. It reuses the hash that
// blobgen.Reader already computes internally via its TeeReader, avoiding
// redundant SHA-256 computation.
type hashVerifyReader struct {
reader io.ReadCloser // underlying decrypted blob reader
reader *blobgen.Reader // underlying decrypted blob reader (has internal hasher)
fetcher io.ReadCloser // raw fetched stream (closed on Close)
hasher hash.Hash // running SHA-256 of plaintext
blobHash string // expected double-SHA-256 hex
done bool // EOF reached
}
func (h *hashVerifyReader) Read(p []byte) (int, error) {
n, err := h.reader.Read(p)
if n > 0 {
h.hasher.Write(p[:n])
}
if err == io.EOF {
h.done = true
}
@@ -41,7 +36,7 @@ func (h *hashVerifyReader) Close() error {
fetcherErr := h.fetcher.Close()
if h.done {
firstHash := h.hasher.Sum(nil)
firstHash := h.reader.Sum256()
secondHasher := sha256.New()
secondHasher.Write(firstHash)
actualHashHex := hex.EncodeToString(secondHasher.Sum(nil))
@@ -75,7 +70,6 @@ func (v *Vaultik) FetchAndDecryptBlob(ctx context.Context, blobHash string, expe
return &hashVerifyReader{
reader: reader,
fetcher: rc,
hasher: sha256.New(),
blobHash: blobHash,
}, nil
}