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