sszutils

package
v1.3.1 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Apr 22, 2026 License: Apache-2.0 Imports: 8 Imported by: 5

Documentation

Overview

Package sszutils provides shared interfaces, encoding/decoding primitives, and utility functions for SSZ (Simple Serialize) operations.

It defines the core interfaces used across the dynamic-ssz library: encoder/decoder abstractions for both buffer and stream modes, hash walker for merkle tree computation, and compatibility interfaces for interoperating with fastssz and dynamic SSZ implementations.

Index

Constants

View Source
const DefaultStreamDecoderBufSize = 2 * 1024

DefaultStreamDecoderBufSize is the default maximum buffer size for StreamDecoder (2KB).

View Source
const DefaultStreamEncoderBufSize = 2 * 1024

DefaultStreamEncoderBufSize is the default internal write buffer size for StreamEncoder (2KB).

Variables

View Source
var (
	// ErrUnexpectedEOF is returned when the SSZ input is shorter than the
	// type requires (e.g. not enough bytes to decode a uint64).
	ErrUnexpectedEOF = fmt.Errorf("unexpected end of SSZ")

	// ErrOffset is returned when an SSZ offset is out of range, does not
	// monotonically increase, or a field does not consume exactly the
	// byte range its offset pair implied.
	ErrOffset = fmt.Errorf("incorrect offset")

	// ErrInvalidValueRange is returned when an SSZ value is outside the
	// valid domain for its type (e.g. non-zero padding bits in a
	// bitvector, unterminated bitlist, or invalid union selector).
	ErrInvalidValueRange = fmt.Errorf("invalid value range")

	// ErrVectorLength is returned when a vector or fixed-length byte
	// array has a length that does not match the schema.
	ErrVectorLength = fmt.Errorf("incorrect vector length")

	// ErrListTooBig is returned when a list's length exceeds its declared
	// SSZ maximum.
	ErrListTooBig = fmt.Errorf("list length is higher than max value")

	// ErrNotImplemented is returned when the SSZ codec encounters a Go
	// type or feature it does not support.
	ErrNotImplemented = fmt.Errorf("not implemented")

	// ErrPlatformOverflow is returned when a SSZ length or count exceeds
	// the platform's integer range (>31-bit sizes on 32-bit platforms).
	ErrPlatformOverflow = fmt.Errorf("value exceeds platform integer range")

	// ErrBitlistNotTerminated is an alias for ErrInvalidValueRange,
	// retained for backward compatibility. New code should use
	// ErrInvalidValueRange with a descriptive message instead.
	ErrBitlistNotTerminated = ErrInvalidValueRange

	// ErrInvalidUnionVariant is an alias for ErrInvalidValueRange,
	// retained for backward compatibility. New code should use
	// ErrInvalidValueRange with a descriptive message instead.
	ErrInvalidUnionVariant = ErrInvalidValueRange
)

Sentinel errors for SSZ operations. Downstream consumers can check error categories via errors.Is(err, sszutils.ErrOffset) etc.

View Source
var (
	// ErrUnsupportedType is returned when a Go type kind is fundamentally
	// incompatible with SSZ (e.g. maps, channels, functions, interfaces).
	ErrUnsupportedType = fmt.Errorf("unsupported type")

	// ErrTypeMismatch is returned when the SSZ type assigned via tag or
	// auto-detection does not match the Go type's kind (e.g. ssz-type:"uint64"
	// on a bool field).
	ErrTypeMismatch = fmt.Errorf("type mismatch")

	// ErrInvalidTag is returned when a struct tag is malformed or contains
	// an unrecognized value (e.g. ssz-type:"foobar", non-numeric ssz-size).
	ErrInvalidTag = fmt.Errorf("invalid tag")

	// ErrInvalidConstraint is returned when tag values are syntactically
	// valid but semantically wrong (e.g. ssz-size:2 on a bool, bit-size on
	// a non-bitvector, vector size exceeding array length, duplicate ssz-index).
	ErrInvalidConstraint = fmt.Errorf("invalid constraint")

	// ErrExtendedTypeDisabled is returned when an extended SSZ type (signed
	// integers, floats, optionals, big.Int) is used without enabling the
	// ExtendedTypes flag on the TypeCache.
	ErrExtendedTypeDisabled = fmt.Errorf("extended type not enabled")

	// ErrMissingInterface is returned when a required method or interface
	// is not found on a type (e.g. missing GetDescriptorType method,
	// custom type without fastssz marshaler/hasher).
	ErrMissingInterface = fmt.Errorf("missing interface")
)

Sentinel errors for type introspection (type cache / descriptor building). These are returned during schema analysis of Go types, not at marshal/unmarshal time. Check with errors.Is(err, sszutils.ErrUnsupportedType) etc.

Functions

func Annotate added in v1.3.0

func Annotate[T any](tag string) bool

Annotate registers SSZ annotations for a named (non-struct) type T. The tag string uses the same format as Go struct field tags:

var _ = sszutils.Annotate[BlobKZGCommitments](`ssz-max:"4096"`)
var _ = sszutils.Annotate[BlobKZGCommitments](`ssz-max:"4096" dynssz-max:"MAX_BLOB_COMMITMENTS"`)

