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