Compare commits

...

28 Commits

Author SHA1 Message Date
Kasey Kirkham
b697dd80da wip 2024-02-16 14:36:10 -06:00
terence tsao
22cf59d020 Gazelle 2024-02-15 19:00:43 -08:00
terence tsao
122bf42ddf Update spec test to v1.4.0-beta.7-hotfix 2024-02-15 18:18:08 -08:00
terence tsao
fb1ea2f507 Update spec test to v1.4.0-beta.7 2024-02-15 11:57:45 -08:00
Potuz
c3708f44f5 gazelle screwed up 2024-02-09 14:40:57 -03:00
Potuz
942137f505 gazelle 2024-02-09 14:38:55 -03:00
Potuz
0eee0b153f add sha 2024-02-09 14:36:44 -03:00
Potuz
2267f59eae add mainnet fork epoch 2024-02-09 14:17:36 -03:00
Aditya Asgaonkar
6a605e6b6d Fork choice filter changes (#13464)
* implement confirmation rule prerequisite - f.c. filter changes

* update tests

* update WORKSPACE for spec v1.4.0-beta.6

* run bazel gazelle

* Fix consensus_spec sha256

* drift also forkchoice time when drifting the service on tests

* update minimal kzg_commitment_inclusion_proof_depth.size

* fix mock engine client

* remove unnecessary helper & revert test changes

* revert change of proof size in minimal preset

* fix tests

* fix loader test

---------

Co-authored-by: terence tsao <terence@prysmaticlabs.com>
Co-authored-by: Potuz <potuz@prysmaticlabs.com>
2024-02-09 17:01:44 +00:00
Nishant Das
a0787e2379 Handle Syncing Executon Client (#13597)
* fix it

* manu's review

* fix failing tests
2024-02-09 09:07:48 +00:00
Nishant Das
621bda068d Suppress Unwanted P2P Errors (#13598)
* supress unwanted errors

* gaz

* mod
2024-02-09 05:13:57 +00:00
Radosław Kapka
91504eb95a Improve vc logs (#13573)
* duties

* atts

* revert some changes

* revert timeTillDuty

* Manu's review

* Revert "Auxiliary commit to revert individual files from 6806ca9fbe18101f58ccb40fe191c61c183735a8"

This reverts commit 0820c870d2627950179b0edf7ce62ee4fa4a03a3.

* remove trash

* more reivew

* making Manu happy

* test fixes
2024-02-08 18:24:03 +00:00
Sammy Rosso
5afb1255fe Add /eth/v1/beacon/deposit_snapshot endpoint (#13514)
* Add endpoint

* Uncomment in InitializeRoutes

* Add test

* Add 404

* Add more checks

* Test improvements

* Ssz

* Add ssz tags

* Add DepositSnapshot to bazel

* Fix tests

* Fix max size

* Resolve conflicts

* Revert untouched code

* Fix test + review

* Lint

* Oops

* Preston + Radek' review

* Only return 3 finalized roots

* Change to deposit contract depth

* Radek' review

* Gaz

---------

Co-authored-by: james-prysm <90280386+james-prysm@users.noreply.github.com>
2024-02-07 22:53:08 +00:00
Manu NALEPA
9d6160e112 Slasher: Remove unused RPC. (#13594) 2024-02-07 21:11:58 +00:00
james-prysm
1383546999 Beacon API: get blob fix retention cases (#13585)
* fixing the handling for certain cases

* fixing tests

* Update beacon-chain/rpc/eth/blob/handlers_test.go

Co-authored-by: Radosław Kapka <rkapka@wp.pl>

* update comment based on review

---------

Co-authored-by: Radosław Kapka <rkapka@wp.pl>
2024-02-06 22:31:17 +00:00
Justin Traglia
01116f7f82 Fix a few minor nits in protobuf definitions (#13512) 2024-02-06 21:17:32 +00:00
Thabokani
692ebd313f Fix typos in doc (#13583)
Signed-off-by: Thabokani <149070269+Thabokani@users.noreply.github.com>
Co-authored-by: Nishant Das <nishdas93@gmail.com>
2024-02-06 10:18:21 +00:00
Nishant Das
6fa656c1ee Add Sync Checker (#13580)
* fix it

* add it in

* typo

* fix tests

* fix tests

* export and add test

* preston's review
2024-02-06 02:34:30 +00:00
Dhruv Bodani
55a29a4670 Implement beacon committee selections (#13503)
* implement beacon committee selections

* fix build

* fix lint

* fix lint

* Update beacon-chain/rpc/eth/shared/structs.go

Co-authored-by: Radosław Kapka <rkapka@wp.pl>

* Update validator/client/beacon-api/beacon_committee_selections.go

Co-authored-by: Radosław Kapka <rkapka@wp.pl>

* Update validator/client/beacon-api/beacon_committee_selections.go

Co-authored-by: Radosław Kapka <rkapka@wp.pl>

* Update validator/client/beacon-api/beacon_committee_selections.go

Co-authored-by: Radosław Kapka <rkapka@wp.pl>

* move beacon committee selection structs to validator module

* fix bazel build files

* add support for POST and GET endpoints for get state validators query

* add a handler to return error from beacon node

* move beacon committee selection to validator top-level module

* fix bazel

* re-arrange fields to fix lint

* fix TestServer_InitializeRoutes

* fix build and lint

* fix build and lint

* fix TestSubmitAggregateAndProof_Distributed

---------

Co-authored-by: Radosław Kapka <rkapka@wp.pl>
2024-02-05 15:43:51 +00:00
Potuz
e2e7e84a96 Get the right head state when proposing a failed reorg (#13579)
* Get the right head state when proposing a failed reorg

* add unit test

* split logic
2024-02-05 13:40:35 +00:00
terence
91b0a93df7 Enhance EL block height log (#13582) 2024-02-05 01:52:01 +00:00
Preston Van Loon
8839015312 docker: Add coreutils to docker images (#13564)
* Add coreutils to docker images

* add coreutils dependencies

* Add a prysmaticlabs.com/uploads backup of the deb files

* Run gazelle and fix issues

* Remove broken tar, change http_archive deps to debian_archive, remove http mirrors in favor of snapshot

* Add comments about which deps are required by other deps
2024-02-03 19:21:21 +00:00
terence
61ab4bf7ca Rename block by range request log (#13561) 2024-02-03 19:20:04 +00:00
Radosław Kapka
e3ce1bde45 Move API structs to api module (#13577) 2024-02-03 11:57:01 +00:00
Nishant Das
9d1189b222 Do Not Cache For Non Active Public Keys (#13581)
* fix it

* clean up
2024-02-03 05:19:54 +00:00
KeienWang
74f5452a64 Fix typo in [beacon-chain/cache/depositsnapshot/deposit_cache_test.go]: Corrected a spelling error. (#13532)
Co-authored-by: Nishant Das <nishdas93@gmail.com>
2024-02-03 05:14:32 +00:00
Nishant Das
ea1204d3c7 Fix Slashing Gossip Checks (#13574)
* fix it

* add for proposals too
2024-02-02 23:13:22 +00:00
Radosław Kapka
d9ac69752b Return consensus block value in Wei (#13575)
* Return consensus block value in Wei

* Return consensus block value in Wei

* review
2024-02-02 18:17:40 +00:00
270 changed files with 5088 additions and 3584 deletions

View File

@@ -106,6 +106,13 @@ load("@rules_distroless//distroless:dependencies.bzl", "rules_distroless_depende
rules_distroless_dependencies()
http_archive(
name = "distroless",
integrity = "sha256-Cf00kUp1NyXA3LzbdyYy4Kda27wbkB8+A9MliTxq4jE=",
strip_prefix = "distroless-9dc924b9fe812eec2fa0061824dcad39eb09d0d6",
url = "https://github.com/GoogleContainerTools/distroless/archive/9dc924b9fe812eec2fa0061824dcad39eb09d0d6.tar.gz", # 2024-01-24
)
load("@aspect_bazel_lib//lib:repositories.bzl", "aspect_bazel_lib_dependencies", "aspect_bazel_lib_register_toolchains")
aspect_bazel_lib_dependencies()
@@ -144,6 +151,10 @@ http_archive(
],
)
load("//:distroless_deps.bzl", "distroless_deps")
distroless_deps()
# Override default import in rules_go with special patch until
# https://github.com/gogo/protobuf/pull/582 is merged.
git_repository(
@@ -223,7 +234,9 @@ filegroup(
url = "https://github.com/ethereum/EIPs/archive/5480440fe51742ed23342b68cf106cefd427e39d.tar.gz",
)
consensus_spec_version = "v1.4.0-beta.5"
consensus_spec_version = "v1.4.0-beta.7"
consensus_spec_test_version = "v1.4.0-beta.7-hotfix"
bls_test_version = "v0.1.1"
@@ -239,8 +252,8 @@ filegroup(
visibility = ["//visibility:public"],
)
""",
sha256 = "9017ffff84d64a7c4c9e6ff9f421f9479f71d3b463b738f54e02158dbb4f50f0",
url = "https://github.com/ethereum/consensus-spec-tests/releases/download/%s/general.tar.gz" % consensus_spec_version,
sha256 = "c282c0f86f23f3d2e0f71f5975769a4077e62a7e3c7382a16bd26a7e589811a0",
url = "https://github.com/ethereum/consensus-spec-tests/releases/download/%s/general.tar.gz" % consensus_spec_test_version,
)
http_archive(
@@ -255,8 +268,8 @@ filegroup(
visibility = ["//visibility:public"],
)
""",
sha256 = "f08711682553fe7c9362f1400ed8c56b2fa9576df08581fcad4c508ba8ad4788",
url = "https://github.com/ethereum/consensus-spec-tests/releases/download/%s/minimal.tar.gz" % consensus_spec_version,
sha256 = "4649c35aa3b8eb0cfdc81bee7c05649f90ef36bede5b0513e1f2e8baf37d6033",
url = "https://github.com/ethereum/consensus-spec-tests/releases/download/%s/minimal.tar.gz" % consensus_spec_test_version,
)
http_archive(
@@ -271,8 +284,8 @@ filegroup(
visibility = ["//visibility:public"],
)
""",
sha256 = "7ea3189e3879f2ac62467cbf2945c00b6c94d30cdefb2d645c630b1018c50e10",
url = "https://github.com/ethereum/consensus-spec-tests/releases/download/%s/mainnet.tar.gz" % consensus_spec_version,
sha256 = "c5a03f724f757456ffaabd2a899992a71d2baf45ee4db65ca3518f2b7ee928c8",
url = "https://github.com/ethereum/consensus-spec-tests/releases/download/%s/mainnet.tar.gz" % consensus_spec_test_version,
)
http_archive(
@@ -286,7 +299,7 @@ filegroup(
visibility = ["//visibility:public"],
)
""",
sha256 = "4119992a2efc79e5cb2bdc07ed08c0b1fa32332cbd0d88e6467f34938df97026",
sha256 = "049c29267310e6b88280f4f834a75866c2f5b9036fa97acb9d9c6db8f64d9118",
strip_prefix = "consensus-specs-" + consensus_spec_version[1:],
url = "https://github.com/ethereum/consensus-specs/archive/refs/tags/%s.tar.gz" % consensus_spec_version,
)
@@ -317,9 +330,9 @@ filegroup(
visibility = ["//visibility:public"],
)
""",
sha256 = "2701e1e1a3ec10c673fe7dbdbbe6f02c8ae8c922aebbf6e720d8c72d5458aafe",
strip_prefix = "eth2-networks-7b4897888cebef23801540236f73123e21774954",
url = "https://github.com/eth-clients/eth2-networks/archive/7b4897888cebef23801540236f73123e21774954.tar.gz",
sha256 = "77e7e3ed65e33b7bb19d30131f4c2bb39e4dfeb188ab9ae84651c3cc7600131d",
strip_prefix = "eth2-networks-934c948e69205dcf2deb87e4ae6cc140c335f94d",
url = "https://github.com/eth-clients/eth2-networks/archive/934c948e69205dcf2deb87e4ae6cc140c335f94d.tar.gz",
)
http_archive(

View File

@@ -12,11 +12,8 @@ go_library(
deps = [
"//api/client:go_default_library",
"//api/server:go_default_library",
"//api/server/structs:go_default_library",
"//beacon-chain/core/helpers:go_default_library",
"//beacon-chain/rpc/eth/beacon:go_default_library",
"//beacon-chain/rpc/eth/config:go_default_library",
"//beacon-chain/rpc/eth/shared:go_default_library",
"//beacon-chain/rpc/prysm/beacon:go_default_library",
"//beacon-chain/state:go_default_library",
"//consensus-types/interfaces:go_default_library",
"//consensus-types/primitives:go_default_library",

View File

@@ -17,10 +17,7 @@ import (
"github.com/pkg/errors"
"github.com/prysmaticlabs/prysm/v4/api/client"
"github.com/prysmaticlabs/prysm/v4/api/server"
"github.com/prysmaticlabs/prysm/v4/beacon-chain/rpc/eth/beacon"
"github.com/prysmaticlabs/prysm/v4/beacon-chain/rpc/eth/config"
"github.com/prysmaticlabs/prysm/v4/beacon-chain/rpc/eth/shared"
apibeacon "github.com/prysmaticlabs/prysm/v4/beacon-chain/rpc/prysm/beacon"
"github.com/prysmaticlabs/prysm/v4/api/server/structs"
"github.com/prysmaticlabs/prysm/v4/consensus-types/primitives"
"github.com/prysmaticlabs/prysm/v4/encoding/bytesutil"
"github.com/prysmaticlabs/prysm/v4/network/forks"
@@ -150,8 +147,8 @@ func (c *Client) GetFork(ctx context.Context, stateId StateOrBlockId) (*ethpb.Fo
if err != nil {
return nil, errors.Wrapf(err, "error requesting fork by state id = %s", stateId)
}
fr := &shared.Fork{}
dataWrapper := &struct{ Data *shared.Fork }{Data: fr}
fr := &structs.Fork{}
dataWrapper := &struct{ Data *structs.Fork }{Data: fr}
err = json.Unmarshal(body, dataWrapper)
if err != nil {
return nil, errors.Wrap(err, "error decoding json response in GetFork")
@@ -179,12 +176,12 @@ func (c *Client) GetForkSchedule(ctx context.Context) (forks.OrderedSchedule, er
}
// GetConfigSpec retrieve the current configs of the network used by the beacon node.
func (c *Client) GetConfigSpec(ctx context.Context) (*config.GetSpecResponse, error) {
func (c *Client) GetConfigSpec(ctx context.Context) (*structs.GetSpecResponse, error) {
body, err := c.Get(ctx, getConfigSpecPath)
if err != nil {
return nil, errors.Wrap(err, "error requesting configSpecPath")
}
fsr := &config.GetSpecResponse{}
fsr := &structs.GetSpecResponse{}
err = json.Unmarshal(body, fsr)
if err != nil {
return nil, err
@@ -259,7 +256,7 @@ func (c *Client) GetWeakSubjectivity(ctx context.Context) (*WeakSubjectivityData
if err != nil {
return nil, err
}
v := &apibeacon.GetWeakSubjectivityResponse{}
v := &structs.GetWeakSubjectivityResponse{}
err = json.Unmarshal(body, v)
if err != nil {
return nil, err
@@ -285,7 +282,7 @@ func (c *Client) GetWeakSubjectivity(ctx context.Context) (*WeakSubjectivityData
// SubmitChangeBLStoExecution calls a beacon API endpoint to set the withdrawal addresses based on the given signed messages.
// If the API responds with something other than OK there will be failure messages associated to the corresponding request message.
func (c *Client) SubmitChangeBLStoExecution(ctx context.Context, request []*shared.SignedBLSToExecutionChange) error {
func (c *Client) SubmitChangeBLStoExecution(ctx context.Context, request []*structs.SignedBLSToExecutionChange) error {
u := c.BaseURL().ResolveReference(&url.URL{Path: changeBLStoExecutionPath})
body, err := json.Marshal(request)
if err != nil {
@@ -324,12 +321,12 @@ func (c *Client) SubmitChangeBLStoExecution(ctx context.Context, request []*shar
// GetBLStoExecutionChanges gets all the set withdrawal messages in the node's operation pool.
// Returns a struct representation of json response.
func (c *Client) GetBLStoExecutionChanges(ctx context.Context) (*beacon.BLSToExecutionChangesPoolResponse, error) {
func (c *Client) GetBLStoExecutionChanges(ctx context.Context) (*structs.BLSToExecutionChangesPoolResponse, error) {
body, err := c.Get(ctx, changeBLStoExecutionPath)
if err != nil {
return nil, err
}
poolResponse := &beacon.BLSToExecutionChangesPoolResponse{}
poolResponse := &structs.BLSToExecutionChangesPoolResponse{}
err = json.Unmarshal(body, poolResponse)
if err != nil {
return nil, err
@@ -338,7 +335,7 @@ func (c *Client) GetBLStoExecutionChanges(ctx context.Context) (*beacon.BLSToExe
}
type forkScheduleResponse struct {
Data []shared.Fork
Data []structs.Fork
}
func (fsr *forkScheduleResponse) OrderedForkSchedule() (forks.OrderedSchedule, error) {

View File

@@ -11,7 +11,7 @@ go_library(
importpath = "github.com/prysmaticlabs/prysm/v4/api/client/builder",
visibility = ["//visibility:public"],
deps = [
"//beacon-chain/rpc/eth/shared:go_default_library",
"//api/server/structs:go_default_library",
"//config/fieldparams:go_default_library",
"//consensus-types:go_default_library",
"//consensus-types/blocks:go_default_library",
@@ -40,7 +40,7 @@ go_test(
data = glob(["testdata/**"]),
embed = [":go_default_library"],
deps = [
"//beacon-chain/rpc/eth/shared:go_default_library",
"//api/server/structs:go_default_library",
"//config/fieldparams:go_default_library",
"//config/params:go_default_library",
"//consensus-types/blocks:go_default_library",

View File

@@ -14,7 +14,7 @@ import (
"text/template"
"github.com/pkg/errors"
"github.com/prysmaticlabs/prysm/v4/beacon-chain/rpc/eth/shared"
"github.com/prysmaticlabs/prysm/v4/api/server/structs"
"github.com/prysmaticlabs/prysm/v4/consensus-types/blocks"
"github.com/prysmaticlabs/prysm/v4/consensus-types/interfaces"
"github.com/prysmaticlabs/prysm/v4/consensus-types/primitives"
@@ -267,9 +267,9 @@ func (c *Client) RegisterValidator(ctx context.Context, svr []*ethpb.SignedValid
tracing.AnnotateError(span, err)
return err
}
vs := make([]*shared.SignedValidatorRegistration, len(svr))
vs := make([]*structs.SignedValidatorRegistration, len(svr))
for i := 0; i < len(svr); i++ {
vs[i] = shared.SignedValidatorRegistrationFromConsensus(svr[i])
vs[i] = structs.SignedValidatorRegistrationFromConsensus(svr[i])
}
body, err := json.Marshal(vs)
if err != nil {
@@ -294,7 +294,7 @@ func (c *Client) SubmitBlindedBlock(ctx context.Context, sb interfaces.ReadOnlyS
if err != nil {
return nil, nil, errors.Wrapf(err, "could not get protobuf block")
}
b, err := shared.SignedBlindedBeaconBlockBellatrixFromConsensus(&ethpb.SignedBlindedBeaconBlockBellatrix{Block: psb.Block, Signature: bytesutil.SafeCopyBytes(psb.Signature)})
b, err := structs.SignedBlindedBeaconBlockBellatrixFromConsensus(&ethpb.SignedBlindedBeaconBlockBellatrix{Block: psb.Block, Signature: bytesutil.SafeCopyBytes(psb.Signature)})
if err != nil {
return nil, nil, errors.Wrapf(err, "could not convert SignedBlindedBeaconBlockBellatrix to json marshalable type")
}
@@ -331,7 +331,7 @@ func (c *Client) SubmitBlindedBlock(ctx context.Context, sb interfaces.ReadOnlyS
if err != nil {
return nil, nil, errors.Wrapf(err, "could not get protobuf block")
}
b, err := shared.SignedBlindedBeaconBlockCapellaFromConsensus(&ethpb.SignedBlindedBeaconBlockCapella{Block: psb.Block, Signature: bytesutil.SafeCopyBytes(psb.Signature)})
b, err := structs.SignedBlindedBeaconBlockCapellaFromConsensus(&ethpb.SignedBlindedBeaconBlockCapella{Block: psb.Block, Signature: bytesutil.SafeCopyBytes(psb.Signature)})
if err != nil {
return nil, nil, errors.Wrapf(err, "could not convert SignedBlindedBeaconBlockCapella to json marshalable type")
}
@@ -368,7 +368,7 @@ func (c *Client) SubmitBlindedBlock(ctx context.Context, sb interfaces.ReadOnlyS
if err != nil {
return nil, nil, errors.Wrapf(err, "could not get protobuf block")
}
b, err := shared.SignedBlindedBeaconBlockDenebFromConsensus(&ethpb.SignedBlindedBeaconBlockDeneb{Message: psb.Message, Signature: bytesutil.SafeCopyBytes(psb.Signature)})
b, err := structs.SignedBlindedBeaconBlockDenebFromConsensus(&ethpb.SignedBlindedBeaconBlockDeneb{Message: psb.Message, Signature: bytesutil.SafeCopyBytes(psb.Signature)})
if err != nil {
return nil, nil, errors.Wrapf(err, "could not convert SignedBlindedBeaconBlockDeneb to json marshalable type")
}

View File

@@ -13,7 +13,7 @@ import (
"testing"
"github.com/prysmaticlabs/go-bitfield"
"github.com/prysmaticlabs/prysm/v4/beacon-chain/rpc/eth/shared"
"github.com/prysmaticlabs/prysm/v4/api/server/structs"
"github.com/prysmaticlabs/prysm/v4/config/params"
"github.com/prysmaticlabs/prysm/v4/consensus-types/blocks"
types "github.com/prysmaticlabs/prysm/v4/consensus-types/primitives"
@@ -376,7 +376,7 @@ func TestSubmitBlindedBlock(t *testing.T) {
Transport: roundtrip(func(r *http.Request) (*http.Response, error) {
require.Equal(t, postBlindedBeaconBlockPath, r.URL.Path)
require.Equal(t, "deneb", r.Header.Get("Eth-Consensus-Version"))
var req shared.SignedBlindedBeaconBlockDeneb
var req structs.SignedBlindedBeaconBlockDeneb
err := json.NewDecoder(r.Body).Decode(&req)
require.NoError(t, err)
block, err := req.ToConsensus()

View File

@@ -13,7 +13,7 @@ import (
"github.com/ethereum/go-ethereum/common/hexutil"
"github.com/prysmaticlabs/go-bitfield"
"github.com/prysmaticlabs/prysm/v4/beacon-chain/rpc/eth/shared"
"github.com/prysmaticlabs/prysm/v4/api/server/structs"
fieldparams "github.com/prysmaticlabs/prysm/v4/config/fieldparams"
"github.com/prysmaticlabs/prysm/v4/math"
v1 "github.com/prysmaticlabs/prysm/v4/proto/engine/v1"
@@ -38,7 +38,7 @@ func TestSignedValidatorRegistration_MarshalJSON(t *testing.T) {
},
Signature: make([]byte, 96),
}
a := shared.SignedValidatorRegistrationFromConsensus(svr)
a := structs.SignedValidatorRegistrationFromConsensus(svr)
je, err := json.Marshal(a)
require.NoError(t, err)
// decode with a struct w/ plain strings so we can check the string encoding of the hex fields
@@ -55,7 +55,7 @@ func TestSignedValidatorRegistration_MarshalJSON(t *testing.T) {
require.Equal(t, "0x000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000", un.Message.Pubkey)
t.Run("roundtrip", func(t *testing.T) {
b := &shared.SignedValidatorRegistration{}
b := &structs.SignedValidatorRegistration{}
if err := json.Unmarshal(je, b); err != nil {
require.NoError(t, err)
}
@@ -1718,7 +1718,7 @@ func TestUint256UnmarshalTooBig(t *testing.T) {
func TestMarshalBlindedBeaconBlockBodyBellatrix(t *testing.T) {
expected, err := os.ReadFile("testdata/blinded-block.json")
require.NoError(t, err)
b, err := shared.BlindedBeaconBlockBellatrixFromConsensus(&eth.BlindedBeaconBlockBellatrix{
b, err := structs.BlindedBeaconBlockBellatrixFromConsensus(&eth.BlindedBeaconBlockBellatrix{
Slot: 1,
ProposerIndex: 1,
ParentRoot: ezDecode(t, "0xcf8e0d4e9587369b2301d0790347320302cc0943d5a1884560367e8208d920f2"),
@@ -1748,7 +1748,7 @@ func TestMarshalBlindedBeaconBlockBodyBellatrix(t *testing.T) {
func TestMarshalBlindedBeaconBlockBodyCapella(t *testing.T) {
expected, err := os.ReadFile("testdata/blinded-block-capella.json")
require.NoError(t, err)
b, err := shared.BlindedBeaconBlockCapellaFromConsensus(&eth.BlindedBeaconBlockCapella{
b, err := structs.BlindedBeaconBlockCapellaFromConsensus(&eth.BlindedBeaconBlockCapella{
Slot: 1,
ProposerIndex: 1,
ParentRoot: ezDecode(t, "0xcf8e0d4e9587369b2301d0790347320302cc0943d5a1884560367e8208d920f2"),

View File

@@ -0,0 +1,50 @@
load("@prysm//tools/go:def.bzl", "go_library", "go_test")
go_library(
name = "go_default_library",
srcs = [
"block.go",
"conversions.go",
"conversions_block.go",
"conversions_state.go",
"endpoints_beacon.go",
"endpoints_blob.go",
"endpoints_builder.go",
"endpoints_config.go",
"endpoints_debug.go",
"endpoints_events.go",
"endpoints_lightclient.go",
"endpoints_node.go",
"endpoints_rewards.go",
"endpoints_validator.go",
"other.go",
"state.go",
],
importpath = "github.com/prysmaticlabs/prysm/v4/api/server/structs",
visibility = ["//visibility:public"],
deps = [
"//api/server:go_default_library",
"//beacon-chain/state:go_default_library",
"//config/fieldparams:go_default_library",
"//consensus-types/primitives:go_default_library",
"//consensus-types/validator:go_default_library",
"//container/slice:go_default_library",
"//encoding/bytesutil:go_default_library",
"//math:go_default_library",
"//proto/engine/v1:go_default_library",
"//proto/prysm/v1alpha1:go_default_library",
"@com_github_ethereum_go_ethereum//common:go_default_library",
"@com_github_ethereum_go_ethereum//common/hexutil:go_default_library",
"@com_github_pkg_errors//:go_default_library",
],
)
go_test(
name = "go_default_test",
srcs = ["conversions_test.go"],
embed = [":go_default_library"],
deps = [
"//proto/prysm/v1alpha1:go_default_library",
"//testing/require:go_default_library",
],
)

View File

@@ -1,4 +1,4 @@
package shared
package structs
type SignedBeaconBlock struct {
Message *BeaconBlock `json:"message"`

View File

@@ -1,4 +1,4 @@
package shared
package structs
import (
"fmt"
@@ -23,7 +23,7 @@ var errNilValue = errors.New("nil value")
func ValidatorFromConsensus(v *eth.Validator) *Validator {
return &Validator{
PublicKey: hexutil.Encode(v.PublicKey),
Pubkey: hexutil.Encode(v.PublicKey),
WithdrawalCredentials: hexutil.Encode(v.WithdrawalCredentials),
EffectiveBalance: fmt.Sprintf("%d", v.EffectiveBalance),
Slashed: v.Slashed,
@@ -1074,3 +1074,17 @@ func sszBytesToUint256String(b []byte) (string, error) {
}
return bi.String(), nil
}
func DepositSnapshotFromConsensus(ds *eth.DepositSnapshot) *DepositSnapshot {
finalized := make([]string, 0, len(ds.Finalized))
for _, f := range ds.Finalized {
finalized = append(finalized, hexutil.Encode(f))
}
return &DepositSnapshot{
Finalized: finalized,
DepositRoot: hexutil.Encode(ds.DepositRoot),
DepositCount: fmt.Sprintf("%d", ds.DepositCount),
ExecutionBlockHash: hexutil.Encode(ds.ExecutionHash),
ExecutionBlockHeight: fmt.Sprintf("%d", ds.ExecutionDepth),
}
}

View File

@@ -1,4 +1,4 @@
package shared
package structs
import (
"fmt"

View File

@@ -1,4 +1,4 @@
package shared
package structs
import (
"errors"

View File

@@ -0,0 +1,26 @@
package structs
import (
"testing"
eth "github.com/prysmaticlabs/prysm/v4/proto/prysm/v1alpha1"
"github.com/prysmaticlabs/prysm/v4/testing/require"
)
func TestDepositSnapshotFromConsensus(t *testing.T) {
ds := &eth.DepositSnapshot{
Finalized: [][]byte{{0xde, 0xad, 0xbe, 0xef}, {0xca, 0xfe, 0xba, 0xbe}},
DepositRoot: []byte{0xab, 0xcd},
DepositCount: 12345,
ExecutionHash: []byte{0x12, 0x34},
ExecutionDepth: 67890,
}
res := DepositSnapshotFromConsensus(ds)
require.NotNil(t, res)
require.DeepEqual(t, []string{"0xdeadbeef", "0xcafebabe"}, res.Finalized)
require.Equal(t, "0xabcd", res.DepositRoot)
require.Equal(t, "12345", res.DepositCount)
require.Equal(t, "0x1234", res.ExecutionBlockHash)
require.Equal(t, "67890", res.ExecutionBlockHeight)
}

View File

@@ -1,9 +1,7 @@
package beacon
package structs
import (
"encoding/json"
"github.com/prysmaticlabs/prysm/v4/beacon-chain/rpc/eth/shared"
)
type BlockRootResponse struct {
@@ -17,31 +15,31 @@ type BlockRoot struct {
}
type GetCommitteesResponse struct {
Data []*shared.Committee `json:"data"`
ExecutionOptimistic bool `json:"execution_optimistic"`
Finalized bool `json:"finalized"`
Data []*Committee `json:"data"`
ExecutionOptimistic bool `json:"execution_optimistic"`
Finalized bool `json:"finalized"`
}
type ListAttestationsResponse struct {
Data []*shared.Attestation `json:"data"`
Data []*Attestation `json:"data"`
}
type SubmitAttestationsRequest struct {
Data []*shared.Attestation `json:"data"`
Data []*Attestation `json:"data"`
}
type ListVoluntaryExitsResponse struct {
Data []*shared.SignedVoluntaryExit `json:"data"`
Data []*SignedVoluntaryExit `json:"data"`
}
type SubmitSyncCommitteeSignaturesRequest struct {
Data []*shared.SyncCommitteeMessage `json:"data"`
Data []*SyncCommitteeMessage `json:"data"`
}
type GetStateForkResponse struct {
Data *shared.Fork `json:"data"`
ExecutionOptimistic bool `json:"execution_optimistic"`
Finalized bool `json:"finalized"`
Data *Fork `json:"data"`
ExecutionOptimistic bool `json:"execution_optimistic"`
Finalized bool `json:"finalized"`
}
type GetFinalityCheckpointsResponse struct {
@@ -51,9 +49,9 @@ type GetFinalityCheckpointsResponse struct {
}
type FinalityCheckpoints struct {
PreviousJustified *shared.Checkpoint `json:"previous_justified"`
CurrentJustified *shared.Checkpoint `json:"current_justified"`
Finalized *shared.Checkpoint `json:"finalized"`
PreviousJustified *Checkpoint `json:"previous_justified"`
CurrentJustified *Checkpoint `json:"current_justified"`
Finalized *Checkpoint `json:"finalized"`
}
type GetGenesisResponse struct {
@@ -67,15 +65,15 @@ type Genesis struct {
}
type GetBlockHeadersResponse struct {
Data []*shared.SignedBeaconBlockHeaderContainer `json:"data"`
ExecutionOptimistic bool `json:"execution_optimistic"`
Finalized bool `json:"finalized"`
Data []*SignedBeaconBlockHeaderContainer `json:"data"`
ExecutionOptimistic bool `json:"execution_optimistic"`
Finalized bool `json:"finalized"`
}
type GetBlockHeaderResponse struct {
ExecutionOptimistic bool `json:"execution_optimistic"`
Finalized bool `json:"finalized"`
Data *shared.SignedBeaconBlockHeaderContainer `json:"data"`
ExecutionOptimistic bool `json:"execution_optimistic"`
Finalized bool `json:"finalized"`
Data *SignedBeaconBlockHeaderContainer `json:"data"`
}
type GetValidatorsRequest struct {
@@ -108,17 +106,6 @@ type ValidatorContainer struct {
Validator *Validator `json:"validator"`
}
type Validator struct {
Pubkey string `json:"pubkey"`
WithdrawalCredentials string `json:"withdrawal_credentials"`
EffectiveBalance string `json:"effective_balance"`
Slashed bool `json:"slashed"`
ActivationEligibilityEpoch string `json:"activation_eligibility_epoch"`
ActivationEpoch string `json:"activation_epoch"`
ExitEpoch string `json:"exit_epoch"`
WithdrawableEpoch string `json:"withdrawable_epoch"`
}
type ValidatorBalance struct {
Index string `json:"index"`
Balance string `json:"balance"`
@@ -141,9 +128,9 @@ type SignedBlock struct {
}
type GetBlockAttestationsResponse struct {
ExecutionOptimistic bool `json:"execution_optimistic"`
Finalized bool `json:"finalized"`
Data []*shared.Attestation `json:"data"`
ExecutionOptimistic bool `json:"execution_optimistic"`
Finalized bool `json:"finalized"`
Data []*Attestation `json:"data"`
}
type GetStateRootResponse struct {
@@ -178,13 +165,34 @@ type SyncCommitteeValidators struct {
}
type BLSToExecutionChangesPoolResponse struct {
Data []*shared.SignedBLSToExecutionChange `json:"data"`
Data []*SignedBLSToExecutionChange `json:"data"`
}
type GetAttesterSlashingsResponse struct {
Data []*shared.AttesterSlashing `json:"data"`
Data []*AttesterSlashing `json:"data"`
}
type GetProposerSlashingsResponse struct {
Data []*shared.ProposerSlashing `json:"data"`
Data []*ProposerSlashing `json:"data"`
}
type GetWeakSubjectivityResponse struct {
Data *WeakSubjectivityData `json:"data"`
}
type WeakSubjectivityData struct {
WsCheckpoint *Checkpoint `json:"ws_checkpoint"`
StateRoot string `json:"state_root"`
}
type GetDepositSnapshotResponse struct {
Data *DepositSnapshot `json:"data"`
}
type DepositSnapshot struct {
Finalized []string `json:"finalized"`
DepositRoot string `json:"deposit_root"`
DepositCount string `json:"deposit_count"`
ExecutionBlockHash string `json:"execution_block_hash"`
ExecutionBlockHeight string `json:"execution_block_height"`
}

View File

@@ -0,0 +1,14 @@
package structs
type SidecarsResponse struct {
Data []*Sidecar `json:"data"`
}
type Sidecar struct {
Index string `json:"index"`
Blob string `json:"blob"`
SignedBeaconBlockHeader *SignedBeaconBlockHeader `json:"signed_block_header"`
KzgCommitment string `json:"kzg_commitment"`
KzgProof string `json:"kzg_proof"`
CommitmentInclusionProof []string `json:"kzg_commitment_inclusion_proof"`
}

View File

@@ -1,4 +1,4 @@
package builder
package structs
type ExpectedWithdrawalsResponse struct {
Data []*ExpectedWithdrawal `json:"data"`

View File

@@ -1,6 +1,4 @@
package config
import "github.com/prysmaticlabs/prysm/v4/beacon-chain/rpc/eth/shared"
package structs
type GetDepositContractResponse struct {
Data *DepositContractData `json:"data"`
@@ -12,7 +10,7 @@ type DepositContractData struct {
}
type GetForkScheduleResponse struct {
Data []*shared.Fork `json:"data"`
Data []*Fork `json:"data"`
}
type GetSpecResponse struct {

View File

@@ -1,9 +1,7 @@
package debug
package structs
import (
"encoding/json"
"github.com/prysmaticlabs/prysm/v4/beacon-chain/rpc/eth/shared"
)
type GetBeaconStateV2Response struct {
@@ -24,18 +22,18 @@ type ForkChoiceHead struct {
}
type GetForkChoiceDumpResponse struct {
JustifiedCheckpoint *shared.Checkpoint `json:"justified_checkpoint"`
FinalizedCheckpoint *shared.Checkpoint `json:"finalized_checkpoint"`
JustifiedCheckpoint *Checkpoint `json:"justified_checkpoint"`
FinalizedCheckpoint *Checkpoint `json:"finalized_checkpoint"`
ForkChoiceNodes []*ForkChoiceNode `json:"fork_choice_nodes"`
ExtraData *ForkChoiceDumpExtraData `json:"extra_data"`
}
type ForkChoiceDumpExtraData struct {
UnrealizedJustifiedCheckpoint *shared.Checkpoint `json:"unrealized_justified_checkpoint"`
UnrealizedFinalizedCheckpoint *shared.Checkpoint `json:"unrealized_finalized_checkpoint"`
ProposerBoostRoot string `json:"proposer_boost_root"`
PreviousProposerBoostRoot string `json:"previous_proposer_boost_root"`
HeadRoot string `json:"head_root"`
UnrealizedJustifiedCheckpoint *Checkpoint `json:"unrealized_justified_checkpoint"`
UnrealizedFinalizedCheckpoint *Checkpoint `json:"unrealized_finalized_checkpoint"`
ProposerBoostRoot string `json:"proposer_boost_root"`
PreviousProposerBoostRoot string `json:"previous_proposer_boost_root"`
HeadRoot string `json:"head_root"`
}
type ForkChoiceNode struct {

View File

@@ -1,9 +1,7 @@
package events
package structs
import (
"encoding/json"
"github.com/prysmaticlabs/prysm/v4/beacon-chain/rpc/eth/shared"
)
type HeadEvent struct {
@@ -23,13 +21,13 @@ type BlockEvent struct {
}
type AggregatedAttEventSource struct {
Aggregate *shared.Attestation `json:"aggregate"`
Aggregate *Attestation `json:"aggregate"`
}
type UnaggregatedAttEventSource struct {
AggregationBits string `json:"aggregation_bits"`
Data *shared.AttestationData `json:"data"`
Signature string `json:"signature"`
AggregationBits string `json:"aggregation_bits"`
Data *AttestationData `json:"data"`
Signature string `json:"signature"`
}
type FinalizedCheckpointEvent struct {
@@ -71,18 +69,18 @@ type PayloadAttributesV1 struct {
}
type PayloadAttributesV2 struct {
Timestamp string `json:"timestamp"`
PrevRandao string `json:"prev_randao"`
SuggestedFeeRecipient string `json:"suggested_fee_recipient"`
Withdrawals []*shared.Withdrawal `json:"withdrawals"`
Timestamp string `json:"timestamp"`
PrevRandao string `json:"prev_randao"`
SuggestedFeeRecipient string `json:"suggested_fee_recipient"`
Withdrawals []*Withdrawal `json:"withdrawals"`
}
type PayloadAttributesV3 struct {
Timestamp string `json:"timestamp"`
PrevRandao string `json:"prev_randao"`
SuggestedFeeRecipient string `json:"suggested_fee_recipient"`
Withdrawals []*shared.Withdrawal `json:"withdrawals"`
ParentBeaconBlockRoot string `json:"parent_beacon_block_root"`
Timestamp string `json:"timestamp"`
PrevRandao string `json:"prev_randao"`
SuggestedFeeRecipient string `json:"suggested_fee_recipient"`
Withdrawals []*Withdrawal `json:"withdrawals"`
ParentBeaconBlockRoot string `json:"parent_beacon_block_root"`
}
type BlobSidecarEvent struct {
@@ -99,11 +97,11 @@ type LightClientFinalityUpdateEvent struct {
}
type LightClientFinalityUpdate struct {
AttestedHeader *shared.BeaconBlockHeader `json:"attested_header"`
FinalizedHeader *shared.BeaconBlockHeader `json:"finalized_header"`
FinalityBranch []string `json:"finality_branch"`
SyncAggregate *shared.SyncAggregate `json:"sync_aggregate"`
SignatureSlot string `json:"signature_slot"`
AttestedHeader *BeaconBlockHeader `json:"attested_header"`
FinalizedHeader *BeaconBlockHeader `json:"finalized_header"`
FinalityBranch []string `json:"finality_branch"`
SyncAggregate *SyncAggregate `json:"sync_aggregate"`
SignatureSlot string `json:"signature_slot"`
}
type LightClientOptimisticUpdateEvent struct {
@@ -112,7 +110,7 @@ type LightClientOptimisticUpdateEvent struct {
}
type LightClientOptimisticUpdate struct {
AttestedHeader *shared.BeaconBlockHeader `json:"attested_header"`
SyncAggregate *shared.SyncAggregate `json:"sync_aggregate"`
SignatureSlot string `json:"signature_slot"`
AttestedHeader *BeaconBlockHeader `json:"attested_header"`
SyncAggregate *SyncAggregate `json:"sync_aggregate"`
SignatureSlot string `json:"signature_slot"`
}

View File

@@ -0,0 +1,31 @@
package structs
type LightClientBootstrapResponse struct {
Version string `json:"version"`
Data *LightClientBootstrap `json:"data"`
}
type LightClientBootstrap struct {
Header *BeaconBlockHeader `json:"header"`
CurrentSyncCommittee *SyncCommittee `json:"current_sync_committee"`
CurrentSyncCommitteeBranch []string `json:"current_sync_committee_branch"`
}
type LightClientUpdate struct {
AttestedHeader *BeaconBlockHeader `json:"attested_header"`
NextSyncCommittee *SyncCommittee `json:"next_sync_committee,omitempty"`
FinalizedHeader *BeaconBlockHeader `json:"finalized_header,omitempty"`
SyncAggregate *SyncAggregate `json:"sync_aggregate"`
NextSyncCommitteeBranch []string `json:"next_sync_committee_branch,omitempty"`
FinalityBranch []string `json:"finality_branch,omitempty"`
SignatureSlot string `json:"signature_slot"`
}
type LightClientUpdateWithVersion struct {
Version string `json:"version"`
Data *LightClientUpdate `json:"data"`
}
type LightClientUpdatesByRangeResponse struct {
Updates []*LightClientUpdateWithVersion `json:"updates"`
}

View File

@@ -1,4 +1,4 @@
package node
package structs
type SyncStatusResponse struct {
Data *SyncStatusResponseData `json:"data"`
@@ -63,3 +63,11 @@ type GetVersionResponse struct {
type Version struct {
Version string `json:"version"`
}
type AddrRequest struct {
Addr string `json:"addr"`
}
type PeersResponse struct {
Peers []*Peer `json:"peers"`
}

View File

@@ -1,4 +1,4 @@
package rewards
package structs
type BlockRewardsResponse struct {
Data *BlockRewards `json:"data"`

View File

@@ -1,37 +1,37 @@
package validator
package structs
import (
"encoding/json"
"github.com/prysmaticlabs/prysm/v4/beacon-chain/rpc/eth/shared"
"github.com/prysmaticlabs/prysm/v4/consensus-types/primitives"
)
type AggregateAttestationResponse struct {
Data *shared.Attestation `json:"data"`
Data *Attestation `json:"data"`
}
type SubmitContributionAndProofsRequest struct {
Data []*shared.SignedContributionAndProof `json:"data"`
Data []*SignedContributionAndProof `json:"data"`
}
type SubmitAggregateAndProofsRequest struct {
Data []*shared.SignedAggregateAttestationAndProof `json:"data"`
Data []*SignedAggregateAttestationAndProof `json:"data"`
}
type SubmitSyncCommitteeSubscriptionsRequest struct {
Data []*shared.SyncCommitteeSubscription `json:"data"`
Data []*SyncCommitteeSubscription `json:"data"`
}
type SubmitBeaconCommitteeSubscriptionsRequest struct {
Data []*shared.BeaconCommitteeSubscription `json:"data"`
Data []*BeaconCommitteeSubscription `json:"data"`
}
type GetAttestationDataResponse struct {
Data *shared.AttestationData `json:"data"`
Data *AttestationData `json:"data"`
}
type ProduceSyncCommitteeContributionResponse struct {
Data *shared.SyncCommitteeContribution `json:"data"`
Data *SyncCommitteeContribution `json:"data"`
}
type GetAttesterDutiesResponse struct {
@@ -90,3 +90,31 @@ type Liveness struct {
Index string `json:"index"`
IsLive bool `json:"is_live"`
}
type GetValidatorCountResponse struct {
ExecutionOptimistic string `json:"execution_optimistic"`
Finalized string `json:"finalized"`
Data []*ValidatorCount `json:"data"`
}
type ValidatorCount struct {
Status string `json:"status"`
Count string `json:"count"`
}
type GetValidatorPerformanceRequest struct {
PublicKeys [][]byte `json:"public_keys,omitempty"`
Indices []primitives.ValidatorIndex `json:"indices,omitempty"`
}
type GetValidatorPerformanceResponse struct {
PublicKeys [][]byte `json:"public_keys,omitempty"`
CorrectlyVotedSource []bool `json:"correctly_voted_source,omitempty"`
CorrectlyVotedTarget []bool `json:"correctly_voted_target,omitempty"`
CorrectlyVotedHead []bool `json:"correctly_voted_head,omitempty"`
CurrentEffectiveBalances []uint64 `json:"current_effective_balances,omitempty"`
BalancesBeforeEpochTransition []uint64 `json:"balances_before_epoch_transition,omitempty"`
BalancesAfterEpochTransition []uint64 `json:"balances_after_epoch_transition,omitempty"`
MissingValidators [][]byte `json:"missing_validators,omitempty"`
InactivityScores []uint64 `json:"inactivity_scores,omitempty"`
}

View File

@@ -1,7 +1,7 @@
package shared
package structs
type Validator struct {
PublicKey string `json:"pubkey"`
Pubkey string `json:"pubkey"`
WithdrawalCredentials string `json:"withdrawal_credentials"`
EffectiveBalance string `json:"effective_balance"`
Slashed bool `json:"slashed"`

View File

@@ -1,4 +1,4 @@
package shared
package structs
type BeaconState struct {
GenesisTime string `json:"genesis_time"`

View File

@@ -557,17 +557,9 @@ func (s *Service) RecentBlockSlot(root [32]byte) (primitives.Slot, error) {
return s.cfg.ForkChoiceStore.Slot(root)
}
// inRegularSync applies the following heuristics to decide if the node is in
// regular sync mode vs init sync mode using only forkchoice.
// It checks that the highest received block is behind the current time by at least 2 epochs
// and that it was imported at least one epoch late if both of these
// tests pass then the node is in init sync. The caller of this function MUST
// have a lock on forkchoice
// inRegularSync queries the initial sync service to
// determine if the node is in regular sync or is still
// syncing to the head of the chain.
func (s *Service) inRegularSync() bool {
currentSlot := s.CurrentSlot()
fc := s.cfg.ForkChoiceStore
if currentSlot-fc.HighestReceivedBlockSlot() < 2*params.BeaconConfig().SlotsPerEpoch {
return true
}
return fc.HighestReceivedBlockDelay() < params.BeaconConfig().SlotsPerEpoch
return s.cfg.SyncChecker.Synced()
}

View File

@@ -593,26 +593,3 @@ func TestService_IsFinalized(t *testing.T) {
require.Equal(t, true, c.IsFinalized(ctx, br))
require.Equal(t, false, c.IsFinalized(ctx, [32]byte{'c'}))
}
func TestService_inRegularSync(t *testing.T) {
ctx := context.Background()
c := &Service{cfg: &config{ForkChoiceStore: doublylinkedtree.New()}, head: &head{root: [32]byte{'b'}}}
ojc := &ethpb.Checkpoint{Root: params.BeaconConfig().ZeroHash[:]}
ofc := &ethpb.Checkpoint{Root: params.BeaconConfig().ZeroHash[:]}
st, blkRoot, err := prepareForkchoiceState(ctx, 100, [32]byte{'a'}, [32]byte{}, params.BeaconConfig().ZeroHash, ojc, ofc)
require.NoError(t, err)
require.NoError(t, c.cfg.ForkChoiceStore.InsertNode(ctx, st, blkRoot))
require.Equal(t, false, c.inRegularSync())
c.SetGenesisTime(time.Now().Add(time.Second * time.Duration(-1*int64(params.BeaconConfig().SlotsPerEpoch)*int64(params.BeaconConfig().SecondsPerSlot))))
st, blkRoot, err = prepareForkchoiceState(ctx, 128, [32]byte{'b'}, [32]byte{'a'}, params.BeaconConfig().ZeroHash, ojc, ofc)
require.NoError(t, err)
require.NoError(t, c.cfg.ForkChoiceStore.InsertNode(ctx, st, blkRoot))
require.Equal(t, false, c.inRegularSync())
c.SetGenesisTime(time.Now().Add(time.Second * time.Duration(-5*int64(params.BeaconConfig().SlotsPerEpoch)*int64(params.BeaconConfig().SecondsPerSlot))))
require.Equal(t, true, c.inRegularSync())
c.SetGenesisTime(time.Now().Add(time.Second * time.Duration(-1*int64(params.BeaconConfig().SlotsPerEpoch)*int64(params.BeaconConfig().SecondsPerSlot))))
c.cfg.ForkChoiceStore.SetGenesisTime(uint64(time.Now().Unix()))
require.Equal(t, true, c.inRegularSync())
}

View File

@@ -198,3 +198,10 @@ func WithBlobStorage(b *filesystem.BlobStorage) Option {
return nil
}
}
func WithSyncChecker(checker Checker) Option {
return func(s *Service) error {
s.cfg.SyncChecker = checker
return nil
}
}

View File

@@ -2046,7 +2046,9 @@ func TestFillMissingBlockPayloadId_PrepareAllPayloads(t *testing.T) {
// boost. It alters the genesisTime tracked by the store.
func driftGenesisTime(s *Service, slot, delay int64) {
offset := slot*int64(params.BeaconConfig().SecondsPerSlot) + delay
s.SetGenesisTime(time.Unix(time.Now().Unix()-offset, 0))
newTime := time.Unix(time.Now().Unix()-offset, 0)
s.SetGenesisTime(newTime)
s.cfg.ForkChoiceStore.SetGenesisTime(uint64(newTime.Unix()))
}
func TestMissingIndices(t *testing.T) {

View File

@@ -93,6 +93,13 @@ type config struct {
BlockFetcher execution.POWBlockFetcher
FinalizedStateAtStartUp state.BeaconState
ExecutionEngineCaller execution.EngineCaller
SyncChecker Checker
}
// Checker is an interface used to determine if a node is in initial sync
// or regular sync.
type Checker interface {
Synced() bool
}
var ErrMissingClockSetter = errors.New("blockchain Service initialized without a startup.ClockSetter")

View File

@@ -6,6 +6,7 @@ import (
"testing"
"github.com/prysmaticlabs/prysm/v4/async/event"
mock "github.com/prysmaticlabs/prysm/v4/beacon-chain/blockchain/testing"
"github.com/prysmaticlabs/prysm/v4/beacon-chain/cache"
"github.com/prysmaticlabs/prysm/v4/beacon-chain/cache/depositcache"
statefeed "github.com/prysmaticlabs/prysm/v4/beacon-chain/core/feed/state"
@@ -118,6 +119,7 @@ func minimalTestService(t *testing.T, opts ...Option) (*Service, *testServiceReq
WithDepositCache(dc),
WithTrackedValidatorsCache(cache.NewTrackedValidatorsCache()),
WithBlobStorage(filesystem.NewEphemeralBlobStorage(t)),
WithSyncChecker(mock.MockChecker{}),
}
// append the variadic opts so they override the defaults by being processed afterwards
opts = append(defOpts, opts...)

View File

@@ -180,6 +180,14 @@ func (mon *MockOperationNotifier) OperationFeed() *event.Feed {
return mon.feed
}
// MockChecker is a mock sync checker.
type MockChecker struct{}
// Synced returns true.
func (_ MockChecker) Synced() bool {
return true
}
// ReceiveBlockInitialSync mocks ReceiveBlockInitialSync method in chain service.
func (s *ChainService) ReceiveBlockInitialSync(ctx context.Context, block interfaces.ReadOnlySignedBeaconBlock, _ [32]byte) error {
if s.State == nil {

View File

@@ -796,7 +796,7 @@ func TestFinalizedDeposits_ReturnsTrieCorrectly(t *testing.T) {
err = dc.InsertFinalizedDeposits(context.Background(), 4, [32]byte{}, 0)
require.NoError(t, err)
// Mimick finalized deposit trie fetch.
// Mimic finalized deposit trie fetch.
fd, err := dc.FinalizedDeposits(context.Background())
require.NoError(t, err)
deps := dc.NonFinalizedDeposits(context.Background(), fd.MerkleTrieIndex(), nil)

View File

@@ -493,7 +493,12 @@ func (s *Service) GetPayloadBodiesByHash(ctx context.Context, executionBlockHash
return result, nil
}
err := s.rpcClient.CallContext(ctx, &result, GetPayloadBodiesByHashV1, executionBlockHashes)
if err != nil {
return nil, handleRPCError(err)
}
if len(result) != len(executionBlockHashes) {
return nil, fmt.Errorf("mismatch of payloads retrieved from the execution client: %d vs %d", len(result), len(executionBlockHashes))
}
for i, item := range result {
if item == nil {
result[i] = &pb.ExecutionPayloadBodyV1{
@@ -502,7 +507,7 @@ func (s *Service) GetPayloadBodiesByHash(ctx context.Context, executionBlockHash
}
}
}
return result, handleRPCError(err)
return result, nil
}
// GetPayloadBodiesByRange returns the relevant payload bodies for the provided range.
@@ -635,6 +640,8 @@ func (s *Service) retrievePayloadFromExecutionHash(ctx context.Context, executio
return fullPayloadFromPayloadBody(header, bdy, version)
}
// This method assumes that the provided execution hashes are all valid and part of the
// canonical chain.
func (s *Service) retrievePayloadsFromExecutionHashes(
ctx context.Context,
executionHashes []common.Hash,

View File

@@ -912,6 +912,73 @@ func TestReconstructFullBellatrixBlockBatch(t *testing.T) {
require.NoError(t, err)
require.DeepEqual(t, payload, got.Proto())
})
t.Run("handles invalid response from EL", func(t *testing.T) {
fix := fixtures()
payload, ok := fix["ExecutionPayload"].(*pb.ExecutionPayload)
require.Equal(t, true, ok)
jsonPayload := make(map[string]interface{})
tx := gethtypes.NewTransaction(
0,
common.HexToAddress("095e7baea6a6c7c4c2dfeb977efac326af552d87"),
big.NewInt(0), 0, big.NewInt(0),
nil,
)
txs := []*gethtypes.Transaction{tx}
encodedBinaryTxs := make([][]byte, 1)
var err error
encodedBinaryTxs[0], err = txs[0].MarshalBinary()
require.NoError(t, err)
payload.Transactions = encodedBinaryTxs
jsonPayload["transactions"] = []hexutil.Bytes{encodedBinaryTxs[0]}
wrappedPayload, err := blocks.WrappedExecutionPayload(payload)
require.NoError(t, err)
header, err := blocks.PayloadToHeader(wrappedPayload)
require.NoError(t, err)
bellatrixBlock := util.NewBlindedBeaconBlockBellatrix()
wanted := util.NewBeaconBlockBellatrix()
wanted.Block.Slot = 1
// Make sure block hash is the zero hash.
bellatrixBlock.Block.Body.ExecutionPayloadHeader.BlockHash = make([]byte, 32)
bellatrixBlock.Block.Slot = 1
wrappedEmpty, err := blocks.NewSignedBeaconBlock(bellatrixBlock)
require.NoError(t, err)
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
defer func() {
require.NoError(t, r.Body.Close())
}()
respJSON := map[string]interface{}{
"jsonrpc": "2.0",
"id": 1,
"result": []map[string]interface{}{},
}
require.NoError(t, json.NewEncoder(w).Encode(respJSON))
}))
defer srv.Close()
rpcClient, err := rpc.DialHTTP(srv.URL)
require.NoError(t, err)
defer rpcClient.Close()
service := &Service{}
service.rpcClient = rpcClient
blindedBlock := util.NewBlindedBeaconBlockBellatrix()
blindedBlock.Block.Body.ExecutionPayloadHeader = header
wrapped, err := blocks.NewSignedBeaconBlock(blindedBlock)
require.NoError(t, err)
copiedWrapped, err := wrapped.Copy()
require.NoError(t, err)
_, err = service.ReconstructFullBellatrixBlockBatch(ctx, []interfaces.ReadOnlySignedBeaconBlock{wrappedEmpty, wrapped, copiedWrapped})
require.ErrorContains(t, "mismatch of payloads retrieved from the execution client", err)
})
}
func TestServer_getPowBlockHashAtTerminalTotalDifficulty(t *testing.T) {
@@ -2166,7 +2233,7 @@ func TestCapella_PayloadBodiesByHash(t *testing.T) {
bRoot := [32]byte{}
copy(bRoot[:], "hash")
results, err := service.GetPayloadBodiesByHash(ctx, []common.Hash{bRoot})
results, err := service.GetPayloadBodiesByHash(ctx, []common.Hash{bRoot, bRoot})
require.NoError(t, err)
require.Equal(t, 2, len(results))

View File

@@ -479,10 +479,10 @@ func (s *Service) handleETH1FollowDistance() {
// If the last requested block has not changed,
// we do not request batched logs as this means there are no new
// logs for the powchain service to process. Also it is a potential
// logs for the execution service to process. Also it is a potential
// failure condition as would mean we have not respected the protocol threshold.
if s.latestEth1Data.LastRequestedBlock == s.latestEth1Data.BlockHeight {
log.Error("Beacon node is not respecting the follow distance")
log.WithField("lastBlockNumber", s.latestEth1Data.LastRequestedBlock).Error("Beacon node is not respecting the follow distance. EL client is syncing.")
return
}
if err := s.requestBatchedHeadersAndLogs(ctx); err != nil {

View File

@@ -77,5 +77,6 @@ go_test(
"//testing/assert:go_default_library",
"//testing/require:go_default_library",
"//testing/util:go_default_library",
"//time/slots:go_default_library",
],
)

View File

@@ -93,13 +93,13 @@ func (n *Node) updateBestDescendant(ctx context.Context, justifiedEpoch, finaliz
// Any node with different finalized or justified epoch than
// the ones in fork choice store should not be viable to head.
func (n *Node) viableForHead(justifiedEpoch, currentEpoch primitives.Epoch) bool {
justified := justifiedEpoch == n.justifiedEpoch || justifiedEpoch == 0
if !justified && justifiedEpoch+1 == currentEpoch {
if n.unrealizedJustifiedEpoch+1 >= currentEpoch && n.justifiedEpoch+2 >= currentEpoch {
justified = true
}
if justifiedEpoch == 0 {
return true
}
return justified
// We use n.justifiedEpoch as the voting source because:
// 1. if this node is from current epoch, n.justifiedEpoch is the realized justification epoch.
// 2. if this node is from a previous epoch, n.justifiedEpoch has already been updated to the unrealized justification epoch.
return n.justifiedEpoch == justifiedEpoch || n.justifiedEpoch+2 >= currentEpoch
}
func (n *Node) leadsToViableHead(justifiedEpoch, currentEpoch primitives.Epoch) bool {

View File

@@ -146,7 +146,9 @@ func TestNode_ViableForHead(t *testing.T) {
{&Node{}, 1, false},
{&Node{finalizedEpoch: 1, justifiedEpoch: 1}, 1, true},
{&Node{finalizedEpoch: 1, justifiedEpoch: 1}, 2, false},
{&Node{finalizedEpoch: 3, justifiedEpoch: 4}, 4, true},
{&Node{finalizedEpoch: 1, justifiedEpoch: 2}, 3, false},
{&Node{finalizedEpoch: 1, justifiedEpoch: 2}, 4, false},
{&Node{finalizedEpoch: 1, justifiedEpoch: 3}, 4, true},
}
for _, tc := range tests {
got := tc.n.viableForHead(tc.justifiedEpoch, 5)

View File

@@ -8,6 +8,7 @@ import (
"github.com/prysmaticlabs/prysm/v4/config/params"
"github.com/prysmaticlabs/prysm/v4/consensus-types/primitives"
"github.com/prysmaticlabs/prysm/v4/testing/require"
"github.com/prysmaticlabs/prysm/v4/time/slots"
)
func TestStore_SetUnrealizedEpochs(t *testing.T) {
@@ -63,14 +64,14 @@ func TestStore_UpdateUnrealizedCheckpoints(t *testing.T) {
func TestStore_LongFork(t *testing.T) {
f := setup(1, 1)
ctx := context.Background()
state, blkRoot, err := prepareForkchoiceState(ctx, 100, [32]byte{'a'}, params.BeaconConfig().ZeroHash, [32]byte{'A'}, 1, 1)
state, blkRoot, err := prepareForkchoiceState(ctx, 75, [32]byte{'a'}, params.BeaconConfig().ZeroHash, [32]byte{'A'}, 1, 1)
require.NoError(t, err)
require.NoError(t, f.InsertNode(ctx, state, blkRoot))
state, blkRoot, err = prepareForkchoiceState(ctx, 101, [32]byte{'b'}, [32]byte{'a'}, [32]byte{'B'}, 1, 1)
state, blkRoot, err = prepareForkchoiceState(ctx, 80, [32]byte{'b'}, [32]byte{'a'}, [32]byte{'B'}, 1, 1)
require.NoError(t, err)
require.NoError(t, f.InsertNode(ctx, state, blkRoot))
require.NoError(t, f.store.setUnrealizedJustifiedEpoch([32]byte{'b'}, 2))
state, blkRoot, err = prepareForkchoiceState(ctx, 102, [32]byte{'c'}, [32]byte{'b'}, [32]byte{'C'}, 1, 1)
state, blkRoot, err = prepareForkchoiceState(ctx, 95, [32]byte{'c'}, [32]byte{'b'}, [32]byte{'C'}, 1, 1)
require.NoError(t, err)
require.NoError(t, f.InsertNode(ctx, state, blkRoot))
require.NoError(t, f.store.setUnrealizedJustifiedEpoch([32]byte{'c'}, 2))
@@ -78,27 +79,28 @@ func TestStore_LongFork(t *testing.T) {
// Add an attestation to c, it is head
f.ProcessAttestation(ctx, []uint64{0}, [32]byte{'c'}, 1)
f.justifiedBalances = []uint64{100}
c := f.store.nodeByRoot[[32]byte{'c'}]
require.Equal(t, primitives.Epoch(2), slots.ToEpoch(c.slot))
driftGenesisTime(f, c.slot, 0)
headRoot, err := f.Head(ctx)
require.NoError(t, err)
require.Equal(t, [32]byte{'c'}, headRoot)
// D is head even though its weight is lower.
// c remains the head even if a block d with higher realized justification is seen
ha := [32]byte{'a'}
state, blkRoot, err = prepareForkchoiceState(ctx, 103, [32]byte{'d'}, [32]byte{'b'}, [32]byte{'D'}, 2, 1)
require.NoError(t, err)
require.NoError(t, f.InsertNode(ctx, state, blkRoot))
require.NoError(t, f.UpdateJustifiedCheckpoint(ctx, &forkchoicetypes.Checkpoint{Epoch: 2, Root: ha}))
headRoot, err = f.Head(ctx)
require.NoError(t, err)
require.Equal(t, [32]byte{'d'}, headRoot)
require.Equal(t, uint64(0), f.store.nodeByRoot[[32]byte{'d'}].weight)
require.Equal(t, uint64(100), f.store.nodeByRoot[[32]byte{'c'}].weight)
// Update unrealized justification, c becomes head
require.NoError(t, f.updateUnrealizedCheckpoints(ctx))
d := f.store.nodeByRoot[[32]byte{'d'}]
require.Equal(t, primitives.Epoch(3), slots.ToEpoch(d.slot))
driftGenesisTime(f, d.slot, 0)
require.Equal(t, true, d.viableForHead(f.store.justifiedCheckpoint.Epoch, slots.ToEpoch(d.slot)))
headRoot, err = f.Head(ctx)
require.NoError(t, err)
require.Equal(t, [32]byte{'c'}, headRoot)
require.Equal(t, uint64(0), f.store.nodeByRoot[[32]byte{'d'}].weight)
require.Equal(t, uint64(100), f.store.nodeByRoot[[32]byte{'c'}].weight)
}
// Epoch 1 Epoch 2 Epoch 3

View File

@@ -120,6 +120,7 @@ type BeaconNode struct {
BlobStorage *filesystem.BlobStorage
blobRetentionEpochs primitives.Epoch
verifyInitWaiter *verification.InitializerWaiter
syncChecker *initialsync.SyncChecker
}
// New creates a new node instance, sets up configuration options, and registers
@@ -192,6 +193,7 @@ func New(cliCtx *cli.Context, cancel context.CancelFunc, opts ...Option) (*Beaco
}
beacon.initialSyncComplete = make(chan struct{})
beacon.syncChecker = &initialsync.SyncChecker{}
for _, opt := range opts {
if err := opt(beacon); err != nil {
return nil, err
@@ -674,6 +676,7 @@ func (b *BeaconNode) registerBlockchainService(fc forkchoice.ForkChoicer, gs *st
blockchain.WithBlobStorage(b.BlobStorage),
blockchain.WithTrackedValidatorsCache(b.trackedValidatorsCache),
blockchain.WithPayloadIDCache(b.payloadIDCache),
blockchain.WithSyncChecker(b.syncChecker),
)
blockchainService, err := blockchain.NewService(b.ctx, opts...)
@@ -767,6 +770,7 @@ func (b *BeaconNode) registerInitialSyncService(complete chan struct{}) error {
opts := []initialsync.Option{
initialsync.WithVerifierWaiter(b.verifyInitWaiter),
initialsync.WithSyncChecker(b.syncChecker),
}
is := initialsync.NewService(b.ctx, &initialsync.Config{
DB: b.db,
@@ -892,7 +896,6 @@ func (b *BeaconNode) registerRPCService(router *mux.Router) error {
ExitPool: b.exitPool,
SlashingsPool: b.slashingsPool,
BLSChangesPool: b.blsToExecPool,
SlashingChecker: slasherService,
SyncCommitteeObjectPool: b.syncCommitteePool,
ExecutionChainService: web3Service,
ExecutionChainInfoFetcher: web3Service,

View File

@@ -27,6 +27,7 @@ import (
ethpb "github.com/prysmaticlabs/prysm/v4/proto/prysm/v1alpha1"
"github.com/prysmaticlabs/prysm/v4/runtime"
"github.com/prysmaticlabs/prysm/v4/runtime/interop"
"github.com/prysmaticlabs/prysm/v4/testing/assert"
"github.com/prysmaticlabs/prysm/v4/testing/require"
logTest "github.com/sirupsen/logrus/hooks/test"
"github.com/urfave/cli/v2"
@@ -91,6 +92,30 @@ func TestNodeStart_Ok(t *testing.T) {
require.LogsContain(t, hook, "Starting beacon node")
}
func TestNodeStart_SyncChecker(t *testing.T) {
hook := logTest.NewGlobal()
app := cli.App{}
tmp := fmt.Sprintf("%s/datadirtest2", t.TempDir())
set := flag.NewFlagSet("test", 0)
set.String("datadir", tmp, "node data directory")
set.String("suggested-fee-recipient", "0x6e35733c5af9B61374A128e6F85f553aF09ff89A", "fee recipient")
require.NoError(t, set.Set("suggested-fee-recipient", "0x6e35733c5af9B61374A128e6F85f553aF09ff89A"))
ctx, cancel := newCliContextWithCancel(&app, set)
node, err := New(ctx, cancel, WithBlockchainFlagOptions([]blockchain.Option{}),
WithBuilderFlagOptions([]builder.Option{}),
WithExecutionChainOptions([]execution.Option{}),
WithBlobStorage(filesystem.NewEphemeralBlobStorage(t)))
require.NoError(t, err)
go func() {
node.Start()
}()
time.Sleep(3 * time.Second)
assert.NotNil(t, node.syncChecker.Svc)
node.Close()
require.LogsContain(t, hook, "Starting beacon node")
}
func TestNodeStart_Ok_registerDeterministicGenesisService(t *testing.T) {
numValidators := uint64(1)
hook := logTest.NewGlobal()

View File

@@ -44,7 +44,6 @@ go_library(
"//beacon-chain/rpc/prysm/v1alpha1/node:go_default_library",
"//beacon-chain/rpc/prysm/v1alpha1/validator:go_default_library",
"//beacon-chain/rpc/prysm/validator:go_default_library",
"//beacon-chain/slasher:go_default_library",
"//beacon-chain/startup:go_default_library",
"//beacon-chain/state/stategen:go_default_library",
"//beacon-chain/sync:go_default_library",

View File

@@ -9,14 +9,15 @@ go_library(
"handlers_validator.go",
"log.go",
"server.go",
"structs.go",
],
importpath = "github.com/prysmaticlabs/prysm/v4/beacon-chain/rpc/eth/beacon",
visibility = ["//visibility:public"],
deps = [
"//api:go_default_library",
"//api/server:go_default_library",
"//api/server/structs:go_default_library",
"//beacon-chain/blockchain:go_default_library",
"//beacon-chain/cache/depositsnapshot:go_default_library",
"//beacon-chain/core/altair:go_default_library",
"//beacon-chain/core/blocks:go_default_library",
"//beacon-chain/core/feed:go_default_library",
@@ -75,7 +76,9 @@ go_test(
deps = [
"//api:go_default_library",
"//api/server:go_default_library",
"//api/server/structs:go_default_library",
"//beacon-chain/blockchain/testing:go_default_library",
"//beacon-chain/cache/depositsnapshot:go_default_library",
"//beacon-chain/core/signing:go_default_library",
"//beacon-chain/core/time:go_default_library",
"//beacon-chain/core/transition:go_default_library",
@@ -90,7 +93,6 @@ go_test(
"//beacon-chain/operations/voluntaryexits/mock:go_default_library",
"//beacon-chain/p2p/testing:go_default_library",
"//beacon-chain/rpc/core:go_default_library",
"//beacon-chain/rpc/eth/shared:go_default_library",
"//beacon-chain/rpc/eth/shared/testing:go_default_library",
"//beacon-chain/rpc/lookup:go_default_library",
"//beacon-chain/rpc/testutil:go_default_library",

View File

@@ -14,6 +14,8 @@ import (
"github.com/gorilla/mux"
"github.com/pkg/errors"
"github.com/prysmaticlabs/prysm/v4/api"
"github.com/prysmaticlabs/prysm/v4/api/server/structs"
"github.com/prysmaticlabs/prysm/v4/beacon-chain/cache/depositsnapshot"
corehelpers "github.com/prysmaticlabs/prysm/v4/beacon-chain/core/helpers"
"github.com/prysmaticlabs/prysm/v4/beacon-chain/core/transition"
"github.com/prysmaticlabs/prysm/v4/beacon-chain/db/filters"
@@ -76,7 +78,7 @@ func (s *Server) getBlock(ctx context.Context, w http.ResponseWriter, blk interf
httputil.HandleError(w, "Could not get block: "+err.Error(), http.StatusInternalServerError)
return
}
resp := &GetBlockResponse{Data: v2Resp.Data}
resp := &structs.GetBlockResponse{Data: v2Resp.Data}
httputil.WriteJson(w, resp)
}
@@ -121,7 +123,7 @@ func (s *Server) getBlockV2(ctx context.Context, w http.ResponseWriter, blk inte
}
finalized := s.FinalizationFetcher.IsFinalized(ctx, blkRoot)
getBlockHandler := func(get func(ctx context.Context, block interfaces.ReadOnlySignedBeaconBlock) (*GetBlockV2Response, error)) handled {
getBlockHandler := func(get func(ctx context.Context, block interfaces.ReadOnlySignedBeaconBlock) (*structs.GetBlockV2Response, error)) handled {
result, err := get(ctx, blk)
if result != nil {
result.Finalized = finalized
@@ -221,7 +223,7 @@ func (s *Server) getBlindedBlock(ctx context.Context, w http.ResponseWriter, blk
}
finalized := s.FinalizationFetcher.IsFinalized(ctx, blkRoot)
getBlockHandler := func(get func(ctx context.Context, block interfaces.ReadOnlySignedBeaconBlock) (*GetBlockV2Response, error)) handled {
getBlockHandler := func(get func(ctx context.Context, block interfaces.ReadOnlySignedBeaconBlock) (*structs.GetBlockV2Response, error)) handled {
result, err := get(ctx, blk)
if result != nil {
result.Finalized = finalized
@@ -290,7 +292,7 @@ func (s *Server) getBlindedBlockSSZ(ctx context.Context, w http.ResponseWriter,
httputil.HandleError(w, fmt.Sprintf("Unknown block type %T", blk), http.StatusInternalServerError)
}
func (*Server) getBlockPhase0(_ context.Context, blk interfaces.ReadOnlySignedBeaconBlock) (*GetBlockV2Response, error) {
func (*Server) getBlockPhase0(_ context.Context, blk interfaces.ReadOnlySignedBeaconBlock) (*structs.GetBlockV2Response, error) {
consensusBlk, err := blk.PbPhase0Block()
if err != nil {
return nil, err
@@ -298,22 +300,22 @@ func (*Server) getBlockPhase0(_ context.Context, blk interfaces.ReadOnlySignedBe
if consensusBlk == nil {
return nil, errNilBlock
}
respBlk := shared.SignedBeaconBlockFromConsensus(consensusBlk)
respBlk := structs.SignedBeaconBlockFromConsensus(consensusBlk)
jsonBytes, err := json.Marshal(respBlk.Message)
if err != nil {
return nil, err
}
return &GetBlockV2Response{
return &structs.GetBlockV2Response{
Version: version.String(version.Phase0),
ExecutionOptimistic: false,
Data: &SignedBlock{
Data: &structs.SignedBlock{
Message: jsonBytes,
Signature: respBlk.Signature,
},
}, nil
}
func (*Server) getBlockAltair(_ context.Context, blk interfaces.ReadOnlySignedBeaconBlock) (*GetBlockV2Response, error) {
func (*Server) getBlockAltair(_ context.Context, blk interfaces.ReadOnlySignedBeaconBlock) (*structs.GetBlockV2Response, error) {
consensusBlk, err := blk.PbAltairBlock()
if err != nil {
return nil, err
@@ -321,22 +323,22 @@ func (*Server) getBlockAltair(_ context.Context, blk interfaces.ReadOnlySignedBe
if consensusBlk == nil {
return nil, errNilBlock
}
respBlk := shared.SignedBeaconBlockAltairFromConsensus(consensusBlk)
respBlk := structs.SignedBeaconBlockAltairFromConsensus(consensusBlk)
jsonBytes, err := json.Marshal(respBlk.Message)
if err != nil {
return nil, err
}
return &GetBlockV2Response{
return &structs.GetBlockV2Response{
Version: version.String(version.Altair),
ExecutionOptimistic: false,
Data: &SignedBlock{
Data: &structs.SignedBlock{
Message: jsonBytes,
Signature: respBlk.Signature,
},
}, nil
}
func (s *Server) getBlockBellatrix(ctx context.Context, blk interfaces.ReadOnlySignedBeaconBlock) (*GetBlockV2Response, error) {
func (s *Server) getBlockBellatrix(ctx context.Context, blk interfaces.ReadOnlySignedBeaconBlock) (*structs.GetBlockV2Response, error) {
consensusBlk, err := blk.PbBellatrixBlock()
if err != nil {
// ErrUnsupportedField means that we have another block type
@@ -372,7 +374,7 @@ func (s *Server) getBlockBellatrix(ctx context.Context, blk interfaces.ReadOnlyS
if err != nil {
return nil, errors.Wrapf(err, "could not check if block is optimistic")
}
respBlk, err := shared.SignedBeaconBlockBellatrixFromConsensus(consensusBlk)
respBlk, err := structs.SignedBeaconBlockBellatrixFromConsensus(consensusBlk)
if err != nil {
return nil, err
}
@@ -380,17 +382,17 @@ func (s *Server) getBlockBellatrix(ctx context.Context, blk interfaces.ReadOnlyS
if err != nil {
return nil, err
}
return &GetBlockV2Response{
return &structs.GetBlockV2Response{
Version: version.String(version.Bellatrix),
ExecutionOptimistic: isOptimistic,
Data: &SignedBlock{
Data: &structs.SignedBlock{
Message: jsonBytes,
Signature: respBlk.Signature,
},
}, nil
}
func (s *Server) getBlockCapella(ctx context.Context, blk interfaces.ReadOnlySignedBeaconBlock) (*GetBlockV2Response, error) {
func (s *Server) getBlockCapella(ctx context.Context, blk interfaces.ReadOnlySignedBeaconBlock) (*structs.GetBlockV2Response, error) {
consensusBlk, err := blk.PbCapellaBlock()
if err != nil {
// ErrUnsupportedField means that we have another block type
@@ -426,7 +428,7 @@ func (s *Server) getBlockCapella(ctx context.Context, blk interfaces.ReadOnlySig
if err != nil {
return nil, errors.Wrapf(err, "could not check if block is optimistic")
}
respBlk, err := shared.SignedBeaconBlockCapellaFromConsensus(consensusBlk)
respBlk, err := structs.SignedBeaconBlockCapellaFromConsensus(consensusBlk)
if err != nil {
return nil, err
}
@@ -434,17 +436,17 @@ func (s *Server) getBlockCapella(ctx context.Context, blk interfaces.ReadOnlySig
if err != nil {
return nil, err
}
return &GetBlockV2Response{
return &structs.GetBlockV2Response{
Version: version.String(version.Capella),
ExecutionOptimistic: isOptimistic,
Data: &SignedBlock{
Data: &structs.SignedBlock{
Message: jsonBytes,
Signature: respBlk.Signature,
},
}, nil
}
func (s *Server) getBlockDeneb(ctx context.Context, blk interfaces.ReadOnlySignedBeaconBlock) (*GetBlockV2Response, error) {
func (s *Server) getBlockDeneb(ctx context.Context, blk interfaces.ReadOnlySignedBeaconBlock) (*structs.GetBlockV2Response, error) {
consensusBlk, err := blk.PbDenebBlock()
if err != nil {
// ErrUnsupportedGetter means that we have another block type
@@ -480,7 +482,7 @@ func (s *Server) getBlockDeneb(ctx context.Context, blk interfaces.ReadOnlySigne
if err != nil {
return nil, errors.Wrapf(err, "could not check if block is optimistic")
}
respBlk, err := shared.SignedBeaconBlockDenebFromConsensus(consensusBlk)
respBlk, err := structs.SignedBeaconBlockDenebFromConsensus(consensusBlk)
if err != nil {
return nil, err
}
@@ -488,10 +490,10 @@ func (s *Server) getBlockDeneb(ctx context.Context, blk interfaces.ReadOnlySigne
if err != nil {
return nil, err
}
return &GetBlockV2Response{
return &structs.GetBlockV2Response{
Version: version.String(version.Deneb),
ExecutionOptimistic: isOptimistic,
Data: &SignedBlock{
Data: &structs.SignedBlock{
Message: jsonBytes,
Signature: respBlk.Signature,
},
@@ -633,7 +635,7 @@ func (s *Server) getBlockDenebSSZ(ctx context.Context, blk interfaces.ReadOnlySi
return sszData, nil
}
func (s *Server) getBlindedBlockBellatrix(ctx context.Context, blk interfaces.ReadOnlySignedBeaconBlock) (*GetBlockV2Response, error) {
func (s *Server) getBlindedBlockBellatrix(ctx context.Context, blk interfaces.ReadOnlySignedBeaconBlock) (*structs.GetBlockV2Response, error) {
blindedConsensusBlk, err := blk.PbBlindedBellatrixBlock()
if err != nil {
// ErrUnsupportedField means that we have another block type
@@ -669,7 +671,7 @@ func (s *Server) getBlindedBlockBellatrix(ctx context.Context, blk interfaces.Re
if err != nil {
return nil, errors.Wrapf(err, "could not check if block is optimistic")
}
respBlk, err := shared.SignedBlindedBeaconBlockBellatrixFromConsensus(blindedConsensusBlk)
respBlk, err := structs.SignedBlindedBeaconBlockBellatrixFromConsensus(blindedConsensusBlk)
if err != nil {
return nil, err
}
@@ -677,17 +679,17 @@ func (s *Server) getBlindedBlockBellatrix(ctx context.Context, blk interfaces.Re
if err != nil {
return nil, err
}
return &GetBlockV2Response{
return &structs.GetBlockV2Response{
Version: version.String(version.Bellatrix),
ExecutionOptimistic: isOptimistic,
Data: &SignedBlock{
Data: &structs.SignedBlock{
Message: jsonBytes,
Signature: respBlk.Signature,
},
}, nil
}
func (s *Server) getBlindedBlockCapella(ctx context.Context, blk interfaces.ReadOnlySignedBeaconBlock) (*GetBlockV2Response, error) {
func (s *Server) getBlindedBlockCapella(ctx context.Context, blk interfaces.ReadOnlySignedBeaconBlock) (*structs.GetBlockV2Response, error) {
blindedConsensusBlk, err := blk.PbBlindedCapellaBlock()
if err != nil {
// ErrUnsupportedField means that we have another block type
@@ -723,7 +725,7 @@ func (s *Server) getBlindedBlockCapella(ctx context.Context, blk interfaces.Read
if err != nil {
return nil, errors.Wrapf(err, "could not check if block is optimistic")
}
respBlk, err := shared.SignedBlindedBeaconBlockCapellaFromConsensus(blindedConsensusBlk)
respBlk, err := structs.SignedBlindedBeaconBlockCapellaFromConsensus(blindedConsensusBlk)
if err != nil {
return nil, err
}
@@ -731,17 +733,17 @@ func (s *Server) getBlindedBlockCapella(ctx context.Context, blk interfaces.Read
if err != nil {
return nil, err
}
return &GetBlockV2Response{
return &structs.GetBlockV2Response{
Version: version.String(version.Capella),
ExecutionOptimistic: isOptimistic,
Data: &SignedBlock{
Data: &structs.SignedBlock{
Message: jsonBytes,
Signature: respBlk.Signature,
},
}, nil
}
func (s *Server) getBlindedBlockDeneb(ctx context.Context, blk interfaces.ReadOnlySignedBeaconBlock) (*GetBlockV2Response, error) {
func (s *Server) getBlindedBlockDeneb(ctx context.Context, blk interfaces.ReadOnlySignedBeaconBlock) (*structs.GetBlockV2Response, error) {
blindedConsensusBlk, err := blk.PbBlindedDenebBlock()
if err != nil {
// ErrUnsupportedGetter means that we have another block type
@@ -777,7 +779,7 @@ func (s *Server) getBlindedBlockDeneb(ctx context.Context, blk interfaces.ReadOn
if err != nil {
return nil, errors.Wrapf(err, "could not check if block is optimistic")
}
respBlk, err := shared.SignedBlindedBeaconBlockDenebFromConsensus(blindedConsensusBlk)
respBlk, err := structs.SignedBlindedBeaconBlockDenebFromConsensus(blindedConsensusBlk)
if err != nil {
return nil, err
}
@@ -785,10 +787,10 @@ func (s *Server) getBlindedBlockDeneb(ctx context.Context, blk interfaces.ReadOn
if err != nil {
return nil, err
}
return &GetBlockV2Response{
return &structs.GetBlockV2Response{
Version: version.String(version.Deneb),
ExecutionOptimistic: isOptimistic,
Data: &SignedBlock{
Data: &structs.SignedBlock{
Message: jsonBytes,
Signature: respBlk.Signature,
},
@@ -916,9 +918,9 @@ func (s *Server) GetBlockAttestations(w http.ResponseWriter, r *http.Request) {
}
consensusAtts := blk.Block().Body().Attestations()
atts := make([]*shared.Attestation, len(consensusAtts))
atts := make([]*structs.Attestation, len(consensusAtts))
for i, att := range consensusAtts {
atts[i] = shared.AttFromConsensus(att)
atts[i] = structs.AttFromConsensus(att)
}
root, err := blk.Block().HashTreeRoot()
if err != nil {
@@ -931,7 +933,7 @@ func (s *Server) GetBlockAttestations(w http.ResponseWriter, r *http.Request) {
return
}
resp := &GetBlockAttestationsResponse{
resp := &structs.GetBlockAttestationsResponse{
Data: atts,
ExecutionOptimistic: isOptimistic,
Finalized: s.FinalizationFetcher.IsFinalized(ctx, root),
@@ -1126,7 +1128,7 @@ func (s *Server) publishBlindedBlock(ctx context.Context, w http.ResponseWriter,
var consensusBlock *eth.GenericSignedBeaconBlock
var denebBlock *shared.SignedBlindedBeaconBlockDeneb
var denebBlock *structs.SignedBlindedBeaconBlockDeneb
if err = unmarshalStrict(body, &denebBlock); err == nil {
consensusBlock, err = denebBlock.ToGeneric()
if err == nil {
@@ -1147,7 +1149,7 @@ func (s *Server) publishBlindedBlock(ctx context.Context, w http.ResponseWriter,
return
}
var capellaBlock *shared.SignedBlindedBeaconBlockCapella
var capellaBlock *structs.SignedBlindedBeaconBlockCapella
if err = unmarshalStrict(body, &capellaBlock); err == nil {
consensusBlock, err = capellaBlock.ToGeneric()
if err == nil {
@@ -1168,7 +1170,7 @@ func (s *Server) publishBlindedBlock(ctx context.Context, w http.ResponseWriter,
return
}
var bellatrixBlock *shared.SignedBlindedBeaconBlockBellatrix
var bellatrixBlock *structs.SignedBlindedBeaconBlockBellatrix
if err = unmarshalStrict(body, &bellatrixBlock); err == nil {
consensusBlock, err = bellatrixBlock.ToGeneric()
if err == nil {
@@ -1189,7 +1191,7 @@ func (s *Server) publishBlindedBlock(ctx context.Context, w http.ResponseWriter,
return
}
var altairBlock *shared.SignedBeaconBlockAltair
var altairBlock *structs.SignedBeaconBlockAltair
if err = unmarshalStrict(body, &altairBlock); err == nil {
consensusBlock, err = altairBlock.ToGeneric()
if err == nil {
@@ -1210,7 +1212,7 @@ func (s *Server) publishBlindedBlock(ctx context.Context, w http.ResponseWriter,
return
}
var phase0Block *shared.SignedBeaconBlock
var phase0Block *structs.SignedBeaconBlock
if err = unmarshalStrict(body, &phase0Block); err == nil {
consensusBlock, err = phase0Block.ToGeneric()
if err == nil {
@@ -1421,7 +1423,7 @@ func (s *Server) publishBlock(ctx context.Context, w http.ResponseWriter, r *htt
var consensusBlock *eth.GenericSignedBeaconBlock
var denebBlockContents *shared.SignedBeaconBlockContentsDeneb
var denebBlockContents *structs.SignedBeaconBlockContentsDeneb
if err = unmarshalStrict(body, &denebBlockContents); err == nil {
consensusBlock, err = denebBlockContents.ToGeneric()
if err == nil {
@@ -1442,7 +1444,7 @@ func (s *Server) publishBlock(ctx context.Context, w http.ResponseWriter, r *htt
return
}
var capellaBlock *shared.SignedBeaconBlockCapella
var capellaBlock *structs.SignedBeaconBlockCapella
if err = unmarshalStrict(body, &capellaBlock); err == nil {
consensusBlock, err = capellaBlock.ToGeneric()
if err == nil {
@@ -1463,7 +1465,7 @@ func (s *Server) publishBlock(ctx context.Context, w http.ResponseWriter, r *htt
return
}
var bellatrixBlock *shared.SignedBeaconBlockBellatrix
var bellatrixBlock *structs.SignedBeaconBlockBellatrix
if err = unmarshalStrict(body, &bellatrixBlock); err == nil {
consensusBlock, err = bellatrixBlock.ToGeneric()
if err == nil {
@@ -1484,7 +1486,7 @@ func (s *Server) publishBlock(ctx context.Context, w http.ResponseWriter, r *htt
return
}
var altairBlock *shared.SignedBeaconBlockAltair
var altairBlock *structs.SignedBeaconBlockAltair
if err = unmarshalStrict(body, &altairBlock); err == nil {
consensusBlock, err = altairBlock.ToGeneric()
if err == nil {
@@ -1505,7 +1507,7 @@ func (s *Server) publishBlock(ctx context.Context, w http.ResponseWriter, r *htt
return
}
var phase0Block *shared.SignedBeaconBlock
var phase0Block *structs.SignedBeaconBlock
if err = unmarshalStrict(body, &phase0Block); err == nil {
consensusBlock, err = phase0Block.ToGeneric()
if err == nil {
@@ -1700,8 +1702,8 @@ func (s *Server) GetBlockRoot(w http.ResponseWriter, r *http.Request) {
httputil.HandleError(w, "Could not check if block is optimistic: "+err.Error(), http.StatusInternalServerError)
return
}
response := &BlockRootResponse{
Data: &BlockRoot{
response := &structs.BlockRootResponse{
Data: &structs.BlockRoot{
Root: hexutil.Encode(root),
},
ExecutionOptimistic: isOptimistic,
@@ -1736,8 +1738,8 @@ func (s *Server) GetStateFork(w http.ResponseWriter, r *http.Request) {
return
}
isFinalized := s.FinalizationFetcher.IsFinalized(ctx, blockRoot)
response := &GetStateForkResponse{
Data: &shared.Fork{
response := &structs.GetStateForkResponse{
Data: &structs.Fork{
PreviousVersion: hexutil.Encode(fork.PreviousVersion),
CurrentVersion: hexutil.Encode(fork.CurrentVersion),
Epoch: fmt.Sprintf("%d", fork.Epoch),
@@ -1800,7 +1802,7 @@ func (s *Server) GetCommittees(w http.ResponseWriter, r *http.Request) {
return
}
committeesPerSlot := corehelpers.SlotCommitteeCount(activeCount)
committees := make([]*shared.Committee, 0)
committees := make([]*structs.Committee, 0)
for slot := startSlot; slot <= endSlot; slot++ {
if rawSlot != "" && slot != primitives.Slot(sl) {
continue
@@ -1818,7 +1820,7 @@ func (s *Server) GetCommittees(w http.ResponseWriter, r *http.Request) {
for _, v := range committee {
validators = append(validators, strconv.FormatUint(uint64(v), 10))
}
committeeContainer := &shared.Committee{
committeeContainer := &structs.Committee{
Index: strconv.FormatUint(uint64(index), 10),
Slot: strconv.FormatUint(uint64(slot), 10),
Validators: validators,
@@ -1839,7 +1841,7 @@ func (s *Server) GetCommittees(w http.ResponseWriter, r *http.Request) {
return
}
isFinalized := s.FinalizationFetcher.IsFinalized(ctx, blockRoot)
httputil.WriteJson(w, &GetCommitteesResponse{Data: committees, ExecutionOptimistic: isOptimistic, Finalized: isFinalized})
httputil.WriteJson(w, &structs.GetCommitteesResponse{Data: committees, ExecutionOptimistic: isOptimistic, Finalized: isFinalized})
}
// GetBlockHeaders retrieves block headers matching given query. By default it will fetch current head slot blocks.
@@ -1889,7 +1891,7 @@ func (s *Server) GetBlockHeaders(w http.ResponseWriter, r *http.Request) {
isOptimistic := false
isFinalized := true
blkHdrs := make([]*shared.SignedBeaconBlockHeaderContainer, len(blks))
blkHdrs := make([]*structs.SignedBeaconBlockHeaderContainer, len(blks))
for i, bl := range blks {
v1alpha1Header, err := bl.Header()
if err != nil {
@@ -1916,9 +1918,9 @@ func (s *Server) GetBlockHeaders(w http.ResponseWriter, r *http.Request) {
if isFinalized {
isFinalized = s.FinalizationFetcher.IsFinalized(ctx, blkRoots[i])
}
blkHdrs[i] = &shared.SignedBeaconBlockHeaderContainer{
Header: &shared.SignedBeaconBlockHeader{
Message: shared.BeaconBlockHeaderFromConsensus(v1alpha1Header.Header),
blkHdrs[i] = &structs.SignedBeaconBlockHeaderContainer{
Header: &structs.SignedBeaconBlockHeader{
Message: structs.BeaconBlockHeaderFromConsensus(v1alpha1Header.Header),
Signature: hexutil.Encode(v1alpha1Header.Signature),
},
Root: hexutil.Encode(headerRoot[:]),
@@ -1926,7 +1928,7 @@ func (s *Server) GetBlockHeaders(w http.ResponseWriter, r *http.Request) {
}
}
response := &GetBlockHeadersResponse{
response := &structs.GetBlockHeadersResponse{
Data: blkHdrs,
ExecutionOptimistic: isOptimistic,
Finalized: isFinalized,
@@ -1976,12 +1978,12 @@ func (s *Server) GetBlockHeader(w http.ResponseWriter, r *http.Request) {
return
}
resp := &GetBlockHeaderResponse{
Data: &shared.SignedBeaconBlockHeaderContainer{
resp := &structs.GetBlockHeaderResponse{
Data: &structs.SignedBeaconBlockHeaderContainer{
Root: hexutil.Encode(headerRoot[:]),
Canonical: canonical,
Header: &shared.SignedBeaconBlockHeader{
Message: shared.BeaconBlockHeaderFromConsensus(blockHeader.Header),
Header: &structs.SignedBeaconBlockHeader{
Message: structs.BeaconBlockHeaderFromConsensus(blockHeader.Header),
Signature: hexutil.Encode(blockHeader.Signature),
},
},
@@ -2023,17 +2025,17 @@ func (s *Server) GetFinalityCheckpoints(w http.ResponseWriter, r *http.Request)
pj := st.PreviousJustifiedCheckpoint()
cj := st.CurrentJustifiedCheckpoint()
f := st.FinalizedCheckpoint()
resp := &GetFinalityCheckpointsResponse{
Data: &FinalityCheckpoints{
PreviousJustified: &shared.Checkpoint{
resp := &structs.GetFinalityCheckpointsResponse{
Data: &structs.FinalityCheckpoints{
PreviousJustified: &structs.Checkpoint{
Epoch: strconv.FormatUint(uint64(pj.Epoch), 10),
Root: hexutil.Encode(pj.Root),
},
CurrentJustified: &shared.Checkpoint{
CurrentJustified: &structs.Checkpoint{
Epoch: strconv.FormatUint(uint64(cj.Epoch), 10),
Root: hexutil.Encode(cj.Root),
},
Finalized: &shared.Checkpoint{
Finalized: &structs.Checkpoint{
Epoch: strconv.FormatUint(uint64(f.Epoch), 10),
Root: hexutil.Encode(f.Root),
},
@@ -2061,8 +2063,8 @@ func (s *Server) GetGenesis(w http.ResponseWriter, r *http.Request) {
}
forkVersion := params.BeaconConfig().GenesisForkVersion
resp := &GetGenesisResponse{
Data: &Genesis{
resp := &structs.GetGenesisResponse{
Data: &structs.Genesis{
GenesisTime: strconv.FormatUint(uint64(genesisTime.Unix()), 10),
GenesisValidatorsRoot: hexutil.Encode(validatorsRoot[:]),
GenesisForkVersion: hexutil.Encode(forkVersion),
@@ -2070,3 +2072,48 @@ func (s *Server) GetGenesis(w http.ResponseWriter, r *http.Request) {
}
httputil.WriteJson(w, resp)
}
// GetDepositSnapshot retrieves the EIP-4881 Deposit Tree Snapshot. Either a JSON or,
// if the Accept header was added, bytes serialized by SSZ will be returned.
func (s *Server) GetDepositSnapshot(w http.ResponseWriter, r *http.Request) {
ctx, span := trace.StartSpan(r.Context(), "beacon.GetDepositSnapshot")
defer span.End()
if s.BeaconDB == nil {
httputil.HandleError(w, "Could not retrieve beaconDB", http.StatusInternalServerError)
return
}
eth1data, err := s.BeaconDB.ExecutionChainData(ctx)
if err != nil {
httputil.HandleError(w, "Could not retrieve execution chain data: "+err.Error(), http.StatusInternalServerError)
return
}
if eth1data == nil {
httputil.HandleError(w, "Could not retrieve execution chain data: empty Eth1Data", http.StatusInternalServerError)
return
}
snapshot := eth1data.DepositSnapshot
if snapshot == nil || len(snapshot.Finalized) == 0 {
httputil.HandleError(w, "No Finalized Snapshot Available", http.StatusNotFound)
return
}
if len(snapshot.Finalized) > depositsnapshot.DepositContractDepth {
httputil.HandleError(w, "Retrieved invalid deposit snapshot", http.StatusInternalServerError)
return
}
if httputil.RespondWithSsz(r) {
sszData, err := snapshot.MarshalSSZ()
if err != nil {
httputil.HandleError(w, "Could not marshal deposit snapshot into SSZ: "+err.Error(), http.StatusInternalServerError)
return
}
httputil.WriteSsz(w, sszData, "deposit_snapshot.ssz")
return
}
httputil.WriteJson(
w,
&structs.GetDepositSnapshotResponse{
Data: structs.DepositSnapshotFromConsensus(snapshot),
},
)
}

View File

@@ -11,6 +11,7 @@ import (
"time"
"github.com/prysmaticlabs/prysm/v4/api/server"
"github.com/prysmaticlabs/prysm/v4/api/server/structs"
"github.com/prysmaticlabs/prysm/v4/beacon-chain/core/blocks"
"github.com/prysmaticlabs/prysm/v4/beacon-chain/core/feed"
"github.com/prysmaticlabs/prysm/v4/beacon-chain/core/feed/operation"
@@ -55,25 +56,25 @@ func (s *Server) ListAttestations(w http.ResponseWriter, r *http.Request) {
attestations = append(attestations, unaggAtts...)
isEmptyReq := rawSlot == "" && rawCommitteeIndex == ""
if isEmptyReq {
allAtts := make([]*shared.Attestation, len(attestations))
allAtts := make([]*structs.Attestation, len(attestations))
for i, att := range attestations {
allAtts[i] = shared.AttFromConsensus(att)
allAtts[i] = structs.AttFromConsensus(att)
}
httputil.WriteJson(w, &ListAttestationsResponse{Data: allAtts})
httputil.WriteJson(w, &structs.ListAttestationsResponse{Data: allAtts})
return
}
bothDefined := rawSlot != "" && rawCommitteeIndex != ""
filteredAtts := make([]*shared.Attestation, 0, len(attestations))
filteredAtts := make([]*structs.Attestation, 0, len(attestations))
for _, att := range attestations {
committeeIndexMatch := rawCommitteeIndex != "" && att.Data.CommitteeIndex == primitives.CommitteeIndex(committeeIndex)
slotMatch := rawSlot != "" && att.Data.Slot == primitives.Slot(slot)
shouldAppend := (bothDefined && committeeIndexMatch && slotMatch) || (!bothDefined && (committeeIndexMatch || slotMatch))
if shouldAppend {
filteredAtts = append(filteredAtts, shared.AttFromConsensus(att))
filteredAtts = append(filteredAtts, structs.AttFromConsensus(att))
}
}
httputil.WriteJson(w, &ListAttestationsResponse{Data: filteredAtts})
httputil.WriteJson(w, &structs.ListAttestationsResponse{Data: filteredAtts})
}
// SubmitAttestations submits an attestation object to node. If the attestation passes all validation
@@ -82,7 +83,7 @@ func (s *Server) SubmitAttestations(w http.ResponseWriter, r *http.Request) {
ctx, span := trace.StartSpan(r.Context(), "beacon.SubmitAttestations")
defer span.End()
var req SubmitAttestationsRequest
var req structs.SubmitAttestationsRequest
err := json.NewDecoder(r.Body).Decode(&req.Data)
switch {
case err == io.EOF:
@@ -186,12 +187,12 @@ func (s *Server) ListVoluntaryExits(w http.ResponseWriter, r *http.Request) {
httputil.HandleError(w, "Could not get exits from the pool: "+err.Error(), http.StatusInternalServerError)
return
}
exits := make([]*shared.SignedVoluntaryExit, len(sourceExits))
exits := make([]*structs.SignedVoluntaryExit, len(sourceExits))
for i, e := range sourceExits {
exits[i] = shared.SignedExitFromConsensus(e)
exits[i] = structs.SignedExitFromConsensus(e)
}
httputil.WriteJson(w, &ListVoluntaryExitsResponse{Data: exits})
httputil.WriteJson(w, &structs.ListVoluntaryExitsResponse{Data: exits})
}
// SubmitVoluntaryExit submits a SignedVoluntaryExit object to node's pool
@@ -200,7 +201,7 @@ func (s *Server) SubmitVoluntaryExit(w http.ResponseWriter, r *http.Request) {
ctx, span := trace.StartSpan(r.Context(), "beacon.SubmitVoluntaryExit")
defer span.End()
var req shared.SignedVoluntaryExit
var req structs.SignedVoluntaryExit
err := json.NewDecoder(r.Body).Decode(&req)
switch {
case err == io.EOF:
@@ -258,7 +259,7 @@ func (s *Server) SubmitSyncCommitteeSignatures(w http.ResponseWriter, r *http.Re
ctx, span := trace.StartSpan(r.Context(), "beacon.SubmitPoolSyncCommitteeSignatures")
defer span.End()
var req SubmitSyncCommitteeSignaturesRequest
var req structs.SubmitSyncCommitteeSignaturesRequest
err := json.NewDecoder(r.Body).Decode(&req.Data)
switch {
case err == io.EOF:
@@ -317,7 +318,7 @@ func (s *Server) SubmitBLSToExecutionChanges(w http.ResponseWriter, r *http.Requ
var failures []*server.IndexedVerificationFailure
var toBroadcast []*eth.SignedBLSToExecutionChange
var req []*shared.SignedBLSToExecutionChange
var req []*structs.SignedBLSToExecutionChange
err = json.NewDecoder(r.Body).Decode(&req)
switch {
case err == io.EOF:
@@ -437,8 +438,8 @@ func (s *Server) ListBLSToExecutionChanges(w http.ResponseWriter, r *http.Reques
return
}
httputil.WriteJson(w, &BLSToExecutionChangesPoolResponse{
Data: shared.SignedBLSChangesFromConsensus(sourceChanges),
httputil.WriteJson(w, &structs.BLSToExecutionChangesPoolResponse{
Data: structs.SignedBLSChangesFromConsensus(sourceChanges),
})
}
@@ -454,9 +455,9 @@ func (s *Server) GetAttesterSlashings(w http.ResponseWriter, r *http.Request) {
return
}
sourceSlashings := s.SlashingsPool.PendingAttesterSlashings(ctx, headState, true /* return unlimited slashings */)
slashings := shared.AttesterSlashingsFromConsensus(sourceSlashings)
slashings := structs.AttesterSlashingsFromConsensus(sourceSlashings)
httputil.WriteJson(w, &GetAttesterSlashingsResponse{Data: slashings})
httputil.WriteJson(w, &structs.GetAttesterSlashingsResponse{Data: slashings})
}
// SubmitAttesterSlashing submits an attester slashing object to node's pool and
@@ -465,7 +466,7 @@ func (s *Server) SubmitAttesterSlashing(w http.ResponseWriter, r *http.Request)
ctx, span := trace.StartSpan(r.Context(), "beacon.SubmitAttesterSlashing")
defer span.End()
var req shared.AttesterSlashing
var req structs.AttesterSlashing
err := json.NewDecoder(r.Body).Decode(&req)
switch {
case err == io.EOF:
@@ -528,9 +529,9 @@ func (s *Server) GetProposerSlashings(w http.ResponseWriter, r *http.Request) {
return
}
sourceSlashings := s.SlashingsPool.PendingProposerSlashings(ctx, headState, true /* return unlimited slashings */)
slashings := shared.ProposerSlashingsFromConsensus(sourceSlashings)
slashings := structs.ProposerSlashingsFromConsensus(sourceSlashings)
httputil.WriteJson(w, &GetProposerSlashingsResponse{Data: slashings})
httputil.WriteJson(w, &structs.GetProposerSlashingsResponse{Data: slashings})
}
// SubmitProposerSlashing submits a proposer slashing object to node's pool and if
@@ -539,7 +540,7 @@ func (s *Server) SubmitProposerSlashing(w http.ResponseWriter, r *http.Request)
ctx, span := trace.StartSpan(r.Context(), "beacon.SubmitProposerSlashing")
defer span.End()
var req shared.ProposerSlashing
var req structs.ProposerSlashing
err := json.NewDecoder(r.Body).Decode(&req)
switch {
case err == io.EOF:

View File

@@ -14,6 +14,7 @@ import (
"github.com/ethereum/go-ethereum/common/hexutil"
"github.com/prysmaticlabs/go-bitfield"
"github.com/prysmaticlabs/prysm/v4/api/server"
"github.com/prysmaticlabs/prysm/v4/api/server/structs"
blockchainmock "github.com/prysmaticlabs/prysm/v4/beacon-chain/blockchain/testing"
"github.com/prysmaticlabs/prysm/v4/beacon-chain/core/signing"
prysmtime "github.com/prysmaticlabs/prysm/v4/beacon-chain/core/time"
@@ -26,7 +27,6 @@ import (
"github.com/prysmaticlabs/prysm/v4/beacon-chain/operations/voluntaryexits/mock"
p2pMock "github.com/prysmaticlabs/prysm/v4/beacon-chain/p2p/testing"
"github.com/prysmaticlabs/prysm/v4/beacon-chain/rpc/core"
"github.com/prysmaticlabs/prysm/v4/beacon-chain/rpc/eth/shared"
state_native "github.com/prysmaticlabs/prysm/v4/beacon-chain/state/state-native"
"github.com/prysmaticlabs/prysm/v4/config/params"
"github.com/prysmaticlabs/prysm/v4/consensus-types/primitives"
@@ -126,7 +126,7 @@ func TestListAttestations(t *testing.T) {
s.ListAttestations(writer, request)
assert.Equal(t, http.StatusOK, writer.Code)
resp := &ListAttestationsResponse{}
resp := &structs.ListAttestationsResponse{}
require.NoError(t, json.Unmarshal(writer.Body.Bytes(), resp))
require.NotNil(t, resp)
require.NotNil(t, resp.Data)
@@ -140,7 +140,7 @@ func TestListAttestations(t *testing.T) {
s.ListAttestations(writer, request)
assert.Equal(t, http.StatusOK, writer.Code)
resp := &ListAttestationsResponse{}
resp := &structs.ListAttestationsResponse{}
require.NoError(t, json.Unmarshal(writer.Body.Bytes(), resp))
require.NotNil(t, resp)
require.NotNil(t, resp.Data)
@@ -157,7 +157,7 @@ func TestListAttestations(t *testing.T) {
s.ListAttestations(writer, request)
assert.Equal(t, http.StatusOK, writer.Code)
resp := &ListAttestationsResponse{}
resp := &structs.ListAttestationsResponse{}
require.NoError(t, json.Unmarshal(writer.Body.Bytes(), resp))
require.NotNil(t, resp)
require.NotNil(t, resp.Data)
@@ -174,7 +174,7 @@ func TestListAttestations(t *testing.T) {
s.ListAttestations(writer, request)
assert.Equal(t, http.StatusOK, writer.Code)
resp := &ListAttestationsResponse{}
resp := &structs.ListAttestationsResponse{}
require.NoError(t, json.Unmarshal(writer.Body.Bytes(), resp))
require.NotNil(t, resp)
require.NotNil(t, resp.Data)
@@ -340,7 +340,7 @@ func TestListVoluntaryExits(t *testing.T) {
s.ListVoluntaryExits(writer, request)
assert.Equal(t, http.StatusOK, writer.Code)
resp := &ListVoluntaryExitsResponse{}
resp := &structs.ListVoluntaryExitsResponse{}
require.NoError(t, json.Unmarshal(writer.Body.Bytes(), resp))
require.NotNil(t, resp)
require.NotNil(t, resp.Data)
@@ -660,11 +660,11 @@ func TestListBLSToExecutionChanges(t *testing.T) {
s.ListBLSToExecutionChanges(writer, request)
assert.Equal(t, http.StatusOK, writer.Code)
resp := &BLSToExecutionChangesPoolResponse{}
resp := &structs.BLSToExecutionChangesPoolResponse{}
require.NoError(t, json.Unmarshal(writer.Body.Bytes(), resp))
require.Equal(t, 2, len(resp.Data))
assert.DeepEqual(t, shared.SignedBLSChangeFromConsensus(change1), resp.Data[0])
assert.DeepEqual(t, shared.SignedBLSChangeFromConsensus(change2), resp.Data[1])
assert.DeepEqual(t, structs.SignedBLSChangeFromConsensus(change1), resp.Data[0])
assert.DeepEqual(t, structs.SignedBLSChangeFromConsensus(change2), resp.Data[1])
}
func TestSubmitSignedBLSToExecutionChanges_Ok(t *testing.T) {
@@ -722,12 +722,12 @@ func TestSubmitSignedBLSToExecutionChanges_Ok(t *testing.T) {
st, err := state_native.InitializeFromProtoCapella(spb)
require.NoError(t, err)
signedChanges := make([]*shared.SignedBLSToExecutionChange, numValidators)
signedChanges := make([]*structs.SignedBLSToExecutionChange, numValidators)
for i, message := range blsChanges {
signature, err := signing.ComputeDomainAndSign(st, prysmtime.CurrentEpoch(st), message, params.BeaconConfig().DomainBLSToExecutionChange, privKeys[i])
require.NoError(t, err)
signed := &shared.SignedBLSToExecutionChange{
Message: shared.BLSChangeFromConsensus(message),
signed := &structs.SignedBLSToExecutionChange{
Message: structs.BLSChangeFromConsensus(message),
Signature: hexutil.Encode(signature),
}
signedChanges[i] = signed
@@ -834,13 +834,13 @@ func TestSubmitSignedBLSToExecutionChanges_Bellatrix(t *testing.T) {
stc, err := state_native.InitializeFromProtoCapella(spc)
require.NoError(t, err)
signedChanges := make([]*shared.SignedBLSToExecutionChange, numValidators)
signedChanges := make([]*structs.SignedBLSToExecutionChange, numValidators)
for i, message := range blsChanges {
signature, err := signing.ComputeDomainAndSign(stc, prysmtime.CurrentEpoch(stc), message, params.BeaconConfig().DomainBLSToExecutionChange, privKeys[i])
require.NoError(t, err)
signedChanges[i] = &shared.SignedBLSToExecutionChange{
Message: shared.BLSChangeFromConsensus(message),
signedChanges[i] = &structs.SignedBLSToExecutionChange{
Message: structs.BLSChangeFromConsensus(message),
Signature: hexutil.Encode(signature),
}
}
@@ -934,15 +934,15 @@ func TestSubmitSignedBLSToExecutionChanges_Failures(t *testing.T) {
st, err := state_native.InitializeFromProtoCapella(spb)
require.NoError(t, err)
signedChanges := make([]*shared.SignedBLSToExecutionChange, numValidators)
signedChanges := make([]*structs.SignedBLSToExecutionChange, numValidators)
for i, message := range blsChanges {
signature, err := signing.ComputeDomainAndSign(st, prysmtime.CurrentEpoch(st), message, params.BeaconConfig().DomainBLSToExecutionChange, privKeys[i])
require.NoError(t, err)
if i == 1 {
signature[0] = 0x00
}
signedChanges[i] = &shared.SignedBLSToExecutionChange{
Message: shared.BLSChangeFromConsensus(message),
signedChanges[i] = &structs.SignedBLSToExecutionChange{
Message: structs.BLSChangeFromConsensus(message),
Signature: hexutil.Encode(signature),
}
}
@@ -975,10 +975,10 @@ func TestSubmitSignedBLSToExecutionChanges_Failures(t *testing.T) {
poolChanges, err := s.BLSChangesPool.PendingBLSToExecChanges()
require.Equal(t, len(poolChanges)+1, len(signedChanges))
require.NoError(t, err)
require.DeepEqual(t, shared.SignedBLSChangeFromConsensus(poolChanges[0]), signedChanges[0])
require.DeepEqual(t, structs.SignedBLSChangeFromConsensus(poolChanges[0]), signedChanges[0])
for i := 2; i < numValidators; i++ {
require.DeepEqual(t, shared.SignedBLSChangeFromConsensus(poolChanges[i-1]), signedChanges[i])
require.DeepEqual(t, structs.SignedBLSChangeFromConsensus(poolChanges[i-1]), signedChanges[i])
}
}
@@ -1069,7 +1069,7 @@ func TestGetAttesterSlashings(t *testing.T) {
s.GetAttesterSlashings(writer, request)
require.Equal(t, http.StatusOK, writer.Code)
resp := &GetAttesterSlashingsResponse{}
resp := &structs.GetAttesterSlashingsResponse{}
require.NoError(t, json.Unmarshal(writer.Body.Bytes(), resp))
require.NotNil(t, resp)
require.NotNil(t, resp.Data)
@@ -1135,7 +1135,7 @@ func TestGetProposerSlashings(t *testing.T) {
s.GetProposerSlashings(writer, request)
require.Equal(t, http.StatusOK, writer.Code)
resp := &GetProposerSlashingsResponse{}
resp := &structs.GetProposerSlashingsResponse{}
require.NoError(t, json.Unmarshal(writer.Body.Bytes(), resp))
require.NotNil(t, resp)
require.NotNil(t, resp.Data)
@@ -1213,7 +1213,7 @@ func TestSubmitAttesterSlashing_Ok(t *testing.T) {
OperationNotifier: chainmock.OperationNotifier(),
}
toSubmit := shared.AttesterSlashingsFromConsensus([]*ethpbv1alpha1.AttesterSlashing{slashing})
toSubmit := structs.AttesterSlashingsFromConsensus([]*ethpbv1alpha1.AttesterSlashing{slashing})
b, err := json.Marshal(toSubmit[0])
require.NoError(t, err)
var body bytes.Buffer
@@ -1305,7 +1305,7 @@ func TestSubmitAttesterSlashing_AcrossFork(t *testing.T) {
OperationNotifier: chainmock.OperationNotifier(),
}
toSubmit := shared.AttesterSlashingsFromConsensus([]*ethpbv1alpha1.AttesterSlashing{slashing})
toSubmit := structs.AttesterSlashingsFromConsensus([]*ethpbv1alpha1.AttesterSlashing{slashing})
b, err := json.Marshal(toSubmit[0])
require.NoError(t, err)
var body bytes.Buffer
@@ -1416,7 +1416,7 @@ func TestSubmitProposerSlashing_Ok(t *testing.T) {
OperationNotifier: chainmock.OperationNotifier(),
}
toSubmit := shared.ProposerSlashingsFromConsensus([]*ethpbv1alpha1.ProposerSlashing{slashing})
toSubmit := structs.ProposerSlashingsFromConsensus([]*ethpbv1alpha1.ProposerSlashing{slashing})
b, err := json.Marshal(toSubmit[0])
require.NoError(t, err)
var body bytes.Buffer
@@ -1500,7 +1500,7 @@ func TestSubmitProposerSlashing_AcrossFork(t *testing.T) {
OperationNotifier: chainmock.OperationNotifier(),
}
toSubmit := shared.ProposerSlashingsFromConsensus([]*ethpbv1alpha1.ProposerSlashing{slashing})
toSubmit := structs.ProposerSlashingsFromConsensus([]*ethpbv1alpha1.ProposerSlashing{slashing})
b, err := json.Marshal(toSubmit[0])
require.NoError(t, err)
var body bytes.Buffer

View File

@@ -8,6 +8,7 @@ import (
"github.com/ethereum/go-ethereum/common/hexutil"
"github.com/gorilla/mux"
"github.com/prysmaticlabs/prysm/v4/api/server/structs"
"github.com/prysmaticlabs/prysm/v4/beacon-chain/core/altair"
"github.com/prysmaticlabs/prysm/v4/beacon-chain/rpc/eth/helpers"
"github.com/prysmaticlabs/prysm/v4/beacon-chain/rpc/eth/shared"
@@ -67,8 +68,8 @@ func (s *Server) GetStateRoot(w http.ResponseWriter, r *http.Request) {
}
isFinalized := s.FinalizationFetcher.IsFinalized(ctx, blockRoot)
resp := &GetStateRootResponse{
Data: &StateRoot{
resp := &structs.GetStateRootResponse{
Data: &structs.StateRoot{
Root: hexutil.Encode(stateRoot),
},
ExecutionOptimistic: isOptimistic,
@@ -137,8 +138,8 @@ func (s *Server) GetRandao(w http.ResponseWriter, r *http.Request) {
}
isFinalized := s.FinalizationFetcher.IsFinalized(ctx, blockRoot)
resp := &GetRandaoResponse{
Data: &Randao{Randao: hexutil.Encode(randao)},
resp := &structs.GetRandaoResponse{
Data: &structs.Randao{Randao: hexutil.Encode(randao)},
ExecutionOptimistic: isOptimistic,
Finalized: isFinalized,
}
@@ -239,8 +240,8 @@ func (s *Server) GetSyncCommittees(w http.ResponseWriter, r *http.Request) {
}
isFinalized := s.FinalizationFetcher.IsFinalized(ctx, blockRoot)
resp := GetSyncCommitteeResponse{
Data: &SyncCommitteeValidators{
resp := structs.GetSyncCommitteeResponse{
Data: &structs.SyncCommitteeValidators{
Validators: committeeIndices,
ValidatorAggregates: subcommittees,
},

View File

@@ -13,6 +13,7 @@ import (
"github.com/ethereum/go-ethereum/common/hexutil"
"github.com/gorilla/mux"
"github.com/prysmaticlabs/prysm/v4/api/server/structs"
chainMock "github.com/prysmaticlabs/prysm/v4/beacon-chain/blockchain/testing"
dbTest "github.com/prysmaticlabs/prysm/v4/beacon-chain/db/testing"
"github.com/prysmaticlabs/prysm/v4/beacon-chain/rpc/testutil"
@@ -61,7 +62,7 @@ func TestGetStateRoot(t *testing.T) {
s.GetStateRoot(writer, request)
require.Equal(t, http.StatusOK, writer.Code)
resp := &GetStateRootResponse{}
resp := &structs.GetStateRootResponse{}
require.NoError(t, json.Unmarshal(writer.Body.Bytes(), resp))
assert.Equal(t, hexutil.Encode(stateRoot[:]), resp.Data.Root)
@@ -85,7 +86,7 @@ func TestGetStateRoot(t *testing.T) {
s.GetStateRoot(writer, request)
require.Equal(t, http.StatusOK, writer.Code)
resp := &GetStateRootResponse{}
resp := &structs.GetStateRootResponse{}
require.NoError(t, json.Unmarshal(writer.Body.Bytes(), resp))
assert.DeepEqual(t, true, resp.ExecutionOptimistic)
})
@@ -116,7 +117,7 @@ func TestGetStateRoot(t *testing.T) {
s.GetStateRoot(writer, request)
require.Equal(t, http.StatusOK, writer.Code)
resp := &GetStateRootResponse{}
resp := &structs.GetStateRootResponse{}
require.NoError(t, json.Unmarshal(writer.Body.Bytes(), resp))
assert.DeepEqual(t, true, resp.Finalized)
})
@@ -163,7 +164,7 @@ func TestGetRandao(t *testing.T) {
s.GetRandao(writer, request)
require.Equal(t, http.StatusOK, writer.Code)
resp := &GetRandaoResponse{}
resp := &structs.GetRandaoResponse{}
require.NoError(t, json.Unmarshal(writer.Body.Bytes(), resp))
assert.Equal(t, hexutil.Encode(mixCurrent[:]), resp.Data.Randao)
})
@@ -175,7 +176,7 @@ func TestGetRandao(t *testing.T) {
s.GetRandao(writer, request)
require.Equal(t, http.StatusOK, writer.Code)
resp := &GetRandaoResponse{}
resp := &structs.GetRandaoResponse{}
require.NoError(t, json.Unmarshal(writer.Body.Bytes(), resp))
assert.Equal(t, hexutil.Encode(mixCurrent[:]), resp.Data.Randao)
})
@@ -187,7 +188,7 @@ func TestGetRandao(t *testing.T) {
s.GetRandao(writer, request)
require.Equal(t, http.StatusOK, writer.Code)
resp := &GetRandaoResponse{}
resp := &structs.GetRandaoResponse{}
require.NoError(t, json.Unmarshal(writer.Body.Bytes(), resp))
assert.Equal(t, hexutil.Encode(mixOld[:]), resp.Data.Randao)
})
@@ -203,7 +204,7 @@ func TestGetRandao(t *testing.T) {
s.GetRandao(writer, request)
require.Equal(t, http.StatusOK, writer.Code)
resp := &GetRandaoResponse{}
resp := &structs.GetRandaoResponse{}
require.NoError(t, json.Unmarshal(writer.Body.Bytes(), resp))
assert.Equal(t, hexutil.Encode(headRandao[:]), resp.Data.Randao)
})
@@ -262,7 +263,7 @@ func TestGetRandao(t *testing.T) {
s.GetRandao(writer, request)
require.Equal(t, http.StatusOK, writer.Code)
resp := &GetRandaoResponse{}
resp := &structs.GetRandaoResponse{}
require.NoError(t, json.Unmarshal(writer.Body.Bytes(), resp))
assert.DeepEqual(t, true, resp.ExecutionOptimistic)
})
@@ -299,7 +300,7 @@ func TestGetRandao(t *testing.T) {
s.GetRandao(writer, request)
require.Equal(t, http.StatusOK, writer.Code)
resp := &GetRandaoResponse{}
resp := &structs.GetRandaoResponse{}
require.NoError(t, json.Unmarshal(writer.Body.Bytes(), resp))
assert.DeepEqual(t, true, resp.Finalized)
})
@@ -458,7 +459,7 @@ func TestGetSyncCommittees(t *testing.T) {
s.GetSyncCommittees(writer, request)
require.Equal(t, http.StatusOK, writer.Code)
resp := &GetSyncCommitteeResponse{}
resp := &structs.GetSyncCommitteeResponse{}
require.NoError(t, json.Unmarshal(writer.Body.Bytes(), resp))
committeeVals := resp.Data.Validators
require.Equal(t, params.BeaconConfig().SyncCommitteeSize, uint64(len(committeeVals)))
@@ -508,7 +509,7 @@ func TestGetSyncCommittees(t *testing.T) {
s.GetSyncCommittees(writer, request)
require.Equal(t, http.StatusOK, writer.Code)
resp := &GetSyncCommitteeResponse{}
resp := &structs.GetSyncCommitteeResponse{}
require.NoError(t, json.Unmarshal(writer.Body.Bytes(), resp))
assert.Equal(t, true, resp.ExecutionOptimistic)
})
@@ -552,7 +553,7 @@ func TestGetSyncCommittees(t *testing.T) {
s.GetSyncCommittees(writer, request)
require.Equal(t, http.StatusOK, writer.Code)
resp := &GetSyncCommitteeResponse{}
resp := &structs.GetSyncCommitteeResponse{}
require.NoError(t, json.Unmarshal(writer.Body.Bytes(), resp))
assert.Equal(t, true, resp.Finalized)
})
@@ -629,7 +630,7 @@ func TestGetSyncCommittees_Future(t *testing.T) {
writer.Body = &bytes.Buffer{}
s.GetSyncCommittees(writer, request)
require.Equal(t, http.StatusOK, writer.Code)
resp := &GetSyncCommitteeResponse{}
resp := &structs.GetSyncCommitteeResponse{}
require.NoError(t, json.Unmarshal(writer.Body.Bytes(), resp))
committeeVals := resp.Data.Validators
require.Equal(t, params.BeaconConfig().SyncCommitteeSize, uint64(len(committeeVals)))

File diff suppressed because it is too large Load Diff

View File

@@ -10,6 +10,7 @@ import (
"github.com/ethereum/go-ethereum/common/hexutil"
"github.com/gorilla/mux"
"github.com/prysmaticlabs/prysm/v4/api/server/structs"
"github.com/prysmaticlabs/prysm/v4/beacon-chain/rpc/eth/helpers"
"github.com/prysmaticlabs/prysm/v4/beacon-chain/rpc/eth/shared"
"github.com/prysmaticlabs/prysm/v4/beacon-chain/state"
@@ -51,7 +52,7 @@ func (s *Server) GetValidators(w http.ResponseWriter, r *http.Request) {
}
isFinalized := s.FinalizationFetcher.IsFinalized(ctx, blockRoot)
var req GetValidatorsRequest
var req structs.GetValidatorsRequest
if r.Method == http.MethodPost {
err = json.NewDecoder(r.Body).Decode(&req)
switch {
@@ -83,8 +84,8 @@ func (s *Server) GetValidators(w http.ResponseWriter, r *http.Request) {
}
// return no data if all IDs are ignored
if len(rawIds) > 0 && len(ids) == 0 {
resp := &GetValidatorsResponse{
Data: []*ValidatorContainer{},
resp := &structs.GetValidatorsResponse{
Data: []*structs.ValidatorContainer{},
ExecutionOptimistic: isOptimistic,
Finalized: isFinalized,
}
@@ -100,7 +101,7 @@ func (s *Server) GetValidators(w http.ResponseWriter, r *http.Request) {
// Exit early if no matching validators were found or we don't want to further filter validators by status.
if len(readOnlyVals) == 0 || len(statuses) == 0 {
containers := make([]*ValidatorContainer, len(readOnlyVals))
containers := make([]*structs.ValidatorContainer, len(readOnlyVals))
for i, val := range readOnlyVals {
valStatus, err := helpers.ValidatorSubStatus(val, epoch)
if err != nil {
@@ -118,7 +119,7 @@ func (s *Server) GetValidators(w http.ResponseWriter, r *http.Request) {
}
containers[i] = valContainerFromReadOnlyVal(val, id, balance, valStatus)
}
resp := &GetValidatorsResponse{
resp := &structs.GetValidatorsResponse{
Data: containers,
ExecutionOptimistic: isOptimistic,
Finalized: isFinalized,
@@ -136,7 +137,7 @@ func (s *Server) GetValidators(w http.ResponseWriter, r *http.Request) {
}
filteredStatuses[vs] = true
}
valContainers := make([]*ValidatorContainer, 0, len(readOnlyVals))
valContainers := make([]*structs.ValidatorContainer, 0, len(readOnlyVals))
for i, val := range readOnlyVals {
valStatus, err := helpers.ValidatorStatus(val, epoch)
if err != nil {
@@ -149,7 +150,7 @@ func (s *Server) GetValidators(w http.ResponseWriter, r *http.Request) {
return
}
if filteredStatuses[valStatus] || filteredStatuses[valSubStatus] {
var container *ValidatorContainer
var container *structs.ValidatorContainer
id := primitives.ValidatorIndex(i)
if len(ids) > 0 {
id = ids[i]
@@ -164,7 +165,7 @@ func (s *Server) GetValidators(w http.ResponseWriter, r *http.Request) {
}
}
resp := &GetValidatorsResponse{
resp := &structs.GetValidatorsResponse{
Data: valContainers,
ExecutionOptimistic: isOptimistic,
Finalized: isFinalized,
@@ -229,7 +230,7 @@ func (s *Server) GetValidator(w http.ResponseWriter, r *http.Request) {
}
isFinalized := s.FinalizationFetcher.IsFinalized(ctx, blockRoot)
resp := &GetValidatorResponse{
resp := &structs.GetValidatorResponse{
Data: container,
ExecutionOptimistic: isOptimistic,
Finalized: isFinalized,
@@ -286,8 +287,8 @@ func (s *Server) GetValidatorBalances(w http.ResponseWriter, r *http.Request) {
}
// return no data if all IDs are ignored
if len(rawIds) > 0 && len(ids) == 0 {
resp := &GetValidatorBalancesResponse{
Data: []*ValidatorBalance{},
resp := &structs.GetValidatorBalancesResponse{
Data: []*structs.ValidatorBalance{},
ExecutionOptimistic: isOptimistic,
Finalized: isFinalized,
}
@@ -296,26 +297,26 @@ func (s *Server) GetValidatorBalances(w http.ResponseWriter, r *http.Request) {
}
bals := st.Balances()
var valBalances []*ValidatorBalance
var valBalances []*structs.ValidatorBalance
if len(ids) == 0 {
valBalances = make([]*ValidatorBalance, len(bals))
valBalances = make([]*structs.ValidatorBalance, len(bals))
for i, b := range bals {
valBalances[i] = &ValidatorBalance{
valBalances[i] = &structs.ValidatorBalance{
Index: strconv.FormatUint(uint64(i), 10),
Balance: strconv.FormatUint(b, 10),
}
}
} else {
valBalances = make([]*ValidatorBalance, len(ids))
valBalances = make([]*structs.ValidatorBalance, len(ids))
for i, id := range ids {
valBalances[i] = &ValidatorBalance{
valBalances[i] = &structs.ValidatorBalance{
Index: strconv.FormatUint(uint64(id), 10),
Balance: strconv.FormatUint(bals[id], 10),
}
}
}
resp := &GetValidatorBalancesResponse{
resp := &structs.GetValidatorBalancesResponse{
Data: valBalances,
ExecutionOptimistic: isOptimistic,
Finalized: isFinalized,
@@ -404,13 +405,13 @@ func valContainerFromReadOnlyVal(
id primitives.ValidatorIndex,
bal uint64,
valStatus validator.Status,
) *ValidatorContainer {
) *structs.ValidatorContainer {
pubkey := val.PublicKey()
return &ValidatorContainer{
return &structs.ValidatorContainer{
Index: strconv.FormatUint(uint64(id), 10),
Balance: strconv.FormatUint(bal, 10),
Status: valStatus.String(),
Validator: &Validator{
Validator: &structs.Validator{
Pubkey: hexutil.Encode(pubkey[:]),
WithdrawalCredentials: hexutil.Encode(val.WithdrawalCredentials()),
EffectiveBalance: strconv.FormatUint(val.EffectiveBalance(), 10),

View File

@@ -12,6 +12,7 @@ import (
"github.com/ethereum/go-ethereum/common/hexutil"
"github.com/gorilla/mux"
"github.com/prysmaticlabs/prysm/v4/api/server/structs"
chainMock "github.com/prysmaticlabs/prysm/v4/beacon-chain/blockchain/testing"
"github.com/prysmaticlabs/prysm/v4/beacon-chain/rpc/lookup"
"github.com/prysmaticlabs/prysm/v4/beacon-chain/rpc/testutil"
@@ -52,7 +53,7 @@ func TestGetValidators(t *testing.T) {
s.GetValidators(writer, request)
assert.Equal(t, http.StatusOK, writer.Code)
resp := &GetValidatorsResponse{}
resp := &structs.GetValidatorsResponse{}
require.NoError(t, json.Unmarshal(writer.Body.Bytes(), resp))
require.Equal(t, 4, len(resp.Data))
val := resp.Data[0]
@@ -91,7 +92,7 @@ func TestGetValidators(t *testing.T) {
s.GetValidators(writer, request)
assert.Equal(t, http.StatusOK, writer.Code)
resp := &GetValidatorsResponse{}
resp := &structs.GetValidatorsResponse{}
require.NoError(t, json.Unmarshal(writer.Body.Bytes(), resp))
require.Equal(t, 2, len(resp.Data))
assert.Equal(t, "0", resp.Data[0].Index)
@@ -123,7 +124,7 @@ func TestGetValidators(t *testing.T) {
s.GetValidators(writer, request)
assert.Equal(t, http.StatusOK, writer.Code)
resp := &GetValidatorsResponse{}
resp := &structs.GetValidatorsResponse{}
require.NoError(t, json.Unmarshal(writer.Body.Bytes(), resp))
require.Equal(t, 2, len(resp.Data))
assert.Equal(t, "0", resp.Data[0].Index)
@@ -153,7 +154,7 @@ func TestGetValidators(t *testing.T) {
s.GetValidators(writer, request)
assert.Equal(t, http.StatusOK, writer.Code)
resp := &GetValidatorsResponse{}
resp := &structs.GetValidatorsResponse{}
require.NoError(t, json.Unmarshal(writer.Body.Bytes(), resp))
require.Equal(t, 2, len(resp.Data))
assert.Equal(t, "0", resp.Data[0].Index)
@@ -202,7 +203,7 @@ func TestGetValidators(t *testing.T) {
s.GetValidators(writer, request)
assert.Equal(t, http.StatusOK, writer.Code)
resp := &GetValidatorsResponse{}
resp := &structs.GetValidatorsResponse{}
require.NoError(t, json.Unmarshal(writer.Body.Bytes(), resp))
require.Equal(t, 1, len(resp.Data))
assert.Equal(t, "1", resp.Data[0].Index)
@@ -225,7 +226,7 @@ func TestGetValidators(t *testing.T) {
s.GetValidators(writer, request)
assert.Equal(t, http.StatusOK, writer.Code)
resp := &GetValidatorsResponse{}
resp := &structs.GetValidatorsResponse{}
require.NoError(t, json.Unmarshal(writer.Body.Bytes(), resp))
require.Equal(t, 1, len(resp.Data))
assert.Equal(t, "1", resp.Data[0].Index)
@@ -248,7 +249,7 @@ func TestGetValidators(t *testing.T) {
s.GetValidators(writer, request)
assert.Equal(t, http.StatusOK, writer.Code)
resp := &GetValidatorsResponse{}
resp := &structs.GetValidatorsResponse{}
require.NoError(t, json.Unmarshal(writer.Body.Bytes(), resp))
assert.Equal(t, true, resp.ExecutionOptimistic)
})
@@ -276,7 +277,7 @@ func TestGetValidators(t *testing.T) {
s.GetValidators(writer, request)
assert.Equal(t, http.StatusOK, writer.Code)
resp := &GetValidatorsResponse{}
resp := &structs.GetValidatorsResponse{}
require.NoError(t, json.Unmarshal(writer.Body.Bytes(), resp))
assert.Equal(t, true, resp.Finalized)
})
@@ -292,7 +293,7 @@ func TestGetValidators(t *testing.T) {
}
var body bytes.Buffer
req := &GetValidatorsRequest{
req := &structs.GetValidatorsRequest{
Ids: []string{"0", strconv.Itoa(exitedValIndex)},
Statuses: []string{"exited"},
}
@@ -311,7 +312,7 @@ func TestGetValidators(t *testing.T) {
s.GetValidators(writer, request)
assert.Equal(t, http.StatusOK, writer.Code)
resp := &GetValidatorsResponse{}
resp := &structs.GetValidatorsResponse{}
require.NoError(t, json.Unmarshal(writer.Body.Bytes(), resp))
require.Equal(t, 1, len(resp.Data))
assert.Equal(t, "3", resp.Data[0].Index)
@@ -328,7 +329,7 @@ func TestGetValidators(t *testing.T) {
}
var body bytes.Buffer
req := &GetValidatorsRequest{
req := &structs.GetValidatorsRequest{
Ids: nil,
Statuses: nil,
}
@@ -347,7 +348,7 @@ func TestGetValidators(t *testing.T) {
s.GetValidators(writer, request)
assert.Equal(t, http.StatusOK, writer.Code)
resp := &GetValidatorsResponse{}
resp := &structs.GetValidatorsResponse{}
require.NoError(t, json.Unmarshal(writer.Body.Bytes(), resp))
require.Equal(t, 4, len(resp.Data))
})
@@ -497,7 +498,7 @@ func TestGetValidators_FilterByStatus(t *testing.T) {
s.GetValidators(writer, request)
assert.Equal(t, http.StatusOK, writer.Code)
resp := &GetValidatorsResponse{}
resp := &structs.GetValidatorsResponse{}
require.NoError(t, json.Unmarshal(writer.Body.Bytes(), resp))
assert.Equal(t, 3, len(resp.Data))
for _, vc := range resp.Data {
@@ -528,7 +529,7 @@ func TestGetValidators_FilterByStatus(t *testing.T) {
s.GetValidators(writer, request)
assert.Equal(t, http.StatusOK, writer.Code)
resp := &GetValidatorsResponse{}
resp := &structs.GetValidatorsResponse{}
require.NoError(t, json.Unmarshal(writer.Body.Bytes(), resp))
assert.Equal(t, 2, len(resp.Data))
for _, vc := range resp.Data {
@@ -558,7 +559,7 @@ func TestGetValidators_FilterByStatus(t *testing.T) {
s.GetValidators(writer, request)
assert.Equal(t, http.StatusOK, writer.Code)
resp := &GetValidatorsResponse{}
resp := &structs.GetValidatorsResponse{}
require.NoError(t, json.Unmarshal(writer.Body.Bytes(), resp))
assert.Equal(t, 4, len(resp.Data))
for _, vc := range resp.Data {
@@ -591,7 +592,7 @@ func TestGetValidators_FilterByStatus(t *testing.T) {
s.GetValidators(writer, request)
assert.Equal(t, http.StatusOK, writer.Code)
resp := &GetValidatorsResponse{}
resp := &structs.GetValidatorsResponse{}
require.NoError(t, json.Unmarshal(writer.Body.Bytes(), resp))
assert.Equal(t, 4, len(resp.Data))
for _, vc := range resp.Data {
@@ -624,7 +625,7 @@ func TestGetValidators_FilterByStatus(t *testing.T) {
s.GetValidators(writer, request)
assert.Equal(t, http.StatusOK, writer.Code)
resp := &GetValidatorsResponse{}
resp := &structs.GetValidatorsResponse{}
require.NoError(t, json.Unmarshal(writer.Body.Bytes(), resp))
assert.Equal(t, 2, len(resp.Data))
for _, vc := range resp.Data {
@@ -659,7 +660,7 @@ func TestGetValidator(t *testing.T) {
s.GetValidator(writer, request)
assert.Equal(t, http.StatusOK, writer.Code)
resp := &GetValidatorResponse{}
resp := &structs.GetValidatorResponse{}
require.NoError(t, json.Unmarshal(writer.Body.Bytes(), resp))
assert.Equal(t, "0", resp.Data.Index)
assert.Equal(t, "32000000000", resp.Data.Balance)
@@ -694,7 +695,7 @@ func TestGetValidator(t *testing.T) {
s.GetValidator(writer, request)
assert.Equal(t, http.StatusOK, writer.Code)
resp := &GetValidatorResponse{}
resp := &structs.GetValidatorResponse{}
require.NoError(t, json.Unmarshal(writer.Body.Bytes(), resp))
assert.Equal(t, "0", resp.Data.Index)
})
@@ -796,7 +797,7 @@ func TestGetValidator(t *testing.T) {
s.GetValidator(writer, request)
assert.Equal(t, http.StatusOK, writer.Code)
resp := &GetValidatorResponse{}
resp := &structs.GetValidatorResponse{}
require.NoError(t, json.Unmarshal(writer.Body.Bytes(), resp))
assert.Equal(t, true, resp.ExecutionOptimistic)
})
@@ -824,7 +825,7 @@ func TestGetValidator(t *testing.T) {
s.GetValidator(writer, request)
assert.Equal(t, http.StatusOK, writer.Code)
resp := &GetValidatorResponse{}
resp := &structs.GetValidatorResponse{}
require.NoError(t, json.Unmarshal(writer.Body.Bytes(), resp))
assert.Equal(t, true, resp.Finalized)
})
@@ -858,7 +859,7 @@ func TestGetValidatorBalances(t *testing.T) {
s.GetValidatorBalances(writer, request)
assert.Equal(t, http.StatusOK, writer.Code)
resp := &GetValidatorBalancesResponse{}
resp := &structs.GetValidatorBalancesResponse{}
require.NoError(t, json.Unmarshal(writer.Body.Bytes(), resp))
require.Equal(t, 4, len(resp.Data))
val := resp.Data[3]
@@ -887,7 +888,7 @@ func TestGetValidatorBalances(t *testing.T) {
s.GetValidatorBalances(writer, request)
assert.Equal(t, http.StatusOK, writer.Code)
resp := &GetValidatorBalancesResponse{}
resp := &structs.GetValidatorBalancesResponse{}
require.NoError(t, json.Unmarshal(writer.Body.Bytes(), resp))
require.Equal(t, 2, len(resp.Data))
assert.Equal(t, "0", resp.Data[0].Index)
@@ -919,7 +920,7 @@ func TestGetValidatorBalances(t *testing.T) {
s.GetValidatorBalances(writer, request)
assert.Equal(t, http.StatusOK, writer.Code)
resp := &GetValidatorBalancesResponse{}
resp := &structs.GetValidatorBalancesResponse{}
require.NoError(t, json.Unmarshal(writer.Body.Bytes(), resp))
require.Equal(t, 2, len(resp.Data))
assert.Equal(t, "0", resp.Data[0].Index)
@@ -949,7 +950,7 @@ func TestGetValidatorBalances(t *testing.T) {
s.GetValidators(writer, request)
assert.Equal(t, http.StatusOK, writer.Code)
resp := &GetValidatorsResponse{}
resp := &structs.GetValidatorsResponse{}
require.NoError(t, json.Unmarshal(writer.Body.Bytes(), resp))
require.Equal(t, 2, len(resp.Data))
assert.Equal(t, "0", resp.Data[0].Index)
@@ -979,7 +980,7 @@ func TestGetValidatorBalances(t *testing.T) {
s.GetValidatorBalances(writer, request)
assert.Equal(t, http.StatusOK, writer.Code)
resp := &GetValidatorBalancesResponse{}
resp := &structs.GetValidatorBalancesResponse{}
require.NoError(t, json.Unmarshal(writer.Body.Bytes(), resp))
require.Equal(t, 1, len(resp.Data))
assert.Equal(t, "1", resp.Data[0].Index)
@@ -1002,7 +1003,7 @@ func TestGetValidatorBalances(t *testing.T) {
s.GetValidatorBalances(writer, request)
assert.Equal(t, http.StatusOK, writer.Code)
resp := &GetValidatorBalancesResponse{}
resp := &structs.GetValidatorBalancesResponse{}
require.NoError(t, json.Unmarshal(writer.Body.Bytes(), resp))
require.Equal(t, 1, len(resp.Data))
assert.Equal(t, "1", resp.Data[0].Index)
@@ -1048,7 +1049,7 @@ func TestGetValidatorBalances(t *testing.T) {
s.GetValidatorBalances(writer, request)
assert.Equal(t, http.StatusOK, writer.Code)
resp := &GetValidatorBalancesResponse{}
resp := &structs.GetValidatorBalancesResponse{}
require.NoError(t, json.Unmarshal(writer.Body.Bytes(), resp))
assert.Equal(t, true, resp.ExecutionOptimistic)
})
@@ -1080,7 +1081,7 @@ func TestGetValidatorBalances(t *testing.T) {
s.GetValidatorBalances(writer, request)
assert.Equal(t, http.StatusOK, writer.Code)
resp := &GetValidatorBalancesResponse{}
resp := &structs.GetValidatorBalancesResponse{}
require.NoError(t, json.Unmarshal(writer.Body.Bytes(), resp))
assert.Equal(t, true, resp.Finalized)
})
@@ -1113,7 +1114,7 @@ func TestGetValidatorBalances(t *testing.T) {
s.GetValidatorBalances(writer, request)
assert.Equal(t, http.StatusOK, writer.Code)
resp := &GetValidatorBalancesResponse{}
resp := &structs.GetValidatorBalancesResponse{}
require.NoError(t, json.Unmarshal(writer.Body.Bytes(), resp))
require.Equal(t, 2, len(resp.Data))
assert.Equal(t, "0", resp.Data[0].Index)

View File

@@ -5,13 +5,12 @@ go_library(
srcs = [
"handlers.go",
"server.go",
"structs.go",
],
importpath = "github.com/prysmaticlabs/prysm/v4/beacon-chain/rpc/eth/blob",
visibility = ["//visibility:public"],
deps = [
"//api/server/structs:go_default_library",
"//beacon-chain/rpc/core:go_default_library",
"//beacon-chain/rpc/eth/shared:go_default_library",
"//beacon-chain/rpc/lookup:go_default_library",
"//config/fieldparams:go_default_library",
"//network/httputil:go_default_library",
@@ -26,10 +25,12 @@ go_test(
srcs = ["handlers_test.go"],
embed = [":go_default_library"],
deps = [
"//api/server/structs:go_default_library",
"//beacon-chain/blockchain/testing:go_default_library",
"//beacon-chain/db/filesystem:go_default_library",
"//beacon-chain/db/testing:go_default_library",
"//beacon-chain/rpc/lookup:go_default_library",
"//beacon-chain/rpc/testutil:go_default_library",
"//beacon-chain/verification:go_default_library",
"//config/params:go_default_library",
"//network/httputil:go_default_library",

View File

@@ -7,8 +7,8 @@ import (
"strings"
"github.com/ethereum/go-ethereum/common/hexutil"
"github.com/prysmaticlabs/prysm/v4/api/server/structs"
"github.com/prysmaticlabs/prysm/v4/beacon-chain/rpc/core"
"github.com/prysmaticlabs/prysm/v4/beacon-chain/rpc/eth/shared"
field_params "github.com/prysmaticlabs/prysm/v4/config/fieldparams"
"github.com/prysmaticlabs/prysm/v4/network/httputil"
eth "github.com/prysmaticlabs/prysm/v4/proto/prysm/v1alpha1"
@@ -85,18 +85,18 @@ loop:
return indices
}
func buildSidecarsResponse(sidecars []*eth.BlobSidecar) *SidecarsResponse {
resp := &SidecarsResponse{Data: make([]*Sidecar, len(sidecars))}
func buildSidecarsResponse(sidecars []*eth.BlobSidecar) *structs.SidecarsResponse {
resp := &structs.SidecarsResponse{Data: make([]*structs.Sidecar, len(sidecars))}
for i, sc := range sidecars {
proofs := make([]string, len(sc.CommitmentInclusionProof))
for j := range sc.CommitmentInclusionProof {
proofs[j] = hexutil.Encode(sc.CommitmentInclusionProof[j])
}
resp.Data[i] = &Sidecar{
resp.Data[i] = &structs.Sidecar{
Index: strconv.FormatUint(sc.Index, 10),
Blob: hexutil.Encode(sc.Blob),
KzgCommitment: hexutil.Encode(sc.KzgCommitment),
SignedBeaconBlockHeader: shared.SignedBeaconBlockHeaderFromConsensus(sc.SignedBlockHeader),
SignedBeaconBlockHeader: structs.SignedBeaconBlockHeaderFromConsensus(sc.SignedBlockHeader),
KzgProof: hexutil.Encode(sc.KzgProof),
CommitmentInclusionProof: proofs,
}

View File

@@ -9,12 +9,15 @@ import (
"net/url"
"strings"
"testing"
"time"
"github.com/ethereum/go-ethereum/common/hexutil"
"github.com/prysmaticlabs/prysm/v4/api/server/structs"
mockChain "github.com/prysmaticlabs/prysm/v4/beacon-chain/blockchain/testing"
"github.com/prysmaticlabs/prysm/v4/beacon-chain/db/filesystem"
testDB "github.com/prysmaticlabs/prysm/v4/beacon-chain/db/testing"
"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/verification"
"github.com/prysmaticlabs/prysm/v4/config/params"
"github.com/prysmaticlabs/prysm/v4/network/httputil"
@@ -70,8 +73,11 @@ func TestBlobs(t *testing.T) {
writer.Body = &bytes.Buffer{}
blocker := &lookup.BeaconDbBlocker{
ChainInfoFetcher: &mockChain.ChainService{Root: blockRoot[:]},
BeaconDB: db,
BlobStorage: bs,
GenesisTimeFetcher: &testutil.MockGenesisTimeFetcher{
Genesis: time.Now(),
},
BeaconDB: db,
BlobStorage: bs,
}
s := &Server{
Blocker: blocker,
@@ -80,7 +86,7 @@ func TestBlobs(t *testing.T) {
s.Blobs(writer, request)
assert.Equal(t, http.StatusOK, writer.Code)
resp := &SidecarsResponse{}
resp := &structs.SidecarsResponse{}
require.NoError(t, json.Unmarshal(writer.Body.Bytes(), resp))
require.Equal(t, 4, len(resp.Data))
sidecar := resp.Data[0]
@@ -115,8 +121,11 @@ func TestBlobs(t *testing.T) {
writer.Body = &bytes.Buffer{}
blocker := &lookup.BeaconDbBlocker{
ChainInfoFetcher: &mockChain.ChainService{FinalizedCheckPoint: &eth.Checkpoint{Root: blockRoot[:]}},
BeaconDB: db,
BlobStorage: bs,
GenesisTimeFetcher: &testutil.MockGenesisTimeFetcher{
Genesis: time.Now(),
},
BeaconDB: db,
BlobStorage: bs,
}
s := &Server{
Blocker: blocker,
@@ -125,7 +134,7 @@ func TestBlobs(t *testing.T) {
s.Blobs(writer, request)
assert.Equal(t, http.StatusOK, writer.Code)
resp := &SidecarsResponse{}
resp := &structs.SidecarsResponse{}
require.NoError(t, json.Unmarshal(writer.Body.Bytes(), resp))
require.Equal(t, 4, len(resp.Data))
})
@@ -136,8 +145,11 @@ func TestBlobs(t *testing.T) {
writer.Body = &bytes.Buffer{}
blocker := &lookup.BeaconDbBlocker{
ChainInfoFetcher: &mockChain.ChainService{CurrentJustifiedCheckPoint: &eth.Checkpoint{Root: blockRoot[:]}},
BeaconDB: db,
BlobStorage: bs,
GenesisTimeFetcher: &testutil.MockGenesisTimeFetcher{
Genesis: time.Now(),
},
BeaconDB: db,
BlobStorage: bs,
}
s := &Server{
Blocker: blocker,
@@ -146,7 +158,7 @@ func TestBlobs(t *testing.T) {
s.Blobs(writer, request)
assert.Equal(t, http.StatusOK, writer.Code)
resp := &SidecarsResponse{}
resp := &structs.SidecarsResponse{}
require.NoError(t, json.Unmarshal(writer.Body.Bytes(), resp))
require.Equal(t, 4, len(resp.Data))
})
@@ -156,7 +168,10 @@ func TestBlobs(t *testing.T) {
writer := httptest.NewRecorder()
writer.Body = &bytes.Buffer{}
blocker := &lookup.BeaconDbBlocker{
BeaconDB: db,
BeaconDB: db,
GenesisTimeFetcher: &testutil.MockGenesisTimeFetcher{
Genesis: time.Now(),
},
BlobStorage: bs,
}
s := &Server{
@@ -166,7 +181,7 @@ func TestBlobs(t *testing.T) {
s.Blobs(writer, request)
assert.Equal(t, http.StatusOK, writer.Code)
resp := &SidecarsResponse{}
resp := &structs.SidecarsResponse{}
require.NoError(t, json.Unmarshal(writer.Body.Bytes(), resp))
require.Equal(t, 4, len(resp.Data))
})
@@ -176,7 +191,10 @@ func TestBlobs(t *testing.T) {
writer := httptest.NewRecorder()
writer.Body = &bytes.Buffer{}
blocker := &lookup.BeaconDbBlocker{
BeaconDB: db,
BeaconDB: db,
GenesisTimeFetcher: &testutil.MockGenesisTimeFetcher{
Genesis: time.Now(),
},
BlobStorage: bs,
}
s := &Server{
@@ -186,7 +204,7 @@ func TestBlobs(t *testing.T) {
s.Blobs(writer, request)
assert.Equal(t, http.StatusOK, writer.Code)
resp := &SidecarsResponse{}
resp := &structs.SidecarsResponse{}
require.NoError(t, json.Unmarshal(writer.Body.Bytes(), resp))
require.Equal(t, 4, len(resp.Data))
})
@@ -197,8 +215,11 @@ func TestBlobs(t *testing.T) {
writer.Body = &bytes.Buffer{}
blocker := &lookup.BeaconDbBlocker{
ChainInfoFetcher: &mockChain.ChainService{FinalizedCheckPoint: &eth.Checkpoint{Root: blockRoot[:]}},
BeaconDB: db,
BlobStorage: bs,
GenesisTimeFetcher: &testutil.MockGenesisTimeFetcher{
Genesis: time.Now(),
},
BeaconDB: db,
BlobStorage: bs,
}
s := &Server{
Blocker: blocker,
@@ -207,7 +228,7 @@ func TestBlobs(t *testing.T) {
s.Blobs(writer, request)
assert.Equal(t, http.StatusOK, writer.Code)
resp := &SidecarsResponse{}
resp := &structs.SidecarsResponse{}
require.NoError(t, json.Unmarshal(writer.Body.Bytes(), resp))
require.Equal(t, 1, len(resp.Data))
sidecar := resp.Data[0]
@@ -224,8 +245,11 @@ func TestBlobs(t *testing.T) {
writer.Body = &bytes.Buffer{}
blocker := &lookup.BeaconDbBlocker{
ChainInfoFetcher: &mockChain.ChainService{FinalizedCheckPoint: &eth.Checkpoint{Root: blockRoot[:]}},
BeaconDB: db,
BlobStorage: filesystem.NewEphemeralBlobStorage(t), // new ephemeral storage
GenesisTimeFetcher: &testutil.MockGenesisTimeFetcher{
Genesis: time.Now(),
},
BeaconDB: db,
BlobStorage: filesystem.NewEphemeralBlobStorage(t), // new ephemeral storage
}
s := &Server{
Blocker: blocker,
@@ -233,10 +257,63 @@ func TestBlobs(t *testing.T) {
s.Blobs(writer, request)
assert.Equal(t, http.StatusOK, writer.Code)
resp := &SidecarsResponse{}
resp := &structs.SidecarsResponse{}
require.NoError(t, json.Unmarshal(writer.Body.Bytes(), resp))
require.Equal(t, len(resp.Data), 0)
})
t.Run("outside retention period returns 200 w/ empty list ", func(t *testing.T) {
u := "http://foo.example/123"
request := httptest.NewRequest("GET", u, nil)
writer := httptest.NewRecorder()
writer.Body = &bytes.Buffer{}
moc := &mockChain.ChainService{FinalizedCheckPoint: &eth.Checkpoint{Root: blockRoot[:]}}
blocker := &lookup.BeaconDbBlocker{
ChainInfoFetcher: moc,
GenesisTimeFetcher: moc, // genesis time is set to 0 here, so it results in current epoch being extremely large
BeaconDB: db,
BlobStorage: bs,
}
s := &Server{
Blocker: blocker,
}
s.Blobs(writer, request)
assert.Equal(t, http.StatusOK, writer.Code)
resp := &structs.SidecarsResponse{}
require.NoError(t, json.Unmarshal(writer.Body.Bytes(), resp))
require.Equal(t, 0, len(resp.Data))
})
t.Run("block without commitments returns 200 w/empty list ", func(t *testing.T) {
denebBlock, _ := util.GenerateTestDenebBlockWithSidecar(t, [32]byte{}, 333, 0)
commitments, err := denebBlock.Block().Body().BlobKzgCommitments()
require.NoError(t, err)
require.Equal(t, len(commitments), 0)
require.NoError(t, db.SaveBlock(context.Background(), denebBlock))
u := "http://foo.example/333"
request := httptest.NewRequest("GET", u, nil)
writer := httptest.NewRecorder()
writer.Body = &bytes.Buffer{}
blocker := &lookup.BeaconDbBlocker{
ChainInfoFetcher: &mockChain.ChainService{FinalizedCheckPoint: &eth.Checkpoint{Root: blockRoot[:]}},
GenesisTimeFetcher: &testutil.MockGenesisTimeFetcher{
Genesis: time.Now(),
},
BeaconDB: db,
BlobStorage: bs,
}
s := &Server{
Blocker: blocker,
}
s.Blobs(writer, request)
assert.Equal(t, http.StatusOK, writer.Code)
resp := &structs.SidecarsResponse{}
require.NoError(t, json.Unmarshal(writer.Body.Bytes(), resp))
require.Equal(t, 0, len(resp.Data))
})
t.Run("slot before Deneb fork", func(t *testing.T) {
u := "http://foo.example/31"
request := httptest.NewRequest("GET", u, nil)
@@ -281,8 +358,11 @@ func TestBlobs(t *testing.T) {
writer.Body = &bytes.Buffer{}
blocker := &lookup.BeaconDbBlocker{
ChainInfoFetcher: &mockChain.ChainService{FinalizedCheckPoint: &eth.Checkpoint{Root: blockRoot[:]}},
BeaconDB: db,
BlobStorage: bs,
GenesisTimeFetcher: &testutil.MockGenesisTimeFetcher{
Genesis: time.Now(),
},
BeaconDB: db,
BlobStorage: bs,
}
s := &Server{
Blocker: blocker,

View File

@@ -1,16 +0,0 @@
package blob
import "github.com/prysmaticlabs/prysm/v4/beacon-chain/rpc/eth/shared"
type SidecarsResponse struct {
Data []*Sidecar `json:"data"`
}
type Sidecar struct {
Index string `json:"index"`
Blob string `json:"blob"`
SignedBeaconBlockHeader *shared.SignedBeaconBlockHeader `json:"signed_block_header"`
KzgCommitment string `json:"kzg_commitment"`
KzgProof string `json:"kzg_proof"`
CommitmentInclusionProof []string `json:"kzg_commitment_inclusion_proof"`
}

View File

@@ -5,11 +5,11 @@ go_library(
srcs = [
"handlers.go",
"server.go",
"structs.go",
],
importpath = "github.com/prysmaticlabs/prysm/v4/beacon-chain/rpc/eth/builder",
visibility = ["//visibility:public"],
deps = [
"//api/server/structs:go_default_library",
"//beacon-chain/blockchain:go_default_library",
"//beacon-chain/core/helpers:go_default_library",
"//beacon-chain/core/transition:go_default_library",
@@ -30,6 +30,7 @@ go_test(
srcs = ["handlers_test.go"],
embed = [":go_default_library"],
deps = [
"//api/server/structs:go_default_library",
"//beacon-chain/blockchain/testing:go_default_library",
"//beacon-chain/rpc/testutil:go_default_library",
"//beacon-chain/state:go_default_library",

View File

@@ -8,6 +8,7 @@ import (
"github.com/ethereum/go-ethereum/common/hexutil"
"github.com/gorilla/mux"
"github.com/pkg/errors"
"github.com/prysmaticlabs/prysm/v4/api/server/structs"
"github.com/prysmaticlabs/prysm/v4/beacon-chain/core/helpers"
"github.com/prysmaticlabs/prysm/v4/beacon-chain/core/transition"
"github.com/prysmaticlabs/prysm/v4/config/params"
@@ -103,17 +104,17 @@ func (s *Server) ExpectedWithdrawals(w http.ResponseWriter, r *http.Request) {
})
return
}
httputil.WriteJson(w, &ExpectedWithdrawalsResponse{
httputil.WriteJson(w, &structs.ExpectedWithdrawalsResponse{
ExecutionOptimistic: isOptimistic,
Finalized: isFinalized,
Data: buildExpectedWithdrawalsData(withdrawals),
})
}
func buildExpectedWithdrawalsData(withdrawals []*enginev1.Withdrawal) []*ExpectedWithdrawal {
data := make([]*ExpectedWithdrawal, len(withdrawals))
func buildExpectedWithdrawalsData(withdrawals []*enginev1.Withdrawal) []*structs.ExpectedWithdrawal {
data := make([]*structs.ExpectedWithdrawal, len(withdrawals))
for i, withdrawal := range withdrawals {
data[i] = &ExpectedWithdrawal{
data[i] = &structs.ExpectedWithdrawal{
Address: hexutil.Encode(withdrawal.Address),
Amount: strconv.FormatUint(withdrawal.Amount, 10),
Index: strconv.FormatUint(withdrawal.Index, 10),

View File

@@ -10,6 +10,7 @@ import (
"github.com/ethereum/go-ethereum/common/hexutil"
"github.com/gorilla/mux"
"github.com/prysmaticlabs/prysm/v4/api/server/structs"
mock "github.com/prysmaticlabs/prysm/v4/beacon-chain/blockchain/testing"
"github.com/prysmaticlabs/prysm/v4/beacon-chain/rpc/testutil"
"github.com/prysmaticlabs/prysm/v4/beacon-chain/state"
@@ -177,26 +178,26 @@ func TestExpectedWithdrawals(t *testing.T) {
s.ExpectedWithdrawals(writer, request)
assert.Equal(t, http.StatusOK, writer.Code)
resp := &ExpectedWithdrawalsResponse{}
resp := &structs.ExpectedWithdrawalsResponse{}
require.NoError(t, json.Unmarshal(writer.Body.Bytes(), resp))
assert.Equal(t, true, resp.ExecutionOptimistic)
assert.Equal(t, false, resp.Finalized)
assert.Equal(t, 3, len(resp.Data))
expectedWithdrawal1 := &ExpectedWithdrawal{
expectedWithdrawal1 := &structs.ExpectedWithdrawal{
Index: strconv.FormatUint(0, 10),
ValidatorIndex: strconv.FormatUint(5, 10),
Address: hexutil.Encode(validators[5].WithdrawalCredentials[12:]),
// Decreased due to epoch processing when state advanced forward
Amount: strconv.FormatUint(31998257885, 10),
}
expectedWithdrawal2 := &ExpectedWithdrawal{
expectedWithdrawal2 := &structs.ExpectedWithdrawal{
Index: strconv.FormatUint(1, 10),
ValidatorIndex: strconv.FormatUint(14, 10),
Address: hexutil.Encode(validators[14].WithdrawalCredentials[12:]),
// MaxEffectiveBalance + MinDepositAmount + decrease after epoch processing
Amount: strconv.FormatUint(32998257885, 10),
}
expectedWithdrawal3 := &ExpectedWithdrawal{
expectedWithdrawal3 := &structs.ExpectedWithdrawal{
Index: strconv.FormatUint(2, 10),
ValidatorIndex: strconv.FormatUint(15, 10),
Address: hexutil.Encode(validators[15].WithdrawalCredentials[12:]),

View File

@@ -2,14 +2,11 @@ load("@prysm//tools/go:def.bzl", "go_library", "go_test")
go_library(
name = "go_default_library",
srcs = [
"handlers.go",
"structs.go",
],
srcs = ["handlers.go"],
importpath = "github.com/prysmaticlabs/prysm/v4/beacon-chain/rpc/eth/config",
visibility = ["//visibility:public"],
deps = [
"//beacon-chain/rpc/eth/shared:go_default_library",
"//api/server/structs:go_default_library",
"//config/params:go_default_library",
"//network/forks:go_default_library",
"//network/httputil:go_default_library",
@@ -23,6 +20,7 @@ go_test(
srcs = ["handlers_test.go"],
embed = [":go_default_library"],
deps = [
"//api/server/structs:go_default_library",
"//config/params:go_default_library",
"//consensus-types/primitives:go_default_library",
"//encoding/bytesutil:go_default_library",

View File

@@ -8,7 +8,7 @@ import (
"strings"
"github.com/ethereum/go-ethereum/common/hexutil"
"github.com/prysmaticlabs/prysm/v4/beacon-chain/rpc/eth/shared"
"github.com/prysmaticlabs/prysm/v4/api/server/structs"
"github.com/prysmaticlabs/prysm/v4/config/params"
"github.com/prysmaticlabs/prysm/v4/network/forks"
"github.com/prysmaticlabs/prysm/v4/network/httputil"
@@ -20,8 +20,8 @@ func GetDepositContract(w http.ResponseWriter, r *http.Request) {
_, span := trace.StartSpan(r.Context(), "config.GetDepositContract")
defer span.End()
httputil.WriteJson(w, &GetDepositContractResponse{
Data: &DepositContractData{
httputil.WriteJson(w, &structs.GetDepositContractResponse{
Data: &structs.DepositContractData{
ChainId: strconv.FormatUint(params.BeaconConfig().DepositChainID, 10),
Address: params.BeaconConfig().DepositContractAddress,
},
@@ -35,14 +35,14 @@ func GetForkSchedule(w http.ResponseWriter, r *http.Request) {
schedule := params.BeaconConfig().ForkVersionSchedule
if len(schedule) == 0 {
httputil.WriteJson(w, &GetForkScheduleResponse{
Data: make([]*shared.Fork, 0),
httputil.WriteJson(w, &structs.GetForkScheduleResponse{
Data: make([]*structs.Fork, 0),
})
return
}
versions := forks.SortedForkVersions(schedule)
chainForks := make([]*shared.Fork, len(schedule))
chainForks := make([]*structs.Fork, len(schedule))
var previous, current []byte
for i, v := range versions {
if i == 0 {
@@ -52,14 +52,14 @@ func GetForkSchedule(w http.ResponseWriter, r *http.Request) {
}
copyV := v
current = copyV[:]
chainForks[i] = &shared.Fork{
chainForks[i] = &structs.Fork{
PreviousVersion: hexutil.Encode(previous),
CurrentVersion: hexutil.Encode(current),
Epoch: fmt.Sprintf("%d", schedule[v]),
}
}
httputil.WriteJson(w, &GetForkScheduleResponse{
httputil.WriteJson(w, &structs.GetForkScheduleResponse{
Data: chainForks,
})
}
@@ -77,7 +77,7 @@ func GetSpec(w http.ResponseWriter, r *http.Request) {
httputil.HandleError(w, "Could not prepare config spec: "+err.Error(), http.StatusInternalServerError)
return
}
httputil.WriteJson(w, &GetSpecResponse{Data: data})
httputil.WriteJson(w, &structs.GetSpecResponse{Data: data})
}
func prepareConfigSpec() (map[string]string, error) {

View File

@@ -11,6 +11,7 @@ import (
"github.com/ethereum/go-ethereum/common"
"github.com/ethereum/go-ethereum/common/hexutil"
"github.com/prysmaticlabs/prysm/v4/api/server/structs"
"github.com/prysmaticlabs/prysm/v4/config/params"
"github.com/prysmaticlabs/prysm/v4/consensus-types/primitives"
@@ -33,7 +34,7 @@ func TestGetDepositContract(t *testing.T) {
GetDepositContract(writer, request)
require.Equal(t, http.StatusOK, writer.Code)
response := GetDepositContractResponse{}
response := structs.GetDepositContractResponse{}
require.NoError(t, json.Unmarshal(writer.Body.Bytes(), &response))
assert.Equal(t, "10", response.Data.ChainId)
assert.Equal(t, "0x4242424242424242424242424242424242424242", response.Data.Address)
@@ -167,7 +168,7 @@ func TestGetSpec(t *testing.T) {
GetSpec(writer, request)
require.Equal(t, http.StatusOK, writer.Code)
resp := GetSpecResponse{}
resp := structs.GetSpecResponse{}
require.NoError(t, json.Unmarshal(writer.Body.Bytes(), &resp))
data, ok := resp.Data.(map[string]interface{})
require.Equal(t, true, ok)
@@ -486,7 +487,7 @@ func TestForkSchedule_Ok(t *testing.T) {
GetForkSchedule(writer, request)
require.Equal(t, http.StatusOK, writer.Code)
resp := &GetForkScheduleResponse{}
resp := &structs.GetForkScheduleResponse{}
require.NoError(t, json.Unmarshal(writer.Body.Bytes(), resp))
require.Equal(t, 3, len(resp.Data))
fork := resp.Data[0]
@@ -509,7 +510,7 @@ func TestForkSchedule_Ok(t *testing.T) {
GetForkSchedule(writer, request)
require.Equal(t, http.StatusOK, writer.Code)
resp := &GetForkScheduleResponse{}
resp := &structs.GetForkScheduleResponse{}
require.NoError(t, json.Unmarshal(writer.Body.Bytes(), resp))
os := forks.NewOrderedSchedule(params.BeaconConfig())
assert.Equal(t, os.Len(), len(resp.Data))

View File

@@ -5,12 +5,12 @@ go_library(
srcs = [
"handlers.go",
"server.go",
"structs.go",
],
importpath = "github.com/prysmaticlabs/prysm/v4/beacon-chain/rpc/eth/debug",
visibility = ["//visibility:public"],
deps = [
"//api:go_default_library",
"//api/server/structs:go_default_library",
"//beacon-chain/blockchain:go_default_library",
"//beacon-chain/db:go_default_library",
"//beacon-chain/rpc/eth/helpers:go_default_library",
@@ -30,11 +30,11 @@ go_test(
embed = [":go_default_library"],
deps = [
"//api:go_default_library",
"//api/server/structs:go_default_library",
"//beacon-chain/blockchain/testing:go_default_library",
"//beacon-chain/db/testing:go_default_library",
"//beacon-chain/forkchoice/doubly-linked-tree:go_default_library",
"//beacon-chain/forkchoice/types:go_default_library",
"//beacon-chain/rpc/eth/shared:go_default_library",
"//beacon-chain/rpc/testutil:go_default_library",
"//encoding/bytesutil:go_default_library",
"//runtime/version:go_default_library",

View File

@@ -9,6 +9,7 @@ import (
"github.com/ethereum/go-ethereum/common/hexutil"
"github.com/gorilla/mux"
"github.com/prysmaticlabs/prysm/v4/api"
"github.com/prysmaticlabs/prysm/v4/api/server/structs"
"github.com/prysmaticlabs/prysm/v4/beacon-chain/rpc/eth/helpers"
"github.com/prysmaticlabs/prysm/v4/beacon-chain/rpc/eth/shared"
"github.com/prysmaticlabs/prysm/v4/network/httputil"
@@ -84,31 +85,31 @@ func (s *Server) getBeaconStateV2(ctx context.Context, w http.ResponseWriter, id
switch st.Version() {
case version.Phase0:
respSt, err = shared.BeaconStateFromConsensus(st)
respSt, err = structs.BeaconStateFromConsensus(st)
if err != nil {
httputil.HandleError(w, errMsgStateFromConsensus+": "+err.Error(), http.StatusInternalServerError)
return
}
case version.Altair:
respSt, err = shared.BeaconStateAltairFromConsensus(st)
respSt, err = structs.BeaconStateAltairFromConsensus(st)
if err != nil {
httputil.HandleError(w, errMsgStateFromConsensus+": "+err.Error(), http.StatusInternalServerError)
return
}
case version.Bellatrix:
respSt, err = shared.BeaconStateBellatrixFromConsensus(st)
respSt, err = structs.BeaconStateBellatrixFromConsensus(st)
if err != nil {
httputil.HandleError(w, errMsgStateFromConsensus+": "+err.Error(), http.StatusInternalServerError)
return
}
case version.Capella:
respSt, err = shared.BeaconStateCapellaFromConsensus(st)
respSt, err = structs.BeaconStateCapellaFromConsensus(st)
if err != nil {
httputil.HandleError(w, errMsgStateFromConsensus+": "+err.Error(), http.StatusInternalServerError)
return
}
case version.Deneb:
respSt, err = shared.BeaconStateDenebFromConsensus(st)
respSt, err = structs.BeaconStateDenebFromConsensus(st)
if err != nil {
httputil.HandleError(w, errMsgStateFromConsensus+": "+err.Error(), http.StatusInternalServerError)
return
@@ -124,7 +125,7 @@ func (s *Server) getBeaconStateV2(ctx context.Context, w http.ResponseWriter, id
return
}
ver := version.String(st.Version())
resp := &GetBeaconStateV2Response{
resp := &structs.GetBeaconStateV2Response{
Version: ver,
ExecutionOptimistic: isOptimistic,
Finalized: isFinalized,
@@ -156,8 +157,8 @@ func (s *Server) GetForkChoiceHeadsV2(w http.ResponseWriter, r *http.Request) {
defer span.End()
headRoots, headSlots := s.HeadFetcher.ChainHeads()
resp := &GetForkChoiceHeadsV2Response{
Data: make([]*ForkChoiceHead, len(headRoots)),
resp := &structs.GetForkChoiceHeadsV2Response{
Data: make([]*structs.ForkChoiceHead, len(headRoots)),
}
for i := range headRoots {
isOptimistic, err := s.OptimisticModeFetcher.IsOptimisticForRoot(ctx, headRoots[i])
@@ -165,7 +166,7 @@ func (s *Server) GetForkChoiceHeadsV2(w http.ResponseWriter, r *http.Request) {
httputil.HandleError(w, "Could not check if head is optimistic: "+err.Error(), http.StatusInternalServerError)
return
}
resp.Data[i] = &ForkChoiceHead{
resp.Data[i] = &structs.ForkChoiceHead{
Root: hexutil.Encode(headRoots[i][:]),
Slot: fmt.Sprintf("%d", headSlots[i]),
ExecutionOptimistic: isOptimistic,
@@ -186,9 +187,9 @@ func (s *Server) GetForkChoice(w http.ResponseWriter, r *http.Request) {
return
}
nodes := make([]*ForkChoiceNode, len(dump.ForkChoiceNodes))
nodes := make([]*structs.ForkChoiceNode, len(dump.ForkChoiceNodes))
for i, n := range dump.ForkChoiceNodes {
nodes[i] = &ForkChoiceNode{
nodes[i] = &structs.ForkChoiceNode{
Slot: fmt.Sprintf("%d", n.Slot),
BlockRoot: hexutil.Encode(n.BlockRoot),
ParentRoot: hexutil.Encode(n.ParentRoot),
@@ -197,7 +198,7 @@ func (s *Server) GetForkChoice(w http.ResponseWriter, r *http.Request) {
Weight: fmt.Sprintf("%d", n.Weight),
ExecutionBlockHash: hexutil.Encode(n.ExecutionBlockHash),
Validity: n.Validity.String(),
ExtraData: &ForkChoiceNodeExtraData{
ExtraData: &structs.ForkChoiceNodeExtraData{
UnrealizedJustifiedEpoch: fmt.Sprintf("%d", n.UnrealizedJustifiedEpoch),
UnrealizedFinalizedEpoch: fmt.Sprintf("%d", n.UnrealizedFinalizedEpoch),
Balance: fmt.Sprintf("%d", n.Balance),
@@ -206,13 +207,13 @@ func (s *Server) GetForkChoice(w http.ResponseWriter, r *http.Request) {
},
}
}
resp := &GetForkChoiceDumpResponse{
JustifiedCheckpoint: shared.CheckpointFromConsensus(dump.JustifiedCheckpoint),
FinalizedCheckpoint: shared.CheckpointFromConsensus(dump.FinalizedCheckpoint),
resp := &structs.GetForkChoiceDumpResponse{
JustifiedCheckpoint: structs.CheckpointFromConsensus(dump.JustifiedCheckpoint),
FinalizedCheckpoint: structs.CheckpointFromConsensus(dump.FinalizedCheckpoint),
ForkChoiceNodes: nodes,
ExtraData: &ForkChoiceDumpExtraData{
UnrealizedJustifiedCheckpoint: shared.CheckpointFromConsensus(dump.UnrealizedJustifiedCheckpoint),
UnrealizedFinalizedCheckpoint: shared.CheckpointFromConsensus(dump.UnrealizedFinalizedCheckpoint),
ExtraData: &structs.ForkChoiceDumpExtraData{
UnrealizedJustifiedCheckpoint: structs.CheckpointFromConsensus(dump.UnrealizedJustifiedCheckpoint),
UnrealizedFinalizedCheckpoint: structs.CheckpointFromConsensus(dump.UnrealizedFinalizedCheckpoint),
ProposerBoostRoot: hexutil.Encode(dump.ProposerBoostRoot),
PreviousProposerBoostRoot: hexutil.Encode(dump.PreviousProposerBoostRoot),
HeadRoot: hexutil.Encode(dump.HeadRoot),

View File

@@ -11,11 +11,11 @@ import (
"github.com/ethereum/go-ethereum/common/hexutil"
"github.com/gorilla/mux"
"github.com/prysmaticlabs/prysm/v4/api"
"github.com/prysmaticlabs/prysm/v4/api/server/structs"
blockchainmock "github.com/prysmaticlabs/prysm/v4/beacon-chain/blockchain/testing"
dbtest "github.com/prysmaticlabs/prysm/v4/beacon-chain/db/testing"
doublylinkedtree "github.com/prysmaticlabs/prysm/v4/beacon-chain/forkchoice/doubly-linked-tree"
forkchoicetypes "github.com/prysmaticlabs/prysm/v4/beacon-chain/forkchoice/types"
"github.com/prysmaticlabs/prysm/v4/beacon-chain/rpc/eth/shared"
"github.com/prysmaticlabs/prysm/v4/beacon-chain/rpc/testutil"
"github.com/prysmaticlabs/prysm/v4/encoding/bytesutil"
"github.com/prysmaticlabs/prysm/v4/runtime/version"
@@ -71,10 +71,10 @@ func TestGetBeaconStateV2(t *testing.T) {
s.GetBeaconStateV2(writer, request)
require.Equal(t, http.StatusOK, writer.Code)
resp := &GetBeaconStateV2Response{}
resp := &structs.GetBeaconStateV2Response{}
require.NoError(t, json.Unmarshal(writer.Body.Bytes(), resp))
assert.Equal(t, version.String(version.Phase0), resp.Version)
st := &shared.BeaconState{}
st := &structs.BeaconState{}
require.NoError(t, json.Unmarshal(resp.Data, st))
assert.Equal(t, "123", st.Slot)
})
@@ -99,10 +99,10 @@ func TestGetBeaconStateV2(t *testing.T) {
s.GetBeaconStateV2(writer, request)
require.Equal(t, http.StatusOK, writer.Code)
resp := &GetBeaconStateV2Response{}
resp := &structs.GetBeaconStateV2Response{}
require.NoError(t, json.Unmarshal(writer.Body.Bytes(), resp))
assert.Equal(t, version.String(version.Altair), resp.Version)
st := &shared.BeaconStateAltair{}
st := &structs.BeaconStateAltair{}
require.NoError(t, json.Unmarshal(resp.Data, st))
assert.Equal(t, "123", st.Slot)
})
@@ -127,10 +127,10 @@ func TestGetBeaconStateV2(t *testing.T) {
s.GetBeaconStateV2(writer, request)
require.Equal(t, http.StatusOK, writer.Code)
resp := &GetBeaconStateV2Response{}
resp := &structs.GetBeaconStateV2Response{}
require.NoError(t, json.Unmarshal(writer.Body.Bytes(), resp))
assert.Equal(t, version.String(version.Bellatrix), resp.Version)
st := &shared.BeaconStateBellatrix{}
st := &structs.BeaconStateBellatrix{}
require.NoError(t, json.Unmarshal(resp.Data, st))
assert.Equal(t, "123", st.Slot)
})
@@ -155,10 +155,10 @@ func TestGetBeaconStateV2(t *testing.T) {
s.GetBeaconStateV2(writer, request)
require.Equal(t, http.StatusOK, writer.Code)
resp := &GetBeaconStateV2Response{}
resp := &structs.GetBeaconStateV2Response{}
require.NoError(t, json.Unmarshal(writer.Body.Bytes(), resp))
assert.Equal(t, version.String(version.Capella), resp.Version)
st := &shared.BeaconStateCapella{}
st := &structs.BeaconStateCapella{}
require.NoError(t, json.Unmarshal(resp.Data, st))
assert.Equal(t, "123", st.Slot)
})
@@ -183,10 +183,10 @@ func TestGetBeaconStateV2(t *testing.T) {
s.GetBeaconStateV2(writer, request)
require.Equal(t, http.StatusOK, writer.Code)
resp := &GetBeaconStateV2Response{}
resp := &structs.GetBeaconStateV2Response{}
require.NoError(t, json.Unmarshal(writer.Body.Bytes(), resp))
assert.Equal(t, version.String(version.Deneb), resp.Version)
st := &shared.BeaconStateDeneb{}
st := &structs.BeaconStateDeneb{}
require.NoError(t, json.Unmarshal(resp.Data, st))
assert.Equal(t, "123", st.Slot)
})
@@ -219,7 +219,7 @@ func TestGetBeaconStateV2(t *testing.T) {
s.GetBeaconStateV2(writer, request)
require.Equal(t, http.StatusOK, writer.Code)
resp := &GetBeaconStateV2Response{}
resp := &structs.GetBeaconStateV2Response{}
require.NoError(t, json.Unmarshal(writer.Body.Bytes(), resp))
assert.Equal(t, true, resp.ExecutionOptimistic)
})
@@ -258,7 +258,7 @@ func TestGetBeaconStateV2(t *testing.T) {
s.GetBeaconStateV2(writer, request)
require.Equal(t, http.StatusOK, writer.Code)
resp := &GetBeaconStateV2Response{}
resp := &structs.GetBeaconStateV2Response{}
require.NoError(t, json.Unmarshal(writer.Body.Bytes(), resp))
assert.Equal(t, true, resp.Finalized)
})
@@ -411,7 +411,7 @@ func TestGetForkChoiceHeadsV2(t *testing.T) {
s.GetForkChoiceHeadsV2(writer, request)
require.Equal(t, http.StatusOK, writer.Code)
resp := &GetForkChoiceHeadsV2Response{}
resp := &structs.GetForkChoiceHeadsV2Response{}
require.NoError(t, json.Unmarshal(writer.Body.Bytes(), resp))
assert.Equal(t, 2, len(resp.Data))
for _, sr := range expectedSlotsAndRoots {
@@ -447,7 +447,7 @@ func TestGetForkChoiceHeadsV2(t *testing.T) {
s.GetForkChoiceHeadsV2(writer, request)
require.Equal(t, http.StatusOK, writer.Code)
resp := &GetForkChoiceHeadsV2Response{}
resp := &structs.GetForkChoiceHeadsV2Response{}
require.NoError(t, json.Unmarshal(writer.Body.Bytes(), resp))
assert.Equal(t, 2, len(resp.Data))
for _, sr := range expectedSlotsAndRoots {
@@ -477,7 +477,7 @@ func TestGetForkChoice(t *testing.T) {
s.GetForkChoice(writer, request)
require.Equal(t, http.StatusOK, writer.Code)
resp := &GetForkChoiceDumpResponse{}
resp := &structs.GetForkChoiceDumpResponse{}
require.NoError(t, json.Unmarshal(writer.Body.Bytes(), resp))
require.Equal(t, "2", resp.FinalizedCheckpoint.Epoch)
}

View File

@@ -5,12 +5,12 @@ go_library(
srcs = [
"events.go",
"server.go",
"structs.go",
],
importpath = "github.com/prysmaticlabs/prysm/v4/beacon-chain/rpc/eth/events",
visibility = ["//visibility:public"],
deps = [
"//api:go_default_library",
"//api/server/structs:go_default_library",
"//beacon-chain/blockchain:go_default_library",
"//beacon-chain/core/feed:go_default_library",
"//beacon-chain/core/feed/operation:go_default_library",
@@ -18,7 +18,6 @@ go_library(
"//beacon-chain/core/helpers:go_default_library",
"//beacon-chain/core/time:go_default_library",
"//beacon-chain/core/transition:go_default_library",
"//beacon-chain/rpc/eth/shared:go_default_library",
"//config/params:go_default_library",
"//network/httputil:go_default_library",
"//proto/eth/v1:go_default_library",

View File

@@ -9,6 +9,7 @@ import (
"github.com/ethereum/go-ethereum/common/hexutil"
"github.com/prysmaticlabs/prysm/v4/api"
"github.com/prysmaticlabs/prysm/v4/api/server/structs"
"github.com/prysmaticlabs/prysm/v4/beacon-chain/blockchain"
"github.com/prysmaticlabs/prysm/v4/beacon-chain/core/feed"
"github.com/prysmaticlabs/prysm/v4/beacon-chain/core/feed/operation"
@@ -16,7 +17,6 @@ import (
"github.com/prysmaticlabs/prysm/v4/beacon-chain/core/helpers"
"github.com/prysmaticlabs/prysm/v4/beacon-chain/core/time"
"github.com/prysmaticlabs/prysm/v4/beacon-chain/core/transition"
"github.com/prysmaticlabs/prysm/v4/beacon-chain/rpc/eth/shared"
"github.com/prysmaticlabs/prysm/v4/config/params"
"github.com/prysmaticlabs/prysm/v4/network/httputil"
ethpb "github.com/prysmaticlabs/prysm/v4/proto/eth/v1"
@@ -151,7 +151,7 @@ func handleBlockOperationEvents(w http.ResponseWriter, flusher http.Flusher, req
write(w, flusher, topicDataMismatch, event.Data, AttestationTopic)
return
}
att := shared.AttFromConsensus(attData.Attestation.Aggregate)
att := structs.AttFromConsensus(attData.Attestation.Aggregate)
send(w, flusher, AttestationTopic, att)
case operation.UnaggregatedAttReceived:
if _, ok := requestedTopics[AttestationTopic]; !ok {
@@ -162,7 +162,7 @@ func handleBlockOperationEvents(w http.ResponseWriter, flusher http.Flusher, req
write(w, flusher, topicDataMismatch, event.Data, AttestationTopic)
return
}
att := shared.AttFromConsensus(attData.Attestation)
att := structs.AttFromConsensus(attData.Attestation)
send(w, flusher, AttestationTopic, att)
case operation.ExitReceived:
if _, ok := requestedTopics[VoluntaryExitTopic]; !ok {
@@ -173,7 +173,7 @@ func handleBlockOperationEvents(w http.ResponseWriter, flusher http.Flusher, req
write(w, flusher, topicDataMismatch, event.Data, VoluntaryExitTopic)
return
}
exit := shared.SignedExitFromConsensus(exitData.Exit)
exit := structs.SignedExitFromConsensus(exitData.Exit)
send(w, flusher, VoluntaryExitTopic, exit)
case operation.SyncCommitteeContributionReceived:
if _, ok := requestedTopics[SyncCommitteeContributionTopic]; !ok {
@@ -184,7 +184,7 @@ func handleBlockOperationEvents(w http.ResponseWriter, flusher http.Flusher, req
write(w, flusher, topicDataMismatch, event.Data, SyncCommitteeContributionTopic)
return
}
contribution := shared.SignedContributionAndProofFromConsensus(contributionData.Contribution)
contribution := structs.SignedContributionAndProofFromConsensus(contributionData.Contribution)
send(w, flusher, SyncCommitteeContributionTopic, contribution)
case operation.BLSToExecutionChangeReceived:
if _, ok := requestedTopics[BLSToExecutionChangeTopic]; !ok {
@@ -195,7 +195,7 @@ func handleBlockOperationEvents(w http.ResponseWriter, flusher http.Flusher, req
write(w, flusher, topicDataMismatch, event.Data, BLSToExecutionChangeTopic)
return
}
send(w, flusher, BLSToExecutionChangeTopic, shared.SignedBLSChangeFromConsensus(changeData.Change))
send(w, flusher, BLSToExecutionChangeTopic, structs.SignedBLSChangeFromConsensus(changeData.Change))
case operation.BlobSidecarReceived:
if _, ok := requestedTopics[BlobSidecarTopic]; !ok {
return
@@ -206,7 +206,7 @@ func handleBlockOperationEvents(w http.ResponseWriter, flusher http.Flusher, req
return
}
versionedHash := blockchain.ConvertKzgCommitmentToVersionedHash(blobData.Blob.KzgCommitment)
blobEvent := &BlobSidecarEvent{
blobEvent := &structs.BlobSidecarEvent{
BlockRoot: hexutil.Encode(blobData.Blob.BlockRootSlice()),
Index: fmt.Sprintf("%d", blobData.Blob.Index),
Slot: fmt.Sprintf("%d", blobData.Blob.Slot()),
@@ -223,7 +223,7 @@ func handleBlockOperationEvents(w http.ResponseWriter, flusher http.Flusher, req
write(w, flusher, topicDataMismatch, event.Data, AttesterSlashingTopic)
return
}
send(w, flusher, AttesterSlashingTopic, shared.AttesterSlashingFromConsensus(attesterSlashingData.AttesterSlashing))
send(w, flusher, AttesterSlashingTopic, structs.AttesterSlashingFromConsensus(attesterSlashingData.AttesterSlashing))
case operation.ProposerSlashingReceived:
if _, ok := requestedTopics[ProposerSlashingTopic]; !ok {
return
@@ -233,7 +233,7 @@ func handleBlockOperationEvents(w http.ResponseWriter, flusher http.Flusher, req
write(w, flusher, topicDataMismatch, event.Data, ProposerSlashingTopic)
return
}
send(w, flusher, ProposerSlashingTopic, shared.ProposerSlashingFromConsensus(proposerSlashingData.ProposerSlashing))
send(w, flusher, ProposerSlashingTopic, structs.ProposerSlashingFromConsensus(proposerSlashingData.ProposerSlashing))
}
}
@@ -246,7 +246,7 @@ func (s *Server) handleStateEvents(ctx context.Context, w http.ResponseWriter, f
write(w, flusher, topicDataMismatch, event.Data, HeadTopic)
return
}
head := &HeadEvent{
head := &structs.HeadEvent{
Slot: fmt.Sprintf("%d", headData.Slot),
Block: hexutil.Encode(headData.Block),
State: hexutil.Encode(headData.State),
@@ -273,7 +273,7 @@ func (s *Server) handleStateEvents(ctx context.Context, w http.ResponseWriter, f
write(w, flusher, topicDataMismatch, event.Data, FinalizedCheckpointTopic)
return
}
checkpoint := &FinalizedCheckpointEvent{
checkpoint := &structs.FinalizedCheckpointEvent{
Block: hexutil.Encode(checkpointData.Block),
State: hexutil.Encode(checkpointData.State),
Epoch: fmt.Sprintf("%d", checkpointData.Epoch),
@@ -294,24 +294,24 @@ func (s *Server) handleStateEvents(ctx context.Context, w http.ResponseWriter, f
for _, b := range updateData.Data.FinalityBranch {
finalityBranch = append(finalityBranch, hexutil.Encode(b))
}
update := &LightClientFinalityUpdateEvent{
update := &structs.LightClientFinalityUpdateEvent{
Version: version.String(int(updateData.Version)),
Data: &LightClientFinalityUpdate{
AttestedHeader: &shared.BeaconBlockHeader{
Data: &structs.LightClientFinalityUpdate{
AttestedHeader: &structs.BeaconBlockHeader{
Slot: fmt.Sprintf("%d", updateData.Data.AttestedHeader.Slot),
ProposerIndex: fmt.Sprintf("%d", updateData.Data.AttestedHeader.ProposerIndex),
ParentRoot: hexutil.Encode(updateData.Data.AttestedHeader.ParentRoot),
StateRoot: hexutil.Encode(updateData.Data.AttestedHeader.StateRoot),
BodyRoot: hexutil.Encode(updateData.Data.AttestedHeader.BodyRoot),
},
FinalizedHeader: &shared.BeaconBlockHeader{
FinalizedHeader: &structs.BeaconBlockHeader{
Slot: fmt.Sprintf("%d", updateData.Data.FinalizedHeader.Slot),
ProposerIndex: fmt.Sprintf("%d", updateData.Data.FinalizedHeader.ProposerIndex),
ParentRoot: hexutil.Encode(updateData.Data.FinalizedHeader.ParentRoot),
StateRoot: hexutil.Encode(updateData.Data.FinalizedHeader.StateRoot),
},
FinalityBranch: finalityBranch,
SyncAggregate: &shared.SyncAggregate{
SyncAggregate: &structs.SyncAggregate{
SyncCommitteeBits: hexutil.Encode(updateData.Data.SyncAggregate.SyncCommitteeBits),
SyncCommitteeSignature: hexutil.Encode(updateData.Data.SyncAggregate.SyncCommitteeSignature),
},
@@ -328,17 +328,17 @@ func (s *Server) handleStateEvents(ctx context.Context, w http.ResponseWriter, f
write(w, flusher, topicDataMismatch, event.Data, LightClientOptimisticUpdateTopic)
return
}
update := &LightClientOptimisticUpdateEvent{
update := &structs.LightClientOptimisticUpdateEvent{
Version: version.String(int(updateData.Version)),
Data: &LightClientOptimisticUpdate{
AttestedHeader: &shared.BeaconBlockHeader{
Data: &structs.LightClientOptimisticUpdate{
AttestedHeader: &structs.BeaconBlockHeader{
Slot: fmt.Sprintf("%d", updateData.Data.AttestedHeader.Slot),
ProposerIndex: fmt.Sprintf("%d", updateData.Data.AttestedHeader.ProposerIndex),
ParentRoot: hexutil.Encode(updateData.Data.AttestedHeader.ParentRoot),
StateRoot: hexutil.Encode(updateData.Data.AttestedHeader.StateRoot),
BodyRoot: hexutil.Encode(updateData.Data.AttestedHeader.BodyRoot),
},
SyncAggregate: &shared.SyncAggregate{
SyncAggregate: &structs.SyncAggregate{
SyncCommitteeBits: hexutil.Encode(updateData.Data.SyncAggregate.SyncCommitteeBits),
SyncCommitteeSignature: hexutil.Encode(updateData.Data.SyncAggregate.SyncCommitteeSignature),
},
@@ -355,7 +355,7 @@ func (s *Server) handleStateEvents(ctx context.Context, w http.ResponseWriter, f
write(w, flusher, topicDataMismatch, event.Data, ChainReorgTopic)
return
}
reorg := &ChainReorgEvent{
reorg := &structs.ChainReorgEvent{
Slot: fmt.Sprintf("%d", reorgData.Slot),
Depth: fmt.Sprintf("%d", reorgData.Depth),
OldHeadBlock: hexutil.Encode(reorgData.OldHeadBlock),
@@ -380,7 +380,7 @@ func (s *Server) handleStateEvents(ctx context.Context, w http.ResponseWriter, f
write(w, flusher, "Could not get block root: "+err.Error())
return
}
blk := &BlockEvent{
blk := &structs.BlockEvent{
Slot: fmt.Sprintf("%d", blkData.Slot),
Block: hexutil.Encode(blockRoot[:]),
ExecutionOptimistic: blkData.Optimistic,
@@ -442,7 +442,7 @@ func (s *Server) sendPayloadAttributes(ctx context.Context, w http.ResponseWrite
var attributes interface{}
switch headState.Version() {
case version.Bellatrix:
attributes = &PayloadAttributesV1{
attributes = &structs.PayloadAttributesV1{
Timestamp: fmt.Sprintf("%d", t.Unix()),
PrevRandao: hexutil.Encode(prevRando),
SuggestedFeeRecipient: hexutil.Encode(headPayload.FeeRecipient()),
@@ -453,11 +453,11 @@ func (s *Server) sendPayloadAttributes(ctx context.Context, w http.ResponseWrite
write(w, flusher, "Could not get head state expected withdrawals: "+err.Error())
return
}
attributes = &PayloadAttributesV2{
attributes = &structs.PayloadAttributesV2{
Timestamp: fmt.Sprintf("%d", t.Unix()),
PrevRandao: hexutil.Encode(prevRando),
SuggestedFeeRecipient: hexutil.Encode(headPayload.FeeRecipient()),
Withdrawals: shared.WithdrawalsFromConsensus(withdrawals),
Withdrawals: structs.WithdrawalsFromConsensus(withdrawals),
}
case version.Deneb:
withdrawals, err := headState.ExpectedWithdrawals()
@@ -470,11 +470,11 @@ func (s *Server) sendPayloadAttributes(ctx context.Context, w http.ResponseWrite
write(w, flusher, "Could not get head block root: "+err.Error())
return
}
attributes = &PayloadAttributesV3{
attributes = &structs.PayloadAttributesV3{
Timestamp: fmt.Sprintf("%d", t.Unix()),
PrevRandao: hexutil.Encode(prevRando),
SuggestedFeeRecipient: hexutil.Encode(headPayload.FeeRecipient()),
Withdrawals: shared.WithdrawalsFromConsensus(withdrawals),
Withdrawals: structs.WithdrawalsFromConsensus(withdrawals),
ParentBeaconBlockRoot: hexutil.Encode(parentRoot[:]),
}
default:
@@ -487,7 +487,7 @@ func (s *Server) sendPayloadAttributes(ctx context.Context, w http.ResponseWrite
write(w, flusher, err.Error())
return
}
eventData := PayloadAttributesEventData{
eventData := structs.PayloadAttributesEventData{
ProposerIndex: fmt.Sprintf("%d", proposerIndex),
ProposalSlot: fmt.Sprintf("%d", headState.Slot()),
ParentBlockNumber: fmt.Sprintf("%d", headPayload.BlockNumber()),
@@ -500,7 +500,7 @@ func (s *Server) sendPayloadAttributes(ctx context.Context, w http.ResponseWrite
write(w, flusher, err.Error())
return
}
send(w, flusher, PayloadAttributesTopic, &PayloadAttributesEvent{
send(w, flusher, PayloadAttributesTopic, &structs.PayloadAttributesEvent{
Version: version.String(headState.Version()),
Data: eventDataBytes,
})

View File

@@ -11,9 +11,9 @@ go_library(
visibility = ["//visibility:public"],
deps = [
"//api/grpc:go_default_library",
"//api/server/structs:go_default_library",
"//beacon-chain/blockchain:go_default_library",
"//beacon-chain/db:go_default_library",
"//beacon-chain/rpc/eth/shared:go_default_library",
"//beacon-chain/rpc/lookup:go_default_library",
"//beacon-chain/state:go_default_library",
"//beacon-chain/state/stategen:go_default_library",

View File

@@ -9,9 +9,9 @@ import (
"github.com/ethereum/go-ethereum/common/hexutil"
"github.com/pkg/errors"
"github.com/prysmaticlabs/prysm/v4/api/grpc"
"github.com/prysmaticlabs/prysm/v4/api/server/structs"
"github.com/prysmaticlabs/prysm/v4/beacon-chain/blockchain"
"github.com/prysmaticlabs/prysm/v4/beacon-chain/db"
"github.com/prysmaticlabs/prysm/v4/beacon-chain/rpc/eth/shared"
"github.com/prysmaticlabs/prysm/v4/beacon-chain/rpc/lookup"
"github.com/prysmaticlabs/prysm/v4/beacon-chain/sync"
"github.com/prysmaticlabs/prysm/v4/config/params"
@@ -40,8 +40,8 @@ func ValidateSyncGRPC(
return status.Errorf(codes.Internal, "Could not check optimistic status: %v", err)
}
syncDetailsContainer := &shared.SyncDetailsContainer{
Data: &shared.SyncDetails{
syncDetailsContainer := &structs.SyncDetailsContainer{
Data: &structs.SyncDetails{
HeadSlot: strconv.FormatUint(uint64(headSlot), 10),
SyncDistance: strconv.FormatUint(uint64(timeFetcher.CurrentSlot()-headSlot), 10),
IsSyncing: true,

View File

@@ -6,11 +6,11 @@ go_library(
"handlers.go",
"helpers.go",
"server.go",
"structs.go",
],
importpath = "github.com/prysmaticlabs/prysm/v4/beacon-chain/rpc/eth/light-client",
visibility = ["//beacon-chain:__subpackages__"],
deps = [
"//api/server/structs:go_default_library",
"//beacon-chain/blockchain:go_default_library",
"//beacon-chain/rpc/eth/shared:go_default_library",
"//beacon-chain/rpc/lookup:go_default_library",
@@ -37,6 +37,7 @@ go_test(
srcs = ["handlers_test.go"],
embed = [":go_default_library"],
deps = [
"//api/server/structs:go_default_library",
"//beacon-chain/blockchain/testing:go_default_library",
"//beacon-chain/core/helpers:go_default_library",
"//beacon-chain/rpc/testutil:go_default_library",

View File

@@ -8,6 +8,7 @@ import (
"github.com/ethereum/go-ethereum/common/hexutil"
"github.com/gorilla/mux"
"github.com/prysmaticlabs/prysm/v4/api/server/structs"
"go.opencensus.io/trace"
"github.com/wealdtech/go-bytesutil"
@@ -53,7 +54,7 @@ func (s *Server) GetLightClientBootstrap(w http.ResponseWriter, req *http.Reques
return
}
response := &LightClientBootstrapResponse{
response := &structs.LightClientBootstrapResponse{
Version: version.String(blk.Version()),
Data: bootstrap,
}
@@ -118,7 +119,7 @@ func (s *Server) GetLightClientUpdatesByRange(w http.ResponseWriter, req *http.R
}
// Populate updates
var updates []*LightClientUpdateWithVersion
var updates []*structs.LightClientUpdateWithVersion
for period := startPeriod; period <= endPeriod; period++ {
// Get the last known state of the period,
// 1. We wish the block has a parent in the same period if possible
@@ -208,7 +209,7 @@ func (s *Server) GetLightClientUpdatesByRange(w http.ResponseWriter, req *http.R
)
if err == nil {
updates = append(updates, &LightClientUpdateWithVersion{
updates = append(updates, &structs.LightClientUpdateWithVersion{
Version: version.String(attestedState.Version()),
Data: update,
})
@@ -282,7 +283,7 @@ func (s *Server) GetLightClientFinalityUpdate(w http.ResponseWriter, req *http.R
return
}
response := &LightClientUpdateWithVersion{
response := &structs.LightClientUpdateWithVersion{
Version: version.String(attestedState.Version()),
Data: update,
}
@@ -339,7 +340,7 @@ func (s *Server) GetLightClientOptimisticUpdate(w http.ResponseWriter, req *http
return
}
response := &LightClientUpdateWithVersion{
response := &structs.LightClientUpdateWithVersion{
Version: version.String(attestedState.Version()),
Data: update,
}

View File

@@ -11,6 +11,7 @@ import (
"github.com/ethereum/go-ethereum/common/hexutil"
"github.com/gorilla/mux"
"github.com/prysmaticlabs/prysm/v4/api/server/structs"
mock "github.com/prysmaticlabs/prysm/v4/beacon-chain/blockchain/testing"
"github.com/prysmaticlabs/prysm/v4/beacon-chain/core/helpers"
@@ -70,7 +71,7 @@ func TestLightClientHandler_GetLightClientBootstrap(t *testing.T) {
s.GetLightClientBootstrap(writer, request)
require.Equal(t, http.StatusOK, writer.Code)
resp := &LightClientBootstrapResponse{}
resp := &structs.LightClientBootstrapResponse{}
require.NoError(t, json.Unmarshal(writer.Body.Bytes(), resp))
require.Equal(t, "capella", resp.Version)
require.Equal(t, hexutil.Encode(header.Header.BodyRoot), resp.Data.Header.BodyRoot)
@@ -171,7 +172,7 @@ func TestLightClientHandler_GetLightClientUpdatesByRange(t *testing.T) {
s.GetLightClientUpdatesByRange(writer, request)
require.Equal(t, http.StatusOK, writer.Code)
var resp []LightClientUpdateWithVersion
var resp []structs.LightClientUpdateWithVersion
require.NoError(t, json.Unmarshal(writer.Body.Bytes(), &resp))
require.Equal(t, 1, len(resp))
require.Equal(t, "capella", resp[0].Version)
@@ -274,7 +275,7 @@ func TestLightClientHandler_GetLightClientUpdatesByRange_TooBigInputCount(t *tes
s.GetLightClientUpdatesByRange(writer, request)
require.Equal(t, http.StatusOK, writer.Code)
var resp []LightClientUpdateWithVersion
var resp []structs.LightClientUpdateWithVersion
require.NoError(t, json.Unmarshal(writer.Body.Bytes(), &resp))
require.Equal(t, 1, len(resp)) // Even with big count input, the response is still the max available period, which is 1 in test case.
require.Equal(t, "capella", resp[0].Version)
@@ -377,7 +378,7 @@ func TestLightClientHandler_GetLightClientUpdatesByRange_TooEarlyPeriod(t *testi
s.GetLightClientUpdatesByRange(writer, request)
require.Equal(t, http.StatusOK, writer.Code)
var resp []LightClientUpdateWithVersion
var resp []structs.LightClientUpdateWithVersion
require.NoError(t, json.Unmarshal(writer.Body.Bytes(), &resp))
require.Equal(t, 1, len(resp))
require.Equal(t, "capella", resp[0].Version)
@@ -480,7 +481,7 @@ func TestLightClientHandler_GetLightClientUpdatesByRange_TooBigCount(t *testing.
s.GetLightClientUpdatesByRange(writer, request)
require.Equal(t, http.StatusOK, writer.Code)
var resp []LightClientUpdateWithVersion
var resp []structs.LightClientUpdateWithVersion
require.NoError(t, json.Unmarshal(writer.Body.Bytes(), &resp))
require.Equal(t, 1, len(resp))
require.Equal(t, "capella", resp[0].Version)
@@ -684,7 +685,7 @@ func TestLightClientHandler_GetLightClientFinalityUpdate(t *testing.T) {
s.GetLightClientFinalityUpdate(writer, request)
require.Equal(t, http.StatusOK, writer.Code)
resp := &LightClientUpdateWithVersion{}
resp := &structs.LightClientUpdateWithVersion{}
require.NoError(t, json.Unmarshal(writer.Body.Bytes(), resp))
require.Equal(t, "capella", resp.Version)
require.Equal(t, hexutil.Encode(attestedHeader.BodyRoot), resp.Data.AttestedHeader.BodyRoot)
@@ -790,7 +791,7 @@ func TestLightClientHandler_GetLightClientOptimisticUpdate(t *testing.T) {
s.GetLightClientOptimisticUpdate(writer, request)
require.Equal(t, http.StatusOK, writer.Code)
resp := &LightClientUpdateWithVersion{}
resp := &structs.LightClientUpdateWithVersion{}
require.NoError(t, json.Unmarshal(writer.Body.Bytes(), resp))
require.Equal(t, "capella", resp.Version)
require.Equal(t, hexutil.Encode(attestedHeader.BodyRoot), resp.Data.AttestedHeader.BodyRoot)

View File

@@ -6,8 +6,8 @@ import (
"strconv"
"github.com/ethereum/go-ethereum/common/hexutil"
"github.com/prysmaticlabs/prysm/v4/api/server/structs"
"github.com/prysmaticlabs/prysm/v4/beacon-chain/blockchain"
"github.com/prysmaticlabs/prysm/v4/beacon-chain/rpc/eth/shared"
"github.com/prysmaticlabs/prysm/v4/beacon-chain/state"
fieldparams "github.com/prysmaticlabs/prysm/v4/config/fieldparams"
"github.com/prysmaticlabs/prysm/v4/config/params"
@@ -35,7 +35,7 @@ import (
// current_sync_committee=state.current_sync_committee,
// current_sync_committee_branch=compute_merkle_proof_for_state(state, CURRENT_SYNC_COMMITTEE_INDEX)
// )
func createLightClientBootstrap(ctx context.Context, state state.BeaconState) (*LightClientBootstrap, error) {
func createLightClientBootstrap(ctx context.Context, state state.BeaconState) (*structs.LightClientBootstrap, error) {
// assert compute_epoch_at_slot(state.slot) >= ALTAIR_FORK_EPOCH
if slots.ToEpoch(state.Slot()) < params.BeaconConfig().AltairForkEpoch {
return nil, fmt.Errorf("light client bootstrap is not supported before Altair, invalid slot %d", state.Slot())
@@ -53,7 +53,7 @@ func createLightClientBootstrap(ctx context.Context, state state.BeaconState) (*
return nil, fmt.Errorf("could not get current sync committee: %s", err.Error())
}
committee := shared.SyncCommitteeFromConsensus(currentSyncCommittee)
committee := structs.SyncCommitteeFromConsensus(currentSyncCommittee)
currentSyncCommitteeProof, err := state.CurrentSyncCommitteeProof(ctx)
if err != nil {
@@ -65,7 +65,7 @@ func createLightClientBootstrap(ctx context.Context, state state.BeaconState) (*
branch[i] = hexutil.Encode(proof)
}
header := shared.BeaconBlockHeaderFromConsensus(latestBlockHeader)
header := structs.BeaconBlockHeaderFromConsensus(latestBlockHeader)
if header == nil {
return nil, fmt.Errorf("could not get beacon block header")
}
@@ -78,7 +78,7 @@ func createLightClientBootstrap(ctx context.Context, state state.BeaconState) (*
header.StateRoot = hexutil.Encode(stateRoot[:])
// Return result
result := &LightClientBootstrap{
result := &structs.LightClientBootstrap{
Header: header,
CurrentSyncCommittee: committee,
CurrentSyncCommitteeBranch: branch,
@@ -150,7 +150,7 @@ func createLightClientUpdate(
state state.BeaconState,
block interfaces.ReadOnlySignedBeaconBlock,
attestedState state.BeaconState,
finalizedBlock interfaces.ReadOnlySignedBeaconBlock) (*LightClientUpdate, error) {
finalizedBlock interfaces.ReadOnlySignedBeaconBlock) (*structs.LightClientUpdate, error) {
result, err := blockchain.NewLightClientFinalityUpdateFromBeaconState(ctx, state, block, attestedState, finalizedBlock)
if err != nil {
return nil, err
@@ -208,7 +208,7 @@ func newLightClientFinalityUpdateFromBeaconState(
state state.BeaconState,
block interfaces.ReadOnlySignedBeaconBlock,
attestedState state.BeaconState,
finalizedBlock interfaces.ReadOnlySignedBeaconBlock) (*LightClientUpdate, error) {
finalizedBlock interfaces.ReadOnlySignedBeaconBlock) (*structs.LightClientUpdate, error) {
result, err := blockchain.NewLightClientFinalityUpdateFromBeaconState(ctx, state, block, attestedState, finalizedBlock)
if err != nil {
return nil, err
@@ -221,7 +221,7 @@ func newLightClientOptimisticUpdateFromBeaconState(
ctx context.Context,
state state.BeaconState,
block interfaces.ReadOnlySignedBeaconBlock,
attestedState state.BeaconState) (*LightClientUpdate, error) {
attestedState state.BeaconState) (*structs.LightClientUpdate, error) {
result, err := blockchain.NewLightClientOptimisticUpdateFromBeaconState(ctx, state, block, attestedState)
if err != nil {
return nil, err
@@ -230,7 +230,7 @@ func newLightClientOptimisticUpdateFromBeaconState(
return newLightClientUpdateToJSON(result), nil
}
func NewLightClientBootstrapFromJSON(bootstrapJSON *LightClientBootstrap) (*v2.LightClientBootstrap, error) {
func NewLightClientBootstrapFromJSON(bootstrapJSON *structs.LightClientBootstrap) (*v2.LightClientBootstrap, error) {
bootstrap := &v2.LightClientBootstrap{}
var err error
@@ -276,33 +276,33 @@ func branchToJSON(branchBytes [][]byte) []string {
return branch
}
func syncAggregateToJSON(input *v1.SyncAggregate) *shared.SyncAggregate {
func syncAggregateToJSON(input *v1.SyncAggregate) *structs.SyncAggregate {
if input == nil {
return nil
}
return &shared.SyncAggregate{
return &structs.SyncAggregate{
SyncCommitteeBits: hexutil.Encode(input.SyncCommitteeBits),
SyncCommitteeSignature: hexutil.Encode(input.SyncCommitteeSignature),
}
}
func newLightClientUpdateToJSON(input *v2.LightClientUpdate) *LightClientUpdate {
func newLightClientUpdateToJSON(input *v2.LightClientUpdate) *structs.LightClientUpdate {
if input == nil {
return nil
}
var nextSyncCommittee *shared.SyncCommittee
var nextSyncCommittee *structs.SyncCommittee
if input.NextSyncCommittee != nil {
nextSyncCommittee = shared.SyncCommitteeFromConsensus(migration.V2SyncCommitteeToV1Alpha1(input.NextSyncCommittee))
nextSyncCommittee = structs.SyncCommitteeFromConsensus(migration.V2SyncCommitteeToV1Alpha1(input.NextSyncCommittee))
}
var finalizedHeader *shared.BeaconBlockHeader
var finalizedHeader *structs.BeaconBlockHeader
if input.FinalizedHeader != nil {
finalizedHeader = shared.BeaconBlockHeaderFromConsensus(migration.V1HeaderToV1Alpha1(input.FinalizedHeader))
finalizedHeader = structs.BeaconBlockHeaderFromConsensus(migration.V1HeaderToV1Alpha1(input.FinalizedHeader))
}
return &LightClientUpdate{
AttestedHeader: shared.BeaconBlockHeaderFromConsensus(migration.V1HeaderToV1Alpha1(input.AttestedHeader)),
return &structs.LightClientUpdate{
AttestedHeader: structs.BeaconBlockHeaderFromConsensus(migration.V1HeaderToV1Alpha1(input.AttestedHeader)),
NextSyncCommittee: nextSyncCommittee,
NextSyncCommitteeBranch: branchToJSON(input.NextSyncCommitteeBranch),
FinalizedHeader: finalizedHeader,

View File

@@ -1,35 +0,0 @@
package lightclient
import (
"github.com/prysmaticlabs/prysm/v4/beacon-chain/rpc/eth/shared"
)
type LightClientBootstrapResponse struct {
Version string `json:"version"`
Data *LightClientBootstrap `json:"data"`
}
type LightClientBootstrap struct {
Header *shared.BeaconBlockHeader `json:"header"`
CurrentSyncCommittee *shared.SyncCommittee `json:"current_sync_committee"`
CurrentSyncCommitteeBranch []string `json:"current_sync_committee_branch"`
}
type LightClientUpdate struct {
AttestedHeader *shared.BeaconBlockHeader `json:"attested_header"`
NextSyncCommittee *shared.SyncCommittee `json:"next_sync_committee,omitempty"`
FinalizedHeader *shared.BeaconBlockHeader `json:"finalized_header,omitempty"`
SyncAggregate *shared.SyncAggregate `json:"sync_aggregate"`
NextSyncCommitteeBranch []string `json:"next_sync_committee_branch,omitempty"`
FinalityBranch []string `json:"finality_branch,omitempty"`
SignatureSlot string `json:"signature_slot"`
}
type LightClientUpdateWithVersion struct {
Version string `json:"version"`
Data *LightClientUpdate `json:"data"`
}
type LightClientUpdatesByRangeResponse struct {
Updates []*LightClientUpdateWithVersion `json:"updates"`
}

View File

@@ -6,11 +6,11 @@ go_library(
"handlers.go",
"handlers_peers.go",
"server.go",
"structs.go",
],
importpath = "github.com/prysmaticlabs/prysm/v4/beacon-chain/rpc/eth/node",
visibility = ["//visibility:public"],
deps = [
"//api/server/structs:go_default_library",
"//beacon-chain/blockchain:go_default_library",
"//beacon-chain/db:go_default_library",
"//beacon-chain/execution:go_default_library",
@@ -41,6 +41,7 @@ go_test(
],
embed = [":go_default_library"],
deps = [
"//api/server/structs:go_default_library",
"//beacon-chain/blockchain/testing:go_default_library",
"//beacon-chain/p2p:go_default_library",
"//beacon-chain/p2p/peers:go_default_library",

View File

@@ -7,6 +7,7 @@ import (
"strconv"
"github.com/ethereum/go-ethereum/common/hexutil"
"github.com/prysmaticlabs/prysm/v4/api/server/structs"
"github.com/prysmaticlabs/prysm/v4/beacon-chain/p2p"
"github.com/prysmaticlabs/prysm/v4/beacon-chain/rpc/eth/shared"
"github.com/prysmaticlabs/prysm/v4/network/httputil"
@@ -37,8 +38,8 @@ func (s *Server) GetSyncStatus(w http.ResponseWriter, r *http.Request) {
}
headSlot := s.HeadFetcher.HeadSlot()
response := &SyncStatusResponse{
Data: &SyncStatusResponseData{
response := &structs.SyncStatusResponse{
Data: &structs.SyncStatusResponseData{
HeadSlot: strconv.FormatUint(uint64(headSlot), 10),
SyncDistance: strconv.FormatUint(uint64(s.GenesisTimeFetcher.CurrentSlot()-headSlot), 10),
IsSyncing: s.SyncChecker.Syncing(),
@@ -75,13 +76,13 @@ func (s *Server) GetIdentity(w http.ResponseWriter, r *http.Request) {
return
}
resp := &GetIdentityResponse{
Data: &Identity{
resp := &structs.GetIdentityResponse{
Data: &structs.Identity{
PeerId: peerId,
Enr: "enr:" + serializedEnr,
P2PAddresses: p2pAddresses,
DiscoveryAddresses: discoveryAddresses,
Metadata: &Metadata{
Metadata: &structs.Metadata{
SeqNumber: strconv.FormatUint(s.MetadataProvider.MetadataSeq(), 10),
Attnets: hexutil.Encode(s.MetadataProvider.Metadata().AttnetsBitfield()),
},
@@ -97,8 +98,8 @@ func (*Server) GetVersion(w http.ResponseWriter, r *http.Request) {
defer span.End()
v := fmt.Sprintf("Prysm/%s (%s %s)", version.SemanticVersion(), runtime.GOOS, runtime.GOARCH)
resp := &GetVersionResponse{
Data: &Version{
resp := &structs.GetVersionResponse{
Data: &structs.Version{
Version: v,
},
}

View File

@@ -8,6 +8,7 @@ import (
"github.com/gorilla/mux"
"github.com/libp2p/go-libp2p/core/peer"
"github.com/pkg/errors"
"github.com/prysmaticlabs/prysm/v4/api/server/structs"
"github.com/prysmaticlabs/prysm/v4/beacon-chain/p2p"
"github.com/prysmaticlabs/prysm/v4/beacon-chain/p2p/peers"
"github.com/prysmaticlabs/prysm/v4/beacon-chain/p2p/peers/peerdata"
@@ -75,8 +76,8 @@ func (s *Server) GetPeer(w http.ResponseWriter, r *http.Request) {
return
}
resp := &GetPeerResponse{
Data: &Peer{
resp := &structs.GetPeerResponse{
Data: &structs.Peer{
PeerId: rawId,
Enr: "enr:" + serializedEnr,
LastSeenP2PAddress: p2pAddress.String(),
@@ -100,7 +101,7 @@ func (s *Server) GetPeers(w http.ResponseWriter, r *http.Request) {
if emptyStateFilter && emptyDirectionFilter {
allIds := peerStatus.All()
allPeers := make([]*Peer, 0, len(allIds))
allPeers := make([]*structs.Peer, 0, len(allIds))
for _, id := range allIds {
p, err := peerInfo(peerStatus, id)
if err != nil {
@@ -112,7 +113,7 @@ func (s *Server) GetPeers(w http.ResponseWriter, r *http.Request) {
}
allPeers = append(allPeers, p)
}
resp := &GetPeersResponse{Data: allPeers}
resp := &structs.GetPeersResponse{Data: allPeers}
httputil.WriteJson(w, resp)
return
}
@@ -164,7 +165,7 @@ func (s *Server) GetPeers(w http.ResponseWriter, r *http.Request) {
}
}
}
filteredPeers := make([]*Peer, 0, len(filteredIds))
filteredPeers := make([]*structs.Peer, 0, len(filteredIds))
for _, id := range filteredIds {
p, err := peerInfo(peerStatus, id)
if err != nil {
@@ -177,7 +178,7 @@ func (s *Server) GetPeers(w http.ResponseWriter, r *http.Request) {
filteredPeers = append(filteredPeers, p)
}
resp := &GetPeersResponse{Data: filteredPeers}
resp := &structs.GetPeersResponse{Data: filteredPeers}
httputil.WriteJson(w, resp)
}
@@ -188,8 +189,8 @@ func (s *Server) GetPeerCount(w http.ResponseWriter, r *http.Request) {
peerStatus := s.PeersFetcher.Peers()
resp := &GetPeerCountResponse{
Data: &PeerCount{
resp := &structs.GetPeerCountResponse{
Data: &structs.PeerCount{
Disconnected: strconv.FormatInt(int64(len(peerStatus.Disconnected())), 10),
Connecting: strconv.FormatInt(int64(len(peerStatus.Connecting())), 10),
Connected: strconv.FormatInt(int64(len(peerStatus.Connected())), 10),
@@ -224,7 +225,7 @@ func handleEmptyFilters(states []string, directions []string) (emptyState, empty
return emptyState, emptyDirection
}
func peerInfo(peerStatus *peers.Status, id peer.ID) (*Peer, error) {
func peerInfo(peerStatus *peers.Status, id peer.ID) (*structs.Peer, error) {
enr, err := peerStatus.ENR(id)
if err != nil {
if errors.Is(err, peerdata.ErrPeerUnknown) {
@@ -263,7 +264,7 @@ func peerInfo(peerStatus *peers.Status, id peer.ID) (*Peer, error) {
if eth.PeerDirection(direction) == eth.PeerDirection_UNKNOWN {
return nil, nil
}
p := &Peer{
p := &structs.Peer{
PeerId: id.String(),
State: strings.ToLower(eth.ConnectionState(connectionState).String()),
Direction: strings.ToLower(eth.PeerDirection(direction).String()),

View File

@@ -15,6 +15,7 @@ import (
"github.com/libp2p/go-libp2p/core/peer"
libp2ptest "github.com/libp2p/go-libp2p/p2p/host/peerstore/test"
ma "github.com/multiformats/go-multiaddr"
"github.com/prysmaticlabs/prysm/v4/api/server/structs"
"github.com/prysmaticlabs/prysm/v4/beacon-chain/p2p"
"github.com/prysmaticlabs/prysm/v4/beacon-chain/p2p/peers"
mockp2p "github.com/prysmaticlabs/prysm/v4/beacon-chain/p2p/testing"
@@ -48,7 +49,7 @@ func TestGetPeer(t *testing.T) {
s.GetPeer(writer, request)
require.Equal(t, http.StatusOK, writer.Code)
resp := &GetPeerResponse{}
resp := &structs.GetPeerResponse{}
require.NoError(t, json.Unmarshal(writer.Body.Bytes(), resp))
assert.Equal(t, rawId, resp.Data.PeerId)
assert.Equal(t, p2pAddr, resp.Data.LastSeenP2PAddress)
@@ -142,7 +143,7 @@ func TestGetPeers(t *testing.T) {
s.GetPeers(writer, request)
require.Equal(t, http.StatusOK, writer.Code)
resp := &GetPeersResponse{}
resp := &structs.GetPeersResponse{}
require.NoError(t, json.Unmarshal(writer.Body.Bytes(), resp))
require.Equal(t, 1, len(resp.Data))
returnedPeer := resp.Data[0]
@@ -226,7 +227,7 @@ func TestGetPeers(t *testing.T) {
s.GetPeers(writer, request)
require.Equal(t, http.StatusOK, writer.Code)
resp := &GetPeersResponse{}
resp := &structs.GetPeersResponse{}
require.NoError(t, json.Unmarshal(writer.Body.Bytes(), resp))
assert.Equal(t, len(tt.wantIds), len(resp.Data), "Wrong number of peers returned")
for _, id := range tt.wantIds {
@@ -257,7 +258,7 @@ func TestGetPeers_NoPeersReturnsEmptyArray(t *testing.T) {
s.GetPeers(writer, request)
require.Equal(t, http.StatusOK, writer.Code)
resp := &GetPeersResponse{}
resp := &structs.GetPeersResponse{}
require.NoError(t, json.Unmarshal(writer.Body.Bytes(), resp))
assert.Equal(t, 0, len(resp.Data))
}
@@ -307,7 +308,7 @@ func TestGetPeerCount(t *testing.T) {
writer.Body = &bytes.Buffer{}
s.GetPeerCount(writer, request)
require.Equal(t, http.StatusOK, writer.Code)
resp := &GetPeerCountResponse{}
resp := &structs.GetPeerCountResponse{}
require.NoError(t, json.Unmarshal(writer.Body.Bytes(), resp))
assert.Equal(t, "1", resp.Data.Connecting, "Wrong number of connecting peers")
assert.Equal(t, "2", resp.Data.Connected, "Wrong number of connected peers")

View File

@@ -14,6 +14,7 @@ import (
"github.com/libp2p/go-libp2p/core/peer"
ma "github.com/multiformats/go-multiaddr"
"github.com/prysmaticlabs/go-bitfield"
"github.com/prysmaticlabs/prysm/v4/api/server/structs"
mock "github.com/prysmaticlabs/prysm/v4/beacon-chain/blockchain/testing"
"github.com/prysmaticlabs/prysm/v4/beacon-chain/p2p"
mockp2p "github.com/prysmaticlabs/prysm/v4/beacon-chain/p2p/testing"
@@ -59,7 +60,7 @@ func TestSyncStatus(t *testing.T) {
s.GetSyncStatus(writer, request)
assert.Equal(t, http.StatusOK, writer.Code)
resp := &SyncStatusResponse{}
resp := &structs.SyncStatusResponse{}
require.NoError(t, json.Unmarshal(writer.Body.Bytes(), resp))
require.NotNil(t, resp)
assert.Equal(t, "100", resp.Data.HeadSlot)
@@ -81,7 +82,7 @@ func TestGetVersion(t *testing.T) {
s := &Server{}
s.GetVersion(writer, request)
assert.Equal(t, http.StatusOK, writer.Code)
resp := &GetVersionResponse{}
resp := &structs.GetVersionResponse{}
require.NoError(t, json.Unmarshal(writer.Body.Bytes(), resp))
assert.StringContains(t, semVer, resp.Data.Version)
assert.StringContains(t, os, resp.Data.Version)
@@ -156,7 +157,7 @@ func TestGetIdentity(t *testing.T) {
s.GetIdentity(writer, request)
require.Equal(t, http.StatusOK, writer.Code)
resp := &GetIdentityResponse{}
resp := &structs.GetIdentityResponse{}
require.NoError(t, json.Unmarshal(writer.Body.Bytes(), resp))
expectedID := peer.ID("foo").String()
assert.Equal(t, expectedID, resp.Data.PeerId)

View File

@@ -6,11 +6,11 @@ go_library(
"handlers.go",
"server.go",
"service.go",
"structs.go",
],
importpath = "github.com/prysmaticlabs/prysm/v4/beacon-chain/rpc/eth/rewards",
visibility = ["//visibility:public"],
deps = [
"//api/server/structs:go_default_library",
"//beacon-chain/blockchain:go_default_library",
"//beacon-chain/core/altair:go_default_library",
"//beacon-chain/core/blocks:go_default_library",
@@ -38,6 +38,7 @@ go_test(
srcs = ["handlers_test.go"],
embed = [":go_default_library"],
deps = [
"//api/server/structs:go_default_library",
"//beacon-chain/blockchain/testing:go_default_library",
"//beacon-chain/core/altair:go_default_library",
"//beacon-chain/core/helpers:go_default_library",

View File

@@ -7,6 +7,7 @@ import (
"strconv"
"strings"
"github.com/prysmaticlabs/prysm/v4/api/server/structs"
"github.com/prysmaticlabs/prysm/v4/beacon-chain/core/altair"
"github.com/prysmaticlabs/prysm/v4/beacon-chain/core/epoch/precompute"
"github.com/prysmaticlabs/prysm/v4/beacon-chain/rpc/eth/shared"
@@ -52,7 +53,7 @@ func (s *Server) BlockRewards(w http.ResponseWriter, r *http.Request) {
httputil.WriteError(w, httpError)
return
}
response := &BlockRewardsResponse{
response := &structs.BlockRewardsResponse{
Data: blockRewards,
ExecutionOptimistic: optimistic,
Finalized: s.FinalizationFetcher.IsFinalized(ctx, blkRoot),
@@ -91,8 +92,8 @@ func (s *Server) AttestationRewards(w http.ResponseWriter, r *http.Request) {
return
}
resp := &AttestationRewardsResponse{
Data: AttestationRewards{
resp := &structs.AttestationRewardsResponse{
Data: structs.AttestationRewards{
IdealRewards: idealRewards,
TotalRewards: totalRewards,
},
@@ -174,14 +175,14 @@ func (s *Server) SyncCommitteeRewards(w http.ResponseWriter, r *http.Request) {
return
}
scRewards := make([]SyncCommitteeReward, len(valIndices))
scRewards := make([]structs.SyncCommitteeReward, len(valIndices))
for i, valIdx := range valIndices {
scRewards[i] = SyncCommitteeReward{
scRewards[i] = structs.SyncCommitteeReward{
ValidatorIndex: strconv.FormatUint(uint64(valIdx), 10),
Reward: strconv.Itoa(rewards[i]),
}
}
response := &SyncCommitteeRewardsResponse{
response := &structs.SyncCommitteeRewardsResponse{
Data: scRewards,
ExecutionOptimistic: optimistic,
Finalized: s.FinalizationFetcher.IsFinalized(r.Context(), blkRoot),
@@ -257,11 +258,11 @@ func idealAttRewards(
st state.BeaconState,
bal *precompute.Balance,
vals []*precompute.Validator,
) ([]IdealAttestationReward, bool) {
) ([]structs.IdealAttestationReward, bool) {
idealValsCount := uint64(16)
minIdealBalance := uint64(17)
maxIdealBalance := minIdealBalance + idealValsCount - 1
idealRewards := make([]IdealAttestationReward, 0, idealValsCount)
idealRewards := make([]structs.IdealAttestationReward, 0, idealValsCount)
idealVals := make([]*precompute.Validator, 0, idealValsCount)
increment := params.BeaconConfig().EffectiveBalanceIncrement
for i := minIdealBalance; i <= maxIdealBalance; i++ {
@@ -276,7 +277,7 @@ func idealAttRewards(
IsPrevEpochTargetAttester: true,
IsPrevEpochHeadAttester: true,
})
idealRewards = append(idealRewards, IdealAttestationReward{
idealRewards = append(idealRewards, structs.IdealAttestationReward{
EffectiveBalance: strconv.FormatUint(effectiveBalance, 10),
Inactivity: strconv.FormatUint(0, 10),
})
@@ -316,10 +317,10 @@ func totalAttRewards(
bal *precompute.Balance,
vals []*precompute.Validator,
valIndices []primitives.ValidatorIndex,
) ([]TotalAttestationReward, bool) {
totalRewards := make([]TotalAttestationReward, len(valIndices))
) ([]structs.TotalAttestationReward, bool) {
totalRewards := make([]structs.TotalAttestationReward, len(valIndices))
for i, v := range valIndices {
totalRewards[i] = TotalAttestationReward{ValidatorIndex: strconv.FormatUint(uint64(v), 10)}
totalRewards[i] = structs.TotalAttestationReward{ValidatorIndex: strconv.FormatUint(uint64(v), 10)}
}
deltas, err := altair.AttestationsDelta(st, bal, vals)
if err != nil {

View File

@@ -13,6 +13,7 @@ import (
"github.com/pkg/errors"
"github.com/prysmaticlabs/go-bitfield"
"github.com/prysmaticlabs/prysm/v4/api/server/structs"
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/helpers"
@@ -236,7 +237,7 @@ func TestBlockRewards(t *testing.T) {
s.BlockRewards(writer, request)
assert.Equal(t, http.StatusOK, writer.Code)
resp := &BlockRewardsResponse{}
resp := &structs.BlockRewardsResponse{}
require.NoError(t, json.Unmarshal(writer.Body.Bytes(), resp))
assert.Equal(t, "12", resp.Data.ProposerIndex)
assert.Equal(t, "125089490", resp.Data.Total)
@@ -269,7 +270,7 @@ func TestBlockRewards(t *testing.T) {
s.BlockRewards(writer, request)
assert.Equal(t, http.StatusOK, writer.Code)
resp := &BlockRewardsResponse{}
resp := &structs.BlockRewardsResponse{}
require.NoError(t, json.Unmarshal(writer.Body.Bytes(), resp))
assert.Equal(t, "12", resp.Data.ProposerIndex)
assert.Equal(t, "125089490", resp.Data.Total)
@@ -302,7 +303,7 @@ func TestBlockRewards(t *testing.T) {
s.BlockRewards(writer, request)
assert.Equal(t, http.StatusOK, writer.Code)
resp := &BlockRewardsResponse{}
resp := &structs.BlockRewardsResponse{}
require.NoError(t, json.Unmarshal(writer.Body.Bytes(), resp))
assert.Equal(t, "12", resp.Data.ProposerIndex)
assert.Equal(t, "125089490", resp.Data.Total)
@@ -335,7 +336,7 @@ func TestBlockRewards(t *testing.T) {
s.BlockRewards(writer, request)
assert.Equal(t, http.StatusOK, writer.Code)
resp := &BlockRewardsResponse{}
resp := &structs.BlockRewardsResponse{}
require.NoError(t, json.Unmarshal(writer.Body.Bytes(), resp))
assert.Equal(t, "12", resp.Data.ProposerIndex)
assert.Equal(t, "125089490", resp.Data.Total)
@@ -404,7 +405,7 @@ func TestAttestationRewards(t *testing.T) {
s.AttestationRewards(writer, request)
assert.Equal(t, http.StatusOK, writer.Code)
resp := &AttestationRewardsResponse{}
resp := &structs.AttestationRewardsResponse{}
require.NoError(t, json.Unmarshal(writer.Body.Bytes(), resp))
require.Equal(t, 16, len(resp.Data.IdealRewards))
sum := uint64(0)
@@ -433,7 +434,7 @@ func TestAttestationRewards(t *testing.T) {
s.AttestationRewards(writer, request)
assert.Equal(t, http.StatusOK, writer.Code)
resp := &AttestationRewardsResponse{}
resp := &structs.AttestationRewardsResponse{}
require.NoError(t, json.Unmarshal(writer.Body.Bytes(), resp))
require.Equal(t, 2, len(resp.Data.TotalRewards))
sum := uint64(0)
@@ -456,7 +457,7 @@ func TestAttestationRewards(t *testing.T) {
s.AttestationRewards(writer, request)
assert.Equal(t, http.StatusOK, writer.Code)
resp := &AttestationRewardsResponse{}
resp := &structs.AttestationRewardsResponse{}
require.NoError(t, json.Unmarshal(writer.Body.Bytes(), resp))
require.Equal(t, 64, len(resp.Data.TotalRewards))
sum := uint64(0)
@@ -498,7 +499,7 @@ func TestAttestationRewards(t *testing.T) {
s.AttestationRewards(writer, request)
assert.Equal(t, http.StatusOK, writer.Code)
resp := &AttestationRewardsResponse{}
resp := &structs.AttestationRewardsResponse{}
require.NoError(t, json.Unmarshal(writer.Body.Bytes(), resp))
assert.Equal(t, "0", resp.Data.TotalRewards[0].Head)
assert.Equal(t, "-439299", resp.Data.TotalRewards[0].Source)
@@ -536,7 +537,7 @@ func TestAttestationRewards(t *testing.T) {
s.AttestationRewards(writer, request)
assert.Equal(t, http.StatusOK, writer.Code)
resp := &AttestationRewardsResponse{}
resp := &structs.AttestationRewardsResponse{}
require.NoError(t, json.Unmarshal(writer.Body.Bytes(), resp))
assert.Equal(t, "-4768", resp.Data.TotalRewards[0].Inactivity)
})
@@ -737,7 +738,7 @@ func TestSyncCommiteeRewards(t *testing.T) {
s.SyncCommitteeRewards(writer, request)
assert.Equal(t, http.StatusOK, writer.Code)
resp := &SyncCommitteeRewardsResponse{}
resp := &structs.SyncCommitteeRewardsResponse{}
require.NoError(t, json.Unmarshal(writer.Body.Bytes(), resp))
require.Equal(t, 2, len(resp.Data))
sum := uint64(0)
@@ -764,7 +765,7 @@ func TestSyncCommiteeRewards(t *testing.T) {
s.SyncCommitteeRewards(writer, request)
assert.Equal(t, http.StatusOK, writer.Code)
resp := &SyncCommitteeRewardsResponse{}
resp := &structs.SyncCommitteeRewardsResponse{}
require.NoError(t, json.Unmarshal(writer.Body.Bytes(), resp))
require.Equal(t, 512, len(resp.Data))
sum := 0
@@ -795,7 +796,7 @@ func TestSyncCommiteeRewards(t *testing.T) {
s.SyncCommitteeRewards(writer, request)
assert.Equal(t, http.StatusOK, writer.Code)
resp := &SyncCommitteeRewardsResponse{}
resp := &structs.SyncCommitteeRewardsResponse{}
require.NoError(t, json.Unmarshal(writer.Body.Bytes(), resp))
require.Equal(t, 2, len(resp.Data))
sum := 0
@@ -826,7 +827,7 @@ func TestSyncCommiteeRewards(t *testing.T) {
s.SyncCommitteeRewards(writer, request)
assert.Equal(t, http.StatusOK, writer.Code)
resp := &SyncCommitteeRewardsResponse{}
resp := &structs.SyncCommitteeRewardsResponse{}
require.NoError(t, json.Unmarshal(writer.Body.Bytes(), resp))
require.Equal(t, 3, len(resp.Data))
sum := 0

View File

@@ -5,6 +5,7 @@ import (
"net/http"
"strconv"
"github.com/prysmaticlabs/prysm/v4/api/server/structs"
"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"
@@ -17,7 +18,7 @@ import (
// BlockRewardsFetcher is a interface that provides access to reward related responses
type BlockRewardsFetcher interface {
GetBlockRewardsData(context.Context, interfaces.ReadOnlyBeaconBlock) (*BlockRewards, *httputil.DefaultJsonError)
GetBlockRewardsData(context.Context, interfaces.ReadOnlyBeaconBlock) (*structs.BlockRewards, *httputil.DefaultJsonError)
GetStateForRewards(context.Context, interfaces.ReadOnlyBeaconBlock) (state.BeaconState, *httputil.DefaultJsonError)
}
@@ -26,8 +27,9 @@ type BlockRewardService struct {
Replayer stategen.ReplayerBuilder
}
// GetBlockRewardsData returns the BlockRewards Object which is used for the BlockRewardsResponse and ProduceBlockV3
func (rs *BlockRewardService) GetBlockRewardsData(ctx context.Context, blk interfaces.ReadOnlyBeaconBlock) (*BlockRewards, *httputil.DefaultJsonError) {
// GetBlockRewardsData returns the BlockRewards object which is used for the BlockRewardsResponse and ProduceBlockV3.
// Rewards are denominated in Gwei.
func (rs *BlockRewardService) GetBlockRewardsData(ctx context.Context, blk interfaces.ReadOnlyBeaconBlock) (*structs.BlockRewards, *httputil.DefaultJsonError) {
if blk == nil || blk.IsNil() {
return nil, &httputil.DefaultJsonError{
Message: consensusblocks.ErrNilBeaconBlock.Error(),
@@ -106,7 +108,7 @@ func (rs *BlockRewardService) GetBlockRewardsData(ctx context.Context, blk inter
}
}
return &BlockRewards{
return &structs.BlockRewards{
ProposerIndex: strconv.FormatUint(uint64(proposerIndex), 10),
Total: strconv.FormatUint(proposerSlashingsBalance-initBalance+syncCommitteeReward, 10),
Attestations: strconv.FormatUint(attBalance-initBalance, 10),

View File

@@ -6,7 +6,7 @@ go_library(
importpath = "github.com/prysmaticlabs/prysm/v4/beacon-chain/rpc/eth/rewards/testing",
visibility = ["//visibility:public"],
deps = [
"//beacon-chain/rpc/eth/rewards:go_default_library",
"//api/server/structs:go_default_library",
"//beacon-chain/state:go_default_library",
"//consensus-types/interfaces:go_default_library",
"//network/httputil:go_default_library",

View File

@@ -3,19 +3,19 @@ package testing
import (
"context"
"github.com/prysmaticlabs/prysm/v4/beacon-chain/rpc/eth/rewards"
"github.com/prysmaticlabs/prysm/v4/api/server/structs"
"github.com/prysmaticlabs/prysm/v4/beacon-chain/state"
"github.com/prysmaticlabs/prysm/v4/consensus-types/interfaces"
"github.com/prysmaticlabs/prysm/v4/network/httputil"
)
type MockBlockRewardFetcher struct {
Rewards *rewards.BlockRewards
Rewards *structs.BlockRewards
Error *httputil.DefaultJsonError
State state.BeaconState
}
func (m *MockBlockRewardFetcher) GetBlockRewardsData(_ context.Context, _ interfaces.ReadOnlyBeaconBlock) (*rewards.BlockRewards, *httputil.DefaultJsonError) {
func (m *MockBlockRewardFetcher) GetBlockRewardsData(_ context.Context, _ interfaces.ReadOnlyBeaconBlock) (*structs.BlockRewards, *httputil.DefaultJsonError) {
if m.Error != nil {
return nil, m.Error
}

View File

@@ -3,38 +3,21 @@ load("@prysm//tools/go:def.bzl", "go_library", "go_test")
go_library(
name = "go_default_library",
srcs = [
"conversions.go",
"conversions_block.go",
"conversions_state.go",
"errors.go",
"request.go",
"structs.go",
"structs_block.go",
"structs_state.go",
],
importpath = "github.com/prysmaticlabs/prysm/v4/beacon-chain/rpc/eth/shared",
visibility = ["//visibility:public"],
deps = [
"//api/server:go_default_library",
"//api/server/structs:go_default_library",
"//beacon-chain/blockchain:go_default_library",
"//beacon-chain/rpc/lookup:go_default_library",
"//beacon-chain/state:go_default_library",
"//beacon-chain/sync:go_default_library",
"//config/fieldparams:go_default_library",
"//consensus-types/blocks:go_default_library",
"//consensus-types/interfaces:go_default_library",
"//consensus-types/primitives:go_default_library",
"//consensus-types/validator:go_default_library",
"//container/slice:go_default_library",
"//encoding/bytesutil:go_default_library",
"//math:go_default_library",
"//network/httputil:go_default_library",
"//proto/engine/v1:go_default_library",
"//proto/prysm/v1alpha1: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_pkg_errors//:go_default_library",
],
)

View File

@@ -10,6 +10,7 @@ import (
"github.com/ethereum/go-ethereum/common/hexutil"
"github.com/gorilla/mux"
"github.com/prysmaticlabs/prysm/v4/api/server/structs"
"github.com/prysmaticlabs/prysm/v4/beacon-chain/blockchain"
"github.com/prysmaticlabs/prysm/v4/beacon-chain/sync"
"github.com/prysmaticlabs/prysm/v4/network/httputil"
@@ -126,8 +127,8 @@ func IsSyncing(
httputil.WriteError(w, errJson)
return true
}
syncDetails := &SyncDetailsContainer{
Data: &SyncDetails{
syncDetails := &structs.SyncDetailsContainer{
Data: &structs.SyncDetails{
HeadSlot: strconv.FormatUint(uint64(headSlot), 10),
SyncDistance: strconv.FormatUint(uint64(timeFetcher.CurrentSlot()-headSlot), 10),
IsSyncing: true,

View File

@@ -6,12 +6,12 @@ go_library(
"handlers.go",
"handlers_block.go",
"server.go",
"structs.go",
],
importpath = "github.com/prysmaticlabs/prysm/v4/beacon-chain/rpc/eth/validator",
visibility = ["//visibility:public"],
deps = [
"//api:go_default_library",
"//api/server/structs:go_default_library",
"//beacon-chain/blockchain:go_default_library",
"//beacon-chain/builder:go_default_library",
"//beacon-chain/cache:go_default_library",
@@ -59,6 +59,7 @@ go_test(
embed = [":go_default_library"],
deps = [
"//api:go_default_library",
"//api/server/structs:go_default_library",
"//beacon-chain/blockchain/testing:go_default_library",
"//beacon-chain/builder/testing:go_default_library",
"//beacon-chain/cache:go_default_library",
@@ -70,9 +71,7 @@ go_test(
"//beacon-chain/operations/synccommittee:go_default_library",
"//beacon-chain/p2p/testing:go_default_library",
"//beacon-chain/rpc/core:go_default_library",
"//beacon-chain/rpc/eth/rewards:go_default_library",
"//beacon-chain/rpc/eth/rewards/testing:go_default_library",
"//beacon-chain/rpc/eth/shared:go_default_library",
"//beacon-chain/rpc/eth/shared/testing:go_default_library",
"//beacon-chain/rpc/testutil:go_default_library",
"//beacon-chain/state:go_default_library",

View File

@@ -13,6 +13,7 @@ import (
"github.com/ethereum/go-ethereum/common/hexutil"
"github.com/pkg/errors"
"github.com/prysmaticlabs/prysm/v4/api/server/structs"
"github.com/prysmaticlabs/prysm/v4/beacon-chain/builder"
"github.com/prysmaticlabs/prysm/v4/beacon-chain/cache"
"github.com/prysmaticlabs/prysm/v4/beacon-chain/core/helpers"
@@ -76,18 +77,18 @@ func (s *Server) GetAggregateAttestation(w http.ResponseWriter, r *http.Request)
return
}
response := &AggregateAttestationResponse{
Data: &shared.Attestation{
response := &structs.AggregateAttestationResponse{
Data: &structs.Attestation{
AggregationBits: hexutil.Encode(match.AggregationBits),
Data: &shared.AttestationData{
Data: &structs.AttestationData{
Slot: strconv.FormatUint(uint64(match.Data.Slot), 10),
CommitteeIndex: strconv.FormatUint(uint64(match.Data.CommitteeIndex), 10),
BeaconBlockRoot: hexutil.Encode(match.Data.BeaconBlockRoot),
Source: &shared.Checkpoint{
Source: &structs.Checkpoint{
Epoch: strconv.FormatUint(uint64(match.Data.Source.Epoch), 10),
Root: hexutil.Encode(match.Data.Source.Root),
},
Target: &shared.Checkpoint{
Target: &structs.Checkpoint{
Epoch: strconv.FormatUint(uint64(match.Data.Target.Epoch), 10),
Root: hexutil.Encode(match.Data.Target.Root),
},
@@ -117,7 +118,7 @@ func (s *Server) SubmitContributionAndProofs(w http.ResponseWriter, r *http.Requ
ctx, span := trace.StartSpan(r.Context(), "validator.SubmitContributionAndProofs")
defer span.End()
var req SubmitContributionAndProofsRequest
var req structs.SubmitContributionAndProofsRequest
err := json.NewDecoder(r.Body).Decode(&req.Data)
switch {
case err == io.EOF:
@@ -150,7 +151,7 @@ func (s *Server) SubmitAggregateAndProofs(w http.ResponseWriter, r *http.Request
ctx, span := trace.StartSpan(r.Context(), "validator.SubmitAggregateAndProofs")
defer span.End()
var req SubmitAggregateAndProofsRequest
var req structs.SubmitAggregateAndProofsRequest
err := json.NewDecoder(r.Body).Decode(&req.Data)
switch {
case err == io.EOF:
@@ -205,7 +206,7 @@ func (s *Server) SubmitSyncCommitteeSubscription(w http.ResponseWriter, r *http.
return
}
var req SubmitSyncCommitteeSubscriptionsRequest
var req structs.SubmitSyncCommitteeSubscriptionsRequest
err := json.NewDecoder(r.Body).Decode(&req.Data)
switch {
case err == io.EOF:
@@ -315,7 +316,7 @@ func (s *Server) SubmitBeaconCommitteeSubscription(w http.ResponseWriter, r *htt
return
}
var req SubmitBeaconCommitteeSubscriptionsRequest
var req structs.SubmitBeaconCommitteeSubscriptionsRequest
err := json.NewDecoder(r.Body).Decode(&req.Data)
switch {
case err == io.EOF:
@@ -421,16 +422,16 @@ func (s *Server) GetAttestationData(w http.ResponseWriter, r *http.Request) {
return
}
response := &GetAttestationDataResponse{
Data: &shared.AttestationData{
response := &structs.GetAttestationDataResponse{
Data: &structs.AttestationData{
Slot: strconv.FormatUint(uint64(attestationData.Slot), 10),
CommitteeIndex: strconv.FormatUint(uint64(attestationData.CommitteeIndex), 10),
BeaconBlockRoot: hexutil.Encode(attestationData.BeaconBlockRoot),
Source: &shared.Checkpoint{
Source: &structs.Checkpoint{
Epoch: strconv.FormatUint(uint64(attestationData.Source.Epoch), 10),
Root: hexutil.Encode(attestationData.Source.Root),
},
Target: &shared.Checkpoint{
Target: &structs.Checkpoint{
Epoch: strconv.FormatUint(uint64(attestationData.Target.Epoch), 10),
Root: hexutil.Encode(attestationData.Target.Root),
},
@@ -462,7 +463,7 @@ func (s *Server) ProduceSyncCommitteeContribution(w http.ResponseWriter, r *http
if !ok {
return
}
response := &ProduceSyncCommitteeContributionResponse{
response := &structs.ProduceSyncCommitteeContributionResponse{
Data: contribution,
}
httputil.WriteJson(w, response)
@@ -475,7 +476,7 @@ func (s *Server) produceSyncCommitteeContribution(
slot primitives.Slot,
index uint64,
blockRoot []byte,
) (*shared.SyncCommitteeContribution, bool) {
) (*structs.SyncCommitteeContribution, bool) {
msgs, err := s.SyncCommitteePool.SyncCommitteeMessages(slot)
if err != nil {
httputil.HandleError(w, "Could not get sync subcommittee messages: "+err.Error(), http.StatusInternalServerError)
@@ -499,7 +500,7 @@ func (s *Server) produceSyncCommitteeContribution(
return nil, false
}
return &shared.SyncCommitteeContribution{
return &structs.SyncCommitteeContribution{
Slot: strconv.FormatUint(uint64(slot), 10),
BeaconBlockRoot: hexutil.Encode(blockRoot),
SubcommitteeIndex: strconv.FormatUint(index, 10),
@@ -518,7 +519,7 @@ func (s *Server) RegisterValidator(w http.ResponseWriter, r *http.Request) {
return
}
var jsonRegistrations []*shared.SignedValidatorRegistration
var jsonRegistrations []*structs.SignedValidatorRegistration
err := json.NewDecoder(r.Body).Decode(&jsonRegistrations)
switch {
case err == io.EOF:
@@ -551,7 +552,7 @@ func (s *Server) RegisterValidator(w http.ResponseWriter, r *http.Request) {
// PrepareBeaconProposer endpoint saves the fee recipient given a validator index, this is used when proposing a block.
func (s *Server) PrepareBeaconProposer(w http.ResponseWriter, r *http.Request) {
var jsonFeeRecipients []*shared.FeeRecipient
var jsonFeeRecipients []*structs.FeeRecipient
err := json.NewDecoder(r.Body).Decode(&jsonFeeRecipients)
switch {
case err == io.EOF:
@@ -675,7 +676,7 @@ func (s *Server) GetAttesterDuties(w http.ResponseWriter, r *http.Request) {
}
committeesAtSlot := helpers.SlotCommitteeCount(activeValidatorCount)
duties := make([]*AttesterDuty, 0, len(requestedValIndices))
duties := make([]*structs.AttesterDuty, 0, len(requestedValIndices))
for _, index := range requestedValIndices {
pubkey := st.PubkeyAtIndex(index)
var zeroPubkey [fieldparams.BLSPubkeyLength]byte
@@ -696,7 +697,7 @@ func (s *Server) GetAttesterDuties(w http.ResponseWriter, r *http.Request) {
break
}
}
duties = append(duties, &AttesterDuty{
duties = append(duties, &structs.AttesterDuty{
Pubkey: hexutil.Encode(pubkey[:]),
ValidatorIndex: strconv.FormatUint(uint64(index), 10),
CommitteeIndex: strconv.FormatUint(uint64(committee.CommitteeIndex), 10),
@@ -718,7 +719,7 @@ func (s *Server) GetAttesterDuties(w http.ResponseWriter, r *http.Request) {
return
}
response := &GetAttesterDutiesResponse{
response := &structs.GetAttesterDutiesResponse{
DependentRoot: hexutil.Encode(dependentRoot),
Data: duties,
ExecutionOptimistic: isOptimistic,
@@ -803,7 +804,7 @@ func (s *Server) GetProposerDuties(w http.ResponseWriter, r *http.Request) {
return
}
duties := make([]*ProposerDuty, 0)
duties := make([]*structs.ProposerDuty, 0)
for index, proposalSlots := range proposals {
val, err := st.ValidatorAtIndexReadOnly(index)
if err != nil {
@@ -813,7 +814,7 @@ func (s *Server) GetProposerDuties(w http.ResponseWriter, r *http.Request) {
pubkey48 := val.PublicKey()
pubkey := pubkey48[:]
for _, slot := range proposalSlots {
duties = append(duties, &ProposerDuty{
duties = append(duties, &structs.ProposerDuty{
Pubkey: hexutil.Encode(pubkey),
ValidatorIndex: strconv.FormatUint(uint64(index), 10),
Slot: strconv.FormatUint(uint64(slot), 10),
@@ -835,7 +836,7 @@ func (s *Server) GetProposerDuties(w http.ResponseWriter, r *http.Request) {
return
}
resp := &GetProposerDutiesResponse{
resp := &structs.GetProposerDutiesResponse{
DependentRoot: hexutil.Encode(dependentRoot),
Data: duties,
ExecutionOptimistic: isOptimistic,
@@ -973,7 +974,7 @@ func (s *Server) GetSyncCommitteeDuties(w http.ResponseWriter, r *http.Request)
return
}
resp := &GetSyncCommitteeDutiesResponse{
resp := &structs.GetSyncCommitteeDutiesResponse{
Data: duties,
ExecutionOptimistic: isOptimistic,
}
@@ -1068,15 +1069,15 @@ func (s *Server) GetLiveness(w http.ResponseWriter, r *http.Request) {
}
}
resp := &GetLivenessResponse{
Data: make([]*Liveness, len(requestedValIndices)),
resp := &structs.GetLivenessResponse{
Data: make([]*structs.Liveness, len(requestedValIndices)),
}
for i, vi := range requestedValIndices {
if vi >= primitives.ValidatorIndex(len(participation)) {
httputil.HandleError(w, fmt.Sprintf("Validator index %d is invalid", vi), http.StatusBadRequest)
return
}
resp.Data[i] = &Liveness{
resp.Data[i] = &structs.Liveness{
Index: strconv.FormatUint(uint64(vi), 10),
IsLive: participation[vi] != 0,
}
@@ -1085,6 +1086,12 @@ func (s *Server) GetLiveness(w http.ResponseWriter, r *http.Request) {
httputil.WriteJson(w, resp)
}
// BeaconCommitteeSelections responds with appropriate message and status code according the spec:
// https://ethereum.github.io/beacon-APIs/#/Validator/submitBeaconCommitteeSelections.
func (s *Server) BeaconCommitteeSelections(w http.ResponseWriter, _ *http.Request) {
httputil.HandleError(w, "Endpoint not implemented", 501)
}
// attestationDependentRoot is get_block_root_at_slot(state, compute_start_slot_at_epoch(epoch - 1) - 1)
// or the genesis block root in the case of underflow.
func attestationDependentRoot(s state.BeaconState, epoch primitives.Epoch) ([]byte, error) {
@@ -1139,11 +1146,11 @@ func syncCommitteeDutiesAndVals(
st state.BeaconState,
requestedValIndices []primitives.ValidatorIndex,
committeePubkeys map[[fieldparams.BLSPubkeyLength]byte][]string,
) ([]*SyncCommitteeDuty, []state.ReadOnlyValidator, error) {
duties := make([]*SyncCommitteeDuty, 0)
) ([]*structs.SyncCommitteeDuty, []state.ReadOnlyValidator, error) {
duties := make([]*structs.SyncCommitteeDuty, 0)
vals := make([]state.ReadOnlyValidator, 0)
for _, index := range requestedValIndices {
duty := &SyncCommitteeDuty{
duty := &structs.SyncCommitteeDuty{
ValidatorIndex: strconv.FormatUint(uint64(index), 10),
}
valPubkey := st.PubkeyAtIndex(index)
@@ -1166,7 +1173,7 @@ func syncCommitteeDutiesAndVals(
return duties, vals, nil
}
func sortProposerDuties(w http.ResponseWriter, duties []*ProposerDuty) bool {
func sortProposerDuties(w http.ResponseWriter, duties []*structs.ProposerDuty) bool {
ok := true
sort.Slice(duties, func(i, j int) bool {
si, err := strconv.ParseUint(duties[i].Slot, 10, 64)

View File

@@ -4,11 +4,13 @@ import (
"context"
"encoding/json"
"fmt"
"math/big"
"net/http"
"strings"
"github.com/pkg/errors"
"github.com/prysmaticlabs/prysm/v4/api"
"github.com/prysmaticlabs/prysm/v4/api/server/structs"
"github.com/prysmaticlabs/prysm/v4/beacon-chain/rpc/eth/rewards"
"github.com/prysmaticlabs/prysm/v4/beacon-chain/rpc/eth/shared"
fieldparams "github.com/prysmaticlabs/prysm/v4/config/fieldparams"
@@ -298,12 +300,21 @@ func getConsensusBlockValue(ctx context.Context, blockRewardsFetcher rewards.Blo
// ignore for phase 0
return "", nil
}
//get consensus payload value which is the same as the total from the block rewards api
// Get consensus payload value which is the same as the total from the block rewards api.
// The value is in Gwei, but Wei should be returned from the endpoint.
blockRewards, httpError := blockRewardsFetcher.GetBlockRewardsData(ctx, bb)
if httpError != nil {
return "", httpError
}
return blockRewards.Total, nil
gwei, ok := big.NewInt(0).SetString(blockRewards.Total, 10)
if !ok {
return "", &httputil.DefaultJsonError{
Message: "Could not parse consensus block value",
Code: http.StatusInternalServerError,
}
}
wei := gwei.Mul(gwei, big.NewInt(1e9))
return wei.String(), nil
}
func handleProducePhase0V3(
@@ -321,12 +332,12 @@ func handleProducePhase0V3(
httputil.WriteSsz(w, sszResp, "phase0Block.ssz")
return
}
jsonBytes, err := json.Marshal(shared.BeaconBlockFromConsensus(blk.Phase0))
jsonBytes, err := json.Marshal(structs.BeaconBlockFromConsensus(blk.Phase0))
if err != nil {
httputil.HandleError(w, err.Error(), http.StatusInternalServerError)
return
}
httputil.WriteJson(w, &ProduceBlockV3Response{
httputil.WriteJson(w, &structs.ProduceBlockV3Response{
Version: version.String(version.Phase0),
ExecutionPayloadBlinded: false,
ExecutionPayloadValue: payloadValue, // mev not available at this point
@@ -351,12 +362,12 @@ func handleProduceAltairV3(
httputil.WriteSsz(w, sszResp, "altairBlock.ssz")
return
}
jsonBytes, err := json.Marshal(shared.BeaconBlockAltairFromConsensus(blk.Altair))
jsonBytes, err := json.Marshal(structs.BeaconBlockAltairFromConsensus(blk.Altair))
if err != nil {
httputil.HandleError(w, err.Error(), http.StatusInternalServerError)
return
}
httputil.WriteJson(w, &ProduceBlockV3Response{
httputil.WriteJson(w, &structs.ProduceBlockV3Response{
Version: version.String(version.Altair),
ExecutionPayloadBlinded: false,
ExecutionPayloadValue: executionPayloadValue, // mev not available at this point
@@ -381,7 +392,7 @@ func handleProduceBellatrixV3(
httputil.WriteSsz(w, sszResp, "bellatrixBlock.ssz")
return
}
block, err := shared.BeaconBlockBellatrixFromConsensus(blk.Bellatrix)
block, err := structs.BeaconBlockBellatrixFromConsensus(blk.Bellatrix)
if err != nil {
httputil.HandleError(w, err.Error(), http.StatusInternalServerError)
return
@@ -391,7 +402,7 @@ func handleProduceBellatrixV3(
httputil.HandleError(w, err.Error(), http.StatusInternalServerError)
return
}
httputil.WriteJson(w, &ProduceBlockV3Response{
httputil.WriteJson(w, &structs.ProduceBlockV3Response{
Version: version.String(version.Bellatrix),
ExecutionPayloadBlinded: false,
ExecutionPayloadValue: executionPayloadValue, // mev not available at this point
@@ -416,7 +427,7 @@ func handleProduceBlindedBellatrixV3(
httputil.WriteSsz(w, sszResp, "blindedBellatrixBlock.ssz")
return
}
block, err := shared.BlindedBeaconBlockBellatrixFromConsensus(blk.BlindedBellatrix)
block, err := structs.BlindedBeaconBlockBellatrixFromConsensus(blk.BlindedBellatrix)
if err != nil {
httputil.HandleError(w, err.Error(), http.StatusInternalServerError)
return
@@ -426,7 +437,7 @@ func handleProduceBlindedBellatrixV3(
httputil.HandleError(w, err.Error(), http.StatusInternalServerError)
return
}
httputil.WriteJson(w, &ProduceBlockV3Response{
httputil.WriteJson(w, &structs.ProduceBlockV3Response{
Version: version.String(version.Bellatrix),
ExecutionPayloadBlinded: true,
ExecutionPayloadValue: executionPayloadValue,
@@ -451,7 +462,7 @@ func handleProduceBlindedCapellaV3(
httputil.WriteSsz(w, sszResp, "blindedCapellaBlock.ssz")
return
}
block, err := shared.BlindedBeaconBlockCapellaFromConsensus(blk.BlindedCapella)
block, err := structs.BlindedBeaconBlockCapellaFromConsensus(blk.BlindedCapella)
if err != nil {
httputil.HandleError(w, err.Error(), http.StatusInternalServerError)
return
@@ -461,7 +472,7 @@ func handleProduceBlindedCapellaV3(
httputil.HandleError(w, err.Error(), http.StatusInternalServerError)
return
}
httputil.WriteJson(w, &ProduceBlockV3Response{
httputil.WriteJson(w, &structs.ProduceBlockV3Response{
Version: version.String(version.Capella),
ExecutionPayloadBlinded: true,
ExecutionPayloadValue: executionPayloadValue,
@@ -486,7 +497,7 @@ func handleProduceCapellaV3(
httputil.WriteSsz(w, sszResp, "capellaBlock.ssz")
return
}
block, err := shared.BeaconBlockCapellaFromConsensus(blk.Capella)
block, err := structs.BeaconBlockCapellaFromConsensus(blk.Capella)
if err != nil {
httputil.HandleError(w, err.Error(), http.StatusInternalServerError)
return
@@ -496,7 +507,7 @@ func handleProduceCapellaV3(
httputil.HandleError(w, err.Error(), http.StatusInternalServerError)
return
}
httputil.WriteJson(w, &ProduceBlockV3Response{
httputil.WriteJson(w, &structs.ProduceBlockV3Response{
Version: version.String(version.Capella),
ExecutionPayloadBlinded: false,
ExecutionPayloadValue: executionPayloadValue, // mev not available at this point
@@ -521,7 +532,7 @@ func handleProduceBlindedDenebV3(
httputil.WriteSsz(w, sszResp, "blindedDenebBlockContents.ssz")
return
}
blindedBlock, err := shared.BlindedBeaconBlockDenebFromConsensus(blk.BlindedDeneb)
blindedBlock, err := structs.BlindedBeaconBlockDenebFromConsensus(blk.BlindedDeneb)
if err != nil {
httputil.HandleError(w, err.Error(), http.StatusInternalServerError)
return
@@ -531,7 +542,7 @@ func handleProduceBlindedDenebV3(
httputil.HandleError(w, err.Error(), http.StatusInternalServerError)
return
}
httputil.WriteJson(w, &ProduceBlockV3Response{
httputil.WriteJson(w, &structs.ProduceBlockV3Response{
Version: version.String(version.Deneb),
ExecutionPayloadBlinded: true,
ExecutionPayloadValue: executionPayloadValue,
@@ -557,7 +568,7 @@ func handleProduceDenebV3(
return
}
blockContents, err := shared.BeaconBlockContentsDenebFromConsensus(blk.Deneb)
blockContents, err := structs.BeaconBlockContentsDenebFromConsensus(blk.Deneb)
if err != nil {
httputil.HandleError(w, err.Error(), http.StatusInternalServerError)
return
@@ -567,7 +578,7 @@ func handleProduceDenebV3(
httputil.HandleError(w, err.Error(), http.StatusInternalServerError)
return
}
httputil.WriteJson(w, &ProduceBlockV3Response{
httputil.WriteJson(w, &structs.ProduceBlockV3Response{
Version: version.String(version.Deneb),
ExecutionPayloadBlinded: false,
ExecutionPayloadValue: executionPayloadValue, // mev not available at this point

View File

@@ -12,10 +12,9 @@ import (
"github.com/ethereum/go-ethereum/common/hexutil"
"github.com/golang/mock/gomock"
"github.com/prysmaticlabs/prysm/v4/api"
"github.com/prysmaticlabs/prysm/v4/api/server/structs"
blockchainTesting "github.com/prysmaticlabs/prysm/v4/beacon-chain/blockchain/testing"
"github.com/prysmaticlabs/prysm/v4/beacon-chain/rpc/eth/rewards"
rewardtesting "github.com/prysmaticlabs/prysm/v4/beacon-chain/rpc/eth/rewards/testing"
"github.com/prysmaticlabs/prysm/v4/beacon-chain/rpc/eth/shared"
rpctesting "github.com/prysmaticlabs/prysm/v4/beacon-chain/rpc/eth/shared/testing"
mockSync "github.com/prysmaticlabs/prysm/v4/beacon-chain/sync/initial-sync/testing"
"github.com/prysmaticlabs/prysm/v4/network/httputil"
@@ -35,10 +34,10 @@ func TestProduceBlockV2(t *testing.T) {
require.NoError(t, err)
chainService := &blockchainTesting.ChainService{}
syncChecker := &mockSync.Sync{IsSyncing: false}
rewardFetcher := &rewardtesting.MockBlockRewardFetcher{Rewards: &rewards.BlockRewards{Total: "10"}}
rewardFetcher := &rewardtesting.MockBlockRewardFetcher{Rewards: &structs.BlockRewards{Total: "10"}}
t.Run("Phase 0", func(t *testing.T) {
var block *shared.SignedBeaconBlock
var block *structs.SignedBeaconBlock
err = json.Unmarshal([]byte(rpctesting.Phase0Block), &block)
require.NoError(t, err)
jsonBytes, err := json.Marshal(block.Message)
@@ -70,7 +69,7 @@ func TestProduceBlockV2(t *testing.T) {
require.Equal(t, "phase0", writer.Header().Get(api.VersionHeader))
})
t.Run("Altair", func(t *testing.T) {
var block *shared.SignedBeaconBlockAltair
var block *structs.SignedBeaconBlockAltair
err = json.Unmarshal([]byte(rpctesting.AltairBlock), &block)
require.NoError(t, err)
jsonBytes, err := json.Marshal(block.Message)
@@ -97,13 +96,13 @@ func TestProduceBlockV2(t *testing.T) {
writer.Body = &bytes.Buffer{}
server.ProduceBlockV2(writer, request)
assert.Equal(t, http.StatusOK, writer.Code)
want := fmt.Sprintf(`{"version":"altair","execution_payload_blinded":false,"execution_payload_value":"","consensus_block_value":"10","data":%s}`, string(jsonBytes))
want := fmt.Sprintf(`{"version":"altair","execution_payload_blinded":false,"execution_payload_value":"","consensus_block_value":"10000000000","data":%s}`, string(jsonBytes))
body := strings.ReplaceAll(writer.Body.String(), "\n", "")
require.Equal(t, want, body)
require.Equal(t, "altair", writer.Header().Get(api.VersionHeader))
})
t.Run("Bellatrix", func(t *testing.T) {
var block *shared.SignedBeaconBlockBellatrix
var block *structs.SignedBeaconBlockBellatrix
err = json.Unmarshal([]byte(rpctesting.BellatrixBlock), &block)
require.NoError(t, err)
jsonBytes, err := json.Marshal(block.Message)
@@ -134,13 +133,13 @@ func TestProduceBlockV2(t *testing.T) {
writer.Body = &bytes.Buffer{}
server.ProduceBlockV2(writer, request)
assert.Equal(t, http.StatusOK, writer.Code)
want := fmt.Sprintf(`{"version":"bellatrix","execution_payload_blinded":false,"execution_payload_value":"2000","consensus_block_value":"10","data":%s}`, string(jsonBytes))
want := fmt.Sprintf(`{"version":"bellatrix","execution_payload_blinded":false,"execution_payload_value":"2000","consensus_block_value":"10000000000","data":%s}`, string(jsonBytes))
body := strings.ReplaceAll(writer.Body.String(), "\n", "")
require.Equal(t, want, body)
require.Equal(t, "bellatrix", writer.Header().Get(api.VersionHeader))
})
t.Run("BlindedBellatrix", func(t *testing.T) {
var block *shared.SignedBlindedBeaconBlockBellatrix
var block *structs.SignedBlindedBeaconBlockBellatrix
err = json.Unmarshal([]byte(rpctesting.BlindedBellatrixBlock), &block)
require.NoError(t, err)
@@ -172,7 +171,7 @@ func TestProduceBlockV2(t *testing.T) {
assert.StringContains(t, "Prepared block is blinded", e.Message)
})
t.Run("Capella", func(t *testing.T) {
var block *shared.SignedBeaconBlockCapella
var block *structs.SignedBeaconBlockCapella
err = json.Unmarshal([]byte(rpctesting.CapellaBlock), &block)
require.NoError(t, err)
jsonBytes, err := json.Marshal(block.Message)
@@ -203,13 +202,13 @@ func TestProduceBlockV2(t *testing.T) {
writer.Body = &bytes.Buffer{}
server.ProduceBlockV2(writer, request)
assert.Equal(t, http.StatusOK, writer.Code)
want := fmt.Sprintf(`{"version":"capella","execution_payload_blinded":false,"execution_payload_value":"2000","consensus_block_value":"10","data":%s}`, string(jsonBytes))
want := fmt.Sprintf(`{"version":"capella","execution_payload_blinded":false,"execution_payload_value":"2000","consensus_block_value":"10000000000","data":%s}`, string(jsonBytes))
body := strings.ReplaceAll(writer.Body.String(), "\n", "")
require.Equal(t, want, body)
require.Equal(t, "capella", writer.Header().Get(api.VersionHeader))
})
t.Run("Blinded Capella", func(t *testing.T) {
var block *shared.SignedBlindedBeaconBlockCapella
var block *structs.SignedBlindedBeaconBlockCapella
err = json.Unmarshal([]byte(rpctesting.BlindedCapellaBlock), &block)
require.NoError(t, err)
@@ -241,7 +240,7 @@ func TestProduceBlockV2(t *testing.T) {
assert.StringContains(t, "Prepared block is blinded", e.Message)
})
t.Run("Deneb", func(t *testing.T) {
var block *shared.SignedBeaconBlockContentsDeneb
var block *structs.SignedBeaconBlockContentsDeneb
err = json.Unmarshal([]byte(rpctesting.DenebBlockContents), &block)
require.NoError(t, err)
jsonBytes, err := json.Marshal(block.ToUnsigned())
@@ -272,13 +271,13 @@ func TestProduceBlockV2(t *testing.T) {
writer.Body = &bytes.Buffer{}
server.ProduceBlockV2(writer, request)
assert.Equal(t, http.StatusOK, writer.Code)
want := fmt.Sprintf(`{"version":"deneb","execution_payload_blinded":false,"execution_payload_value":"2000","consensus_block_value":"10","data":%s}`, string(jsonBytes))
want := fmt.Sprintf(`{"version":"deneb","execution_payload_blinded":false,"execution_payload_value":"2000","consensus_block_value":"10000000000","data":%s}`, string(jsonBytes))
body := strings.ReplaceAll(writer.Body.String(), "\n", "")
require.Equal(t, want, body)
require.Equal(t, "deneb", writer.Header().Get(api.VersionHeader))
})
t.Run("Blinded Deneb", func(t *testing.T) {
var block *shared.SignedBlindedBeaconBlockDeneb
var block *structs.SignedBlindedBeaconBlockDeneb
err = json.Unmarshal([]byte(rpctesting.BlindedDenebBlock), &block)
require.NoError(t, err)
@@ -375,10 +374,10 @@ func TestProduceBlockV2SSZ(t *testing.T) {
require.NoError(t, err)
chainService := &blockchainTesting.ChainService{}
syncChecker := &mockSync.Sync{IsSyncing: false}
rewardFetcher := &rewardtesting.MockBlockRewardFetcher{Rewards: &rewards.BlockRewards{Total: "10"}}
rewardFetcher := &rewardtesting.MockBlockRewardFetcher{Rewards: &structs.BlockRewards{Total: "10"}}
t.Run("Phase 0", func(t *testing.T) {
var block *shared.SignedBeaconBlock
var block *structs.SignedBeaconBlock
err = json.Unmarshal([]byte(rpctesting.Phase0Block), &block)
require.NoError(t, err)
@@ -413,7 +412,7 @@ func TestProduceBlockV2SSZ(t *testing.T) {
require.Equal(t, "phase0", writer.Header().Get(api.VersionHeader))
})
t.Run("Altair", func(t *testing.T) {
var block *shared.SignedBeaconBlockAltair
var block *structs.SignedBeaconBlockAltair
err = json.Unmarshal([]byte(rpctesting.AltairBlock), &block)
require.NoError(t, err)
@@ -450,7 +449,7 @@ func TestProduceBlockV2SSZ(t *testing.T) {
require.Equal(t, "altair", writer.Header().Get(api.VersionHeader))
})
t.Run("Bellatrix", func(t *testing.T) {
var block *shared.SignedBeaconBlockBellatrix
var block *structs.SignedBeaconBlockBellatrix
err = json.Unmarshal([]byte(rpctesting.BellatrixBlock), &block)
require.NoError(t, err)
@@ -487,7 +486,7 @@ func TestProduceBlockV2SSZ(t *testing.T) {
require.Equal(t, "bellatrix", writer.Header().Get(api.VersionHeader))
})
t.Run("BlindedBellatrix", func(t *testing.T) {
var block *shared.SignedBlindedBeaconBlockBellatrix
var block *structs.SignedBlindedBeaconBlockBellatrix
err = json.Unmarshal([]byte(rpctesting.BlindedBellatrixBlock), &block)
require.NoError(t, err)
@@ -520,7 +519,7 @@ func TestProduceBlockV2SSZ(t *testing.T) {
assert.StringContains(t, "Prepared block is blinded", e.Message)
})
t.Run("Capella", func(t *testing.T) {
var block *shared.SignedBeaconBlockCapella
var block *structs.SignedBeaconBlockCapella
err = json.Unmarshal([]byte(rpctesting.CapellaBlock), &block)
require.NoError(t, err)
@@ -557,7 +556,7 @@ func TestProduceBlockV2SSZ(t *testing.T) {
require.Equal(t, "capella", writer.Header().Get(api.VersionHeader))
})
t.Run("Blinded Capella", func(t *testing.T) {
var block *shared.SignedBlindedBeaconBlockCapella
var block *structs.SignedBlindedBeaconBlockCapella
err = json.Unmarshal([]byte(rpctesting.BlindedCapellaBlock), &block)
require.NoError(t, err)
@@ -593,7 +592,7 @@ func TestProduceBlockV2SSZ(t *testing.T) {
assert.StringContains(t, "Prepared block is blinded", e.Message)
})
t.Run("Deneb", func(t *testing.T) {
var block *shared.SignedBeaconBlockContentsDeneb
var block *structs.SignedBeaconBlockContentsDeneb
err = json.Unmarshal([]byte(rpctesting.DenebBlockContents), &block)
require.NoError(t, err)
@@ -630,7 +629,7 @@ func TestProduceBlockV2SSZ(t *testing.T) {
require.Equal(t, "deneb", writer.Header().Get(api.VersionHeader))
})
t.Run("Blinded Deneb", func(t *testing.T) {
var block *shared.SignedBlindedBeaconBlockDeneb
var block *structs.SignedBlindedBeaconBlockDeneb
err = json.Unmarshal([]byte(rpctesting.BlindedDenebBlock), &block)
require.NoError(t, err)
@@ -674,10 +673,10 @@ func TestProduceBlindedBlock(t *testing.T) {
require.NoError(t, err)
chainService := &blockchainTesting.ChainService{}
syncChecker := &mockSync.Sync{IsSyncing: false}
rewardFetcher := &rewardtesting.MockBlockRewardFetcher{Rewards: &rewards.BlockRewards{Total: "10"}}
rewardFetcher := &rewardtesting.MockBlockRewardFetcher{Rewards: &structs.BlockRewards{Total: "10"}}
t.Run("Phase 0", func(t *testing.T) {
var block *shared.SignedBeaconBlock
var block *structs.SignedBeaconBlock
err = json.Unmarshal([]byte(rpctesting.Phase0Block), &block)
require.NoError(t, err)
@@ -707,7 +706,7 @@ func TestProduceBlindedBlock(t *testing.T) {
assert.StringContains(t, "Prepared block is not blinded", e.Message)
})
t.Run("Altair", func(t *testing.T) {
var block *shared.SignedBeaconBlockAltair
var block *structs.SignedBeaconBlockAltair
err = json.Unmarshal([]byte(rpctesting.AltairBlock), &block)
require.NoError(t, err)
@@ -739,7 +738,7 @@ func TestProduceBlindedBlock(t *testing.T) {
assert.StringContains(t, "Prepared block is not blinded", e.Message)
})
t.Run("Bellatrix", func(t *testing.T) {
var block *shared.SignedBeaconBlockBellatrix
var block *structs.SignedBeaconBlockBellatrix
err = json.Unmarshal([]byte(rpctesting.BellatrixBlock), &block)
require.NoError(t, err)
@@ -771,7 +770,7 @@ func TestProduceBlindedBlock(t *testing.T) {
assert.StringContains(t, "Prepared block is not blinded", e.Message)
})
t.Run("BlindedBellatrix", func(t *testing.T) {
var block *shared.SignedBlindedBeaconBlockBellatrix
var block *structs.SignedBlindedBeaconBlockBellatrix
err = json.Unmarshal([]byte(rpctesting.BlindedBellatrixBlock), &block)
require.NoError(t, err)
jsonBytes, err := json.Marshal(block.Message)
@@ -802,13 +801,13 @@ func TestProduceBlindedBlock(t *testing.T) {
writer.Body = &bytes.Buffer{}
server.ProduceBlindedBlock(writer, request)
assert.Equal(t, http.StatusOK, writer.Code)
want := fmt.Sprintf(`{"version":"bellatrix","execution_payload_blinded":true,"execution_payload_value":"2000","consensus_block_value":"10","data":%s}`, string(jsonBytes))
want := fmt.Sprintf(`{"version":"bellatrix","execution_payload_blinded":true,"execution_payload_value":"2000","consensus_block_value":"10000000000","data":%s}`, string(jsonBytes))
body := strings.ReplaceAll(writer.Body.String(), "\n", "")
require.Equal(t, want, body)
require.Equal(t, "bellatrix", writer.Header().Get(api.VersionHeader))
})
t.Run("Capella", func(t *testing.T) {
var block *shared.SignedBeaconBlockCapella
var block *structs.SignedBeaconBlockCapella
err = json.Unmarshal([]byte(rpctesting.CapellaBlock), &block)
require.NoError(t, err)
@@ -840,7 +839,7 @@ func TestProduceBlindedBlock(t *testing.T) {
assert.StringContains(t, "Prepared block is not blinded", e.Message)
})
t.Run("Blinded Capella", func(t *testing.T) {
var block *shared.SignedBlindedBeaconBlockCapella
var block *structs.SignedBlindedBeaconBlockCapella
err = json.Unmarshal([]byte(rpctesting.BlindedCapellaBlock), &block)
require.NoError(t, err)
jsonBytes, err := json.Marshal(block.Message)
@@ -871,13 +870,13 @@ func TestProduceBlindedBlock(t *testing.T) {
writer.Body = &bytes.Buffer{}
server.ProduceBlindedBlock(writer, request)
assert.Equal(t, http.StatusOK, writer.Code)
want := fmt.Sprintf(`{"version":"capella","execution_payload_blinded":true,"execution_payload_value":"2000","consensus_block_value":"10","data":%s}`, string(jsonBytes))
want := fmt.Sprintf(`{"version":"capella","execution_payload_blinded":true,"execution_payload_value":"2000","consensus_block_value":"10000000000","data":%s}`, string(jsonBytes))
body := strings.ReplaceAll(writer.Body.String(), "\n", "")
require.Equal(t, want, body)
require.Equal(t, "capella", writer.Header().Get(api.VersionHeader))
})
t.Run("Deneb", func(t *testing.T) {
var block *shared.SignedBeaconBlockContentsDeneb
var block *structs.SignedBeaconBlockContentsDeneb
err = json.Unmarshal([]byte(rpctesting.DenebBlockContents), &block)
require.NoError(t, err)
@@ -909,7 +908,7 @@ func TestProduceBlindedBlock(t *testing.T) {
assert.StringContains(t, "Prepared block is not blinded", e.Message)
})
t.Run("Blinded Deneb", func(t *testing.T) {
var block *shared.SignedBlindedBeaconBlockDeneb
var block *structs.SignedBlindedBeaconBlockDeneb
err = json.Unmarshal([]byte(rpctesting.BlindedDenebBlock), &block)
require.NoError(t, err)
jsonBytes, err := json.Marshal(block.Message)
@@ -940,7 +939,7 @@ func TestProduceBlindedBlock(t *testing.T) {
writer.Body = &bytes.Buffer{}
server.ProduceBlindedBlock(writer, request)
assert.Equal(t, http.StatusOK, writer.Code)
want := fmt.Sprintf(`{"version":"deneb","execution_payload_blinded":true,"execution_payload_value":"2000","consensus_block_value":"10","data":%s}`, string(jsonBytes))
want := fmt.Sprintf(`{"version":"deneb","execution_payload_blinded":true,"execution_payload_value":"2000","consensus_block_value":"10000000000","data":%s}`, string(jsonBytes))
body := strings.ReplaceAll(writer.Body.String(), "\n", "")
require.Equal(t, want, body)
require.Equal(t, "deneb", writer.Header().Get(api.VersionHeader))
@@ -1011,10 +1010,10 @@ func TestProduceBlockV3(t *testing.T) {
require.NoError(t, err)
chainService := &blockchainTesting.ChainService{}
syncChecker := &mockSync.Sync{IsSyncing: false}
rewardFetcher := &rewardtesting.MockBlockRewardFetcher{Rewards: &rewards.BlockRewards{Total: "10"}}
rewardFetcher := &rewardtesting.MockBlockRewardFetcher{Rewards: &structs.BlockRewards{Total: "10"}}
t.Run("Phase 0", func(t *testing.T) {
var block *shared.SignedBeaconBlock
var block *structs.SignedBeaconBlock
err := json.Unmarshal([]byte(rpctesting.Phase0Block), &block)
require.NoError(t, err)
jsonBytes, err := json.Marshal(block.Message)
@@ -1047,7 +1046,7 @@ func TestProduceBlockV3(t *testing.T) {
require.Equal(t, "", writer.Header().Get(api.ConsensusBlockValueHeader))
})
t.Run("Altair", func(t *testing.T) {
var block *shared.SignedBeaconBlockAltair
var block *structs.SignedBeaconBlockAltair
err := json.Unmarshal([]byte(rpctesting.AltairBlock), &block)
require.NoError(t, err)
@@ -1074,16 +1073,16 @@ func TestProduceBlockV3(t *testing.T) {
writer.Body = &bytes.Buffer{}
server.ProduceBlockV3(writer, request)
assert.Equal(t, http.StatusOK, writer.Code)
want := fmt.Sprintf(`{"version":"altair","execution_payload_blinded":false,"execution_payload_value":"","consensus_block_value":"10","data":%s}`, string(jsonBytes))
want := fmt.Sprintf(`{"version":"altair","execution_payload_blinded":false,"execution_payload_value":"","consensus_block_value":"10000000000","data":%s}`, string(jsonBytes))
body := strings.ReplaceAll(writer.Body.String(), "\n", "")
require.Equal(t, want, body)
require.Equal(t, "false", writer.Header().Get(api.ExecutionPayloadBlindedHeader))
require.Equal(t, "", writer.Header().Get(api.ExecutionPayloadValueHeader))
require.Equal(t, "altair", writer.Header().Get(api.VersionHeader))
require.Equal(t, "10", writer.Header().Get(api.ConsensusBlockValueHeader))
require.Equal(t, "10000000000", writer.Header().Get(api.ConsensusBlockValueHeader))
})
t.Run("Bellatrix", func(t *testing.T) {
var block *shared.SignedBeaconBlockBellatrix
var block *structs.SignedBeaconBlockBellatrix
err := json.Unmarshal([]byte(rpctesting.BellatrixBlock), &block)
require.NoError(t, err)
jsonBytes, err := json.Marshal(block.Message)
@@ -1112,16 +1111,16 @@ func TestProduceBlockV3(t *testing.T) {
writer.Body = &bytes.Buffer{}
server.ProduceBlockV3(writer, request)
assert.Equal(t, http.StatusOK, writer.Code)
want := fmt.Sprintf(`{"version":"bellatrix","execution_payload_blinded":false,"execution_payload_value":"2000","consensus_block_value":"10","data":%s}`, string(jsonBytes))
want := fmt.Sprintf(`{"version":"bellatrix","execution_payload_blinded":false,"execution_payload_value":"2000","consensus_block_value":"10000000000","data":%s}`, string(jsonBytes))
body := strings.ReplaceAll(writer.Body.String(), "\n", "")
require.Equal(t, want, body)
require.Equal(t, "false", writer.Header().Get(api.ExecutionPayloadBlindedHeader))
require.Equal(t, "2000", writer.Header().Get(api.ExecutionPayloadValueHeader))
require.Equal(t, "bellatrix", writer.Header().Get(api.VersionHeader))
require.Equal(t, "10", writer.Header().Get(api.ConsensusBlockValueHeader))
require.Equal(t, "10000000000", writer.Header().Get(api.ConsensusBlockValueHeader))
})
t.Run("BlindedBellatrix", func(t *testing.T) {
var block *shared.SignedBlindedBeaconBlockBellatrix
var block *structs.SignedBlindedBeaconBlockBellatrix
err := json.Unmarshal([]byte(rpctesting.BlindedBellatrixBlock), &block)
require.NoError(t, err)
jsonBytes, err := json.Marshal(block.Message)
@@ -1150,16 +1149,16 @@ func TestProduceBlockV3(t *testing.T) {
writer.Body = &bytes.Buffer{}
server.ProduceBlockV3(writer, request)
assert.Equal(t, http.StatusOK, writer.Code)
want := fmt.Sprintf(`{"version":"bellatrix","execution_payload_blinded":true,"execution_payload_value":"2000","consensus_block_value":"10","data":%s}`, string(jsonBytes))
want := fmt.Sprintf(`{"version":"bellatrix","execution_payload_blinded":true,"execution_payload_value":"2000","consensus_block_value":"10000000000","data":%s}`, string(jsonBytes))
body := strings.ReplaceAll(writer.Body.String(), "\n", "")
require.Equal(t, want, body)
require.Equal(t, "true", writer.Header().Get(api.ExecutionPayloadBlindedHeader))
require.Equal(t, "2000", writer.Header().Get(api.ExecutionPayloadValueHeader))
require.Equal(t, "bellatrix", writer.Header().Get(api.VersionHeader))
require.Equal(t, "10", writer.Header().Get(api.ConsensusBlockValueHeader))
require.Equal(t, "10000000000", writer.Header().Get(api.ConsensusBlockValueHeader))
})
t.Run("Capella", func(t *testing.T) {
var block *shared.SignedBeaconBlockCapella
var block *structs.SignedBeaconBlockCapella
err := json.Unmarshal([]byte(rpctesting.CapellaBlock), &block)
require.NoError(t, err)
jsonBytes, err := json.Marshal(block.Message)
@@ -1188,16 +1187,16 @@ func TestProduceBlockV3(t *testing.T) {
writer.Body = &bytes.Buffer{}
server.ProduceBlockV3(writer, request)
assert.Equal(t, http.StatusOK, writer.Code)
want := fmt.Sprintf(`{"version":"capella","execution_payload_blinded":false,"execution_payload_value":"2000","consensus_block_value":"10","data":%s}`, string(jsonBytes))
want := fmt.Sprintf(`{"version":"capella","execution_payload_blinded":false,"execution_payload_value":"2000","consensus_block_value":"10000000000","data":%s}`, string(jsonBytes))
body := strings.ReplaceAll(writer.Body.String(), "\n", "")
require.Equal(t, want, body)
require.Equal(t, "false", writer.Header().Get(api.ExecutionPayloadBlindedHeader))
require.Equal(t, "2000", writer.Header().Get(api.ExecutionPayloadValueHeader))
require.Equal(t, "capella", writer.Header().Get(api.VersionHeader))
require.Equal(t, "10", writer.Header().Get(api.ConsensusBlockValueHeader))
require.Equal(t, "10000000000", writer.Header().Get(api.ConsensusBlockValueHeader))
})
t.Run("Blinded Capella", func(t *testing.T) {
var block *shared.SignedBlindedBeaconBlockCapella
var block *structs.SignedBlindedBeaconBlockCapella
err := json.Unmarshal([]byte(rpctesting.BlindedCapellaBlock), &block)
require.NoError(t, err)
jsonBytes, err := json.Marshal(block.Message)
@@ -1226,16 +1225,16 @@ func TestProduceBlockV3(t *testing.T) {
writer.Body = &bytes.Buffer{}
server.ProduceBlockV3(writer, request)
assert.Equal(t, http.StatusOK, writer.Code)
want := fmt.Sprintf(`{"version":"capella","execution_payload_blinded":true,"execution_payload_value":"2000","consensus_block_value":"10","data":%s}`, string(jsonBytes))
want := fmt.Sprintf(`{"version":"capella","execution_payload_blinded":true,"execution_payload_value":"2000","consensus_block_value":"10000000000","data":%s}`, string(jsonBytes))
body := strings.ReplaceAll(writer.Body.String(), "\n", "")
require.Equal(t, want, body)
require.Equal(t, "true", writer.Header().Get(api.ExecutionPayloadBlindedHeader))
require.Equal(t, "2000", writer.Header().Get(api.ExecutionPayloadValueHeader))
require.Equal(t, "capella", writer.Header().Get(api.VersionHeader))
require.Equal(t, "10", writer.Header().Get(api.ConsensusBlockValueHeader))
require.Equal(t, "10000000000", writer.Header().Get(api.ConsensusBlockValueHeader))
})
t.Run("Deneb", func(t *testing.T) {
var block *shared.SignedBeaconBlockContentsDeneb
var block *structs.SignedBeaconBlockContentsDeneb
err := json.Unmarshal([]byte(rpctesting.DenebBlockContents), &block)
require.NoError(t, err)
jsonBytes, err := json.Marshal(block.ToUnsigned())
@@ -1264,16 +1263,16 @@ func TestProduceBlockV3(t *testing.T) {
writer.Body = &bytes.Buffer{}
server.ProduceBlockV3(writer, request)
assert.Equal(t, http.StatusOK, writer.Code)
want := fmt.Sprintf(`{"version":"deneb","execution_payload_blinded":false,"execution_payload_value":"2000","consensus_block_value":"10","data":%s}`, string(jsonBytes))
want := fmt.Sprintf(`{"version":"deneb","execution_payload_blinded":false,"execution_payload_value":"2000","consensus_block_value":"10000000000","data":%s}`, string(jsonBytes))
body := strings.ReplaceAll(writer.Body.String(), "\n", "")
require.Equal(t, want, body)
require.Equal(t, "false", writer.Header().Get(api.ExecutionPayloadBlindedHeader))
require.Equal(t, "2000", writer.Header().Get(api.ExecutionPayloadValueHeader))
require.Equal(t, "deneb", writer.Header().Get(api.VersionHeader))
require.Equal(t, "10", writer.Header().Get(api.ConsensusBlockValueHeader))
require.Equal(t, "10000000000", writer.Header().Get(api.ConsensusBlockValueHeader))
})
t.Run("Blinded Deneb", func(t *testing.T) {
var block *shared.SignedBlindedBeaconBlockDeneb
var block *structs.SignedBlindedBeaconBlockDeneb
err := json.Unmarshal([]byte(rpctesting.BlindedDenebBlock), &block)
require.NoError(t, err)
jsonBytes, err := json.Marshal(block.Message)
@@ -1302,13 +1301,13 @@ func TestProduceBlockV3(t *testing.T) {
writer.Body = &bytes.Buffer{}
server.ProduceBlockV3(writer, request)
assert.Equal(t, http.StatusOK, writer.Code)
want := fmt.Sprintf(`{"version":"deneb","execution_payload_blinded":true,"execution_payload_value":"2000","consensus_block_value":"10","data":%s}`, string(jsonBytes))
want := fmt.Sprintf(`{"version":"deneb","execution_payload_blinded":true,"execution_payload_value":"2000","consensus_block_value":"10000000000","data":%s}`, string(jsonBytes))
body := strings.ReplaceAll(writer.Body.String(), "\n", "")
require.Equal(t, want, body)
require.Equal(t, "true", writer.Header().Get(api.ExecutionPayloadBlindedHeader))
require.Equal(t, "2000", writer.Header().Get(api.ExecutionPayloadValueHeader))
require.Equal(t, "deneb", writer.Header().Get(api.VersionHeader))
require.Equal(t, "10", writer.Header().Get(api.ConsensusBlockValueHeader))
require.Equal(t, "10000000000", writer.Header().Get(api.ConsensusBlockValueHeader))
})
t.Run("invalid query parameter slot empty", func(t *testing.T) {
v1alpha1Server := mock2.NewMockBeaconNodeValidatorServer(ctrl)
@@ -1375,10 +1374,10 @@ func TestProduceBlockV3SSZ(t *testing.T) {
require.NoError(t, err)
chainService := &blockchainTesting.ChainService{}
syncChecker := &mockSync.Sync{IsSyncing: false}
rewardFetcher := &rewardtesting.MockBlockRewardFetcher{Rewards: &rewards.BlockRewards{Total: "10"}}
rewardFetcher := &rewardtesting.MockBlockRewardFetcher{Rewards: &structs.BlockRewards{Total: "10"}}
t.Run("Phase 0", func(t *testing.T) {
var block *shared.SignedBeaconBlock
var block *structs.SignedBeaconBlock
err := json.Unmarshal([]byte(rpctesting.Phase0Block), &block)
require.NoError(t, err)
v1alpha1Server := mock2.NewMockBeaconNodeValidatorServer(ctrl)
@@ -1414,7 +1413,7 @@ func TestProduceBlockV3SSZ(t *testing.T) {
require.Equal(t, "", writer.Header().Get(api.ConsensusBlockValueHeader))
})
t.Run("Altair", func(t *testing.T) {
var block *shared.SignedBeaconBlockAltair
var block *structs.SignedBeaconBlockAltair
err := json.Unmarshal([]byte(rpctesting.AltairBlock), &block)
require.NoError(t, err)
v1alpha1Server := mock2.NewMockBeaconNodeValidatorServer(ctrl)
@@ -1449,10 +1448,10 @@ func TestProduceBlockV3SSZ(t *testing.T) {
require.Equal(t, "false", writer.Header().Get(api.ExecutionPayloadBlindedHeader))
require.Equal(t, "", writer.Header().Get(api.ExecutionPayloadValueHeader))
require.Equal(t, "altair", writer.Header().Get(api.VersionHeader))
require.Equal(t, "10", writer.Header().Get(api.ConsensusBlockValueHeader))
require.Equal(t, "10000000000", writer.Header().Get(api.ConsensusBlockValueHeader))
})
t.Run("Bellatrix", func(t *testing.T) {
var block *shared.SignedBeaconBlockBellatrix
var block *structs.SignedBeaconBlockBellatrix
err := json.Unmarshal([]byte(rpctesting.BellatrixBlock), &block)
require.NoError(t, err)
v1alpha1Server := mock2.NewMockBeaconNodeValidatorServer(ctrl)
@@ -1491,10 +1490,10 @@ func TestProduceBlockV3SSZ(t *testing.T) {
require.Equal(t, "false", writer.Header().Get(api.ExecutionPayloadBlindedHeader))
require.Equal(t, "2000", writer.Header().Get(api.ExecutionPayloadValueHeader))
require.Equal(t, "bellatrix", writer.Header().Get(api.VersionHeader))
require.Equal(t, "10", writer.Header().Get(api.ConsensusBlockValueHeader))
require.Equal(t, "10000000000", writer.Header().Get(api.ConsensusBlockValueHeader))
})
t.Run("BlindedBellatrix", func(t *testing.T) {
var block *shared.SignedBlindedBeaconBlockBellatrix
var block *structs.SignedBlindedBeaconBlockBellatrix
err := json.Unmarshal([]byte(rpctesting.BlindedBellatrixBlock), &block)
require.NoError(t, err)
v1alpha1Server := mock2.NewMockBeaconNodeValidatorServer(ctrl)
@@ -1532,10 +1531,10 @@ func TestProduceBlockV3SSZ(t *testing.T) {
require.Equal(t, "true", writer.Header().Get(api.ExecutionPayloadBlindedHeader))
require.Equal(t, "2000", writer.Header().Get(api.ExecutionPayloadValueHeader))
require.Equal(t, "bellatrix", writer.Header().Get(api.VersionHeader))
require.Equal(t, "10", writer.Header().Get(api.ConsensusBlockValueHeader))
require.Equal(t, "10000000000", writer.Header().Get(api.ConsensusBlockValueHeader))
})
t.Run("Capella", func(t *testing.T) {
var block *shared.SignedBeaconBlockCapella
var block *structs.SignedBeaconBlockCapella
err := json.Unmarshal([]byte(rpctesting.CapellaBlock), &block)
require.NoError(t, err)
v1alpha1Server := mock2.NewMockBeaconNodeValidatorServer(ctrl)
@@ -1573,10 +1572,10 @@ func TestProduceBlockV3SSZ(t *testing.T) {
require.Equal(t, "false", writer.Header().Get(api.ExecutionPayloadBlindedHeader))
require.Equal(t, "2000", writer.Header().Get(api.ExecutionPayloadValueHeader))
require.Equal(t, "capella", writer.Header().Get(api.VersionHeader))
require.Equal(t, "10", writer.Header().Get(api.ConsensusBlockValueHeader))
require.Equal(t, "10000000000", writer.Header().Get(api.ConsensusBlockValueHeader))
})
t.Run("Blinded Capella", func(t *testing.T) {
var block *shared.SignedBlindedBeaconBlockCapella
var block *structs.SignedBlindedBeaconBlockCapella
err := json.Unmarshal([]byte(rpctesting.BlindedCapellaBlock), &block)
require.NoError(t, err)
v1alpha1Server := mock2.NewMockBeaconNodeValidatorServer(ctrl)
@@ -1614,10 +1613,10 @@ func TestProduceBlockV3SSZ(t *testing.T) {
require.Equal(t, "true", writer.Header().Get(api.ExecutionPayloadBlindedHeader))
require.Equal(t, "2000", writer.Header().Get(api.ExecutionPayloadValueHeader))
require.Equal(t, "capella", writer.Header().Get(api.VersionHeader))
require.Equal(t, "10", writer.Header().Get(api.ConsensusBlockValueHeader))
require.Equal(t, "10000000000", writer.Header().Get(api.ConsensusBlockValueHeader))
})
t.Run("Deneb", func(t *testing.T) {
var block *shared.SignedBeaconBlockContentsDeneb
var block *structs.SignedBeaconBlockContentsDeneb
err := json.Unmarshal([]byte(rpctesting.DenebBlockContents), &block)
require.NoError(t, err)
v1alpha1Server := mock2.NewMockBeaconNodeValidatorServer(ctrl)
@@ -1655,10 +1654,10 @@ func TestProduceBlockV3SSZ(t *testing.T) {
require.Equal(t, "false", writer.Header().Get(api.ExecutionPayloadBlindedHeader))
require.Equal(t, "2000", writer.Header().Get(api.ExecutionPayloadValueHeader))
require.Equal(t, "deneb", writer.Header().Get(api.VersionHeader))
require.Equal(t, "10", writer.Header().Get(api.ConsensusBlockValueHeader))
require.Equal(t, "10000000000", writer.Header().Get(api.ConsensusBlockValueHeader))
})
t.Run("Blinded Deneb", func(t *testing.T) {
var block *shared.SignedBlindedBeaconBlockDeneb
var block *structs.SignedBlindedBeaconBlockDeneb
err := json.Unmarshal([]byte(rpctesting.BlindedDenebBlock), &block)
require.NoError(t, err)
v1alpha1Server := mock2.NewMockBeaconNodeValidatorServer(ctrl)
@@ -1696,6 +1695,6 @@ func TestProduceBlockV3SSZ(t *testing.T) {
require.Equal(t, "true", writer.Header().Get(api.ExecutionPayloadBlindedHeader))
require.Equal(t, "2000", writer.Header().Get(api.ExecutionPayloadValueHeader))
require.Equal(t, "deneb", writer.Header().Get(api.VersionHeader))
require.Equal(t, "10", writer.Header().Get(api.ConsensusBlockValueHeader))
require.Equal(t, "10000000000", writer.Header().Get(api.ConsensusBlockValueHeader))
})
}

View File

@@ -15,6 +15,7 @@ import (
"github.com/ethereum/go-ethereum/common/hexutil"
"github.com/gorilla/mux"
"github.com/pkg/errors"
"github.com/prysmaticlabs/prysm/v4/api/server/structs"
mockChain "github.com/prysmaticlabs/prysm/v4/beacon-chain/blockchain/testing"
builderTest "github.com/prysmaticlabs/prysm/v4/beacon-chain/builder/testing"
"github.com/prysmaticlabs/prysm/v4/beacon-chain/cache"
@@ -26,7 +27,6 @@ import (
"github.com/prysmaticlabs/prysm/v4/beacon-chain/operations/synccommittee"
p2pmock "github.com/prysmaticlabs/prysm/v4/beacon-chain/p2p/testing"
"github.com/prysmaticlabs/prysm/v4/beacon-chain/rpc/core"
"github.com/prysmaticlabs/prysm/v4/beacon-chain/rpc/eth/shared"
"github.com/prysmaticlabs/prysm/v4/beacon-chain/rpc/testutil"
"github.com/prysmaticlabs/prysm/v4/beacon-chain/state"
"github.com/prysmaticlabs/prysm/v4/beacon-chain/state/stategen"
@@ -163,7 +163,7 @@ func TestGetAggregateAttestation(t *testing.T) {
s.GetAggregateAttestation(writer, request)
assert.Equal(t, http.StatusOK, writer.Code)
resp := &AggregateAttestationResponse{}
resp := &structs.AggregateAttestationResponse{}
require.NoError(t, json.Unmarshal(writer.Body.Bytes(), resp))
require.NotNil(t, resp)
require.NotNil(t, resp.Data)
@@ -190,7 +190,7 @@ func TestGetAggregateAttestation(t *testing.T) {
s.GetAggregateAttestation(writer, request)
assert.Equal(t, http.StatusOK, writer.Code)
resp := &AggregateAttestationResponse{}
resp := &structs.AggregateAttestationResponse{}
require.NoError(t, json.Unmarshal(writer.Body.Bytes(), resp))
require.NotNil(t, resp)
require.NotNil(t, resp.Data)
@@ -329,7 +329,7 @@ func TestGetAggregateAttestation_SameSlotAndRoot_ReturnMostAggregationBits(t *te
s.GetAggregateAttestation(writer, request)
assert.Equal(t, http.StatusOK, writer.Code)
resp := &AggregateAttestationResponse{}
resp := &structs.AggregateAttestationResponse{}
require.NoError(t, json.Unmarshal(writer.Body.Bytes(), resp))
require.NotNil(t, resp)
assert.DeepEqual(t, "0x03000001", resp.Data.AggregationBits)
@@ -872,16 +872,16 @@ func TestGetAttestationData(t *testing.T) {
s.GetAttestationData(writer, request)
expectedResponse := &GetAttestationDataResponse{
Data: &shared.AttestationData{
expectedResponse := &structs.GetAttestationDataResponse{
Data: &structs.AttestationData{
Slot: strconv.FormatUint(uint64(slot), 10),
BeaconBlockRoot: hexutil.Encode(blockRoot[:]),
CommitteeIndex: strconv.FormatUint(0, 10),
Source: &shared.Checkpoint{
Source: &structs.Checkpoint{
Epoch: strconv.FormatUint(2, 10),
Root: hexutil.Encode(justifiedRoot[:]),
},
Target: &shared.Checkpoint{
Target: &structs.Checkpoint{
Epoch: strconv.FormatUint(3, 10),
Root: hexutil.Encode(blockRoot[:]),
},
@@ -889,7 +889,7 @@ func TestGetAttestationData(t *testing.T) {
}
assert.Equal(t, http.StatusOK, writer.Code)
resp := &GetAttestationDataResponse{}
resp := &structs.GetAttestationDataResponse{}
require.NoError(t, json.Unmarshal(writer.Body.Bytes(), resp))
require.NotNil(t, resp)
assert.DeepEqual(t, expectedResponse, resp)
@@ -1110,16 +1110,16 @@ func TestGetAttestationData(t *testing.T) {
s.GetAttestationData(writer, request)
expectedResponse := &GetAttestationDataResponse{
Data: &shared.AttestationData{
expectedResponse := &structs.GetAttestationDataResponse{
Data: &structs.AttestationData{
Slot: strconv.FormatUint(uint64(slot), 10),
BeaconBlockRoot: hexutil.Encode(blockRoot[:]),
CommitteeIndex: strconv.FormatUint(0, 10),
Source: &shared.Checkpoint{
Source: &structs.Checkpoint{
Epoch: strconv.FormatUint(0, 10),
Root: hexutil.Encode(justifiedRoot[:]),
},
Target: &shared.Checkpoint{
Target: &structs.Checkpoint{
Epoch: strconv.FormatUint(0, 10),
Root: hexutil.Encode(blockRoot[:]),
},
@@ -1127,7 +1127,7 @@ func TestGetAttestationData(t *testing.T) {
}
assert.Equal(t, http.StatusOK, writer.Code)
resp := &GetAttestationDataResponse{}
resp := &structs.GetAttestationDataResponse{}
require.NoError(t, json.Unmarshal(writer.Body.Bytes(), resp))
require.NotNil(t, resp)
assert.DeepEqual(t, expectedResponse, resp)
@@ -1197,16 +1197,16 @@ func TestGetAttestationData(t *testing.T) {
s.GetAttestationData(writer, request)
expectedResponse := &GetAttestationDataResponse{
Data: &shared.AttestationData{
expectedResponse := &structs.GetAttestationDataResponse{
Data: &structs.AttestationData{
Slot: strconv.FormatUint(uint64(slot), 10),
BeaconBlockRoot: hexutil.Encode(blockRoot[:]),
CommitteeIndex: strconv.FormatUint(0, 10),
Source: &shared.Checkpoint{
Source: &structs.Checkpoint{
Epoch: strconv.FormatUint(uint64(slots.ToEpoch(1500)), 10),
Root: hexutil.Encode(justifiedBlockRoot[:]),
},
Target: &shared.Checkpoint{
Target: &structs.Checkpoint{
Epoch: strconv.FormatUint(312, 10),
Root: hexutil.Encode(blockRoot[:]),
},
@@ -1214,7 +1214,7 @@ func TestGetAttestationData(t *testing.T) {
}
assert.Equal(t, http.StatusOK, writer.Code)
resp := &GetAttestationDataResponse{}
resp := &structs.GetAttestationDataResponse{}
require.NoError(t, json.Unmarshal(writer.Body.Bytes(), resp))
require.NotNil(t, resp)
assert.DeepEqual(t, expectedResponse, resp)
@@ -1248,7 +1248,7 @@ func TestProduceSyncCommitteeContribution(t *testing.T) {
server.ProduceSyncCommitteeContribution(writer, request)
assert.Equal(t, http.StatusOK, writer.Code)
resp := &ProduceSyncCommitteeContributionResponse{}
resp := &structs.ProduceSyncCommitteeContributionResponse{}
require.NoError(t, json.Unmarshal(writer.Body.Bytes(), resp))
require.NotNil(t, resp.Data)
require.Equal(t, resp.Data.Slot, "1")
@@ -1263,7 +1263,7 @@ func TestProduceSyncCommitteeContribution(t *testing.T) {
server.ProduceSyncCommitteeContribution(writer, request)
assert.Equal(t, http.StatusBadRequest, writer.Code)
resp := &ProduceSyncCommitteeContributionResponse{}
resp := &structs.ProduceSyncCommitteeContributionResponse{}
require.NoError(t, json.Unmarshal(writer.Body.Bytes(), resp))
require.ErrorContains(t, "slot is required", errors.New(writer.Body.String()))
})
@@ -1275,7 +1275,7 @@ func TestProduceSyncCommitteeContribution(t *testing.T) {
server.ProduceSyncCommitteeContribution(writer, request)
assert.Equal(t, http.StatusBadRequest, writer.Code)
resp := &ProduceSyncCommitteeContributionResponse{}
resp := &structs.ProduceSyncCommitteeContributionResponse{}
require.NoError(t, json.Unmarshal(writer.Body.Bytes(), resp))
require.ErrorContains(t, "subcommittee_index is required", errors.New(writer.Body.String()))
})
@@ -1287,7 +1287,7 @@ func TestProduceSyncCommitteeContribution(t *testing.T) {
server.ProduceSyncCommitteeContribution(writer, request)
assert.Equal(t, http.StatusBadRequest, writer.Code)
resp := &ProduceSyncCommitteeContributionResponse{}
resp := &structs.ProduceSyncCommitteeContributionResponse{}
require.NoError(t, json.Unmarshal(writer.Body.Bytes(), resp))
require.ErrorContains(t, "Invalid Beacon Block Root: empty hex string", errors.New(writer.Body.String()))
})
@@ -1299,7 +1299,7 @@ func TestProduceSyncCommitteeContribution(t *testing.T) {
server.ProduceSyncCommitteeContribution(writer, request)
assert.Equal(t, http.StatusBadRequest, writer.Code)
resp := &ProduceSyncCommitteeContributionResponse{}
resp := &structs.ProduceSyncCommitteeContributionResponse{}
require.NoError(t, json.Unmarshal(writer.Body.Bytes(), resp))
require.ErrorContains(t, "Invalid Beacon Block Root: hex string without 0x prefix", errors.New(writer.Body.String()))
})
@@ -1311,7 +1311,7 @@ func TestProduceSyncCommitteeContribution(t *testing.T) {
server.ProduceSyncCommitteeContribution(writer, request)
assert.Equal(t, http.StatusOK, writer.Code)
resp := &ProduceSyncCommitteeContributionResponse{}
resp := &structs.ProduceSyncCommitteeContributionResponse{}
require.NoError(t, json.Unmarshal(writer.Body.Bytes(), resp))
require.NotNil(t, resp)
require.NotNil(t, resp.Data)
@@ -1330,7 +1330,7 @@ func TestProduceSyncCommitteeContribution(t *testing.T) {
}
server.ProduceSyncCommitteeContribution(writer, request)
assert.Equal(t, http.StatusNotFound, writer.Code)
resp2 := &ProduceSyncCommitteeContributionResponse{}
resp2 := &structs.ProduceSyncCommitteeContributionResponse{}
require.NoError(t, json.Unmarshal(writer.Body.Bytes(), resp2))
require.ErrorContains(t, "No subcommittee messages found", errors.New(writer.Body.String()))
})
@@ -1449,7 +1449,7 @@ func TestGetAttesterDuties(t *testing.T) {
s.GetAttesterDuties(writer, request)
assert.Equal(t, http.StatusOK, writer.Code)
resp := &GetAttesterDutiesResponse{}
resp := &structs.GetAttesterDutiesResponse{}
require.NoError(t, json.Unmarshal(writer.Body.Bytes(), resp))
assert.Equal(t, hexutil.Encode(genesisRoot[:]), resp.DependentRoot)
require.Equal(t, 1, len(resp.Data))
@@ -1473,7 +1473,7 @@ func TestGetAttesterDuties(t *testing.T) {
s.GetAttesterDuties(writer, request)
assert.Equal(t, http.StatusOK, writer.Code)
resp := &GetAttesterDutiesResponse{}
resp := &structs.GetAttesterDutiesResponse{}
require.NoError(t, json.Unmarshal(writer.Body.Bytes(), resp))
require.Equal(t, 2, len(resp.Data))
})
@@ -1532,7 +1532,7 @@ func TestGetAttesterDuties(t *testing.T) {
s.GetAttesterDuties(writer, request)
assert.Equal(t, http.StatusOK, writer.Code)
resp := &GetAttesterDutiesResponse{}
resp := &structs.GetAttesterDutiesResponse{}
require.NoError(t, json.Unmarshal(writer.Body.Bytes(), resp))
assert.Equal(t, hexutil.Encode(genesisRoot[:]), resp.DependentRoot)
require.Equal(t, 1, len(resp.Data))
@@ -1589,7 +1589,7 @@ func TestGetAttesterDuties(t *testing.T) {
s.GetAttesterDuties(writer, request)
assert.Equal(t, http.StatusOK, writer.Code)
resp := &GetAttesterDutiesResponse{}
resp := &structs.GetAttesterDutiesResponse{}
require.NoError(t, json.Unmarshal(writer.Body.Bytes(), resp))
require.Equal(t, 0, len(resp.Data))
})
@@ -1627,7 +1627,7 @@ func TestGetAttesterDuties(t *testing.T) {
s.GetAttesterDuties(writer, request)
require.Equal(t, http.StatusOK, writer.Code)
resp := &GetAttesterDutiesResponse{}
resp := &structs.GetAttesterDutiesResponse{}
require.NoError(t, json.Unmarshal(writer.Body.Bytes(), resp))
assert.Equal(t, true, resp.ExecutionOptimistic)
})
@@ -1702,12 +1702,12 @@ func TestGetProposerDuties(t *testing.T) {
s.GetProposerDuties(writer, request)
assert.Equal(t, http.StatusOK, writer.Code)
resp := &GetProposerDutiesResponse{}
resp := &structs.GetProposerDutiesResponse{}
require.NoError(t, json.Unmarshal(writer.Body.Bytes(), resp))
assert.Equal(t, hexutil.Encode(genesisRoot[:]), resp.DependentRoot)
assert.Equal(t, 31, len(resp.Data))
// We expect a proposer duty for slot 11.
var expectedDuty *ProposerDuty
var expectedDuty *structs.ProposerDuty
for _, duty := range resp.Data {
if duty.Slot == "11" {
expectedDuty = duty
@@ -1742,12 +1742,12 @@ func TestGetProposerDuties(t *testing.T) {
s.GetProposerDuties(writer, request)
assert.Equal(t, http.StatusOK, writer.Code)
resp := &GetProposerDutiesResponse{}
resp := &structs.GetProposerDutiesResponse{}
require.NoError(t, json.Unmarshal(writer.Body.Bytes(), resp))
assert.Equal(t, hexutil.Encode(genesisRoot[:]), resp.DependentRoot)
assert.Equal(t, 32, len(resp.Data))
// We expect a proposer duty for slot 43.
var expectedDuty *ProposerDuty
var expectedDuty *structs.ProposerDuty
for _, duty := range resp.Data {
if duty.Slot == "43" {
expectedDuty = duty
@@ -1828,7 +1828,7 @@ func TestGetProposerDuties(t *testing.T) {
s.GetProposerDuties(writer, request)
assert.Equal(t, http.StatusOK, writer.Code)
resp := &GetProposerDutiesResponse{}
resp := &structs.GetProposerDutiesResponse{}
require.NoError(t, json.Unmarshal(writer.Body.Bytes(), resp))
assert.Equal(t, true, resp.ExecutionOptimistic)
})
@@ -1906,7 +1906,7 @@ func TestGetSyncCommitteeDuties(t *testing.T) {
s.GetSyncCommitteeDuties(writer, request)
assert.Equal(t, http.StatusOK, writer.Code)
resp := &GetSyncCommitteeDutiesResponse{}
resp := &structs.GetSyncCommitteeDutiesResponse{}
require.NoError(t, json.Unmarshal(writer.Body.Bytes(), resp))
require.Equal(t, 1, len(resp.Data))
duty := resp.Data[0]
@@ -1929,7 +1929,7 @@ func TestGetSyncCommitteeDuties(t *testing.T) {
s.GetSyncCommitteeDuties(writer, request)
assert.Equal(t, http.StatusOK, writer.Code)
resp := &GetSyncCommitteeDutiesResponse{}
resp := &structs.GetSyncCommitteeDutiesResponse{}
require.NoError(t, json.Unmarshal(writer.Body.Bytes(), resp))
require.Equal(t, 2, len(resp.Data))
})
@@ -1988,7 +1988,7 @@ func TestGetSyncCommitteeDuties(t *testing.T) {
s.GetSyncCommitteeDuties(writer, request)
assert.Equal(t, http.StatusOK, writer.Code)
resp := &GetSyncCommitteeDutiesResponse{}
resp := &structs.GetSyncCommitteeDutiesResponse{}
require.NoError(t, json.Unmarshal(writer.Body.Bytes(), resp))
require.Equal(t, 1, len(resp.Data))
assert.Equal(t, "1", resp.Data[0].ValidatorIndex)
@@ -2004,7 +2004,7 @@ func TestGetSyncCommitteeDuties(t *testing.T) {
s.GetSyncCommitteeDuties(writer, request)
assert.Equal(t, http.StatusOK, writer.Code)
resp := &GetSyncCommitteeDutiesResponse{}
resp := &structs.GetSyncCommitteeDutiesResponse{}
require.NoError(t, json.Unmarshal(writer.Body.Bytes(), resp))
duty := resp.Data[0]
require.Equal(t, 2, len(duty.ValidatorSyncCommitteeIndices))
@@ -2037,7 +2037,7 @@ func TestGetSyncCommitteeDuties(t *testing.T) {
s.GetSyncCommitteeDuties(writer, request)
assert.Equal(t, http.StatusOK, writer.Code)
resp := &GetSyncCommitteeDutiesResponse{}
resp := &structs.GetSyncCommitteeDutiesResponse{}
require.NoError(t, json.Unmarshal(writer.Body.Bytes(), resp))
require.Equal(t, 1, len(resp.Data))
duty := resp.Data[0]
@@ -2094,7 +2094,7 @@ func TestGetSyncCommitteeDuties(t *testing.T) {
s.GetSyncCommitteeDuties(writer, request)
assert.Equal(t, http.StatusOK, writer.Code)
resp := &GetSyncCommitteeDutiesResponse{}
resp := &structs.GetSyncCommitteeDutiesResponse{}
require.NoError(t, json.Unmarshal(writer.Body.Bytes(), resp))
require.Equal(t, 1, len(resp.Data))
duty := resp.Data[0]
@@ -2114,7 +2114,7 @@ func TestGetSyncCommitteeDuties(t *testing.T) {
s.GetSyncCommitteeDuties(writer, request)
assert.Equal(t, http.StatusOK, writer.Code)
resp := &GetSyncCommitteeDutiesResponse{}
resp := &structs.GetSyncCommitteeDutiesResponse{}
require.NoError(t, json.Unmarshal(writer.Body.Bytes(), resp))
require.Equal(t, 1, len(resp.Data))
duty := resp.Data[0]
@@ -2190,7 +2190,7 @@ func TestGetSyncCommitteeDuties(t *testing.T) {
s.GetSyncCommitteeDuties(writer, request)
assert.Equal(t, http.StatusOK, writer.Code)
resp := &GetSyncCommitteeDutiesResponse{}
resp := &structs.GetSyncCommitteeDutiesResponse{}
require.NoError(t, json.Unmarshal(writer.Body.Bytes(), resp))
assert.Equal(t, true, resp.ExecutionOptimistic)
})
@@ -2221,13 +2221,13 @@ func TestGetSyncCommitteeDuties(t *testing.T) {
func TestPrepareBeaconProposer(t *testing.T) {
tests := []struct {
name string
request []*shared.FeeRecipient
request []*structs.FeeRecipient
code int
wantErr string
}{
{
name: "Happy Path",
request: []*shared.FeeRecipient{{
request: []*structs.FeeRecipient{{
FeeRecipient: "0xb698D697092822185bF0311052215d5B5e1F3934",
ValidatorIndex: "1",
},
@@ -2237,7 +2237,7 @@ func TestPrepareBeaconProposer(t *testing.T) {
},
{
name: "invalid fee recipient length",
request: []*shared.FeeRecipient{{
request: []*structs.FeeRecipient{{
FeeRecipient: "0xb698D697092822185bF0311052",
ValidatorIndex: "1",
},
@@ -2290,7 +2290,7 @@ func TestProposer_PrepareBeaconProposerOverlapping(t *testing.T) {
TrackedValidatorsCache: cache.NewTrackedValidatorsCache(),
PayloadIDCache: cache.NewPayloadIDCache(),
}
req := []*shared.FeeRecipient{{
req := []*structs.FeeRecipient{{
FeeRecipient: hexutil.Encode(bytesutil.PadTo([]byte{0xFF, 0x01, 0xFF, 0x01, 0xFF, 0x01, 0xFF, 0x01, 0xFF, 0xFF, 0x01, 0xFF, 0x01, 0xFF, 0x01, 0xFF, 0x01, 0xFF}, fieldparams.FeeRecipientLength)),
ValidatorIndex: "1",
}}
@@ -2319,7 +2319,7 @@ func TestProposer_PrepareBeaconProposerOverlapping(t *testing.T) {
// Same validator with different fee recipient
hook.Reset()
req = []*shared.FeeRecipient{{
req = []*structs.FeeRecipient{{
FeeRecipient: hexutil.Encode(bytesutil.PadTo([]byte{0x01, 0x01, 0xFF, 0x01, 0xFF, 0x01, 0xFF, 0x01, 0xFF, 0xFF, 0x01, 0xFF, 0x01, 0xFF, 0x01, 0xFF, 0x01, 0xFF}, fieldparams.FeeRecipientLength)),
ValidatorIndex: "1",
}}
@@ -2335,7 +2335,7 @@ func TestProposer_PrepareBeaconProposerOverlapping(t *testing.T) {
// More than one validator
hook.Reset()
req = []*shared.FeeRecipient{
req = []*structs.FeeRecipient{
{
FeeRecipient: hexutil.Encode(bytesutil.PadTo([]byte{0x01, 0x01, 0xFF, 0x01, 0xFF, 0x01, 0xFF, 0x01, 0xFF, 0xFF, 0x01, 0xFF, 0x01, 0xFF, 0x01, 0xFF, 0x01, 0xFF}, fieldparams.FeeRecipientLength)),
ValidatorIndex: "1",
@@ -2376,9 +2376,9 @@ func BenchmarkServer_PrepareBeaconProposer(b *testing.B) {
PayloadIDCache: cache.NewPayloadIDCache(),
}
f := bytesutil.PadTo([]byte{0xFF, 0x01, 0xFF, 0x01, 0xFF, 0x01, 0xFF, 0x01, 0xFF, 0xFF, 0x01, 0xFF, 0x01, 0xFF, 0x01, 0xFF, 0x01, 0xFF}, fieldparams.FeeRecipientLength)
recipients := make([]*shared.FeeRecipient, 0)
recipients := make([]*structs.FeeRecipient, 0)
for i := 0; i < 10000; i++ {
recipients = append(recipients, &shared.FeeRecipient{FeeRecipient: hexutil.Encode(f), ValidatorIndex: fmt.Sprint(i)})
recipients = append(recipients, &structs.FeeRecipient{FeeRecipient: hexutil.Encode(f), ValidatorIndex: fmt.Sprint(i)})
}
byt, err := json.Marshal(recipients)
require.NoError(b, err)
@@ -2436,7 +2436,7 @@ func TestGetLiveness(t *testing.T) {
s.GetLiveness(writer, request)
assert.Equal(t, http.StatusOK, writer.Code)
resp := &GetLivenessResponse{}
resp := &structs.GetLivenessResponse{}
require.NoError(t, json.Unmarshal(writer.Body.Bytes(), resp))
require.NotNil(t, resp.Data)
data0 := resp.Data[0]
@@ -2455,7 +2455,7 @@ func TestGetLiveness(t *testing.T) {
s.GetLiveness(writer, request)
assert.Equal(t, http.StatusOK, writer.Code)
resp := &GetLivenessResponse{}
resp := &structs.GetLivenessResponse{}
require.NoError(t, json.Unmarshal(writer.Body.Bytes(), resp))
require.NotNil(t, resp.Data)
data0 := resp.Data[0]
@@ -2474,7 +2474,7 @@ func TestGetLiveness(t *testing.T) {
s.GetLiveness(writer, request)
assert.Equal(t, http.StatusOK, writer.Code)
resp := &GetLivenessResponse{}
resp := &structs.GetLivenessResponse{}
require.NoError(t, json.Unmarshal(writer.Body.Bytes(), resp))
require.NotNil(t, resp.Data)
data0 := resp.Data[0]

View File

@@ -47,9 +47,10 @@ type Blocker interface {
// BeaconDbBlocker is an implementation of Blocker. It retrieves blocks from the beacon chain database.
type BeaconDbBlocker struct {
BeaconDB db.ReadOnlyDatabase
ChainInfoFetcher blockchain.ChainInfoFetcher
BlobStorage *filesystem.BlobStorage
BeaconDB db.ReadOnlyDatabase
ChainInfoFetcher blockchain.ChainInfoFetcher
GenesisTimeFetcher blockchain.TimeFetcher
BlobStorage *filesystem.BlobStorage
}
// Block returns the beacon block for a given identifier. The identifier can be one of:
@@ -139,6 +140,13 @@ func (p *BeaconDbBlocker) Block(ctx context.Context, id []byte) (interfaces.Read
// - <slot>
// - <hex encoded block root with '0x' prefix>
// - <block root>
//
// cases:
// - no block, 404
// - block exists, no commitment, 200 w/ empty list
// - block exists, has commitments, inside retention period (greater of protocol- or user-specified) serve then w/ 200 unless we hit an error reading them.
// we are technically not supposed to import a block to forkchoice unless we have the blobs, so the nuance here is if we can't find the file and we are inside the protocol-defined retention period, then it's actually a 500.
// - block exists, has commitments, outside retention period (greater of protocol- or user-specified) - ie just like block exists, no commitment
func (p *BeaconDbBlocker) Blobs(ctx context.Context, id string, indices []uint64) ([]*blocks.VerifiedROBlob, *core.RpcError) {
var root []byte
switch id {
@@ -207,7 +215,25 @@ func (p *BeaconDbBlocker) Blobs(ctx context.Context, id string, indices []uint64
}
}
}
if !p.BeaconDB.HasBlock(ctx, bytesutil.ToBytes32(root)) {
return nil, &core.RpcError{Err: errors.New("block not found"), Reason: core.NotFound}
}
b, err := p.BeaconDB.Block(ctx, bytesutil.ToBytes32(root))
if err != nil {
return nil, &core.RpcError{Err: errors.Wrap(err, "failed to retrieve block from db"), Reason: core.Internal}
}
// if block is not in the retention window return 200 w/ empty list
if !params.WithinDAPeriod(slots.ToEpoch(b.Block().Slot()), slots.ToEpoch(p.GenesisTimeFetcher.CurrentSlot())) {
return make([]*blocks.VerifiedROBlob, 0), nil
}
commitments, err := b.Block().Body().BlobKzgCommitments()
if err != nil {
return nil, &core.RpcError{Err: errors.Wrap(err, "failed to retrieve kzg commitments from block"), Reason: core.Internal}
}
// if there are no commitments return 200 w/ empty list
if len(commitments) == 0 {
return make([]*blocks.VerifiedROBlob, 0), nil
}
if len(indices) == 0 {
m, err := p.BlobStorage.Indices(bytesutil.ToBytes32(root))
if err != nil {

View File

@@ -6,6 +6,7 @@ import (
"net/http"
"reflect"
"testing"
"time"
"github.com/ethereum/go-ethereum/common/hexutil"
mockChain "github.com/prysmaticlabs/prysm/v4/beacon-chain/blockchain/testing"
@@ -180,8 +181,11 @@ func TestGetBlob(t *testing.T) {
t.Run("head", func(t *testing.T) {
blocker := &BeaconDbBlocker{
ChainInfoFetcher: &mockChain.ChainService{Root: blockRoot[:]},
BeaconDB: db,
BlobStorage: bs,
GenesisTimeFetcher: &testutil.MockGenesisTimeFetcher{
Genesis: time.Now(),
},
BeaconDB: db,
BlobStorage: bs,
}
verifiedBlobs, rpcErr := blocker.Blobs(ctx, "head", nil)
assert.Equal(t, rpcErr == nil, true)
@@ -214,8 +218,11 @@ func TestGetBlob(t *testing.T) {
t.Run("finalized", func(t *testing.T) {
blocker := &BeaconDbBlocker{
ChainInfoFetcher: &mockChain.ChainService{FinalizedCheckPoint: &ethpbalpha.Checkpoint{Root: blockRoot[:]}},
BeaconDB: db,
BlobStorage: bs,
GenesisTimeFetcher: &testutil.MockGenesisTimeFetcher{
Genesis: time.Now(),
},
BeaconDB: db,
BlobStorage: bs,
}
verifiedBlobs, rpcErr := blocker.Blobs(ctx, "finalized", nil)
@@ -225,8 +232,11 @@ func TestGetBlob(t *testing.T) {
t.Run("justified", func(t *testing.T) {
blocker := &BeaconDbBlocker{
ChainInfoFetcher: &mockChain.ChainService{CurrentJustifiedCheckPoint: &ethpbalpha.Checkpoint{Root: blockRoot[:]}},
BeaconDB: db,
BlobStorage: bs,
GenesisTimeFetcher: &testutil.MockGenesisTimeFetcher{
Genesis: time.Now(),
},
BeaconDB: db,
BlobStorage: bs,
}
verifiedBlobs, rpcErr := blocker.Blobs(ctx, "justified", nil)
@@ -235,6 +245,9 @@ func TestGetBlob(t *testing.T) {
})
t.Run("root", func(t *testing.T) {
blocker := &BeaconDbBlocker{
GenesisTimeFetcher: &testutil.MockGenesisTimeFetcher{
Genesis: time.Now(),
},
BeaconDB: db,
BlobStorage: bs,
}
@@ -244,6 +257,9 @@ func TestGetBlob(t *testing.T) {
})
t.Run("slot", func(t *testing.T) {
blocker := &BeaconDbBlocker{
GenesisTimeFetcher: &testutil.MockGenesisTimeFetcher{
Genesis: time.Now(),
},
BeaconDB: db,
BlobStorage: bs,
}
@@ -254,8 +270,11 @@ func TestGetBlob(t *testing.T) {
t.Run("one blob only", func(t *testing.T) {
blocker := &BeaconDbBlocker{
ChainInfoFetcher: &mockChain.ChainService{FinalizedCheckPoint: &ethpbalpha.Checkpoint{Root: blockRoot[:]}},
BeaconDB: db,
BlobStorage: bs,
GenesisTimeFetcher: &testutil.MockGenesisTimeFetcher{
Genesis: time.Now(),
},
BeaconDB: db,
BlobStorage: bs,
}
verifiedBlobs, rpcErr := blocker.Blobs(ctx, "123", []uint64{2})
assert.Equal(t, rpcErr == nil, true)
@@ -270,8 +289,11 @@ func TestGetBlob(t *testing.T) {
t.Run("no blobs returns an empty array", func(t *testing.T) {
blocker := &BeaconDbBlocker{
ChainInfoFetcher: &mockChain.ChainService{FinalizedCheckPoint: &ethpbalpha.Checkpoint{Root: blockRoot[:]}},
BeaconDB: db,
BlobStorage: filesystem.NewEphemeralBlobStorage(t),
GenesisTimeFetcher: &testutil.MockGenesisTimeFetcher{
Genesis: time.Now(),
},
BeaconDB: db,
BlobStorage: filesystem.NewEphemeralBlobStorage(t),
}
verifiedBlobs, rpcErr := blocker.Blobs(ctx, "123", nil)
assert.Equal(t, rpcErr == nil, true)

View File

@@ -5,11 +5,11 @@ go_library(
srcs = [
"handlers.go",
"server.go",
"structs.go",
],
importpath = "github.com/prysmaticlabs/prysm/v4/beacon-chain/rpc/prysm/beacon",
visibility = ["//visibility:public"],
deps = [
"//api/server/structs:go_default_library",
"//beacon-chain/blockchain:go_default_library",
"//beacon-chain/core/helpers:go_default_library",
"//beacon-chain/db:go_default_library",

View File

@@ -7,6 +7,7 @@ import (
"strconv"
"github.com/ethereum/go-ethereum/common/hexutil"
"github.com/prysmaticlabs/prysm/v4/api/server/structs"
"github.com/prysmaticlabs/prysm/v4/beacon-chain/core/helpers"
"github.com/prysmaticlabs/prysm/v4/beacon-chain/rpc/eth/shared"
"github.com/prysmaticlabs/prysm/v4/config/params"
@@ -57,9 +58,9 @@ func (s *Server) GetWeakSubjectivity(w http.ResponseWriter, r *http.Request) {
stateRoot := cb.Block().StateRoot()
log.Printf("Weak subjectivity checkpoint reported as epoch=%d, block root=%#x, state root=%#x", wsEpoch, cbr, stateRoot)
resp := &GetWeakSubjectivityResponse{
Data: &WeakSubjectivityData{
WsCheckpoint: &shared.Checkpoint{
resp := &structs.GetWeakSubjectivityResponse{
Data: &structs.WeakSubjectivityData{
WsCheckpoint: &structs.Checkpoint{
Epoch: strconv.FormatUint(uint64(wsEpoch), 10),
Root: hexutil.Encode(cbr[:]),
},

View File

@@ -1,12 +0,0 @@
package beacon
import "github.com/prysmaticlabs/prysm/v4/beacon-chain/rpc/eth/shared"
type GetWeakSubjectivityResponse struct {
Data *WeakSubjectivityData `json:"data"`
}
type WeakSubjectivityData struct {
WsCheckpoint *shared.Checkpoint `json:"ws_checkpoint"`
StateRoot string `json:"state_root"`
}

View File

@@ -5,11 +5,11 @@ go_library(
srcs = [
"handlers.go",
"server.go",
"structs.go",
],
importpath = "github.com/prysmaticlabs/prysm/v4/beacon-chain/rpc/prysm/node",
visibility = ["//beacon-chain:__subpackages__"],
deps = [
"//api/server/structs:go_default_library",
"//beacon-chain/blockchain:go_default_library",
"//beacon-chain/db:go_default_library",
"//beacon-chain/execution:go_default_library",
@@ -28,12 +28,10 @@ go_library(
go_test(
name = "go_default_test",
srcs = [
"handlers_test.go",
"server_test.go",
],
srcs = ["handlers_test.go"],
embed = [":go_default_library"],
deps = [
"//api/server/structs:go_default_library",
"//beacon-chain/p2p:go_default_library",
"//beacon-chain/p2p/peers:go_default_library",
"//beacon-chain/p2p/testing:go_default_library",

View File

@@ -9,6 +9,7 @@ import (
corenet "github.com/libp2p/go-libp2p/core/network"
"github.com/libp2p/go-libp2p/core/peer"
"github.com/pkg/errors"
"github.com/prysmaticlabs/prysm/v4/api/server/structs"
"github.com/prysmaticlabs/prysm/v4/beacon-chain/p2p"
"github.com/prysmaticlabs/prysm/v4/beacon-chain/p2p/peers"
"github.com/prysmaticlabs/prysm/v4/beacon-chain/p2p/peers/peerdata"
@@ -24,7 +25,7 @@ func (s *Server) ListTrustedPeer(w http.ResponseWriter, r *http.Request) {
peerStatus := s.PeersFetcher.Peers()
allIds := s.PeersFetcher.Peers().GetTrustedPeers()
allPeers := make([]*Peer, 0, len(allIds))
allPeers := make([]*structs.Peer, 0, len(allIds))
for _, id := range allIds {
p, err := httpPeerInfo(peerStatus, id)
if err != nil {
@@ -37,8 +38,8 @@ func (s *Server) ListTrustedPeer(w http.ResponseWriter, r *http.Request) {
}
// peers added into trusted set but never connected should also be listed
if p == nil {
p = &Peer{
PeerID: id.String(),
p = &structs.Peer{
PeerId: id.String(),
Enr: "",
LastSeenP2PAddress: "",
State: eth.ConnectionState(corenet.NotConnected).String(),
@@ -47,7 +48,7 @@ func (s *Server) ListTrustedPeer(w http.ResponseWriter, r *http.Request) {
}
allPeers = append(allPeers, p)
}
response := &PeersResponse{Peers: allPeers}
response := &structs.PeersResponse{Peers: allPeers}
httputil.WriteJson(w, response)
}
@@ -65,7 +66,7 @@ func (s *Server) AddTrustedPeer(w http.ResponseWriter, r *http.Request) {
httputil.WriteError(w, errJson)
return
}
var addrRequest *AddrRequest
var addrRequest *structs.AddrRequest
err = json.Unmarshal(body, &addrRequest)
if err != nil {
errJson := &httputil.DefaultJsonError{
@@ -130,7 +131,7 @@ func (s *Server) RemoveTrustedPeer(w http.ResponseWriter, r *http.Request) {
// httpPeerInfo does the same thing as peerInfo function in node.go but returns the
// http peer response.
func httpPeerInfo(peerStatus *peers.Status, id peer.ID) (*Peer, error) {
func httpPeerInfo(peerStatus *peers.Status, id peer.ID) (*structs.Peer, error) {
enr, err := peerStatus.ENR(id)
if err != nil {
if errors.Is(err, peerdata.ErrPeerUnknown) {
@@ -171,8 +172,8 @@ func httpPeerInfo(peerStatus *peers.Status, id peer.ID) (*Peer, error) {
}
v1ConnState := eth.ConnectionState(connectionState).String()
v1PeerDirection := eth.PeerDirection(direction).String()
p := Peer{
PeerID: id.String(),
p := structs.Peer{
PeerId: id.String(),
State: v1ConnState,
Direction: v1PeerDirection,
}

View File

@@ -14,6 +14,7 @@ import (
"github.com/libp2p/go-libp2p/core/peer"
libp2ptest "github.com/libp2p/go-libp2p/p2p/host/peerstore/test"
ma "github.com/multiformats/go-multiaddr"
"github.com/prysmaticlabs/prysm/v4/api/server/structs"
"github.com/prysmaticlabs/prysm/v4/beacon-chain/p2p"
"github.com/prysmaticlabs/prysm/v4/beacon-chain/p2p/peers"
mockp2p "github.com/prysmaticlabs/prysm/v4/beacon-chain/p2p/testing"
@@ -84,14 +85,14 @@ func TestListTrustedPeer(t *testing.T) {
writer.Body = &bytes.Buffer{}
s.ListTrustedPeer(writer, request)
assert.Equal(t, http.StatusOK, writer.Code)
resp := &PeersResponse{}
resp := &structs.PeersResponse{}
require.NoError(t, json.Unmarshal(writer.Body.Bytes(), resp))
peers := resp.Peers
// assert number of trusted peer is right
assert.Equal(t, 9, len(peers))
for i := 0; i < 9; i++ {
pid, err := peer.Decode(peers[i].PeerID)
pid, err := peer.Decode(peers[i].PeerId)
require.NoError(t, err)
if pid == ids[8] {
assert.Equal(t, "", peers[i].Enr)
@@ -151,7 +152,7 @@ func TestListTrustedPeers_NoPeersReturnsEmptyArray(t *testing.T) {
writer.Body = &bytes.Buffer{}
s.ListTrustedPeer(writer, request)
assert.Equal(t, http.StatusOK, writer.Code)
resp := &PeersResponse{}
resp := &structs.PeersResponse{}
require.NoError(t, json.Unmarshal(writer.Body.Bytes(), resp))
peers := resp.Peers
assert.Equal(t, 0, len(peers))
@@ -163,7 +164,7 @@ func TestAddTrustedPeer(t *testing.T) {
s := Server{PeersFetcher: peerFetcher}
url := "http://anything.is.fine"
addr := &AddrRequest{
addr := &structs.AddrRequest{
Addr: "/ip4/127.0.0.1/tcp/30303/p2p/16Uiu2HAm1n583t4huDMMqEUUBuQs6bLts21mxCfX3tiqu9JfHvRJ",
}
addrJson, err := json.Marshal(addr)
@@ -201,7 +202,7 @@ func TestAddTrustedPeer_BadAddress(t *testing.T) {
s := Server{PeersFetcher: peerFetcher}
url := "http://anything.is.fine"
addr := &AddrRequest{
addr := &structs.AddrRequest{
Addr: "anything/but/not/an/address",
}
addrJson, err := json.Marshal(addr)

Some files were not shown because too many files have changed in this diff Show More