2019-08-14 21:18:32 +00:00
|
|
|
package encoder
|
|
|
|
|
|
|
|
import (
|
|
|
|
"bytes"
|
|
|
|
"testing"
|
|
|
|
|
|
|
|
"github.com/gogo/protobuf/proto"
|
2023-03-17 18:52:56 +00:00
|
|
|
"github.com/prysmaticlabs/prysm/v4/testing/assert"
|
|
|
|
"github.com/prysmaticlabs/prysm/v4/testing/require"
|
2019-08-14 21:18:32 +00:00
|
|
|
)
|
|
|
|
|
|
|
|
func TestReadVarint(t *testing.T) {
|
|
|
|
data := []byte("foobar data")
|
|
|
|
prefixedData := append(proto.EncodeVarint(uint64(len(data))), data...)
|
|
|
|
|
|
|
|
vi, err := readVarint(bytes.NewBuffer(prefixedData))
|
2020-07-14 16:51:39 +00:00
|
|
|
require.NoError(t, err)
|
|
|
|
assert.Equal(t, uint64(len(data)), vi, "Received wrong varint")
|
2019-08-14 21:18:32 +00:00
|
|
|
}
|
2020-07-13 19:02:03 +00:00
|
|
|
|
|
|
|
func TestReadVarint_ExceedsMaxLength(t *testing.T) {
|
|
|
|
fByte := byte(1 << 7)
|
|
|
|
// Terminating byte.
|
|
|
|
tByte := byte(1 << 6)
|
2020-10-12 08:11:05 +00:00
|
|
|
var header []byte
|
2020-07-13 19:02:03 +00:00
|
|
|
for i := 0; i < 9; i++ {
|
|
|
|
header = append(header, fByte)
|
|
|
|
}
|
|
|
|
header = append(header, tByte)
|
|
|
|
_, err := readVarint(bytes.NewBuffer(header))
|
2020-07-14 16:51:39 +00:00
|
|
|
require.NoError(t, err, "Expected no error from reading valid header")
|
2020-07-13 19:02:03 +00:00
|
|
|
length := len(header)
|
|
|
|
// Add an additional byte to make header invalid.
|
|
|
|
header = append(header[:length-1], []byte{fByte, tByte}...)
|
|
|
|
|
|
|
|
_, err = readVarint(bytes.NewBuffer(header))
|
2020-07-14 16:51:39 +00:00
|
|
|
assert.ErrorContains(t, errExcessMaxLength.Error(), err, "Expected error from reading invalid header")
|
2020-07-13 19:02:03 +00:00
|
|
|
}
|