This is the canonical way to attach SSZ metadata to non-struct types that lack struct field tags. Both the reflection path and the code generator consume these annotations.

Call this at package level (var block or init function) so the annotation is registered before any marshal/unmarshal/codegen operation.

func AppendZeroPadding

func AppendZeroPadding(buf []byte, count int) []byte

AppendZeroPadding appends the specified number of zero bytes to buf

func CalculateLimit

func CalculateLimit(maxCapacity, numItems, size uint64) uint64

CalculateLimit computes the merkle tree chunk limit for a list or vector given its maximum capacity, current number of items, and per-item byte size.

func DecodeUint64Slice added in v1.3.0

func DecodeUint64Slice[T ~uint64](dec Decoder, dst []T) error

DecodeUint64Slice decodes uint64 values from a Decoder directly into dst using bulk memory copy. On little-endian architectures (x86, ARM64) this avoids per-element DecodeUint64 overhead.

func EncodeUint64Slice added in v1.3.0

func EncodeUint64Slice[T ~uint64](enc Encoder, s []T)

EncodeUint64Slice encodes a uint64 slice to an Encoder using bulk memory copy. On little-endian architectures (x86, ARM64) this avoids per-element EncodeUint64 overhead.

func ErrBigIntTypeExpectedFn added in v1.3.0

func ErrBigIntTypeExpectedFn(got any) error

ErrBigIntTypeExpectedFn is returned when a BigInt SSZ field does not hold a big.Int value.

func ErrBitlistLengthFn added in v1.3.0

func ErrBitlistLengthFn(length, limit any) error

ErrBitlistLengthFn is returned when a bitlist's bit count exceeds the declared maximum.

func ErrBitlistNotTerminatedFn added in v1.3.0

func ErrBitlistNotTerminatedFn() error

ErrBitlistNotTerminatedFn is returned when a bitlist is missing its mandatory termination bit.

func ErrBitvectorPaddingFn added in v1.3.0

func ErrBitvectorPaddingFn() error

ErrBitvectorPaddingFn is returned when a bitvector's padding bits (above the declared bit-size) are non-zero.

func ErrByteVectorEOFFn added in v1.3.0

func ErrByteVectorEOFFn(have, needed any) error

ErrByteVectorEOFFn is returned when the buffer is too short for a byte vector / byte array.

func ErrCustomTypeNotSupportedFn added in v1.3.0

func ErrCustomTypeNotSupportedFn() error

ErrCustomTypeNotSupportedFn is returned when codegen encounters a custom type that cannot be handled by the code generator.

func ErrElementOffsetOutOfRangeFn added in v1.3.0

func ErrElementOffsetOutOfRangeFn(end, start, limit any) error

ErrElementOffsetOutOfRangeFn is returned when a dynamic collection element's offset is out of the valid data range.

func ErrFieldNotConsumedFn added in v1.3.0

func ErrFieldNotConsumedFn(pos, expected any) error

ErrFieldNotConsumedFn is returned when a static-size field did not advance the decoder position by exactly the expected amount.

func ErrFirstOffsetMismatchFn added in v1.3.0

func ErrFirstOffsetMismatchFn(offset, expected any) error

ErrFirstOffsetMismatchFn is returned when the first dynamic field's offset does not equal the expected static-part length.

func ErrFixedFieldsEOFFn added in v1.3.0

func ErrFixedFieldsEOFFn(have, needed any) error

ErrFixedFieldsEOFFn is returned when the buffer is too short for the fixed-size portion of a container.

func ErrInvalidBoolValueFn added in v1.3.0

func ErrInvalidBoolValueFn() error

ErrInvalidBoolValueFn is returned when a bool byte is neither 0 nor 1.

func ErrInvalidListStartOffsetFn added in v1.3.0

func ErrInvalidListStartOffsetFn(offset, bufLen any) error

ErrInvalidListStartOffsetFn is returned when the first offset in a dynamic list is malformed (not a multiple of 4 or out of range).

func ErrInvalidUnionVariantFn added in v1.3.0

func ErrInvalidUnionVariantFn() error

ErrInvalidUnionVariantFn is returned when a union selector byte does not match any declared variant.

func ErrLargeUintLengthFn added in v1.3.0

func ErrLargeUintLengthFn(got, expected any) error

ErrLargeUintLengthFn is returned when a uint128/uint256 backing array has an unexpected byte length.

func ErrListLengthFn added in v1.3.0

func ErrListLengthFn(length, limit any) error

ErrListLengthFn is returned when a list's element count exceeds the declared maximum.

func ErrListNotAlignedFn added in v1.3.0

func ErrListNotAlignedFn(length, elemSize any) error

ErrListNotAlignedFn is returned when a list's byte length is not an exact multiple of the element size.

func ErrListOffsetsEOFFn added in v1.3.0

func ErrListOffsetsEOFFn(have, needed any) error

ErrListOffsetsEOFFn is returned when the buffer is too short for the list offset table.

func ErrNeedBytesFn added in v1.3.0

func ErrNeedBytesFn(needed int, typeName string) error

ErrNeedBytesFn is returned when a primitive type cannot be decoded because the buffer is too short (e.g. "need 4 bytes for uint32").

func ErrOffsetOutOfRangeFn added in v1.3.0

func ErrOffsetOutOfRangeFn(offset, prev, limit any) error

ErrOffsetOutOfRangeFn is returned when a field offset is not monotonically increasing or exceeds the data bounds.

func ErrOptionalFlagEOFFn added in v1.3.0

func ErrOptionalFlagEOFFn() error

ErrOptionalFlagEOFFn is returned when there is no byte available to read the optional presence flag.

func ErrOptionalValueEOFFn added in v1.3.0

func ErrOptionalValueEOFFn() error

ErrOptionalValueEOFFn is returned when the buffer is too short for an optional value.

func ErrPlatformOverflowFn added in v1.3.0

func ErrPlatformOverflowFn(description string, value any) error

ErrPlatformOverflowFn is returned when a SSZ size or count exceeds the platform's integer range (e.g. >31 bits on 32-bit systems).

func ErrStaticElementNotConsumedFn added in v1.3.0

func ErrStaticElementNotConsumedFn(pos, expected any) error

ErrStaticElementNotConsumedFn is returned when a static collection element did not advance the decoder position by exactly the expected amount.

func ErrTimeTypeExpectedFn added in v1.3.0

func ErrTimeTypeExpectedFn(got any) error

ErrTimeTypeExpectedFn is returned when a uint64-backed time field does not hold a time.Time value.

func ErrTrailingDataFn added in v1.3.0

func ErrTrailingDataFn(trailing any) error

ErrTrailingDataFn is returned when a dynamic field or element has unconsumed bytes after decoding.

func ErrUnionSelectorEOFFn added in v1.3.0

func ErrUnionSelectorEOFFn() error

ErrUnionSelectorEOFFn is returned when there is no byte available to read the union selector.

func ErrUnionTypeMismatchFn added in v1.3.0

func ErrUnionTypeMismatchFn() error

ErrUnionTypeMismatchFn is returned when the concrete type stored in a union's Data field does not match the expected variant type.

func ErrUnionVariantEOFFn added in v1.3.0

func ErrUnionVariantEOFFn(have, needed any) error

ErrUnionVariantEOFFn is returned when the buffer is too short for a union variant value.

func ErrUnknownTypeFn added in v1.3.0

func ErrUnknownTypeFn(typeName any) error

ErrUnknownTypeFn is returned when the type dispatcher encounters a type it does not handle.

func ErrVectorElementsEOFFn added in v1.3.0

func ErrVectorElementsEOFFn(have, needed any) error

ErrVectorElementsEOFFn is returned when the buffer is too short for static vector elements.

func ErrVectorLengthFn added in v1.3.0

func ErrVectorLengthFn(length, limit any) error

ErrVectorLengthFn is returned when a vector or fixed-size byte array has more elements than the schema allows.

func ErrVectorOffsetsEOFFn added in v1.3.0

func ErrVectorOffsetsEOFFn(have, needed any) error

ErrVectorOffsetsEOFFn is returned when the buffer is too short for the vector offset table.

func ErrVectorSizeExceedsArrayFn added in v1.3.0

func ErrVectorSizeExceedsArrayFn(dynamicSize, arrayLen any) error

ErrVectorSizeExceedsArrayFn is returned when a dynamic size expression yields a vector size larger than the backing Go array.

func ErrorWithPath added in v1.3.0

func ErrorWithPath(err error, segment string) error

ErrorWithPath appends a path segment to an sszError as it bubbles up. If err is not already an sszError, it is wrapped in one. Segments are collected innermost-first and reversed when formatting.

func ErrorWithPathf added in v1.3.0

func ErrorWithPathf(err error, format string, args ...any) error

ErrorWithPathf appends a formatted path segment to an sszError as it bubbles up. If err is not already an sszError, it is wrapped in one. Segments are collected innermost-first and reversed when formatting.

func ExpandSlice added in v1.1.1

func ExpandSlice[T any](src []T, size int) []T

ExpandSlice expands a slice to a byte slice

func GetOffsetSlice added in v1.2.0

func GetOffsetSlice(size int) []uint32

GetOffsetSlice returns a uint32 slice of the given size from a shared pool, suitable for use as an SSZ offset buffer. The caller must return it via PutOffsetSlice when done.

func HashUint64Slice added in v1.3.0

func HashUint64Slice[T ~uint64](hh HashWalker, s []T)

HashUint64Slice appends the little-endian encoding of a uint64 slice directly to a HashWalker's buffer. On little-endian architectures (x86, ARM64) this is a single bulk memory copy, avoiding per-element AppendUint64 overhead.

func LookupAnnotation added in v1.3.0

func LookupAnnotation(t reflect.Type) (string, bool)

LookupAnnotation returns the raw SSZ tag string registered for the given reflect.Type via Annotate[T](), or ("", false) if none was registered.

func MarshalBool

func MarshalBool(dst []byte, b bool) []byte

MarshalBool marshals a boolean to dst

func MarshalOffset

