From e4c68a967d4f2750622d3ad023550e9db411f0c6 Mon Sep 17 00:00:00 2001 From: rkapka Date: Mon, 6 Feb 2023 18:22:42 +0100 Subject: [PATCH 01/40] in progress --- beacon-chain/rpc/BUILD.bazel | 1 + beacon-chain/rpc/blockfetcher/BUILD.bazel | 16 +++ beacon-chain/rpc/blockfetcher/fetcher.go | 101 ++++++++++++++++++ beacon-chain/rpc/eth/beacon/BUILD.bazel | 1 + beacon-chain/rpc/eth/beacon/blinded_blocks.go | 4 +- beacon-chain/rpc/eth/beacon/blocks.go | 92 ++-------------- beacon-chain/rpc/eth/beacon/server.go | 2 + .../rpc/eth/helpers/error_handling.go | 12 +++ beacon-chain/rpc/eth/rewards/BUILD.bazel | 32 ++++++ beacon-chain/rpc/eth/rewards/handlers.go | 82 ++++++++++++++ beacon-chain/rpc/eth/rewards/server.go | 11 ++ beacon-chain/rpc/eth/rewards/structs.go | 89 +++++++++++++++ beacon-chain/rpc/eth/rewards/structs_test.go | 78 ++++++++++++++ beacon-chain/rpc/service.go | 5 + 14 files changed, 440 insertions(+), 86 deletions(-) create mode 100644 beacon-chain/rpc/blockfetcher/BUILD.bazel create mode 100644 beacon-chain/rpc/blockfetcher/fetcher.go create mode 100644 beacon-chain/rpc/eth/rewards/BUILD.bazel create mode 100644 beacon-chain/rpc/eth/rewards/handlers.go create mode 100644 beacon-chain/rpc/eth/rewards/server.go create mode 100644 beacon-chain/rpc/eth/rewards/structs.go create mode 100644 beacon-chain/rpc/eth/rewards/structs_test.go diff --git a/beacon-chain/rpc/BUILD.bazel b/beacon-chain/rpc/BUILD.bazel index 4ef5ac853d59..a2a8d13ca725 100644 --- a/beacon-chain/rpc/BUILD.bazel +++ b/beacon-chain/rpc/BUILD.bazel @@ -24,6 +24,7 @@ go_library( "//beacon-chain/operations/synccommittee:go_default_library", "//beacon-chain/operations/voluntaryexits:go_default_library", "//beacon-chain/p2p:go_default_library", + "//beacon-chain/rpc/blockfetcher:go_default_library", "//beacon-chain/rpc/eth/beacon:go_default_library", "//beacon-chain/rpc/eth/debug:go_default_library", "//beacon-chain/rpc/eth/events:go_default_library", diff --git a/beacon-chain/rpc/blockfetcher/BUILD.bazel b/beacon-chain/rpc/blockfetcher/BUILD.bazel new file mode 100644 index 000000000000..265557616e05 --- /dev/null +++ b/beacon-chain/rpc/blockfetcher/BUILD.bazel @@ -0,0 +1,16 @@ +load("@prysm//tools/go:def.bzl", "go_library") + +go_library( + name = "go_default_library", + srcs = ["fetcher.go"], + importpath = "github.com/prysmaticlabs/prysm/v3/beacon-chain/rpc/blockfetcher", + visibility = ["//visibility:public"], + deps = [ + "//beacon-chain/blockchain:go_default_library", + "//beacon-chain/db:go_default_library", + "//consensus-types/interfaces:go_default_library", + "//consensus-types/primitives:go_default_library", + "//encoding/bytesutil:go_default_library", + "@com_github_pkg_errors//:go_default_library", + ], +) diff --git a/beacon-chain/rpc/blockfetcher/fetcher.go b/beacon-chain/rpc/blockfetcher/fetcher.go new file mode 100644 index 000000000000..037dcd4fedca --- /dev/null +++ b/beacon-chain/rpc/blockfetcher/fetcher.go @@ -0,0 +1,101 @@ +package blockfetcher + +import ( + "context" + "strconv" + + "github.com/pkg/errors" + "github.com/prysmaticlabs/prysm/v3/beacon-chain/blockchain" + "github.com/prysmaticlabs/prysm/v3/beacon-chain/db" + "github.com/prysmaticlabs/prysm/v3/consensus-types/interfaces" + "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" + "github.com/prysmaticlabs/prysm/v3/encoding/bytesutil" +) + +// BlockIdParseError represents an error scenario where a block ID could not be parsed. +type BlockIdParseError struct { + message string +} + +// NewBlockIdParseError creates a new error instance. +func NewBlockIdParseError(reason error) BlockIdParseError { + return BlockIdParseError{ + message: errors.Wrapf(reason, "could not parse block ID").Error(), + } +} + +// Error returns the underlying error message. +func (e BlockIdParseError) Error() string { + return e.message +} + +// Fetcher is responsible for retrieving info related with the beacon block. +type Fetcher interface { + Block(ctx context.Context, blockId []byte) (interfaces.SignedBeaconBlock, error) +} + +// BlockProvider is a real implementation of Fetcher. +type BlockProvider struct { + BeaconDB db.ReadOnlyDatabase + ChainInfoFetcher blockchain.ChainInfoFetcher +} + +func (p *BlockProvider) Block(ctx context.Context, blockId []byte) (interfaces.SignedBeaconBlock, error) { + var err error + var blk interfaces.SignedBeaconBlock + switch string(blockId) { + case "head": + blk, err = p.ChainInfoFetcher.HeadBlock(ctx) + if err != nil { + return nil, errors.Wrap(err, "could not retrieve head block") + } + case "finalized": + finalized := p.ChainInfoFetcher.FinalizedCheckpt() + finalizedRoot := bytesutil.ToBytes32(finalized.Root) + blk, err = p.BeaconDB.Block(ctx, finalizedRoot) + if err != nil { + return nil, errors.New("could not get finalized block from db") + } + case "genesis": + blk, err = p.BeaconDB.GenesisBlock(ctx) + if err != nil { + return nil, errors.Wrap(err, "could not retrieve genesis block") + } + default: + if len(blockId) == 32 { + blk, err = p.BeaconDB.Block(ctx, bytesutil.ToBytes32(blockId)) + if err != nil { + return nil, errors.Wrap(err, "could not retrieve block") + } + } else { + slot, err := strconv.ParseUint(string(blockId), 10, 64) + if err != nil { + e := NewBlockIdParseError(err) + return nil, &e + } + blks, err := p.BeaconDB.BlocksBySlot(ctx, primitives.Slot(slot)) + if err != nil { + return nil, errors.Wrapf(err, "could not retrieve blocks for slot %d", slot) + } + _, roots, err := p.BeaconDB.BlockRootsBySlot(ctx, primitives.Slot(slot)) + if err != nil { + return nil, errors.Wrapf(err, "could not retrieve block roots for slot %d", slot) + } + numBlks := len(blks) + if numBlks == 0 { + return nil, nil + } + for i, b := range blks { + canonical, err := p.ChainInfoFetcher.IsCanonical(ctx, roots[i]) + if err != nil { + return nil, errors.Wrapf(err, "could not determine if block root is canonical") + } + if canonical { + blk = b + break + } + } + } + } + return blk, nil +} diff --git a/beacon-chain/rpc/eth/beacon/BUILD.bazel b/beacon-chain/rpc/eth/beacon/BUILD.bazel index 2acb8bcde93c..51f946d07492 100644 --- a/beacon-chain/rpc/eth/beacon/BUILD.bazel +++ b/beacon-chain/rpc/eth/beacon/BUILD.bazel @@ -33,6 +33,7 @@ go_library( "//beacon-chain/operations/slashings:go_default_library", "//beacon-chain/operations/voluntaryexits:go_default_library", "//beacon-chain/p2p:go_default_library", + "//beacon-chain/rpc/blockfetcher:go_default_library", "//beacon-chain/rpc/eth/helpers:go_default_library", "//beacon-chain/rpc/prysm/v1alpha1/validator:go_default_library", "//beacon-chain/rpc/statefetcher:go_default_library", diff --git a/beacon-chain/rpc/eth/beacon/blinded_blocks.go b/beacon-chain/rpc/eth/beacon/blinded_blocks.go index bb82a1c00620..38180aa2ba15 100644 --- a/beacon-chain/rpc/eth/beacon/blinded_blocks.go +++ b/beacon-chain/rpc/eth/beacon/blinded_blocks.go @@ -25,7 +25,7 @@ func (bs *Server) GetBlindedBlock(ctx context.Context, req *ethpbv1.BlockRequest ctx, span := trace.StartSpan(ctx, "beacon.GetBlindedBlock") defer span.End() - blk, err := bs.blockFromBlockID(ctx, req.BlockId) + blk, err := bs.BlockFetcher.Block(ctx, req.BlockId) err = handleGetBlockError(blk, err) if err != nil { return nil, err @@ -80,7 +80,7 @@ func (bs *Server) GetBlindedBlockSSZ(ctx context.Context, req *ethpbv1.BlockRequ ctx, span := trace.StartSpan(ctx, "beacon.GetBlindedBlockSSZ") defer span.End() - blk, err := bs.blockFromBlockID(ctx, req.BlockId) + blk, err := bs.BlockFetcher.Block(ctx, req.BlockId) err = handleGetBlockError(blk, err) if err != nil { return nil, err diff --git a/beacon-chain/rpc/eth/beacon/blocks.go b/beacon-chain/rpc/eth/beacon/blocks.go index 310dc935027e..739dc6471b6c 100644 --- a/beacon-chain/rpc/eth/beacon/blocks.go +++ b/beacon-chain/rpc/eth/beacon/blocks.go @@ -11,6 +11,7 @@ import ( blockfeed "github.com/prysmaticlabs/prysm/v3/beacon-chain/core/feed/block" "github.com/prysmaticlabs/prysm/v3/beacon-chain/core/helpers" "github.com/prysmaticlabs/prysm/v3/beacon-chain/db/filters" + "github.com/prysmaticlabs/prysm/v3/beacon-chain/rpc/blockfetcher" rpchelpers "github.com/prysmaticlabs/prysm/v3/beacon-chain/rpc/eth/helpers" fieldparams "github.com/prysmaticlabs/prysm/v3/config/fieldparams" "github.com/prysmaticlabs/prysm/v3/config/params" @@ -37,23 +38,6 @@ var ( errNilBlock = errors.New("nil block") ) -// blockIdParseError represents an error scenario where a block ID could not be parsed. -type blockIdParseError struct { - message string -} - -// newBlockIdParseError creates a new error instance. -func newBlockIdParseError(reason error) blockIdParseError { - return blockIdParseError{ - message: errors.Wrapf(reason, "could not parse block ID").Error(), - } -} - -// Error returns the underlying error message. -func (e *blockIdParseError) Error() string { - return e.message -} - // GetWeakSubjectivity computes the starting epoch of the current weak subjectivity period, and then also // determines the best block root and state root to use for a Checkpoint Sync starting from that point. func (bs *Server) GetWeakSubjectivity(ctx context.Context, _ *empty.Empty) (*ethpbv1.WeakSubjectivityResponse, error) { @@ -100,7 +84,7 @@ func (bs *Server) GetBlockHeader(ctx context.Context, req *ethpbv1.BlockRequest) ctx, span := trace.StartSpan(ctx, "beacon.GetBlockHeader") defer span.End() - blk, err := bs.blockFromBlockID(ctx, req.BlockId) + blk, err := bs.BlockFetcher.Block(ctx, req.BlockId) err = handleGetBlockError(blk, err) if err != nil { return nil, err @@ -288,7 +272,7 @@ func (bs *Server) GetBlock(ctx context.Context, req *ethpbv1.BlockRequest) (*eth ctx, span := trace.StartSpan(ctx, "beacon.GetBlock") defer span.End() - blk, err := bs.blockFromBlockID(ctx, req.BlockId) + blk, err := bs.BlockFetcher.Block(ctx, req.BlockId) err = handleGetBlockError(blk, err) if err != nil { return nil, err @@ -311,7 +295,7 @@ func (bs *Server) GetBlockSSZ(ctx context.Context, req *ethpbv1.BlockRequest) (* ctx, span := trace.StartSpan(ctx, "beacon.GetBlockSSZ") defer span.End() - blk, err := bs.blockFromBlockID(ctx, req.BlockId) + blk, err := bs.BlockFetcher.Block(ctx, req.BlockId) err = handleGetBlockError(blk, err) if err != nil { return nil, err @@ -333,7 +317,7 @@ func (bs *Server) GetBlockV2(ctx context.Context, req *ethpbv2.BlockRequestV2) ( ctx, span := trace.StartSpan(ctx, "beacon.GetBlockV2") defer span.End() - blk, err := bs.blockFromBlockID(ctx, req.BlockId) + blk, err := bs.BlockFetcher.Block(ctx, req.BlockId) err = handleGetBlockError(blk, err) if err != nil { return nil, err @@ -387,7 +371,7 @@ func (bs *Server) GetBlockSSZV2(ctx context.Context, req *ethpbv2.BlockRequestV2 ctx, span := trace.StartSpan(ctx, "beacon.GetBlockSSZV2") defer span.End() - blk, err := bs.blockFromBlockID(ctx, req.BlockId) + blk, err := bs.BlockFetcher.Block(ctx, req.BlockId) err = handleGetBlockError(blk, err) if err != nil { return nil, err @@ -529,7 +513,7 @@ func (bs *Server) ListBlockAttestations(ctx context.Context, req *ethpbv1.BlockR ctx, span := trace.StartSpan(ctx, "beacon.ListBlockAttestations") defer span.End() - blk, err := bs.blockFromBlockID(ctx, req.BlockId) + blk, err := bs.BlockFetcher.Block(ctx, req.BlockId) err = handleGetBlockError(blk, err) if err != nil { return nil, err @@ -556,68 +540,8 @@ func (bs *Server) ListBlockAttestations(ctx context.Context, req *ethpbv1.BlockR }, nil } -func (bs *Server) blockFromBlockID(ctx context.Context, blockId []byte) (interfaces.SignedBeaconBlock, error) { - var err error - var blk interfaces.SignedBeaconBlock - switch string(blockId) { - case "head": - blk, err = bs.ChainInfoFetcher.HeadBlock(ctx) - if err != nil { - return nil, errors.Wrap(err, "could not retrieve head block") - } - case "finalized": - finalized := bs.ChainInfoFetcher.FinalizedCheckpt() - finalizedRoot := bytesutil.ToBytes32(finalized.Root) - blk, err = bs.BeaconDB.Block(ctx, finalizedRoot) - if err != nil { - return nil, errors.New("could not get finalized block from db") - } - case "genesis": - blk, err = bs.BeaconDB.GenesisBlock(ctx) - if err != nil { - return nil, errors.Wrap(err, "could not retrieve blocks for genesis slot") - } - default: - if len(blockId) == 32 { - blk, err = bs.BeaconDB.Block(ctx, bytesutil.ToBytes32(blockId)) - if err != nil { - return nil, errors.Wrap(err, "could not retrieve block") - } - } else { - slot, err := strconv.ParseUint(string(blockId), 10, 64) - if err != nil { - e := newBlockIdParseError(err) - return nil, &e - } - blks, err := bs.BeaconDB.BlocksBySlot(ctx, primitives.Slot(slot)) - if err != nil { - return nil, errors.Wrapf(err, "could not retrieve blocks for slot %d", slot) - } - _, roots, err := bs.BeaconDB.BlockRootsBySlot(ctx, primitives.Slot(slot)) - if err != nil { - return nil, errors.Wrapf(err, "could not retrieve block roots for slot %d", slot) - } - numBlks := len(blks) - if numBlks == 0 { - return nil, nil - } - for i, b := range blks { - canonical, err := bs.ChainInfoFetcher.IsCanonical(ctx, roots[i]) - if err != nil { - return nil, status.Errorf(codes.Internal, "Could not determine if block root is canonical: %v", err) - } - if canonical { - blk = b - break - } - } - } - } - return blk, nil -} - func handleGetBlockError(blk interfaces.SignedBeaconBlock, err error) error { - if invalidBlockIdErr, ok := err.(*blockIdParseError); ok { + if invalidBlockIdErr, ok := err.(*blockfetcher.BlockIdParseError); ok { return status.Errorf(codes.InvalidArgument, "Invalid block ID: %v", invalidBlockIdErr) } if err != nil { diff --git a/beacon-chain/rpc/eth/beacon/server.go b/beacon-chain/rpc/eth/beacon/server.go index 0db2060a7651..5d13d069e036 100644 --- a/beacon-chain/rpc/eth/beacon/server.go +++ b/beacon-chain/rpc/eth/beacon/server.go @@ -14,6 +14,7 @@ import ( "github.com/prysmaticlabs/prysm/v3/beacon-chain/operations/slashings" "github.com/prysmaticlabs/prysm/v3/beacon-chain/operations/voluntaryexits" "github.com/prysmaticlabs/prysm/v3/beacon-chain/p2p" + "github.com/prysmaticlabs/prysm/v3/beacon-chain/rpc/blockfetcher" v1alpha1validator "github.com/prysmaticlabs/prysm/v3/beacon-chain/rpc/prysm/v1alpha1/validator" "github.com/prysmaticlabs/prysm/v3/beacon-chain/rpc/statefetcher" "github.com/prysmaticlabs/prysm/v3/beacon-chain/state/stategen" @@ -35,6 +36,7 @@ type Server struct { VoluntaryExitsPool voluntaryexits.PoolManager StateGenService stategen.StateManager StateFetcher statefetcher.Fetcher + BlockFetcher blockfetcher.Fetcher HeadFetcher blockchain.HeadFetcher OptimisticModeFetcher blockchain.OptimisticModeFetcher V1Alpha1ValidatorServer *v1alpha1validator.Server diff --git a/beacon-chain/rpc/eth/helpers/error_handling.go b/beacon-chain/rpc/eth/helpers/error_handling.go index 9915d3c94d3d..0e4028476e15 100644 --- a/beacon-chain/rpc/eth/helpers/error_handling.go +++ b/beacon-chain/rpc/eth/helpers/error_handling.go @@ -2,6 +2,7 @@ package helpers import ( "errors" + "net/http" "github.com/prysmaticlabs/prysm/v3/beacon-chain/rpc/statefetcher" "github.com/prysmaticlabs/prysm/v3/beacon-chain/state/stategen" @@ -34,3 +35,14 @@ type SingleIndexedVerificationFailure struct { Index int `json:"index"` Message string `json:"message"` } + +// DefaultErrorJson is a JSON representation of a simple error value, containing only a message and an error code. +type DefaultErrorJson struct { + Message string `json:"message"` + Code int `json:"code"` +} + +// WriteError writes the error by manipulating headers and the body of the final response. +func WriteError(w http.ResponseWriter, errJson *DefaultErrorJson) { + +} diff --git a/beacon-chain/rpc/eth/rewards/BUILD.bazel b/beacon-chain/rpc/eth/rewards/BUILD.bazel new file mode 100644 index 000000000000..ca2ab6b74a8b --- /dev/null +++ b/beacon-chain/rpc/eth/rewards/BUILD.bazel @@ -0,0 +1,32 @@ +load("@prysm//tools/go:def.bzl", "go_library", "go_test") + +go_library( + name = "go_default_library", + srcs = [ + "handlers.go", + "server.go", + "structs.go", + ], + importpath = "github.com/prysmaticlabs/prysm/v3/beacon-chain/rpc/eth/rewards", + visibility = ["//visibility:public"], + deps = [ + "//beacon-chain/core/altair:go_default_library", + "//beacon-chain/rpc/blockfetcher:go_default_library", + "//beacon-chain/rpc/eth/helpers:go_default_library", + "//beacon-chain/rpc/statefetcher:go_default_library", + "//consensus-types/blocks:go_default_library", + "//consensus-types/interfaces:go_default_library", + "//consensus-types/primitives:go_default_library", + "@com_github_pkg_errors//:go_default_library", + ], +) + +go_test( + name = "go_default_test", + srcs = ["structs_test.go"], + deps = [ + ":go_default_library", + "//testing/assert:go_default_library", + "//testing/require:go_default_library", + ], +) diff --git a/beacon-chain/rpc/eth/rewards/handlers.go b/beacon-chain/rpc/eth/rewards/handlers.go new file mode 100644 index 000000000000..149465adf94e --- /dev/null +++ b/beacon-chain/rpc/eth/rewards/handlers.go @@ -0,0 +1,82 @@ +package rewards + +import ( + "encoding/json" + "io" + "net/http" + + "github.com/pkg/errors" + "github.com/prysmaticlabs/prysm/v3/beacon-chain/core/altair" + "github.com/prysmaticlabs/prysm/v3/beacon-chain/rpc/blockfetcher" + "github.com/prysmaticlabs/prysm/v3/beacon-chain/rpc/eth/helpers" + "github.com/prysmaticlabs/prysm/v3/consensus-types/blocks" + "github.com/prysmaticlabs/prysm/v3/consensus-types/interfaces" +) + +func (s *Server) BlockRewards(w http.ResponseWriter, r *http.Request) { + body, err := io.ReadAll(r.Body) + if err != nil { + errJson := &helpers.DefaultErrorJson{ + Message: errors.Wrapf(err, "could not read request body").Error(), + Code: http.StatusInternalServerError, + } + helpers.WriteError(w, errJson) + return + } + rewardsRequest := &BlockRewardsRequest{} + if err := json.Unmarshal(body, rewardsRequest); err != nil { + errJson := &helpers.DefaultErrorJson{ + Message: errors.Wrapf(err, "could not unmarshal request body").Error(), + Code: http.StatusInternalServerError, + } + helpers.WriteError(w, errJson) + return + } + blk, err := s.BlockFetcher.Block(r.Context(), []byte(rewardsRequest.BlockId)) + if errJson := handleGetBlockError(blk, err); errJson != nil { + helpers.WriteError(w, errJson) + return + } + stateRoot := blk.Block().StateRoot() + st, err := s.StateFetcher.State(r.Context(), stateRoot[:]) + if err != nil { + errJson := &helpers.DefaultErrorJson{ + Message: errors.Wrapf(err, "could not get state").Error(), + Code: http.StatusInternalServerError, + } + helpers.WriteError(w, errJson) + return + } + vals, bal, err := altair.InitializePrecomputeValidators(r.Context(), st) + if err != nil { + errJson := &helpers.DefaultErrorJson{ + Message: errors.Wrapf(err, "could not initialize precompute validators").Error(), + Code: http.StatusInternalServerError, + } + helpers.WriteError(w, errJson) + return + } + +} + +func handleGetBlockError(blk interfaces.SignedBeaconBlock, err error) *helpers.DefaultErrorJson { + if errors.Is(err, blockfetcher.BlockIdParseError{}) { + return &helpers.DefaultErrorJson{ + Message: errors.Wrapf(err, "invalid block ID").Error(), + Code: http.StatusBadRequest, + } + } + if err != nil { + return &helpers.DefaultErrorJson{ + Message: errors.Wrapf(err, "could not get block from block ID").Error(), + Code: http.StatusInternalServerError, + } + } + if err := blocks.BeaconBlockIsNil(blk); err != nil { + return &helpers.DefaultErrorJson{ + Message: errors.Wrapf(err, "could not find requested block").Error(), + Code: http.StatusNotFound, + } + } + return nil +} diff --git a/beacon-chain/rpc/eth/rewards/server.go b/beacon-chain/rpc/eth/rewards/server.go new file mode 100644 index 000000000000..a478461fb322 --- /dev/null +++ b/beacon-chain/rpc/eth/rewards/server.go @@ -0,0 +1,11 @@ +package rewards + +import ( + "github.com/prysmaticlabs/prysm/v3/beacon-chain/rpc/blockfetcher" + "github.com/prysmaticlabs/prysm/v3/beacon-chain/rpc/statefetcher" +) + +type Server struct { + BlockFetcher blockfetcher.Fetcher + StateFetcher statefetcher.Fetcher +} diff --git a/beacon-chain/rpc/eth/rewards/structs.go b/beacon-chain/rpc/eth/rewards/structs.go new file mode 100644 index 000000000000..0db75f784f4c --- /dev/null +++ b/beacon-chain/rpc/eth/rewards/structs.go @@ -0,0 +1,89 @@ +package rewards + +import ( + "encoding/json" + "strconv" + + "github.com/pkg/errors" + types "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" +) + +type BlockRewardsRequest struct { + BlockId string `json:"block_id"` +} + +type BlockRewardsResponse struct { + Data *BlockRewards `json:"data"` + ExecutionOptimistic bool `json:"execution_optimistic"` + Finalized bool `json:"finalized"` +} + +type BlockRewards struct { + ProposerIndex types.ValidatorIndex + Total uint64 + Attestations uint64 + SyncAggregate uint64 + ProposerSlashings uint64 + AttesterSlashings uint64 +} + +type BlockRewardsJson struct { + ProposerIndex string `json:"proposer_index"` + Total string `json:"total"` + Attestations string `json:"attestations"` + SyncAggregate string `json:"sync_aggregate"` + ProposerSlashings string `json:"proposer_slashings"` + AttesterSlashings string `json:"attester_slashings"` +} + +func (r *BlockRewards) MarshalJSON() ([]byte, error) { + return json.Marshal(&BlockRewardsJson{ + ProposerIndex: strconv.FormatUint(uint64(r.ProposerIndex), 10), + Total: strconv.FormatUint(r.Total, 10), + Attestations: strconv.FormatUint(r.Attestations, 10), + SyncAggregate: strconv.FormatUint(r.SyncAggregate, 10), + ProposerSlashings: strconv.FormatUint(r.ProposerSlashings, 10), + AttesterSlashings: strconv.FormatUint(r.AttesterSlashings, 10), + }) +} + +func (r *BlockRewards) UnmarshalJSON(b []byte) error { + j := &BlockRewardsJson{} + err := json.Unmarshal(b, j) + if err != nil { + return err + } + proposerIndex, err := strconv.ParseUint(j.ProposerIndex, 10, 64) + if err != nil { + return errors.Wrapf(err, "could not unmarshal proposer index") + } + total, err := strconv.ParseUint(j.Total, 10, 64) + if err != nil { + return errors.Wrapf(err, "could not unmarshal total") + } + attestations, err := strconv.ParseUint(j.Attestations, 10, 64) + if err != nil { + return errors.Wrapf(err, "could not unmarshal attestations") + } + syncAggregate, err := strconv.ParseUint(j.SyncAggregate, 10, 64) + if err != nil { + return errors.Wrapf(err, "could not unmarshal sync aggregate") + } + proposerSlashings, err := strconv.ParseUint(j.ProposerSlashings, 10, 64) + if err != nil { + return errors.Wrapf(err, "could not unmarshal proposer slashings") + } + attesterSlashings, err := strconv.ParseUint(j.AttesterSlashings, 10, 64) + if err != nil { + return errors.Wrapf(err, "could not unmarshal attester slashings") + } + *r = BlockRewards{ + ProposerIndex: types.ValidatorIndex(proposerIndex), + Total: total, + Attestations: attestations, + SyncAggregate: syncAggregate, + ProposerSlashings: proposerSlashings, + AttesterSlashings: attesterSlashings, + } + return nil +} diff --git a/beacon-chain/rpc/eth/rewards/structs_test.go b/beacon-chain/rpc/eth/rewards/structs_test.go new file mode 100644 index 000000000000..47c3af97b7c5 --- /dev/null +++ b/beacon-chain/rpc/eth/rewards/structs_test.go @@ -0,0 +1,78 @@ +package rewards_test + +import ( + "encoding/json" + "testing" + + "github.com/prysmaticlabs/prysm/v3/beacon-chain/rpc/eth/rewards" + "github.com/prysmaticlabs/prysm/v3/testing/assert" + "github.com/prysmaticlabs/prysm/v3/testing/require" +) + +func TestMarshalBlockRewards(t *testing.T) { + r := &rewards.BlockRewards{ + ProposerIndex: 123, + Total: 123, + Attestations: 123, + SyncAggregate: 123, + ProposerSlashings: 123, + AttesterSlashings: 123, + } + j, err := json.Marshal(r) + require.NoError(t, err) + expected := `{"proposer_index":"123","total":"123","attestations":"123","sync_aggregate":"123","proposer_slashings":"123","attester_slashings":"123"}` + assert.Equal(t, expected, string(j)) +} + +func TestUnmarshalBlockRewards(t *testing.T) { + t.Run("ok", func(t *testing.T) { + s := `{"proposer_index":"123","total":"123","attestations":"123","sync_aggregate":"123","proposer_slashings":"123","attester_slashings":"123"}` + r := &rewards.BlockRewards{} + require.NoError(t, r.UnmarshalJSON([]byte(s))) + expected := &rewards.BlockRewards{ + ProposerIndex: 123, + Total: 123, + Attestations: 123, + SyncAggregate: 123, + ProposerSlashings: 123, + AttesterSlashings: 123, + } + assert.DeepEqual(t, expected, r) + }) + t.Run("invalid proposer index", func(t *testing.T) { + s := `{"proposer_index":"foo","total":"123","attestations":"123","sync_aggregate":"123","proposer_slashings":"123","attester_slashings":"123"}` + r := &rewards.BlockRewards{} + err := r.UnmarshalJSON([]byte(s)) + assert.ErrorContains(t, "could not unmarshal proposer index", err) + }) + t.Run("invalid total", func(t *testing.T) { + s := `{"proposer_index":"123","total":"foo","attestations":"123","sync_aggregate":"123","proposer_slashings":"123","attester_slashings":"123"}` + r := &rewards.BlockRewards{} + err := r.UnmarshalJSON([]byte(s)) + assert.ErrorContains(t, "could not unmarshal total", err) + }) + t.Run("invalid attestations", func(t *testing.T) { + s := `{"proposer_index":"123","total":"123","attestations":"foo","sync_aggregate":"123","proposer_slashings":"123","attester_slashings":"123"}` + r := &rewards.BlockRewards{} + err := r.UnmarshalJSON([]byte(s)) + assert.ErrorContains(t, "could not unmarshal attestations", err) + }) + t.Run("invalid sync aggregate", func(t *testing.T) { + s := `{"proposer_index":"123","total":"123","attestations":"123","sync_aggregate":"foo","proposer_slashings":"123","attester_slashings":"123"}` + r := &rewards.BlockRewards{} + err := r.UnmarshalJSON([]byte(s)) + assert.ErrorContains(t, "could not unmarshal sync aggregate", err) + }) + t.Run("invalid proposer slashings", func(t *testing.T) { + s := `{"proposer_index":"123","total":"123","attestations":"123","sync_aggregate":"123","proposer_slashings":"foo","attester_slashings":"123"}` + r := &rewards.BlockRewards{} + err := r.UnmarshalJSON([]byte(s)) + assert.ErrorContains(t, "could not unmarshal proposer slashings", err) + }) + t.Run("invalid attester slashings", func(t *testing.T) { + s := `{"proposer_index":"123","total":"123","attestations":"123","sync_aggregate":"123","proposer_slashings":"123","attester_slashings":"foo"}` + r := &rewards.BlockRewards{} + err := r.UnmarshalJSON([]byte(s)) + assert.ErrorContains(t, "could not unmarshal attester slashings", err) + }) +} diff --git a/beacon-chain/rpc/service.go b/beacon-chain/rpc/service.go index 7c8ac89f3bc7..1293abb2c396 100644 --- a/beacon-chain/rpc/service.go +++ b/beacon-chain/rpc/service.go @@ -28,6 +28,7 @@ import ( "github.com/prysmaticlabs/prysm/v3/beacon-chain/operations/synccommittee" "github.com/prysmaticlabs/prysm/v3/beacon-chain/operations/voluntaryexits" "github.com/prysmaticlabs/prysm/v3/beacon-chain/p2p" + "github.com/prysmaticlabs/prysm/v3/beacon-chain/rpc/blockfetcher" "github.com/prysmaticlabs/prysm/v3/beacon-chain/rpc/eth/beacon" "github.com/prysmaticlabs/prysm/v3/beacon-chain/rpc/eth/debug" "github.com/prysmaticlabs/prysm/v3/beacon-chain/rpc/eth/events" @@ -315,6 +316,10 @@ func (s *Service) Start() { StateGenService: s.cfg.StateGen, ReplayerBuilder: ch, }, + BlockFetcher: &blockfetcher.BlockProvider{ + BeaconDB: s.cfg.BeaconDB, + ChainInfoFetcher: s.cfg.ChainInfoFetcher, + }, OptimisticModeFetcher: s.cfg.OptimisticModeFetcher, HeadFetcher: s.cfg.HeadFetcher, VoluntaryExitsPool: s.cfg.ExitPool, From a5c71faebdee5749bb74b8c9f7b224420b50cedd Mon Sep 17 00:00:00 2001 From: rkapka Date: Thu, 16 Feb 2023 15:24:36 +0100 Subject: [PATCH 02/40] block rewards --- beacon-chain/core/blocks/BUILD.bazel | 1 + beacon-chain/core/blocks/rewards.go | 37 +++++++++++++++++++ beacon-chain/core/epoch/precompute/new.go | 2 +- .../core/epoch/precompute/reward_penalty.go | 2 +- beacon-chain/core/validators/validator.go | 1 - 5 files changed, 40 insertions(+), 3 deletions(-) create mode 100644 beacon-chain/core/blocks/rewards.go diff --git a/beacon-chain/core/blocks/BUILD.bazel b/beacon-chain/core/blocks/BUILD.bazel index 38c2cde22a11..2e2eaf2ace63 100644 --- a/beacon-chain/core/blocks/BUILD.bazel +++ b/beacon-chain/core/blocks/BUILD.bazel @@ -15,6 +15,7 @@ go_library( "payload.go", "proposer_slashing.go", "randao.go", + "rewards.go", "signature.go", "withdrawals.go", ], diff --git a/beacon-chain/core/blocks/rewards.go b/beacon-chain/core/blocks/rewards.go new file mode 100644 index 000000000000..c8c88cf28f0d --- /dev/null +++ b/beacon-chain/core/blocks/rewards.go @@ -0,0 +1,37 @@ +package blocks + +import ( + "github.com/pkg/errors" + "github.com/prysmaticlabs/prysm/v3/beacon-chain/state" + "github.com/prysmaticlabs/prysm/v3/config/params" + "github.com/prysmaticlabs/prysm/v3/consensus-types/interfaces" + "github.com/prysmaticlabs/prysm/v3/math" +) + +type validatorInfo struct { + isPrevEpochAttester bool + isSlashed bool +} + +func AttestationRewards(st state.ReadOnlyBeaconState, b interfaces.BeaconBlockBody) (uint64, error) { + currEpochActiveBalance := uint64(0) + if err := st.ReadFromEveryValidator(func(idx int, val state.ReadOnlyValidator) error { + currEpochActiveBalance += val.EffectiveBalance() + return nil + }); err != nil { + return 0, errors.Wrap(err, "failed to read validator data") + } + balanceSqrt := math.IntegerSquareRoot(currEpochActiveBalance) + // Balance square root cannot be 0, this prevents division by 0. + if balanceSqrt == 0 { + balanceSqrt = 1 + } + + baseRewardFactor := params.BeaconConfig().BaseRewardFactor + baseRewardsPerEpoch := params.BeaconConfig().BaseRewardsPerEpoch + proposerRewardQuotient := params.BeaconConfig().ProposerRewardQuotient + baseReward := currEpochActiveBalance * baseRewardFactor / balanceSqrt / baseRewardsPerEpoch + proposerReward := baseReward / proposerRewardQuotient + + return proposerReward * uint64(len(b.Attestations())), nil +} diff --git a/beacon-chain/core/epoch/precompute/new.go b/beacon-chain/core/epoch/precompute/new.go index bf3907f11355..0446f1892412 100644 --- a/beacon-chain/core/epoch/precompute/new.go +++ b/beacon-chain/core/epoch/precompute/new.go @@ -17,7 +17,7 @@ import ( // New gets called at the beginning of process epoch cycle to return // pre computed instances of validators attesting records and total // balances attested in an epoch. -func New(ctx context.Context, s state.BeaconState) ([]*Validator, *Balance, error) { +func New(ctx context.Context, s state.ReadOnlyBeaconState) ([]*Validator, *Balance, error) { ctx, span := trace.StartSpan(ctx, "precomputeEpoch.New") defer span.End() diff --git a/beacon-chain/core/epoch/precompute/reward_penalty.go b/beacon-chain/core/epoch/precompute/reward_penalty.go index 68d7a3b5d09e..e240d1170ef2 100644 --- a/beacon-chain/core/epoch/precompute/reward_penalty.go +++ b/beacon-chain/core/epoch/precompute/reward_penalty.go @@ -175,7 +175,7 @@ func ProposersDelta(state state.ReadOnlyBeaconState, pBal *Balance, vp []*Valida // This should never happen with a valid state / validator. return nil, errors.New("proposer index out of range") } - // Only apply inclusion rewards to proposer only if the attested hasn't been slashed. + // Only apply inclusion rewards to proposer only if the attester hasn't been slashed. if v.IsPrevEpochAttester && !v.IsSlashed { vBalance := v.CurrentEpochEffectiveBalance baseReward := vBalance * baseRewardFactor / balanceSqrt / baseRewardsPerEpoch diff --git a/beacon-chain/core/validators/validator.go b/beacon-chain/core/validators/validator.go index 67e74142d6b9..6569321e3411 100644 --- a/beacon-chain/core/validators/validator.go +++ b/beacon-chain/core/validators/validator.go @@ -178,7 +178,6 @@ func SlashValidator( if err != nil { return nil, errors.Wrap(err, "could not get proposer idx") } - // In phase 0, the proposer is the whistleblower. whistleBlowerIdx := proposerIdx whistleblowerReward := validator.EffectiveBalance / params.BeaconConfig().WhistleBlowerRewardQuotient proposerReward := whistleblowerReward / proposerRewardQuotient From d68bfea6a1c6315ab640548e32822e97466f32d3 Mon Sep 17 00:00:00 2001 From: rkapka Date: Mon, 20 Feb 2023 19:38:30 +0100 Subject: [PATCH 03/40] calculate rewards --- api/gateway/gateway.go | 4 +- beacon-chain/core/altair/block.go | 40 +++--- .../transition/transition_no_verify_sig.go | 2 +- beacon-chain/node/BUILD.bazel | 1 + beacon-chain/node/node.go | 13 +- beacon-chain/rpc/BUILD.bazel | 2 + beacon-chain/rpc/eth/helpers/BUILD.bazel | 2 + .../rpc/eth/helpers/error_handling.go | 12 -- beacon-chain/rpc/eth/helpers/http.go | 41 ++++++ beacon-chain/rpc/eth/rewards/BUILD.bazel | 4 + beacon-chain/rpc/eth/rewards/handlers.go | 136 ++++++++++++++++-- beacon-chain/rpc/eth/rewards/server.go | 7 +- beacon-chain/rpc/eth/rewards/structs.go | 4 - beacon-chain/rpc/service.go | 26 +++- beacon-chain/server/main.go | 5 +- .../altair/operations/sync_committee.go | 6 +- .../bellatrix/operations/sync_committee.go | 6 +- .../capella/operations/sync_committee.go | 6 +- validator/node/BUILD.bazel | 1 + validator/node/node.go | 3 +- 20 files changed, 255 insertions(+), 66 deletions(-) create mode 100644 beacon-chain/rpc/eth/helpers/http.go diff --git a/api/gateway/gateway.go b/api/gateway/gateway.go index f768b4fc432e..e37d3cf6c218 100644 --- a/api/gateway/gateway.go +++ b/api/gateway/gateway.go @@ -67,11 +67,11 @@ type Gateway struct { } // New returns a new instance of the Gateway. -func New(ctx context.Context, opts ...Option) (*Gateway, error) { +func New(ctx context.Context, router *mux.Router, opts ...Option) (*Gateway, error) { g := &Gateway{ ctx: ctx, cfg: &config{ - router: mux.NewRouter(), + router: router, }, } for _, opt := range opts { diff --git a/beacon-chain/core/altair/block.go b/beacon-chain/core/altair/block.go index d5717af30ac0..5936a7b3bf92 100644 --- a/beacon-chain/core/altair/block.go +++ b/beacon-chain/core/altair/block.go @@ -44,49 +44,51 @@ import ( // increase_balance(state, get_beacon_proposer_index(state), proposer_reward) // else: // decrease_balance(state, participant_index, participant_reward) -func ProcessSyncAggregate(ctx context.Context, s state.BeaconState, sync *ethpb.SyncAggregate) (state.BeaconState, error) { - s, votedKeys, err := processSyncAggregate(ctx, s, sync) +func ProcessSyncAggregate(ctx context.Context, s state.BeaconState, sync *ethpb.SyncAggregate) (state.BeaconState, uint64, error) { + s, votedKeys, reward, err := processSyncAggregate(ctx, s, sync) if err != nil { - return nil, errors.Wrap(err, "could not filter sync committee votes") + return nil, 0, errors.Wrap(err, "could not filter sync committee votes") } if err := VerifySyncCommitteeSig(s, votedKeys, sync.SyncCommitteeSignature); err != nil { - return nil, errors.Wrap(err, "could not verify sync committee signature") + return nil, 0, errors.Wrap(err, "could not verify sync committee signature") } - return s, nil + return s, reward, nil } // processSyncAggregate applies all the logic in the spec function `process_sync_aggregate` except -// verifying the BLS signatures. It returns the modified beacons state and the list of validators' -// public keys that voted, for future signature verification. +// verifying the BLS signatures. It returns the modified beacons state, the list of validators' +// public keys that voted (for future signature verification) and the proposer reward for including +// sync aggregate messages. func processSyncAggregate(ctx context.Context, s state.BeaconState, sync *ethpb.SyncAggregate) ( state.BeaconState, []bls.PublicKey, + uint64, error) { currentSyncCommittee, err := s.CurrentSyncCommittee() if err != nil { - return nil, nil, err + return nil, nil, 0, err } if currentSyncCommittee == nil { - return nil, nil, errors.New("nil current sync committee in state") + return nil, nil, 0, errors.New("nil current sync committee in state") } committeeKeys := currentSyncCommittee.Pubkeys if sync.SyncCommitteeBits.Len() > uint64(len(committeeKeys)) { - return nil, nil, errors.New("bits length exceeds committee length") + return nil, nil, 0, errors.New("bits length exceeds committee length") } votedKeys := make([]bls.PublicKey, 0, len(committeeKeys)) activeBalance, err := helpers.TotalActiveBalance(s) if err != nil { - return nil, nil, err + return nil, nil, 0, err } proposerReward, participantReward, err := SyncRewards(activeBalance) if err != nil { - return nil, nil, err + return nil, nil, 0, err } proposerIndex, err := helpers.BeaconProposerIndex(ctx, s) if err != nil { - return nil, nil, err + return nil, nil, 0, err } earnedProposerReward := uint64(0) @@ -94,29 +96,29 @@ func processSyncAggregate(ctx context.Context, s state.BeaconState, sync *ethpb. vIdx, exists := s.ValidatorIndexByPubkey(bytesutil.ToBytes48(committeeKeys[i])) // Impossible scenario. if !exists { - return nil, nil, errors.New("validator public key does not exist in state") + return nil, nil, 0, errors.New("validator public key does not exist in state") } if sync.SyncCommitteeBits.BitAt(i) { pubKey, err := bls.PublicKeyFromBytes(committeeKeys[i]) if err != nil { - return nil, nil, err + return nil, nil, 0, err } votedKeys = append(votedKeys, pubKey) if err := helpers.IncreaseBalance(s, vIdx, participantReward); err != nil { - return nil, nil, err + return nil, nil, 0, err } earnedProposerReward += proposerReward } else { if err := helpers.DecreaseBalance(s, vIdx, participantReward); err != nil { - return nil, nil, err + return nil, nil, 0, err } } } if err := helpers.IncreaseBalance(s, proposerIndex, earnedProposerReward); err != nil { - return nil, nil, err + return nil, nil, 0, err } - return s, votedKeys, err + return s, votedKeys, proposerReward, err } // VerifySyncCommitteeSig verifies sync committee signature `syncSig` is valid with respect to public keys `syncKeys`. diff --git a/beacon-chain/core/transition/transition_no_verify_sig.go b/beacon-chain/core/transition/transition_no_verify_sig.go index 27f025e33df8..ed39e675b575 100644 --- a/beacon-chain/core/transition/transition_no_verify_sig.go +++ b/beacon-chain/core/transition/transition_no_verify_sig.go @@ -351,7 +351,7 @@ func ProcessBlockForStateRoot( if err != nil { return nil, errors.Wrap(err, "could not get sync aggregate from block") } - state, err = altair.ProcessSyncAggregate(ctx, state, sa) + state, _, err = altair.ProcessSyncAggregate(ctx, state, sa) if err != nil { return nil, errors.Wrap(err, "process_sync_aggregate failed") } diff --git a/beacon-chain/node/BUILD.bazel b/beacon-chain/node/BUILD.bazel index 21384c629978..00195f14f3e7 100644 --- a/beacon-chain/node/BUILD.bazel +++ b/beacon-chain/node/BUILD.bazel @@ -61,6 +61,7 @@ go_library( "//runtime/prereqs:go_default_library", "//runtime/version:go_default_library", "@com_github_ethereum_go_ethereum//common:go_default_library", + "@com_github_gorilla_mux//:go_default_library", "@com_github_pkg_errors//:go_default_library", "@com_github_prometheus_client_golang//prometheus:go_default_library", "@com_github_prysmaticlabs_fastssz//:go_default_library", diff --git a/beacon-chain/node/node.go b/beacon-chain/node/node.go index d58c931c87b3..e788e5d78e2a 100644 --- a/beacon-chain/node/node.go +++ b/beacon-chain/node/node.go @@ -16,6 +16,7 @@ import ( "syscall" "github.com/ethereum/go-ethereum/common" + "github.com/gorilla/mux" "github.com/pkg/errors" apigateway "github.com/prysmaticlabs/prysm/v3/api/gateway" "github.com/prysmaticlabs/prysm/v3/async/event" @@ -257,12 +258,13 @@ func New(cliCtx *cli.Context, opts ...Option) (*BeaconNode, error) { } log.Debugln("Registering RPC Service") - if err := beacon.registerRPCService(); err != nil { + router := mux.NewRouter() + if err := beacon.registerRPCService(router); err != nil { return nil, err } log.Debugln("Registering GRPC Gateway Service") - if err := beacon.registerGRPCGateway(); err != nil { + if err := beacon.registerGRPCGateway(router); err != nil { return nil, err } @@ -738,7 +740,7 @@ func (b *BeaconNode) registerSlasherService() error { return b.services.RegisterService(slasherSrv) } -func (b *BeaconNode) registerRPCService() error { +func (b *BeaconNode) registerRPCService(router *mux.Router) error { var chainService *blockchain.Service if err := b.services.FetchService(&chainService); err != nil { return err @@ -793,6 +795,7 @@ func (b *BeaconNode) registerRPCService() error { p2pService := b.fetchP2P() rpcService := rpc.NewService(b.ctx, &rpc.Config{ + Router: router, ExecutionEngineCaller: web3Service, ExecutionPayloadReconstructor: web3Service, Host: host, @@ -866,7 +869,7 @@ func (b *BeaconNode) registerPrometheusService(_ *cli.Context) error { return b.services.RegisterService(service) } -func (b *BeaconNode) registerGRPCGateway() error { +func (b *BeaconNode) registerGRPCGateway(router *mux.Router) error { if b.cliCtx.Bool(flags.DisableGRPCGateway.Name) { return nil } @@ -907,7 +910,7 @@ func (b *BeaconNode) registerGRPCGateway() error { if flags.EnableHTTPEthAPI(httpModules) { opts = append(opts, apigateway.WithApiMiddleware(&apimiddleware.BeaconEndpointFactory{})) } - g, err := apigateway.New(b.ctx, opts...) + g, err := apigateway.New(b.ctx, router, opts...) if err != nil { return err } diff --git a/beacon-chain/rpc/BUILD.bazel b/beacon-chain/rpc/BUILD.bazel index a2a8d13ca725..e3b6086ab22a 100644 --- a/beacon-chain/rpc/BUILD.bazel +++ b/beacon-chain/rpc/BUILD.bazel @@ -29,6 +29,7 @@ go_library( "//beacon-chain/rpc/eth/debug:go_default_library", "//beacon-chain/rpc/eth/events:go_default_library", "//beacon-chain/rpc/eth/node:go_default_library", + "//beacon-chain/rpc/eth/rewards:go_default_library", "//beacon-chain/rpc/eth/validator:go_default_library", "//beacon-chain/rpc/prysm/v1alpha1/beacon:go_default_library", "//beacon-chain/rpc/prysm/v1alpha1/debug:go_default_library", @@ -44,6 +45,7 @@ go_library( "//monitoring/tracing:go_default_library", "//proto/eth/service:go_default_library", "//proto/prysm/v1alpha1:go_default_library", + "@com_github_gorilla_mux//:go_default_library", "@com_github_grpc_ecosystem_go_grpc_middleware//:go_default_library", "@com_github_grpc_ecosystem_go_grpc_middleware//recovery:go_default_library", "@com_github_grpc_ecosystem_go_grpc_middleware//tracing/opentracing:go_default_library", diff --git a/beacon-chain/rpc/eth/helpers/BUILD.bazel b/beacon-chain/rpc/eth/helpers/BUILD.bazel index aae2dfa73a19..703da2c4c8b0 100644 --- a/beacon-chain/rpc/eth/helpers/BUILD.bazel +++ b/beacon-chain/rpc/eth/helpers/BUILD.bazel @@ -4,6 +4,7 @@ go_library( name = "go_default_library", srcs = [ "error_handling.go", + "http.go", "sync.go", "validator_status.go", ], @@ -20,6 +21,7 @@ go_library( "//consensus-types/primitives:go_default_library", "//proto/eth/v1:go_default_library", "@com_github_pkg_errors//:go_default_library", + "@com_github_sirupsen_logrus//:go_default_library", "@org_golang_google_grpc//codes:go_default_library", "@org_golang_google_grpc//status:go_default_library", ], diff --git a/beacon-chain/rpc/eth/helpers/error_handling.go b/beacon-chain/rpc/eth/helpers/error_handling.go index 0e4028476e15..9915d3c94d3d 100644 --- a/beacon-chain/rpc/eth/helpers/error_handling.go +++ b/beacon-chain/rpc/eth/helpers/error_handling.go @@ -2,7 +2,6 @@ package helpers import ( "errors" - "net/http" "github.com/prysmaticlabs/prysm/v3/beacon-chain/rpc/statefetcher" "github.com/prysmaticlabs/prysm/v3/beacon-chain/state/stategen" @@ -35,14 +34,3 @@ type SingleIndexedVerificationFailure struct { Index int `json:"index"` Message string `json:"message"` } - -// DefaultErrorJson is a JSON representation of a simple error value, containing only a message and an error code. -type DefaultErrorJson struct { - Message string `json:"message"` - Code int `json:"code"` -} - -// WriteError writes the error by manipulating headers and the body of the final response. -func WriteError(w http.ResponseWriter, errJson *DefaultErrorJson) { - -} diff --git a/beacon-chain/rpc/eth/helpers/http.go b/beacon-chain/rpc/eth/helpers/http.go new file mode 100644 index 000000000000..cf5adb0e025e --- /dev/null +++ b/beacon-chain/rpc/eth/helpers/http.go @@ -0,0 +1,41 @@ +package helpers + +import ( + "bytes" + "encoding/json" + "io" + "net/http" + "strconv" + + log "github.com/sirupsen/logrus" +) + +// DefaultErrorJson is a JSON representation of a simple error value, containing only a message and an error code. +type DefaultErrorJson struct { + Message string `json:"message"` + Code int `json:"code"` +} + +// WriteJson writes the response message in JSON format. +func WriteJson(w http.ResponseWriter, v any) { + w.Header().Set("Content-Type", "application/json") + w.WriteHeader(http.StatusOK) + if err := json.NewEncoder(w).Encode(v); err != nil { + log.WithError(err).Error("Could not write response message") + } +} + +// WriteError writes the error by manipulating headers and the body of the final response. +func WriteError(w http.ResponseWriter, errJson *DefaultErrorJson) { + j, err := json.Marshal(errJson) + if err != nil { + log.WithError(err).Error("Could not marshal error message") + return + } + w.Header().Set("Content-Length", strconv.Itoa(len(j))) + w.Header().Set("Content-Type", "application/json") + w.WriteHeader(errJson.Code) + if _, err := io.Copy(w, io.NopCloser(bytes.NewReader(j))); err != nil { + log.WithError(err).Error("Could not write error message") + } +} diff --git a/beacon-chain/rpc/eth/rewards/BUILD.bazel b/beacon-chain/rpc/eth/rewards/BUILD.bazel index ca2ab6b74a8b..ed635b3da33c 100644 --- a/beacon-chain/rpc/eth/rewards/BUILD.bazel +++ b/beacon-chain/rpc/eth/rewards/BUILD.bazel @@ -10,13 +10,17 @@ go_library( importpath = "github.com/prysmaticlabs/prysm/v3/beacon-chain/rpc/eth/rewards", visibility = ["//visibility:public"], deps = [ + "//beacon-chain/blockchain:go_default_library", "//beacon-chain/core/altair:go_default_library", + "//beacon-chain/core/blocks:go_default_library", + "//beacon-chain/core/validators:go_default_library", "//beacon-chain/rpc/blockfetcher:go_default_library", "//beacon-chain/rpc/eth/helpers:go_default_library", "//beacon-chain/rpc/statefetcher:go_default_library", "//consensus-types/blocks:go_default_library", "//consensus-types/interfaces:go_default_library", "//consensus-types/primitives:go_default_library", + "//runtime/version:go_default_library", "@com_github_pkg_errors//:go_default_library", ], ) diff --git a/beacon-chain/rpc/eth/rewards/handlers.go b/beacon-chain/rpc/eth/rewards/handlers.go index 149465adf94e..75b9cb765fc3 100644 --- a/beacon-chain/rpc/eth/rewards/handlers.go +++ b/beacon-chain/rpc/eth/rewards/handlers.go @@ -1,62 +1,170 @@ package rewards import ( - "encoding/json" - "io" "net/http" + "strings" "github.com/pkg/errors" "github.com/prysmaticlabs/prysm/v3/beacon-chain/core/altair" + blocks2 "github.com/prysmaticlabs/prysm/v3/beacon-chain/core/blocks" + "github.com/prysmaticlabs/prysm/v3/beacon-chain/core/validators" "github.com/prysmaticlabs/prysm/v3/beacon-chain/rpc/blockfetcher" "github.com/prysmaticlabs/prysm/v3/beacon-chain/rpc/eth/helpers" "github.com/prysmaticlabs/prysm/v3/consensus-types/blocks" "github.com/prysmaticlabs/prysm/v3/consensus-types/interfaces" + "github.com/prysmaticlabs/prysm/v3/runtime/version" ) +// BlockRewards is an HTTP handler for Beacon API getBlockRewards. func (s *Server) BlockRewards(w http.ResponseWriter, r *http.Request) { - body, err := io.ReadAll(r.Body) + segments := strings.Split(r.URL.Path, "/") + blockId := segments[len(segments)-1] + + blk, err := s.BlockFetcher.Block(r.Context(), []byte(blockId)) + if errJson := handleGetBlockError(blk, err); errJson != nil { + helpers.WriteError(w, errJson) + return + } + if blk.Version() == version.Phase0 { + errJson := &helpers.DefaultErrorJson{ + Message: errors.Wrapf(err, "block rewards are not supported for Phase 0 blocks").Error(), + Code: http.StatusBadRequest, + } + helpers.WriteError(w, errJson) + return + } + stateRoot := blk.Block().StateRoot() + st, err := s.StateFetcher.State(r.Context(), stateRoot[:]) if err != nil { errJson := &helpers.DefaultErrorJson{ - Message: errors.Wrapf(err, "could not read request body").Error(), + Message: errors.Wrapf(err, "could not get state").Error(), Code: http.StatusInternalServerError, } helpers.WriteError(w, errJson) return } - rewardsRequest := &BlockRewardsRequest{} - if err := json.Unmarshal(body, rewardsRequest); err != nil { + + proposerIndex := blk.Block().ProposerIndex() + oldBalance, err := st.BalanceAtIndex(proposerIndex) + if err != nil { errJson := &helpers.DefaultErrorJson{ - Message: errors.Wrapf(err, "could not unmarshal request body").Error(), + Message: errors.Wrapf(err, "could not get proposer's balance").Error(), Code: http.StatusInternalServerError, } helpers.WriteError(w, errJson) return } - blk, err := s.BlockFetcher.Block(r.Context(), []byte(rewardsRequest.BlockId)) - if errJson := handleGetBlockError(blk, err); errJson != nil { + st, err = altair.ProcessAttestationsNoVerifySignature(r.Context(), st, blk) + if err != nil { + errJson := &helpers.DefaultErrorJson{ + Message: errors.Wrapf(err, "could not get attestation rewards").Error(), + Code: http.StatusInternalServerError, + } helpers.WriteError(w, errJson) return } - stateRoot := blk.Block().StateRoot() - st, err := s.StateFetcher.State(r.Context(), stateRoot[:]) + newBalance, err := st.BalanceAtIndex(proposerIndex) if err != nil { errJson := &helpers.DefaultErrorJson{ - Message: errors.Wrapf(err, "could not get state").Error(), + Message: errors.Wrapf(err, "could not get proposer's balance").Error(), + Code: http.StatusInternalServerError, + } + helpers.WriteError(w, errJson) + return + } + attsReward := newBalance - oldBalance + oldBalance = newBalance + st, err = blocks2.ProcessAttesterSlashings(r.Context(), st, blk.Block().Body().AttesterSlashings(), validators.SlashValidator) + if err != nil { + errJson := &helpers.DefaultErrorJson{ + Message: errors.Wrapf(err, "could not get attester slashing rewards").Error(), + Code: http.StatusInternalServerError, + } + helpers.WriteError(w, errJson) + return + } + newBalance, err = st.BalanceAtIndex(proposerIndex) + if err != nil { + errJson := &helpers.DefaultErrorJson{ + Message: errors.Wrapf(err, "could not get proposer's balance").Error(), Code: http.StatusInternalServerError, } helpers.WriteError(w, errJson) return } - vals, bal, err := altair.InitializePrecomputeValidators(r.Context(), st) + attSlashingsReward := newBalance - oldBalance + oldBalance = newBalance + st, err = blocks2.ProcessProposerSlashings(r.Context(), st, blk.Block().Body().ProposerSlashings(), validators.SlashValidator) if err != nil { errJson := &helpers.DefaultErrorJson{ - Message: errors.Wrapf(err, "could not initialize precompute validators").Error(), + Message: errors.Wrapf(err, "could not get proposer slashing rewards").Error(), + Code: http.StatusInternalServerError, + } + helpers.WriteError(w, errJson) + return + } + newBalance, err = st.BalanceAtIndex(proposerIndex) + if err != nil { + errJson := &helpers.DefaultErrorJson{ + Message: errors.Wrapf(err, "could not get proposer's balance").Error(), + Code: http.StatusInternalServerError, + } + helpers.WriteError(w, errJson) + return + } + proposerSlashingsReward := newBalance - oldBalance + sa, err := blk.Block().Body().SyncAggregate() + if err != nil { + errJson := &helpers.DefaultErrorJson{ + Message: errors.Wrapf(err, "could not get sync aggregate").Error(), + Code: http.StatusInternalServerError, + } + helpers.WriteError(w, errJson) + return + } + var syncCommitteeReward uint64 + st, syncCommitteeReward, err = altair.ProcessSyncAggregate(r.Context(), st, sa) + if err != nil { + errJson := &helpers.DefaultErrorJson{ + Message: errors.Wrapf(err, "could not get sync aggregate rewards").Error(), + Code: http.StatusInternalServerError, + } + helpers.WriteError(w, errJson) + return + } + + optimistic, err := s.OptimisticModeFetcher.IsOptimistic(r.Context()) + if err != nil { + errJson := &helpers.DefaultErrorJson{ + Message: errors.Wrapf(err, "could not get optimistic mode info").Error(), + Code: http.StatusInternalServerError, + } + helpers.WriteError(w, errJson) + return + } + blkRoot, err := blk.Block().HashTreeRoot() + if err != nil { + errJson := &helpers.DefaultErrorJson{ + Message: errors.Wrapf(err, "could not get block root").Error(), Code: http.StatusInternalServerError, } helpers.WriteError(w, errJson) return } + response := &BlockRewardsResponse{ + Data: &BlockRewards{ + ProposerIndex: proposerIndex, + Total: attsReward + proposerSlashingsReward + attSlashingsReward + syncCommitteeReward, + Attestations: attsReward, + SyncAggregate: syncCommitteeReward, + ProposerSlashings: proposerSlashingsReward, + AttesterSlashings: attSlashingsReward, + }, + ExecutionOptimistic: optimistic, + Finalized: s.FinalizationFetcher.IsFinalized(r.Context(), blkRoot), + } + helpers.WriteJson(w, response) } func handleGetBlockError(blk interfaces.SignedBeaconBlock, err error) *helpers.DefaultErrorJson { diff --git a/beacon-chain/rpc/eth/rewards/server.go b/beacon-chain/rpc/eth/rewards/server.go index a478461fb322..1dbd2568baa8 100644 --- a/beacon-chain/rpc/eth/rewards/server.go +++ b/beacon-chain/rpc/eth/rewards/server.go @@ -1,11 +1,14 @@ package rewards import ( + "github.com/prysmaticlabs/prysm/v3/beacon-chain/blockchain" "github.com/prysmaticlabs/prysm/v3/beacon-chain/rpc/blockfetcher" "github.com/prysmaticlabs/prysm/v3/beacon-chain/rpc/statefetcher" ) type Server struct { - BlockFetcher blockfetcher.Fetcher - StateFetcher statefetcher.Fetcher + BlockFetcher blockfetcher.Fetcher + StateFetcher statefetcher.Fetcher + OptimisticModeFetcher blockchain.OptimisticModeFetcher + FinalizationFetcher blockchain.FinalizationFetcher } diff --git a/beacon-chain/rpc/eth/rewards/structs.go b/beacon-chain/rpc/eth/rewards/structs.go index 0db75f784f4c..817b35b67baf 100644 --- a/beacon-chain/rpc/eth/rewards/structs.go +++ b/beacon-chain/rpc/eth/rewards/structs.go @@ -8,10 +8,6 @@ import ( types "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" ) -type BlockRewardsRequest struct { - BlockId string `json:"block_id"` -} - type BlockRewardsResponse struct { Data *BlockRewards `json:"data"` ExecutionOptimistic bool `json:"execution_optimistic"` diff --git a/beacon-chain/rpc/service.go b/beacon-chain/rpc/service.go index 1293abb2c396..e77711e66462 100644 --- a/beacon-chain/rpc/service.go +++ b/beacon-chain/rpc/service.go @@ -8,6 +8,7 @@ import ( "net" "sync" + "github.com/gorilla/mux" middleware "github.com/grpc-ecosystem/go-grpc-middleware" recovery "github.com/grpc-ecosystem/go-grpc-middleware/recovery" grpcopentracing "github.com/grpc-ecosystem/go-grpc-middleware/tracing/opentracing" @@ -33,6 +34,7 @@ import ( "github.com/prysmaticlabs/prysm/v3/beacon-chain/rpc/eth/debug" "github.com/prysmaticlabs/prysm/v3/beacon-chain/rpc/eth/events" "github.com/prysmaticlabs/prysm/v3/beacon-chain/rpc/eth/node" + "github.com/prysmaticlabs/prysm/v3/beacon-chain/rpc/eth/rewards" "github.com/prysmaticlabs/prysm/v3/beacon-chain/rpc/eth/validator" beaconv1alpha1 "github.com/prysmaticlabs/prysm/v3/beacon-chain/rpc/prysm/v1alpha1/beacon" debugv1alpha1 "github.com/prysmaticlabs/prysm/v3/beacon-chain/rpc/prysm/v1alpha1/debug" @@ -73,7 +75,7 @@ type Service struct { // Config options for the beacon node RPC server. type Config struct { - ExecutionPayloadReconstructor execution.ExecutionPayloadReconstructor + Router *mux.Router Host string Port string CertFlag string @@ -118,6 +120,7 @@ type Config struct { ProposerIdsCache *cache.ProposerPayloadIDsCache OptimisticModeFetcher blockchain.OptimisticModeFetcher BlockBuilder builder.BlockBuilder + ExecutionPayloadReconstructor execution.ExecutionPayloadReconstructor } // NewService instantiates a new RPC service instance that will @@ -191,6 +194,8 @@ func (s *Service) Start() { withCache := stategen.WithCache(stateCache) ch := stategen.NewCanonicalHistory(s.cfg.BeaconDB, s.cfg.ChainInfoFetcher, s.cfg.ChainInfoFetcher, withCache) + s.registerHTTPHandlers(ch) + validatorServer := &validatorv1alpha1.Server{ Ctx: s.ctx, AttestationCache: cache.NewAttestationCache(), @@ -450,3 +455,22 @@ func (s *Service) logNewClientConnection(ctx context.Context) { } } } + +func (s *Service) registerHTTPHandlers(ch *stategen.CanonicalHistory) { + rewardsServer := &rewards.Server{ + BlockFetcher: &blockfetcher.BlockProvider{ + BeaconDB: s.cfg.BeaconDB, + ChainInfoFetcher: s.cfg.ChainInfoFetcher, + }, + StateFetcher: &statefetcher.StateProvider{ + BeaconDB: s.cfg.BeaconDB, + ChainInfoFetcher: s.cfg.ChainInfoFetcher, + GenesisTimeFetcher: s.cfg.GenesisTimeFetcher, + StateGenService: s.cfg.StateGen, + ReplayerBuilder: ch, + }, + OptimisticModeFetcher: s.cfg.OptimisticModeFetcher, + FinalizationFetcher: s.cfg.FinalizationFetcher, + } + s.cfg.Router.HandleFunc("/eth/v1/beacon/rewards/blocks/{block_id}", rewardsServer.BlockRewards) +} diff --git a/beacon-chain/server/main.go b/beacon-chain/server/main.go index 8dab3d63432b..5b288713efa2 100644 --- a/beacon-chain/server/main.go +++ b/beacon-chain/server/main.go @@ -65,12 +65,13 @@ func main() { opts = append(opts, gateway.WithApiMiddleware(&apimiddleware.BeaconEndpointFactory{})) } - gw, err := gateway.New(context.Background(), opts...) + r := mux.NewRouter() + + gw, err := gateway.New(context.Background(), r, opts...) if err != nil { log.Fatal(err) } - r := mux.NewRouter() r.HandleFunc("/swagger/", gateway.SwaggerServer()) r.HandleFunc("/healthz", healthzServer(gw)) gw.SetRouter(r) diff --git a/testing/spectest/shared/altair/operations/sync_committee.go b/testing/spectest/shared/altair/operations/sync_committee.go index 03e80c8961ec..1f39a14acca7 100644 --- a/testing/spectest/shared/altair/operations/sync_committee.go +++ b/testing/spectest/shared/altair/operations/sync_committee.go @@ -33,7 +33,11 @@ func RunSyncCommitteeTest(t *testing.T, config string) { body := ðpb.BeaconBlockBodyAltair{SyncAggregate: sc} RunBlockOperationTest(t, folderPath, body, func(ctx context.Context, s state.BeaconState, b interfaces.SignedBeaconBlock) (state.BeaconState, error) { - return altair.ProcessSyncAggregate(context.Background(), s, body.SyncAggregate) + st, _, err := altair.ProcessSyncAggregate(context.Background(), s, body.SyncAggregate) + if err != nil { + return nil, err + } + return st, nil }) }) } diff --git a/testing/spectest/shared/bellatrix/operations/sync_committee.go b/testing/spectest/shared/bellatrix/operations/sync_committee.go index bc2c25ebde29..1e78f90ee836 100644 --- a/testing/spectest/shared/bellatrix/operations/sync_committee.go +++ b/testing/spectest/shared/bellatrix/operations/sync_committee.go @@ -33,7 +33,11 @@ func RunSyncCommitteeTest(t *testing.T, config string) { body := ðpb.BeaconBlockBodyBellatrix{SyncAggregate: sc} RunBlockOperationTest(t, folderPath, body, func(ctx context.Context, s state.BeaconState, b interfaces.SignedBeaconBlock) (state.BeaconState, error) { - return altair.ProcessSyncAggregate(context.Background(), s, body.SyncAggregate) + st, _, err := altair.ProcessSyncAggregate(context.Background(), s, body.SyncAggregate) + if err != nil { + return nil, err + } + return st, nil }) }) } diff --git a/testing/spectest/shared/capella/operations/sync_committee.go b/testing/spectest/shared/capella/operations/sync_committee.go index a815c9a9beec..3cdc1caba7f4 100644 --- a/testing/spectest/shared/capella/operations/sync_committee.go +++ b/testing/spectest/shared/capella/operations/sync_committee.go @@ -33,7 +33,11 @@ func RunSyncCommitteeTest(t *testing.T, config string) { body := ðpb.BeaconBlockBodyCapella{SyncAggregate: sc} RunBlockOperationTest(t, folderPath, body, func(ctx context.Context, s state.BeaconState, b interfaces.SignedBeaconBlock) (state.BeaconState, error) { - return altair.ProcessSyncAggregate(context.Background(), s, body.SyncAggregate) + st, _, err := altair.ProcessSyncAggregate(context.Background(), s, body.SyncAggregate) + if err != nil { + return nil, err + } + return st, nil }) }) } diff --git a/validator/node/BUILD.bazel b/validator/node/BUILD.bazel index 6937a7009bf0..9f68463aa8e6 100644 --- a/validator/node/BUILD.bazel +++ b/validator/node/BUILD.bazel @@ -69,6 +69,7 @@ go_library( "//validator/web:go_default_library", "@com_github_ethereum_go_ethereum//common:go_default_library", "@com_github_ethereum_go_ethereum//common/hexutil:go_default_library", + "@com_github_gorilla_mux//:go_default_library", "@com_github_grpc_ecosystem_grpc_gateway_v2//runtime:go_default_library", "@com_github_pkg_errors//:go_default_library", "@com_github_prysmaticlabs_fastssz//:go_default_library", diff --git a/validator/node/node.go b/validator/node/node.go index effb4a8741bd..34e1dd3aff80 100644 --- a/validator/node/node.go +++ b/validator/node/node.go @@ -22,6 +22,7 @@ import ( "github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/common/hexutil" + "github.com/gorilla/mux" gwruntime "github.com/grpc-ecosystem/grpc-gateway/v2/runtime" "github.com/pkg/errors" fastssz "github.com/prysmaticlabs/fastssz" @@ -766,7 +767,7 @@ func (c *ValidatorClient) registerRPCGatewayService(cliCtx *cli.Context) error { gateway.WithMuxHandler(muxHandler), gateway.WithTimeout(uint64(timeout)), } - gw, err := gateway.New(cliCtx.Context, opts...) + gw, err := gateway.New(cliCtx.Context, mux.NewRouter(), opts...) if err != nil { return err } From e645ceaa28e1a1a584cbd1eda9818f9448dd200c Mon Sep 17 00:00:00 2001 From: rkapka Date: Mon, 20 Feb 2023 19:46:24 +0100 Subject: [PATCH 04/40] remove file --- beacon-chain/core/blocks/BUILD.bazel | 1 - beacon-chain/core/blocks/rewards.go | 37 ---------------------------- 2 files changed, 38 deletions(-) delete mode 100644 beacon-chain/core/blocks/rewards.go diff --git a/beacon-chain/core/blocks/BUILD.bazel b/beacon-chain/core/blocks/BUILD.bazel index 2e2eaf2ace63..38c2cde22a11 100644 --- a/beacon-chain/core/blocks/BUILD.bazel +++ b/beacon-chain/core/blocks/BUILD.bazel @@ -15,7 +15,6 @@ go_library( "payload.go", "proposer_slashing.go", "randao.go", - "rewards.go", "signature.go", "withdrawals.go", ], diff --git a/beacon-chain/core/blocks/rewards.go b/beacon-chain/core/blocks/rewards.go deleted file mode 100644 index c8c88cf28f0d..000000000000 --- a/beacon-chain/core/blocks/rewards.go +++ /dev/null @@ -1,37 +0,0 @@ -package blocks - -import ( - "github.com/pkg/errors" - "github.com/prysmaticlabs/prysm/v3/beacon-chain/state" - "github.com/prysmaticlabs/prysm/v3/config/params" - "github.com/prysmaticlabs/prysm/v3/consensus-types/interfaces" - "github.com/prysmaticlabs/prysm/v3/math" -) - -type validatorInfo struct { - isPrevEpochAttester bool - isSlashed bool -} - -func AttestationRewards(st state.ReadOnlyBeaconState, b interfaces.BeaconBlockBody) (uint64, error) { - currEpochActiveBalance := uint64(0) - if err := st.ReadFromEveryValidator(func(idx int, val state.ReadOnlyValidator) error { - currEpochActiveBalance += val.EffectiveBalance() - return nil - }); err != nil { - return 0, errors.Wrap(err, "failed to read validator data") - } - balanceSqrt := math.IntegerSquareRoot(currEpochActiveBalance) - // Balance square root cannot be 0, this prevents division by 0. - if balanceSqrt == 0 { - balanceSqrt = 1 - } - - baseRewardFactor := params.BeaconConfig().BaseRewardFactor - baseRewardsPerEpoch := params.BeaconConfig().BaseRewardsPerEpoch - proposerRewardQuotient := params.BeaconConfig().ProposerRewardQuotient - baseReward := currEpochActiveBalance * baseRewardFactor / balanceSqrt / baseRewardsPerEpoch - proposerReward := baseReward / proposerRewardQuotient - - return proposerReward * uint64(len(b.Attestations())), nil -} From 3d4d38083d3760c4d4fad6e4676c6622156c1a56 Mon Sep 17 00:00:00 2001 From: rkapka Date: Mon, 20 Feb 2023 19:47:57 +0100 Subject: [PATCH 05/40] revert precompute changes --- beacon-chain/core/epoch/precompute/new.go | 2 +- beacon-chain/core/epoch/precompute/reward_penalty.go | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/beacon-chain/core/epoch/precompute/new.go b/beacon-chain/core/epoch/precompute/new.go index 0446f1892412..bf3907f11355 100644 --- a/beacon-chain/core/epoch/precompute/new.go +++ b/beacon-chain/core/epoch/precompute/new.go @@ -17,7 +17,7 @@ import ( // New gets called at the beginning of process epoch cycle to return // pre computed instances of validators attesting records and total // balances attested in an epoch. -func New(ctx context.Context, s state.ReadOnlyBeaconState) ([]*Validator, *Balance, error) { +func New(ctx context.Context, s state.BeaconState) ([]*Validator, *Balance, error) { ctx, span := trace.StartSpan(ctx, "precomputeEpoch.New") defer span.End() diff --git a/beacon-chain/core/epoch/precompute/reward_penalty.go b/beacon-chain/core/epoch/precompute/reward_penalty.go index e240d1170ef2..68d7a3b5d09e 100644 --- a/beacon-chain/core/epoch/precompute/reward_penalty.go +++ b/beacon-chain/core/epoch/precompute/reward_penalty.go @@ -175,7 +175,7 @@ func ProposersDelta(state state.ReadOnlyBeaconState, pBal *Balance, vp []*Valida // This should never happen with a valid state / validator. return nil, errors.New("proposer index out of range") } - // Only apply inclusion rewards to proposer only if the attester hasn't been slashed. + // Only apply inclusion rewards to proposer only if the attested hasn't been slashed. if v.IsPrevEpochAttester && !v.IsSlashed { vBalance := v.CurrentEpochEffectiveBalance baseReward := vBalance * baseRewardFactor / balanceSqrt / baseRewardsPerEpoch From 41c5886235e759e82e2d020fd85372f7c61be2a3 Mon Sep 17 00:00:00 2001 From: rkapka Date: Tue, 21 Feb 2023 15:23:41 +0100 Subject: [PATCH 06/40] use replayer --- beacon-chain/rpc/blockfetcher/fetcher.go | 6 +++--- beacon-chain/rpc/eth/rewards/BUILD.bazel | 1 + beacon-chain/rpc/eth/rewards/handlers.go | 5 ++--- beacon-chain/rpc/eth/rewards/server.go | 2 ++ beacon-chain/rpc/service.go | 1 + 5 files changed, 9 insertions(+), 6 deletions(-) diff --git a/beacon-chain/rpc/blockfetcher/fetcher.go b/beacon-chain/rpc/blockfetcher/fetcher.go index 037dcd4fedca..17b436c74e15 100644 --- a/beacon-chain/rpc/blockfetcher/fetcher.go +++ b/beacon-chain/rpc/blockfetcher/fetcher.go @@ -31,7 +31,7 @@ func (e BlockIdParseError) Error() string { // Fetcher is responsible for retrieving info related with the beacon block. type Fetcher interface { - Block(ctx context.Context, blockId []byte) (interfaces.SignedBeaconBlock, error) + Block(ctx context.Context, blockId []byte) (interfaces.ReadOnlySignedBeaconBlock, error) } // BlockProvider is a real implementation of Fetcher. @@ -40,9 +40,9 @@ type BlockProvider struct { ChainInfoFetcher blockchain.ChainInfoFetcher } -func (p *BlockProvider) Block(ctx context.Context, blockId []byte) (interfaces.SignedBeaconBlock, error) { +func (p *BlockProvider) Block(ctx context.Context, blockId []byte) (interfaces.ReadOnlySignedBeaconBlock, error) { var err error - var blk interfaces.SignedBeaconBlock + var blk interfaces.ReadOnlySignedBeaconBlock switch string(blockId) { case "head": blk, err = p.ChainInfoFetcher.HeadBlock(ctx) diff --git a/beacon-chain/rpc/eth/rewards/BUILD.bazel b/beacon-chain/rpc/eth/rewards/BUILD.bazel index ed635b3da33c..09b4847f7c18 100644 --- a/beacon-chain/rpc/eth/rewards/BUILD.bazel +++ b/beacon-chain/rpc/eth/rewards/BUILD.bazel @@ -17,6 +17,7 @@ go_library( "//beacon-chain/rpc/blockfetcher:go_default_library", "//beacon-chain/rpc/eth/helpers:go_default_library", "//beacon-chain/rpc/statefetcher:go_default_library", + "//beacon-chain/state/stategen:go_default_library", "//consensus-types/blocks:go_default_library", "//consensus-types/interfaces:go_default_library", "//consensus-types/primitives:go_default_library", diff --git a/beacon-chain/rpc/eth/rewards/handlers.go b/beacon-chain/rpc/eth/rewards/handlers.go index 75b9cb765fc3..e97bd2c9cb5e 100644 --- a/beacon-chain/rpc/eth/rewards/handlers.go +++ b/beacon-chain/rpc/eth/rewards/handlers.go @@ -33,8 +33,7 @@ func (s *Server) BlockRewards(w http.ResponseWriter, r *http.Request) { helpers.WriteError(w, errJson) return } - stateRoot := blk.Block().StateRoot() - st, err := s.StateFetcher.State(r.Context(), stateRoot[:]) + st, err := s.CanonicalHistory.ReplayerForSlot(blk.Block().Slot()-1).ReplayToSlot(r.Context(), blk.Block().Slot()) if err != nil { errJson := &helpers.DefaultErrorJson{ Message: errors.Wrapf(err, "could not get state").Error(), @@ -167,7 +166,7 @@ func (s *Server) BlockRewards(w http.ResponseWriter, r *http.Request) { helpers.WriteJson(w, response) } -func handleGetBlockError(blk interfaces.SignedBeaconBlock, err error) *helpers.DefaultErrorJson { +func handleGetBlockError(blk interfaces.ReadOnlySignedBeaconBlock, err error) *helpers.DefaultErrorJson { if errors.Is(err, blockfetcher.BlockIdParseError{}) { return &helpers.DefaultErrorJson{ Message: errors.Wrapf(err, "invalid block ID").Error(), diff --git a/beacon-chain/rpc/eth/rewards/server.go b/beacon-chain/rpc/eth/rewards/server.go index 1dbd2568baa8..cd255361bae8 100644 --- a/beacon-chain/rpc/eth/rewards/server.go +++ b/beacon-chain/rpc/eth/rewards/server.go @@ -4,6 +4,7 @@ import ( "github.com/prysmaticlabs/prysm/v3/beacon-chain/blockchain" "github.com/prysmaticlabs/prysm/v3/beacon-chain/rpc/blockfetcher" "github.com/prysmaticlabs/prysm/v3/beacon-chain/rpc/statefetcher" + "github.com/prysmaticlabs/prysm/v3/beacon-chain/state/stategen" ) type Server struct { @@ -11,4 +12,5 @@ type Server struct { StateFetcher statefetcher.Fetcher OptimisticModeFetcher blockchain.OptimisticModeFetcher FinalizationFetcher blockchain.FinalizationFetcher + CanonicalHistory *stategen.CanonicalHistory } diff --git a/beacon-chain/rpc/service.go b/beacon-chain/rpc/service.go index e77711e66462..00bc53801e38 100644 --- a/beacon-chain/rpc/service.go +++ b/beacon-chain/rpc/service.go @@ -471,6 +471,7 @@ func (s *Service) registerHTTPHandlers(ch *stategen.CanonicalHistory) { }, OptimisticModeFetcher: s.cfg.OptimisticModeFetcher, FinalizationFetcher: s.cfg.FinalizationFetcher, + CanonicalHistory: ch, } s.cfg.Router.HandleFunc("/eth/v1/beacon/rewards/blocks/{block_id}", rewardsServer.BlockRewards) } From 6279b59fb932ab0e8bdb9f5d1adaf17bf24433f3 Mon Sep 17 00:00:00 2001 From: rkapka Date: Tue, 21 Feb 2023 15:37:38 +0100 Subject: [PATCH 07/40] rename import --- beacon-chain/rpc/eth/rewards/handlers.go | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/beacon-chain/rpc/eth/rewards/handlers.go b/beacon-chain/rpc/eth/rewards/handlers.go index e97bd2c9cb5e..c7e5f4572e37 100644 --- a/beacon-chain/rpc/eth/rewards/handlers.go +++ b/beacon-chain/rpc/eth/rewards/handlers.go @@ -6,7 +6,7 @@ import ( "github.com/pkg/errors" "github.com/prysmaticlabs/prysm/v3/beacon-chain/core/altair" - blocks2 "github.com/prysmaticlabs/prysm/v3/beacon-chain/core/blocks" + coreblocks "github.com/prysmaticlabs/prysm/v3/beacon-chain/core/blocks" "github.com/prysmaticlabs/prysm/v3/beacon-chain/core/validators" "github.com/prysmaticlabs/prysm/v3/beacon-chain/rpc/blockfetcher" "github.com/prysmaticlabs/prysm/v3/beacon-chain/rpc/eth/helpers" @@ -73,7 +73,7 @@ func (s *Server) BlockRewards(w http.ResponseWriter, r *http.Request) { } attsReward := newBalance - oldBalance oldBalance = newBalance - st, err = blocks2.ProcessAttesterSlashings(r.Context(), st, blk.Block().Body().AttesterSlashings(), validators.SlashValidator) + st, err = coreblocks.ProcessAttesterSlashings(r.Context(), st, blk.Block().Body().AttesterSlashings(), validators.SlashValidator) if err != nil { errJson := &helpers.DefaultErrorJson{ Message: errors.Wrapf(err, "could not get attester slashing rewards").Error(), @@ -93,7 +93,7 @@ func (s *Server) BlockRewards(w http.ResponseWriter, r *http.Request) { } attSlashingsReward := newBalance - oldBalance oldBalance = newBalance - st, err = blocks2.ProcessProposerSlashings(r.Context(), st, blk.Block().Body().ProposerSlashings(), validators.SlashValidator) + st, err = coreblocks.ProcessProposerSlashings(r.Context(), st, blk.Block().Body().ProposerSlashings(), validators.SlashValidator) if err != nil { errJson := &helpers.DefaultErrorJson{ Message: errors.Wrapf(err, "could not get proposer slashing rewards").Error(), From f781ca55550829fa563dd1c1e1058cb14d8d5a34 Mon Sep 17 00:00:00 2001 From: rkapka Date: Tue, 21 Feb 2023 21:14:03 +0100 Subject: [PATCH 08/40] tests --- beacon-chain/core/altair/block_test.go | 10 +- beacon-chain/rpc/eth/beacon/BUILD.bazel | 1 - .../rpc/eth/beacon/blinded_blocks_test.go | 819 ++----- beacon-chain/rpc/eth/beacon/blocks_test.go | 2033 +++++------------ beacon-chain/rpc/testutil/BUILD.bazel | 2 + .../rpc/testutil/mock_block_fetcher.go | 16 + 6 files changed, 754 insertions(+), 2127 deletions(-) create mode 100644 beacon-chain/rpc/testutil/mock_block_fetcher.go diff --git a/beacon-chain/core/altair/block_test.go b/beacon-chain/core/altair/block_test.go index aa2992933313..d3e4210378ad 100644 --- a/beacon-chain/core/altair/block_test.go +++ b/beacon-chain/core/altair/block_test.go @@ -53,7 +53,7 @@ func TestProcessSyncCommittee_PerfectParticipation(t *testing.T) { SyncCommitteeSignature: aggregatedSig, } - beaconState, err = altair.ProcessSyncAggregate(context.Background(), beaconState, syncAggregate) + beaconState, _, err = altair.ProcessSyncAggregate(context.Background(), beaconState, syncAggregate) require.NoError(t, err) // Use a non-sync committee index to compare profitability. @@ -127,7 +127,7 @@ func TestProcessSyncCommittee_MixParticipation_BadSignature(t *testing.T) { SyncCommitteeSignature: aggregatedSig, } - _, err = altair.ProcessSyncAggregate(context.Background(), beaconState, syncAggregate) + _, _, err = altair.ProcessSyncAggregate(context.Background(), beaconState, syncAggregate) require.ErrorContains(t, "invalid sync committee signature", err) } @@ -164,7 +164,7 @@ func TestProcessSyncCommittee_MixParticipation_GoodSignature(t *testing.T) { SyncCommitteeSignature: aggregatedSig, } - _, err = altair.ProcessSyncAggregate(context.Background(), beaconState, syncAggregate) + _, _, err = altair.ProcessSyncAggregate(context.Background(), beaconState, syncAggregate) require.NoError(t, err) } @@ -189,7 +189,7 @@ func TestProcessSyncCommittee_DontPrecompute(t *testing.T) { SyncCommitteeBits: syncBits, } require.NoError(t, beaconState.UpdateBalancesAtIndex(idx, 0)) - st, votedKeys, err := altair.ProcessSyncAggregateEported(context.Background(), beaconState, syncAggregate) + st, votedKeys, _, err := altair.ProcessSyncAggregateEported(context.Background(), beaconState, syncAggregate) require.NoError(t, err) require.Equal(t, 511, len(votedKeys)) require.DeepEqual(t, committeeKeys[0], votedKeys[0].Marshal()) @@ -212,7 +212,7 @@ func TestProcessSyncCommittee_processSyncAggregate(t *testing.T) { SyncCommitteeBits: syncBits, } - st, votedKeys, err := altair.ProcessSyncAggregateEported(context.Background(), beaconState, syncAggregate) + st, votedKeys, _, err := altair.ProcessSyncAggregateEported(context.Background(), beaconState, syncAggregate) require.NoError(t, err) votedMap := make(map[[fieldparams.BLSPubkeyLength]byte]bool) for _, key := range votedKeys { diff --git a/beacon-chain/rpc/eth/beacon/BUILD.bazel b/beacon-chain/rpc/eth/beacon/BUILD.bazel index 51f946d07492..9721b9bf4177 100644 --- a/beacon-chain/rpc/eth/beacon/BUILD.bazel +++ b/beacon-chain/rpc/eth/beacon/BUILD.bazel @@ -93,7 +93,6 @@ go_test( "//beacon-chain/core/transition:go_default_library", "//beacon-chain/db:go_default_library", "//beacon-chain/db/testing:go_default_library", - "//beacon-chain/execution/testing:go_default_library", "//beacon-chain/operations/attestations:go_default_library", "//beacon-chain/operations/blstoexec:go_default_library", "//beacon-chain/operations/blstoexec/mock:go_default_library", diff --git a/beacon-chain/rpc/eth/beacon/blinded_blocks_test.go b/beacon-chain/rpc/eth/beacon/blinded_blocks_test.go index 6399dce7bf30..60c27d8d353b 100644 --- a/beacon-chain/rpc/eth/beacon/blinded_blocks_test.go +++ b/beacon-chain/rpc/eth/beacon/blinded_blocks_test.go @@ -2,17 +2,15 @@ package beacon import ( "context" - "fmt" - "reflect" "testing" mock "github.com/prysmaticlabs/prysm/v3/beacon-chain/blockchain/testing" builderTest "github.com/prysmaticlabs/prysm/v3/beacon-chain/builder/testing" dbTest "github.com/prysmaticlabs/prysm/v3/beacon-chain/db/testing" - executionTest "github.com/prysmaticlabs/prysm/v3/beacon-chain/execution/testing" "github.com/prysmaticlabs/prysm/v3/beacon-chain/operations/synccommittee" mockp2p "github.com/prysmaticlabs/prysm/v3/beacon-chain/p2p/testing" "github.com/prysmaticlabs/prysm/v3/beacon-chain/rpc/prysm/v1alpha1/validator" + "github.com/prysmaticlabs/prysm/v3/beacon-chain/rpc/testutil" "github.com/prysmaticlabs/prysm/v3/config/params" "github.com/prysmaticlabs/prysm/v3/consensus-types/blocks" "github.com/prysmaticlabs/prysm/v3/crypto/hash" @@ -22,7 +20,6 @@ import ( ethpbv1 "github.com/prysmaticlabs/prysm/v3/proto/eth/v1" ethpbv2 "github.com/prysmaticlabs/prysm/v3/proto/eth/v2" "github.com/prysmaticlabs/prysm/v3/proto/migration" - ethpbalpha "github.com/prysmaticlabs/prysm/v3/proto/prysm/v1alpha1" "github.com/prysmaticlabs/prysm/v3/testing/assert" "github.com/prysmaticlabs/prysm/v3/testing/require" "github.com/prysmaticlabs/prysm/v3/testing/util" @@ -30,770 +27,280 @@ import ( ) func TestServer_GetBlindedBlock(t *testing.T) { - t.Run("Phase 0", func(t *testing.T) { - beaconDB := dbTest.SetupDB(t) - ctx := context.Background() + ctx := context.Background() - genBlk, blkContainers := fillDBTestBlocks(ctx, t, beaconDB) - canonicalRoots := make(map[[32]byte]bool) - for _, bContr := range blkContainers { - canonicalRoots[bytesutil.ToBytes32(bContr.BlockRoot)] = true - } - headBlock := blkContainers[len(blkContainers)-1] - nextSlot := headBlock.GetPhase0Block().Block.Slot + 1 - wsb, err := blocks.NewSignedBeaconBlock(headBlock.Block.(*ethpbalpha.BeaconBlockContainer_Phase0Block).Phase0Block) + t.Run("Phase 0", func(t *testing.T) { + b := util.NewBeaconBlock() + blk, err := blocks.NewSignedBeaconBlock(b) require.NoError(t, err) - mockChainService := &mock.ChainService{ - DB: beaconDB, - Block: wsb, - Root: headBlock.BlockRoot, - FinalizedCheckPoint: ðpbalpha.Checkpoint{Root: blkContainers[64].BlockRoot}, - CanonicalRoots: canonicalRoots, - FinalizedRoots: map[[32]byte]bool{}, - } + bs := &Server{ - BeaconDB: beaconDB, - ChainInfoFetcher: mockChainService, - HeadFetcher: mockChainService, - OptimisticModeFetcher: mockChainService, - FinalizationFetcher: mockChainService, + FinalizationFetcher: &mock.ChainService{}, + BlockFetcher: &testutil.MockBlockFetcher{BlockToReturn: blk}, } - root, err := genBlk.Block.HashTreeRoot() + expected, err := migration.V1Alpha1ToV1SignedBlock(b) require.NoError(t, err) - - tests := []struct { - name string - blockID []byte - want *ethpbalpha.SignedBeaconBlock - wantErr bool - }{ - { - name: "slot", - blockID: []byte("30"), - want: blkContainers[30].Block.(*ethpbalpha.BeaconBlockContainer_Phase0Block).Phase0Block, - }, - { - name: "bad formatting", - blockID: []byte("3bad0"), - wantErr: true, - }, - { - name: "canonical", - blockID: []byte("30"), - want: blkContainers[30].Block.(*ethpbalpha.BeaconBlockContainer_Phase0Block).Phase0Block, - }, - { - name: "non canonical", - blockID: []byte(fmt.Sprintf("%d", nextSlot)), - wantErr: true, - }, - { - name: "head", - blockID: []byte("head"), - want: headBlock.Block.(*ethpbalpha.BeaconBlockContainer_Phase0Block).Phase0Block, - }, - { - name: "finalized", - blockID: []byte("finalized"), - want: blkContainers[64].Block.(*ethpbalpha.BeaconBlockContainer_Phase0Block).Phase0Block, - }, - { - name: "genesis", - blockID: []byte("genesis"), - want: genBlk, - }, - { - name: "genesis root", - blockID: root[:], - want: genBlk, - }, - { - name: "root", - blockID: blkContainers[20].BlockRoot, - want: blkContainers[20].Block.(*ethpbalpha.BeaconBlockContainer_Phase0Block).Phase0Block, - }, - { - name: "non-existent root", - blockID: bytesutil.PadTo([]byte("hi there"), 32), - wantErr: true, - }, - { - name: "no block", - blockID: []byte("105"), - wantErr: true, - }, - } - for _, tt := range tests { - t.Run(tt.name, func(t *testing.T) { - blk, err := bs.GetBlindedBlock(ctx, ðpbv1.BlockRequest{ - BlockId: tt.blockID, - }) - if tt.wantErr { - require.NotEqual(t, err, nil) - return - } - require.NoError(t, err) - - v1Block, err := migration.V1Alpha1ToV1SignedBlock(tt.want) - require.NoError(t, err) - - phase0Block, ok := blk.Data.Message.(*ethpbv2.SignedBlindedBeaconBlockContainer_Phase0Block) - require.Equal(t, true, ok) - if !reflect.DeepEqual(phase0Block.Phase0Block, v1Block.Block) { - t.Error("Expected blocks to equal") - } - assert.Equal(t, ethpbv2.Version_PHASE0, blk.Version) - }) - } + resp, err := bs.GetBlindedBlock(ctx, ðpbv1.BlockRequest{}) + require.NoError(t, err) + phase0Block, ok := resp.Data.Message.(*ethpbv2.SignedBlindedBeaconBlockContainer_Phase0Block) + require.Equal(t, true, ok) + assert.DeepEqual(t, expected.Block, phase0Block.Phase0Block) + assert.Equal(t, ethpbv2.Version_PHASE0, resp.Version) }) - t.Run("Altair", func(t *testing.T) { - beaconDB := dbTest.SetupDB(t) - ctx := context.Background() - - genBlk, blkContainers := fillDBTestBlocksAltair(ctx, t, beaconDB) - canonicalRoots := make(map[[32]byte]bool) - for _, bContr := range blkContainers { - canonicalRoots[bytesutil.ToBytes32(bContr.BlockRoot)] = true - } - headBlock := blkContainers[len(blkContainers)-1] - nextSlot := headBlock.GetAltairBlock().Block.Slot + 1 - chainBlk, err := blocks.NewSignedBeaconBlock(headBlock.GetAltairBlock()) + b := util.NewBeaconBlockAltair() + blk, err := blocks.NewSignedBeaconBlock(b) require.NoError(t, err) - mockChainService := &mock.ChainService{ - DB: beaconDB, - Block: chainBlk, - Root: headBlock.BlockRoot, - FinalizedCheckPoint: ðpbalpha.Checkpoint{Root: blkContainers[64].BlockRoot}, - CanonicalRoots: canonicalRoots, - FinalizedRoots: map[[32]byte]bool{}, - } + bs := &Server{ - BeaconDB: beaconDB, - ChainInfoFetcher: mockChainService, - HeadFetcher: mockChainService, - OptimisticModeFetcher: mockChainService, - FinalizationFetcher: mockChainService, + FinalizationFetcher: &mock.ChainService{}, + BlockFetcher: &testutil.MockBlockFetcher{BlockToReturn: blk}, } - root, err := genBlk.Block.HashTreeRoot() + expected, err := migration.V1Alpha1BeaconBlockAltairToV2(b.Block) require.NoError(t, err) - - tests := []struct { - name string - blockID []byte - want *ethpbalpha.SignedBeaconBlockAltair - wantErr bool - }{ - { - name: "slot", - blockID: []byte("30"), - want: blkContainers[30].GetAltairBlock(), - }, - { - name: "bad formatting", - blockID: []byte("3bad0"), - wantErr: true, - }, - { - name: "canonical", - blockID: []byte("30"), - want: blkContainers[30].GetAltairBlock(), - }, - { - name: "non canonical", - blockID: []byte(fmt.Sprintf("%d", nextSlot)), - wantErr: true, - }, - { - name: "head", - blockID: []byte("head"), - want: headBlock.GetAltairBlock(), - }, - { - name: "finalized", - blockID: []byte("finalized"), - want: blkContainers[64].GetAltairBlock(), - }, - { - name: "genesis", - blockID: []byte("genesis"), - want: genBlk, - }, - { - name: "genesis root", - blockID: root[:], - want: genBlk, - }, - { - name: "root", - blockID: blkContainers[20].BlockRoot, - want: blkContainers[20].GetAltairBlock(), - }, - { - name: "non-existent root", - blockID: bytesutil.PadTo([]byte("hi there"), 32), - wantErr: true, - }, - { - name: "no block", - blockID: []byte("105"), - wantErr: true, - }, - } - for _, tt := range tests { - t.Run(tt.name, func(t *testing.T) { - blk, err := bs.GetBlindedBlock(ctx, ðpbv1.BlockRequest{ - BlockId: tt.blockID, - }) - if tt.wantErr { - require.NotEqual(t, err, nil) - return - } - require.NoError(t, err) - - v2Block, err := migration.V1Alpha1BeaconBlockAltairToV2(tt.want.Block) - require.NoError(t, err) - - altairBlock, ok := blk.Data.Message.(*ethpbv2.SignedBlindedBeaconBlockContainer_AltairBlock) - require.Equal(t, true, ok) - if !reflect.DeepEqual(altairBlock.AltairBlock, v2Block) { - t.Error("Expected blocks to equal") - } - assert.Equal(t, ethpbv2.Version_ALTAIR, blk.Version) - }) - } + resp, err := bs.GetBlindedBlock(ctx, ðpbv1.BlockRequest{}) + require.NoError(t, err) + altairBlock, ok := resp.Data.Message.(*ethpbv2.SignedBlindedBeaconBlockContainer_AltairBlock) + require.Equal(t, true, ok) + assert.DeepEqual(t, expected, altairBlock.AltairBlock) + assert.Equal(t, ethpbv2.Version_ALTAIR, resp.Version) }) - t.Run("Bellatrix", func(t *testing.T) { - beaconDB := dbTest.SetupDB(t) - ctx := context.Background() - - genBlk, blkContainers := fillDBTestBlocksBellatrixBlinded(ctx, t, beaconDB) - canonicalRoots := make(map[[32]byte]bool) - for _, bContr := range blkContainers { - canonicalRoots[bytesutil.ToBytes32(bContr.BlockRoot)] = true - } - headBlock := blkContainers[len(blkContainers)-1] - nextSlot := headBlock.GetBlindedBellatrixBlock().Block.Slot + 1 - chainBlk, err := blocks.NewSignedBeaconBlock(headBlock.GetBlindedBellatrixBlock()) + b := util.NewBlindedBeaconBlockBellatrix() + blk, err := blocks.NewSignedBeaconBlock(b) require.NoError(t, err) - mockChainService := &mock.ChainService{ - DB: beaconDB, - Block: chainBlk, - Root: headBlock.BlockRoot, - FinalizedCheckPoint: ðpbalpha.Checkpoint{Root: blkContainers[64].BlockRoot}, - CanonicalRoots: canonicalRoots, - FinalizedRoots: map[[32]byte]bool{}, - } + + mockChainService := &mock.ChainService{} bs := &Server{ - BeaconDB: beaconDB, - ChainInfoFetcher: mockChainService, - HeadFetcher: mockChainService, + FinalizationFetcher: mockChainService, + BlockFetcher: &testutil.MockBlockFetcher{BlockToReturn: blk}, OptimisticModeFetcher: mockChainService, - ExecutionPayloadReconstructor: &executionTest.EngineClient{ - ExecutionPayloadByBlockHash: map[[32]byte]*enginev1.ExecutionPayload{}, - }, - FinalizationFetcher: mockChainService, } - root, err := genBlk.Block.HashTreeRoot() + expected, err := migration.V1Alpha1BeaconBlockBlindedBellatrixToV2Blinded(b.Block) require.NoError(t, err) - - tests := []struct { - name string - blockID []byte - want *ethpbalpha.SignedBlindedBeaconBlockBellatrix - wantErr bool - }{ - { - name: "slot", - blockID: []byte("30"), - want: blkContainers[30].GetBlindedBellatrixBlock(), - }, - { - name: "bad formatting", - blockID: []byte("3bad0"), - wantErr: true, - }, - { - name: "canonical", - blockID: []byte("30"), - want: blkContainers[30].GetBlindedBellatrixBlock(), - }, - { - name: "non canonical", - blockID: []byte(fmt.Sprintf("%d", nextSlot)), - wantErr: true, - }, - { - name: "head", - blockID: []byte("head"), - want: headBlock.GetBlindedBellatrixBlock(), - }, - { - name: "finalized", - blockID: []byte("finalized"), - want: blkContainers[64].GetBlindedBellatrixBlock(), - }, - { - name: "genesis", - blockID: []byte("genesis"), - want: genBlk, - }, - { - name: "genesis root", - blockID: root[:], - want: genBlk, - }, - { - name: "root", - blockID: blkContainers[20].BlockRoot, - want: blkContainers[20].GetBlindedBellatrixBlock(), - }, - { - name: "non-existent root", - blockID: bytesutil.PadTo([]byte("hi there"), 32), - wantErr: true, - }, - { - name: "no block", - blockID: []byte("105"), - wantErr: true, - }, - } - for _, tt := range tests { - t.Run(tt.name, func(t *testing.T) { - blk, err := bs.GetBlindedBlock(ctx, ðpbv1.BlockRequest{ - BlockId: tt.blockID, - }) - if tt.wantErr { - require.NotEqual(t, err, nil) - return - } - require.NoError(t, err) - - v2Block, err := migration.V1Alpha1BeaconBlockBlindedBellatrixToV2Blinded(tt.want.Block) - require.NoError(t, err) - - b, ok := blk.Data.Message.(*ethpbv2.SignedBlindedBeaconBlockContainer_BellatrixBlock) - require.Equal(t, true, ok) - if !reflect.DeepEqual(b.BellatrixBlock, v2Block) { - t.Error("Expected blocks to equal") - } - assert.Equal(t, ethpbv2.Version_BELLATRIX, blk.Version) - }) - } + resp, err := bs.GetBlindedBlock(ctx, ðpbv1.BlockRequest{}) + require.NoError(t, err) + bellatrixBlock, ok := resp.Data.Message.(*ethpbv2.SignedBlindedBeaconBlockContainer_BellatrixBlock) + require.Equal(t, true, ok) + assert.DeepEqual(t, expected, bellatrixBlock.BellatrixBlock) + assert.Equal(t, ethpbv2.Version_BELLATRIX, resp.Version) }) - t.Run("Capella", func(t *testing.T) { - beaconDB := dbTest.SetupDB(t) - ctx := context.Background() - - genBlk, blkContainers := fillDBTestBlocksCapellaBlinded(ctx, t, beaconDB) - canonicalRoots := make(map[[32]byte]bool) - for _, bContr := range blkContainers { - canonicalRoots[bytesutil.ToBytes32(bContr.BlockRoot)] = true - } - headBlock := blkContainers[len(blkContainers)-1] - nextSlot := headBlock.GetBlindedCapellaBlock().Block.Slot + 1 - chainBlk, err := blocks.NewSignedBeaconBlock(headBlock.GetBlindedCapellaBlock()) + b := util.NewBlindedBeaconBlockCapella() + blk, err := blocks.NewSignedBeaconBlock(b) require.NoError(t, err) - mockChainService := &mock.ChainService{ - DB: beaconDB, - Block: chainBlk, - Root: headBlock.BlockRoot, - FinalizedCheckPoint: ðpbalpha.Checkpoint{Root: blkContainers[64].BlockRoot}, - CanonicalRoots: canonicalRoots, - FinalizedRoots: map[[32]byte]bool{}, - } + + mockChainService := &mock.ChainService{} bs := &Server{ - BeaconDB: beaconDB, - ChainInfoFetcher: mockChainService, - HeadFetcher: mockChainService, + FinalizationFetcher: mockChainService, + BlockFetcher: &testutil.MockBlockFetcher{BlockToReturn: blk}, OptimisticModeFetcher: mockChainService, - ExecutionPayloadReconstructor: &executionTest.EngineClient{ - ExecutionPayloadByBlockHash: map[[32]byte]*enginev1.ExecutionPayload{}, - }, - FinalizationFetcher: mockChainService, } - root, err := genBlk.Block.HashTreeRoot() + expected, err := migration.V1Alpha1BeaconBlockBlindedCapellaToV2Blinded(b.Block) require.NoError(t, err) - - tests := []struct { - name string - blockID []byte - want *ethpbalpha.SignedBlindedBeaconBlockCapella - wantErr bool - }{ - { - name: "slot", - blockID: []byte("30"), - want: blkContainers[30].GetBlindedCapellaBlock(), - }, - { - name: "bad formatting", - blockID: []byte("3bad0"), - wantErr: true, - }, - { - name: "canonical", - blockID: []byte("30"), - want: blkContainers[30].GetBlindedCapellaBlock(), - }, - { - name: "non canonical", - blockID: []byte(fmt.Sprintf("%d", nextSlot)), - wantErr: true, - }, - { - name: "head", - blockID: []byte("head"), - want: headBlock.GetBlindedCapellaBlock(), - }, - { - name: "finalized", - blockID: []byte("finalized"), - want: blkContainers[64].GetBlindedCapellaBlock(), - }, - { - name: "genesis", - blockID: []byte("genesis"), - want: genBlk, - }, - { - name: "genesis root", - blockID: root[:], - want: genBlk, - }, - { - name: "root", - blockID: blkContainers[20].BlockRoot, - want: blkContainers[20].GetBlindedCapellaBlock(), - }, - { - name: "non-existent root", - blockID: bytesutil.PadTo([]byte("hi there"), 32), - wantErr: true, - }, - { - name: "no block", - blockID: []byte("105"), - wantErr: true, - }, - } - for _, tt := range tests { - t.Run(tt.name, func(t *testing.T) { - blk, err := bs.GetBlindedBlock(ctx, ðpbv1.BlockRequest{ - BlockId: tt.blockID, - }) - if tt.wantErr { - require.NotEqual(t, err, nil) - return - } - require.NoError(t, err) - - v2Block, err := migration.V1Alpha1BeaconBlockBlindedCapellaToV2Blinded(tt.want.Block) - require.NoError(t, err) - - b, ok := blk.Data.Message.(*ethpbv2.SignedBlindedBeaconBlockContainer_CapellaBlock) - require.Equal(t, true, ok) - if !reflect.DeepEqual(b.CapellaBlock, v2Block) { - t.Error("Expected blocks to equal") - } - assert.Equal(t, ethpbv2.Version_CAPELLA, blk.Version) - }) - } + resp, err := bs.GetBlindedBlock(ctx, ðpbv1.BlockRequest{}) + require.NoError(t, err) + capellaBlock, ok := resp.Data.Message.(*ethpbv2.SignedBlindedBeaconBlockContainer_CapellaBlock) + require.Equal(t, true, ok) + assert.DeepEqual(t, expected, capellaBlock.CapellaBlock) + assert.Equal(t, ethpbv2.Version_CAPELLA, resp.Version) }) - t.Run("execution optimistic", func(t *testing.T) { - beaconDB := dbTest.SetupDB(t) - ctx := context.Background() - - _, blkContainers := fillDBTestBlocksBellatrix(ctx, t, beaconDB) - headBlock := blkContainers[len(blkContainers)-1] - chainBlk, err := blocks.NewSignedBeaconBlock(headBlock.GetBellatrixBlock()) + b := util.NewBlindedBeaconBlockBellatrix() + blk, err := blocks.NewSignedBeaconBlock(b) require.NoError(t, err) + mockChainService := &mock.ChainService{ - DB: beaconDB, - Block: chainBlk, - Root: headBlock.BlockRoot, - FinalizedCheckPoint: ðpbalpha.Checkpoint{Root: blkContainers[64].BlockRoot}, - Optimistic: true, - FinalizedRoots: map[[32]byte]bool{}, + Optimistic: true, } bs := &Server{ - BeaconDB: beaconDB, - ChainInfoFetcher: mockChainService, - HeadFetcher: mockChainService, - OptimisticModeFetcher: mockChainService, FinalizationFetcher: mockChainService, + BlockFetcher: &testutil.MockBlockFetcher{BlockToReturn: blk}, + OptimisticModeFetcher: mockChainService, } - blk, err := bs.GetBlindedBlock(ctx, ðpbv1.BlockRequest{ - BlockId: []byte("head"), - }) + resp, err := bs.GetBlindedBlock(ctx, ðpbv1.BlockRequest{}) require.NoError(t, err) - assert.Equal(t, true, blk.ExecutionOptimistic) + assert.Equal(t, true, resp.ExecutionOptimistic) }) - t.Run("finalized", func(t *testing.T) { - beaconDB := dbTest.SetupDB(t) - ctx := context.Background() - - _, blkContainers := fillDBTestBlocks(ctx, t, beaconDB) - headBlock := blkContainers[len(blkContainers)-1] - chainBlk, err := blocks.NewSignedBeaconBlock(headBlock.GetPhase0Block()) + b := util.NewBeaconBlock() + blk, err := blocks.NewSignedBeaconBlock(b) + require.NoError(t, err) + root, err := blk.Block().HashTreeRoot() require.NoError(t, err) + mockChainService := &mock.ChainService{ - DB: beaconDB, - Block: chainBlk, - Root: headBlock.BlockRoot, - FinalizedCheckPoint: ðpbalpha.Checkpoint{Root: blkContainers[64].BlockRoot}, - Optimistic: true, - FinalizedRoots: map[[32]byte]bool{ - bytesutil.ToBytes32(blkContainers[32].BlockRoot): true, - bytesutil.ToBytes32(blkContainers[64].BlockRoot): false, - }, + FinalizedRoots: map[[32]byte]bool{root: true}, } bs := &Server{ - BeaconDB: beaconDB, - ChainInfoFetcher: mockChainService, - HeadFetcher: mockChainService, - OptimisticModeFetcher: mockChainService, - FinalizationFetcher: mockChainService, + FinalizationFetcher: mockChainService, + BlockFetcher: &testutil.MockBlockFetcher{BlockToReturn: blk}, } - t.Run("true", func(t *testing.T) { - blk, err := bs.GetBlindedBlock(ctx, ðpbv1.BlockRequest{ - BlockId: []byte("32"), - }) - require.NoError(t, err) - assert.Equal(t, true, blk.Finalized) - }) - t.Run("false", func(t *testing.T) { - blk, err := bs.GetBlindedBlock(ctx, ðpbv1.BlockRequest{ - BlockId: []byte("64"), - }) - require.NoError(t, err) - assert.Equal(t, false, blk.Finalized) - }) + resp, err := bs.GetBlindedBlock(ctx, ðpbv1.BlockRequest{BlockId: root[:]}) + require.NoError(t, err) + assert.Equal(t, true, resp.Finalized) }) -} - -func TestServer_GetBlindedBlockSSZ(t *testing.T) { - t.Run("Phase 0", func(t *testing.T) { - beaconDB := dbTest.SetupDB(t) - ctx := context.Background() - - _, blkContainers := fillDBTestBlocks(ctx, t, beaconDB) - headBlock := blkContainers[len(blkContainers)-1] - wsb, err := blocks.NewSignedBeaconBlock(headBlock.Block.(*ethpbalpha.BeaconBlockContainer_Phase0Block).Phase0Block) + t.Run("not finalized", func(t *testing.T) { + b := util.NewBeaconBlock() + blk, err := blocks.NewSignedBeaconBlock(b) + require.NoError(t, err) + root, err := blk.Block().HashTreeRoot() require.NoError(t, err) + mockChainService := &mock.ChainService{ - DB: beaconDB, - Block: wsb, - Root: headBlock.BlockRoot, - FinalizedCheckPoint: ðpbalpha.Checkpoint{Root: blkContainers[64].BlockRoot}, - FinalizedRoots: map[[32]byte]bool{}, + FinalizedRoots: map[[32]byte]bool{root: false}, } bs := &Server{ - BeaconDB: beaconDB, - ChainInfoFetcher: mockChainService, FinalizationFetcher: mockChainService, + BlockFetcher: &testutil.MockBlockFetcher{BlockToReturn: blk}, } - blks, err := beaconDB.BlocksBySlot(ctx, 30) - require.Equal(t, true, len(blks) > 0) + resp, err := bs.GetBlindedBlock(ctx, ðpbv1.BlockRequest{BlockId: root[:]}) require.NoError(t, err) - sszBlock, err := blks[0].MarshalSSZ() + assert.Equal(t, false, resp.Finalized) + }) +} + +func TestServer_GetBlindedBlockSSZ(t *testing.T) { + ctx := context.Background() + + t.Run("Phase 0", func(t *testing.T) { + b := util.NewBeaconBlock() + blk, err := blocks.NewSignedBeaconBlock(b) require.NoError(t, err) - resp, err := bs.GetBlindedBlockSSZ(ctx, ðpbv1.BlockRequest{BlockId: []byte("30")}) + bs := &Server{ + FinalizationFetcher: &mock.ChainService{}, + BlockFetcher: &testutil.MockBlockFetcher{BlockToReturn: blk}, + } + + expected, err := blk.MarshalSSZ() + require.NoError(t, err) + resp, err := bs.GetBlindedBlockSSZ(ctx, ðpbv1.BlockRequest{}) require.NoError(t, err) assert.NotNil(t, resp) - assert.DeepEqual(t, sszBlock, resp.Data) + assert.DeepEqual(t, expected, resp.Data) assert.Equal(t, ethpbv2.Version_PHASE0, resp.Version) }) - t.Run("Altair", func(t *testing.T) { - beaconDB := dbTest.SetupDB(t) - ctx := context.Background() - - _, blkContainers := fillDBTestBlocksAltair(ctx, t, beaconDB) - headBlock := blkContainers[len(blkContainers)-1] - chainBlk, err := blocks.NewSignedBeaconBlock(headBlock.GetAltairBlock()) + b := util.NewBeaconBlockAltair() + blk, err := blocks.NewSignedBeaconBlock(b) require.NoError(t, err) - mockChainService := &mock.ChainService{ - DB: beaconDB, - Block: chainBlk, - Root: headBlock.BlockRoot, - FinalizedCheckPoint: ðpbalpha.Checkpoint{Root: blkContainers[64].BlockRoot}, - FinalizedRoots: map[[32]byte]bool{}, - } + bs := &Server{ - BeaconDB: beaconDB, - ChainInfoFetcher: mockChainService, - FinalizationFetcher: mockChainService, + FinalizationFetcher: &mock.ChainService{}, + BlockFetcher: &testutil.MockBlockFetcher{BlockToReturn: blk}, } - blks, err := beaconDB.BlocksBySlot(ctx, 30) - require.Equal(t, true, len(blks) > 0) + expected, err := blk.MarshalSSZ() require.NoError(t, err) - sszBlock, err := blks[0].MarshalSSZ() - require.NoError(t, err) - - resp, err := bs.GetBlindedBlockSSZ(ctx, ðpbv1.BlockRequest{BlockId: []byte("30")}) + resp, err := bs.GetBlindedBlockSSZ(ctx, ðpbv1.BlockRequest{}) require.NoError(t, err) assert.NotNil(t, resp) - assert.DeepEqual(t, sszBlock, resp.Data) + assert.DeepEqual(t, expected, resp.Data) assert.Equal(t, ethpbv2.Version_ALTAIR, resp.Version) }) - t.Run("Bellatrix", func(t *testing.T) { - beaconDB := dbTest.SetupDB(t) - ctx := context.Background() - - _, blkContainers := fillDBTestBlocksBellatrixBlinded(ctx, t, beaconDB) - headBlock := blkContainers[len(blkContainers)-1] - chainBlk, err := blocks.NewSignedBeaconBlock(headBlock.GetBlindedBellatrixBlock()) + b := util.NewBlindedBeaconBlockBellatrix() + blk, err := blocks.NewSignedBeaconBlock(b) require.NoError(t, err) - mockChainService := &mock.ChainService{ - DB: beaconDB, - Block: chainBlk, - Root: headBlock.BlockRoot, - FinalizedCheckPoint: ðpbalpha.Checkpoint{Root: blkContainers[64].BlockRoot}, - FinalizedRoots: map[[32]byte]bool{}, - } + + mockChainService := &mock.ChainService{} bs := &Server{ - BeaconDB: beaconDB, - ChainInfoFetcher: mockChainService, - OptimisticModeFetcher: mockChainService, FinalizationFetcher: mockChainService, + BlockFetcher: &testutil.MockBlockFetcher{BlockToReturn: blk}, + OptimisticModeFetcher: mockChainService, } - blks, err := beaconDB.BlocksBySlot(ctx, 30) - require.Equal(t, true, len(blks) > 0) - require.NoError(t, err) - sszBlock, err := blks[0].MarshalSSZ() + expected, err := blk.MarshalSSZ() require.NoError(t, err) - - resp, err := bs.GetBlindedBlockSSZ(ctx, ðpbv1.BlockRequest{BlockId: []byte("30")}) + resp, err := bs.GetBlindedBlockSSZ(ctx, ðpbv1.BlockRequest{}) require.NoError(t, err) assert.NotNil(t, resp) - assert.DeepEqual(t, sszBlock, resp.Data) + assert.DeepEqual(t, expected, resp.Data) assert.Equal(t, ethpbv2.Version_BELLATRIX, resp.Version) }) - t.Run("Capella", func(t *testing.T) { - beaconDB := dbTest.SetupDB(t) - ctx := context.Background() - - _, blkContainers := fillDBTestBlocksCapellaBlinded(ctx, t, beaconDB) - headBlock := blkContainers[len(blkContainers)-1] - chainBlk, err := blocks.NewSignedBeaconBlock(headBlock.GetBlindedCapellaBlock()) + b := util.NewBlindedBeaconBlockCapella() + blk, err := blocks.NewSignedBeaconBlock(b) require.NoError(t, err) - mockChainService := &mock.ChainService{ - DB: beaconDB, - Block: chainBlk, - Root: headBlock.BlockRoot, - FinalizedCheckPoint: ðpbalpha.Checkpoint{Root: blkContainers[64].BlockRoot}, - FinalizedRoots: map[[32]byte]bool{}, - } + + mockChainService := &mock.ChainService{} bs := &Server{ - BeaconDB: beaconDB, - ChainInfoFetcher: mockChainService, - OptimisticModeFetcher: mockChainService, FinalizationFetcher: mockChainService, + BlockFetcher: &testutil.MockBlockFetcher{BlockToReturn: blk}, + OptimisticModeFetcher: mockChainService, } - blks, err := beaconDB.BlocksBySlot(ctx, 30) - require.Equal(t, true, len(blks) > 0) - require.NoError(t, err) - sszBlock, err := blks[0].MarshalSSZ() + expected, err := blk.MarshalSSZ() require.NoError(t, err) - - resp, err := bs.GetBlindedBlockSSZ(ctx, ðpbv1.BlockRequest{BlockId: []byte("30")}) + resp, err := bs.GetBlindedBlockSSZ(ctx, ðpbv1.BlockRequest{}) require.NoError(t, err) assert.NotNil(t, resp) - assert.DeepEqual(t, sszBlock, resp.Data) + assert.DeepEqual(t, expected, resp.Data) assert.Equal(t, ethpbv2.Version_CAPELLA, resp.Version) }) - t.Run("execution optimistic", func(t *testing.T) { - beaconDB := dbTest.SetupDB(t) - ctx := context.Background() - - _, blkContainers := fillDBTestBlocksBellatrix(ctx, t, beaconDB) - headBlock := blkContainers[len(blkContainers)-1] - chainBlk, err := blocks.NewSignedBeaconBlock(headBlock.GetBellatrixBlock()) + b := util.NewBlindedBeaconBlockBellatrix() + blk, err := blocks.NewSignedBeaconBlock(b) require.NoError(t, err) + mockChainService := &mock.ChainService{ - DB: beaconDB, - Block: chainBlk, - Root: headBlock.BlockRoot, - FinalizedCheckPoint: ðpbalpha.Checkpoint{Root: blkContainers[64].BlockRoot}, - Optimistic: true, - FinalizedRoots: map[[32]byte]bool{}, + Optimistic: true, } bs := &Server{ - BeaconDB: beaconDB, - ChainInfoFetcher: mockChainService, - HeadFetcher: mockChainService, - OptimisticModeFetcher: mockChainService, FinalizationFetcher: mockChainService, + BlockFetcher: &testutil.MockBlockFetcher{BlockToReturn: blk}, + OptimisticModeFetcher: mockChainService, } - blk, err := bs.GetBlindedBlockSSZ(ctx, ðpbv1.BlockRequest{ - BlockId: []byte("head"), - }) + resp, err := bs.GetBlindedBlockSSZ(ctx, ðpbv1.BlockRequest{}) require.NoError(t, err) - assert.Equal(t, true, blk.ExecutionOptimistic) + assert.Equal(t, true, resp.ExecutionOptimistic) }) - t.Run("finalized", func(t *testing.T) { - beaconDB := dbTest.SetupDB(t) - ctx := context.Background() + b := util.NewBeaconBlock() + blk, err := blocks.NewSignedBeaconBlock(b) + require.NoError(t, err) + root, err := blk.Block().HashTreeRoot() + require.NoError(t, err) - _, blkContainers := fillDBTestBlocks(ctx, t, beaconDB) - headBlock := blkContainers[len(blkContainers)-1] - chainBlk, err := blocks.NewSignedBeaconBlock(headBlock.GetPhase0Block()) + mockChainService := &mock.ChainService{ + FinalizedRoots: map[[32]byte]bool{root: true}, + } + bs := &Server{ + FinalizationFetcher: mockChainService, + BlockFetcher: &testutil.MockBlockFetcher{BlockToReturn: blk}, + } + + resp, err := bs.GetBlindedBlockSSZ(ctx, ðpbv1.BlockRequest{BlockId: root[:]}) + require.NoError(t, err) + assert.Equal(t, true, resp.Finalized) + }) + t.Run("not finalized", func(t *testing.T) { + b := util.NewBeaconBlock() + blk, err := blocks.NewSignedBeaconBlock(b) require.NoError(t, err) + root, err := blk.Block().HashTreeRoot() + require.NoError(t, err) + mockChainService := &mock.ChainService{ - DB: beaconDB, - Block: chainBlk, - Root: headBlock.BlockRoot, - FinalizedCheckPoint: ðpbalpha.Checkpoint{Root: blkContainers[64].BlockRoot}, - Optimistic: true, - FinalizedRoots: map[[32]byte]bool{ - bytesutil.ToBytes32(blkContainers[32].BlockRoot): true, - bytesutil.ToBytes32(blkContainers[64].BlockRoot): false, - }, + FinalizedRoots: map[[32]byte]bool{root: false}, } bs := &Server{ - BeaconDB: beaconDB, - ChainInfoFetcher: mockChainService, - HeadFetcher: mockChainService, - OptimisticModeFetcher: mockChainService, - FinalizationFetcher: mockChainService, + FinalizationFetcher: mockChainService, + BlockFetcher: &testutil.MockBlockFetcher{BlockToReturn: blk}, } - t.Run("true", func(t *testing.T) { - blk, err := bs.GetBlindedBlockSSZ(ctx, ðpbv1.BlockRequest{ - BlockId: []byte("32"), - }) - require.NoError(t, err) - assert.Equal(t, true, blk.Finalized) - }) - t.Run("false", func(t *testing.T) { - blk, err := bs.GetBlindedBlockSSZ(ctx, ðpbv1.BlockRequest{ - BlockId: []byte("64"), - }) - require.NoError(t, err) - assert.Equal(t, false, blk.Finalized) - }) + resp, err := bs.GetBlindedBlockSSZ(ctx, ðpbv1.BlockRequest{BlockId: root[:]}) + require.NoError(t, err) + assert.Equal(t, false, resp.Finalized) }) } diff --git a/beacon-chain/rpc/eth/beacon/blocks_test.go b/beacon-chain/rpc/eth/beacon/blocks_test.go index 8a49d2893e7f..894f6a954b83 100644 --- a/beacon-chain/rpc/eth/beacon/blocks_test.go +++ b/beacon-chain/rpc/eth/beacon/blocks_test.go @@ -2,16 +2,14 @@ package beacon import ( "context" - "fmt" - "reflect" "testing" "github.com/prysmaticlabs/go-bitfield" mock "github.com/prysmaticlabs/prysm/v3/beacon-chain/blockchain/testing" "github.com/prysmaticlabs/prysm/v3/beacon-chain/db" dbTest "github.com/prysmaticlabs/prysm/v3/beacon-chain/db/testing" - executionTest "github.com/prysmaticlabs/prysm/v3/beacon-chain/execution/testing" mockp2p "github.com/prysmaticlabs/prysm/v3/beacon-chain/p2p/testing" + "github.com/prysmaticlabs/prysm/v3/beacon-chain/rpc/testutil" "github.com/prysmaticlabs/prysm/v3/config/params" "github.com/prysmaticlabs/prysm/v3/consensus-types/blocks" "github.com/prysmaticlabs/prysm/v3/consensus-types/interfaces" @@ -349,171 +347,122 @@ func fillDBTestBlocksCapellaBlinded(ctx context.Context, t *testing.T, beaconDB } func TestServer_GetBlockHeader(t *testing.T) { - beaconDB := dbTest.SetupDB(t) ctx := context.Background() - genBlk, blkContainers := fillDBTestBlocks(ctx, t, beaconDB) - root, err := genBlk.Block.HashTreeRoot() - require.NoError(t, err) - headBlock := blkContainers[len(blkContainers)-1] - t.Run("get header", func(t *testing.T) { - wsb, err := blocks.NewSignedBeaconBlock(headBlock.Block.(*ethpbalpha.BeaconBlockContainer_Phase0Block).Phase0Block) + b := util.NewBeaconBlock() + b.Block.Slot = 123 + b.Block.ProposerIndex = 123 + b.Block.ParentRoot = bytesutil.PadTo([]byte("parent_root"), 32) + b.Block.StateRoot = bytesutil.PadTo([]byte("state_root"), 32) + blk, err := blocks.NewSignedBeaconBlock(b) require.NoError(t, err) - mockChainService := &mock.ChainService{ - DB: beaconDB, - Block: wsb, - Root: headBlock.BlockRoot, - FinalizedCheckPoint: ðpbalpha.Checkpoint{Root: blkContainers[64].BlockRoot}, - FinalizedRoots: map[[32]byte]bool{}, - } + + mockChainService := &mock.ChainService{} bs := &Server{ - BeaconDB: beaconDB, + FinalizationFetcher: mockChainService, + BlockFetcher: &testutil.MockBlockFetcher{BlockToReturn: blk}, ChainInfoFetcher: mockChainService, - HeadFetcher: mockChainService, OptimisticModeFetcher: mockChainService, - FinalizationFetcher: mockChainService, } - tests := []struct { - name string - blockID []byte - want *ethpbalpha.SignedBeaconBlock - wantErr bool - }{ - { - name: "slot", - blockID: []byte("10"), - want: blkContainers[10].Block.(*ethpbalpha.BeaconBlockContainer_Phase0Block).Phase0Block, - }, - { - name: "root", - blockID: blkContainers[20].BlockRoot, - want: blkContainers[20].Block.(*ethpbalpha.BeaconBlockContainer_Phase0Block).Phase0Block, - }, - { - name: "canonical", - blockID: []byte("30"), - want: blkContainers[30].Block.(*ethpbalpha.BeaconBlockContainer_Phase0Block).Phase0Block, - }, - { - name: "genesis", - blockID: []byte("genesis"), - want: genBlk, - }, - { - name: "genesis root", - blockID: root[:], - want: genBlk, - }, - { - name: "head", - blockID: []byte("head"), - want: headBlock.Block.(*ethpbalpha.BeaconBlockContainer_Phase0Block).Phase0Block, - }, - { - name: "finalized", - blockID: []byte("finalized"), - want: blkContainers[64].Block.(*ethpbalpha.BeaconBlockContainer_Phase0Block).Phase0Block, - }, - { - name: "no block", - blockID: []byte("105"), - wantErr: true, - }, + resp, err := bs.GetBlockHeader(ctx, ðpbv1.BlockRequest{}) + require.NoError(t, err) + expectedBodyRoot, err := b.Block.Body.HashTreeRoot() + require.NoError(t, err) + expectedHeader := ðpbv1.BeaconBlockHeader{ + Slot: 123, + ProposerIndex: 123, + ParentRoot: bytesutil.PadTo([]byte("parent_root"), 32), + StateRoot: bytesutil.PadTo([]byte("state_root"), 32), + BodyRoot: expectedBodyRoot[:], } - for _, tt := range tests { - t.Run(tt.name, func(t *testing.T) { - header, err := bs.GetBlockHeader(ctx, ðpbv1.BlockRequest{ - BlockId: tt.blockID, - }) - if !tt.wantErr { - require.NoError(t, err) - } else { - require.NotEqual(t, err, nil) - return - } - - expectedBodyRoot, err := tt.want.Block.Body.HashTreeRoot() - require.NoError(t, err) - expectedHeader := ðpbv1.BeaconBlockHeader{ - Slot: tt.want.Block.Slot, - ProposerIndex: tt.want.Block.ProposerIndex, - ParentRoot: tt.want.Block.ParentRoot, - StateRoot: make([]byte, 32), - BodyRoot: expectedBodyRoot[:], - } - expectedHeaderRoot, err := expectedHeader.HashTreeRoot() - require.NoError(t, err) - headerRoot, err := header.Data.Header.Message.HashTreeRoot() - require.NoError(t, err) - assert.DeepEqual(t, expectedHeaderRoot, headerRoot) + expectedHeaderRoot, err := expectedHeader.HashTreeRoot() + require.NoError(t, err) + respRoot, err := resp.Data.Header.Message.HashTreeRoot() + require.NoError(t, err) + assert.DeepEqual(t, expectedHeaderRoot, respRoot) + assert.Equal(t, primitives.Slot(123), resp.Data.Header.Message.Slot) + assert.Equal(t, primitives.ValidatorIndex(123), resp.Data.Header.Message.ProposerIndex) + assert.DeepEqual(t, bytesutil.PadTo([]byte("state_root"), 32), resp.Data.Header.Message.StateRoot) + assert.DeepEqual(t, bytesutil.PadTo([]byte("parent_root"), 32), resp.Data.Header.Message.ParentRoot) + expectedRoot, err := b.Block.Body.HashTreeRoot() + require.NoError(t, err) + assert.DeepEqual(t, expectedRoot[:], resp.Data.Header.Message.BodyRoot) + }) + t.Run("canonical", func(t *testing.T) { + b := util.NewBeaconBlock() + blk, err := blocks.NewSignedBeaconBlock(b) + require.NoError(t, err) + root, err := b.Block.HashTreeRoot() + require.NoError(t, err) - assert.Equal(t, tt.want.Block.Slot, header.Data.Header.Message.Slot) - assert.DeepEqual(t, tt.want.Block.StateRoot, header.Data.Header.Message.StateRoot) - assert.DeepEqual(t, tt.want.Block.ParentRoot, header.Data.Header.Message.ParentRoot) - expectedRoot, err := tt.want.Block.Body.HashTreeRoot() - require.NoError(t, err) - assert.DeepEqual(t, expectedRoot[:], header.Data.Header.Message.BodyRoot) - assert.Equal(t, tt.want.Block.ProposerIndex, header.Data.Header.Message.ProposerIndex) - }) + mockChainService := &mock.ChainService{CanonicalRoots: map[[32]byte]bool{root: true}} + bs := &Server{ + FinalizationFetcher: mockChainService, + BlockFetcher: &testutil.MockBlockFetcher{BlockToReturn: blk}, + ChainInfoFetcher: mockChainService, + OptimisticModeFetcher: mockChainService, } - }) + resp, err := bs.GetBlockHeader(ctx, ðpbv1.BlockRequest{}) + require.NoError(t, err) + assert.Equal(t, true, resp.Data.Canonical) + }) t.Run("execution optimistic", func(t *testing.T) { - wsb, err := blocks.NewSignedBeaconBlock(headBlock.Block.(*ethpbalpha.BeaconBlockContainer_Phase0Block).Phase0Block) + b := util.NewBeaconBlock() + blk, err := blocks.NewSignedBeaconBlock(b) require.NoError(t, err) - mockChainService := &mock.ChainService{ - DB: beaconDB, - Block: wsb, - Root: headBlock.BlockRoot, - FinalizedCheckPoint: ðpbalpha.Checkpoint{Root: blkContainers[64].BlockRoot}, - Optimistic: true, - FinalizedRoots: map[[32]byte]bool{}, - } + + mockChainService := &mock.ChainService{Optimistic: true} bs := &Server{ - BeaconDB: beaconDB, + FinalizationFetcher: mockChainService, + BlockFetcher: &testutil.MockBlockFetcher{BlockToReturn: blk}, ChainInfoFetcher: mockChainService, - HeadFetcher: mockChainService, OptimisticModeFetcher: mockChainService, - FinalizationFetcher: mockChainService, } - header, err := bs.GetBlockHeader(ctx, ðpbv1.BlockRequest{BlockId: []byte("head")}) + + resp, err := bs.GetBlockHeader(ctx, ðpbv1.BlockRequest{}) require.NoError(t, err) - assert.Equal(t, true, header.ExecutionOptimistic) + assert.Equal(t, true, resp.ExecutionOptimistic) }) - t.Run("finalized", func(t *testing.T) { - wsb, err := blocks.NewSignedBeaconBlock(headBlock.Block.(*ethpbalpha.BeaconBlockContainer_Phase0Block).Phase0Block) + b := util.NewBeaconBlock() + root, err := b.Block.HashTreeRoot() require.NoError(t, err) - mockChainService := &mock.ChainService{ - DB: beaconDB, - Block: wsb, - Root: headBlock.BlockRoot, - FinalizedCheckPoint: ðpbalpha.Checkpoint{Root: blkContainers[64].BlockRoot}, - FinalizedRoots: map[[32]byte]bool{ - bytesutil.ToBytes32(blkContainers[32].BlockRoot): true, - bytesutil.ToBytes32(blkContainers[64].BlockRoot): false, - }, - } + blk, err := blocks.NewSignedBeaconBlock(b) + require.NoError(t, err) + + mockChainService := &mock.ChainService{FinalizedRoots: map[[32]byte]bool{root: true}} bs := &Server{ - BeaconDB: beaconDB, + FinalizationFetcher: mockChainService, + BlockFetcher: &testutil.MockBlockFetcher{BlockToReturn: blk}, ChainInfoFetcher: mockChainService, - HeadFetcher: mockChainService, OptimisticModeFetcher: mockChainService, + } + + resp, err := bs.GetBlockHeader(ctx, ðpbv1.BlockRequest{BlockId: root[:]}) + require.NoError(t, err) + assert.Equal(t, true, resp.Finalized) + }) + t.Run("not finalized", func(t *testing.T) { + b := util.NewBeaconBlock() + root, err := b.Block.HashTreeRoot() + require.NoError(t, err) + blk, err := blocks.NewSignedBeaconBlock(b) + require.NoError(t, err) + + mockChainService := &mock.ChainService{FinalizedRoots: map[[32]byte]bool{root: false}} + bs := &Server{ FinalizationFetcher: mockChainService, + BlockFetcher: &testutil.MockBlockFetcher{BlockToReturn: blk}, + ChainInfoFetcher: mockChainService, + OptimisticModeFetcher: mockChainService, } - t.Run("true", func(t *testing.T) { - header, err := bs.GetBlockHeader(ctx, ðpbv1.BlockRequest{BlockId: blkContainers[32].BlockRoot}) - require.NoError(t, err) - assert.Equal(t, true, header.Finalized) - }) - t.Run("false", func(t *testing.T) { - header, err := bs.GetBlockHeader(ctx, ðpbv1.BlockRequest{BlockId: blkContainers[64].BlockRoot}) - require.NoError(t, err) - assert.Equal(t, false, header.Finalized) - }) + resp, err := bs.GetBlockHeader(ctx, ðpbv1.BlockRequest{BlockId: root[:]}) + require.NoError(t, err) + assert.Equal(t, false, resp.Finalized) }) } @@ -1031,1395 +980,391 @@ func TestServer_SubmitBlockSSZ_OK(t *testing.T) { } func TestServer_GetBlock(t *testing.T) { - beaconDB := dbTest.SetupDB(t) ctx := context.Background() - - genBlk, blkContainers := fillDBTestBlocks(ctx, t, beaconDB) - canonicalRoots := make(map[[32]byte]bool) - - for _, bContr := range blkContainers { - canonicalRoots[bytesutil.ToBytes32(bContr.BlockRoot)] = true - } - headBlock := blkContainers[len(blkContainers)-1] - nextSlot := headBlock.GetPhase0Block().Block.Slot + 1 - - b2 := util.NewBeaconBlock() - b2.Block.Slot = 30 - b2.Block.ParentRoot = bytesutil.PadTo([]byte{1}, 32) - util.SaveBlock(t, ctx, beaconDB, b2) - b3 := util.NewBeaconBlock() - b3.Block.Slot = 30 - b3.Block.ParentRoot = bytesutil.PadTo([]byte{4}, 32) - util.SaveBlock(t, ctx, beaconDB, b3) - b4 := util.NewBeaconBlock() - b4.Block.Slot = nextSlot - b4.Block.ParentRoot = bytesutil.PadTo([]byte{8}, 32) - util.SaveBlock(t, ctx, beaconDB, b4) - - wsb, err := blocks.NewSignedBeaconBlock(headBlock.Block.(*ethpbalpha.BeaconBlockContainer_Phase0Block).Phase0Block) + b := util.NewBeaconBlock() + blk, err := blocks.NewSignedBeaconBlock(b) require.NoError(t, err) bs := &Server{ - BeaconDB: beaconDB, - ChainInfoFetcher: &mock.ChainService{ - DB: beaconDB, - Block: wsb, - Root: headBlock.BlockRoot, - FinalizedCheckPoint: ðpbalpha.Checkpoint{Root: blkContainers[64].BlockRoot}, - CanonicalRoots: canonicalRoots, - }, + FinalizationFetcher: &mock.ChainService{}, + BlockFetcher: &testutil.MockBlockFetcher{BlockToReturn: blk}, } - root, err := genBlk.Block.HashTreeRoot() + expected, err := migration.V1Alpha1ToV1SignedBlock(b) require.NoError(t, err) - - tests := []struct { - name string - blockID []byte - want *ethpbalpha.SignedBeaconBlock - wantErr bool - }{ - { - name: "slot", - blockID: []byte("30"), - want: blkContainers[30].Block.(*ethpbalpha.BeaconBlockContainer_Phase0Block).Phase0Block, - }, - { - name: "bad formatting", - blockID: []byte("3bad0"), - wantErr: true, - }, - { - name: "canonical", - blockID: []byte("30"), - want: blkContainers[30].Block.(*ethpbalpha.BeaconBlockContainer_Phase0Block).Phase0Block, - }, - { - name: "non canonical", - blockID: []byte(fmt.Sprintf("%d", nextSlot)), - wantErr: true, - }, - { - name: "head", - blockID: []byte("head"), - want: headBlock.Block.(*ethpbalpha.BeaconBlockContainer_Phase0Block).Phase0Block, - }, - { - name: "finalized", - blockID: []byte("finalized"), - want: blkContainers[64].Block.(*ethpbalpha.BeaconBlockContainer_Phase0Block).Phase0Block, - }, - { - name: "genesis", - blockID: []byte("genesis"), - want: genBlk, - }, - { - name: "genesis root", - blockID: root[:], - want: genBlk, - }, - { - name: "root", - blockID: blkContainers[20].BlockRoot, - want: blkContainers[20].Block.(*ethpbalpha.BeaconBlockContainer_Phase0Block).Phase0Block, - }, - { - name: "non-existent root", - blockID: bytesutil.PadTo([]byte("hi there"), 32), - wantErr: true, - }, - { - name: "no block", - blockID: []byte("105"), - wantErr: true, - }, - } - for _, tt := range tests { - t.Run(tt.name, func(t *testing.T) { - blk, err := bs.GetBlock(ctx, ðpbv1.BlockRequest{ - BlockId: tt.blockID, - }) - if tt.wantErr { - require.NotEqual(t, err, nil, "no error has been returned") - return - } - require.NoError(t, err) - - v1Block, err := migration.V1Alpha1ToV1SignedBlock(tt.want) - require.NoError(t, err) - - if !reflect.DeepEqual(blk.Data.Message, v1Block.Block) { - t.Error("Expected blocks to equal") - } - }) - } + resp, err := bs.GetBlockV2(ctx, ðpbv2.BlockRequestV2{}) + require.NoError(t, err) + phase0Block, ok := resp.Data.Message.(*ethpbv2.SignedBeaconBlockContainer_Phase0Block) + require.Equal(t, true, ok) + assert.DeepEqual(t, expected.Block, phase0Block.Phase0Block) + assert.Equal(t, ethpbv2.Version_PHASE0, resp.Version) } func TestServer_GetBlockV2(t *testing.T) { + ctx := context.Background() + t.Run("Phase 0", func(t *testing.T) { - beaconDB := dbTest.SetupDB(t) - ctx := context.Background() + b := util.NewBeaconBlock() + blk, err := blocks.NewSignedBeaconBlock(b) + require.NoError(t, err) - genBlk, blkContainers := fillDBTestBlocks(ctx, t, beaconDB) - canonicalRoots := make(map[[32]byte]bool) - for _, bContr := range blkContainers { - canonicalRoots[bytesutil.ToBytes32(bContr.BlockRoot)] = true + bs := &Server{ + FinalizationFetcher: &mock.ChainService{}, + BlockFetcher: &testutil.MockBlockFetcher{BlockToReturn: blk}, } - headBlock := blkContainers[len(blkContainers)-1] - nextSlot := headBlock.GetPhase0Block().Block.Slot + 1 - wsb, err := blocks.NewSignedBeaconBlock(headBlock.Block.(*ethpbalpha.BeaconBlockContainer_Phase0Block).Phase0Block) + expected, err := migration.V1Alpha1ToV1SignedBlock(b) + require.NoError(t, err) + resp, err := bs.GetBlockV2(ctx, ðpbv2.BlockRequestV2{}) + require.NoError(t, err) + phase0Block, ok := resp.Data.Message.(*ethpbv2.SignedBeaconBlockContainer_Phase0Block) + require.Equal(t, true, ok) + assert.DeepEqual(t, expected.Block, phase0Block.Phase0Block) + assert.Equal(t, ethpbv2.Version_PHASE0, resp.Version) + }) + t.Run("Altair", func(t *testing.T) { + b := util.NewBeaconBlockAltair() + blk, err := blocks.NewSignedBeaconBlock(b) require.NoError(t, err) - mockChainService := &mock.ChainService{ - DB: beaconDB, - Block: wsb, - Root: headBlock.BlockRoot, - FinalizedCheckPoint: ðpbalpha.Checkpoint{Root: blkContainers[64].BlockRoot}, - CanonicalRoots: canonicalRoots, - FinalizedRoots: map[[32]byte]bool{}, + bs := &Server{ + FinalizationFetcher: &mock.ChainService{}, + BlockFetcher: &testutil.MockBlockFetcher{BlockToReturn: blk}, } + + expected, err := migration.V1Alpha1BeaconBlockAltairToV2(b.Block) + require.NoError(t, err) + resp, err := bs.GetBlockV2(ctx, ðpbv2.BlockRequestV2{}) + require.NoError(t, err) + altairBlock, ok := resp.Data.Message.(*ethpbv2.SignedBeaconBlockContainer_AltairBlock) + require.Equal(t, true, ok) + assert.DeepEqual(t, expected, altairBlock.AltairBlock) + assert.Equal(t, ethpbv2.Version_ALTAIR, resp.Version) + }) + t.Run("Bellatrix", func(t *testing.T) { + b := util.NewBeaconBlockBellatrix() + blk, err := blocks.NewSignedBeaconBlock(b) + require.NoError(t, err) + + mockChainService := &mock.ChainService{} bs := &Server{ - BeaconDB: beaconDB, - ChainInfoFetcher: mockChainService, - HeadFetcher: mockChainService, + FinalizationFetcher: mockChainService, + BlockFetcher: &testutil.MockBlockFetcher{BlockToReturn: blk}, OptimisticModeFetcher: mockChainService, + } + + expected, err := migration.V1Alpha1BeaconBlockBellatrixToV2(b.Block) + require.NoError(t, err) + resp, err := bs.GetBlockV2(ctx, ðpbv2.BlockRequestV2{}) + require.NoError(t, err) + bellatrixBlock, ok := resp.Data.Message.(*ethpbv2.SignedBeaconBlockContainer_BellatrixBlock) + require.Equal(t, true, ok) + assert.DeepEqual(t, expected, bellatrixBlock.BellatrixBlock) + assert.Equal(t, ethpbv2.Version_BELLATRIX, resp.Version) + }) + t.Run("Capella", func(t *testing.T) { + b := util.NewBeaconBlockCapella() + blk, err := blocks.NewSignedBeaconBlock(b) + require.NoError(t, err) + + mockChainService := &mock.ChainService{} + bs := &Server{ FinalizationFetcher: mockChainService, + BlockFetcher: &testutil.MockBlockFetcher{BlockToReturn: blk}, + OptimisticModeFetcher: mockChainService, } - root, err := genBlk.Block.HashTreeRoot() + expected, err := migration.V1Alpha1BeaconBlockCapellaToV2(b.Block) + require.NoError(t, err) + resp, err := bs.GetBlockV2(ctx, ðpbv2.BlockRequestV2{}) + require.NoError(t, err) + capellaBlock, ok := resp.Data.Message.(*ethpbv2.SignedBeaconBlockContainer_CapellaBlock) + require.Equal(t, true, ok) + assert.DeepEqual(t, expected, capellaBlock.CapellaBlock) + assert.Equal(t, ethpbv2.Version_CAPELLA, resp.Version) + }) + t.Run("execution optimistic", func(t *testing.T) { + b := util.NewBeaconBlockBellatrix() + blk, err := blocks.NewSignedBeaconBlock(b) require.NoError(t, err) - tests := []struct { - name string - blockID []byte - want *ethpbalpha.SignedBeaconBlock - wantErr bool - }{ - { - name: "slot", - blockID: []byte("30"), - want: blkContainers[30].Block.(*ethpbalpha.BeaconBlockContainer_Phase0Block).Phase0Block, - }, - { - name: "bad formatting", - blockID: []byte("3bad0"), - wantErr: true, - }, - { - name: "canonical", - blockID: []byte("30"), - want: blkContainers[30].Block.(*ethpbalpha.BeaconBlockContainer_Phase0Block).Phase0Block, - }, - { - name: "non canonical", - blockID: []byte(fmt.Sprintf("%d", nextSlot)), - wantErr: true, - }, - { - name: "head", - blockID: []byte("head"), - want: headBlock.Block.(*ethpbalpha.BeaconBlockContainer_Phase0Block).Phase0Block, - }, - { - name: "finalized", - blockID: []byte("finalized"), - want: blkContainers[64].Block.(*ethpbalpha.BeaconBlockContainer_Phase0Block).Phase0Block, - }, - { - name: "genesis", - blockID: []byte("genesis"), - want: genBlk, - }, - { - name: "genesis root", - blockID: root[:], - want: genBlk, - }, - { - name: "root", - blockID: blkContainers[20].BlockRoot, - want: blkContainers[20].Block.(*ethpbalpha.BeaconBlockContainer_Phase0Block).Phase0Block, - }, - { - name: "non-existent root", - blockID: bytesutil.PadTo([]byte("hi there"), 32), - wantErr: true, - }, - { - name: "no block", - blockID: []byte("105"), - wantErr: true, - }, - } - for _, tt := range tests { - t.Run(tt.name, func(t *testing.T) { - blk, err := bs.GetBlockV2(ctx, ðpbv2.BlockRequestV2{ - BlockId: tt.blockID, - }) - if tt.wantErr { - require.NotEqual(t, err, nil) - return - } - require.NoError(t, err) - - v1Block, err := migration.V1Alpha1ToV1SignedBlock(tt.want) - require.NoError(t, err) - - phase0Block, ok := blk.Data.Message.(*ethpbv2.SignedBeaconBlockContainer_Phase0Block) - require.Equal(t, true, ok) - if !reflect.DeepEqual(phase0Block.Phase0Block, v1Block.Block) { - t.Error("Expected blocks to equal") - } - assert.Equal(t, ethpbv2.Version_PHASE0, blk.Version) - }) - } - }) - - t.Run("Altair", func(t *testing.T) { - beaconDB := dbTest.SetupDB(t) - ctx := context.Background() - - genBlk, blkContainers := fillDBTestBlocksAltair(ctx, t, beaconDB) - canonicalRoots := make(map[[32]byte]bool) - for _, bContr := range blkContainers { - canonicalRoots[bytesutil.ToBytes32(bContr.BlockRoot)] = true - } - headBlock := blkContainers[len(blkContainers)-1] - nextSlot := headBlock.GetAltairBlock().Block.Slot + 1 - - chainBlk, err := blocks.NewSignedBeaconBlock(headBlock.GetAltairBlock()) - require.NoError(t, err) - mockChainService := &mock.ChainService{ - DB: beaconDB, - Block: chainBlk, - Root: headBlock.BlockRoot, - FinalizedCheckPoint: ðpbalpha.Checkpoint{Root: blkContainers[64].BlockRoot}, - CanonicalRoots: canonicalRoots, - FinalizedRoots: map[[32]byte]bool{}, - } - bs := &Server{ - BeaconDB: beaconDB, - ChainInfoFetcher: mockChainService, - HeadFetcher: mockChainService, - OptimisticModeFetcher: mockChainService, - FinalizationFetcher: mockChainService, - } - - root, err := genBlk.Block.HashTreeRoot() - require.NoError(t, err) - - tests := []struct { - name string - blockID []byte - want *ethpbalpha.SignedBeaconBlockAltair - wantErr bool - }{ - { - name: "slot", - blockID: []byte("30"), - want: blkContainers[30].GetAltairBlock(), - }, - { - name: "bad formatting", - blockID: []byte("3bad0"), - wantErr: true, - }, - { - name: "canonical", - blockID: []byte("30"), - want: blkContainers[30].GetAltairBlock(), - }, - { - name: "non canonical", - blockID: []byte(fmt.Sprintf("%d", nextSlot)), - wantErr: true, - }, - { - name: "head", - blockID: []byte("head"), - want: headBlock.GetAltairBlock(), - }, - { - name: "finalized", - blockID: []byte("finalized"), - want: blkContainers[64].GetAltairBlock(), - }, - { - name: "genesis", - blockID: []byte("genesis"), - want: genBlk, - }, - { - name: "genesis root", - blockID: root[:], - want: genBlk, - }, - { - name: "root", - blockID: blkContainers[20].BlockRoot, - want: blkContainers[20].GetAltairBlock(), - }, - { - name: "non-existent root", - blockID: bytesutil.PadTo([]byte("hi there"), 32), - wantErr: true, - }, - { - name: "no block", - blockID: []byte("105"), - wantErr: true, - }, - } - for _, tt := range tests { - t.Run(tt.name, func(t *testing.T) { - blk, err := bs.GetBlockV2(ctx, ðpbv2.BlockRequestV2{ - BlockId: tt.blockID, - }) - if tt.wantErr { - require.NotEqual(t, err, nil) - return - } - require.NoError(t, err) - - v2Block, err := migration.V1Alpha1BeaconBlockAltairToV2(tt.want.Block) - require.NoError(t, err) - - altairBlock, ok := blk.Data.Message.(*ethpbv2.SignedBeaconBlockContainer_AltairBlock) - require.Equal(t, true, ok) - if !reflect.DeepEqual(altairBlock.AltairBlock, v2Block) { - t.Error("Expected blocks to equal") - } - assert.Equal(t, ethpbv2.Version_ALTAIR, blk.Version) - }) - } - }) - - t.Run("Bellatrix", func(t *testing.T) { - beaconDB := dbTest.SetupDB(t) - ctx := context.Background() - - genBlk, blkContainers := fillDBTestBlocksBellatrix(ctx, t, beaconDB) - canonicalRoots := make(map[[32]byte]bool) - for _, bContr := range blkContainers { - canonicalRoots[bytesutil.ToBytes32(bContr.BlockRoot)] = true - } - headBlock := blkContainers[len(blkContainers)-1] - nextSlot := headBlock.GetBellatrixBlock().Block.Slot + 1 - - chainBlk, err := blocks.NewSignedBeaconBlock(headBlock.GetBellatrixBlock()) - require.NoError(t, err) - mockChainService := &mock.ChainService{ - DB: beaconDB, - Block: chainBlk, - Root: headBlock.BlockRoot, - FinalizedCheckPoint: ðpbalpha.Checkpoint{Root: blkContainers[64].BlockRoot}, - CanonicalRoots: canonicalRoots, - FinalizedRoots: map[[32]byte]bool{}, - } - bs := &Server{ - BeaconDB: beaconDB, - ChainInfoFetcher: mockChainService, - HeadFetcher: mockChainService, - OptimisticModeFetcher: mockChainService, - ExecutionPayloadReconstructor: &executionTest.EngineClient{ - ExecutionPayloadByBlockHash: map[[32]byte]*enginev1.ExecutionPayload{}, - }, - FinalizationFetcher: mockChainService, - } - - root, err := genBlk.Block.HashTreeRoot() - require.NoError(t, err) - - tests := []struct { - name string - blockID []byte - want *ethpbalpha.SignedBeaconBlockBellatrix - wantErr bool - }{ - { - name: "slot", - blockID: []byte("30"), - want: blkContainers[30].GetBellatrixBlock(), - }, - { - name: "bad formatting", - blockID: []byte("3bad0"), - wantErr: true, - }, - { - name: "canonical", - blockID: []byte("30"), - want: blkContainers[30].GetBellatrixBlock(), - }, - { - name: "non canonical", - blockID: []byte(fmt.Sprintf("%d", nextSlot)), - wantErr: true, - }, - { - name: "head", - blockID: []byte("head"), - want: headBlock.GetBellatrixBlock(), - }, - { - name: "finalized", - blockID: []byte("finalized"), - want: blkContainers[64].GetBellatrixBlock(), - }, - { - name: "genesis", - blockID: []byte("genesis"), - want: genBlk, - }, - { - name: "genesis root", - blockID: root[:], - want: genBlk, - }, - { - name: "root", - blockID: blkContainers[20].BlockRoot, - want: blkContainers[20].GetBellatrixBlock(), - }, - { - name: "non-existent root", - blockID: bytesutil.PadTo([]byte("hi there"), 32), - wantErr: true, - }, - { - name: "no block", - blockID: []byte("105"), - wantErr: true, - }, - } - for _, tt := range tests { - t.Run(tt.name, func(t *testing.T) { - blk, err := bs.GetBlockV2(ctx, ðpbv2.BlockRequestV2{ - BlockId: tt.blockID, - }) - if tt.wantErr { - require.NotEqual(t, err, nil) - return - } - require.NoError(t, err) - - v2Block, err := migration.V1Alpha1BeaconBlockBellatrixToV2(tt.want.Block) - require.NoError(t, err) - - b, ok := blk.Data.Message.(*ethpbv2.SignedBeaconBlockContainer_BellatrixBlock) - require.Equal(t, true, ok) - if !reflect.DeepEqual(b.BellatrixBlock, v2Block) { - t.Error("Expected blocks to equal") - } - assert.Equal(t, ethpbv2.Version_BELLATRIX, blk.Version) - }) - } - }) - - t.Run("Capella", func(t *testing.T) { - beaconDB := dbTest.SetupDB(t) - ctx := context.Background() - - genBlk, blkContainers := fillDBTestBlocksCapella(ctx, t, beaconDB) - canonicalRoots := make(map[[32]byte]bool) - - for _, bContr := range blkContainers { - canonicalRoots[bytesutil.ToBytes32(bContr.BlockRoot)] = true - } - headBlock := blkContainers[len(blkContainers)-1] - nextSlot := headBlock.GetCapellaBlock().Block.Slot + 1 - - chainBlk, err := blocks.NewSignedBeaconBlock(headBlock.GetCapellaBlock()) - require.NoError(t, err) - mockChainService := &mock.ChainService{ - DB: beaconDB, - Block: chainBlk, - Root: headBlock.BlockRoot, - FinalizedCheckPoint: ðpbalpha.Checkpoint{Root: blkContainers[64].BlockRoot}, - CanonicalRoots: canonicalRoots, - FinalizedRoots: map[[32]byte]bool{}, - } - bs := &Server{ - BeaconDB: beaconDB, - ChainInfoFetcher: mockChainService, - HeadFetcher: mockChainService, - OptimisticModeFetcher: mockChainService, - ExecutionPayloadReconstructor: &executionTest.EngineClient{ - ExecutionPayloadByBlockHash: map[[32]byte]*enginev1.ExecutionPayload{}, - }, - FinalizationFetcher: mockChainService, - } - - root, err := genBlk.Block.HashTreeRoot() - require.NoError(t, err) - - tests := []struct { - name string - blockID []byte - want *ethpbalpha.SignedBeaconBlockCapella - wantErr bool - }{ - { - name: "slot", - blockID: []byte("30"), - want: blkContainers[30].GetCapellaBlock(), - }, - { - name: "bad formatting", - blockID: []byte("3bad0"), - wantErr: true, - }, - { - name: "canonical", - blockID: []byte("30"), - want: blkContainers[30].GetCapellaBlock(), - }, - { - name: "non canonical", - blockID: []byte(fmt.Sprintf("%d", nextSlot)), - wantErr: true, - }, - { - name: "head", - blockID: []byte("head"), - want: headBlock.GetCapellaBlock(), - }, - { - name: "finalized", - blockID: []byte("finalized"), - want: blkContainers[64].GetCapellaBlock(), - }, - { - name: "genesis", - blockID: []byte("genesis"), - want: genBlk, - }, - { - name: "genesis root", - blockID: root[:], - want: genBlk, - }, - { - name: "root", - blockID: blkContainers[20].BlockRoot, - want: blkContainers[20].GetCapellaBlock(), - }, - { - name: "non-existent root", - blockID: bytesutil.PadTo([]byte("hi there"), 32), - wantErr: true, - }, - { - name: "no block", - blockID: []byte("105"), - wantErr: true, - }, - } - for _, tt := range tests { - t.Run(tt.name, func(t *testing.T) { - blk, err := bs.GetBlockV2(ctx, ðpbv2.BlockRequestV2{ - BlockId: tt.blockID, - }) - if tt.wantErr { - require.NotEqual(t, err, nil) - return - } - require.NoError(t, err) - - v2Block, err := migration.V1Alpha1BeaconBlockCapellaToV2(tt.want.Block) - require.NoError(t, err) - - b, ok := blk.Data.Message.(*ethpbv2.SignedBeaconBlockContainer_CapellaBlock) - require.Equal(t, true, ok) - if !reflect.DeepEqual(b.CapellaBlock, v2Block) { - t.Error("Expected blocks to equal") - } - assert.Equal(t, ethpbv2.Version_CAPELLA, blk.Version) - }) - } - }) - - t.Run("execution optimistic", func(t *testing.T) { - beaconDB := dbTest.SetupDB(t) - ctx := context.Background() - - _, blkContainers := fillDBTestBlocksBellatrix(ctx, t, beaconDB) - headBlock := blkContainers[len(blkContainers)-1] - - chainBlk, err := blocks.NewSignedBeaconBlock(headBlock.GetBellatrixBlock()) - require.NoError(t, err) - mockChainService := &mock.ChainService{ - DB: beaconDB, - Block: chainBlk, - Root: headBlock.BlockRoot, - FinalizedCheckPoint: ðpbalpha.Checkpoint{Root: blkContainers[64].BlockRoot}, - Optimistic: true, - FinalizedRoots: map[[32]byte]bool{}, - } - bs := &Server{ - BeaconDB: beaconDB, - ChainInfoFetcher: mockChainService, - HeadFetcher: mockChainService, - OptimisticModeFetcher: mockChainService, - FinalizationFetcher: mockChainService, - } - - blk, err := bs.GetBlockV2(ctx, ðpbv2.BlockRequestV2{ - BlockId: []byte("head"), - }) - require.NoError(t, err) - assert.Equal(t, true, blk.ExecutionOptimistic) - }) - - t.Run("finalized", func(t *testing.T) { - beaconDB := dbTest.SetupDB(t) - ctx := context.Background() - - _, blkContainers := fillDBTestBlocks(ctx, t, beaconDB) - headBlock := blkContainers[len(blkContainers)-1] - - chainBlk, err := blocks.NewSignedBeaconBlock(headBlock.GetPhase0Block()) - require.NoError(t, err) - mockChainService := &mock.ChainService{ - DB: beaconDB, - Block: chainBlk, - Root: headBlock.BlockRoot, - FinalizedCheckPoint: ðpbalpha.Checkpoint{Root: blkContainers[64].BlockRoot}, - Optimistic: true, - FinalizedRoots: map[[32]byte]bool{ - bytesutil.ToBytes32(blkContainers[32].BlockRoot): true, - bytesutil.ToBytes32(blkContainers[64].BlockRoot): false, - }, - } - bs := &Server{ - BeaconDB: beaconDB, - ChainInfoFetcher: mockChainService, - HeadFetcher: mockChainService, - OptimisticModeFetcher: mockChainService, - FinalizationFetcher: mockChainService, - } - - t.Run("true", func(t *testing.T) { - blk, err := bs.GetBlockV2(ctx, ðpbv2.BlockRequestV2{ - BlockId: []byte("32"), - }) - require.NoError(t, err) - assert.Equal(t, true, blk.Finalized) - }) - t.Run("false", func(t *testing.T) { - blk, err := bs.GetBlockV2(ctx, ðpbv2.BlockRequestV2{ - BlockId: []byte("64"), - }) - require.NoError(t, err) - assert.Equal(t, false, blk.Finalized) - }) - }) -} - -func TestServer_GetBlockSSZ(t *testing.T) { - beaconDB := dbTest.SetupDB(t) - ctx := context.Background() - - _, blkContainers := fillDBTestBlocks(ctx, t, beaconDB) - headBlock := blkContainers[len(blkContainers)-1] - - b2 := util.NewBeaconBlock() - b2.Block.Slot = 30 - b2.Block.ParentRoot = bytesutil.PadTo([]byte{1}, 32) - util.SaveBlock(t, ctx, beaconDB, b2) - - wsb, err := blocks.NewSignedBeaconBlock(headBlock.Block.(*ethpbalpha.BeaconBlockContainer_Phase0Block).Phase0Block) - require.NoError(t, err) - - bs := &Server{ - BeaconDB: beaconDB, - ChainInfoFetcher: &mock.ChainService{ - DB: beaconDB, - Block: wsb, - Root: headBlock.BlockRoot, - FinalizedCheckPoint: ðpbalpha.Checkpoint{Root: blkContainers[64].BlockRoot}, - }, - } - - blks, err := beaconDB.BlocksBySlot(ctx, 30) - require.Equal(t, true, len(blks) > 0) - require.NoError(t, err) - sszBlock, err := blks[0].MarshalSSZ() - require.NoError(t, err) - - resp, err := bs.GetBlockSSZ(ctx, ðpbv1.BlockRequest{BlockId: []byte("30")}) - require.NoError(t, err) - assert.NotNil(t, resp) - assert.DeepEqual(t, sszBlock, resp.Data) -} - -func TestServer_GetBlockSSZV2(t *testing.T) { - t.Run("Phase 0", func(t *testing.T) { - beaconDB := dbTest.SetupDB(t) - ctx := context.Background() - - _, blkContainers := fillDBTestBlocks(ctx, t, beaconDB) - headBlock := blkContainers[len(blkContainers)-1] - wsb, err := blocks.NewSignedBeaconBlock(headBlock.Block.(*ethpbalpha.BeaconBlockContainer_Phase0Block).Phase0Block) - require.NoError(t, err) - mockChainService := &mock.ChainService{ - DB: beaconDB, - Block: wsb, - Root: headBlock.BlockRoot, - FinalizedCheckPoint: ðpbalpha.Checkpoint{Root: blkContainers[64].BlockRoot}, - FinalizedRoots: map[[32]byte]bool{}, - } - bs := &Server{ - BeaconDB: beaconDB, - ChainInfoFetcher: mockChainService, - FinalizationFetcher: mockChainService, - } - - blks, err := beaconDB.BlocksBySlot(ctx, 30) - require.Equal(t, true, len(blks) > 0) - require.NoError(t, err) - sszBlock, err := blks[0].MarshalSSZ() - require.NoError(t, err) - - resp, err := bs.GetBlockSSZV2(ctx, ðpbv2.BlockRequestV2{BlockId: []byte("30")}) - require.NoError(t, err) - assert.NotNil(t, resp) - assert.DeepEqual(t, sszBlock, resp.Data) - assert.Equal(t, ethpbv2.Version_PHASE0, resp.Version) - }) - - t.Run("Altair", func(t *testing.T) { - beaconDB := dbTest.SetupDB(t) - ctx := context.Background() - - _, blkContainers := fillDBTestBlocksAltair(ctx, t, beaconDB) - headBlock := blkContainers[len(blkContainers)-1] - chainBlk, err := blocks.NewSignedBeaconBlock(headBlock.GetAltairBlock()) - require.NoError(t, err) - mockChainService := &mock.ChainService{ - DB: beaconDB, - Block: chainBlk, - Root: headBlock.BlockRoot, - FinalizedCheckPoint: ðpbalpha.Checkpoint{Root: blkContainers[64].BlockRoot}, - FinalizedRoots: map[[32]byte]bool{}, - } - bs := &Server{ - BeaconDB: beaconDB, - ChainInfoFetcher: mockChainService, - FinalizationFetcher: mockChainService, - } - - blks, err := beaconDB.BlocksBySlot(ctx, 30) - require.Equal(t, true, len(blks) > 0) - require.NoError(t, err) - sszBlock, err := blks[0].MarshalSSZ() - require.NoError(t, err) - - resp, err := bs.GetBlockSSZV2(ctx, ðpbv2.BlockRequestV2{BlockId: []byte("30")}) - require.NoError(t, err) - assert.NotNil(t, resp) - assert.DeepEqual(t, sszBlock, resp.Data) - assert.Equal(t, ethpbv2.Version_ALTAIR, resp.Version) - }) - - t.Run("Bellatrix", func(t *testing.T) { - beaconDB := dbTest.SetupDB(t) - ctx := context.Background() - - _, blkContainers := fillDBTestBlocksBellatrix(ctx, t, beaconDB) - headBlock := blkContainers[len(blkContainers)-1] - chainBlk, err := blocks.NewSignedBeaconBlock(headBlock.GetBellatrixBlock()) - require.NoError(t, err) - mockChainService := &mock.ChainService{ - DB: beaconDB, - Block: chainBlk, - Root: headBlock.BlockRoot, - FinalizedCheckPoint: ðpbalpha.Checkpoint{Root: blkContainers[64].BlockRoot}, - FinalizedRoots: map[[32]byte]bool{}, - } - bs := &Server{ - BeaconDB: beaconDB, - ChainInfoFetcher: mockChainService, - OptimisticModeFetcher: mockChainService, - FinalizationFetcher: mockChainService, - } - - blks, err := beaconDB.BlocksBySlot(ctx, 30) - require.Equal(t, true, len(blks) > 0) - require.NoError(t, err) - sszBlock, err := blks[0].MarshalSSZ() - require.NoError(t, err) - - resp, err := bs.GetBlockSSZV2(ctx, ðpbv2.BlockRequestV2{BlockId: []byte("30")}) - require.NoError(t, err) - assert.NotNil(t, resp) - assert.DeepEqual(t, sszBlock, resp.Data) - assert.Equal(t, ethpbv2.Version_BELLATRIX, resp.Version) - }) - - t.Run("Capella", func(t *testing.T) { - beaconDB := dbTest.SetupDB(t) - ctx := context.Background() - - _, blkContainers := fillDBTestBlocksCapella(ctx, t, beaconDB) - headBlock := blkContainers[len(blkContainers)-1] - chainBlk, err := blocks.NewSignedBeaconBlock(headBlock.GetCapellaBlock()) - require.NoError(t, err) - mockChainService := &mock.ChainService{ - DB: beaconDB, - Block: chainBlk, - Root: headBlock.BlockRoot, - FinalizedCheckPoint: ðpbalpha.Checkpoint{Root: blkContainers[64].BlockRoot}, - FinalizedRoots: map[[32]byte]bool{}, - } - bs := &Server{ - BeaconDB: beaconDB, - ChainInfoFetcher: mockChainService, - OptimisticModeFetcher: mockChainService, - FinalizationFetcher: mockChainService, - } - - blks, err := beaconDB.BlocksBySlot(ctx, 30) - require.Equal(t, true, len(blks) > 0) - require.NoError(t, err) - sszBlock, err := blks[0].MarshalSSZ() - require.NoError(t, err) - - resp, err := bs.GetBlockSSZV2(ctx, ðpbv2.BlockRequestV2{BlockId: []byte("30")}) - require.NoError(t, err) - assert.NotNil(t, resp) - assert.DeepEqual(t, sszBlock, resp.Data) - assert.Equal(t, ethpbv2.Version_CAPELLA, resp.Version) - }) - - t.Run("execution optimistic", func(t *testing.T) { - beaconDB := dbTest.SetupDB(t) - ctx := context.Background() - - _, blkContainers := fillDBTestBlocksBellatrix(ctx, t, beaconDB) - headBlock := blkContainers[len(blkContainers)-1] - - chainBlk, err := blocks.NewSignedBeaconBlock(headBlock.GetBellatrixBlock()) - require.NoError(t, err) - mockChainService := &mock.ChainService{ - DB: beaconDB, - Block: chainBlk, - Root: headBlock.BlockRoot, - FinalizedCheckPoint: ðpbalpha.Checkpoint{Root: blkContainers[64].BlockRoot}, - Optimistic: true, - FinalizedRoots: map[[32]byte]bool{}, - } - bs := &Server{ - BeaconDB: beaconDB, - ChainInfoFetcher: mockChainService, - HeadFetcher: mockChainService, - OptimisticModeFetcher: mockChainService, - FinalizationFetcher: mockChainService, - } - - blk, err := bs.GetBlockSSZV2(ctx, ðpbv2.BlockRequestV2{ - BlockId: []byte("head"), - }) - require.NoError(t, err) - assert.Equal(t, true, blk.ExecutionOptimistic) - }) - - t.Run("finalized", func(t *testing.T) { - beaconDB := dbTest.SetupDB(t) - ctx := context.Background() - - _, blkContainers := fillDBTestBlocks(ctx, t, beaconDB) - headBlock := blkContainers[len(blkContainers)-1] - - chainBlk, err := blocks.NewSignedBeaconBlock(headBlock.GetPhase0Block()) - require.NoError(t, err) mockChainService := &mock.ChainService{ - DB: beaconDB, - Block: chainBlk, - Root: headBlock.BlockRoot, - FinalizedCheckPoint: ðpbalpha.Checkpoint{Root: blkContainers[64].BlockRoot}, - Optimistic: true, - FinalizedRoots: map[[32]byte]bool{ - bytesutil.ToBytes32(blkContainers[32].BlockRoot): true, - bytesutil.ToBytes32(blkContainers[64].BlockRoot): false, - }, - } - bs := &Server{ - BeaconDB: beaconDB, - ChainInfoFetcher: mockChainService, - HeadFetcher: mockChainService, - OptimisticModeFetcher: mockChainService, - FinalizationFetcher: mockChainService, - } - - t.Run("true", func(t *testing.T) { - blk, err := bs.GetBlockV2(ctx, ðpbv2.BlockRequestV2{ - BlockId: []byte("32"), - }) - require.NoError(t, err) - assert.Equal(t, true, blk.Finalized) - }) - t.Run("false", func(t *testing.T) { - blk, err := bs.GetBlockV2(ctx, ðpbv2.BlockRequestV2{ - BlockId: []byte("64"), - }) - require.NoError(t, err) - assert.Equal(t, false, blk.Finalized) - }) - }) -} - -func TestServer_GetBlockRoot(t *testing.T) { - beaconDB := dbTest.SetupDB(t) - ctx := context.Background() - - genBlk, blkContainers := fillDBTestBlocks(ctx, t, beaconDB) - headBlock := blkContainers[len(blkContainers)-1] - - t.Run("get root", func(t *testing.T) { - wsb, err := blocks.NewSignedBeaconBlock(headBlock.Block.(*ethpbalpha.BeaconBlockContainer_Phase0Block).Phase0Block) - require.NoError(t, err) - mockChainFetcher := &mock.ChainService{ - DB: beaconDB, - Block: wsb, - Root: headBlock.BlockRoot, - FinalizedCheckPoint: ðpbalpha.Checkpoint{Root: blkContainers[64].BlockRoot}, - FinalizedRoots: map[[32]byte]bool{}, - } - bs := &Server{ - BeaconDB: beaconDB, - ChainInfoFetcher: mockChainFetcher, - HeadFetcher: mockChainFetcher, - OptimisticModeFetcher: mockChainFetcher, - FinalizationFetcher: mockChainFetcher, - } - - root, err := genBlk.Block.HashTreeRoot() - require.NoError(t, err) - - tests := []struct { - name string - blockID []byte - want []byte - wantErr bool - }{ - { - name: "bad formatting", - blockID: []byte("3bad0"), - wantErr: true, - }, - { - name: "canonical slot", - blockID: []byte("30"), - want: blkContainers[30].BlockRoot, - }, - { - name: "head", - blockID: []byte("head"), - want: headBlock.BlockRoot, - }, - { - name: "finalized", - blockID: []byte("finalized"), - want: blkContainers[64].BlockRoot, - }, - { - name: "genesis", - blockID: []byte("genesis"), - want: root[:], - }, - { - name: "genesis root", - blockID: root[:], - want: root[:], - }, - { - name: "root", - blockID: blkContainers[20].BlockRoot, - want: blkContainers[20].BlockRoot, - }, - { - name: "non-existent root", - blockID: bytesutil.PadTo([]byte("hi there"), 32), - wantErr: true, - }, - { - name: "slot", - blockID: []byte("40"), - want: blkContainers[40].BlockRoot, - }, - { - name: "no block", - blockID: []byte("105"), - wantErr: true, - }, + Optimistic: true, } - for _, tt := range tests { - t.Run(tt.name, func(t *testing.T) { - blockRootResp, err := bs.GetBlockRoot(ctx, ðpbv1.BlockRequest{ - BlockId: tt.blockID, - }) - if tt.wantErr { - require.NotEqual(t, err, nil) - return - } - require.NoError(t, err) - assert.DeepEqual(t, tt.want, blockRootResp.Data.Root) - }) + bs := &Server{ + FinalizationFetcher: mockChainService, + BlockFetcher: &testutil.MockBlockFetcher{BlockToReturn: blk}, + OptimisticModeFetcher: mockChainService, } - }) - t.Run("execution optimistic", func(t *testing.T) { - wsb, err := blocks.NewSignedBeaconBlock(headBlock.Block.(*ethpbalpha.BeaconBlockContainer_Phase0Block).Phase0Block) + resp, err := bs.GetBlockV2(ctx, ðpbv2.BlockRequestV2{}) require.NoError(t, err) - mockChainFetcher := &mock.ChainService{ - DB: beaconDB, - Block: wsb, - Root: headBlock.BlockRoot, - FinalizedCheckPoint: ðpbalpha.Checkpoint{Root: blkContainers[64].BlockRoot}, - Optimistic: true, - FinalizedRoots: map[[32]byte]bool{}, + assert.Equal(t, true, resp.ExecutionOptimistic) + }) + t.Run("finalized", func(t *testing.T) { + b := util.NewBeaconBlock() + blk, err := blocks.NewSignedBeaconBlock(b) + require.NoError(t, err) + root, err := blk.Block().HashTreeRoot() + require.NoError(t, err) + + mockChainService := &mock.ChainService{ + FinalizedRoots: map[[32]byte]bool{root: true}, } bs := &Server{ - BeaconDB: beaconDB, - ChainInfoFetcher: mockChainFetcher, - HeadFetcher: mockChainFetcher, - OptimisticModeFetcher: mockChainFetcher, - FinalizationFetcher: mockChainFetcher, + FinalizationFetcher: mockChainService, + BlockFetcher: &testutil.MockBlockFetcher{BlockToReturn: blk}, } - blockRootResp, err := bs.GetBlockRoot(ctx, ðpbv1.BlockRequest{ - BlockId: []byte("head"), - }) + + resp, err := bs.GetBlockV2(ctx, ðpbv2.BlockRequestV2{BlockId: root[:]}) require.NoError(t, err) - assert.Equal(t, true, blockRootResp.ExecutionOptimistic) + assert.Equal(t, true, resp.Finalized) }) - - t.Run("finalized", func(t *testing.T) { - wsb, err := blocks.NewSignedBeaconBlock(headBlock.Block.(*ethpbalpha.BeaconBlockContainer_Phase0Block).Phase0Block) + t.Run("not finalized", func(t *testing.T) { + b := util.NewBeaconBlock() + blk, err := blocks.NewSignedBeaconBlock(b) require.NoError(t, err) - mockChainFetcher := &mock.ChainService{ - DB: beaconDB, - Block: wsb, - Root: headBlock.BlockRoot, - FinalizedCheckPoint: ðpbalpha.Checkpoint{Root: blkContainers[64].BlockRoot}, - Optimistic: true, - FinalizedRoots: map[[32]byte]bool{ - bytesutil.ToBytes32(blkContainers[32].BlockRoot): true, - bytesutil.ToBytes32(blkContainers[64].BlockRoot): false, - }, + root, err := blk.Block().HashTreeRoot() + require.NoError(t, err) + + mockChainService := &mock.ChainService{ + FinalizedRoots: map[[32]byte]bool{root: false}, } bs := &Server{ - BeaconDB: beaconDB, - ChainInfoFetcher: mockChainFetcher, - HeadFetcher: mockChainFetcher, - OptimisticModeFetcher: mockChainFetcher, - FinalizationFetcher: mockChainFetcher, + FinalizationFetcher: mockChainService, + BlockFetcher: &testutil.MockBlockFetcher{BlockToReturn: blk}, } - t.Run("true", func(t *testing.T) { - blockRootResp, err := bs.GetBlockRoot(ctx, ðpbv1.BlockRequest{ - BlockId: []byte("32"), - }) - require.NoError(t, err) - assert.Equal(t, true, blockRootResp.Finalized) - }) - t.Run("false", func(t *testing.T) { - blockRootResp, err := bs.GetBlockRoot(ctx, ðpbv1.BlockRequest{ - BlockId: []byte("64"), - }) - require.NoError(t, err) - assert.Equal(t, false, blockRootResp.Finalized) - }) + resp, err := bs.GetBlockV2(ctx, ðpbv2.BlockRequestV2{BlockId: root[:]}) + require.NoError(t, err) + assert.Equal(t, false, resp.Finalized) }) } -func TestServer_ListBlockAttestations(t *testing.T) { - t.Run("Phase 0", func(t *testing.T) { - beaconDB := dbTest.SetupDB(t) - ctx := context.Background() +func TestServer_GetBlockSSZ(t *testing.T) { + ctx := context.Background() + b := util.NewBeaconBlock() + blk, err := blocks.NewSignedBeaconBlock(b) + require.NoError(t, err) - _, blkContainers := fillDBTestBlocks(ctx, t, beaconDB) - headBlock := blkContainers[len(blkContainers)-1] - wsb, err := blocks.NewSignedBeaconBlock(headBlock.Block.(*ethpbalpha.BeaconBlockContainer_Phase0Block).Phase0Block) - require.NoError(t, err) - mockChainService := &mock.ChainService{ - DB: beaconDB, - Block: wsb, - Root: headBlock.BlockRoot, - FinalizedCheckPoint: ðpbalpha.Checkpoint{Root: blkContainers[64].BlockRoot}, - FinalizedRoots: map[[32]byte]bool{}, - } - bs := &Server{ - BeaconDB: beaconDB, - ChainInfoFetcher: mockChainService, - HeadFetcher: mockChainService, - OptimisticModeFetcher: mockChainService, - FinalizationFetcher: mockChainService, - } + bs := &Server{ + FinalizationFetcher: &mock.ChainService{}, + BlockFetcher: &testutil.MockBlockFetcher{BlockToReturn: blk}, + } - genBlk, blkContainers := fillDBTestBlocks(ctx, t, beaconDB) - root, err := genBlk.Block.HashTreeRoot() + expected, err := blk.MarshalSSZ() + require.NoError(t, err) + resp, err := bs.GetBlockSSZ(ctx, ðpbv1.BlockRequest{}) + require.NoError(t, err) + assert.NotNil(t, resp) + assert.DeepEqual(t, expected, resp.Data) +} + +func TestServer_GetBlockSSZV2(t *testing.T) { + ctx := context.Background() + + t.Run("Phase 0", func(t *testing.T) { + b := util.NewBeaconBlock() + blk, err := blocks.NewSignedBeaconBlock(b) require.NoError(t, err) - tests := []struct { - name string - blockID []byte - want *ethpbalpha.SignedBeaconBlock - wantErr bool - }{ - { - name: "slot", - blockID: []byte("30"), - want: blkContainers[30].Block.(*ethpbalpha.BeaconBlockContainer_Phase0Block).Phase0Block, - }, - { - name: "bad formatting", - blockID: []byte("3bad0"), - wantErr: true, - }, - { - name: "head", - blockID: []byte("head"), - want: headBlock.Block.(*ethpbalpha.BeaconBlockContainer_Phase0Block).Phase0Block, - }, - { - name: "finalized", - blockID: []byte("finalized"), - want: blkContainers[64].Block.(*ethpbalpha.BeaconBlockContainer_Phase0Block).Phase0Block, - }, - { - name: "genesis", - blockID: []byte("genesis"), - want: genBlk, - }, - { - name: "genesis root", - blockID: root[:], - want: genBlk, - }, - { - name: "root", - blockID: blkContainers[20].BlockRoot, - want: blkContainers[20].Block.(*ethpbalpha.BeaconBlockContainer_Phase0Block).Phase0Block, - }, - { - name: "non-existent root", - blockID: bytesutil.PadTo([]byte("hi there"), 32), - wantErr: true, - }, - { - name: "slot", - blockID: []byte("40"), - want: blkContainers[40].Block.(*ethpbalpha.BeaconBlockContainer_Phase0Block).Phase0Block, - }, - { - name: "no block", - blockID: []byte("105"), - wantErr: true, - }, + bs := &Server{ + FinalizationFetcher: &mock.ChainService{}, + BlockFetcher: &testutil.MockBlockFetcher{BlockToReturn: blk}, } - for _, tt := range tests { - t.Run(tt.name, func(t *testing.T) { - blk, err := bs.ListBlockAttestations(ctx, ðpbv1.BlockRequest{ - BlockId: tt.blockID, - }) - if tt.wantErr { - require.NotEqual(t, err, nil) - return - } - require.NoError(t, err) - v1Block, err := migration.V1Alpha1ToV1SignedBlock(tt.want) - require.NoError(t, err) - blkAtts := blk.Data - if len(blkAtts) == 0 { - blkAtts = nil - } - if !reflect.DeepEqual(blkAtts, v1Block.Block.Body.Attestations) { - t.Error("Expected attestations to equal") - } - }) - } + expected, err := blk.MarshalSSZ() + require.NoError(t, err) + resp, err := bs.GetBlockSSZV2(ctx, ðpbv2.BlockRequestV2{}) + require.NoError(t, err) + assert.NotNil(t, resp) + assert.DeepEqual(t, expected, resp.Data) + assert.Equal(t, ethpbv2.Version_PHASE0, resp.Version) }) - t.Run("Altair", func(t *testing.T) { - beaconDB := dbTest.SetupDB(t) - ctx := context.Background() - - _, blkContainers := fillDBTestBlocksAltair(ctx, t, beaconDB) - headBlock := blkContainers[len(blkContainers)-1] - blk, err := blocks.NewSignedBeaconBlock(headBlock.Block.(*ethpbalpha.BeaconBlockContainer_AltairBlock).AltairBlock) + b := util.NewBeaconBlockAltair() + blk, err := blocks.NewSignedBeaconBlock(b) require.NoError(t, err) - mockChainService := &mock.ChainService{ - DB: beaconDB, - Block: blk, - Root: headBlock.BlockRoot, - FinalizedCheckPoint: ðpbalpha.Checkpoint{Root: blkContainers[64].BlockRoot}, - FinalizedRoots: map[[32]byte]bool{}, - } + bs := &Server{ - BeaconDB: beaconDB, - ChainInfoFetcher: mockChainService, - HeadFetcher: mockChainService, - OptimisticModeFetcher: mockChainService, - FinalizationFetcher: mockChainService, + FinalizationFetcher: &mock.ChainService{}, + BlockFetcher: &testutil.MockBlockFetcher{BlockToReturn: blk}, } - genBlk, blkContainers := fillDBTestBlocksAltair(ctx, t, beaconDB) - root, err := genBlk.Block.HashTreeRoot() + expected, err := blk.MarshalSSZ() + require.NoError(t, err) + resp, err := bs.GetBlockSSZV2(ctx, ðpbv2.BlockRequestV2{}) + require.NoError(t, err) + assert.NotNil(t, resp) + assert.DeepEqual(t, expected, resp.Data) + assert.Equal(t, ethpbv2.Version_ALTAIR, resp.Version) + }) + t.Run("Bellatrix", func(t *testing.T) { + b := util.NewBeaconBlockBellatrix() + blk, err := blocks.NewSignedBeaconBlock(b) require.NoError(t, err) - tests := []struct { - name string - blockID []byte - want *ethpbalpha.SignedBeaconBlockAltair - wantErr bool - }{ - { - name: "slot", - blockID: []byte("30"), - want: blkContainers[30].Block.(*ethpbalpha.BeaconBlockContainer_AltairBlock).AltairBlock, - }, - { - name: "bad formatting", - blockID: []byte("3bad0"), - wantErr: true, - }, - { - name: "head", - blockID: []byte("head"), - want: headBlock.Block.(*ethpbalpha.BeaconBlockContainer_AltairBlock).AltairBlock, - }, - { - name: "finalized", - blockID: []byte("finalized"), - want: blkContainers[64].Block.(*ethpbalpha.BeaconBlockContainer_AltairBlock).AltairBlock, - }, - { - name: "genesis", - blockID: []byte("genesis"), - want: genBlk, - }, - { - name: "genesis root", - blockID: root[:], - want: genBlk, - }, - { - name: "root", - blockID: blkContainers[20].BlockRoot, - want: blkContainers[20].Block.(*ethpbalpha.BeaconBlockContainer_AltairBlock).AltairBlock, - }, - { - name: "non-existent root", - blockID: bytesutil.PadTo([]byte("hi there"), 32), - wantErr: true, - }, - { - name: "slot", - blockID: []byte("40"), - want: blkContainers[40].Block.(*ethpbalpha.BeaconBlockContainer_AltairBlock).AltairBlock, - }, - { - name: "no block", - blockID: []byte("105"), - wantErr: true, - }, + mockChainService := &mock.ChainService{} + bs := &Server{ + FinalizationFetcher: mockChainService, + BlockFetcher: &testutil.MockBlockFetcher{BlockToReturn: blk}, + OptimisticModeFetcher: mockChainService, } - for _, tt := range tests { - t.Run(tt.name, func(t *testing.T) { - blk, err := bs.ListBlockAttestations(ctx, ðpbv1.BlockRequest{ - BlockId: tt.blockID, - }) - if tt.wantErr { - require.NotEqual(t, err, nil) - return - } - require.NoError(t, err) - v1Block, err := migration.V1Alpha1BeaconBlockAltairToV2(tt.want.Block) - require.NoError(t, err) + expected, err := blk.MarshalSSZ() + require.NoError(t, err) + resp, err := bs.GetBlockSSZV2(ctx, ðpbv2.BlockRequestV2{}) + require.NoError(t, err) + assert.NotNil(t, resp) + assert.DeepEqual(t, expected, resp.Data) + assert.Equal(t, ethpbv2.Version_BELLATRIX, resp.Version) + }) + t.Run("Capella", func(t *testing.T) { + b := util.NewBeaconBlockCapella() + blk, err := blocks.NewSignedBeaconBlock(b) + require.NoError(t, err) - blkAtts := blk.Data - if len(blkAtts) == 0 { - blkAtts = nil - } - if !reflect.DeepEqual(blkAtts, v1Block.Body.Attestations) { - t.Error("Expected attestations to equal") - } - }) + mockChainService := &mock.ChainService{} + bs := &Server{ + FinalizationFetcher: mockChainService, + BlockFetcher: &testutil.MockBlockFetcher{BlockToReturn: blk}, + OptimisticModeFetcher: mockChainService, + } + + expected, err := blk.MarshalSSZ() + require.NoError(t, err) + resp, err := bs.GetBlockSSZV2(ctx, ðpbv2.BlockRequestV2{}) + require.NoError(t, err) + assert.NotNil(t, resp) + assert.DeepEqual(t, expected, resp.Data) + assert.Equal(t, ethpbv2.Version_CAPELLA, resp.Version) + }) + t.Run("execution optimistic", func(t *testing.T) { + b := util.NewBeaconBlockBellatrix() + blk, err := blocks.NewSignedBeaconBlock(b) + require.NoError(t, err) + + mockChainService := &mock.ChainService{ + Optimistic: true, + } + bs := &Server{ + FinalizationFetcher: mockChainService, + BlockFetcher: &testutil.MockBlockFetcher{BlockToReturn: blk}, + OptimisticModeFetcher: mockChainService, } + + resp, err := bs.GetBlockSSZV2(ctx, ðpbv2.BlockRequestV2{}) + require.NoError(t, err) + assert.Equal(t, true, resp.ExecutionOptimistic) }) + t.Run("finalized", func(t *testing.T) { + b := util.NewBeaconBlock() + blk, err := blocks.NewSignedBeaconBlock(b) + require.NoError(t, err) + root, err := blk.Block().HashTreeRoot() + require.NoError(t, err) - t.Run("Bellatrix", func(t *testing.T) { - beaconDB := dbTest.SetupDB(t) - ctx := context.Background() + mockChainService := &mock.ChainService{ + FinalizedRoots: map[[32]byte]bool{root: true}, + } + bs := &Server{ + FinalizationFetcher: mockChainService, + BlockFetcher: &testutil.MockBlockFetcher{BlockToReturn: blk}, + } - _, blkContainers := fillDBTestBlocksBellatrix(ctx, t, beaconDB) - headBlock := blkContainers[len(blkContainers)-1] - blk, err := blocks.NewSignedBeaconBlock(headBlock.Block.(*ethpbalpha.BeaconBlockContainer_BellatrixBlock).BellatrixBlock) + resp, err := bs.GetBlockSSZV2(ctx, ðpbv2.BlockRequestV2{BlockId: root[:]}) + require.NoError(t, err) + assert.Equal(t, true, resp.Finalized) + }) + t.Run("not finalized", func(t *testing.T) { + b := util.NewBeaconBlock() + blk, err := blocks.NewSignedBeaconBlock(b) + require.NoError(t, err) + root, err := blk.Block().HashTreeRoot() require.NoError(t, err) + mockChainService := &mock.ChainService{ + FinalizedRoots: map[[32]byte]bool{root: false}, + } + bs := &Server{ + FinalizationFetcher: mockChainService, + BlockFetcher: &testutil.MockBlockFetcher{BlockToReturn: blk}, + } + + resp, err := bs.GetBlockSSZV2(ctx, ðpbv2.BlockRequestV2{BlockId: root[:]}) + require.NoError(t, err) + assert.Equal(t, false, resp.Finalized) + }) +} + +func TestServer_GetBlockRoot(t *testing.T) { + beaconDB := dbTest.SetupDB(t) + ctx := context.Background() + + genBlk, blkContainers := fillDBTestBlocks(ctx, t, beaconDB) + headBlock := blkContainers[len(blkContainers)-1] + + t.Run("get root", func(t *testing.T) { + wsb, err := blocks.NewSignedBeaconBlock(headBlock.Block.(*ethpbalpha.BeaconBlockContainer_Phase0Block).Phase0Block) + require.NoError(t, err) + mockChainFetcher := &mock.ChainService{ DB: beaconDB, - Block: blk, + Block: wsb, Root: headBlock.BlockRoot, FinalizedCheckPoint: ðpbalpha.Checkpoint{Root: blkContainers[64].BlockRoot}, FinalizedRoots: map[[32]byte]bool{}, } bs := &Server{ BeaconDB: beaconDB, - ChainInfoFetcher: mockChainService, - HeadFetcher: mockChainService, - OptimisticModeFetcher: mockChainService, - FinalizationFetcher: mockChainService, + ChainInfoFetcher: mockChainFetcher, + HeadFetcher: mockChainFetcher, + OptimisticModeFetcher: mockChainFetcher, + FinalizationFetcher: mockChainFetcher, } - genBlk, blkContainers := fillDBTestBlocksBellatrix(ctx, t, beaconDB) root, err := genBlk.Block.HashTreeRoot() require.NoError(t, err) tests := []struct { name string blockID []byte - want *ethpbalpha.SignedBeaconBlockBellatrix + want []byte wantErr bool }{ - { - name: "slot", - blockID: []byte("30"), - want: blkContainers[30].Block.(*ethpbalpha.BeaconBlockContainer_BellatrixBlock).BellatrixBlock, - }, { name: "bad formatting", blockID: []byte("3bad0"), wantErr: true, }, + { + name: "canonical slot", + blockID: []byte("30"), + want: blkContainers[30].BlockRoot, + }, { name: "head", blockID: []byte("head"), - want: headBlock.Block.(*ethpbalpha.BeaconBlockContainer_BellatrixBlock).BellatrixBlock, + want: headBlock.BlockRoot, }, { name: "finalized", blockID: []byte("finalized"), - want: blkContainers[64].Block.(*ethpbalpha.BeaconBlockContainer_BellatrixBlock).BellatrixBlock, + want: blkContainers[64].BlockRoot, }, { name: "genesis", blockID: []byte("genesis"), - want: genBlk, + want: root[:], }, { name: "genesis root", blockID: root[:], - want: genBlk, + want: root[:], }, { name: "root", blockID: blkContainers[20].BlockRoot, - want: blkContainers[20].Block.(*ethpbalpha.BeaconBlockContainer_BellatrixBlock).BellatrixBlock, + want: blkContainers[20].BlockRoot, }, { name: "non-existent root", @@ -2429,7 +1374,7 @@ func TestServer_ListBlockAttestations(t *testing.T) { { name: "slot", blockID: []byte("40"), - want: blkContainers[40].Block.(*ethpbalpha.BeaconBlockContainer_BellatrixBlock).BellatrixBlock, + want: blkContainers[40].BlockRoot, }, { name: "no block", @@ -2439,7 +1384,7 @@ func TestServer_ListBlockAttestations(t *testing.T) { } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { - blk, err := bs.ListBlockAttestations(ctx, ðpbv1.BlockRequest{ + blockRootResp, err := bs.GetBlockRoot(ctx, ðpbv1.BlockRequest{ BlockId: tt.blockID, }) if tt.wantErr { @@ -2447,32 +1392,17 @@ func TestServer_ListBlockAttestations(t *testing.T) { return } require.NoError(t, err) - - v1Block, err := migration.V1Alpha1BeaconBlockBellatrixToV2(tt.want.Block) - require.NoError(t, err) - - blkAtts := blk.Data - if len(blkAtts) == 0 { - blkAtts = nil - } - if !reflect.DeepEqual(blkAtts, v1Block.Body.Attestations) { - t.Error("Expected attestations to equal") - } + assert.DeepEqual(t, tt.want, blockRootResp.Data.Root) }) } }) t.Run("execution optimistic", func(t *testing.T) { - beaconDB := dbTest.SetupDB(t) - ctx := context.Background() - - _, blkContainers := fillDBTestBlocksBellatrix(ctx, t, beaconDB) - headBlock := blkContainers[len(blkContainers)-1] - blk, err := blocks.NewSignedBeaconBlock(headBlock.Block.(*ethpbalpha.BeaconBlockContainer_BellatrixBlock).BellatrixBlock) + wsb, err := blocks.NewSignedBeaconBlock(headBlock.Block.(*ethpbalpha.BeaconBlockContainer_Phase0Block).Phase0Block) require.NoError(t, err) - mockChainService := &mock.ChainService{ + mockChainFetcher := &mock.ChainService{ DB: beaconDB, - Block: blk, + Block: wsb, Root: headBlock.BlockRoot, FinalizedCheckPoint: ðpbalpha.Checkpoint{Root: blkContainers[64].BlockRoot}, Optimistic: true, @@ -2480,31 +1410,27 @@ func TestServer_ListBlockAttestations(t *testing.T) { } bs := &Server{ BeaconDB: beaconDB, - ChainInfoFetcher: mockChainService, - HeadFetcher: mockChainService, - OptimisticModeFetcher: mockChainService, - FinalizationFetcher: mockChainService, + ChainInfoFetcher: mockChainFetcher, + HeadFetcher: mockChainFetcher, + OptimisticModeFetcher: mockChainFetcher, + FinalizationFetcher: mockChainFetcher, } - resp, err := bs.ListBlockAttestations(ctx, ðpbv1.BlockRequest{ + blockRootResp, err := bs.GetBlockRoot(ctx, ðpbv1.BlockRequest{ BlockId: []byte("head"), }) require.NoError(t, err) - assert.Equal(t, true, resp.ExecutionOptimistic) + assert.Equal(t, true, blockRootResp.ExecutionOptimistic) }) t.Run("finalized", func(t *testing.T) { - beaconDB := dbTest.SetupDB(t) - ctx := context.Background() - - _, blkContainers := fillDBTestBlocks(ctx, t, beaconDB) - headBlock := blkContainers[len(blkContainers)-1] - blk, err := blocks.NewSignedBeaconBlock(headBlock.Block.(*ethpbalpha.BeaconBlockContainer_Phase0Block).Phase0Block) + wsb, err := blocks.NewSignedBeaconBlock(headBlock.Block.(*ethpbalpha.BeaconBlockContainer_Phase0Block).Phase0Block) require.NoError(t, err) - mockChainService := &mock.ChainService{ + mockChainFetcher := &mock.ChainService{ DB: beaconDB, - Block: blk, + Block: wsb, Root: headBlock.BlockRoot, FinalizedCheckPoint: ðpbalpha.Checkpoint{Root: blkContainers[64].BlockRoot}, + Optimistic: true, FinalizedRoots: map[[32]byte]bool{ bytesutil.ToBytes32(blkContainers[32].BlockRoot): true, bytesutil.ToBytes32(blkContainers[64].BlockRoot): false, @@ -2512,25 +1438,202 @@ func TestServer_ListBlockAttestations(t *testing.T) { } bs := &Server{ BeaconDB: beaconDB, - ChainInfoFetcher: mockChainService, - HeadFetcher: mockChainService, - OptimisticModeFetcher: mockChainService, - FinalizationFetcher: mockChainService, + ChainInfoFetcher: mockChainFetcher, + HeadFetcher: mockChainFetcher, + OptimisticModeFetcher: mockChainFetcher, + FinalizationFetcher: mockChainFetcher, } t.Run("true", func(t *testing.T) { - resp, err := bs.ListBlockAttestations(ctx, ðpbv1.BlockRequest{ + blockRootResp, err := bs.GetBlockRoot(ctx, ðpbv1.BlockRequest{ BlockId: []byte("32"), }) require.NoError(t, err) - assert.Equal(t, true, resp.Finalized) + assert.Equal(t, true, blockRootResp.Finalized) }) t.Run("false", func(t *testing.T) { - resp, err := bs.ListBlockAttestations(ctx, ðpbv1.BlockRequest{ + blockRootResp, err := bs.GetBlockRoot(ctx, ðpbv1.BlockRequest{ BlockId: []byte("64"), }) require.NoError(t, err) - assert.Equal(t, false, resp.Finalized) + assert.Equal(t, false, blockRootResp.Finalized) }) }) } + +func TestServer_List(t *testing.T) { + ctx := context.Background() + b := util.NewBeaconBlock() + blk, err := blocks.NewSignedBeaconBlock(b) + require.NoError(t, err) + + bs := &Server{ + FinalizationFetcher: &mock.ChainService{}, + BlockFetcher: &testutil.MockBlockFetcher{BlockToReturn: blk}, + } + + expected, err := migration.V1Alpha1ToV1SignedBlock(b) + require.NoError(t, err) + resp, err := bs.GetBlockV2(ctx, ðpbv2.BlockRequestV2{}) + require.NoError(t, err) + phase0Block, ok := resp.Data.Message.(*ethpbv2.SignedBeaconBlockContainer_Phase0Block) + require.Equal(t, true, ok) + assert.DeepEqual(t, expected.Block, phase0Block.Phase0Block) + assert.Equal(t, ethpbv2.Version_PHASE0, resp.Version) +} + +func TestServer_ListBlockAttestations(t *testing.T) { + ctx := context.Background() + atts := []*ethpbalpha.Attestation{{ + AggregationBits: bitfield.Bitlist{0b101}, + Data: ðpbalpha.AttestationData{ + Slot: 123, + CommitteeIndex: 123, + BeaconBlockRoot: bytesutil.PadTo([]byte("beacon_block_root"), 32), + Source: ðpbalpha.Checkpoint{ + Epoch: 123, + Root: bytesutil.PadTo([]byte("root"), 32), + }, + Target: ðpbalpha.Checkpoint{ + Epoch: 123, + Root: bytesutil.PadTo([]byte("root"), 32), + }, + }, + Signature: bytesutil.PadTo([]byte("signature"), 96), + }} + + t.Run("Phase 0", func(t *testing.T) { + b := util.NewBeaconBlock() + b.Block.Body.Attestations = atts + blk, err := blocks.NewSignedBeaconBlock(b) + require.NoError(t, err) + + mockChainService := &mock.ChainService{} + bs := &Server{ + FinalizationFetcher: mockChainService, + BlockFetcher: &testutil.MockBlockFetcher{BlockToReturn: blk}, + OptimisticModeFetcher: mockChainService, + } + + expected, err := migration.V1Alpha1ToV1SignedBlock(b) + require.NoError(t, err) + resp, err := bs.ListBlockAttestations(ctx, ðpbv1.BlockRequest{}) + require.NoError(t, err) + assert.DeepEqual(t, expected.Block.Body.Attestations, resp.Data) + }) + t.Run("Altair", func(t *testing.T) { + b := util.NewBeaconBlockAltair() + b.Block.Body.Attestations = atts + blk, err := blocks.NewSignedBeaconBlock(b) + require.NoError(t, err) + + mockChainService := &mock.ChainService{} + bs := &Server{ + FinalizationFetcher: mockChainService, + BlockFetcher: &testutil.MockBlockFetcher{BlockToReturn: blk}, + OptimisticModeFetcher: mockChainService, + } + + expected, err := migration.V1Alpha1BeaconBlockAltairToV2(b.Block) + require.NoError(t, err) + resp, err := bs.ListBlockAttestations(ctx, ðpbv1.BlockRequest{}) + require.NoError(t, err) + assert.DeepEqual(t, expected.Body.Attestations, resp.Data) + }) + t.Run("Bellatrix", func(t *testing.T) { + b := util.NewBeaconBlockBellatrix() + b.Block.Body.Attestations = atts + blk, err := blocks.NewSignedBeaconBlock(b) + require.NoError(t, err) + + mockChainService := &mock.ChainService{} + bs := &Server{ + FinalizationFetcher: mockChainService, + BlockFetcher: &testutil.MockBlockFetcher{BlockToReturn: blk}, + OptimisticModeFetcher: mockChainService, + } + + expected, err := migration.V1Alpha1BeaconBlockBellatrixToV2(b.Block) + require.NoError(t, err) + resp, err := bs.ListBlockAttestations(ctx, ðpbv1.BlockRequest{}) + require.NoError(t, err) + assert.DeepEqual(t, expected.Body.Attestations, resp.Data) + }) + t.Run("Capella", func(t *testing.T) { + b := util.NewBeaconBlockCapella() + b.Block.Body.Attestations = atts + blk, err := blocks.NewSignedBeaconBlock(b) + require.NoError(t, err) + + mockChainService := &mock.ChainService{} + bs := &Server{ + FinalizationFetcher: mockChainService, + BlockFetcher: &testutil.MockBlockFetcher{BlockToReturn: blk}, + OptimisticModeFetcher: mockChainService, + } + + expected, err := migration.V1Alpha1BeaconBlockCapellaToV2(b.Block) + require.NoError(t, err) + resp, err := bs.ListBlockAttestations(ctx, ðpbv1.BlockRequest{}) + require.NoError(t, err) + assert.DeepEqual(t, expected.Body.Attestations, resp.Data) + }) + t.Run("execution optimistic", func(t *testing.T) { + b := util.NewBeaconBlockBellatrix() + blk, err := blocks.NewSignedBeaconBlock(b) + require.NoError(t, err) + + mockChainService := &mock.ChainService{ + Optimistic: true, + } + bs := &Server{ + FinalizationFetcher: mockChainService, + BlockFetcher: &testutil.MockBlockFetcher{BlockToReturn: blk}, + OptimisticModeFetcher: mockChainService, + } + + resp, err := bs.ListBlockAttestations(ctx, ðpbv1.BlockRequest{}) + require.NoError(t, err) + assert.Equal(t, true, resp.ExecutionOptimistic) + }) + t.Run("finalized", func(t *testing.T) { + b := util.NewBeaconBlock() + blk, err := blocks.NewSignedBeaconBlock(b) + require.NoError(t, err) + root, err := blk.Block().HashTreeRoot() + require.NoError(t, err) + + mockChainService := &mock.ChainService{ + FinalizedRoots: map[[32]byte]bool{root: true}, + } + bs := &Server{ + FinalizationFetcher: mockChainService, + BlockFetcher: &testutil.MockBlockFetcher{BlockToReturn: blk}, + OptimisticModeFetcher: mockChainService, + } + + resp, err := bs.ListBlockAttestations(ctx, ðpbv1.BlockRequest{}) + require.NoError(t, err) + assert.Equal(t, true, resp.Finalized) + }) + t.Run("not finalized", func(t *testing.T) { + b := util.NewBeaconBlock() + blk, err := blocks.NewSignedBeaconBlock(b) + require.NoError(t, err) + root, err := blk.Block().HashTreeRoot() + require.NoError(t, err) + + mockChainService := &mock.ChainService{ + FinalizedRoots: map[[32]byte]bool{root: false}, + } + bs := &Server{ + FinalizationFetcher: mockChainService, + BlockFetcher: &testutil.MockBlockFetcher{BlockToReturn: blk}, + OptimisticModeFetcher: mockChainService, + } + + resp, err := bs.ListBlockAttestations(ctx, ðpbv1.BlockRequest{}) + require.NoError(t, err) + assert.Equal(t, false, resp.Finalized) + }) +} diff --git a/beacon-chain/rpc/testutil/BUILD.bazel b/beacon-chain/rpc/testutil/BUILD.bazel index 3210cc7fa0ff..3c80ce4e928e 100644 --- a/beacon-chain/rpc/testutil/BUILD.bazel +++ b/beacon-chain/rpc/testutil/BUILD.bazel @@ -4,6 +4,7 @@ go_library( name = "go_default_library", testonly = True, srcs = [ + "mock_block_fetcher.go", "mock_exec_chain_info_fetcher.go", "mock_genesis_timefetcher.go", "mock_state_fetcher.go", @@ -13,6 +14,7 @@ go_library( deps = [ "//beacon-chain/state:go_default_library", "//config/params:go_default_library", + "//consensus-types/interfaces:go_default_library", "//consensus-types/primitives:go_default_library", ], ) diff --git a/beacon-chain/rpc/testutil/mock_block_fetcher.go b/beacon-chain/rpc/testutil/mock_block_fetcher.go new file mode 100644 index 000000000000..c372e730efd9 --- /dev/null +++ b/beacon-chain/rpc/testutil/mock_block_fetcher.go @@ -0,0 +1,16 @@ +package testutil + +import ( + "context" + + "github.com/prysmaticlabs/prysm/v3/consensus-types/interfaces" +) + +// MockBlockFetcher is a fake implementation of blockfetcher.Fetcher. +type MockBlockFetcher struct { + BlockToReturn interfaces.ReadOnlySignedBeaconBlock +} + +func (m *MockBlockFetcher) Block(_ context.Context, _ []byte) (interfaces.ReadOnlySignedBeaconBlock, error) { + return m.BlockToReturn, nil +} From 470996d13ce3c8cf728e4421ab88fa46a7b3d2c8 Mon Sep 17 00:00:00 2001 From: rkapka Date: Tue, 21 Feb 2023 21:31:04 +0100 Subject: [PATCH 09/40] fix gateway tests --- api/gateway/gateway_test.go | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/api/gateway/gateway_test.go b/api/gateway/gateway_test.go index 804e1370e634..d2e52cd5b71c 100644 --- a/api/gateway/gateway_test.go +++ b/api/gateway/gateway_test.go @@ -55,7 +55,7 @@ func TestGateway_Customized(t *testing.T) { }), } - g, err := New(context.Background(), opts...) + g, err := New(context.Background(), mux.NewRouter(), opts...) require.NoError(t, err) assert.Equal(t, r, g.cfg.router) @@ -91,7 +91,7 @@ func TestGateway_StartStop(t *testing.T) { }), } - g, err := New(context.Background(), opts...) + g, err := New(context.Background(), mux.NewRouter(), opts...) require.NoError(t, err) g.Start() @@ -119,7 +119,7 @@ func TestGateway_NilHandler_NotFoundHandlerRegistered(t *testing.T) { WithRemoteAddr(selfAddress), } - g, err := New(context.Background(), opts...) + g, err := New(context.Background(), mux.NewRouter(), opts...) require.NoError(t, err) writer := httptest.NewRecorder() From 8269bc8fa258236ceab5d72ce9718c53be4cc4bc Mon Sep 17 00:00:00 2001 From: rkapka Date: Thu, 23 Feb 2023 18:39:14 +0100 Subject: [PATCH 10/40] fix test --- beacon-chain/rpc/service_test.go | 2 ++ 1 file changed, 2 insertions(+) diff --git a/beacon-chain/rpc/service_test.go b/beacon-chain/rpc/service_test.go index f2cfe1dfc128..ee98458038f7 100644 --- a/beacon-chain/rpc/service_test.go +++ b/beacon-chain/rpc/service_test.go @@ -7,6 +7,7 @@ import ( "testing" "time" + "github.com/gorilla/mux" mock "github.com/prysmaticlabs/prysm/v3/beacon-chain/blockchain/testing" mockExecution "github.com/prysmaticlabs/prysm/v3/beacon-chain/execution/testing" mockSync "github.com/prysmaticlabs/prysm/v3/beacon-chain/sync/initial-sync/testing" @@ -35,6 +36,7 @@ func TestLifecycle_OK(t *testing.T) { GenesisTimeFetcher: chainService, ExecutionChainService: &mockExecution.Chain{}, StateNotifier: chainService.StateNotifier(), + Router: mux.NewRouter(), }) rpcService.Start() From e68ba200c4536c3865702d5ee5579ba482179349 Mon Sep 17 00:00:00 2001 From: rkapka Date: Thu, 23 Feb 2023 18:40:50 +0100 Subject: [PATCH 11/40] gzl --- beacon-chain/rpc/BUILD.bazel | 1 + 1 file changed, 1 insertion(+) diff --git a/beacon-chain/rpc/BUILD.bazel b/beacon-chain/rpc/BUILD.bazel index e3b6086ab22a..908182024761 100644 --- a/beacon-chain/rpc/BUILD.bazel +++ b/beacon-chain/rpc/BUILD.bazel @@ -71,6 +71,7 @@ go_test( "//beacon-chain/sync/initial-sync/testing:go_default_library", "//testing/assert:go_default_library", "//testing/require:go_default_library", + "@com_github_gorilla_mux//:go_default_library", "@com_github_sirupsen_logrus//:go_default_library", "@com_github_sirupsen_logrus//hooks/test:go_default_library", ], From 95989cf6ced7ce43225cd97c106f41aca37d5d5c Mon Sep 17 00:00:00 2001 From: rkapka Date: Wed, 1 Mar 2023 16:10:41 +0100 Subject: [PATCH 12/40] tests in progress --- beacon-chain/rpc/blockfetcher/BUILD.bazel | 19 +- beacon-chain/rpc/blockfetcher/fetcher_test.go | 144 ++++++++ beacon-chain/rpc/eth/beacon/BUILD.bazel | 2 - beacon-chain/rpc/eth/beacon/blocks_test.go | 327 +----------------- beacon-chain/rpc/testutil/BUILD.bazel | 7 + beacon-chain/rpc/testutil/db.go | 51 +++ 6 files changed, 222 insertions(+), 328 deletions(-) create mode 100644 beacon-chain/rpc/blockfetcher/fetcher_test.go create mode 100644 beacon-chain/rpc/testutil/db.go diff --git a/beacon-chain/rpc/blockfetcher/BUILD.bazel b/beacon-chain/rpc/blockfetcher/BUILD.bazel index 265557616e05..6fe83a854e34 100644 --- a/beacon-chain/rpc/blockfetcher/BUILD.bazel +++ b/beacon-chain/rpc/blockfetcher/BUILD.bazel @@ -1,4 +1,4 @@ -load("@prysm//tools/go:def.bzl", "go_library") +load("@prysm//tools/go:def.bzl", "go_library", "go_test") go_library( name = "go_default_library", @@ -14,3 +14,20 @@ go_library( "@com_github_pkg_errors//:go_default_library", ], ) + +go_test( + name = "go_default_test", + srcs = ["fetcher_test.go"], + embed = [":go_default_library"], + deps = [ + "//beacon-chain/blockchain/testing:go_default_library", + "//beacon-chain/db/testing:go_default_library", + "//beacon-chain/rpc/testutil:go_default_library", + "//consensus-types/blocks:go_default_library", + "//encoding/bytesutil:go_default_library", + "//proto/migration:go_default_library", + "//proto/prysm/v1alpha1:go_default_library", + "//testing/require:go_default_library", + "//testing/util:go_default_library", + ], +) diff --git a/beacon-chain/rpc/blockfetcher/fetcher_test.go b/beacon-chain/rpc/blockfetcher/fetcher_test.go new file mode 100644 index 000000000000..0107d5e58947 --- /dev/null +++ b/beacon-chain/rpc/blockfetcher/fetcher_test.go @@ -0,0 +1,144 @@ +package blockfetcher + +import ( + "context" + "fmt" + "reflect" + "testing" + + mock "github.com/prysmaticlabs/prysm/v3/beacon-chain/blockchain/testing" + dbtesting "github.com/prysmaticlabs/prysm/v3/beacon-chain/db/testing" + "github.com/prysmaticlabs/prysm/v3/beacon-chain/rpc/testutil" + "github.com/prysmaticlabs/prysm/v3/consensus-types/blocks" + "github.com/prysmaticlabs/prysm/v3/encoding/bytesutil" + "github.com/prysmaticlabs/prysm/v3/proto/migration" + ethpbalpha "github.com/prysmaticlabs/prysm/v3/proto/prysm/v1alpha1" + "github.com/prysmaticlabs/prysm/v3/testing/require" + "github.com/prysmaticlabs/prysm/v3/testing/util" +) + +func TestGetBlock(t *testing.T) { + beaconDB := dbtesting.SetupDB(t) + ctx := context.Background() + + genBlk, blkContainers := testutil.FillDBWithBlocks(ctx, t, beaconDB) + canonicalRoots := make(map[[32]byte]bool) + + for _, bContr := range blkContainers { + canonicalRoots[bytesutil.ToBytes32(bContr.BlockRoot)] = true + } + headBlock := blkContainers[len(blkContainers)-1] + nextSlot := headBlock.GetPhase0Block().Block.Slot + 1 + + b2 := util.NewBeaconBlock() + b2.Block.Slot = 30 + b2.Block.ParentRoot = bytesutil.PadTo([]byte{1}, 32) + util.SaveBlock(t, ctx, beaconDB, b2) + b3 := util.NewBeaconBlock() + b3.Block.Slot = 30 + b3.Block.ParentRoot = bytesutil.PadTo([]byte{4}, 32) + util.SaveBlock(t, ctx, beaconDB, b3) + b4 := util.NewBeaconBlock() + b4.Block.Slot = nextSlot + b4.Block.ParentRoot = bytesutil.PadTo([]byte{8}, 32) + util.SaveBlock(t, ctx, beaconDB, b4) + + wsb, err := blocks.NewSignedBeaconBlock(headBlock.Block.(*ethpbalpha.BeaconBlockContainer_Phase0Block).Phase0Block) + require.NoError(t, err) + + fetcher := &BlockProvider{ + BeaconDB: beaconDB, + ChainInfoFetcher: &mock.ChainService{ + DB: beaconDB, + Block: wsb, + Root: headBlock.BlockRoot, + FinalizedCheckPoint: ðpbalpha.Checkpoint{Root: blkContainers[64].BlockRoot}, + CanonicalRoots: canonicalRoots, + }, + } + + root, err := genBlk.Block.HashTreeRoot() + require.NoError(t, err) + + tests := []struct { + name string + blockID []byte + want *ethpbalpha.SignedBeaconBlock + wantErr bool + }{ + { + name: "slot", + blockID: []byte("30"), + want: blkContainers[30].Block.(*ethpbalpha.BeaconBlockContainer_Phase0Block).Phase0Block, + }, + { + name: "bad formatting", + blockID: []byte("3bad0"), + wantErr: true, + }, + { + name: "canonical", + blockID: []byte("30"), + want: blkContainers[30].Block.(*ethpbalpha.BeaconBlockContainer_Phase0Block).Phase0Block, + }, + { + name: "non canonical", + blockID: []byte(fmt.Sprintf("%d", nextSlot)), + wantErr: true, + }, + { + name: "head", + blockID: []byte("head"), + want: headBlock.Block.(*ethpbalpha.BeaconBlockContainer_Phase0Block).Phase0Block, + }, + { + name: "finalized", + blockID: []byte("finalized"), + want: blkContainers[64].Block.(*ethpbalpha.BeaconBlockContainer_Phase0Block).Phase0Block, + }, + { + name: "genesis", + blockID: []byte("genesis"), + want: genBlk, + }, + { + name: "genesis root", + blockID: root[:], + want: genBlk, + }, + { + name: "root", + blockID: blkContainers[20].BlockRoot, + want: blkContainers[20].Block.(*ethpbalpha.BeaconBlockContainer_Phase0Block).Phase0Block, + }, + { + name: "non-existent root", + blockID: bytesutil.PadTo([]byte("hi there"), 32), + wantErr: true, + }, + { + name: "no block", + blockID: []byte("105"), + wantErr: true, + }, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + result, err := fetcher.Block(ctx, tt.blockID) + if tt.wantErr { + require.NotEqual(t, err, nil, "no error has been returned") + return + } + require.NoError(t, err) + + expected, err := migration.V1Alpha1ToV1SignedBlock(tt.want) + require.NoError(t, err) + + pbBlock, err := result.PbPhase0Block() + require.NoError(t, err) + if !reflect.DeepEqual(pbBlock.Block, expected.Block) { + t.Error("Expected blocks to equal") + } + }) + } +} diff --git a/beacon-chain/rpc/eth/beacon/BUILD.bazel b/beacon-chain/rpc/eth/beacon/BUILD.bazel index 9721b9bf4177..a098cf9a3fa4 100644 --- a/beacon-chain/rpc/eth/beacon/BUILD.bazel +++ b/beacon-chain/rpc/eth/beacon/BUILD.bazel @@ -91,7 +91,6 @@ go_test( "//beacon-chain/core/signing:go_default_library", "//beacon-chain/core/time:go_default_library", "//beacon-chain/core/transition:go_default_library", - "//beacon-chain/db:go_default_library", "//beacon-chain/db/testing:go_default_library", "//beacon-chain/operations/attestations:go_default_library", "//beacon-chain/operations/blstoexec:go_default_library", @@ -108,7 +107,6 @@ go_test( "//beacon-chain/state/state-native:go_default_library", "//config/params:go_default_library", "//consensus-types/blocks:go_default_library", - "//consensus-types/interfaces:go_default_library", "//consensus-types/primitives:go_default_library", "//crypto/bls:go_default_library", "//crypto/bls/common:go_default_library", diff --git a/beacon-chain/rpc/eth/beacon/blocks_test.go b/beacon-chain/rpc/eth/beacon/blocks_test.go index 894f6a954b83..6950ccfdecdf 100644 --- a/beacon-chain/rpc/eth/beacon/blocks_test.go +++ b/beacon-chain/rpc/eth/beacon/blocks_test.go @@ -6,16 +6,13 @@ import ( "github.com/prysmaticlabs/go-bitfield" mock "github.com/prysmaticlabs/prysm/v3/beacon-chain/blockchain/testing" - "github.com/prysmaticlabs/prysm/v3/beacon-chain/db" dbTest "github.com/prysmaticlabs/prysm/v3/beacon-chain/db/testing" mockp2p "github.com/prysmaticlabs/prysm/v3/beacon-chain/p2p/testing" "github.com/prysmaticlabs/prysm/v3/beacon-chain/rpc/testutil" "github.com/prysmaticlabs/prysm/v3/config/params" "github.com/prysmaticlabs/prysm/v3/consensus-types/blocks" - "github.com/prysmaticlabs/prysm/v3/consensus-types/interfaces" "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" "github.com/prysmaticlabs/prysm/v3/encoding/bytesutil" - enginev1 "github.com/prysmaticlabs/prysm/v3/proto/engine/v1" ethpbv1 "github.com/prysmaticlabs/prysm/v3/proto/eth/v1" ethpbv2 "github.com/prysmaticlabs/prysm/v3/proto/eth/v2" "github.com/prysmaticlabs/prysm/v3/proto/migration" @@ -26,326 +23,6 @@ import ( "google.golang.org/grpc/metadata" ) -func fillDBTestBlocks(ctx context.Context, t *testing.T, beaconDB db.Database) (*ethpbalpha.SignedBeaconBlock, []*ethpbalpha.BeaconBlockContainer) { - parentRoot := [32]byte{1, 2, 3} - genBlk := util.NewBeaconBlock() - genBlk.Block.ParentRoot = parentRoot[:] - root, err := genBlk.Block.HashTreeRoot() - require.NoError(t, err) - util.SaveBlock(t, ctx, beaconDB, genBlk) - require.NoError(t, beaconDB.SaveGenesisBlockRoot(ctx, root)) - - count := primitives.Slot(100) - blks := make([]interfaces.ReadOnlySignedBeaconBlock, count) - blkContainers := make([]*ethpbalpha.BeaconBlockContainer, count) - for i := primitives.Slot(0); i < count; i++ { - b := util.NewBeaconBlock() - b.Block.Slot = i - b.Block.ParentRoot = bytesutil.PadTo([]byte{uint8(i)}, 32) - root, err := b.Block.HashTreeRoot() - require.NoError(t, err) - blks[i], err = blocks.NewSignedBeaconBlock(b) - require.NoError(t, err) - blkContainers[i] = ðpbalpha.BeaconBlockContainer{ - Block: ðpbalpha.BeaconBlockContainer_Phase0Block{Phase0Block: b}, - BlockRoot: root[:], - } - } - require.NoError(t, beaconDB.SaveBlocks(ctx, blks)) - headRoot := bytesutil.ToBytes32(blkContainers[len(blks)-1].BlockRoot) - summary := ðpbalpha.StateSummary{ - Root: headRoot[:], - Slot: blkContainers[len(blks)-1].Block.(*ethpbalpha.BeaconBlockContainer_Phase0Block).Phase0Block.Block.Slot, - } - require.NoError(t, beaconDB.SaveStateSummary(ctx, summary)) - require.NoError(t, beaconDB.SaveHeadBlockRoot(ctx, headRoot)) - return genBlk, blkContainers -} - -func fillDBTestBlocksAltair(ctx context.Context, t *testing.T, beaconDB db.Database) (*ethpbalpha.SignedBeaconBlockAltair, []*ethpbalpha.BeaconBlockContainer) { - parentRoot := [32]byte{1, 2, 3} - genBlk := util.NewBeaconBlockAltair() - genBlk.Block.ParentRoot = parentRoot[:] - root, err := genBlk.Block.HashTreeRoot() - require.NoError(t, err) - util.SaveBlock(t, ctx, beaconDB, genBlk) - require.NoError(t, beaconDB.SaveGenesisBlockRoot(ctx, root)) - - count := primitives.Slot(100) - blks := make([]interfaces.ReadOnlySignedBeaconBlock, count) - blkContainers := make([]*ethpbalpha.BeaconBlockContainer, count) - for i := primitives.Slot(0); i < count; i++ { - b := util.NewBeaconBlockAltair() - b.Block.Slot = i - b.Block.ParentRoot = bytesutil.PadTo([]byte{uint8(i)}, 32) - syncCommitteeBits := bitfield.NewBitvector512() - syncCommitteeBits.SetBitAt(100, true) - b.Block.Body.SyncAggregate = ðpbalpha.SyncAggregate{ - SyncCommitteeBits: syncCommitteeBits, - SyncCommitteeSignature: bytesutil.PadTo([]byte("signature"), 96), - } - root, err := b.Block.HashTreeRoot() - require.NoError(t, err) - signedB, err := blocks.NewSignedBeaconBlock(b) - require.NoError(t, err) - blks[i] = signedB - blkContainers[i] = ðpbalpha.BeaconBlockContainer{ - Block: ðpbalpha.BeaconBlockContainer_AltairBlock{AltairBlock: b}, BlockRoot: root[:]} - } - require.NoError(t, beaconDB.SaveBlocks(ctx, blks)) - headRoot := bytesutil.ToBytes32(blkContainers[len(blks)-1].BlockRoot) - summary := ðpbalpha.StateSummary{ - Root: headRoot[:], - Slot: blkContainers[len(blks)-1].Block.(*ethpbalpha.BeaconBlockContainer_AltairBlock).AltairBlock.Block.Slot, - } - require.NoError(t, beaconDB.SaveStateSummary(ctx, summary)) - require.NoError(t, beaconDB.SaveHeadBlockRoot(ctx, headRoot)) - return genBlk, blkContainers -} - -func fillDBTestBlocksBellatrix(ctx context.Context, t *testing.T, beaconDB db.Database) (*ethpbalpha.SignedBeaconBlockBellatrix, []*ethpbalpha.BeaconBlockContainer) { - parentRoot := [32]byte{1, 2, 3} - genBlk := util.NewBeaconBlockBellatrix() - genBlk.Block.ParentRoot = parentRoot[:] - root, err := genBlk.Block.HashTreeRoot() - require.NoError(t, err) - util.SaveBlock(t, ctx, beaconDB, genBlk) - require.NoError(t, beaconDB.SaveGenesisBlockRoot(ctx, root)) - - count := primitives.Slot(100) - blks := make([]interfaces.ReadOnlySignedBeaconBlock, count) - blkContainers := make([]*ethpbalpha.BeaconBlockContainer, count) - for i := primitives.Slot(0); i < count; i++ { - b := util.NewBeaconBlockBellatrix() - b.Block.Slot = i - b.Block.ParentRoot = bytesutil.PadTo([]byte{uint8(i)}, 32) - syncCommitteeBits := bitfield.NewBitvector512() - syncCommitteeBits.SetBitAt(100, true) - b.Block.Body.SyncAggregate = ðpbalpha.SyncAggregate{ - SyncCommitteeBits: syncCommitteeBits, - SyncCommitteeSignature: bytesutil.PadTo([]byte("signature"), 96), - } - b.Block.Body.ExecutionPayload = &enginev1.ExecutionPayload{ - ParentHash: bytesutil.PadTo([]byte("parent_hash"), 32), - FeeRecipient: bytesutil.PadTo([]byte("fee_recipient"), 20), - StateRoot: bytesutil.PadTo([]byte("state_root"), 32), - ReceiptsRoot: bytesutil.PadTo([]byte("receipts_root"), 32), - LogsBloom: bytesutil.PadTo([]byte("logs_bloom"), 256), - PrevRandao: bytesutil.PadTo([]byte("prev_randao"), 32), - BlockNumber: 123, - GasLimit: 123, - GasUsed: 123, - Timestamp: 123, - ExtraData: bytesutil.PadTo([]byte("extra_data"), 32), - BaseFeePerGas: bytesutil.PadTo([]byte("base_fee_per_gas"), 32), - BlockHash: bytesutil.PadTo([]byte("block_hash"), 32), - Transactions: [][]byte{[]byte("transaction1"), []byte("transaction2")}, - } - root, err := b.Block.HashTreeRoot() - require.NoError(t, err) - signedB, err := blocks.NewSignedBeaconBlock(b) - require.NoError(t, err) - blks[i] = signedB - blkContainers[i] = ðpbalpha.BeaconBlockContainer{ - Block: ðpbalpha.BeaconBlockContainer_BellatrixBlock{BellatrixBlock: b}, BlockRoot: root[:]} - } - require.NoError(t, beaconDB.SaveBlocks(ctx, blks)) - headRoot := bytesutil.ToBytes32(blkContainers[len(blks)-1].BlockRoot) - summary := ðpbalpha.StateSummary{ - Root: headRoot[:], - Slot: blkContainers[len(blks)-1].Block.(*ethpbalpha.BeaconBlockContainer_BellatrixBlock).BellatrixBlock.Block.Slot, - } - require.NoError(t, beaconDB.SaveStateSummary(ctx, summary)) - require.NoError(t, beaconDB.SaveHeadBlockRoot(ctx, headRoot)) - return genBlk, blkContainers -} - -func fillDBTestBlocksCapella(ctx context.Context, t *testing.T, beaconDB db.Database) (*ethpbalpha.SignedBeaconBlockCapella, []*ethpbalpha.BeaconBlockContainer) { - parentRoot := [32]byte{1, 2, 3} - genBlk := util.NewBeaconBlockCapella() - genBlk.Block.ParentRoot = parentRoot[:] - root, err := genBlk.Block.HashTreeRoot() - require.NoError(t, err) - util.SaveBlock(t, ctx, beaconDB, genBlk) - require.NoError(t, beaconDB.SaveGenesisBlockRoot(ctx, root)) - - count := primitives.Slot(100) - blks := make([]interfaces.ReadOnlySignedBeaconBlock, count) - blkContainers := make([]*ethpbalpha.BeaconBlockContainer, count) - for i := primitives.Slot(0); i < count; i++ { - b := util.NewBeaconBlockCapella() - b.Block.Slot = i - b.Block.ParentRoot = bytesutil.PadTo([]byte{uint8(i)}, 32) - syncCommitteeBits := bitfield.NewBitvector512() - syncCommitteeBits.SetBitAt(100, true) - b.Block.Body.SyncAggregate = ðpbalpha.SyncAggregate{ - SyncCommitteeBits: syncCommitteeBits, - SyncCommitteeSignature: bytesutil.PadTo([]byte("signature"), 96), - } - b.Block.Body.ExecutionPayload = &enginev1.ExecutionPayloadCapella{ - ParentHash: bytesutil.PadTo([]byte("parent_hash"), 32), - FeeRecipient: bytesutil.PadTo([]byte("fee_recipient"), 20), - StateRoot: bytesutil.PadTo([]byte("state_root"), 32), - ReceiptsRoot: bytesutil.PadTo([]byte("receipts_root"), 32), - LogsBloom: bytesutil.PadTo([]byte("logs_bloom"), 256), - PrevRandao: bytesutil.PadTo([]byte("prev_randao"), 32), - BlockNumber: 123, - GasLimit: 123, - GasUsed: 123, - Timestamp: 123, - ExtraData: bytesutil.PadTo([]byte("extra_data"), 32), - BaseFeePerGas: bytesutil.PadTo([]byte("base_fee_per_gas"), 32), - BlockHash: bytesutil.PadTo([]byte("block_hash"), 32), - Transactions: [][]byte{[]byte("transaction1"), []byte("transaction2")}, - Withdrawals: []*enginev1.Withdrawal{ - { - Index: 1, - ValidatorIndex: 1, - Address: bytesutil.PadTo([]byte("address1"), 20), - Amount: 1, - }, - { - Index: 2, - ValidatorIndex: 2, - Address: bytesutil.PadTo([]byte("address2"), 20), - Amount: 2, - }, - }, - } - root, err := b.Block.HashTreeRoot() - require.NoError(t, err) - signedB, err := blocks.NewSignedBeaconBlock(b) - require.NoError(t, err) - blks[i] = signedB - blkContainers[i] = ðpbalpha.BeaconBlockContainer{ - Block: ðpbalpha.BeaconBlockContainer_CapellaBlock{CapellaBlock: b}, BlockRoot: root[:]} - } - require.NoError(t, beaconDB.SaveBlocks(ctx, blks)) - headRoot := bytesutil.ToBytes32(blkContainers[len(blks)-1].BlockRoot) - summary := ðpbalpha.StateSummary{ - Root: headRoot[:], - Slot: blkContainers[len(blks)-1].Block.(*ethpbalpha.BeaconBlockContainer_CapellaBlock).CapellaBlock.Block.Slot, - } - require.NoError(t, beaconDB.SaveStateSummary(ctx, summary)) - require.NoError(t, beaconDB.SaveHeadBlockRoot(ctx, headRoot)) - return genBlk, blkContainers -} - -func fillDBTestBlocksBellatrixBlinded(ctx context.Context, t *testing.T, beaconDB db.Database) (*ethpbalpha.SignedBlindedBeaconBlockBellatrix, []*ethpbalpha.BeaconBlockContainer) { - parentRoot := [32]byte{1, 2, 3} - genBlk := util.NewBlindedBeaconBlockBellatrix() - genBlk.Block.ParentRoot = parentRoot[:] - root, err := genBlk.Block.HashTreeRoot() - require.NoError(t, err) - util.SaveBlock(t, ctx, beaconDB, genBlk) - require.NoError(t, beaconDB.SaveGenesisBlockRoot(ctx, root)) - - count := primitives.Slot(100) - blks := make([]interfaces.ReadOnlySignedBeaconBlock, count) - blkContainers := make([]*ethpbalpha.BeaconBlockContainer, count) - for i := primitives.Slot(0); i < count; i++ { - b := util.NewBlindedBeaconBlockBellatrix() - b.Block.Slot = i - b.Block.ParentRoot = bytesutil.PadTo([]byte{uint8(i)}, 32) - syncCommitteeBits := bitfield.NewBitvector512() - syncCommitteeBits.SetBitAt(100, true) - b.Block.Body.SyncAggregate = ðpbalpha.SyncAggregate{ - SyncCommitteeBits: syncCommitteeBits, - SyncCommitteeSignature: bytesutil.PadTo([]byte("signature"), 96), - } - b.Block.Body.ExecutionPayloadHeader = &enginev1.ExecutionPayloadHeader{ - ParentHash: bytesutil.PadTo([]byte("parent_hash"), 32), - FeeRecipient: bytesutil.PadTo([]byte("fee_recipient"), 20), - StateRoot: bytesutil.PadTo([]byte("state_root"), 32), - ReceiptsRoot: bytesutil.PadTo([]byte("receipts_root"), 32), - LogsBloom: bytesutil.PadTo([]byte("logs_bloom"), 256), - PrevRandao: bytesutil.PadTo([]byte("prev_randao"), 32), - BlockNumber: 123, - GasLimit: 123, - GasUsed: 123, - Timestamp: 123, - ExtraData: bytesutil.PadTo([]byte("extra_data"), 32), - BaseFeePerGas: bytesutil.PadTo([]byte("base_fee_per_gas"), 32), - BlockHash: bytesutil.PadTo([]byte("block_hash"), 32), - TransactionsRoot: bytesutil.PadTo([]byte("transactions_root"), 32), - } - root, err := b.Block.HashTreeRoot() - require.NoError(t, err) - signedB, err := blocks.NewSignedBeaconBlock(b) - require.NoError(t, err) - blks[i] = signedB - blkContainers[i] = ðpbalpha.BeaconBlockContainer{ - Block: ðpbalpha.BeaconBlockContainer_BlindedBellatrixBlock{BlindedBellatrixBlock: b}, BlockRoot: root[:]} - } - require.NoError(t, beaconDB.SaveBlocks(ctx, blks)) - headRoot := bytesutil.ToBytes32(blkContainers[len(blks)-1].BlockRoot) - summary := ðpbalpha.StateSummary{ - Root: headRoot[:], - Slot: blkContainers[len(blks)-1].Block.(*ethpbalpha.BeaconBlockContainer_BlindedBellatrixBlock).BlindedBellatrixBlock.Block.Slot, - } - require.NoError(t, beaconDB.SaveStateSummary(ctx, summary)) - require.NoError(t, beaconDB.SaveHeadBlockRoot(ctx, headRoot)) - return genBlk, blkContainers -} - -func fillDBTestBlocksCapellaBlinded(ctx context.Context, t *testing.T, beaconDB db.Database) (*ethpbalpha.SignedBlindedBeaconBlockCapella, []*ethpbalpha.BeaconBlockContainer) { - parentRoot := [32]byte{1, 2, 3} - genBlk := util.NewBlindedBeaconBlockCapella() - genBlk.Block.ParentRoot = parentRoot[:] - root, err := genBlk.Block.HashTreeRoot() - require.NoError(t, err) - util.SaveBlock(t, ctx, beaconDB, genBlk) - require.NoError(t, beaconDB.SaveGenesisBlockRoot(ctx, root)) - - count := primitives.Slot(100) - blks := make([]interfaces.ReadOnlySignedBeaconBlock, count) - blkContainers := make([]*ethpbalpha.BeaconBlockContainer, count) - for i := primitives.Slot(0); i < count; i++ { - b := util.NewBlindedBeaconBlockCapella() - b.Block.Slot = i - b.Block.ParentRoot = bytesutil.PadTo([]byte{uint8(i)}, 32) - syncCommitteeBits := bitfield.NewBitvector512() - syncCommitteeBits.SetBitAt(100, true) - b.Block.Body.SyncAggregate = ðpbalpha.SyncAggregate{ - SyncCommitteeBits: syncCommitteeBits, - SyncCommitteeSignature: bytesutil.PadTo([]byte("signature"), 96), - } - b.Block.Body.ExecutionPayloadHeader = &enginev1.ExecutionPayloadHeaderCapella{ - ParentHash: bytesutil.PadTo([]byte("parent_hash"), 32), - FeeRecipient: bytesutil.PadTo([]byte("fee_recipient"), 20), - StateRoot: bytesutil.PadTo([]byte("state_root"), 32), - ReceiptsRoot: bytesutil.PadTo([]byte("receipts_root"), 32), - LogsBloom: bytesutil.PadTo([]byte("logs_bloom"), 256), - PrevRandao: bytesutil.PadTo([]byte("prev_randao"), 32), - BlockNumber: 123, - GasLimit: 123, - GasUsed: 123, - Timestamp: 123, - ExtraData: bytesutil.PadTo([]byte("extra_data"), 32), - BaseFeePerGas: bytesutil.PadTo([]byte("base_fee_per_gas"), 32), - BlockHash: bytesutil.PadTo([]byte("block_hash"), 32), - TransactionsRoot: bytesutil.PadTo([]byte("transactions_root"), 32), - WithdrawalsRoot: bytesutil.PadTo([]byte("withdrawals_root"), 32), - } - root, err := b.Block.HashTreeRoot() - require.NoError(t, err) - signedB, err := blocks.NewSignedBeaconBlock(b) - require.NoError(t, err) - blks[i] = signedB - blkContainers[i] = ðpbalpha.BeaconBlockContainer{ - Block: ðpbalpha.BeaconBlockContainer_BlindedCapellaBlock{BlindedCapellaBlock: b}, BlockRoot: root[:]} - } - require.NoError(t, beaconDB.SaveBlocks(ctx, blks)) - headRoot := bytesutil.ToBytes32(blkContainers[len(blks)-1].BlockRoot) - summary := ðpbalpha.StateSummary{ - Root: headRoot[:], - Slot: blkContainers[len(blks)-1].Block.(*ethpbalpha.BeaconBlockContainer_BlindedCapellaBlock).BlindedCapellaBlock.Block.Slot, - } - require.NoError(t, beaconDB.SaveStateSummary(ctx, summary)) - require.NoError(t, beaconDB.SaveHeadBlockRoot(ctx, headRoot)) - return genBlk, blkContainers -} - func TestServer_GetBlockHeader(t *testing.T) { ctx := context.Background() @@ -470,7 +147,7 @@ func TestServer_ListBlockHeaders(t *testing.T) { beaconDB := dbTest.SetupDB(t) ctx := context.Background() - _, blkContainers := fillDBTestBlocks(ctx, t, beaconDB) + _, blkContainers := testutil.FillDBWithBlocks(ctx, t, beaconDB) headBlock := blkContainers[len(blkContainers)-1] b1 := util.NewBeaconBlock() @@ -1301,7 +978,7 @@ func TestServer_GetBlockRoot(t *testing.T) { beaconDB := dbTest.SetupDB(t) ctx := context.Background() - genBlk, blkContainers := fillDBTestBlocks(ctx, t, beaconDB) + genBlk, blkContainers := testutil.FillDBWithBlocks(ctx, t, beaconDB) headBlock := blkContainers[len(blkContainers)-1] t.Run("get root", func(t *testing.T) { diff --git a/beacon-chain/rpc/testutil/BUILD.bazel b/beacon-chain/rpc/testutil/BUILD.bazel index 3c80ce4e928e..fa5752d04029 100644 --- a/beacon-chain/rpc/testutil/BUILD.bazel +++ b/beacon-chain/rpc/testutil/BUILD.bazel @@ -4,6 +4,7 @@ go_library( name = "go_default_library", testonly = True, srcs = [ + "db.go", "mock_block_fetcher.go", "mock_exec_chain_info_fetcher.go", "mock_genesis_timefetcher.go", @@ -12,9 +13,15 @@ go_library( importpath = "github.com/prysmaticlabs/prysm/v3/beacon-chain/rpc/testutil", visibility = ["//beacon-chain:__subpackages__"], deps = [ + "//beacon-chain/db:go_default_library", "//beacon-chain/state:go_default_library", "//config/params:go_default_library", + "//consensus-types/blocks:go_default_library", "//consensus-types/interfaces:go_default_library", "//consensus-types/primitives:go_default_library", + "//encoding/bytesutil:go_default_library", + "//proto/prysm/v1alpha1:go_default_library", + "//testing/require:go_default_library", + "//testing/util:go_default_library", ], ) diff --git a/beacon-chain/rpc/testutil/db.go b/beacon-chain/rpc/testutil/db.go new file mode 100644 index 000000000000..ad0fe37e6852 --- /dev/null +++ b/beacon-chain/rpc/testutil/db.go @@ -0,0 +1,51 @@ +package testutil + +import ( + "context" + "testing" + + "github.com/prysmaticlabs/prysm/v3/beacon-chain/db" + "github.com/prysmaticlabs/prysm/v3/consensus-types/blocks" + "github.com/prysmaticlabs/prysm/v3/consensus-types/interfaces" + "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" + "github.com/prysmaticlabs/prysm/v3/encoding/bytesutil" + ethpbalpha "github.com/prysmaticlabs/prysm/v3/proto/prysm/v1alpha1" + "github.com/prysmaticlabs/prysm/v3/testing/require" + "github.com/prysmaticlabs/prysm/v3/testing/util" +) + +func FillDBWithBlocks(ctx context.Context, t *testing.T, beaconDB db.Database) (*ethpbalpha.SignedBeaconBlock, []*ethpbalpha.BeaconBlockContainer) { + parentRoot := [32]byte{1, 2, 3} + genBlk := util.NewBeaconBlock() + genBlk.Block.ParentRoot = parentRoot[:] + root, err := genBlk.Block.HashTreeRoot() + require.NoError(t, err) + util.SaveBlock(t, ctx, beaconDB, genBlk) + require.NoError(t, beaconDB.SaveGenesisBlockRoot(ctx, root)) + + count := primitives.Slot(100) + blks := make([]interfaces.ReadOnlySignedBeaconBlock, count) + blkContainers := make([]*ethpbalpha.BeaconBlockContainer, count) + for i := primitives.Slot(0); i < count; i++ { + b := util.NewBeaconBlock() + b.Block.Slot = i + b.Block.ParentRoot = bytesutil.PadTo([]byte{uint8(i)}, 32) + root, err := b.Block.HashTreeRoot() + require.NoError(t, err) + blks[i], err = blocks.NewSignedBeaconBlock(b) + require.NoError(t, err) + blkContainers[i] = ðpbalpha.BeaconBlockContainer{ + Block: ðpbalpha.BeaconBlockContainer_Phase0Block{Phase0Block: b}, + BlockRoot: root[:], + } + } + require.NoError(t, beaconDB.SaveBlocks(ctx, blks)) + headRoot := bytesutil.ToBytes32(blkContainers[len(blks)-1].BlockRoot) + summary := ðpbalpha.StateSummary{ + Root: headRoot[:], + Slot: blkContainers[len(blks)-1].Block.(*ethpbalpha.BeaconBlockContainer_Phase0Block).Phase0Block.Block.Slot, + } + require.NoError(t, beaconDB.SaveStateSummary(ctx, summary)) + require.NoError(t, beaconDB.SaveHeadBlockRoot(ctx, headRoot)) + return genBlk, blkContainers +} From 6e5c6bcbe549bd3b642322be1e1a3803004b4910 Mon Sep 17 00:00:00 2001 From: rkapka Date: Wed, 1 Mar 2023 16:25:23 +0100 Subject: [PATCH 13/40] simplify tests --- beacon-chain/rpc/blockfetcher/BUILD.bazel | 1 - beacon-chain/rpc/blockfetcher/fetcher_test.go | 7 +------ 2 files changed, 1 insertion(+), 7 deletions(-) diff --git a/beacon-chain/rpc/blockfetcher/BUILD.bazel b/beacon-chain/rpc/blockfetcher/BUILD.bazel index 6fe83a854e34..6784e2b69c96 100644 --- a/beacon-chain/rpc/blockfetcher/BUILD.bazel +++ b/beacon-chain/rpc/blockfetcher/BUILD.bazel @@ -25,7 +25,6 @@ go_test( "//beacon-chain/rpc/testutil:go_default_library", "//consensus-types/blocks:go_default_library", "//encoding/bytesutil:go_default_library", - "//proto/migration:go_default_library", "//proto/prysm/v1alpha1:go_default_library", "//testing/require:go_default_library", "//testing/util:go_default_library", diff --git a/beacon-chain/rpc/blockfetcher/fetcher_test.go b/beacon-chain/rpc/blockfetcher/fetcher_test.go index 0107d5e58947..267a8e0233bd 100644 --- a/beacon-chain/rpc/blockfetcher/fetcher_test.go +++ b/beacon-chain/rpc/blockfetcher/fetcher_test.go @@ -11,7 +11,6 @@ import ( "github.com/prysmaticlabs/prysm/v3/beacon-chain/rpc/testutil" "github.com/prysmaticlabs/prysm/v3/consensus-types/blocks" "github.com/prysmaticlabs/prysm/v3/encoding/bytesutil" - "github.com/prysmaticlabs/prysm/v3/proto/migration" ethpbalpha "github.com/prysmaticlabs/prysm/v3/proto/prysm/v1alpha1" "github.com/prysmaticlabs/prysm/v3/testing/require" "github.com/prysmaticlabs/prysm/v3/testing/util" @@ -130,13 +129,9 @@ func TestGetBlock(t *testing.T) { return } require.NoError(t, err) - - expected, err := migration.V1Alpha1ToV1SignedBlock(tt.want) - require.NoError(t, err) - pbBlock, err := result.PbPhase0Block() require.NoError(t, err) - if !reflect.DeepEqual(pbBlock.Block, expected.Block) { + if !reflect.DeepEqual(pbBlock, tt.want) { t.Error("Expected blocks to equal") } }) From b3059691e85492e9dacc626c560bbcda3c1fa571 Mon Sep 17 00:00:00 2001 From: rkapka Date: Wed, 1 Mar 2023 16:31:47 +0100 Subject: [PATCH 14/40] correct tests --- beacon-chain/rpc/blockfetcher/BUILD.bazel | 1 + beacon-chain/rpc/blockfetcher/fetcher_test.go | 13 +++++++++---- 2 files changed, 10 insertions(+), 4 deletions(-) diff --git a/beacon-chain/rpc/blockfetcher/BUILD.bazel b/beacon-chain/rpc/blockfetcher/BUILD.bazel index 6784e2b69c96..084ef5ec110c 100644 --- a/beacon-chain/rpc/blockfetcher/BUILD.bazel +++ b/beacon-chain/rpc/blockfetcher/BUILD.bazel @@ -26,6 +26,7 @@ go_test( "//consensus-types/blocks:go_default_library", "//encoding/bytesutil:go_default_library", "//proto/prysm/v1alpha1:go_default_library", + "//testing/assert:go_default_library", "//testing/require:go_default_library", "//testing/util:go_default_library", ], diff --git a/beacon-chain/rpc/blockfetcher/fetcher_test.go b/beacon-chain/rpc/blockfetcher/fetcher_test.go index 267a8e0233bd..b4da149f88b0 100644 --- a/beacon-chain/rpc/blockfetcher/fetcher_test.go +++ b/beacon-chain/rpc/blockfetcher/fetcher_test.go @@ -12,6 +12,7 @@ import ( "github.com/prysmaticlabs/prysm/v3/consensus-types/blocks" "github.com/prysmaticlabs/prysm/v3/encoding/bytesutil" ethpbalpha "github.com/prysmaticlabs/prysm/v3/proto/prysm/v1alpha1" + "github.com/prysmaticlabs/prysm/v3/testing/assert" "github.com/prysmaticlabs/prysm/v3/testing/require" "github.com/prysmaticlabs/prysm/v3/testing/util" ) @@ -83,7 +84,7 @@ func TestGetBlock(t *testing.T) { { name: "non canonical", blockID: []byte(fmt.Sprintf("%d", nextSlot)), - wantErr: true, + want: nil, }, { name: "head", @@ -113,19 +114,23 @@ func TestGetBlock(t *testing.T) { { name: "non-existent root", blockID: bytesutil.PadTo([]byte("hi there"), 32), - wantErr: true, + want: nil, }, { name: "no block", blockID: []byte("105"), - wantErr: true, + want: nil, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { result, err := fetcher.Block(ctx, tt.blockID) if tt.wantErr { - require.NotEqual(t, err, nil, "no error has been returned") + assert.NotEqual(t, err, nil, "no error has been returned") + return + } + if tt.want == nil { + assert.Equal(t, nil, result) return } require.NoError(t, err) From 7d20017fa78c14350cceec6872f381aa3a1ccbe3 Mon Sep 17 00:00:00 2001 From: rkapka Date: Thu, 2 Mar 2023 19:05:52 +0100 Subject: [PATCH 15/40] make router an option --- api/gateway/gateway.go | 9 +++++---- api/gateway/gateway_test.go | 6 +++--- api/gateway/options.go | 5 ----- beacon-chain/node/node.go | 3 ++- beacon-chain/server/main.go | 7 +++---- validator/node/node.go | 3 ++- 6 files changed, 15 insertions(+), 18 deletions(-) diff --git a/api/gateway/gateway.go b/api/gateway/gateway.go index e37d3cf6c218..01adfc995f23 100644 --- a/api/gateway/gateway.go +++ b/api/gateway/gateway.go @@ -67,18 +67,19 @@ type Gateway struct { } // New returns a new instance of the Gateway. -func New(ctx context.Context, router *mux.Router, opts ...Option) (*Gateway, error) { +func New(ctx context.Context, opts ...Option) (*Gateway, error) { g := &Gateway{ ctx: ctx, - cfg: &config{ - router: router, - }, + cfg: &config{}, } for _, opt := range opts { if err := opt(g); err != nil { return nil, err } } + if g.cfg.router == nil { + g.cfg.router = mux.NewRouter() + } return g, nil } diff --git a/api/gateway/gateway_test.go b/api/gateway/gateway_test.go index d2e52cd5b71c..804e1370e634 100644 --- a/api/gateway/gateway_test.go +++ b/api/gateway/gateway_test.go @@ -55,7 +55,7 @@ func TestGateway_Customized(t *testing.T) { }), } - g, err := New(context.Background(), mux.NewRouter(), opts...) + g, err := New(context.Background(), opts...) require.NoError(t, err) assert.Equal(t, r, g.cfg.router) @@ -91,7 +91,7 @@ func TestGateway_StartStop(t *testing.T) { }), } - g, err := New(context.Background(), mux.NewRouter(), opts...) + g, err := New(context.Background(), opts...) require.NoError(t, err) g.Start() @@ -119,7 +119,7 @@ func TestGateway_NilHandler_NotFoundHandlerRegistered(t *testing.T) { WithRemoteAddr(selfAddress), } - g, err := New(context.Background(), mux.NewRouter(), opts...) + g, err := New(context.Background(), opts...) require.NoError(t, err) writer := httptest.NewRecorder() diff --git a/api/gateway/options.go b/api/gateway/options.go index 236bfd73ede2..dcca4ff08d15 100644 --- a/api/gateway/options.go +++ b/api/gateway/options.go @@ -10,11 +10,6 @@ import ( type Option func(g *Gateway) error -func (g *Gateway) SetRouter(r *mux.Router) *Gateway { - g.cfg.router = r - return g -} - func WithPbHandlers(handlers []*PbMux) Option { return func(g *Gateway) error { g.cfg.pbHandlers = handlers diff --git a/beacon-chain/node/node.go b/beacon-chain/node/node.go index e788e5d78e2a..92db201ba5a2 100644 --- a/beacon-chain/node/node.go +++ b/beacon-chain/node/node.go @@ -898,6 +898,7 @@ func (b *BeaconNode) registerGRPCGateway(router *mux.Router) error { } opts := []apigateway.Option{ + apigateway.WithRouter(router), apigateway.WithGatewayAddr(gatewayAddress), apigateway.WithRemoteAddr(selfAddress), apigateway.WithPbHandlers(muxs), @@ -910,7 +911,7 @@ func (b *BeaconNode) registerGRPCGateway(router *mux.Router) error { if flags.EnableHTTPEthAPI(httpModules) { opts = append(opts, apigateway.WithApiMiddleware(&apimiddleware.BeaconEndpointFactory{})) } - g, err := apigateway.New(b.ctx, router, opts...) + g, err := apigateway.New(b.ctx, opts...) if err != nil { return err } diff --git a/beacon-chain/server/main.go b/beacon-chain/server/main.go index 5b288713efa2..0f6803a62982 100644 --- a/beacon-chain/server/main.go +++ b/beacon-chain/server/main.go @@ -44,6 +44,7 @@ func main() { log.SetLevel(logrus.DebugLevel) } + r := mux.NewRouter() gatewayConfig := beaconGateway.DefaultConfig(*enableDebugRPCEndpoints, *httpModules) muxs := make([]*gateway.PbMux, 0) if gatewayConfig.V1AlphaPbMux != nil { @@ -53,6 +54,7 @@ func main() { muxs = append(muxs, gatewayConfig.EthPbMux) } opts := []gateway.Option{ + gateway.WithRouter(r), gateway.WithPbHandlers(muxs), gateway.WithMuxHandler(gatewayConfig.Handler), gateway.WithRemoteAddr(*beaconRPC), @@ -65,16 +67,13 @@ func main() { opts = append(opts, gateway.WithApiMiddleware(&apimiddleware.BeaconEndpointFactory{})) } - r := mux.NewRouter() - - gw, err := gateway.New(context.Background(), r, opts...) + gw, err := gateway.New(context.Background(), opts...) if err != nil { log.Fatal(err) } r.HandleFunc("/swagger/", gateway.SwaggerServer()) r.HandleFunc("/healthz", healthzServer(gw)) - gw.SetRouter(r) gw.Start() diff --git a/validator/node/node.go b/validator/node/node.go index d54c6d60d28b..64d16b08f476 100644 --- a/validator/node/node.go +++ b/validator/node/node.go @@ -765,6 +765,7 @@ func (c *ValidatorClient) registerRPCGatewayService(cliCtx *cli.Context) error { Mux: gwmux, } opts := []gateway.Option{ + gateway.WithRouter(mux.NewRouter()), gateway.WithRemoteAddr(rpcAddr), gateway.WithGatewayAddr(gatewayAddress), gateway.WithMaxCallRecvMsgSize(maxCallSize), @@ -774,7 +775,7 @@ func (c *ValidatorClient) registerRPCGatewayService(cliCtx *cli.Context) error { gateway.WithMuxHandler(muxHandler), gateway.WithTimeout(uint64(timeout)), } - gw, err := gateway.New(cliCtx.Context, mux.NewRouter(), opts...) + gw, err := gateway.New(cliCtx.Context, opts...) if err != nil { return err } From 89a00a21de1d3c4ecf2049ee0d0025eff90e5e20 Mon Sep 17 00:00:00 2001 From: rkapka Date: Fri, 3 Mar 2023 11:21:33 +0100 Subject: [PATCH 16/40] mock --- beacon-chain/rpc/eth/rewards/BUILD.bazel | 7 +++++-- beacon-chain/rpc/eth/rewards/handlers_test.go | 7 +++++++ beacon-chain/rpc/testutil/mock_block_fetcher.go | 4 ++++ 3 files changed, 16 insertions(+), 2 deletions(-) create mode 100644 beacon-chain/rpc/eth/rewards/handlers_test.go diff --git a/beacon-chain/rpc/eth/rewards/BUILD.bazel b/beacon-chain/rpc/eth/rewards/BUILD.bazel index 09b4847f7c18..f943567e3989 100644 --- a/beacon-chain/rpc/eth/rewards/BUILD.bazel +++ b/beacon-chain/rpc/eth/rewards/BUILD.bazel @@ -28,9 +28,12 @@ go_library( go_test( name = "go_default_test", - srcs = ["structs_test.go"], + srcs = [ + "handlers_test.go", + "structs_test.go", + ], + embed = [":go_default_library"], deps = [ - ":go_default_library", "//testing/assert:go_default_library", "//testing/require:go_default_library", ], diff --git a/beacon-chain/rpc/eth/rewards/handlers_test.go b/beacon-chain/rpc/eth/rewards/handlers_test.go new file mode 100644 index 000000000000..9286518e4a2e --- /dev/null +++ b/beacon-chain/rpc/eth/rewards/handlers_test.go @@ -0,0 +1,7 @@ +package rewards + +import "testing" + +func TestBlockRewards(t *testing.T) { + +} diff --git a/beacon-chain/rpc/testutil/mock_block_fetcher.go b/beacon-chain/rpc/testutil/mock_block_fetcher.go index c372e730efd9..36c032122c30 100644 --- a/beacon-chain/rpc/testutil/mock_block_fetcher.go +++ b/beacon-chain/rpc/testutil/mock_block_fetcher.go @@ -9,8 +9,12 @@ import ( // MockBlockFetcher is a fake implementation of blockfetcher.Fetcher. type MockBlockFetcher struct { BlockToReturn interfaces.ReadOnlySignedBeaconBlock + ErrorToReturn error } func (m *MockBlockFetcher) Block(_ context.Context, _ []byte) (interfaces.ReadOnlySignedBeaconBlock, error) { + if m.ErrorToReturn != nil { + return nil, m.ErrorToReturn + } return m.BlockToReturn, nil } From 8af14dbac0839f9e2a5c4a561cc7b657925c69dc Mon Sep 17 00:00:00 2001 From: rkapka Date: Thu, 16 Mar 2023 10:20:18 +0100 Subject: [PATCH 17/40] test in progress --- beacon-chain/rpc/eth/rewards/BUILD.bazel | 12 +- beacon-chain/rpc/eth/rewards/handlers.go | 4 +- beacon-chain/rpc/eth/rewards/handlers_test.go | 129 +++++++++++++++++- beacon-chain/rpc/eth/rewards/server.go | 4 +- beacon-chain/rpc/service.go | 11 +- 5 files changed, 144 insertions(+), 16 deletions(-) diff --git a/beacon-chain/rpc/eth/rewards/BUILD.bazel b/beacon-chain/rpc/eth/rewards/BUILD.bazel index f943567e3989..07a65c04aac5 100644 --- a/beacon-chain/rpc/eth/rewards/BUILD.bazel +++ b/beacon-chain/rpc/eth/rewards/BUILD.bazel @@ -16,7 +16,6 @@ go_library( "//beacon-chain/core/validators:go_default_library", "//beacon-chain/rpc/blockfetcher:go_default_library", "//beacon-chain/rpc/eth/helpers:go_default_library", - "//beacon-chain/rpc/statefetcher:go_default_library", "//beacon-chain/state/stategen:go_default_library", "//consensus-types/blocks:go_default_library", "//consensus-types/interfaces:go_default_library", @@ -34,7 +33,18 @@ go_test( ], embed = [":go_default_library"], deps = [ + "//beacon-chain/blockchain/testing:go_default_library", + "//beacon-chain/core/signing:go_default_library", + "//beacon-chain/rpc/testutil:go_default_library", + "//beacon-chain/state/stategen/mock:go_default_library", + "//config/params:go_default_library", + "//consensus-types/blocks:go_default_library", + "//crypto/bls:go_default_library", + "//encoding/bytesutil:go_default_library", + "//proto/prysm/v1alpha1:go_default_library", "//testing/assert:go_default_library", "//testing/require:go_default_library", + "//testing/util:go_default_library", + "@com_github_prysmaticlabs_go_bitfield//:go_default_library", ], ) diff --git a/beacon-chain/rpc/eth/rewards/handlers.go b/beacon-chain/rpc/eth/rewards/handlers.go index c7e5f4572e37..f18111cc1445 100644 --- a/beacon-chain/rpc/eth/rewards/handlers.go +++ b/beacon-chain/rpc/eth/rewards/handlers.go @@ -27,13 +27,13 @@ func (s *Server) BlockRewards(w http.ResponseWriter, r *http.Request) { } if blk.Version() == version.Phase0 { errJson := &helpers.DefaultErrorJson{ - Message: errors.Wrapf(err, "block rewards are not supported for Phase 0 blocks").Error(), + Message: "block rewards are not supported for Phase 0 blocks", Code: http.StatusBadRequest, } helpers.WriteError(w, errJson) return } - st, err := s.CanonicalHistory.ReplayerForSlot(blk.Block().Slot()-1).ReplayToSlot(r.Context(), blk.Block().Slot()) + st, err := s.ReplayerBuilder.ReplayerForSlot(blk.Block().Slot()-1).ReplayToSlot(r.Context(), blk.Block().Slot()) if err != nil { errJson := &helpers.DefaultErrorJson{ Message: errors.Wrapf(err, "could not get state").Error(), diff --git a/beacon-chain/rpc/eth/rewards/handlers_test.go b/beacon-chain/rpc/eth/rewards/handlers_test.go index 9286518e4a2e..cb1ba8cbab0a 100644 --- a/beacon-chain/rpc/eth/rewards/handlers_test.go +++ b/beacon-chain/rpc/eth/rewards/handlers_test.go @@ -1,7 +1,134 @@ package rewards -import "testing" +import ( + "bytes" + "net/http/httptest" + "testing" + + "github.com/prysmaticlabs/go-bitfield" + mock "github.com/prysmaticlabs/prysm/v3/beacon-chain/blockchain/testing" + "github.com/prysmaticlabs/prysm/v3/beacon-chain/core/signing" + "github.com/prysmaticlabs/prysm/v3/beacon-chain/rpc/testutil" + mockstategen "github.com/prysmaticlabs/prysm/v3/beacon-chain/state/stategen/mock" + "github.com/prysmaticlabs/prysm/v3/config/params" + "github.com/prysmaticlabs/prysm/v3/consensus-types/blocks" + "github.com/prysmaticlabs/prysm/v3/crypto/bls" + "github.com/prysmaticlabs/prysm/v3/encoding/bytesutil" + eth "github.com/prysmaticlabs/prysm/v3/proto/prysm/v1alpha1" + "github.com/prysmaticlabs/prysm/v3/testing/require" + "github.com/prysmaticlabs/prysm/v3/testing/util" +) func TestBlockRewards(t *testing.T) { + valCount := 64 + + st, err := util.NewBeaconStateAltair() + require.NoError(t, st.SetSlot(1)) + require.NoError(t, err) + validators := make([]*eth.Validator, 0, valCount) + balances := make([]uint64, 0, valCount) + keys := make([]bls.SecretKey, 0, valCount) + for i := 0; i < valCount; i++ { + blsKey, err := bls.RandKey() + require.NoError(t, err) + keys = append(keys, blsKey) + validators = append(validators, ð.Validator{ + PublicKey: blsKey.PublicKey().Marshal(), + ExitEpoch: params.BeaconConfig().FarFutureEpoch, + WithdrawableEpoch: params.BeaconConfig().FarFutureEpoch, + EffectiveBalance: params.BeaconConfig().MaxEffectiveBalance, + }) + balances = append(balances, params.BeaconConfig().MaxEffectiveBalance) + } + require.NoError(t, st.SetValidators(validators)) + require.NoError(t, st.SetBalances(balances)) + require.NoError(t, st.SetCurrentParticipationBits(make([]byte, valCount))) + + b := util.NewBeaconBlockAltair() + b.Block.Slot = 2 + // we have to set the proposer index to the value that will be randomly chosen (fortunately it's deterministic) + b.Block.ProposerIndex = 12 + b.Block.Body.Attestations = []*eth.Attestation{ + { + AggregationBits: bitfield.Bitlist{0b00000111}, + Data: util.HydrateAttestationData(ð.AttestationData{}), + }, + { + AggregationBits: bitfield.Bitlist{0b00000111}, + Data: util.HydrateAttestationData(ð.AttestationData{}), + }, + } + attData1 := util.HydrateAttestationData(ð.AttestationData{BeaconBlockRoot: bytesutil.PadTo([]byte("root1"), 32)}) + attData2 := util.HydrateAttestationData(ð.AttestationData{BeaconBlockRoot: bytesutil.PadTo([]byte("root2"), 32)}) + domain, err := signing.Domain(st.Fork(), 0, params.BeaconConfig().DomainBeaconAttester, st.GenesisValidatorsRoot()) + require.NoError(t, err) + sigRoot1, err := signing.ComputeSigningRoot(attData1, domain) + require.NoError(t, err) + sigRoot2, err := signing.ComputeSigningRoot(attData2, domain) + require.NoError(t, err) + b.Block.Body.AttesterSlashings = []*eth.AttesterSlashing{ + { + Attestation_1: ð.IndexedAttestation{ + AttestingIndices: []uint64{0}, + Data: attData1, + Signature: keys[0].Sign(sigRoot1[:]).Marshal(), + }, + Attestation_2: ð.IndexedAttestation{ + AttestingIndices: []uint64{0}, + Data: attData2, + Signature: keys[0].Sign(sigRoot2[:]).Marshal(), + }, + }, + } + header1 := ð.BeaconBlockHeader{ + Slot: 0, + ProposerIndex: 1, + ParentRoot: bytesutil.PadTo([]byte("root1"), 32), + StateRoot: bytesutil.PadTo([]byte("root1"), 32), + BodyRoot: bytesutil.PadTo([]byte("root1"), 32), + } + header2 := ð.BeaconBlockHeader{ + Slot: 0, + ProposerIndex: 1, + ParentRoot: bytesutil.PadTo([]byte("root2"), 32), + StateRoot: bytesutil.PadTo([]byte("root2"), 32), + BodyRoot: bytesutil.PadTo([]byte("root2"), 32), + } + domain, err = signing.Domain(st.Fork(), 0, params.BeaconConfig().DomainBeaconProposer, st.GenesisValidatorsRoot()) + require.NoError(t, err) + sigRoot1, err = signing.ComputeSigningRoot(header1, domain) + require.NoError(t, err) + sigRoot2, err = signing.ComputeSigningRoot(header2, domain) + require.NoError(t, err) + b.Block.Body.ProposerSlashings = []*eth.ProposerSlashing{ + { + Header_1: ð.SignedBeaconBlockHeader{ + Header: header1, + Signature: keys[1].Sign(sigRoot1[:]).Marshal(), + }, + Header_2: ð.SignedBeaconBlockHeader{ + Header: header2, + Signature: keys[1].Sign(sigRoot2[:]).Marshal(), + }, + }, + } + + sbb, err := blocks.NewSignedBeaconBlock(b) + require.NoError(t, err) + mockChainService := &mock.ChainService{} + s := &Server{ + BlockFetcher: &testutil.MockBlockFetcher{BlockToReturn: sbb}, + OptimisticModeFetcher: mockChainService, + FinalizationFetcher: mockChainService, + ReplayerBuilder: mockstategen.NewMockReplayerBuilder(mockstategen.WithMockState(st)), + } + + t.Run("ok", func(t *testing.T) { + url := "http://only.the.slot.number.at.the.end.is.important/0" + request := httptest.NewRequest("GET", url, nil) + writer := httptest.NewRecorder() + writer.Body = &bytes.Buffer{} + s.BlockRewards(writer, request) + }) } diff --git a/beacon-chain/rpc/eth/rewards/server.go b/beacon-chain/rpc/eth/rewards/server.go index cd255361bae8..35727d071387 100644 --- a/beacon-chain/rpc/eth/rewards/server.go +++ b/beacon-chain/rpc/eth/rewards/server.go @@ -3,14 +3,12 @@ package rewards import ( "github.com/prysmaticlabs/prysm/v3/beacon-chain/blockchain" "github.com/prysmaticlabs/prysm/v3/beacon-chain/rpc/blockfetcher" - "github.com/prysmaticlabs/prysm/v3/beacon-chain/rpc/statefetcher" "github.com/prysmaticlabs/prysm/v3/beacon-chain/state/stategen" ) type Server struct { BlockFetcher blockfetcher.Fetcher - StateFetcher statefetcher.Fetcher OptimisticModeFetcher blockchain.OptimisticModeFetcher FinalizationFetcher blockchain.FinalizationFetcher - CanonicalHistory *stategen.CanonicalHistory + ReplayerBuilder stategen.ReplayerBuilder } diff --git a/beacon-chain/rpc/service.go b/beacon-chain/rpc/service.go index 8c7460e84e4f..10ffd1274ad5 100644 --- a/beacon-chain/rpc/service.go +++ b/beacon-chain/rpc/service.go @@ -457,22 +457,15 @@ func (s *Service) logNewClientConnection(ctx context.Context) { } } -func (s *Service) registerHTTPHandlers(ch *stategen.CanonicalHistory) { +func (s *Service) registerHTTPHandlers(replayer stategen.ReplayerBuilder) { rewardsServer := &rewards.Server{ BlockFetcher: &blockfetcher.BlockProvider{ BeaconDB: s.cfg.BeaconDB, ChainInfoFetcher: s.cfg.ChainInfoFetcher, }, - StateFetcher: &statefetcher.StateProvider{ - BeaconDB: s.cfg.BeaconDB, - ChainInfoFetcher: s.cfg.ChainInfoFetcher, - GenesisTimeFetcher: s.cfg.GenesisTimeFetcher, - StateGenService: s.cfg.StateGen, - ReplayerBuilder: ch, - }, OptimisticModeFetcher: s.cfg.OptimisticModeFetcher, FinalizationFetcher: s.cfg.FinalizationFetcher, - CanonicalHistory: ch, + ReplayerBuilder: replayer, } s.cfg.Router.HandleFunc("/eth/v1/beacon/rewards/blocks/{block_id}", rewardsServer.BlockRewards) } From 9bac92aa1f077bb322cee99c13c3bbe4e8d348f7 Mon Sep 17 00:00:00 2001 From: rkapka Date: Mon, 20 Mar 2023 17:23:36 +0100 Subject: [PATCH 18/40] complete test --- beacon-chain/rpc/eth/rewards/BUILD.bazel | 6 ++ beacon-chain/rpc/eth/rewards/handlers_test.go | 84 +++++++++++++++++-- .../rpc/testutil/mock_block_fetcher.go | 11 ++- 3 files changed, 90 insertions(+), 11 deletions(-) diff --git a/beacon-chain/rpc/eth/rewards/BUILD.bazel b/beacon-chain/rpc/eth/rewards/BUILD.bazel index 07a65c04aac5..0535dec3d0e5 100644 --- a/beacon-chain/rpc/eth/rewards/BUILD.bazel +++ b/beacon-chain/rpc/eth/rewards/BUILD.bazel @@ -34,12 +34,18 @@ go_test( embed = [":go_default_library"], deps = [ "//beacon-chain/blockchain/testing:go_default_library", + "//beacon-chain/core/altair:go_default_library", "//beacon-chain/core/signing:go_default_library", + "//beacon-chain/rpc/eth/helpers:go_default_library", "//beacon-chain/rpc/testutil:go_default_library", "//beacon-chain/state/stategen/mock:go_default_library", + "//config/fieldparams:go_default_library", "//config/params:go_default_library", "//consensus-types/blocks:go_default_library", + "//consensus-types/interfaces:go_default_library", + "//consensus-types/primitives:go_default_library", "//crypto/bls:go_default_library", + "//crypto/bls/blst:go_default_library", "//encoding/bytesutil:go_default_library", "//proto/prysm/v1alpha1:go_default_library", "//testing/assert:go_default_library", diff --git a/beacon-chain/rpc/eth/rewards/handlers_test.go b/beacon-chain/rpc/eth/rewards/handlers_test.go index cb1ba8cbab0a..c1b1a580b6e6 100644 --- a/beacon-chain/rpc/eth/rewards/handlers_test.go +++ b/beacon-chain/rpc/eth/rewards/handlers_test.go @@ -2,19 +2,29 @@ package rewards import ( "bytes" + "context" + "encoding/json" + "net/http" "net/http/httptest" "testing" "github.com/prysmaticlabs/go-bitfield" mock "github.com/prysmaticlabs/prysm/v3/beacon-chain/blockchain/testing" + "github.com/prysmaticlabs/prysm/v3/beacon-chain/core/altair" "github.com/prysmaticlabs/prysm/v3/beacon-chain/core/signing" + "github.com/prysmaticlabs/prysm/v3/beacon-chain/rpc/eth/helpers" "github.com/prysmaticlabs/prysm/v3/beacon-chain/rpc/testutil" mockstategen "github.com/prysmaticlabs/prysm/v3/beacon-chain/state/stategen/mock" + fieldparams "github.com/prysmaticlabs/prysm/v3/config/fieldparams" "github.com/prysmaticlabs/prysm/v3/config/params" "github.com/prysmaticlabs/prysm/v3/consensus-types/blocks" + "github.com/prysmaticlabs/prysm/v3/consensus-types/interfaces" + "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" "github.com/prysmaticlabs/prysm/v3/crypto/bls" + "github.com/prysmaticlabs/prysm/v3/crypto/bls/blst" "github.com/prysmaticlabs/prysm/v3/encoding/bytesutil" eth "github.com/prysmaticlabs/prysm/v3/proto/prysm/v1alpha1" + "github.com/prysmaticlabs/prysm/v3/testing/assert" "github.com/prysmaticlabs/prysm/v3/testing/require" "github.com/prysmaticlabs/prysm/v3/testing/util" ) @@ -27,11 +37,12 @@ func TestBlockRewards(t *testing.T) { require.NoError(t, err) validators := make([]*eth.Validator, 0, valCount) balances := make([]uint64, 0, valCount) - keys := make([]bls.SecretKey, 0, valCount) + secretKeys := make([]bls.SecretKey, 0, valCount) + pubkeys := make([][]byte, 0, valCount) for i := 0; i < valCount; i++ { blsKey, err := bls.RandKey() require.NoError(t, err) - keys = append(keys, blsKey) + secretKeys = append(secretKeys, blsKey) validators = append(validators, ð.Validator{ PublicKey: blsKey.PublicKey().Marshal(), ExitEpoch: params.BeaconConfig().FarFutureEpoch, @@ -39,12 +50,20 @@ func TestBlockRewards(t *testing.T) { EffectiveBalance: params.BeaconConfig().MaxEffectiveBalance, }) balances = append(balances, params.BeaconConfig().MaxEffectiveBalance) + pubkeys = append(pubkeys, blsKey.PublicKey().Marshal()) } require.NoError(t, st.SetValidators(validators)) require.NoError(t, st.SetBalances(balances)) require.NoError(t, st.SetCurrentParticipationBits(make([]byte, valCount))) + syncCommittee, err := altair.NextSyncCommittee(context.Background(), st) + require.NoError(t, err) + require.NoError(t, st.SetCurrentSyncCommittee(syncCommittee)) + slot0bRoot := bytesutil.PadTo([]byte("slot0root"), 32) + bRoots := make([][]byte, fieldparams.BlockRootsLength) + bRoots[0] = slot0bRoot + require.NoError(t, st.SetBlockRoots(bRoots)) - b := util.NewBeaconBlockAltair() + b := util.HydrateSignedBeaconBlockAltair(util.NewBeaconBlockAltair()) b.Block.Slot = 2 // we have to set the proposer index to the value that will be randomly chosen (fortunately it's deterministic) b.Block.ProposerIndex = 12 @@ -52,10 +71,12 @@ func TestBlockRewards(t *testing.T) { { AggregationBits: bitfield.Bitlist{0b00000111}, Data: util.HydrateAttestationData(ð.AttestationData{}), + Signature: make([]byte, fieldparams.BLSSignatureLength), }, { AggregationBits: bitfield.Bitlist{0b00000111}, Data: util.HydrateAttestationData(ð.AttestationData{}), + Signature: make([]byte, fieldparams.BLSSignatureLength), }, } attData1 := util.HydrateAttestationData(ð.AttestationData{BeaconBlockRoot: bytesutil.PadTo([]byte("root1"), 32)}) @@ -71,12 +92,12 @@ func TestBlockRewards(t *testing.T) { Attestation_1: ð.IndexedAttestation{ AttestingIndices: []uint64{0}, Data: attData1, - Signature: keys[0].Sign(sigRoot1[:]).Marshal(), + Signature: secretKeys[0].Sign(sigRoot1[:]).Marshal(), }, Attestation_2: ð.IndexedAttestation{ AttestingIndices: []uint64{0}, Data: attData2, - Signature: keys[0].Sign(sigRoot2[:]).Marshal(), + Signature: secretKeys[0].Sign(sigRoot2[:]).Marshal(), }, }, } @@ -104,31 +125,76 @@ func TestBlockRewards(t *testing.T) { { Header_1: ð.SignedBeaconBlockHeader{ Header: header1, - Signature: keys[1].Sign(sigRoot1[:]).Marshal(), + Signature: secretKeys[1].Sign(sigRoot1[:]).Marshal(), }, Header_2: ð.SignedBeaconBlockHeader{ Header: header2, - Signature: keys[1].Sign(sigRoot2[:]).Marshal(), + Signature: secretKeys[1].Sign(sigRoot2[:]).Marshal(), }, }, } + scBits := bitfield.NewBitvector512() + scBits.SetBitAt(10, true) + scBits.SetBitAt(100, true) + domain, err = signing.Domain(st.Fork(), 0, params.BeaconConfig().DomainSyncCommittee, st.GenesisValidatorsRoot()) + require.NoError(t, err) + 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()) + require.NoError(t, err) + sig2, err := blst.SignatureFromBytes(secretKeys[19].Sign(r[:]).Marshal()) + require.NoError(t, err) + aggSig := bls.AggregateSignatures([]bls.Signature{sig1, sig2}).Marshal() + b.Block.Body.SyncAggregate = ð.SyncAggregate{SyncCommitteeBits: scBits, SyncCommitteeSignature: aggSig} sbb, err := blocks.NewSignedBeaconBlock(b) require.NoError(t, err) - mockChainService := &mock.ChainService{} + phase0block, err := blocks.NewSignedBeaconBlock(util.NewBeaconBlock()) + require.NoError(t, err) + mockChainService := &mock.ChainService{Optimistic: true} s := &Server{ - BlockFetcher: &testutil.MockBlockFetcher{BlockToReturn: sbb}, + BlockFetcher: &testutil.MockBlockFetcher{SlotBlockMap: map[primitives.Slot]interfaces.ReadOnlySignedBeaconBlock{ + 0: phase0block, + 2: sbb, + }}, OptimisticModeFetcher: mockChainService, FinalizationFetcher: mockChainService, ReplayerBuilder: mockstategen.NewMockReplayerBuilder(mockstategen.WithMockState(st)), } t.Run("ok", func(t *testing.T) { + 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) + assert.Equal(t, http.StatusOK, writer.Code) + resp := &BlockRewardsResponse{} + require.NoError(t, json.Unmarshal(writer.Body.Bytes(), resp)) + assert.Equal(t, primitives.ValidatorIndex(12), resp.Data.ProposerIndex) + assert.Equal(t, uint64(125089490), resp.Data.Total) + assert.Equal(t, uint64(89442), resp.Data.Attestations) + assert.Equal(t, uint64(48), resp.Data.SyncAggregate) + assert.Equal(t, uint64(62500000), resp.Data.AttesterSlashings) + assert.Equal(t, uint64(62500000), resp.Data.ProposerSlashings) + assert.Equal(t, true, resp.ExecutionOptimistic) + assert.Equal(t, false, resp.Finalized) + }) + t.Run("phase 0", func(t *testing.T) { url := "http://only.the.slot.number.at.the.end.is.important/0" request := httptest.NewRequest("GET", url, nil) writer := httptest.NewRecorder() writer.Body = &bytes.Buffer{} s.BlockRewards(writer, request) + assert.Equal(t, http.StatusBadRequest, writer.Code) + e := &helpers.DefaultErrorJson{} + require.NoError(t, json.Unmarshal(writer.Body.Bytes(), e)) + assert.Equal(t, http.StatusBadRequest, e.Code) + assert.Equal(t, "block rewards are not supported for Phase 0 blocks", e.Message) }) } diff --git a/beacon-chain/rpc/testutil/mock_block_fetcher.go b/beacon-chain/rpc/testutil/mock_block_fetcher.go index 36c032122c30..59899d7f2e8c 100644 --- a/beacon-chain/rpc/testutil/mock_block_fetcher.go +++ b/beacon-chain/rpc/testutil/mock_block_fetcher.go @@ -2,19 +2,26 @@ package testutil import ( "context" + "strconv" "github.com/prysmaticlabs/prysm/v3/consensus-types/interfaces" + "github.com/prysmaticlabs/prysm/v3/consensus-types/primitives" ) // MockBlockFetcher is a fake implementation of blockfetcher.Fetcher. type MockBlockFetcher struct { BlockToReturn interfaces.ReadOnlySignedBeaconBlock ErrorToReturn error + SlotBlockMap map[primitives.Slot]interfaces.ReadOnlySignedBeaconBlock } -func (m *MockBlockFetcher) Block(_ context.Context, _ []byte) (interfaces.ReadOnlySignedBeaconBlock, error) { +func (m *MockBlockFetcher) Block(_ context.Context, b []byte) (interfaces.ReadOnlySignedBeaconBlock, error) { if m.ErrorToReturn != nil { return nil, m.ErrorToReturn } - return m.BlockToReturn, nil + slotNumber, parseErr := strconv.ParseUint(string(b), 10, 64) + if parseErr != nil { + return m.BlockToReturn, nil + } + return m.SlotBlockMap[primitives.Slot(slotNumber)], nil } From 9cd5c2b82a6a3522fd7e6eaed9ba4c37230f043a Mon Sep 17 00:00:00 2001 From: rkapka Date: Mon, 20 Mar 2023 17:47:15 +0100 Subject: [PATCH 19/40] gzl --- beacon-chain/rpc/BUILD.bazel | 4 ---- beacon-chain/rpc/blockfetcher/BUILD.bazel | 13 +------------ beacon-chain/rpc/eth/beacon/BUILD.bazel | 4 ++++ beacon-chain/rpc/eth/rewards/BUILD.bazel | 2 +- 4 files changed, 6 insertions(+), 17 deletions(-) diff --git a/beacon-chain/rpc/BUILD.bazel b/beacon-chain/rpc/BUILD.bazel index aa9e39ab77f3..0f0d79f4e2f5 100644 --- a/beacon-chain/rpc/BUILD.bazel +++ b/beacon-chain/rpc/BUILD.bazel @@ -24,12 +24,10 @@ go_library( "//beacon-chain/operations/synccommittee:go_default_library", "//beacon-chain/operations/voluntaryexits:go_default_library", "//beacon-chain/p2p:go_default_library", - "//beacon-chain/rpc/blockfetcher:go_default_library", "//beacon-chain/rpc/eth/beacon:go_default_library", "//beacon-chain/rpc/eth/debug:go_default_library", "//beacon-chain/rpc/eth/events:go_default_library", "//beacon-chain/rpc/eth/node:go_default_library", - "//beacon-chain/rpc/eth/rewards:go_default_library", "//beacon-chain/rpc/eth/validator:go_default_library", "//beacon-chain/rpc/prysm/v1alpha1/beacon:go_default_library", "//beacon-chain/rpc/prysm/v1alpha1/debug:go_default_library", @@ -45,7 +43,6 @@ go_library( "//monitoring/tracing:go_default_library", "//proto/eth/service:go_default_library", "//proto/prysm/v1alpha1:go_default_library", - "@com_github_gorilla_mux//:go_default_library", "@com_github_grpc_ecosystem_go_grpc_middleware//:go_default_library", "@com_github_grpc_ecosystem_go_grpc_middleware//recovery:go_default_library", "@com_github_grpc_ecosystem_go_grpc_middleware//tracing/opentracing:go_default_library", @@ -71,7 +68,6 @@ go_test( "//beacon-chain/sync/initial-sync/testing:go_default_library", "//testing/assert:go_default_library", "//testing/require:go_default_library", - "@com_github_gorilla_mux//:go_default_library", "@com_github_sirupsen_logrus//:go_default_library", "@com_github_sirupsen_logrus//hooks/test:go_default_library", ], diff --git a/beacon-chain/rpc/blockfetcher/BUILD.bazel b/beacon-chain/rpc/blockfetcher/BUILD.bazel index 084ef5ec110c..364778825daf 100644 --- a/beacon-chain/rpc/blockfetcher/BUILD.bazel +++ b/beacon-chain/rpc/blockfetcher/BUILD.bazel @@ -3,7 +3,7 @@ load("@prysm//tools/go:def.bzl", "go_library", "go_test") go_library( name = "go_default_library", srcs = ["fetcher.go"], - importpath = "github.com/prysmaticlabs/prysm/v3/beacon-chain/rpc/blockfetcher", + importpath = "github.com/prysmaticlabs/prysm/v4/beacon-chain/rpc/blockfetcher", visibility = ["//visibility:public"], deps = [ "//beacon-chain/blockchain:go_default_library", @@ -19,15 +19,4 @@ go_test( name = "go_default_test", srcs = ["fetcher_test.go"], embed = [":go_default_library"], - deps = [ - "//beacon-chain/blockchain/testing:go_default_library", - "//beacon-chain/db/testing:go_default_library", - "//beacon-chain/rpc/testutil:go_default_library", - "//consensus-types/blocks:go_default_library", - "//encoding/bytesutil:go_default_library", - "//proto/prysm/v1alpha1:go_default_library", - "//testing/assert:go_default_library", - "//testing/require:go_default_library", - "//testing/util:go_default_library", - ], ) diff --git a/beacon-chain/rpc/eth/beacon/BUILD.bazel b/beacon-chain/rpc/eth/beacon/BUILD.bazel index b3f3a3ed2790..3f73c68eaea8 100644 --- a/beacon-chain/rpc/eth/beacon/BUILD.bazel +++ b/beacon-chain/rpc/eth/beacon/BUILD.bazel @@ -91,7 +91,9 @@ go_test( "//beacon-chain/core/signing:go_default_library", "//beacon-chain/core/time:go_default_library", "//beacon-chain/core/transition:go_default_library", + "//beacon-chain/db:go_default_library", "//beacon-chain/db/testing:go_default_library", + "//beacon-chain/execution/testing:go_default_library", "//beacon-chain/operations/attestations:go_default_library", "//beacon-chain/operations/blstoexec:go_default_library", "//beacon-chain/operations/blstoexec/mock:go_default_library", @@ -105,8 +107,10 @@ go_test( "//beacon-chain/rpc/testutil:go_default_library", "//beacon-chain/state:go_default_library", "//beacon-chain/state/state-native:go_default_library", + "//config/features:go_default_library", "//config/params:go_default_library", "//consensus-types/blocks:go_default_library", + "//consensus-types/interfaces:go_default_library", "//consensus-types/primitives:go_default_library", "//crypto/bls:go_default_library", "//crypto/bls/common:go_default_library", diff --git a/beacon-chain/rpc/eth/rewards/BUILD.bazel b/beacon-chain/rpc/eth/rewards/BUILD.bazel index 0535dec3d0e5..7a6d4900d24d 100644 --- a/beacon-chain/rpc/eth/rewards/BUILD.bazel +++ b/beacon-chain/rpc/eth/rewards/BUILD.bazel @@ -7,7 +7,7 @@ go_library( "server.go", "structs.go", ], - importpath = "github.com/prysmaticlabs/prysm/v3/beacon-chain/rpc/eth/rewards", + importpath = "github.com/prysmaticlabs/prysm/v4/beacon-chain/rpc/eth/rewards", visibility = ["//visibility:public"], deps = [ "//beacon-chain/blockchain:go_default_library", From 0d649e755a1ce4dd881319b9737ebe657ed2e5cb Mon Sep 17 00:00:00 2001 From: rkapka Date: Mon, 20 Mar 2023 18:44:12 +0100 Subject: [PATCH 20/40] import fix --- beacon-chain/rpc/eth/rewards/structs_test.go | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/beacon-chain/rpc/eth/rewards/structs_test.go b/beacon-chain/rpc/eth/rewards/structs_test.go index 47c3af97b7c5..66c6fcec9d8a 100644 --- a/beacon-chain/rpc/eth/rewards/structs_test.go +++ b/beacon-chain/rpc/eth/rewards/structs_test.go @@ -4,9 +4,9 @@ import ( "encoding/json" "testing" - "github.com/prysmaticlabs/prysm/v3/beacon-chain/rpc/eth/rewards" - "github.com/prysmaticlabs/prysm/v3/testing/assert" - "github.com/prysmaticlabs/prysm/v3/testing/require" + "github.com/prysmaticlabs/prysm/v4/beacon-chain/rpc/eth/rewards" + "github.com/prysmaticlabs/prysm/v4/testing/assert" + "github.com/prysmaticlabs/prysm/v4/testing/require" ) func TestMarshalBlockRewards(t *testing.T) { From dc717a3a3db8aa2380b1d8473588991f31b5cb51 Mon Sep 17 00:00:00 2001 From: rkapka Date: Mon, 20 Mar 2023 18:47:57 +0100 Subject: [PATCH 21/40] import fix once more --- beacon-chain/rpc/blockfetcher/BUILD.bazel | 11 +++++++++++ beacon-chain/rpc/blockfetcher/fetcher_test.go | 18 +++++++++--------- 2 files changed, 20 insertions(+), 9 deletions(-) diff --git a/beacon-chain/rpc/blockfetcher/BUILD.bazel b/beacon-chain/rpc/blockfetcher/BUILD.bazel index 364778825daf..5b8dc280ff3a 100644 --- a/beacon-chain/rpc/blockfetcher/BUILD.bazel +++ b/beacon-chain/rpc/blockfetcher/BUILD.bazel @@ -19,4 +19,15 @@ go_test( name = "go_default_test", srcs = ["fetcher_test.go"], embed = [":go_default_library"], + deps = [ + "//beacon-chain/blockchain/testing:go_default_library", + "//beacon-chain/db/testing:go_default_library", + "//beacon-chain/rpc/testutil:go_default_library", + "//consensus-types/blocks:go_default_library", + "//encoding/bytesutil:go_default_library", + "//proto/prysm/v1alpha1:go_default_library", + "//testing/assert:go_default_library", + "//testing/require:go_default_library", + "//testing/util:go_default_library", + ], ) diff --git a/beacon-chain/rpc/blockfetcher/fetcher_test.go b/beacon-chain/rpc/blockfetcher/fetcher_test.go index b4da149f88b0..efb7ffb94b79 100644 --- a/beacon-chain/rpc/blockfetcher/fetcher_test.go +++ b/beacon-chain/rpc/blockfetcher/fetcher_test.go @@ -6,15 +6,15 @@ import ( "reflect" "testing" - mock "github.com/prysmaticlabs/prysm/v3/beacon-chain/blockchain/testing" - dbtesting "github.com/prysmaticlabs/prysm/v3/beacon-chain/db/testing" - "github.com/prysmaticlabs/prysm/v3/beacon-chain/rpc/testutil" - "github.com/prysmaticlabs/prysm/v3/consensus-types/blocks" - "github.com/prysmaticlabs/prysm/v3/encoding/bytesutil" - ethpbalpha "github.com/prysmaticlabs/prysm/v3/proto/prysm/v1alpha1" - "github.com/prysmaticlabs/prysm/v3/testing/assert" - "github.com/prysmaticlabs/prysm/v3/testing/require" - "github.com/prysmaticlabs/prysm/v3/testing/util" + mock "github.com/prysmaticlabs/prysm/v4/beacon-chain/blockchain/testing" + dbtesting "github.com/prysmaticlabs/prysm/v4/beacon-chain/db/testing" + "github.com/prysmaticlabs/prysm/v4/beacon-chain/rpc/testutil" + "github.com/prysmaticlabs/prysm/v4/consensus-types/blocks" + "github.com/prysmaticlabs/prysm/v4/encoding/bytesutil" + ethpbalpha "github.com/prysmaticlabs/prysm/v4/proto/prysm/v1alpha1" + "github.com/prysmaticlabs/prysm/v4/testing/assert" + "github.com/prysmaticlabs/prysm/v4/testing/require" + "github.com/prysmaticlabs/prysm/v4/testing/util" ) func TestGetBlock(t *testing.T) { From eb4a48eacfe7d8c33515f87c4f4ef3c092500958 Mon Sep 17 00:00:00 2001 From: rkapka Date: Tue, 21 Mar 2023 15:17:05 +0100 Subject: [PATCH 22/40] remove unused function --- beacon-chain/rpc/eth/beacon/blocks_test.go | 58 ---------------------- 1 file changed, 58 deletions(-) diff --git a/beacon-chain/rpc/eth/beacon/blocks_test.go b/beacon-chain/rpc/eth/beacon/blocks_test.go index 762fe8477f23..53051f7949fb 100644 --- a/beacon-chain/rpc/eth/beacon/blocks_test.go +++ b/beacon-chain/rpc/eth/beacon/blocks_test.go @@ -291,64 +291,6 @@ func fillDBTestBlocksBellatrixBlinded(ctx context.Context, t *testing.T, beaconD return genBlk, blkContainers } -func fillDBTestBlocksCapellaBlinded(ctx context.Context, t *testing.T, beaconDB db.Database) (*ethpbalpha.SignedBlindedBeaconBlockCapella, []*ethpbalpha.BeaconBlockContainer) { - parentRoot := [32]byte{1, 2, 3} - genBlk := util.NewBlindedBeaconBlockCapella() - genBlk.Block.ParentRoot = parentRoot[:] - root, err := genBlk.Block.HashTreeRoot() - require.NoError(t, err) - util.SaveBlock(t, ctx, beaconDB, genBlk) - require.NoError(t, beaconDB.SaveGenesisBlockRoot(ctx, root)) - - count := primitives.Slot(100) - blks := make([]interfaces.ReadOnlySignedBeaconBlock, count) - blkContainers := make([]*ethpbalpha.BeaconBlockContainer, count) - for i := primitives.Slot(0); i < count; i++ { - b := util.NewBlindedBeaconBlockCapella() - b.Block.Slot = i - b.Block.ParentRoot = bytesutil.PadTo([]byte{uint8(i)}, 32) - syncCommitteeBits := bitfield.NewBitvector512() - syncCommitteeBits.SetBitAt(100, true) - b.Block.Body.SyncAggregate = ðpbalpha.SyncAggregate{ - SyncCommitteeBits: syncCommitteeBits, - SyncCommitteeSignature: bytesutil.PadTo([]byte("signature"), 96), - } - b.Block.Body.ExecutionPayloadHeader = &enginev1.ExecutionPayloadHeaderCapella{ - ParentHash: bytesutil.PadTo([]byte("parent_hash"), 32), - FeeRecipient: bytesutil.PadTo([]byte("fee_recipient"), 20), - StateRoot: bytesutil.PadTo([]byte("state_root"), 32), - ReceiptsRoot: bytesutil.PadTo([]byte("receipts_root"), 32), - LogsBloom: bytesutil.PadTo([]byte("logs_bloom"), 256), - PrevRandao: bytesutil.PadTo([]byte("prev_randao"), 32), - BlockNumber: 123, - GasLimit: 123, - GasUsed: 123, - Timestamp: 123, - ExtraData: bytesutil.PadTo([]byte("extra_data"), 32), - BaseFeePerGas: bytesutil.PadTo([]byte("base_fee_per_gas"), 32), - BlockHash: bytesutil.PadTo([]byte("block_hash"), 32), - TransactionsRoot: bytesutil.PadTo([]byte("transactions_root"), 32), - WithdrawalsRoot: bytesutil.PadTo([]byte("withdrawals_root"), 32), - } - root, err := b.Block.HashTreeRoot() - require.NoError(t, err) - signedB, err := blocks.NewSignedBeaconBlock(b) - require.NoError(t, err) - blks[i] = signedB - blkContainers[i] = ðpbalpha.BeaconBlockContainer{ - Block: ðpbalpha.BeaconBlockContainer_BlindedCapellaBlock{BlindedCapellaBlock: b}, BlockRoot: root[:]} - } - require.NoError(t, beaconDB.SaveBlocks(ctx, blks)) - headRoot := bytesutil.ToBytes32(blkContainers[len(blks)-1].BlockRoot) - summary := ðpbalpha.StateSummary{ - Root: headRoot[:], - Slot: blkContainers[len(blks)-1].Block.(*ethpbalpha.BeaconBlockContainer_BlindedCapellaBlock).BlindedCapellaBlock.Block.Slot, - } - require.NoError(t, beaconDB.SaveStateSummary(ctx, summary)) - require.NoError(t, beaconDB.SaveHeadBlockRoot(ctx, headRoot)) - return genBlk, blkContainers -} - func TestServer_GetBlockHeader(t *testing.T) { beaconDB := dbTest.SetupDB(t) ctx := context.Background() From dd005477ae94e61f8380db67ce61cfb44498d450 Mon Sep 17 00:00:00 2001 From: rkapka Date: Tue, 21 Mar 2023 17:30:32 +0100 Subject: [PATCH 23/40] fix all tests --- beacon-chain/rpc/eth/beacon/blocks_test.go | 2338 ++++++-------------- 1 file changed, 648 insertions(+), 1690 deletions(-) diff --git a/beacon-chain/rpc/eth/beacon/blocks_test.go b/beacon-chain/rpc/eth/beacon/blocks_test.go index 53051f7949fb..2da13c8d2f72 100644 --- a/beacon-chain/rpc/eth/beacon/blocks_test.go +++ b/beacon-chain/rpc/eth/beacon/blocks_test.go @@ -2,23 +2,19 @@ package beacon import ( "context" - "fmt" - "reflect" "testing" "github.com/prysmaticlabs/go-bitfield" mock "github.com/prysmaticlabs/prysm/v4/beacon-chain/blockchain/testing" "github.com/prysmaticlabs/prysm/v4/beacon-chain/db" dbTest "github.com/prysmaticlabs/prysm/v4/beacon-chain/db/testing" - executionTest "github.com/prysmaticlabs/prysm/v4/beacon-chain/execution/testing" mockp2p "github.com/prysmaticlabs/prysm/v4/beacon-chain/p2p/testing" - "github.com/prysmaticlabs/prysm/v4/config/features" + "github.com/prysmaticlabs/prysm/v4/beacon-chain/rpc/testutil" "github.com/prysmaticlabs/prysm/v4/config/params" "github.com/prysmaticlabs/prysm/v4/consensus-types/blocks" "github.com/prysmaticlabs/prysm/v4/consensus-types/interfaces" "github.com/prysmaticlabs/prysm/v4/consensus-types/primitives" "github.com/prysmaticlabs/prysm/v4/encoding/bytesutil" - enginev1 "github.com/prysmaticlabs/prysm/v4/proto/engine/v1" ethpbv1 "github.com/prysmaticlabs/prysm/v4/proto/eth/v1" ethpbv2 "github.com/prysmaticlabs/prysm/v4/proto/eth/v2" "github.com/prysmaticlabs/prysm/v4/proto/migration" @@ -65,361 +61,63 @@ func fillDBTestBlocks(ctx context.Context, t *testing.T, beaconDB db.Database) ( return genBlk, blkContainers } -func fillDBTestBlocksAltair(ctx context.Context, t *testing.T, beaconDB db.Database) (*ethpbalpha.SignedBeaconBlockAltair, []*ethpbalpha.BeaconBlockContainer) { - parentRoot := [32]byte{1, 2, 3} - genBlk := util.NewBeaconBlockAltair() - genBlk.Block.ParentRoot = parentRoot[:] - root, err := genBlk.Block.HashTreeRoot() - require.NoError(t, err) - util.SaveBlock(t, ctx, beaconDB, genBlk) - require.NoError(t, beaconDB.SaveGenesisBlockRoot(ctx, root)) - - count := primitives.Slot(100) - blks := make([]interfaces.ReadOnlySignedBeaconBlock, count) - blkContainers := make([]*ethpbalpha.BeaconBlockContainer, count) - for i := primitives.Slot(0); i < count; i++ { - b := util.NewBeaconBlockAltair() - b.Block.Slot = i - b.Block.ParentRoot = bytesutil.PadTo([]byte{uint8(i)}, 32) - syncCommitteeBits := bitfield.NewBitvector512() - syncCommitteeBits.SetBitAt(100, true) - b.Block.Body.SyncAggregate = ðpbalpha.SyncAggregate{ - SyncCommitteeBits: syncCommitteeBits, - SyncCommitteeSignature: bytesutil.PadTo([]byte("signature"), 96), - } - root, err := b.Block.HashTreeRoot() - require.NoError(t, err) - signedB, err := blocks.NewSignedBeaconBlock(b) - require.NoError(t, err) - blks[i] = signedB - blkContainers[i] = ðpbalpha.BeaconBlockContainer{ - Block: ðpbalpha.BeaconBlockContainer_AltairBlock{AltairBlock: b}, BlockRoot: root[:]} - } - require.NoError(t, beaconDB.SaveBlocks(ctx, blks)) - headRoot := bytesutil.ToBytes32(blkContainers[len(blks)-1].BlockRoot) - summary := ðpbalpha.StateSummary{ - Root: headRoot[:], - Slot: blkContainers[len(blks)-1].Block.(*ethpbalpha.BeaconBlockContainer_AltairBlock).AltairBlock.Block.Slot, - } - require.NoError(t, beaconDB.SaveStateSummary(ctx, summary)) - require.NoError(t, beaconDB.SaveHeadBlockRoot(ctx, headRoot)) - return genBlk, blkContainers -} - -func fillDBTestBlocksBellatrix(ctx context.Context, t *testing.T, beaconDB db.Database) (*ethpbalpha.SignedBeaconBlockBellatrix, []*ethpbalpha.BeaconBlockContainer) { - parentRoot := [32]byte{1, 2, 3} - genBlk := util.NewBeaconBlockBellatrix() - genBlk.Block.ParentRoot = parentRoot[:] - root, err := genBlk.Block.HashTreeRoot() - require.NoError(t, err) - util.SaveBlock(t, ctx, beaconDB, genBlk) - require.NoError(t, beaconDB.SaveGenesisBlockRoot(ctx, root)) - - count := primitives.Slot(100) - blks := make([]interfaces.ReadOnlySignedBeaconBlock, count) - blkContainers := make([]*ethpbalpha.BeaconBlockContainer, count) - for i := primitives.Slot(0); i < count; i++ { - b := util.NewBeaconBlockBellatrix() - b.Block.Slot = i - b.Block.ParentRoot = bytesutil.PadTo([]byte{uint8(i)}, 32) - syncCommitteeBits := bitfield.NewBitvector512() - syncCommitteeBits.SetBitAt(100, true) - b.Block.Body.SyncAggregate = ðpbalpha.SyncAggregate{ - SyncCommitteeBits: syncCommitteeBits, - SyncCommitteeSignature: bytesutil.PadTo([]byte("signature"), 96), - } - b.Block.Body.ExecutionPayload = &enginev1.ExecutionPayload{ - ParentHash: bytesutil.PadTo([]byte("parent_hash"), 32), - FeeRecipient: bytesutil.PadTo([]byte("fee_recipient"), 20), - StateRoot: bytesutil.PadTo([]byte("state_root"), 32), - ReceiptsRoot: bytesutil.PadTo([]byte("receipts_root"), 32), - LogsBloom: bytesutil.PadTo([]byte("logs_bloom"), 256), - PrevRandao: bytesutil.PadTo([]byte("prev_randao"), 32), - BlockNumber: 123, - GasLimit: 123, - GasUsed: 123, - Timestamp: 123, - ExtraData: bytesutil.PadTo([]byte("extra_data"), 32), - BaseFeePerGas: bytesutil.PadTo([]byte("base_fee_per_gas"), 32), - BlockHash: bytesutil.PadTo([]byte("block_hash"), 32), - Transactions: [][]byte{[]byte("transaction1"), []byte("transaction2")}, - } - root, err := b.Block.HashTreeRoot() - require.NoError(t, err) - signedB, err := blocks.NewSignedBeaconBlock(b) - require.NoError(t, err) - blks[i] = signedB - blkContainers[i] = ðpbalpha.BeaconBlockContainer{ - Block: ðpbalpha.BeaconBlockContainer_BellatrixBlock{BellatrixBlock: b}, BlockRoot: root[:]} - } - require.NoError(t, beaconDB.SaveBlocks(ctx, blks)) - headRoot := bytesutil.ToBytes32(blkContainers[len(blks)-1].BlockRoot) - summary := ðpbalpha.StateSummary{ - Root: headRoot[:], - Slot: blkContainers[len(blks)-1].Block.(*ethpbalpha.BeaconBlockContainer_BellatrixBlock).BellatrixBlock.Block.Slot, - } - require.NoError(t, beaconDB.SaveStateSummary(ctx, summary)) - require.NoError(t, beaconDB.SaveHeadBlockRoot(ctx, headRoot)) - return genBlk, blkContainers -} - -func fillDBTestBlocksCapella(ctx context.Context, t *testing.T, beaconDB db.Database) (*ethpbalpha.SignedBeaconBlockCapella, []*ethpbalpha.BeaconBlockContainer) { - parentRoot := [32]byte{1, 2, 3} - genBlk := util.NewBeaconBlockCapella() - genBlk.Block.ParentRoot = parentRoot[:] - root, err := genBlk.Block.HashTreeRoot() - require.NoError(t, err) - util.SaveBlock(t, ctx, beaconDB, genBlk) - require.NoError(t, beaconDB.SaveGenesisBlockRoot(ctx, root)) - - count := primitives.Slot(100) - blks := make([]interfaces.ReadOnlySignedBeaconBlock, count) - blkContainers := make([]*ethpbalpha.BeaconBlockContainer, count) - for i := primitives.Slot(0); i < count; i++ { - b := util.NewBeaconBlockCapella() - b.Block.Slot = i - b.Block.ParentRoot = bytesutil.PadTo([]byte{uint8(i)}, 32) - syncCommitteeBits := bitfield.NewBitvector512() - syncCommitteeBits.SetBitAt(100, true) - b.Block.Body.SyncAggregate = ðpbalpha.SyncAggregate{ - SyncCommitteeBits: syncCommitteeBits, - SyncCommitteeSignature: bytesutil.PadTo([]byte("signature"), 96), - } - b.Block.Body.ExecutionPayload = &enginev1.ExecutionPayloadCapella{ - ParentHash: bytesutil.PadTo([]byte("parent_hash"), 32), - FeeRecipient: bytesutil.PadTo([]byte("fee_recipient"), 20), - StateRoot: bytesutil.PadTo([]byte("state_root"), 32), - ReceiptsRoot: bytesutil.PadTo([]byte("receipts_root"), 32), - LogsBloom: bytesutil.PadTo([]byte("logs_bloom"), 256), - PrevRandao: bytesutil.PadTo([]byte("prev_randao"), 32), - BlockNumber: 123, - GasLimit: 123, - GasUsed: 123, - Timestamp: 123, - ExtraData: bytesutil.PadTo([]byte("extra_data"), 32), - BaseFeePerGas: bytesutil.PadTo([]byte("base_fee_per_gas"), 32), - BlockHash: bytesutil.PadTo([]byte("block_hash"), 32), - Transactions: [][]byte{[]byte("transaction1"), []byte("transaction2")}, - Withdrawals: []*enginev1.Withdrawal{ - { - Index: 1, - ValidatorIndex: 1, - Address: bytesutil.PadTo([]byte("address1"), 20), - Amount: 1, - }, - { - Index: 2, - ValidatorIndex: 2, - Address: bytesutil.PadTo([]byte("address2"), 20), - Amount: 2, - }, - }, - } - root, err := b.Block.HashTreeRoot() - require.NoError(t, err) - signedB, err := blocks.NewSignedBeaconBlock(b) - require.NoError(t, err) - blks[i] = signedB - blkContainers[i] = ðpbalpha.BeaconBlockContainer{ - Block: ðpbalpha.BeaconBlockContainer_CapellaBlock{CapellaBlock: b}, BlockRoot: root[:]} - } - require.NoError(t, beaconDB.SaveBlocks(ctx, blks)) - headRoot := bytesutil.ToBytes32(blkContainers[len(blks)-1].BlockRoot) - summary := ðpbalpha.StateSummary{ - Root: headRoot[:], - Slot: blkContainers[len(blks)-1].Block.(*ethpbalpha.BeaconBlockContainer_CapellaBlock).CapellaBlock.Block.Slot, - } - require.NoError(t, beaconDB.SaveStateSummary(ctx, summary)) - require.NoError(t, beaconDB.SaveHeadBlockRoot(ctx, headRoot)) - return genBlk, blkContainers -} - -func fillDBTestBlocksBellatrixBlinded(ctx context.Context, t *testing.T, beaconDB db.Database) (*ethpbalpha.SignedBlindedBeaconBlockBellatrix, []*ethpbalpha.BeaconBlockContainer) { - parentRoot := [32]byte{1, 2, 3} - genBlk := util.NewBlindedBeaconBlockBellatrix() - genBlk.Block.ParentRoot = parentRoot[:] - root, err := genBlk.Block.HashTreeRoot() - require.NoError(t, err) - util.SaveBlock(t, ctx, beaconDB, genBlk) - require.NoError(t, beaconDB.SaveGenesisBlockRoot(ctx, root)) - - count := primitives.Slot(100) - blks := make([]interfaces.ReadOnlySignedBeaconBlock, count) - blkContainers := make([]*ethpbalpha.BeaconBlockContainer, count) - for i := primitives.Slot(0); i < count; i++ { - b := util.NewBlindedBeaconBlockBellatrix() - b.Block.Slot = i - b.Block.ParentRoot = bytesutil.PadTo([]byte{uint8(i)}, 32) - syncCommitteeBits := bitfield.NewBitvector512() - syncCommitteeBits.SetBitAt(100, true) - b.Block.Body.SyncAggregate = ðpbalpha.SyncAggregate{ - SyncCommitteeBits: syncCommitteeBits, - SyncCommitteeSignature: bytesutil.PadTo([]byte("signature"), 96), - } - b.Block.Body.ExecutionPayloadHeader = &enginev1.ExecutionPayloadHeader{ - ParentHash: bytesutil.PadTo([]byte("parent_hash"), 32), - FeeRecipient: bytesutil.PadTo([]byte("fee_recipient"), 20), - StateRoot: bytesutil.PadTo([]byte("state_root"), 32), - ReceiptsRoot: bytesutil.PadTo([]byte("receipts_root"), 32), - LogsBloom: bytesutil.PadTo([]byte("logs_bloom"), 256), - PrevRandao: bytesutil.PadTo([]byte("prev_randao"), 32), - BlockNumber: 123, - GasLimit: 123, - GasUsed: 123, - Timestamp: 123, - ExtraData: bytesutil.PadTo([]byte("extra_data"), 32), - BaseFeePerGas: bytesutil.PadTo([]byte("base_fee_per_gas"), 32), - BlockHash: bytesutil.PadTo([]byte("block_hash"), 32), - TransactionsRoot: bytesutil.PadTo([]byte("transactions_root"), 32), - } - root, err := b.Block.HashTreeRoot() - require.NoError(t, err) - signedB, err := blocks.NewSignedBeaconBlock(b) - require.NoError(t, err) - blks[i] = signedB - blkContainers[i] = ðpbalpha.BeaconBlockContainer{ - Block: ðpbalpha.BeaconBlockContainer_BlindedBellatrixBlock{BlindedBellatrixBlock: b}, BlockRoot: root[:]} - } - require.NoError(t, beaconDB.SaveBlocks(ctx, blks)) - headRoot := bytesutil.ToBytes32(blkContainers[len(blks)-1].BlockRoot) - summary := ðpbalpha.StateSummary{ - Root: headRoot[:], - Slot: blkContainers[len(blks)-1].Block.(*ethpbalpha.BeaconBlockContainer_BlindedBellatrixBlock).BlindedBellatrixBlock.Block.Slot, - } - require.NoError(t, beaconDB.SaveStateSummary(ctx, summary)) - require.NoError(t, beaconDB.SaveHeadBlockRoot(ctx, headRoot)) - return genBlk, blkContainers -} - func TestServer_GetBlockHeader(t *testing.T) { - beaconDB := dbTest.SetupDB(t) ctx := context.Background() - - genBlk, blkContainers := fillDBTestBlocks(ctx, t, beaconDB) - root, err := genBlk.Block.HashTreeRoot() + b := util.NewBeaconBlock() + b.Block.Slot = 123 + b.Block.ProposerIndex = 123 + b.Block.StateRoot = bytesutil.PadTo([]byte("stateroot"), 32) + sb, err := blocks.NewSignedBeaconBlock(b) require.NoError(t, err) - headBlock := blkContainers[len(blkContainers)-1] + mockBlockFetcher := &testutil.MockBlockFetcher{BlockToReturn: sb} t.Run("get header", func(t *testing.T) { - wsb, err := blocks.NewSignedBeaconBlock(headBlock.Block.(*ethpbalpha.BeaconBlockContainer_Phase0Block).Phase0Block) - require.NoError(t, err) mockChainService := &mock.ChainService{ - DB: beaconDB, - Block: wsb, - Root: headBlock.BlockRoot, - FinalizedCheckPoint: ðpbalpha.Checkpoint{Root: blkContainers[64].BlockRoot}, - FinalizedRoots: map[[32]byte]bool{}, + FinalizedRoots: map[[32]byte]bool{}, } bs := &Server{ - BeaconDB: beaconDB, ChainInfoFetcher: mockChainService, - HeadFetcher: mockChainService, OptimisticModeFetcher: mockChainService, FinalizationFetcher: mockChainService, + BlockFetcher: mockBlockFetcher, } - tests := []struct { - name string - blockID []byte - want *ethpbalpha.SignedBeaconBlock - wantErr bool - }{ - { - name: "slot", - blockID: []byte("10"), - want: blkContainers[10].Block.(*ethpbalpha.BeaconBlockContainer_Phase0Block).Phase0Block, - }, - { - name: "root", - blockID: blkContainers[20].BlockRoot, - want: blkContainers[20].Block.(*ethpbalpha.BeaconBlockContainer_Phase0Block).Phase0Block, - }, - { - name: "canonical", - blockID: []byte("30"), - want: blkContainers[30].Block.(*ethpbalpha.BeaconBlockContainer_Phase0Block).Phase0Block, - }, - { - name: "genesis", - blockID: []byte("genesis"), - want: genBlk, - }, - { - name: "genesis root", - blockID: root[:], - want: genBlk, - }, - { - name: "head", - blockID: []byte("head"), - want: headBlock.Block.(*ethpbalpha.BeaconBlockContainer_Phase0Block).Phase0Block, - }, - { - name: "finalized", - blockID: []byte("finalized"), - want: blkContainers[64].Block.(*ethpbalpha.BeaconBlockContainer_Phase0Block).Phase0Block, - }, - { - name: "no block", - blockID: []byte("105"), - wantErr: true, - }, - } - for _, tt := range tests { - t.Run(tt.name, func(t *testing.T) { - header, err := bs.GetBlockHeader(ctx, ðpbv1.BlockRequest{ - BlockId: tt.blockID, - }) - if !tt.wantErr { - require.NoError(t, err) - } else { - require.NotEqual(t, err, nil) - return - } - - expectedBodyRoot, err := tt.want.Block.Body.HashTreeRoot() - require.NoError(t, err) - expectedHeader := ðpbv1.BeaconBlockHeader{ - Slot: tt.want.Block.Slot, - ProposerIndex: tt.want.Block.ProposerIndex, - ParentRoot: tt.want.Block.ParentRoot, - StateRoot: make([]byte, 32), - BodyRoot: expectedBodyRoot[:], - } - expectedHeaderRoot, err := expectedHeader.HashTreeRoot() - require.NoError(t, err) - headerRoot, err := header.Data.Header.Message.HashTreeRoot() - require.NoError(t, err) - assert.DeepEqual(t, expectedHeaderRoot, headerRoot) + header, err := bs.GetBlockHeader(ctx, ðpbv1.BlockRequest{}) + require.NoError(t, err) - assert.Equal(t, tt.want.Block.Slot, header.Data.Header.Message.Slot) - assert.DeepEqual(t, tt.want.Block.StateRoot, header.Data.Header.Message.StateRoot) - assert.DeepEqual(t, tt.want.Block.ParentRoot, header.Data.Header.Message.ParentRoot) - expectedRoot, err := tt.want.Block.Body.HashTreeRoot() - require.NoError(t, err) - assert.DeepEqual(t, expectedRoot[:], header.Data.Header.Message.BodyRoot) - assert.Equal(t, tt.want.Block.ProposerIndex, header.Data.Header.Message.ProposerIndex) - }) + expectedBodyRoot, err := sb.Block().Body().HashTreeRoot() + require.NoError(t, err) + expectedParentRoot := sb.Block().ParentRoot() + expectedHeader := ðpbv1.BeaconBlockHeader{ + Slot: sb.Block().Slot(), + ProposerIndex: sb.Block().ProposerIndex(), + ParentRoot: expectedParentRoot[:], + StateRoot: bytesutil.PadTo([]byte("stateroot"), 32), + BodyRoot: expectedBodyRoot[:], } + expectedHeaderRoot, err := expectedHeader.HashTreeRoot() + require.NoError(t, err) + headerRoot, err := header.Data.Header.Message.HashTreeRoot() + require.NoError(t, err) + assert.DeepEqual(t, expectedHeaderRoot, headerRoot) + assert.Equal(t, sb.Block().Slot(), header.Data.Header.Message.Slot) + expectedStateRoot := sb.Block().StateRoot() + assert.DeepEqual(t, expectedStateRoot[:], header.Data.Header.Message.StateRoot) + assert.DeepEqual(t, expectedParentRoot[:], header.Data.Header.Message.ParentRoot) + assert.DeepEqual(t, expectedBodyRoot[:], header.Data.Header.Message.BodyRoot) + assert.Equal(t, sb.Block().ProposerIndex(), header.Data.Header.Message.ProposerIndex) }) t.Run("execution optimistic", func(t *testing.T) { - wsb, err := blocks.NewSignedBeaconBlock(headBlock.Block.(*ethpbalpha.BeaconBlockContainer_Phase0Block).Phase0Block) - require.NoError(t, err) mockChainService := &mock.ChainService{ - DB: beaconDB, - Block: wsb, - Root: headBlock.BlockRoot, - FinalizedCheckPoint: ðpbalpha.Checkpoint{Root: blkContainers[64].BlockRoot}, - Optimistic: true, - FinalizedRoots: map[[32]byte]bool{}, + Optimistic: true, + FinalizedRoots: map[[32]byte]bool{}, } bs := &Server{ - BeaconDB: beaconDB, ChainInfoFetcher: mockChainService, - HeadFetcher: mockChainService, OptimisticModeFetcher: mockChainService, FinalizationFetcher: mockChainService, + BlockFetcher: mockBlockFetcher, } header, err := bs.GetBlockHeader(ctx, ðpbv1.BlockRequest{BlockId: []byte("head")}) require.NoError(t, err) @@ -427,33 +125,32 @@ func TestServer_GetBlockHeader(t *testing.T) { }) t.Run("finalized", func(t *testing.T) { - wsb, err := blocks.NewSignedBeaconBlock(headBlock.Block.(*ethpbalpha.BeaconBlockContainer_Phase0Block).Phase0Block) + r, err := sb.Block().HashTreeRoot() require.NoError(t, err) - mockChainService := &mock.ChainService{ - DB: beaconDB, - Block: wsb, - Root: headBlock.BlockRoot, - FinalizedCheckPoint: ðpbalpha.Checkpoint{Root: blkContainers[64].BlockRoot}, - FinalizedRoots: map[[32]byte]bool{ - bytesutil.ToBytes32(blkContainers[32].BlockRoot): true, - bytesutil.ToBytes32(blkContainers[64].BlockRoot): false, - }, - } - bs := &Server{ - BeaconDB: beaconDB, - ChainInfoFetcher: mockChainService, - HeadFetcher: mockChainService, - OptimisticModeFetcher: mockChainService, - FinalizationFetcher: mockChainService, - } t.Run("true", func(t *testing.T) { - header, err := bs.GetBlockHeader(ctx, ðpbv1.BlockRequest{BlockId: blkContainers[32].BlockRoot}) + mockChainService := &mock.ChainService{FinalizedRoots: map[[32]byte]bool{r: true}} + bs := &Server{ + ChainInfoFetcher: mockChainService, + OptimisticModeFetcher: mockChainService, + FinalizationFetcher: mockChainService, + BlockFetcher: mockBlockFetcher, + } + + header, err := bs.GetBlockHeader(ctx, ðpbv1.BlockRequest{BlockId: r[:]}) require.NoError(t, err) assert.Equal(t, true, header.Finalized) }) t.Run("false", func(t *testing.T) { - header, err := bs.GetBlockHeader(ctx, ðpbv1.BlockRequest{BlockId: blkContainers[64].BlockRoot}) + mockChainService := &mock.ChainService{FinalizedRoots: map[[32]byte]bool{r: false}} + bs := &Server{ + ChainInfoFetcher: mockChainService, + OptimisticModeFetcher: mockChainService, + FinalizationFetcher: mockChainService, + BlockFetcher: mockBlockFetcher, + } + + header, err := bs.GetBlockHeader(ctx, ðpbv1.BlockRequest{BlockId: r[:]}) require.NoError(t, err) assert.Equal(t, false, header.Finalized) }) @@ -497,7 +194,6 @@ func TestServer_ListBlockHeaders(t *testing.T) { bs := &Server{ BeaconDB: beaconDB, ChainInfoFetcher: mockChainFetcher, - HeadFetcher: mockChainFetcher, OptimisticModeFetcher: mockChainFetcher, FinalizationFetcher: mockChainFetcher, } @@ -580,7 +276,6 @@ func TestServer_ListBlockHeaders(t *testing.T) { bs := &Server{ BeaconDB: beaconDB, ChainInfoFetcher: mockChainFetcher, - HeadFetcher: mockChainFetcher, OptimisticModeFetcher: mockChainFetcher, FinalizationFetcher: mockChainFetcher, } @@ -617,7 +312,6 @@ func TestServer_ListBlockHeaders(t *testing.T) { bs := &Server{ BeaconDB: beaconDB, ChainInfoFetcher: mockChainFetcher, - HeadFetcher: mockChainFetcher, OptimisticModeFetcher: mockChainFetcher, FinalizationFetcher: mockChainFetcher, } @@ -974,1411 +668,409 @@ func TestServer_SubmitBlockSSZ_OK(t *testing.T) { } func TestServer_GetBlock(t *testing.T) { - beaconDB := dbTest.SetupDB(t) ctx := context.Background() - - genBlk, blkContainers := fillDBTestBlocks(ctx, t, beaconDB) - canonicalRoots := make(map[[32]byte]bool) - - for _, bContr := range blkContainers { - canonicalRoots[bytesutil.ToBytes32(bContr.BlockRoot)] = true - } - headBlock := blkContainers[len(blkContainers)-1] - nextSlot := headBlock.GetPhase0Block().Block.Slot + 1 - - b2 := util.NewBeaconBlock() - b2.Block.Slot = 30 - b2.Block.ParentRoot = bytesutil.PadTo([]byte{1}, 32) - util.SaveBlock(t, ctx, beaconDB, b2) - b3 := util.NewBeaconBlock() - b3.Block.Slot = 30 - b3.Block.ParentRoot = bytesutil.PadTo([]byte{4}, 32) - util.SaveBlock(t, ctx, beaconDB, b3) - b4 := util.NewBeaconBlock() - b4.Block.Slot = nextSlot - b4.Block.ParentRoot = bytesutil.PadTo([]byte{8}, 32) - util.SaveBlock(t, ctx, beaconDB, b4) - - wsb, err := blocks.NewSignedBeaconBlock(headBlock.Block.(*ethpbalpha.BeaconBlockContainer_Phase0Block).Phase0Block) + b := util.NewBeaconBlock() + b.Block.Slot = 123 + sb, err := blocks.NewSignedBeaconBlock(b) require.NoError(t, err) - bs := &Server{ - BeaconDB: beaconDB, - ChainInfoFetcher: &mock.ChainService{ - DB: beaconDB, - Block: wsb, - Root: headBlock.BlockRoot, - FinalizedCheckPoint: ðpbalpha.Checkpoint{Root: blkContainers[64].BlockRoot}, - CanonicalRoots: canonicalRoots, - }, + BlockFetcher: &testutil.MockBlockFetcher{BlockToReturn: sb}, } - root, err := genBlk.Block.HashTreeRoot() + blk, err := bs.GetBlock(ctx, ðpbv1.BlockRequest{}) + v1Block, err := migration.V1Alpha1ToV1SignedBlock(b) require.NoError(t, err) - - tests := []struct { - name string - blockID []byte - want *ethpbalpha.SignedBeaconBlock - wantErr bool - }{ - { - name: "slot", - blockID: []byte("30"), - want: blkContainers[30].Block.(*ethpbalpha.BeaconBlockContainer_Phase0Block).Phase0Block, - }, - { - name: "bad formatting", - blockID: []byte("3bad0"), - wantErr: true, - }, - { - name: "canonical", - blockID: []byte("30"), - want: blkContainers[30].Block.(*ethpbalpha.BeaconBlockContainer_Phase0Block).Phase0Block, - }, - { - name: "non canonical", - blockID: []byte(fmt.Sprintf("%d", nextSlot)), - wantErr: true, - }, - { - name: "head", - blockID: []byte("head"), - want: headBlock.Block.(*ethpbalpha.BeaconBlockContainer_Phase0Block).Phase0Block, - }, - { - name: "finalized", - blockID: []byte("finalized"), - want: blkContainers[64].Block.(*ethpbalpha.BeaconBlockContainer_Phase0Block).Phase0Block, - }, - { - name: "genesis", - blockID: []byte("genesis"), - want: genBlk, - }, - { - name: "genesis root", - blockID: root[:], - want: genBlk, - }, - { - name: "root", - blockID: blkContainers[20].BlockRoot, - want: blkContainers[20].Block.(*ethpbalpha.BeaconBlockContainer_Phase0Block).Phase0Block, - }, - { - name: "non-existent root", - blockID: bytesutil.PadTo([]byte("hi there"), 32), - wantErr: true, - }, - { - name: "no block", - blockID: []byte("105"), - wantErr: true, - }, - } - for _, tt := range tests { - t.Run(tt.name, func(t *testing.T) { - blk, err := bs.GetBlock(ctx, ðpbv1.BlockRequest{ - BlockId: tt.blockID, - }) - if tt.wantErr { - require.NotEqual(t, err, nil, "no error has been returned") - return - } - require.NoError(t, err) - - v1Block, err := migration.V1Alpha1ToV1SignedBlock(tt.want) - require.NoError(t, err) - - if !reflect.DeepEqual(blk.Data.Message, v1Block.Block) { - t.Error("Expected blocks to equal") - } - }) - } + assert.DeepEqual(t, v1Block.Block, blk.Data.Message) } func TestServer_GetBlockV2(t *testing.T) { + ctx := context.Background() + t.Run("Phase 0", func(t *testing.T) { - beaconDB := dbTest.SetupDB(t) - ctx := context.Background() + b := util.NewBeaconBlock() + b.Block.Slot = 123 + sb, err := blocks.NewSignedBeaconBlock(b) + require.NoError(t, err) + mockBlockFetcher := &testutil.MockBlockFetcher{BlockToReturn: sb} + mockChainService := &mock.ChainService{ + FinalizedRoots: map[[32]byte]bool{}, + } + bs := &Server{ + FinalizationFetcher: mockChainService, + BlockFetcher: mockBlockFetcher, + } + + blk, err := bs.GetBlockV2(ctx, ðpbv2.BlockRequestV2{}) + require.NoError(t, err) - genBlk, blkContainers := fillDBTestBlocks(ctx, t, beaconDB) - canonicalRoots := make(map[[32]byte]bool) - for _, bContr := range blkContainers { - canonicalRoots[bytesutil.ToBytes32(bContr.BlockRoot)] = true + v1Block, err := migration.V1Alpha1ToV1SignedBlock(b) + require.NoError(t, err) + phase0Block, ok := blk.Data.Message.(*ethpbv2.SignedBeaconBlockContainer_Phase0Block) + require.Equal(t, true, ok) + assert.DeepEqual(t, v1Block.Block, phase0Block.Phase0Block) + assert.Equal(t, ethpbv2.Version_PHASE0, blk.Version) + }) + t.Run("Altair", func(t *testing.T) { + b := util.NewBeaconBlockAltair() + b.Block.Slot = 123 + sb, err := blocks.NewSignedBeaconBlock(b) + require.NoError(t, err) + mockBlockFetcher := &testutil.MockBlockFetcher{BlockToReturn: sb} + mockChainService := &mock.ChainService{ + FinalizedRoots: map[[32]byte]bool{}, + } + bs := &Server{ + FinalizationFetcher: mockChainService, + BlockFetcher: mockBlockFetcher, } - headBlock := blkContainers[len(blkContainers)-1] - nextSlot := headBlock.GetPhase0Block().Block.Slot + 1 - wsb, err := blocks.NewSignedBeaconBlock(headBlock.Block.(*ethpbalpha.BeaconBlockContainer_Phase0Block).Phase0Block) + blk, err := bs.GetBlockV2(ctx, ðpbv2.BlockRequestV2{}) require.NoError(t, err) + v1Block, err := migration.V1Alpha1BeaconBlockAltairToV2(b.Block) + require.NoError(t, err) + altairBlock, ok := blk.Data.Message.(*ethpbv2.SignedBeaconBlockContainer_AltairBlock) + require.Equal(t, true, ok) + assert.DeepEqual(t, v1Block, altairBlock.AltairBlock) + assert.Equal(t, ethpbv2.Version_ALTAIR, blk.Version) + }) + t.Run("Bellatrix", func(t *testing.T) { + b := util.NewBeaconBlockBellatrix() + b.Block.Slot = 123 + sb, err := blocks.NewSignedBeaconBlock(b) + require.NoError(t, err) + mockBlockFetcher := &testutil.MockBlockFetcher{BlockToReturn: sb} mockChainService := &mock.ChainService{ - DB: beaconDB, - Block: wsb, - Root: headBlock.BlockRoot, - FinalizedCheckPoint: ðpbalpha.Checkpoint{Root: blkContainers[64].BlockRoot}, - CanonicalRoots: canonicalRoots, - FinalizedRoots: map[[32]byte]bool{}, + FinalizedRoots: map[[32]byte]bool{}, } bs := &Server{ - BeaconDB: beaconDB, - ChainInfoFetcher: mockChainService, - HeadFetcher: mockChainService, OptimisticModeFetcher: mockChainService, FinalizationFetcher: mockChainService, + BlockFetcher: mockBlockFetcher, } - root, err := genBlk.Block.HashTreeRoot() + blk, err := bs.GetBlockV2(ctx, ðpbv2.BlockRequestV2{}) require.NoError(t, err) - tests := []struct { - name string - blockID []byte - want *ethpbalpha.SignedBeaconBlock - wantErr bool - }{ - { - name: "slot", - blockID: []byte("30"), - want: blkContainers[30].Block.(*ethpbalpha.BeaconBlockContainer_Phase0Block).Phase0Block, - }, - { - name: "bad formatting", - blockID: []byte("3bad0"), - wantErr: true, - }, - { - name: "canonical", - blockID: []byte("30"), - want: blkContainers[30].Block.(*ethpbalpha.BeaconBlockContainer_Phase0Block).Phase0Block, - }, - { - name: "non canonical", - blockID: []byte(fmt.Sprintf("%d", nextSlot)), - wantErr: true, - }, - { - name: "head", - blockID: []byte("head"), - want: headBlock.Block.(*ethpbalpha.BeaconBlockContainer_Phase0Block).Phase0Block, - }, - { - name: "finalized", - blockID: []byte("finalized"), - want: blkContainers[64].Block.(*ethpbalpha.BeaconBlockContainer_Phase0Block).Phase0Block, - }, - { - name: "genesis", - blockID: []byte("genesis"), - want: genBlk, - }, - { - name: "genesis root", - blockID: root[:], - want: genBlk, - }, - { - name: "root", - blockID: blkContainers[20].BlockRoot, - want: blkContainers[20].Block.(*ethpbalpha.BeaconBlockContainer_Phase0Block).Phase0Block, - }, - { - name: "non-existent root", - blockID: bytesutil.PadTo([]byte("hi there"), 32), - wantErr: true, - }, - { - name: "no block", - blockID: []byte("105"), - wantErr: true, - }, + v1Block, err := migration.V1Alpha1BeaconBlockBellatrixToV2(b.Block) + require.NoError(t, err) + bellatrixBlock, ok := blk.Data.Message.(*ethpbv2.SignedBeaconBlockContainer_BellatrixBlock) + require.Equal(t, true, ok) + assert.DeepEqual(t, v1Block, bellatrixBlock.BellatrixBlock) + assert.Equal(t, ethpbv2.Version_BELLATRIX, blk.Version) + }) + t.Run("Capella", func(t *testing.T) { + b := util.NewBeaconBlockCapella() + b.Block.Slot = 123 + sb, err := blocks.NewSignedBeaconBlock(b) + require.NoError(t, err) + mockBlockFetcher := &testutil.MockBlockFetcher{BlockToReturn: sb} + mockChainService := &mock.ChainService{ + FinalizedRoots: map[[32]byte]bool{}, } - for _, tt := range tests { - t.Run(tt.name, func(t *testing.T) { - blk, err := bs.GetBlockV2(ctx, ðpbv2.BlockRequestV2{ - BlockId: tt.blockID, - }) - if tt.wantErr { - require.NotEqual(t, err, nil) - return - } - require.NoError(t, err) - - v1Block, err := migration.V1Alpha1ToV1SignedBlock(tt.want) - require.NoError(t, err) - - phase0Block, ok := blk.Data.Message.(*ethpbv2.SignedBeaconBlockContainer_Phase0Block) - require.Equal(t, true, ok) - if !reflect.DeepEqual(phase0Block.Phase0Block, v1Block.Block) { - t.Error("Expected blocks to equal") - } - assert.Equal(t, ethpbv2.Version_PHASE0, blk.Version) - }) + bs := &Server{ + OptimisticModeFetcher: mockChainService, + FinalizationFetcher: mockChainService, + BlockFetcher: mockBlockFetcher, } - }) - - t.Run("Altair", func(t *testing.T) { - beaconDB := dbTest.SetupDB(t) - ctx := context.Background() - genBlk, blkContainers := fillDBTestBlocksAltair(ctx, t, beaconDB) - canonicalRoots := make(map[[32]byte]bool) - for _, bContr := range blkContainers { - canonicalRoots[bytesutil.ToBytes32(bContr.BlockRoot)] = true - } - headBlock := blkContainers[len(blkContainers)-1] - nextSlot := headBlock.GetAltairBlock().Block.Slot + 1 + blk, err := bs.GetBlockV2(ctx, ðpbv2.BlockRequestV2{}) + require.NoError(t, err) - chainBlk, err := blocks.NewSignedBeaconBlock(headBlock.GetAltairBlock()) + v1Block, err := migration.V1Alpha1BeaconBlockCapellaToV2(b.Block) + require.NoError(t, err) + bellatrixBlock, ok := blk.Data.Message.(*ethpbv2.SignedBeaconBlockContainer_CapellaBlock) + require.Equal(t, true, ok) + assert.DeepEqual(t, v1Block, bellatrixBlock.CapellaBlock) + assert.Equal(t, ethpbv2.Version_CAPELLA, blk.Version) + }) + t.Run("execution optimistic", func(t *testing.T) { + b := util.NewBeaconBlockBellatrix() + sb, err := blocks.NewSignedBeaconBlock(b) require.NoError(t, err) + mockBlockFetcher := &testutil.MockBlockFetcher{BlockToReturn: sb} mockChainService := &mock.ChainService{ - DB: beaconDB, - Block: chainBlk, - Root: headBlock.BlockRoot, - FinalizedCheckPoint: ðpbalpha.Checkpoint{Root: blkContainers[64].BlockRoot}, - CanonicalRoots: canonicalRoots, - FinalizedRoots: map[[32]byte]bool{}, + Optimistic: true, + FinalizedRoots: map[[32]byte]bool{}, } bs := &Server{ - BeaconDB: beaconDB, - ChainInfoFetcher: mockChainService, - HeadFetcher: mockChainService, OptimisticModeFetcher: mockChainService, FinalizationFetcher: mockChainService, + BlockFetcher: mockBlockFetcher, } - root, err := genBlk.Block.HashTreeRoot() + blk, err := bs.GetBlockV2(ctx, ðpbv2.BlockRequestV2{}) + require.NoError(t, err) + assert.Equal(t, true, blk.ExecutionOptimistic) + }) + t.Run("finalized", func(t *testing.T) { + b := util.NewBeaconBlock() + sb, err := blocks.NewSignedBeaconBlock(b) require.NoError(t, err) + r, err := sb.Block().HashTreeRoot() + require.NoError(t, err) + mockBlockFetcher := &testutil.MockBlockFetcher{BlockToReturn: sb} - tests := []struct { - name string - blockID []byte - want *ethpbalpha.SignedBeaconBlockAltair - wantErr bool - }{ - { - name: "slot", - blockID: []byte("30"), - want: blkContainers[30].GetAltairBlock(), - }, - { - name: "bad formatting", - blockID: []byte("3bad0"), - wantErr: true, - }, - { - name: "canonical", - blockID: []byte("30"), - want: blkContainers[30].GetAltairBlock(), - }, - { - name: "non canonical", - blockID: []byte(fmt.Sprintf("%d", nextSlot)), - wantErr: true, - }, - { - name: "head", - blockID: []byte("head"), - want: headBlock.GetAltairBlock(), - }, - { - name: "finalized", - blockID: []byte("finalized"), - want: blkContainers[64].GetAltairBlock(), - }, - { - name: "genesis", - blockID: []byte("genesis"), - want: genBlk, - }, - { - name: "genesis root", - blockID: root[:], - want: genBlk, - }, - { - name: "root", - blockID: blkContainers[20].BlockRoot, - want: blkContainers[20].GetAltairBlock(), - }, - { - name: "non-existent root", - blockID: bytesutil.PadTo([]byte("hi there"), 32), - wantErr: true, - }, - { - name: "no block", - blockID: []byte("105"), - wantErr: true, - }, - } - for _, tt := range tests { - t.Run(tt.name, func(t *testing.T) { - blk, err := bs.GetBlockV2(ctx, ðpbv2.BlockRequestV2{ - BlockId: tt.blockID, - }) - if tt.wantErr { - require.NotEqual(t, err, nil) - return - } - require.NoError(t, err) + t.Run("true", func(t *testing.T) { + mockChainService := &mock.ChainService{FinalizedRoots: map[[32]byte]bool{r: true}} + bs := &Server{ + OptimisticModeFetcher: mockChainService, + FinalizationFetcher: mockChainService, + BlockFetcher: mockBlockFetcher, + } - v2Block, err := migration.V1Alpha1BeaconBlockAltairToV2(tt.want.Block) - require.NoError(t, err) + header, err := bs.GetBlockV2(ctx, ðpbv2.BlockRequestV2{BlockId: r[:]}) + require.NoError(t, err) + assert.Equal(t, true, header.Finalized) + }) + t.Run("false", func(t *testing.T) { + mockChainService := &mock.ChainService{FinalizedRoots: map[[32]byte]bool{r: false}} + bs := &Server{ + OptimisticModeFetcher: mockChainService, + FinalizationFetcher: mockChainService, + BlockFetcher: mockBlockFetcher, + } - altairBlock, ok := blk.Data.Message.(*ethpbv2.SignedBeaconBlockContainer_AltairBlock) - require.Equal(t, true, ok) - if !reflect.DeepEqual(altairBlock.AltairBlock, v2Block) { - t.Error("Expected blocks to equal") - } - assert.Equal(t, ethpbv2.Version_ALTAIR, blk.Version) - }) - } + resp, err := bs.GetBlockV2(ctx, ðpbv2.BlockRequestV2{BlockId: r[:]}) + require.NoError(t, err) + assert.Equal(t, false, resp.Finalized) + }) }) +} - t.Run("Bellatrix", func(t *testing.T) { - resetFn := features.InitWithReset(&features.Flags{ - SaveFullExecutionPayloads: true, - }) - defer resetFn() - beaconDB := dbTest.SetupDB(t) - ctx := context.Background() +func TestServer_GetBlockSSZ(t *testing.T) { + ctx := context.Background() + b := util.NewBeaconBlock() + b.Block.Slot = 123 + sb, err := blocks.NewSignedBeaconBlock(b) + require.NoError(t, err) + bs := &Server{ + BlockFetcher: &testutil.MockBlockFetcher{BlockToReturn: sb}, + } - genBlk, blkContainers := fillDBTestBlocksBellatrix(ctx, t, beaconDB) - canonicalRoots := make(map[[32]byte]bool) - for _, bContr := range blkContainers { - canonicalRoots[bytesutil.ToBytes32(bContr.BlockRoot)] = true - } - headBlock := blkContainers[len(blkContainers)-1] - nextSlot := headBlock.GetBellatrixBlock().Block.Slot + 1 + resp, err := bs.GetBlockSSZ(ctx, ðpbv1.BlockRequest{}) + require.NoError(t, err) + assert.NotNil(t, resp) + sszBlock, err := b.MarshalSSZ() + require.NoError(t, err) + assert.DeepEqual(t, sszBlock, resp.Data) +} + +func TestServer_GetBlockSSZV2(t *testing.T) { + ctx := context.Background() - chainBlk, err := blocks.NewSignedBeaconBlock(headBlock.GetBellatrixBlock()) + t.Run("Phase 0", func(t *testing.T) { + b := util.NewBeaconBlock() + b.Block.Slot = 123 + sb, err := blocks.NewSignedBeaconBlock(b) require.NoError(t, err) + mockChainService := &mock.ChainService{ - DB: beaconDB, - Block: chainBlk, - Root: headBlock.BlockRoot, - FinalizedCheckPoint: ðpbalpha.Checkpoint{Root: blkContainers[64].BlockRoot}, - CanonicalRoots: canonicalRoots, - FinalizedRoots: map[[32]byte]bool{}, + FinalizedRoots: map[[32]byte]bool{}, } bs := &Server{ - BeaconDB: beaconDB, - ChainInfoFetcher: mockChainService, - HeadFetcher: mockChainService, - OptimisticModeFetcher: mockChainService, - ExecutionPayloadReconstructor: &executionTest.EngineClient{ - ExecutionPayloadByBlockHash: map[[32]byte]*enginev1.ExecutionPayload{}, - }, FinalizationFetcher: mockChainService, + BlockFetcher: &testutil.MockBlockFetcher{BlockToReturn: sb}, } - root, err := genBlk.Block.HashTreeRoot() + resp, err := bs.GetBlockSSZV2(ctx, ðpbv2.BlockRequestV2{}) + require.NoError(t, err) + assert.NotNil(t, resp) + sszBlock, err := b.MarshalSSZ() + require.NoError(t, err) + assert.DeepEqual(t, sszBlock, resp.Data) + assert.Equal(t, ethpbv2.Version_PHASE0, resp.Version) + }) + t.Run("Altair", func(t *testing.T) { + b := util.NewBeaconBlockAltair() + b.Block.Slot = 123 + sb, err := blocks.NewSignedBeaconBlock(b) require.NoError(t, err) - tests := []struct { - name string - blockID []byte - want *ethpbalpha.SignedBeaconBlockBellatrix - wantErr bool - }{ - { - name: "slot", - blockID: []byte("30"), - want: blkContainers[30].GetBellatrixBlock(), - }, - { - name: "bad formatting", - blockID: []byte("3bad0"), - wantErr: true, - }, - { - name: "canonical", - blockID: []byte("30"), - want: blkContainers[30].GetBellatrixBlock(), - }, - { - name: "non canonical", - blockID: []byte(fmt.Sprintf("%d", nextSlot)), - wantErr: true, - }, - { - name: "head", - blockID: []byte("head"), - want: headBlock.GetBellatrixBlock(), - }, - { - name: "finalized", - blockID: []byte("finalized"), - want: blkContainers[64].GetBellatrixBlock(), - }, - { - name: "genesis", - blockID: []byte("genesis"), - want: genBlk, - }, - { - name: "genesis root", - blockID: root[:], - want: genBlk, - }, - { - name: "root", - blockID: blkContainers[20].BlockRoot, - want: blkContainers[20].GetBellatrixBlock(), - }, - { - name: "non-existent root", - blockID: bytesutil.PadTo([]byte("hi there"), 32), - wantErr: true, - }, - { - name: "no block", - blockID: []byte("105"), - wantErr: true, - }, - } - for _, tt := range tests { - t.Run(tt.name, func(t *testing.T) { - blk, err := bs.GetBlockV2(ctx, ðpbv2.BlockRequestV2{ - BlockId: tt.blockID, - }) - if tt.wantErr { - require.NotEqual(t, err, nil) - return - } - require.NoError(t, err) - - v2Block, err := migration.V1Alpha1BeaconBlockBellatrixToV2(tt.want.Block) - require.NoError(t, err) - - b, ok := blk.Data.Message.(*ethpbv2.SignedBeaconBlockContainer_BellatrixBlock) - require.Equal(t, true, ok) - if !reflect.DeepEqual(b.BellatrixBlock, v2Block) { - t.Error("Expected blocks to equal") - } - assert.Equal(t, ethpbv2.Version_BELLATRIX, blk.Version) - }) - } - }) - - t.Run("Capella", func(t *testing.T) { - resetFn := features.InitWithReset(&features.Flags{ - SaveFullExecutionPayloads: true, - }) - defer resetFn() - beaconDB := dbTest.SetupDB(t) - ctx := context.Background() - - genBlk, blkContainers := fillDBTestBlocksCapella(ctx, t, beaconDB) - canonicalRoots := make(map[[32]byte]bool) - - for _, bContr := range blkContainers { - canonicalRoots[bytesutil.ToBytes32(bContr.BlockRoot)] = true - } - headBlock := blkContainers[len(blkContainers)-1] - nextSlot := headBlock.GetCapellaBlock().Block.Slot + 1 - - chainBlk, err := blocks.NewSignedBeaconBlock(headBlock.GetCapellaBlock()) - require.NoError(t, err) mockChainService := &mock.ChainService{ - DB: beaconDB, - Block: chainBlk, - Root: headBlock.BlockRoot, - FinalizedCheckPoint: ðpbalpha.Checkpoint{Root: blkContainers[64].BlockRoot}, - CanonicalRoots: canonicalRoots, - FinalizedRoots: map[[32]byte]bool{}, + FinalizedRoots: map[[32]byte]bool{}, } bs := &Server{ - BeaconDB: beaconDB, - ChainInfoFetcher: mockChainService, - HeadFetcher: mockChainService, - OptimisticModeFetcher: mockChainService, - ExecutionPayloadReconstructor: &executionTest.EngineClient{ - ExecutionPayloadByBlockHash: map[[32]byte]*enginev1.ExecutionPayload{}, - }, FinalizationFetcher: mockChainService, + BlockFetcher: &testutil.MockBlockFetcher{BlockToReturn: sb}, } - root, err := genBlk.Block.HashTreeRoot() - require.NoError(t, err) - - tests := []struct { - name string - blockID []byte - want *ethpbalpha.SignedBeaconBlockCapella - wantErr bool - }{ - { - name: "slot", - blockID: []byte("30"), - want: blkContainers[30].GetCapellaBlock(), - }, - { - name: "bad formatting", - blockID: []byte("3bad0"), - wantErr: true, - }, - { - name: "canonical", - blockID: []byte("30"), - want: blkContainers[30].GetCapellaBlock(), - }, - { - name: "non canonical", - blockID: []byte(fmt.Sprintf("%d", nextSlot)), - wantErr: true, - }, - { - name: "head", - blockID: []byte("head"), - want: headBlock.GetCapellaBlock(), - }, - { - name: "finalized", - blockID: []byte("finalized"), - want: blkContainers[64].GetCapellaBlock(), - }, - { - name: "genesis", - blockID: []byte("genesis"), - want: genBlk, - }, - { - name: "genesis root", - blockID: root[:], - want: genBlk, - }, - { - name: "root", - blockID: blkContainers[20].BlockRoot, - want: blkContainers[20].GetCapellaBlock(), - }, - { - name: "non-existent root", - blockID: bytesutil.PadTo([]byte("hi there"), 32), - wantErr: true, - }, - { - name: "no block", - blockID: []byte("105"), - wantErr: true, - }, - } - for _, tt := range tests { - t.Run(tt.name, func(t *testing.T) { - blk, err := bs.GetBlockV2(ctx, ðpbv2.BlockRequestV2{ - BlockId: tt.blockID, - }) - if tt.wantErr { - require.NotEqual(t, err, nil) - return - } - require.NoError(t, err) - - v2Block, err := migration.V1Alpha1BeaconBlockCapellaToV2(tt.want.Block) - require.NoError(t, err) - - b, ok := blk.Data.Message.(*ethpbv2.SignedBeaconBlockContainer_CapellaBlock) - require.Equal(t, true, ok) - if !reflect.DeepEqual(b.CapellaBlock, v2Block) { - t.Error("Expected blocks to equal") - } - assert.Equal(t, ethpbv2.Version_CAPELLA, blk.Version) - }) - } - }) - - t.Run("execution optimistic", func(t *testing.T) { - beaconDB := dbTest.SetupDB(t) - ctx := context.Background() - - _, blkContainers := fillDBTestBlocksBellatrix(ctx, t, beaconDB) - headBlock := blkContainers[len(blkContainers)-1] - - chainBlk, err := blocks.NewSignedBeaconBlock(headBlock.GetBellatrixBlock()) + resp, err := bs.GetBlockSSZV2(ctx, ðpbv2.BlockRequestV2{}) require.NoError(t, err) - mockChainService := &mock.ChainService{ - DB: beaconDB, - Block: chainBlk, - Root: headBlock.BlockRoot, - FinalizedCheckPoint: ðpbalpha.Checkpoint{Root: blkContainers[64].BlockRoot}, - Optimistic: true, - FinalizedRoots: map[[32]byte]bool{}, - } - bs := &Server{ - BeaconDB: beaconDB, - ChainInfoFetcher: mockChainService, - HeadFetcher: mockChainService, - OptimisticModeFetcher: mockChainService, - FinalizationFetcher: mockChainService, - } - - blk, err := bs.GetBlockV2(ctx, ðpbv2.BlockRequestV2{ - BlockId: []byte("head"), - }) + assert.NotNil(t, resp) + sszBlock, err := b.MarshalSSZ() require.NoError(t, err) - assert.Equal(t, true, blk.ExecutionOptimistic) + assert.DeepEqual(t, sszBlock, resp.Data) + assert.Equal(t, ethpbv2.Version_ALTAIR, resp.Version) }) - - t.Run("finalized", func(t *testing.T) { - beaconDB := dbTest.SetupDB(t) - ctx := context.Background() - - _, blkContainers := fillDBTestBlocks(ctx, t, beaconDB) - headBlock := blkContainers[len(blkContainers)-1] - - chainBlk, err := blocks.NewSignedBeaconBlock(headBlock.GetPhase0Block()) + t.Run("Bellatrix", func(t *testing.T) { + b := util.NewBeaconBlockBellatrix() + b.Block.Slot = 123 + sb, err := blocks.NewSignedBeaconBlock(b) require.NoError(t, err) - mockChainService := &mock.ChainService{ - DB: beaconDB, - Block: chainBlk, - Root: headBlock.BlockRoot, - FinalizedCheckPoint: ðpbalpha.Checkpoint{Root: blkContainers[64].BlockRoot}, - Optimistic: true, - FinalizedRoots: map[[32]byte]bool{ - bytesutil.ToBytes32(blkContainers[32].BlockRoot): true, - bytesutil.ToBytes32(blkContainers[64].BlockRoot): false, - }, - } - bs := &Server{ - BeaconDB: beaconDB, - ChainInfoFetcher: mockChainService, - HeadFetcher: mockChainService, - OptimisticModeFetcher: mockChainService, - FinalizationFetcher: mockChainService, - } - - t.Run("true", func(t *testing.T) { - blk, err := bs.GetBlockV2(ctx, ðpbv2.BlockRequestV2{ - BlockId: []byte("32"), - }) - require.NoError(t, err) - assert.Equal(t, true, blk.Finalized) - }) - t.Run("false", func(t *testing.T) { - blk, err := bs.GetBlockV2(ctx, ðpbv2.BlockRequestV2{ - BlockId: []byte("64"), - }) - require.NoError(t, err) - assert.Equal(t, false, blk.Finalized) - }) - }) -} - -func TestServer_GetBlockSSZ(t *testing.T) { - beaconDB := dbTest.SetupDB(t) - ctx := context.Background() - - _, blkContainers := fillDBTestBlocks(ctx, t, beaconDB) - headBlock := blkContainers[len(blkContainers)-1] - - b2 := util.NewBeaconBlock() - b2.Block.Slot = 30 - b2.Block.ParentRoot = bytesutil.PadTo([]byte{1}, 32) - util.SaveBlock(t, ctx, beaconDB, b2) - - wsb, err := blocks.NewSignedBeaconBlock(headBlock.Block.(*ethpbalpha.BeaconBlockContainer_Phase0Block).Phase0Block) - require.NoError(t, err) - - bs := &Server{ - BeaconDB: beaconDB, - ChainInfoFetcher: &mock.ChainService{ - DB: beaconDB, - Block: wsb, - Root: headBlock.BlockRoot, - FinalizedCheckPoint: ðpbalpha.Checkpoint{Root: blkContainers[64].BlockRoot}, - }, - } - - blks, err := beaconDB.BlocksBySlot(ctx, 30) - require.Equal(t, true, len(blks) > 0) - require.NoError(t, err) - sszBlock, err := blks[0].MarshalSSZ() - require.NoError(t, err) - - resp, err := bs.GetBlockSSZ(ctx, ðpbv1.BlockRequest{BlockId: []byte("30")}) - require.NoError(t, err) - assert.NotNil(t, resp) - assert.DeepEqual(t, sszBlock, resp.Data) -} - -func TestServer_GetBlockSSZV2(t *testing.T) { - t.Run("Phase 0", func(t *testing.T) { - beaconDB := dbTest.SetupDB(t) - ctx := context.Background() - _, blkContainers := fillDBTestBlocks(ctx, t, beaconDB) - headBlock := blkContainers[len(blkContainers)-1] - wsb, err := blocks.NewSignedBeaconBlock(headBlock.Block.(*ethpbalpha.BeaconBlockContainer_Phase0Block).Phase0Block) - require.NoError(t, err) mockChainService := &mock.ChainService{ - DB: beaconDB, - Block: wsb, - Root: headBlock.BlockRoot, - FinalizedCheckPoint: ðpbalpha.Checkpoint{Root: blkContainers[64].BlockRoot}, - FinalizedRoots: map[[32]byte]bool{}, + FinalizedRoots: map[[32]byte]bool{}, } bs := &Server{ - BeaconDB: beaconDB, - ChainInfoFetcher: mockChainService, - FinalizationFetcher: mockChainService, - } - - blks, err := beaconDB.BlocksBySlot(ctx, 30) - require.Equal(t, true, len(blks) > 0) - require.NoError(t, err) - sszBlock, err := blks[0].MarshalSSZ() - require.NoError(t, err) - - resp, err := bs.GetBlockSSZV2(ctx, ðpbv2.BlockRequestV2{BlockId: []byte("30")}) - require.NoError(t, err) - assert.NotNil(t, resp) - assert.DeepEqual(t, sszBlock, resp.Data) - assert.Equal(t, ethpbv2.Version_PHASE0, resp.Version) - }) - - t.Run("Altair", func(t *testing.T) { - beaconDB := dbTest.SetupDB(t) - ctx := context.Background() - - _, blkContainers := fillDBTestBlocksAltair(ctx, t, beaconDB) - headBlock := blkContainers[len(blkContainers)-1] - chainBlk, err := blocks.NewSignedBeaconBlock(headBlock.GetAltairBlock()) - require.NoError(t, err) - mockChainService := &mock.ChainService{ - DB: beaconDB, - Block: chainBlk, - Root: headBlock.BlockRoot, - FinalizedCheckPoint: ðpbalpha.Checkpoint{Root: blkContainers[64].BlockRoot}, - FinalizedRoots: map[[32]byte]bool{}, - } - bs := &Server{ - BeaconDB: beaconDB, - ChainInfoFetcher: mockChainService, - FinalizationFetcher: mockChainService, - } - - blks, err := beaconDB.BlocksBySlot(ctx, 30) - require.Equal(t, true, len(blks) > 0) - require.NoError(t, err) - sszBlock, err := blks[0].MarshalSSZ() - require.NoError(t, err) - - resp, err := bs.GetBlockSSZV2(ctx, ðpbv2.BlockRequestV2{BlockId: []byte("30")}) - require.NoError(t, err) - assert.NotNil(t, resp) - assert.DeepEqual(t, sszBlock, resp.Data) - assert.Equal(t, ethpbv2.Version_ALTAIR, resp.Version) - }) - - t.Run("Bellatrix", func(t *testing.T) { - resetFn := features.InitWithReset(&features.Flags{ - SaveFullExecutionPayloads: true, - }) - defer resetFn() - beaconDB := dbTest.SetupDB(t) - ctx := context.Background() - - _, blkContainers := fillDBTestBlocksBellatrix(ctx, t, beaconDB) - headBlock := blkContainers[len(blkContainers)-1] - chainBlk, err := blocks.NewSignedBeaconBlock(headBlock.GetBellatrixBlock()) - require.NoError(t, err) - mockChainService := &mock.ChainService{ - DB: beaconDB, - Block: chainBlk, - Root: headBlock.BlockRoot, - FinalizedCheckPoint: ðpbalpha.Checkpoint{Root: blkContainers[64].BlockRoot}, - FinalizedRoots: map[[32]byte]bool{}, - } - bs := &Server{ - BeaconDB: beaconDB, - ChainInfoFetcher: mockChainService, - OptimisticModeFetcher: mockChainService, - FinalizationFetcher: mockChainService, - } - - blks, err := beaconDB.BlocksBySlot(ctx, 30) - require.Equal(t, true, len(blks) > 0) - require.NoError(t, err) - sszBlock, err := blks[0].MarshalSSZ() - require.NoError(t, err) - - resp, err := bs.GetBlockSSZV2(ctx, ðpbv2.BlockRequestV2{BlockId: []byte("30")}) - require.NoError(t, err) - assert.NotNil(t, resp) - assert.DeepEqual(t, sszBlock, resp.Data) - assert.Equal(t, ethpbv2.Version_BELLATRIX, resp.Version) - }) - - t.Run("Capella", func(t *testing.T) { - resetFn := features.InitWithReset(&features.Flags{ - SaveFullExecutionPayloads: true, - }) - defer resetFn() - beaconDB := dbTest.SetupDB(t) - ctx := context.Background() - - _, blkContainers := fillDBTestBlocksCapella(ctx, t, beaconDB) - headBlock := blkContainers[len(blkContainers)-1] - chainBlk, err := blocks.NewSignedBeaconBlock(headBlock.GetCapellaBlock()) - require.NoError(t, err) - mockChainService := &mock.ChainService{ - DB: beaconDB, - Block: chainBlk, - Root: headBlock.BlockRoot, - FinalizedCheckPoint: ðpbalpha.Checkpoint{Root: blkContainers[64].BlockRoot}, - FinalizedRoots: map[[32]byte]bool{}, - } - bs := &Server{ - BeaconDB: beaconDB, - ChainInfoFetcher: mockChainService, - OptimisticModeFetcher: mockChainService, - FinalizationFetcher: mockChainService, - } - - blks, err := beaconDB.BlocksBySlot(ctx, 30) - require.Equal(t, true, len(blks) > 0) - require.NoError(t, err) - sszBlock, err := blks[0].MarshalSSZ() - require.NoError(t, err) - - resp, err := bs.GetBlockSSZV2(ctx, ðpbv2.BlockRequestV2{BlockId: []byte("30")}) - require.NoError(t, err) - assert.NotNil(t, resp) - assert.DeepEqual(t, sszBlock, resp.Data) - assert.Equal(t, ethpbv2.Version_CAPELLA, resp.Version) - }) - - t.Run("execution optimistic", func(t *testing.T) { - beaconDB := dbTest.SetupDB(t) - ctx := context.Background() - - _, blkContainers := fillDBTestBlocksBellatrix(ctx, t, beaconDB) - headBlock := blkContainers[len(blkContainers)-1] - - chainBlk, err := blocks.NewSignedBeaconBlock(headBlock.GetBellatrixBlock()) - require.NoError(t, err) - mockChainService := &mock.ChainService{ - DB: beaconDB, - Block: chainBlk, - Root: headBlock.BlockRoot, - FinalizedCheckPoint: ðpbalpha.Checkpoint{Root: blkContainers[64].BlockRoot}, - Optimistic: true, - FinalizedRoots: map[[32]byte]bool{}, - } - bs := &Server{ - BeaconDB: beaconDB, - ChainInfoFetcher: mockChainService, - HeadFetcher: mockChainService, - OptimisticModeFetcher: mockChainService, - FinalizationFetcher: mockChainService, - } - - blk, err := bs.GetBlockSSZV2(ctx, ðpbv2.BlockRequestV2{ - BlockId: []byte("head"), - }) - require.NoError(t, err) - assert.Equal(t, true, blk.ExecutionOptimistic) - }) - - t.Run("finalized", func(t *testing.T) { - beaconDB := dbTest.SetupDB(t) - ctx := context.Background() - - _, blkContainers := fillDBTestBlocks(ctx, t, beaconDB) - headBlock := blkContainers[len(blkContainers)-1] - - chainBlk, err := blocks.NewSignedBeaconBlock(headBlock.GetPhase0Block()) - require.NoError(t, err) - mockChainService := &mock.ChainService{ - DB: beaconDB, - Block: chainBlk, - Root: headBlock.BlockRoot, - FinalizedCheckPoint: ðpbalpha.Checkpoint{Root: blkContainers[64].BlockRoot}, - Optimistic: true, - FinalizedRoots: map[[32]byte]bool{ - bytesutil.ToBytes32(blkContainers[32].BlockRoot): true, - bytesutil.ToBytes32(blkContainers[64].BlockRoot): false, - }, - } - bs := &Server{ - BeaconDB: beaconDB, - ChainInfoFetcher: mockChainService, - HeadFetcher: mockChainService, - OptimisticModeFetcher: mockChainService, - FinalizationFetcher: mockChainService, - } - - t.Run("true", func(t *testing.T) { - blk, err := bs.GetBlockV2(ctx, ðpbv2.BlockRequestV2{ - BlockId: []byte("32"), - }) - require.NoError(t, err) - assert.Equal(t, true, blk.Finalized) - }) - t.Run("false", func(t *testing.T) { - blk, err := bs.GetBlockV2(ctx, ðpbv2.BlockRequestV2{ - BlockId: []byte("64"), - }) - require.NoError(t, err) - assert.Equal(t, false, blk.Finalized) - }) - }) -} - -func TestServer_GetBlockRoot(t *testing.T) { - beaconDB := dbTest.SetupDB(t) - ctx := context.Background() - - genBlk, blkContainers := fillDBTestBlocks(ctx, t, beaconDB) - headBlock := blkContainers[len(blkContainers)-1] - - t.Run("get root", func(t *testing.T) { - wsb, err := blocks.NewSignedBeaconBlock(headBlock.Block.(*ethpbalpha.BeaconBlockContainer_Phase0Block).Phase0Block) - require.NoError(t, err) - mockChainFetcher := &mock.ChainService{ - DB: beaconDB, - Block: wsb, - Root: headBlock.BlockRoot, - FinalizedCheckPoint: ðpbalpha.Checkpoint{Root: blkContainers[64].BlockRoot}, - FinalizedRoots: map[[32]byte]bool{}, - } - bs := &Server{ - BeaconDB: beaconDB, - ChainInfoFetcher: mockChainFetcher, - HeadFetcher: mockChainFetcher, - OptimisticModeFetcher: mockChainFetcher, - FinalizationFetcher: mockChainFetcher, - } - - root, err := genBlk.Block.HashTreeRoot() - require.NoError(t, err) - - tests := []struct { - name string - blockID []byte - want []byte - wantErr bool - }{ - { - name: "bad formatting", - blockID: []byte("3bad0"), - wantErr: true, - }, - { - name: "canonical slot", - blockID: []byte("30"), - want: blkContainers[30].BlockRoot, - }, - { - name: "head", - blockID: []byte("head"), - want: headBlock.BlockRoot, - }, - { - name: "finalized", - blockID: []byte("finalized"), - want: blkContainers[64].BlockRoot, - }, - { - name: "genesis", - blockID: []byte("genesis"), - want: root[:], - }, - { - name: "genesis root", - blockID: root[:], - want: root[:], - }, - { - name: "root", - blockID: blkContainers[20].BlockRoot, - want: blkContainers[20].BlockRoot, - }, - { - name: "non-existent root", - blockID: bytesutil.PadTo([]byte("hi there"), 32), - wantErr: true, - }, - { - name: "slot", - blockID: []byte("40"), - want: blkContainers[40].BlockRoot, - }, - { - name: "no block", - blockID: []byte("105"), - wantErr: true, - }, - } - for _, tt := range tests { - t.Run(tt.name, func(t *testing.T) { - blockRootResp, err := bs.GetBlockRoot(ctx, ðpbv1.BlockRequest{ - BlockId: tt.blockID, - }) - if tt.wantErr { - require.NotEqual(t, err, nil) - return - } - require.NoError(t, err) - assert.DeepEqual(t, tt.want, blockRootResp.Data.Root) - }) - } - }) - - t.Run("execution optimistic", func(t *testing.T) { - wsb, err := blocks.NewSignedBeaconBlock(headBlock.Block.(*ethpbalpha.BeaconBlockContainer_Phase0Block).Phase0Block) - require.NoError(t, err) - mockChainFetcher := &mock.ChainService{ - DB: beaconDB, - Block: wsb, - Root: headBlock.BlockRoot, - FinalizedCheckPoint: ðpbalpha.Checkpoint{Root: blkContainers[64].BlockRoot}, - Optimistic: true, - FinalizedRoots: map[[32]byte]bool{}, - } - bs := &Server{ - BeaconDB: beaconDB, - ChainInfoFetcher: mockChainFetcher, - HeadFetcher: mockChainFetcher, - OptimisticModeFetcher: mockChainFetcher, - FinalizationFetcher: mockChainFetcher, - } - blockRootResp, err := bs.GetBlockRoot(ctx, ðpbv1.BlockRequest{ - BlockId: []byte("head"), - }) - require.NoError(t, err) - assert.Equal(t, true, blockRootResp.ExecutionOptimistic) - }) - - t.Run("finalized", func(t *testing.T) { - wsb, err := blocks.NewSignedBeaconBlock(headBlock.Block.(*ethpbalpha.BeaconBlockContainer_Phase0Block).Phase0Block) - require.NoError(t, err) - mockChainFetcher := &mock.ChainService{ - DB: beaconDB, - Block: wsb, - Root: headBlock.BlockRoot, - FinalizedCheckPoint: ðpbalpha.Checkpoint{Root: blkContainers[64].BlockRoot}, - Optimistic: true, - FinalizedRoots: map[[32]byte]bool{ - bytesutil.ToBytes32(blkContainers[32].BlockRoot): true, - bytesutil.ToBytes32(blkContainers[64].BlockRoot): false, - }, - } - bs := &Server{ - BeaconDB: beaconDB, - ChainInfoFetcher: mockChainFetcher, - HeadFetcher: mockChainFetcher, - OptimisticModeFetcher: mockChainFetcher, - FinalizationFetcher: mockChainFetcher, - } - - t.Run("true", func(t *testing.T) { - blockRootResp, err := bs.GetBlockRoot(ctx, ðpbv1.BlockRequest{ - BlockId: []byte("32"), - }) - require.NoError(t, err) - assert.Equal(t, true, blockRootResp.Finalized) - }) - t.Run("false", func(t *testing.T) { - blockRootResp, err := bs.GetBlockRoot(ctx, ðpbv1.BlockRequest{ - BlockId: []byte("64"), - }) - require.NoError(t, err) - assert.Equal(t, false, blockRootResp.Finalized) - }) - }) -} - -func TestServer_ListBlockAttestations(t *testing.T) { - t.Run("Phase 0", func(t *testing.T) { - beaconDB := dbTest.SetupDB(t) - ctx := context.Background() - - _, blkContainers := fillDBTestBlocks(ctx, t, beaconDB) - headBlock := blkContainers[len(blkContainers)-1] - wsb, err := blocks.NewSignedBeaconBlock(headBlock.Block.(*ethpbalpha.BeaconBlockContainer_Phase0Block).Phase0Block) - require.NoError(t, err) - mockChainService := &mock.ChainService{ - DB: beaconDB, - Block: wsb, - Root: headBlock.BlockRoot, - FinalizedCheckPoint: ðpbalpha.Checkpoint{Root: blkContainers[64].BlockRoot}, - FinalizedRoots: map[[32]byte]bool{}, - } - bs := &Server{ - BeaconDB: beaconDB, - ChainInfoFetcher: mockChainService, - HeadFetcher: mockChainService, - OptimisticModeFetcher: mockChainService, - FinalizationFetcher: mockChainService, - } - - genBlk, blkContainers := fillDBTestBlocks(ctx, t, beaconDB) - root, err := genBlk.Block.HashTreeRoot() - require.NoError(t, err) - - tests := []struct { - name string - blockID []byte - want *ethpbalpha.SignedBeaconBlock - wantErr bool - }{ - { - name: "slot", - blockID: []byte("30"), - want: blkContainers[30].Block.(*ethpbalpha.BeaconBlockContainer_Phase0Block).Phase0Block, - }, - { - name: "bad formatting", - blockID: []byte("3bad0"), - wantErr: true, - }, - { - name: "head", - blockID: []byte("head"), - want: headBlock.Block.(*ethpbalpha.BeaconBlockContainer_Phase0Block).Phase0Block, - }, - { - name: "finalized", - blockID: []byte("finalized"), - want: blkContainers[64].Block.(*ethpbalpha.BeaconBlockContainer_Phase0Block).Phase0Block, - }, - { - name: "genesis", - blockID: []byte("genesis"), - want: genBlk, - }, - { - name: "genesis root", - blockID: root[:], - want: genBlk, - }, - { - name: "root", - blockID: blkContainers[20].BlockRoot, - want: blkContainers[20].Block.(*ethpbalpha.BeaconBlockContainer_Phase0Block).Phase0Block, - }, - { - name: "non-existent root", - blockID: bytesutil.PadTo([]byte("hi there"), 32), - wantErr: true, - }, - { - name: "slot", - blockID: []byte("40"), - want: blkContainers[40].Block.(*ethpbalpha.BeaconBlockContainer_Phase0Block).Phase0Block, - }, - { - name: "no block", - blockID: []byte("105"), - wantErr: true, - }, - } - for _, tt := range tests { - t.Run(tt.name, func(t *testing.T) { - blk, err := bs.ListBlockAttestations(ctx, ðpbv1.BlockRequest{ - BlockId: tt.blockID, - }) - if tt.wantErr { - require.NotEqual(t, err, nil) - return - } - require.NoError(t, err) - - v1Block, err := migration.V1Alpha1ToV1SignedBlock(tt.want) - require.NoError(t, err) - blkAtts := blk.Data - if len(blkAtts) == 0 { - blkAtts = nil - } - if !reflect.DeepEqual(blkAtts, v1Block.Block.Body.Attestations) { - t.Error("Expected attestations to equal") - } - }) - } - }) - - t.Run("Altair", func(t *testing.T) { - beaconDB := dbTest.SetupDB(t) - ctx := context.Background() - - _, blkContainers := fillDBTestBlocksAltair(ctx, t, beaconDB) - headBlock := blkContainers[len(blkContainers)-1] - blk, err := blocks.NewSignedBeaconBlock(headBlock.Block.(*ethpbalpha.BeaconBlockContainer_AltairBlock).AltairBlock) - require.NoError(t, err) - mockChainService := &mock.ChainService{ - DB: beaconDB, - Block: blk, - Root: headBlock.BlockRoot, - FinalizedCheckPoint: ðpbalpha.Checkpoint{Root: blkContainers[64].BlockRoot}, - FinalizedRoots: map[[32]byte]bool{}, - } - bs := &Server{ - BeaconDB: beaconDB, - ChainInfoFetcher: mockChainService, - HeadFetcher: mockChainService, - OptimisticModeFetcher: mockChainService, - FinalizationFetcher: mockChainService, - } - - genBlk, blkContainers := fillDBTestBlocksAltair(ctx, t, beaconDB) - root, err := genBlk.Block.HashTreeRoot() - require.NoError(t, err) - - tests := []struct { - name string - blockID []byte - want *ethpbalpha.SignedBeaconBlockAltair - wantErr bool - }{ - { - name: "slot", - blockID: []byte("30"), - want: blkContainers[30].Block.(*ethpbalpha.BeaconBlockContainer_AltairBlock).AltairBlock, - }, - { - name: "bad formatting", - blockID: []byte("3bad0"), - wantErr: true, - }, - { - name: "head", - blockID: []byte("head"), - want: headBlock.Block.(*ethpbalpha.BeaconBlockContainer_AltairBlock).AltairBlock, - }, - { - name: "finalized", - blockID: []byte("finalized"), - want: blkContainers[64].Block.(*ethpbalpha.BeaconBlockContainer_AltairBlock).AltairBlock, - }, - { - name: "genesis", - blockID: []byte("genesis"), - want: genBlk, - }, - { - name: "genesis root", - blockID: root[:], - want: genBlk, - }, - { - name: "root", - blockID: blkContainers[20].BlockRoot, - want: blkContainers[20].Block.(*ethpbalpha.BeaconBlockContainer_AltairBlock).AltairBlock, - }, - { - name: "non-existent root", - blockID: bytesutil.PadTo([]byte("hi there"), 32), - wantErr: true, - }, - { - name: "slot", - blockID: []byte("40"), - want: blkContainers[40].Block.(*ethpbalpha.BeaconBlockContainer_AltairBlock).AltairBlock, - }, - { - name: "no block", - blockID: []byte("105"), - wantErr: true, - }, + OptimisticModeFetcher: mockChainService, + FinalizationFetcher: mockChainService, + BlockFetcher: &testutil.MockBlockFetcher{BlockToReturn: sb}, } - for _, tt := range tests { - t.Run(tt.name, func(t *testing.T) { - blk, err := bs.ListBlockAttestations(ctx, ðpbv1.BlockRequest{ - BlockId: tt.blockID, - }) - if tt.wantErr { - require.NotEqual(t, err, nil) - return - } - require.NoError(t, err) - v1Block, err := migration.V1Alpha1BeaconBlockAltairToV2(tt.want.Block) - require.NoError(t, err) + resp, err := bs.GetBlockSSZV2(ctx, ðpbv2.BlockRequestV2{}) + require.NoError(t, err) + assert.NotNil(t, resp) + sszBlock, err := b.MarshalSSZ() + require.NoError(t, err) + assert.DeepEqual(t, sszBlock, resp.Data) + assert.Equal(t, ethpbv2.Version_BELLATRIX, resp.Version) + }) + t.Run("Capella", func(t *testing.T) { + b := util.NewBeaconBlockCapella() + b.Block.Slot = 123 + sb, err := blocks.NewSignedBeaconBlock(b) + require.NoError(t, err) - blkAtts := blk.Data - if len(blkAtts) == 0 { - blkAtts = nil - } - if !reflect.DeepEqual(blkAtts, v1Block.Body.Attestations) { - t.Error("Expected attestations to equal") - } - }) + mockChainService := &mock.ChainService{ + FinalizedRoots: map[[32]byte]bool{}, + } + bs := &Server{ + OptimisticModeFetcher: mockChainService, + FinalizationFetcher: mockChainService, + BlockFetcher: &testutil.MockBlockFetcher{BlockToReturn: sb}, } + + resp, err := bs.GetBlockSSZV2(ctx, ðpbv2.BlockRequestV2{}) + require.NoError(t, err) + assert.NotNil(t, resp) + sszBlock, err := b.MarshalSSZ() + require.NoError(t, err) + assert.DeepEqual(t, sszBlock, resp.Data) + assert.Equal(t, ethpbv2.Version_CAPELLA, resp.Version) }) + t.Run("execution optimistic", func(t *testing.T) { + b := util.NewBeaconBlockBellatrix() + sb, err := blocks.NewSignedBeaconBlock(b) + require.NoError(t, err) - t.Run("Bellatrix", func(t *testing.T) { - beaconDB := dbTest.SetupDB(t) - ctx := context.Background() + mockChainService := &mock.ChainService{ + Optimistic: true, + FinalizedRoots: map[[32]byte]bool{}, + } + bs := &Server{ + OptimisticModeFetcher: mockChainService, + FinalizationFetcher: mockChainService, + BlockFetcher: &testutil.MockBlockFetcher{BlockToReturn: sb}, + } - _, blkContainers := fillDBTestBlocksBellatrix(ctx, t, beaconDB) - headBlock := blkContainers[len(blkContainers)-1] - blk, err := blocks.NewSignedBeaconBlock(headBlock.Block.(*ethpbalpha.BeaconBlockContainer_BellatrixBlock).BellatrixBlock) + resp, err := bs.GetBlockSSZV2(ctx, ðpbv2.BlockRequestV2{}) require.NoError(t, err) - mockChainService := &mock.ChainService{ + assert.Equal(t, true, resp.ExecutionOptimistic) + }) + t.Run("finalized", func(t *testing.T) { + b := util.NewBeaconBlock() + sb, err := blocks.NewSignedBeaconBlock(b) + require.NoError(t, err) + r, err := sb.Block().HashTreeRoot() + require.NoError(t, err) + mockBlockFetcher := &testutil.MockBlockFetcher{BlockToReturn: sb} + + t.Run("true", func(t *testing.T) { + mockChainService := &mock.ChainService{FinalizedRoots: map[[32]byte]bool{r: true}} + bs := &Server{ + OptimisticModeFetcher: mockChainService, + FinalizationFetcher: mockChainService, + BlockFetcher: mockBlockFetcher, + } + + header, err := bs.GetBlockSSZV2(ctx, ðpbv2.BlockRequestV2{BlockId: r[:]}) + require.NoError(t, err) + assert.Equal(t, true, header.Finalized) + }) + t.Run("false", func(t *testing.T) { + mockChainService := &mock.ChainService{FinalizedRoots: map[[32]byte]bool{r: false}} + bs := &Server{ + OptimisticModeFetcher: mockChainService, + FinalizationFetcher: mockChainService, + BlockFetcher: mockBlockFetcher, + } + + resp, err := bs.GetBlockSSZV2(ctx, ðpbv2.BlockRequestV2{BlockId: r[:]}) + require.NoError(t, err) + assert.Equal(t, false, resp.Finalized) + }) + }) +} + +func TestServer_GetBlockRoot(t *testing.T) { + beaconDB := dbTest.SetupDB(t) + ctx := context.Background() + + genBlk, blkContainers := fillDBTestBlocks(ctx, t, beaconDB) + headBlock := blkContainers[len(blkContainers)-1] + + t.Run("get root", func(t *testing.T) { + wsb, err := blocks.NewSignedBeaconBlock(headBlock.Block.(*ethpbalpha.BeaconBlockContainer_Phase0Block).Phase0Block) + require.NoError(t, err) + mockChainFetcher := &mock.ChainService{ DB: beaconDB, - Block: blk, + Block: wsb, Root: headBlock.BlockRoot, FinalizedCheckPoint: ðpbalpha.Checkpoint{Root: blkContainers[64].BlockRoot}, FinalizedRoots: map[[32]byte]bool{}, } bs := &Server{ BeaconDB: beaconDB, - ChainInfoFetcher: mockChainService, - HeadFetcher: mockChainService, - OptimisticModeFetcher: mockChainService, - FinalizationFetcher: mockChainService, + ChainInfoFetcher: mockChainFetcher, + HeadFetcher: mockChainFetcher, + OptimisticModeFetcher: mockChainFetcher, + FinalizationFetcher: mockChainFetcher, } - genBlk, blkContainers := fillDBTestBlocksBellatrix(ctx, t, beaconDB) root, err := genBlk.Block.HashTreeRoot() require.NoError(t, err) tests := []struct { name string blockID []byte - want *ethpbalpha.SignedBeaconBlockBellatrix + want []byte wantErr bool }{ - { - name: "slot", - blockID: []byte("30"), - want: blkContainers[30].Block.(*ethpbalpha.BeaconBlockContainer_BellatrixBlock).BellatrixBlock, - }, { name: "bad formatting", blockID: []byte("3bad0"), wantErr: true, }, + { + name: "canonical slot", + blockID: []byte("30"), + want: blkContainers[30].BlockRoot, + }, { name: "head", blockID: []byte("head"), - want: headBlock.Block.(*ethpbalpha.BeaconBlockContainer_BellatrixBlock).BellatrixBlock, + want: headBlock.BlockRoot, }, { name: "finalized", blockID: []byte("finalized"), - want: blkContainers[64].Block.(*ethpbalpha.BeaconBlockContainer_BellatrixBlock).BellatrixBlock, + want: blkContainers[64].BlockRoot, }, { name: "genesis", blockID: []byte("genesis"), - want: genBlk, + want: root[:], }, { name: "genesis root", blockID: root[:], - want: genBlk, + want: root[:], }, { name: "root", blockID: blkContainers[20].BlockRoot, - want: blkContainers[20].Block.(*ethpbalpha.BeaconBlockContainer_BellatrixBlock).BellatrixBlock, + want: blkContainers[20].BlockRoot, }, { name: "non-existent root", @@ -2388,7 +1080,7 @@ func TestServer_ListBlockAttestations(t *testing.T) { { name: "slot", blockID: []byte("40"), - want: blkContainers[40].Block.(*ethpbalpha.BeaconBlockContainer_BellatrixBlock).BellatrixBlock, + want: blkContainers[40].BlockRoot, }, { name: "no block", @@ -2398,7 +1090,7 @@ func TestServer_ListBlockAttestations(t *testing.T) { } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { - blk, err := bs.ListBlockAttestations(ctx, ðpbv1.BlockRequest{ + blockRootResp, err := bs.GetBlockRoot(ctx, ðpbv1.BlockRequest{ BlockId: tt.blockID, }) if tt.wantErr { @@ -2406,32 +1098,17 @@ func TestServer_ListBlockAttestations(t *testing.T) { return } require.NoError(t, err) - - v1Block, err := migration.V1Alpha1BeaconBlockBellatrixToV2(tt.want.Block) - require.NoError(t, err) - - blkAtts := blk.Data - if len(blkAtts) == 0 { - blkAtts = nil - } - if !reflect.DeepEqual(blkAtts, v1Block.Body.Attestations) { - t.Error("Expected attestations to equal") - } + assert.DeepEqual(t, tt.want, blockRootResp.Data.Root) }) } }) t.Run("execution optimistic", func(t *testing.T) { - beaconDB := dbTest.SetupDB(t) - ctx := context.Background() - - _, blkContainers := fillDBTestBlocksBellatrix(ctx, t, beaconDB) - headBlock := blkContainers[len(blkContainers)-1] - blk, err := blocks.NewSignedBeaconBlock(headBlock.Block.(*ethpbalpha.BeaconBlockContainer_BellatrixBlock).BellatrixBlock) + wsb, err := blocks.NewSignedBeaconBlock(headBlock.Block.(*ethpbalpha.BeaconBlockContainer_Phase0Block).Phase0Block) require.NoError(t, err) - mockChainService := &mock.ChainService{ + mockChainFetcher := &mock.ChainService{ DB: beaconDB, - Block: blk, + Block: wsb, Root: headBlock.BlockRoot, FinalizedCheckPoint: ðpbalpha.Checkpoint{Root: blkContainers[64].BlockRoot}, Optimistic: true, @@ -2439,31 +1116,27 @@ func TestServer_ListBlockAttestations(t *testing.T) { } bs := &Server{ BeaconDB: beaconDB, - ChainInfoFetcher: mockChainService, - HeadFetcher: mockChainService, - OptimisticModeFetcher: mockChainService, - FinalizationFetcher: mockChainService, + ChainInfoFetcher: mockChainFetcher, + HeadFetcher: mockChainFetcher, + OptimisticModeFetcher: mockChainFetcher, + FinalizationFetcher: mockChainFetcher, } - resp, err := bs.ListBlockAttestations(ctx, ðpbv1.BlockRequest{ + blockRootResp, err := bs.GetBlockRoot(ctx, ðpbv1.BlockRequest{ BlockId: []byte("head"), }) require.NoError(t, err) - assert.Equal(t, true, resp.ExecutionOptimistic) + assert.Equal(t, true, blockRootResp.ExecutionOptimistic) }) t.Run("finalized", func(t *testing.T) { - beaconDB := dbTest.SetupDB(t) - ctx := context.Background() - - _, blkContainers := fillDBTestBlocks(ctx, t, beaconDB) - headBlock := blkContainers[len(blkContainers)-1] - blk, err := blocks.NewSignedBeaconBlock(headBlock.Block.(*ethpbalpha.BeaconBlockContainer_Phase0Block).Phase0Block) + wsb, err := blocks.NewSignedBeaconBlock(headBlock.Block.(*ethpbalpha.BeaconBlockContainer_Phase0Block).Phase0Block) require.NoError(t, err) - mockChainService := &mock.ChainService{ + mockChainFetcher := &mock.ChainService{ DB: beaconDB, - Block: blk, + Block: wsb, Root: headBlock.BlockRoot, FinalizedCheckPoint: ðpbalpha.Checkpoint{Root: blkContainers[64].BlockRoot}, + Optimistic: true, FinalizedRoots: map[[32]byte]bool{ bytesutil.ToBytes32(blkContainers[32].BlockRoot): true, bytesutil.ToBytes32(blkContainers[64].BlockRoot): false, @@ -2471,24 +1144,309 @@ func TestServer_ListBlockAttestations(t *testing.T) { } bs := &Server{ BeaconDB: beaconDB, - ChainInfoFetcher: mockChainService, - HeadFetcher: mockChainService, - OptimisticModeFetcher: mockChainService, - FinalizationFetcher: mockChainService, + ChainInfoFetcher: mockChainFetcher, + HeadFetcher: mockChainFetcher, + OptimisticModeFetcher: mockChainFetcher, + FinalizationFetcher: mockChainFetcher, } t.Run("true", func(t *testing.T) { - resp, err := bs.ListBlockAttestations(ctx, ðpbv1.BlockRequest{ + blockRootResp, err := bs.GetBlockRoot(ctx, ðpbv1.BlockRequest{ BlockId: []byte("32"), }) require.NoError(t, err) - assert.Equal(t, true, resp.Finalized) + assert.Equal(t, true, blockRootResp.Finalized) }) t.Run("false", func(t *testing.T) { - resp, err := bs.ListBlockAttestations(ctx, ðpbv1.BlockRequest{ + blockRootResp, err := bs.GetBlockRoot(ctx, ðpbv1.BlockRequest{ BlockId: []byte("64"), }) require.NoError(t, err) + assert.Equal(t, false, blockRootResp.Finalized) + }) + }) +} + +func TestServer_ListBlockAttestations(t *testing.T) { + ctx := context.Background() + + t.Run("Phase 0", func(t *testing.T) { + b := util.NewBeaconBlock() + b.Block.Body.Attestations = []*ethpbalpha.Attestation{ + { + AggregationBits: bitfield.Bitlist{0x00}, + Data: ðpbalpha.AttestationData{ + Slot: 123, + CommitteeIndex: 123, + BeaconBlockRoot: bytesutil.PadTo([]byte("root1"), 32), + Source: ðpbalpha.Checkpoint{ + Epoch: 123, + Root: bytesutil.PadTo([]byte("root1"), 32), + }, + Target: ðpbalpha.Checkpoint{ + Epoch: 123, + Root: bytesutil.PadTo([]byte("root1"), 32), + }, + }, + Signature: bytesutil.PadTo([]byte("sig1"), 96), + }, + { + AggregationBits: bitfield.Bitlist{0x01}, + Data: ðpbalpha.AttestationData{ + Slot: 456, + CommitteeIndex: 456, + BeaconBlockRoot: bytesutil.PadTo([]byte("root2"), 32), + Source: ðpbalpha.Checkpoint{ + Epoch: 456, + Root: bytesutil.PadTo([]byte("root2"), 32), + }, + Target: ðpbalpha.Checkpoint{ + Epoch: 456, + Root: bytesutil.PadTo([]byte("root2"), 32), + }, + }, + Signature: bytesutil.PadTo([]byte("sig2"), 96), + }, + } + sb, err := blocks.NewSignedBeaconBlock(b) + require.NoError(t, err) + mockBlockFetcher := &testutil.MockBlockFetcher{BlockToReturn: sb} + mockChainService := &mock.ChainService{ + FinalizedRoots: map[[32]byte]bool{}, + } + bs := &Server{ + OptimisticModeFetcher: mockChainService, + FinalizationFetcher: mockChainService, + BlockFetcher: mockBlockFetcher, + } + + resp, err := bs.ListBlockAttestations(ctx, ðpbv1.BlockRequest{}) + require.NoError(t, err) + + v1Block, err := migration.V1Alpha1ToV1SignedBlock(b) + require.NoError(t, err) + assert.DeepEqual(t, v1Block.Block.Body.Attestations, resp.Data) + }) + t.Run("Altair", func(t *testing.T) { + b := util.NewBeaconBlockAltair() + b.Block.Body.Attestations = []*ethpbalpha.Attestation{ + { + AggregationBits: bitfield.Bitlist{0x00}, + Data: ðpbalpha.AttestationData{ + Slot: 123, + CommitteeIndex: 123, + BeaconBlockRoot: bytesutil.PadTo([]byte("root1"), 32), + Source: ðpbalpha.Checkpoint{ + Epoch: 123, + Root: bytesutil.PadTo([]byte("root1"), 32), + }, + Target: ðpbalpha.Checkpoint{ + Epoch: 123, + Root: bytesutil.PadTo([]byte("root1"), 32), + }, + }, + Signature: bytesutil.PadTo([]byte("sig1"), 96), + }, + { + AggregationBits: bitfield.Bitlist{0x01}, + Data: ðpbalpha.AttestationData{ + Slot: 456, + CommitteeIndex: 456, + BeaconBlockRoot: bytesutil.PadTo([]byte("root2"), 32), + Source: ðpbalpha.Checkpoint{ + Epoch: 456, + Root: bytesutil.PadTo([]byte("root2"), 32), + }, + Target: ðpbalpha.Checkpoint{ + Epoch: 456, + Root: bytesutil.PadTo([]byte("root2"), 32), + }, + }, + Signature: bytesutil.PadTo([]byte("sig2"), 96), + }, + } + sb, err := blocks.NewSignedBeaconBlock(b) + require.NoError(t, err) + mockBlockFetcher := &testutil.MockBlockFetcher{BlockToReturn: sb} + mockChainService := &mock.ChainService{ + FinalizedRoots: map[[32]byte]bool{}, + } + bs := &Server{ + OptimisticModeFetcher: mockChainService, + FinalizationFetcher: mockChainService, + BlockFetcher: mockBlockFetcher, + } + + resp, err := bs.ListBlockAttestations(ctx, ðpbv1.BlockRequest{}) + require.NoError(t, err) + + v1Block, err := migration.V1Alpha1BeaconBlockAltairToV2(b.Block) + require.NoError(t, err) + assert.DeepEqual(t, v1Block.Body.Attestations, resp.Data) + }) + t.Run("Bellatrix", func(t *testing.T) { + b := util.NewBeaconBlockBellatrix() + b.Block.Body.Attestations = []*ethpbalpha.Attestation{ + { + AggregationBits: bitfield.Bitlist{0x00}, + Data: ðpbalpha.AttestationData{ + Slot: 123, + CommitteeIndex: 123, + BeaconBlockRoot: bytesutil.PadTo([]byte("root1"), 32), + Source: ðpbalpha.Checkpoint{ + Epoch: 123, + Root: bytesutil.PadTo([]byte("root1"), 32), + }, + Target: ðpbalpha.Checkpoint{ + Epoch: 123, + Root: bytesutil.PadTo([]byte("root1"), 32), + }, + }, + Signature: bytesutil.PadTo([]byte("sig1"), 96), + }, + { + AggregationBits: bitfield.Bitlist{0x01}, + Data: ðpbalpha.AttestationData{ + Slot: 456, + CommitteeIndex: 456, + BeaconBlockRoot: bytesutil.PadTo([]byte("root2"), 32), + Source: ðpbalpha.Checkpoint{ + Epoch: 456, + Root: bytesutil.PadTo([]byte("root2"), 32), + }, + Target: ðpbalpha.Checkpoint{ + Epoch: 456, + Root: bytesutil.PadTo([]byte("root2"), 32), + }, + }, + Signature: bytesutil.PadTo([]byte("sig2"), 96), + }, + } + sb, err := blocks.NewSignedBeaconBlock(b) + require.NoError(t, err) + mockBlockFetcher := &testutil.MockBlockFetcher{BlockToReturn: sb} + mockChainService := &mock.ChainService{ + FinalizedRoots: map[[32]byte]bool{}, + } + bs := &Server{ + OptimisticModeFetcher: mockChainService, + FinalizationFetcher: mockChainService, + BlockFetcher: mockBlockFetcher, + } + + resp, err := bs.ListBlockAttestations(ctx, ðpbv1.BlockRequest{}) + require.NoError(t, err) + + v1Block, err := migration.V1Alpha1BeaconBlockBellatrixToV2(b.Block) + require.NoError(t, err) + assert.DeepEqual(t, v1Block.Body.Attestations, resp.Data) + }) + t.Run("Capella", func(t *testing.T) { + b := util.NewBeaconBlockCapella() + b.Block.Body.Attestations = []*ethpbalpha.Attestation{ + { + AggregationBits: bitfield.Bitlist{0x00}, + Data: ðpbalpha.AttestationData{ + Slot: 123, + CommitteeIndex: 123, + BeaconBlockRoot: bytesutil.PadTo([]byte("root1"), 32), + Source: ðpbalpha.Checkpoint{ + Epoch: 123, + Root: bytesutil.PadTo([]byte("root1"), 32), + }, + Target: ðpbalpha.Checkpoint{ + Epoch: 123, + Root: bytesutil.PadTo([]byte("root1"), 32), + }, + }, + Signature: bytesutil.PadTo([]byte("sig1"), 96), + }, + { + AggregationBits: bitfield.Bitlist{0x01}, + Data: ðpbalpha.AttestationData{ + Slot: 456, + CommitteeIndex: 456, + BeaconBlockRoot: bytesutil.PadTo([]byte("root2"), 32), + Source: ðpbalpha.Checkpoint{ + Epoch: 456, + Root: bytesutil.PadTo([]byte("root2"), 32), + }, + Target: ðpbalpha.Checkpoint{ + Epoch: 456, + Root: bytesutil.PadTo([]byte("root2"), 32), + }, + }, + Signature: bytesutil.PadTo([]byte("sig2"), 96), + }, + } + sb, err := blocks.NewSignedBeaconBlock(b) + require.NoError(t, err) + mockBlockFetcher := &testutil.MockBlockFetcher{BlockToReturn: sb} + mockChainService := &mock.ChainService{ + FinalizedRoots: map[[32]byte]bool{}, + } + bs := &Server{ + OptimisticModeFetcher: mockChainService, + FinalizationFetcher: mockChainService, + BlockFetcher: mockBlockFetcher, + } + + resp, err := bs.ListBlockAttestations(ctx, ðpbv1.BlockRequest{}) + require.NoError(t, err) + + v1Block, err := migration.V1Alpha1BeaconBlockCapellaToV2(b.Block) + require.NoError(t, err) + assert.DeepEqual(t, v1Block.Body.Attestations, resp.Data) + }) + t.Run("execution optimistic", func(t *testing.T) { + b := util.NewBeaconBlockBellatrix() + sb, err := blocks.NewSignedBeaconBlock(b) + require.NoError(t, err) + mockBlockFetcher := &testutil.MockBlockFetcher{BlockToReturn: sb} + mockChainService := &mock.ChainService{ + Optimistic: true, + FinalizedRoots: map[[32]byte]bool{}, + } + bs := &Server{ + OptimisticModeFetcher: mockChainService, + FinalizationFetcher: mockChainService, + BlockFetcher: mockBlockFetcher, + } + + resp, err := bs.ListBlockAttestations(ctx, ðpbv1.BlockRequest{}) + require.NoError(t, err) + assert.Equal(t, true, resp.ExecutionOptimistic) + }) + t.Run("finalized", func(t *testing.T) { + b := util.NewBeaconBlock() + sb, err := blocks.NewSignedBeaconBlock(b) + require.NoError(t, err) + r, err := sb.Block().HashTreeRoot() + require.NoError(t, err) + mockBlockFetcher := &testutil.MockBlockFetcher{BlockToReturn: sb} + + t.Run("true", func(t *testing.T) { + mockChainService := &mock.ChainService{FinalizedRoots: map[[32]byte]bool{r: true}} + bs := &Server{ + OptimisticModeFetcher: mockChainService, + FinalizationFetcher: mockChainService, + BlockFetcher: mockBlockFetcher, + } + + resp, err := bs.ListBlockAttestations(ctx, ðpbv1.BlockRequest{BlockId: r[:]}) + require.NoError(t, err) + assert.Equal(t, true, resp.Finalized) + }) + t.Run("false", func(t *testing.T) { + mockChainService := &mock.ChainService{FinalizedRoots: map[[32]byte]bool{r: false}} + bs := &Server{ + OptimisticModeFetcher: mockChainService, + FinalizationFetcher: mockChainService, + BlockFetcher: mockBlockFetcher, + } + + resp, err := bs.ListBlockAttestations(ctx, ðpbv1.BlockRequest{BlockId: r[:]}) + require.NoError(t, err) assert.Equal(t, false, resp.Finalized) }) }) From 53c8367d6c6117f509ba8f50cdde23b1c1304a0e Mon Sep 17 00:00:00 2001 From: rkapka Date: Tue, 21 Mar 2023 17:32:25 +0100 Subject: [PATCH 24/40] bzl --- beacon-chain/rpc/eth/beacon/BUILD.bazel | 2 -- 1 file changed, 2 deletions(-) diff --git a/beacon-chain/rpc/eth/beacon/BUILD.bazel b/beacon-chain/rpc/eth/beacon/BUILD.bazel index 3f73c68eaea8..966a3aa0fb3e 100644 --- a/beacon-chain/rpc/eth/beacon/BUILD.bazel +++ b/beacon-chain/rpc/eth/beacon/BUILD.bazel @@ -93,7 +93,6 @@ go_test( "//beacon-chain/core/transition:go_default_library", "//beacon-chain/db:go_default_library", "//beacon-chain/db/testing:go_default_library", - "//beacon-chain/execution/testing:go_default_library", "//beacon-chain/operations/attestations:go_default_library", "//beacon-chain/operations/blstoexec:go_default_library", "//beacon-chain/operations/blstoexec/mock:go_default_library", @@ -107,7 +106,6 @@ go_test( "//beacon-chain/rpc/testutil:go_default_library", "//beacon-chain/state:go_default_library", "//beacon-chain/state/state-native:go_default_library", - "//config/features:go_default_library", "//config/params:go_default_library", "//consensus-types/blocks:go_default_library", "//consensus-types/interfaces:go_default_library", From 075b00ac86b50795750ae208bbd01e381a2e9e25 Mon Sep 17 00:00:00 2001 From: rkapka Date: Tue, 21 Mar 2023 18:07:54 +0100 Subject: [PATCH 25/40] handle err --- beacon-chain/rpc/eth/beacon/blocks_test.go | 1 + 1 file changed, 1 insertion(+) diff --git a/beacon-chain/rpc/eth/beacon/blocks_test.go b/beacon-chain/rpc/eth/beacon/blocks_test.go index 87be1155f8a0..02460f651cdd 100644 --- a/beacon-chain/rpc/eth/beacon/blocks_test.go +++ b/beacon-chain/rpc/eth/beacon/blocks_test.go @@ -683,6 +683,7 @@ func TestServer_GetBlock(t *testing.T) { } blk, err := bs.GetBlock(ctx, ðpbv1.BlockRequest{}) + require.NoError(t, err) v1Block, err := migration.V1Alpha1ToV1SignedBlock(b) require.NoError(t, err) assert.DeepEqual(t, v1Block.Block, blk.Data.Message) From ea22cafc7da3fb0da3a9e3454afeba10e728da94 Mon Sep 17 00:00:00 2001 From: rkapka Date: Wed, 22 Mar 2023 14:07:09 +0100 Subject: [PATCH 26/40] review feedback --- beacon-chain/rpc/blockfetcher/fetcher.go | 19 ++++-- beacon-chain/rpc/eth/helpers/BUILD.bazel | 2 - beacon-chain/rpc/eth/rewards/BUILD.bazel | 4 +- beacon-chain/rpc/eth/rewards/handlers.go | 66 +++++++++---------- beacon-chain/rpc/eth/rewards/handlers_test.go | 4 +- network/BUILD.bazel | 2 + .../rpc/eth/helpers => network}/http.go | 2 +- 7 files changed, 53 insertions(+), 46 deletions(-) rename {beacon-chain/rpc/eth/helpers => network}/http.go (98%) diff --git a/beacon-chain/rpc/blockfetcher/fetcher.go b/beacon-chain/rpc/blockfetcher/fetcher.go index 1134a776ec9a..09defdef64d8 100644 --- a/beacon-chain/rpc/blockfetcher/fetcher.go +++ b/beacon-chain/rpc/blockfetcher/fetcher.go @@ -31,7 +31,7 @@ func (e BlockIdParseError) Error() string { // Fetcher is responsible for retrieving info related with the beacon block. type Fetcher interface { - Block(ctx context.Context, blockId []byte) (interfaces.ReadOnlySignedBeaconBlock, error) + Block(ctx context.Context, id []byte) (interfaces.ReadOnlySignedBeaconBlock, error) } // BlockProvider is a real implementation of Fetcher. @@ -40,10 +40,17 @@ type BlockProvider struct { ChainInfoFetcher blockchain.ChainInfoFetcher } -func (p *BlockProvider) Block(ctx context.Context, blockId []byte) (interfaces.ReadOnlySignedBeaconBlock, error) { +// Block returns the beacon block for a given identifier. The identifier can be one of: +// - "head" (canonical head in node's view) +// - "genesis" +// - "finalized" +// - "justified" +// - +// - +func (p *BlockProvider) Block(ctx context.Context, id []byte) (interfaces.ReadOnlySignedBeaconBlock, error) { var err error var blk interfaces.ReadOnlySignedBeaconBlock - switch string(blockId) { + switch string(id) { case "head": blk, err = p.ChainInfoFetcher.HeadBlock(ctx) if err != nil { @@ -62,13 +69,13 @@ func (p *BlockProvider) Block(ctx context.Context, blockId []byte) (interfaces.R return nil, errors.Wrap(err, "could not retrieve genesis block") } default: - if len(blockId) == 32 { - blk, err = p.BeaconDB.Block(ctx, bytesutil.ToBytes32(blockId)) + if len(id) == 32 { + blk, err = p.BeaconDB.Block(ctx, bytesutil.ToBytes32(id)) if err != nil { return nil, errors.Wrap(err, "could not retrieve block") } } else { - slot, err := strconv.ParseUint(string(blockId), 10, 64) + slot, err := strconv.ParseUint(string(id), 10, 64) if err != nil { e := NewBlockIdParseError(err) return nil, &e diff --git a/beacon-chain/rpc/eth/helpers/BUILD.bazel b/beacon-chain/rpc/eth/helpers/BUILD.bazel index 8b156a3b25ef..2b40430813ac 100644 --- a/beacon-chain/rpc/eth/helpers/BUILD.bazel +++ b/beacon-chain/rpc/eth/helpers/BUILD.bazel @@ -4,7 +4,6 @@ go_library( name = "go_default_library", srcs = [ "error_handling.go", - "http.go", "sync.go", "validator_status.go", ], @@ -24,7 +23,6 @@ go_library( "//proto/eth/v1:go_default_library", "//time/slots:go_default_library", "@com_github_pkg_errors//:go_default_library", - "@com_github_sirupsen_logrus//:go_default_library", "@org_golang_google_grpc//codes:go_default_library", "@org_golang_google_grpc//status:go_default_library", ], diff --git a/beacon-chain/rpc/eth/rewards/BUILD.bazel b/beacon-chain/rpc/eth/rewards/BUILD.bazel index 7a6d4900d24d..a7e0b7ce9f2a 100644 --- a/beacon-chain/rpc/eth/rewards/BUILD.bazel +++ b/beacon-chain/rpc/eth/rewards/BUILD.bazel @@ -15,11 +15,11 @@ go_library( "//beacon-chain/core/blocks:go_default_library", "//beacon-chain/core/validators:go_default_library", "//beacon-chain/rpc/blockfetcher:go_default_library", - "//beacon-chain/rpc/eth/helpers:go_default_library", "//beacon-chain/state/stategen:go_default_library", "//consensus-types/blocks:go_default_library", "//consensus-types/interfaces:go_default_library", "//consensus-types/primitives:go_default_library", + "//network:go_default_library", "//runtime/version:go_default_library", "@com_github_pkg_errors//:go_default_library", ], @@ -36,7 +36,6 @@ go_test( "//beacon-chain/blockchain/testing:go_default_library", "//beacon-chain/core/altair:go_default_library", "//beacon-chain/core/signing:go_default_library", - "//beacon-chain/rpc/eth/helpers:go_default_library", "//beacon-chain/rpc/testutil:go_default_library", "//beacon-chain/state/stategen/mock:go_default_library", "//config/fieldparams:go_default_library", @@ -47,6 +46,7 @@ go_test( "//crypto/bls:go_default_library", "//crypto/bls/blst:go_default_library", "//encoding/bytesutil:go_default_library", + "//network:go_default_library", "//proto/prysm/v1alpha1:go_default_library", "//testing/assert:go_default_library", "//testing/require:go_default_library", diff --git a/beacon-chain/rpc/eth/rewards/handlers.go b/beacon-chain/rpc/eth/rewards/handlers.go index e657cca916c9..1a72b5a69fff 100644 --- a/beacon-chain/rpc/eth/rewards/handlers.go +++ b/beacon-chain/rpc/eth/rewards/handlers.go @@ -9,9 +9,9 @@ import ( coreblocks "github.com/prysmaticlabs/prysm/v4/beacon-chain/core/blocks" "github.com/prysmaticlabs/prysm/v4/beacon-chain/core/validators" "github.com/prysmaticlabs/prysm/v4/beacon-chain/rpc/blockfetcher" - "github.com/prysmaticlabs/prysm/v4/beacon-chain/rpc/eth/helpers" "github.com/prysmaticlabs/prysm/v4/consensus-types/blocks" "github.com/prysmaticlabs/prysm/v4/consensus-types/interfaces" + "github.com/prysmaticlabs/prysm/v4/network" "github.com/prysmaticlabs/prysm/v4/runtime/version" ) @@ -22,132 +22,132 @@ func (s *Server) BlockRewards(w http.ResponseWriter, r *http.Request) { blk, err := s.BlockFetcher.Block(r.Context(), []byte(blockId)) if errJson := handleGetBlockError(blk, err); errJson != nil { - helpers.WriteError(w, errJson) + network.WriteError(w, errJson) return } if blk.Version() == version.Phase0 { - errJson := &helpers.DefaultErrorJson{ + errJson := &network.DefaultErrorJson{ Message: "block rewards are not supported for Phase 0 blocks", Code: http.StatusBadRequest, } - helpers.WriteError(w, errJson) + network.WriteError(w, errJson) return } st, err := s.ReplayerBuilder.ReplayerForSlot(blk.Block().Slot()-1).ReplayToSlot(r.Context(), blk.Block().Slot()) if err != nil { - errJson := &helpers.DefaultErrorJson{ + errJson := &network.DefaultErrorJson{ Message: errors.Wrapf(err, "could not get state").Error(), Code: http.StatusInternalServerError, } - helpers.WriteError(w, errJson) + network.WriteError(w, errJson) return } proposerIndex := blk.Block().ProposerIndex() oldBalance, err := st.BalanceAtIndex(proposerIndex) if err != nil { - errJson := &helpers.DefaultErrorJson{ + errJson := &network.DefaultErrorJson{ Message: errors.Wrapf(err, "could not get proposer's balance").Error(), Code: http.StatusInternalServerError, } - helpers.WriteError(w, errJson) + network.WriteError(w, errJson) return } st, err = altair.ProcessAttestationsNoVerifySignature(r.Context(), st, blk) if err != nil { - errJson := &helpers.DefaultErrorJson{ + errJson := &network.DefaultErrorJson{ Message: errors.Wrapf(err, "could not get attestation rewards").Error(), Code: http.StatusInternalServerError, } - helpers.WriteError(w, errJson) + network.WriteError(w, errJson) return } newBalance, err := st.BalanceAtIndex(proposerIndex) if err != nil { - errJson := &helpers.DefaultErrorJson{ + errJson := &network.DefaultErrorJson{ Message: errors.Wrapf(err, "could not get proposer's balance").Error(), Code: http.StatusInternalServerError, } - helpers.WriteError(w, errJson) + network.WriteError(w, errJson) return } attsReward := newBalance - oldBalance oldBalance = newBalance st, err = coreblocks.ProcessAttesterSlashings(r.Context(), st, blk.Block().Body().AttesterSlashings(), validators.SlashValidator) if err != nil { - errJson := &helpers.DefaultErrorJson{ + errJson := &network.DefaultErrorJson{ Message: errors.Wrapf(err, "could not get attester slashing rewards").Error(), Code: http.StatusInternalServerError, } - helpers.WriteError(w, errJson) + network.WriteError(w, errJson) return } newBalance, err = st.BalanceAtIndex(proposerIndex) if err != nil { - errJson := &helpers.DefaultErrorJson{ + errJson := &network.DefaultErrorJson{ Message: errors.Wrapf(err, "could not get proposer's balance").Error(), Code: http.StatusInternalServerError, } - helpers.WriteError(w, errJson) + network.WriteError(w, errJson) return } attSlashingsReward := newBalance - oldBalance oldBalance = newBalance st, err = coreblocks.ProcessProposerSlashings(r.Context(), st, blk.Block().Body().ProposerSlashings(), validators.SlashValidator) if err != nil { - errJson := &helpers.DefaultErrorJson{ + errJson := &network.DefaultErrorJson{ Message: errors.Wrapf(err, "could not get proposer slashing rewards").Error(), Code: http.StatusInternalServerError, } - helpers.WriteError(w, errJson) + network.WriteError(w, errJson) return } newBalance, err = st.BalanceAtIndex(proposerIndex) if err != nil { - errJson := &helpers.DefaultErrorJson{ + errJson := &network.DefaultErrorJson{ Message: errors.Wrapf(err, "could not get proposer's balance").Error(), Code: http.StatusInternalServerError, } - helpers.WriteError(w, errJson) + network.WriteError(w, errJson) return } proposerSlashingsReward := newBalance - oldBalance sa, err := blk.Block().Body().SyncAggregate() if err != nil { - errJson := &helpers.DefaultErrorJson{ + errJson := &network.DefaultErrorJson{ Message: errors.Wrapf(err, "could not get sync aggregate").Error(), Code: http.StatusInternalServerError, } - helpers.WriteError(w, errJson) + network.WriteError(w, errJson) return } var syncCommitteeReward uint64 st, syncCommitteeReward, err = altair.ProcessSyncAggregate(r.Context(), st, sa) if err != nil { - errJson := &helpers.DefaultErrorJson{ + errJson := &network.DefaultErrorJson{ Message: errors.Wrapf(err, "could not get sync aggregate rewards").Error(), Code: http.StatusInternalServerError, } - helpers.WriteError(w, errJson) + network.WriteError(w, errJson) return } optimistic, err := s.OptimisticModeFetcher.IsOptimistic(r.Context()) if err != nil { - errJson := &helpers.DefaultErrorJson{ + errJson := &network.DefaultErrorJson{ Message: errors.Wrapf(err, "could not get optimistic mode info").Error(), Code: http.StatusInternalServerError, } - helpers.WriteError(w, errJson) + network.WriteError(w, errJson) return } blkRoot, err := blk.Block().HashTreeRoot() if err != nil { - errJson := &helpers.DefaultErrorJson{ + errJson := &network.DefaultErrorJson{ Message: errors.Wrapf(err, "could not get block root").Error(), Code: http.StatusInternalServerError, } - helpers.WriteError(w, errJson) + network.WriteError(w, errJson) return } @@ -163,24 +163,24 @@ func (s *Server) BlockRewards(w http.ResponseWriter, r *http.Request) { ExecutionOptimistic: optimistic, Finalized: s.FinalizationFetcher.IsFinalized(r.Context(), blkRoot), } - helpers.WriteJson(w, response) + network.WriteJson(w, response) } -func handleGetBlockError(blk interfaces.ReadOnlySignedBeaconBlock, err error) *helpers.DefaultErrorJson { +func handleGetBlockError(blk interfaces.ReadOnlySignedBeaconBlock, err error) *network.DefaultErrorJson { if errors.Is(err, blockfetcher.BlockIdParseError{}) { - return &helpers.DefaultErrorJson{ + return &network.DefaultErrorJson{ Message: errors.Wrapf(err, "invalid block ID").Error(), Code: http.StatusBadRequest, } } if err != nil { - return &helpers.DefaultErrorJson{ + return &network.DefaultErrorJson{ Message: errors.Wrapf(err, "could not get block from block ID").Error(), Code: http.StatusInternalServerError, } } if err := blocks.BeaconBlockIsNil(blk); err != nil { - return &helpers.DefaultErrorJson{ + return &network.DefaultErrorJson{ Message: errors.Wrapf(err, "could not find requested block").Error(), Code: http.StatusNotFound, } diff --git a/beacon-chain/rpc/eth/rewards/handlers_test.go b/beacon-chain/rpc/eth/rewards/handlers_test.go index 7f5c2df1e00c..6b38b72a15ae 100644 --- a/beacon-chain/rpc/eth/rewards/handlers_test.go +++ b/beacon-chain/rpc/eth/rewards/handlers_test.go @@ -12,7 +12,6 @@ import ( mock "github.com/prysmaticlabs/prysm/v4/beacon-chain/blockchain/testing" "github.com/prysmaticlabs/prysm/v4/beacon-chain/core/altair" "github.com/prysmaticlabs/prysm/v4/beacon-chain/core/signing" - "github.com/prysmaticlabs/prysm/v4/beacon-chain/rpc/eth/helpers" "github.com/prysmaticlabs/prysm/v4/beacon-chain/rpc/testutil" mockstategen "github.com/prysmaticlabs/prysm/v4/beacon-chain/state/stategen/mock" fieldparams "github.com/prysmaticlabs/prysm/v4/config/fieldparams" @@ -23,6 +22,7 @@ import ( "github.com/prysmaticlabs/prysm/v4/crypto/bls" "github.com/prysmaticlabs/prysm/v4/crypto/bls/blst" "github.com/prysmaticlabs/prysm/v4/encoding/bytesutil" + "github.com/prysmaticlabs/prysm/v4/network" eth "github.com/prysmaticlabs/prysm/v4/proto/prysm/v1alpha1" "github.com/prysmaticlabs/prysm/v4/testing/assert" "github.com/prysmaticlabs/prysm/v4/testing/require" @@ -192,7 +192,7 @@ func TestBlockRewards(t *testing.T) { s.BlockRewards(writer, request) assert.Equal(t, http.StatusBadRequest, writer.Code) - e := &helpers.DefaultErrorJson{} + e := &network.DefaultErrorJson{} require.NoError(t, json.Unmarshal(writer.Body.Bytes(), e)) assert.Equal(t, http.StatusBadRequest, e.Code) assert.Equal(t, "block rewards are not supported for Phase 0 blocks", e.Message) diff --git a/network/BUILD.bazel b/network/BUILD.bazel index 99f460c42653..2197ea7ab128 100644 --- a/network/BUILD.bazel +++ b/network/BUILD.bazel @@ -6,6 +6,7 @@ go_library( "auth.go", "endpoint.go", "external_ip.go", + "http.go", ], importpath = "github.com/prysmaticlabs/prysm/v4/network", visibility = ["//visibility:public"], @@ -13,6 +14,7 @@ go_library( "//network/authorization:go_default_library", "@com_github_golang_jwt_jwt_v4//:go_default_library", "@com_github_pkg_errors//:go_default_library", + "@com_github_sirupsen_logrus//:go_default_library", ], ) diff --git a/beacon-chain/rpc/eth/helpers/http.go b/network/http.go similarity index 98% rename from beacon-chain/rpc/eth/helpers/http.go rename to network/http.go index cf5adb0e025e..f7b886a16223 100644 --- a/beacon-chain/rpc/eth/helpers/http.go +++ b/network/http.go @@ -1,4 +1,4 @@ -package helpers +package network import ( "bytes" From b1ab58559f5446c6222cfe585b04eaccc178eb0c Mon Sep 17 00:00:00 2001 From: rkapka Date: Wed, 22 Mar 2023 14:07:44 +0100 Subject: [PATCH 27/40] move state fetcher to lookup package --- beacon-chain/rpc/BUILD.bazel | 2 +- beacon-chain/rpc/eth/beacon/BUILD.bazel | 4 ++-- beacon-chain/rpc/eth/beacon/server.go | 4 ++-- beacon-chain/rpc/eth/beacon/state.go | 6 +++--- beacon-chain/rpc/eth/beacon/validator_test.go | 12 ++++++------ beacon-chain/rpc/eth/debug/BUILD.bazel | 2 +- beacon-chain/rpc/eth/debug/server.go | 4 ++-- beacon-chain/rpc/eth/helpers/BUILD.bazel | 2 +- beacon-chain/rpc/eth/helpers/error_handling.go | 6 +++--- beacon-chain/rpc/eth/helpers/sync.go | 8 ++++---- beacon-chain/rpc/eth/validator/BUILD.bazel | 2 +- beacon-chain/rpc/eth/validator/server.go | 4 ++-- .../rpc/{statefetcher => lookup}/BUILD.bazel | 4 ++-- beacon-chain/rpc/{statefetcher => lookup}/fetcher.go | 2 +- .../rpc/{statefetcher => lookup}/fetcher_test.go | 2 +- beacon-chain/rpc/service.go | 8 ++++---- 16 files changed, 36 insertions(+), 36 deletions(-) rename beacon-chain/rpc/{statefetcher => lookup}/BUILD.bazel (95%) rename beacon-chain/rpc/{statefetcher => lookup}/fetcher.go (99%) rename beacon-chain/rpc/{statefetcher => lookup}/fetcher_test.go (99%) diff --git a/beacon-chain/rpc/BUILD.bazel b/beacon-chain/rpc/BUILD.bazel index 0f0d79f4e2f5..7c5d3220e9fc 100644 --- a/beacon-chain/rpc/BUILD.bazel +++ b/beacon-chain/rpc/BUILD.bazel @@ -29,11 +29,11 @@ go_library( "//beacon-chain/rpc/eth/events:go_default_library", "//beacon-chain/rpc/eth/node:go_default_library", "//beacon-chain/rpc/eth/validator:go_default_library", + "//beacon-chain/rpc/lookup:go_default_library", "//beacon-chain/rpc/prysm/v1alpha1/beacon:go_default_library", "//beacon-chain/rpc/prysm/v1alpha1/debug:go_default_library", "//beacon-chain/rpc/prysm/v1alpha1/node:go_default_library", "//beacon-chain/rpc/prysm/v1alpha1/validator:go_default_library", - "//beacon-chain/rpc/statefetcher:go_default_library", "//beacon-chain/slasher:go_default_library", "//beacon-chain/state/stategen:go_default_library", "//beacon-chain/sync:go_default_library", diff --git a/beacon-chain/rpc/eth/beacon/BUILD.bazel b/beacon-chain/rpc/eth/beacon/BUILD.bazel index 966a3aa0fb3e..54fcdcd9195a 100644 --- a/beacon-chain/rpc/eth/beacon/BUILD.bazel +++ b/beacon-chain/rpc/eth/beacon/BUILD.bazel @@ -35,8 +35,8 @@ go_library( "//beacon-chain/p2p:go_default_library", "//beacon-chain/rpc/blockfetcher:go_default_library", "//beacon-chain/rpc/eth/helpers:go_default_library", + "//beacon-chain/rpc/lookup:go_default_library", "//beacon-chain/rpc/prysm/v1alpha1/validator:go_default_library", - "//beacon-chain/rpc/statefetcher:go_default_library", "//beacon-chain/state:go_default_library", "//beacon-chain/state/state-native:go_default_library", "//beacon-chain/state/stategen:go_default_library", @@ -101,8 +101,8 @@ go_test( "//beacon-chain/operations/voluntaryexits/mock:go_default_library", "//beacon-chain/p2p/testing:go_default_library", "//beacon-chain/rpc/eth/helpers:go_default_library", + "//beacon-chain/rpc/lookup:go_default_library", "//beacon-chain/rpc/prysm/v1alpha1/validator:go_default_library", - "//beacon-chain/rpc/statefetcher:go_default_library", "//beacon-chain/rpc/testutil:go_default_library", "//beacon-chain/state:go_default_library", "//beacon-chain/state/state-native:go_default_library", diff --git a/beacon-chain/rpc/eth/beacon/server.go b/beacon-chain/rpc/eth/beacon/server.go index 8518c0b111d8..9c68966be7e4 100644 --- a/beacon-chain/rpc/eth/beacon/server.go +++ b/beacon-chain/rpc/eth/beacon/server.go @@ -15,8 +15,8 @@ import ( "github.com/prysmaticlabs/prysm/v4/beacon-chain/operations/voluntaryexits" "github.com/prysmaticlabs/prysm/v4/beacon-chain/p2p" "github.com/prysmaticlabs/prysm/v4/beacon-chain/rpc/blockfetcher" + "github.com/prysmaticlabs/prysm/v4/beacon-chain/rpc/lookup" v1alpha1validator "github.com/prysmaticlabs/prysm/v4/beacon-chain/rpc/prysm/v1alpha1/validator" - "github.com/prysmaticlabs/prysm/v4/beacon-chain/rpc/statefetcher" "github.com/prysmaticlabs/prysm/v4/beacon-chain/state/stategen" "github.com/prysmaticlabs/prysm/v4/beacon-chain/sync" ) @@ -35,7 +35,7 @@ type Server struct { SlashingsPool slashings.PoolManager VoluntaryExitsPool voluntaryexits.PoolManager StateGenService stategen.StateManager - StateFetcher statefetcher.Fetcher + StateFetcher lookup.Fetcher BlockFetcher blockfetcher.Fetcher HeadFetcher blockchain.HeadFetcher OptimisticModeFetcher blockchain.OptimisticModeFetcher diff --git a/beacon-chain/rpc/eth/beacon/state.go b/beacon-chain/rpc/eth/beacon/state.go index dc19ca58a458..9bfd6aa2e813 100644 --- a/beacon-chain/rpc/eth/beacon/state.go +++ b/beacon-chain/rpc/eth/beacon/state.go @@ -6,7 +6,7 @@ import ( "strconv" "github.com/prysmaticlabs/prysm/v4/beacon-chain/rpc/eth/helpers" - "github.com/prysmaticlabs/prysm/v4/beacon-chain/rpc/statefetcher" + "github.com/prysmaticlabs/prysm/v4/beacon-chain/rpc/lookup" "github.com/prysmaticlabs/prysm/v4/beacon-chain/state" "github.com/prysmaticlabs/prysm/v4/config/params" "github.com/prysmaticlabs/prysm/v4/consensus-types/primitives" @@ -60,9 +60,9 @@ func (bs *Server) GetStateRoot(ctx context.Context, req *ethpb.StateRequest) (*e stateRoot, err := bs.StateFetcher.StateRoot(ctx, req.StateId) if err != nil { - if rootNotFoundErr, ok := err.(*statefetcher.StateRootNotFoundError); ok { + if rootNotFoundErr, ok := err.(*lookup.StateRootNotFoundError); ok { return nil, status.Errorf(codes.NotFound, "State root not found: %v", rootNotFoundErr) - } else if parseErr, ok := err.(*statefetcher.StateIdParseError); ok { + } else if parseErr, ok := err.(*lookup.StateIdParseError); ok { return nil, status.Errorf(codes.InvalidArgument, "Invalid state ID: %v", parseErr) } return nil, status.Errorf(codes.Internal, "Could not get state root: %v", err) diff --git a/beacon-chain/rpc/eth/beacon/validator_test.go b/beacon-chain/rpc/eth/beacon/validator_test.go index 7081ab0eddc3..79e69e514fb6 100644 --- a/beacon-chain/rpc/eth/beacon/validator_test.go +++ b/beacon-chain/rpc/eth/beacon/validator_test.go @@ -9,7 +9,7 @@ import ( chainMock "github.com/prysmaticlabs/prysm/v4/beacon-chain/blockchain/testing" dbTest "github.com/prysmaticlabs/prysm/v4/beacon-chain/db/testing" rpchelpers "github.com/prysmaticlabs/prysm/v4/beacon-chain/rpc/eth/helpers" - "github.com/prysmaticlabs/prysm/v4/beacon-chain/rpc/statefetcher" + "github.com/prysmaticlabs/prysm/v4/beacon-chain/rpc/lookup" "github.com/prysmaticlabs/prysm/v4/beacon-chain/rpc/testutil" "github.com/prysmaticlabs/prysm/v4/beacon-chain/state" state_native "github.com/prysmaticlabs/prysm/v4/beacon-chain/state/state-native" @@ -440,7 +440,7 @@ func TestListValidators_Status(t *testing.T) { t.Run("Head List All ACTIVE Validators", func(t *testing.T) { chainService := &chainMock.ChainService{} s := Server{ - StateFetcher: &statefetcher.StateProvider{ + StateFetcher: &lookup.StateProvider{ ChainInfoFetcher: &chainMock.ChainService{State: st}, }, HeadFetcher: chainService, @@ -478,7 +478,7 @@ func TestListValidators_Status(t *testing.T) { t.Run("Head List All ACTIVE_ONGOING Validators", func(t *testing.T) { chainService := &chainMock.ChainService{} s := Server{ - StateFetcher: &statefetcher.StateProvider{ + StateFetcher: &lookup.StateProvider{ ChainInfoFetcher: &chainMock.ChainService{State: st}, }, HeadFetcher: chainService, @@ -515,7 +515,7 @@ func TestListValidators_Status(t *testing.T) { t.Run("Head List All EXITED Validators", func(t *testing.T) { chainService := &chainMock.ChainService{} s := Server{ - StateFetcher: &statefetcher.StateProvider{ + StateFetcher: &lookup.StateProvider{ ChainInfoFetcher: &chainMock.ChainService{State: st}, }, HeadFetcher: chainService, @@ -551,7 +551,7 @@ func TestListValidators_Status(t *testing.T) { t.Run("Head List All PENDING_INITIALIZED and EXITED_UNSLASHED Validators", func(t *testing.T) { chainService := &chainMock.ChainService{} s := Server{ - StateFetcher: &statefetcher.StateProvider{ + StateFetcher: &lookup.StateProvider{ ChainInfoFetcher: &chainMock.ChainService{State: st}, }, HeadFetcher: chainService, @@ -587,7 +587,7 @@ func TestListValidators_Status(t *testing.T) { t.Run("Head List All PENDING and EXITED Validators", func(t *testing.T) { chainService := &chainMock.ChainService{} s := Server{ - StateFetcher: &statefetcher.StateProvider{ + StateFetcher: &lookup.StateProvider{ ChainInfoFetcher: &chainMock.ChainService{State: st}, }, HeadFetcher: chainService, diff --git a/beacon-chain/rpc/eth/debug/BUILD.bazel b/beacon-chain/rpc/eth/debug/BUILD.bazel index 7de47ffe5204..6400f3e9c86e 100644 --- a/beacon-chain/rpc/eth/debug/BUILD.bazel +++ b/beacon-chain/rpc/eth/debug/BUILD.bazel @@ -12,7 +12,7 @@ go_library( "//beacon-chain/blockchain:go_default_library", "//beacon-chain/db:go_default_library", "//beacon-chain/rpc/eth/helpers:go_default_library", - "//beacon-chain/rpc/statefetcher:go_default_library", + "//beacon-chain/rpc/lookup:go_default_library", "//proto/eth/v1:go_default_library", "//proto/eth/v2:go_default_library", "//proto/migration:go_default_library", diff --git a/beacon-chain/rpc/eth/debug/server.go b/beacon-chain/rpc/eth/debug/server.go index 8581209989a9..aad278f97525 100644 --- a/beacon-chain/rpc/eth/debug/server.go +++ b/beacon-chain/rpc/eth/debug/server.go @@ -6,7 +6,7 @@ package debug import ( "github.com/prysmaticlabs/prysm/v4/beacon-chain/blockchain" "github.com/prysmaticlabs/prysm/v4/beacon-chain/db" - "github.com/prysmaticlabs/prysm/v4/beacon-chain/rpc/statefetcher" + "github.com/prysmaticlabs/prysm/v4/beacon-chain/rpc/lookup" ) // Server defines a server implementation of the gRPC Beacon Chain service, @@ -14,7 +14,7 @@ import ( type Server struct { BeaconDB db.ReadOnlyDatabase HeadFetcher blockchain.HeadFetcher - StateFetcher statefetcher.Fetcher + StateFetcher lookup.Fetcher OptimisticModeFetcher blockchain.OptimisticModeFetcher ForkFetcher blockchain.ForkFetcher FinalizationFetcher blockchain.FinalizationFetcher diff --git a/beacon-chain/rpc/eth/helpers/BUILD.bazel b/beacon-chain/rpc/eth/helpers/BUILD.bazel index 2b40430813ac..b72a4950bcc9 100644 --- a/beacon-chain/rpc/eth/helpers/BUILD.bazel +++ b/beacon-chain/rpc/eth/helpers/BUILD.bazel @@ -13,7 +13,7 @@ go_library( "//api/grpc:go_default_library", "//beacon-chain/blockchain:go_default_library", "//beacon-chain/db:go_default_library", - "//beacon-chain/rpc/statefetcher:go_default_library", + "//beacon-chain/rpc/lookup:go_default_library", "//beacon-chain/state:go_default_library", "//beacon-chain/state/stategen:go_default_library", "//beacon-chain/sync:go_default_library", diff --git a/beacon-chain/rpc/eth/helpers/error_handling.go b/beacon-chain/rpc/eth/helpers/error_handling.go index 73ccd8e93ee9..8e2967a36bb8 100644 --- a/beacon-chain/rpc/eth/helpers/error_handling.go +++ b/beacon-chain/rpc/eth/helpers/error_handling.go @@ -3,7 +3,7 @@ package helpers import ( "errors" - "github.com/prysmaticlabs/prysm/v4/beacon-chain/rpc/statefetcher" + "github.com/prysmaticlabs/prysm/v4/beacon-chain/rpc/lookup" "github.com/prysmaticlabs/prysm/v4/beacon-chain/state/stategen" "google.golang.org/grpc/codes" "google.golang.org/grpc/status" @@ -15,10 +15,10 @@ func PrepareStateFetchGRPCError(err error) error { if errors.Is(err, stategen.ErrNoDataForSlot) { return status.Errorf(codes.NotFound, "lacking historical data needed to fulfill request") } - if stateNotFoundErr, ok := err.(*statefetcher.StateNotFoundError); ok { + if stateNotFoundErr, ok := err.(*lookup.StateNotFoundError); ok { return status.Errorf(codes.NotFound, "State not found: %v", stateNotFoundErr) } - if parseErr, ok := err.(*statefetcher.StateIdParseError); ok { + if parseErr, ok := err.(*lookup.StateIdParseError); ok { return status.Errorf(codes.InvalidArgument, "Invalid state ID: %v", parseErr) } return status.Errorf(codes.Internal, "Invalid state ID: %v", err) diff --git a/beacon-chain/rpc/eth/helpers/sync.go b/beacon-chain/rpc/eth/helpers/sync.go index 4a07a238889d..f9b04ab79975 100644 --- a/beacon-chain/rpc/eth/helpers/sync.go +++ b/beacon-chain/rpc/eth/helpers/sync.go @@ -9,7 +9,7 @@ import ( "github.com/prysmaticlabs/prysm/v4/api/grpc" "github.com/prysmaticlabs/prysm/v4/beacon-chain/blockchain" "github.com/prysmaticlabs/prysm/v4/beacon-chain/db" - "github.com/prysmaticlabs/prysm/v4/beacon-chain/rpc/statefetcher" + "github.com/prysmaticlabs/prysm/v4/beacon-chain/rpc/lookup" "github.com/prysmaticlabs/prysm/v4/beacon-chain/sync" "github.com/prysmaticlabs/prysm/v4/consensus-types/primitives" "github.com/prysmaticlabs/prysm/v4/encoding/bytesutil" @@ -61,7 +61,7 @@ func IsOptimistic( ctx context.Context, stateId []byte, optimisticModeFetcher blockchain.OptimisticModeFetcher, - stateFetcher statefetcher.Fetcher, + stateFetcher lookup.Fetcher, chainInfo blockchain.ChainInfoFetcher, database db.ReadOnlyDatabase, ) (bool, error) { @@ -97,7 +97,7 @@ func IsOptimistic( slotNumber, parseErr := strconv.ParseUint(stateIdString, 10, 64) if parseErr != nil { // ID format does not match any valid options. - e := statefetcher.NewStateIdParseError(parseErr) + e := lookup.NewStateIdParseError(parseErr) return true, &e } fcp := chainInfo.FinalizedCheckpt() @@ -146,7 +146,7 @@ func isStateRootOptimistic( ctx context.Context, stateId []byte, optimisticModeFetcher blockchain.OptimisticModeFetcher, - stateFetcher statefetcher.Fetcher, + stateFetcher lookup.Fetcher, chainInfo blockchain.ChainInfoFetcher, database db.ReadOnlyDatabase, ) (bool, error) { diff --git a/beacon-chain/rpc/eth/validator/BUILD.bazel b/beacon-chain/rpc/eth/validator/BUILD.bazel index 185c7b05ee3a..d82a26cf06a6 100644 --- a/beacon-chain/rpc/eth/validator/BUILD.bazel +++ b/beacon-chain/rpc/eth/validator/BUILD.bazel @@ -19,8 +19,8 @@ go_library( "//beacon-chain/operations/synccommittee:go_default_library", "//beacon-chain/p2p:go_default_library", "//beacon-chain/rpc/eth/helpers:go_default_library", + "//beacon-chain/rpc/lookup:go_default_library", "//beacon-chain/rpc/prysm/v1alpha1/validator:go_default_library", - "//beacon-chain/rpc/statefetcher:go_default_library", "//beacon-chain/state:go_default_library", "//beacon-chain/state/state-native:go_default_library", "//beacon-chain/sync:go_default_library", diff --git a/beacon-chain/rpc/eth/validator/server.go b/beacon-chain/rpc/eth/validator/server.go index a5aa7f99fc7e..5f56ffc3234a 100644 --- a/beacon-chain/rpc/eth/validator/server.go +++ b/beacon-chain/rpc/eth/validator/server.go @@ -7,8 +7,8 @@ import ( "github.com/prysmaticlabs/prysm/v4/beacon-chain/operations/attestations" "github.com/prysmaticlabs/prysm/v4/beacon-chain/operations/synccommittee" "github.com/prysmaticlabs/prysm/v4/beacon-chain/p2p" + "github.com/prysmaticlabs/prysm/v4/beacon-chain/rpc/lookup" v1alpha1validator "github.com/prysmaticlabs/prysm/v4/beacon-chain/rpc/prysm/v1alpha1/validator" - "github.com/prysmaticlabs/prysm/v4/beacon-chain/rpc/statefetcher" "github.com/prysmaticlabs/prysm/v4/beacon-chain/sync" ) @@ -22,7 +22,7 @@ type Server struct { AttestationsPool attestations.Pool PeerManager p2p.PeerManager Broadcaster p2p.Broadcaster - StateFetcher statefetcher.Fetcher + StateFetcher lookup.Fetcher OptimisticModeFetcher blockchain.OptimisticModeFetcher SyncCommitteePool synccommittee.Pool V1Alpha1Server *v1alpha1validator.Server diff --git a/beacon-chain/rpc/statefetcher/BUILD.bazel b/beacon-chain/rpc/lookup/BUILD.bazel similarity index 95% rename from beacon-chain/rpc/statefetcher/BUILD.bazel rename to beacon-chain/rpc/lookup/BUILD.bazel index 84490038468e..97bfd7cd8fe8 100644 --- a/beacon-chain/rpc/statefetcher/BUILD.bazel +++ b/beacon-chain/rpc/lookup/BUILD.bazel @@ -3,8 +3,8 @@ load("@prysm//tools/go:def.bzl", "go_library", "go_test") go_library( name = "go_default_library", srcs = ["fetcher.go"], - importpath = "github.com/prysmaticlabs/prysm/v4/beacon-chain/rpc/statefetcher", - visibility = ["//beacon-chain:__subpackages__"], + importpath = "github.com/prysmaticlabs/prysm/v4/beacon-chain/rpc/lookup", + visibility = ["//visibility:public"], deps = [ "//beacon-chain/blockchain:go_default_library", "//beacon-chain/db:go_default_library", diff --git a/beacon-chain/rpc/statefetcher/fetcher.go b/beacon-chain/rpc/lookup/fetcher.go similarity index 99% rename from beacon-chain/rpc/statefetcher/fetcher.go rename to beacon-chain/rpc/lookup/fetcher.go index 0a4019dee3bf..5180ba7bc04a 100644 --- a/beacon-chain/rpc/statefetcher/fetcher.go +++ b/beacon-chain/rpc/lookup/fetcher.go @@ -1,4 +1,4 @@ -package statefetcher +package lookup import ( "bytes" diff --git a/beacon-chain/rpc/statefetcher/fetcher_test.go b/beacon-chain/rpc/lookup/fetcher_test.go similarity index 99% rename from beacon-chain/rpc/statefetcher/fetcher_test.go rename to beacon-chain/rpc/lookup/fetcher_test.go index 93eeca3ddc06..dff639c3cc7a 100644 --- a/beacon-chain/rpc/statefetcher/fetcher_test.go +++ b/beacon-chain/rpc/lookup/fetcher_test.go @@ -1,4 +1,4 @@ -package statefetcher +package lookup import ( "context" diff --git a/beacon-chain/rpc/service.go b/beacon-chain/rpc/service.go index 90f40bf2e5a8..3b7ffba8a999 100644 --- a/beacon-chain/rpc/service.go +++ b/beacon-chain/rpc/service.go @@ -33,11 +33,11 @@ import ( "github.com/prysmaticlabs/prysm/v4/beacon-chain/rpc/eth/events" "github.com/prysmaticlabs/prysm/v4/beacon-chain/rpc/eth/node" "github.com/prysmaticlabs/prysm/v4/beacon-chain/rpc/eth/validator" + "github.com/prysmaticlabs/prysm/v4/beacon-chain/rpc/lookup" beaconv1alpha1 "github.com/prysmaticlabs/prysm/v4/beacon-chain/rpc/prysm/v1alpha1/beacon" debugv1alpha1 "github.com/prysmaticlabs/prysm/v4/beacon-chain/rpc/prysm/v1alpha1/debug" nodev1alpha1 "github.com/prysmaticlabs/prysm/v4/beacon-chain/rpc/prysm/v1alpha1/node" validatorv1alpha1 "github.com/prysmaticlabs/prysm/v4/beacon-chain/rpc/prysm/v1alpha1/validator" - "github.com/prysmaticlabs/prysm/v4/beacon-chain/rpc/statefetcher" slasherservice "github.com/prysmaticlabs/prysm/v4/beacon-chain/slasher" "github.com/prysmaticlabs/prysm/v4/beacon-chain/state/stategen" chainSync "github.com/prysmaticlabs/prysm/v4/beacon-chain/sync" @@ -235,7 +235,7 @@ func (s *Service) Start() { PeerManager: s.cfg.PeerManager, Broadcaster: s.cfg.Broadcaster, V1Alpha1Server: validatorServer, - StateFetcher: &statefetcher.StateProvider{ + StateFetcher: &lookup.StateProvider{ BeaconDB: s.cfg.BeaconDB, ChainInfoFetcher: s.cfg.ChainInfoFetcher, GenesisTimeFetcher: s.cfg.GenesisTimeFetcher, @@ -311,7 +311,7 @@ func (s *Service) Start() { Broadcaster: s.cfg.Broadcaster, BlockReceiver: s.cfg.BlockReceiver, StateGenService: s.cfg.StateGen, - StateFetcher: &statefetcher.StateProvider{ + StateFetcher: &lookup.StateProvider{ BeaconDB: s.cfg.BeaconDB, ChainInfoFetcher: s.cfg.ChainInfoFetcher, GenesisTimeFetcher: s.cfg.GenesisTimeFetcher, @@ -354,7 +354,7 @@ func (s *Service) Start() { debugServerV1 := &debug.Server{ BeaconDB: s.cfg.BeaconDB, HeadFetcher: s.cfg.HeadFetcher, - StateFetcher: &statefetcher.StateProvider{ + StateFetcher: &lookup.StateProvider{ BeaconDB: s.cfg.BeaconDB, ChainInfoFetcher: s.cfg.ChainInfoFetcher, GenesisTimeFetcher: s.cfg.GenesisTimeFetcher, From 28c16ef31abfdd54ad3d8c5dad32b6dcd874e848 Mon Sep 17 00:00:00 2001 From: rkapka Date: Wed, 22 Mar 2023 14:12:39 +0100 Subject: [PATCH 28/40] rename types --- beacon-chain/rpc/eth/beacon/server.go | 2 +- beacon-chain/rpc/eth/beacon/state_test.go | 26 ++++---- .../rpc/eth/beacon/sync_committee_test.go | 6 +- beacon-chain/rpc/eth/beacon/validator_test.go | 60 +++++++++---------- beacon-chain/rpc/eth/debug/debug_test.go | 22 +++---- beacon-chain/rpc/eth/debug/server.go | 2 +- beacon-chain/rpc/eth/helpers/sync.go | 4 +- beacon-chain/rpc/eth/helpers/sync_test.go | 24 ++++---- beacon-chain/rpc/eth/validator/server.go | 2 +- .../rpc/eth/validator/validator_test.go | 22 +++---- beacon-chain/rpc/lookup/fetcher.go | 32 +++++----- beacon-chain/rpc/lookup/fetcher_test.go | 38 ++++++------ beacon-chain/rpc/service.go | 6 +- .../rpc/testutil/mock_state_fetcher.go | 11 ++-- 14 files changed, 129 insertions(+), 128 deletions(-) diff --git a/beacon-chain/rpc/eth/beacon/server.go b/beacon-chain/rpc/eth/beacon/server.go index 9c68966be7e4..8e07075915cd 100644 --- a/beacon-chain/rpc/eth/beacon/server.go +++ b/beacon-chain/rpc/eth/beacon/server.go @@ -35,7 +35,7 @@ type Server struct { SlashingsPool slashings.PoolManager VoluntaryExitsPool voluntaryexits.PoolManager StateGenService stategen.StateManager - StateFetcher lookup.Fetcher + StateFetcher lookup.Stater BlockFetcher blockfetcher.Fetcher HeadFetcher blockchain.HeadFetcher OptimisticModeFetcher blockchain.OptimisticModeFetcher diff --git a/beacon-chain/rpc/eth/beacon/state_test.go b/beacon-chain/rpc/eth/beacon/state_test.go index 162c7e8017ab..839a26cdbf16 100644 --- a/beacon-chain/rpc/eth/beacon/state_test.go +++ b/beacon-chain/rpc/eth/beacon/state_test.go @@ -83,7 +83,7 @@ func TestGetStateRoot(t *testing.T) { chainService := &chainMock.ChainService{} server := &Server{ - StateFetcher: &testutil.MockFetcher{ + StateFetcher: &testutil.MockStater{ BeaconStateRoot: stateRoot[:], BeaconState: fakeState, }, @@ -111,7 +111,7 @@ func TestGetStateRoot(t *testing.T) { chainService := &chainMock.ChainService{Optimistic: true} server := &Server{ - StateFetcher: &testutil.MockFetcher{ + StateFetcher: &testutil.MockStater{ BeaconStateRoot: stateRoot[:], BeaconState: fakeState, }, @@ -145,7 +145,7 @@ func TestGetStateRoot(t *testing.T) { }, } server := &Server{ - StateFetcher: &testutil.MockFetcher{ + StateFetcher: &testutil.MockStater{ BeaconStateRoot: stateRoot[:], BeaconState: fakeState, }, @@ -179,7 +179,7 @@ func TestGetStateFork(t *testing.T) { chainService := &chainMock.ChainService{} server := &Server{ - StateFetcher: &testutil.MockFetcher{ + StateFetcher: &testutil.MockStater{ BeaconState: fakeState, }, HeadFetcher: chainService, @@ -209,7 +209,7 @@ func TestGetStateFork(t *testing.T) { chainService := &chainMock.ChainService{Optimistic: true} server := &Server{ - StateFetcher: &testutil.MockFetcher{ + StateFetcher: &testutil.MockStater{ BeaconState: fakeState, }, HeadFetcher: chainService, @@ -242,7 +242,7 @@ func TestGetStateFork(t *testing.T) { }, } server := &Server{ - StateFetcher: &testutil.MockFetcher{ + StateFetcher: &testutil.MockStater{ BeaconState: fakeState, }, HeadFetcher: chainService, @@ -282,7 +282,7 @@ func TestGetFinalityCheckpoints(t *testing.T) { chainService := &chainMock.ChainService{} server := &Server{ - StateFetcher: &testutil.MockFetcher{ + StateFetcher: &testutil.MockStater{ BeaconState: fakeState, }, HeadFetcher: chainService, @@ -314,7 +314,7 @@ func TestGetFinalityCheckpoints(t *testing.T) { chainService := &chainMock.ChainService{Optimistic: true} server := &Server{ - StateFetcher: &testutil.MockFetcher{ + StateFetcher: &testutil.MockStater{ BeaconState: fakeState, }, HeadFetcher: chainService, @@ -347,7 +347,7 @@ func TestGetFinalityCheckpoints(t *testing.T) { }, } server := &Server{ - StateFetcher: &testutil.MockFetcher{ + StateFetcher: &testutil.MockStater{ BeaconState: fakeState, }, HeadFetcher: chainService, @@ -388,7 +388,7 @@ func TestGetRandao(t *testing.T) { db := dbTest.SetupDB(t) chainService := &chainMock.ChainService{} server := &Server{ - StateFetcher: &testutil.MockFetcher{ + StateFetcher: &testutil.MockStater{ BeaconState: st, }, HeadFetcher: chainService, @@ -413,7 +413,7 @@ func TestGetRandao(t *testing.T) { assert.DeepEqual(t, mixOld, resp.Data.Randao) }) t.Run("head state below `EpochsPerHistoricalVector`", func(t *testing.T) { - server.StateFetcher = &testutil.MockFetcher{ + server.StateFetcher = &testutil.MockStater{ BeaconState: headSt, } resp, err := server.GetRandao(ctx, ð2.RandaoRequest{StateId: []byte("head")}) @@ -441,7 +441,7 @@ func TestGetRandao(t *testing.T) { chainService := &chainMock.ChainService{Optimistic: true} server := &Server{ - StateFetcher: &testutil.MockFetcher{ + StateFetcher: &testutil.MockStater{ BeaconState: st, }, HeadFetcher: chainService, @@ -473,7 +473,7 @@ func TestGetRandao(t *testing.T) { }, } server := &Server{ - StateFetcher: &testutil.MockFetcher{ + StateFetcher: &testutil.MockStater{ BeaconState: st, }, HeadFetcher: chainService, diff --git a/beacon-chain/rpc/eth/beacon/sync_committee_test.go b/beacon-chain/rpc/eth/beacon/sync_committee_test.go index 1416b7415542..dbee74f4072f 100644 --- a/beacon-chain/rpc/eth/beacon/sync_committee_test.go +++ b/beacon-chain/rpc/eth/beacon/sync_committee_test.go @@ -167,7 +167,7 @@ func TestListSyncCommittees(t *testing.T) { GenesisTimeFetcher: &testutil.MockGenesisTimeFetcher{ Genesis: time.Now(), }, - StateFetcher: &testutil.MockFetcher{ + StateFetcher: &testutil.MockStater{ BeaconState: st, }, HeadFetcher: chainService, @@ -213,7 +213,7 @@ func TestListSyncCommittees(t *testing.T) { GenesisTimeFetcher: &testutil.MockGenesisTimeFetcher{ Genesis: time.Now(), }, - StateFetcher: &testutil.MockFetcher{ + StateFetcher: &testutil.MockStater{ BeaconState: st, }, HeadFetcher: chainService, @@ -249,7 +249,7 @@ func TestListSyncCommittees(t *testing.T) { GenesisTimeFetcher: &testutil.MockGenesisTimeFetcher{ Genesis: time.Now(), }, - StateFetcher: &testutil.MockFetcher{ + StateFetcher: &testutil.MockStater{ BeaconState: st, }, HeadFetcher: chainService, diff --git a/beacon-chain/rpc/eth/beacon/validator_test.go b/beacon-chain/rpc/eth/beacon/validator_test.go index 79e69e514fb6..e3a1bd8c70c2 100644 --- a/beacon-chain/rpc/eth/beacon/validator_test.go +++ b/beacon-chain/rpc/eth/beacon/validator_test.go @@ -34,7 +34,7 @@ func TestGetValidator(t *testing.T) { t.Run("Head Get Validator by index", func(t *testing.T) { chainService := &chainMock.ChainService{} s := Server{ - StateFetcher: &testutil.MockFetcher{ + StateFetcher: &testutil.MockStater{ BeaconState: st, }, HeadFetcher: chainService, @@ -54,7 +54,7 @@ func TestGetValidator(t *testing.T) { t.Run("Head Get Validator by pubkey", func(t *testing.T) { chainService := &chainMock.ChainService{} s := Server{ - StateFetcher: &testutil.MockFetcher{ + StateFetcher: &testutil.MockStater{ BeaconState: st, }, HeadFetcher: chainService, @@ -75,7 +75,7 @@ func TestGetValidator(t *testing.T) { t.Run("Validator ID required", func(t *testing.T) { s := Server{ - StateFetcher: &testutil.MockFetcher{ + StateFetcher: &testutil.MockStater{ BeaconState: st, }, HeadFetcher: &chainMock.ChainService{}, @@ -98,7 +98,7 @@ func TestGetValidator(t *testing.T) { chainService := &chainMock.ChainService{Optimistic: true} s := Server{ - StateFetcher: &testutil.MockFetcher{ + StateFetcher: &testutil.MockStater{ BeaconState: st, }, HeadFetcher: chainService, @@ -131,7 +131,7 @@ func TestGetValidator(t *testing.T) { }, } s := Server{ - StateFetcher: &testutil.MockFetcher{ + StateFetcher: &testutil.MockStater{ BeaconState: st, }, HeadFetcher: chainService, @@ -157,7 +157,7 @@ func TestListValidators(t *testing.T) { t.Run("Head List All Validators", func(t *testing.T) { chainService := &chainMock.ChainService{} s := Server{ - StateFetcher: &testutil.MockFetcher{ + StateFetcher: &testutil.MockStater{ BeaconState: st, }, HeadFetcher: chainService, @@ -179,7 +179,7 @@ func TestListValidators(t *testing.T) { t.Run("Head List Validators by index", func(t *testing.T) { chainService := &chainMock.ChainService{} s := Server{ - StateFetcher: &testutil.MockFetcher{ + StateFetcher: &testutil.MockStater{ BeaconState: st, }, HeadFetcher: chainService, @@ -204,7 +204,7 @@ func TestListValidators(t *testing.T) { t.Run("Head List Validators by pubkey", func(t *testing.T) { chainService := &chainMock.ChainService{} s := Server{ - StateFetcher: &testutil.MockFetcher{ + StateFetcher: &testutil.MockStater{ BeaconState: st, }, HeadFetcher: chainService, @@ -233,7 +233,7 @@ func TestListValidators(t *testing.T) { t.Run("Head List Validators by both index and pubkey", func(t *testing.T) { chainService := &chainMock.ChainService{} s := Server{ - StateFetcher: &testutil.MockFetcher{ + StateFetcher: &testutil.MockStater{ BeaconState: st, }, HeadFetcher: chainService, @@ -264,7 +264,7 @@ func TestListValidators(t *testing.T) { t.Run("Unknown public key is ignored", func(t *testing.T) { chainService := &chainMock.ChainService{} s := Server{ - StateFetcher: &testutil.MockFetcher{ + StateFetcher: &testutil.MockStater{ BeaconState: st, }, HeadFetcher: chainService, @@ -287,7 +287,7 @@ func TestListValidators(t *testing.T) { t.Run("Unknown index is ignored", func(t *testing.T) { chainService := &chainMock.ChainService{} s := Server{ - StateFetcher: &testutil.MockFetcher{ + StateFetcher: &testutil.MockStater{ BeaconState: st, }, HeadFetcher: chainService, @@ -317,7 +317,7 @@ func TestListValidators(t *testing.T) { chainService := &chainMock.ChainService{Optimistic: true} s := Server{ - StateFetcher: &testutil.MockFetcher{ + StateFetcher: &testutil.MockStater{ BeaconState: st, }, HeadFetcher: chainService, @@ -349,7 +349,7 @@ func TestListValidators(t *testing.T) { }, } s := Server{ - StateFetcher: &testutil.MockFetcher{ + StateFetcher: &testutil.MockStater{ BeaconState: st, }, HeadFetcher: chainService, @@ -440,7 +440,7 @@ func TestListValidators_Status(t *testing.T) { t.Run("Head List All ACTIVE Validators", func(t *testing.T) { chainService := &chainMock.ChainService{} s := Server{ - StateFetcher: &lookup.StateProvider{ + StateFetcher: &lookup.BeaconDbStater{ ChainInfoFetcher: &chainMock.ChainService{State: st}, }, HeadFetcher: chainService, @@ -478,7 +478,7 @@ func TestListValidators_Status(t *testing.T) { t.Run("Head List All ACTIVE_ONGOING Validators", func(t *testing.T) { chainService := &chainMock.ChainService{} s := Server{ - StateFetcher: &lookup.StateProvider{ + StateFetcher: &lookup.BeaconDbStater{ ChainInfoFetcher: &chainMock.ChainService{State: st}, }, HeadFetcher: chainService, @@ -515,7 +515,7 @@ func TestListValidators_Status(t *testing.T) { t.Run("Head List All EXITED Validators", func(t *testing.T) { chainService := &chainMock.ChainService{} s := Server{ - StateFetcher: &lookup.StateProvider{ + StateFetcher: &lookup.BeaconDbStater{ ChainInfoFetcher: &chainMock.ChainService{State: st}, }, HeadFetcher: chainService, @@ -551,7 +551,7 @@ func TestListValidators_Status(t *testing.T) { t.Run("Head List All PENDING_INITIALIZED and EXITED_UNSLASHED Validators", func(t *testing.T) { chainService := &chainMock.ChainService{} s := Server{ - StateFetcher: &lookup.StateProvider{ + StateFetcher: &lookup.BeaconDbStater{ ChainInfoFetcher: &chainMock.ChainService{State: st}, }, HeadFetcher: chainService, @@ -587,7 +587,7 @@ func TestListValidators_Status(t *testing.T) { t.Run("Head List All PENDING and EXITED Validators", func(t *testing.T) { chainService := &chainMock.ChainService{} s := Server{ - StateFetcher: &lookup.StateProvider{ + StateFetcher: &lookup.BeaconDbStater{ ChainInfoFetcher: &chainMock.ChainService{State: st}, }, HeadFetcher: chainService, @@ -638,7 +638,7 @@ func TestListValidatorBalances(t *testing.T) { t.Run("Head List Validators Balance by index", func(t *testing.T) { chainService := &chainMock.ChainService{} s := Server{ - StateFetcher: &testutil.MockFetcher{ + StateFetcher: &testutil.MockStater{ BeaconState: st, }, HeadFetcher: chainService, @@ -663,7 +663,7 @@ func TestListValidatorBalances(t *testing.T) { t.Run("Head List Validators Balance by pubkey", func(t *testing.T) { chainService := &chainMock.ChainService{} s := Server{ - StateFetcher: &testutil.MockFetcher{ + StateFetcher: &testutil.MockStater{ BeaconState: st, }, HeadFetcher: chainService, @@ -691,7 +691,7 @@ func TestListValidatorBalances(t *testing.T) { t.Run("Head List Validators Balance by both index and pubkey", func(t *testing.T) { chainService := &chainMock.ChainService{} s := Server{ - StateFetcher: &testutil.MockFetcher{ + StateFetcher: &testutil.MockStater{ BeaconState: st, }, HeadFetcher: chainService, @@ -726,7 +726,7 @@ func TestListValidatorBalances(t *testing.T) { chainService := &chainMock.ChainService{Optimistic: true} s := Server{ - StateFetcher: &testutil.MockFetcher{ + StateFetcher: &testutil.MockStater{ BeaconState: st, }, HeadFetcher: chainService, @@ -761,7 +761,7 @@ func TestListValidatorBalances(t *testing.T) { }, } s := Server{ - StateFetcher: &testutil.MockFetcher{ + StateFetcher: &testutil.MockStater{ BeaconState: st, }, HeadFetcher: chainService, @@ -791,7 +791,7 @@ func TestListCommittees(t *testing.T) { t.Run("Head All Committees", func(t *testing.T) { chainService := &chainMock.ChainService{} s := Server{ - StateFetcher: &testutil.MockFetcher{ + StateFetcher: &testutil.MockStater{ BeaconState: st, }, HeadFetcher: chainService, @@ -814,7 +814,7 @@ func TestListCommittees(t *testing.T) { t.Run("Head All Committees of Epoch 10", func(t *testing.T) { chainService := &chainMock.ChainService{} s := Server{ - StateFetcher: &testutil.MockFetcher{ + StateFetcher: &testutil.MockStater{ BeaconState: st, }, HeadFetcher: chainService, @@ -836,7 +836,7 @@ func TestListCommittees(t *testing.T) { t.Run("Head All Committees of Slot 4", func(t *testing.T) { chainService := &chainMock.ChainService{} s := Server{ - StateFetcher: &testutil.MockFetcher{ + StateFetcher: &testutil.MockStater{ BeaconState: st, }, HeadFetcher: chainService, @@ -864,7 +864,7 @@ func TestListCommittees(t *testing.T) { t.Run("Head All Committees of Index 1", func(t *testing.T) { chainService := &chainMock.ChainService{} s := Server{ - StateFetcher: &testutil.MockFetcher{ + StateFetcher: &testutil.MockStater{ BeaconState: st, }, HeadFetcher: chainService, @@ -892,7 +892,7 @@ func TestListCommittees(t *testing.T) { t.Run("Head All Committees of Slot 2, Index 1", func(t *testing.T) { chainService := &chainMock.ChainService{} s := Server{ - StateFetcher: &testutil.MockFetcher{ + StateFetcher: &testutil.MockStater{ BeaconState: st, }, HeadFetcher: chainService, @@ -928,7 +928,7 @@ func TestListCommittees(t *testing.T) { chainService := &chainMock.ChainService{Optimistic: true} s := Server{ - StateFetcher: &testutil.MockFetcher{ + StateFetcher: &testutil.MockStater{ BeaconState: st, }, HeadFetcher: chainService, @@ -961,7 +961,7 @@ func TestListCommittees(t *testing.T) { }, } s := Server{ - StateFetcher: &testutil.MockFetcher{ + StateFetcher: &testutil.MockStater{ BeaconState: st, }, HeadFetcher: chainService, diff --git a/beacon-chain/rpc/eth/debug/debug_test.go b/beacon-chain/rpc/eth/debug/debug_test.go index 00872c5b6abc..df345663bff9 100644 --- a/beacon-chain/rpc/eth/debug/debug_test.go +++ b/beacon-chain/rpc/eth/debug/debug_test.go @@ -28,7 +28,7 @@ func TestGetBeaconStateV2(t *testing.T) { fakeState, err := util.NewBeaconState() require.NoError(t, err) server := &Server{ - StateFetcher: &testutil.MockFetcher{ + StateFetcher: &testutil.MockStater{ BeaconState: fakeState, }, HeadFetcher: &blockchainmock.ChainService{}, @@ -46,7 +46,7 @@ func TestGetBeaconStateV2(t *testing.T) { t.Run("Altair", func(t *testing.T) { fakeState, _ := util.DeterministicGenesisStateAltair(t, 1) server := &Server{ - StateFetcher: &testutil.MockFetcher{ + StateFetcher: &testutil.MockStater{ BeaconState: fakeState, }, HeadFetcher: &blockchainmock.ChainService{}, @@ -64,7 +64,7 @@ func TestGetBeaconStateV2(t *testing.T) { t.Run("Bellatrix", func(t *testing.T) { fakeState, _ := util.DeterministicGenesisStateBellatrix(t, 1) server := &Server{ - StateFetcher: &testutil.MockFetcher{ + StateFetcher: &testutil.MockStater{ BeaconState: fakeState, }, HeadFetcher: &blockchainmock.ChainService{}, @@ -82,7 +82,7 @@ func TestGetBeaconStateV2(t *testing.T) { t.Run("Capella", func(t *testing.T) { fakeState, _ := util.DeterministicGenesisStateCapella(t, 1) server := &Server{ - StateFetcher: &testutil.MockFetcher{ + StateFetcher: &testutil.MockStater{ BeaconState: fakeState, }, HeadFetcher: &blockchainmock.ChainService{}, @@ -108,7 +108,7 @@ func TestGetBeaconStateV2(t *testing.T) { fakeState, _ := util.DeterministicGenesisStateBellatrix(t, 1) server := &Server{ - StateFetcher: &testutil.MockFetcher{ + StateFetcher: &testutil.MockStater{ BeaconState: fakeState, }, HeadFetcher: &blockchainmock.ChainService{}, @@ -141,7 +141,7 @@ func TestGetBeaconStateV2(t *testing.T) { }, } server := &Server{ - StateFetcher: &testutil.MockFetcher{ + StateFetcher: &testutil.MockStater{ BeaconState: fakeState, }, HeadFetcher: chainService, @@ -165,7 +165,7 @@ func TestGetBeaconStateSSZ(t *testing.T) { require.NoError(t, err) server := &Server{ - StateFetcher: &testutil.MockFetcher{ + StateFetcher: &testutil.MockStater{ BeaconState: fakeState, }, } @@ -186,7 +186,7 @@ func TestGetBeaconStateSSZV2(t *testing.T) { require.NoError(t, err) server := &Server{ - StateFetcher: &testutil.MockFetcher{ + StateFetcher: &testutil.MockStater{ BeaconState: fakeState, }, } @@ -205,7 +205,7 @@ func TestGetBeaconStateSSZV2(t *testing.T) { require.NoError(t, err) server := &Server{ - StateFetcher: &testutil.MockFetcher{ + StateFetcher: &testutil.MockStater{ BeaconState: fakeState, }, } @@ -224,7 +224,7 @@ func TestGetBeaconStateSSZV2(t *testing.T) { require.NoError(t, err) server := &Server{ - StateFetcher: &testutil.MockFetcher{ + StateFetcher: &testutil.MockStater{ BeaconState: fakeState, }, } @@ -243,7 +243,7 @@ func TestGetBeaconStateSSZV2(t *testing.T) { require.NoError(t, err) server := &Server{ - StateFetcher: &testutil.MockFetcher{ + StateFetcher: &testutil.MockStater{ BeaconState: fakeState, }, } diff --git a/beacon-chain/rpc/eth/debug/server.go b/beacon-chain/rpc/eth/debug/server.go index aad278f97525..b50f05b5e69b 100644 --- a/beacon-chain/rpc/eth/debug/server.go +++ b/beacon-chain/rpc/eth/debug/server.go @@ -14,7 +14,7 @@ import ( type Server struct { BeaconDB db.ReadOnlyDatabase HeadFetcher blockchain.HeadFetcher - StateFetcher lookup.Fetcher + StateFetcher lookup.Stater OptimisticModeFetcher blockchain.OptimisticModeFetcher ForkFetcher blockchain.ForkFetcher FinalizationFetcher blockchain.FinalizationFetcher diff --git a/beacon-chain/rpc/eth/helpers/sync.go b/beacon-chain/rpc/eth/helpers/sync.go index f9b04ab79975..87f835d1aa44 100644 --- a/beacon-chain/rpc/eth/helpers/sync.go +++ b/beacon-chain/rpc/eth/helpers/sync.go @@ -61,7 +61,7 @@ func IsOptimistic( ctx context.Context, stateId []byte, optimisticModeFetcher blockchain.OptimisticModeFetcher, - stateFetcher lookup.Fetcher, + stateFetcher lookup.Stater, chainInfo blockchain.ChainInfoFetcher, database db.ReadOnlyDatabase, ) (bool, error) { @@ -146,7 +146,7 @@ func isStateRootOptimistic( ctx context.Context, stateId []byte, optimisticModeFetcher blockchain.OptimisticModeFetcher, - stateFetcher lookup.Fetcher, + stateFetcher lookup.Stater, chainInfo blockchain.ChainInfoFetcher, database db.ReadOnlyDatabase, ) (bool, error) { diff --git a/beacon-chain/rpc/eth/helpers/sync_test.go b/beacon-chain/rpc/eth/helpers/sync_test.go index 2ad142ba3eaf..527880b5f33d 100644 --- a/beacon-chain/rpc/eth/helpers/sync_test.go +++ b/beacon-chain/rpc/eth/helpers/sync_test.go @@ -97,7 +97,7 @@ func TestIsOptimistic(t *testing.T) { st, err := util.NewBeaconState() require.NoError(t, err) cs := &chainmock.ChainService{Optimistic: true, FinalizedCheckPoint: ð.Checkpoint{}, OptimisticRoots: map[[32]byte]bool{[32]byte{}: true}} - mf := &testutil.MockFetcher{BeaconState: st} + mf := &testutil.MockStater{BeaconState: st} o, err := IsOptimistic(ctx, []byte("finalized"), cs, mf, cs, nil) require.NoError(t, err) assert.Equal(t, true, o) @@ -106,7 +106,7 @@ func TestIsOptimistic(t *testing.T) { st, err := util.NewBeaconState() require.NoError(t, err) cs := &chainmock.ChainService{Optimistic: true, FinalizedCheckPoint: ð.Checkpoint{}} - mf := &testutil.MockFetcher{BeaconState: st} + mf := &testutil.MockStater{BeaconState: st} o, err := IsOptimistic(ctx, []byte("finalized"), cs, mf, cs, nil) require.NoError(t, err) assert.Equal(t, false, o) @@ -117,7 +117,7 @@ func TestIsOptimistic(t *testing.T) { st, err := util.NewBeaconState() require.NoError(t, err) cs := &chainmock.ChainService{Optimistic: true, CurrentJustifiedCheckPoint: ð.Checkpoint{}, OptimisticRoots: map[[32]byte]bool{[32]byte{}: true}} - mf := &testutil.MockFetcher{BeaconState: st} + mf := &testutil.MockStater{BeaconState: st} o, err := IsOptimistic(ctx, []byte("justified"), cs, mf, cs, nil) require.NoError(t, err) assert.Equal(t, true, o) @@ -126,7 +126,7 @@ func TestIsOptimistic(t *testing.T) { st, err := util.NewBeaconState() require.NoError(t, err) cs := &chainmock.ChainService{Optimistic: true, CurrentJustifiedCheckPoint: ð.Checkpoint{}} - mf := &testutil.MockFetcher{BeaconState: st} + mf := &testutil.MockStater{BeaconState: st} o, err := IsOptimistic(ctx, []byte("justified"), cs, mf, cs, nil) require.NoError(t, err) assert.Equal(t, false, o) @@ -137,7 +137,7 @@ func TestIsOptimistic(t *testing.T) { st, err := util.NewBeaconState() require.NoError(t, err) cs := &chainmock.ChainService{Optimistic: true} - mf := &testutil.MockFetcher{BeaconState: st} + mf := &testutil.MockStater{BeaconState: st} o, err := IsOptimistic(ctx, bytesutil.PadTo([]byte("root"), 32), cs, mf, cs, nil) require.NoError(t, err) assert.Equal(t, true, o) @@ -146,7 +146,7 @@ func TestIsOptimistic(t *testing.T) { st, err := util.NewBeaconState() require.NoError(t, err) cs := &chainmock.ChainService{Optimistic: false} - mf := &testutil.MockFetcher{BeaconState: st} + mf := &testutil.MockStater{BeaconState: st} o, err := IsOptimistic(ctx, bytesutil.PadTo([]byte("root"), 32), cs, mf, cs, nil) require.NoError(t, err) assert.Equal(t, false, o) @@ -165,7 +165,7 @@ func TestIsOptimistic(t *testing.T) { bRoot, err := b.Block().HashTreeRoot() require.NoError(t, err) cs := &chainmock.ChainService{State: chainSt, OptimisticRoots: map[[32]byte]bool{bRoot: true}} - mf := &testutil.MockFetcher{BeaconState: fetcherSt} + mf := &testutil.MockStater{BeaconState: fetcherSt} o, err := IsOptimistic(ctx, bytesutil.PadTo([]byte("root"), 32), cs, mf, cs, db) require.NoError(t, err) assert.Equal(t, true, o) @@ -182,7 +182,7 @@ func TestIsOptimistic(t *testing.T) { require.NoError(t, err) require.NoError(t, chainSt.SetSlot(fieldparams.SlotsPerEpoch)) cs := &chainmock.ChainService{State: chainSt} - mf := &testutil.MockFetcher{BeaconState: fetcherSt} + mf := &testutil.MockStater{BeaconState: fetcherSt} o, err := IsOptimistic(ctx, bytesutil.PadTo([]byte("root"), 32), cs, mf, cs, db) require.NoError(t, err) assert.Equal(t, false, o) @@ -198,7 +198,7 @@ func TestIsOptimistic(t *testing.T) { require.NoError(t, err) require.NoError(t, chainSt.SetSlot(fieldparams.SlotsPerEpoch)) cs := &chainmock.ChainService{Optimistic: false, State: chainSt, CanonicalRoots: map[[32]byte]bool{}} - mf := &testutil.MockFetcher{BeaconState: fetcherSt} + mf := &testutil.MockStater{BeaconState: fetcherSt} o, err := IsOptimistic(ctx, bytesutil.PadTo([]byte("root"), 32), nil, mf, cs, db) require.NoError(t, err) assert.Equal(t, true, o) @@ -248,7 +248,7 @@ func TestIsOptimistic(t *testing.T) { require.NoError(t, err) require.NoError(t, chainSt.SetSlot(fieldparams.SlotsPerEpoch*2)) cs := &chainmock.ChainService{Optimistic: true, State: chainSt, FinalizedCheckPoint: ð.Checkpoint{Epoch: 0}} - mf := &testutil.MockFetcher{BeaconState: fetcherSt} + mf := &testutil.MockStater{BeaconState: fetcherSt} o, err := IsOptimistic(ctx, []byte(strconv.Itoa(fieldparams.SlotsPerEpoch*2)), cs, mf, cs, db) require.NoError(t, err) assert.Equal(t, true, o) @@ -268,7 +268,7 @@ func TestIsOptimistic(t *testing.T) { require.NoError(t, err) require.NoError(t, fcs.InsertNode(ctx, st, root)) cs := &chainmock.ChainService{Root: headRoot[:], Optimistic: true, ForkChoiceStore: fcs, OptimisticRoots: map[[32]byte]bool{r: true}, FinalizedCheckPoint: finalizedCheckpt} - mf := &testutil.MockFetcher{BeaconState: st} + mf := &testutil.MockStater{BeaconState: st} o, err := IsOptimistic(ctx, []byte(strconv.Itoa(fieldparams.SlotsPerEpoch*2)), cs, mf, cs, db) require.NoError(t, err) assert.Equal(t, true, o) @@ -288,7 +288,7 @@ func TestIsOptimistic(t *testing.T) { require.NoError(t, err) require.NoError(t, fcs.InsertNode(ctx, st, root)) cs := &chainmock.ChainService{Root: headRoot[:], Optimistic: true, ForkChoiceStore: fcs, OptimisticRoots: map[[32]byte]bool{r: false}, FinalizedCheckPoint: finalizedCheckpt} - mf := &testutil.MockFetcher{BeaconState: st} + mf := &testutil.MockStater{BeaconState: st} o, err := IsOptimistic(ctx, []byte(strconv.Itoa(fieldparams.SlotsPerEpoch*2)), cs, mf, cs, db) require.NoError(t, err) assert.Equal(t, false, o) diff --git a/beacon-chain/rpc/eth/validator/server.go b/beacon-chain/rpc/eth/validator/server.go index 5f56ffc3234a..2aa276344782 100644 --- a/beacon-chain/rpc/eth/validator/server.go +++ b/beacon-chain/rpc/eth/validator/server.go @@ -22,7 +22,7 @@ type Server struct { AttestationsPool attestations.Pool PeerManager p2p.PeerManager Broadcaster p2p.Broadcaster - StateFetcher lookup.Fetcher + StateFetcher lookup.Stater OptimisticModeFetcher blockchain.OptimisticModeFetcher SyncCommitteePool synccommittee.Pool V1Alpha1Server *v1alpha1validator.Server diff --git a/beacon-chain/rpc/eth/validator/validator_test.go b/beacon-chain/rpc/eth/validator/validator_test.go index 0c98a1e020ec..25941cb7eeda 100644 --- a/beacon-chain/rpc/eth/validator/validator_test.go +++ b/beacon-chain/rpc/eth/validator/validator_test.go @@ -93,7 +93,7 @@ func TestGetAttesterDuties(t *testing.T) { State: bs, Root: genesisRoot[:], Slot: &chainSlot, } vs := &Server{ - StateFetcher: &testutil.MockFetcher{ + StateFetcher: &testutil.MockStater{ StatesBySlot: map[primitives.Slot]state.BeaconState{ 0: bs, params.BeaconConfig().SlotsPerEpoch: nextEpochState, @@ -198,7 +198,7 @@ func TestGetAttesterDuties(t *testing.T) { State: bs, Root: genesisRoot[:], Slot: &chainSlot, Optimistic: true, } vs := &Server{ - StateFetcher: &testutil.MockFetcher{StatesBySlot: map[primitives.Slot]state.BeaconState{0: bs}}, + StateFetcher: &testutil.MockStater{StatesBySlot: map[primitives.Slot]state.BeaconState{0: bs}}, TimeFetcher: chain, OptimisticModeFetcher: chain, SyncChecker: &mockSync.Sync{IsSyncing: false}, @@ -258,7 +258,7 @@ func TestGetProposerDuties(t *testing.T) { State: bs, Root: genesisRoot[:], Slot: &chainSlot, } vs := &Server{ - StateFetcher: &testutil.MockFetcher{StatesBySlot: map[primitives.Slot]state.BeaconState{0: bs}}, + StateFetcher: &testutil.MockStater{StatesBySlot: map[primitives.Slot]state.BeaconState{0: bs}}, HeadFetcher: chain, TimeFetcher: chain, OptimisticModeFetcher: chain, @@ -297,7 +297,7 @@ func TestGetProposerDuties(t *testing.T) { State: bs, Root: genesisRoot[:], Slot: &chainSlot, } vs := &Server{ - StateFetcher: &testutil.MockFetcher{StatesBySlot: map[primitives.Slot]state.BeaconState{0: bs}}, + StateFetcher: &testutil.MockStater{StatesBySlot: map[primitives.Slot]state.BeaconState{0: bs}}, HeadFetcher: chain, TimeFetcher: chain, OptimisticModeFetcher: chain, @@ -337,7 +337,7 @@ func TestGetProposerDuties(t *testing.T) { State: bs, Root: genesisRoot[:], Slot: &chainSlot, } vs := &Server{ - StateFetcher: &testutil.MockFetcher{StatesBySlot: map[primitives.Slot]state.BeaconState{params.BeaconConfig().SlotsPerEpoch: bs}}, + StateFetcher: &testutil.MockStater{StatesBySlot: map[primitives.Slot]state.BeaconState{params.BeaconConfig().SlotsPerEpoch: bs}}, HeadFetcher: chain, TimeFetcher: chain, OptimisticModeFetcher: chain, @@ -377,7 +377,7 @@ func TestGetProposerDuties(t *testing.T) { State: bs, Root: genesisRoot[:], Slot: &chainSlot, } vs := &Server{ - StateFetcher: &testutil.MockFetcher{StatesBySlot: map[primitives.Slot]state.BeaconState{0: bs}}, + StateFetcher: &testutil.MockStater{StatesBySlot: map[primitives.Slot]state.BeaconState{0: bs}}, HeadFetcher: chain, TimeFetcher: chain, OptimisticModeFetcher: chain, @@ -414,7 +414,7 @@ func TestGetProposerDuties(t *testing.T) { State: bs, Root: genesisRoot[:], Slot: &chainSlot, Optimistic: true, } vs := &Server{ - StateFetcher: &testutil.MockFetcher{StatesBySlot: map[primitives.Slot]state.BeaconState{0: bs}}, + StateFetcher: &testutil.MockStater{StatesBySlot: map[primitives.Slot]state.BeaconState{0: bs}}, HeadFetcher: chain, TimeFetcher: chain, OptimisticModeFetcher: chain, @@ -469,7 +469,7 @@ func TestGetSyncCommitteeDuties(t *testing.T) { mockChainService := &mockChain.ChainService{Genesis: genesisTime} vs := &Server{ - StateFetcher: &testutil.MockFetcher{BeaconState: st}, + StateFetcher: &testutil.MockStater{BeaconState: st}, SyncChecker: &mockSync.Sync{IsSyncing: false}, TimeFetcher: mockChainService, HeadFetcher: mockChainService, @@ -611,7 +611,7 @@ func TestGetSyncCommitteeDuties(t *testing.T) { } mockChainService := &mockChain.ChainService{Genesis: genesisTime, Slot: &newSyncPeriodStartSlot} vs := &Server{ - StateFetcher: &testutil.MockFetcher{BeaconState: stateFetchFn(newSyncPeriodStartSlot)}, + StateFetcher: &testutil.MockStater{BeaconState: stateFetchFn(newSyncPeriodStartSlot)}, SyncChecker: &mockSync.Sync{IsSyncing: false}, TimeFetcher: mockChainService, HeadFetcher: mockChainService, @@ -665,7 +665,7 @@ func TestGetSyncCommitteeDuties(t *testing.T) { State: state, } vs := &Server{ - StateFetcher: &testutil.MockFetcher{BeaconState: st}, + StateFetcher: &testutil.MockStater{BeaconState: st}, SyncChecker: &mockSync.Sync{IsSyncing: false}, TimeFetcher: mockChainService, HeadFetcher: mockChainService, @@ -5015,7 +5015,7 @@ func TestGetLiveness(t *testing.T) { server := &Server{ HeadFetcher: &mockChain.ChainService{State: headSt}, - StateFetcher: &testutil.MockFetcher{ + StateFetcher: &testutil.MockStater{ // We configure states for last slots of an epoch StatesBySlot: map[primitives.Slot]state.BeaconState{ params.BeaconConfig().SlotsPerEpoch - 1: oldSt, diff --git a/beacon-chain/rpc/lookup/fetcher.go b/beacon-chain/rpc/lookup/fetcher.go index 5180ba7bc04a..6da0e1a2d7a7 100644 --- a/beacon-chain/rpc/lookup/fetcher.go +++ b/beacon-chain/rpc/lookup/fetcher.go @@ -71,15 +71,15 @@ func (e *StateRootNotFoundError) Error() string { return e.message } -// Fetcher is responsible for retrieving info related with the beacon chain. -type Fetcher interface { - State(ctx context.Context, stateId []byte) (state.BeaconState, error) - StateRoot(ctx context.Context, stateId []byte) ([]byte, error) +// Stater is responsible for retrieving states. +type Stater interface { + State(ctx context.Context, id []byte) (state.BeaconState, error) + StateRoot(ctx context.Context, id []byte) ([]byte, error) StateBySlot(ctx context.Context, slot primitives.Slot) (state.BeaconState, error) } -// StateProvider is a real implementation of Fetcher. -type StateProvider struct { +// BeaconDbStater is an implementation of Stater. It retrieves states from the beacon chain database. +type BeaconDbStater struct { BeaconDB db.ReadOnlyDatabase ChainInfoFetcher blockchain.ChainInfoFetcher GenesisTimeFetcher blockchain.TimeFetcher @@ -94,7 +94,7 @@ type StateProvider struct { // - "justified" // - // - -func (p *StateProvider) State(ctx context.Context, stateId []byte) (state.BeaconState, error) { +func (p *BeaconDbStater) State(ctx context.Context, stateId []byte) (state.BeaconState, error) { var ( s state.BeaconState err error @@ -164,7 +164,7 @@ func (p *StateProvider) State(ctx context.Context, stateId []byte) (state.Beacon // - "justified" // - // - -func (p *StateProvider) StateRoot(ctx context.Context, stateId []byte) (root []byte, err error) { +func (p *BeaconDbStater) StateRoot(ctx context.Context, stateId []byte) (root []byte, err error) { stateIdString := strings.ToLower(string(stateId)) switch stateIdString { case "head": @@ -192,7 +192,7 @@ func (p *StateProvider) StateRoot(ctx context.Context, stateId []byte) (root []b return root, err } -func (p *StateProvider) stateByRoot(ctx context.Context, stateRoot []byte) (state.BeaconState, error) { +func (p *BeaconDbStater) stateByRoot(ctx context.Context, stateRoot []byte) (state.BeaconState, error) { headState, err := p.ChainInfoFetcher.HeadStateReadOnly(ctx) if err != nil { return nil, errors.Wrap(err, "could not get head state") @@ -213,7 +213,7 @@ func (p *StateProvider) stateByRoot(ctx context.Context, stateRoot []byte) (stat // between the found state's slot and the target slot. // process_blocks is applied for all canonical blocks, and process_slots is called for any skipped // slots, or slots following the most recent canonical block up to and including the target slot. -func (p *StateProvider) StateBySlot(ctx context.Context, target primitives.Slot) (state.BeaconState, error) { +func (p *BeaconDbStater) StateBySlot(ctx context.Context, target primitives.Slot) (state.BeaconState, error) { ctx, span := trace.StartSpan(ctx, "statefetcher.StateBySlot") defer span.End() @@ -229,7 +229,7 @@ func (p *StateProvider) StateBySlot(ctx context.Context, target primitives.Slot) return st, nil } -func (p *StateProvider) headStateRoot(ctx context.Context) ([]byte, error) { +func (p *BeaconDbStater) headStateRoot(ctx context.Context) ([]byte, error) { b, err := p.ChainInfoFetcher.HeadBlock(ctx) if err != nil { return nil, errors.Wrap(err, "could not get head block") @@ -241,7 +241,7 @@ func (p *StateProvider) headStateRoot(ctx context.Context) ([]byte, error) { return stateRoot[:], nil } -func (p *StateProvider) genesisStateRoot(ctx context.Context) ([]byte, error) { +func (p *BeaconDbStater) genesisStateRoot(ctx context.Context) ([]byte, error) { b, err := p.BeaconDB.GenesisBlock(ctx) if err != nil { return nil, errors.Wrap(err, "could not get genesis block") @@ -253,7 +253,7 @@ func (p *StateProvider) genesisStateRoot(ctx context.Context) ([]byte, error) { return stateRoot[:], nil } -func (p *StateProvider) finalizedStateRoot(ctx context.Context) ([]byte, error) { +func (p *BeaconDbStater) finalizedStateRoot(ctx context.Context) ([]byte, error) { cp, err := p.BeaconDB.FinalizedCheckpoint(ctx) if err != nil { return nil, errors.Wrap(err, "could not get finalized checkpoint") @@ -269,7 +269,7 @@ func (p *StateProvider) finalizedStateRoot(ctx context.Context) ([]byte, error) return stateRoot[:], nil } -func (p *StateProvider) justifiedStateRoot(ctx context.Context) ([]byte, error) { +func (p *BeaconDbStater) justifiedStateRoot(ctx context.Context) ([]byte, error) { cp, err := p.BeaconDB.JustifiedCheckpoint(ctx) if err != nil { return nil, errors.Wrap(err, "could not get justified checkpoint") @@ -285,7 +285,7 @@ func (p *StateProvider) justifiedStateRoot(ctx context.Context) ([]byte, error) return stateRoot[:], nil } -func (p *StateProvider) stateRootByRoot(ctx context.Context, stateRoot []byte) ([]byte, error) { +func (p *BeaconDbStater) stateRootByRoot(ctx context.Context, stateRoot []byte) ([]byte, error) { var r [32]byte copy(r[:], stateRoot) headState, err := p.ChainInfoFetcher.HeadStateReadOnly(ctx) @@ -302,7 +302,7 @@ func (p *StateProvider) stateRootByRoot(ctx context.Context, stateRoot []byte) ( return nil, &rootNotFoundErr } -func (p *StateProvider) stateRootBySlot(ctx context.Context, slot primitives.Slot) ([]byte, error) { +func (p *BeaconDbStater) stateRootBySlot(ctx context.Context, slot primitives.Slot) ([]byte, error) { currentSlot := p.GenesisTimeFetcher.CurrentSlot() if slot > currentSlot { return nil, errors.New("slot cannot be in the future") diff --git a/beacon-chain/rpc/lookup/fetcher_test.go b/beacon-chain/rpc/lookup/fetcher_test.go index dff639c3cc7a..cc7ca07f4409 100644 --- a/beacon-chain/rpc/lookup/fetcher_test.go +++ b/beacon-chain/rpc/lookup/fetcher_test.go @@ -38,7 +38,7 @@ func TestGetState(t *testing.T) { require.NoError(t, err) t.Run("head", func(t *testing.T) { - p := StateProvider{ + p := BeaconDbStater{ ChainInfoFetcher: &chainMock.ChainService{State: newBeaconState}, } @@ -78,7 +78,7 @@ func TestGetState(t *testing.T) { cs := &mockstategen.MockCurrentSlotter{Slot: bs.Slot() + 1} ch := stategen.NewCanonicalHistory(db, cc, cs) currentSlot := primitives.Slot(0) - p := StateProvider{ + p := BeaconDbStater{ BeaconDB: db, ReplayerBuilder: ch, GenesisTimeFetcher: &chainMock.ChainService{Slot: ¤tSlot}, @@ -98,7 +98,7 @@ func TestGetState(t *testing.T) { replayer.SetMockStateForSlot(newBeaconState, params.BeaconConfig().SlotsPerEpoch*10) stateGen.StatesByRoot[stateRoot] = newBeaconState - p := StateProvider{ + p := BeaconDbStater{ ChainInfoFetcher: &chainMock.ChainService{ FinalizedCheckPoint: ðpb.Checkpoint{ Root: stateRoot[:], @@ -122,7 +122,7 @@ func TestGetState(t *testing.T) { replayer.SetMockStateForSlot(newBeaconState, params.BeaconConfig().SlotsPerEpoch*10) stateGen.StatesByRoot[stateRoot] = newBeaconState - p := StateProvider{ + p := BeaconDbStater{ ChainInfoFetcher: &chainMock.ChainService{ CurrentJustifiedCheckPoint: ðpb.Checkpoint{ Root: stateRoot[:], @@ -146,7 +146,7 @@ func TestGetState(t *testing.T) { stateGen := mockstategen.NewMockService() stateGen.StatesByRoot[bytesutil.ToBytes32(stateId)] = newBeaconState - p := StateProvider{ + p := BeaconDbStater{ ChainInfoFetcher: &chainMock.ChainService{State: newBeaconState}, StateGenService: stateGen, } @@ -159,7 +159,7 @@ func TestGetState(t *testing.T) { }) t.Run("hex_root_not_found", func(t *testing.T) { - p := StateProvider{ + p := BeaconDbStater{ ChainInfoFetcher: &chainMock.ChainService{State: newBeaconState}, } stateId, err := hexutil.Decode("0x" + strings.Repeat("f", 64)) @@ -169,7 +169,7 @@ func TestGetState(t *testing.T) { }) t.Run("slot", func(t *testing.T) { - p := StateProvider{ + p := BeaconDbStater{ GenesisTimeFetcher: &chainMock.ChainService{Slot: &headSlot}, ChainInfoFetcher: &chainMock.ChainService{ CanonicalRoots: map[[32]byte]bool{ @@ -188,7 +188,7 @@ func TestGetState(t *testing.T) { }) t.Run("invalid_state", func(t *testing.T) { - p := StateProvider{} + p := BeaconDbStater{} _, err := p.State(ctx, []byte("foo")) require.ErrorContains(t, "could not parse state ID", err) }) @@ -212,7 +212,7 @@ func TestGetStateRoot(t *testing.T) { b.Block.StateRoot = stateRoot[:] wsb, err := blocks.NewSignedBeaconBlock(b) require.NoError(t, err) - p := StateProvider{ + p := BeaconDbStater{ ChainInfoFetcher: &chainMock.ChainService{ State: newBeaconState, Block: wsb, @@ -241,7 +241,7 @@ func TestGetStateRoot(t *testing.T) { require.NoError(t, db.SaveGenesisBlockRoot(ctx, r)) require.NoError(t, db.SaveState(ctx, bs, r)) - p := StateProvider{ + p := BeaconDbStater{ BeaconDB: db, } @@ -275,7 +275,7 @@ func TestGetStateRoot(t *testing.T) { require.NoError(t, db.SaveState(ctx, st, root)) require.NoError(t, db.SaveFinalizedCheckpoint(ctx, cp)) - p := StateProvider{ + p := BeaconDbStater{ BeaconDB: db, } @@ -306,7 +306,7 @@ func TestGetStateRoot(t *testing.T) { require.NoError(t, db.SaveState(ctx, st, root)) require.NoError(t, db.SaveJustifiedCheckpoint(ctx, cp)) - p := StateProvider{ + p := BeaconDbStater{ BeaconDB: db, } @@ -319,7 +319,7 @@ func TestGetStateRoot(t *testing.T) { stateId, err := hexutil.Decode("0x" + strings.Repeat("0", 63) + "1") require.NoError(t, err) - p := StateProvider{ + p := BeaconDbStater{ ChainInfoFetcher: &chainMock.ChainService{State: newBeaconState}, } @@ -329,7 +329,7 @@ func TestGetStateRoot(t *testing.T) { }) t.Run("hex_root_not_found", func(t *testing.T) { - p := StateProvider{ + p := BeaconDbStater{ ChainInfoFetcher: &chainMock.ChainService{State: newBeaconState}, } stateId, err := hexutil.Decode("0x" + strings.Repeat("f", 64)) @@ -355,7 +355,7 @@ func TestGetStateRoot(t *testing.T) { require.NoError(t, db.SaveState(ctx, st, root)) slot := primitives.Slot(40) - p := StateProvider{ + p := BeaconDbStater{ GenesisTimeFetcher: &chainMock.ChainService{Slot: &slot}, BeaconDB: db, } @@ -366,7 +366,7 @@ func TestGetStateRoot(t *testing.T) { }) t.Run("slot_too_big", func(t *testing.T) { - p := StateProvider{ + p := BeaconDbStater{ GenesisTimeFetcher: &chainMock.ChainService{ Genesis: time.Now(), }, @@ -376,7 +376,7 @@ func TestGetStateRoot(t *testing.T) { }) t.Run("invalid_state", func(t *testing.T) { - p := StateProvider{} + p := BeaconDbStater{} _, err := p.StateRoot(ctx, []byte("foo")) require.ErrorContains(t, "could not parse state ID", err) }) @@ -389,7 +389,7 @@ func TestNewStateNotFoundError(t *testing.T) { func TestStateBySlot_FutureSlot(t *testing.T) { slot := primitives.Slot(100) - p := StateProvider{GenesisTimeFetcher: &chainMock.ChainService{Slot: &slot}} + p := BeaconDbStater{GenesisTimeFetcher: &chainMock.ChainService{Slot: &slot}} _, err := p.StateBySlot(context.Background(), 101) assert.ErrorContains(t, "requested slot is in the future", err) } @@ -403,7 +403,7 @@ func TestStateBySlot_AfterHeadSlot(t *testing.T) { mock := &chainMock.ChainService{State: headSt, Slot: ¤tSlot} mockReplayer := mockstategen.NewMockReplayerBuilder() mockReplayer.SetMockStateForSlot(slotSt, 101) - p := StateProvider{ChainInfoFetcher: mock, GenesisTimeFetcher: mock, ReplayerBuilder: mockReplayer} + p := BeaconDbStater{ChainInfoFetcher: mock, GenesisTimeFetcher: mock, ReplayerBuilder: mockReplayer} st, err := p.StateBySlot(context.Background(), 101) require.NoError(t, err) assert.Equal(t, primitives.Slot(101), st.Slot()) diff --git a/beacon-chain/rpc/service.go b/beacon-chain/rpc/service.go index 3b7ffba8a999..ffb106915ddc 100644 --- a/beacon-chain/rpc/service.go +++ b/beacon-chain/rpc/service.go @@ -235,7 +235,7 @@ func (s *Service) Start() { PeerManager: s.cfg.PeerManager, Broadcaster: s.cfg.Broadcaster, V1Alpha1Server: validatorServer, - StateFetcher: &lookup.StateProvider{ + StateFetcher: &lookup.BeaconDbStater{ BeaconDB: s.cfg.BeaconDB, ChainInfoFetcher: s.cfg.ChainInfoFetcher, GenesisTimeFetcher: s.cfg.GenesisTimeFetcher, @@ -311,7 +311,7 @@ func (s *Service) Start() { Broadcaster: s.cfg.Broadcaster, BlockReceiver: s.cfg.BlockReceiver, StateGenService: s.cfg.StateGen, - StateFetcher: &lookup.StateProvider{ + StateFetcher: &lookup.BeaconDbStater{ BeaconDB: s.cfg.BeaconDB, ChainInfoFetcher: s.cfg.ChainInfoFetcher, GenesisTimeFetcher: s.cfg.GenesisTimeFetcher, @@ -354,7 +354,7 @@ func (s *Service) Start() { debugServerV1 := &debug.Server{ BeaconDB: s.cfg.BeaconDB, HeadFetcher: s.cfg.HeadFetcher, - StateFetcher: &lookup.StateProvider{ + StateFetcher: &lookup.BeaconDbStater{ BeaconDB: s.cfg.BeaconDB, ChainInfoFetcher: s.cfg.ChainInfoFetcher, GenesisTimeFetcher: s.cfg.GenesisTimeFetcher, diff --git a/beacon-chain/rpc/testutil/mock_state_fetcher.go b/beacon-chain/rpc/testutil/mock_state_fetcher.go index e0e59225cf7a..4e7a5f728c8d 100644 --- a/beacon-chain/rpc/testutil/mock_state_fetcher.go +++ b/beacon-chain/rpc/testutil/mock_state_fetcher.go @@ -7,23 +7,24 @@ import ( "github.com/prysmaticlabs/prysm/v4/consensus-types/primitives" ) -// MockFetcher is a fake implementation of statefetcher.Fetcher. -type MockFetcher struct { +// MockStater is a fake implementation of lookup.Stater. +type MockStater struct { BeaconState state.BeaconState BeaconStateRoot []byte StatesBySlot map[primitives.Slot]state.BeaconState } // State -- -func (m *MockFetcher) State(context.Context, []byte) (state.BeaconState, error) { +func (m *MockStater) State(context.Context, []byte) (state.BeaconState, error) { return m.BeaconState, nil } // StateRoot -- -func (m *MockFetcher) StateRoot(context.Context, []byte) ([]byte, error) { +func (m *MockStater) StateRoot(context.Context, []byte) ([]byte, error) { return m.BeaconStateRoot, nil } -func (m *MockFetcher) StateBySlot(_ context.Context, s primitives.Slot) (state.BeaconState, error) { +// StateBySlot -- +func (m *MockStater) StateBySlot(_ context.Context, s primitives.Slot) (state.BeaconState, error) { return m.StatesBySlot[s], nil } From 5296367932e0304102ece51c1ee1f8e5e844a981 Mon Sep 17 00:00:00 2001 From: rkapka Date: Wed, 22 Mar 2023 14:13:04 +0100 Subject: [PATCH 29/40] rename files --- beacon-chain/rpc/lookup/BUILD.bazel | 4 ++-- beacon-chain/rpc/lookup/{fetcher.go => stater.go} | 0 beacon-chain/rpc/lookup/{fetcher_test.go => stater_test.go} | 0 3 files changed, 2 insertions(+), 2 deletions(-) rename beacon-chain/rpc/lookup/{fetcher.go => stater.go} (100%) rename beacon-chain/rpc/lookup/{fetcher_test.go => stater_test.go} (100%) diff --git a/beacon-chain/rpc/lookup/BUILD.bazel b/beacon-chain/rpc/lookup/BUILD.bazel index 97bfd7cd8fe8..ca8c5a19f5dc 100644 --- a/beacon-chain/rpc/lookup/BUILD.bazel +++ b/beacon-chain/rpc/lookup/BUILD.bazel @@ -2,7 +2,7 @@ load("@prysm//tools/go:def.bzl", "go_library", "go_test") go_library( name = "go_default_library", - srcs = ["fetcher.go"], + srcs = ["stater.go"], importpath = "github.com/prysmaticlabs/prysm/v4/beacon-chain/rpc/lookup", visibility = ["//visibility:public"], deps = [ @@ -22,7 +22,7 @@ go_library( go_test( name = "go_default_test", - srcs = ["fetcher_test.go"], + srcs = ["stater_test.go"], embed = [":go_default_library"], deps = [ "//beacon-chain/blockchain/testing:go_default_library", diff --git a/beacon-chain/rpc/lookup/fetcher.go b/beacon-chain/rpc/lookup/stater.go similarity index 100% rename from beacon-chain/rpc/lookup/fetcher.go rename to beacon-chain/rpc/lookup/stater.go diff --git a/beacon-chain/rpc/lookup/fetcher_test.go b/beacon-chain/rpc/lookup/stater_test.go similarity index 100% rename from beacon-chain/rpc/lookup/fetcher_test.go rename to beacon-chain/rpc/lookup/stater_test.go From 4d49ad8ee8a6c495a0a4bc5901df8a800e0a8a44 Mon Sep 17 00:00:00 2001 From: rkapka Date: Wed, 22 Mar 2023 14:13:45 +0100 Subject: [PATCH 30/40] move blockfetcher to lookup package --- beacon-chain/rpc/blockfetcher/BUILD.bazel | 33 ------------------- beacon-chain/rpc/eth/beacon/BUILD.bazel | 1 - beacon-chain/rpc/eth/beacon/blocks.go | 4 +-- beacon-chain/rpc/eth/beacon/server.go | 3 +- beacon-chain/rpc/eth/rewards/BUILD.bazel | 2 +- beacon-chain/rpc/eth/rewards/handlers.go | 4 +-- beacon-chain/rpc/eth/rewards/server.go | 4 +-- beacon-chain/rpc/lookup/BUILD.bazel | 12 +++++-- .../rpc/{blockfetcher => lookup}/fetcher.go | 2 +- .../{blockfetcher => lookup}/fetcher_test.go | 2 +- 10 files changed, 20 insertions(+), 47 deletions(-) delete mode 100644 beacon-chain/rpc/blockfetcher/BUILD.bazel rename beacon-chain/rpc/{blockfetcher => lookup}/fetcher.go (99%) rename beacon-chain/rpc/{blockfetcher => lookup}/fetcher_test.go (99%) diff --git a/beacon-chain/rpc/blockfetcher/BUILD.bazel b/beacon-chain/rpc/blockfetcher/BUILD.bazel deleted file mode 100644 index 5b8dc280ff3a..000000000000 --- a/beacon-chain/rpc/blockfetcher/BUILD.bazel +++ /dev/null @@ -1,33 +0,0 @@ -load("@prysm//tools/go:def.bzl", "go_library", "go_test") - -go_library( - name = "go_default_library", - srcs = ["fetcher.go"], - importpath = "github.com/prysmaticlabs/prysm/v4/beacon-chain/rpc/blockfetcher", - visibility = ["//visibility:public"], - deps = [ - "//beacon-chain/blockchain:go_default_library", - "//beacon-chain/db:go_default_library", - "//consensus-types/interfaces:go_default_library", - "//consensus-types/primitives:go_default_library", - "//encoding/bytesutil:go_default_library", - "@com_github_pkg_errors//:go_default_library", - ], -) - -go_test( - name = "go_default_test", - srcs = ["fetcher_test.go"], - embed = [":go_default_library"], - deps = [ - "//beacon-chain/blockchain/testing:go_default_library", - "//beacon-chain/db/testing:go_default_library", - "//beacon-chain/rpc/testutil:go_default_library", - "//consensus-types/blocks:go_default_library", - "//encoding/bytesutil:go_default_library", - "//proto/prysm/v1alpha1:go_default_library", - "//testing/assert:go_default_library", - "//testing/require:go_default_library", - "//testing/util:go_default_library", - ], -) diff --git a/beacon-chain/rpc/eth/beacon/BUILD.bazel b/beacon-chain/rpc/eth/beacon/BUILD.bazel index 54fcdcd9195a..df9877a14833 100644 --- a/beacon-chain/rpc/eth/beacon/BUILD.bazel +++ b/beacon-chain/rpc/eth/beacon/BUILD.bazel @@ -33,7 +33,6 @@ go_library( "//beacon-chain/operations/slashings:go_default_library", "//beacon-chain/operations/voluntaryexits:go_default_library", "//beacon-chain/p2p:go_default_library", - "//beacon-chain/rpc/blockfetcher:go_default_library", "//beacon-chain/rpc/eth/helpers:go_default_library", "//beacon-chain/rpc/lookup:go_default_library", "//beacon-chain/rpc/prysm/v1alpha1/validator:go_default_library", diff --git a/beacon-chain/rpc/eth/beacon/blocks.go b/beacon-chain/rpc/eth/beacon/blocks.go index 04baa7b295f6..b4e8b46e6a53 100644 --- a/beacon-chain/rpc/eth/beacon/blocks.go +++ b/beacon-chain/rpc/eth/beacon/blocks.go @@ -11,8 +11,8 @@ import ( blockfeed "github.com/prysmaticlabs/prysm/v4/beacon-chain/core/feed/block" "github.com/prysmaticlabs/prysm/v4/beacon-chain/core/helpers" "github.com/prysmaticlabs/prysm/v4/beacon-chain/db/filters" - "github.com/prysmaticlabs/prysm/v4/beacon-chain/rpc/blockfetcher" rpchelpers "github.com/prysmaticlabs/prysm/v4/beacon-chain/rpc/eth/helpers" + "github.com/prysmaticlabs/prysm/v4/beacon-chain/rpc/lookup" fieldparams "github.com/prysmaticlabs/prysm/v4/config/fieldparams" "github.com/prysmaticlabs/prysm/v4/config/params" "github.com/prysmaticlabs/prysm/v4/consensus-types/blocks" @@ -544,7 +544,7 @@ func (bs *Server) ListBlockAttestations(ctx context.Context, req *ethpbv1.BlockR } func handleGetBlockError(blk interfaces.ReadOnlySignedBeaconBlock, err error) error { - if invalidBlockIdErr, ok := err.(*blockfetcher.BlockIdParseError); ok { + if invalidBlockIdErr, ok := err.(*lookup.BlockIdParseError); ok { return status.Errorf(codes.InvalidArgument, "Invalid block ID: %v", invalidBlockIdErr) } if err != nil { diff --git a/beacon-chain/rpc/eth/beacon/server.go b/beacon-chain/rpc/eth/beacon/server.go index 8e07075915cd..4d6c45dd9473 100644 --- a/beacon-chain/rpc/eth/beacon/server.go +++ b/beacon-chain/rpc/eth/beacon/server.go @@ -14,7 +14,6 @@ import ( "github.com/prysmaticlabs/prysm/v4/beacon-chain/operations/slashings" "github.com/prysmaticlabs/prysm/v4/beacon-chain/operations/voluntaryexits" "github.com/prysmaticlabs/prysm/v4/beacon-chain/p2p" - "github.com/prysmaticlabs/prysm/v4/beacon-chain/rpc/blockfetcher" "github.com/prysmaticlabs/prysm/v4/beacon-chain/rpc/lookup" v1alpha1validator "github.com/prysmaticlabs/prysm/v4/beacon-chain/rpc/prysm/v1alpha1/validator" "github.com/prysmaticlabs/prysm/v4/beacon-chain/state/stategen" @@ -36,7 +35,7 @@ type Server struct { VoluntaryExitsPool voluntaryexits.PoolManager StateGenService stategen.StateManager StateFetcher lookup.Stater - BlockFetcher blockfetcher.Fetcher + BlockFetcher lookup.Fetcher HeadFetcher blockchain.HeadFetcher OptimisticModeFetcher blockchain.OptimisticModeFetcher V1Alpha1ValidatorServer *v1alpha1validator.Server diff --git a/beacon-chain/rpc/eth/rewards/BUILD.bazel b/beacon-chain/rpc/eth/rewards/BUILD.bazel index a7e0b7ce9f2a..2778236a0998 100644 --- a/beacon-chain/rpc/eth/rewards/BUILD.bazel +++ b/beacon-chain/rpc/eth/rewards/BUILD.bazel @@ -14,7 +14,7 @@ go_library( "//beacon-chain/core/altair:go_default_library", "//beacon-chain/core/blocks:go_default_library", "//beacon-chain/core/validators:go_default_library", - "//beacon-chain/rpc/blockfetcher:go_default_library", + "//beacon-chain/rpc/lookup:go_default_library", "//beacon-chain/state/stategen:go_default_library", "//consensus-types/blocks:go_default_library", "//consensus-types/interfaces:go_default_library", diff --git a/beacon-chain/rpc/eth/rewards/handlers.go b/beacon-chain/rpc/eth/rewards/handlers.go index 1a72b5a69fff..71e0ef0ed061 100644 --- a/beacon-chain/rpc/eth/rewards/handlers.go +++ b/beacon-chain/rpc/eth/rewards/handlers.go @@ -8,7 +8,7 @@ import ( "github.com/prysmaticlabs/prysm/v4/beacon-chain/core/altair" coreblocks "github.com/prysmaticlabs/prysm/v4/beacon-chain/core/blocks" "github.com/prysmaticlabs/prysm/v4/beacon-chain/core/validators" - "github.com/prysmaticlabs/prysm/v4/beacon-chain/rpc/blockfetcher" + "github.com/prysmaticlabs/prysm/v4/beacon-chain/rpc/lookup" "github.com/prysmaticlabs/prysm/v4/consensus-types/blocks" "github.com/prysmaticlabs/prysm/v4/consensus-types/interfaces" "github.com/prysmaticlabs/prysm/v4/network" @@ -167,7 +167,7 @@ func (s *Server) BlockRewards(w http.ResponseWriter, r *http.Request) { } func handleGetBlockError(blk interfaces.ReadOnlySignedBeaconBlock, err error) *network.DefaultErrorJson { - if errors.Is(err, blockfetcher.BlockIdParseError{}) { + if errors.Is(err, lookup.BlockIdParseError{}) { return &network.DefaultErrorJson{ Message: errors.Wrapf(err, "invalid block ID").Error(), Code: http.StatusBadRequest, diff --git a/beacon-chain/rpc/eth/rewards/server.go b/beacon-chain/rpc/eth/rewards/server.go index 56f8aebe04ea..110a75588e64 100644 --- a/beacon-chain/rpc/eth/rewards/server.go +++ b/beacon-chain/rpc/eth/rewards/server.go @@ -2,12 +2,12 @@ package rewards import ( "github.com/prysmaticlabs/prysm/v4/beacon-chain/blockchain" - "github.com/prysmaticlabs/prysm/v4/beacon-chain/rpc/blockfetcher" + "github.com/prysmaticlabs/prysm/v4/beacon-chain/rpc/lookup" "github.com/prysmaticlabs/prysm/v4/beacon-chain/state/stategen" ) type Server struct { - BlockFetcher blockfetcher.Fetcher + BlockFetcher lookup.Fetcher OptimisticModeFetcher blockchain.OptimisticModeFetcher FinalizationFetcher blockchain.FinalizationFetcher ReplayerBuilder stategen.ReplayerBuilder diff --git a/beacon-chain/rpc/lookup/BUILD.bazel b/beacon-chain/rpc/lookup/BUILD.bazel index ca8c5a19f5dc..a5ddc0876733 100644 --- a/beacon-chain/rpc/lookup/BUILD.bazel +++ b/beacon-chain/rpc/lookup/BUILD.bazel @@ -2,7 +2,10 @@ load("@prysm//tools/go:def.bzl", "go_library", "go_test") go_library( name = "go_default_library", - srcs = ["stater.go"], + srcs = [ + "fetcher.go", + "stater.go", + ], importpath = "github.com/prysmaticlabs/prysm/v4/beacon-chain/rpc/lookup", visibility = ["//visibility:public"], deps = [ @@ -12,6 +15,7 @@ go_library( "//beacon-chain/state/stategen:go_default_library", "//config/params:go_default_library", "//consensus-types/blocks:go_default_library", + "//consensus-types/interfaces:go_default_library", "//consensus-types/primitives:go_default_library", "//encoding/bytesutil:go_default_library", "//time/slots:go_default_library", @@ -22,11 +26,15 @@ go_library( go_test( name = "go_default_test", - srcs = ["stater_test.go"], + srcs = [ + "fetcher_test.go", + "stater_test.go", + ], embed = [":go_default_library"], deps = [ "//beacon-chain/blockchain/testing:go_default_library", "//beacon-chain/db/testing:go_default_library", + "//beacon-chain/rpc/testutil:go_default_library", "//beacon-chain/state/state-native:go_default_library", "//beacon-chain/state/stategen:go_default_library", "//beacon-chain/state/stategen/mock:go_default_library", diff --git a/beacon-chain/rpc/blockfetcher/fetcher.go b/beacon-chain/rpc/lookup/fetcher.go similarity index 99% rename from beacon-chain/rpc/blockfetcher/fetcher.go rename to beacon-chain/rpc/lookup/fetcher.go index 09defdef64d8..d7674d2d9e6d 100644 --- a/beacon-chain/rpc/blockfetcher/fetcher.go +++ b/beacon-chain/rpc/lookup/fetcher.go @@ -1,4 +1,4 @@ -package blockfetcher +package lookup import ( "context" diff --git a/beacon-chain/rpc/blockfetcher/fetcher_test.go b/beacon-chain/rpc/lookup/fetcher_test.go similarity index 99% rename from beacon-chain/rpc/blockfetcher/fetcher_test.go rename to beacon-chain/rpc/lookup/fetcher_test.go index efb7ffb94b79..99a3bb7d76a8 100644 --- a/beacon-chain/rpc/blockfetcher/fetcher_test.go +++ b/beacon-chain/rpc/lookup/fetcher_test.go @@ -1,4 +1,4 @@ -package blockfetcher +package lookup import ( "context" From a1d973a05c033e01a764cd3fe4eff47a60237bd2 Mon Sep 17 00:00:00 2001 From: rkapka Date: Wed, 22 Mar 2023 14:15:39 +0100 Subject: [PATCH 31/40] rename types --- .../rpc/eth/beacon/blinded_blocks_test.go | 28 ++++++------- beacon-chain/rpc/eth/beacon/blocks_test.go | 42 +++++++++---------- beacon-chain/rpc/eth/beacon/server.go | 2 +- beacon-chain/rpc/eth/rewards/handlers_test.go | 2 +- beacon-chain/rpc/eth/rewards/server.go | 2 +- beacon-chain/rpc/lookup/fetcher.go | 10 ++--- beacon-chain/rpc/lookup/fetcher_test.go | 2 +- .../rpc/testutil/mock_block_fetcher.go | 7 ++-- 8 files changed, 48 insertions(+), 47 deletions(-) diff --git a/beacon-chain/rpc/eth/beacon/blinded_blocks_test.go b/beacon-chain/rpc/eth/beacon/blinded_blocks_test.go index e6093ee43d3d..a7b1256654cb 100644 --- a/beacon-chain/rpc/eth/beacon/blinded_blocks_test.go +++ b/beacon-chain/rpc/eth/beacon/blinded_blocks_test.go @@ -35,7 +35,7 @@ func TestServer_GetBlindedBlock(t *testing.T) { bs := &Server{ FinalizationFetcher: &mock.ChainService{}, - BlockFetcher: &testutil.MockBlockFetcher{BlockToReturn: blk}, + BlockFetcher: &testutil.MockBlocker{BlockToReturn: blk}, } expected, err := migration.V1Alpha1ToV1SignedBlock(b) @@ -54,7 +54,7 @@ func TestServer_GetBlindedBlock(t *testing.T) { bs := &Server{ FinalizationFetcher: &mock.ChainService{}, - BlockFetcher: &testutil.MockBlockFetcher{BlockToReturn: blk}, + BlockFetcher: &testutil.MockBlocker{BlockToReturn: blk}, } expected, err := migration.V1Alpha1BeaconBlockAltairToV2(b.Block) @@ -74,7 +74,7 @@ func TestServer_GetBlindedBlock(t *testing.T) { mockChainService := &mock.ChainService{} bs := &Server{ FinalizationFetcher: mockChainService, - BlockFetcher: &testutil.MockBlockFetcher{BlockToReturn: blk}, + BlockFetcher: &testutil.MockBlocker{BlockToReturn: blk}, OptimisticModeFetcher: mockChainService, } @@ -95,7 +95,7 @@ func TestServer_GetBlindedBlock(t *testing.T) { mockChainService := &mock.ChainService{} bs := &Server{ FinalizationFetcher: mockChainService, - BlockFetcher: &testutil.MockBlockFetcher{BlockToReturn: blk}, + BlockFetcher: &testutil.MockBlocker{BlockToReturn: blk}, OptimisticModeFetcher: mockChainService, } @@ -120,7 +120,7 @@ func TestServer_GetBlindedBlock(t *testing.T) { } bs := &Server{ FinalizationFetcher: mockChainService, - BlockFetcher: &testutil.MockBlockFetcher{BlockToReturn: blk}, + BlockFetcher: &testutil.MockBlocker{BlockToReturn: blk}, OptimisticModeFetcher: mockChainService, } @@ -140,7 +140,7 @@ func TestServer_GetBlindedBlock(t *testing.T) { } bs := &Server{ FinalizationFetcher: mockChainService, - BlockFetcher: &testutil.MockBlockFetcher{BlockToReturn: blk}, + BlockFetcher: &testutil.MockBlocker{BlockToReturn: blk}, } resp, err := bs.GetBlindedBlock(ctx, ðpbv1.BlockRequest{BlockId: root[:]}) @@ -159,7 +159,7 @@ func TestServer_GetBlindedBlock(t *testing.T) { } bs := &Server{ FinalizationFetcher: mockChainService, - BlockFetcher: &testutil.MockBlockFetcher{BlockToReturn: blk}, + BlockFetcher: &testutil.MockBlocker{BlockToReturn: blk}, } resp, err := bs.GetBlindedBlock(ctx, ðpbv1.BlockRequest{BlockId: root[:]}) @@ -178,7 +178,7 @@ func TestServer_GetBlindedBlockSSZ(t *testing.T) { bs := &Server{ FinalizationFetcher: &mock.ChainService{}, - BlockFetcher: &testutil.MockBlockFetcher{BlockToReturn: blk}, + BlockFetcher: &testutil.MockBlocker{BlockToReturn: blk}, } expected, err := blk.MarshalSSZ() @@ -196,7 +196,7 @@ func TestServer_GetBlindedBlockSSZ(t *testing.T) { bs := &Server{ FinalizationFetcher: &mock.ChainService{}, - BlockFetcher: &testutil.MockBlockFetcher{BlockToReturn: blk}, + BlockFetcher: &testutil.MockBlocker{BlockToReturn: blk}, } expected, err := blk.MarshalSSZ() @@ -215,7 +215,7 @@ func TestServer_GetBlindedBlockSSZ(t *testing.T) { mockChainService := &mock.ChainService{} bs := &Server{ FinalizationFetcher: mockChainService, - BlockFetcher: &testutil.MockBlockFetcher{BlockToReturn: blk}, + BlockFetcher: &testutil.MockBlocker{BlockToReturn: blk}, OptimisticModeFetcher: mockChainService, } @@ -235,7 +235,7 @@ func TestServer_GetBlindedBlockSSZ(t *testing.T) { mockChainService := &mock.ChainService{} bs := &Server{ FinalizationFetcher: mockChainService, - BlockFetcher: &testutil.MockBlockFetcher{BlockToReturn: blk}, + BlockFetcher: &testutil.MockBlocker{BlockToReturn: blk}, OptimisticModeFetcher: mockChainService, } @@ -259,7 +259,7 @@ func TestServer_GetBlindedBlockSSZ(t *testing.T) { } bs := &Server{ FinalizationFetcher: mockChainService, - BlockFetcher: &testutil.MockBlockFetcher{BlockToReturn: blk}, + BlockFetcher: &testutil.MockBlocker{BlockToReturn: blk}, OptimisticModeFetcher: mockChainService, } @@ -279,7 +279,7 @@ func TestServer_GetBlindedBlockSSZ(t *testing.T) { } bs := &Server{ FinalizationFetcher: mockChainService, - BlockFetcher: &testutil.MockBlockFetcher{BlockToReturn: blk}, + BlockFetcher: &testutil.MockBlocker{BlockToReturn: blk}, } resp, err := bs.GetBlindedBlockSSZ(ctx, ðpbv1.BlockRequest{BlockId: root[:]}) @@ -298,7 +298,7 @@ func TestServer_GetBlindedBlockSSZ(t *testing.T) { } bs := &Server{ FinalizationFetcher: mockChainService, - BlockFetcher: &testutil.MockBlockFetcher{BlockToReturn: blk}, + BlockFetcher: &testutil.MockBlocker{BlockToReturn: blk}, } resp, err := bs.GetBlindedBlockSSZ(ctx, ðpbv1.BlockRequest{BlockId: root[:]}) diff --git a/beacon-chain/rpc/eth/beacon/blocks_test.go b/beacon-chain/rpc/eth/beacon/blocks_test.go index 02460f651cdd..a19f3a0166c9 100644 --- a/beacon-chain/rpc/eth/beacon/blocks_test.go +++ b/beacon-chain/rpc/eth/beacon/blocks_test.go @@ -69,7 +69,7 @@ func TestServer_GetBlockHeader(t *testing.T) { b.Block.StateRoot = bytesutil.PadTo([]byte("stateroot"), 32) sb, err := blocks.NewSignedBeaconBlock(b) require.NoError(t, err) - mockBlockFetcher := &testutil.MockBlockFetcher{BlockToReturn: sb} + mockBlockFetcher := &testutil.MockBlocker{BlockToReturn: sb} t.Run("get header", func(t *testing.T) { mockChainService := &mock.ChainService{ @@ -679,7 +679,7 @@ func TestServer_GetBlock(t *testing.T) { sb, err := blocks.NewSignedBeaconBlock(b) require.NoError(t, err) bs := &Server{ - BlockFetcher: &testutil.MockBlockFetcher{BlockToReturn: sb}, + BlockFetcher: &testutil.MockBlocker{BlockToReturn: sb}, } blk, err := bs.GetBlock(ctx, ðpbv1.BlockRequest{}) @@ -697,7 +697,7 @@ func TestServer_GetBlockV2(t *testing.T) { b.Block.Slot = 123 sb, err := blocks.NewSignedBeaconBlock(b) require.NoError(t, err) - mockBlockFetcher := &testutil.MockBlockFetcher{BlockToReturn: sb} + mockBlockFetcher := &testutil.MockBlocker{BlockToReturn: sb} mockChainService := &mock.ChainService{ FinalizedRoots: map[[32]byte]bool{}, } @@ -721,7 +721,7 @@ func TestServer_GetBlockV2(t *testing.T) { b.Block.Slot = 123 sb, err := blocks.NewSignedBeaconBlock(b) require.NoError(t, err) - mockBlockFetcher := &testutil.MockBlockFetcher{BlockToReturn: sb} + mockBlockFetcher := &testutil.MockBlocker{BlockToReturn: sb} mockChainService := &mock.ChainService{ FinalizedRoots: map[[32]byte]bool{}, } @@ -745,7 +745,7 @@ func TestServer_GetBlockV2(t *testing.T) { b.Block.Slot = 123 sb, err := blocks.NewSignedBeaconBlock(b) require.NoError(t, err) - mockBlockFetcher := &testutil.MockBlockFetcher{BlockToReturn: sb} + mockBlockFetcher := &testutil.MockBlocker{BlockToReturn: sb} mockChainService := &mock.ChainService{ FinalizedRoots: map[[32]byte]bool{}, } @@ -770,7 +770,7 @@ func TestServer_GetBlockV2(t *testing.T) { b.Block.Slot = 123 sb, err := blocks.NewSignedBeaconBlock(b) require.NoError(t, err) - mockBlockFetcher := &testutil.MockBlockFetcher{BlockToReturn: sb} + mockBlockFetcher := &testutil.MockBlocker{BlockToReturn: sb} mockChainService := &mock.ChainService{ FinalizedRoots: map[[32]byte]bool{}, } @@ -796,7 +796,7 @@ func TestServer_GetBlockV2(t *testing.T) { require.NoError(t, err) r, err := sb.Block().HashTreeRoot() require.NoError(t, err) - mockBlockFetcher := &testutil.MockBlockFetcher{BlockToReturn: sb} + mockBlockFetcher := &testutil.MockBlocker{BlockToReturn: sb} mockChainService := &mock.ChainService{ OptimisticRoots: map[[32]byte]bool{r: true}, FinalizedRoots: map[[32]byte]bool{}, @@ -817,7 +817,7 @@ func TestServer_GetBlockV2(t *testing.T) { require.NoError(t, err) r, err := sb.Block().HashTreeRoot() require.NoError(t, err) - mockBlockFetcher := &testutil.MockBlockFetcher{BlockToReturn: sb} + mockBlockFetcher := &testutil.MockBlocker{BlockToReturn: sb} t.Run("true", func(t *testing.T) { mockChainService := &mock.ChainService{FinalizedRoots: map[[32]byte]bool{r: true}} @@ -853,7 +853,7 @@ func TestServer_GetBlockSSZ(t *testing.T) { sb, err := blocks.NewSignedBeaconBlock(b) require.NoError(t, err) bs := &Server{ - BlockFetcher: &testutil.MockBlockFetcher{BlockToReturn: sb}, + BlockFetcher: &testutil.MockBlocker{BlockToReturn: sb}, } resp, err := bs.GetBlockSSZ(ctx, ðpbv1.BlockRequest{}) @@ -878,7 +878,7 @@ func TestServer_GetBlockSSZV2(t *testing.T) { } bs := &Server{ FinalizationFetcher: mockChainService, - BlockFetcher: &testutil.MockBlockFetcher{BlockToReturn: sb}, + BlockFetcher: &testutil.MockBlocker{BlockToReturn: sb}, } resp, err := bs.GetBlockSSZV2(ctx, ðpbv2.BlockRequestV2{}) @@ -900,7 +900,7 @@ func TestServer_GetBlockSSZV2(t *testing.T) { } bs := &Server{ FinalizationFetcher: mockChainService, - BlockFetcher: &testutil.MockBlockFetcher{BlockToReturn: sb}, + BlockFetcher: &testutil.MockBlocker{BlockToReturn: sb}, } resp, err := bs.GetBlockSSZV2(ctx, ðpbv2.BlockRequestV2{}) @@ -923,7 +923,7 @@ func TestServer_GetBlockSSZV2(t *testing.T) { bs := &Server{ OptimisticModeFetcher: mockChainService, FinalizationFetcher: mockChainService, - BlockFetcher: &testutil.MockBlockFetcher{BlockToReturn: sb}, + BlockFetcher: &testutil.MockBlocker{BlockToReturn: sb}, } resp, err := bs.GetBlockSSZV2(ctx, ðpbv2.BlockRequestV2{}) @@ -946,7 +946,7 @@ func TestServer_GetBlockSSZV2(t *testing.T) { bs := &Server{ OptimisticModeFetcher: mockChainService, FinalizationFetcher: mockChainService, - BlockFetcher: &testutil.MockBlockFetcher{BlockToReturn: sb}, + BlockFetcher: &testutil.MockBlocker{BlockToReturn: sb}, } resp, err := bs.GetBlockSSZV2(ctx, ðpbv2.BlockRequestV2{}) @@ -971,7 +971,7 @@ func TestServer_GetBlockSSZV2(t *testing.T) { bs := &Server{ OptimisticModeFetcher: mockChainService, FinalizationFetcher: mockChainService, - BlockFetcher: &testutil.MockBlockFetcher{BlockToReturn: sb}, + BlockFetcher: &testutil.MockBlocker{BlockToReturn: sb}, } resp, err := bs.GetBlockSSZV2(ctx, ðpbv2.BlockRequestV2{}) @@ -984,7 +984,7 @@ func TestServer_GetBlockSSZV2(t *testing.T) { require.NoError(t, err) r, err := sb.Block().HashTreeRoot() require.NoError(t, err) - mockBlockFetcher := &testutil.MockBlockFetcher{BlockToReturn: sb} + mockBlockFetcher := &testutil.MockBlocker{BlockToReturn: sb} t.Run("true", func(t *testing.T) { mockChainService := &mock.ChainService{FinalizedRoots: map[[32]byte]bool{r: true}} @@ -1223,7 +1223,7 @@ func TestServer_ListBlockAttestations(t *testing.T) { } sb, err := blocks.NewSignedBeaconBlock(b) require.NoError(t, err) - mockBlockFetcher := &testutil.MockBlockFetcher{BlockToReturn: sb} + mockBlockFetcher := &testutil.MockBlocker{BlockToReturn: sb} mockChainService := &mock.ChainService{ FinalizedRoots: map[[32]byte]bool{}, } @@ -1280,7 +1280,7 @@ func TestServer_ListBlockAttestations(t *testing.T) { } sb, err := blocks.NewSignedBeaconBlock(b) require.NoError(t, err) - mockBlockFetcher := &testutil.MockBlockFetcher{BlockToReturn: sb} + mockBlockFetcher := &testutil.MockBlocker{BlockToReturn: sb} mockChainService := &mock.ChainService{ FinalizedRoots: map[[32]byte]bool{}, } @@ -1337,7 +1337,7 @@ func TestServer_ListBlockAttestations(t *testing.T) { } sb, err := blocks.NewSignedBeaconBlock(b) require.NoError(t, err) - mockBlockFetcher := &testutil.MockBlockFetcher{BlockToReturn: sb} + mockBlockFetcher := &testutil.MockBlocker{BlockToReturn: sb} mockChainService := &mock.ChainService{ FinalizedRoots: map[[32]byte]bool{}, } @@ -1394,7 +1394,7 @@ func TestServer_ListBlockAttestations(t *testing.T) { } sb, err := blocks.NewSignedBeaconBlock(b) require.NoError(t, err) - mockBlockFetcher := &testutil.MockBlockFetcher{BlockToReturn: sb} + mockBlockFetcher := &testutil.MockBlocker{BlockToReturn: sb} mockChainService := &mock.ChainService{ FinalizedRoots: map[[32]byte]bool{}, } @@ -1417,7 +1417,7 @@ func TestServer_ListBlockAttestations(t *testing.T) { require.NoError(t, err) r, err := sb.Block().HashTreeRoot() require.NoError(t, err) - mockBlockFetcher := &testutil.MockBlockFetcher{BlockToReturn: sb} + mockBlockFetcher := &testutil.MockBlocker{BlockToReturn: sb} mockChainService := &mock.ChainService{ OptimisticRoots: map[[32]byte]bool{r: true}, FinalizedRoots: map[[32]byte]bool{}, @@ -1438,7 +1438,7 @@ func TestServer_ListBlockAttestations(t *testing.T) { require.NoError(t, err) r, err := sb.Block().HashTreeRoot() require.NoError(t, err) - mockBlockFetcher := &testutil.MockBlockFetcher{BlockToReturn: sb} + mockBlockFetcher := &testutil.MockBlocker{BlockToReturn: sb} t.Run("true", func(t *testing.T) { mockChainService := &mock.ChainService{FinalizedRoots: map[[32]byte]bool{r: true}} diff --git a/beacon-chain/rpc/eth/beacon/server.go b/beacon-chain/rpc/eth/beacon/server.go index 4d6c45dd9473..7166508c2f88 100644 --- a/beacon-chain/rpc/eth/beacon/server.go +++ b/beacon-chain/rpc/eth/beacon/server.go @@ -35,7 +35,7 @@ type Server struct { VoluntaryExitsPool voluntaryexits.PoolManager StateGenService stategen.StateManager StateFetcher lookup.Stater - BlockFetcher lookup.Fetcher + BlockFetcher lookup.Blocker HeadFetcher blockchain.HeadFetcher OptimisticModeFetcher blockchain.OptimisticModeFetcher V1Alpha1ValidatorServer *v1alpha1validator.Server diff --git a/beacon-chain/rpc/eth/rewards/handlers_test.go b/beacon-chain/rpc/eth/rewards/handlers_test.go index 6b38b72a15ae..b21a31b224d5 100644 --- a/beacon-chain/rpc/eth/rewards/handlers_test.go +++ b/beacon-chain/rpc/eth/rewards/handlers_test.go @@ -156,7 +156,7 @@ func TestBlockRewards(t *testing.T) { require.NoError(t, err) mockChainService := &mock.ChainService{Optimistic: true} s := &Server{ - BlockFetcher: &testutil.MockBlockFetcher{SlotBlockMap: map[primitives.Slot]interfaces.ReadOnlySignedBeaconBlock{ + BlockFetcher: &testutil.MockBlocker{SlotBlockMap: map[primitives.Slot]interfaces.ReadOnlySignedBeaconBlock{ 0: phase0block, 2: sbb, }}, diff --git a/beacon-chain/rpc/eth/rewards/server.go b/beacon-chain/rpc/eth/rewards/server.go index 110a75588e64..e43eae08a4c8 100644 --- a/beacon-chain/rpc/eth/rewards/server.go +++ b/beacon-chain/rpc/eth/rewards/server.go @@ -7,7 +7,7 @@ import ( ) type Server struct { - BlockFetcher lookup.Fetcher + BlockFetcher lookup.Blocker OptimisticModeFetcher blockchain.OptimisticModeFetcher FinalizationFetcher blockchain.FinalizationFetcher ReplayerBuilder stategen.ReplayerBuilder diff --git a/beacon-chain/rpc/lookup/fetcher.go b/beacon-chain/rpc/lookup/fetcher.go index d7674d2d9e6d..46bb84610b55 100644 --- a/beacon-chain/rpc/lookup/fetcher.go +++ b/beacon-chain/rpc/lookup/fetcher.go @@ -29,13 +29,13 @@ func (e BlockIdParseError) Error() string { return e.message } -// Fetcher is responsible for retrieving info related with the beacon block. -type Fetcher interface { +// Blocker is responsible for retrieving blocks. +type Blocker interface { Block(ctx context.Context, id []byte) (interfaces.ReadOnlySignedBeaconBlock, error) } -// BlockProvider is a real implementation of Fetcher. -type BlockProvider struct { +// BeaconDbBlocker is an implementation of Blocker. It retrieves blocks from the beacon chain database. +type BeaconDbBlocker struct { BeaconDB db.ReadOnlyDatabase ChainInfoFetcher blockchain.ChainInfoFetcher } @@ -47,7 +47,7 @@ type BlockProvider struct { // - "justified" // - // - -func (p *BlockProvider) Block(ctx context.Context, id []byte) (interfaces.ReadOnlySignedBeaconBlock, error) { +func (p *BeaconDbBlocker) Block(ctx context.Context, id []byte) (interfaces.ReadOnlySignedBeaconBlock, error) { var err error var blk interfaces.ReadOnlySignedBeaconBlock switch string(id) { diff --git a/beacon-chain/rpc/lookup/fetcher_test.go b/beacon-chain/rpc/lookup/fetcher_test.go index 99a3bb7d76a8..4cf55e35a6e7 100644 --- a/beacon-chain/rpc/lookup/fetcher_test.go +++ b/beacon-chain/rpc/lookup/fetcher_test.go @@ -46,7 +46,7 @@ func TestGetBlock(t *testing.T) { wsb, err := blocks.NewSignedBeaconBlock(headBlock.Block.(*ethpbalpha.BeaconBlockContainer_Phase0Block).Phase0Block) require.NoError(t, err) - fetcher := &BlockProvider{ + fetcher := &BeaconDbBlocker{ BeaconDB: beaconDB, ChainInfoFetcher: &mock.ChainService{ DB: beaconDB, diff --git a/beacon-chain/rpc/testutil/mock_block_fetcher.go b/beacon-chain/rpc/testutil/mock_block_fetcher.go index ee053c1bdc57..dac5a8851071 100644 --- a/beacon-chain/rpc/testutil/mock_block_fetcher.go +++ b/beacon-chain/rpc/testutil/mock_block_fetcher.go @@ -8,14 +8,15 @@ import ( "github.com/prysmaticlabs/prysm/v4/consensus-types/primitives" ) -// MockBlockFetcher is a fake implementation of blockfetcher.Fetcher. -type MockBlockFetcher struct { +// MockBlocker is a fake implementation of lookup.Blocker. +type MockBlocker struct { BlockToReturn interfaces.ReadOnlySignedBeaconBlock ErrorToReturn error SlotBlockMap map[primitives.Slot]interfaces.ReadOnlySignedBeaconBlock } -func (m *MockBlockFetcher) Block(_ context.Context, b []byte) (interfaces.ReadOnlySignedBeaconBlock, error) { +// Block -- +func (m *MockBlocker) Block(_ context.Context, b []byte) (interfaces.ReadOnlySignedBeaconBlock, error) { if m.ErrorToReturn != nil { return nil, m.ErrorToReturn } From 9788b2171a5028ee77fb70d4381b0d432d921f2f Mon Sep 17 00:00:00 2001 From: rkapka Date: Wed, 22 Mar 2023 14:16:09 +0100 Subject: [PATCH 32/40] rename files --- beacon-chain/rpc/lookup/BUILD.bazel | 4 ++-- beacon-chain/rpc/lookup/{fetcher.go => blocker.go} | 0 beacon-chain/rpc/lookup/{fetcher_test.go => blocker_test.go} | 0 beacon-chain/rpc/testutil/BUILD.bazel | 4 ++-- .../rpc/testutil/{mock_block_fetcher.go => mock_blocker.go} | 0 .../rpc/testutil/{mock_state_fetcher.go => mock_stater.go} | 0 6 files changed, 4 insertions(+), 4 deletions(-) rename beacon-chain/rpc/lookup/{fetcher.go => blocker.go} (100%) rename beacon-chain/rpc/lookup/{fetcher_test.go => blocker_test.go} (100%) rename beacon-chain/rpc/testutil/{mock_block_fetcher.go => mock_blocker.go} (100%) rename beacon-chain/rpc/testutil/{mock_state_fetcher.go => mock_stater.go} (100%) diff --git a/beacon-chain/rpc/lookup/BUILD.bazel b/beacon-chain/rpc/lookup/BUILD.bazel index a5ddc0876733..4b39e7657206 100644 --- a/beacon-chain/rpc/lookup/BUILD.bazel +++ b/beacon-chain/rpc/lookup/BUILD.bazel @@ -3,7 +3,7 @@ load("@prysm//tools/go:def.bzl", "go_library", "go_test") go_library( name = "go_default_library", srcs = [ - "fetcher.go", + "blocker.go", "stater.go", ], importpath = "github.com/prysmaticlabs/prysm/v4/beacon-chain/rpc/lookup", @@ -27,7 +27,7 @@ go_library( go_test( name = "go_default_test", srcs = [ - "fetcher_test.go", + "blocker_test.go", "stater_test.go", ], embed = [":go_default_library"], diff --git a/beacon-chain/rpc/lookup/fetcher.go b/beacon-chain/rpc/lookup/blocker.go similarity index 100% rename from beacon-chain/rpc/lookup/fetcher.go rename to beacon-chain/rpc/lookup/blocker.go diff --git a/beacon-chain/rpc/lookup/fetcher_test.go b/beacon-chain/rpc/lookup/blocker_test.go similarity index 100% rename from beacon-chain/rpc/lookup/fetcher_test.go rename to beacon-chain/rpc/lookup/blocker_test.go diff --git a/beacon-chain/rpc/testutil/BUILD.bazel b/beacon-chain/rpc/testutil/BUILD.bazel index 388becbdf746..27ca73821e29 100644 --- a/beacon-chain/rpc/testutil/BUILD.bazel +++ b/beacon-chain/rpc/testutil/BUILD.bazel @@ -5,10 +5,10 @@ go_library( testonly = True, srcs = [ "db.go", - "mock_block_fetcher.go", + "mock_blocker.go", "mock_exec_chain_info_fetcher.go", "mock_genesis_timefetcher.go", - "mock_state_fetcher.go", + "mock_stater.go", ], importpath = "github.com/prysmaticlabs/prysm/v4/beacon-chain/rpc/testutil", visibility = ["//beacon-chain:__subpackages__"], diff --git a/beacon-chain/rpc/testutil/mock_block_fetcher.go b/beacon-chain/rpc/testutil/mock_blocker.go similarity index 100% rename from beacon-chain/rpc/testutil/mock_block_fetcher.go rename to beacon-chain/rpc/testutil/mock_blocker.go diff --git a/beacon-chain/rpc/testutil/mock_state_fetcher.go b/beacon-chain/rpc/testutil/mock_stater.go similarity index 100% rename from beacon-chain/rpc/testutil/mock_state_fetcher.go rename to beacon-chain/rpc/testutil/mock_stater.go From 589b6e0befd92e961c29775be6edb97273753727 Mon Sep 17 00:00:00 2001 From: rkapka Date: Wed, 22 Mar 2023 14:23:06 +0100 Subject: [PATCH 33/40] rename fields --- beacon-chain/rpc/eth/beacon/blinded_blocks.go | 4 +- .../rpc/eth/beacon/blinded_blocks_test.go | 28 ++++----- beacon-chain/rpc/eth/beacon/blocks.go | 12 ++-- beacon-chain/rpc/eth/beacon/blocks_test.go | 54 ++++++++--------- beacon-chain/rpc/eth/beacon/server.go | 4 +- beacon-chain/rpc/eth/beacon/state.go | 22 +++---- beacon-chain/rpc/eth/beacon/state_test.go | 26 ++++---- beacon-chain/rpc/eth/beacon/sync_committee.go | 2 +- .../rpc/eth/beacon/sync_committee_test.go | 8 +-- beacon-chain/rpc/eth/beacon/validator.go | 16 ++--- beacon-chain/rpc/eth/beacon/validator_test.go | 60 +++++++++---------- beacon-chain/rpc/eth/debug/debug.go | 8 +-- beacon-chain/rpc/eth/debug/debug_test.go | 22 +++---- beacon-chain/rpc/eth/debug/server.go | 2 +- beacon-chain/rpc/eth/rewards/handlers.go | 2 +- beacon-chain/rpc/eth/rewards/handlers_test.go | 2 +- beacon-chain/rpc/eth/rewards/server.go | 2 +- beacon-chain/rpc/eth/validator/server.go | 2 +- beacon-chain/rpc/eth/validator/validator.go | 10 ++-- .../rpc/eth/validator/validator_test.go | 22 +++---- beacon-chain/rpc/service.go | 6 +- 21 files changed, 157 insertions(+), 157 deletions(-) diff --git a/beacon-chain/rpc/eth/beacon/blinded_blocks.go b/beacon-chain/rpc/eth/beacon/blinded_blocks.go index 86c4d76e2fd4..fb13c3d51223 100644 --- a/beacon-chain/rpc/eth/beacon/blinded_blocks.go +++ b/beacon-chain/rpc/eth/beacon/blinded_blocks.go @@ -25,7 +25,7 @@ func (bs *Server) GetBlindedBlock(ctx context.Context, req *ethpbv1.BlockRequest ctx, span := trace.StartSpan(ctx, "beacon.GetBlindedBlock") defer span.End() - blk, err := bs.BlockFetcher.Block(ctx, req.BlockId) + blk, err := bs.Blocker.Block(ctx, req.BlockId) err = handleGetBlockError(blk, err) if err != nil { return nil, err @@ -80,7 +80,7 @@ func (bs *Server) GetBlindedBlockSSZ(ctx context.Context, req *ethpbv1.BlockRequ ctx, span := trace.StartSpan(ctx, "beacon.GetBlindedBlockSSZ") defer span.End() - blk, err := bs.BlockFetcher.Block(ctx, req.BlockId) + blk, err := bs.Blocker.Block(ctx, req.BlockId) err = handleGetBlockError(blk, err) if err != nil { return nil, err diff --git a/beacon-chain/rpc/eth/beacon/blinded_blocks_test.go b/beacon-chain/rpc/eth/beacon/blinded_blocks_test.go index a7b1256654cb..c5b711612c60 100644 --- a/beacon-chain/rpc/eth/beacon/blinded_blocks_test.go +++ b/beacon-chain/rpc/eth/beacon/blinded_blocks_test.go @@ -35,7 +35,7 @@ func TestServer_GetBlindedBlock(t *testing.T) { bs := &Server{ FinalizationFetcher: &mock.ChainService{}, - BlockFetcher: &testutil.MockBlocker{BlockToReturn: blk}, + Blocker: &testutil.MockBlocker{BlockToReturn: blk}, } expected, err := migration.V1Alpha1ToV1SignedBlock(b) @@ -54,7 +54,7 @@ func TestServer_GetBlindedBlock(t *testing.T) { bs := &Server{ FinalizationFetcher: &mock.ChainService{}, - BlockFetcher: &testutil.MockBlocker{BlockToReturn: blk}, + Blocker: &testutil.MockBlocker{BlockToReturn: blk}, } expected, err := migration.V1Alpha1BeaconBlockAltairToV2(b.Block) @@ -74,7 +74,7 @@ func TestServer_GetBlindedBlock(t *testing.T) { mockChainService := &mock.ChainService{} bs := &Server{ FinalizationFetcher: mockChainService, - BlockFetcher: &testutil.MockBlocker{BlockToReturn: blk}, + Blocker: &testutil.MockBlocker{BlockToReturn: blk}, OptimisticModeFetcher: mockChainService, } @@ -95,7 +95,7 @@ func TestServer_GetBlindedBlock(t *testing.T) { mockChainService := &mock.ChainService{} bs := &Server{ FinalizationFetcher: mockChainService, - BlockFetcher: &testutil.MockBlocker{BlockToReturn: blk}, + Blocker: &testutil.MockBlocker{BlockToReturn: blk}, OptimisticModeFetcher: mockChainService, } @@ -120,7 +120,7 @@ func TestServer_GetBlindedBlock(t *testing.T) { } bs := &Server{ FinalizationFetcher: mockChainService, - BlockFetcher: &testutil.MockBlocker{BlockToReturn: blk}, + Blocker: &testutil.MockBlocker{BlockToReturn: blk}, OptimisticModeFetcher: mockChainService, } @@ -140,7 +140,7 @@ func TestServer_GetBlindedBlock(t *testing.T) { } bs := &Server{ FinalizationFetcher: mockChainService, - BlockFetcher: &testutil.MockBlocker{BlockToReturn: blk}, + Blocker: &testutil.MockBlocker{BlockToReturn: blk}, } resp, err := bs.GetBlindedBlock(ctx, ðpbv1.BlockRequest{BlockId: root[:]}) @@ -159,7 +159,7 @@ func TestServer_GetBlindedBlock(t *testing.T) { } bs := &Server{ FinalizationFetcher: mockChainService, - BlockFetcher: &testutil.MockBlocker{BlockToReturn: blk}, + Blocker: &testutil.MockBlocker{BlockToReturn: blk}, } resp, err := bs.GetBlindedBlock(ctx, ðpbv1.BlockRequest{BlockId: root[:]}) @@ -178,7 +178,7 @@ func TestServer_GetBlindedBlockSSZ(t *testing.T) { bs := &Server{ FinalizationFetcher: &mock.ChainService{}, - BlockFetcher: &testutil.MockBlocker{BlockToReturn: blk}, + Blocker: &testutil.MockBlocker{BlockToReturn: blk}, } expected, err := blk.MarshalSSZ() @@ -196,7 +196,7 @@ func TestServer_GetBlindedBlockSSZ(t *testing.T) { bs := &Server{ FinalizationFetcher: &mock.ChainService{}, - BlockFetcher: &testutil.MockBlocker{BlockToReturn: blk}, + Blocker: &testutil.MockBlocker{BlockToReturn: blk}, } expected, err := blk.MarshalSSZ() @@ -215,7 +215,7 @@ func TestServer_GetBlindedBlockSSZ(t *testing.T) { mockChainService := &mock.ChainService{} bs := &Server{ FinalizationFetcher: mockChainService, - BlockFetcher: &testutil.MockBlocker{BlockToReturn: blk}, + Blocker: &testutil.MockBlocker{BlockToReturn: blk}, OptimisticModeFetcher: mockChainService, } @@ -235,7 +235,7 @@ func TestServer_GetBlindedBlockSSZ(t *testing.T) { mockChainService := &mock.ChainService{} bs := &Server{ FinalizationFetcher: mockChainService, - BlockFetcher: &testutil.MockBlocker{BlockToReturn: blk}, + Blocker: &testutil.MockBlocker{BlockToReturn: blk}, OptimisticModeFetcher: mockChainService, } @@ -259,7 +259,7 @@ func TestServer_GetBlindedBlockSSZ(t *testing.T) { } bs := &Server{ FinalizationFetcher: mockChainService, - BlockFetcher: &testutil.MockBlocker{BlockToReturn: blk}, + Blocker: &testutil.MockBlocker{BlockToReturn: blk}, OptimisticModeFetcher: mockChainService, } @@ -279,7 +279,7 @@ func TestServer_GetBlindedBlockSSZ(t *testing.T) { } bs := &Server{ FinalizationFetcher: mockChainService, - BlockFetcher: &testutil.MockBlocker{BlockToReturn: blk}, + Blocker: &testutil.MockBlocker{BlockToReturn: blk}, } resp, err := bs.GetBlindedBlockSSZ(ctx, ðpbv1.BlockRequest{BlockId: root[:]}) @@ -298,7 +298,7 @@ func TestServer_GetBlindedBlockSSZ(t *testing.T) { } bs := &Server{ FinalizationFetcher: mockChainService, - BlockFetcher: &testutil.MockBlocker{BlockToReturn: blk}, + Blocker: &testutil.MockBlocker{BlockToReturn: blk}, } resp, err := bs.GetBlindedBlockSSZ(ctx, ðpbv1.BlockRequest{BlockId: root[:]}) diff --git a/beacon-chain/rpc/eth/beacon/blocks.go b/beacon-chain/rpc/eth/beacon/blocks.go index b4e8b46e6a53..45151955af06 100644 --- a/beacon-chain/rpc/eth/beacon/blocks.go +++ b/beacon-chain/rpc/eth/beacon/blocks.go @@ -85,7 +85,7 @@ func (bs *Server) GetBlockHeader(ctx context.Context, req *ethpbv1.BlockRequest) ctx, span := trace.StartSpan(ctx, "beacon.GetBlockHeader") defer span.End() - blk, err := bs.BlockFetcher.Block(ctx, req.BlockId) + blk, err := bs.Blocker.Block(ctx, req.BlockId) err = handleGetBlockError(blk, err) if err != nil { return nil, err @@ -274,7 +274,7 @@ func (bs *Server) GetBlock(ctx context.Context, req *ethpbv1.BlockRequest) (*eth ctx, span := trace.StartSpan(ctx, "beacon.GetBlock") defer span.End() - blk, err := bs.BlockFetcher.Block(ctx, req.BlockId) + blk, err := bs.Blocker.Block(ctx, req.BlockId) err = handleGetBlockError(blk, err) if err != nil { return nil, err @@ -298,7 +298,7 @@ func (bs *Server) GetBlockSSZ(ctx context.Context, req *ethpbv1.BlockRequest) (* ctx, span := trace.StartSpan(ctx, "beacon.GetBlockSSZ") defer span.End() - blk, err := bs.BlockFetcher.Block(ctx, req.BlockId) + blk, err := bs.Blocker.Block(ctx, req.BlockId) err = handleGetBlockError(blk, err) if err != nil { return nil, err @@ -320,7 +320,7 @@ func (bs *Server) GetBlockV2(ctx context.Context, req *ethpbv2.BlockRequestV2) ( ctx, span := trace.StartSpan(ctx, "beacon.GetBlockV2") defer span.End() - blk, err := bs.BlockFetcher.Block(ctx, req.BlockId) + blk, err := bs.Blocker.Block(ctx, req.BlockId) err = handleGetBlockError(blk, err) if err != nil { return nil, err @@ -374,7 +374,7 @@ func (bs *Server) GetBlockSSZV2(ctx context.Context, req *ethpbv2.BlockRequestV2 ctx, span := trace.StartSpan(ctx, "beacon.GetBlockSSZV2") defer span.End() - blk, err := bs.BlockFetcher.Block(ctx, req.BlockId) + blk, err := bs.Blocker.Block(ctx, req.BlockId) err = handleGetBlockError(blk, err) if err != nil { return nil, err @@ -516,7 +516,7 @@ func (bs *Server) ListBlockAttestations(ctx context.Context, req *ethpbv1.BlockR ctx, span := trace.StartSpan(ctx, "beacon.ListBlockAttestations") defer span.End() - blk, err := bs.BlockFetcher.Block(ctx, req.BlockId) + blk, err := bs.Blocker.Block(ctx, req.BlockId) err = handleGetBlockError(blk, err) if err != nil { return nil, err diff --git a/beacon-chain/rpc/eth/beacon/blocks_test.go b/beacon-chain/rpc/eth/beacon/blocks_test.go index a19f3a0166c9..ee8a86cb63df 100644 --- a/beacon-chain/rpc/eth/beacon/blocks_test.go +++ b/beacon-chain/rpc/eth/beacon/blocks_test.go @@ -79,7 +79,7 @@ func TestServer_GetBlockHeader(t *testing.T) { ChainInfoFetcher: mockChainService, OptimisticModeFetcher: mockChainService, FinalizationFetcher: mockChainService, - BlockFetcher: mockBlockFetcher, + Blocker: mockBlockFetcher, } header, err := bs.GetBlockHeader(ctx, ðpbv1.BlockRequest{}) @@ -119,7 +119,7 @@ func TestServer_GetBlockHeader(t *testing.T) { ChainInfoFetcher: mockChainService, OptimisticModeFetcher: mockChainService, FinalizationFetcher: mockChainService, - BlockFetcher: mockBlockFetcher, + Blocker: mockBlockFetcher, } header, err := bs.GetBlockHeader(ctx, ðpbv1.BlockRequest{BlockId: []byte("head")}) require.NoError(t, err) @@ -136,7 +136,7 @@ func TestServer_GetBlockHeader(t *testing.T) { ChainInfoFetcher: mockChainService, OptimisticModeFetcher: mockChainService, FinalizationFetcher: mockChainService, - BlockFetcher: mockBlockFetcher, + Blocker: mockBlockFetcher, } header, err := bs.GetBlockHeader(ctx, ðpbv1.BlockRequest{BlockId: r[:]}) @@ -149,7 +149,7 @@ func TestServer_GetBlockHeader(t *testing.T) { ChainInfoFetcher: mockChainService, OptimisticModeFetcher: mockChainService, FinalizationFetcher: mockChainService, - BlockFetcher: mockBlockFetcher, + Blocker: mockBlockFetcher, } header, err := bs.GetBlockHeader(ctx, ðpbv1.BlockRequest{BlockId: r[:]}) @@ -679,7 +679,7 @@ func TestServer_GetBlock(t *testing.T) { sb, err := blocks.NewSignedBeaconBlock(b) require.NoError(t, err) bs := &Server{ - BlockFetcher: &testutil.MockBlocker{BlockToReturn: sb}, + Blocker: &testutil.MockBlocker{BlockToReturn: sb}, } blk, err := bs.GetBlock(ctx, ðpbv1.BlockRequest{}) @@ -703,7 +703,7 @@ func TestServer_GetBlockV2(t *testing.T) { } bs := &Server{ FinalizationFetcher: mockChainService, - BlockFetcher: mockBlockFetcher, + Blocker: mockBlockFetcher, } blk, err := bs.GetBlockV2(ctx, ðpbv2.BlockRequestV2{}) @@ -727,7 +727,7 @@ func TestServer_GetBlockV2(t *testing.T) { } bs := &Server{ FinalizationFetcher: mockChainService, - BlockFetcher: mockBlockFetcher, + Blocker: mockBlockFetcher, } blk, err := bs.GetBlockV2(ctx, ðpbv2.BlockRequestV2{}) @@ -752,7 +752,7 @@ func TestServer_GetBlockV2(t *testing.T) { bs := &Server{ OptimisticModeFetcher: mockChainService, FinalizationFetcher: mockChainService, - BlockFetcher: mockBlockFetcher, + Blocker: mockBlockFetcher, } blk, err := bs.GetBlockV2(ctx, ðpbv2.BlockRequestV2{}) @@ -777,7 +777,7 @@ func TestServer_GetBlockV2(t *testing.T) { bs := &Server{ OptimisticModeFetcher: mockChainService, FinalizationFetcher: mockChainService, - BlockFetcher: mockBlockFetcher, + Blocker: mockBlockFetcher, } blk, err := bs.GetBlockV2(ctx, ðpbv2.BlockRequestV2{}) @@ -804,7 +804,7 @@ func TestServer_GetBlockV2(t *testing.T) { bs := &Server{ OptimisticModeFetcher: mockChainService, FinalizationFetcher: mockChainService, - BlockFetcher: mockBlockFetcher, + Blocker: mockBlockFetcher, } blk, err := bs.GetBlockV2(ctx, ðpbv2.BlockRequestV2{}) @@ -824,7 +824,7 @@ func TestServer_GetBlockV2(t *testing.T) { bs := &Server{ OptimisticModeFetcher: mockChainService, FinalizationFetcher: mockChainService, - BlockFetcher: mockBlockFetcher, + Blocker: mockBlockFetcher, } header, err := bs.GetBlockV2(ctx, ðpbv2.BlockRequestV2{BlockId: r[:]}) @@ -836,7 +836,7 @@ func TestServer_GetBlockV2(t *testing.T) { bs := &Server{ OptimisticModeFetcher: mockChainService, FinalizationFetcher: mockChainService, - BlockFetcher: mockBlockFetcher, + Blocker: mockBlockFetcher, } resp, err := bs.GetBlockV2(ctx, ðpbv2.BlockRequestV2{BlockId: r[:]}) @@ -853,7 +853,7 @@ func TestServer_GetBlockSSZ(t *testing.T) { sb, err := blocks.NewSignedBeaconBlock(b) require.NoError(t, err) bs := &Server{ - BlockFetcher: &testutil.MockBlocker{BlockToReturn: sb}, + Blocker: &testutil.MockBlocker{BlockToReturn: sb}, } resp, err := bs.GetBlockSSZ(ctx, ðpbv1.BlockRequest{}) @@ -878,7 +878,7 @@ func TestServer_GetBlockSSZV2(t *testing.T) { } bs := &Server{ FinalizationFetcher: mockChainService, - BlockFetcher: &testutil.MockBlocker{BlockToReturn: sb}, + Blocker: &testutil.MockBlocker{BlockToReturn: sb}, } resp, err := bs.GetBlockSSZV2(ctx, ðpbv2.BlockRequestV2{}) @@ -900,7 +900,7 @@ func TestServer_GetBlockSSZV2(t *testing.T) { } bs := &Server{ FinalizationFetcher: mockChainService, - BlockFetcher: &testutil.MockBlocker{BlockToReturn: sb}, + Blocker: &testutil.MockBlocker{BlockToReturn: sb}, } resp, err := bs.GetBlockSSZV2(ctx, ðpbv2.BlockRequestV2{}) @@ -923,7 +923,7 @@ func TestServer_GetBlockSSZV2(t *testing.T) { bs := &Server{ OptimisticModeFetcher: mockChainService, FinalizationFetcher: mockChainService, - BlockFetcher: &testutil.MockBlocker{BlockToReturn: sb}, + Blocker: &testutil.MockBlocker{BlockToReturn: sb}, } resp, err := bs.GetBlockSSZV2(ctx, ðpbv2.BlockRequestV2{}) @@ -946,7 +946,7 @@ func TestServer_GetBlockSSZV2(t *testing.T) { bs := &Server{ OptimisticModeFetcher: mockChainService, FinalizationFetcher: mockChainService, - BlockFetcher: &testutil.MockBlocker{BlockToReturn: sb}, + Blocker: &testutil.MockBlocker{BlockToReturn: sb}, } resp, err := bs.GetBlockSSZV2(ctx, ðpbv2.BlockRequestV2{}) @@ -971,7 +971,7 @@ func TestServer_GetBlockSSZV2(t *testing.T) { bs := &Server{ OptimisticModeFetcher: mockChainService, FinalizationFetcher: mockChainService, - BlockFetcher: &testutil.MockBlocker{BlockToReturn: sb}, + Blocker: &testutil.MockBlocker{BlockToReturn: sb}, } resp, err := bs.GetBlockSSZV2(ctx, ðpbv2.BlockRequestV2{}) @@ -991,7 +991,7 @@ func TestServer_GetBlockSSZV2(t *testing.T) { bs := &Server{ OptimisticModeFetcher: mockChainService, FinalizationFetcher: mockChainService, - BlockFetcher: mockBlockFetcher, + Blocker: mockBlockFetcher, } header, err := bs.GetBlockSSZV2(ctx, ðpbv2.BlockRequestV2{BlockId: r[:]}) @@ -1003,7 +1003,7 @@ func TestServer_GetBlockSSZV2(t *testing.T) { bs := &Server{ OptimisticModeFetcher: mockChainService, FinalizationFetcher: mockChainService, - BlockFetcher: mockBlockFetcher, + Blocker: mockBlockFetcher, } resp, err := bs.GetBlockSSZV2(ctx, ðpbv2.BlockRequestV2{BlockId: r[:]}) @@ -1230,7 +1230,7 @@ func TestServer_ListBlockAttestations(t *testing.T) { bs := &Server{ OptimisticModeFetcher: mockChainService, FinalizationFetcher: mockChainService, - BlockFetcher: mockBlockFetcher, + Blocker: mockBlockFetcher, } resp, err := bs.ListBlockAttestations(ctx, ðpbv1.BlockRequest{}) @@ -1287,7 +1287,7 @@ func TestServer_ListBlockAttestations(t *testing.T) { bs := &Server{ OptimisticModeFetcher: mockChainService, FinalizationFetcher: mockChainService, - BlockFetcher: mockBlockFetcher, + Blocker: mockBlockFetcher, } resp, err := bs.ListBlockAttestations(ctx, ðpbv1.BlockRequest{}) @@ -1344,7 +1344,7 @@ func TestServer_ListBlockAttestations(t *testing.T) { bs := &Server{ OptimisticModeFetcher: mockChainService, FinalizationFetcher: mockChainService, - BlockFetcher: mockBlockFetcher, + Blocker: mockBlockFetcher, } resp, err := bs.ListBlockAttestations(ctx, ðpbv1.BlockRequest{}) @@ -1401,7 +1401,7 @@ func TestServer_ListBlockAttestations(t *testing.T) { bs := &Server{ OptimisticModeFetcher: mockChainService, FinalizationFetcher: mockChainService, - BlockFetcher: mockBlockFetcher, + Blocker: mockBlockFetcher, } resp, err := bs.ListBlockAttestations(ctx, ðpbv1.BlockRequest{}) @@ -1425,7 +1425,7 @@ func TestServer_ListBlockAttestations(t *testing.T) { bs := &Server{ OptimisticModeFetcher: mockChainService, FinalizationFetcher: mockChainService, - BlockFetcher: mockBlockFetcher, + Blocker: mockBlockFetcher, } resp, err := bs.ListBlockAttestations(ctx, ðpbv1.BlockRequest{}) @@ -1445,7 +1445,7 @@ func TestServer_ListBlockAttestations(t *testing.T) { bs := &Server{ OptimisticModeFetcher: mockChainService, FinalizationFetcher: mockChainService, - BlockFetcher: mockBlockFetcher, + Blocker: mockBlockFetcher, } resp, err := bs.ListBlockAttestations(ctx, ðpbv1.BlockRequest{BlockId: r[:]}) @@ -1457,7 +1457,7 @@ func TestServer_ListBlockAttestations(t *testing.T) { bs := &Server{ OptimisticModeFetcher: mockChainService, FinalizationFetcher: mockChainService, - BlockFetcher: mockBlockFetcher, + Blocker: mockBlockFetcher, } resp, err := bs.ListBlockAttestations(ctx, ðpbv1.BlockRequest{BlockId: r[:]}) diff --git a/beacon-chain/rpc/eth/beacon/server.go b/beacon-chain/rpc/eth/beacon/server.go index 7166508c2f88..def50b84b38d 100644 --- a/beacon-chain/rpc/eth/beacon/server.go +++ b/beacon-chain/rpc/eth/beacon/server.go @@ -34,8 +34,8 @@ type Server struct { SlashingsPool slashings.PoolManager VoluntaryExitsPool voluntaryexits.PoolManager StateGenService stategen.StateManager - StateFetcher lookup.Stater - BlockFetcher lookup.Blocker + Stater lookup.Stater + Blocker lookup.Blocker HeadFetcher blockchain.HeadFetcher OptimisticModeFetcher blockchain.OptimisticModeFetcher V1Alpha1ValidatorServer *v1alpha1validator.Server diff --git a/beacon-chain/rpc/eth/beacon/state.go b/beacon-chain/rpc/eth/beacon/state.go index 9bfd6aa2e813..a057d274e6e1 100644 --- a/beacon-chain/rpc/eth/beacon/state.go +++ b/beacon-chain/rpc/eth/beacon/state.go @@ -58,7 +58,7 @@ func (bs *Server) GetStateRoot(ctx context.Context, req *ethpb.StateRequest) (*e ctx, span := trace.StartSpan(ctx, "beacon.GetStateRoot") defer span.End() - stateRoot, err := bs.StateFetcher.StateRoot(ctx, req.StateId) + stateRoot, err := bs.Stater.StateRoot(ctx, req.StateId) if err != nil { if rootNotFoundErr, ok := err.(*lookup.StateRootNotFoundError); ok { return nil, status.Errorf(codes.NotFound, "State root not found: %v", rootNotFoundErr) @@ -67,11 +67,11 @@ func (bs *Server) GetStateRoot(ctx context.Context, req *ethpb.StateRequest) (*e } return nil, status.Errorf(codes.Internal, "Could not get state root: %v", err) } - st, err := bs.StateFetcher.State(ctx, req.StateId) + st, err := bs.Stater.State(ctx, req.StateId) if err != nil { return nil, status.Errorf(codes.Internal, "Could not get state: %v", err) } - isOptimistic, err := helpers.IsOptimistic(ctx, req.StateId, bs.OptimisticModeFetcher, bs.StateFetcher, bs.ChainInfoFetcher, bs.BeaconDB) + isOptimistic, err := helpers.IsOptimistic(ctx, req.StateId, bs.OptimisticModeFetcher, bs.Stater, bs.ChainInfoFetcher, bs.BeaconDB) if err != nil { return nil, status.Errorf(codes.Internal, "Could not check if slot's block is optimistic: %v", err) } @@ -95,12 +95,12 @@ func (bs *Server) GetStateFork(ctx context.Context, req *ethpb.StateRequest) (*e ctx, span := trace.StartSpan(ctx, "beacon.GetStateFork") defer span.End() - st, err := bs.StateFetcher.State(ctx, req.StateId) + st, err := bs.Stater.State(ctx, req.StateId) if err != nil { return nil, helpers.PrepareStateFetchGRPCError(err) } fork := st.Fork() - isOptimistic, err := helpers.IsOptimistic(ctx, req.StateId, bs.OptimisticModeFetcher, bs.StateFetcher, bs.ChainInfoFetcher, bs.BeaconDB) + isOptimistic, err := helpers.IsOptimistic(ctx, req.StateId, bs.OptimisticModeFetcher, bs.Stater, bs.ChainInfoFetcher, bs.BeaconDB) if err != nil { return nil, status.Errorf(codes.Internal, "Could not check if slot's block is optimistic: %v", err) } @@ -127,11 +127,11 @@ func (bs *Server) GetFinalityCheckpoints(ctx context.Context, req *ethpb.StateRe ctx, span := trace.StartSpan(ctx, "beacon.GetFinalityCheckpoints") defer span.End() - st, err := bs.StateFetcher.State(ctx, req.StateId) + st, err := bs.Stater.State(ctx, req.StateId) if err != nil { return nil, helpers.PrepareStateFetchGRPCError(err) } - isOptimistic, err := helpers.IsOptimistic(ctx, req.StateId, bs.OptimisticModeFetcher, bs.StateFetcher, bs.ChainInfoFetcher, bs.BeaconDB) + isOptimistic, err := helpers.IsOptimistic(ctx, req.StateId, bs.OptimisticModeFetcher, bs.Stater, bs.ChainInfoFetcher, bs.BeaconDB) if err != nil { return nil, status.Errorf(codes.Internal, "Could not check if slot's block is optimistic: %v", err) } @@ -160,7 +160,7 @@ func (bs *Server) GetRandao(ctx context.Context, req *eth2.RandaoRequest) (*eth2 ctx, span := trace.StartSpan(ctx, "beacon.GetRandao") defer span.End() - st, err := bs.StateFetcher.State(ctx, req.StateId) + st, err := bs.Stater.State(ctx, req.StateId) if err != nil { return nil, helpers.PrepareStateFetchGRPCError(err) } @@ -186,7 +186,7 @@ func (bs *Server) GetRandao(ctx context.Context, req *eth2.RandaoRequest) (*eth2 return nil, status.Errorf(codes.Internal, "Could not get randao mix at index %d", idx) } - isOptimistic, err := helpers.IsOptimistic(ctx, req.StateId, bs.OptimisticModeFetcher, bs.StateFetcher, bs.ChainInfoFetcher, bs.BeaconDB) + isOptimistic, err := helpers.IsOptimistic(ctx, req.StateId, bs.OptimisticModeFetcher, bs.Stater, bs.ChainInfoFetcher, bs.BeaconDB) if err != nil { return nil, status.Errorf(codes.Internal, "Could not check if slot's block is optimistic: %v", err) } @@ -215,14 +215,14 @@ func (bs *Server) stateFromRequest(ctx context.Context, req *stateRequest) (stat err, ) } - st, err := bs.StateFetcher.State(ctx, []byte(strconv.FormatUint(uint64(slot), 10))) + st, err := bs.Stater.State(ctx, []byte(strconv.FormatUint(uint64(slot), 10))) if err != nil { return nil, helpers.PrepareStateFetchGRPCError(err) } return st, nil } var err error - st, err := bs.StateFetcher.State(ctx, req.stateId) + st, err := bs.Stater.State(ctx, req.stateId) if err != nil { return nil, helpers.PrepareStateFetchGRPCError(err) } diff --git a/beacon-chain/rpc/eth/beacon/state_test.go b/beacon-chain/rpc/eth/beacon/state_test.go index 839a26cdbf16..97960ca8f193 100644 --- a/beacon-chain/rpc/eth/beacon/state_test.go +++ b/beacon-chain/rpc/eth/beacon/state_test.go @@ -83,7 +83,7 @@ func TestGetStateRoot(t *testing.T) { chainService := &chainMock.ChainService{} server := &Server{ - StateFetcher: &testutil.MockStater{ + Stater: &testutil.MockStater{ BeaconStateRoot: stateRoot[:], BeaconState: fakeState, }, @@ -111,7 +111,7 @@ func TestGetStateRoot(t *testing.T) { chainService := &chainMock.ChainService{Optimistic: true} server := &Server{ - StateFetcher: &testutil.MockStater{ + Stater: &testutil.MockStater{ BeaconStateRoot: stateRoot[:], BeaconState: fakeState, }, @@ -145,7 +145,7 @@ func TestGetStateRoot(t *testing.T) { }, } server := &Server{ - StateFetcher: &testutil.MockStater{ + Stater: &testutil.MockStater{ BeaconStateRoot: stateRoot[:], BeaconState: fakeState, }, @@ -179,7 +179,7 @@ func TestGetStateFork(t *testing.T) { chainService := &chainMock.ChainService{} server := &Server{ - StateFetcher: &testutil.MockStater{ + Stater: &testutil.MockStater{ BeaconState: fakeState, }, HeadFetcher: chainService, @@ -209,7 +209,7 @@ func TestGetStateFork(t *testing.T) { chainService := &chainMock.ChainService{Optimistic: true} server := &Server{ - StateFetcher: &testutil.MockStater{ + Stater: &testutil.MockStater{ BeaconState: fakeState, }, HeadFetcher: chainService, @@ -242,7 +242,7 @@ func TestGetStateFork(t *testing.T) { }, } server := &Server{ - StateFetcher: &testutil.MockStater{ + Stater: &testutil.MockStater{ BeaconState: fakeState, }, HeadFetcher: chainService, @@ -282,7 +282,7 @@ func TestGetFinalityCheckpoints(t *testing.T) { chainService := &chainMock.ChainService{} server := &Server{ - StateFetcher: &testutil.MockStater{ + Stater: &testutil.MockStater{ BeaconState: fakeState, }, HeadFetcher: chainService, @@ -314,7 +314,7 @@ func TestGetFinalityCheckpoints(t *testing.T) { chainService := &chainMock.ChainService{Optimistic: true} server := &Server{ - StateFetcher: &testutil.MockStater{ + Stater: &testutil.MockStater{ BeaconState: fakeState, }, HeadFetcher: chainService, @@ -347,7 +347,7 @@ func TestGetFinalityCheckpoints(t *testing.T) { }, } server := &Server{ - StateFetcher: &testutil.MockStater{ + Stater: &testutil.MockStater{ BeaconState: fakeState, }, HeadFetcher: chainService, @@ -388,7 +388,7 @@ func TestGetRandao(t *testing.T) { db := dbTest.SetupDB(t) chainService := &chainMock.ChainService{} server := &Server{ - StateFetcher: &testutil.MockStater{ + Stater: &testutil.MockStater{ BeaconState: st, }, HeadFetcher: chainService, @@ -413,7 +413,7 @@ func TestGetRandao(t *testing.T) { assert.DeepEqual(t, mixOld, resp.Data.Randao) }) t.Run("head state below `EpochsPerHistoricalVector`", func(t *testing.T) { - server.StateFetcher = &testutil.MockStater{ + server.Stater = &testutil.MockStater{ BeaconState: headSt, } resp, err := server.GetRandao(ctx, ð2.RandaoRequest{StateId: []byte("head")}) @@ -441,7 +441,7 @@ func TestGetRandao(t *testing.T) { chainService := &chainMock.ChainService{Optimistic: true} server := &Server{ - StateFetcher: &testutil.MockStater{ + Stater: &testutil.MockStater{ BeaconState: st, }, HeadFetcher: chainService, @@ -473,7 +473,7 @@ func TestGetRandao(t *testing.T) { }, } server := &Server{ - StateFetcher: &testutil.MockStater{ + Stater: &testutil.MockStater{ BeaconState: st, }, HeadFetcher: chainService, diff --git a/beacon-chain/rpc/eth/beacon/sync_committee.go b/beacon-chain/rpc/eth/beacon/sync_committee.go index 266e2085a9d1..9a414d082d9a 100644 --- a/beacon-chain/rpc/eth/beacon/sync_committee.go +++ b/beacon-chain/rpc/eth/beacon/sync_committee.go @@ -91,7 +91,7 @@ func (bs *Server) ListSyncCommittees(ctx context.Context, req *ethpbv2.StateSync return nil, status.Errorf(codes.Internal, "Could not extract sync subcommittees: %v", err) } - isOptimistic, err := helpers.IsOptimistic(ctx, req.StateId, bs.OptimisticModeFetcher, bs.StateFetcher, bs.ChainInfoFetcher, bs.BeaconDB) + isOptimistic, err := helpers.IsOptimistic(ctx, req.StateId, bs.OptimisticModeFetcher, bs.Stater, bs.ChainInfoFetcher, bs.BeaconDB) if err != nil { return nil, status.Errorf(codes.Internal, "Could not check if slot's block is optimistic: %v", err) } diff --git a/beacon-chain/rpc/eth/beacon/sync_committee_test.go b/beacon-chain/rpc/eth/beacon/sync_committee_test.go index dbee74f4072f..5d08c19356b6 100644 --- a/beacon-chain/rpc/eth/beacon/sync_committee_test.go +++ b/beacon-chain/rpc/eth/beacon/sync_committee_test.go @@ -167,7 +167,7 @@ func TestListSyncCommittees(t *testing.T) { GenesisTimeFetcher: &testutil.MockGenesisTimeFetcher{ Genesis: time.Now(), }, - StateFetcher: &testutil.MockStater{ + Stater: &testutil.MockStater{ BeaconState: st, }, HeadFetcher: chainService, @@ -213,7 +213,7 @@ func TestListSyncCommittees(t *testing.T) { GenesisTimeFetcher: &testutil.MockGenesisTimeFetcher{ Genesis: time.Now(), }, - StateFetcher: &testutil.MockStater{ + Stater: &testutil.MockStater{ BeaconState: st, }, HeadFetcher: chainService, @@ -249,7 +249,7 @@ func TestListSyncCommittees(t *testing.T) { GenesisTimeFetcher: &testutil.MockGenesisTimeFetcher{ Genesis: time.Now(), }, - StateFetcher: &testutil.MockStater{ + Stater: &testutil.MockStater{ BeaconState: st, }, HeadFetcher: chainService, @@ -309,7 +309,7 @@ func TestListSyncCommitteesFuture(t *testing.T) { GenesisTimeFetcher: &testutil.MockGenesisTimeFetcher{ Genesis: time.Now(), }, - StateFetcher: &futureSyncMockFetcher{ + Stater: &futureSyncMockFetcher{ BeaconState: st, }, HeadFetcher: chainService, diff --git a/beacon-chain/rpc/eth/beacon/validator.go b/beacon-chain/rpc/eth/beacon/validator.go index bb808aebf10c..c79d7e2bc474 100644 --- a/beacon-chain/rpc/eth/beacon/validator.go +++ b/beacon-chain/rpc/eth/beacon/validator.go @@ -42,7 +42,7 @@ func (bs *Server) GetValidator(ctx context.Context, req *ethpb.StateValidatorReq ctx, span := trace.StartSpan(ctx, "beacon.GetValidator") defer span.End() - st, err := bs.StateFetcher.State(ctx, req.StateId) + st, err := bs.Stater.State(ctx, req.StateId) if err != nil { return nil, helpers.PrepareStateFetchGRPCError(err) } @@ -57,7 +57,7 @@ func (bs *Server) GetValidator(ctx context.Context, req *ethpb.StateValidatorReq return nil, status.Error(codes.NotFound, "Could not find validator") } - isOptimistic, err := helpers.IsOptimistic(ctx, req.StateId, bs.OptimisticModeFetcher, bs.StateFetcher, bs.ChainInfoFetcher, bs.BeaconDB) + isOptimistic, err := helpers.IsOptimistic(ctx, req.StateId, bs.OptimisticModeFetcher, bs.Stater, bs.ChainInfoFetcher, bs.BeaconDB) if err != nil { return nil, status.Errorf(codes.Internal, "Could not check if slot's block is optimistic: %v", err) } @@ -76,7 +76,7 @@ func (bs *Server) ListValidators(ctx context.Context, req *ethpb.StateValidators ctx, span := trace.StartSpan(ctx, "beacon.ListValidators") defer span.End() - st, err := bs.StateFetcher.State(ctx, req.StateId) + st, err := bs.Stater.State(ctx, req.StateId) if err != nil { return nil, helpers.PrepareStateFetchGRPCError(err) } @@ -86,7 +86,7 @@ func (bs *Server) ListValidators(ctx context.Context, req *ethpb.StateValidators return nil, handleValContainerErr(err) } - isOptimistic, err := helpers.IsOptimistic(ctx, req.StateId, bs.OptimisticModeFetcher, bs.StateFetcher, bs.ChainInfoFetcher, bs.BeaconDB) + isOptimistic, err := helpers.IsOptimistic(ctx, req.StateId, bs.OptimisticModeFetcher, bs.Stater, bs.ChainInfoFetcher, bs.BeaconDB) if err != nil { return nil, status.Errorf(codes.Internal, "Could not check if slot's block is optimistic: %v", err) } @@ -138,7 +138,7 @@ func (bs *Server) ListValidatorBalances(ctx context.Context, req *ethpb.Validato ctx, span := trace.StartSpan(ctx, "beacon.ListValidatorBalances") defer span.End() - st, err := bs.StateFetcher.State(ctx, req.StateId) + st, err := bs.Stater.State(ctx, req.StateId) if err != nil { return nil, helpers.PrepareStateFetchGRPCError(err) } @@ -155,7 +155,7 @@ func (bs *Server) ListValidatorBalances(ctx context.Context, req *ethpb.Validato } } - isOptimistic, err := helpers.IsOptimistic(ctx, req.StateId, bs.OptimisticModeFetcher, bs.StateFetcher, bs.ChainInfoFetcher, bs.BeaconDB) + isOptimistic, err := helpers.IsOptimistic(ctx, req.StateId, bs.OptimisticModeFetcher, bs.Stater, bs.ChainInfoFetcher, bs.BeaconDB) if err != nil { return nil, status.Errorf(codes.Internal, "Could not check if slot's block is optimistic: %v", err) } @@ -175,7 +175,7 @@ func (bs *Server) ListCommittees(ctx context.Context, req *ethpb.StateCommittees ctx, span := trace.StartSpan(ctx, "beacon.ListCommittees") defer span.End() - st, err := bs.StateFetcher.State(ctx, req.StateId) + st, err := bs.Stater.State(ctx, req.StateId) if err != nil { return nil, helpers.PrepareStateFetchGRPCError(err) } @@ -220,7 +220,7 @@ func (bs *Server) ListCommittees(ctx context.Context, req *ethpb.StateCommittees } } - isOptimistic, err := helpers.IsOptimistic(ctx, req.StateId, bs.OptimisticModeFetcher, bs.StateFetcher, bs.ChainInfoFetcher, bs.BeaconDB) + isOptimistic, err := helpers.IsOptimistic(ctx, req.StateId, bs.OptimisticModeFetcher, bs.Stater, bs.ChainInfoFetcher, bs.BeaconDB) if err != nil { return nil, status.Errorf(codes.Internal, "Could not check if slot's block is optimistic: %v", err) } diff --git a/beacon-chain/rpc/eth/beacon/validator_test.go b/beacon-chain/rpc/eth/beacon/validator_test.go index e3a1bd8c70c2..bca1f7f61360 100644 --- a/beacon-chain/rpc/eth/beacon/validator_test.go +++ b/beacon-chain/rpc/eth/beacon/validator_test.go @@ -34,7 +34,7 @@ func TestGetValidator(t *testing.T) { t.Run("Head Get Validator by index", func(t *testing.T) { chainService := &chainMock.ChainService{} s := Server{ - StateFetcher: &testutil.MockStater{ + Stater: &testutil.MockStater{ BeaconState: st, }, HeadFetcher: chainService, @@ -54,7 +54,7 @@ func TestGetValidator(t *testing.T) { t.Run("Head Get Validator by pubkey", func(t *testing.T) { chainService := &chainMock.ChainService{} s := Server{ - StateFetcher: &testutil.MockStater{ + Stater: &testutil.MockStater{ BeaconState: st, }, HeadFetcher: chainService, @@ -75,7 +75,7 @@ func TestGetValidator(t *testing.T) { t.Run("Validator ID required", func(t *testing.T) { s := Server{ - StateFetcher: &testutil.MockStater{ + Stater: &testutil.MockStater{ BeaconState: st, }, HeadFetcher: &chainMock.ChainService{}, @@ -98,7 +98,7 @@ func TestGetValidator(t *testing.T) { chainService := &chainMock.ChainService{Optimistic: true} s := Server{ - StateFetcher: &testutil.MockStater{ + Stater: &testutil.MockStater{ BeaconState: st, }, HeadFetcher: chainService, @@ -131,7 +131,7 @@ func TestGetValidator(t *testing.T) { }, } s := Server{ - StateFetcher: &testutil.MockStater{ + Stater: &testutil.MockStater{ BeaconState: st, }, HeadFetcher: chainService, @@ -157,7 +157,7 @@ func TestListValidators(t *testing.T) { t.Run("Head List All Validators", func(t *testing.T) { chainService := &chainMock.ChainService{} s := Server{ - StateFetcher: &testutil.MockStater{ + Stater: &testutil.MockStater{ BeaconState: st, }, HeadFetcher: chainService, @@ -179,7 +179,7 @@ func TestListValidators(t *testing.T) { t.Run("Head List Validators by index", func(t *testing.T) { chainService := &chainMock.ChainService{} s := Server{ - StateFetcher: &testutil.MockStater{ + Stater: &testutil.MockStater{ BeaconState: st, }, HeadFetcher: chainService, @@ -204,7 +204,7 @@ func TestListValidators(t *testing.T) { t.Run("Head List Validators by pubkey", func(t *testing.T) { chainService := &chainMock.ChainService{} s := Server{ - StateFetcher: &testutil.MockStater{ + Stater: &testutil.MockStater{ BeaconState: st, }, HeadFetcher: chainService, @@ -233,7 +233,7 @@ func TestListValidators(t *testing.T) { t.Run("Head List Validators by both index and pubkey", func(t *testing.T) { chainService := &chainMock.ChainService{} s := Server{ - StateFetcher: &testutil.MockStater{ + Stater: &testutil.MockStater{ BeaconState: st, }, HeadFetcher: chainService, @@ -264,7 +264,7 @@ func TestListValidators(t *testing.T) { t.Run("Unknown public key is ignored", func(t *testing.T) { chainService := &chainMock.ChainService{} s := Server{ - StateFetcher: &testutil.MockStater{ + Stater: &testutil.MockStater{ BeaconState: st, }, HeadFetcher: chainService, @@ -287,7 +287,7 @@ func TestListValidators(t *testing.T) { t.Run("Unknown index is ignored", func(t *testing.T) { chainService := &chainMock.ChainService{} s := Server{ - StateFetcher: &testutil.MockStater{ + Stater: &testutil.MockStater{ BeaconState: st, }, HeadFetcher: chainService, @@ -317,7 +317,7 @@ func TestListValidators(t *testing.T) { chainService := &chainMock.ChainService{Optimistic: true} s := Server{ - StateFetcher: &testutil.MockStater{ + Stater: &testutil.MockStater{ BeaconState: st, }, HeadFetcher: chainService, @@ -349,7 +349,7 @@ func TestListValidators(t *testing.T) { }, } s := Server{ - StateFetcher: &testutil.MockStater{ + Stater: &testutil.MockStater{ BeaconState: st, }, HeadFetcher: chainService, @@ -440,7 +440,7 @@ func TestListValidators_Status(t *testing.T) { t.Run("Head List All ACTIVE Validators", func(t *testing.T) { chainService := &chainMock.ChainService{} s := Server{ - StateFetcher: &lookup.BeaconDbStater{ + Stater: &lookup.BeaconDbStater{ ChainInfoFetcher: &chainMock.ChainService{State: st}, }, HeadFetcher: chainService, @@ -478,7 +478,7 @@ func TestListValidators_Status(t *testing.T) { t.Run("Head List All ACTIVE_ONGOING Validators", func(t *testing.T) { chainService := &chainMock.ChainService{} s := Server{ - StateFetcher: &lookup.BeaconDbStater{ + Stater: &lookup.BeaconDbStater{ ChainInfoFetcher: &chainMock.ChainService{State: st}, }, HeadFetcher: chainService, @@ -515,7 +515,7 @@ func TestListValidators_Status(t *testing.T) { t.Run("Head List All EXITED Validators", func(t *testing.T) { chainService := &chainMock.ChainService{} s := Server{ - StateFetcher: &lookup.BeaconDbStater{ + Stater: &lookup.BeaconDbStater{ ChainInfoFetcher: &chainMock.ChainService{State: st}, }, HeadFetcher: chainService, @@ -551,7 +551,7 @@ func TestListValidators_Status(t *testing.T) { t.Run("Head List All PENDING_INITIALIZED and EXITED_UNSLASHED Validators", func(t *testing.T) { chainService := &chainMock.ChainService{} s := Server{ - StateFetcher: &lookup.BeaconDbStater{ + Stater: &lookup.BeaconDbStater{ ChainInfoFetcher: &chainMock.ChainService{State: st}, }, HeadFetcher: chainService, @@ -587,7 +587,7 @@ func TestListValidators_Status(t *testing.T) { t.Run("Head List All PENDING and EXITED Validators", func(t *testing.T) { chainService := &chainMock.ChainService{} s := Server{ - StateFetcher: &lookup.BeaconDbStater{ + Stater: &lookup.BeaconDbStater{ ChainInfoFetcher: &chainMock.ChainService{State: st}, }, HeadFetcher: chainService, @@ -638,7 +638,7 @@ func TestListValidatorBalances(t *testing.T) { t.Run("Head List Validators Balance by index", func(t *testing.T) { chainService := &chainMock.ChainService{} s := Server{ - StateFetcher: &testutil.MockStater{ + Stater: &testutil.MockStater{ BeaconState: st, }, HeadFetcher: chainService, @@ -663,7 +663,7 @@ func TestListValidatorBalances(t *testing.T) { t.Run("Head List Validators Balance by pubkey", func(t *testing.T) { chainService := &chainMock.ChainService{} s := Server{ - StateFetcher: &testutil.MockStater{ + Stater: &testutil.MockStater{ BeaconState: st, }, HeadFetcher: chainService, @@ -691,7 +691,7 @@ func TestListValidatorBalances(t *testing.T) { t.Run("Head List Validators Balance by both index and pubkey", func(t *testing.T) { chainService := &chainMock.ChainService{} s := Server{ - StateFetcher: &testutil.MockStater{ + Stater: &testutil.MockStater{ BeaconState: st, }, HeadFetcher: chainService, @@ -726,7 +726,7 @@ func TestListValidatorBalances(t *testing.T) { chainService := &chainMock.ChainService{Optimistic: true} s := Server{ - StateFetcher: &testutil.MockStater{ + Stater: &testutil.MockStater{ BeaconState: st, }, HeadFetcher: chainService, @@ -761,7 +761,7 @@ func TestListValidatorBalances(t *testing.T) { }, } s := Server{ - StateFetcher: &testutil.MockStater{ + Stater: &testutil.MockStater{ BeaconState: st, }, HeadFetcher: chainService, @@ -791,7 +791,7 @@ func TestListCommittees(t *testing.T) { t.Run("Head All Committees", func(t *testing.T) { chainService := &chainMock.ChainService{} s := Server{ - StateFetcher: &testutil.MockStater{ + Stater: &testutil.MockStater{ BeaconState: st, }, HeadFetcher: chainService, @@ -814,7 +814,7 @@ func TestListCommittees(t *testing.T) { t.Run("Head All Committees of Epoch 10", func(t *testing.T) { chainService := &chainMock.ChainService{} s := Server{ - StateFetcher: &testutil.MockStater{ + Stater: &testutil.MockStater{ BeaconState: st, }, HeadFetcher: chainService, @@ -836,7 +836,7 @@ func TestListCommittees(t *testing.T) { t.Run("Head All Committees of Slot 4", func(t *testing.T) { chainService := &chainMock.ChainService{} s := Server{ - StateFetcher: &testutil.MockStater{ + Stater: &testutil.MockStater{ BeaconState: st, }, HeadFetcher: chainService, @@ -864,7 +864,7 @@ func TestListCommittees(t *testing.T) { t.Run("Head All Committees of Index 1", func(t *testing.T) { chainService := &chainMock.ChainService{} s := Server{ - StateFetcher: &testutil.MockStater{ + Stater: &testutil.MockStater{ BeaconState: st, }, HeadFetcher: chainService, @@ -892,7 +892,7 @@ func TestListCommittees(t *testing.T) { t.Run("Head All Committees of Slot 2, Index 1", func(t *testing.T) { chainService := &chainMock.ChainService{} s := Server{ - StateFetcher: &testutil.MockStater{ + Stater: &testutil.MockStater{ BeaconState: st, }, HeadFetcher: chainService, @@ -928,7 +928,7 @@ func TestListCommittees(t *testing.T) { chainService := &chainMock.ChainService{Optimistic: true} s := Server{ - StateFetcher: &testutil.MockStater{ + Stater: &testutil.MockStater{ BeaconState: st, }, HeadFetcher: chainService, @@ -961,7 +961,7 @@ func TestListCommittees(t *testing.T) { }, } s := Server{ - StateFetcher: &testutil.MockStater{ + Stater: &testutil.MockStater{ BeaconState: st, }, HeadFetcher: chainService, diff --git a/beacon-chain/rpc/eth/debug/debug.go b/beacon-chain/rpc/eth/debug/debug.go index a757f9c01d09..493108f16af0 100644 --- a/beacon-chain/rpc/eth/debug/debug.go +++ b/beacon-chain/rpc/eth/debug/debug.go @@ -19,7 +19,7 @@ func (ds *Server) GetBeaconStateSSZ(ctx context.Context, req *ethpbv1.StateReque ctx, span := trace.StartSpan(ctx, "debug.GetBeaconStateSSZ") defer span.End() - state, err := ds.StateFetcher.State(ctx, req.StateId) + state, err := ds.Stater.State(ctx, req.StateId) if err != nil { return nil, helpers.PrepareStateFetchGRPCError(err) } @@ -37,11 +37,11 @@ func (ds *Server) GetBeaconStateV2(ctx context.Context, req *ethpbv2.BeaconState ctx, span := trace.StartSpan(ctx, "debug.GetBeaconStateV2") defer span.End() - beaconSt, err := ds.StateFetcher.State(ctx, req.StateId) + beaconSt, err := ds.Stater.State(ctx, req.StateId) if err != nil { return nil, helpers.PrepareStateFetchGRPCError(err) } - isOptimistic, err := helpers.IsOptimistic(ctx, req.StateId, ds.OptimisticModeFetcher, ds.StateFetcher, ds.ChainInfoFetcher, ds.BeaconDB) + isOptimistic, err := helpers.IsOptimistic(ctx, req.StateId, ds.OptimisticModeFetcher, ds.Stater, ds.ChainInfoFetcher, ds.BeaconDB) if err != nil { return nil, status.Errorf(codes.Internal, "Could not check if slot's block is optimistic: %v", err) } @@ -114,7 +114,7 @@ func (ds *Server) GetBeaconStateSSZV2(ctx context.Context, req *ethpbv2.BeaconSt ctx, span := trace.StartSpan(ctx, "debug.GetBeaconStateSSZV2") defer span.End() - st, err := ds.StateFetcher.State(ctx, req.StateId) + st, err := ds.Stater.State(ctx, req.StateId) if err != nil { return nil, helpers.PrepareStateFetchGRPCError(err) } diff --git a/beacon-chain/rpc/eth/debug/debug_test.go b/beacon-chain/rpc/eth/debug/debug_test.go index 27d93930da7c..7c772e89baef 100644 --- a/beacon-chain/rpc/eth/debug/debug_test.go +++ b/beacon-chain/rpc/eth/debug/debug_test.go @@ -28,7 +28,7 @@ func TestGetBeaconStateV2(t *testing.T) { fakeState, err := util.NewBeaconState() require.NoError(t, err) server := &Server{ - StateFetcher: &testutil.MockStater{ + Stater: &testutil.MockStater{ BeaconState: fakeState, }, HeadFetcher: &blockchainmock.ChainService{}, @@ -46,7 +46,7 @@ func TestGetBeaconStateV2(t *testing.T) { t.Run("Altair", func(t *testing.T) { fakeState, _ := util.DeterministicGenesisStateAltair(t, 1) server := &Server{ - StateFetcher: &testutil.MockStater{ + Stater: &testutil.MockStater{ BeaconState: fakeState, }, HeadFetcher: &blockchainmock.ChainService{}, @@ -64,7 +64,7 @@ func TestGetBeaconStateV2(t *testing.T) { t.Run("Bellatrix", func(t *testing.T) { fakeState, _ := util.DeterministicGenesisStateBellatrix(t, 1) server := &Server{ - StateFetcher: &testutil.MockStater{ + Stater: &testutil.MockStater{ BeaconState: fakeState, }, HeadFetcher: &blockchainmock.ChainService{}, @@ -82,7 +82,7 @@ func TestGetBeaconStateV2(t *testing.T) { t.Run("Capella", func(t *testing.T) { fakeState, _ := util.DeterministicGenesisStateCapella(t, 1) server := &Server{ - StateFetcher: &testutil.MockStater{ + Stater: &testutil.MockStater{ BeaconState: fakeState, }, HeadFetcher: &blockchainmock.ChainService{}, @@ -108,7 +108,7 @@ func TestGetBeaconStateV2(t *testing.T) { fakeState, _ := util.DeterministicGenesisStateBellatrix(t, 1) server := &Server{ - StateFetcher: &testutil.MockStater{ + Stater: &testutil.MockStater{ BeaconState: fakeState, }, HeadFetcher: &blockchainmock.ChainService{}, @@ -141,7 +141,7 @@ func TestGetBeaconStateV2(t *testing.T) { }, } server := &Server{ - StateFetcher: &testutil.MockStater{ + Stater: &testutil.MockStater{ BeaconState: fakeState, }, HeadFetcher: chainService, @@ -165,7 +165,7 @@ func TestGetBeaconStateSSZ(t *testing.T) { require.NoError(t, err) server := &Server{ - StateFetcher: &testutil.MockStater{ + Stater: &testutil.MockStater{ BeaconState: fakeState, }, } @@ -186,7 +186,7 @@ func TestGetBeaconStateSSZV2(t *testing.T) { require.NoError(t, err) server := &Server{ - StateFetcher: &testutil.MockStater{ + Stater: &testutil.MockStater{ BeaconState: fakeState, }, } @@ -205,7 +205,7 @@ func TestGetBeaconStateSSZV2(t *testing.T) { require.NoError(t, err) server := &Server{ - StateFetcher: &testutil.MockStater{ + Stater: &testutil.MockStater{ BeaconState: fakeState, }, } @@ -224,7 +224,7 @@ func TestGetBeaconStateSSZV2(t *testing.T) { require.NoError(t, err) server := &Server{ - StateFetcher: &testutil.MockStater{ + Stater: &testutil.MockStater{ BeaconState: fakeState, }, } @@ -243,7 +243,7 @@ func TestGetBeaconStateSSZV2(t *testing.T) { require.NoError(t, err) server := &Server{ - StateFetcher: &testutil.MockStater{ + Stater: &testutil.MockStater{ BeaconState: fakeState, }, } diff --git a/beacon-chain/rpc/eth/debug/server.go b/beacon-chain/rpc/eth/debug/server.go index 0378bbace9f3..2c5ccbd0c973 100644 --- a/beacon-chain/rpc/eth/debug/server.go +++ b/beacon-chain/rpc/eth/debug/server.go @@ -14,7 +14,7 @@ import ( type Server struct { BeaconDB db.ReadOnlyDatabase HeadFetcher blockchain.HeadFetcher - StateFetcher lookup.Stater + Stater lookup.Stater OptimisticModeFetcher blockchain.OptimisticModeFetcher ForkFetcher blockchain.ForkFetcher ForkchoiceFetcher blockchain.ForkchoiceFetcher diff --git a/beacon-chain/rpc/eth/rewards/handlers.go b/beacon-chain/rpc/eth/rewards/handlers.go index 71e0ef0ed061..8cec5ca4b346 100644 --- a/beacon-chain/rpc/eth/rewards/handlers.go +++ b/beacon-chain/rpc/eth/rewards/handlers.go @@ -20,7 +20,7 @@ func (s *Server) BlockRewards(w http.ResponseWriter, r *http.Request) { segments := strings.Split(r.URL.Path, "/") blockId := segments[len(segments)-1] - blk, err := s.BlockFetcher.Block(r.Context(), []byte(blockId)) + blk, err := s.Blocker.Block(r.Context(), []byte(blockId)) if errJson := handleGetBlockError(blk, err); errJson != nil { network.WriteError(w, errJson) return diff --git a/beacon-chain/rpc/eth/rewards/handlers_test.go b/beacon-chain/rpc/eth/rewards/handlers_test.go index b21a31b224d5..c855d7b4ad43 100644 --- a/beacon-chain/rpc/eth/rewards/handlers_test.go +++ b/beacon-chain/rpc/eth/rewards/handlers_test.go @@ -156,7 +156,7 @@ func TestBlockRewards(t *testing.T) { require.NoError(t, err) mockChainService := &mock.ChainService{Optimistic: true} s := &Server{ - BlockFetcher: &testutil.MockBlocker{SlotBlockMap: map[primitives.Slot]interfaces.ReadOnlySignedBeaconBlock{ + Blocker: &testutil.MockBlocker{SlotBlockMap: map[primitives.Slot]interfaces.ReadOnlySignedBeaconBlock{ 0: phase0block, 2: sbb, }}, diff --git a/beacon-chain/rpc/eth/rewards/server.go b/beacon-chain/rpc/eth/rewards/server.go index e43eae08a4c8..d1c11fce1983 100644 --- a/beacon-chain/rpc/eth/rewards/server.go +++ b/beacon-chain/rpc/eth/rewards/server.go @@ -7,7 +7,7 @@ import ( ) type Server struct { - BlockFetcher lookup.Blocker + Blocker lookup.Blocker OptimisticModeFetcher blockchain.OptimisticModeFetcher FinalizationFetcher blockchain.FinalizationFetcher ReplayerBuilder stategen.ReplayerBuilder diff --git a/beacon-chain/rpc/eth/validator/server.go b/beacon-chain/rpc/eth/validator/server.go index e28c3417c047..ca3592284058 100644 --- a/beacon-chain/rpc/eth/validator/server.go +++ b/beacon-chain/rpc/eth/validator/server.go @@ -21,7 +21,7 @@ type Server struct { AttestationsPool attestations.Pool PeerManager p2p.PeerManager Broadcaster p2p.Broadcaster - StateFetcher lookup.Stater + Stater lookup.Stater OptimisticModeFetcher blockchain.OptimisticModeFetcher SyncCommitteePool synccommittee.Pool V1Alpha1Server *v1alpha1validator.Server diff --git a/beacon-chain/rpc/eth/validator/validator.go b/beacon-chain/rpc/eth/validator/validator.go index 5e4126d538b2..fd53e41e571f 100644 --- a/beacon-chain/rpc/eth/validator/validator.go +++ b/beacon-chain/rpc/eth/validator/validator.go @@ -70,7 +70,7 @@ func (vs *Server) GetAttesterDuties(ctx context.Context, req *ethpbv1.AttesterDu return nil, status.Errorf(codes.Internal, "Could not get start slot from epoch %d: %v", req.Epoch, err) } - s, err := vs.StateFetcher.StateBySlot(ctx, startSlot) + s, err := vs.Stater.StateBySlot(ctx, startSlot) if err != nil { return nil, status.Errorf(codes.Internal, "Could not get state: %v", err) } @@ -159,7 +159,7 @@ func (vs *Server) GetProposerDuties(ctx context.Context, req *ethpbv1.ProposerDu if err != nil { return nil, status.Errorf(codes.Internal, "Could not get start slot from epoch %d: %v", req.Epoch, err) } - s, err := vs.StateFetcher.StateBySlot(ctx, startSlot) + s, err := vs.Stater.StateBySlot(ctx, startSlot) if err != nil { return nil, status.Errorf(codes.Internal, "Could not get state: %v", err) } @@ -243,7 +243,7 @@ func (vs *Server) GetSyncCommitteeDuties(ctx context.Context, req *ethpbv2.SyncC if err != nil { return nil, status.Errorf(codes.Internal, "Could not get sync committee slot: %v", err) } - st, err := vs.StateFetcher.State(ctx, []byte(strconv.FormatUint(uint64(slot), 10))) + st, err := vs.Stater.State(ctx, []byte(strconv.FormatUint(uint64(slot), 10))) if err != nil { return nil, status.Errorf(codes.Internal, "Could not get sync committee state: %v", err) } @@ -282,7 +282,7 @@ func (vs *Server) GetSyncCommitteeDuties(ctx context.Context, req *ethpbv2.SyncC ctx, []byte(strconv.FormatUint(uint64(slot), 10)), vs.OptimisticModeFetcher, - vs.StateFetcher, + vs.Stater, vs.ChainInfoFetcher, vs.BeaconDB, ) @@ -1081,7 +1081,7 @@ func (vs *Server) GetLiveness(ctx context.Context, req *ethpbv2.GetLivenessReque if err != nil { return nil, status.Error(codes.Internal, "Could not get requested epoch's end slot") } - st, err = vs.StateFetcher.StateBySlot(ctx, epochEnd) + st, err = vs.Stater.StateBySlot(ctx, epochEnd) if err != nil { return nil, status.Error(codes.Internal, "Could not get slot for requested epoch") } diff --git a/beacon-chain/rpc/eth/validator/validator_test.go b/beacon-chain/rpc/eth/validator/validator_test.go index 4d8472a80bcb..d502794a61af 100644 --- a/beacon-chain/rpc/eth/validator/validator_test.go +++ b/beacon-chain/rpc/eth/validator/validator_test.go @@ -93,7 +93,7 @@ func TestGetAttesterDuties(t *testing.T) { State: bs, Root: genesisRoot[:], Slot: &chainSlot, } vs := &Server{ - StateFetcher: &testutil.MockStater{ + Stater: &testutil.MockStater{ StatesBySlot: map[primitives.Slot]state.BeaconState{ 0: bs, params.BeaconConfig().SlotsPerEpoch: nextEpochState, @@ -198,7 +198,7 @@ func TestGetAttesterDuties(t *testing.T) { State: bs, Root: genesisRoot[:], Slot: &chainSlot, Optimistic: true, } vs := &Server{ - StateFetcher: &testutil.MockStater{StatesBySlot: map[primitives.Slot]state.BeaconState{0: bs}}, + Stater: &testutil.MockStater{StatesBySlot: map[primitives.Slot]state.BeaconState{0: bs}}, TimeFetcher: chain, OptimisticModeFetcher: chain, SyncChecker: &mockSync.Sync{IsSyncing: false}, @@ -258,7 +258,7 @@ func TestGetProposerDuties(t *testing.T) { State: bs, Root: genesisRoot[:], Slot: &chainSlot, } vs := &Server{ - StateFetcher: &testutil.MockStater{StatesBySlot: map[primitives.Slot]state.BeaconState{0: bs}}, + Stater: &testutil.MockStater{StatesBySlot: map[primitives.Slot]state.BeaconState{0: bs}}, HeadFetcher: chain, TimeFetcher: chain, OptimisticModeFetcher: chain, @@ -297,7 +297,7 @@ func TestGetProposerDuties(t *testing.T) { State: bs, Root: genesisRoot[:], Slot: &chainSlot, } vs := &Server{ - StateFetcher: &testutil.MockStater{StatesBySlot: map[primitives.Slot]state.BeaconState{0: bs}}, + Stater: &testutil.MockStater{StatesBySlot: map[primitives.Slot]state.BeaconState{0: bs}}, HeadFetcher: chain, TimeFetcher: chain, OptimisticModeFetcher: chain, @@ -337,7 +337,7 @@ func TestGetProposerDuties(t *testing.T) { State: bs, Root: genesisRoot[:], Slot: &chainSlot, } vs := &Server{ - StateFetcher: &testutil.MockStater{StatesBySlot: map[primitives.Slot]state.BeaconState{params.BeaconConfig().SlotsPerEpoch: bs}}, + Stater: &testutil.MockStater{StatesBySlot: map[primitives.Slot]state.BeaconState{params.BeaconConfig().SlotsPerEpoch: bs}}, HeadFetcher: chain, TimeFetcher: chain, OptimisticModeFetcher: chain, @@ -377,7 +377,7 @@ func TestGetProposerDuties(t *testing.T) { State: bs, Root: genesisRoot[:], Slot: &chainSlot, } vs := &Server{ - StateFetcher: &testutil.MockStater{StatesBySlot: map[primitives.Slot]state.BeaconState{0: bs}}, + Stater: &testutil.MockStater{StatesBySlot: map[primitives.Slot]state.BeaconState{0: bs}}, HeadFetcher: chain, TimeFetcher: chain, OptimisticModeFetcher: chain, @@ -414,7 +414,7 @@ func TestGetProposerDuties(t *testing.T) { State: bs, Root: genesisRoot[:], Slot: &chainSlot, Optimistic: true, } vs := &Server{ - StateFetcher: &testutil.MockStater{StatesBySlot: map[primitives.Slot]state.BeaconState{0: bs}}, + Stater: &testutil.MockStater{StatesBySlot: map[primitives.Slot]state.BeaconState{0: bs}}, HeadFetcher: chain, TimeFetcher: chain, OptimisticModeFetcher: chain, @@ -469,7 +469,7 @@ func TestGetSyncCommitteeDuties(t *testing.T) { mockChainService := &mockChain.ChainService{Genesis: genesisTime} vs := &Server{ - StateFetcher: &testutil.MockStater{BeaconState: st}, + Stater: &testutil.MockStater{BeaconState: st}, SyncChecker: &mockSync.Sync{IsSyncing: false}, TimeFetcher: mockChainService, HeadFetcher: mockChainService, @@ -611,7 +611,7 @@ func TestGetSyncCommitteeDuties(t *testing.T) { } mockChainService := &mockChain.ChainService{Genesis: genesisTime, Slot: &newSyncPeriodStartSlot} vs := &Server{ - StateFetcher: &testutil.MockStater{BeaconState: stateFetchFn(newSyncPeriodStartSlot)}, + Stater: &testutil.MockStater{BeaconState: stateFetchFn(newSyncPeriodStartSlot)}, SyncChecker: &mockSync.Sync{IsSyncing: false}, TimeFetcher: mockChainService, HeadFetcher: mockChainService, @@ -665,7 +665,7 @@ func TestGetSyncCommitteeDuties(t *testing.T) { State: state, } vs := &Server{ - StateFetcher: &testutil.MockStater{BeaconState: st}, + Stater: &testutil.MockStater{BeaconState: st}, SyncChecker: &mockSync.Sync{IsSyncing: false}, TimeFetcher: mockChainService, HeadFetcher: mockChainService, @@ -5021,7 +5021,7 @@ func TestGetLiveness(t *testing.T) { server := &Server{ HeadFetcher: &mockChain.ChainService{State: headSt}, - StateFetcher: &testutil.MockStater{ + Stater: &testutil.MockStater{ // We configure states for last slots of an epoch StatesBySlot: map[primitives.Slot]state.BeaconState{ params.BeaconConfig().SlotsPerEpoch - 1: oldSt, diff --git a/beacon-chain/rpc/service.go b/beacon-chain/rpc/service.go index 1d60c0b8af89..22d3d600debf 100644 --- a/beacon-chain/rpc/service.go +++ b/beacon-chain/rpc/service.go @@ -234,7 +234,7 @@ func (s *Service) Start() { PeerManager: s.cfg.PeerManager, Broadcaster: s.cfg.Broadcaster, V1Alpha1Server: validatorServer, - StateFetcher: &lookup.BeaconDbStater{ + Stater: &lookup.BeaconDbStater{ BeaconDB: s.cfg.BeaconDB, ChainInfoFetcher: s.cfg.ChainInfoFetcher, GenesisTimeFetcher: s.cfg.GenesisTimeFetcher, @@ -309,7 +309,7 @@ func (s *Service) Start() { Broadcaster: s.cfg.Broadcaster, BlockReceiver: s.cfg.BlockReceiver, StateGenService: s.cfg.StateGen, - StateFetcher: &lookup.BeaconDbStater{ + Stater: &lookup.BeaconDbStater{ BeaconDB: s.cfg.BeaconDB, ChainInfoFetcher: s.cfg.ChainInfoFetcher, GenesisTimeFetcher: s.cfg.GenesisTimeFetcher, @@ -352,7 +352,7 @@ func (s *Service) Start() { debugServerV1 := &debug.Server{ BeaconDB: s.cfg.BeaconDB, HeadFetcher: s.cfg.HeadFetcher, - StateFetcher: &lookup.BeaconDbStater{ + Stater: &lookup.BeaconDbStater{ BeaconDB: s.cfg.BeaconDB, ChainInfoFetcher: s.cfg.ChainInfoFetcher, GenesisTimeFetcher: s.cfg.GenesisTimeFetcher, From 6d4f32bb6e532d8e8869c5d083bd0ed0d345ac02 Mon Sep 17 00:00:00 2001 From: rkapka Date: Wed, 22 Mar 2023 14:25:41 +0100 Subject: [PATCH 34/40] rename http to writer --- network/BUILD.bazel | 2 +- network/{http.go => writer.go} | 0 2 files changed, 1 insertion(+), 1 deletion(-) rename network/{http.go => writer.go} (100%) diff --git a/network/BUILD.bazel b/network/BUILD.bazel index 2197ea7ab128..1412b2d2a7d1 100644 --- a/network/BUILD.bazel +++ b/network/BUILD.bazel @@ -6,7 +6,7 @@ go_library( "auth.go", "endpoint.go", "external_ip.go", - "http.go", + "writer.go", ], importpath = "github.com/prysmaticlabs/prysm/v4/network", visibility = ["//visibility:public"], diff --git a/network/http.go b/network/writer.go similarity index 100% rename from network/http.go rename to network/writer.go From afc3170a0041600bee49d6e0c91bccef49e88231 Mon Sep 17 00:00:00 2001 From: rkapka Date: Fri, 24 Mar 2023 14:56:26 +0100 Subject: [PATCH 35/40] Kasey's feedback --- beacon-chain/rpc/eth/rewards/BUILD.bazel | 6 +- beacon-chain/rpc/eth/rewards/handlers.go | 30 +++---- beacon-chain/rpc/eth/rewards/handlers_test.go | 12 +-- beacon-chain/rpc/eth/rewards/structs.go | 69 ---------------- beacon-chain/rpc/eth/rewards/structs_test.go | 78 ------------------- 5 files changed, 22 insertions(+), 173 deletions(-) delete mode 100644 beacon-chain/rpc/eth/rewards/structs_test.go diff --git a/beacon-chain/rpc/eth/rewards/BUILD.bazel b/beacon-chain/rpc/eth/rewards/BUILD.bazel index 2778236a0998..78d6df3712a8 100644 --- a/beacon-chain/rpc/eth/rewards/BUILD.bazel +++ b/beacon-chain/rpc/eth/rewards/BUILD.bazel @@ -18,7 +18,6 @@ go_library( "//beacon-chain/state/stategen:go_default_library", "//consensus-types/blocks:go_default_library", "//consensus-types/interfaces:go_default_library", - "//consensus-types/primitives:go_default_library", "//network:go_default_library", "//runtime/version:go_default_library", "@com_github_pkg_errors//:go_default_library", @@ -27,10 +26,7 @@ go_library( go_test( name = "go_default_test", - srcs = [ - "handlers_test.go", - "structs_test.go", - ], + srcs = ["handlers_test.go"], embed = [":go_default_library"], deps = [ "//beacon-chain/blockchain/testing:go_default_library", diff --git a/beacon-chain/rpc/eth/rewards/handlers.go b/beacon-chain/rpc/eth/rewards/handlers.go index 8cec5ca4b346..059e2633e421 100644 --- a/beacon-chain/rpc/eth/rewards/handlers.go +++ b/beacon-chain/rpc/eth/rewards/handlers.go @@ -2,6 +2,7 @@ package rewards import ( "net/http" + "strconv" "strings" "github.com/pkg/errors" @@ -33,6 +34,10 @@ func (s *Server) BlockRewards(w http.ResponseWriter, r *http.Request) { network.WriteError(w, errJson) return } + + // We want to run several block processing functions that update the proposer's balance. + // This will allow us to calculate proposer rewards for each operation (atts, slashings etc). + // To do this, we replay the state up to the block's slot, but before processing the block. st, err := s.ReplayerBuilder.ReplayerForSlot(blk.Block().Slot()-1).ReplayToSlot(r.Context(), blk.Block().Slot()) if err != nil { errJson := &network.DefaultErrorJson{ @@ -44,7 +49,7 @@ func (s *Server) BlockRewards(w http.ResponseWriter, r *http.Request) { } proposerIndex := blk.Block().ProposerIndex() - oldBalance, err := st.BalanceAtIndex(proposerIndex) + initBalance, err := st.BalanceAtIndex(proposerIndex) if err != nil { errJson := &network.DefaultErrorJson{ Message: errors.Wrapf(err, "could not get proposer's balance").Error(), @@ -62,7 +67,7 @@ func (s *Server) BlockRewards(w http.ResponseWriter, r *http.Request) { network.WriteError(w, errJson) return } - newBalance, err := st.BalanceAtIndex(proposerIndex) + attBalance, err := st.BalanceAtIndex(proposerIndex) if err != nil { errJson := &network.DefaultErrorJson{ Message: errors.Wrapf(err, "could not get proposer's balance").Error(), @@ -71,8 +76,6 @@ func (s *Server) BlockRewards(w http.ResponseWriter, r *http.Request) { network.WriteError(w, errJson) return } - attsReward := newBalance - oldBalance - oldBalance = newBalance st, err = coreblocks.ProcessAttesterSlashings(r.Context(), st, blk.Block().Body().AttesterSlashings(), validators.SlashValidator) if err != nil { errJson := &network.DefaultErrorJson{ @@ -82,7 +85,7 @@ func (s *Server) BlockRewards(w http.ResponseWriter, r *http.Request) { network.WriteError(w, errJson) return } - newBalance, err = st.BalanceAtIndex(proposerIndex) + attSlashingsBalance, err := st.BalanceAtIndex(proposerIndex) if err != nil { errJson := &network.DefaultErrorJson{ Message: errors.Wrapf(err, "could not get proposer's balance").Error(), @@ -91,8 +94,6 @@ func (s *Server) BlockRewards(w http.ResponseWriter, r *http.Request) { network.WriteError(w, errJson) return } - attSlashingsReward := newBalance - oldBalance - oldBalance = newBalance st, err = coreblocks.ProcessProposerSlashings(r.Context(), st, blk.Block().Body().ProposerSlashings(), validators.SlashValidator) if err != nil { errJson := &network.DefaultErrorJson{ @@ -102,7 +103,7 @@ func (s *Server) BlockRewards(w http.ResponseWriter, r *http.Request) { network.WriteError(w, errJson) return } - newBalance, err = st.BalanceAtIndex(proposerIndex) + proposerSlashingsBalance, err := st.BalanceAtIndex(proposerIndex) if err != nil { errJson := &network.DefaultErrorJson{ Message: errors.Wrapf(err, "could not get proposer's balance").Error(), @@ -111,7 +112,6 @@ func (s *Server) BlockRewards(w http.ResponseWriter, r *http.Request) { network.WriteError(w, errJson) return } - proposerSlashingsReward := newBalance - oldBalance sa, err := blk.Block().Body().SyncAggregate() if err != nil { errJson := &network.DefaultErrorJson{ @@ -153,12 +153,12 @@ func (s *Server) BlockRewards(w http.ResponseWriter, r *http.Request) { response := &BlockRewardsResponse{ Data: &BlockRewards{ - ProposerIndex: proposerIndex, - Total: attsReward + proposerSlashingsReward + attSlashingsReward + syncCommitteeReward, - Attestations: attsReward, - SyncAggregate: syncCommitteeReward, - ProposerSlashings: proposerSlashingsReward, - AttesterSlashings: attSlashingsReward, + ProposerIndex: strconv.FormatUint(uint64(proposerIndex), 10), + Total: strconv.FormatUint(proposerSlashingsBalance-initBalance+syncCommitteeReward, 10), + Attestations: strconv.FormatUint(attBalance-initBalance, 10), + SyncAggregate: strconv.FormatUint(syncCommitteeReward, 10), + ProposerSlashings: strconv.FormatUint(proposerSlashingsBalance-attSlashingsBalance, 10), + AttesterSlashings: strconv.FormatUint(attSlashingsBalance-attBalance, 10), }, ExecutionOptimistic: optimistic, Finalized: s.FinalizationFetcher.IsFinalized(r.Context(), blkRoot), diff --git a/beacon-chain/rpc/eth/rewards/handlers_test.go b/beacon-chain/rpc/eth/rewards/handlers_test.go index c855d7b4ad43..fdd99c4069a4 100644 --- a/beacon-chain/rpc/eth/rewards/handlers_test.go +++ b/beacon-chain/rpc/eth/rewards/handlers_test.go @@ -175,12 +175,12 @@ func TestBlockRewards(t *testing.T) { assert.Equal(t, http.StatusOK, writer.Code) resp := &BlockRewardsResponse{} require.NoError(t, json.Unmarshal(writer.Body.Bytes(), resp)) - assert.Equal(t, primitives.ValidatorIndex(12), resp.Data.ProposerIndex) - assert.Equal(t, uint64(125089490), resp.Data.Total) - assert.Equal(t, uint64(89442), resp.Data.Attestations) - assert.Equal(t, uint64(48), resp.Data.SyncAggregate) - assert.Equal(t, uint64(62500000), resp.Data.AttesterSlashings) - assert.Equal(t, uint64(62500000), resp.Data.ProposerSlashings) + assert.Equal(t, "12", resp.Data.ProposerIndex) + assert.Equal(t, "125089490", resp.Data.Total) + assert.Equal(t, "89442", resp.Data.Attestations) + assert.Equal(t, "48", resp.Data.SyncAggregate) + assert.Equal(t, "62500000", resp.Data.AttesterSlashings) + assert.Equal(t, "62500000", resp.Data.ProposerSlashings) assert.Equal(t, true, resp.ExecutionOptimistic) assert.Equal(t, false, resp.Finalized) }) diff --git a/beacon-chain/rpc/eth/rewards/structs.go b/beacon-chain/rpc/eth/rewards/structs.go index 8abc2fb0ccad..924e6023a380 100644 --- a/beacon-chain/rpc/eth/rewards/structs.go +++ b/beacon-chain/rpc/eth/rewards/structs.go @@ -1,13 +1,5 @@ package rewards -import ( - "encoding/json" - "strconv" - - "github.com/pkg/errors" - types "github.com/prysmaticlabs/prysm/v4/consensus-types/primitives" -) - type BlockRewardsResponse struct { Data *BlockRewards `json:"data"` ExecutionOptimistic bool `json:"execution_optimistic"` @@ -15,15 +7,6 @@ type BlockRewardsResponse struct { } type BlockRewards struct { - ProposerIndex types.ValidatorIndex - Total uint64 - Attestations uint64 - SyncAggregate uint64 - ProposerSlashings uint64 - AttesterSlashings uint64 -} - -type BlockRewardsJson struct { ProposerIndex string `json:"proposer_index"` Total string `json:"total"` Attestations string `json:"attestations"` @@ -31,55 +14,3 @@ type BlockRewardsJson struct { ProposerSlashings string `json:"proposer_slashings"` AttesterSlashings string `json:"attester_slashings"` } - -func (r *BlockRewards) MarshalJSON() ([]byte, error) { - return json.Marshal(&BlockRewardsJson{ - ProposerIndex: strconv.FormatUint(uint64(r.ProposerIndex), 10), - Total: strconv.FormatUint(r.Total, 10), - Attestations: strconv.FormatUint(r.Attestations, 10), - SyncAggregate: strconv.FormatUint(r.SyncAggregate, 10), - ProposerSlashings: strconv.FormatUint(r.ProposerSlashings, 10), - AttesterSlashings: strconv.FormatUint(r.AttesterSlashings, 10), - }) -} - -func (r *BlockRewards) UnmarshalJSON(b []byte) error { - j := &BlockRewardsJson{} - err := json.Unmarshal(b, j) - if err != nil { - return err - } - proposerIndex, err := strconv.ParseUint(j.ProposerIndex, 10, 64) - if err != nil { - return errors.Wrapf(err, "could not unmarshal proposer index") - } - total, err := strconv.ParseUint(j.Total, 10, 64) - if err != nil { - return errors.Wrapf(err, "could not unmarshal total") - } - attestations, err := strconv.ParseUint(j.Attestations, 10, 64) - if err != nil { - return errors.Wrapf(err, "could not unmarshal attestations") - } - syncAggregate, err := strconv.ParseUint(j.SyncAggregate, 10, 64) - if err != nil { - return errors.Wrapf(err, "could not unmarshal sync aggregate") - } - proposerSlashings, err := strconv.ParseUint(j.ProposerSlashings, 10, 64) - if err != nil { - return errors.Wrapf(err, "could not unmarshal proposer slashings") - } - attesterSlashings, err := strconv.ParseUint(j.AttesterSlashings, 10, 64) - if err != nil { - return errors.Wrapf(err, "could not unmarshal attester slashings") - } - *r = BlockRewards{ - ProposerIndex: types.ValidatorIndex(proposerIndex), - Total: total, - Attestations: attestations, - SyncAggregate: syncAggregate, - ProposerSlashings: proposerSlashings, - AttesterSlashings: attesterSlashings, - } - return nil -} diff --git a/beacon-chain/rpc/eth/rewards/structs_test.go b/beacon-chain/rpc/eth/rewards/structs_test.go deleted file mode 100644 index 66c6fcec9d8a..000000000000 --- a/beacon-chain/rpc/eth/rewards/structs_test.go +++ /dev/null @@ -1,78 +0,0 @@ -package rewards_test - -import ( - "encoding/json" - "testing" - - "github.com/prysmaticlabs/prysm/v4/beacon-chain/rpc/eth/rewards" - "github.com/prysmaticlabs/prysm/v4/testing/assert" - "github.com/prysmaticlabs/prysm/v4/testing/require" -) - -func TestMarshalBlockRewards(t *testing.T) { - r := &rewards.BlockRewards{ - ProposerIndex: 123, - Total: 123, - Attestations: 123, - SyncAggregate: 123, - ProposerSlashings: 123, - AttesterSlashings: 123, - } - j, err := json.Marshal(r) - require.NoError(t, err) - expected := `{"proposer_index":"123","total":"123","attestations":"123","sync_aggregate":"123","proposer_slashings":"123","attester_slashings":"123"}` - assert.Equal(t, expected, string(j)) -} - -func TestUnmarshalBlockRewards(t *testing.T) { - t.Run("ok", func(t *testing.T) { - s := `{"proposer_index":"123","total":"123","attestations":"123","sync_aggregate":"123","proposer_slashings":"123","attester_slashings":"123"}` - r := &rewards.BlockRewards{} - require.NoError(t, r.UnmarshalJSON([]byte(s))) - expected := &rewards.BlockRewards{ - ProposerIndex: 123, - Total: 123, - Attestations: 123, - SyncAggregate: 123, - ProposerSlashings: 123, - AttesterSlashings: 123, - } - assert.DeepEqual(t, expected, r) - }) - t.Run("invalid proposer index", func(t *testing.T) { - s := `{"proposer_index":"foo","total":"123","attestations":"123","sync_aggregate":"123","proposer_slashings":"123","attester_slashings":"123"}` - r := &rewards.BlockRewards{} - err := r.UnmarshalJSON([]byte(s)) - assert.ErrorContains(t, "could not unmarshal proposer index", err) - }) - t.Run("invalid total", func(t *testing.T) { - s := `{"proposer_index":"123","total":"foo","attestations":"123","sync_aggregate":"123","proposer_slashings":"123","attester_slashings":"123"}` - r := &rewards.BlockRewards{} - err := r.UnmarshalJSON([]byte(s)) - assert.ErrorContains(t, "could not unmarshal total", err) - }) - t.Run("invalid attestations", func(t *testing.T) { - s := `{"proposer_index":"123","total":"123","attestations":"foo","sync_aggregate":"123","proposer_slashings":"123","attester_slashings":"123"}` - r := &rewards.BlockRewards{} - err := r.UnmarshalJSON([]byte(s)) - assert.ErrorContains(t, "could not unmarshal attestations", err) - }) - t.Run("invalid sync aggregate", func(t *testing.T) { - s := `{"proposer_index":"123","total":"123","attestations":"123","sync_aggregate":"foo","proposer_slashings":"123","attester_slashings":"123"}` - r := &rewards.BlockRewards{} - err := r.UnmarshalJSON([]byte(s)) - assert.ErrorContains(t, "could not unmarshal sync aggregate", err) - }) - t.Run("invalid proposer slashings", func(t *testing.T) { - s := `{"proposer_index":"123","total":"123","attestations":"123","sync_aggregate":"123","proposer_slashings":"foo","attester_slashings":"123"}` - r := &rewards.BlockRewards{} - err := r.UnmarshalJSON([]byte(s)) - assert.ErrorContains(t, "could not unmarshal proposer slashings", err) - }) - t.Run("invalid attester slashings", func(t *testing.T) { - s := `{"proposer_index":"123","total":"123","attestations":"123","sync_aggregate":"123","proposer_slashings":"123","attester_slashings":"foo"}` - r := &rewards.BlockRewards{} - err := r.UnmarshalJSON([]byte(s)) - assert.ErrorContains(t, "could not unmarshal attester slashings", err) - }) -} From 534367b1605b145308d31f80de7b532d7026dc21 Mon Sep 17 00:00:00 2001 From: rkapka Date: Fri, 24 Mar 2023 15:11:20 +0100 Subject: [PATCH 36/40] deepsource issues --- beacon-chain/rpc/eth/rewards/handlers.go | 2 +- beacon-chain/rpc/eth/rewards/handlers_test.go | 2 -- 2 files changed, 1 insertion(+), 3 deletions(-) diff --git a/beacon-chain/rpc/eth/rewards/handlers.go b/beacon-chain/rpc/eth/rewards/handlers.go index 059e2633e421..ff1fccb84e54 100644 --- a/beacon-chain/rpc/eth/rewards/handlers.go +++ b/beacon-chain/rpc/eth/rewards/handlers.go @@ -122,7 +122,7 @@ func (s *Server) BlockRewards(w http.ResponseWriter, r *http.Request) { return } var syncCommitteeReward uint64 - st, syncCommitteeReward, err = altair.ProcessSyncAggregate(r.Context(), st, sa) + _, syncCommitteeReward, err = altair.ProcessSyncAggregate(r.Context(), st, sa) if err != nil { errJson := &network.DefaultErrorJson{ Message: errors.Wrapf(err, "could not get sync aggregate rewards").Error(), diff --git a/beacon-chain/rpc/eth/rewards/handlers_test.go b/beacon-chain/rpc/eth/rewards/handlers_test.go index fdd99c4069a4..25a0464aa051 100644 --- a/beacon-chain/rpc/eth/rewards/handlers_test.go +++ b/beacon-chain/rpc/eth/rewards/handlers_test.go @@ -38,7 +38,6 @@ func TestBlockRewards(t *testing.T) { validators := make([]*eth.Validator, 0, valCount) balances := make([]uint64, 0, valCount) secretKeys := make([]bls.SecretKey, 0, valCount) - pubkeys := make([][]byte, 0, valCount) for i := 0; i < valCount; i++ { blsKey, err := bls.RandKey() require.NoError(t, err) @@ -50,7 +49,6 @@ func TestBlockRewards(t *testing.T) { EffectiveBalance: params.BeaconConfig().MaxEffectiveBalance, }) balances = append(balances, params.BeaconConfig().MaxEffectiveBalance) - pubkeys = append(pubkeys, blsKey.PublicKey().Marshal()) } require.NoError(t, st.SetValidators(validators)) require.NoError(t, st.SetBalances(balances)) From a101ef2ee526f50232fbc5f3faa5448afb27e859 Mon Sep 17 00:00:00 2001 From: rkapka Date: Tue, 28 Mar 2023 14:03:51 +0200 Subject: [PATCH 37/40] register endpoint --- beacon-chain/node/node.go | 5 +++-- beacon-chain/rpc/BUILD.bazel | 2 ++ beacon-chain/rpc/service.go | 14 ++++++++++++++ 3 files changed, 19 insertions(+), 2 deletions(-) diff --git a/beacon-chain/node/node.go b/beacon-chain/node/node.go index ea607095e9ad..f360a87677a4 100644 --- a/beacon-chain/node/node.go +++ b/beacon-chain/node/node.go @@ -255,7 +255,7 @@ func New(cliCtx *cli.Context, opts ...Option) (*BeaconNode, error) { log.Debugln("Registering RPC Service") router := mux.NewRouter() - if err := beacon.registerRPCService(); err != nil { + if err := beacon.registerRPCService(router); err != nil { return nil, err } @@ -736,7 +736,7 @@ func (b *BeaconNode) registerSlasherService() error { return b.services.RegisterService(slasherSrv) } -func (b *BeaconNode) registerRPCService() error { +func (b *BeaconNode) registerRPCService(router *mux.Router) error { var chainService *blockchain.Service if err := b.services.FetchService(&chainService); err != nil { return err @@ -832,6 +832,7 @@ func (b *BeaconNode) registerRPCService() error { MaxMsgSize: maxMsgSize, ProposerIdsCache: b.proposerIdsCache, BlockBuilder: b.fetchBuilderService(), + Router: router, }) return b.services.RegisterService(rpcService) diff --git a/beacon-chain/rpc/BUILD.bazel b/beacon-chain/rpc/BUILD.bazel index 7c5d3220e9fc..3f94be7b011f 100644 --- a/beacon-chain/rpc/BUILD.bazel +++ b/beacon-chain/rpc/BUILD.bazel @@ -28,6 +28,7 @@ go_library( "//beacon-chain/rpc/eth/debug:go_default_library", "//beacon-chain/rpc/eth/events:go_default_library", "//beacon-chain/rpc/eth/node:go_default_library", + "//beacon-chain/rpc/eth/rewards:go_default_library", "//beacon-chain/rpc/eth/validator:go_default_library", "//beacon-chain/rpc/lookup:go_default_library", "//beacon-chain/rpc/prysm/v1alpha1/beacon:go_default_library", @@ -43,6 +44,7 @@ go_library( "//monitoring/tracing:go_default_library", "//proto/eth/service:go_default_library", "//proto/prysm/v1alpha1:go_default_library", + "@com_github_gorilla_mux//:go_default_library", "@com_github_grpc_ecosystem_go_grpc_middleware//:go_default_library", "@com_github_grpc_ecosystem_go_grpc_middleware//recovery:go_default_library", "@com_github_grpc_ecosystem_go_grpc_middleware//tracing/opentracing:go_default_library", diff --git a/beacon-chain/rpc/service.go b/beacon-chain/rpc/service.go index 22d3d600debf..af64ad00604d 100644 --- a/beacon-chain/rpc/service.go +++ b/beacon-chain/rpc/service.go @@ -8,6 +8,7 @@ import ( "net" "sync" + "github.com/gorilla/mux" middleware "github.com/grpc-ecosystem/go-grpc-middleware" recovery "github.com/grpc-ecosystem/go-grpc-middleware/recovery" grpcopentracing "github.com/grpc-ecosystem/go-grpc-middleware/tracing/opentracing" @@ -32,6 +33,7 @@ import ( "github.com/prysmaticlabs/prysm/v4/beacon-chain/rpc/eth/debug" "github.com/prysmaticlabs/prysm/v4/beacon-chain/rpc/eth/events" "github.com/prysmaticlabs/prysm/v4/beacon-chain/rpc/eth/node" + "github.com/prysmaticlabs/prysm/v4/beacon-chain/rpc/eth/rewards" "github.com/prysmaticlabs/prysm/v4/beacon-chain/rpc/eth/validator" "github.com/prysmaticlabs/prysm/v4/beacon-chain/rpc/lookup" beaconv1alpha1 "github.com/prysmaticlabs/prysm/v4/beacon-chain/rpc/prysm/v1alpha1/beacon" @@ -117,6 +119,7 @@ type Config struct { ProposerIdsCache *cache.ProposerPayloadIDsCache OptimisticModeFetcher blockchain.OptimisticModeFetcher BlockBuilder builder.BlockBuilder + Router *mux.Router } // NewService instantiates a new RPC service instance that will @@ -190,6 +193,17 @@ func (s *Service) Start() { withCache := stategen.WithCache(stateCache) ch := stategen.NewCanonicalHistory(s.cfg.BeaconDB, s.cfg.ChainInfoFetcher, s.cfg.ChainInfoFetcher, withCache) + rewardsServer := &rewards.Server{ + Blocker: &lookup.BeaconDbBlocker{ + BeaconDB: s.cfg.BeaconDB, + ChainInfoFetcher: s.cfg.ChainInfoFetcher, + }, + OptimisticModeFetcher: s.cfg.OptimisticModeFetcher, + FinalizationFetcher: s.cfg.FinalizationFetcher, + ReplayerBuilder: ch, + } + s.cfg.Router.HandleFunc("/eth/v1/beacon/rewards/blocks/{block_id}", rewardsServer.BlockRewards) + validatorServer := &validatorv1alpha1.Server{ Ctx: s.ctx, AttestationCache: cache.NewAttestationCache(), From 874fb4115357a603c2298e6255ca99c89b196100 Mon Sep 17 00:00:00 2001 From: rkapka Date: Tue, 28 Mar 2023 17:39:17 +0200 Subject: [PATCH 38/40] initialize blocker --- beacon-chain/rpc/service.go | 83 +++++++++++++++++-------------------- 1 file changed, 37 insertions(+), 46 deletions(-) diff --git a/beacon-chain/rpc/service.go b/beacon-chain/rpc/service.go index af64ad00604d..55e241832a16 100644 --- a/beacon-chain/rpc/service.go +++ b/beacon-chain/rpc/service.go @@ -192,12 +192,20 @@ func (s *Service) Start() { } withCache := stategen.WithCache(stateCache) ch := stategen.NewCanonicalHistory(s.cfg.BeaconDB, s.cfg.ChainInfoFetcher, s.cfg.ChainInfoFetcher, withCache) + stater := &lookup.BeaconDbStater{ + BeaconDB: s.cfg.BeaconDB, + ChainInfoFetcher: s.cfg.ChainInfoFetcher, + GenesisTimeFetcher: s.cfg.GenesisTimeFetcher, + StateGenService: s.cfg.StateGen, + ReplayerBuilder: ch, + } + blocker := &lookup.BeaconDbBlocker{ + BeaconDB: s.cfg.BeaconDB, + ChainInfoFetcher: s.cfg.ChainInfoFetcher, + } rewardsServer := &rewards.Server{ - Blocker: &lookup.BeaconDbBlocker{ - BeaconDB: s.cfg.BeaconDB, - ChainInfoFetcher: s.cfg.ChainInfoFetcher, - }, + Blocker: blocker, OptimisticModeFetcher: s.cfg.OptimisticModeFetcher, FinalizationFetcher: s.cfg.FinalizationFetcher, ReplayerBuilder: ch, @@ -240,21 +248,15 @@ func (s *Service) Start() { BLSChangesPool: s.cfg.BLSChangesPool, } validatorServerV1 := &validator.Server{ - HeadFetcher: s.cfg.HeadFetcher, - TimeFetcher: s.cfg.GenesisTimeFetcher, - SyncChecker: s.cfg.SyncService, - OptimisticModeFetcher: s.cfg.OptimisticModeFetcher, - AttestationsPool: s.cfg.AttestationsPool, - PeerManager: s.cfg.PeerManager, - Broadcaster: s.cfg.Broadcaster, - V1Alpha1Server: validatorServer, - Stater: &lookup.BeaconDbStater{ - BeaconDB: s.cfg.BeaconDB, - ChainInfoFetcher: s.cfg.ChainInfoFetcher, - GenesisTimeFetcher: s.cfg.GenesisTimeFetcher, - StateGenService: s.cfg.StateGen, - ReplayerBuilder: ch, - }, + HeadFetcher: s.cfg.HeadFetcher, + TimeFetcher: s.cfg.GenesisTimeFetcher, + SyncChecker: s.cfg.SyncService, + OptimisticModeFetcher: s.cfg.OptimisticModeFetcher, + AttestationsPool: s.cfg.AttestationsPool, + PeerManager: s.cfg.PeerManager, + Broadcaster: s.cfg.Broadcaster, + V1Alpha1Server: validatorServer, + Stater: stater, SyncCommitteePool: s.cfg.SyncCommitteeObjectPool, ProposerSlotIndexCache: s.cfg.ProposerIdsCache, ChainInfoFetcher: s.cfg.ChainInfoFetcher, @@ -312,24 +314,19 @@ func (s *Service) Start() { ReplayerBuilder: ch, } beaconChainServerV1 := &beacon.Server{ - CanonicalHistory: ch, - BeaconDB: s.cfg.BeaconDB, - AttestationsPool: s.cfg.AttestationsPool, - SlashingsPool: s.cfg.SlashingsPool, - ChainInfoFetcher: s.cfg.ChainInfoFetcher, - GenesisTimeFetcher: s.cfg.GenesisTimeFetcher, - BlockNotifier: s.cfg.BlockNotifier, - OperationNotifier: s.cfg.OperationNotifier, - Broadcaster: s.cfg.Broadcaster, - BlockReceiver: s.cfg.BlockReceiver, - StateGenService: s.cfg.StateGen, - Stater: &lookup.BeaconDbStater{ - BeaconDB: s.cfg.BeaconDB, - ChainInfoFetcher: s.cfg.ChainInfoFetcher, - GenesisTimeFetcher: s.cfg.GenesisTimeFetcher, - StateGenService: s.cfg.StateGen, - ReplayerBuilder: ch, - }, + CanonicalHistory: ch, + BeaconDB: s.cfg.BeaconDB, + AttestationsPool: s.cfg.AttestationsPool, + SlashingsPool: s.cfg.SlashingsPool, + ChainInfoFetcher: s.cfg.ChainInfoFetcher, + GenesisTimeFetcher: s.cfg.GenesisTimeFetcher, + BlockNotifier: s.cfg.BlockNotifier, + OperationNotifier: s.cfg.OperationNotifier, + Broadcaster: s.cfg.Broadcaster, + BlockReceiver: s.cfg.BlockReceiver, + StateGenService: s.cfg.StateGen, + Stater: stater, + Blocker: blocker, OptimisticModeFetcher: s.cfg.OptimisticModeFetcher, HeadFetcher: s.cfg.HeadFetcher, VoluntaryExitsPool: s.cfg.ExitPool, @@ -364,15 +361,9 @@ func (s *Service) Start() { ReplayerBuilder: ch, } debugServerV1 := &debug.Server{ - BeaconDB: s.cfg.BeaconDB, - HeadFetcher: s.cfg.HeadFetcher, - Stater: &lookup.BeaconDbStater{ - BeaconDB: s.cfg.BeaconDB, - ChainInfoFetcher: s.cfg.ChainInfoFetcher, - GenesisTimeFetcher: s.cfg.GenesisTimeFetcher, - StateGenService: s.cfg.StateGen, - ReplayerBuilder: ch, - }, + BeaconDB: s.cfg.BeaconDB, + HeadFetcher: s.cfg.HeadFetcher, + Stater: stater, OptimisticModeFetcher: s.cfg.OptimisticModeFetcher, ForkFetcher: s.cfg.ForkFetcher, ForkchoiceFetcher: s.cfg.ForkchoiceFetcher, From b0064fb787ce13c10f8ffd26555da6e7eb6fee37 Mon Sep 17 00:00:00 2001 From: rkapka Date: Tue, 28 Mar 2023 17:56:01 +0200 Subject: [PATCH 39/40] test fix --- beacon-chain/rpc/BUILD.bazel | 1 + beacon-chain/rpc/service_test.go | 2 ++ 2 files changed, 3 insertions(+) diff --git a/beacon-chain/rpc/BUILD.bazel b/beacon-chain/rpc/BUILD.bazel index 3f94be7b011f..ae5473e36026 100644 --- a/beacon-chain/rpc/BUILD.bazel +++ b/beacon-chain/rpc/BUILD.bazel @@ -70,6 +70,7 @@ go_test( "//beacon-chain/sync/initial-sync/testing:go_default_library", "//testing/assert:go_default_library", "//testing/require:go_default_library", + "@com_github_gorilla_mux//:go_default_library", "@com_github_sirupsen_logrus//:go_default_library", "@com_github_sirupsen_logrus//hooks/test:go_default_library", ], diff --git a/beacon-chain/rpc/service_test.go b/beacon-chain/rpc/service_test.go index 39fa40207240..f27afe1cbe7b 100644 --- a/beacon-chain/rpc/service_test.go +++ b/beacon-chain/rpc/service_test.go @@ -7,6 +7,7 @@ import ( "testing" "time" + "github.com/gorilla/mux" mock "github.com/prysmaticlabs/prysm/v4/beacon-chain/blockchain/testing" mockExecution "github.com/prysmaticlabs/prysm/v4/beacon-chain/execution/testing" mockSync "github.com/prysmaticlabs/prysm/v4/beacon-chain/sync/initial-sync/testing" @@ -35,6 +36,7 @@ func TestLifecycle_OK(t *testing.T) { GenesisTimeFetcher: chainService, ExecutionChainService: &mockExecution.Chain{}, StateNotifier: chainService.StateNotifier(), + Router: mux.NewRouter(), }) rpcService.Start() From f17430a4c7775a1bd972455216f3ef77e2d09af0 Mon Sep 17 00:00:00 2001 From: rkapka Date: Tue, 28 Mar 2023 17:56:01 +0200 Subject: [PATCH 40/40] test fix --- beacon-chain/rpc/service_test.go | 1 + 1 file changed, 1 insertion(+) diff --git a/beacon-chain/rpc/service_test.go b/beacon-chain/rpc/service_test.go index f27afe1cbe7b..2d0d5344ae6d 100644 --- a/beacon-chain/rpc/service_test.go +++ b/beacon-chain/rpc/service_test.go @@ -77,6 +77,7 @@ func TestRPC_InsecureEndpoint(t *testing.T) { HeadFetcher: chainService, ExecutionChainService: &mockExecution.Chain{}, StateNotifier: chainService.StateNotifier(), + Router: mux.NewRouter(), }) rpcService.Start()