Skip to content

Commit

Permalink
actually stream verified Bao data
Browse files Browse the repository at this point in the history
  • Loading branch information
lukechampine committed May 2, 2024
1 parent a6d1ce1 commit 2ae44f0
Show file tree
Hide file tree
Showing 2 changed files with 47 additions and 1 deletion.
11 changes: 10 additions & 1 deletion bao.go
Original file line number Diff line number Diff line change
Expand Up @@ -134,6 +134,11 @@ func BaoDecode(dst io.Writer, data, outboard io.Reader, group int, root [32]byte
}
return p
}
write := func(w io.Writer, p []byte) {
if err == nil {
_, err = w.Write(p)
}
}
readParent := func() (l, r [8]uint32) {
read(outboard, buf[:64])
return bytesToCV(buf[:32]), bytesToCV(buf[32:])
Expand All @@ -147,7 +152,11 @@ func BaoDecode(dst io.Writer, data, outboard io.Reader, group int, root [32]byte
n := compressGroup(read(data, buf[:bufLen]), counter)
counter += bufLen / chunkSize
n.flags |= flags
return cv == chainingValue(n)
valid := cv == chainingValue(n)
if valid {
write(dst, buf[:bufLen])
}
return valid
}
l, r := readParent()
n := parentNode(l, r, iv, flags)
Expand Down
37 changes: 37 additions & 0 deletions bao_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -153,3 +153,40 @@ func TestBaoChunkGroup(t *testing.T) {
}
}
}

func TestBaoStreaming(t *testing.T) {
data := make([]byte, 1<<20)
blake3.New(0, nil).XOF().Read(data)

enc, root := blake3.BaoEncodeBuf(data, 0, false)
if root != blake3.Sum256(data) {
t.Fatal("bad root")
}
var buf bytes.Buffer
if ok, err := blake3.BaoDecode(&buf, bytes.NewReader(enc), nil, 0, root); err != nil || !ok {
t.Fatal("decode failed")
} else if !bytes.Equal(buf.Bytes(), data) {
t.Fatal("bad decode")
}

// corrupt root; nothing should be written to buf
buf.Reset()
if ok, err := blake3.BaoDecode(&buf, bytes.NewReader(enc), nil, 0, [32]byte{}); err != nil {
t.Fatal("decode failed")
} else if ok {
t.Fatal("decode succeeded with bad root")
} else if buf.Len() != 0 {
t.Fatal("buf was written with bad root")
}

// corrupt a byte halfway through; buf should only be partially written
buf.Reset()
enc[len(enc)/2] ^= 1
if ok, err := blake3.BaoDecode(&buf, bytes.NewReader(enc), nil, 0, root); err != nil {
t.Fatal("decode failed")
} else if ok {
t.Fatal("decode succeeded with bad data")
} else if !bytes.Equal(buf.Bytes(), data[:buf.Len()]) {
t.Fatal("invalid data was written to buf")
}
}

0 comments on commit 2ae44f0

Please sign in to comment.