func MarshalOffset(dst []byte, offset int) []byte

MarshalOffset marshals an offset to dst

func MarshalUint8

func MarshalUint8(dst []byte, i uint8) []byte

MarshalUint8 marshals a little endian uint8 to dst

func MarshalUint16

func MarshalUint16(dst []byte, i uint16) []byte

MarshalUint16 marshals a little endian uint16 to dst

func MarshalUint32

func MarshalUint32(dst []byte, i uint32) []byte

MarshalUint32 marshals a little endian uint32 to dst

func MarshalUint64

func MarshalUint64(dst []byte, i uint64) []byte

MarshalUint64 marshals a little endian uint64 to dst

func MarshalUint64Slice added in v1.3.0

func MarshalUint64Slice[T ~uint64](dst []byte, s []T) []byte

MarshalUint64Slice appends the little-endian encoding of a uint64 slice to dst. On little-endian architectures (x86, ARM64) this is a single bulk memory copy, avoiding per-element encoding overhead.

func NewSszError added in v1.3.0

func NewSszError(base error, msg string) error

NewSszError creates a new sszError with the given sentinel and detail message.

func NewSszErrorf added in v1.3.0

func NewSszErrorf(base error, format string, args ...any) error

NewSszErrorf creates a new sszError with a formatted detail message.

func NextPowerOfTwo added in v1.1.1

func NextPowerOfTwo(v uint64) uint64

NextPowerOfTwo returns the smallest power of two greater than or equal to v.

func PutOffsetSlice added in v1.2.0

func PutOffsetSlice(slice []uint32)

PutOffsetSlice returns a uint32 offset slice to the shared pool for reuse.

func ReadOffset

func ReadOffset(buf []byte) uint64

ReadOffset reads an offset from buf

func ResolveSpecValueWithDefault added in v1.2.0

func ResolveSpecValueWithDefault(ds DynamicSpecs, name string, defaultValue uint64) (uint64, error)

ResolveSpecValueWithDefault resolves a named specification value using ds, returning defaultValue if the name is not found.

func UnmarshalBool

func UnmarshalBool(src []byte) bool

UnmarshalBool unmarshals a boolean from the src input

func UnmarshalUint64Slice added in v1.3.0

func UnmarshalUint64Slice[T ~uint64](dst []T, buf []byte)

UnmarshalUint64Slice decodes little-endian encoded uint64 values from buf into dst. On little-endian architectures (x86, ARM64) this is a single bulk memory copy.

func UnmarshallUint8

func UnmarshallUint8(src []byte) uint8

UnmarshallUint8 unmarshals a little endian uint8 from the src input

func UnmarshallUint16

func UnmarshallUint16(src []byte) uint16

UnmarshallUint16 unmarshals a little endian uint16 from the src input

func UnmarshallUint32

func UnmarshallUint32(src []byte) uint32

UnmarshallUint32 unmarshals a little endian uint32 from the src input

func UnmarshallUint64

func UnmarshallUint64(src []byte) uint64

UnmarshallUint64 unmarshals a little endian uint64 from the src input

func UpdateOffset

func UpdateOffset(dst []byte, offset int)

UpdateOffset updates the offset in dst

func ZeroBytes

func ZeroBytes() []byte

ZeroBytes returns a shared 1024-byte slice of zeros, initializing it on first call. The returned slice must not be modified by callers.

Types

type BufferDecoder added in v1.2.0

type BufferDecoder struct {
	// contains filtered or unexported fields
}

BufferDecoder is a seekable Decoder implementation backed by an in-memory byte buffer. It supports random-access offset reads via DecodeOffsetAt and byte skipping via SkipBytes.

func NewBufferDecoder added in v1.2.0

func NewBufferDecoder(buffer []byte) *BufferDecoder

NewBufferDecoder creates a new BufferDecoder that reads SSZ data from the provided byte buffer.

func (*BufferDecoder) DecodeBool added in v1.2.0

func (e *BufferDecoder) DecodeBool() (bool, error)

DecodeBool reads a single byte and returns its boolean value. Returns ErrUnexpectedEOF if no bytes remain, or ErrInvalidValueRange if the byte is not 0x00 or 0x01.

func (*BufferDecoder) DecodeBytes added in v1.2.0

func (e *BufferDecoder) DecodeBytes(buf []byte) ([]byte, error)

DecodeBytes reads len(buf) bytes into the provided buffer and returns the filled slice. Returns ErrUnexpectedEOF if fewer bytes remain than requested.

func (*BufferDecoder) DecodeBytesBuf added in v1.2.0

func (e *BufferDecoder) DecodeBytesBuf(length int) ([]byte, error)

DecodeBytesBuf returns a slice of the underlying buffer containing the next length bytes. If length is negative, all remaining bytes within the current limit are returned. The returned slice shares memory with the decoder's buffer and must not be modified. Returns ErrUnexpectedEOF if fewer bytes remain than requested.

func (*BufferDecoder) DecodeOffset added in v1.2.0

func (e *BufferDecoder) DecodeOffset() (uint32, error)

DecodeOffset reads a 4-byte little-endian SSZ offset from the current position and advances by 4 bytes. Returns ErrUnexpectedEOF if fewer than 4 bytes remain.

