Skip to content

fix(io): read the whole slice in ReadBytesShort - #1849

Open
0xShadowX wants to merge 1 commit into
Consensys-Incorporated:masterfrom
0xShadowX:fix/io-read-bytes-short
Open

0xShadowX wants to merge 1 commit into
Consensys-Incorporated:masterfrom
0xShadowX:fix/io-read-bytes-short

Conversation

@0xShadowX

Copy link
Copy Markdown

io.ReadBytesShort reads the payload with a single reader.Read call. io.Reader allows Read to return fewer bytes than requested with a nil error, so with a reader that does short reads the rest of the slice stays zero and no error is returned:

var buf bytes.Buffer
gnarkio.WriteBytesShort(challenge, &buf) // 32-byte challenge
got, n, err := gnarkio.ReadBytesShort(iotest.OneByteReader(&buf))
// err == nil, n == 2, got == ab000000...00

This happens in practice with bufio.Reader at a buffer boundary, pipes or network streams. A stream that ends in the middle of the payload isn't reported either. The function is used by the groth16 mpcsetup Phase1/Phase2 ReadFrom on all curves to read the contribution challenge, so a contribution read that way would carry a wrong challenge.

The fix uses io.ReadFull, which keeps reading until the slice is full and returns io.ErrUnexpectedEOF on a truncated stream.

Tests:

go test -count=1 -run TestReadBytesShort ./io/
go test -short ./backend/groth16/bn254/mpcsetup/ ./backend/groth16/bls12-377/mpcsetup/ ./backend/groth16/bls12-381/mpcsetup/ ./backend/groth16/bw6-761/mpcsetup/

TestReadBytesShortPartialReads (one byte per Read) and TestReadBytesShortTruncated both fail on master and pass with the change.

  • regression tests added
  • no generated files touched

A single Read call may return fewer bytes than requested with a nil error
(bufio.Reader at a buffer boundary, pipes, network streams). The rest of the
challenge was then left as zeros, the returned byte count was wrong and no
error was reported. A truncated stream wasn't reported either. Use
io.ReadFull, which reads the whole slice or returns io.ErrUnexpectedEOF.
@0xShadowX
0xShadowX requested a review from a team as a code owner September 28, 2026 17:15
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant