Compare commits

...

8 Commits

Author SHA1 Message Date
Saolyn
e27377ef9d Add deposit snapshot to DownloadFinalizedData 2025-01-22 18:07:05 +01:00
Radosław Kapka
2845ab9365 Update proto_test.go to Electra (#14817) 2025-01-21 20:30:52 +00:00
Radosław Kapka
4f43c15ebb Update rewards API to Electra (#14816) 2025-01-21 20:13:36 +00:00
Radosław Kapka
e473d7cc4d Use SingleAttestation for Fulu in p2p attestation map (#14809)
* Use `SingleAttestation` for Fulu in p2p attestation map.

* Fix `TestExtractDataType`.

---------

Co-authored-by: Manu NALEPA <enalepa@offchainlabs.com>
2025-01-20 10:35:52 +00:00
Potuz
794a05af26 Remove unused Copy() from the ReadOnlyBeaconBlock interface (#14811) 2025-01-19 19:56:14 +00:00
hidewrong
15df13c7e6 Signed-off-by: hidewrong <hidewrong@outlook.com> (#14792)
Signed-off-by: hidewrong <hidewrong@outlook.com>
2025-01-17 15:59:29 +00:00
Potuz
b76f7fed2f move credential helpers to ReadOnlyValidator methods (#14808)
* move credential helpers to ReadOnlyValidator methods

* Changelog + Gazelle

* Fix nil tests

* Fix more nil tests

* Fix another nil test
2025-01-17 12:37:08 +00:00
james-prysm
e263687ea5 Remote Signer: Electra (#14477)
* updating blockv2 to handle electra blocks

* adding aggregate attesation and proof electra

* gaz

* changelogs

* updating web3signer dependency

* test mock was flipped

* fixing hex value

* accidently checked in dependency changes

* preston feedback

* readding old metrics to not break linting

* review feedback and changelog

* gaz
2025-01-16 17:51:59 +00:00
49 changed files with 1302 additions and 430 deletions

View File

@@ -26,13 +26,15 @@ var errCheckpointBlockMismatch = errors.New("mismatch between checkpoint sync st
// OriginData represents the BeaconState and ReadOnlySignedBeaconBlock necessary to start an empty Beacon Node
// using Checkpoint Sync.
type OriginData struct {
sb []byte
bb []byte
st state.BeaconState
b interfaces.ReadOnlySignedBeaconBlock
vu *detect.VersionedUnmarshaler
br [32]byte
sr [32]byte
sb []byte
bb []byte
dsb []byte // Deposit snapshot serialized bytes
st state.BeaconState
b interfaces.ReadOnlySignedBeaconBlock
vu *detect.VersionedUnmarshaler
br [32]byte
sr [32]byte
dr [32]byte // Deposit snapshot root
}
// SaveBlock saves the downloaded block to a unique file in the given path.
@@ -49,6 +51,12 @@ func (o *OriginData) SaveState(dir string) (string, error) {
return statePath, file.WriteFile(statePath, o.StateBytes())
}
// SaveDepositSnapshot saves the downloaded deposit snapshot to a unique file in the given path.
func (o *OriginData) SaveDepositSnapshot(dir string) (string, error) {
depositPath := path.Join(dir, fname("deposit_snapshot", o.vu, o.st.Slot(), o.dr))
return depositPath, file.WriteFile(depositPath, o.DepositSnapshotBytes())
}
// StateBytes returns the ssz-encoded bytes of the downloaded BeaconState value.
func (o *OriginData) StateBytes() []byte {
return o.sb
@@ -59,6 +67,11 @@ func (o *OriginData) BlockBytes() []byte {
return o.bb
}
// DepositSnapshotBytes returns the serialized bytes of the downloaded DepositSnapshot value.
func (o *OriginData) DepositSnapshotBytes() []byte {
return o.dsb
}
func fname(prefix string, vu *detect.VersionedUnmarshaler, slot primitives.Slot, root [32]byte) string {
return fmt.Sprintf("%s_%s_%s_%d-%#x.ssz", prefix, vu.Config.ConfigName, version.String(vu.Fork), slot, root)
}
@@ -112,20 +125,35 @@ func DownloadFinalizedData(ctx context.Context, client *Client) (*OriginData, er
return nil, errors.Wrapf(err, "failed to compute htr for finalized state at slot=%d", s.Slot())
}
log.
WithField("blockSlot", b.Block().Slot()).
WithField("stateSlot", s.Slot()).
WithField("stateRoot", hexutil.Encode(sr[:])).
WithField("blockRoot", hexutil.Encode(br[:])).
Info("Downloaded checkpoint sync state and block.")
// Download deposit snapshot
dsb, err := client.GetDepositSnapshot(ctx)
if err != nil {
return nil, errors.Wrap(err, "error retrieving deposit snapshot")
}
dr, err := helpers.ComputeDepositSnapshotRoot(dsb)
if err != nil {
return nil, errors.Wrap(err, "error computing deposit snapshot root")
}
log.WithFields(logrus.Fields{
"blockSlot": b.Block().Slot(),
"stateSlot": s.Slot(),
"stateRoot": hexutil.Encode(sr[:]),
"blockRoot": hexutil.Encode(br[:]),
"depositRoot": hexutil.Encode(dr[:]),
}).Info("Downloaded checkpoint sync state, block, and deposit snapshot.")
return &OriginData{
st: s,
b: b,
sb: sb,
bb: bb,
vu: vu,
br: br,
sr: sr,
st: s,
b: b,
sb: sb,
bb: bb,
dsb: dsb,
vu: vu,
br: br,
sr: sr,
dr: dr,
}, nil
}

View File

@@ -35,6 +35,7 @@ const (
getStatePath = "/eth/v2/debug/beacon/states"
getNodeVersionPath = "/eth/v1/node/version"
changeBLStoExecutionPath = "/eth/v1/beacon/pool/bls_to_execution_changes"
getDepositSnapshot = "/eth/v1/beacon/deposit_snapshot"
)
// StateOrBlockId represents the block_id / state_id parameters that several of the Eth Beacon API methods accept.
@@ -361,3 +362,12 @@ func (fsr *forkScheduleResponse) OrderedForkSchedule() (forks.OrderedSchedule, e
sort.Sort(ofs)
return ofs, nil
}
// GetDepositSnapshot calls a beacon API endpoint to retrieve the EIP-4881 Deposit Tree Snapshot.
func (c *Client) GetDepositSnapshot(ctx context.Context) ([]byte, error) {
b, err := c.Get(ctx, getDepositSnapshot, client.WithSSZEncoding())
if err != nil {
return nil, err
}
return b, nil
}

View File

@@ -9,6 +9,7 @@ import (
"github.com/pkg/errors"
"github.com/prysmaticlabs/prysm/v5/beacon-chain/core/helpers"
"github.com/prysmaticlabs/prysm/v5/beacon-chain/state"
state_native "github.com/prysmaticlabs/prysm/v5/beacon-chain/state/state-native"
"github.com/prysmaticlabs/prysm/v5/config/params"
"github.com/prysmaticlabs/prysm/v5/consensus-types/primitives"
"github.com/prysmaticlabs/prysm/v5/encoding/bytesutil"
@@ -233,13 +234,18 @@ func ProcessConsolidationRequests(ctx context.Context, st state.BeaconState, req
return fmt.Errorf("failed to fetch source validator: %w", err) // This should never happen.
}
roSrcV, err := state_native.NewValidator(srcV)
if err != nil {
return err
}
tgtV, err := st.ValidatorAtIndexReadOnly(tgtIdx)
if err != nil {
return fmt.Errorf("failed to fetch target validator: %w", err) // This should never happen.
}
// Verify source withdrawal credentials
if !helpers.HasExecutionWithdrawalCredentials(srcV) {
if !roSrcV.HasExecutionWithdrawalCredentials() {
continue
}
// Confirm source_validator.withdrawal_credentials[12:] == consolidation_request.source_address
@@ -248,7 +254,7 @@ func ProcessConsolidationRequests(ctx context.Context, st state.BeaconState, req
}
// Target validator must have their withdrawal credentials set appropriately.
if !helpers.HasCompoundingWithdrawalCredential(tgtV) {
if !tgtV.HasCompoundingWithdrawalCredentials() {
continue
}
@@ -364,7 +370,7 @@ func IsValidSwitchToCompoundingRequest(st state.BeaconState, req *enginev1.Conso
return false
}
if !helpers.HasETH1WithdrawalCredential(srcV) {
if !srcV.HasETH1WithdrawalCredentials() {
return false
}

View File

@@ -3,7 +3,6 @@ package electra
import (
"fmt"
"github.com/prysmaticlabs/prysm/v5/beacon-chain/core/helpers"
"github.com/prysmaticlabs/prysm/v5/beacon-chain/state"
"github.com/prysmaticlabs/prysm/v5/config/params"
ethpb "github.com/prysmaticlabs/prysm/v5/proto/prysm/v1alpha1"
@@ -40,7 +39,7 @@ func ProcessEffectiveBalanceUpdates(st state.BeaconState) error {
// Update effective balances with hysteresis.
validatorFunc := func(idx int, val state.ReadOnlyValidator) (newVal *ethpb.Validator, err error) {
if val == nil {
if val.IsNil() {
return nil, fmt.Errorf("validator %d is nil in state", idx)
}
if idx >= len(bals) {
@@ -49,7 +48,7 @@ func ProcessEffectiveBalanceUpdates(st state.BeaconState) error {
balance := bals[idx]
effectiveBalanceLimit := params.BeaconConfig().MinActivationBalance
if helpers.HasCompoundingWithdrawalCredential(val) {
if val.HasCompoundingWithdrawalCredentials() {
effectiveBalanceLimit = params.BeaconConfig().MaxEffectiveBalanceElectra
}

View File

@@ -77,7 +77,7 @@ func TestProcessEffectiveBalnceUpdates(t *testing.T) {
Validators: []*eth.Validator{
{
EffectiveBalance: params.BeaconConfig().MinActivationBalance / 2,
WithdrawalCredentials: nil,
WithdrawalCredentials: make([]byte, 32),
},
},
Balances: []uint64{

View File

@@ -194,7 +194,7 @@ func UpgradeToElectra(beaconState state.BeaconState) (state.BeaconState, error)
if val.ActivationEpoch() == params.BeaconConfig().FarFutureEpoch {
preActivationIndices = append(preActivationIndices, primitives.ValidatorIndex(index))
}
if helpers.HasCompoundingWithdrawalCredential(val) {
if val.HasCompoundingWithdrawalCredentials() {
compoundWithdrawalIndices = append(compoundWithdrawalIndices, primitives.ValidatorIndex(index))
}
return nil

View File

@@ -116,7 +116,7 @@ func ProcessWithdrawalRequests(ctx context.Context, st state.BeaconState, wrs []
return nil, err
}
// Verify withdrawal credentials
hasCorrectCredential := helpers.HasExecutionWithdrawalCredentials(validator)
hasCorrectCredential := validator.HasExecutionWithdrawalCredentials()
wc := validator.GetWithdrawalCredentials()
isCorrectSourceAddress := bytes.Equal(wc[12:], wr.SourceAddress)
if !hasCorrectCredential || !isCorrectSourceAddress {
@@ -165,7 +165,7 @@ func ProcessWithdrawalRequests(ctx context.Context, st state.BeaconState, wrs []
hasExcessBalance := vBal > params.BeaconConfig().MinActivationBalance+pendingBalanceToWithdraw
// Only allow partial withdrawals with compounding withdrawal credentials
if helpers.HasCompoundingWithdrawalCredential(validator) && hasSufficientEffectiveBalance && hasExcessBalance {
if validator.HasCompoundingWithdrawalCredentials() && hasSufficientEffectiveBalance && hasExcessBalance {
// Spec definition:
// to_withdraw = min(
// state.balances[index] - MIN_ACTIVATION_BALANCE - pending_balance_to_withdraw,

View File

@@ -85,7 +85,7 @@ func UpgradeToFulu(beaconState state.BeaconState) (state.BeaconState, error) {
if val.ActivationEpoch() == params.BeaconConfig().FarFutureEpoch {
preActivationIndices = append(preActivationIndices, primitives.ValidatorIndex(index))
}
if helpers.HasCompoundingWithdrawalCredential(val) {
if val.HasCompoundingWithdrawalCredentials() {
compoundWithdrawalIndices = append(compoundWithdrawalIndices, primitives.ValidatorIndex(index))
}
return nil

View File

@@ -25,7 +25,6 @@ go_library(
"//beacon-chain/state:go_default_library",
"//config/fieldparams:go_default_library",
"//config/params:go_default_library",
"//consensus-types/interfaces:go_default_library",
"//consensus-types/primitives:go_default_library",
"//container/slice:go_default_library",
"//container/trie:go_default_library",

View File

@@ -14,7 +14,6 @@ import (
"github.com/prysmaticlabs/prysm/v5/beacon-chain/state"
fieldparams "github.com/prysmaticlabs/prysm/v5/config/fieldparams"
"github.com/prysmaticlabs/prysm/v5/config/params"
"github.com/prysmaticlabs/prysm/v5/consensus-types/interfaces"
"github.com/prysmaticlabs/prysm/v5/consensus-types/primitives"
"github.com/prysmaticlabs/prysm/v5/crypto/hash"
"github.com/prysmaticlabs/prysm/v5/encoding/bytesutil"
@@ -515,63 +514,6 @@ func LastActivatedValidatorIndex(ctx context.Context, st state.ReadOnlyBeaconSta
return lastActivatedvalidatorIndex, nil
}
// hasETH1WithdrawalCredential returns whether the validator has an ETH1
// Withdrawal prefix. It assumes that the caller has a lock on the state
func HasETH1WithdrawalCredential(val interfaces.WithWithdrawalCredentials) bool {
if val == nil {
return false
}
return isETH1WithdrawalCredential(val.GetWithdrawalCredentials())
}
func isETH1WithdrawalCredential(creds []byte) bool {
return bytes.HasPrefix(creds, []byte{params.BeaconConfig().ETH1AddressWithdrawalPrefixByte})
}
// HasCompoundingWithdrawalCredential checks if the validator has a compounding withdrawal credential.
// New in Electra EIP-7251: https://eips.ethereum.org/EIPS/eip-7251
//
// Spec definition:
//
// def has_compounding_withdrawal_credential(validator: Validator) -> bool:
// """
// Check if ``validator`` has an 0x02 prefixed "compounding" withdrawal credential.
// """
// return is_compounding_withdrawal_credential(validator.withdrawal_credentials)
func HasCompoundingWithdrawalCredential(v interfaces.WithWithdrawalCredentials) bool {
if v == nil {
return false
}
return IsCompoundingWithdrawalCredential(v.GetWithdrawalCredentials())
}
// IsCompoundingWithdrawalCredential checks if the credentials are a compounding withdrawal credential.
//
// Spec definition:
//
// def is_compounding_withdrawal_credential(withdrawal_credentials: Bytes32) -> bool:
// return withdrawal_credentials[:1] == COMPOUNDING_WITHDRAWAL_PREFIX
func IsCompoundingWithdrawalCredential(creds []byte) bool {
return bytes.HasPrefix(creds, []byte{params.BeaconConfig().CompoundingWithdrawalPrefixByte})
}
// HasExecutionWithdrawalCredentials checks if the validator has an execution withdrawal credential or compounding credential.
// New in Electra EIP-7251: https://eips.ethereum.org/EIPS/eip-7251
//
// Spec definition:
//
// def has_execution_withdrawal_credential(validator: Validator) -> bool:
// """
// Check if ``validator`` has a 0x01 or 0x02 prefixed withdrawal credential.
// """
// return has_compounding_withdrawal_credential(validator) or has_eth1_withdrawal_credential(validator)
func HasExecutionWithdrawalCredentials(v interfaces.WithWithdrawalCredentials) bool {
if v == nil {
return false
}
return HasCompoundingWithdrawalCredential(v) || HasETH1WithdrawalCredential(v)
}
// IsSameWithdrawalCredentials returns true if both validators have the same withdrawal credentials.
//
// return a.withdrawal_credentials[12:] == b.withdrawal_credentials[12:]
@@ -606,10 +548,10 @@ func IsFullyWithdrawableValidator(val state.ReadOnlyValidator, balance uint64, e
// Electra / EIP-7251 logic
if fork >= version.Electra {
return HasExecutionWithdrawalCredentials(val) && val.WithdrawableEpoch() <= epoch
return val.HasExecutionWithdrawalCredentials() && val.WithdrawableEpoch() <= epoch
}
return HasETH1WithdrawalCredential(val) && val.WithdrawableEpoch() <= epoch
return val.HasETH1WithdrawalCredentials() && val.WithdrawableEpoch() <= epoch
}
// IsPartiallyWithdrawableValidator returns whether the validator is able to perform a
@@ -650,7 +592,7 @@ func isPartiallyWithdrawableValidatorElectra(val state.ReadOnlyValidator, balanc
hasMaxBalance := val.EffectiveBalance() == maxEB
hasExcessBalance := balance > maxEB
return HasExecutionWithdrawalCredentials(val) &&
return val.HasExecutionWithdrawalCredentials() &&
hasMaxBalance &&
hasExcessBalance
}
@@ -670,7 +612,7 @@ func isPartiallyWithdrawableValidatorElectra(val state.ReadOnlyValidator, balanc
func isPartiallyWithdrawableValidatorCapella(val state.ReadOnlyValidator, balance uint64, epoch primitives.Epoch) bool {
hasMaxBalance := val.EffectiveBalance() == params.BeaconConfig().MaxEffectiveBalance
hasExcessBalance := balance > params.BeaconConfig().MaxEffectiveBalance
return HasETH1WithdrawalCredential(val) && hasExcessBalance && hasMaxBalance
return val.HasETH1WithdrawalCredentials() && hasExcessBalance && hasMaxBalance
}
// ValidatorMaxEffectiveBalance returns the maximum effective balance for a validator.
@@ -686,7 +628,7 @@ func isPartiallyWithdrawableValidatorCapella(val state.ReadOnlyValidator, balanc
// else:
// return MIN_ACTIVATION_BALANCE
func ValidatorMaxEffectiveBalance(val state.ReadOnlyValidator) uint64 {
if HasCompoundingWithdrawalCredential(val) {
if val.HasCompoundingWithdrawalCredentials() {
return params.BeaconConfig().MaxEffectiveBalanceElectra
}
return params.BeaconConfig().MinActivationBalance

View File

@@ -910,13 +910,15 @@ func TestProposerIndexFromCheckpoint(t *testing.T) {
func TestHasETH1WithdrawalCredentials(t *testing.T) {
creds := []byte{0xFA, 0xCC}
v := &ethpb.Validator{WithdrawalCredentials: creds}
require.Equal(t, false, helpers.HasETH1WithdrawalCredential(v))
roV, err := state_native.NewValidator(v)
require.NoError(t, err)
require.Equal(t, false, roV.HasETH1WithdrawalCredentials())
creds = []byte{params.BeaconConfig().ETH1AddressWithdrawalPrefixByte, 0xCC}
v = &ethpb.Validator{WithdrawalCredentials: creds}
require.Equal(t, true, helpers.HasETH1WithdrawalCredential(v))
roV, err = state_native.NewValidator(v)
require.NoError(t, err)
require.Equal(t, true, roV.HasETH1WithdrawalCredentials())
// No Withdrawal cred
v = &ethpb.Validator{}
require.Equal(t, false, helpers.HasETH1WithdrawalCredential(v))
}
func TestHasCompoundingWithdrawalCredential(t *testing.T) {
@@ -931,11 +933,12 @@ func TestHasCompoundingWithdrawalCredential(t *testing.T) {
{"Does not have compounding withdrawal credential",
&ethpb.Validator{WithdrawalCredentials: bytesutil.PadTo([]byte{0x00}, 32)},
false},
{"Handles nil case", nil, false},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
assert.Equal(t, tt.want, helpers.HasCompoundingWithdrawalCredential(tt.validator))
roV, err := state_native.NewValidator(tt.validator)
require.NoError(t, err)
assert.Equal(t, tt.want, roV.HasCompoundingWithdrawalCredentials())
})
}
}
@@ -955,11 +958,12 @@ func TestHasExecutionWithdrawalCredentials(t *testing.T) {
{"Does not have compounding withdrawal credential or eth1 withdrawal credential",
&ethpb.Validator{WithdrawalCredentials: bytesutil.PadTo([]byte{0x00}, 32)},
false},
{"Handles nil case", nil, false},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
assert.Equal(t, tt.want, helpers.HasExecutionWithdrawalCredentials(tt.validator))
roV, err := state_native.NewValidator(tt.validator)
require.NoError(t, err)
assert.Equal(t, tt.want, roV.HasExecutionWithdrawalCredentials())
})
}
}

View File

@@ -213,3 +213,15 @@ func MinEpochsForBlockRequests() primitives.Epoch {
return params.BeaconConfig().MinValidatorWithdrawabilityDelay +
primitives.Epoch(params.BeaconConfig().ChurnLimitQuotient/2)
}
func ComputeDepositSnapshotRoot(marshaled []byte) ([32]byte, error) {
ds := &v1alpha1.DepositSnapshot{}
err := ds.UnmarshalSSZ(marshaled)
if err != nil {
return [32]byte{}, err
}
if len(ds.DepositRoot) != 32 {
return [32]byte{}, errors.New("invalid deposit root length")
}
return bytesutil.ToBytes32(ds.DepositRoot), nil
}

View File

@@ -123,7 +123,7 @@ func InitializeDataMaps() {
return &ethpb.SingleAttestation{}, nil
},
bytesutil.ToBytes4(params.BeaconConfig().FuluForkVersion): func() (ethpb.Att, error) {
return &ethpb.AttestationElectra{}, nil
return &ethpb.SingleAttestation{}, nil
},
}

View File

@@ -461,7 +461,7 @@ func TestStreamEvents_OperationsEvents(t *testing.T) {
defer testSync.cleanup()
st := tc.getState()
v := &eth.Validator{ExitEpoch: math.MaxUint64, EffectiveBalance: params.BeaconConfig().MinActivationBalance}
v := &eth.Validator{ExitEpoch: math.MaxUint64, EffectiveBalance: params.BeaconConfig().MinActivationBalance, WithdrawalCredentials: make([]byte, 32)}
require.NoError(t, st.SetValidators([]*eth.Validator{v}))
currentSlot := primitives.Slot(0)
// to avoid slot processing

View File

@@ -63,6 +63,7 @@ go_test(
"//encoding/bytesutil:go_default_library",
"//network/httputil:go_default_library",
"//proto/prysm/v1alpha1:go_default_library",
"//runtime/version:go_default_library",
"//testing/assert:go_default_library",
"//testing/require:go_default_library",
"//testing/util:go_default_library",

View File

@@ -32,45 +32,52 @@ import (
"github.com/prysmaticlabs/prysm/v5/encoding/bytesutil"
"github.com/prysmaticlabs/prysm/v5/network/httputil"
eth "github.com/prysmaticlabs/prysm/v5/proto/prysm/v1alpha1"
"github.com/prysmaticlabs/prysm/v5/runtime/version"
"github.com/prysmaticlabs/prysm/v5/testing/assert"
"github.com/prysmaticlabs/prysm/v5/testing/require"
"github.com/prysmaticlabs/prysm/v5/testing/util"
)
func BlockRewardTestSetup(t *testing.T, forkName string) (state.BeaconState, interfaces.SignedBeaconBlock, error) {
func BlockRewardTestSetup(t *testing.T, ver int) (state.BeaconState, interfaces.SignedBeaconBlock, error) {
helpers.ClearCache()
var sbb interfaces.SignedBeaconBlock
var st state.BeaconState
var err error
switch forkName {
case "phase0":
switch ver {
case version.Phase0:
return nil, nil, errors.New("phase0 not supported")
case "altair":
case version.Altair:
st, err = util.NewBeaconStateAltair()
require.NoError(t, err)
b := util.HydrateSignedBeaconBlockAltair(util.NewBeaconBlockAltair())
sbb, err = blocks.NewSignedBeaconBlock(b)
require.NoError(t, err)
case "bellatrix":
case version.Bellatrix:
st, err = util.NewBeaconStateBellatrix()
require.NoError(t, err)
b := util.HydrateSignedBeaconBlockBellatrix(util.NewBeaconBlockBellatrix())
sbb, err = blocks.NewSignedBeaconBlock(b)
require.NoError(t, err)
case "capella":
case version.Capella:
st, err = util.NewBeaconStateCapella()
require.NoError(t, err)
b := util.HydrateSignedBeaconBlockCapella(util.NewBeaconBlockCapella())
sbb, err = blocks.NewSignedBeaconBlock(b)
require.NoError(t, err)
case "deneb":
case version.Deneb:
st, err = util.NewBeaconStateDeneb()
require.NoError(t, err)
b := util.HydrateSignedBeaconBlockDeneb(util.NewBeaconBlockDeneb())
sbb, err = blocks.NewSignedBeaconBlock(b)
require.NoError(t, err)
case version.Electra:
st, err = util.NewBeaconStateElectra()
require.NoError(t, err)
b := util.HydrateSignedBeaconBlockElectra(util.NewBeaconBlockElectra())
sbb, err = blocks.NewSignedBeaconBlock(b)
require.NoError(t, err)
default:
return nil, nil, errors.New("fork is not supported")
return nil, nil, fmt.Errorf("fork %s is not supported", version.String(ver))
}
valCount := 64
require.NoError(t, st.SetSlot(1))
@@ -102,20 +109,47 @@ func BlockRewardTestSetup(t *testing.T, forkName string) (state.BeaconState, int
require.NoError(t, st.SetBlockRoots(bRoots))
sbb.SetSlot(2)
// we have to set the proposer index to the value that will be randomly chosen (fortunately it's deterministic)
sbb.SetProposerIndex(12)
require.NoError(t, sbb.SetAttestations([]eth.Att{
&eth.Attestation{
AggregationBits: bitfield.Bitlist{0b00000111},
Data: util.HydrateAttestationData(&eth.AttestationData{}),
Signature: make([]byte, fieldparams.BLSSignatureLength),
},
&eth.Attestation{
AggregationBits: bitfield.Bitlist{0b00000111},
Data: util.HydrateAttestationData(&eth.AttestationData{}),
Signature: make([]byte, fieldparams.BLSSignatureLength),
},
}))
if ver >= version.Electra {
sbb.SetProposerIndex(4)
} else {
sbb.SetProposerIndex(12)
}
var atts []eth.Att
if ver >= version.Electra {
cb := primitives.NewAttestationCommitteeBits()
cb.SetBitAt(0, true)
atts = []eth.Att{
&eth.AttestationElectra{
AggregationBits: bitfield.Bitlist{0b00000111},
Data: util.HydrateAttestationData(&eth.AttestationData{}),
Signature: make([]byte, fieldparams.BLSSignatureLength),
CommitteeBits: cb,
},
&eth.AttestationElectra{
AggregationBits: bitfield.Bitlist{0b00000111},
Data: util.HydrateAttestationData(&eth.AttestationData{}),
Signature: make([]byte, fieldparams.BLSSignatureLength),
CommitteeBits: cb,
},
}
} else {
atts = []eth.Att{
&eth.Attestation{
AggregationBits: bitfield.Bitlist{0b00000111},
Data: util.HydrateAttestationData(&eth.AttestationData{}),
Signature: make([]byte, fieldparams.BLSSignatureLength),
},
&eth.Attestation{
AggregationBits: bitfield.Bitlist{0b00000111},
Data: util.HydrateAttestationData(&eth.AttestationData{}),
Signature: make([]byte, fieldparams.BLSSignatureLength),
},
}
}
require.NoError(t, sbb.SetAttestations(atts))
attData1 := util.HydrateAttestationData(&eth.AttestationData{BeaconBlockRoot: bytesutil.PadTo([]byte("root1"), 32)})
attData2 := util.HydrateAttestationData(&eth.AttestationData{BeaconBlockRoot: bytesutil.PadTo([]byte("root2"), 32)})
@@ -125,8 +159,23 @@ func BlockRewardTestSetup(t *testing.T, forkName string) (state.BeaconState, int
require.NoError(t, err)
sigRoot2, err := signing.ComputeSigningRoot(attData2, domain)
require.NoError(t, err)
require.NoError(t, sbb.SetAttesterSlashings([]eth.AttSlashing{
&eth.AttesterSlashing{
var attSlashing eth.AttSlashing
if ver >= version.Electra {
attSlashing = &eth.AttesterSlashingElectra{
Attestation_1: &eth.IndexedAttestationElectra{
AttestingIndices: []uint64{0},
Data: attData1,
Signature: secretKeys[0].Sign(sigRoot1[:]).Marshal(),
},
Attestation_2: &eth.IndexedAttestationElectra{
AttestingIndices: []uint64{0},
Data: attData2,
Signature: secretKeys[0].Sign(sigRoot2[:]).Marshal(),
},
}
} else {
attSlashing = &eth.AttesterSlashing{
Attestation_1: &eth.IndexedAttestation{
AttestingIndices: []uint64{0},
Data: attData1,
@@ -137,8 +186,10 @@ func BlockRewardTestSetup(t *testing.T, forkName string) (state.BeaconState, int
Data: attData2,
Signature: secretKeys[0].Sign(sigRoot2[:]).Marshal(),
},
},
}))
}
}
require.NoError(t, sbb.SetAttesterSlashings([]eth.AttSlashing{attSlashing}))
header1 := &eth.BeaconBlockHeader{
Slot: 0,
ProposerIndex: 1,
@@ -179,11 +230,21 @@ func BlockRewardTestSetup(t *testing.T, forkName string) (state.BeaconState, int
sszBytes := primitives.SSZBytes(slot0bRoot)
r, err := signing.ComputeSigningRoot(&sszBytes, domain)
require.NoError(t, err)
// Bits set in sync committee bits determine which validators will be treated as participating in sync committee.
// These validators have to sign the message.
sig1, err := blst.SignatureFromBytes(secretKeys[47].Sign(r[:]).Marshal())
var scValIdx1 int
var scValIdx2 int
if ver >= version.Electra {
scValIdx1 = 14
scValIdx2 = 27
} else {
scValIdx1 = 47
scValIdx2 = 19
}
sig1, err := blst.SignatureFromBytes(secretKeys[scValIdx1].Sign(r[:]).Marshal())
require.NoError(t, err)
sig2, err := blst.SignatureFromBytes(secretKeys[19].Sign(r[:]).Marshal())
sig2, err := blst.SignatureFromBytes(secretKeys[scValIdx2].Sign(r[:]).Marshal())
require.NoError(t, err)
aggSig := bls.AggregateSignatures([]bls.Signature{sig1, sig2}).Marshal()
err = sbb.SetSyncAggregate(&eth.SyncAggregate{SyncCommitteeBits: scBits, SyncCommitteeSignature: aggSig})
@@ -211,14 +272,14 @@ func TestBlockRewards(t *testing.T) {
writer.Body = &bytes.Buffer{}
s.BlockRewards(writer, request)
assert.Equal(t, http.StatusBadRequest, writer.Code)
require.Equal(t, http.StatusBadRequest, writer.Code)
e := &httputil.DefaultJsonError{}
require.NoError(t, json.Unmarshal(writer.Body.Bytes(), e))
assert.Equal(t, http.StatusBadRequest, e.Code)
require.Equal(t, http.StatusBadRequest, e.Code)
assert.Equal(t, "Block rewards are not supported for Phase 0 blocks", e.Message)
})
t.Run("altair", func(t *testing.T) {
st, sbb, err := BlockRewardTestSetup(t, "altair")
st, sbb, err := BlockRewardTestSetup(t, version.Altair)
require.NoError(t, err)
mockChainService := &mock.ChainService{Optimistic: true}
@@ -241,7 +302,7 @@ func TestBlockRewards(t *testing.T) {
writer.Body = &bytes.Buffer{}
s.BlockRewards(writer, request)
assert.Equal(t, http.StatusOK, writer.Code)
require.Equal(t, http.StatusOK, writer.Code)
resp := &structs.BlockRewardsResponse{}
require.NoError(t, json.Unmarshal(writer.Body.Bytes(), resp))
assert.Equal(t, "12", resp.Data.ProposerIndex)
@@ -254,7 +315,7 @@ func TestBlockRewards(t *testing.T) {
assert.Equal(t, false, resp.Finalized)
})
t.Run("bellatrix", func(t *testing.T) {
st, sbb, err := BlockRewardTestSetup(t, "bellatrix")
st, sbb, err := BlockRewardTestSetup(t, version.Bellatrix)
require.NoError(t, err)
mockChainService := &mock.ChainService{Optimistic: true}
@@ -277,7 +338,7 @@ func TestBlockRewards(t *testing.T) {
writer.Body = &bytes.Buffer{}
s.BlockRewards(writer, request)
assert.Equal(t, http.StatusOK, writer.Code)
require.Equal(t, http.StatusOK, writer.Code)
resp := &structs.BlockRewardsResponse{}
require.NoError(t, json.Unmarshal(writer.Body.Bytes(), resp))
assert.Equal(t, "12", resp.Data.ProposerIndex)
@@ -290,7 +351,7 @@ func TestBlockRewards(t *testing.T) {
assert.Equal(t, false, resp.Finalized)
})
t.Run("capella", func(t *testing.T) {
st, sbb, err := BlockRewardTestSetup(t, "capella")
st, sbb, err := BlockRewardTestSetup(t, version.Capella)
require.NoError(t, err)
mockChainService := &mock.ChainService{Optimistic: true}
@@ -313,7 +374,7 @@ func TestBlockRewards(t *testing.T) {
writer.Body = &bytes.Buffer{}
s.BlockRewards(writer, request)
assert.Equal(t, http.StatusOK, writer.Code)
require.Equal(t, http.StatusOK, writer.Code)
resp := &structs.BlockRewardsResponse{}
require.NoError(t, json.Unmarshal(writer.Body.Bytes(), resp))
assert.Equal(t, "12", resp.Data.ProposerIndex)
@@ -326,7 +387,7 @@ func TestBlockRewards(t *testing.T) {
assert.Equal(t, false, resp.Finalized)
})
t.Run("deneb", func(t *testing.T) {
st, sbb, err := BlockRewardTestSetup(t, "deneb")
st, sbb, err := BlockRewardTestSetup(t, version.Deneb)
require.NoError(t, err)
mockChainService := &mock.ChainService{Optimistic: true}
@@ -349,7 +410,7 @@ func TestBlockRewards(t *testing.T) {
writer.Body = &bytes.Buffer{}
s.BlockRewards(writer, request)
assert.Equal(t, http.StatusOK, writer.Code)
require.Equal(t, http.StatusOK, writer.Code)
resp := &structs.BlockRewardsResponse{}
require.NoError(t, json.Unmarshal(writer.Body.Bytes(), resp))
assert.Equal(t, "12", resp.Data.ProposerIndex)
@@ -361,6 +422,42 @@ func TestBlockRewards(t *testing.T) {
assert.Equal(t, true, resp.ExecutionOptimistic)
assert.Equal(t, false, resp.Finalized)
})
t.Run("electra", func(t *testing.T) {
st, sbb, err := BlockRewardTestSetup(t, version.Electra)
require.NoError(t, err)
mockChainService := &mock.ChainService{Optimistic: true}
s := &Server{
Blocker: &testutil.MockBlocker{SlotBlockMap: map[primitives.Slot]interfaces.ReadOnlySignedBeaconBlock{
0: phase0block,
2: sbb,
}},
OptimisticModeFetcher: mockChainService,
FinalizationFetcher: mockChainService,
BlockRewardFetcher: &BlockRewardService{
Replayer: mockstategen.NewReplayerBuilder(mockstategen.WithMockState(st)),
DB: db,
},
}
url := "http://only.the.slot.number.at.the.end.is.important/2"
request := httptest.NewRequest("GET", url, nil)
writer := httptest.NewRecorder()
writer.Body = &bytes.Buffer{}
s.BlockRewards(writer, request)
require.Equal(t, http.StatusOK, writer.Code)
resp := &structs.BlockRewardsResponse{}
require.NoError(t, json.Unmarshal(writer.Body.Bytes(), resp))
assert.Equal(t, "4", resp.Data.ProposerIndex)
assert.Equal(t, "15714490", resp.Data.Total)
assert.Equal(t, "89442", resp.Data.Attestations)
assert.Equal(t, "48", resp.Data.SyncAggregate)
assert.Equal(t, "7812500", resp.Data.AttesterSlashings)
assert.Equal(t, "7812500", resp.Data.ProposerSlashings)
assert.Equal(t, true, resp.ExecutionOptimistic)
assert.Equal(t, false, resp.Finalized)
})
}
func TestAttestationRewards(t *testing.T) {

View File

@@ -119,6 +119,9 @@ type ReadOnlyValidator interface {
Copy() *ethpb.Validator
Slashed() bool
IsNil() bool
HasETH1WithdrawalCredentials() bool
HasCompoundingWithdrawalCredentials() bool
HasExecutionWithdrawalCredentials() bool
}
// ReadOnlyValidators defines a struct which only has read access to validators methods.

View File

@@ -4,6 +4,7 @@ import (
"github.com/pkg/errors"
"github.com/prysmaticlabs/prysm/v5/beacon-chain/state"
fieldparams "github.com/prysmaticlabs/prysm/v5/config/fieldparams"
"github.com/prysmaticlabs/prysm/v5/config/params"
"github.com/prysmaticlabs/prysm/v5/consensus-types/primitives"
ethpb "github.com/prysmaticlabs/prysm/v5/proto/prysm/v1alpha1"
)
@@ -88,6 +89,27 @@ func (v readOnlyValidator) IsNil() bool {
return v.validator == nil
}
// HasETH1WithdrawalCredentials returns true if the validator has an ETH1 withdrawal credentials.
func (v readOnlyValidator) HasETH1WithdrawalCredentials() bool {
if v.IsNil() {
return false
}
return v.validator.WithdrawalCredentials[0] == params.BeaconConfig().ETH1AddressWithdrawalPrefixByte
}
// HasCompoundingWithdrawalCredentials returns true if the validator has a compounding withdrawal credentials.
func (v readOnlyValidator) HasCompoundingWithdrawalCredentials() bool {
if v.IsNil() {
return false
}
return v.validator.WithdrawalCredentials[0] == params.BeaconConfig().CompoundingWithdrawalPrefixByte
}
// HasExecutionWithdrawalCredentials returns true if the validator has an execution withdrawal credentials.
func (v readOnlyValidator) HasExecutionWithdrawalCredentials() bool {
return v.HasETH1WithdrawalCredentials() || v.HasCompoundingWithdrawalCredentials()
}
// Copy returns a new validator from the read only validator
func (v readOnlyValidator) Copy() *ethpb.Validator {
pubKey := v.PublicKey()

View File

@@ -292,7 +292,7 @@ func TestExtractDataType(t *testing.T) {
return wsb
}(),
wantMd: wrapper.WrappedMetadataV1(&ethpb.MetaDataV1{}),
wantAtt: &ethpb.AttestationElectra{},
wantAtt: &ethpb.SingleAttestation{},
wantAggregate: &ethpb.SignedAggregateAttestationAndProofElectra{},
wantErr: false,
},

View File

@@ -0,0 +1,2 @@
### Changed
- Refactor `2006-01-02 15:04:05` to `time.DateTime`

View File

@@ -0,0 +1,3 @@
### Added
- Remote signer electra fork support.

View File

@@ -0,0 +1,2 @@
### Changed
- Remove helpers to check for execution/compounding withdrawal credentials and expose them as methods.

View File

@@ -0,0 +1,3 @@
### Removed
- Remove `Copy()` from the `ReadOnlyBeaconBlock` interface.

View File

@@ -0,0 +1,3 @@
### Fixed
- Use `SingleAttestation` for Fulu in p2p attestation map.

View File

@@ -0,0 +1,3 @@
### Added
- Update `proto_test.go` to Electra.

View File

@@ -0,0 +1,3 @@
### Added
- Add Electra test case to rewards API.

View File

@@ -7,6 +7,7 @@ import (
"os"
"path/filepath"
runtimeDebug "runtime/debug"
"time"
gethlog "github.com/ethereum/go-ethereum/log"
golog "github.com/ipfs/go-log/v2"
@@ -163,7 +164,7 @@ func before(ctx *cli.Context) error {
switch format {
case "text":
formatter := new(prefixed.TextFormatter)
formatter.TimestampFormat = "2006-01-02 15:04:05"
formatter.TimestampFormat = time.DateTime
formatter.FullTimestamp = true
// If persistent log files are written - we disable the log messages coloring because

View File

@@ -60,7 +60,7 @@ func main() {
switch format {
case "text":
formatter := new(prefixed.TextFormatter)
formatter.TimestampFormat = "2006-01-02 15:04:05"
formatter.TimestampFormat = time.DateTime
formatter.FullTimestamp = true
// If persistent log files are written - we disable the log messages coloring because
// the colors are ANSI codes and seen as gibberish in the log files.

View File

@@ -8,6 +8,7 @@ import (
"os"
"path/filepath"
runtimeDebug "runtime/debug"
"time"
joonix "github.com/joonix/log"
"github.com/pkg/errors"
@@ -153,7 +154,7 @@ func main() {
switch format {
case "text":
formatter := new(prefixed.TextFormatter)
formatter.TimestampFormat = "2006-01-02 15:04:05"
formatter.TimestampFormat = time.DateTime
formatter.FullTimestamp = true
// If persistent log files are written - we disable the log messages coloring because
// the colors are ANSI codes and seen as gibberish in the log files.

View File

@@ -55,6 +55,7 @@ go_test(
embed = [":go_default_library"],
deps = [
"//config/fieldparams:go_default_library",
"//config/params:go_default_library",
"//consensus-types:go_default_library",
"//consensus-types/interfaces:go_default_library",
"//consensus-types/primitives:go_default_library",

View File

@@ -1107,50 +1107,6 @@ func (b *BeaconBlock) AsSignRequestObject() (validatorpb.SignRequestObject, erro
}
}
func (b *BeaconBlock) Copy() (interfaces.ReadOnlyBeaconBlock, error) {
if b == nil {
return nil, nil
}
pb, err := b.Proto()
if err != nil {
return nil, err
}
switch b.version {
case version.Phase0:
return initBlockFromProtoPhase0(pb.(*eth.BeaconBlock).Copy())
case version.Altair:
return initBlockFromProtoAltair(pb.(*eth.BeaconBlockAltair).Copy())
case version.Bellatrix:
if b.IsBlinded() {
return initBlindedBlockFromProtoBellatrix(pb.(*eth.BlindedBeaconBlockBellatrix).Copy())
}
return initBlockFromProtoBellatrix(pb.(*eth.BeaconBlockBellatrix).Copy())
case version.Capella:
if b.IsBlinded() {
return initBlindedBlockFromProtoCapella(pb.(*eth.BlindedBeaconBlockCapella).Copy())
}
return initBlockFromProtoCapella(pb.(*eth.BeaconBlockCapella).Copy())
case version.Deneb:
if b.IsBlinded() {
return initBlindedBlockFromProtoDeneb(pb.(*eth.BlindedBeaconBlockDeneb).Copy())
}
return initBlockFromProtoDeneb(pb.(*eth.BeaconBlockDeneb).Copy())
case version.Electra:
if b.IsBlinded() {
return initBlindedBlockFromProtoElectra(pb.(*eth.BlindedBeaconBlockElectra).Copy())
}
return initBlockFromProtoElectra(pb.(*eth.BeaconBlockElectra).Copy())
case version.Fulu:
if b.IsBlinded() {
return initBlindedBlockFromProtoFulu(pb.(*eth.BlindedBeaconBlockFulu).Copy())
}
return initBlockFromProtoFulu(pb.(*eth.BeaconBlockFulu).Copy())
default:
return nil, errIncorrectBlockVersion
}
}
// IsNil checks if the block body is nil.
func (b *BeaconBlockBody) IsNil() bool {
return b == nil

View File

@@ -169,70 +169,6 @@ func Test_BeaconBlock_Body(t *testing.T) {
assert.Equal(t, bb, b.Body())
}
func Test_BeaconBlock_Copy(t *testing.T) {
bb := &BeaconBlockBody{randaoReveal: bytesutil.ToBytes96([]byte{246}), graffiti: bytesutil.ToBytes32([]byte("graffiti"))}
b := &BeaconBlock{body: bb, slot: 123, proposerIndex: 456, parentRoot: bytesutil.ToBytes32([]byte("parentroot")), stateRoot: bytesutil.ToBytes32([]byte("stateroot"))}
cp, err := b.Copy()
require.NoError(t, err)
assert.NotEqual(t, cp, b)
assert.NotEqual(t, cp.Body(), bb)
b.version = version.Altair
b.body.version = b.version
cp, err = b.Copy()
require.NoError(t, err)
assert.NotEqual(t, cp, b)
assert.NotEqual(t, cp.Body(), bb)
b.version = version.Bellatrix
b.body.version = b.version
cp, err = b.Copy()
require.NoError(t, err)
assert.NotEqual(t, cp, b)
assert.NotEqual(t, cp.Body(), bb)
b.version = version.Capella
b.body.version = b.version
cp, err = b.Copy()
require.NoError(t, err)
assert.NotEqual(t, cp, b)
assert.NotEqual(t, cp.Body(), bb)
b.version = version.Bellatrix
b.body.version = b.version
cp, err = b.Copy()
require.NoError(t, err)
assert.NotEqual(t, cp, b)
assert.NotEqual(t, cp.Body(), bb)
b.version = version.Capella
b.body.version = b.version
cp, err = b.Copy()
require.NoError(t, err)
assert.NotEqual(t, cp, b)
assert.NotEqual(t, cp.Body(), bb)
payload := &pb.ExecutionPayloadDeneb{ExcessBlobGas: 123}
header := &pb.ExecutionPayloadHeaderDeneb{ExcessBlobGas: 223}
payloadInterface, err := WrappedExecutionPayloadDeneb(payload)
require.NoError(t, err)
headerInterface, err := WrappedExecutionPayloadHeaderDeneb(header)
require.NoError(t, err)
bb = &BeaconBlockBody{executionPayload: payloadInterface, executionPayloadHeader: headerInterface, randaoReveal: bytesutil.ToBytes96([]byte{246}), graffiti: bytesutil.ToBytes32([]byte("graffiti"))}
b = &BeaconBlock{body: bb, slot: 123, proposerIndex: 456, parentRoot: bytesutil.ToBytes32([]byte("parentroot")), stateRoot: bytesutil.ToBytes32([]byte("stateroot"))}
b.version = version.Deneb
b.body.version = b.version
cp, err = b.Copy()
require.NoError(t, err)
assert.NotEqual(t, cp, b)
assert.NotEqual(t, cp.Body(), bb)
e, err := cp.Body().Execution()
require.NoError(t, err)
gas, err := e.ExcessBlobGas()
require.NoError(t, err)
require.DeepEqual(t, gas, uint64(123))
}
func Test_BeaconBlock_IsNil(t *testing.T) {
t.Run("nil block", func(t *testing.T) {
var b *BeaconBlock

View File

@@ -4,6 +4,8 @@ import (
"testing"
"github.com/prysmaticlabs/go-bitfield"
"github.com/prysmaticlabs/prysm/v5/config/params"
"github.com/prysmaticlabs/prysm/v5/consensus-types/primitives"
"github.com/prysmaticlabs/prysm/v5/encoding/bytesutil"
enginev1 "github.com/prysmaticlabs/prysm/v5/proto/engine/v1"
eth "github.com/prysmaticlabs/prysm/v5/proto/prysm/v1alpha1"
@@ -17,8 +19,10 @@ type fields struct {
sig [96]byte
deposits []*eth.Deposit
atts []*eth.Attestation
attsElectra []*eth.AttestationElectra
proposerSlashings []*eth.ProposerSlashing
attesterSlashings []*eth.AttesterSlashing
attesterSlashingsElectra []*eth.AttesterSlashingElectra
voluntaryExits []*eth.SignedVoluntaryExit
syncAggregate *eth.SyncAggregate
execPayload *enginev1.ExecutionPayload
@@ -29,6 +33,7 @@ type fields struct {
execPayloadHeaderDeneb *enginev1.ExecutionPayloadHeaderDeneb
blsToExecutionChanges []*eth.SignedBLSToExecutionChange
kzgCommitments [][]byte
execRequests *enginev1.ExecutionRequests
}
func Test_SignedBeaconBlock_Proto(t *testing.T) {
@@ -306,6 +311,74 @@ func Test_SignedBeaconBlock_Proto(t *testing.T) {
require.NoError(t, err)
assert.DeepEqual(t, expectedHTR, resultHTR)
})
t.Run("Electra", func(t *testing.T) {
expectedBlock := &eth.SignedBeaconBlockElectra{
Block: &eth.BeaconBlockElectra{
Slot: 128,
ProposerIndex: 128,
ParentRoot: f.root[:],
StateRoot: f.root[:],
Body: bodyPbElectra(),
},
Signature: f.sig[:],
}
block := &SignedBeaconBlock{
version: version.Electra,
block: &BeaconBlock{
version: version.Electra,
slot: 128,
proposerIndex: 128,
parentRoot: f.root,
stateRoot: f.root,
body: bodyElectra(t),
},
signature: f.sig,
}
result, err := block.Proto()
require.NoError(t, err)
resultBlock, ok := result.(*eth.SignedBeaconBlockElectra)
require.Equal(t, true, ok)
resultHTR, err := resultBlock.HashTreeRoot()
require.NoError(t, err)
expectedHTR, err := expectedBlock.HashTreeRoot()
require.NoError(t, err)
assert.DeepEqual(t, expectedHTR, resultHTR)
})
t.Run("ElectraBlind", func(t *testing.T) {
expectedBlock := &eth.SignedBlindedBeaconBlockElectra{
Message: &eth.BlindedBeaconBlockElectra{
Slot: 128,
ProposerIndex: 128,
ParentRoot: f.root[:],
StateRoot: f.root[:],
Body: bodyPbBlindedElectra(),
},
Signature: f.sig[:],
}
block := &SignedBeaconBlock{
version: version.Electra,
block: &BeaconBlock{
version: version.Electra,
slot: 128,
proposerIndex: 128,
parentRoot: f.root,
stateRoot: f.root,
body: bodyBlindedElectra(t),
},
signature: f.sig,
}
result, err := block.Proto()
require.NoError(t, err)
resultBlock, ok := result.(*eth.SignedBlindedBeaconBlockElectra)
require.Equal(t, true, ok)
resultHTR, err := resultBlock.HashTreeRoot()
require.NoError(t, err)
expectedHTR, err := expectedBlock.HashTreeRoot()
require.NoError(t, err)
assert.DeepEqual(t, expectedHTR, resultHTR)
})
}
func Test_BeaconBlock_Proto(t *testing.T) {
@@ -527,6 +600,60 @@ func Test_BeaconBlock_Proto(t *testing.T) {
require.NoError(t, err)
assert.DeepEqual(t, expectedHTR, resultHTR)
})
t.Run("Electra", func(t *testing.T) {
expectedBlock := &eth.BeaconBlockElectra{
Slot: 128,
ProposerIndex: 128,
ParentRoot: f.root[:],
StateRoot: f.root[:],
Body: bodyPbElectra(),
}
block := &BeaconBlock{
version: version.Electra,
slot: 128,
proposerIndex: 128,
parentRoot: f.root,
stateRoot: f.root,
body: bodyElectra(t),
}
result, err := block.Proto()
require.NoError(t, err)
resultBlock, ok := result.(*eth.BeaconBlockElectra)
require.Equal(t, true, ok)
resultHTR, err := resultBlock.HashTreeRoot()
require.NoError(t, err)
expectedHTR, err := expectedBlock.HashTreeRoot()
require.NoError(t, err)
assert.DeepEqual(t, expectedHTR, resultHTR)
})
t.Run("ElectraBlind", func(t *testing.T) {
expectedBlock := &eth.BlindedBeaconBlockElectra{
Slot: 128,
ProposerIndex: 128,
ParentRoot: f.root[:],
StateRoot: f.root[:],
Body: bodyPbBlindedElectra(),
}
block := &BeaconBlock{
version: version.Electra,
slot: 128,
proposerIndex: 128,
parentRoot: f.root,
stateRoot: f.root,
body: bodyBlindedElectra(t),
}
result, err := block.Proto()
require.NoError(t, err)
resultBlock, ok := result.(*eth.BlindedBeaconBlockElectra)
require.Equal(t, true, ok)
resultHTR, err := resultBlock.HashTreeRoot()
require.NoError(t, err)
expectedHTR, err := expectedBlock.HashTreeRoot()
require.NoError(t, err)
assert.DeepEqual(t, expectedHTR, resultHTR)
})
}
func Test_BeaconBlockBody_Proto(t *testing.T) {
@@ -635,6 +762,32 @@ func Test_BeaconBlockBody_Proto(t *testing.T) {
require.NoError(t, err)
assert.DeepEqual(t, expectedHTR, resultHTR)
})
t.Run("Electra", func(t *testing.T) {
expectedBody := bodyPbElectra()
body := bodyElectra(t)
result, err := body.Proto()
require.NoError(t, err)
resultBlock, ok := result.(*eth.BeaconBlockBodyElectra)
require.Equal(t, true, ok)
resultHTR, err := resultBlock.HashTreeRoot()
require.NoError(t, err)
expectedHTR, err := expectedBody.HashTreeRoot()
require.NoError(t, err)
assert.DeepEqual(t, expectedHTR, resultHTR)
})
t.Run("ElectraBlind", func(t *testing.T) {
expectedBody := bodyPbBlindedElectra()
body := bodyBlindedElectra(t)
result, err := body.Proto()
require.NoError(t, err)
resultBlock, ok := result.(*eth.BlindedBeaconBlockBodyElectra)
require.Equal(t, true, ok)
resultHTR, err := resultBlock.HashTreeRoot()
require.NoError(t, err)
expectedHTR, err := expectedBody.HashTreeRoot()
require.NoError(t, err)
assert.DeepEqual(t, expectedHTR, resultHTR)
})
t.Run("Bellatrix - wrong payload type", func(t *testing.T) {
body := bodyBellatrix(t)
body.executionPayload = &executionPayloadHeader{}
@@ -671,6 +824,18 @@ func Test_BeaconBlockBody_Proto(t *testing.T) {
_, err := body.Proto()
require.ErrorIs(t, err, errPayloadHeaderWrongType)
})
t.Run("Electra - wrong payload type", func(t *testing.T) {
body := bodyElectra(t)
body.executionPayload = &executionPayloadHeaderDeneb{}
_, err := body.Proto()
require.ErrorIs(t, err, errPayloadWrongType)
})
t.Run("ElectraBlind - wrong payload type", func(t *testing.T) {
body := bodyBlindedElectra(t)
body.executionPayloadHeader = &executionPayloadDeneb{}
_, err := body.Proto()
require.ErrorIs(t, err, errPayloadHeaderWrongType)
})
}
func Test_initSignedBlockFromProtoPhase0(t *testing.T) {
@@ -849,6 +1014,50 @@ func Test_initBlindedSignedBlockFromProtoDeneb(t *testing.T) {
assert.DeepEqual(t, expectedBlock.Signature, resultBlock.signature[:])
}
func Test_initSignedBlockFromProtoElectra(t *testing.T) {
f := getFields()
expectedBlock := &eth.SignedBeaconBlockElectra{
Block: &eth.BeaconBlockElectra{
Slot: 128,
ProposerIndex: 128,
ParentRoot: f.root[:],
StateRoot: f.root[:],
Body: bodyPbElectra(),
},
Signature: f.sig[:],
}
resultBlock, err := initSignedBlockFromProtoElectra(expectedBlock)
require.NoError(t, err)
resultHTR, err := resultBlock.block.HashTreeRoot()
require.NoError(t, err)
expectedHTR, err := expectedBlock.Block.HashTreeRoot()
require.NoError(t, err)
assert.DeepEqual(t, expectedHTR, resultHTR)
assert.DeepEqual(t, expectedBlock.Signature, resultBlock.signature[:])
}
func Test_initBlindedSignedBlockFromProtoElectra(t *testing.T) {
f := getFields()
expectedBlock := &eth.SignedBlindedBeaconBlockElectra{
Message: &eth.BlindedBeaconBlockElectra{
Slot: 128,
ProposerIndex: 128,
ParentRoot: f.root[:],
StateRoot: f.root[:],
Body: bodyPbBlindedElectra(),
},
Signature: f.sig[:],
}
resultBlock, err := initBlindedSignedBlockFromProtoElectra(expectedBlock)
require.NoError(t, err)
resultHTR, err := resultBlock.block.HashTreeRoot()
require.NoError(t, err)
expectedHTR, err := expectedBlock.Message.HashTreeRoot()
require.NoError(t, err)
assert.DeepEqual(t, expectedHTR, resultHTR)
assert.DeepEqual(t, expectedBlock.Signature, resultBlock.signature[:])
}
func Test_initBlockFromProtoPhase0(t *testing.T) {
f := getFields()
expectedBlock := &eth.BeaconBlock{
@@ -993,6 +1202,42 @@ func Test_initBlockFromProtoBlindedDeneb(t *testing.T) {
assert.DeepEqual(t, expectedHTR, resultHTR)
}
func Test_initBlockFromProtoElectra(t *testing.T) {
f := getFields()
expectedBlock := &eth.BeaconBlockElectra{
Slot: 128,
ProposerIndex: 128,
ParentRoot: f.root[:],
StateRoot: f.root[:],
Body: bodyPbElectra(),
}
resultBlock, err := initBlockFromProtoElectra(expectedBlock)
require.NoError(t, err)
resultHTR, err := resultBlock.HashTreeRoot()
require.NoError(t, err)
expectedHTR, err := expectedBlock.HashTreeRoot()
require.NoError(t, err)
assert.DeepEqual(t, expectedHTR, resultHTR)
}
func Test_initBlockFromProtoBlindedElectra(t *testing.T) {
f := getFields()
expectedBlock := &eth.BlindedBeaconBlockElectra{
Slot: 128,
ProposerIndex: 128,
ParentRoot: f.root[:],
StateRoot: f.root[:],
Body: bodyPbBlindedElectra(),
}
resultBlock, err := initBlindedBlockFromProtoElectra(expectedBlock)
require.NoError(t, err)
resultHTR, err := resultBlock.HashTreeRoot()
require.NoError(t, err)
expectedHTR, err := expectedBlock.HashTreeRoot()
require.NoError(t, err)
assert.DeepEqual(t, expectedHTR, resultHTR)
}
func Test_initBlockBodyFromProtoPhase0(t *testing.T) {
expectedBody := bodyPbPhase0()
resultBody, err := initBlockBodyFromProtoPhase0(expectedBody)
@@ -1081,6 +1326,28 @@ func Test_initBlockBodyFromProtoBlindedDeneb(t *testing.T) {
assert.DeepEqual(t, expectedHTR, resultHTR)
}
func Test_initBlockBodyFromProtoElectra(t *testing.T) {
expectedBody := bodyPbElectra()
resultBody, err := initBlockBodyFromProtoElectra(expectedBody)
require.NoError(t, err)
resultHTR, err := resultBody.HashTreeRoot()
require.NoError(t, err)
expectedHTR, err := expectedBody.HashTreeRoot()
require.NoError(t, err)
assert.DeepEqual(t, expectedHTR, resultHTR)
}
func Test_initBlockBodyFromProtoBlindedElectra(t *testing.T) {
expectedBody := bodyPbBlindedElectra()
resultBody, err := initBlindedBlockBodyFromProtoElectra(expectedBody)
require.NoError(t, err)
resultHTR, err := resultBody.HashTreeRoot()
require.NoError(t, err)
expectedHTR, err := expectedBody.HashTreeRoot()
require.NoError(t, err)
assert.DeepEqual(t, expectedHTR, resultHTR)
}
func bodyPbPhase0() *eth.BeaconBlockBody {
f := getFields()
return &eth.BeaconBlockBody{
@@ -1244,6 +1511,52 @@ func bodyPbBlindedDeneb() *eth.BlindedBeaconBlockBodyDeneb {
}
}
func bodyPbElectra() *eth.BeaconBlockBodyElectra {
f := getFields()
return &eth.BeaconBlockBodyElectra{
RandaoReveal: f.sig[:],
Eth1Data: &eth.Eth1Data{
DepositRoot: f.root[:],
DepositCount: 128,
BlockHash: f.root[:],
},
Graffiti: f.root[:],
ProposerSlashings: f.proposerSlashings,
AttesterSlashings: f.attesterSlashingsElectra,
Attestations: f.attsElectra,
Deposits: f.deposits,
VoluntaryExits: f.voluntaryExits,
SyncAggregate: f.syncAggregate,
ExecutionPayload: f.execPayloadDeneb,
BlsToExecutionChanges: f.blsToExecutionChanges,
BlobKzgCommitments: f.kzgCommitments,
ExecutionRequests: f.execRequests,
}
}
func bodyPbBlindedElectra() *eth.BlindedBeaconBlockBodyElectra {
f := getFields()
return &eth.BlindedBeaconBlockBodyElectra{
RandaoReveal: f.sig[:],
Eth1Data: &eth.Eth1Data{
DepositRoot: f.root[:],
DepositCount: 128,
BlockHash: f.root[:],
},
Graffiti: f.root[:],
ProposerSlashings: f.proposerSlashings,
AttesterSlashings: f.attesterSlashingsElectra,
Attestations: f.attsElectra,
Deposits: f.deposits,
VoluntaryExits: f.voluntaryExits,
SyncAggregate: f.syncAggregate,
ExecutionPayloadHeader: f.execPayloadHeaderDeneb,
BlsToExecutionChanges: f.blsToExecutionChanges,
BlobKzgCommitments: f.kzgCommitments,
ExecutionRequests: f.execRequests,
}
}
func bodyPhase0() *BeaconBlockBody {
f := getFields()
return &BeaconBlockBody{
@@ -1427,6 +1740,58 @@ func bodyBlindedDeneb(t *testing.T) *BeaconBlockBody {
}
}
func bodyElectra(t *testing.T) *BeaconBlockBody {
f := getFields()
p, err := WrappedExecutionPayloadDeneb(f.execPayloadDeneb)
require.NoError(t, err)
return &BeaconBlockBody{
version: version.Electra,
randaoReveal: f.sig,
eth1Data: &eth.Eth1Data{
DepositRoot: f.root[:],
DepositCount: 128,
BlockHash: f.root[:],
},
graffiti: f.root,
proposerSlashings: f.proposerSlashings,
attesterSlashingsElectra: f.attesterSlashingsElectra,
attestationsElectra: f.attsElectra,
deposits: f.deposits,
voluntaryExits: f.voluntaryExits,
syncAggregate: f.syncAggregate,
executionPayload: p,
blsToExecutionChanges: f.blsToExecutionChanges,
blobKzgCommitments: f.kzgCommitments,
executionRequests: f.execRequests,
}
}
func bodyBlindedElectra(t *testing.T) *BeaconBlockBody {
f := getFields()
ph, err := WrappedExecutionPayloadHeaderDeneb(f.execPayloadHeaderDeneb)
require.NoError(t, err)
return &BeaconBlockBody{
version: version.Electra,
randaoReveal: f.sig,
eth1Data: &eth.Eth1Data{
DepositRoot: f.root[:],
DepositCount: 128,
BlockHash: f.root[:],
},
graffiti: f.root,
proposerSlashings: f.proposerSlashings,
attesterSlashingsElectra: f.attesterSlashingsElectra,
attestationsElectra: f.attsElectra,
deposits: f.deposits,
voluntaryExits: f.voluntaryExits,
syncAggregate: f.syncAggregate,
executionPayloadHeader: ph,
blsToExecutionChanges: f.blsToExecutionChanges,
blobKzgCommitments: f.kzgCommitments,
executionRequests: f.execRequests,
}
}
func getFields() fields {
b20 := make([]byte, 20)
b48 := make([]byte, 48)
@@ -1452,11 +1817,14 @@ func getFields() fields {
Signature: sig[:],
}
}
atts := make([]*eth.Attestation, 128)
attBits := bitfield.NewBitlist(1)
committeeBits := primitives.NewAttestationCommitteeBits()
atts := make([]*eth.Attestation, params.BeaconConfig().MaxAttestations)
for i := range atts {
atts[i] = &eth.Attestation{}
atts[i].Signature = sig[:]
atts[i].AggregationBits = bitfield.NewBitlist(1)
atts[i].AggregationBits = attBits
atts[i].Data = &eth.AttestationData{
Slot: 128,
CommitteeIndex: 128,
@@ -1471,6 +1839,27 @@ func getFields() fields {
},
}
}
attsElectra := make([]*eth.AttestationElectra, params.BeaconConfig().MaxAttestationsElectra)
for i := range attsElectra {
attsElectra[i] = &eth.AttestationElectra{}
attsElectra[i].Signature = sig[:]
attsElectra[i].AggregationBits = attBits
attsElectra[i].CommitteeBits = committeeBits
attsElectra[i].Data = &eth.AttestationData{
Slot: 128,
CommitteeIndex: 128,
BeaconBlockRoot: root[:],
Source: &eth.Checkpoint{
Epoch: 128,
Root: root[:],
},
Target: &eth.Checkpoint{
Epoch: 128,
Root: root[:],
},
}
}
proposerSlashing := &eth.ProposerSlashing{
Header_1: &eth.SignedBeaconBlockHeader{
Header: &eth.BeaconBlockHeader{
@@ -1529,6 +1918,42 @@ func getFields() fields {
Signature: sig[:],
},
}
attesterSlashingElectra := &eth.AttesterSlashingElectra{
Attestation_1: &eth.IndexedAttestationElectra{
AttestingIndices: []uint64{1, 2, 8},
Data: &eth.AttestationData{
Slot: 128,
CommitteeIndex: 128,
BeaconBlockRoot: root[:],
Source: &eth.Checkpoint{
Epoch: 128,
Root: root[:],
},
Target: &eth.Checkpoint{
Epoch: 128,
Root: root[:],
},
},
Signature: sig[:],
},
Attestation_2: &eth.IndexedAttestationElectra{
AttestingIndices: []uint64{1, 2, 8},
Data: &eth.AttestationData{
Slot: 128,
CommitteeIndex: 128,
BeaconBlockRoot: root[:],
Source: &eth.Checkpoint{
Epoch: 128,
Root: root[:],
},
Target: &eth.Checkpoint{
Epoch: 128,
Root: root[:],
},
},
Signature: sig[:],
},
}
voluntaryExit := &eth.SignedVoluntaryExit{
Exit: &eth.VoluntaryExit{
Epoch: 128,
@@ -1689,13 +2114,35 @@ func getFields() fields {
bytesutil.PadTo([]byte{143}, 48),
}
execRequests := &enginev1.ExecutionRequests{
Deposits: []*enginev1.DepositRequest{{
Pubkey: b48,
WithdrawalCredentials: root[:],
Amount: 128,
Signature: sig[:],
Index: 128,
}},
Withdrawals: []*enginev1.WithdrawalRequest{{
SourceAddress: b20,
ValidatorPubkey: b48,
Amount: 128,
}},
Consolidations: []*enginev1.ConsolidationRequest{{
SourceAddress: b20,
SourcePubkey: b48,
TargetPubkey: b48,
}},
}
return fields{
root: root,
sig: sig,
deposits: deposits,
atts: atts,
attsElectra: attsElectra,
proposerSlashings: []*eth.ProposerSlashing{proposerSlashing},
attesterSlashings: []*eth.AttesterSlashing{attesterSlashing},
attesterSlashingsElectra: []*eth.AttesterSlashingElectra{attesterSlashingElectra},
voluntaryExits: []*eth.SignedVoluntaryExit{voluntaryExit},
syncAggregate: syncAggregate,
execPayload: execPayload,
@@ -1706,5 +2153,6 @@ func getFields() fields {
execPayloadHeaderDeneb: execPayloadHeaderDeneb,
blsToExecutionChanges: blsToExecutionChanges,
kzgCommitments: kzgCommitments,
execRequests: execRequests,
}
}

View File

@@ -47,7 +47,6 @@ type ReadOnlyBeaconBlock interface {
ssz.HashRoot
Version() int
AsSignRequestObject() (validatorpb.SignRequestObject, error)
Copy() (ReadOnlyBeaconBlock, error)
}
// ReadOnlyBeaconBlockBody describes the method set employed by an object

View File

@@ -163,10 +163,6 @@ func (BeaconBlock) SetParentRoot(_ []byte) {
panic("implement me")
}
func (BeaconBlock) Copy() (interfaces.ReadOnlyBeaconBlock, error) {
panic("implement me")
}
type BeaconBlockBody struct{}
func (BeaconBlockBody) RandaoReveal() [field_params.BLSSignatureLength]byte {

View File

@@ -6,10 +6,10 @@ lighthouse_archive_name = "lighthouse-%s-x86_64-unknown-linux-gnu-portable.tar.g
def e2e_deps():
http_archive(
name = "web3signer",
urls = ["https://artifacts.consensys.net/public/web3signer/raw/names/web3signer.tar.gz/versions/23.11.0/web3signer-23.11.0.tar.gz"],
sha256 = "e7643a6aa32efd859e96a82cb3ea03a294fd92c22fffeab987e5ec97500867a8",
urls = ["https://artifacts.consensys.net/public/web3signer/raw/names/web3signer.tar.gz/versions/24.12.0/web3signer-24.12.0.tar.gz"],
sha256 = "5d2eff119e065a50bd2bd727e098963d0e61a3f6525bdc12b11515d3677a84d1",
build_file = "@prysm//testing/endtoend:web3signer.BUILD",
strip_prefix = "web3signer-23.11.0",
strip_prefix = "web3signer-24.12.0",
)
http_archive(

View File

@@ -299,7 +299,7 @@ var stateTransitionCommand = &cli.Command{
func main() {
customFormatter := new(prefixed.TextFormatter)
customFormatter.TimestampFormat = "2006-01-02 15:04:05"
customFormatter.TimestampFormat = time.DateTime
customFormatter.FullTimestamp = true
log.SetFormatter(customFormatter)
app := cli.App{}

View File

@@ -20,10 +20,11 @@ go_library(
"//io/file:go_default_library",
"//monitoring/tracing/trace:go_default_library",
"//proto/prysm/v1alpha1/validator-client:go_default_library",
"//runtime/version:go_default_library",
"//validator/accounts/petnames:go_default_library",
"//validator/keymanager:go_default_library",
"//validator/keymanager/remote-web3signer/internal:go_default_library",
"//validator/keymanager/remote-web3signer/v1:go_default_library",
"//validator/keymanager/remote-web3signer/types:go_default_library",
"@com_github_ethereum_go_ethereum//common/hexutil:go_default_library",
"@com_github_fsnotify_fsnotify//:go_default_library",
"@com_github_go_playground_validator_v10//:go_default_library",
@@ -48,7 +49,7 @@ go_test(
"//testing/require:go_default_library",
"//validator/keymanager:go_default_library",
"//validator/keymanager/remote-web3signer/internal:go_default_library",
"//validator/keymanager/remote-web3signer/v1/mock:go_default_library",
"//validator/keymanager/remote-web3signer/types/mock:go_default_library",
"@com_github_ethereum_go_ethereum//common/hexutil:go_default_library",
"@com_github_sirupsen_logrus//hooks/test:go_default_library",
"@com_github_stretchr_testify//assert:go_default_library",

View File

@@ -24,10 +24,11 @@ import (
"github.com/prysmaticlabs/prysm/v5/io/file"
"github.com/prysmaticlabs/prysm/v5/monitoring/tracing/trace"
validatorpb "github.com/prysmaticlabs/prysm/v5/proto/prysm/v1alpha1/validator-client"
"github.com/prysmaticlabs/prysm/v5/runtime/version"
"github.com/prysmaticlabs/prysm/v5/validator/accounts/petnames"
"github.com/prysmaticlabs/prysm/v5/validator/keymanager"
"github.com/prysmaticlabs/prysm/v5/validator/keymanager/remote-web3signer/internal"
web3signerv1 "github.com/prysmaticlabs/prysm/v5/validator/keymanager/remote-web3signer/v1"
"github.com/prysmaticlabs/prysm/v5/validator/keymanager/remote-web3signer/types"
"github.com/sirupsen/logrus"
"golang.org/x/exp/maps"
)
@@ -405,7 +406,10 @@ func getSignRequestJson(ctx context.Context, validator *validator.Validate, requ
case *validatorpb.SignRequest_AttestationData:
return handleAttestationData(ctx, validator, request, genesisValidatorsRoot)
case *validatorpb.SignRequest_AggregateAttestationAndProof:
// TODO: update to V2 sometime after release
return handleAggregateAttestationAndProof(ctx, validator, request, genesisValidatorsRoot)
case *validatorpb.SignRequest_AggregateAttestationAndProofElectra:
return handleAggregateAttestationAndProofV2(ctx, version.Electra, validator, request, genesisValidatorsRoot)
case *validatorpb.SignRequest_Slot:
return handleAggregationSlot(ctx, validator, request, genesisValidatorsRoot)
case *validatorpb.SignRequest_BlockAltair:
@@ -422,6 +426,10 @@ func getSignRequestJson(ctx context.Context, validator *validator.Validate, requ
return handleBlockDeneb(ctx, validator, request, genesisValidatorsRoot)
case *validatorpb.SignRequest_BlindedBlockDeneb:
return handleBlindedBlockDeneb(ctx, validator, request, genesisValidatorsRoot)
case *validatorpb.SignRequest_BlockElectra:
return handleBlockElectra(ctx, validator, request, genesisValidatorsRoot)
case *validatorpb.SignRequest_BlindedBlockElectra:
return handleBlindedBlockElectra(ctx, validator, request, genesisValidatorsRoot)
// We do not support "DEPOSIT" type.
/*
case *validatorpb.:
@@ -447,7 +455,7 @@ func getSignRequestJson(ctx context.Context, validator *validator.Validate, requ
}
func handleBlock(ctx context.Context, validator *validator.Validate, request *validatorpb.SignRequest, genesisValidatorsRoot []byte) ([]byte, error) {
bockSignRequest, err := web3signerv1.GetBlockSignRequest(request, genesisValidatorsRoot)
bockSignRequest, err := types.GetBlockSignRequest(request, genesisValidatorsRoot)
if err != nil {
return nil, err
}
@@ -459,7 +467,7 @@ func handleBlock(ctx context.Context, validator *validator.Validate, request *va
}
func handleAttestationData(ctx context.Context, validator *validator.Validate, request *validatorpb.SignRequest, genesisValidatorsRoot []byte) ([]byte, error) {
attestationSignRequest, err := web3signerv1.GetAttestationSignRequest(request, genesisValidatorsRoot)
attestationSignRequest, err := types.GetAttestationSignRequest(request, genesisValidatorsRoot)
if err != nil {
return nil, err
}
@@ -471,7 +479,7 @@ func handleAttestationData(ctx context.Context, validator *validator.Validate, r
}
func handleAggregateAttestationAndProof(ctx context.Context, validator *validator.Validate, request *validatorpb.SignRequest, genesisValidatorsRoot []byte) ([]byte, error) {
aggregateAndProofSignRequest, err := web3signerv1.GetAggregateAndProofSignRequest(request, genesisValidatorsRoot)
aggregateAndProofSignRequest, err := types.GetAggregateAndProofSignRequest(request, genesisValidatorsRoot)
if err != nil {
return nil, err
}
@@ -482,8 +490,20 @@ func handleAggregateAttestationAndProof(ctx context.Context, validator *validato
return json.Marshal(aggregateAndProofSignRequest)
}
func handleAggregateAttestationAndProofV2(ctx context.Context, fork int, validator *validator.Validate, request *validatorpb.SignRequest, genesisValidatorsRoot []byte) ([]byte, error) {
aggregateAndProofSignRequestV2, err := types.GetAggregateAndProofV2SignRequest(fork, request, genesisValidatorsRoot)
if err != nil {
return nil, err
}
if err = validator.StructCtx(ctx, aggregateAndProofSignRequestV2); err != nil {
return nil, err
}
aggregateAndProofSignRequestsTotal.Inc()
return json.Marshal(aggregateAndProofSignRequestV2)
}
func handleAggregationSlot(ctx context.Context, validator *validator.Validate, request *validatorpb.SignRequest, genesisValidatorsRoot []byte) ([]byte, error) {
aggregationSlotSignRequest, err := web3signerv1.GetAggregationSlotSignRequest(request, genesisValidatorsRoot)
aggregationSlotSignRequest, err := types.GetAggregationSlotSignRequest(request, genesisValidatorsRoot)
if err != nil {
return nil, err
}
@@ -495,7 +515,7 @@ func handleAggregationSlot(ctx context.Context, validator *validator.Validate, r
}
func handleBlockAltair(ctx context.Context, validator *validator.Validate, request *validatorpb.SignRequest, genesisValidatorsRoot []byte) ([]byte, error) {
blockv2AltairSignRequest, err := web3signerv1.GetBlockAltairSignRequest(request, genesisValidatorsRoot)
blockv2AltairSignRequest, err := types.GetBlockAltairSignRequest(request, genesisValidatorsRoot)
if err != nil {
return nil, err
}
@@ -507,7 +527,7 @@ func handleBlockAltair(ctx context.Context, validator *validator.Validate, reque
}
func handleBlockBellatrix(ctx context.Context, validator *validator.Validate, request *validatorpb.SignRequest, genesisValidatorsRoot []byte) ([]byte, error) {
blockv2BellatrixSignRequest, err := web3signerv1.GetBlockV2BlindedSignRequest(request, genesisValidatorsRoot)
blockv2BellatrixSignRequest, err := types.GetBlockV2BlindedSignRequest(request, genesisValidatorsRoot)
if err != nil {
return nil, err
}
@@ -519,7 +539,7 @@ func handleBlockBellatrix(ctx context.Context, validator *validator.Validate, re
}
func handleBlindedBlockBellatrix(ctx context.Context, validator *validator.Validate, request *validatorpb.SignRequest, genesisValidatorsRoot []byte) ([]byte, error) {
blindedBlockv2SignRequest, err := web3signerv1.GetBlockV2BlindedSignRequest(request, genesisValidatorsRoot)
blindedBlockv2SignRequest, err := types.GetBlockV2BlindedSignRequest(request, genesisValidatorsRoot)
if err != nil {
return nil, err
}
@@ -531,7 +551,7 @@ func handleBlindedBlockBellatrix(ctx context.Context, validator *validator.Valid
}
func handleBlockCapella(ctx context.Context, validator *validator.Validate, request *validatorpb.SignRequest, genesisValidatorsRoot []byte) ([]byte, error) {
blockv2CapellaSignRequest, err := web3signerv1.GetBlockV2BlindedSignRequest(request, genesisValidatorsRoot)
blockv2CapellaSignRequest, err := types.GetBlockV2BlindedSignRequest(request, genesisValidatorsRoot)
if err != nil {
return nil, err
}
@@ -543,7 +563,7 @@ func handleBlockCapella(ctx context.Context, validator *validator.Validate, requ
}
func handleBlindedBlockCapella(ctx context.Context, validator *validator.Validate, request *validatorpb.SignRequest, genesisValidatorsRoot []byte) ([]byte, error) {
blindedBlockv2CapellaSignRequest, err := web3signerv1.GetBlockV2BlindedSignRequest(request, genesisValidatorsRoot)
blindedBlockv2CapellaSignRequest, err := types.GetBlockV2BlindedSignRequest(request, genesisValidatorsRoot)
if err != nil {
return nil, err
}
@@ -555,7 +575,7 @@ func handleBlindedBlockCapella(ctx context.Context, validator *validator.Validat
}
func handleBlockDeneb(ctx context.Context, validator *validator.Validate, request *validatorpb.SignRequest, genesisValidatorsRoot []byte) ([]byte, error) {
blockv2DenebSignRequest, err := web3signerv1.GetBlockV2BlindedSignRequest(request, genesisValidatorsRoot)
blockv2DenebSignRequest, err := types.GetBlockV2BlindedSignRequest(request, genesisValidatorsRoot)
if err != nil {
return nil, err
}
@@ -567,7 +587,7 @@ func handleBlockDeneb(ctx context.Context, validator *validator.Validate, reques
}
func handleBlindedBlockDeneb(ctx context.Context, validator *validator.Validate, request *validatorpb.SignRequest, genesisValidatorsRoot []byte) ([]byte, error) {
blindedBlockv2DenebSignRequest, err := web3signerv1.GetBlockV2BlindedSignRequest(request, genesisValidatorsRoot)
blindedBlockv2DenebSignRequest, err := types.GetBlockV2BlindedSignRequest(request, genesisValidatorsRoot)
if err != nil {
return nil, err
}
@@ -578,8 +598,32 @@ func handleBlindedBlockDeneb(ctx context.Context, validator *validator.Validate,
return json.Marshal(blindedBlockv2DenebSignRequest)
}
func handleBlockElectra(ctx context.Context, validator *validator.Validate, request *validatorpb.SignRequest, genesisValidatorsRoot []byte) ([]byte, error) {
blockv2ElectraSignRequest, err := types.GetBlockV2BlindedSignRequest(request, genesisValidatorsRoot)
if err != nil {
return nil, err
}
if err = validator.StructCtx(ctx, blockv2ElectraSignRequest); err != nil {
return nil, err
}
remoteBlockSignRequestsTotal.WithLabelValues("electra", "false").Inc()
return json.Marshal(blockv2ElectraSignRequest)
}
func handleBlindedBlockElectra(ctx context.Context, validator *validator.Validate, request *validatorpb.SignRequest, genesisValidatorsRoot []byte) ([]byte, error) {
blindedBlockv2ElectraSignRequest, err := types.GetBlockV2BlindedSignRequest(request, genesisValidatorsRoot)
if err != nil {
return nil, err
}
if err = validator.StructCtx(ctx, blindedBlockv2ElectraSignRequest); err != nil {
return nil, err
}
remoteBlockSignRequestsTotal.WithLabelValues("electra", "true").Inc()
return json.Marshal(blindedBlockv2ElectraSignRequest)
}
func handleRandaoReveal(ctx context.Context, validator *validator.Validate, request *validatorpb.SignRequest, genesisValidatorsRoot []byte) ([]byte, error) {
randaoRevealSignRequest, err := web3signerv1.GetRandaoRevealSignRequest(request, genesisValidatorsRoot)
randaoRevealSignRequest, err := types.GetRandaoRevealSignRequest(request, genesisValidatorsRoot)
if err != nil {
return nil, err
}
@@ -591,7 +635,7 @@ func handleRandaoReveal(ctx context.Context, validator *validator.Validate, requ
}
func handleVoluntaryExit(ctx context.Context, validator *validator.Validate, request *validatorpb.SignRequest, genesisValidatorsRoot []byte) ([]byte, error) {
voluntaryExitRequest, err := web3signerv1.GetVoluntaryExitSignRequest(request, genesisValidatorsRoot)
voluntaryExitRequest, err := types.GetVoluntaryExitSignRequest(request, genesisValidatorsRoot)
if err != nil {
return nil, err
}
@@ -603,7 +647,7 @@ func handleVoluntaryExit(ctx context.Context, validator *validator.Validate, req
}
func handleSyncMessageBlockRoot(ctx context.Context, validator *validator.Validate, request *validatorpb.SignRequest, genesisValidatorsRoot []byte) ([]byte, error) {
syncCommitteeMessageRequest, err := web3signerv1.GetSyncCommitteeMessageSignRequest(request, genesisValidatorsRoot)
syncCommitteeMessageRequest, err := types.GetSyncCommitteeMessageSignRequest(request, genesisValidatorsRoot)
if err != nil {
return nil, err
}
@@ -615,7 +659,7 @@ func handleSyncMessageBlockRoot(ctx context.Context, validator *validator.Valida
}
func handleSyncAggregatorSelectionData(ctx context.Context, validator *validator.Validate, request *validatorpb.SignRequest, genesisValidatorsRoot []byte) ([]byte, error) {
syncCommitteeSelectionProofRequest, err := web3signerv1.GetSyncCommitteeSelectionProofSignRequest(request, genesisValidatorsRoot)
syncCommitteeSelectionProofRequest, err := types.GetSyncCommitteeSelectionProofSignRequest(request, genesisValidatorsRoot)
if err != nil {
return nil, err
}
@@ -627,7 +671,7 @@ func handleSyncAggregatorSelectionData(ctx context.Context, validator *validator
}
func handleContributionAndProof(ctx context.Context, validator *validator.Validate, request *validatorpb.SignRequest, genesisValidatorsRoot []byte) ([]byte, error) {
contributionAndProofRequest, err := web3signerv1.GetSyncCommitteeContributionAndProofSignRequest(request, genesisValidatorsRoot)
contributionAndProofRequest, err := types.GetSyncCommitteeContributionAndProofSignRequest(request, genesisValidatorsRoot)
if err != nil {
return nil, err
}
@@ -639,7 +683,7 @@ func handleContributionAndProof(ctx context.Context, validator *validator.Valida
}
func handleRegistration(ctx context.Context, validator *validator.Validate, request *validatorpb.SignRequest) ([]byte, error) {
validatorRegistrationRequest, err := web3signerv1.GetValidatorRegistrationSignRequest(request)
validatorRegistrationRequest, err := types.GetValidatorRegistrationSignRequest(request)
if err != nil {
return nil, err
}

View File

@@ -22,7 +22,7 @@ import (
"github.com/prysmaticlabs/prysm/v5/testing/require"
"github.com/prysmaticlabs/prysm/v5/validator/keymanager"
"github.com/prysmaticlabs/prysm/v5/validator/keymanager/remote-web3signer/internal"
"github.com/prysmaticlabs/prysm/v5/validator/keymanager/remote-web3signer/v1/mock"
"github.com/prysmaticlabs/prysm/v5/validator/keymanager/remote-web3signer/types/mock"
logTest "github.com/sirupsen/logrus/hooks/test"
"github.com/stretchr/testify/assert"
)
@@ -407,6 +407,14 @@ func TestKeymanager_Sign(t *testing.T) {
want: desiredSig,
wantErr: false,
},
{
name: "AGGREGATE_AND_PROOF_V2",
args: args{
request: mock.GetMockSignRequest("AGGREGATE_AND_PROOF_V2"),
},
want: desiredSig,
wantErr: false,
},
{
name: "ATTESTATION",
args: args{

View File

@@ -14,10 +14,7 @@ var (
Name: "remote_web3signer_errored_responses_total",
Help: "Total number of errored responses when calling web3signer",
})
blockSignRequestsTotal = promauto.NewCounter(prometheus.CounterOpts{
Name: "remote_web3signer_block_sign_requests_total",
Help: "Total number of block sign requests",
})
aggregationSlotSignRequestsTotal = promauto.NewCounter(prometheus.CounterOpts{
Name: "remote_web3signer_aggregation_slot_requests_total",
Help: "Total number of aggregation slot requests",
@@ -30,6 +27,11 @@ var (
Name: "remote_web3signer_attestation_sign_requests_total",
Help: "Total number of attestation sign requests",
})
//TODO: deprecate these fork specific counters in prysm v6...
blockSignRequestsTotal = promauto.NewCounter(prometheus.CounterOpts{
Name: "remote_web3signer_block_sign_requests_total",
Help: "Total number of block sign requests",
})
blockAltairSignRequestsTotal = promauto.NewCounter(prometheus.CounterOpts{
Name: "remote_web3signer_block_altair_sign_requests_total",
Help: "Total number of block altair sign requests",
@@ -58,6 +60,13 @@ var (
Name: "remote_web3signer_blinded_block_deneb_sign_requests_total",
Help: "Total number of blinded block deneb sign requests",
})
/////
remoteBlockSignRequestsTotal = promauto.NewCounterVec(prometheus.CounterOpts{
Name: "remote_block_sign_requests_total",
Help: "Total number of block sign requests with fork and blinded block check",
}, []string{"fork", "isBlinded"})
randaoRevealSignRequestsTotal = promauto.NewCounter(prometheus.CounterOpts{
Name: "remote_web3signer_randao_reveal_sign_requests_total",
Help: "Total number of randao reveal sign requests",

View File

@@ -7,7 +7,7 @@ go_library(
"requests.go",
"web3signer_types.go",
],
importpath = "github.com/prysmaticlabs/prysm/v5/validator/keymanager/remote-web3signer/v1",
importpath = "github.com/prysmaticlabs/prysm/v5/validator/keymanager/remote-web3signer/types",
visibility = ["//visibility:public"],
deps = [
"//consensus-types/blocks:go_default_library",
@@ -16,6 +16,7 @@ go_library(
"//network/forks:go_default_library",
"//proto/prysm/v1alpha1:go_default_library",
"//proto/prysm/v1alpha1/validator-client:go_default_library",
"//runtime/version:go_default_library",
"//time/slots:go_default_library",
"@com_github_ethereum_go_ethereum//common/hexutil:go_default_library",
"@com_github_pkg_errors//:go_default_library",
@@ -35,7 +36,7 @@ go_test(
"//proto/prysm/v1alpha1:go_default_library",
"//proto/prysm/v1alpha1/validator-client:go_default_library",
"//testing/require:go_default_library",
"//validator/keymanager/remote-web3signer/v1/mock:go_default_library",
"//validator/keymanager/remote-web3signer/types/mock:go_default_library",
"@com_github_ethereum_go_ethereum//common/hexutil:go_default_library",
"@com_github_prysmaticlabs_go_bitfield//:go_default_library",
],

View File

@@ -1,4 +1,4 @@
package v1
package types
import (
"fmt"
@@ -44,6 +44,22 @@ func MapAggregateAndProof(from *ethpb.AggregateAttestationAndProof) (*AggregateA
}, nil
}
// MapAggregateAndProofElectra maps the eth2.AggregateAndProofElectra proto to the Web3Signer spec.
func MapAggregateAndProofElectra(from *ethpb.AggregateAttestationAndProofElectra) (*AggregateAndProofElectra, error) {
if from == nil {
return nil, fmt.Errorf("AggregateAttestationAndProof is nil")
}
aggregate, err := MapAttestationElectra(from.Aggregate)
if err != nil {
return nil, err
}
return &AggregateAndProofElectra{
AggregatorIndex: fmt.Sprint(from.AggregatorIndex),
Aggregate: aggregate,
SelectionProof: from.SelectionProof,
}, nil
}
// MapAttestation maps the eth2.Attestation proto to the Web3Signer spec.
func MapAttestation(attestation *ethpb.Attestation) (*Attestation, error) {
if attestation == nil {
@@ -63,6 +79,29 @@ func MapAttestation(attestation *ethpb.Attestation) (*Attestation, error) {
}, nil
}
// MapAttestationElectra maps the eth2.Attestation proto to the Web3Signer spec.
func MapAttestationElectra(attestation *ethpb.AttestationElectra) (*AttestationElectra, error) {
if attestation == nil {
return nil, fmt.Errorf("attestation is nil")
}
if attestation.AggregationBits == nil {
return nil, fmt.Errorf("aggregation bits in attestation is nil")
}
if attestation.CommitteeBits == nil {
return nil, fmt.Errorf("committee bits in attestation is nil")
}
data, err := MapAttestationData(attestation.Data)
if err != nil {
return nil, err
}
return &AttestationElectra{
AggregationBits: []byte(attestation.AggregationBits),
Data: data,
Signature: attestation.Signature,
CommitteeBits: attestation.CommitteeBits.Bytes(),
}, nil
}
// MapAttestationData maps the eth2.AttestationData proto to the Web3Signer spec.
func MapAttestationData(data *ethpb.AttestationData) (*AttestationData, error) {
if data == nil {

View File

@@ -1,4 +1,4 @@
package v1_test
package types_test
import (
"reflect"
@@ -8,8 +8,8 @@ import (
fieldparams "github.com/prysmaticlabs/prysm/v5/config/fieldparams"
"github.com/prysmaticlabs/prysm/v5/consensus-types/primitives"
ethpb "github.com/prysmaticlabs/prysm/v5/proto/prysm/v1alpha1"
v1 "github.com/prysmaticlabs/prysm/v5/validator/keymanager/remote-web3signer/v1"
"github.com/prysmaticlabs/prysm/v5/validator/keymanager/remote-web3signer/v1/mock"
"github.com/prysmaticlabs/prysm/v5/validator/keymanager/remote-web3signer/types"
"github.com/prysmaticlabs/prysm/v5/validator/keymanager/remote-web3signer/types/mock"
)
func TestMapAggregateAndProof(t *testing.T) {
@@ -19,7 +19,7 @@ func TestMapAggregateAndProof(t *testing.T) {
tests := []struct {
name string
args args
want *v1.AggregateAndProof
want *types.AggregateAndProof
wantErr bool
}{
{
@@ -43,7 +43,7 @@ func TestMapAggregateAndProof(t *testing.T) {
SelectionProof: make([]byte, fieldparams.BLSSignatureLength),
},
},
want: &v1.AggregateAndProof{
want: &types.AggregateAndProof{
AggregatorIndex: "0",
Aggregate: mock.Attestation(),
SelectionProof: make([]byte, fieldparams.BLSSignatureLength),
@@ -53,7 +53,65 @@ func TestMapAggregateAndProof(t *testing.T) {
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
got, err := v1.MapAggregateAndProof(tt.args.from)
got, err := types.MapAggregateAndProof(tt.args.from)
if (err != nil) != tt.wantErr {
t.Errorf("MapAggregateAndProof() error = %v, wantErr %v", err, tt.wantErr)
return
}
if !reflect.DeepEqual(got.Aggregate, tt.want.Aggregate) {
t.Errorf("MapAggregateAndProof() got = %v, want %v", got.Aggregate, tt.want.Aggregate)
}
})
}
}
func TestMapAggregateAndProofElectra(t *testing.T) {
type args struct {
from *ethpb.AggregateAttestationAndProofElectra
}
tests := []struct {
name string
args args
want *types.AggregateAndProofElectra
wantErr bool
}{
{
name: "HappyPathTest",
args: args{
from: &ethpb.AggregateAttestationAndProofElectra{
AggregatorIndex: 0,
Aggregate: &ethpb.AttestationElectra{
AggregationBits: bitfield.Bitlist{0b1101},
Data: &ethpb.AttestationData{
BeaconBlockRoot: make([]byte, fieldparams.RootLength),
Source: &ethpb.Checkpoint{
Root: make([]byte, fieldparams.RootLength),
},
Target: &ethpb.Checkpoint{
Root: make([]byte, fieldparams.RootLength),
},
},
Signature: make([]byte, 96),
CommitteeBits: func() bitfield.Bitvector64 {
committeeBits := bitfield.NewBitvector64()
committeeBits.SetBitAt(0, true)
return committeeBits
}(),
},
SelectionProof: make([]byte, fieldparams.BLSSignatureLength),
},
},
want: &types.AggregateAndProofElectra{
AggregatorIndex: "0",
Aggregate: mock.AttestationElectra(),
SelectionProof: make([]byte, fieldparams.BLSSignatureLength),
},
wantErr: false,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
got, err := types.MapAggregateAndProofElectra(tt.args.from)
if (err != nil) != tt.wantErr {
t.Errorf("MapAggregateAndProof() error = %v, wantErr %v", err, tt.wantErr)
return
@@ -72,7 +130,7 @@ func TestMapAttestation(t *testing.T) {
tests := []struct {
name string
args args
want *v1.Attestation
want *types.Attestation
wantErr bool
}{
{
@@ -98,7 +156,57 @@ func TestMapAttestation(t *testing.T) {
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
got, err := v1.MapAttestation(tt.args.attestation)
got, err := types.MapAttestation(tt.args.attestation)
if (err != nil) != tt.wantErr {
t.Errorf("MapAttestation() error = %v, wantErr %v", err, tt.wantErr)
return
}
if !reflect.DeepEqual(got, tt.want) {
t.Errorf("MapAttestation() got = %v, want %v", got, tt.want)
}
})
}
}
func TestMapAttestationElectra(t *testing.T) {
type args struct {
attestation *ethpb.AttestationElectra
}
tests := []struct {
name string
args args
want *types.AttestationElectra
wantErr bool
}{
{
name: "HappyPathTest",
args: args{
attestation: &ethpb.AttestationElectra{
AggregationBits: bitfield.Bitlist{0b1101},
Data: &ethpb.AttestationData{
BeaconBlockRoot: make([]byte, fieldparams.RootLength),
Source: &ethpb.Checkpoint{
Root: make([]byte, fieldparams.RootLength),
},
Target: &ethpb.Checkpoint{
Root: make([]byte, fieldparams.RootLength),
},
},
CommitteeBits: func() bitfield.Bitvector64 {
committeeBits := bitfield.NewBitvector64()
committeeBits.SetBitAt(0, true)
return committeeBits
}(),
Signature: make([]byte, 96),
},
},
want: mock.AttestationElectra(),
wantErr: false,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
got, err := types.MapAttestationElectra(tt.args.attestation)
if (err != nil) != tt.wantErr {
t.Errorf("MapAttestation() error = %v, wantErr %v", err, tt.wantErr)
return
@@ -117,7 +225,7 @@ func TestMapAttestationData(t *testing.T) {
tests := []struct {
name string
args args
want *v1.AttestationData
want *types.AttestationData
wantErr bool
}{
{
@@ -139,7 +247,7 @@ func TestMapAttestationData(t *testing.T) {
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
got, err := v1.MapAttestationData(tt.args.data)
got, err := types.MapAttestationData(tt.args.data)
if (err != nil) != tt.wantErr {
t.Errorf("MapAttestationData() error = %v, wantErr %v", err, tt.wantErr)
return
@@ -158,7 +266,7 @@ func TestMapAttesterSlashing(t *testing.T) {
tests := []struct {
name string
args args
want *v1.AttesterSlashing
want *types.AttesterSlashing
wantErr bool
}{
{
@@ -193,7 +301,7 @@ func TestMapAttesterSlashing(t *testing.T) {
},
},
},
want: &v1.AttesterSlashing{
want: &types.AttesterSlashing{
Attestation1: mock.IndexedAttestation(),
Attestation2: mock.IndexedAttestation(),
},
@@ -202,7 +310,7 @@ func TestMapAttesterSlashing(t *testing.T) {
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
got, err := v1.MapAttesterSlashing(tt.args.slashing)
got, err := types.MapAttesterSlashing(tt.args.slashing)
if (err != nil) != tt.wantErr {
t.Errorf("MapAttesterSlashing() error = %v, wantErr %v", err, tt.wantErr)
return
@@ -221,7 +329,7 @@ func TestMapBeaconBlockAltair(t *testing.T) {
tests := []struct {
name string
args args
want *v1.BeaconBlockAltair
want *types.BeaconBlockAltair
wantErr bool
}{
{
@@ -342,7 +450,7 @@ func TestMapBeaconBlockAltair(t *testing.T) {
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
got, err := v1.MapBeaconBlockAltair(tt.args.block)
got, err := types.MapBeaconBlockAltair(tt.args.block)
if (err != nil) != tt.wantErr {
t.Errorf("MapBeaconBlockAltair() error = %v, wantErr %v", err, tt.wantErr)
return
@@ -361,7 +469,7 @@ func TestMapBeaconBlockBody(t *testing.T) {
tests := []struct {
name string
args args
want *v1.BeaconBlockBody
want *types.BeaconBlockBody
wantErr bool
}{
{
@@ -472,7 +580,7 @@ func TestMapBeaconBlockBody(t *testing.T) {
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
got, err := v1.MapBeaconBlockBody(tt.args.body)
got, err := types.MapBeaconBlockBody(tt.args.body)
if (err != nil) != tt.wantErr {
t.Errorf("MapBeaconBlockBody() error = %v, wantErr %v", err, tt.wantErr)
return
@@ -491,7 +599,7 @@ func TestMapContributionAndProof(t *testing.T) {
tests := []struct {
name string
args args
want *v1.ContributionAndProof
want *types.ContributionAndProof
wantErr bool
}{
{
@@ -514,7 +622,7 @@ func TestMapContributionAndProof(t *testing.T) {
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
got, err := v1.MapContributionAndProof(tt.args.contribution)
got, err := types.MapContributionAndProof(tt.args.contribution)
if (err != nil) != tt.wantErr {
t.Errorf("MapContributionAndProof() error = %v, wantErr %v", err, tt.wantErr)
return
@@ -535,7 +643,7 @@ func TestMapForkInfo(t *testing.T) {
tests := []struct {
name string
args args
want *v1.ForkInfo
want *types.ForkInfo
wantErr bool
}{
{
@@ -550,7 +658,7 @@ func TestMapForkInfo(t *testing.T) {
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
got, err := v1.MapForkInfo(tt.args.slot, tt.args.genesisValidatorsRoot)
got, err := types.MapForkInfo(tt.args.slot, tt.args.genesisValidatorsRoot)
if (err != nil) != tt.wantErr {
t.Errorf("MapForkInfo() error = %v, wantErr %v", err, tt.wantErr)
return
@@ -569,7 +677,7 @@ func TestMapSyncAggregatorSelectionData(t *testing.T) {
tests := []struct {
name string
args args
want *v1.SyncAggregatorSelectionData
want *types.SyncAggregatorSelectionData
wantErr bool
}{
{
@@ -580,7 +688,7 @@ func TestMapSyncAggregatorSelectionData(t *testing.T) {
SubcommitteeIndex: 0,
},
},
want: &v1.SyncAggregatorSelectionData{
want: &types.SyncAggregatorSelectionData{
Slot: "0",
SubcommitteeIndex: "0",
},
@@ -589,7 +697,7 @@ func TestMapSyncAggregatorSelectionData(t *testing.T) {
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
got, err := v1.MapSyncAggregatorSelectionData(tt.args.data)
got, err := types.MapSyncAggregatorSelectionData(tt.args.data)
if (err != nil) != tt.wantErr {
t.Errorf("MapSyncAggregatorSelectionData() error = %v, wantErr %v", err, tt.wantErr)
return

View File

@@ -4,14 +4,14 @@ go_library(
name = "go_default_library",
testonly = True,
srcs = ["mocks.go"],
importpath = "github.com/prysmaticlabs/prysm/v5/validator/keymanager/remote-web3signer/v1/mock",
importpath = "github.com/prysmaticlabs/prysm/v5/validator/keymanager/remote-web3signer/types/mock",
visibility = ["//visibility:public"],
deps = [
"//config/fieldparams:go_default_library",
"//proto/prysm/v1alpha1:go_default_library",
"//proto/prysm/v1alpha1/validator-client:go_default_library",
"//testing/util:go_default_library",
"//validator/keymanager/remote-web3signer/v1:go_default_library",
"//validator/keymanager/remote-web3signer/types:go_default_library",
"@com_github_ethereum_go_ethereum//common/hexutil:go_default_library",
"@com_github_prysmaticlabs_go_bitfield//:go_default_library",
],

View File

@@ -9,7 +9,7 @@ import (
eth "github.com/prysmaticlabs/prysm/v5/proto/prysm/v1alpha1"
validatorpb "github.com/prysmaticlabs/prysm/v5/proto/prysm/v1alpha1/validator-client"
"github.com/prysmaticlabs/prysm/v5/testing/util"
v1 "github.com/prysmaticlabs/prysm/v5/validator/keymanager/remote-web3signer/v1"
"github.com/prysmaticlabs/prysm/v5/validator/keymanager/remote-web3signer/types"
)
/////////////////////////////////////////////////////////////////////////////////////////////////
@@ -79,6 +79,33 @@ func GetMockSignRequest(t string) *validatorpb.SignRequest {
},
SigningSlot: 0,
}
case "AGGREGATE_AND_PROOF_V2":
return &validatorpb.SignRequest{
PublicKey: make([]byte, fieldparams.BLSPubkeyLength),
SigningRoot: make([]byte, fieldparams.RootLength),
SignatureDomain: make([]byte, 4),
Object: &validatorpb.SignRequest_AggregateAttestationAndProofElectra{
AggregateAttestationAndProofElectra: &eth.AggregateAttestationAndProofElectra{
AggregatorIndex: 0,
Aggregate: &eth.AttestationElectra{
AggregationBits: bitfield.Bitlist{0b1101},
Data: &eth.AttestationData{
BeaconBlockRoot: make([]byte, fieldparams.RootLength),
Source: &eth.Checkpoint{
Root: make([]byte, fieldparams.RootLength),
},
Target: &eth.Checkpoint{
Root: make([]byte, fieldparams.RootLength),
},
},
Signature: make([]byte, 96),
CommitteeBits: bitfield.Bitvector64{0x01},
},
SelectionProof: make([]byte, fieldparams.BLSSignatureLength),
},
},
SigningSlot: 0,
}
case "ATTESTATION":
return &validatorpb.SignRequest{
PublicKey: make([]byte, fieldparams.BLSPubkeyLength),
@@ -381,6 +408,24 @@ func GetMockSignRequest(t string) *validatorpb.SignRequest {
BlindedBlockDeneb: util.HydrateBlindedBeaconBlockDeneb(&eth.BlindedBeaconBlockDeneb{}),
},
}
case "BLOCK_V2_ELECTRA":
return &validatorpb.SignRequest{
PublicKey: make([]byte, fieldparams.BLSPubkeyLength),
SigningRoot: make([]byte, fieldparams.RootLength),
SignatureDomain: make([]byte, 4),
Object: &validatorpb.SignRequest_BlockElectra{
BlockElectra: util.HydrateBeaconBlockElectra(&eth.BeaconBlockElectra{}),
},
}
case "BLOCK_V2_BLINDED_ELECTRA":
return &validatorpb.SignRequest{
PublicKey: make([]byte, fieldparams.BLSPubkeyLength),
SigningRoot: make([]byte, fieldparams.RootLength),
SignatureDomain: make([]byte, 4),
Object: &validatorpb.SignRequest_BlindedBlockElectra{
BlindedBlockElectra: util.HydrateBlindedBeaconBlockElectra(&eth.BlindedBeaconBlockElectra{}),
},
}
case "RANDAO_REVEAL":
return &validatorpb.SignRequest{
PublicKey: make([]byte, fieldparams.BLSPubkeyLength),
@@ -469,22 +514,22 @@ func GetMockSignRequest(t string) *validatorpb.SignRequest {
}
// AggregationSlotSignRequest is a mock implementation of the AggregationSlotSignRequest.
func AggregationSlotSignRequest() *v1.AggregationSlotSignRequest {
return &v1.AggregationSlotSignRequest{
func AggregationSlotSignRequest() *types.AggregationSlotSignRequest {
return &types.AggregationSlotSignRequest{
Type: "AGGREGATION_SLOT",
ForkInfo: ForkInfo(),
SigningRoot: make([]byte, fieldparams.RootLength),
AggregationSlot: &v1.AggregationSlot{Slot: "0"},
AggregationSlot: &types.AggregationSlot{Slot: "0"},
}
}
// AggregateAndProofSignRequest is a mock implementation of the AggregateAndProofSignRequest.
func AggregateAndProofSignRequest() *v1.AggregateAndProofSignRequest {
return &v1.AggregateAndProofSignRequest{
func AggregateAndProofSignRequest() *types.AggregateAndProofSignRequest {
return &types.AggregateAndProofSignRequest{
Type: "AGGREGATE_AND_PROOF",
ForkInfo: ForkInfo(),
SigningRoot: make([]byte, fieldparams.RootLength),
AggregateAndProof: &v1.AggregateAndProof{
AggregateAndProof: &types.AggregateAndProof{
AggregatorIndex: "0",
Aggregate: Attestation(),
SelectionProof: make([]byte, fieldparams.BLSSignatureLength),
@@ -493,8 +538,8 @@ func AggregateAndProofSignRequest() *v1.AggregateAndProofSignRequest {
}
// AttestationSignRequest is a mock implementation of the AttestationSignRequest.
func AttestationSignRequest() *v1.AttestationSignRequest {
return &v1.AttestationSignRequest{
func AttestationSignRequest() *types.AttestationSignRequest {
return &types.AttestationSignRequest{
Type: "ATTESTATION",
ForkInfo: ForkInfo(),
SigningRoot: make([]byte, fieldparams.RootLength),
@@ -503,12 +548,12 @@ func AttestationSignRequest() *v1.AttestationSignRequest {
}
// BlockSignRequest is a mock implementation of the BlockSignRequest.
func BlockSignRequest() *v1.BlockSignRequest {
return &v1.BlockSignRequest{
func BlockSignRequest() *types.BlockSignRequest {
return &types.BlockSignRequest{
Type: "BLOCK",
ForkInfo: ForkInfo(),
SigningRoot: make([]byte, fieldparams.RootLength),
Block: &v1.BeaconBlock{
Block: &types.BeaconBlock{
Slot: "0",
ProposerIndex: "0",
ParentRoot: make([]byte, fieldparams.RootLength),
@@ -519,26 +564,26 @@ func BlockSignRequest() *v1.BlockSignRequest {
}
// BlockV2AltairSignRequest is a mock implementation of the BlockAltairSignRequest.
func BlockV2AltairSignRequest() *v1.BlockAltairSignRequest {
return &v1.BlockAltairSignRequest{
func BlockV2AltairSignRequest() *types.BlockAltairSignRequest {
return &types.BlockAltairSignRequest{
Type: "BLOCK_V2",
ForkInfo: ForkInfo(),
SigningRoot: make([]byte, fieldparams.RootLength),
BeaconBlock: &v1.BeaconBlockAltairBlockV2{
BeaconBlock: &types.BeaconBlockAltairBlockV2{
Version: "ALTAIR",
Block: BeaconBlockAltair(),
},
}
}
func BlockV2BlindedSignRequest(bodyRoot []byte, version string) *v1.BlockV2BlindedSignRequest {
return &v1.BlockV2BlindedSignRequest{
func BlockV2BlindedSignRequest(bodyRoot []byte, version string) *types.BlockV2BlindedSignRequest {
return &types.BlockV2BlindedSignRequest{
Type: "BLOCK_V2",
ForkInfo: ForkInfo(),
SigningRoot: make([]byte, fieldparams.RootLength),
BeaconBlock: &v1.BeaconBlockV2Blinded{
BeaconBlock: &types.BeaconBlockV2Blinded{
Version: version,
BlockHeader: &v1.BeaconBlockHeader{
BlockHeader: &types.BeaconBlockHeader{
Slot: "0",
ProposerIndex: "0",
ParentRoot: make([]byte, fieldparams.RootLength),
@@ -550,20 +595,20 @@ func BlockV2BlindedSignRequest(bodyRoot []byte, version string) *v1.BlockV2Blind
}
// RandaoRevealSignRequest is a mock implementation of the RandaoRevealSignRequest.
func RandaoRevealSignRequest() *v1.RandaoRevealSignRequest {
return &v1.RandaoRevealSignRequest{
func RandaoRevealSignRequest() *types.RandaoRevealSignRequest {
return &types.RandaoRevealSignRequest{
Type: "RANDAO_REVEAL",
ForkInfo: ForkInfo(),
SigningRoot: make([]byte, fieldparams.RootLength),
RandaoReveal: &v1.RandaoReveal{
RandaoReveal: &types.RandaoReveal{
Epoch: "0",
},
}
}
// SyncCommitteeContributionAndProofSignRequest is a mock implementation of the SyncCommitteeContributionAndProofSignRequest.
func SyncCommitteeContributionAndProofSignRequest() *v1.SyncCommitteeContributionAndProofSignRequest {
return &v1.SyncCommitteeContributionAndProofSignRequest{
func SyncCommitteeContributionAndProofSignRequest() *types.SyncCommitteeContributionAndProofSignRequest {
return &types.SyncCommitteeContributionAndProofSignRequest{
Type: "SYNC_COMMITTEE_CONTRIBUTION_AND_PROOF",
ForkInfo: ForkInfo(),
SigningRoot: make([]byte, fieldparams.RootLength),
@@ -572,12 +617,12 @@ func SyncCommitteeContributionAndProofSignRequest() *v1.SyncCommitteeContributio
}
// SyncCommitteeMessageSignRequest is a mock implementation of the SyncCommitteeMessageSignRequest.
func SyncCommitteeMessageSignRequest() *v1.SyncCommitteeMessageSignRequest {
return &v1.SyncCommitteeMessageSignRequest{
func SyncCommitteeMessageSignRequest() *types.SyncCommitteeMessageSignRequest {
return &types.SyncCommitteeMessageSignRequest{
Type: "SYNC_COMMITTEE_MESSAGE",
ForkInfo: ForkInfo(),
SigningRoot: make([]byte, fieldparams.RootLength),
SyncCommitteeMessage: &v1.SyncCommitteeMessage{
SyncCommitteeMessage: &types.SyncCommitteeMessage{
BeaconBlockRoot: make([]byte, fieldparams.RootLength),
Slot: "0",
},
@@ -585,12 +630,12 @@ func SyncCommitteeMessageSignRequest() *v1.SyncCommitteeMessageSignRequest {
}
// SyncCommitteeSelectionProofSignRequest is a mock implementation of the SyncCommitteeSelectionProofSignRequest.
func SyncCommitteeSelectionProofSignRequest() *v1.SyncCommitteeSelectionProofSignRequest {
return &v1.SyncCommitteeSelectionProofSignRequest{
func SyncCommitteeSelectionProofSignRequest() *types.SyncCommitteeSelectionProofSignRequest {
return &types.SyncCommitteeSelectionProofSignRequest{
Type: "SYNC_COMMITTEE_SELECTION_PROOF",
ForkInfo: ForkInfo(),
SigningRoot: make([]byte, fieldparams.RootLength),
SyncAggregatorSelectionData: &v1.SyncAggregatorSelectionData{
SyncAggregatorSelectionData: &types.SyncAggregatorSelectionData{
Slot: "0",
SubcommitteeIndex: "0",
},
@@ -598,12 +643,12 @@ func SyncCommitteeSelectionProofSignRequest() *v1.SyncCommitteeSelectionProofSig
}
// VoluntaryExitSignRequest is a mock implementation of the VoluntaryExitSignRequest.
func VoluntaryExitSignRequest() *v1.VoluntaryExitSignRequest {
return &v1.VoluntaryExitSignRequest{
func VoluntaryExitSignRequest() *types.VoluntaryExitSignRequest {
return &types.VoluntaryExitSignRequest{
Type: "VOLUNTARY_EXIT",
ForkInfo: ForkInfo(),
SigningRoot: make([]byte, fieldparams.RootLength),
VoluntaryExit: &v1.VoluntaryExit{
VoluntaryExit: &types.VoluntaryExit{
Epoch: "0",
ValidatorIndex: "0",
},
@@ -611,11 +656,11 @@ func VoluntaryExitSignRequest() *v1.VoluntaryExitSignRequest {
}
// ValidatorRegistrationSignRequest is a mock implementation of the ValidatorRegistrationSignRequest.
func ValidatorRegistrationSignRequest() *v1.ValidatorRegistrationSignRequest {
return &v1.ValidatorRegistrationSignRequest{
func ValidatorRegistrationSignRequest() *types.ValidatorRegistrationSignRequest {
return &types.ValidatorRegistrationSignRequest{
Type: "VALIDATOR_REGISTRATION",
SigningRoot: make([]byte, fieldparams.RootLength),
ValidatorRegistration: &v1.ValidatorRegistration{
ValidatorRegistration: &types.ValidatorRegistration{
FeeRecipient: make([]byte, fieldparams.FeeRecipientLength),
GasLimit: fmt.Sprint(0),
Timestamp: fmt.Sprint(0),
@@ -629,9 +674,9 @@ func ValidatorRegistrationSignRequest() *v1.ValidatorRegistrationSignRequest {
/////////////////////////////////////////////////////////////////////////////////////////////////
// ForkInfo is a mock implementation of the ForkInfo.
func ForkInfo() *v1.ForkInfo {
return &v1.ForkInfo{
Fork: &v1.Fork{
func ForkInfo() *types.ForkInfo {
return &types.ForkInfo{
Fork: &types.Fork{
PreviousVersion: make([]byte, 4),
CurrentVersion: make([]byte, 4),
Epoch: "0",
@@ -641,18 +686,18 @@ func ForkInfo() *v1.ForkInfo {
}
// Attestation is a mock implementation of the Attestation.
func Attestation() *v1.Attestation {
return &v1.Attestation{
func Attestation() *types.Attestation {
return &types.Attestation{
AggregationBits: []byte(bitfield.Bitlist{0b1101}),
Data: &v1.AttestationData{
Data: &types.AttestationData{
Slot: "0",
Index: "0",
BeaconBlockRoot: make([]byte, fieldparams.RootLength),
Source: &v1.Checkpoint{
Source: &types.Checkpoint{
Epoch: "0",
Root: hexutil.Encode(make([]byte, fieldparams.RootLength)),
},
Target: &v1.Checkpoint{
Target: &types.Checkpoint{
Epoch: "0",
Root: hexutil.Encode(make([]byte, fieldparams.RootLength)),
},
@@ -661,18 +706,42 @@ func Attestation() *v1.Attestation {
}
}
func IndexedAttestation() *v1.IndexedAttestation {
return &v1.IndexedAttestation{
// AttestationElectra is a mock implementation of the AttestationElectra.
func AttestationElectra() *types.AttestationElectra {
committeeBits := bitfield.NewBitvector64()
committeeBits.SetBitAt(0, true)
return &types.AttestationElectra{
AggregationBits: []byte(bitfield.Bitlist{0b1101}),
Data: &types.AttestationData{
Slot: "0",
Index: "0",
BeaconBlockRoot: make([]byte, fieldparams.RootLength),
Source: &types.Checkpoint{
Epoch: "0",
Root: hexutil.Encode(make([]byte, fieldparams.RootLength)),
},
Target: &types.Checkpoint{
Epoch: "0",
Root: hexutil.Encode(make([]byte, fieldparams.RootLength)),
},
},
Signature: make([]byte, fieldparams.BLSSignatureLength),
CommitteeBits: []byte(committeeBits),
}
}
func IndexedAttestation() *types.IndexedAttestation {
return &types.IndexedAttestation{
AttestingIndices: []string{"0", "1", "2"},
Data: &v1.AttestationData{
Data: &types.AttestationData{
Slot: "0",
Index: "0",
BeaconBlockRoot: make([]byte, fieldparams.RootLength),
Source: &v1.Checkpoint{
Source: &types.Checkpoint{
Epoch: "0",
Root: hexutil.Encode(make([]byte, fieldparams.RootLength)),
},
Target: &v1.Checkpoint{
Target: &types.Checkpoint{
Epoch: "0",
Root: hexutil.Encode(make([]byte, fieldparams.RootLength)),
},
@@ -681,24 +750,24 @@ func IndexedAttestation() *v1.IndexedAttestation {
}
}
func BeaconBlockAltair() *v1.BeaconBlockAltair {
return &v1.BeaconBlockAltair{
func BeaconBlockAltair() *types.BeaconBlockAltair {
return &types.BeaconBlockAltair{
Slot: "0",
ProposerIndex: "0",
ParentRoot: make([]byte, fieldparams.RootLength),
StateRoot: make([]byte, fieldparams.RootLength),
Body: &v1.BeaconBlockBodyAltair{
Body: &types.BeaconBlockBodyAltair{
RandaoReveal: make([]byte, 32),
Eth1Data: &v1.Eth1Data{
Eth1Data: &types.Eth1Data{
DepositRoot: make([]byte, fieldparams.RootLength),
DepositCount: "0",
BlockHash: make([]byte, 32),
},
Graffiti: make([]byte, 32),
ProposerSlashings: []*v1.ProposerSlashing{
ProposerSlashings: []*types.ProposerSlashing{
{
Signedheader1: &v1.SignedBeaconBlockHeader{
Message: &v1.BeaconBlockHeader{
Signedheader1: &types.SignedBeaconBlockHeader{
Message: &types.BeaconBlockHeader{
Slot: "0",
ProposerIndex: "0",
ParentRoot: make([]byte, fieldparams.RootLength),
@@ -707,8 +776,8 @@ func BeaconBlockAltair() *v1.BeaconBlockAltair {
},
Signature: make([]byte, fieldparams.BLSSignatureLength),
},
Signedheader2: &v1.SignedBeaconBlockHeader{
Message: &v1.BeaconBlockHeader{
Signedheader2: &types.SignedBeaconBlockHeader{
Message: &types.BeaconBlockHeader{
Slot: "0",
ProposerIndex: "0",
ParentRoot: make([]byte, fieldparams.RootLength),
@@ -719,19 +788,19 @@ func BeaconBlockAltair() *v1.BeaconBlockAltair {
},
},
},
AttesterSlashings: []*v1.AttesterSlashing{
AttesterSlashings: []*types.AttesterSlashing{
{
Attestation1: IndexedAttestation(),
Attestation2: IndexedAttestation(),
},
},
Attestations: []*v1.Attestation{
Attestations: []*types.Attestation{
Attestation(),
},
Deposits: []*v1.Deposit{
Deposits: []*types.Deposit{
{
Proof: []string{"0x41"},
Data: &v1.DepositData{
Data: &types.DepositData{
PublicKey: make([]byte, fieldparams.BLSPubkeyLength),
WithdrawalCredentials: make([]byte, 32),
Amount: "0",
@@ -739,16 +808,16 @@ func BeaconBlockAltair() *v1.BeaconBlockAltair {
},
},
},
VoluntaryExits: []*v1.SignedVoluntaryExit{
VoluntaryExits: []*types.SignedVoluntaryExit{
{
Message: &v1.VoluntaryExit{
Message: &types.VoluntaryExit{
Epoch: "0",
ValidatorIndex: "0",
},
Signature: make([]byte, fieldparams.BLSSignatureLength),
},
},
SyncAggregate: &v1.SyncAggregate{
SyncAggregate: &types.SyncAggregate{
SyncCommitteeSignature: make([]byte, fieldparams.BLSSignatureLength),
SyncCommitteeBits: SyncComitteeBits(),
},
@@ -756,19 +825,19 @@ func BeaconBlockAltair() *v1.BeaconBlockAltair {
}
}
func BeaconBlockBody() *v1.BeaconBlockBody {
return &v1.BeaconBlockBody{
func BeaconBlockBody() *types.BeaconBlockBody {
return &types.BeaconBlockBody{
RandaoReveal: make([]byte, 32),
Eth1Data: &v1.Eth1Data{
Eth1Data: &types.Eth1Data{
DepositRoot: make([]byte, fieldparams.RootLength),
DepositCount: "0",
BlockHash: make([]byte, 32),
},
Graffiti: make([]byte, 32),
ProposerSlashings: []*v1.ProposerSlashing{
ProposerSlashings: []*types.ProposerSlashing{
{
Signedheader1: &v1.SignedBeaconBlockHeader{
Message: &v1.BeaconBlockHeader{
Signedheader1: &types.SignedBeaconBlockHeader{
Message: &types.BeaconBlockHeader{
Slot: "0",
ProposerIndex: "0",
ParentRoot: make([]byte, fieldparams.RootLength),
@@ -777,8 +846,8 @@ func BeaconBlockBody() *v1.BeaconBlockBody {
},
Signature: make([]byte, fieldparams.BLSSignatureLength),
},
Signedheader2: &v1.SignedBeaconBlockHeader{
Message: &v1.BeaconBlockHeader{
Signedheader2: &types.SignedBeaconBlockHeader{
Message: &types.BeaconBlockHeader{
Slot: "0",
ProposerIndex: "0",
ParentRoot: make([]byte, fieldparams.RootLength),
@@ -789,19 +858,19 @@ func BeaconBlockBody() *v1.BeaconBlockBody {
},
},
},
AttesterSlashings: []*v1.AttesterSlashing{
AttesterSlashings: []*types.AttesterSlashing{
{
Attestation1: IndexedAttestation(),
Attestation2: IndexedAttestation(),
},
},
Attestations: []*v1.Attestation{
Attestations: []*types.Attestation{
Attestation(),
},
Deposits: []*v1.Deposit{
Deposits: []*types.Deposit{
{
Proof: []string{"0x41"},
Data: &v1.DepositData{
Data: &types.DepositData{
PublicKey: make([]byte, fieldparams.BLSPubkeyLength),
WithdrawalCredentials: make([]byte, 32),
Amount: "0",
@@ -809,9 +878,9 @@ func BeaconBlockBody() *v1.BeaconBlockBody {
},
},
},
VoluntaryExits: []*v1.SignedVoluntaryExit{
VoluntaryExits: []*types.SignedVoluntaryExit{
{
Message: &v1.VoluntaryExit{
Message: &types.VoluntaryExit{
Epoch: "0",
ValidatorIndex: "0",
},
@@ -821,10 +890,10 @@ func BeaconBlockBody() *v1.BeaconBlockBody {
}
}
func ContributionAndProof() *v1.ContributionAndProof {
return &v1.ContributionAndProof{
func ContributionAndProof() *types.ContributionAndProof {
return &types.ContributionAndProof{
AggregatorIndex: "0",
Contribution: &v1.SyncCommitteeContribution{
Contribution: &types.SyncCommitteeContribution{
Slot: "0",
BeaconBlockRoot: make([]byte, fieldparams.RootLength),
SubcommitteeIndex: "0",

View File

@@ -1,12 +1,14 @@
package v1
package types
import (
"fmt"
"strings"
"github.com/pkg/errors"
"github.com/prysmaticlabs/prysm/v5/consensus-types/blocks"
"github.com/prysmaticlabs/prysm/v5/consensus-types/interfaces"
validatorpb "github.com/prysmaticlabs/prysm/v5/proto/prysm/v1alpha1/validator-client"
"github.com/prysmaticlabs/prysm/v5/runtime/version"
)
// GetBlockSignRequest maps the request for signing type BLOCK.
@@ -88,6 +90,34 @@ func GetAggregateAndProofSignRequest(request *validatorpb.SignRequest, genesisVa
}, nil
}
// GetAggregateAndProofV2SignRequest maps the request for signing type AGGREGATE_AND_PROOF_V2 on Electra changes.
func GetAggregateAndProofV2SignRequest(v int, request *validatorpb.SignRequest, genesisValidatorsRoot []byte) (*AggregateAndProofV2SignRequest, error) {
aggregateAttestationAndProof, ok := request.Object.(*validatorpb.SignRequest_AggregateAttestationAndProofElectra)
if !ok {
return nil, errors.New("failed to cast request object to aggregate attestation and proof")
}
if aggregateAttestationAndProof == nil {
return nil, errors.New("invalid sign request: AggregateAndProof is nil")
}
fork, err := MapForkInfo(request.SigningSlot, genesisValidatorsRoot)
if err != nil {
return nil, err
}
aggregateAndProof, err := MapAggregateAndProofElectra(aggregateAttestationAndProof.AggregateAttestationAndProofElectra)
if err != nil {
return nil, err
}
return &AggregateAndProofV2SignRequest{
Type: "AGGREGATE_AND_PROOF_V2",
ForkInfo: fork,
SigningRoot: request.SigningRoot,
AggregateAndProof: &AggregateAndProofV2{
Version: strings.ToUpper(version.String(v)),
Data: aggregateAndProof,
},
}, nil
}
// GetAttestationSignRequest maps the request for signing type ATTESTATION.
func GetAttestationSignRequest(request *validatorpb.SignRequest, genesisValidatorsRoot []byte) (*AttestationSignRequest, error) {
attestation, ok := request.Object.(*validatorpb.SignRequest_AttestationData)
@@ -365,6 +395,34 @@ func GetBlockV2BlindedSignRequest(request *validatorpb.SignRequest, genesisValid
return nil, err
}
b = beaconBlock
case *validatorpb.SignRequest_BlockElectra:
version = "ELECTRA"
blockElectra, ok := request.Object.(*validatorpb.SignRequest_BlockElectra)
if !ok {
return nil, errors.New("failed to cast request object to electra block")
}
if blockElectra == nil {
return nil, errors.New("invalid sign request: electra block is nil")
}
beaconBlock, err := blocks.NewBeaconBlock(blockElectra.BlockElectra)
if err != nil {
return nil, err
}
b = beaconBlock
case *validatorpb.SignRequest_BlindedBlockElectra:
version = "ELECTRA"
blindedBlockElectra, ok := request.Object.(*validatorpb.SignRequest_BlindedBlockElectra)
if !ok {
return nil, errors.New("failed to cast request object to blinded electra block")
}
if blindedBlockElectra == nil {
return nil, errors.New("invalid sign request: blinded electra block is nil")
}
beaconBlock, err := blocks.NewBeaconBlock(blindedBlockElectra.BlindedBlockElectra)
if err != nil {
return nil, err
}
b = beaconBlock
default:
return nil, errors.New("invalid sign request - invalid object type")
}

View File

@@ -1,4 +1,4 @@
package v1_test
package types_test
import (
"reflect"
@@ -8,8 +8,8 @@ import (
fieldparams "github.com/prysmaticlabs/prysm/v5/config/fieldparams"
validatorpb "github.com/prysmaticlabs/prysm/v5/proto/prysm/v1alpha1/validator-client"
"github.com/prysmaticlabs/prysm/v5/testing/require"
v1 "github.com/prysmaticlabs/prysm/v5/validator/keymanager/remote-web3signer/v1"
"github.com/prysmaticlabs/prysm/v5/validator/keymanager/remote-web3signer/v1/mock"
"github.com/prysmaticlabs/prysm/v5/validator/keymanager/remote-web3signer/types"
"github.com/prysmaticlabs/prysm/v5/validator/keymanager/remote-web3signer/types/mock"
)
func TestGetAggregateAndProofSignRequest(t *testing.T) {
@@ -20,7 +20,7 @@ func TestGetAggregateAndProofSignRequest(t *testing.T) {
tests := []struct {
name string
args args
want *v1.AggregateAndProofSignRequest
want *types.AggregateAndProofSignRequest
wantErr bool
}{
{
@@ -35,7 +35,7 @@ func TestGetAggregateAndProofSignRequest(t *testing.T) {
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
got, err := v1.GetAggregateAndProofSignRequest(tt.args.request, tt.args.genesisValidatorsRoot)
got, err := types.GetAggregateAndProofSignRequest(tt.args.request, tt.args.genesisValidatorsRoot)
if (err != nil) != tt.wantErr {
t.Errorf("GetAggregateAndProofSignRequest() error = %v, wantErr %v", err, tt.wantErr)
return
@@ -55,7 +55,7 @@ func TestGetAggregationSlotSignRequest(t *testing.T) {
tests := []struct {
name string
args args
want *v1.AggregationSlotSignRequest
want *types.AggregationSlotSignRequest
wantErr bool
}{
{
@@ -70,7 +70,7 @@ func TestGetAggregationSlotSignRequest(t *testing.T) {
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
got, err := v1.GetAggregationSlotSignRequest(tt.args.request, tt.args.genesisValidatorsRoot)
got, err := types.GetAggregationSlotSignRequest(tt.args.request, tt.args.genesisValidatorsRoot)
if (err != nil) != tt.wantErr {
t.Errorf("GetAggregationSlotSignRequest() error = %v, wantErr %v", err, tt.wantErr)
return
@@ -90,7 +90,7 @@ func TestGetAttestationSignRequest(t *testing.T) {
tests := []struct {
name string
args args
want *v1.AttestationSignRequest
want *types.AttestationSignRequest
wantErr bool
}{
{
@@ -104,7 +104,7 @@ func TestGetAttestationSignRequest(t *testing.T) {
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
got, err := v1.GetAttestationSignRequest(tt.args.request, tt.args.genesisValidatorsRoot)
got, err := types.GetAttestationSignRequest(tt.args.request, tt.args.genesisValidatorsRoot)
if (err != nil) != tt.wantErr {
t.Errorf("GetAttestationSignRequest() error = %v, wantErr %v", err, tt.wantErr)
return
@@ -124,7 +124,7 @@ func TestGetBlockSignRequest(t *testing.T) {
tests := []struct {
name string
args args
want *v1.BlockSignRequest
want *types.BlockSignRequest
wantErr bool
}{
{
@@ -139,7 +139,7 @@ func TestGetBlockSignRequest(t *testing.T) {
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
got, err := v1.GetBlockSignRequest(tt.args.request, tt.args.genesisValidatorsRoot)
got, err := types.GetBlockSignRequest(tt.args.request, tt.args.genesisValidatorsRoot)
if (err != nil) != tt.wantErr {
t.Errorf("GetBlockSignRequest() error = %v, wantErr %v", err, tt.wantErr)
return
@@ -159,7 +159,7 @@ func TestGetBlockV2AltairSignRequest(t *testing.T) {
tests := []struct {
name string
args args
want *v1.BlockAltairSignRequest
want *types.BlockAltairSignRequest
wantErr bool
}{
{
@@ -174,7 +174,7 @@ func TestGetBlockV2AltairSignRequest(t *testing.T) {
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
got, err := v1.GetBlockAltairSignRequest(tt.args.request, tt.args.genesisValidatorsRoot)
got, err := types.GetBlockAltairSignRequest(tt.args.request, tt.args.genesisValidatorsRoot)
if (err != nil) != tt.wantErr {
t.Errorf("GetBlockAltairSignRequest() error = %v, wantErr %v", err, tt.wantErr)
return
@@ -194,7 +194,7 @@ func TestGetRandaoRevealSignRequest(t *testing.T) {
tests := []struct {
name string
args args
want *v1.RandaoRevealSignRequest
want *types.RandaoRevealSignRequest
wantErr bool
}{
{
@@ -209,7 +209,7 @@ func TestGetRandaoRevealSignRequest(t *testing.T) {
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
got, err := v1.GetRandaoRevealSignRequest(tt.args.request, tt.args.genesisValidatorsRoot)
got, err := types.GetRandaoRevealSignRequest(tt.args.request, tt.args.genesisValidatorsRoot)
if (err != nil) != tt.wantErr {
t.Errorf("GetRandaoRevealSignRequest() error = %v, wantErr %v", err, tt.wantErr)
return
@@ -229,7 +229,7 @@ func TestGetSyncCommitteeContributionAndProofSignRequest(t *testing.T) {
tests := []struct {
name string
args args
want *v1.SyncCommitteeContributionAndProofSignRequest
want *types.SyncCommitteeContributionAndProofSignRequest
wantErr bool
}{
{
@@ -244,7 +244,7 @@ func TestGetSyncCommitteeContributionAndProofSignRequest(t *testing.T) {
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
got, err := v1.GetSyncCommitteeContributionAndProofSignRequest(tt.args.request, tt.args.genesisValidatorsRoot)
got, err := types.GetSyncCommitteeContributionAndProofSignRequest(tt.args.request, tt.args.genesisValidatorsRoot)
if (err != nil) != tt.wantErr {
t.Errorf("GetSyncCommitteeContributionAndProofSignRequest() error = %v, wantErr %v", err, tt.wantErr)
return
@@ -264,7 +264,7 @@ func TestGetSyncCommitteeMessageSignRequest(t *testing.T) {
tests := []struct {
name string
args args
want *v1.SyncCommitteeMessageSignRequest
want *types.SyncCommitteeMessageSignRequest
wantErr bool
}{
{
@@ -279,7 +279,7 @@ func TestGetSyncCommitteeMessageSignRequest(t *testing.T) {
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
got, err := v1.GetSyncCommitteeMessageSignRequest(tt.args.request, tt.args.genesisValidatorsRoot)
got, err := types.GetSyncCommitteeMessageSignRequest(tt.args.request, tt.args.genesisValidatorsRoot)
if (err != nil) != tt.wantErr {
t.Errorf("GetSyncCommitteeMessageSignRequest() error = %v, wantErr %v", err, tt.wantErr)
return
@@ -299,7 +299,7 @@ func TestGetSyncCommitteeSelectionProofSignRequest(t *testing.T) {
tests := []struct {
name string
args args
want *v1.SyncCommitteeSelectionProofSignRequest
want *types.SyncCommitteeSelectionProofSignRequest
wantErr bool
}{
{
@@ -314,7 +314,7 @@ func TestGetSyncCommitteeSelectionProofSignRequest(t *testing.T) {
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
got, err := v1.GetSyncCommitteeSelectionProofSignRequest(tt.args.request, tt.args.genesisValidatorsRoot)
got, err := types.GetSyncCommitteeSelectionProofSignRequest(tt.args.request, tt.args.genesisValidatorsRoot)
if (err != nil) != tt.wantErr {
t.Errorf("GetSyncCommitteeSelectionProofSignRequest() error = %v, wantErr %v", err, tt.wantErr)
return
@@ -334,7 +334,7 @@ func TestGetVoluntaryExitSignRequest(t *testing.T) {
tests := []struct {
name string
args args
want *v1.VoluntaryExitSignRequest
want *types.VoluntaryExitSignRequest
wantErr bool
}{
{
@@ -349,7 +349,7 @@ func TestGetVoluntaryExitSignRequest(t *testing.T) {
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
got, err := v1.GetVoluntaryExitSignRequest(tt.args.request, tt.args.genesisValidatorsRoot)
got, err := types.GetVoluntaryExitSignRequest(tt.args.request, tt.args.genesisValidatorsRoot)
if (err != nil) != tt.wantErr {
t.Errorf("GetVoluntaryExitSignRequest() error = %v, wantErr %v", err, tt.wantErr)
return
@@ -369,7 +369,7 @@ func TestGetBlockV2BlindedSignRequest(t *testing.T) {
tests := []struct {
name string
args args
want *v1.BlockV2BlindedSignRequest
want *types.BlockV2BlindedSignRequest
wantErr bool
}{
{
@@ -450,10 +450,36 @@ func TestGetBlockV2BlindedSignRequest(t *testing.T) {
}(t), "DENEB"),
wantErr: false,
},
{
name: "Happy Path Test non blinded Electra",
args: args{
request: mock.GetMockSignRequest("BLOCK_V2_ELECTRA"),
genesisValidatorsRoot: make([]byte, fieldparams.RootLength),
},
want: mock.BlockV2BlindedSignRequest(func(t *testing.T) []byte {
bytevalue, err := hexutil.Decode("0xca4f98890bc98a59f015d06375a5e00546b8f2ac1e88d31b1774ea28d4b3e7d1")
require.NoError(t, err)
return bytevalue
}(t), "ELECTRA"),
wantErr: false,
},
{
name: "Happy Path Test blinded Electra",
args: args{
request: mock.GetMockSignRequest("BLOCK_V2_BLINDED_ELECTRA"),
genesisValidatorsRoot: make([]byte, fieldparams.RootLength),
},
want: mock.BlockV2BlindedSignRequest(func(t *testing.T) []byte {
bytevalue, err := hexutil.Decode("0x60cd4e8a557e64d00f63777b53f18c10cc122997c55f40a37cb19dc2edd3b0c7")
require.NoError(t, err)
return bytevalue
}(t), "ELECTRA"),
wantErr: false,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
got, err := v1.GetBlockV2BlindedSignRequest(tt.args.request, tt.args.genesisValidatorsRoot)
got, err := types.GetBlockV2BlindedSignRequest(tt.args.request, tt.args.genesisValidatorsRoot)
if (err != nil) != tt.wantErr {
t.Errorf("GetBlockV2BlindedSignRequest() error = %v, wantErr %v", err, tt.wantErr)
return
@@ -472,7 +498,7 @@ func TestGetValidatorRegistrationSignRequest(t *testing.T) {
tests := []struct {
name string
args args
want *v1.ValidatorRegistrationSignRequest
want *types.ValidatorRegistrationSignRequest
wantErr bool
}{
{
@@ -486,7 +512,7 @@ func TestGetValidatorRegistrationSignRequest(t *testing.T) {
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
got, err := v1.GetValidatorRegistrationSignRequest(tt.args.request)
got, err := types.GetValidatorRegistrationSignRequest(tt.args.request)
if (err != nil) != tt.wantErr {
t.Errorf("GetValidatorRegistrationSignRequest() error = %v, wantErr %v", err, tt.wantErr)
return

View File

@@ -1,6 +1,6 @@
// Package v1 defines mappings of types as defined by the web3signer official specification for its v1 version i.e. /api/v1/eth2
/* Web3Signer Specs are found by searching Consensys' Web3Signer API specification*/
package v1
package types
import (
"github.com/ethereum/go-ethereum/common/hexutil"
@@ -22,6 +22,20 @@ type AggregateAndProofSignRequest struct {
AggregateAndProof *AggregateAndProof `json:"aggregate_and_proof" validate:"required"`
}
// AggregateAndProofV2SignRequest is a request object for web3signer sign api.
type AggregateAndProofV2SignRequest struct {
Type string `json:"type" validate:"required"`
ForkInfo *ForkInfo `json:"fork_info" validate:"required"`
SigningRoot hexutil.Bytes `json:"signingRoot"`
AggregateAndProof *AggregateAndProofV2 `json:"aggregate_and_proof" validate:"required"`
}
// AggregateAndProofV2 is a wrapper object for AggregateAndProofV2SignRequest
type AggregateAndProofV2 struct {
Version string `json:"version" validate:"required"`
Data *AggregateAndProofElectra `json:"data" validate:"required"` // specifies Electra for now
}
// AttestationSignRequest is a request object for web3signer sign api.
type AttestationSignRequest struct {
Type string `json:"type" validate:"required"`
@@ -134,6 +148,13 @@ type AggregateAndProof struct {
SelectionProof hexutil.Bytes `json:"selection_proof"` /* 96 bytes */
}
// AggregateAndProofElectra a sub property of AggregateAndProofV2ElectraSignRequest.
type AggregateAndProofElectra struct {
AggregatorIndex string `json:"aggregator_index"` /* uint64 */
Aggregate *AttestationElectra `json:"aggregate"`
SelectionProof hexutil.Bytes `json:"selection_proof"` /* 96 bytes */
}
// Attestation a sub property of AggregateAndProofSignRequest.
type Attestation struct {
AggregationBits hexutil.Bytes `json:"aggregation_bits"` /*hex bitlist*/
@@ -141,6 +162,14 @@ type Attestation struct {
Signature hexutil.Bytes `json:"signature"`
}
// AttestationElectra a sub property of AggregateAndProofElectra.
type AttestationElectra struct {
AggregationBits hexutil.Bytes `json:"aggregation_bits"` /*hex bitlist*/
Data *AttestationData `json:"data"`
Signature hexutil.Bytes `json:"signature"`
CommitteeBits hexutil.Bytes `json:"committee_bits"` /* SSZ hexadecimal string */
}
// AttestationData a sub property of Attestation.
type AttestationData struct {
Slot string `json:"slot"` /* uint64 */