func (*BufferDecoder) DecodeOffsetAt added in v1.2.0

func (e *BufferDecoder) DecodeOffsetAt(pos int) uint32

DecodeOffsetAt reads a 4-byte little-endian SSZ offset at the given absolute position without advancing the current read position. The caller must ensure pos is within bounds.

func (*BufferDecoder) DecodeUint8 added in v1.2.0

func (e *BufferDecoder) DecodeUint8() (uint8, error)

DecodeUint8 reads a single byte and returns it as uint8. Returns ErrUnexpectedEOF if no bytes remain.

func (*BufferDecoder) DecodeUint16 added in v1.2.0

func (e *BufferDecoder) DecodeUint16() (uint16, error)

DecodeUint16 reads 2 bytes in little-endian order and returns a uint16. Returns ErrUnexpectedEOF if fewer than 2 bytes remain.

func (*BufferDecoder) DecodeUint32 added in v1.2.0

func (e *BufferDecoder) DecodeUint32() (uint32, error)

DecodeUint32 reads 4 bytes in little-endian order and returns a uint32. Returns ErrUnexpectedEOF if fewer than 4 bytes remain.

func (*BufferDecoder) DecodeUint64 added in v1.2.0

func (e *BufferDecoder) DecodeUint64() (uint64, error)

DecodeUint64 reads 8 bytes in little-endian order and returns a uint64. Returns ErrUnexpectedEOF if fewer than 8 bytes remain.

func (*BufferDecoder) GetLength added in v1.2.0

func (e *BufferDecoder) GetLength() int

GetLength returns the number of remaining bytes available for reading, taking into account the current limit.

func (*BufferDecoder) GetPosition added in v1.2.0

func (e *BufferDecoder) GetPosition() int

GetPosition returns the current read position in the buffer.

func (*BufferDecoder) PopLimit added in v1.2.0

func (e *BufferDecoder) PopLimit() int

PopLimit removes the most recently pushed limit and returns the number of unconsumed bytes that were remaining within that limit.

func (*BufferDecoder) PushLimit added in v1.2.0

func (e *BufferDecoder) PushLimit(limit int)

PushLimit restricts reading to the next limit bytes from the current position. If the limit extends beyond the enclosing limit, it is clamped. Limits can be nested and must be removed with PopLimit.

func (*BufferDecoder) Seekable added in v1.2.0

func (e *BufferDecoder) Seekable() bool

Seekable returns true, indicating that BufferDecoder supports random-access offset reads via DecodeOffsetAt and byte skipping via SkipBytes.

func (*BufferDecoder) SkipBytes added in v1.2.0

func (e *BufferDecoder) SkipBytes(n int)

SkipBytes advances the read position by n bytes without reading the data.

type BufferEncoder added in v1.2.0

type BufferEncoder struct {
	// contains filtered or unexported fields
}

BufferEncoder is a seekable Encoder implementation backed by an in-memory byte buffer. It supports random-access offset writes via EncodeOffsetAt.

func NewBufferEncoder added in v1.2.0

func NewBufferEncoder(buffer []byte) *BufferEncoder

NewBufferEncoder creates a new BufferEncoder using the provided buffer. The buffer should have sufficient capacity for the expected output.

func (*BufferEncoder) EncodeBool added in v1.2.0

func (e *BufferEncoder) EncodeBool(v bool)

EncodeBool writes a single-byte boolean value (0x00 or 0x01) at the current position and advances by 1 byte.

func (*BufferEncoder) EncodeBytes added in v1.2.0

func (e *BufferEncoder) EncodeBytes(v []byte)

EncodeBytes copies the given byte slice into the buffer at the current position and advances by len(v) bytes.

func (*BufferEncoder) EncodeOffset added in v1.2.0

func (e *BufferEncoder) EncodeOffset(v uint32)

EncodeOffset writes a 4-byte little-endian SSZ offset at the current position and advances by 4 bytes.

func (*BufferEncoder) EncodeOffsetAt added in v1.2.0

func (e *BufferEncoder) EncodeOffsetAt(pos int, v uint32)

EncodeOffsetAt writes a 4-byte little-endian SSZ offset at the given absolute position without advancing the current write position. This is used for back-patching offsets after dynamic-length fields have been written.

func (*BufferEncoder) EncodeUint8 added in v1.2.0

func (e *BufferEncoder) EncodeUint8(v uint8)

EncodeUint8 writes a single byte at the current position and advances by 1 byte.

func (*BufferEncoder) EncodeUint16 added in v1.2.0

func (e *BufferEncoder) EncodeUint16(v uint16)

EncodeUint16 writes a little-endian uint16 at the current position and advances by 2 bytes.

func (*BufferEncoder) EncodeUint32 added in v1.2.0

func (e *BufferEncoder) EncodeUint32(v uint32)

EncodeUint32 writes a little-endian uint32 at the current position and advances by 4 bytes.

func (*BufferEncoder) EncodeUint64 added in v1.2.0

func (e *BufferEncoder) EncodeUint64(v uint64)

