Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Clear decoder buffer #166

Merged
merged 6 commits into from
Jun 7, 2024
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 1 addition & 5 deletions gateway/encoding.go
Original file line number Diff line number Diff line change
Expand Up @@ -247,11 +247,7 @@ func (r *RPCSendBlocks) encodeResponse(e *types.Encoder) {
}
}
func (r *RPCSendBlocks) decodeResponse(d *types.Decoder) {
if n := d.ReadPrefix(); n <= cap(r.Blocks) {
r.Blocks = r.Blocks[:n]
} else {
r.Blocks = make([]types.Block, n)
}
r.Blocks = make([]types.Block, d.ReadPrefix())
for i := range r.Blocks {
(*types.V1Block)(&r.Blocks[i]).DecodeFrom(d)
}
Expand Down
11 changes: 9 additions & 2 deletions types/encoding.go
Original file line number Diff line number Diff line change
Expand Up @@ -136,8 +136,15 @@ func (d *Decoder) Read(p []byte) (int, error) {
if want > len(d.buf) {
want = len(d.buf)
}
var read int
read, d.err = io.ReadFull(&d.lr, d.buf[:want])
n8maninger marked this conversation as resolved.
Show resolved Hide resolved
read, err := io.ReadFull(&d.lr, d.buf[:want])
if err != nil {
// When the decoder encounters an error, it must clear its buffer and
// return empty values for the remaining decodes. Because the decoder uses
// sticky errors instead of immediately returning a bad decode can
// potentially cause a massive allocation.
d.SetErr(err)
return n, err
}
n8maninger marked this conversation as resolved.
Show resolved Hide resolved
n += copy(p[n:], d.buf[:read])
}
return n, d.err
Expand Down
46 changes: 46 additions & 0 deletions types/encoding_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
package types

import (
"io"
"testing"
)

type readErrorer struct {
err error
r io.Reader
}

func (r *readErrorer) Read(p []byte) (n int, err error) {
if r.err != nil {
return 0, r.err
}
return r.r.Read(p)
}

func TestDecoderError(t *testing.T) {
r, w := io.Pipe()
re := &readErrorer{r: r}
enc := NewEncoder(w)
d := NewDecoder(io.LimitedReader{R: re, N: 1e6})

go func() {
// writing to the pipe blocks until we read from it
enc.WritePrefix(1000)
enc.Flush()
}()

// read the value from the encoder
n := d.ReadPrefix()
if n != 1000 {
t.Fatalf("expected 1000, got %d", n)
}

// set the error and try to read again
re.err = io.EOF

// should return 0 since the decoder errored
n = d.ReadPrefix()
if n != 0 {
t.Fatalf("expected 0, got %d", n)
}
}
Loading