Files
prysm/beacon-chain/db/kv/encoding.go
terence 774b9a7159 Migrate Prysm repo to Offchain Labs organization ahead of Pectra V6 (#15140)
* Migrate Prysm repo to Offchain Labs organization ahead of Pectra upgrade v6

* Replace prysmaticlabs with OffchainLabs on general markdowns

* Update mock

* Gazelle and add mock.go to excluded generated mock file
2025-04-10 15:40:39 +00:00

87 lines
1.9 KiB
Go

package kv
import (
"context"
"errors"
"reflect"
"github.com/OffchainLabs/prysm/v6/monitoring/tracing/trace"
ethpb "github.com/OffchainLabs/prysm/v6/proto/prysm/v1alpha1"
"github.com/golang/snappy"
fastssz "github.com/prysmaticlabs/fastssz"
"google.golang.org/protobuf/proto"
)
func decode(ctx context.Context, data []byte, dst proto.Message) error {
ctx, span := trace.StartSpan(ctx, "BeaconDB.decode")
defer span.End()
if ctx.Err() != nil {
return ctx.Err()
}
data, err := snappy.Decode(nil, data)
if err != nil {
return err
}
if isSSZStorageFormat(dst) {
return dst.(fastssz.Unmarshaler).UnmarshalSSZ(data)
}
return proto.Unmarshal(data, dst)
}
func encode(ctx context.Context, msg proto.Message) ([]byte, error) {
ctx, span := trace.StartSpan(ctx, "BeaconDB.encode")
defer span.End()
if ctx.Err() != nil {
return nil, ctx.Err()
}
if msg == nil || reflect.ValueOf(msg).IsNil() {
return nil, errors.New("cannot encode nil message")
}
var enc []byte
var err error
if isSSZStorageFormat(msg) {
enc, err = msg.(fastssz.Marshaler).MarshalSSZ()
if err != nil {
return nil, err
}
} else {
enc, err = proto.Marshal(msg)
if err != nil {
return nil, err
}
}
return snappy.Encode(nil, enc), nil
}
// isSSZStorageFormat returns true if the object type should be saved in SSZ encoded format.
func isSSZStorageFormat(obj interface{}) bool {
switch obj.(type) {
case *ethpb.BeaconState:
return true
case *ethpb.SignedBeaconBlock:
return true
case *ethpb.SignedAggregateAttestationAndProof:
return true
case *ethpb.BeaconBlock:
return true
case *ethpb.Attestation, *ethpb.AttestationElectra:
return true
case *ethpb.Deposit:
return true
case *ethpb.AttesterSlashing, *ethpb.AttesterSlashingElectra:
return true
case *ethpb.ProposerSlashing:
return true
case *ethpb.VoluntaryExit:
return true
case *ethpb.ValidatorRegistrationV1:
return true
default:
return false
}
}