EncodeUint64 writes a little-endian uint64 at the current position and advances by 8 bytes.

func (*BufferEncoder) EncodeZeroPadding added in v1.2.0

func (e *BufferEncoder) EncodeZeroPadding(n int)

EncodeZeroPadding writes n zero bytes at the current position and advances by n bytes. Uses clear for efficient zeroing.

func (*BufferEncoder) GetBuffer added in v1.2.0

func (e *BufferEncoder) GetBuffer() []byte

GetBuffer returns the buffer contents written so far (from start to current position).

func (*BufferEncoder) GetPosition added in v1.2.0

func (e *BufferEncoder) GetPosition() int

GetPosition returns the current write position in the buffer.

func (*BufferEncoder) Seekable added in v1.2.0

func (e *BufferEncoder) Seekable() bool

Seekable returns true, indicating that BufferEncoder supports random-access offset writes via EncodeOffsetAt.

func (*BufferEncoder) SetBuffer added in v1.2.0

func (e *BufferEncoder) SetBuffer(buffer []byte)

SetBuffer replaces the underlying buffer and resets the write position to the end of the provided buffer's length, using its full capacity for future writes.

type Decoder added in v1.2.0

type Decoder interface {
	Seekable() bool   // can use DecodeOffsetAt() and SkipBytes()
	GetPosition() int // return current position
	GetLength() int   // return remaining length
	PushLimit(limit int)
	PopLimit() int
	DecodeBool() (bool, error)
	DecodeUint8() (uint8, error)
	DecodeUint16() (uint16, error)
	DecodeUint32() (uint32, error)
	DecodeUint64() (uint64, error)
	DecodeBytes(buf []byte) ([]byte, error)
	DecodeBytesBuf(len int) ([]byte, error)
	DecodeOffset() (uint32, error)
	DecodeOffsetAt(pos int) uint32
	SkipBytes(n int)
}

Decoder is the interface for reading SSZ-encoded data. It supports both seekable (buffer-backed) and non-seekable (stream-backed) implementations.

type DynamicDecoder added in v1.2.0

type DynamicDecoder interface {
	UnmarshalSSZDecoder(ds DynamicSpecs, decoder Decoder) error
}

DynamicDecoder is the interface implemented by types that can unmarshal using dynamic SSZ and a decoder

type DynamicEncoder added in v1.2.0

type DynamicEncoder interface {
	MarshalSSZEncoder(ds DynamicSpecs, encoder Encoder) error
}

DynamicEncoder is the interface implemented by types that can marshal themselves using dynamic SSZ and an encoder

type DynamicHashRoot

type DynamicHashRoot interface {
	HashTreeRootWithDyn(ds DynamicSpecs, hh HashWalker) error
}

DynamicHashRoot is the interface implemented by types that can compute their SSZ hash tree root using dynamic specification values and a HashWalker.

type DynamicMarshaler

type DynamicMarshaler interface {
	MarshalSSZDyn(ds DynamicSpecs, buf []byte) ([]byte, error)
}

DynamicMarshaler is the interface implemented by types that can marshal themselves using dynamic SSZ

type DynamicSizer

type DynamicSizer interface {
	SizeSSZDyn(ds DynamicSpecs) int
}

DynamicSizer is the interface implemented by types that can calculate their own SSZ size dynamically

type DynamicSpecs added in v1.1.0

type DynamicSpecs interface {
	ResolveSpecValue(name string) (bool, uint64, error)
}

DynamicSpecs is the interface for resolving dynamic specification values at runtime. Implementations provide named values (e.g., "SYNC_COMMITTEE_SIZE") that control SSZ field sizes.

ResolveSpecValue returns whether the named value exists, its uint64 value, and any error. The name may be a simple identifier or a mathematical expression referencing other spec values.

type DynamicUnmarshaler

type DynamicUnmarshaler interface {
	UnmarshalSSZDyn(ds DynamicSpecs, buf []byte) error
}

DynamicUnmarshaler is the interface implemented by types that can unmarshal using dynamic SSZ

type DynamicViewDecoder added in v1.3.0

type DynamicViewDecoder interface {
	UnmarshalSSZDecoderView(view any) func(ds DynamicSpecs, decoder Decoder) error
}

DynamicViewDecoder is the interface implemented by types that can unmarshal using dynamic SSZ, a decoder, and a view. Returns nil if the view is not supported, otherwise returns the decode function.

type DynamicViewEncoder added in v1.3.0

type DynamicViewEncoder interface {
	MarshalSSZEncoderView(view any) func(ds DynamicSpecs, encoder Encoder) error
}

DynamicViewEncoder is the interface implemented by types that can marshal themselves using dynamic SSZ, an encoder, and a view. Returns nil if the view is not supported, otherwise returns the encode function.

type DynamicViewHashRoot added in v1.3.0

type DynamicViewHashRoot interface {
	HashTreeRootWithDynView(view any) func(ds DynamicSpecs, hh HashWalker) error
}

DynamicViewHashRoot is the interface implemented by types that can calculate their own SSZ hash tree root dynamically. Returns nil if the view is not supported, otherwise returns the hash function.

type DynamicViewMarshaler added in v1.3.0

