From 0010d6c5b939e2bd1bb7b2a7925a79ccb2b65f1e Mon Sep 17 00:00:00 2001 From: Derrick Hammer Date: Sun, 25 Feb 2024 07:22:17 -0500 Subject: [PATCH] feat: add verifier class that wraps a reader and proof --- bao/bao.go | 37 +++++++++++++++++++++++++++++++++++++ 1 file changed, 37 insertions(+) diff --git a/bao/bao.go b/bao/bao.go index 9e5e87b..21b9b40 100644 --- a/bao/bao.go +++ b/bao/bao.go @@ -22,6 +22,39 @@ var pluginBin []byte var bao Bao var client *plugin.Client +var _ io.ReadCloser = (*Verifier)(nil) + +var ErrVerifyFailed = errors.New("verification failed") + +type Verifier struct { + r io.ReadCloser + proof Result + read uint64 +} + +func (v Verifier) Read(p []byte) (n int, err error) { + var buf [VERIFY_CHUNK_SIZE]byte + + n, err = io.ReadAtLeast(v.r, buf[:], VERIFY_CHUNK_SIZE) + if err != nil { + return 0, err + } + + if !bao.Verify(buf[:n], v.read, v.proof.Proof, v.proof.Hash) { + return 0, ErrVerifyFailed + } + + v.read += uint64(n) + + copy(p, buf[:n]) + + return n, nil +} + +func (v Verifier) Close() error { + return v.r.Close() +} + func init() { temp, err := os.CreateTemp(os.TempDir(), "bao") if err != nil { @@ -110,3 +143,7 @@ func Hash(r io.Reader) (*Result, error) { return &result, nil } + +func NewVerifier(r io.ReadCloser, proof Result) *Verifier { + return &Verifier{r: r, proof: proof} +}