type DynamicViewMarshaler interface {
	MarshalSSZDynView(view any) func(ds DynamicSpecs, buf []byte) ([]byte, error)
}

DynamicViewMarshaler is the interface implemented by types that can marshal themselves using dynamic SSZ and a view. Returns nil if the view is not supported, otherwise returns the marshal function.

type DynamicViewSizer added in v1.3.0

type DynamicViewSizer interface {
	SizeSSZDynView(view any) func(ds DynamicSpecs) int
}

DynamicViewSizer is the interface implemented by types that can calculate their own SSZ size dynamically with a view. Returns nil if the view is not supported, otherwise returns the size function.

type DynamicViewUnmarshaler added in v1.3.0

type DynamicViewUnmarshaler interface {
	UnmarshalSSZDynView(view any) func(ds DynamicSpecs, buf []byte) error
}

DynamicViewUnmarshaler is the interface implemented by types that can unmarshal using dynamic SSZ and a view. Returns nil if the view is not supported, otherwise returns the unmarshal function.

type Encoder added in v1.2.0

type Encoder interface {
	Seekable() bool // can use EncodeOffsetAt()
	GetPosition() int
	GetBuffer() []byte       // return the output buffer (or a temp buffer if Seekable() is false)
	SetBuffer(buffer []byte) // set new output buffer (or write the buffer to the stream if Seekable() is false)
	EncodeBool(v bool)
	EncodeUint8(v uint8)
	EncodeUint16(v uint16)
	EncodeUint32(v uint32)
	EncodeUint64(v uint64)
	EncodeBytes(v []byte)
	EncodeOffset(v uint32)
	EncodeOffsetAt(pos int, v uint32)
	EncodeZeroPadding(n int)
}

Encoder is the interface for writing SSZ-encoded data. It supports both seekable (buffer-backed) and non-seekable (stream-backed) implementations.

type FastsszHashRoot

type FastsszHashRoot interface {
	HashTreeRoot() ([32]byte, error)
}

FastsszHashRoot is the interface implemented by types that can compute their SSZ hash tree root using fastssz.

type FastsszMarshaler

type FastsszMarshaler interface {
	MarshalSSZTo(dst []byte) ([]byte, error)
	MarshalSSZ() ([]byte, error)
	SizeSSZ() int
}

FastsszMarshaler is the interface implemented by types that can marshal themselves into valid SZZ using fastssz.

type FastsszUnmarshaler

type FastsszUnmarshaler interface {
	UnmarshalSSZ(buf []byte) error
}

FastsszUnmarshaler is the interface implemented by types that can unmarshal a SSZ description of themselves

type HashWalker

type HashWalker interface {
	// Hash returns the latest hash generated during merkleize
	Hash() []byte

	// Methods for appending single values
	AppendBool(b bool)
	AppendUint8(i uint8)
	AppendUint16(i uint16)
	AppendUint32(i uint32)
	AppendUint64(i uint64)
	AppendBytes32(b []byte)

	// Methods for putting values into the buffer
	PutUint64Array(b []uint64, maxCapacity ...uint64)
	PutUint64(i uint64)
	PutUint32(i uint32)
	PutUint16(i uint16)
	PutUint8(i uint8)
	PutBitlist(bb []byte, maxSize uint64)
	PutProgressiveBitlist(bb []byte)
	PutBool(b bool)
	PutBytes(b []byte)

	// Buffer manipulation methods
	FillUpTo32()
	Append(i []byte)
	Index() int                      // deprecated: use StartTree(TreeTypeNone) instead
	CurrentIndex() int               // returns the current buffer index (debug only)
	StartTree(treeType TreeType) int // start a new SSZ object scope and return the buffer index (close with Merkleize*)
	Collapse()                       // Hint to collapse accumulated chunks if threshold is reached

	// temporary buffer methods
	WithTemp(func(tmp []byte) []byte)

	// Merkleization methods
	Merkleize(indx int)
	MerkleizeWithMixin(indx int, num, limit uint64)
	MerkleizeProgressive(indx int)
	MerkleizeProgressiveWithMixin(indx int, num uint64)
	MerkleizeProgressiveWithActiveFields(indx int, activeFields []byte)

	// HashRoot methods
	HashRoot() ([32]byte, error)
}

HashWalker is our own interface that mirrors fastssz.HashWalker This allows us to avoid importing fastssz directly while still being compatible with types that implement HashTreeRootWith

type StreamDecoder added in v1.2.0

type StreamDecoder struct {
	// contains filtered or unexported fields
}

StreamDecoder is a non-seekable Decoder implementation that reads SSZ data from an io.Reader. It uses an internal buffer for efficient sequential reads but does not support DecodeOffsetAt or SkipBytes.

func NewStreamDecoder added in v1.2.0

func NewStreamDecoder(reader io.Reader, totalLen, maxBufSize int) *StreamDecoder

NewStreamDecoder creates a new StreamDecoder that reads SSZ data from the provided io.Reader. totalLen specifies the total expected byte length of the SSZ payload. maxBufSize controls the maximum internal read buffer size; if <= 0, DefaultStreamDecoderBufSize is used.

func (*StreamDecoder) DecodeBool added in v1.2.0

func (e *StreamDecoder) DecodeBool() (bool, error)

func (*StreamDecoder) DecodeBytes added in v1.2.0

func (e *StreamDecoder) DecodeBytes(buf []byte) ([]byte, error)

func (*StreamDecoder) DecodeBytesBuf added in v1.2.0

func (e *StreamDecoder) DecodeBytesBuf(l int) ([]byte, error)

func (*StreamDecoder) DecodeOffset added in v1.2.0

func (e *StreamDecoder) DecodeOffset() (uint32, error)

func (*StreamDecoder) DecodeOffsetAt added in v1.2.0

func (e *StreamDecoder) DecodeOffsetAt(pos int) uint32

func (*StreamDecoder) DecodeUint8 added in v1.2.0

func (e *StreamDecoder) DecodeUint8() (uint8, error)

func (*StreamDecoder) DecodeUint16 added in v1.2.0

func (e *StreamDecoder) DecodeUint16() (uint16, error)

func (*StreamDecoder) DecodeUint32 added in v1.2.0

func (e *StreamDecoder) DecodeUint32() (uint32, error)

func (*StreamDecoder) DecodeUint64 added in v1.2.0

func (e *StreamDecoder) DecodeUint64() (uint64, error)

func (*StreamDecoder) GetLength added in v1.2.0

func (e *StreamDecoder) GetLength() int

func (*StreamDecoder) GetPosition added in v1.2.0

func (e *StreamDecoder) GetPosition() int

func (*StreamDecoder) PopLimit added in v1.2.0

func (e *StreamDecoder) PopLimit() int

func (*StreamDecoder) PushLimit added in v1.2.0

func (e *StreamDecoder) PushLimit(limit int)

func (*StreamDecoder) Seekable added in v1.2.0

func (e *StreamDecoder) Seekable() bool

func (*StreamDecoder) SkipBytes added in v1.2.0

func (e *StreamDecoder) SkipBytes(n int)

type StreamEncoder added in v1.2.0

type StreamEncoder struct {
	// contains filtered or unexported fields
}

StreamEncoder is a non-seekable Encoder implementation that writes SSZ data to an io.Writer with internal buffering. It does not support EncodeOffsetAt.

func NewStreamEncoder added in v1.2.0

func NewStreamEncoder(writer io.Writer, bufSize int) *StreamEncoder

NewStreamEncoder creates a new StreamEncoder that writes SSZ data to the provided io.Writer. bufSize controls the internal write buffer size; if <= 0, DefaultStreamEncoderBufSize is used.

func (*StreamEncoder) EncodeBool added in v1.2.0

func (e *StreamEncoder) EncodeBool(v bool)

func (*StreamEncoder) EncodeBytes added in v1.2.0

func (e *StreamEncoder) EncodeBytes(v []byte)

func (*StreamEncoder) EncodeOffset added in v1.2.0

func (e *StreamEncoder) EncodeOffset(v uint32)

func (*StreamEncoder) EncodeOffsetAt added in v1.2.0

func (e *StreamEncoder) EncodeOffsetAt(pos int, v uint32)

func (*StreamEncoder) EncodeUint8 added in v1.2.0

func (e *StreamEncoder) EncodeUint8(v uint8)

func (*StreamEncoder) EncodeUint16 added in v1.2.0

func (e *StreamEncoder) EncodeUint16(v uint16)

func (*StreamEncoder) EncodeUint32 added in v1.2.0

func (e *StreamEncoder) EncodeUint32(v uint32)

func (*StreamEncoder) EncodeUint64 added in v1.2.0

func (e *StreamEncoder) EncodeUint64(v uint64)

func (*StreamEncoder) EncodeZeroPadding added in v1.2.0

func (e *StreamEncoder) EncodeZeroPadding(n int)

func (*StreamEncoder) Flush added in v1.3.0

func (e *StreamEncoder) Flush()

Flush flushes any buffered data to the underlying io.Writer.

func (*StreamEncoder) GetBuffer added in v1.2.0

func (e *StreamEncoder) GetBuffer() []byte

func (*StreamEncoder) GetPosition added in v1.2.0

func (e *StreamEncoder) GetPosition() int

func (*StreamEncoder) GetWriteError added in v1.2.0

func (e *StreamEncoder) GetWriteError() error

GetWriteError returns the first write error encountered during encoding, or nil if no errors occurred.

func (*StreamEncoder) Seekable added in v1.2.0

func (e *StreamEncoder) Seekable() bool

func (*StreamEncoder) SetBuffer added in v1.2.0

func (e *StreamEncoder) SetBuffer(buffer []byte)

type TreeType added in v1.3.0

type TreeType uint8

TreeType specifies the merkle tree shape for an SSZ object scope.

const (
	// TreeTypeNone disables incremental hashing for this scope.
	TreeTypeNone TreeType = iota
	// TreeTypeBinary is the standard SSZ binary merkle tree.
	TreeTypeBinary
	// TreeTypeProgressive is the progressive merkle tree (subtree_fill_progressive).
	TreeTypeProgressive
)

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL