Compare commits

...

42 Commits

Author SHA1 Message Date
james-prysm
9470fc6e95 fixing beacon 2025-04-03 16:15:56 -05:00
james-prysm
e88b611aeb fixing grpc issue 2025-04-03 15:26:29 -05:00
james-prysm
6168cdc135 merging apiutil and httputil 2025-04-03 15:20:04 -05:00
james-prysm
3cbdb2f333 Merge branch 'develop' into migrate-json-rest-handler 2025-04-03 15:17:55 -05:00
james-prysm
fe2fd9fe67 wip 2025-04-03 15:14:14 -05:00
james-prysm
6c1f064ac1 init 2025-04-03 14:49:50 -05:00
james-prysm
4a1c627f6f migrates some helper functions from beacon API to apiutil (#15125)
* migration and changelog

* missed valid root

* removing unneeded test, more optimization

* adding strict dependency

* linting

* fixing 1 more test

* bastin's suggestion
2025-04-03 19:48:26 +00:00
Nishant Das
0c2464c497 Handle Consolidation Processing Edge Case (#15122)
* Clean it up

* Add regression test case

* changelog
2025-04-03 16:07:33 +00:00
james-prysm
2cfc204e9a removed redundant mock validator and replaced with test util one (#15111) 2025-04-02 21:17:20 +00:00
Nishant Das
877d9ee948 Revert Execution Requests in E2E (#15119)
* Revert "Disable Execution Request Testing On Mainnet (#15115)"

This reverts commit 70c31949ba.

* Revert "Trigger Execution Requests In E2E (#14971)"

This reverts commit e38fdb09a4.

* Changelog
2025-04-02 16:12:35 +00:00
Kaloyan Tanev
785fefa3f1 Do not cache slot committee aggregations for DVs (#15110)
* Do not cache slot committee for DV agggregations

* Add changelog

---------

Co-authored-by: Radosław Kapka <rkapka@wp.pl>
2025-04-02 15:54:47 +00:00
kevincatty
0c22d91a55 fix: remove duplicate WithBlobStorage in options initialization (#15036)
Signed-off-by: kevincatty <zhanshanmao@outlook.com>
Co-authored-by: Radosław Kapka <rkapka@wp.pl>
2025-04-02 15:25:00 +00:00
NikolaiKryshnev
fb60456116 Improved README structure and visual presentation (#14860)
Co-authored-by: Radosław Kapka <rkapka@wp.pl>
2025-04-02 15:23:10 +00:00
jinjiadu
be56711892 fix: fix slice init length (#14407)
Signed-off-by: jinjiadu <jinjiadu@aliyun.com>
Co-authored-by: Radosław Kapka <rkapka@wp.pl>
2025-04-02 15:21:26 +00:00
kasey
96f1ebf706 more efficient ancestry db queries, stategen (#15063)
Co-authored-by: Kasey <kasey@users.noreply.github.com>
2025-04-01 20:16:58 +00:00
John
bdb12c7d2f fix: use io.ReadFull instead of stream.Read (#15089) 2025-04-01 19:23:04 +00:00
LesCyber
83cf0f8658 refactor: use errors.New to replace fmt.Errorf with no parameters (#15007)
Signed-off-by: LesCyber <andi4cing@gmail.com>
2025-04-01 19:03:16 +00:00
VolodymyrBg
762594a368 feat(proposer): add gas limit range warnings (#15078)
* feat(proposer): add gas limit range warnings

* Update config/proposer/loader/loader.go

Co-authored-by: Preston Van Loon <preston@prysmaticlabs.com>

* Update config/proposer/loader/loader.go

Co-authored-by: Preston Van Loon <preston@prysmaticlabs.com>

* Create volodymyrbg_gas_limit_warnings.md

---------

Co-authored-by: Preston Van Loon <preston@prysmaticlabs.com>
2025-04-01 19:00:21 +00:00
kilavvy
c1fc812a38 Fix typos in test code (#14991)
* Update keymanager_test.go

* Update fork_test.go

* Update README.md

* Update README.md
2025-04-01 18:31:59 +00:00
riyueguang
340935af9c refactor: use the built-in min to simplify the code (#15091)
Signed-off-by: riyueguang <rustruby@outlook.com>
2025-04-01 17:57:22 +00:00
kasey
17d0082c5c cleanup block indices for missing blocks (#15040)
Co-authored-by: Kasey Kirkham <kasey@users.noreply.github.com>
2025-04-01 17:54:35 +00:00
terence
e998b5ec97 Use latest state to pack attestation (#15113)
* Use latest state to pack attestation

* Add a test to make sure it would have failed when using head state instead of latest state
2025-04-01 15:31:45 +00:00
james-prysm
5d0eb3168c small optimization (#15116) 2025-04-01 14:55:29 +00:00
terence
e0c2aa71d4 Update spec tests to beta 4 (#15114)
* Update spec tests to beta 4

* Change log to ignored
2025-04-01 14:32:57 +00:00
Nishant Das
70c31949ba Disable Execution Request Testing On Mainnet (#15115)
* DisableOnMainnet

* Changelog
2025-04-01 10:38:05 +00:00
Nishant Das
e38fdb09a4 Trigger Execution Requests In E2E (#14971)
* Trigger Consolidation

* Finally have it working

* Fix Build

* Revert Change

* Fix Context

* Finally have consolidations working

* Get Evaluator Working

* Get Withdrawals Working

* Changelog

* Finally Passes

* New line

* Try again

* fmt

* fmt

* Fix Test
2025-04-01 06:49:51 +00:00
james-prysm
a50e981c74 removing redundant loop in computeOnChainAggregate (#15108)
* removing redundant loop

* Update beacon-chain/rpc/prysm/v1alpha1/validator/proposer_attestations_electra.go

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

* removing unused import

* replacing with more used function

* resolving Unsafe cast from uint64 to int error

---------

Co-authored-by: Radosław Kapka <rkapka@wp.pl>
2025-03-31 21:22:47 +00:00
Bastin
8be205cf3d Use fieldparams.RootLength instead of local variable in p2p types.go (#15106)
* use fieldparams.RootLength instead of local var

* gazelle fix
2025-03-31 12:42:07 +00:00
kasey
1b65e00096 refactor state-by-root test to table-driven (#15087)
Co-authored-by: Kasey Kirkham <kasey@users.noreply.github.com>
2025-03-28 23:34:34 +00:00
james-prysm
e3fb4e86ec validator client initialization cleanup (#15080)
* cleanup

* fixing optimal sort order for struct

* reverting clictx change based on kasey's feedback

* adding in fix for old trace file flag

* more cleanup for clarity

* optimizing if statement check and fixing wallet open on web enable

* optimizing if statement check and fixing wallet open on web enable

* some more cleanup and bug fix on open wallet

* reverting debug.go changes will handle in a separate PR

* removing useless comment

* changing useWeb to enableAPI

* fixing tests and linting

* manu feedback and one optimization removing auth token check

* gaz
2025-03-28 14:03:42 +00:00
terence
70aaad1904 Add more tests to process pending deposits (#15099) 2025-03-27 14:16:41 +00:00
Radosław Kapka
e42611ec72 Allow hex strings in /eth/v1/beacon/states/{state_id}/root endpoint (#15098)
* Allow hex strings in `/eth/v1/beacon/states/{state_id}/root` endpoint

* changelog <3

* remove redundant conversion

* use `bytesutil.IsHex`
2025-03-27 14:13:57 +00:00
Bastin
a3e61275a3 Add light client types to spectest (#15097)
* add light client types to spectest

* changelog entry

* remove lightclientSnapshot from tests
2025-03-26 17:44:30 +00:00
terence
e82f9ccca3 Proposer: change attestation sorting to reward numerator (#15093)
* Change proposer block's sorting algo to proposer reward numerator

* Feedback

* Comments

* Add a cache for attestation reward numerator
2025-03-26 16:21:41 +00:00
Bastin
38a6a7a4ea Add SSZ support for light client updates by range API (#15082)
* create ssz payload

* remove unused function

* remove access to state

* gazelle fix

* fix ssz size for electra finality update

* fix fork digest version problem

* fix chunk size

* fix fork version

* fix fork version

* add tests

* add changelog entry

* add PR link in changelog entry

* fix lint error

* Update beacon-chain/rpc/eth/light-client/handlers.go

Co-authored-by: Preston Van Loon <pvanloon@offchainlabs.com>

* check for context error

* send response in chunks

* remove content disposition header

---------

Co-authored-by: Preston Van Loon <pvanloon@offchainlabs.com>
2025-03-26 15:06:03 +00:00
Bastin
1295c987e8 Remove content disposition header from httputil.WriteSSZ (#15092)
* remove content disposition header from httputil.WriteSSZ

* fix changelog

* fix newly added calls to WriteSSZ
2025-03-26 14:17:19 +00:00
Radosław Kapka
6a27c41aad Implement validator identities Beacon API endpoint (#15086)
* implementation

* tests

* changelog <3

* linter fix

* test fix
2025-03-25 16:49:35 +00:00
Radosław Kapka
98b13ea144 Update changelog for v5.3.2 release (#15096)
* Changelog for v5.3.2

* add header section

* fragment file
2025-03-25 16:38:29 +00:00
james-prysm
c735ed2e32 Remove use of committee list from validator client (#15039)
* wip

* fixing unit tests

* changing is aggregator function

* wip

* fully removing the use of committee from validator client, adding a wrapper type for duties

* fixing tests

* fixing linting

* fixing more tests

* changelog

* adding some more tests

* Update proto/prysm/v1alpha1/validator.go

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

* radek's feedback

* removing accidently checked in

---------

Co-authored-by: Radosław Kapka <rkapka@wp.pl>
2025-03-25 16:25:42 +00:00
Potuz
bd17779231 Use headstate to validate canonical attestations for old targets (#15095)
* Use headstate to validate canonical attestations for old targets

* Update beacon-chain/blockchain/process_attestation_helpers.go

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

---------

Co-authored-by: Radosław Kapka <rkapka@wp.pl>
2025-03-25 13:36:47 +00:00
james-prysm
e08ed0d823 Deprecate broken and unused debug flags in favor of --pprof (#15083)
* deprecating the trace and cpuprofile flags in favor of pprof

* gaz

* fixing change log title

* added hidden tags
2025-03-24 19:30:32 +00:00
xinhangzhou
2b4d8a09ff refactor: use maps.Copy for cleaner map handling (#15090)
Signed-off-by: xinhangzhou <shuangcui@aliyun.com>
2025-03-24 19:23:10 +00:00
340 changed files with 5640 additions and 4007 deletions

View File

@@ -4,6 +4,43 @@ All notable changes to this project will be documented in this file.
The format is based on Keep a Changelog, and this project adheres to Semantic Versioning.
## [v5.3.2](https://github.com/prysmaticlabs/prysm/compare/v5.3.1...v5.3.2) - 2025-03-25
This release introduces support for the `Hoodi` testnet.
Release highlights:
- Ability to run the node on the `Hoodi` tesnet. See https://blog.ethereum.org/2025/03/18/hoodi-holesky for more information about `Hoodi`.
- A new feature that allows treat certain blocks as invalid. This is especially useful when the network is split, allowing the node to discontinue following unwanted forks.
Testnet operators are required to update to this release. Without this release you will be unable to run the node on the `Hoodi` testnet.
Mainnet operators are recommended to update to this release at their regular cadence.
### Added
- enable SSZ for builder API calls. [[PR]](https://github.com/prysmaticlabs/prysm/pull/14976)
- Add Hoodi testnet flag `--hoodi` to specify Hoodi testnet config and bootnodes. [[PR]](https://github.com/prysmaticlabs/prysm/pull/15057)
- block_gossip topic support to the beacon api event stream. [[PR]](https://github.com/prysmaticlabs/prysm/pull/15038)
- Added a static analyzer to discourage use of panic() in Prysm. [[PR]](https://github.com/prysmaticlabs/prysm/pull/15075)
- Add a feature flag `--blacklist-roots` to allow the node to specify blocks that will be treated as invalid. [[PR]](https://github.com/prysmaticlabs/prysm/pull/15030)
### Changed
- changed request object for `POST /eth/v1/beacon/states/head/validators` to omit the field if empty for satisfying other clients. [[PR]](https://github.com/prysmaticlabs/prysm/pull/15031)
- Update spec test to v1.5.0-beta.3. [[PR]](https://github.com/prysmaticlabs/prysm/pull/15050)
- Update Gossip and RPC message limits to comply with the spec. [[PR]](https://github.com/prysmaticlabs/prysm/pull/14799)
- Return 404 instead of 500 from API when when a blob for a requested index is not found. [[PR]](https://github.com/prysmaticlabs/prysm/pull/14845)
- Save Electra orphaned attestations into attestations pool's block attestations. [[PR]](https://github.com/prysmaticlabs/prysm/pull/15060)
- Removed redundant string conversion in `BeaconDbStater.State` to improve code clarity and maintainability. [[PR]](https://github.com/prysmaticlabs/prysm/pull/15081)
### Fixed
- Update seen unaggregated att cache to properly handle Electra attestations. [[PR]](https://github.com/prysmaticlabs/prysm/pull/15034)
- cosmetic fix for calling `/prysm/validators/performance` when connecting to non prysm beacon nodes and removing the 404 error log. [[PR]](https://github.com/prysmaticlabs/prysm/pull/15062)
- Tracked validator cache: Make sure no to loose the reference. [[PR]](https://github.com/prysmaticlabs/prysm/pull/15077)
- Fixed proposing at genesis when starting post Bellatrix. [[PR]](https://github.com/prysmaticlabs/prysm/pull/15084)
## [v5.3.1](https://github.com/prysmaticlabs/prysm/compare/v5.3.0...v5.3.1) - 2025-03-13
This release is packed with critical fixes for **Electra** and some important fixes for mainnet too.
@@ -21,7 +58,7 @@ Known issues in **Electra**:
Testnet operators are strongly encouraged to update to this release. There are many fixes and improvements from the Holesky upgrade incident.
Mainner operators are recommended to update to this release at their regular cadence.
Mainnet operators are recommended to update to this release at their regular cadence.
### Added
@@ -3218,4 +3255,4 @@ There are no security updates in this release.
# Older than v2.0.0
For changelog history for releases older than v2.0.0, please refer to https://github.com/prysmaticlabs/prysm/releases
For changelog history for releases older than v2.0.0, please refer to https://github.com/prysmaticlabs/prysm/releases

View File

@@ -1,5 +1,7 @@
# Prysm: An Ethereum Consensus Implementation Written in Go
<h1 align="left">Prysm: An Ethereum Consensus Implementation Written in Go</h1>
<div align="left">
[![Build status](https://badge.buildkite.com/b555891daf3614bae4284dcf365b2340cefc0089839526f096.svg?branch=master)](https://buildkite.com/prysmatic-labs/prysm)
[![Go Report Card](https://goreportcard.com/badge/github.com/prysmaticlabs/prysm)](https://goreportcard.com/report/github.com/prysmaticlabs/prysm)
[![Consensus_Spec_Version 1.4.0](https://img.shields.io/badge/Consensus%20Spec%20Version-v1.4.0-blue.svg)](https://github.com/ethereum/consensus-specs/tree/v1.4.0)
@@ -7,31 +9,60 @@
[![Discord](https://user-images.githubusercontent.com/7288322/34471967-1df7808a-efbb-11e7-9088-ed0b04151291.png)](https://discord.gg/prysmaticlabs)
[![GitPOAP Badge](https://public-api.gitpoap.io/v1/repo/prysmaticlabs/prysm/badge)](https://www.gitpoap.io/gh/prysmaticlabs/prysm)
This is the core repository for Prysm, a [Golang](https://golang.org/) implementation of the [Ethereum Consensus](https://ethereum.org/en/developers/docs/consensus-mechanisms/#proof-of-stake) [specification](https://github.com/ethereum/consensus-specs), developed by [Offchain Labs](https://www.offchainlabs.com). See the [Changelog](https://github.com/prysmaticlabs/prysm/releases) for details of the latest releases and upcoming breaking changes.
</div>
### Getting Started
---
A detailed set of installation and usage instructions as well as breakdowns of each individual component are available in the [official documentation portal](https://docs.prylabs.network). If you still have questions, feel free to stop by our [Discord](https://discord.gg/prysmaticlabs).
## 📖 Overview
### Staking on Mainnet
This is the core repository for Prysm, a [Golang](https://golang.org/) implementation of the [Ethereum Consensus](https://ethereum.org/en/developers/docs/consensus-mechanisms/#proof-of-stake) [specification](https://github.com/ethereum/consensus-specs), developed by [Offchain Labs](https://www.offchainlabs.com).
To participate in staking, you can join the [official eth2 launchpad](https://launchpad.ethereum.org). The launchpad is the only recommended way to become a validator on mainnet. You can explore validator rewards/penalties via Bitfly's block explorer: [beaconcha.in](https://beaconcha.in), and follow the latest blocks added to the chain on [beaconscan](https://beaconscan.com).
See the [Changelog](https://github.com/prysmaticlabs/prysm/releases) for details of the latest releases and upcoming breaking changes.
---
## 🚀 Getting Started
A detailed set of installation and usage instructions as well as breakdowns of each individual component are available in the **[official documentation portal](https://docs.prylabs.network)**.
💬 **Need help?** Join our **[Discord Community](https://discord.gg/prysmaticlabs)** for support.
---
## 🏆 Staking on Mainnet
To participate in staking, you can join the **[official Ethereum launchpad](https://launchpad.ethereum.org)**. The launchpad is the **only recommended** way to become a validator on mainnet.
🔍 Explore validator rewards/penalties:
- **[beaconcha.in](https://beaconcha.in)**
- **[beaconscan](https://beaconscan.com)**
---
## 🤝 Contributing
### 🔥 Branches
## Contributing
### Branches
Prysm maintains two permanent branches:
* [master](https://github.com/prysmaticlabs/prysm/tree/master): This points to the latest stable release. It is ideal for most users.
* [develop](https://github.com/prysmaticlabs/prysm/tree/develop): This is used for development, it contains the latest PRs. Developers should base their PRs on this branch.
- **[`master`](https://github.com/prysmaticlabs/prysm/tree/master)** - This points to the latest stable release. It is ideal for most users.
- **[`develop`](https://github.com/prysmaticlabs/prysm/tree/develop)** - This is used for development and contains the latest PRs. Developers should base their PRs on this branch.
### Guide
Want to get involved? Check out our [Contribution Guide](https://docs.prylabs.network/docs/contribute/contribution-guidelines/) to learn more!
### 🛠 Contribution Guide
## License
Want to get involved? Check out our **[Contribution Guide](https://docs.prylabs.network/docs/contribute/contribution-guidelines/)** to learn more!
[GNU General Public License v3.0](https://www.gnu.org/licenses/gpl-3.0.en.html)
---
## Legal Disclaimer
## 📜 License
[Terms of Use](/TERMS_OF_SERVICE.md)
[![License: GPL v3](https://img.shields.io/badge/License-GPLv3-blue.svg)](https://www.gnu.org/licenses/gpl-3.0.en.html)
This project is licensed under the **GNU General Public License v3.0**.
---
## ⚖️ Legal Disclaimer
📜 [Terms of Use](/TERMS_OF_SERVICE.md)

View File

@@ -255,7 +255,7 @@ filegroup(
url = "https://github.com/ethereum/EIPs/archive/5480440fe51742ed23342b68cf106cefd427e39d.tar.gz",
)
consensus_spec_version = "v1.5.0-beta.3"
consensus_spec_version = "v1.5.0-beta.4"
bls_test_version = "v0.1.1"
@@ -271,7 +271,7 @@ filegroup(
visibility = ["//visibility:public"],
)
""",
integrity = "sha256-z+j0BEJuXMBKbGL+7jq35zddzZMW1je8/uvTz5+wboQ=",
integrity = "sha256-QG0NUqaCvP5lKaKKwF/fmeICZVjONMlb7EE+MtYl0C0=",
url = "https://github.com/ethereum/consensus-spec-tests/releases/download/%s/general.tar.gz" % consensus_spec_version,
)
@@ -287,7 +287,7 @@ filegroup(
visibility = ["//visibility:public"],
)
""",
integrity = "sha256-5/YUOXH65CmM1plZ8twJ3BQxwM51jgSpOB8/VSBI19k=",
integrity = "sha256-8NQngTSSqzW/j3tOUi3r5h+94ChRbLNWTt7BOGqr4+E=",
url = "https://github.com/ethereum/consensus-spec-tests/releases/download/%s/minimal.tar.gz" % consensus_spec_version,
)
@@ -303,7 +303,7 @@ filegroup(
visibility = ["//visibility:public"],
)
""",
integrity = "sha256-iZ2eNhwRnbxrjR+5gMBUYakaCXicvPChwFUkZtQUbbI=",
integrity = "sha256-gFqxbaBnJ7dtdoj0zFbVrtlHv/bLNuWjrTHkyCAjFjI=",
url = "https://github.com/ethereum/consensus-spec-tests/releases/download/%s/mainnet.tar.gz" % consensus_spec_version,
)
@@ -318,7 +318,7 @@ filegroup(
visibility = ["//visibility:public"],
)
""",
integrity = "sha256-inAXV7xNM5J1aUdP7JNXFO2iFFZ7dth38Ji+mJW50Ts=",
integrity = "sha256-9paalF0POULpP2ga+4ouHSETKYrWNCUCZoJHPuFw06E=",
strip_prefix = "consensus-specs-" + consensus_spec_version[1:],
url = "https://github.com/ethereum/consensus-specs/archive/refs/tags/%s.tar.gz" % consensus_spec_version,
)

View File

@@ -2,11 +2,7 @@ load("@prysm//tools/go:def.bzl", "go_library", "go_test")
go_library(
name = "go_default_library",
srcs = [
"constants.go",
"headers.go",
"jwt.go",
],
srcs = ["jwt.go"],
importpath = "github.com/prysmaticlabs/prysm/v5/api",
visibility = ["//visibility:public"],
deps = [

View File

@@ -4,17 +4,29 @@ go_library(
name = "go_default_library",
srcs = [
"client.go",
"errors.go",
"json_rest_handler.go",
"options.go",
],
importpath = "github.com/prysmaticlabs/prysm/v5/api/client",
visibility = ["//visibility:public"],
deps = ["@com_github_pkg_errors//:go_default_library"],
deps = [
"//api/httputil:go_default_library",
"@com_github_pkg_errors//:go_default_library",
],
)
go_test(
name = "go_default_test",
srcs = ["client_test.go"],
srcs = [
"client_test.go",
"json_rest_handler_test.go",
],
embed = [":go_default_library"],
deps = ["//testing/require:go_default_library"],
deps = [
"//api/httputil:go_default_library",
"//api/server/structs:go_default_library",
"//testing/assert:go_default_library",
"//testing/require:go_default_library",
"@com_github_pkg_errors//:go_default_library",
],
)

View File

@@ -0,0 +1,9 @@
load("@prysm//tools/go:def.bzl", "go_library")
go_library(
name = "go_default_library",
srcs = ["json_rest_handler_mock.go"],
importpath = "github.com/prysmaticlabs/prysm/v5/api/client/Mock",
visibility = ["//visibility:public"],
deps = ["@org_uber_go_mock//gomock:go_default_library"],
)

View File

@@ -7,7 +7,7 @@
//
// Package mock is a generated GoMock package.
package mock
package Mock
import (
bytes "bytes"

View File

@@ -14,6 +14,7 @@ go_library(
deps = [
"//api/client:go_default_library",
"//api/client/beacon/iface:go_default_library",
"//api/httputil:go_default_library",
"//api/server:go_default_library",
"//api/server/structs:go_default_library",
"//consensus-types/primitives:go_default_library",
@@ -34,8 +35,8 @@ go_test(
],
embed = [":go_default_library"],
deps = [
"//api/client:go_default_library",
"//api/client/beacon/testing:go_default_library",
"//api/httputil:go_default_library",
"//testing/require:go_default_library",
"@org_uber_go_mock//gomock:go_default_library",
],

View File

@@ -15,6 +15,7 @@ import (
"github.com/ethereum/go-ethereum/common/hexutil"
"github.com/pkg/errors"
"github.com/prysmaticlabs/prysm/v5/api/client"
"github.com/prysmaticlabs/prysm/v5/api/httputil"
"github.com/prysmaticlabs/prysm/v5/api/server"
"github.com/prysmaticlabs/prysm/v5/api/server/structs"
"github.com/prysmaticlabs/prysm/v5/consensus-types/primitives"
@@ -184,7 +185,7 @@ var versionRE = regexp.MustCompile(`^(\w+)/(v\d+\.\d+\.\d+[-a-zA-Z0-9]*)\s*/?(.*
func parseNodeVersion(v string) (*NodeVersion, error) {
groups := versionRE.FindStringSubmatch(v)
if len(groups) != 4 {
return nil, errors.Wrapf(client.ErrInvalidNodeVersion, "could not be parsed: %s", v)
return nil, errors.Wrapf(httputil.ErrInvalidNodeVersion, "could not be parsed: %s", v)
}
return &NodeVersion{
implementation: groups[1],

View File

@@ -4,7 +4,7 @@ import (
"net/url"
"testing"
"github.com/prysmaticlabs/prysm/v5/api/client"
"github.com/prysmaticlabs/prysm/v5/api/httputil"
"github.com/prysmaticlabs/prysm/v5/testing/require"
)
@@ -18,17 +18,17 @@ func TestParseNodeVersion(t *testing.T) {
{
name: "empty string",
v: "",
err: client.ErrInvalidNodeVersion,
err: httputil.ErrInvalidNodeVersion,
},
{
name: "Prysm as the version string",
v: "Prysm",
err: client.ErrInvalidNodeVersion,
err: httputil.ErrInvalidNodeVersion,
},
{
name: "semver only",
v: "v2.0.6",
err: client.ErrInvalidNodeVersion,
err: httputil.ErrInvalidNodeVersion,
},
{
name: "complete version",
@@ -92,7 +92,7 @@ func TestValidHostname(t *testing.T) {
{
name: "hostname without port",
hostArg: "mydomain.org",
err: client.ErrMalformedHostname,
err: httputil.ErrMalformedHostname,
},
{
name: "hostname with port",

View File

@@ -11,8 +11,7 @@ go_library(
importpath = "github.com/prysmaticlabs/prysm/v5/api/client/builder",
visibility = ["//visibility:public"],
deps = [
"//api:go_default_library",
"//api/client:go_default_library",
"//api/httputil:go_default_library",
"//api/server:go_default_library",
"//api/server/structs:go_default_library",
"//config/fieldparams:go_default_library",
@@ -47,7 +46,7 @@ go_test(
data = glob(["testdata/**"]),
embed = [":go_default_library"],
deps = [
"//api:go_default_library",
"//api/httputil:go_default_library",
"//api/server/structs:go_default_library",
"//config/fieldparams:go_default_library",
"//config/params:go_default_library",

View File

@@ -13,8 +13,7 @@ import (
"text/template"
"github.com/pkg/errors"
"github.com/prysmaticlabs/prysm/v5/api"
"github.com/prysmaticlabs/prysm/v5/api/client"
"github.com/prysmaticlabs/prysm/v5/api/httputil"
"github.com/prysmaticlabs/prysm/v5/api/server/structs"
"github.com/prysmaticlabs/prysm/v5/config/params"
"github.com/prysmaticlabs/prysm/v5/consensus-types/blocks"
@@ -191,7 +190,7 @@ func (c *Client) do(ctx context.Context, method string, path string, body io.Rea
err = non200Err(r)
return
}
res, err = io.ReadAll(io.LimitReader(r.Body, client.MaxBodySize))
res, err = io.ReadAll(io.LimitReader(r.Body, httputil.MaxBodySize))
if err != nil {
err = errors.Wrap(err, "error reading http response body from builder server")
return
@@ -229,11 +228,11 @@ func (c *Client) GetHeader(ctx context.Context, slot primitives.Slot, parentHash
var getOpts reqOption
if c.sszEnabled {
getOpts = func(r *http.Request) {
r.Header.Set("Accept", api.OctetStreamMediaType)
r.Header.Set("Accept", httputil.OctetStreamMediaType)
}
} else {
getOpts = func(r *http.Request) {
r.Header.Set("Accept", api.JsonMediaType)
r.Header.Set("Accept", httputil.JsonMediaType)
}
}
data, header, err := c.do(ctx, http.MethodGet, path, nil, getOpts)
@@ -256,8 +255,8 @@ func (c *Client) GetHeader(ctx context.Context, slot primitives.Slot, parentHash
func (c *Client) parseHeaderResponse(data []byte, header http.Header) (SignedBid, error) {
var versionHeader string
if c.sszEnabled || header.Get(api.VersionHeader) != "" {
versionHeader = header.Get(api.VersionHeader)
if c.sszEnabled || header.Get(httputil.VersionHeader) != "" {
versionHeader = header.Get(httputil.VersionHeader)
} else {
// If we don't have a version header, attempt to parse JSON for version
v := &VersionResponse{}
@@ -387,8 +386,8 @@ func (c *Client) RegisterValidator(ctx context.Context, svr []*ethpb.SignedValid
)
if c.sszEnabled {
postOpts = func(r *http.Request) {
r.Header.Set("Content-Type", api.OctetStreamMediaType)
r.Header.Set("Accept", api.OctetStreamMediaType)
r.Header.Set("Content-Type", httputil.OctetStreamMediaType)
r.Header.Set("Accept", httputil.OctetStreamMediaType)
}
body, err = sszValidatorRegisterRequest(svr)
if err != nil {
@@ -398,8 +397,8 @@ func (c *Client) RegisterValidator(ctx context.Context, svr []*ethpb.SignedValid
}
} else {
postOpts = func(r *http.Request) {
r.Header.Set("Content-Type", api.JsonMediaType)
r.Header.Set("Accept", api.JsonMediaType)
r.Header.Set("Content-Type", httputil.JsonMediaType)
r.Header.Set("Accept", httputil.JsonMediaType)
}
body, err = jsonValidatorRegisterRequest(svr)
if err != nil {
@@ -443,7 +442,7 @@ func sszValidatorRegisterRequest(svr []*ethpb.SignedValidatorRegistrationV1) ([]
return ssz, nil
}
var errResponseVersionMismatch = errors.New("builder API response uses a different version than requested in " + api.VersionHeader + " header")
var errResponseVersionMismatch = errors.New("builder API response uses a different version than requested in " + httputil.VersionHeader + " header")
func getVersionsBlockToPayload(blockVersion int) (int, error) {
if blockVersion >= version.Deneb {
@@ -501,7 +500,7 @@ func (c *Client) SubmitBlindedBlock(ctx context.Context, sb interfaces.ReadOnlyS
func (c *Client) checkBlockVersion(respBytes []byte, header http.Header) (int, error) {
var versionHeader string
if c.sszEnabled {
versionHeader = strings.ToLower(header.Get(api.VersionHeader))
versionHeader = strings.ToLower(header.Get(httputil.VersionHeader))
} else {
// fallback to JSON-based version extraction
v := &VersionResponse{}
@@ -531,9 +530,9 @@ func (c *Client) buildBlindedBlockRequest(sb interfaces.ReadOnlySignedBeaconBloc
return nil, nil, errors.Wrap(err, "could not marshal SSZ for blinded block")
}
opt := func(r *http.Request) {
r.Header.Set(api.VersionHeader, version.String(sb.Version()))
r.Header.Set("Content-Type", api.OctetStreamMediaType)
r.Header.Set("Accept", api.OctetStreamMediaType)
r.Header.Set(httputil.VersionHeader, version.String(sb.Version()))
r.Header.Set("Content-Type", httputil.OctetStreamMediaType)
r.Header.Set("Accept", httputil.OctetStreamMediaType)
}
return body, opt, nil
}
@@ -547,9 +546,9 @@ func (c *Client) buildBlindedBlockRequest(sb interfaces.ReadOnlySignedBeaconBloc
return nil, nil, errors.Wrap(err, "error marshaling blinded block to JSON")
}
opt := func(r *http.Request) {
r.Header.Set(api.VersionHeader, version.String(sb.Version()))
r.Header.Set("Content-Type", api.JsonMediaType)
r.Header.Set("Accept", api.JsonMediaType)
r.Header.Set(httputil.VersionHeader, version.String(sb.Version()))
r.Header.Set("Content-Type", httputil.JsonMediaType)
r.Header.Set("Accept", httputil.JsonMediaType)
}
return body, opt, nil
}
@@ -642,14 +641,14 @@ func (c *Client) parseBlindedBlockResponseJSON(
// happy path, and an error with information about the server response body for a non-200 response.
func (c *Client) Status(ctx context.Context) error {
getOpts := func(r *http.Request) {
r.Header.Set("Accept", api.JsonMediaType)
r.Header.Set("Accept", httputil.JsonMediaType)
}
_, _, err := c.do(ctx, http.MethodGet, getStatus, nil, getOpts)
return err
}
func non200Err(response *http.Response) error {
bodyBytes, err := io.ReadAll(io.LimitReader(response.Body, client.MaxErrBodySize))
bodyBytes, err := io.ReadAll(io.LimitReader(response.Body, httputil.MaxErrBodySize))
var errMessage ErrorMessage
var body string
if err != nil {

View File

@@ -11,7 +11,7 @@ import (
"testing"
"github.com/prysmaticlabs/go-bitfield"
"github.com/prysmaticlabs/prysm/v5/api"
"github.com/prysmaticlabs/prysm/v5/api/httputil"
"github.com/prysmaticlabs/prysm/v5/api/server/structs"
"github.com/prysmaticlabs/prysm/v5/config/params"
"github.com/prysmaticlabs/prysm/v5/consensus-types/blocks"
@@ -90,8 +90,8 @@ func TestClient_RegisterValidator(t *testing.T) {
t.Run("JSON success", func(t *testing.T) {
hc := &http.Client{
Transport: roundtrip(func(r *http.Request) (*http.Response, error) {
require.Equal(t, api.JsonMediaType, r.Header.Get("Content-Type"))
require.Equal(t, api.JsonMediaType, r.Header.Get("Accept"))
require.Equal(t, httputil.JsonMediaType, r.Header.Get("Content-Type"))
require.Equal(t, httputil.JsonMediaType, r.Header.Get("Accept"))
body, err := io.ReadAll(r.Body)
defer func() {
require.NoError(t, r.Body.Close())
@@ -125,8 +125,8 @@ func TestClient_RegisterValidator(t *testing.T) {
t.Run("SSZ success", func(t *testing.T) {
hc := &http.Client{
Transport: roundtrip(func(r *http.Request) (*http.Response, error) {
require.Equal(t, api.OctetStreamMediaType, r.Header.Get("Content-Type"))
require.Equal(t, api.OctetStreamMediaType, r.Header.Get("Accept"))
require.Equal(t, httputil.OctetStreamMediaType, r.Header.Get("Content-Type"))
require.Equal(t, httputil.OctetStreamMediaType, r.Header.Get("Accept"))
body, err := io.ReadAll(r.Body)
defer func() {
require.NoError(t, r.Body.Close())
@@ -220,7 +220,7 @@ func TestClient_GetHeader(t *testing.T) {
hc := &http.Client{
Transport: roundtrip(func(r *http.Request) (*http.Response, error) {
require.Equal(t, expectedPath, r.URL.Path)
require.Equal(t, api.JsonMediaType, r.Header.Get("Accept"))
require.Equal(t, httputil.JsonMediaType, r.Header.Get("Accept"))
return &http.Response{
StatusCode: http.StatusOK,
Body: io.NopCloser(bytes.NewBufferString(testExampleHeaderResponse)),
@@ -255,7 +255,7 @@ func TestClient_GetHeader(t *testing.T) {
t.Run("bellatrix ssz", func(t *testing.T) {
hc := &http.Client{
Transport: roundtrip(func(r *http.Request) (*http.Response, error) {
require.Equal(t, api.OctetStreamMediaType, r.Header.Get("Accept"))
require.Equal(t, httputil.OctetStreamMediaType, r.Header.Get("Accept"))
require.Equal(t, expectedPath, r.URL.Path)
epr := &ExecHeaderResponse{}
require.NoError(t, json.Unmarshal([]byte(testExampleHeaderResponse), epr))
@@ -264,7 +264,7 @@ func TestClient_GetHeader(t *testing.T) {
ssz, err := pro.MarshalSSZ()
require.NoError(t, err)
header := http.Header{}
header.Set(api.VersionHeader, "bellatrix")
header.Set(httputil.VersionHeader, "bellatrix")
return &http.Response{
StatusCode: http.StatusOK,
Header: header,
@@ -301,7 +301,7 @@ func TestClient_GetHeader(t *testing.T) {
t.Run("capella", func(t *testing.T) {
hc := &http.Client{
Transport: roundtrip(func(r *http.Request) (*http.Response, error) {
require.Equal(t, api.JsonMediaType, r.Header.Get("Accept"))
require.Equal(t, httputil.JsonMediaType, r.Header.Get("Accept"))
require.Equal(t, expectedPath, r.URL.Path)
return &http.Response{
StatusCode: http.StatusOK,
@@ -333,7 +333,7 @@ func TestClient_GetHeader(t *testing.T) {
t.Run("capella ssz", func(t *testing.T) {
hc := &http.Client{
Transport: roundtrip(func(r *http.Request) (*http.Response, error) {
require.Equal(t, api.OctetStreamMediaType, r.Header.Get("Accept"))
require.Equal(t, httputil.OctetStreamMediaType, r.Header.Get("Accept"))
require.Equal(t, expectedPath, r.URL.Path)
epr := &ExecHeaderResponseCapella{}
require.NoError(t, json.Unmarshal([]byte(testExampleHeaderResponseCapella), epr))
@@ -342,7 +342,7 @@ func TestClient_GetHeader(t *testing.T) {
ssz, err := pro.MarshalSSZ()
require.NoError(t, err)
header := http.Header{}
header.Set(api.VersionHeader, "capella")
header.Set(httputil.VersionHeader, "capella")
return &http.Response{
StatusCode: http.StatusOK,
Header: header,
@@ -375,7 +375,7 @@ func TestClient_GetHeader(t *testing.T) {
t.Run("deneb", func(t *testing.T) {
hc := &http.Client{
Transport: roundtrip(func(r *http.Request) (*http.Response, error) {
require.Equal(t, api.JsonMediaType, r.Header.Get("Accept"))
require.Equal(t, httputil.JsonMediaType, r.Header.Get("Accept"))
require.Equal(t, expectedPath, r.URL.Path)
return &http.Response{
StatusCode: http.StatusOK,
@@ -415,7 +415,7 @@ func TestClient_GetHeader(t *testing.T) {
t.Run("deneb ssz", func(t *testing.T) {
hc := &http.Client{
Transport: roundtrip(func(r *http.Request) (*http.Response, error) {
require.Equal(t, api.OctetStreamMediaType, r.Header.Get("Accept"))
require.Equal(t, httputil.OctetStreamMediaType, r.Header.Get("Accept"))
require.Equal(t, expectedPath, r.URL.Path)
epr := &ExecHeaderResponseDeneb{}
require.NoError(t, json.Unmarshal([]byte(testExampleHeaderResponseDeneb), epr))
@@ -424,7 +424,7 @@ func TestClient_GetHeader(t *testing.T) {
ssz, err := pro.MarshalSSZ()
require.NoError(t, err)
header := http.Header{}
header.Set(api.VersionHeader, "deneb")
header.Set(httputil.VersionHeader, "deneb")
return &http.Response{
StatusCode: http.StatusOK,
Header: header,
@@ -483,7 +483,7 @@ func TestClient_GetHeader(t *testing.T) {
t.Run("electra", func(t *testing.T) {
hc := &http.Client{
Transport: roundtrip(func(r *http.Request) (*http.Response, error) {
require.Equal(t, api.JsonMediaType, r.Header.Get("Accept"))
require.Equal(t, httputil.JsonMediaType, r.Header.Get("Accept"))
require.Equal(t, expectedPath, r.URL.Path)
return &http.Response{
StatusCode: http.StatusOK,
@@ -528,7 +528,7 @@ func TestClient_GetHeader(t *testing.T) {
t.Run("electra ssz", func(t *testing.T) {
hc := &http.Client{
Transport: roundtrip(func(r *http.Request) (*http.Response, error) {
require.Equal(t, api.OctetStreamMediaType, r.Header.Get("Accept"))
require.Equal(t, httputil.OctetStreamMediaType, r.Header.Get("Accept"))
require.Equal(t, expectedPath, r.URL.Path)
epr := &ExecHeaderResponseElectra{}
require.NoError(t, json.Unmarshal([]byte(testExampleHeaderResponseElectra), epr))
@@ -537,7 +537,7 @@ func TestClient_GetHeader(t *testing.T) {
ssz, err := pro.MarshalSSZ()
require.NoError(t, err)
header := http.Header{}
header.Set(api.VersionHeader, "electra")
header.Set(httputil.VersionHeader, "electra")
return &http.Response{
StatusCode: http.StatusOK,
Header: header,
@@ -608,8 +608,8 @@ func TestSubmitBlindedBlock(t *testing.T) {
Transport: roundtrip(func(r *http.Request) (*http.Response, error) {
require.Equal(t, postBlindedBeaconBlockPath, r.URL.Path)
require.Equal(t, "bellatrix", r.Header.Get("Eth-Consensus-Version"))
require.Equal(t, api.JsonMediaType, r.Header.Get("Content-Type"))
require.Equal(t, api.JsonMediaType, r.Header.Get("Accept"))
require.Equal(t, httputil.JsonMediaType, r.Header.Get("Content-Type"))
require.Equal(t, httputil.JsonMediaType, r.Header.Get("Accept"))
return &http.Response{
StatusCode: http.StatusOK,
Body: io.NopCloser(bytes.NewBufferString(testExampleExecutionPayload)),
@@ -635,9 +635,9 @@ func TestSubmitBlindedBlock(t *testing.T) {
hc := &http.Client{
Transport: roundtrip(func(r *http.Request) (*http.Response, error) {
require.Equal(t, postBlindedBeaconBlockPath, r.URL.Path)
require.Equal(t, "bellatrix", r.Header.Get(api.VersionHeader))
require.Equal(t, api.OctetStreamMediaType, r.Header.Get("Content-Type"))
require.Equal(t, api.OctetStreamMediaType, r.Header.Get("Accept"))
require.Equal(t, "bellatrix", r.Header.Get(httputil.VersionHeader))
require.Equal(t, httputil.OctetStreamMediaType, r.Header.Get("Content-Type"))
require.Equal(t, httputil.OctetStreamMediaType, r.Header.Get("Accept"))
epr := &ExecutionPayloadResponse{}
require.NoError(t, json.Unmarshal([]byte(testExampleExecutionPayload), epr))
ep := &ExecutionPayload{}
@@ -647,7 +647,7 @@ func TestSubmitBlindedBlock(t *testing.T) {
ssz, err := pro.MarshalSSZ()
require.NoError(t, err)
header := http.Header{}
header.Set(api.VersionHeader, "bellatrix")
header.Set(httputil.VersionHeader, "bellatrix")
return &http.Response{
StatusCode: http.StatusOK,
Header: header,
@@ -675,9 +675,9 @@ func TestSubmitBlindedBlock(t *testing.T) {
hc := &http.Client{
Transport: roundtrip(func(r *http.Request) (*http.Response, error) {
require.Equal(t, postBlindedBeaconBlockPath, r.URL.Path)
require.Equal(t, "capella", r.Header.Get(api.VersionHeader))
require.Equal(t, api.JsonMediaType, r.Header.Get("Content-Type"))
require.Equal(t, api.JsonMediaType, r.Header.Get("Accept"))
require.Equal(t, "capella", r.Header.Get(httputil.VersionHeader))
require.Equal(t, httputil.JsonMediaType, r.Header.Get("Content-Type"))
require.Equal(t, httputil.JsonMediaType, r.Header.Get("Accept"))
return &http.Response{
StatusCode: http.StatusOK,
Body: io.NopCloser(bytes.NewBufferString(testExampleExecutionPayloadCapella)),
@@ -705,9 +705,9 @@ func TestSubmitBlindedBlock(t *testing.T) {
hc := &http.Client{
Transport: roundtrip(func(r *http.Request) (*http.Response, error) {
require.Equal(t, postBlindedBeaconBlockPath, r.URL.Path)
require.Equal(t, "capella", r.Header.Get(api.VersionHeader))
require.Equal(t, api.OctetStreamMediaType, r.Header.Get("Content-Type"))
require.Equal(t, api.OctetStreamMediaType, r.Header.Get("Accept"))
require.Equal(t, "capella", r.Header.Get(httputil.VersionHeader))
require.Equal(t, httputil.OctetStreamMediaType, r.Header.Get("Content-Type"))
require.Equal(t, httputil.OctetStreamMediaType, r.Header.Get("Accept"))
epr := &ExecutionPayloadResponse{}
require.NoError(t, json.Unmarshal([]byte(testExampleExecutionPayloadCapella), epr))
ep := &ExecutionPayloadCapella{}
@@ -717,7 +717,7 @@ func TestSubmitBlindedBlock(t *testing.T) {
ssz, err := pro.MarshalSSZ()
require.NoError(t, err)
header := http.Header{}
header.Set(api.VersionHeader, "capella")
header.Set(httputil.VersionHeader, "capella")
return &http.Response{
StatusCode: http.StatusOK,
Header: header,
@@ -748,9 +748,9 @@ func TestSubmitBlindedBlock(t *testing.T) {
hc := &http.Client{
Transport: roundtrip(func(r *http.Request) (*http.Response, error) {
require.Equal(t, postBlindedBeaconBlockPath, r.URL.Path)
require.Equal(t, "deneb", r.Header.Get(api.VersionHeader))
require.Equal(t, api.JsonMediaType, r.Header.Get("Content-Type"))
require.Equal(t, api.JsonMediaType, r.Header.Get("Accept"))
require.Equal(t, "deneb", r.Header.Get(httputil.VersionHeader))
require.Equal(t, httputil.JsonMediaType, r.Header.Get("Content-Type"))
require.Equal(t, httputil.JsonMediaType, r.Header.Get("Accept"))
var req structs.SignedBlindedBeaconBlockDeneb
err := json.NewDecoder(r.Body).Decode(&req)
require.NoError(t, err)
@@ -788,9 +788,9 @@ func TestSubmitBlindedBlock(t *testing.T) {
hc := &http.Client{
Transport: roundtrip(func(r *http.Request) (*http.Response, error) {
require.Equal(t, postBlindedBeaconBlockPath, r.URL.Path)
require.Equal(t, "deneb", r.Header.Get(api.VersionHeader))
require.Equal(t, api.OctetStreamMediaType, r.Header.Get("Content-Type"))
require.Equal(t, api.OctetStreamMediaType, r.Header.Get("Accept"))
require.Equal(t, "deneb", r.Header.Get(httputil.VersionHeader))
require.Equal(t, httputil.OctetStreamMediaType, r.Header.Get("Content-Type"))
require.Equal(t, httputil.OctetStreamMediaType, r.Header.Get("Accept"))
epr := &ExecPayloadResponseDeneb{}
require.NoError(t, json.Unmarshal([]byte(testExampleExecutionPayloadDeneb), epr))
pro, blob, err := epr.ToProto()
@@ -802,7 +802,7 @@ func TestSubmitBlindedBlock(t *testing.T) {
ssz, err := combined.MarshalSSZ()
require.NoError(t, err)
header := http.Header{}
header.Set(api.VersionHeader, "deneb")
header.Set(httputil.VersionHeader, "deneb")
return &http.Response{
StatusCode: http.StatusOK,
Header: header,
@@ -835,9 +835,9 @@ func TestSubmitBlindedBlock(t *testing.T) {
hc := &http.Client{
Transport: roundtrip(func(r *http.Request) (*http.Response, error) {
require.Equal(t, postBlindedBeaconBlockPath, r.URL.Path)
require.Equal(t, "electra", r.Header.Get(api.VersionHeader))
require.Equal(t, api.JsonMediaType, r.Header.Get("Content-Type"))
require.Equal(t, api.JsonMediaType, r.Header.Get("Accept"))
require.Equal(t, "electra", r.Header.Get(httputil.VersionHeader))
require.Equal(t, httputil.JsonMediaType, r.Header.Get("Content-Type"))
require.Equal(t, httputil.JsonMediaType, r.Header.Get("Accept"))
var req structs.SignedBlindedBeaconBlockElectra
err := json.NewDecoder(r.Body).Decode(&req)
require.NoError(t, err)
@@ -875,9 +875,9 @@ func TestSubmitBlindedBlock(t *testing.T) {
hc := &http.Client{
Transport: roundtrip(func(r *http.Request) (*http.Response, error) {
require.Equal(t, postBlindedBeaconBlockPath, r.URL.Path)
require.Equal(t, "electra", r.Header.Get(api.VersionHeader))
require.Equal(t, api.OctetStreamMediaType, r.Header.Get("Content-Type"))
require.Equal(t, api.OctetStreamMediaType, r.Header.Get("Accept"))
require.Equal(t, "electra", r.Header.Get(httputil.VersionHeader))
require.Equal(t, httputil.OctetStreamMediaType, r.Header.Get("Content-Type"))
require.Equal(t, httputil.OctetStreamMediaType, r.Header.Get("Accept"))
epr := &ExecPayloadResponseDeneb{}
require.NoError(t, json.Unmarshal([]byte(testExampleExecutionPayloadDeneb), epr))
pro, blob, err := epr.ToProto()
@@ -889,7 +889,7 @@ func TestSubmitBlindedBlock(t *testing.T) {
ssz, err := combined.MarshalSSZ()
require.NoError(t, err)
header := http.Header{}
header.Set(api.VersionHeader, "electra")
header.Set(httputil.VersionHeader, "electra")
return &http.Response{
StatusCode: http.StatusOK,
Header: header,

View File

@@ -8,12 +8,7 @@ import (
"net/url"
"github.com/pkg/errors"
)
const (
MaxBodySize int64 = 1 << 23 // 8MB default, WithMaxBodySize can override
MaxBodySizeState int64 = 1 << 29 // 512MB
MaxErrBodySize int64 = 1 << 17 // 128KB
"github.com/prysmaticlabs/prysm/v5/api/httputil"
)
// Client is a wrapper object around the HTTP client.
@@ -35,7 +30,7 @@ func NewClient(host string, opts ...ClientOpt) (*Client, error) {
c := &Client{
hc: &http.Client{},
baseURL: u,
maxBodySize: MaxBodySize,
maxBodySize: httputil.MaxBodySize,
}
for _, o := range opts {
o(c)
@@ -67,7 +62,7 @@ func urlForHost(h string) (*url.URL, error) {
// try to parse as host:port
host, port, err := net.SplitHostPort(h)
if err != nil {
return nil, ErrMalformedHostname
return nil, httputil.ErrMalformedHostname
}
return &url.URL{Host: net.JoinHostPort(host, port), Scheme: "http"}, nil
}
@@ -95,7 +90,7 @@ func (c *Client) Get(ctx context.Context, path string, opts ...ReqOption) ([]byt
err = r.Body.Close()
}()
if r.StatusCode != http.StatusOK {
return nil, Non200Err(r)
return nil, httputil.Non200Err(r)
}
b, err := io.ReadAll(io.LimitReader(r.Body, c.maxBodySize))
if err != nil {

View File

@@ -4,6 +4,7 @@ import (
"net/url"
"testing"
"github.com/prysmaticlabs/prysm/v5/api/httputil"
"github.com/prysmaticlabs/prysm/v5/testing/require"
)
@@ -18,7 +19,7 @@ func TestValidHostname(t *testing.T) {
{
name: "hostname without port",
hostArg: "mydomain.org",
err: ErrMalformedHostname,
err: httputil.ErrMalformedHostname,
},
}
for _, c := range cases {

View File

@@ -9,8 +9,7 @@ go_library(
importpath = "github.com/prysmaticlabs/prysm/v5/api/client/event",
visibility = ["//visibility:public"],
deps = [
"//api:go_default_library",
"//api/client:go_default_library",
"//api/httputil:go_default_library",
"@com_github_pkg_errors//:go_default_library",
"@com_github_sirupsen_logrus//:go_default_library",
],

View File

@@ -8,8 +8,7 @@ import (
"strings"
"github.com/pkg/errors"
"github.com/prysmaticlabs/prysm/v5/api"
"github.com/prysmaticlabs/prysm/v5/api/client"
"github.com/prysmaticlabs/prysm/v5/api/httputil"
log "github.com/sirupsen/logrus"
)
@@ -85,13 +84,13 @@ func (h *EventStream) Subscribe(eventsChannel chan<- *Event) {
Data: []byte(errors.Wrap(err, "failed to create HTTP request").Error()),
}
}
req.Header.Set("Accept", api.EventStreamMediaType)
req.Header.Set("Connection", api.KeepAlive)
req.Header.Set("Accept", httputil.EventStreamMediaType)
req.Header.Set("Connection", httputil.KeepAlive)
resp, err := h.httpClient.Do(req)
if err != nil {
eventsChannel <- &Event{
EventType: EventConnectionError,
Data: []byte(errors.Wrap(err, client.ErrConnectionIssue.Error()).Error()),
Data: []byte(errors.Wrap(err, httputil.ErrConnectionIssue.Error()).Error()),
}
return
}
@@ -145,7 +144,7 @@ func (h *EventStream) Subscribe(eventsChannel chan<- *Event) {
if err := scanner.Err(); err != nil {
eventsChannel <- &Event{
EventType: EventConnectionError,
Data: []byte(errors.Wrap(err, errors.Wrap(client.ErrConnectionIssue, "scanner failed").Error()).Error()),
Data: []byte(errors.Wrap(err, errors.Wrap(httputil.ErrConnectionIssue, "scanner failed").Error()).Error()),
}
}
}

View File

@@ -1,4 +1,4 @@
package beacon_api
package client
import (
"bytes"
@@ -9,8 +9,7 @@ import (
"strings"
"github.com/pkg/errors"
"github.com/prysmaticlabs/prysm/v5/api"
"github.com/prysmaticlabs/prysm/v5/network/httputil"
"github.com/prysmaticlabs/prysm/v5/api/httputil"
)
type JsonRestHandler interface {
@@ -88,7 +87,7 @@ func (c *BeaconApiJsonRestHandler) Post(
for headerKey, headerValue := range headers {
req.Header.Set(headerKey, headerValue)
}
req.Header.Set("Content-Type", api.JsonMediaType)
req.Header.Set("Content-Type", httputil.JsonMediaType)
httpResp, err := c.client.Do(req)
if err != nil {
@@ -109,7 +108,7 @@ func decodeResp(httpResp *http.Response, resp interface{}) error {
return errors.Wrapf(err, "failed to read response body for %s", httpResp.Request.URL)
}
if !strings.Contains(httpResp.Header.Get("Content-Type"), api.JsonMediaType) {
if !strings.Contains(httpResp.Header.Get("Content-Type"), httputil.JsonMediaType) {
// 2XX codes are a success
if strings.HasPrefix(httpResp.Status, "2") {
return nil

View File

@@ -1,4 +1,4 @@
package beacon_api
package client
import (
"bytes"
@@ -11,9 +11,8 @@ import (
"time"
"github.com/pkg/errors"
"github.com/prysmaticlabs/prysm/v5/api"
"github.com/prysmaticlabs/prysm/v5/api/httputil"
"github.com/prysmaticlabs/prysm/v5/api/server/structs"
"github.com/prysmaticlabs/prysm/v5/network/httputil"
"github.com/prysmaticlabs/prysm/v5/testing/assert"
"github.com/prysmaticlabs/prysm/v5/testing/require"
)
@@ -33,7 +32,7 @@ func TestGet(t *testing.T) {
marshalledJson, err := json.Marshal(genesisJson)
require.NoError(t, err)
w.Header().Set("Content-Type", api.JsonMediaType)
w.Header().Set("Content-Type", httputil.JsonMediaType)
_, err = w.Write(marshalledJson)
require.NoError(t, err)
})
@@ -67,7 +66,7 @@ func TestPost(t *testing.T) {
mux.HandleFunc(endpoint, func(w http.ResponseWriter, r *http.Request) {
// Make sure the request headers have been set
assert.Equal(t, "bar", r.Header.Get("foo"))
assert.Equal(t, api.JsonMediaType, r.Header.Get("Content-Type"))
assert.Equal(t, httputil.JsonMediaType, r.Header.Get("Content-Type"))
// Make sure the data matches
receivedBytes := make([]byte, len(dataBytes))
@@ -79,7 +78,7 @@ func TestPost(t *testing.T) {
marshalledJson, err := json.Marshal(genesisJson)
require.NoError(t, err)
w.Header().Set("Content-Type", api.JsonMediaType)
w.Header().Set("Content-Type", httputil.JsonMediaType)
_, err = w.Write(marshalledJson)
require.NoError(t, err)
})
@@ -115,7 +114,7 @@ func Test_decodeResp(t *testing.T) {
Status: "200",
StatusCode: http.StatusOK,
Body: io.NopCloser(&body),
Header: map[string][]string{"Content-Type": {api.OctetStreamMediaType}},
Header: map[string][]string{"Content-Type": {httputil.OctetStreamMediaType}},
}
require.NoError(t, decodeResp(r, nil))
})
@@ -125,7 +124,7 @@ func Test_decodeResp(t *testing.T) {
Status: "204",
StatusCode: http.StatusNoContent,
Body: io.NopCloser(&body),
Header: map[string][]string{"Content-Type": {api.OctetStreamMediaType}},
Header: map[string][]string{"Content-Type": {httputil.OctetStreamMediaType}},
}
require.NoError(t, decodeResp(r, nil))
})
@@ -137,7 +136,7 @@ func Test_decodeResp(t *testing.T) {
Status: "500",
StatusCode: http.StatusInternalServerError,
Body: io.NopCloser(&body),
Header: map[string][]string{"Content-Type": {api.OctetStreamMediaType}},
Header: map[string][]string{"Content-Type": {httputil.OctetStreamMediaType}},
}
err = decodeResp(r, nil)
errJson := &httputil.DefaultJsonError{}
@@ -154,7 +153,7 @@ func Test_decodeResp(t *testing.T) {
Status: "200",
StatusCode: http.StatusOK,
Body: io.NopCloser(&body),
Header: map[string][]string{"Content-Type": {api.JsonMediaType}},
Header: map[string][]string{"Content-Type": {httputil.JsonMediaType}},
}
resp := &j{}
require.NoError(t, decodeResp(r, resp))
@@ -166,7 +165,7 @@ func Test_decodeResp(t *testing.T) {
Status: "200",
StatusCode: http.StatusOK,
Body: io.NopCloser(&body),
Header: map[string][]string{"Content-Type": {api.JsonMediaType}},
Header: map[string][]string{"Content-Type": {httputil.JsonMediaType}},
}
require.NoError(t, decodeResp(r, nil))
})
@@ -176,7 +175,7 @@ func Test_decodeResp(t *testing.T) {
Status: "204",
StatusCode: http.StatusNoContent,
Body: io.NopCloser(&body),
Header: map[string][]string{"Content-Type": {api.JsonMediaType}},
Header: map[string][]string{"Content-Type": {httputil.JsonMediaType}},
}
require.NoError(t, decodeResp(r, nil))
})
@@ -189,7 +188,7 @@ func Test_decodeResp(t *testing.T) {
Status: "500",
StatusCode: http.StatusInternalServerError,
Body: io.NopCloser(&body),
Header: map[string][]string{"Content-Type": {api.JsonMediaType}},
Header: map[string][]string{"Content-Type": {httputil.JsonMediaType}},
}
err = decodeResp(r, nil)
errJson := &httputil.DefaultJsonError{}
@@ -205,7 +204,7 @@ func Test_decodeResp(t *testing.T) {
Status: "200",
StatusCode: http.StatusOK,
Body: io.NopCloser(&body),
Header: map[string][]string{"Content-Type": {api.JsonMediaType}},
Header: map[string][]string{"Content-Type": {httputil.JsonMediaType}},
Request: &http.Request{},
}
resp := &j{}
@@ -220,7 +219,7 @@ func Test_decodeResp(t *testing.T) {
Status: "500",
StatusCode: http.StatusInternalServerError,
Body: io.NopCloser(&body),
Header: map[string][]string{"Content-Type": {api.JsonMediaType}},
Header: map[string][]string{"Content-Type": {httputil.JsonMediaType}},
Request: &http.Request{},
}
err = decodeResp(r, nil)

View File

@@ -3,10 +3,10 @@ load("@prysm//tools/go:def.bzl", "go_library", "go_test")
go_library(
name = "go_default_library",
srcs = [
"grpcutils.go",
"common.go",
"parameters.go",
],
importpath = "github.com/prysmaticlabs/prysm/v5/api/grpc",
importpath = "github.com/prysmaticlabs/prysm/v5/api/grpcutil",
visibility = ["//visibility:public"],
deps = [
"@com_github_sirupsen_logrus//:go_default_library",
@@ -17,7 +17,7 @@ go_library(
go_test(
name = "go_default_test",
srcs = ["grpcutils_test.go"],
srcs = ["common_test.go"],
embed = [":go_default_library"],
deps = [
"//testing/assert:go_default_library",

View File

@@ -1,4 +1,4 @@
package grpc
package grpcutil
import (
"context"

View File

@@ -1,4 +1,4 @@
package grpc
package grpcutil
import (
"context"

View File

@@ -1,4 +1,4 @@
package grpc
package grpcutil
// CustomErrorMetadataKey is the name of the metadata key storing additional error information.
// Metadata value is expected to be a byte-encoded JSON object.

View File

@@ -3,24 +3,31 @@ load("@prysm//tools/go:def.bzl", "go_library", "go_test")
go_library(
name = "go_default_library",
srcs = [
"common.go",
"constants.go",
"errors.go",
"headers.go",
"reader.go",
"writer.go",
],
importpath = "github.com/prysmaticlabs/prysm/v5/network/httputil",
importpath = "github.com/prysmaticlabs/prysm/v5/api/httputil",
visibility = ["//visibility:public"],
deps = [
"//api:go_default_library",
"//consensus-types/primitives:go_default_library",
"@com_github_pkg_errors//:go_default_library",
"@com_github_sirupsen_logrus//:go_default_library",
],
)
go_test(
name = "go_default_test",
srcs = ["reader_test.go"],
srcs = [
"common_test.go",
"reader_test.go",
],
embed = [":go_default_library"],
deps = [
"//api:go_default_library",
"//consensus-types/primitives:go_default_library",
"//testing/assert:go_default_library",
"//testing/require:go_default_library",
],

23
api/httputil/common.go Normal file
View File

@@ -0,0 +1,23 @@
package httputil
import (
"fmt"
neturl "net/url"
"strconv"
"github.com/prysmaticlabs/prysm/v5/consensus-types/primitives"
)
// Uint64ToString is a util function that will convert uints to string
func Uint64ToString[T uint64 | primitives.Slot | primitives.ValidatorIndex | primitives.CommitteeIndex | primitives.Epoch](val T) string {
return strconv.FormatUint(uint64(val), 10)
}
// BuildURL is a util function that assists with adding query parameters to the url
func BuildURL(path string, queryParams ...neturl.Values) string {
if len(queryParams) == 0 {
return path
}
return fmt.Sprintf("%s?%s", path, queryParams[0].Encode())
}

View File

@@ -0,0 +1,37 @@
package httputil
import (
"net/url"
"testing"
"github.com/prysmaticlabs/prysm/v5/consensus-types/primitives"
"github.com/prysmaticlabs/prysm/v5/testing/assert"
)
func TestBeaconApiHelpers_TestUint64ToString(t *testing.T) {
const expectedResult = "1234"
const val = uint64(1234)
assert.Equal(t, expectedResult, Uint64ToString(val))
assert.Equal(t, expectedResult, Uint64ToString(primitives.Slot(val)))
assert.Equal(t, expectedResult, Uint64ToString(primitives.ValidatorIndex(val)))
assert.Equal(t, expectedResult, Uint64ToString(primitives.CommitteeIndex(val)))
assert.Equal(t, expectedResult, Uint64ToString(primitives.Epoch(val)))
}
func TestBuildURL_NoParams(t *testing.T) {
wanted := "/aaa/bbb/ccc"
actual := BuildURL("/aaa/bbb/ccc")
assert.Equal(t, wanted, actual)
}
func TestBuildURL_WithParams(t *testing.T) {
params := url.Values{}
params.Add("xxxx", "1")
params.Add("yyyy", "2")
params.Add("zzzz", "3")
wanted := "/aaa/bbb/ccc?xxxx=1&yyyy=2&zzzz=3"
actual := BuildURL("/aaa/bbb/ccc", params)
assert.Equal(t, wanted, actual)
}

View File

@@ -1,4 +1,4 @@
package api
package httputil
const (
WebUrlPrefix = "/v2/validator/"
@@ -7,3 +7,9 @@ const (
SystemLogsPrefix = "health/logs"
AuthTokenFileName = "auth-token"
)
const (
MaxBodySize int64 = 1 << 23 // 8MB default, WithMaxBodySize can override
MaxBodySizeState int64 = 1 << 29 // 512MB
MaxErrBodySize int64 = 1 << 17 // 128KB
)

View File

@@ -1,4 +1,4 @@
package client
package httputil
import (
"fmt"
@@ -8,6 +8,14 @@ import (
"github.com/pkg/errors"
)
func HandleError(w http.ResponseWriter, message string, code int) {
errJson := &DefaultJsonError{
Message: message,
Code: code,
}
WriteError(w, errJson)
}
// ErrMalformedHostname is used to indicate if a host name's format is incorrect.
var ErrMalformedHostname = errors.New("hostname must include port, separated by one colon, like example.com:3500")
@@ -24,6 +32,9 @@ var ErrInvalidNodeVersion = errors.New("invalid node version response")
// ErrConnectionIssue represents a connection problem.
var ErrConnectionIssue = errors.New("could not connect")
// ErrNotSupported represents a connection to a beacon node that is non prysm or wrong version
var ErrNotSupported = errors.New("endpoint not supported")
// Non200Err is a function that parses an HTTP response to handle responses that are not 200 with a formatted error.
func Non200Err(r *http.Response) error {
b, err := io.ReadAll(io.LimitReader(r.Body, MaxErrBodySize))

View File

@@ -1,4 +1,4 @@
package api
package httputil
import "net/http"

View File

@@ -5,8 +5,6 @@ import (
"regexp"
"strconv"
"strings"
"github.com/prysmaticlabs/prysm/v5/api"
)
// match a number with optional decimals
@@ -23,7 +21,7 @@ func RespondWithSsz(req *http.Request) bool {
for _, t := range types {
values := strings.Split(t, ";")
name := values[0]
if name != api.JsonMediaType && name != api.OctetStreamMediaType {
if name != JsonMediaType && name != OctetStreamMediaType {
continue
}
// no params specified
@@ -49,10 +47,10 @@ func RespondWithSsz(req *http.Request) bool {
}
}
return currentType == api.OctetStreamMediaType
return currentType == OctetStreamMediaType
}
// IsRequestSsz checks if the request object should be interpreted as ssz
func IsRequestSsz(req *http.Request) bool {
return req.Header.Get("Content-Type") == api.OctetStreamMediaType
return req.Header.Get("Content-Type") == OctetStreamMediaType
}

View File

@@ -7,7 +7,6 @@ import (
"net/http/httptest"
"testing"
"github.com/prysmaticlabs/prysm/v5/api"
"github.com/prysmaticlabs/prysm/v5/testing/assert"
"github.com/prysmaticlabs/prysm/v5/testing/require"
)
@@ -15,42 +14,42 @@ import (
func TestRespondWithSsz(t *testing.T) {
t.Run("ssz_requested", func(t *testing.T) {
request := httptest.NewRequest(http.MethodGet, "http://foo.example", nil)
request.Header["Accept"] = []string{api.OctetStreamMediaType}
request.Header["Accept"] = []string{OctetStreamMediaType}
result := RespondWithSsz(request)
assert.Equal(t, true, result)
})
t.Run("ssz_content_type_first", func(t *testing.T) {
request := httptest.NewRequest("GET", "http://foo.example", nil)
request.Header["Accept"] = []string{fmt.Sprintf("%s,%s", api.OctetStreamMediaType, api.JsonMediaType)}
request.Header["Accept"] = []string{fmt.Sprintf("%s,%s", OctetStreamMediaType, JsonMediaType)}
result := RespondWithSsz(request)
assert.Equal(t, true, result)
})
t.Run("ssz_content_type_preferred_1", func(t *testing.T) {
request := httptest.NewRequest(http.MethodGet, "http://foo.example", nil)
request.Header["Accept"] = []string{fmt.Sprintf("%s;q=0.9,%s", api.JsonMediaType, api.OctetStreamMediaType)}
request.Header["Accept"] = []string{fmt.Sprintf("%s;q=0.9,%s", JsonMediaType, OctetStreamMediaType)}
result := RespondWithSsz(request)
assert.Equal(t, true, result)
})
t.Run("ssz_content_type_preferred_2", func(t *testing.T) {
request := httptest.NewRequest(http.MethodGet, "http://foo.example", nil)
request.Header["Accept"] = []string{fmt.Sprintf("%s;q=0.95,%s;q=0.9", api.OctetStreamMediaType, api.JsonMediaType)}
request.Header["Accept"] = []string{fmt.Sprintf("%s;q=0.95,%s;q=0.9", OctetStreamMediaType, JsonMediaType)}
result := RespondWithSsz(request)
assert.Equal(t, true, result)
})
t.Run("other_content_type_preferred", func(t *testing.T) {
request := httptest.NewRequest("GET", "http://foo.example", nil)
request.Header["Accept"] = []string{fmt.Sprintf("%s,%s;q=0.9", api.JsonMediaType, api.OctetStreamMediaType)}
request.Header["Accept"] = []string{fmt.Sprintf("%s,%s;q=0.9", JsonMediaType, OctetStreamMediaType)}
result := RespondWithSsz(request)
assert.Equal(t, false, result)
})
t.Run("other_params", func(t *testing.T) {
request := httptest.NewRequest(http.MethodGet, "http://foo.example", nil)
request.Header["Accept"] = []string{fmt.Sprintf("%s,%s;q=0.9,otherparam=xyz", api.JsonMediaType, api.OctetStreamMediaType)}
request.Header["Accept"] = []string{fmt.Sprintf("%s,%s;q=0.9,otherparam=xyz", JsonMediaType, OctetStreamMediaType)}
result := RespondWithSsz(request)
assert.Equal(t, false, result)
})
@@ -96,7 +95,7 @@ func TestIsRequestSsz(t *testing.T) {
_, err := body.WriteString("something")
require.NoError(t, err)
request := httptest.NewRequest(http.MethodPost, "http://foo.example", &body)
request.Header["Content-Type"] = []string{api.OctetStreamMediaType}
request.Header["Content-Type"] = []string{OctetStreamMediaType}
result := IsRequestSsz(request)
assert.Equal(t, true, result)
})
@@ -116,7 +115,7 @@ func TestIsRequestSsz(t *testing.T) {
t.Run("ssz Post json content type", func(t *testing.T) {
request := httptest.NewRequest(http.MethodPost, "http://foo.example", nil)
request.Header["Content-Type"] = []string{api.JsonMediaType}
request.Header["Content-Type"] = []string{JsonMediaType}
result := IsRequestSsz(request)
assert.Equal(t, false, result)
})

View File

@@ -8,7 +8,6 @@ import (
"net/http"
"strconv"
"github.com/prysmaticlabs/prysm/v5/api"
log "github.com/sirupsen/logrus"
)
@@ -32,7 +31,7 @@ func (e *DefaultJsonError) Error() string {
// WriteJson writes the response message in JSON format.
func WriteJson(w http.ResponseWriter, v any) {
w.Header().Set("Content-Type", api.JsonMediaType)
w.Header().Set("Content-Type", JsonMediaType)
w.WriteHeader(http.StatusOK)
if err := json.NewEncoder(w).Encode(v); err != nil {
log.WithError(err).Error("Could not write response message")
@@ -40,10 +39,9 @@ func WriteJson(w http.ResponseWriter, v any) {
}
// WriteSsz writes the response message in ssz format
func WriteSsz(w http.ResponseWriter, respSsz []byte, fileName string) {
func WriteSsz(w http.ResponseWriter, respSsz []byte) {
w.Header().Set("Content-Length", strconv.Itoa(len(respSsz)))
w.Header().Set("Content-Type", api.OctetStreamMediaType)
w.Header().Set("Content-Disposition", "attachment; filename="+fileName)
w.Header().Set("Content-Type", OctetStreamMediaType)
if _, err := io.Copy(w, io.NopCloser(bytes.NewReader(respSsz))); err != nil {
log.WithError(err).Error("could not write response message")
}
@@ -57,7 +55,7 @@ func WriteError(w http.ResponseWriter, errJson HasStatusCode) {
return
}
w.Header().Set("Content-Length", strconv.Itoa(len(j)))
w.Header().Set("Content-Type", api.JsonMediaType)
w.Header().Set("Content-Type", JsonMediaType)
w.WriteHeader(errJson.StatusCode())
if _, err := io.Copy(w, io.NopCloser(bytes.NewReader(j))); err != nil {
log.WithError(err).Error("Could not write error message")

View File

@@ -19,7 +19,7 @@ go_test(
],
embed = [":go_default_library"],
deps = [
"//api:go_default_library",
"//api/httputil:go_default_library",
"//testing/assert:go_default_library",
"//testing/require:go_default_library",
],

View File

@@ -5,7 +5,7 @@ import (
"net/http/httptest"
"testing"
"github.com/prysmaticlabs/prysm/v5/api"
"github.com/prysmaticlabs/prysm/v5/api/httputil"
"github.com/prysmaticlabs/prysm/v5/testing/require"
)
@@ -55,7 +55,7 @@ func TestNormalizeQueryValuesHandler(t *testing.T) {
}
func TestContentTypeHandler(t *testing.T) {
acceptedMediaTypes := []string{api.JsonMediaType, api.OctetStreamMediaType}
acceptedMediaTypes := []string{httputil.JsonMediaType, httputil.OctetStreamMediaType}
nextHandler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
_, err := w.Write([]byte("next handler"))
@@ -72,12 +72,12 @@ func TestContentTypeHandler(t *testing.T) {
}{
{
name: "Accepted Content-Type - application/json",
contentType: api.JsonMediaType,
contentType: httputil.JsonMediaType,
expectedStatusCode: http.StatusOK,
},
{
name: "Accepted Content-Type - ssz format",
contentType: api.OctetStreamMediaType,
contentType: httputil.OctetStreamMediaType,
expectedStatusCode: http.StatusOK,
},
{

View File

@@ -100,6 +100,12 @@ type GetValidatorBalancesResponse struct {
Data []*ValidatorBalance `json:"data"`
}
type GetValidatorIdentitiesResponse struct {
ExecutionOptimistic bool `json:"execution_optimistic"`
Finalized bool `json:"finalized"`
Data []*ValidatorIdentity `json:"data"`
}
type ValidatorContainer struct {
Index string `json:"index"`
Balance string `json:"balance"`
@@ -112,6 +118,12 @@ type ValidatorBalance struct {
Balance string `json:"balance"`
}
type ValidatorIdentity struct {
Index string `json:"index"`
Pubkey string `json:"pubkey"`
ActivationEpoch string `json:"activation_epoch"`
}
type GetBlockResponse struct {
Data *SignedBlock `json:"data"`
}

View File

@@ -18,6 +18,7 @@ import (
"github.com/prysmaticlabs/prysm/v5/time/slots"
)
// The caller of this function must have a lock on forkchoice.
func (s *Service) getRecentPreState(ctx context.Context, c *ethpb.Checkpoint) state.ReadOnlyBeaconState {
headEpoch := slots.ToEpoch(s.HeadSlot())
if c.Epoch < headEpoch {
@@ -27,13 +28,6 @@ func (s *Service) getRecentPreState(ctx context.Context, c *ethpb.Checkpoint) st
return nil
}
if c.Epoch == headEpoch {
targetSlot, err := s.cfg.ForkChoiceStore.Slot([32]byte(c.Root))
if err != nil {
return nil
}
if slots.ToEpoch(targetSlot)+1 < headEpoch {
return nil
}
st, err := s.HeadStateReadOnly(ctx)
if err != nil {
return nil
@@ -65,12 +59,13 @@ func (s *Service) getRecentPreState(ctx context.Context, c *ethpb.Checkpoint) st
return nil
}
if err := s.checkpointStateCache.AddCheckpointState(c, st); err != nil {
return nil
log.WithError(err).Error("Could not save checkpoint state to cache")
}
return st
}
// getAttPreState retrieves the att pre state by either from the cache or the DB.
// The caller of this function must have a lock on forkchoice.
func (s *Service) getAttPreState(ctx context.Context, c *ethpb.Checkpoint) (state.ReadOnlyBeaconState, error) {
// If the attestation is recent and canonical we can use the head state to compute the shuffling.
if st := s.getRecentPreState(ctx, c); st != nil {

View File

@@ -75,6 +75,7 @@ type ChainService struct {
SyncingRoot [32]byte
Blobs []blocks.VerifiedROBlob
TargetRoot [32]byte
MockHeadSlot *primitives.Slot
}
func (s *ChainService) Ancestor(ctx context.Context, root []byte, slot primitives.Slot) ([]byte, error) {
@@ -334,6 +335,9 @@ func (s *ChainService) ReceiveBlock(ctx context.Context, block interfaces.ReadOn
// HeadSlot mocks HeadSlot method in chain service.
func (s *ChainService) HeadSlot() primitives.Slot {
if s.MockHeadSlot != nil {
return *s.MockHeadSlot
}
if s.State == nil {
return 0
}

View File

@@ -165,7 +165,7 @@ func AddValidatorFlag(flag, flagPosition uint8) (uint8, error) {
// if flag_index in participation_flag_indices and not has_flag(epoch_participation[index], flag_index):
// epoch_participation[index] = add_flag(epoch_participation[index], flag_index)
// proposer_reward_numerator += get_base_reward(state, index) * weight
func EpochParticipation(beaconState state.BeaconState, indices []uint64, epochParticipation []byte, participatedFlags map[uint8]bool, totalBalance uint64) (uint64, []byte, error) {
func EpochParticipation(beaconState state.ReadOnlyBeaconState, indices []uint64, epochParticipation []byte, participatedFlags map[uint8]bool, totalBalance uint64) (uint64, []byte, error) {
cfg := params.BeaconConfig()
sourceFlagIndex := cfg.TimelySourceFlagIndex
targetFlagIndex := cfg.TimelyTargetFlagIndex
@@ -267,7 +267,7 @@ func RewardProposer(ctx context.Context, beaconState state.BeaconState, proposer
// participation_flag_indices.append(TIMELY_HEAD_FLAG_INDEX)
//
// return participation_flag_indices
func AttestationParticipationFlagIndices(beaconState state.BeaconState, data *ethpb.AttestationData, delay primitives.Slot) (map[uint8]bool, error) {
func AttestationParticipationFlagIndices(beaconState state.ReadOnlyBeaconState, data *ethpb.AttestationData, delay primitives.Slot) (map[uint8]bool, error) {
currEpoch := time.CurrentEpoch(beaconState)
var justifiedCheckpt *ethpb.Checkpoint
if data.Target.Epoch == currEpoch {
@@ -312,7 +312,7 @@ func AttestationParticipationFlagIndices(beaconState state.BeaconState, data *et
// is_matching_source = data.source == justified_checkpoint
// is_matching_target = is_matching_source and data.target.root == get_block_root(state, data.target.epoch)
// is_matching_head = is_matching_target and data.beacon_block_root == get_block_root_at_slot(state, data.slot)
func MatchingStatus(beaconState state.BeaconState, data *ethpb.AttestationData, cp *ethpb.Checkpoint) (matchedSrc, matchedTgt, matchedHead bool, err error) {
func MatchingStatus(beaconState state.ReadOnlyBeaconState, data *ethpb.AttestationData, cp *ethpb.Checkpoint) (matchedSrc, matchedTgt, matchedHead bool, err error) {
matchedSrc = attestation.CheckPointIsEqual(data.Source, cp)
r, err := helpers.BlockRoot(beaconState, data.Target.Epoch)

View File

@@ -29,6 +29,7 @@ go_library(
"//beacon-chain/core/validators:go_default_library",
"//beacon-chain/state:go_default_library",
"//beacon-chain/state/state-native:go_default_library",
"//beacon-chain/state/state-native/custom-types:go_default_library",
"//config/params:go_default_library",
"//consensus-types/interfaces:go_default_library",
"//consensus-types/primitives:go_default_library",
@@ -39,6 +40,7 @@ go_library(
"//monitoring/tracing/trace:go_default_library",
"//proto/engine/v1:go_default_library",
"//proto/prysm/v1alpha1:go_default_library",
"//proto/prysm/v1alpha1/attestation:go_default_library",
"//runtime/version:go_default_library",
"//time/slots:go_default_library",
"@com_github_ethereum_go_ethereum//common/hexutil:go_default_library",

View File

@@ -1,7 +1,94 @@
package electra
import "github.com/prysmaticlabs/prysm/v5/beacon-chain/core/altair"
import (
"context"
"fmt"
"github.com/prysmaticlabs/prysm/v5/beacon-chain/core/altair"
"github.com/prysmaticlabs/prysm/v5/beacon-chain/core/helpers"
"github.com/prysmaticlabs/prysm/v5/beacon-chain/core/time"
"github.com/prysmaticlabs/prysm/v5/beacon-chain/state"
customtypes "github.com/prysmaticlabs/prysm/v5/beacon-chain/state/state-native/custom-types"
"github.com/prysmaticlabs/prysm/v5/config/params"
"github.com/prysmaticlabs/prysm/v5/consensus-types/primitives"
ethpb "github.com/prysmaticlabs/prysm/v5/proto/prysm/v1alpha1"
"github.com/prysmaticlabs/prysm/v5/proto/prysm/v1alpha1/attestation"
)
var (
ProcessAttestationsNoVerifySignature = altair.ProcessAttestationsNoVerifySignature
)
// GetProposerRewardNumerator returns the numerator of the proposer reward for an attestation.
func GetProposerRewardNumerator(
ctx context.Context,
st state.ReadOnlyBeaconState,
att ethpb.Att,
totalBalance uint64,
) (uint64, error) {
data := att.GetData()
delay, err := st.Slot().SafeSubSlot(data.Slot)
if err != nil {
return 0, fmt.Errorf("attestation slot %d exceeds state slot %d", data.Slot, st.Slot())
}
flags, err := altair.AttestationParticipationFlagIndices(st, data, delay)
if err != nil {
return 0, err
}
committees, err := helpers.AttestationCommitteesFromState(ctx, st, att)
if err != nil {
return 0, err
}
indices, err := attestation.AttestingIndices(att, committees...)
if err != nil {
return 0, err
}
var participation customtypes.ReadOnlyParticipation
if data.Target.Epoch == time.CurrentEpoch(st) {
participation, err = st.CurrentEpochParticipationReadOnly()
} else {
participation, err = st.PreviousEpochParticipationReadOnly()
}
if err != nil {
return 0, err
}
cfg := params.BeaconConfig()
var rewardNumerator uint64
for _, index := range indices {
if index >= uint64(participation.Len()) {
return 0, fmt.Errorf("index %d exceeds participation length %d", index, participation.Len())
}
br, err := altair.BaseRewardWithTotalBalance(st, primitives.ValidatorIndex(index), totalBalance)
if err != nil {
return 0, err
}
for _, entry := range []struct {
flagIndex uint8
weight uint64
}{
{cfg.TimelySourceFlagIndex, cfg.TimelySourceWeight},
{cfg.TimelyTargetFlagIndex, cfg.TimelyTargetWeight},
{cfg.TimelyHeadFlagIndex, cfg.TimelyHeadWeight},
} {
if flags[entry.flagIndex] { // If set, the validator voted correctly for the attestation given flag index.
hasVoted, err := altair.HasValidatorFlag(participation.At(index), entry.flagIndex)
if err != nil {
return 0, err
}
if !hasVoted { // If set, the validator has already voted in the beacon state so we don't double count.
rewardNumerator += br * entry.weight
}
}
}
}
return rewardNumerator, nil
}

View File

@@ -211,7 +211,7 @@ func ProcessConsolidationRequests(ctx context.Context, st state.BeaconState, req
if npc, err := st.NumPendingConsolidations(); err != nil {
return fmt.Errorf("failed to fetch number of pending consolidations: %w", err) // This should never happen.
} else if npc >= pcLimit {
return nil
continue
}
activeBal, err := helpers.TotalActiveBalance(st)
@@ -220,7 +220,7 @@ func ProcessConsolidationRequests(ctx context.Context, st state.BeaconState, req
}
churnLimit := helpers.ConsolidationChurnLimit(primitives.Gwei(activeBal))
if churnLimit <= primitives.Gwei(params.BeaconConfig().MinActivationBalance) {
return nil
continue
}
srcIdx, ok := st.ValidatorIndexByPubkey(sourcePubkey)

View File

@@ -415,6 +415,44 @@ func TestProcessConsolidationRequests(t *testing.T) {
require.Equal(t, params.BeaconConfig().FarFutureEpoch, src.WithdrawableEpoch, "source validator withdrawable epoch should not be updated")
},
},
{
name: "pending consolidations limit reached and compounded consolidation after",
state: func() state.BeaconState {
st := &eth.BeaconStateElectra{
Slot: params.BeaconConfig().SlotsPerEpoch.Mul(uint64(params.BeaconConfig().ShardCommitteePeriod)),
Validators: createValidatorsWithTotalActiveBalance(32000000000000000), // 32M ETH
PendingConsolidations: make([]*eth.PendingConsolidation, params.BeaconConfig().PendingConsolidationsLimit),
}
// To allow compounding consolidation requests.
st.Validators[3].WithdrawalCredentials[0] = params.BeaconConfig().ETH1AddressWithdrawalPrefixByte
s, err := state_native.InitializeFromProtoElectra(st)
require.NoError(t, err)
return s
}(),
reqs: []*enginev1.ConsolidationRequest{
{
SourceAddress: append(bytesutil.PadTo(nil, 19), byte(1)),
SourcePubkey: []byte("val_1"),
TargetPubkey: []byte("val_2"),
},
{
SourceAddress: append(bytesutil.PadTo(nil, 19), byte(3)),
SourcePubkey: []byte("val_3"),
TargetPubkey: []byte("val_3"),
},
},
validate: func(t *testing.T, st state.BeaconState) {
// Verify a pending consolidation is created.
numPC, err := st.NumPendingConsolidations()
require.NoError(t, err)
require.Equal(t, params.BeaconConfig().PendingConsolidationsLimit, numPC)
// Verify that the last consolidation was included
src, err := st.ValidatorAtIndex(3)
require.NoError(t, err)
require.Equal(t, params.BeaconConfig().CompoundingWithdrawalPrefixByte, src.WithdrawalCredentials[0], "source validator was not compounded")
},
},
}
for _, tt := range tests {

View File

@@ -307,7 +307,7 @@ func TestProcessPendingDeposits(t *testing.T) {
}
func TestBatchProcessNewPendingDeposits(t *testing.T) {
t.Run("invalid batch initiates correct individual validation", func(t *testing.T) {
t.Run("one valid deposit one garbage deposit", func(t *testing.T) {
st := stateWithActiveBalanceETH(t, 0)
require.Equal(t, 0, len(st.Validators()))
require.Equal(t, 0, len(st.Balances()))
@@ -318,13 +318,47 @@ func TestBatchProcessNewPendingDeposits(t *testing.T) {
wc[31] = byte(0)
validDep := stateTesting.GeneratePendingDeposit(t, sk, params.BeaconConfig().MinActivationBalance, bytesutil.ToBytes32(wc), 0)
invalidDep := &eth.PendingDeposit{PublicKey: make([]byte, 48)}
// have a combination of valid and invalid deposits
deps := []*eth.PendingDeposit{validDep, invalidDep}
require.NoError(t, electra.BatchProcessNewPendingDeposits(context.Background(), st, deps))
// successfully added to register
require.Equal(t, 1, len(st.Validators()))
require.Equal(t, 1, len(st.Balances()))
})
t.Run("two valid deposits from same key", func(t *testing.T) {
st := stateWithActiveBalanceETH(t, 0)
require.Equal(t, 0, len(st.Validators()))
require.Equal(t, 0, len(st.Balances()))
sk, err := bls.RandKey()
require.NoError(t, err)
wc := make([]byte, 32)
wc[0] = params.BeaconConfig().ETH1AddressWithdrawalPrefixByte
wc[31] = byte(0)
validDep := stateTesting.GeneratePendingDeposit(t, sk, params.BeaconConfig().MinActivationBalance, bytesutil.ToBytes32(wc), 0)
deps := []*eth.PendingDeposit{validDep, validDep}
require.NoError(t, electra.BatchProcessNewPendingDeposits(context.Background(), st, deps))
require.Equal(t, 1, len(st.Validators()))
require.Equal(t, 1, len(st.Balances()))
require.Equal(t, params.BeaconConfig().MinActivationBalance*2, st.Balances()[0])
})
t.Run("one valid one with invalid signature deposit", func(t *testing.T) {
st := stateWithActiveBalanceETH(t, 0)
require.Equal(t, 0, len(st.Validators()))
require.Equal(t, 0, len(st.Balances()))
sk, err := bls.RandKey()
require.NoError(t, err)
wc := make([]byte, 32)
wc[0] = params.BeaconConfig().ETH1AddressWithdrawalPrefixByte
wc[31] = byte(0)
validDep := stateTesting.GeneratePendingDeposit(t, sk, params.BeaconConfig().MinActivationBalance, bytesutil.ToBytes32(wc), 0)
invalidSigDep := stateTesting.GeneratePendingDeposit(t, sk, params.BeaconConfig().MinActivationBalance, bytesutil.ToBytes32(wc), 0)
invalidSigDep.Signature = make([]byte, 96)
deps := []*eth.PendingDeposit{validDep, invalidSigDep}
require.NoError(t, electra.BatchProcessNewPendingDeposits(context.Background(), st, deps))
require.Equal(t, 1, len(st.Validators()))
require.Equal(t, 1, len(st.Balances()))
require.Equal(t, 2*params.BeaconConfig().MinActivationBalance, st.Balances()[0])
})
}
func TestProcessDepositRequests(t *testing.T) {

View File

@@ -10,7 +10,6 @@ import (
"github.com/prysmaticlabs/prysm/v5/consensus-types/primitives"
"github.com/prysmaticlabs/prysm/v5/crypto/hash"
ethpb "github.com/prysmaticlabs/prysm/v5/proto/prysm/v1alpha1"
"github.com/prysmaticlabs/prysm/v5/runtime/version"
prysmTime "github.com/prysmaticlabs/prysm/v5/time"
"github.com/prysmaticlabs/prysm/v5/time/slots"
)
@@ -86,15 +85,7 @@ func IsAggregator(committeeCount uint64, slotSig []byte) (bool, error) {
//
// return uint64((committees_since_epoch_start + committee_index) % ATTESTATION_SUBNET_COUNT)
func ComputeSubnetForAttestation(activeValCount uint64, att ethpb.Att) uint64 {
if att.Version() >= version.Electra {
committeeIndex := 0
committeeIndices := att.CommitteeBitsVal().BitIndices()
if len(committeeIndices) > 0 {
committeeIndex = committeeIndices[0]
}
return ComputeSubnetFromCommitteeAndSlot(activeValCount, primitives.CommitteeIndex(committeeIndex), att.GetData().Slot)
}
return ComputeSubnetFromCommitteeAndSlot(activeValCount, att.GetData().CommitteeIndex, att.GetData().Slot)
return ComputeSubnetFromCommitteeAndSlot(activeValCount, att.GetCommitteeIndex(), att.GetData().Slot)
}
// ComputeSubnetFromCommitteeAndSlot is a flattened version of ComputeSubnetForAttestation where we only pass in

View File

@@ -2,13 +2,19 @@ load("@prysm//tools/go:def.bzl", "go_library", "go_test")
go_library(
name = "go_default_library",
srcs = ["filter.go"],
srcs = [
"errors.go",
"filter.go",
],
importpath = "github.com/prysmaticlabs/prysm/v5/beacon-chain/db/filters",
visibility = [
"//beacon-chain:__subpackages__",
"//tools:__subpackages__",
],
deps = ["//consensus-types/primitives:go_default_library"],
deps = [
"//consensus-types/primitives:go_default_library",
"@com_github_pkg_errors//:go_default_library",
],
)
go_test(
@@ -18,5 +24,6 @@ go_test(
deps = [
"//consensus-types/primitives:go_default_library",
"//testing/assert:go_default_library",
"//testing/require:go_default_library",
],
)

View File

@@ -0,0 +1,9 @@
package filters
import "errors"
var (
ErrIncompatibleFilters = errors.New("combination of filters is not valid")
ErrNotSet = errors.New("filter was not set")
ErrInvalidQuery = errors.New("invalid query")
)

View File

@@ -14,7 +14,10 @@
// }
package filters
import primitives "github.com/prysmaticlabs/prysm/v5/consensus-types/primitives"
import (
"github.com/pkg/errors"
"github.com/prysmaticlabs/prysm/v5/consensus-types/primitives"
)
// FilterType defines an enum which is used as the keys in a map that tracks
// set attribute filters for data as part of the `FilterQuery` struct type.
@@ -45,10 +48,34 @@ const (
SlotStep
)
// SlotRoot is the slot and root of a single block.
type SlotRoot struct {
Slot primitives.Slot
Root [32]byte
}
// AncestryQuery is a special query that describes a chain of blocks that satisfies the invariant of:
// blocks[n].parent_root == blocks[n-1].root.
type AncestryQuery struct {
// Slot of oldest to return.
Earliest primitives.Slot
// Descendent that all ancestors in chain must descend from.
Descendent SlotRoot
set bool
}
func (aq AncestryQuery) Span() primitives.Slot {
if aq.Earliest > aq.Descendent.Slot {
return 0
}
return (aq.Descendent.Slot - aq.Earliest) + 1 // +1 to include upper bound
}
// QueryFilter defines a generic interface for type-asserting
// specific filters to use in querying DB objects.
type QueryFilter struct {
queries map[FilterType]interface{}
queries map[FilterType]interface{}
ancestry AncestryQuery
}
// NewFilter instantiates a new QueryFilter type used to build filters for
@@ -132,3 +159,42 @@ func (q *QueryFilter) SetSlotStep(val uint64) *QueryFilter {
q.queries[SlotStep] = val
return q
}
// SimpleSlotRange returns the start and end slot of a query filter if it is a simple slot range query.
// A simple slot range query is one where the filter only contains a start slot and an end slot.
// If the query is not a simple slot range query, the bool return value will be false.
func (q *QueryFilter) SimpleSlotRange() (primitives.Slot, primitives.Slot, bool) {
if len(q.queries) != 2 || q.queries[StartSlot] == nil || q.queries[EndSlot] == nil {
return 0, 0, false
}
start, ok := q.queries[StartSlot].(primitives.Slot)
if !ok {
return 0, 0, false
}
end, ok := q.queries[EndSlot].(primitives.Slot)
if !ok {
return 0, 0, false
}
return start, end, true
}
// SetAncestryQuery sets the filter to be an ancestryQuery. Note that this filter type is exclusive with
// other filters, so call ing GetAncestryQuery will return an error if other values are set.
func (q *QueryFilter) SetAncestryQuery(aq AncestryQuery) *QueryFilter {
aq.set = true
q.ancestry = aq
return q
}
func (q *QueryFilter) GetAncestryQuery() (AncestryQuery, error) {
if !q.ancestry.set {
return q.ancestry, ErrNotSet
}
if len(q.queries) > 0 {
return q.ancestry, errors.Wrap(ErrIncompatibleFilters, "AncestryQuery cannot be combined with other filters")
}
if q.ancestry.Earliest > q.ancestry.Descendent.Slot {
return q.ancestry, errors.Wrap(ErrInvalidQuery, "descendent slot must come after earliest slot")
}
return q.ancestry, nil
}

View File

@@ -5,6 +5,7 @@ import (
"github.com/prysmaticlabs/prysm/v5/consensus-types/primitives"
"github.com/prysmaticlabs/prysm/v5/testing/assert"
"github.com/prysmaticlabs/prysm/v5/testing/require"
)
func TestQueryFilter_ChainsCorrectly(t *testing.T) {
@@ -28,3 +29,64 @@ func TestQueryFilter_ChainsCorrectly(t *testing.T) {
}
}
}
func TestSimpleSlotRange(t *testing.T) {
type tc struct {
name string
applFilters []func(*QueryFilter) *QueryFilter
isSimple bool
start primitives.Slot
end primitives.Slot
}
cases := []tc{
{
name: "no filters",
applFilters: []func(*QueryFilter) *QueryFilter{},
isSimple: false,
},
{
name: "start slot",
applFilters: []func(*QueryFilter) *QueryFilter{
func(f *QueryFilter) *QueryFilter {
return f.SetStartSlot(3)
},
},
isSimple: false,
},
{
name: "end slot",
applFilters: []func(*QueryFilter) *QueryFilter{
func(f *QueryFilter) *QueryFilter {
return f.SetEndSlot(3)
},
},
isSimple: false,
},
{
name: "end slot",
applFilters: []func(*QueryFilter) *QueryFilter{
func(f *QueryFilter) *QueryFilter {
return f.SetStartSlot(3)
},
func(f *QueryFilter) *QueryFilter {
return f.SetEndSlot(7)
},
},
start: 3,
end: 7,
isSimple: true,
},
}
for _, c := range cases {
t.Run(c.name, func(t *testing.T) {
f := NewFilter()
for _, filt := range c.applFilters {
f = filt(f)
}
start, end, isSimple := f.SimpleSlotRange()
require.Equal(t, c.isSimple, isSimple)
require.Equal(t, c.start, start)
require.Equal(t, c.end, end)
})
}
}

View File

@@ -4,6 +4,7 @@ import (
"bytes"
"context"
"fmt"
"slices"
"github.com/ethereum/go-ethereum/common"
"github.com/golang/snappy"
@@ -117,13 +118,95 @@ func (s *Store) HeadBlock(ctx context.Context) (interfaces.ReadOnlySignedBeaconB
return headBlock, err
}
// blocksAncestryQuery returns all blocks *before* the descendent block;
// that is: inclusive of q.Earliest, exclusive of q.Descendent.Slot.
func (s *Store) blocksAncestryQuery(ctx context.Context, q filters.AncestryQuery) ([]interfaces.ReadOnlySignedBeaconBlock, [][32]byte, error) {
// Save resources if no blocks will be found by the query.
if q.Span() < 1 {
return nil, nil, filters.ErrInvalidQuery
}
blocks := make([]interfaces.ReadOnlySignedBeaconBlock, 0, q.Span())
roots := make([][32]byte, 0, q.Span())
// Handle edge case where start and end are equal; slotRootsInRange would see end < start and err.
// So, just grab the descendent in its own tx and stop there.
if q.Span() == 1 {
err := s.db.View(func(tx *bolt.Tx) error {
descendent, err := s.getBlock(ctx, q.Descendent.Root, tx)
if err != nil {
return errors.Wrap(err, "descendent block not in db")
}
blocks = append(blocks, descendent)
roots = append(roots, q.Descendent.Root)
return nil
})
return blocks, roots, err
}
// stop before the descendent slot since it is determined by the query
sr, err := s.slotRootsInRange(ctx, q.Earliest, q.Descendent.Slot-1, -1)
if err != nil {
return nil, nil, err
}
err = s.db.View(func(tx *bolt.Tx) error {
descendent, err := s.getBlock(ctx, q.Descendent.Root, tx)
if err != nil {
return errors.Wrap(err, "descendent block not in db")
}
proot := descendent.Block().ParentRoot()
lowest := descendent.Block().Slot()
blocks = append(blocks, descendent)
roots = append(roots, q.Descendent.Root)
// slotRootsInRange returns the roots in descending order
for _, prev := range sr {
if prev.slot < q.Earliest {
return nil
}
if prev.slot >= lowest {
continue
}
if prev.root == proot {
p, err := s.getBlock(ctx, prev.root, tx)
if err != nil {
return err
}
roots = append(roots, prev.root)
blocks = append(blocks, p)
proot = p.Block().ParentRoot()
lowest = p.Block().Slot()
}
}
return nil
})
if err != nil {
return nil, nil, err
}
slices.Reverse(roots)
slices.Reverse(blocks)
return blocks, roots, err
}
// Blocks retrieves a list of beacon blocks and its respective roots by filter criteria.
func (s *Store) Blocks(ctx context.Context, f *filters.QueryFilter) ([]interfaces.ReadOnlySignedBeaconBlock, [][32]byte, error) {
ctx, span := trace.StartSpan(ctx, "BeaconDB.Blocks")
defer span.End()
if q, err := f.GetAncestryQuery(); err == nil {
return s.blocksAncestryQuery(ctx, q)
} else {
if !errors.Is(err, filters.ErrNotSet) {
return nil, nil, err
}
}
blocks := make([]interfaces.ReadOnlySignedBeaconBlock, 0)
blockRoots := make([][32]byte, 0)
if start, end, isSimple := f.SimpleSlotRange(); isSimple {
return s.blocksForSlotRange(ctx, start, end)
}
err := s.db.View(func(tx *bolt.Tx) error {
bkt := tx.Bucket(blocksBucket)
@@ -146,6 +229,69 @@ func (s *Store) Blocks(ctx context.Context, f *filters.QueryFilter) ([]interface
return blocks, blockRoots, err
}
// cleanupMissingBlockIndices cleans up the slot->root mapping, and the parent root index pointing
// from each of these blocks to each of their children. Since we don't have the blocks themselves,
// we don't know their parent root to efficiently clean the index going the other direction.
func (s *Store) cleanupMissingBlockIndices(ctx context.Context, badBlocks []slotRoot) {
errs := make([]error, 0)
err := s.db.Update(func(tx *bolt.Tx) error {
for _, sr := range badBlocks {
log.WithField("root", fmt.Sprintf("%#x", sr.root)).WithField("slot", sr.slot).Warn("Cleaning up indices for missing block")
if err := s.deleteSlotIndexEntry(tx, sr.slot, sr.root); err != nil {
errs = append(errs, errors.Wrapf(err, "failed to clean up slot index entry for root %#x and slot %d", sr.root, sr.slot))
}
if err := tx.Bucket(blockParentRootIndicesBucket).Delete(sr.root[:]); err != nil {
errs = append(errs, errors.Wrapf(err, "failed to clean up block parent index for root %#x", sr.root))
}
}
return nil
})
if err != nil {
errs = append(errs, err)
}
for _, err := range errs {
log.WithError(err).Error("Failed to clean up indices for missing block")
}
}
// blocksForSlotRange gets all blocks and roots for a given slot range.
// This function uses the slot->root index, which can contain multiple entries for the same slot
// in case of forks. It will return all blocks for the given slot range, and the roots of those blocks.
// The [i]th element of the blocks slice corresponds to the [i]th element of the roots slice.
// If a block is not found, it will be added to a slice of missing blocks, which will have their indices cleaned
// in a separate Update transaction before the method returns. This is done to compensate for a previous bug where
// block deletions left danging index entries.
func (s *Store) blocksForSlotRange(ctx context.Context, startSlot, endSlot primitives.Slot) ([]interfaces.ReadOnlySignedBeaconBlock, [][32]byte, error) {
slotRootPairs, err := s.slotRootsInRange(ctx, startSlot, endSlot, -1) // set batch size to zero to retrieve all
if err != nil {
return nil, nil, err
}
slices.Reverse(slotRootPairs)
badBlocks := make([]slotRoot, 0)
defer func() { s.cleanupMissingBlockIndices(ctx, badBlocks) }()
roots := make([][32]byte, 0, len(slotRootPairs))
blks := make([]interfaces.ReadOnlySignedBeaconBlock, 0, len(slotRootPairs))
err = s.db.View(func(tx *bolt.Tx) error {
for _, sr := range slotRootPairs {
blk, err := s.getBlock(ctx, sr.root, tx)
if err != nil {
if errors.Is(err, ErrNotFound) {
badBlocks = append(badBlocks, sr)
continue
}
return err
}
roots = append(roots, sr.root)
blks = append(blks, blk)
}
return nil
})
if err != nil {
return nil, nil, err
}
return blks, roots, nil
}
// BlockRoots retrieves a list of beacon block roots by filter criteria. If the caller
// requires both the blocks and the block roots for a certain filter they should instead
// use the Blocks function rather than use BlockRoots. During periods of non finality
@@ -720,6 +866,7 @@ type slotRoot struct {
}
// slotRootsInRange returns slot and block root pairs of length min(batchSize, end-slot)
// If batchSize < 0, the limit check will be skipped entirely.
func (s *Store) slotRootsInRange(ctx context.Context, start, end primitives.Slot, batchSize int) ([]slotRoot, error) {
_, span := trace.StartSpan(ctx, "BeaconDB.slotRootsInRange")
defer span.End()
@@ -729,10 +876,26 @@ func (s *Store) slotRootsInRange(ctx context.Context, start, end primitives.Slot
var pairs []slotRoot
key := bytesutil.SlotToBytesBigEndian(end)
edge := false // used to detect whether we are at the very beginning or end of the index
err := s.db.View(func(tx *bolt.Tx) error {
bkt := tx.Bucket(blockSlotIndicesBucket)
c := bkt.Cursor()
for k, v := c.Seek(key); k != nil; k, v = c.Prev() {
for k, v := c.Seek(key); ; /* rely on internal checks to exit */ k, v = c.Prev() {
if len(k) == 0 && len(v) == 0 {
// The `edge`` variable and this `if` deal with 2 edge cases:
// - Seeking past the end of the bucket (the `end` param is higher than the highest slot).
// - Seeking before the beginning of the bucket (the `start` param is lower than the lowest slot).
// In both of these cases k,v will be nil and we can handle the same way using `edge` to
// - continue to the next iteration. If the following Prev() key/value is nil, Prev has gone past the beginning.
// - Otherwise, iterate as usual.
if edge {
return nil
}
edge = true
continue
}
edge = false
slot := bytesutil.BytesToSlotBigEndian(k)
if slot > end {
continue // Seek will seek to the next key *after* the given one if not present
@@ -747,11 +910,13 @@ func (s *Store) slotRootsInRange(ctx context.Context, start, end primitives.Slot
for _, r := range roots {
pairs = append(pairs, slotRoot{slot: slot, root: r})
}
if batchSize < 0 {
continue
}
if len(pairs) >= batchSize {
return nil // allows code to easily cap the number of items pruned
}
}
return nil
})
return pairs, err

View File

@@ -24,9 +24,11 @@ import (
"google.golang.org/protobuf/proto"
)
type testNewBlockFunc func(primitives.Slot, []byte) (interfaces.ReadOnlySignedBeaconBlock, error)
var blockTests = []struct {
name string
newBlock func(primitives.Slot, []byte) (interfaces.ReadOnlySignedBeaconBlock, error)
newBlock testNewBlockFunc
}{
{
name: "phase0",
@@ -742,6 +744,120 @@ func TestStore_Blocks_FiltersCorrectly(t *testing.T) {
}
}
func testBlockChain(t *testing.T, nb testNewBlockFunc, slots []primitives.Slot, parent []byte) []interfaces.ReadOnlySignedBeaconBlock {
if len(parent) < 32 {
var zero [32]byte
copy(parent, zero[:])
}
chain := make([]interfaces.ReadOnlySignedBeaconBlock, 0, len(slots))
for _, slot := range slots {
pr := make([]byte, 32)
copy(pr, parent)
b, err := nb(slot, pr)
require.NoError(t, err)
chain = append(chain, b)
npr, err := b.Block().HashTreeRoot()
parent = npr[:]
require.NoError(t, err)
}
return chain
}
func testSlotSlice(start, end primitives.Slot) []primitives.Slot {
end += 1 // add 1 to make the range inclusive
slots := make([]primitives.Slot, 0, end-start)
for ; start < end; start++ {
slots = append(slots, start)
}
return slots
}
func TestCleanupMissingBlockIndices(t *testing.T) {
for _, tt := range blockTests {
t.Run(tt.name, func(t *testing.T) {
ctx := context.Background()
db := setupDB(t)
chain := testBlockChain(t, tt.newBlock, testSlotSlice(1, 10), nil)
require.NoError(t, db.SaveBlocks(ctx, chain))
corrupt, err := blocks.NewROBlock(chain[5])
require.NoError(t, err)
cr := corrupt.Root()
require.NoError(t, db.db.Update(func(tx *bolt.Tx) error {
return tx.Bucket(blocksBucket).Delete(cr[:])
}))
// Need to also delete it from the cache!!
db.blockCache.Del(string(cr[:]))
res, roots, err := db.Blocks(ctx, filters.NewFilter().SetEndSlot(10).SetStartSlot(1))
require.NoError(t, err)
require.Equal(t, 9, len(roots))
require.Equal(t, len(res), len(roots))
require.NoError(t, db.db.View(func(tx *bolt.Tx) error {
encSlot := bytesutil.SlotToBytesBigEndian(corrupt.Block().Slot())
// make sure slot->root index is cleaned up
require.Equal(t, 0, len(tx.Bucket(blockSlotIndicesBucket).Get(encSlot)))
require.Equal(t, 0, len(tx.Bucket(blockParentRootIndicesBucket).Get(cr[:])))
return nil
}))
})
}
}
func TestCleanupMissingForkedBlockIndices(t *testing.T) {
for _, tt := range blockTests[0:1] {
t.Run(tt.name, func(t *testing.T) {
ctx := context.Background()
db := setupDB(t)
chain := testBlockChain(t, tt.newBlock, testSlotSlice(1, 10), nil)
require.NoError(t, db.SaveBlocks(ctx, chain))
// forkChain should skip the slot at skipBlock, and have the same parent
skipBlockParent := chain[4].Block().ParentRoot()
// It should start at the same slot as missingBlock, which comes one slot after the skip slot,
// so there are 2 blocks in that slot
missingBlock, err := blocks.NewROBlock(chain[5])
require.NoError(t, err)
// missingBlock will be deleted in the main chain, but there will be a block at that slot in the fork chain
forkChain := testBlockChain(t, tt.newBlock, testSlotSlice(missingBlock.Block().Slot(), 10), skipBlockParent[:])
require.NoError(t, db.SaveBlocks(ctx, forkChain))
forkChainStart, err := blocks.NewROBlock(forkChain[0])
require.NoError(t, err)
encMissingSlot := bytesutil.SlotToBytesBigEndian(missingBlock.Block().Slot())
require.NoError(t, db.db.View(func(tx *bolt.Tx) error {
require.Equal(t, 32, len(tx.Bucket(blockParentRootIndicesBucket).Get(missingBlock.RootSlice())))
// There are 2 block roots packed in this slot, so it is 64 bytes long
require.Equal(t, 64, len(tx.Bucket(blockSlotIndicesBucket).Get(encMissingSlot)))
// skipBlockParent should also have 2 entries and be 64 bytes, since the forkChain is based on the same parent as the skip block
childRoots := tx.Bucket(blockParentRootIndicesBucket).Get(skipBlockParent[:])
require.Equal(t, 64, len(childRoots))
return nil
}))
require.NoError(t, db.db.Update(func(tx *bolt.Tx) error {
return tx.Bucket(blocksBucket).Delete(missingBlock.RootSlice())
}))
// Need to also delete it from the cache!!
db.blockCache.Del(string(missingBlock.RootSlice()))
// Blocks should give us blocks from all chains.
res, roots, err := db.Blocks(ctx, filters.NewFilter().SetEndSlot(10).SetStartSlot(1))
require.NoError(t, err)
require.Equal(t, (len(chain)-1)+len(forkChain), len(roots))
require.Equal(t, len(res), len(roots))
require.NoError(t, db.db.View(func(tx *bolt.Tx) error {
// There should now be 32 bytes in this index - one root from the forked chain
slotIdxVal := tx.Bucket(blockSlotIndicesBucket).Get(encMissingSlot)
require.Equal(t, forkChainStart.Root(), [32]byte(slotIdxVal))
require.Equal(t, 0, len(tx.Bucket(blockParentRootIndicesBucket).Get(missingBlock.RootSlice())))
forkChildRoot := tx.Bucket(blockParentRootIndicesBucket).Get(skipBlockParent[:])
require.Equal(t, 64, len(forkChildRoot))
return nil
}))
})
}
}
func TestStore_Blocks_VerifyBlockRoots(t *testing.T) {
for _, tt := range blockTests {
t.Run(tt.name, func(t *testing.T) {

View File

@@ -587,7 +587,7 @@ func BenchmarkHighestAttestations(b *testing.B) {
beaconDB := setupDB(b)
require.NoError(b, beaconDB.SaveAttestationRecordsForValidators(ctx, atts))
allIndices := make([]primitives.ValidatorIndex, valsPerAtt*count)
allIndices := make([]primitives.ValidatorIndex, 0, valsPerAtt*count)
for i := 0; i < count; i++ {
indicesForAtt := make([]primitives.ValidatorIndex, valsPerAtt)
for r := 0; r < valsPerAtt; r++ {

View File

@@ -61,7 +61,6 @@ go_library(
"//monitoring/prometheus:go_default_library",
"//monitoring/tracing:go_default_library",
"//runtime:go_default_library",
"//runtime/debug:go_default_library",
"//runtime/prereqs:go_default_library",
"//runtime/version:go_default_library",
"@com_github_ethereum_go_ethereum//common:go_default_library",

View File

@@ -64,7 +64,6 @@ import (
"github.com/prysmaticlabs/prysm/v5/encoding/bytesutil"
"github.com/prysmaticlabs/prysm/v5/monitoring/prometheus"
"github.com/prysmaticlabs/prysm/v5/runtime"
"github.com/prysmaticlabs/prysm/v5/runtime/debug"
"github.com/prysmaticlabs/prysm/v5/runtime/prereqs"
"github.com/prysmaticlabs/prysm/v5/runtime/version"
"github.com/sirupsen/logrus"
@@ -432,7 +431,6 @@ func (b *BeaconNode) Start() {
defer signal.Stop(sigc)
<-sigc
log.Info("Got interrupt, shutting down...")
debug.Exit(b.cliCtx) // Ensure trace and CPU profile data are flushed.
go b.Close()
for i := 10; i > 0; i-- {
<-sigc

View File

@@ -17,6 +17,7 @@ go_library(
"//validator/client:__pkg__",
],
deps = [
"//config/fieldparams:go_default_library",
"//config/params:go_default_library",
"//consensus-types/blocks:go_default_library",
"//consensus-types/interfaces:go_default_library",

View File

@@ -9,12 +9,11 @@ import (
"github.com/pkg/errors"
ssz "github.com/prysmaticlabs/fastssz"
fieldparams "github.com/prysmaticlabs/prysm/v5/config/fieldparams"
"github.com/prysmaticlabs/prysm/v5/config/params"
eth "github.com/prysmaticlabs/prysm/v5/proto/prysm/v1alpha1"
)
const rootLength = 32
const maxErrorLength = 256
// SSZBytes is a bytes slice that satisfies the fast-ssz interface.
@@ -34,7 +33,7 @@ func (b *SSZBytes) HashTreeRootWith(hh *ssz.Hasher) error {
}
// BeaconBlockByRootsReq specifies the block by roots request type.
type BeaconBlockByRootsReq [][rootLength]byte
type BeaconBlockByRootsReq [][fieldparams.RootLength]byte
// MarshalSSZTo marshals the block by roots request with the provided byte slice.
func (r *BeaconBlockByRootsReq) MarshalSSZTo(dst []byte) ([]byte, error) {
@@ -59,25 +58,25 @@ func (r *BeaconBlockByRootsReq) MarshalSSZ() ([]byte, error) {
// SizeSSZ returns the size of the serialized representation.
func (r *BeaconBlockByRootsReq) SizeSSZ() int {
return len(*r) * rootLength
return len(*r) * fieldparams.RootLength
}
// UnmarshalSSZ unmarshals the provided bytes buffer into the
// block by roots request object.
func (r *BeaconBlockByRootsReq) UnmarshalSSZ(buf []byte) error {
bufLen := len(buf)
maxLength := int(params.BeaconConfig().MaxRequestBlocks * rootLength)
maxLength := int(params.BeaconConfig().MaxRequestBlocks * fieldparams.RootLength)
if bufLen > maxLength {
return errors.Errorf("expected buffer with length of up to %d but received length %d", maxLength, bufLen)
}
if bufLen%rootLength != 0 {
if bufLen%fieldparams.RootLength != 0 {
return ssz.ErrIncorrectByteSize
}
numOfRoots := bufLen / rootLength
roots := make([][rootLength]byte, 0, numOfRoots)
numOfRoots := bufLen / fieldparams.RootLength
roots := make([][fieldparams.RootLength]byte, 0, numOfRoots)
for i := 0; i < numOfRoots; i++ {
var rt [rootLength]byte
copy(rt[:], buf[i*rootLength:(i+1)*rootLength])
var rt [fieldparams.RootLength]byte
copy(rt[:], buf[i*fieldparams.RootLength:(i+1)*fieldparams.RootLength])
roots = append(roots, rt)
}
*r = roots

View File

@@ -11,7 +11,7 @@ go_library(
importpath = "github.com/prysmaticlabs/prysm/v5/beacon-chain/rpc",
visibility = ["//beacon-chain:__subpackages__"],
deps = [
"//api:go_default_library",
"//api/httputil:go_default_library",
"//api/server/middleware:go_default_library",
"//beacon-chain/blockchain:go_default_library",
"//beacon-chain/builder:go_default_library",

View File

@@ -5,7 +5,7 @@ import (
"github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/client_golang/prometheus/promhttp"
"github.com/prysmaticlabs/prysm/v5/api"
"github.com/prysmaticlabs/prysm/v5/api/httputil"
"github.com/prysmaticlabs/prysm/v5/api/server/middleware"
"github.com/prysmaticlabs/prysm/v5/beacon-chain/rpc/core"
"github.com/prysmaticlabs/prysm/v5/beacon-chain/rpc/eth/beacon"
@@ -123,7 +123,7 @@ func (s *Service) rewardsEndpoints(blocker lookup.Blocker, stater lookup.Stater,
template: "/eth/v1/beacon/rewards/blocks/{block_id}",
name: namespace + ".BlockRewards",
middleware: []middleware.Middleware{
middleware.AcceptHeaderHandler([]string{api.JsonMediaType}),
middleware.AcceptHeaderHandler([]string{httputil.JsonMediaType}),
},
handler: server.BlockRewards,
methods: []string{http.MethodGet},
@@ -132,8 +132,8 @@ func (s *Service) rewardsEndpoints(blocker lookup.Blocker, stater lookup.Stater,
template: "/eth/v1/beacon/rewards/attestations/{epoch}",
name: namespace + ".AttestationRewards",
middleware: []middleware.Middleware{
middleware.ContentTypeHandler([]string{api.JsonMediaType}),
middleware.AcceptHeaderHandler([]string{api.JsonMediaType}),
middleware.ContentTypeHandler([]string{httputil.JsonMediaType}),
middleware.AcceptHeaderHandler([]string{httputil.JsonMediaType}),
},
handler: server.AttestationRewards,
methods: []string{http.MethodPost},
@@ -142,8 +142,8 @@ func (s *Service) rewardsEndpoints(blocker lookup.Blocker, stater lookup.Stater,
template: "/eth/v1/beacon/rewards/sync_committee/{block_id}",
name: namespace + ".SyncCommitteeRewards",
middleware: []middleware.Middleware{
middleware.ContentTypeHandler([]string{api.JsonMediaType}),
middleware.AcceptHeaderHandler([]string{api.JsonMediaType}),
middleware.ContentTypeHandler([]string{httputil.JsonMediaType}),
middleware.AcceptHeaderHandler([]string{httputil.JsonMediaType}),
},
handler: server.SyncCommitteeRewards,
methods: []string{http.MethodPost},
@@ -165,7 +165,7 @@ func (s *Service) builderEndpoints(stater lookup.Stater) []endpoint {
template: "/eth/v1/builder/states/{state_id}/expected_withdrawals",
name: namespace + ".ExpectedWithdrawals",
middleware: []middleware.Middleware{
middleware.AcceptHeaderHandler([]string{api.JsonMediaType, api.OctetStreamMediaType}),
middleware.AcceptHeaderHandler([]string{httputil.JsonMediaType, httputil.OctetStreamMediaType}),
},
handler: server.ExpectedWithdrawals,
methods: []string{http.MethodGet},
@@ -187,7 +187,7 @@ func (s *Service) blobEndpoints(blocker lookup.Blocker) []endpoint {
template: "/eth/v1/beacon/blob_sidecars/{block_id}",
name: namespace + ".Blobs",
middleware: []middleware.Middleware{
middleware.AcceptHeaderHandler([]string{api.JsonMediaType, api.OctetStreamMediaType}),
middleware.AcceptHeaderHandler([]string{httputil.JsonMediaType, httputil.OctetStreamMediaType}),
},
handler: server.Blobs,
methods: []string{http.MethodGet},
@@ -230,7 +230,7 @@ func (s *Service) validatorEndpoints(
template: "/eth/v1/validator/aggregate_attestation",
name: namespace + ".GetAggregateAttestation",
middleware: []middleware.Middleware{
middleware.AcceptHeaderHandler([]string{api.JsonMediaType}),
middleware.AcceptHeaderHandler([]string{httputil.JsonMediaType}),
},
handler: server.GetAggregateAttestation,
methods: []string{http.MethodGet},
@@ -239,7 +239,7 @@ func (s *Service) validatorEndpoints(
template: "/eth/v2/validator/aggregate_attestation",
name: namespace + ".GetAggregateAttestationV2",
middleware: []middleware.Middleware{
middleware.AcceptHeaderHandler([]string{api.JsonMediaType}),
middleware.AcceptHeaderHandler([]string{httputil.JsonMediaType}),
},
handler: server.GetAggregateAttestationV2,
methods: []string{http.MethodGet},
@@ -248,8 +248,8 @@ func (s *Service) validatorEndpoints(
template: "/eth/v1/validator/contribution_and_proofs",
name: namespace + ".SubmitContributionAndProofs",
middleware: []middleware.Middleware{
middleware.ContentTypeHandler([]string{api.JsonMediaType}),
middleware.AcceptHeaderHandler([]string{api.JsonMediaType}),
middleware.ContentTypeHandler([]string{httputil.JsonMediaType}),
middleware.AcceptHeaderHandler([]string{httputil.JsonMediaType}),
},
handler: server.SubmitContributionAndProofs,
methods: []string{http.MethodPost},
@@ -259,8 +259,8 @@ func (s *Service) validatorEndpoints(
template: "/eth/v1/validator/aggregate_and_proofs",
name: namespace + ".SubmitAggregateAndProofs",
middleware: []middleware.Middleware{
middleware.ContentTypeHandler([]string{api.JsonMediaType}),
middleware.AcceptHeaderHandler([]string{api.JsonMediaType}),
middleware.ContentTypeHandler([]string{httputil.JsonMediaType}),
middleware.AcceptHeaderHandler([]string{httputil.JsonMediaType}),
},
handler: server.SubmitAggregateAndProofs,
methods: []string{http.MethodPost},
@@ -269,8 +269,8 @@ func (s *Service) validatorEndpoints(
template: "/eth/v2/validator/aggregate_and_proofs",
name: namespace + ".SubmitAggregateAndProofsV2",
middleware: []middleware.Middleware{
middleware.ContentTypeHandler([]string{api.JsonMediaType}),
middleware.AcceptHeaderHandler([]string{api.JsonMediaType}),
middleware.ContentTypeHandler([]string{httputil.JsonMediaType}),
middleware.AcceptHeaderHandler([]string{httputil.JsonMediaType}),
},
handler: server.SubmitAggregateAndProofsV2,
methods: []string{http.MethodPost},
@@ -279,7 +279,7 @@ func (s *Service) validatorEndpoints(
template: "/eth/v1/validator/sync_committee_contribution",
name: namespace + ".ProduceSyncCommitteeContribution",
middleware: []middleware.Middleware{
middleware.AcceptHeaderHandler([]string{api.JsonMediaType}),
middleware.AcceptHeaderHandler([]string{httputil.JsonMediaType}),
},
handler: server.ProduceSyncCommitteeContribution,
methods: []string{http.MethodGet},
@@ -288,8 +288,8 @@ func (s *Service) validatorEndpoints(
template: "/eth/v1/validator/sync_committee_subscriptions",
name: namespace + ".SubmitSyncCommitteeSubscription",
middleware: []middleware.Middleware{
middleware.ContentTypeHandler([]string{api.JsonMediaType}),
middleware.AcceptHeaderHandler([]string{api.JsonMediaType}),
middleware.ContentTypeHandler([]string{httputil.JsonMediaType}),
middleware.AcceptHeaderHandler([]string{httputil.JsonMediaType}),
},
handler: server.SubmitSyncCommitteeSubscription,
methods: []string{http.MethodPost},
@@ -298,8 +298,8 @@ func (s *Service) validatorEndpoints(
template: "/eth/v1/validator/beacon_committee_subscriptions",
name: namespace + ".SubmitBeaconCommitteeSubscription",
middleware: []middleware.Middleware{
middleware.ContentTypeHandler([]string{api.JsonMediaType}),
middleware.AcceptHeaderHandler([]string{api.JsonMediaType}),
middleware.ContentTypeHandler([]string{httputil.JsonMediaType}),
middleware.AcceptHeaderHandler([]string{httputil.JsonMediaType}),
},
handler: server.SubmitBeaconCommitteeSubscription,
methods: []string{http.MethodPost},
@@ -308,7 +308,7 @@ func (s *Service) validatorEndpoints(
template: "/eth/v1/validator/attestation_data",
name: namespace + ".GetAttestationData",
middleware: []middleware.Middleware{
middleware.AcceptHeaderHandler([]string{api.JsonMediaType}),
middleware.AcceptHeaderHandler([]string{httputil.JsonMediaType}),
},
handler: server.GetAttestationData,
methods: []string{http.MethodGet},
@@ -317,8 +317,8 @@ func (s *Service) validatorEndpoints(
template: "/eth/v1/validator/register_validator",
name: namespace + ".RegisterValidator",
middleware: []middleware.Middleware{
middleware.ContentTypeHandler([]string{api.JsonMediaType}),
middleware.AcceptHeaderHandler([]string{api.JsonMediaType}),
middleware.ContentTypeHandler([]string{httputil.JsonMediaType}),
middleware.AcceptHeaderHandler([]string{httputil.JsonMediaType}),
},
handler: server.RegisterValidator,
methods: []string{http.MethodPost},
@@ -327,8 +327,8 @@ func (s *Service) validatorEndpoints(
template: "/eth/v1/validator/duties/attester/{epoch}",
name: namespace + ".GetAttesterDuties",
middleware: []middleware.Middleware{
middleware.ContentTypeHandler([]string{api.JsonMediaType}),
middleware.AcceptHeaderHandler([]string{api.JsonMediaType}),
middleware.ContentTypeHandler([]string{httputil.JsonMediaType}),
middleware.AcceptHeaderHandler([]string{httputil.JsonMediaType}),
},
handler: server.GetAttesterDuties,
methods: []string{http.MethodPost},
@@ -337,7 +337,7 @@ func (s *Service) validatorEndpoints(
template: "/eth/v1/validator/duties/proposer/{epoch}",
name: namespace + ".GetProposerDuties",
middleware: []middleware.Middleware{
middleware.AcceptHeaderHandler([]string{api.JsonMediaType}),
middleware.AcceptHeaderHandler([]string{httputil.JsonMediaType}),
},
handler: server.GetProposerDuties,
methods: []string{http.MethodGet},
@@ -346,8 +346,8 @@ func (s *Service) validatorEndpoints(
template: "/eth/v1/validator/duties/sync/{epoch}",
name: namespace + ".GetSyncCommitteeDuties",
middleware: []middleware.Middleware{
middleware.ContentTypeHandler([]string{api.JsonMediaType}),
middleware.AcceptHeaderHandler([]string{api.JsonMediaType}),
middleware.ContentTypeHandler([]string{httputil.JsonMediaType}),
middleware.AcceptHeaderHandler([]string{httputil.JsonMediaType}),
},
handler: server.GetSyncCommitteeDuties,
methods: []string{http.MethodPost},
@@ -356,8 +356,8 @@ func (s *Service) validatorEndpoints(
template: "/eth/v1/validator/prepare_beacon_proposer",
name: namespace + ".PrepareBeaconProposer",
middleware: []middleware.Middleware{
middleware.ContentTypeHandler([]string{api.JsonMediaType}),
middleware.AcceptHeaderHandler([]string{api.JsonMediaType}),
middleware.ContentTypeHandler([]string{httputil.JsonMediaType}),
middleware.AcceptHeaderHandler([]string{httputil.JsonMediaType}),
},
handler: server.PrepareBeaconProposer,
methods: []string{http.MethodPost},
@@ -366,8 +366,8 @@ func (s *Service) validatorEndpoints(
template: "/eth/v1/validator/liveness/{epoch}",
name: namespace + ".GetLiveness",
middleware: []middleware.Middleware{
middleware.ContentTypeHandler([]string{api.JsonMediaType}),
middleware.AcceptHeaderHandler([]string{api.JsonMediaType}),
middleware.ContentTypeHandler([]string{httputil.JsonMediaType}),
middleware.AcceptHeaderHandler([]string{httputil.JsonMediaType}),
},
handler: server.GetLiveness,
methods: []string{http.MethodPost},
@@ -376,7 +376,7 @@ func (s *Service) validatorEndpoints(
template: "/eth/v2/validator/blocks/{slot}",
name: namespace + ".ProduceBlockV2",
middleware: []middleware.Middleware{
middleware.AcceptHeaderHandler([]string{api.JsonMediaType, api.OctetStreamMediaType}),
middleware.AcceptHeaderHandler([]string{httputil.JsonMediaType, httputil.OctetStreamMediaType}),
},
handler: server.ProduceBlockV2,
methods: []string{http.MethodGet},
@@ -385,7 +385,7 @@ func (s *Service) validatorEndpoints(
template: "/eth/v1/validator/blinded_blocks/{slot}",
name: namespace + ".ProduceBlindedBlock",
middleware: []middleware.Middleware{
middleware.AcceptHeaderHandler([]string{api.JsonMediaType, api.OctetStreamMediaType}),
middleware.AcceptHeaderHandler([]string{httputil.JsonMediaType, httputil.OctetStreamMediaType}),
},
handler: server.ProduceBlindedBlock,
methods: []string{http.MethodGet},
@@ -394,7 +394,7 @@ func (s *Service) validatorEndpoints(
template: "/eth/v3/validator/blocks/{slot}",
name: namespace + ".ProduceBlockV3",
middleware: []middleware.Middleware{
middleware.AcceptHeaderHandler([]string{api.JsonMediaType, api.OctetStreamMediaType}),
middleware.AcceptHeaderHandler([]string{httputil.JsonMediaType, httputil.OctetStreamMediaType}),
},
handler: server.ProduceBlockV3,
methods: []string{http.MethodGet},
@@ -403,7 +403,7 @@ func (s *Service) validatorEndpoints(
template: "/eth/v1/validator/beacon_committee_selections",
name: namespace + ".BeaconCommitteeSelections",
middleware: []middleware.Middleware{
middleware.ContentTypeHandler([]string{api.JsonMediaType}),
middleware.ContentTypeHandler([]string{httputil.JsonMediaType}),
},
handler: server.BeaconCommitteeSelections,
methods: []string{http.MethodPost},
@@ -412,7 +412,7 @@ func (s *Service) validatorEndpoints(
template: "/eth/v1/validator/sync_committee_selections",
name: namespace + ".SyncCommittee Selections",
middleware: []middleware.Middleware{
middleware.ContentTypeHandler([]string{api.JsonMediaType}),
middleware.ContentTypeHandler([]string{httputil.JsonMediaType}),
},
handler: server.SyncCommitteeSelections,
methods: []string{http.MethodPost},
@@ -440,7 +440,7 @@ func (s *Service) nodeEndpoints() []endpoint {
template: "/eth/v1/node/syncing",
name: namespace + ".GetSyncStatus",
middleware: []middleware.Middleware{
middleware.AcceptHeaderHandler([]string{api.JsonMediaType}),
middleware.AcceptHeaderHandler([]string{httputil.JsonMediaType}),
},
handler: server.GetSyncStatus,
methods: []string{http.MethodGet},
@@ -449,7 +449,7 @@ func (s *Service) nodeEndpoints() []endpoint {
template: "/eth/v1/node/identity",
name: namespace + ".GetIdentity",
middleware: []middleware.Middleware{
middleware.AcceptHeaderHandler([]string{api.JsonMediaType}),
middleware.AcceptHeaderHandler([]string{httputil.JsonMediaType}),
},
handler: server.GetIdentity,
methods: []string{http.MethodGet},
@@ -458,7 +458,7 @@ func (s *Service) nodeEndpoints() []endpoint {
template: "/eth/v1/node/peers/{peer_id}",
name: namespace + ".GetPeer",
middleware: []middleware.Middleware{
middleware.AcceptHeaderHandler([]string{api.JsonMediaType}),
middleware.AcceptHeaderHandler([]string{httputil.JsonMediaType}),
},
handler: server.GetPeer,
methods: []string{http.MethodGet},
@@ -467,7 +467,7 @@ func (s *Service) nodeEndpoints() []endpoint {
template: "/eth/v1/node/peers",
name: namespace + ".GetPeers",
middleware: []middleware.Middleware{
middleware.AcceptHeaderHandler([]string{api.JsonMediaType}),
middleware.AcceptHeaderHandler([]string{httputil.JsonMediaType}),
},
handler: server.GetPeers,
methods: []string{http.MethodGet},
@@ -476,7 +476,7 @@ func (s *Service) nodeEndpoints() []endpoint {
template: "/eth/v1/node/peer_count",
name: namespace + ".GetPeerCount",
middleware: []middleware.Middleware{
middleware.AcceptHeaderHandler([]string{api.JsonMediaType}),
middleware.AcceptHeaderHandler([]string{httputil.JsonMediaType}),
},
handler: server.GetPeerCount,
methods: []string{http.MethodGet},
@@ -485,7 +485,7 @@ func (s *Service) nodeEndpoints() []endpoint {
template: "/eth/v1/node/version",
name: namespace + ".GetVersion",
middleware: []middleware.Middleware{
middleware.AcceptHeaderHandler([]string{api.JsonMediaType}),
middleware.AcceptHeaderHandler([]string{httputil.JsonMediaType}),
},
handler: server.GetVersion,
methods: []string{http.MethodGet},
@@ -494,7 +494,7 @@ func (s *Service) nodeEndpoints() []endpoint {
template: "/eth/v1/node/health",
name: namespace + ".GetHealth",
middleware: []middleware.Middleware{
middleware.AcceptHeaderHandler([]string{api.JsonMediaType}),
middleware.AcceptHeaderHandler([]string{httputil.JsonMediaType}),
},
handler: server.GetHealth,
methods: []string{http.MethodGet},
@@ -544,7 +544,7 @@ func (s *Service) beaconEndpoints(
template: "/eth/v1/beacon/states/{state_id}/committees",
name: namespace + ".GetCommittees",
middleware: []middleware.Middleware{
middleware.AcceptHeaderHandler([]string{api.JsonMediaType}),
middleware.AcceptHeaderHandler([]string{httputil.JsonMediaType}),
},
handler: server.GetCommittees,
methods: []string{http.MethodGet},
@@ -553,7 +553,7 @@ func (s *Service) beaconEndpoints(
template: "/eth/v1/beacon/states/{state_id}/fork",
name: namespace + ".GetStateFork",
middleware: []middleware.Middleware{
middleware.AcceptHeaderHandler([]string{api.JsonMediaType}),
middleware.AcceptHeaderHandler([]string{httputil.JsonMediaType}),
},
handler: server.GetStateFork,
methods: []string{http.MethodGet},
@@ -562,7 +562,7 @@ func (s *Service) beaconEndpoints(
template: "/eth/v1/beacon/states/{state_id}/root",
name: namespace + ".GetStateRoot",
middleware: []middleware.Middleware{
middleware.AcceptHeaderHandler([]string{api.JsonMediaType}),
middleware.AcceptHeaderHandler([]string{httputil.JsonMediaType}),
},
handler: server.GetStateRoot,
methods: []string{http.MethodGet},
@@ -571,7 +571,7 @@ func (s *Service) beaconEndpoints(
template: "/eth/v1/beacon/states/{state_id}/sync_committees",
name: namespace + ".GetSyncCommittees",
middleware: []middleware.Middleware{
middleware.AcceptHeaderHandler([]string{api.JsonMediaType}),
middleware.AcceptHeaderHandler([]string{httputil.JsonMediaType}),
},
handler: server.GetSyncCommittees,
methods: []string{http.MethodGet},
@@ -580,7 +580,7 @@ func (s *Service) beaconEndpoints(
template: "/eth/v1/beacon/states/{state_id}/randao",
name: namespace + ".GetRandao",
middleware: []middleware.Middleware{
middleware.AcceptHeaderHandler([]string{api.JsonMediaType}),
middleware.AcceptHeaderHandler([]string{httputil.JsonMediaType}),
},
handler: server.GetRandao,
methods: []string{http.MethodGet},
@@ -590,8 +590,8 @@ func (s *Service) beaconEndpoints(
template: "/eth/v1/beacon/blocks",
name: namespace + ".PublishBlock",
middleware: []middleware.Middleware{
middleware.ContentTypeHandler([]string{api.JsonMediaType, api.OctetStreamMediaType}),
middleware.AcceptHeaderHandler([]string{api.JsonMediaType}),
middleware.ContentTypeHandler([]string{httputil.JsonMediaType, httputil.OctetStreamMediaType}),
middleware.AcceptHeaderHandler([]string{httputil.JsonMediaType}),
},
handler: server.PublishBlock,
methods: []string{http.MethodPost},
@@ -601,8 +601,8 @@ func (s *Service) beaconEndpoints(
template: "/eth/v1/beacon/blinded_blocks",
name: namespace + ".PublishBlindedBlock",
middleware: []middleware.Middleware{
middleware.ContentTypeHandler([]string{api.JsonMediaType, api.OctetStreamMediaType}),
middleware.AcceptHeaderHandler([]string{api.JsonMediaType}),
middleware.ContentTypeHandler([]string{httputil.JsonMediaType, httputil.OctetStreamMediaType}),
middleware.AcceptHeaderHandler([]string{httputil.JsonMediaType}),
},
handler: server.PublishBlindedBlock,
methods: []string{http.MethodPost},
@@ -611,8 +611,8 @@ func (s *Service) beaconEndpoints(
template: "/eth/v2/beacon/blocks",
name: namespace + ".PublishBlockV2",
middleware: []middleware.Middleware{
middleware.ContentTypeHandler([]string{api.JsonMediaType, api.OctetStreamMediaType}),
middleware.AcceptHeaderHandler([]string{api.JsonMediaType}),
middleware.ContentTypeHandler([]string{httputil.JsonMediaType, httputil.OctetStreamMediaType}),
middleware.AcceptHeaderHandler([]string{httputil.JsonMediaType}),
},
handler: server.PublishBlockV2,
methods: []string{http.MethodPost},
@@ -621,8 +621,8 @@ func (s *Service) beaconEndpoints(
template: "/eth/v2/beacon/blinded_blocks",
name: namespace + ".PublishBlindedBlockV2",
middleware: []middleware.Middleware{
middleware.ContentTypeHandler([]string{api.JsonMediaType, api.OctetStreamMediaType}),
middleware.AcceptHeaderHandler([]string{api.JsonMediaType}),
middleware.ContentTypeHandler([]string{httputil.JsonMediaType, httputil.OctetStreamMediaType}),
middleware.AcceptHeaderHandler([]string{httputil.JsonMediaType}),
},
handler: server.PublishBlindedBlockV2,
methods: []string{http.MethodPost},
@@ -631,7 +631,7 @@ func (s *Service) beaconEndpoints(
template: "/eth/v2/beacon/blocks/{block_id}",
name: namespace + ".GetBlockV2",
middleware: []middleware.Middleware{
middleware.AcceptHeaderHandler([]string{api.JsonMediaType, api.OctetStreamMediaType}),
middleware.AcceptHeaderHandler([]string{httputil.JsonMediaType, httputil.OctetStreamMediaType}),
},
handler: server.GetBlockV2,
methods: []string{http.MethodGet},
@@ -641,7 +641,7 @@ func (s *Service) beaconEndpoints(
template: "/eth/v1/beacon/blocks/{block_id}/attestations",
name: namespace + ".GetBlockAttestations",
middleware: []middleware.Middleware{
middleware.AcceptHeaderHandler([]string{api.JsonMediaType}),
middleware.AcceptHeaderHandler([]string{httputil.JsonMediaType}),
},
handler: server.GetBlockAttestations,
methods: []string{http.MethodGet},
@@ -650,7 +650,7 @@ func (s *Service) beaconEndpoints(
template: "/eth/v2/beacon/blocks/{block_id}/attestations",
name: namespace + ".GetBlockAttestationsV2",
middleware: []middleware.Middleware{
middleware.AcceptHeaderHandler([]string{api.JsonMediaType}),
middleware.AcceptHeaderHandler([]string{httputil.JsonMediaType}),
},
handler: server.GetBlockAttestationsV2,
methods: []string{http.MethodGet},
@@ -659,7 +659,7 @@ func (s *Service) beaconEndpoints(
template: "/eth/v1/beacon/blinded_blocks/{block_id}",
name: namespace + ".GetBlindedBlock",
middleware: []middleware.Middleware{
middleware.AcceptHeaderHandler([]string{api.JsonMediaType, api.OctetStreamMediaType}),
middleware.AcceptHeaderHandler([]string{httputil.JsonMediaType, httputil.OctetStreamMediaType}),
},
handler: server.GetBlindedBlock,
methods: []string{http.MethodGet},
@@ -668,7 +668,7 @@ func (s *Service) beaconEndpoints(
template: "/eth/v1/beacon/blocks/{block_id}/root",
name: namespace + ".GetBlockRoot",
middleware: []middleware.Middleware{
middleware.AcceptHeaderHandler([]string{api.JsonMediaType}),
middleware.AcceptHeaderHandler([]string{httputil.JsonMediaType}),
},
handler: server.GetBlockRoot,
methods: []string{http.MethodGet},
@@ -678,7 +678,7 @@ func (s *Service) beaconEndpoints(
template: "/eth/v1/beacon/pool/attestations",
name: namespace + ".ListAttestations",
middleware: []middleware.Middleware{
middleware.AcceptHeaderHandler([]string{api.JsonMediaType}),
middleware.AcceptHeaderHandler([]string{httputil.JsonMediaType}),
},
handler: server.ListAttestations,
methods: []string{http.MethodGet},
@@ -687,7 +687,7 @@ func (s *Service) beaconEndpoints(
template: "/eth/v2/beacon/pool/attestations",
name: namespace + ".ListAttestationsV2",
middleware: []middleware.Middleware{
middleware.AcceptHeaderHandler([]string{api.JsonMediaType}),
middleware.AcceptHeaderHandler([]string{httputil.JsonMediaType}),
},
handler: server.ListAttestationsV2,
methods: []string{http.MethodGet},
@@ -696,8 +696,8 @@ func (s *Service) beaconEndpoints(
template: "/eth/v1/beacon/pool/attestations",
name: namespace + ".SubmitAttestations",
middleware: []middleware.Middleware{
middleware.ContentTypeHandler([]string{api.JsonMediaType}),
middleware.AcceptHeaderHandler([]string{api.JsonMediaType}),
middleware.ContentTypeHandler([]string{httputil.JsonMediaType}),
middleware.AcceptHeaderHandler([]string{httputil.JsonMediaType}),
},
handler: server.SubmitAttestations,
methods: []string{http.MethodPost},
@@ -706,8 +706,8 @@ func (s *Service) beaconEndpoints(
template: "/eth/v2/beacon/pool/attestations",
name: namespace + ".SubmitAttestationsV2",
middleware: []middleware.Middleware{
middleware.ContentTypeHandler([]string{api.JsonMediaType}),
middleware.AcceptHeaderHandler([]string{api.JsonMediaType}),
middleware.ContentTypeHandler([]string{httputil.JsonMediaType}),
middleware.AcceptHeaderHandler([]string{httputil.JsonMediaType}),
},
handler: server.SubmitAttestationsV2,
methods: []string{http.MethodPost},
@@ -716,7 +716,7 @@ func (s *Service) beaconEndpoints(
template: "/eth/v1/beacon/pool/voluntary_exits",
name: namespace + ".ListVoluntaryExits",
middleware: []middleware.Middleware{
middleware.AcceptHeaderHandler([]string{api.JsonMediaType}),
middleware.AcceptHeaderHandler([]string{httputil.JsonMediaType}),
},
handler: server.ListVoluntaryExits,
methods: []string{http.MethodGet},
@@ -725,8 +725,8 @@ func (s *Service) beaconEndpoints(
template: "/eth/v1/beacon/pool/voluntary_exits",
name: namespace + ".SubmitVoluntaryExit",
middleware: []middleware.Middleware{
middleware.ContentTypeHandler([]string{api.JsonMediaType}),
middleware.AcceptHeaderHandler([]string{api.JsonMediaType}),
middleware.ContentTypeHandler([]string{httputil.JsonMediaType}),
middleware.AcceptHeaderHandler([]string{httputil.JsonMediaType}),
},
handler: server.SubmitVoluntaryExit,
methods: []string{http.MethodPost},
@@ -735,8 +735,8 @@ func (s *Service) beaconEndpoints(
template: "/eth/v1/beacon/pool/sync_committees",
name: namespace + ".SubmitSyncCommitteeSignatures",
middleware: []middleware.Middleware{
middleware.ContentTypeHandler([]string{api.JsonMediaType}),
middleware.AcceptHeaderHandler([]string{api.JsonMediaType}),
middleware.ContentTypeHandler([]string{httputil.JsonMediaType}),
middleware.AcceptHeaderHandler([]string{httputil.JsonMediaType}),
},
handler: server.SubmitSyncCommitteeSignatures,
methods: []string{http.MethodPost},
@@ -745,7 +745,7 @@ func (s *Service) beaconEndpoints(
template: "/eth/v1/beacon/pool/bls_to_execution_changes",
name: namespace + ".ListBLSToExecutionChanges",
middleware: []middleware.Middleware{
middleware.AcceptHeaderHandler([]string{api.JsonMediaType}),
middleware.AcceptHeaderHandler([]string{httputil.JsonMediaType}),
},
handler: server.ListBLSToExecutionChanges,
methods: []string{http.MethodGet},
@@ -754,8 +754,8 @@ func (s *Service) beaconEndpoints(
template: "/eth/v1/beacon/pool/bls_to_execution_changes",
name: namespace + ".SubmitBLSToExecutionChanges",
middleware: []middleware.Middleware{
middleware.ContentTypeHandler([]string{api.JsonMediaType}),
middleware.AcceptHeaderHandler([]string{api.JsonMediaType}),
middleware.ContentTypeHandler([]string{httputil.JsonMediaType}),
middleware.AcceptHeaderHandler([]string{httputil.JsonMediaType}),
},
handler: server.SubmitBLSToExecutionChanges,
methods: []string{http.MethodPost},
@@ -765,7 +765,7 @@ func (s *Service) beaconEndpoints(
template: "/eth/v1/beacon/pool/attester_slashings",
name: namespace + ".GetAttesterSlashings",
middleware: []middleware.Middleware{
middleware.AcceptHeaderHandler([]string{api.JsonMediaType}),
middleware.AcceptHeaderHandler([]string{httputil.JsonMediaType}),
},
handler: server.GetAttesterSlashings,
methods: []string{http.MethodGet},
@@ -774,7 +774,7 @@ func (s *Service) beaconEndpoints(
template: "/eth/v2/beacon/pool/attester_slashings",
name: namespace + ".GetAttesterSlashingsV2",
middleware: []middleware.Middleware{
middleware.AcceptHeaderHandler([]string{api.JsonMediaType}),
middleware.AcceptHeaderHandler([]string{httputil.JsonMediaType}),
},
handler: server.GetAttesterSlashingsV2,
methods: []string{http.MethodGet},
@@ -783,8 +783,8 @@ func (s *Service) beaconEndpoints(
template: "/eth/v1/beacon/pool/attester_slashings",
name: namespace + ".SubmitAttesterSlashings",
middleware: []middleware.Middleware{
middleware.ContentTypeHandler([]string{api.JsonMediaType}),
middleware.AcceptHeaderHandler([]string{api.JsonMediaType}),
middleware.ContentTypeHandler([]string{httputil.JsonMediaType}),
middleware.AcceptHeaderHandler([]string{httputil.JsonMediaType}),
},
handler: server.SubmitAttesterSlashings,
methods: []string{http.MethodPost},
@@ -793,8 +793,8 @@ func (s *Service) beaconEndpoints(
template: "/eth/v2/beacon/pool/attester_slashings",
name: namespace + ".SubmitAttesterSlashingsV2",
middleware: []middleware.Middleware{
middleware.ContentTypeHandler([]string{api.JsonMediaType}),
middleware.AcceptHeaderHandler([]string{api.JsonMediaType}),
middleware.ContentTypeHandler([]string{httputil.JsonMediaType}),
middleware.AcceptHeaderHandler([]string{httputil.JsonMediaType}),
},
handler: server.SubmitAttesterSlashingsV2,
methods: []string{http.MethodPost},
@@ -803,7 +803,7 @@ func (s *Service) beaconEndpoints(
template: "/eth/v1/beacon/pool/proposer_slashings",
name: namespace + ".GetProposerSlashings",
middleware: []middleware.Middleware{
middleware.AcceptHeaderHandler([]string{api.JsonMediaType}),
middleware.AcceptHeaderHandler([]string{httputil.JsonMediaType}),
},
handler: server.GetProposerSlashings,
methods: []string{http.MethodGet},
@@ -812,8 +812,8 @@ func (s *Service) beaconEndpoints(
template: "/eth/v1/beacon/pool/proposer_slashings",
name: namespace + ".SubmitProposerSlashing",
middleware: []middleware.Middleware{
middleware.ContentTypeHandler([]string{api.JsonMediaType}),
middleware.AcceptHeaderHandler([]string{api.JsonMediaType}),
middleware.ContentTypeHandler([]string{httputil.JsonMediaType}),
middleware.AcceptHeaderHandler([]string{httputil.JsonMediaType}),
},
handler: server.SubmitProposerSlashing,
methods: []string{http.MethodPost},
@@ -822,7 +822,7 @@ func (s *Service) beaconEndpoints(
template: "/eth/v1/beacon/headers",
name: namespace + ".GetBlockHeaders",
middleware: []middleware.Middleware{
middleware.AcceptHeaderHandler([]string{api.JsonMediaType}),
middleware.AcceptHeaderHandler([]string{httputil.JsonMediaType}),
},
handler: server.GetBlockHeaders,
methods: []string{http.MethodGet},
@@ -831,7 +831,7 @@ func (s *Service) beaconEndpoints(
template: "/eth/v1/beacon/headers/{block_id}",
name: namespace + ".GetBlockHeader",
middleware: []middleware.Middleware{
middleware.AcceptHeaderHandler([]string{api.JsonMediaType}),
middleware.AcceptHeaderHandler([]string{httputil.JsonMediaType}),
},
handler: server.GetBlockHeader,
methods: []string{http.MethodGet},
@@ -840,7 +840,7 @@ func (s *Service) beaconEndpoints(
template: "/eth/v1/beacon/genesis",
name: namespace + ".GetGenesis",
middleware: []middleware.Middleware{
middleware.AcceptHeaderHandler([]string{api.JsonMediaType}),
middleware.AcceptHeaderHandler([]string{httputil.JsonMediaType}),
},
handler: server.GetGenesis,
methods: []string{http.MethodGet},
@@ -849,7 +849,7 @@ func (s *Service) beaconEndpoints(
template: "/eth/v1/beacon/states/{state_id}/finality_checkpoints",
name: namespace + ".GetFinalityCheckpoints",
middleware: []middleware.Middleware{
middleware.AcceptHeaderHandler([]string{api.JsonMediaType}),
middleware.AcceptHeaderHandler([]string{httputil.JsonMediaType}),
},
handler: server.GetFinalityCheckpoints,
methods: []string{http.MethodGet},
@@ -858,8 +858,8 @@ func (s *Service) beaconEndpoints(
template: "/eth/v1/beacon/states/{state_id}/validators",
name: namespace + ".GetValidators",
middleware: []middleware.Middleware{
middleware.ContentTypeHandler([]string{api.JsonMediaType}),
middleware.AcceptHeaderHandler([]string{api.JsonMediaType}),
middleware.ContentTypeHandler([]string{httputil.JsonMediaType}),
middleware.AcceptHeaderHandler([]string{httputil.JsonMediaType}),
},
handler: server.GetValidators,
methods: []string{http.MethodGet, http.MethodPost},
@@ -868,7 +868,7 @@ func (s *Service) beaconEndpoints(
template: "/eth/v1/beacon/states/{state_id}/validators/{validator_id}",
name: namespace + ".GetValidator",
middleware: []middleware.Middleware{
middleware.AcceptHeaderHandler([]string{api.JsonMediaType}),
middleware.AcceptHeaderHandler([]string{httputil.JsonMediaType}),
},
handler: server.GetValidator,
methods: []string{http.MethodGet},
@@ -877,18 +877,28 @@ func (s *Service) beaconEndpoints(
template: "/eth/v1/beacon/states/{state_id}/validator_balances",
name: namespace + ".GetValidatorBalances",
middleware: []middleware.Middleware{
middleware.ContentTypeHandler([]string{api.JsonMediaType}),
middleware.AcceptHeaderHandler([]string{api.JsonMediaType}),
middleware.ContentTypeHandler([]string{httputil.JsonMediaType}),
middleware.AcceptHeaderHandler([]string{httputil.JsonMediaType}),
},
handler: server.GetValidatorBalances,
methods: []string{http.MethodGet, http.MethodPost},
},
{
template: "/eth/v1/beacon/states/{state_id}/validator_identities",
name: namespace + ".GetValidatorIdentities",
middleware: []middleware.Middleware{
middleware.ContentTypeHandler([]string{httputil.JsonMediaType}),
middleware.AcceptHeaderHandler([]string{httputil.JsonMediaType, httputil.OctetStreamMediaType}),
},
handler: server.GetValidatorIdentities,
methods: []string{http.MethodPost},
},
{
// Deprecated: no longer needed post Electra
template: "/eth/v1/beacon/deposit_snapshot",
name: namespace + ".GetDepositSnapshot",
middleware: []middleware.Middleware{
middleware.AcceptHeaderHandler([]string{api.JsonMediaType}),
middleware.AcceptHeaderHandler([]string{httputil.JsonMediaType}),
},
handler: server.GetDepositSnapshot,
methods: []string{http.MethodGet},
@@ -897,7 +907,7 @@ func (s *Service) beaconEndpoints(
template: "/eth/v1/beacon/states/{state_id}/pending_deposits",
name: namespace + ".GetPendingDeposits",
middleware: []middleware.Middleware{
middleware.AcceptHeaderHandler([]string{api.JsonMediaType}),
middleware.AcceptHeaderHandler([]string{httputil.JsonMediaType}),
},
handler: server.GetPendingDeposits,
methods: []string{http.MethodGet},
@@ -906,7 +916,7 @@ func (s *Service) beaconEndpoints(
template: "/eth/v1/beacon/states/{state_id}/pending_partial_withdrawals",
name: namespace + ".GetPendingPartialWithdrawals",
middleware: []middleware.Middleware{
middleware.AcceptHeaderHandler([]string{api.JsonMediaType}),
middleware.AcceptHeaderHandler([]string{httputil.JsonMediaType}),
},
handler: server.GetPendingPartialWithdrawals,
methods: []string{http.MethodGet},
@@ -921,7 +931,7 @@ func (*Service) configEndpoints() []endpoint {
template: "/eth/v1/config/deposit_contract",
name: namespace + ".GetDepositContract",
middleware: []middleware.Middleware{
middleware.AcceptHeaderHandler([]string{api.JsonMediaType}),
middleware.AcceptHeaderHandler([]string{httputil.JsonMediaType}),
},
handler: config.GetDepositContract,
methods: []string{http.MethodGet},
@@ -930,7 +940,7 @@ func (*Service) configEndpoints() []endpoint {
template: "/eth/v1/config/fork_schedule",
name: namespace + ".GetForkSchedule",
middleware: []middleware.Middleware{
middleware.AcceptHeaderHandler([]string{api.JsonMediaType}),
middleware.AcceptHeaderHandler([]string{httputil.JsonMediaType}),
},
handler: config.GetForkSchedule,
methods: []string{http.MethodGet},
@@ -939,7 +949,7 @@ func (*Service) configEndpoints() []endpoint {
template: "/eth/v1/config/spec",
name: namespace + ".GetSpec",
middleware: []middleware.Middleware{
middleware.AcceptHeaderHandler([]string{api.JsonMediaType}),
middleware.AcceptHeaderHandler([]string{httputil.JsonMediaType}),
},
handler: config.GetSpec,
methods: []string{http.MethodGet},
@@ -962,7 +972,7 @@ func (s *Service) lightClientEndpoints(blocker lookup.Blocker, stater lookup.Sta
template: "/eth/v1/beacon/light_client/bootstrap/{block_root}",
name: namespace + ".GetLightClientBootstrap",
middleware: []middleware.Middleware{
middleware.AcceptHeaderHandler([]string{api.JsonMediaType, api.OctetStreamMediaType}),
middleware.AcceptHeaderHandler([]string{httputil.JsonMediaType, httputil.OctetStreamMediaType}),
},
handler: server.GetLightClientBootstrap,
methods: []string{http.MethodGet},
@@ -971,7 +981,7 @@ func (s *Service) lightClientEndpoints(blocker lookup.Blocker, stater lookup.Sta
template: "/eth/v1/beacon/light_client/updates",
name: namespace + ".GetLightClientUpdatesByRange",
middleware: []middleware.Middleware{
middleware.AcceptHeaderHandler([]string{api.JsonMediaType, api.OctetStreamMediaType}),
middleware.AcceptHeaderHandler([]string{httputil.JsonMediaType, httputil.OctetStreamMediaType}),
},
handler: server.GetLightClientUpdatesByRange,
methods: []string{http.MethodGet},
@@ -980,7 +990,7 @@ func (s *Service) lightClientEndpoints(blocker lookup.Blocker, stater lookup.Sta
template: "/eth/v1/beacon/light_client/finality_update",
name: namespace + ".GetLightClientFinalityUpdate",
middleware: []middleware.Middleware{
middleware.AcceptHeaderHandler([]string{api.JsonMediaType, api.OctetStreamMediaType}),
middleware.AcceptHeaderHandler([]string{httputil.JsonMediaType, httputil.OctetStreamMediaType}),
},
handler: server.GetLightClientFinalityUpdate,
methods: []string{http.MethodGet},
@@ -989,7 +999,7 @@ func (s *Service) lightClientEndpoints(blocker lookup.Blocker, stater lookup.Sta
template: "/eth/v1/beacon/light_client/optimistic_update",
name: namespace + ".GetLightClientOptimisticUpdate",
middleware: []middleware.Middleware{
middleware.AcceptHeaderHandler([]string{api.JsonMediaType, api.OctetStreamMediaType}),
middleware.AcceptHeaderHandler([]string{httputil.JsonMediaType, httputil.OctetStreamMediaType}),
},
handler: server.GetLightClientOptimisticUpdate,
methods: []string{http.MethodGet},
@@ -1015,7 +1025,7 @@ func (s *Service) debugEndpoints(stater lookup.Stater) []endpoint {
template: "/eth/v2/debug/beacon/states/{state_id}",
name: namespace + ".GetBeaconStateV2",
middleware: []middleware.Middleware{
middleware.AcceptHeaderHandler([]string{api.JsonMediaType, api.OctetStreamMediaType}),
middleware.AcceptHeaderHandler([]string{httputil.JsonMediaType, httputil.OctetStreamMediaType}),
},
handler: server.GetBeaconStateV2,
methods: []string{http.MethodGet},
@@ -1024,7 +1034,7 @@ func (s *Service) debugEndpoints(stater lookup.Stater) []endpoint {
template: "/eth/v2/debug/beacon/heads",
name: namespace + ".GetForkChoiceHeadsV2",
middleware: []middleware.Middleware{
middleware.AcceptHeaderHandler([]string{api.JsonMediaType}),
middleware.AcceptHeaderHandler([]string{httputil.JsonMediaType}),
},
handler: server.GetForkChoiceHeadsV2,
methods: []string{http.MethodGet},
@@ -1033,7 +1043,7 @@ func (s *Service) debugEndpoints(stater lookup.Stater) []endpoint {
template: "/eth/v1/debug/fork_choice",
name: namespace + ".GetForkChoice",
middleware: []middleware.Middleware{
middleware.AcceptHeaderHandler([]string{api.JsonMediaType}),
middleware.AcceptHeaderHandler([]string{httputil.JsonMediaType}),
},
handler: server.GetForkChoice,
methods: []string{http.MethodGet},
@@ -1056,7 +1066,7 @@ func (s *Service) eventsEndpoints() []endpoint {
template: "/eth/v1/events",
name: namespace + ".StreamEvents",
middleware: []middleware.Middleware{
middleware.AcceptHeaderHandler([]string{api.EventStreamMediaType}),
middleware.AcceptHeaderHandler([]string{httputil.EventStreamMediaType}),
},
handler: server.StreamEvents,
methods: []string{http.MethodGet},
@@ -1091,7 +1101,7 @@ func (s *Service) prysmBeaconEndpoints(
template: "/prysm/v1/beacon/weak_subjectivity",
name: namespace + ".GetWeakSubjectivity",
middleware: []middleware.Middleware{
middleware.AcceptHeaderHandler([]string{api.JsonMediaType}),
middleware.AcceptHeaderHandler([]string{httputil.JsonMediaType}),
},
handler: server.GetWeakSubjectivity,
methods: []string{http.MethodGet},
@@ -1100,7 +1110,7 @@ func (s *Service) prysmBeaconEndpoints(
template: "/eth/v1/beacon/states/{state_id}/validator_count",
name: namespace + ".GetValidatorCount",
middleware: []middleware.Middleware{
middleware.AcceptHeaderHandler([]string{api.JsonMediaType}),
middleware.AcceptHeaderHandler([]string{httputil.JsonMediaType}),
},
handler: server.GetValidatorCount,
methods: []string{http.MethodGet},
@@ -1109,7 +1119,7 @@ func (s *Service) prysmBeaconEndpoints(
template: "/prysm/v1/beacon/states/{state_id}/validator_count",
name: namespace + ".GetValidatorCount",
middleware: []middleware.Middleware{
middleware.AcceptHeaderHandler([]string{api.JsonMediaType}),
middleware.AcceptHeaderHandler([]string{httputil.JsonMediaType}),
},
handler: server.GetValidatorCount,
methods: []string{http.MethodGet},
@@ -1118,8 +1128,8 @@ func (s *Service) prysmBeaconEndpoints(
template: "/prysm/v1/beacon/individual_votes",
name: namespace + ".GetIndividualVotes",
middleware: []middleware.Middleware{
middleware.ContentTypeHandler([]string{api.JsonMediaType}),
middleware.AcceptHeaderHandler([]string{api.JsonMediaType}),
middleware.ContentTypeHandler([]string{httputil.JsonMediaType}),
middleware.AcceptHeaderHandler([]string{httputil.JsonMediaType}),
},
handler: server.GetIndividualVotes,
methods: []string{http.MethodPost},
@@ -1128,7 +1138,7 @@ func (s *Service) prysmBeaconEndpoints(
template: "/prysm/v1/beacon/chain_head",
name: namespace + ".GetChainHead",
middleware: []middleware.Middleware{
middleware.AcceptHeaderHandler([]string{api.JsonMediaType}),
middleware.AcceptHeaderHandler([]string{httputil.JsonMediaType}),
},
handler: server.GetChainHead,
methods: []string{http.MethodGet},
@@ -1137,8 +1147,8 @@ func (s *Service) prysmBeaconEndpoints(
template: "/prysm/v1/beacon/blobs",
name: namespace + ".PublishBlobs",
middleware: []middleware.Middleware{
middleware.ContentTypeHandler([]string{api.JsonMediaType}),
middleware.AcceptHeaderHandler([]string{api.JsonMediaType}),
middleware.ContentTypeHandler([]string{httputil.JsonMediaType}),
middleware.AcceptHeaderHandler([]string{httputil.JsonMediaType}),
},
handler: server.PublishBlobs,
methods: []string{http.MethodPost},
@@ -1165,7 +1175,7 @@ func (s *Service) prysmNodeEndpoints() []endpoint {
template: "/prysm/node/trusted_peers",
name: namespace + ".ListTrustedPeer",
middleware: []middleware.Middleware{
middleware.AcceptHeaderHandler([]string{api.JsonMediaType}),
middleware.AcceptHeaderHandler([]string{httputil.JsonMediaType}),
},
handler: server.ListTrustedPeer,
methods: []string{http.MethodGet},
@@ -1174,7 +1184,7 @@ func (s *Service) prysmNodeEndpoints() []endpoint {
template: "/prysm/v1/node/trusted_peers",
name: namespace + ".ListTrustedPeer",
middleware: []middleware.Middleware{
middleware.AcceptHeaderHandler([]string{api.JsonMediaType}),
middleware.AcceptHeaderHandler([]string{httputil.JsonMediaType}),
},
handler: server.ListTrustedPeer,
methods: []string{http.MethodGet},
@@ -1183,8 +1193,8 @@ func (s *Service) prysmNodeEndpoints() []endpoint {
template: "/prysm/node/trusted_peers",
name: namespace + ".AddTrustedPeer",
middleware: []middleware.Middleware{
middleware.ContentTypeHandler([]string{api.JsonMediaType}),
middleware.AcceptHeaderHandler([]string{api.JsonMediaType}),
middleware.ContentTypeHandler([]string{httputil.JsonMediaType}),
middleware.AcceptHeaderHandler([]string{httputil.JsonMediaType}),
},
handler: server.AddTrustedPeer,
methods: []string{http.MethodPost},
@@ -1193,8 +1203,8 @@ func (s *Service) prysmNodeEndpoints() []endpoint {
template: "/prysm/v1/node/trusted_peers",
name: namespace + ".AddTrustedPeer",
middleware: []middleware.Middleware{
middleware.ContentTypeHandler([]string{api.JsonMediaType}),
middleware.AcceptHeaderHandler([]string{api.JsonMediaType}),
middleware.ContentTypeHandler([]string{httputil.JsonMediaType}),
middleware.AcceptHeaderHandler([]string{httputil.JsonMediaType}),
},
handler: server.AddTrustedPeer,
methods: []string{http.MethodPost},
@@ -1203,7 +1213,7 @@ func (s *Service) prysmNodeEndpoints() []endpoint {
template: "/prysm/node/trusted_peers/{peer_id}",
name: namespace + ".RemoveTrustedPeer",
middleware: []middleware.Middleware{
middleware.AcceptHeaderHandler([]string{api.JsonMediaType}),
middleware.AcceptHeaderHandler([]string{httputil.JsonMediaType}),
},
handler: server.RemoveTrustedPeer,
methods: []string{http.MethodDelete},
@@ -1212,7 +1222,7 @@ func (s *Service) prysmNodeEndpoints() []endpoint {
template: "/prysm/v1/node/trusted_peers/{peer_id}",
name: namespace + ".RemoveTrustedPeer",
middleware: []middleware.Middleware{
middleware.AcceptHeaderHandler([]string{api.JsonMediaType}),
middleware.AcceptHeaderHandler([]string{httputil.JsonMediaType}),
},
handler: server.RemoveTrustedPeer,
methods: []string{http.MethodDelete},
@@ -1233,8 +1243,8 @@ func (s *Service) prysmValidatorEndpoints(stater lookup.Stater, coreService *cor
template: "/prysm/validators/performance",
name: namespace + ".GetPerformance",
middleware: []middleware.Middleware{
middleware.ContentTypeHandler([]string{api.JsonMediaType}),
middleware.AcceptHeaderHandler([]string{api.JsonMediaType}),
middleware.ContentTypeHandler([]string{httputil.JsonMediaType}),
middleware.AcceptHeaderHandler([]string{httputil.JsonMediaType}),
},
handler: server.GetPerformance,
methods: []string{http.MethodPost},
@@ -1243,8 +1253,8 @@ func (s *Service) prysmValidatorEndpoints(stater lookup.Stater, coreService *cor
template: "/prysm/v1/validators/performance",
name: namespace + ".GetPerformance",
middleware: []middleware.Middleware{
middleware.ContentTypeHandler([]string{api.JsonMediaType}),
middleware.AcceptHeaderHandler([]string{api.JsonMediaType}),
middleware.ContentTypeHandler([]string{httputil.JsonMediaType}),
middleware.AcceptHeaderHandler([]string{httputil.JsonMediaType}),
},
handler: server.GetPerformance,
methods: []string{http.MethodPost},
@@ -1253,7 +1263,7 @@ func (s *Service) prysmValidatorEndpoints(stater lookup.Stater, coreService *cor
template: "/prysm/v1/validators/participation",
name: namespace + ".GetParticipation",
middleware: []middleware.Middleware{
middleware.AcceptHeaderHandler([]string{api.JsonMediaType}),
middleware.AcceptHeaderHandler([]string{httputil.JsonMediaType}),
},
handler: server.GetParticipation,
methods: []string{http.MethodGet},
@@ -1262,7 +1272,7 @@ func (s *Service) prysmValidatorEndpoints(stater lookup.Stater, coreService *cor
template: "/prysm/v1/validators/active_set_changes",
name: namespace + ".GetActiveSetChanges",
middleware: []middleware.Middleware{
middleware.AcceptHeaderHandler([]string{api.JsonMediaType}),
middleware.AcceptHeaderHandler([]string{httputil.JsonMediaType}),
},
handler: server.GetActiveSetChanges,
methods: []string{http.MethodGet},

View File

@@ -24,6 +24,7 @@ func Test_endpoints(t *testing.T) {
"/eth/v1/beacon/states/{state_id}/validators": {http.MethodGet, http.MethodPost},
"/eth/v1/beacon/states/{state_id}/validators/{validator_id}": {http.MethodGet},
"/eth/v1/beacon/states/{state_id}/validator_balances": {http.MethodGet, http.MethodPost},
"/eth/v1/beacon/states/{state_id}/validator_identities": {http.MethodPost},
"/eth/v1/beacon/states/{state_id}/committees": {http.MethodGet},
"/eth/v1/beacon/states/{state_id}/sync_committees": {http.MethodGet},
"/eth/v1/beacon/states/{state_id}/randao": {http.MethodGet},
@@ -150,7 +151,14 @@ func Test_endpoints(t *testing.T) {
actualRoutes[e.template] = e.methods
}
}
expectedRoutes := combineMaps(beaconRoutes, builderRoutes, configRoutes, debugRoutes, eventsRoutes, nodeRoutes, validatorRoutes, rewardsRoutes, lightClientRoutes, blobRoutes, prysmValidatorRoutes, prysmNodeRoutes, prysmBeaconRoutes)
expectedRoutes := make(map[string][]string)
for _, m := range []map[string][]string{
beaconRoutes, builderRoutes, configRoutes, debugRoutes, eventsRoutes,
nodeRoutes, validatorRoutes, rewardsRoutes, lightClientRoutes, blobRoutes,
prysmValidatorRoutes, prysmNodeRoutes, prysmBeaconRoutes,
} {
maps.Copy(expectedRoutes, m)
}
assert.Equal(t, true, maps.EqualFunc(expectedRoutes, actualRoutes, func(actualMethods []string, expectedMethods []string) bool {
return slices.Equal(expectedMethods, actualMethods)

View File

@@ -13,7 +13,7 @@ go_library(
importpath = "github.com/prysmaticlabs/prysm/v5/beacon-chain/rpc/eth/beacon",
visibility = ["//visibility:public"],
deps = [
"//api:go_default_library",
"//api/httputil:go_default_library",
"//api/server:go_default_library",
"//api/server/structs:go_default_library",
"//beacon-chain/blockchain:go_default_library",
@@ -54,7 +54,6 @@ go_library(
"//crypto/bls:go_default_library",
"//encoding/bytesutil:go_default_library",
"//monitoring/tracing/trace:go_default_library",
"//network/httputil:go_default_library",
"//proto/prysm/v1alpha1:go_default_library",
"//runtime/version:go_default_library",
"//time/slots:go_default_library",
@@ -77,7 +76,7 @@ go_test(
],
embed = [":go_default_library"],
deps = [
"//api:go_default_library",
"//api/httputil:go_default_library",
"//api/server:go_default_library",
"//api/server/structs:go_default_library",
"//beacon-chain/blockchain/testing:go_default_library",
@@ -112,7 +111,6 @@ go_test(
"//crypto/hash:go_default_library",
"//encoding/bytesutil:go_default_library",
"//encoding/ssz:go_default_library",
"//network/httputil:go_default_library",
"//proto/prysm/v1alpha1:go_default_library",
"//runtime/version:go_default_library",
"//testing/assert:go_default_library",

View File

@@ -14,7 +14,7 @@ import (
"github.com/ethereum/go-ethereum/crypto/kzg4844"
"github.com/pkg/errors"
ssz "github.com/prysmaticlabs/fastssz"
"github.com/prysmaticlabs/prysm/v5/api"
httputil2 "github.com/prysmaticlabs/prysm/v5/api/httputil"
"github.com/prysmaticlabs/prysm/v5/api/server/structs"
"github.com/prysmaticlabs/prysm/v5/beacon-chain/cache/depositsnapshot"
corehelpers "github.com/prysmaticlabs/prysm/v5/beacon-chain/core/helpers"
@@ -30,7 +30,6 @@ import (
"github.com/prysmaticlabs/prysm/v5/consensus-types/primitives"
"github.com/prysmaticlabs/prysm/v5/encoding/bytesutil"
"github.com/prysmaticlabs/prysm/v5/monitoring/tracing/trace"
"github.com/prysmaticlabs/prysm/v5/network/httputil"
eth "github.com/prysmaticlabs/prysm/v5/proto/prysm/v1alpha1"
"github.com/prysmaticlabs/prysm/v5/runtime/version"
"github.com/prysmaticlabs/prysm/v5/time/slots"
@@ -100,9 +99,9 @@ func versionHeaderFromRequest(body []byte) (string, error) {
// from the request. If the version header is not provided and not required, it attempts
// to derive it from the request body.
func validateVersionHeader(r *http.Request, body []byte, versionRequired bool) (string, error) {
versionHeader := r.Header.Get(api.VersionHeader)
versionHeader := r.Header.Get(httputil2.VersionHeader)
if versionRequired && versionHeader == "" {
return "", fmt.Errorf("%s header is required", api.VersionHeader)
return "", fmt.Errorf("%s header is required", httputil2.VersionHeader)
}
if !versionRequired && versionHeader == "" {
@@ -152,7 +151,7 @@ func (s *Server) GetBlockV2(w http.ResponseWriter, r *http.Request) {
blockId := r.PathValue("block_id")
if blockId == "" {
httputil.HandleError(w, "block_id is required in URL params", http.StatusBadRequest)
httputil2.HandleError(w, "block_id is required in URL params", http.StatusBadRequest)
return
}
blk, err := s.Blocker.Block(ctx, []byte(blockId))
@@ -164,12 +163,12 @@ func (s *Server) GetBlockV2(w http.ResponseWriter, r *http.Request) {
if blk.Version() >= version.Bellatrix && blk.IsBlinded() {
blk, err = s.ExecutionReconstructor.ReconstructFullBlock(ctx, blk)
if err != nil {
httputil.HandleError(w, errors.Wrapf(err, "could not reconstruct full execution payload to create signed beacon block").Error(), http.StatusBadRequest)
httputil2.HandleError(w, errors.Wrapf(err, "could not reconstruct full execution payload to create signed beacon block").Error(), http.StatusBadRequest)
return
}
}
if httputil.RespondWithSsz(r) {
if httputil2.RespondWithSsz(r) {
s.getBlockV2Ssz(w, blk)
} else {
s.getBlockV2Json(ctx, w, blk)
@@ -183,7 +182,7 @@ func (s *Server) GetBlindedBlock(w http.ResponseWriter, r *http.Request) {
blockId := r.PathValue("block_id")
if blockId == "" {
httputil.HandleError(w, "block_id is required in URL params", http.StatusBadRequest)
httputil2.HandleError(w, "block_id is required in URL params", http.StatusBadRequest)
return
}
blk, err := s.Blocker.Block(ctx, []byte(blockId))
@@ -200,7 +199,7 @@ func (s *Server) GetBlindedBlock(w http.ResponseWriter, r *http.Request) {
}
}
if httputil.RespondWithSsz(r) {
if httputil2.RespondWithSsz(r) {
s.getBlockV2Ssz(w, blk)
} else {
s.getBlockV2Json(ctx, w, blk)
@@ -211,15 +210,15 @@ func (s *Server) GetBlindedBlock(w http.ResponseWriter, r *http.Request) {
func (s *Server) getBlockV2Ssz(w http.ResponseWriter, blk interfaces.ReadOnlySignedBeaconBlock) {
result, err := s.getBlockResponseBodySsz(blk)
if err != nil {
httputil.HandleError(w, "Could not get signed beacon block: "+err.Error(), http.StatusInternalServerError)
httputil2.HandleError(w, "Could not get signed beacon block: "+err.Error(), http.StatusInternalServerError)
return
}
if result == nil {
httputil.HandleError(w, fmt.Sprintf("Unknown block type %T", blk), http.StatusInternalServerError)
httputil2.HandleError(w, fmt.Sprintf("Unknown block type %T", blk), http.StatusInternalServerError)
return
}
w.Header().Set(api.VersionHeader, version.String(blk.Version()))
httputil.WriteSsz(w, result, "beacon_block.ssz")
w.Header().Set(httputil2.VersionHeader, version.String(blk.Version()))
httputil2.WriteSsz(w, result)
}
func (*Server) getBlockResponseBodySsz(blk interfaces.ReadOnlySignedBeaconBlock) ([]byte, error) {
@@ -246,15 +245,15 @@ func (*Server) getBlockResponseBodySsz(blk interfaces.ReadOnlySignedBeaconBlock)
func (s *Server) getBlockV2Json(ctx context.Context, w http.ResponseWriter, blk interfaces.ReadOnlySignedBeaconBlock) {
result, err := s.getBlockResponseBodyJson(ctx, blk)
if err != nil {
httputil.HandleError(w, "Error processing request: "+err.Error(), http.StatusInternalServerError)
httputil2.HandleError(w, "Error processing request: "+err.Error(), http.StatusInternalServerError)
return
}
if result == nil {
httputil.HandleError(w, fmt.Sprintf("Unknown block type %T", blk), http.StatusInternalServerError)
httputil2.HandleError(w, fmt.Sprintf("Unknown block type %T", blk), http.StatusInternalServerError)
return
}
w.Header().Set(api.VersionHeader, result.Version)
httputil.WriteJson(w, result)
w.Header().Set(httputil2.VersionHeader, result.Version)
httputil2.WriteJson(w, result)
}
func (s *Server) getBlockResponseBodyJson(ctx context.Context, blk interfaces.ReadOnlySignedBeaconBlock) (*structs.GetBlockV2Response, error) {
@@ -309,7 +308,7 @@ func (s *Server) GetBlockAttestations(w http.ResponseWriter, r *http.Request) {
if ok {
atts[i] = structs.AttFromConsensus(a)
} else {
httputil.HandleError(w, fmt.Sprintf("unable to convert consensus attestations of type %T", att), http.StatusInternalServerError)
httputil2.HandleError(w, fmt.Sprintf("unable to convert consensus attestations of type %T", att), http.StatusInternalServerError)
return
}
}
@@ -318,7 +317,7 @@ func (s *Server) GetBlockAttestations(w http.ResponseWriter, r *http.Request) {
ExecutionOptimistic: isOptimistic,
Finalized: s.FinalizationFetcher.IsFinalized(ctx, root),
}
httputil.WriteJson(w, resp)
httputil2.WriteJson(w, resp)
}
// GetBlockAttestationsV2 retrieves attestation included in requested block.
@@ -338,7 +337,7 @@ func (s *Server) GetBlockAttestationsV2(w http.ResponseWriter, r *http.Request)
for _, att := range consensusAtts {
a, ok := att.(*eth.AttestationElectra)
if !ok {
httputil.HandleError(w, fmt.Sprintf("unable to convert consensus attestations electra of type %T", att), http.StatusInternalServerError)
httputil2.HandleError(w, fmt.Sprintf("unable to convert consensus attestations electra of type %T", att), http.StatusInternalServerError)
return
}
attStruct := structs.AttElectraFromConsensus(a)
@@ -348,7 +347,7 @@ func (s *Server) GetBlockAttestationsV2(w http.ResponseWriter, r *http.Request)
for _, att := range consensusAtts {
a, ok := att.(*eth.Attestation)
if !ok {
httputil.HandleError(w, fmt.Sprintf("unable to convert consensus attestation of type %T", att), http.StatusInternalServerError)
httputil2.HandleError(w, fmt.Sprintf("unable to convert consensus attestation of type %T", att), http.StatusInternalServerError)
return
}
attStruct := structs.AttFromConsensus(a)
@@ -358,7 +357,7 @@ func (s *Server) GetBlockAttestationsV2(w http.ResponseWriter, r *http.Request)
attBytes, err := json.Marshal(attStructs)
if err != nil {
httputil.HandleError(w, fmt.Sprintf("failed to marshal attestations: %v", err), http.StatusInternalServerError)
httputil2.HandleError(w, fmt.Sprintf("failed to marshal attestations: %v", err), http.StatusInternalServerError)
return
}
resp := &structs.GetBlockAttestationsV2Response{
@@ -367,14 +366,14 @@ func (s *Server) GetBlockAttestationsV2(w http.ResponseWriter, r *http.Request)
Finalized: s.FinalizationFetcher.IsFinalized(ctx, root),
Data: attBytes,
}
w.Header().Set(api.VersionHeader, version.String(v))
httputil.WriteJson(w, resp)
w.Header().Set(httputil2.VersionHeader, version.String(v))
httputil2.WriteJson(w, resp)
}
func (s *Server) blockData(ctx context.Context, w http.ResponseWriter, r *http.Request) (interfaces.ReadOnlySignedBeaconBlock, bool, [32]byte) {
blockId := r.PathValue("block_id")
if blockId == "" {
httputil.HandleError(w, "block_id is required in URL params", http.StatusBadRequest)
httputil2.HandleError(w, "block_id is required in URL params", http.StatusBadRequest)
return nil, false, [32]byte{}
}
blk, err := s.Blocker.Block(ctx, []byte(blockId))
@@ -384,12 +383,12 @@ func (s *Server) blockData(ctx context.Context, w http.ResponseWriter, r *http.R
root, err := blk.Block().HashTreeRoot()
if err != nil {
httputil.HandleError(w, "Could not get block root: "+err.Error(), http.StatusInternalServerError)
httputil2.HandleError(w, "Could not get block root: "+err.Error(), http.StatusInternalServerError)
return nil, false, [32]byte{}
}
isOptimistic, err := s.OptimisticModeFetcher.IsOptimisticForRoot(ctx, root)
if err != nil {
httputil.HandleError(w, "Could not check if block is optimistic: "+err.Error(), http.StatusInternalServerError)
httputil2.HandleError(w, "Could not check if block is optimistic: "+err.Error(), http.StatusInternalServerError)
return nil, false, [32]byte{}
}
return blk, isOptimistic, root
@@ -410,7 +409,7 @@ func (s *Server) PublishBlindedBlock(w http.ResponseWriter, r *http.Request) {
if shared.IsSyncing(r.Context(), w, s.SyncChecker, s.HeadFetcher, s.TimeFetcher, s.OptimisticModeFetcher) {
return
}
if httputil.IsRequestSsz(r) {
if httputil2.IsRequestSsz(r) {
s.publishBlindedBlockSSZ(ctx, w, r, false)
} else {
s.publishBlindedBlock(ctx, w, r, false)
@@ -434,7 +433,7 @@ func (s *Server) PublishBlindedBlockV2(w http.ResponseWriter, r *http.Request) {
if shared.IsSyncing(r.Context(), w, s.SyncChecker, s.HeadFetcher, s.TimeFetcher, s.OptimisticModeFetcher) {
return
}
if httputil.IsRequestSsz(r) {
if httputil2.IsRequestSsz(r) {
s.publishBlindedBlockSSZ(ctx, w, r, true)
} else {
s.publishBlindedBlock(ctx, w, r, true)
@@ -445,24 +444,24 @@ func (s *Server) PublishBlindedBlockV2(w http.ResponseWriter, r *http.Request) {
func (s *Server) publishBlindedBlockSSZ(ctx context.Context, w http.ResponseWriter, r *http.Request, versionRequired bool) {
body, err := readRequestBody(r)
if err != nil {
httputil.HandleError(w, "Could not read request body: "+err.Error(), http.StatusInternalServerError)
httputil2.HandleError(w, "Could not read request body: "+err.Error(), http.StatusInternalServerError)
return
}
versionHeader, err := validateVersionHeader(r, body, versionRequired)
if err != nil {
httputil.HandleError(w, err.Error(), http.StatusBadRequest)
httputil2.HandleError(w, err.Error(), http.StatusBadRequest)
return
}
genericBlock, err := decodeBlindedBlockSSZ(versionHeader, body)
if err != nil {
httputil.HandleError(w, err.Error(), http.StatusBadRequest)
httputil2.HandleError(w, err.Error(), http.StatusBadRequest)
return
}
if err := s.validateBroadcast(ctx, r, genericBlock); err != nil {
httputil.HandleError(w, err.Error(), http.StatusBadRequest)
httputil2.HandleError(w, err.Error(), http.StatusBadRequest)
return
}
s.proposeBlock(ctx, w, genericBlock)
@@ -550,24 +549,24 @@ func decodeBlindedBellatrixSSZ(body []byte) (*eth.GenericSignedBeaconBlock, erro
func (s *Server) publishBlindedBlock(ctx context.Context, w http.ResponseWriter, r *http.Request, versionRequired bool) {
body, err := readRequestBody(r)
if err != nil {
httputil.HandleError(w, "Could not read request body", http.StatusInternalServerError)
httputil2.HandleError(w, "Could not read request body", http.StatusInternalServerError)
return
}
versionHeader, err := validateVersionHeader(r, body, versionRequired)
if err != nil {
httputil.HandleError(w, err.Error(), http.StatusBadRequest)
httputil2.HandleError(w, err.Error(), http.StatusBadRequest)
return
}
genericBlock, err := decodeBlindedBlockJSON(versionHeader, body)
if err != nil {
httputil.HandleError(w, err.Error(), http.StatusBadRequest)
httputil2.HandleError(w, err.Error(), http.StatusBadRequest)
return
}
if err := s.validateBroadcast(ctx, r, genericBlock); err != nil {
httputil.HandleError(w, err.Error(), http.StatusBadRequest)
httputil2.HandleError(w, err.Error(), http.StatusBadRequest)
return
}
s.proposeBlock(ctx, w, genericBlock)
@@ -641,7 +640,7 @@ func (s *Server) PublishBlock(w http.ResponseWriter, r *http.Request) {
if shared.IsSyncing(r.Context(), w, s.SyncChecker, s.HeadFetcher, s.TimeFetcher, s.OptimisticModeFetcher) {
return
}
if httputil.IsRequestSsz(r) {
if httputil2.IsRequestSsz(r) {
s.publishBlockSSZ(ctx, w, r, false)
} else {
s.publishBlock(ctx, w, r, false)
@@ -663,7 +662,7 @@ func (s *Server) PublishBlockV2(w http.ResponseWriter, r *http.Request) {
if shared.IsSyncing(r.Context(), w, s.SyncChecker, s.HeadFetcher, s.TimeFetcher, s.OptimisticModeFetcher) {
return
}
if httputil.IsRequestSsz(r) {
if httputil2.IsRequestSsz(r) {
s.publishBlockSSZ(ctx, w, r, true)
} else {
s.publishBlock(ctx, w, r, true)
@@ -674,20 +673,20 @@ func (s *Server) PublishBlockV2(w http.ResponseWriter, r *http.Request) {
func (s *Server) publishBlockSSZ(ctx context.Context, w http.ResponseWriter, r *http.Request, versionRequired bool) {
body, err := readRequestBody(r)
if err != nil {
httputil.HandleError(w, "Could not read request body", http.StatusInternalServerError)
httputil2.HandleError(w, "Could not read request body", http.StatusInternalServerError)
return
}
versionHeader, err := validateVersionHeader(r, body, versionRequired)
if err != nil {
httputil.HandleError(w, err.Error(), http.StatusBadRequest)
httputil2.HandleError(w, err.Error(), http.StatusBadRequest)
return
}
// Decode SSZ into a generic block.
genericBlock, err := decodeSSZToGenericBlock(versionHeader, body)
if err != nil {
httputil.HandleError(w, err.Error(), http.StatusBadRequest)
httputil2.HandleError(w, err.Error(), http.StatusBadRequest)
return
}
@@ -696,14 +695,14 @@ func (s *Server) publishBlockSSZ(ctx context.Context, w http.ResponseWriter, r *
if errors.Is(err, errEquivocatedBlock) {
b, err := blocks.NewSignedBeaconBlock(genericBlock)
if err != nil {
httputil.HandleError(w, err.Error(), http.StatusBadRequest)
httputil2.HandleError(w, err.Error(), http.StatusBadRequest)
return
}
if err = broadcastSidecarsIfSupported(ctx, s, b, genericBlock, versionHeader); err != nil {
log.WithError(err).Error("Failed to broadcast blob sidecars")
}
}
httputil.HandleError(w, err.Error(), http.StatusBadRequest)
httputil2.HandleError(w, err.Error(), http.StatusBadRequest)
return
}
@@ -828,20 +827,20 @@ func decodePhase0SSZ(body []byte) (*eth.GenericSignedBeaconBlock, error) {
func (s *Server) publishBlock(ctx context.Context, w http.ResponseWriter, r *http.Request, versionRequired bool) {
body, err := readRequestBody(r)
if err != nil {
httputil.HandleError(w, "Could not read request body", http.StatusInternalServerError)
httputil2.HandleError(w, "Could not read request body", http.StatusInternalServerError)
return
}
versionHeader, err := validateVersionHeader(r, body, versionRequired)
if err != nil {
httputil.HandleError(w, err.Error(), http.StatusBadRequest)
httputil2.HandleError(w, err.Error(), http.StatusBadRequest)
return
}
// Decode JSON into a generic block.
genericBlock, decodeErr := decodeJSONToGenericBlock(versionHeader, body)
if decodeErr != nil {
httputil.HandleError(w, decodeErr.Error(), http.StatusBadRequest)
httputil2.HandleError(w, decodeErr.Error(), http.StatusBadRequest)
return
}
@@ -850,7 +849,7 @@ func (s *Server) publishBlock(ctx context.Context, w http.ResponseWriter, r *htt
if errors.Is(err, errEquivocatedBlock) {
b, err := blocks.NewSignedBeaconBlock(genericBlock)
if err != nil {
httputil.HandleError(w, err.Error(), http.StatusBadRequest)
httputil2.HandleError(w, err.Error(), http.StatusBadRequest)
return
}
@@ -858,7 +857,7 @@ func (s *Server) publishBlock(ctx context.Context, w http.ResponseWriter, r *htt
log.WithError(err).Error("Failed to broadcast blob sidecars")
}
}
httputil.HandleError(w, err.Error(), http.StatusBadRequest)
httputil2.HandleError(w, err.Error(), http.StatusBadRequest)
return
}
@@ -950,7 +949,7 @@ func broadcastSidecarsIfSupported(ctx context.Context, s *Server, b interfaces.S
func (s *Server) proposeBlock(ctx context.Context, w http.ResponseWriter, blk *eth.GenericSignedBeaconBlock) {
_, err := s.V1Alpha1ValidatorServer.ProposeBeaconBlock(ctx, blk)
if err != nil {
httputil.HandleError(w, err.Error(), http.StatusInternalServerError)
httputil2.HandleError(w, err.Error(), http.StatusInternalServerError)
return
}
}
@@ -1069,18 +1068,18 @@ func (s *Server) GetBlockRoot(w http.ResponseWriter, r *http.Request) {
var root []byte
blockID := r.PathValue("block_id")
if blockID == "" {
httputil.HandleError(w, "block_id is required in URL params", http.StatusBadRequest)
httputil2.HandleError(w, "block_id is required in URL params", http.StatusBadRequest)
return
}
switch blockID {
case "head":
root, err = s.ChainInfoFetcher.HeadRoot(ctx)
if err != nil {
httputil.HandleError(w, "Could not retrieve head root: "+err.Error(), http.StatusInternalServerError)
httputil2.HandleError(w, "Could not retrieve head root: "+err.Error(), http.StatusInternalServerError)
return
}
if root == nil {
httputil.HandleError(w, "No head root was found", http.StatusNotFound)
httputil2.HandleError(w, "No head root was found", http.StatusNotFound)
return
}
case "finalized":
@@ -1089,16 +1088,16 @@ func (s *Server) GetBlockRoot(w http.ResponseWriter, r *http.Request) {
case "genesis":
blk, err := s.BeaconDB.GenesisBlock(ctx)
if err != nil {
httputil.HandleError(w, "Could not retrieve genesis block: "+err.Error(), http.StatusInternalServerError)
httputil2.HandleError(w, "Could not retrieve genesis block: "+err.Error(), http.StatusInternalServerError)
return
}
if err := blocks.BeaconBlockIsNil(blk); err != nil {
httputil.HandleError(w, "Could not find genesis block: "+err.Error(), http.StatusNotFound)
httputil2.HandleError(w, "Could not find genesis block: "+err.Error(), http.StatusNotFound)
return
}
blkRoot, err := blk.Block().HashTreeRoot()
if err != nil {
httputil.HandleError(w, "Could not hash genesis block: "+err.Error(), http.StatusInternalServerError)
httputil2.HandleError(w, "Could not hash genesis block: "+err.Error(), http.StatusInternalServerError)
return
}
root = blkRoot[:]
@@ -1107,38 +1106,38 @@ func (s *Server) GetBlockRoot(w http.ResponseWriter, r *http.Request) {
if isHex {
blockIDBytes, err := hexutil.Decode(blockID)
if err != nil {
httputil.HandleError(w, "Could not decode block ID into bytes: "+err.Error(), http.StatusBadRequest)
httputil2.HandleError(w, "Could not decode block ID into bytes: "+err.Error(), http.StatusBadRequest)
return
}
if len(blockIDBytes) != fieldparams.RootLength {
httputil.HandleError(w, fmt.Sprintf("Block ID has length %d instead of %d", len(blockIDBytes), fieldparams.RootLength), http.StatusBadRequest)
httputil2.HandleError(w, fmt.Sprintf("Block ID has length %d instead of %d", len(blockIDBytes), fieldparams.RootLength), http.StatusBadRequest)
return
}
blockID32 := bytesutil.ToBytes32(blockIDBytes)
blk, err := s.BeaconDB.Block(ctx, blockID32)
if err != nil {
httputil.HandleError(w, fmt.Sprintf("Could not retrieve block for block root %#x: %v", blockID, err), http.StatusInternalServerError)
httputil2.HandleError(w, fmt.Sprintf("Could not retrieve block for block root %#x: %v", blockID, err), http.StatusInternalServerError)
return
}
if err := blocks.BeaconBlockIsNil(blk); err != nil {
httputil.HandleError(w, "Could not find block: "+err.Error(), http.StatusNotFound)
httputil2.HandleError(w, "Could not find block: "+err.Error(), http.StatusNotFound)
return
}
root = blockIDBytes
} else {
slot, err := strconv.ParseUint(blockID, 10, 64)
if err != nil {
httputil.HandleError(w, "Could not parse block ID: "+err.Error(), http.StatusBadRequest)
httputil2.HandleError(w, "Could not parse block ID: "+err.Error(), http.StatusBadRequest)
return
}
hasRoots, roots, err := s.BeaconDB.BlockRootsBySlot(ctx, primitives.Slot(slot))
if err != nil {
httputil.HandleError(w, fmt.Sprintf("Could not retrieve blocks for slot %d: %v", slot, err), http.StatusInternalServerError)
httputil2.HandleError(w, fmt.Sprintf("Could not retrieve blocks for slot %d: %v", slot, err), http.StatusInternalServerError)
return
}
if !hasRoots {
httputil.HandleError(w, "Could not find any blocks with given slot", http.StatusNotFound)
httputil2.HandleError(w, "Could not find any blocks with given slot", http.StatusNotFound)
return
}
root = roots[0][:]
@@ -1148,7 +1147,7 @@ func (s *Server) GetBlockRoot(w http.ResponseWriter, r *http.Request) {
for _, blockRoot := range roots {
canonical, err := s.ChainInfoFetcher.IsCanonical(ctx, blockRoot)
if err != nil {
httputil.HandleError(w, "Could not determine if block root is canonical: "+err.Error(), http.StatusInternalServerError)
httputil2.HandleError(w, "Could not determine if block root is canonical: "+err.Error(), http.StatusInternalServerError)
return
}
if canonical {
@@ -1162,7 +1161,7 @@ func (s *Server) GetBlockRoot(w http.ResponseWriter, r *http.Request) {
b32Root := bytesutil.ToBytes32(root)
isOptimistic, err := s.OptimisticModeFetcher.IsOptimisticForRoot(ctx, b32Root)
if err != nil {
httputil.HandleError(w, "Could not check if block is optimistic: "+err.Error(), http.StatusInternalServerError)
httputil2.HandleError(w, "Could not check if block is optimistic: "+err.Error(), http.StatusInternalServerError)
return
}
response := &structs.BlockRootResponse{
@@ -1172,7 +1171,7 @@ func (s *Server) GetBlockRoot(w http.ResponseWriter, r *http.Request) {
ExecutionOptimistic: isOptimistic,
Finalized: s.FinalizationFetcher.IsFinalized(ctx, b32Root),
}
httputil.WriteJson(w, response)
httputil2.WriteJson(w, response)
}
// GetStateFork returns Fork object for state with given 'stateId'.
@@ -1182,7 +1181,7 @@ func (s *Server) GetStateFork(w http.ResponseWriter, r *http.Request) {
stateId := r.PathValue("state_id")
if stateId == "" {
httputil.HandleError(w, "state_id is required in URL params", http.StatusBadRequest)
httputil2.HandleError(w, "state_id is required in URL params", http.StatusBadRequest)
return
}
st, err := s.Stater.State(ctx, []byte(stateId))
@@ -1193,12 +1192,12 @@ func (s *Server) GetStateFork(w http.ResponseWriter, r *http.Request) {
fork := st.Fork()
isOptimistic, err := helpers.IsOptimistic(ctx, []byte(stateId), s.OptimisticModeFetcher, s.Stater, s.ChainInfoFetcher, s.BeaconDB)
if err != nil {
httputil.HandleError(w, "Could not check optimistic status"+err.Error(), http.StatusInternalServerError)
httputil2.HandleError(w, "Could not check optimistic status"+err.Error(), http.StatusInternalServerError)
return
}
blockRoot, err := st.LatestBlockHeader().HashTreeRoot()
if err != nil {
httputil.HandleError(w, errors.Wrap(err, "Could not calculate root of latest block header: ").Error(), http.StatusInternalServerError)
httputil2.HandleError(w, errors.Wrap(err, "Could not calculate root of latest block header: ").Error(), http.StatusInternalServerError)
return
}
isFinalized := s.FinalizationFetcher.IsFinalized(ctx, blockRoot)
@@ -1211,7 +1210,7 @@ func (s *Server) GetStateFork(w http.ResponseWriter, r *http.Request) {
ExecutionOptimistic: isOptimistic,
Finalized: isFinalized,
}
httputil.WriteJson(w, response)
httputil2.WriteJson(w, response)
}
// GetCommittees retrieves the committees for the given state at the given epoch.
@@ -1222,7 +1221,7 @@ func (s *Server) GetCommittees(w http.ResponseWriter, r *http.Request) {
stateId := r.PathValue("state_id")
if stateId == "" {
httputil.HandleError(w, "state_id is required in URL params", http.StatusBadRequest)
httputil2.HandleError(w, "state_id is required in URL params", http.StatusBadRequest)
return
}
@@ -1251,18 +1250,18 @@ func (s *Server) GetCommittees(w http.ResponseWriter, r *http.Request) {
}
activeCount, err := corehelpers.ActiveValidatorCount(ctx, st, epoch)
if err != nil {
httputil.HandleError(w, "Could not get active validator count: "+err.Error(), http.StatusInternalServerError)
httputil2.HandleError(w, "Could not get active validator count: "+err.Error(), http.StatusInternalServerError)
return
}
startSlot, err := slots.EpochStart(epoch)
if err != nil {
httputil.HandleError(w, "Could not get epoch start slot: "+err.Error(), http.StatusInternalServerError)
httputil2.HandleError(w, "Could not get epoch start slot: "+err.Error(), http.StatusInternalServerError)
return
}
endSlot, err := slots.EpochEnd(epoch)
if err != nil {
httputil.HandleError(w, "Could not get epoch end slot: "+err.Error(), http.StatusInternalServerError)
httputil2.HandleError(w, "Could not get epoch end slot: "+err.Error(), http.StatusInternalServerError)
return
}
committeesPerSlot := corehelpers.SlotCommitteeCount(activeCount)
@@ -1277,7 +1276,7 @@ func (s *Server) GetCommittees(w http.ResponseWriter, r *http.Request) {
}
committee, err := corehelpers.BeaconCommitteeFromState(ctx, st, slot, index)
if err != nil {
httputil.HandleError(w, "Could not get committee: "+err.Error(), http.StatusInternalServerError)
httputil2.HandleError(w, "Could not get committee: "+err.Error(), http.StatusInternalServerError)
return
}
var validators []string
@@ -1295,17 +1294,17 @@ func (s *Server) GetCommittees(w http.ResponseWriter, r *http.Request) {
isOptimistic, err := helpers.IsOptimistic(ctx, []byte(stateId), s.OptimisticModeFetcher, s.Stater, s.ChainInfoFetcher, s.BeaconDB)
if err != nil {
httputil.HandleError(w, "Could not check optimistic status: "+err.Error(), http.StatusInternalServerError)
httputil2.HandleError(w, "Could not check optimistic status: "+err.Error(), http.StatusInternalServerError)
return
}
blockRoot, err := st.LatestBlockHeader().HashTreeRoot()
if err != nil {
httputil.HandleError(w, "Could not calculate root of latest block header: "+err.Error(), http.StatusInternalServerError)
httputil2.HandleError(w, "Could not calculate root of latest block header: "+err.Error(), http.StatusInternalServerError)
return
}
isFinalized := s.FinalizationFetcher.IsFinalized(ctx, blockRoot)
httputil.WriteJson(w, &structs.GetCommitteesResponse{Data: committees, ExecutionOptimistic: isOptimistic, Finalized: isFinalized})
httputil2.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.
@@ -1329,7 +1328,7 @@ func (s *Server) GetBlockHeaders(w http.ResponseWriter, r *http.Request) {
if rawParentRoot != "" {
blks, blkRoots, err = s.BeaconDB.Blocks(ctx, filters.NewFilter().SetParentRoot(parentRoot))
if err != nil {
httputil.HandleError(w, errors.Wrapf(err, "Could not retrieve blocks for parent root %s", parentRoot).Error(), http.StatusInternalServerError)
httputil2.HandleError(w, errors.Wrapf(err, "Could not retrieve blocks for parent root %s", parentRoot).Error(), http.StatusInternalServerError)
return
}
} else {
@@ -1338,18 +1337,18 @@ func (s *Server) GetBlockHeaders(w http.ResponseWriter, r *http.Request) {
}
blks, err = s.BeaconDB.BlocksBySlot(ctx, primitives.Slot(slot))
if err != nil {
httputil.HandleError(w, errors.Wrapf(err, "Could not retrieve blocks for slot %d", slot).Error(), http.StatusInternalServerError)
httputil2.HandleError(w, errors.Wrapf(err, "Could not retrieve blocks for slot %d", slot).Error(), http.StatusInternalServerError)
return
}
_, blkRoots, err = s.BeaconDB.BlockRootsBySlot(ctx, primitives.Slot(slot))
if err != nil {
httputil.HandleError(w, errors.Wrapf(err, "Could not retrieve blocks for slot %d", slot).Error(), http.StatusInternalServerError)
httputil2.HandleError(w, errors.Wrapf(err, "Could not retrieve blocks for slot %d", slot).Error(), http.StatusInternalServerError)
return
}
}
if len(blks) == 0 {
httputil.HandleError(w, "No blocks found", http.StatusNotFound)
httputil2.HandleError(w, "No blocks found", http.StatusNotFound)
return
}
@@ -1359,23 +1358,23 @@ func (s *Server) GetBlockHeaders(w http.ResponseWriter, r *http.Request) {
for i, bl := range blks {
v1alpha1Header, err := bl.Header()
if err != nil {
httputil.HandleError(w, errors.Wrapf(err, "Could not get block header from block").Error(), http.StatusInternalServerError)
httputil2.HandleError(w, errors.Wrapf(err, "Could not get block header from block").Error(), http.StatusInternalServerError)
return
}
headerRoot, err := v1alpha1Header.Header.HashTreeRoot()
if err != nil {
httputil.HandleError(w, errors.Wrapf(err, "Could not hash block header").Error(), http.StatusInternalServerError)
httputil2.HandleError(w, errors.Wrapf(err, "Could not hash block header").Error(), http.StatusInternalServerError)
return
}
canonical, err := s.ChainInfoFetcher.IsCanonical(ctx, blkRoots[i])
if err != nil {
httputil.HandleError(w, errors.Wrapf(err, "Could not determine if block root is canonical").Error(), http.StatusInternalServerError)
httputil2.HandleError(w, errors.Wrapf(err, "Could not determine if block root is canonical").Error(), http.StatusInternalServerError)
return
}
if !isOptimistic {
isOptimistic, err = s.OptimisticModeFetcher.IsOptimisticForRoot(ctx, blkRoots[i])
if err != nil {
httputil.HandleError(w, errors.Wrapf(err, "Could not check if block is optimistic").Error(), http.StatusInternalServerError)
httputil2.HandleError(w, errors.Wrapf(err, "Could not check if block is optimistic").Error(), http.StatusInternalServerError)
return
}
}
@@ -1397,7 +1396,7 @@ func (s *Server) GetBlockHeaders(w http.ResponseWriter, r *http.Request) {
ExecutionOptimistic: isOptimistic,
Finalized: isFinalized,
}
httputil.WriteJson(w, response)
httputil2.WriteJson(w, response)
}
// GetBlockHeader retrieves block header for given block id.
@@ -1407,7 +1406,7 @@ func (s *Server) GetBlockHeader(w http.ResponseWriter, r *http.Request) {
blockID := r.PathValue("block_id")
if blockID == "" {
httputil.HandleError(w, "block_id is required in URL params", http.StatusBadRequest)
httputil2.HandleError(w, "block_id is required in URL params", http.StatusBadRequest)
return
}
@@ -1418,27 +1417,27 @@ func (s *Server) GetBlockHeader(w http.ResponseWriter, r *http.Request) {
}
blockHeader, err := blk.Header()
if err != nil {
httputil.HandleError(w, "Could not get block header: %s"+err.Error(), http.StatusInternalServerError)
httputil2.HandleError(w, "Could not get block header: %s"+err.Error(), http.StatusInternalServerError)
return
}
headerRoot, err := blockHeader.Header.HashTreeRoot()
if err != nil {
httputil.HandleError(w, "Could not hash block header: %s"+err.Error(), http.StatusInternalServerError)
httputil2.HandleError(w, "Could not hash block header: %s"+err.Error(), http.StatusInternalServerError)
return
}
blkRoot, err := blk.Block().HashTreeRoot()
if err != nil {
httputil.HandleError(w, "Could not hash block: %s"+err.Error(), http.StatusInternalServerError)
httputil2.HandleError(w, "Could not hash block: %s"+err.Error(), http.StatusInternalServerError)
return
}
canonical, err := s.ChainInfoFetcher.IsCanonical(ctx, blkRoot)
if err != nil {
httputil.HandleError(w, "Could not determine if block root is canonical: %s"+err.Error(), http.StatusInternalServerError)
httputil2.HandleError(w, "Could not determine if block root is canonical: %s"+err.Error(), http.StatusInternalServerError)
return
}
isOptimistic, err := s.OptimisticModeFetcher.IsOptimisticForRoot(ctx, blkRoot)
if err != nil {
httputil.HandleError(w, "Could not check if block is optimistic: %s"+err.Error(), http.StatusInternalServerError)
httputil2.HandleError(w, "Could not check if block is optimistic: %s"+err.Error(), http.StatusInternalServerError)
return
}
@@ -1454,7 +1453,7 @@ func (s *Server) GetBlockHeader(w http.ResponseWriter, r *http.Request) {
ExecutionOptimistic: isOptimistic,
Finalized: s.FinalizationFetcher.IsFinalized(ctx, blkRoot),
}
httputil.WriteJson(w, resp)
httputil2.WriteJson(w, resp)
}
// GetFinalityCheckpoints returns finality checkpoints for state with given 'stateId'. In case finality is
@@ -1465,7 +1464,7 @@ func (s *Server) GetFinalityCheckpoints(w http.ResponseWriter, r *http.Request)
stateId := r.PathValue("state_id")
if stateId == "" {
httputil.HandleError(w, "state_id is required in URL params", http.StatusBadRequest)
httputil2.HandleError(w, "state_id is required in URL params", http.StatusBadRequest)
return
}
@@ -1476,12 +1475,12 @@ func (s *Server) GetFinalityCheckpoints(w http.ResponseWriter, r *http.Request)
}
isOptimistic, err := helpers.IsOptimistic(ctx, []byte(stateId), s.OptimisticModeFetcher, s.Stater, s.ChainInfoFetcher, s.BeaconDB)
if err != nil {
httputil.HandleError(w, "Could not check optimistic status: "+err.Error(), http.StatusInternalServerError)
httputil2.HandleError(w, "Could not check optimistic status: "+err.Error(), http.StatusInternalServerError)
return
}
blockRoot, err := st.LatestBlockHeader().HashTreeRoot()
if err != nil {
httputil.HandleError(w, "Could not calculate root of latest block header: "+err.Error(), http.StatusInternalServerError)
httputil2.HandleError(w, "Could not calculate root of latest block header: "+err.Error(), http.StatusInternalServerError)
return
}
isFinalized := s.FinalizationFetcher.IsFinalized(ctx, blockRoot)
@@ -1507,7 +1506,7 @@ func (s *Server) GetFinalityCheckpoints(w http.ResponseWriter, r *http.Request)
ExecutionOptimistic: isOptimistic,
Finalized: isFinalized,
}
httputil.WriteJson(w, resp)
httputil2.WriteJson(w, resp)
}
// GetGenesis retrieves details of the chain's genesis which can be used to identify chain.
@@ -1517,12 +1516,12 @@ func (s *Server) GetGenesis(w http.ResponseWriter, r *http.Request) {
genesisTime := s.GenesisTimeFetcher.GenesisTime()
if genesisTime.IsZero() {
httputil.HandleError(w, "Chain genesis info is not yet known", http.StatusNotFound)
httputil2.HandleError(w, "Chain genesis info is not yet known", http.StatusNotFound)
return
}
validatorsRoot := s.ChainInfoFetcher.GenesisValidatorsRoot()
if bytes.Equal(validatorsRoot[:], params.BeaconConfig().ZeroHash[:]) {
httputil.HandleError(w, "Chain genesis info is not yet known", http.StatusNotFound)
httputil2.HandleError(w, "Chain genesis info is not yet known", http.StatusNotFound)
return
}
forkVersion := params.BeaconConfig().GenesisForkVersion
@@ -1534,7 +1533,7 @@ func (s *Server) GetGenesis(w http.ResponseWriter, r *http.Request) {
GenesisForkVersion: hexutil.Encode(forkVersion),
},
}
httputil.WriteJson(w, resp)
httputil2.WriteJson(w, resp)
}
// Deprecated: no longer needed post Electra
@@ -1546,32 +1545,32 @@ func (s *Server) GetDepositSnapshot(w http.ResponseWriter, r *http.Request) {
eth1data, err := s.BeaconDB.ExecutionChainData(ctx)
if err != nil {
httputil.HandleError(w, "Could not retrieve execution chain data: "+err.Error(), http.StatusInternalServerError)
httputil2.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)
httputil2.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)
httputil2.HandleError(w, "No finalized snapshot available", http.StatusNotFound)
return
}
if len(snapshot.Finalized) > depositsnapshot.DepositContractDepth {
httputil.HandleError(w, "Retrieved invalid deposit snapshot", http.StatusInternalServerError)
httputil2.HandleError(w, "Retrieved invalid deposit snapshot", http.StatusInternalServerError)
return
}
if httputil.RespondWithSsz(r) {
if httputil2.RespondWithSsz(r) {
sszData, err := snapshot.MarshalSSZ()
if err != nil {
httputil.HandleError(w, "Could not marshal deposit snapshot into SSZ: "+err.Error(), http.StatusInternalServerError)
httputil2.HandleError(w, "Could not marshal deposit snapshot into SSZ: "+err.Error(), http.StatusInternalServerError)
return
}
httputil.WriteSsz(w, sszData, "deposit_snapshot.ssz")
httputil2.WriteSsz(w, sszData)
return
}
httputil.WriteJson(
httputil2.WriteJson(
w,
&structs.GetDepositSnapshotResponse{
Data: structs.DepositSnapshotFromConsensus(snapshot),
@@ -1622,7 +1621,7 @@ func (s *Server) GetPendingDeposits(w http.ResponseWriter, r *http.Request) {
stateId := r.PathValue("state_id")
if stateId == "" {
httputil.HandleError(w, "state_id is required in URL params", http.StatusBadRequest)
httputil2.HandleError(w, "state_id is required in URL params", http.StatusBadRequest)
return
}
st, err := s.Stater.State(ctx, []byte(stateId))
@@ -1631,31 +1630,31 @@ func (s *Server) GetPendingDeposits(w http.ResponseWriter, r *http.Request) {
return
}
if st.Version() < version.Electra {
httputil.HandleError(w, "state_id is prior to electra", http.StatusBadRequest)
httputil2.HandleError(w, "state_id is prior to electra", http.StatusBadRequest)
return
}
pd, err := st.PendingDeposits()
if err != nil {
httputil.HandleError(w, "Could not get pending deposits: "+err.Error(), http.StatusInternalServerError)
httputil2.HandleError(w, "Could not get pending deposits: "+err.Error(), http.StatusInternalServerError)
return
}
w.Header().Set(api.VersionHeader, version.String(st.Version()))
if httputil.RespondWithSsz(r) {
w.Header().Set(httputil2.VersionHeader, version.String(st.Version()))
if httputil2.RespondWithSsz(r) {
sszData, err := serializeItems(pd)
if err != nil {
httputil.HandleError(w, "Failed to serialize pending deposits: "+err.Error(), http.StatusInternalServerError)
httputil2.HandleError(w, "Failed to serialize pending deposits: "+err.Error(), http.StatusInternalServerError)
return
}
httputil.WriteSsz(w, sszData, "pending_deposits.ssz")
httputil2.WriteSsz(w, sszData)
} else {
isOptimistic, err := helpers.IsOptimistic(ctx, []byte(stateId), s.OptimisticModeFetcher, s.Stater, s.ChainInfoFetcher, s.BeaconDB)
if err != nil {
httputil.HandleError(w, "Could not check optimistic status: "+err.Error(), http.StatusInternalServerError)
httputil2.HandleError(w, "Could not check optimistic status: "+err.Error(), http.StatusInternalServerError)
return
}
blockRoot, err := st.LatestBlockHeader().HashTreeRoot()
if err != nil {
httputil.HandleError(w, "Could not calculate root of latest block header: "+err.Error(), http.StatusInternalServerError)
httputil2.HandleError(w, "Could not calculate root of latest block header: "+err.Error(), http.StatusInternalServerError)
return
}
isFinalized := s.FinalizationFetcher.IsFinalized(ctx, blockRoot)
@@ -1665,7 +1664,7 @@ func (s *Server) GetPendingDeposits(w http.ResponseWriter, r *http.Request) {
Finalized: isFinalized,
Data: structs.PendingDepositsFromConsensus(pd),
}
httputil.WriteJson(w, resp)
httputil2.WriteJson(w, resp)
}
}
@@ -1678,7 +1677,7 @@ func (s *Server) GetPendingPartialWithdrawals(w http.ResponseWriter, r *http.Req
stateId := r.PathValue("state_id")
if stateId == "" {
httputil.HandleError(w, "state_id is required in URL params", http.StatusBadRequest)
httputil2.HandleError(w, "state_id is required in URL params", http.StatusBadRequest)
return
}
st, err := s.Stater.State(ctx, []byte(stateId))
@@ -1687,31 +1686,31 @@ func (s *Server) GetPendingPartialWithdrawals(w http.ResponseWriter, r *http.Req
return
}
if st.Version() < version.Electra {
httputil.HandleError(w, "state_id is prior to electra", http.StatusBadRequest)
httputil2.HandleError(w, "state_id is prior to electra", http.StatusBadRequest)
return
}
ppw, err := st.PendingPartialWithdrawals()
if err != nil {
httputil.HandleError(w, "Could not get pending partial withdrawals: "+err.Error(), http.StatusInternalServerError)
httputil2.HandleError(w, "Could not get pending partial withdrawals: "+err.Error(), http.StatusInternalServerError)
return
}
w.Header().Set(api.VersionHeader, version.String(st.Version()))
if httputil.RespondWithSsz(r) {
w.Header().Set(httputil2.VersionHeader, version.String(st.Version()))
if httputil2.RespondWithSsz(r) {
sszData, err := serializeItems(ppw)
if err != nil {
httputil.HandleError(w, "Failed to serialize pending partial withdrawals: "+err.Error(), http.StatusInternalServerError)
httputil2.HandleError(w, "Failed to serialize pending partial withdrawals: "+err.Error(), http.StatusInternalServerError)
return
}
httputil.WriteSsz(w, sszData, "pending_partial_withdrawals.ssz")
httputil2.WriteSsz(w, sszData)
} else {
isOptimistic, err := helpers.IsOptimistic(ctx, []byte(stateId), s.OptimisticModeFetcher, s.Stater, s.ChainInfoFetcher, s.BeaconDB)
if err != nil {
httputil.HandleError(w, "Could not check optimistic status: "+err.Error(), http.StatusInternalServerError)
httputil2.HandleError(w, "Could not check optimistic status: "+err.Error(), http.StatusInternalServerError)
return
}
blockRoot, err := st.LatestBlockHeader().HashTreeRoot()
if err != nil {
httputil.HandleError(w, "Could not calculate root of latest block header: "+err.Error(), http.StatusInternalServerError)
httputil2.HandleError(w, "Could not calculate root of latest block header: "+err.Error(), http.StatusInternalServerError)
return
}
isFinalized := s.FinalizationFetcher.IsFinalized(ctx, blockRoot)
@@ -1721,7 +1720,7 @@ func (s *Server) GetPendingPartialWithdrawals(w http.ResponseWriter, r *http.Req
Finalized: isFinalized,
Data: structs.PendingPartialWithdrawalsFromConsensus(ppw),
}
httputil.WriteJson(w, resp)
httputil2.WriteJson(w, resp)
}
}

View File

@@ -11,7 +11,7 @@ import (
"time"
"github.com/pkg/errors"
"github.com/prysmaticlabs/prysm/v5/api"
httputil2 "github.com/prysmaticlabs/prysm/v5/api/httputil"
"github.com/prysmaticlabs/prysm/v5/api/server"
"github.com/prysmaticlabs/prysm/v5/api/server/structs"
"github.com/prysmaticlabs/prysm/v5/beacon-chain/core/blocks"
@@ -26,7 +26,6 @@ import (
"github.com/prysmaticlabs/prysm/v5/consensus-types/primitives"
"github.com/prysmaticlabs/prysm/v5/crypto/bls"
"github.com/prysmaticlabs/prysm/v5/monitoring/tracing/trace"
"github.com/prysmaticlabs/prysm/v5/network/httputil"
eth "github.com/prysmaticlabs/prysm/v5/proto/prysm/v1alpha1"
"github.com/prysmaticlabs/prysm/v5/runtime/version"
"github.com/prysmaticlabs/prysm/v5/time/slots"
@@ -64,7 +63,7 @@ func (s *Server) ListAttestations(w http.ResponseWriter, r *http.Request) {
var includeAttestation bool
att, ok := a.(*eth.Attestation)
if !ok {
httputil.HandleError(w, fmt.Sprintf("Unable to convert attestation of type %T", a), http.StatusInternalServerError)
httputil2.HandleError(w, fmt.Sprintf("Unable to convert attestation of type %T", a), http.StatusInternalServerError)
return
}
@@ -77,11 +76,11 @@ func (s *Server) ListAttestations(w http.ResponseWriter, r *http.Request) {
attsData, err := json.Marshal(filteredAtts)
if err != nil {
httputil.HandleError(w, "Could not marshal attestations: "+err.Error(), http.StatusInternalServerError)
httputil2.HandleError(w, "Could not marshal attestations: "+err.Error(), http.StatusInternalServerError)
return
}
httputil.WriteJson(w, &structs.ListAttestationsResponse{
httputil2.WriteJson(w, &structs.ListAttestationsResponse{
Data: attsData,
})
}
@@ -120,7 +119,7 @@ func (s *Server) ListAttestationsV2(w http.ResponseWriter, r *http.Request) {
if v >= version.Electra && att.Version() >= version.Electra {
attElectra, ok := att.(*eth.AttestationElectra)
if !ok {
httputil.HandleError(w, fmt.Sprintf("Unable to convert attestation of type %T", att), http.StatusInternalServerError)
httputil2.HandleError(w, fmt.Sprintf("Unable to convert attestation of type %T", att), http.StatusInternalServerError)
return
}
@@ -132,7 +131,7 @@ func (s *Server) ListAttestationsV2(w http.ResponseWriter, r *http.Request) {
} else if v < version.Electra && att.Version() < version.Electra {
attOld, ok := att.(*eth.Attestation)
if !ok {
httputil.HandleError(w, fmt.Sprintf("Unable to convert attestation of type %T", att), http.StatusInternalServerError)
httputil2.HandleError(w, fmt.Sprintf("Unable to convert attestation of type %T", att), http.StatusInternalServerError)
return
}
@@ -146,12 +145,12 @@ func (s *Server) ListAttestationsV2(w http.ResponseWriter, r *http.Request) {
attsData, err := json.Marshal(filteredAtts)
if err != nil {
httputil.HandleError(w, "Could not marshal attestations: "+err.Error(), http.StatusInternalServerError)
httputil2.HandleError(w, "Could not marshal attestations: "+err.Error(), http.StatusInternalServerError)
return
}
w.Header().Set(api.VersionHeader, version.String(v))
httputil.WriteJson(w, &structs.ListAttestationsResponse{
w.Header().Set(httputil2.VersionHeader, version.String(v))
httputil2.WriteJson(w, &structs.ListAttestationsResponse{
Version: version.String(v),
Data: attsData,
})
@@ -186,21 +185,21 @@ func (s *Server) SubmitAttestations(w http.ResponseWriter, r *http.Request) {
err := json.NewDecoder(r.Body).Decode(&req.Data)
switch {
case errors.Is(err, io.EOF):
httputil.HandleError(w, "No data submitted", http.StatusBadRequest)
httputil2.HandleError(w, "No data submitted", http.StatusBadRequest)
return
case err != nil:
httputil.HandleError(w, "Could not decode request body: "+err.Error(), http.StatusBadRequest)
httputil2.HandleError(w, "Could not decode request body: "+err.Error(), http.StatusBadRequest)
return
}
attFailures, failedBroadcasts, err := s.handleAttestations(ctx, req.Data)
if err != nil {
httputil.HandleError(w, err.Error(), http.StatusBadRequest)
httputil2.HandleError(w, err.Error(), http.StatusBadRequest)
return
}
if len(failedBroadcasts) > 0 {
httputil.HandleError(
httputil2.HandleError(
w,
fmt.Sprintf("Attestations at index %s could not be broadcasted", strings.Join(failedBroadcasts, ", ")),
http.StatusInternalServerError,
@@ -214,7 +213,7 @@ func (s *Server) SubmitAttestations(w http.ResponseWriter, r *http.Request) {
Message: "One or more attestations failed validation",
Failures: attFailures,
}
httputil.WriteError(w, failuresErr)
httputil2.WriteError(w, failuresErr)
}
}
@@ -224,14 +223,14 @@ func (s *Server) SubmitAttestationsV2(w http.ResponseWriter, r *http.Request) {
ctx, span := trace.StartSpan(r.Context(), "beacon.SubmitAttestationsV2")
defer span.End()
versionHeader := r.Header.Get(api.VersionHeader)
versionHeader := r.Header.Get(httputil2.VersionHeader)
if versionHeader == "" {
httputil.HandleError(w, api.VersionHeader+" header is required", http.StatusBadRequest)
httputil2.HandleError(w, httputil2.VersionHeader+" header is required", http.StatusBadRequest)
return
}
v, err := version.FromString(versionHeader)
if err != nil {
httputil.HandleError(w, "Invalid version: "+err.Error(), http.StatusBadRequest)
httputil2.HandleError(w, "Invalid version: "+err.Error(), http.StatusBadRequest)
return
}
@@ -239,10 +238,10 @@ func (s *Server) SubmitAttestationsV2(w http.ResponseWriter, r *http.Request) {
err = json.NewDecoder(r.Body).Decode(&req.Data)
switch {
case errors.Is(err, io.EOF):
httputil.HandleError(w, "No data submitted", http.StatusBadRequest)
httputil2.HandleError(w, "No data submitted", http.StatusBadRequest)
return
case err != nil:
httputil.HandleError(w, "Could not decode request body: "+err.Error(), http.StatusBadRequest)
httputil2.HandleError(w, "Could not decode request body: "+err.Error(), http.StatusBadRequest)
return
}
@@ -255,12 +254,12 @@ func (s *Server) SubmitAttestationsV2(w http.ResponseWriter, r *http.Request) {
attFailures, failedBroadcasts, err = s.handleAttestations(ctx, req.Data)
}
if err != nil {
httputil.HandleError(w, fmt.Sprintf("Failed to handle attestations: %v", err), http.StatusBadRequest)
httputil2.HandleError(w, fmt.Sprintf("Failed to handle attestations: %v", err), http.StatusBadRequest)
return
}
if len(failedBroadcasts) > 0 {
httputil.HandleError(
httputil2.HandleError(
w,
fmt.Sprintf("Attestations at index %s could not be broadcasted", strings.Join(failedBroadcasts, ", ")),
http.StatusInternalServerError,
@@ -274,7 +273,7 @@ func (s *Server) SubmitAttestationsV2(w http.ResponseWriter, r *http.Request) {
Message: "One or more attestations failed validation",
Failures: attFailures,
}
httputil.WriteError(w, failuresErr)
httputil2.WriteError(w, failuresErr)
}
}
@@ -441,7 +440,7 @@ func (s *Server) ListVoluntaryExits(w http.ResponseWriter, r *http.Request) {
sourceExits, err := s.VoluntaryExitsPool.PendingExits()
if err != nil {
httputil.HandleError(w, "Could not get exits from the pool: "+err.Error(), http.StatusInternalServerError)
httputil2.HandleError(w, "Could not get exits from the pool: "+err.Error(), http.StatusInternalServerError)
return
}
exits := make([]*structs.SignedVoluntaryExit, len(sourceExits))
@@ -449,7 +448,7 @@ func (s *Server) ListVoluntaryExits(w http.ResponseWriter, r *http.Request) {
exits[i] = structs.SignedExitFromConsensus(e)
}
httputil.WriteJson(w, &structs.ListVoluntaryExitsResponse{Data: exits})
httputil2.WriteJson(w, &structs.ListVoluntaryExitsResponse{Data: exits})
}
// SubmitVoluntaryExit submits a SignedVoluntaryExit object to node's pool
@@ -462,51 +461,51 @@ func (s *Server) SubmitVoluntaryExit(w http.ResponseWriter, r *http.Request) {
err := json.NewDecoder(r.Body).Decode(&req)
switch {
case errors.Is(err, io.EOF):
httputil.HandleError(w, "No data submitted", http.StatusBadRequest)
httputil2.HandleError(w, "No data submitted", http.StatusBadRequest)
return
case err != nil:
httputil.HandleError(w, "Could not decode request body: "+err.Error(), http.StatusBadRequest)
httputil2.HandleError(w, "Could not decode request body: "+err.Error(), http.StatusBadRequest)
return
}
exit, err := req.ToConsensus()
if err != nil {
httputil.HandleError(w, "Could not convert request exit to consensus exit: "+err.Error(), http.StatusBadRequest)
httputil2.HandleError(w, "Could not convert request exit to consensus exit: "+err.Error(), http.StatusBadRequest)
return
}
headState, err := s.ChainInfoFetcher.HeadState(ctx)
if err != nil {
httputil.HandleError(w, "Could not get head state: "+err.Error(), http.StatusInternalServerError)
httputil2.HandleError(w, "Could not get head state: "+err.Error(), http.StatusInternalServerError)
return
}
epochStart, err := slots.EpochStart(exit.Exit.Epoch)
if err != nil {
httputil.HandleError(w, "Could not get epoch start: "+err.Error(), http.StatusInternalServerError)
httputil2.HandleError(w, "Could not get epoch start: "+err.Error(), http.StatusInternalServerError)
return
}
headState, err = transition.ProcessSlotsIfPossible(ctx, headState, epochStart)
if err != nil {
httputil.HandleError(w, "Could not process slots: "+err.Error(), http.StatusInternalServerError)
httputil2.HandleError(w, "Could not process slots: "+err.Error(), http.StatusInternalServerError)
return
}
val, err := headState.ValidatorAtIndexReadOnly(exit.Exit.ValidatorIndex)
if err != nil {
if errors.Is(err, consensus_types.ErrOutOfBounds) {
httputil.HandleError(w, "Could not get validator: "+err.Error(), http.StatusBadRequest)
httputil2.HandleError(w, "Could not get validator: "+err.Error(), http.StatusBadRequest)
return
}
httputil.HandleError(w, "Could not get validator: "+err.Error(), http.StatusInternalServerError)
httputil2.HandleError(w, "Could not get validator: "+err.Error(), http.StatusInternalServerError)
return
}
if err = blocks.VerifyExitAndSignature(val, headState, exit); err != nil {
httputil.HandleError(w, "Invalid exit: "+err.Error(), http.StatusBadRequest)
httputil2.HandleError(w, "Invalid exit: "+err.Error(), http.StatusBadRequest)
return
}
s.VoluntaryExitsPool.InsertVoluntaryExit(exit)
if err = s.Broadcaster.Broadcast(ctx, exit); err != nil {
httputil.HandleError(w, "Could not broadcast exit: "+err.Error(), http.StatusInternalServerError)
httputil2.HandleError(w, "Could not broadcast exit: "+err.Error(), http.StatusInternalServerError)
return
}
}
@@ -520,14 +519,14 @@ func (s *Server) SubmitSyncCommitteeSignatures(w http.ResponseWriter, r *http.Re
err := json.NewDecoder(r.Body).Decode(&req.Data)
switch {
case errors.Is(err, io.EOF):
httputil.HandleError(w, "No data submitted", http.StatusBadRequest)
httputil2.HandleError(w, "No data submitted", http.StatusBadRequest)
return
case err != nil:
httputil.HandleError(w, "Could not decode request body: "+err.Error(), http.StatusBadRequest)
httputil2.HandleError(w, "Could not decode request body: "+err.Error(), http.StatusBadRequest)
return
}
if len(req.Data) == 0 {
httputil.HandleError(w, "No data submitted", http.StatusBadRequest)
httputil2.HandleError(w, "No data submitted", http.StatusBadRequest)
return
}
@@ -547,7 +546,7 @@ func (s *Server) SubmitSyncCommitteeSignatures(w http.ResponseWriter, r *http.Re
for _, msg := range validMessages {
if rpcerr := s.CoreService.SubmitSyncMessage(ctx, msg); rpcerr != nil {
httputil.HandleError(w, "Could not submit message: "+rpcerr.Err.Error(), core.ErrorReasonToHTTP(rpcerr.Reason))
httputil2.HandleError(w, "Could not submit message: "+rpcerr.Err.Error(), core.ErrorReasonToHTTP(rpcerr.Reason))
return
}
}
@@ -558,7 +557,7 @@ func (s *Server) SubmitSyncCommitteeSignatures(w http.ResponseWriter, r *http.Re
Message: "One or more messages failed validation",
Failures: msgFailures,
}
httputil.WriteError(w, failuresErr)
httputil2.WriteError(w, failuresErr)
}
}
@@ -569,7 +568,7 @@ func (s *Server) SubmitBLSToExecutionChanges(w http.ResponseWriter, r *http.Requ
defer span.End()
st, err := s.ChainInfoFetcher.HeadStateReadOnly(ctx)
if err != nil {
httputil.HandleError(w, fmt.Sprintf("Could not get head state: %v", err), http.StatusInternalServerError)
httputil2.HandleError(w, fmt.Sprintf("Could not get head state: %v", err), http.StatusInternalServerError)
return
}
var failures []*server.IndexedVerificationFailure
@@ -579,14 +578,14 @@ func (s *Server) SubmitBLSToExecutionChanges(w http.ResponseWriter, r *http.Requ
err = json.NewDecoder(r.Body).Decode(&req)
switch {
case errors.Is(err, io.EOF):
httputil.HandleError(w, "No data submitted", http.StatusBadRequest)
httputil2.HandleError(w, "No data submitted", http.StatusBadRequest)
return
case err != nil:
httputil.HandleError(w, "Could not decode request body: "+err.Error(), http.StatusBadRequest)
httputil2.HandleError(w, "Could not decode request body: "+err.Error(), http.StatusBadRequest)
return
}
if len(req) == 0 {
httputil.HandleError(w, "No data submitted", http.StatusBadRequest)
httputil2.HandleError(w, "No data submitted", http.StatusBadRequest)
return
}
@@ -632,7 +631,7 @@ func (s *Server) SubmitBLSToExecutionChanges(w http.ResponseWriter, r *http.Requ
Message: "One or more BLSToExecutionChange failed validation",
Failures: failures,
}
httputil.WriteError(w, failuresErr)
httputil2.WriteError(w, failuresErr)
}
}
@@ -691,11 +690,11 @@ func (s *Server) ListBLSToExecutionChanges(w http.ResponseWriter, r *http.Reques
sourceChanges, err := s.BLSChangesPool.PendingBLSToExecChanges()
if err != nil {
httputil.HandleError(w, fmt.Sprintf("Could not get BLS to execution changes: %v", err), http.StatusInternalServerError)
httputil2.HandleError(w, fmt.Sprintf("Could not get BLS to execution changes: %v", err), http.StatusInternalServerError)
return
}
httputil.WriteJson(w, &structs.BLSToExecutionChangesPoolResponse{
httputil2.WriteJson(w, &structs.BLSToExecutionChangesPoolResponse{
Data: structs.SignedBLSChangesFromConsensus(sourceChanges),
})
}
@@ -709,7 +708,7 @@ func (s *Server) GetAttesterSlashings(w http.ResponseWriter, r *http.Request) {
headState, err := s.ChainInfoFetcher.HeadStateReadOnly(ctx)
if err != nil {
httputil.HandleError(w, "Could not get head state: "+err.Error(), http.StatusInternalServerError)
httputil2.HandleError(w, "Could not get head state: "+err.Error(), http.StatusInternalServerError)
return
}
sourceSlashings := s.SlashingsPool.PendingAttesterSlashings(ctx, headState, true /* return unlimited slashings */)
@@ -717,17 +716,17 @@ func (s *Server) GetAttesterSlashings(w http.ResponseWriter, r *http.Request) {
for i, slashing := range sourceSlashings {
as, ok := slashing.(*eth.AttesterSlashing)
if !ok {
httputil.HandleError(w, fmt.Sprintf("Unable to convert slashing of type %T", slashing), http.StatusInternalServerError)
httputil2.HandleError(w, fmt.Sprintf("Unable to convert slashing of type %T", slashing), http.StatusInternalServerError)
return
}
slashings[i] = structs.AttesterSlashingFromConsensus(as)
}
attBytes, err := json.Marshal(slashings)
if err != nil {
httputil.HandleError(w, fmt.Sprintf("Failed to marshal slashings: %v", err), http.StatusInternalServerError)
httputil2.HandleError(w, fmt.Sprintf("Failed to marshal slashings: %v", err), http.StatusInternalServerError)
return
}
httputil.WriteJson(w, &structs.GetAttesterSlashingsResponse{Data: attBytes})
httputil2.WriteJson(w, &structs.GetAttesterSlashingsResponse{Data: attBytes})
}
// GetAttesterSlashingsV2 retrieves attester slashings known by the node but
@@ -739,7 +738,7 @@ func (s *Server) GetAttesterSlashingsV2(w http.ResponseWriter, r *http.Request)
v := slots.ToForkVersion(s.TimeFetcher.CurrentSlot())
headState, err := s.ChainInfoFetcher.HeadStateReadOnly(ctx)
if err != nil {
httputil.HandleError(w, "Could not get head state: "+err.Error(), http.StatusInternalServerError)
httputil2.HandleError(w, "Could not get head state: "+err.Error(), http.StatusInternalServerError)
return
}
var attStructs []interface{}
@@ -750,14 +749,14 @@ func (s *Server) GetAttesterSlashingsV2(w http.ResponseWriter, r *http.Request)
if v >= version.Electra && slashing.Version() >= version.Electra {
a, ok := slashing.(*eth.AttesterSlashingElectra)
if !ok {
httputil.HandleError(w, fmt.Sprintf("Unable to convert slashing of type %T to an Electra slashing", slashing), http.StatusInternalServerError)
httputil2.HandleError(w, fmt.Sprintf("Unable to convert slashing of type %T to an Electra slashing", slashing), http.StatusInternalServerError)
return
}
attStruct = structs.AttesterSlashingElectraFromConsensus(a)
} else if v < version.Electra && slashing.Version() < version.Electra {
a, ok := slashing.(*eth.AttesterSlashing)
if !ok {
httputil.HandleError(w, fmt.Sprintf("Unable to convert slashing of type %T to a Phase0 slashing", slashing), http.StatusInternalServerError)
httputil2.HandleError(w, fmt.Sprintf("Unable to convert slashing of type %T to a Phase0 slashing", slashing), http.StatusInternalServerError)
return
}
attStruct = structs.AttesterSlashingFromConsensus(a)
@@ -769,7 +768,7 @@ func (s *Server) GetAttesterSlashingsV2(w http.ResponseWriter, r *http.Request)
attBytes, err := json.Marshal(attStructs)
if err != nil {
httputil.HandleError(w, fmt.Sprintf("Failed to marshal slashing: %v", err), http.StatusInternalServerError)
httputil2.HandleError(w, fmt.Sprintf("Failed to marshal slashing: %v", err), http.StatusInternalServerError)
return
}
@@ -777,8 +776,8 @@ func (s *Server) GetAttesterSlashingsV2(w http.ResponseWriter, r *http.Request)
Version: version.String(v),
Data: attBytes,
}
w.Header().Set(api.VersionHeader, version.String(v))
httputil.WriteJson(w, resp)
w.Header().Set(httputil2.VersionHeader, version.String(v))
httputil2.WriteJson(w, resp)
}
// SubmitAttesterSlashings submits an attester slashing object to node's pool and
@@ -791,16 +790,16 @@ func (s *Server) SubmitAttesterSlashings(w http.ResponseWriter, r *http.Request)
err := json.NewDecoder(r.Body).Decode(&req)
switch {
case errors.Is(err, io.EOF):
httputil.HandleError(w, "No data submitted", http.StatusBadRequest)
httputil2.HandleError(w, "No data submitted", http.StatusBadRequest)
return
case err != nil:
httputil.HandleError(w, "Could not decode request body: "+err.Error(), http.StatusBadRequest)
httputil2.HandleError(w, "Could not decode request body: "+err.Error(), http.StatusBadRequest)
return
}
slashing, err := req.ToConsensus()
if err != nil {
httputil.HandleError(w, "Could not convert request slashing to consensus slashing: "+err.Error(), http.StatusBadRequest)
httputil2.HandleError(w, "Could not convert request slashing to consensus slashing: "+err.Error(), http.StatusBadRequest)
return
}
s.submitAttesterSlashing(w, ctx, slashing)
@@ -812,13 +811,13 @@ func (s *Server) SubmitAttesterSlashingsV2(w http.ResponseWriter, r *http.Reques
ctx, span := trace.StartSpan(r.Context(), "beacon.SubmitAttesterSlashingsV2")
defer span.End()
versionHeader := r.Header.Get(api.VersionHeader)
versionHeader := r.Header.Get(httputil2.VersionHeader)
if versionHeader == "" {
httputil.HandleError(w, api.VersionHeader+" header is required", http.StatusBadRequest)
httputil2.HandleError(w, httputil2.VersionHeader+" header is required", http.StatusBadRequest)
}
v, err := version.FromString(versionHeader)
if err != nil {
httputil.HandleError(w, "Invalid version: "+err.Error(), http.StatusBadRequest)
httputil2.HandleError(w, "Invalid version: "+err.Error(), http.StatusBadRequest)
return
}
@@ -827,16 +826,16 @@ func (s *Server) SubmitAttesterSlashingsV2(w http.ResponseWriter, r *http.Reques
err := json.NewDecoder(r.Body).Decode(&req)
switch {
case errors.Is(err, io.EOF):
httputil.HandleError(w, "No data submitted", http.StatusBadRequest)
httputil2.HandleError(w, "No data submitted", http.StatusBadRequest)
return
case err != nil:
httputil.HandleError(w, "Could not decode request body: "+err.Error(), http.StatusBadRequest)
httputil2.HandleError(w, "Could not decode request body: "+err.Error(), http.StatusBadRequest)
return
}
slashing, err := req.ToConsensus()
if err != nil {
httputil.HandleError(w, "Could not convert request slashing to consensus slashing: "+err.Error(), http.StatusBadRequest)
httputil2.HandleError(w, "Could not convert request slashing to consensus slashing: "+err.Error(), http.StatusBadRequest)
return
}
s.submitAttesterSlashing(w, ctx, slashing)
@@ -845,16 +844,16 @@ func (s *Server) SubmitAttesterSlashingsV2(w http.ResponseWriter, r *http.Reques
err := json.NewDecoder(r.Body).Decode(&req)
switch {
case errors.Is(err, io.EOF):
httputil.HandleError(w, "No data submitted", http.StatusBadRequest)
httputil2.HandleError(w, "No data submitted", http.StatusBadRequest)
return
case err != nil:
httputil.HandleError(w, "Could not decode request body: "+err.Error(), http.StatusBadRequest)
httputil2.HandleError(w, "Could not decode request body: "+err.Error(), http.StatusBadRequest)
return
}
slashing, err := req.ToConsensus()
if err != nil {
httputil.HandleError(w, "Could not convert request slashing to consensus slashing: "+err.Error(), http.StatusBadRequest)
httputil2.HandleError(w, "Could not convert request slashing to consensus slashing: "+err.Error(), http.StatusBadRequest)
return
}
s.submitAttesterSlashing(w, ctx, slashing)
@@ -868,23 +867,23 @@ func (s *Server) submitAttesterSlashing(
) {
headState, err := s.ChainInfoFetcher.HeadState(ctx)
if err != nil {
httputil.HandleError(w, "Could not get head state: "+err.Error(), http.StatusInternalServerError)
httputil2.HandleError(w, "Could not get head state: "+err.Error(), http.StatusInternalServerError)
return
}
headState, err = transition.ProcessSlotsIfPossible(ctx, headState, slashing.FirstAttestation().GetData().Slot)
if err != nil {
httputil.HandleError(w, "Could not process slots: "+err.Error(), http.StatusInternalServerError)
httputil2.HandleError(w, "Could not process slots: "+err.Error(), http.StatusInternalServerError)
return
}
err = blocks.VerifyAttesterSlashing(ctx, headState, slashing)
if err != nil {
httputil.HandleError(w, "Invalid attester slashing: "+err.Error(), http.StatusBadRequest)
httputil2.HandleError(w, "Invalid attester slashing: "+err.Error(), http.StatusBadRequest)
return
}
err = s.SlashingsPool.InsertAttesterSlashing(ctx, headState, slashing)
if err != nil {
httputil.HandleError(w, "Could not insert attester slashing into pool: "+err.Error(), http.StatusInternalServerError)
httputil2.HandleError(w, "Could not insert attester slashing into pool: "+err.Error(), http.StatusInternalServerError)
return
}
// notify events
@@ -896,7 +895,7 @@ func (s *Server) submitAttesterSlashing(
})
if !features.Get().DisableBroadcastSlashings {
if err = s.Broadcaster.Broadcast(ctx, slashing); err != nil {
httputil.HandleError(w, "Could not broadcast slashing object: "+err.Error(), http.StatusInternalServerError)
httputil2.HandleError(w, "Could not broadcast slashing object: "+err.Error(), http.StatusInternalServerError)
return
}
}
@@ -910,13 +909,13 @@ func (s *Server) GetProposerSlashings(w http.ResponseWriter, r *http.Request) {
headState, err := s.ChainInfoFetcher.HeadStateReadOnly(ctx)
if err != nil {
httputil.HandleError(w, "Could not get head state: "+err.Error(), http.StatusInternalServerError)
httputil2.HandleError(w, "Could not get head state: "+err.Error(), http.StatusInternalServerError)
return
}
sourceSlashings := s.SlashingsPool.PendingProposerSlashings(ctx, headState, true /* return unlimited slashings */)
slashings := structs.ProposerSlashingsFromConsensus(sourceSlashings)
httputil.WriteJson(w, &structs.GetProposerSlashingsResponse{Data: slashings})
httputil2.WriteJson(w, &structs.GetProposerSlashingsResponse{Data: slashings})
}
// SubmitProposerSlashing submits a proposer slashing object to node's pool and if
@@ -929,37 +928,37 @@ func (s *Server) SubmitProposerSlashing(w http.ResponseWriter, r *http.Request)
err := json.NewDecoder(r.Body).Decode(&req)
switch {
case errors.Is(err, io.EOF):
httputil.HandleError(w, "No data submitted", http.StatusBadRequest)
httputil2.HandleError(w, "No data submitted", http.StatusBadRequest)
return
case err != nil:
httputil.HandleError(w, "Could not decode request body: "+err.Error(), http.StatusBadRequest)
httputil2.HandleError(w, "Could not decode request body: "+err.Error(), http.StatusBadRequest)
return
}
slashing, err := req.ToConsensus()
if err != nil {
httputil.HandleError(w, "Could not convert request slashing to consensus slashing: "+err.Error(), http.StatusBadRequest)
httputil2.HandleError(w, "Could not convert request slashing to consensus slashing: "+err.Error(), http.StatusBadRequest)
return
}
headState, err := s.ChainInfoFetcher.HeadState(ctx)
if err != nil {
httputil.HandleError(w, "Could not get head state: "+err.Error(), http.StatusInternalServerError)
httputil2.HandleError(w, "Could not get head state: "+err.Error(), http.StatusInternalServerError)
return
}
headState, err = transition.ProcessSlotsIfPossible(ctx, headState, slashing.Header_1.Header.Slot)
if err != nil {
httputil.HandleError(w, "Could not process slots: "+err.Error(), http.StatusInternalServerError)
httputil2.HandleError(w, "Could not process slots: "+err.Error(), http.StatusInternalServerError)
return
}
err = blocks.VerifyProposerSlashing(headState, slashing)
if err != nil {
httputil.HandleError(w, "Invalid proposer slashing: "+err.Error(), http.StatusBadRequest)
httputil2.HandleError(w, "Invalid proposer slashing: "+err.Error(), http.StatusBadRequest)
return
}
err = s.SlashingsPool.InsertProposerSlashing(ctx, headState, slashing)
if err != nil {
httputil.HandleError(w, "Could not insert proposer slashing into pool: "+err.Error(), http.StatusInternalServerError)
httputil2.HandleError(w, "Could not insert proposer slashing into pool: "+err.Error(), http.StatusInternalServerError)
return
}
@@ -973,7 +972,7 @@ func (s *Server) SubmitProposerSlashing(w http.ResponseWriter, r *http.Request)
if !features.Get().DisableBroadcastSlashings {
if err = s.Broadcaster.Broadcast(ctx, slashing); err != nil {
httputil.HandleError(w, "Could not broadcast slashing object: "+err.Error(), http.StatusInternalServerError)
httputil2.HandleError(w, "Could not broadcast slashing object: "+err.Error(), http.StatusInternalServerError)
return
}
}

View File

@@ -13,7 +13,7 @@ import (
"github.com/ethereum/go-ethereum/common/hexutil"
"github.com/prysmaticlabs/go-bitfield"
"github.com/prysmaticlabs/prysm/v5/api"
"github.com/prysmaticlabs/prysm/v5/api/httputil"
"github.com/prysmaticlabs/prysm/v5/api/server"
"github.com/prysmaticlabs/prysm/v5/api/server/structs"
blockchainmock "github.com/prysmaticlabs/prysm/v5/beacon-chain/blockchain/testing"
@@ -36,7 +36,6 @@ import (
"github.com/prysmaticlabs/prysm/v5/crypto/hash"
"github.com/prysmaticlabs/prysm/v5/encoding/bytesutil"
"github.com/prysmaticlabs/prysm/v5/encoding/ssz"
"github.com/prysmaticlabs/prysm/v5/network/httputil"
ethpbv1alpha1 "github.com/prysmaticlabs/prysm/v5/proto/prysm/v1alpha1"
"github.com/prysmaticlabs/prysm/v5/runtime/version"
"github.com/prysmaticlabs/prysm/v5/testing/assert"
@@ -632,7 +631,7 @@ func TestSubmitAttestations(t *testing.T) {
_, err := body.WriteString(singleAtt)
require.NoError(t, err)
request := httptest.NewRequest(http.MethodPost, "http://example.com", &body)
request.Header.Set(api.VersionHeader, version.String(version.Phase0))
request.Header.Set(httputil.VersionHeader, version.String(version.Phase0))
writer := httptest.NewRecorder()
writer.Body = &bytes.Buffer{}
@@ -661,7 +660,7 @@ func TestSubmitAttestations(t *testing.T) {
_, err := body.WriteString(multipleAtts)
require.NoError(t, err)
request := httptest.NewRequest(http.MethodPost, "http://example.com", &body)
request.Header.Set(api.VersionHeader, version.String(version.Phase0))
request.Header.Set(httputil.VersionHeader, version.String(version.Phase0))
writer := httptest.NewRecorder()
writer.Body = &bytes.Buffer{}
@@ -673,7 +672,7 @@ func TestSubmitAttestations(t *testing.T) {
})
t.Run("no body", func(t *testing.T) {
request := httptest.NewRequest(http.MethodPost, "http://example.com", nil)
request.Header.Set(api.VersionHeader, version.String(version.Phase0))
request.Header.Set(httputil.VersionHeader, version.String(version.Phase0))
writer := httptest.NewRecorder()
writer.Body = &bytes.Buffer{}
@@ -689,7 +688,7 @@ func TestSubmitAttestations(t *testing.T) {
_, err := body.WriteString("[]")
require.NoError(t, err)
request := httptest.NewRequest(http.MethodPost, "http://example.com", &body)
request.Header.Set(api.VersionHeader, version.String(version.Phase0))
request.Header.Set(httputil.VersionHeader, version.String(version.Phase0))
writer := httptest.NewRecorder()
writer.Body = &bytes.Buffer{}
@@ -705,7 +704,7 @@ func TestSubmitAttestations(t *testing.T) {
_, err := body.WriteString(invalidAtt)
require.NoError(t, err)
request := httptest.NewRequest(http.MethodPost, "http://example.com", &body)
request.Header.Set(api.VersionHeader, version.String(version.Phase0))
request.Header.Set(httputil.VersionHeader, version.String(version.Phase0))
writer := httptest.NewRecorder()
writer.Body = &bytes.Buffer{}
@@ -728,7 +727,7 @@ func TestSubmitAttestations(t *testing.T) {
_, err := body.WriteString(singleAttElectra)
require.NoError(t, err)
request := httptest.NewRequest(http.MethodPost, "http://example.com", &body)
request.Header.Set(api.VersionHeader, version.String(version.Electra))
request.Header.Set(httputil.VersionHeader, version.String(version.Electra))
writer := httptest.NewRecorder()
writer.Body = &bytes.Buffer{}
@@ -757,7 +756,7 @@ func TestSubmitAttestations(t *testing.T) {
_, err := body.WriteString(multipleAttsElectra)
require.NoError(t, err)
request := httptest.NewRequest(http.MethodPost, "http://example.com", &body)
request.Header.Set(api.VersionHeader, version.String(version.Electra))
request.Header.Set(httputil.VersionHeader, version.String(version.Electra))
writer := httptest.NewRecorder()
writer.Body = &bytes.Buffer{}
@@ -769,7 +768,7 @@ func TestSubmitAttestations(t *testing.T) {
})
t.Run("no body", func(t *testing.T) {
request := httptest.NewRequest(http.MethodPost, "http://example.com", nil)
request.Header.Set(api.VersionHeader, version.String(version.Electra))
request.Header.Set(httputil.VersionHeader, version.String(version.Electra))
writer := httptest.NewRecorder()
writer.Body = &bytes.Buffer{}
@@ -785,7 +784,7 @@ func TestSubmitAttestations(t *testing.T) {
_, err := body.WriteString("[]")
require.NoError(t, err)
request := httptest.NewRequest(http.MethodPost, "http://example.com", &body)
request.Header.Set(api.VersionHeader, version.String(version.Electra))
request.Header.Set(httputil.VersionHeader, version.String(version.Electra))
writer := httptest.NewRecorder()
writer.Body = &bytes.Buffer{}
@@ -801,7 +800,7 @@ func TestSubmitAttestations(t *testing.T) {
_, err := body.WriteString(invalidAttElectra)
require.NoError(t, err)
request := httptest.NewRequest(http.MethodPost, "http://example.com", &body)
request.Header.Set(api.VersionHeader, version.String(version.Electra))
request.Header.Set(httputil.VersionHeader, version.String(version.Electra))
writer := httptest.NewRecorder()
writer.Body = &bytes.Buffer{}
@@ -2100,7 +2099,7 @@ func TestSubmitAttesterSlashings(t *testing.T) {
_, err = body.Write(b)
require.NoError(t, err)
request := httptest.NewRequest(http.MethodPost, "http://example.com/beacon/pool/attester_electras", &body)
request.Header.Set(api.VersionHeader, version.String(version.Electra))
request.Header.Set(httputil.VersionHeader, version.String(version.Electra))
writer := httptest.NewRecorder()
writer.Body = &bytes.Buffer{}
@@ -2164,7 +2163,7 @@ func TestSubmitAttesterSlashings(t *testing.T) {
_, err = body.Write(b)
require.NoError(t, err)
request := httptest.NewRequest(http.MethodPost, "http://example.com/beacon/pool/attester_slashings", &body)
request.Header.Set(api.VersionHeader, version.String(version.Electra))
request.Header.Set(httputil.VersionHeader, version.String(version.Electra))
writer := httptest.NewRecorder()
writer.Body = &bytes.Buffer{}
@@ -2194,7 +2193,7 @@ func TestSubmitAttesterSlashings(t *testing.T) {
_, err = body.WriteString(invalidAttesterSlashing)
require.NoError(t, err)
request := httptest.NewRequest(http.MethodPost, "http://example.com/beacon/pool/attester_slashings", &body)
request.Header.Set(api.VersionHeader, version.String(version.Electra))
request.Header.Set(httputil.VersionHeader, version.String(version.Electra))
writer := httptest.NewRecorder()
writer.Body = &bytes.Buffer{}

View File

@@ -8,6 +8,7 @@ import (
"strconv"
"github.com/ethereum/go-ethereum/common/hexutil"
httputil2 "github.com/prysmaticlabs/prysm/v5/api/httputil"
"github.com/prysmaticlabs/prysm/v5/api/server/structs"
"github.com/prysmaticlabs/prysm/v5/beacon-chain/core/altair"
"github.com/prysmaticlabs/prysm/v5/beacon-chain/rpc/eth/helpers"
@@ -18,7 +19,6 @@ import (
"github.com/prysmaticlabs/prysm/v5/consensus-types/primitives"
"github.com/prysmaticlabs/prysm/v5/encoding/bytesutil"
"github.com/prysmaticlabs/prysm/v5/monitoring/tracing/trace"
"github.com/prysmaticlabs/prysm/v5/network/httputil"
ethpbalpha "github.com/prysmaticlabs/prysm/v5/proto/prysm/v1alpha1"
"github.com/prysmaticlabs/prysm/v5/time/slots"
)
@@ -35,7 +35,7 @@ func (s *Server) GetStateRoot(w http.ResponseWriter, r *http.Request) {
stateId := r.PathValue("state_id")
if stateId == "" {
httputil.HandleError(w, "state_id is required in URL params", http.StatusBadRequest)
httputil2.HandleError(w, "state_id is required in URL params", http.StatusBadRequest)
return
}
@@ -43,10 +43,10 @@ func (s *Server) GetStateRoot(w http.ResponseWriter, r *http.Request) {
if err != nil {
var rootNotFoundErr *lookup.StateRootNotFoundError
if errors.As(err, &rootNotFoundErr) {
httputil.HandleError(w, "State root not found: "+rootNotFoundErr.Error(), http.StatusNotFound)
httputil2.HandleError(w, "State root not found: "+rootNotFoundErr.Error(), http.StatusNotFound)
return
}
httputil.HandleError(w, "Could not get state root: "+err.Error(), http.StatusInternalServerError)
httputil2.HandleError(w, "Could not get state root: "+err.Error(), http.StatusInternalServerError)
return
}
st, err := s.Stater.State(ctx, []byte(stateId))
@@ -56,12 +56,12 @@ func (s *Server) GetStateRoot(w http.ResponseWriter, r *http.Request) {
}
isOptimistic, err := helpers.IsOptimistic(ctx, []byte(stateId), s.OptimisticModeFetcher, s.Stater, s.ChainInfoFetcher, s.BeaconDB)
if err != nil {
httputil.HandleError(w, "Could not check optimistic status: "+err.Error(), http.StatusInternalServerError)
httputil2.HandleError(w, "Could not check optimistic status: "+err.Error(), http.StatusInternalServerError)
return
}
blockRoot, err := st.LatestBlockHeader().HashTreeRoot()
if err != nil {
httputil.HandleError(w, "Could not calculate root of latest block header: "+err.Error(), http.StatusInternalServerError)
httputil2.HandleError(w, "Could not calculate root of latest block header: "+err.Error(), http.StatusInternalServerError)
return
}
isFinalized := s.FinalizationFetcher.IsFinalized(ctx, blockRoot)
@@ -73,7 +73,7 @@ func (s *Server) GetStateRoot(w http.ResponseWriter, r *http.Request) {
ExecutionOptimistic: isOptimistic,
Finalized: isFinalized,
}
httputil.WriteJson(w, resp)
httputil2.WriteJson(w, resp)
}
// GetRandao fetches the RANDAO mix for the requested epoch from the state identified by state_id.
@@ -86,7 +86,7 @@ func (s *Server) GetRandao(w http.ResponseWriter, r *http.Request) {
stateId := r.PathValue("state_id")
if stateId == "" {
httputil.HandleError(w, "state_id is required in URL params", http.StatusBadRequest)
httputil2.HandleError(w, "state_id is required in URL params", http.StatusBadRequest)
return
}
rawEpoch, e, ok := shared.UintFromQuery(w, r, "epoch", false)
@@ -113,25 +113,25 @@ func (s *Server) GetRandao(w http.ResponseWriter, r *http.Request) {
randaoEpochLowerBound = uint64(stEpoch) - uint64(st.RandaoMixesLength())
}
if epoch > stEpoch || uint64(epoch) < randaoEpochLowerBound+1 {
httputil.HandleError(w, "Epoch is out of range for the randao mixes of the state", http.StatusBadRequest)
httputil2.HandleError(w, "Epoch is out of range for the randao mixes of the state", http.StatusBadRequest)
return
}
idx := epoch % params.BeaconConfig().EpochsPerHistoricalVector
randao, err := st.RandaoMixAtIndex(uint64(idx))
if err != nil {
httputil.HandleError(w, fmt.Sprintf("Could not get randao mix at index %d: %v", idx, err), http.StatusInternalServerError)
httputil2.HandleError(w, fmt.Sprintf("Could not get randao mix at index %d: %v", idx, err), http.StatusInternalServerError)
return
}
isOptimistic, err := helpers.IsOptimistic(ctx, []byte(stateId), s.OptimisticModeFetcher, s.Stater, s.ChainInfoFetcher, s.BeaconDB)
if err != nil {
httputil.HandleError(w, "Could not check optimistic status: "+err.Error(), http.StatusInternalServerError)
httputil2.HandleError(w, "Could not check optimistic status: "+err.Error(), http.StatusInternalServerError)
return
}
blockRoot, err := st.LatestBlockHeader().HashTreeRoot()
if err != nil {
httputil.HandleError(w, "Could not calculate root of latest block header: "+err.Error(), http.StatusInternalServerError)
httputil2.HandleError(w, "Could not calculate root of latest block header: "+err.Error(), http.StatusInternalServerError)
return
}
isFinalized := s.FinalizationFetcher.IsFinalized(ctx, blockRoot)
@@ -141,7 +141,7 @@ func (s *Server) GetRandao(w http.ResponseWriter, r *http.Request) {
ExecutionOptimistic: isOptimistic,
Finalized: isFinalized,
}
httputil.WriteJson(w, resp)
httputil2.WriteJson(w, resp)
}
// GetSyncCommittees retrieves the sync committees for the given epoch.
@@ -152,7 +152,7 @@ func (s *Server) GetSyncCommittees(w http.ResponseWriter, r *http.Request) {
stateId := r.PathValue("state_id")
if stateId == "" {
httputil.HandleError(w, "state_id is required in URL params", http.StatusBadRequest)
httputil2.HandleError(w, "state_id is required in URL params", http.StatusBadRequest)
return
}
rawEpoch, e, ok := shared.UintFromQuery(w, r, "epoch", false)
@@ -165,7 +165,7 @@ func (s *Server) GetSyncCommittees(w http.ResponseWriter, r *http.Request) {
currentEpoch := slots.ToEpoch(currentSlot)
currentPeriodStartEpoch, err := slots.SyncCommitteePeriodStartEpoch(currentEpoch)
if err != nil {
httputil.HandleError(w, fmt.Sprintf("Could not calculate start period for slot %d: %v", currentSlot, err), http.StatusInternalServerError)
httputil2.HandleError(w, fmt.Sprintf("Could not calculate start period for slot %d: %v", currentSlot, err), http.StatusInternalServerError)
return
}
@@ -173,11 +173,11 @@ func (s *Server) GetSyncCommittees(w http.ResponseWriter, r *http.Request) {
if rawEpoch != "" {
reqPeriodStartEpoch, err := slots.SyncCommitteePeriodStartEpoch(epoch)
if err != nil {
httputil.HandleError(w, fmt.Sprintf("Could not calculate start period for epoch %d: %v", e, err), http.StatusInternalServerError)
httputil2.HandleError(w, fmt.Sprintf("Could not calculate start period for epoch %d: %v", e, err), http.StatusInternalServerError)
return
}
if reqPeriodStartEpoch > currentPeriodStartEpoch+params.BeaconConfig().EpochsPerSyncCommitteePeriod {
httputil.HandleError(
httputil2.HandleError(
w,
fmt.Sprintf("Could not fetch sync committee too far in the future (requested epoch %d, current epoch %d)", e, currentEpoch),
http.StatusBadRequest,
@@ -208,32 +208,32 @@ func (s *Server) GetSyncCommittees(w http.ResponseWriter, r *http.Request) {
// Get the next sync committee and sync committee indices from the state.
committeeIndices, committee, err = nextCommitteeIndicesFromState(st)
if err != nil {
httputil.HandleError(w, "Could not get next sync committee indices: "+err.Error(), http.StatusInternalServerError)
httputil2.HandleError(w, "Could not get next sync committee indices: "+err.Error(), http.StatusInternalServerError)
return
}
} else {
// Get the current sync committee and sync committee indices from the state.
committeeIndices, committee, err = currentCommitteeIndicesFromState(st)
if err != nil {
httputil.HandleError(w, "Could not get current sync committee indices: "+err.Error(), http.StatusInternalServerError)
httputil2.HandleError(w, "Could not get current sync committee indices: "+err.Error(), http.StatusInternalServerError)
return
}
}
subcommittees, err := extractSyncSubcommittees(st, committee)
if err != nil {
httputil.HandleError(w, "Could not extract sync subcommittees: "+err.Error(), http.StatusInternalServerError)
httputil2.HandleError(w, "Could not extract sync subcommittees: "+err.Error(), http.StatusInternalServerError)
return
}
isOptimistic, err := helpers.IsOptimistic(ctx, []byte(stateId), s.OptimisticModeFetcher, s.Stater, s.ChainInfoFetcher, s.BeaconDB)
if err != nil {
httputil.HandleError(w, "Could not check optimistic status: "+err.Error(), http.StatusInternalServerError)
httputil2.HandleError(w, "Could not check optimistic status: "+err.Error(), http.StatusInternalServerError)
return
}
blockRoot, err := st.LatestBlockHeader().HashTreeRoot()
if err != nil {
httputil.HandleError(w, "Could not calculate root of latest block header: "+err.Error(), http.StatusInternalServerError)
httputil2.HandleError(w, "Could not calculate root of latest block header: "+err.Error(), http.StatusInternalServerError)
return
}
isFinalized := s.FinalizationFetcher.IsFinalized(ctx, blockRoot)
@@ -246,7 +246,7 @@ func (s *Server) GetSyncCommittees(w http.ResponseWriter, r *http.Request) {
ExecutionOptimistic: isOptimistic,
Finalized: isFinalized,
}
httputil.WriteJson(w, resp)
httputil2.WriteJson(w, resp)
}
func committeeIndicesFromState(st state.BeaconState, committee *ethpbalpha.SyncCommittee) ([]string, *ethpbalpha.SyncCommittee, error) {
@@ -316,7 +316,7 @@ func (s *Server) stateForSyncCommittee(ctx context.Context, w http.ResponseWrite
if req.epoch != nil {
slot, err := slots.EpochStart(*req.epoch)
if err != nil {
httputil.HandleError(w, fmt.Sprintf("Could not calculate start slot for epoch %d: %v", *req.epoch, err), http.StatusInternalServerError)
httputil2.HandleError(w, fmt.Sprintf("Could not calculate start slot for epoch %d: %v", *req.epoch, err), http.StatusInternalServerError)
return nil, false
}
st, err := s.Stater.State(ctx, []byte(strconv.FormatUint(uint64(slot), 10)))

View File

@@ -12,6 +12,7 @@ import (
"time"
"github.com/ethereum/go-ethereum/common/hexutil"
"github.com/prysmaticlabs/prysm/v5/api/httputil"
"github.com/prysmaticlabs/prysm/v5/api/server/structs"
chainMock "github.com/prysmaticlabs/prysm/v5/beacon-chain/blockchain/testing"
dbTest "github.com/prysmaticlabs/prysm/v5/beacon-chain/db/testing"
@@ -20,7 +21,6 @@ import (
"github.com/prysmaticlabs/prysm/v5/config/params"
"github.com/prysmaticlabs/prysm/v5/consensus-types/primitives"
"github.com/prysmaticlabs/prysm/v5/encoding/bytesutil"
"github.com/prysmaticlabs/prysm/v5/network/httputil"
ethpbalpha "github.com/prysmaticlabs/prysm/v5/proto/prysm/v1alpha1"
"github.com/prysmaticlabs/prysm/v5/testing/assert"
"github.com/prysmaticlabs/prysm/v5/testing/require"

View File

@@ -16,7 +16,7 @@ import (
"github.com/ethereum/go-ethereum/common/hexutil"
"github.com/pkg/errors"
"github.com/prysmaticlabs/go-bitfield"
"github.com/prysmaticlabs/prysm/v5/api"
"github.com/prysmaticlabs/prysm/v5/api/httputil"
"github.com/prysmaticlabs/prysm/v5/api/server/structs"
chainMock "github.com/prysmaticlabs/prysm/v5/beacon-chain/blockchain/testing"
"github.com/prysmaticlabs/prysm/v5/beacon-chain/cache/depositsnapshot"
@@ -36,7 +36,6 @@ import (
"github.com/prysmaticlabs/prysm/v5/consensus-types/primitives"
"github.com/prysmaticlabs/prysm/v5/crypto/bls"
"github.com/prysmaticlabs/prysm/v5/encoding/bytesutil"
"github.com/prysmaticlabs/prysm/v5/network/httputil"
eth "github.com/prysmaticlabs/prysm/v5/proto/prysm/v1alpha1"
"github.com/prysmaticlabs/prysm/v5/runtime/version"
"github.com/prysmaticlabs/prysm/v5/testing/assert"
@@ -424,13 +423,13 @@ func TestGetBlockSSZV2(t *testing.T) {
request := httptest.NewRequest(http.MethodGet, "http://foo.example/eth/v2/beacon/blocks/{block_id}", nil)
request.SetPathValue("block_id", "head")
request.Header.Set("Accept", api.OctetStreamMediaType)
request.Header.Set("Accept", httputil.OctetStreamMediaType)
writer := httptest.NewRecorder()
writer.Body = &bytes.Buffer{}
s.GetBlockV2(writer, request)
require.Equal(t, http.StatusOK, writer.Code)
assert.Equal(t, version.String(version.Phase0), writer.Header().Get(api.VersionHeader))
assert.Equal(t, version.String(version.Phase0), writer.Header().Get(httputil.VersionHeader))
sszExpected, err := b.MarshalSSZ()
require.NoError(t, err)
assert.DeepEqual(t, sszExpected, writer.Body.Bytes())
@@ -447,13 +446,13 @@ func TestGetBlockSSZV2(t *testing.T) {
request := httptest.NewRequest(http.MethodGet, "http://foo.example/eth/v2/beacon/blocks/{block_id}", nil)
request.SetPathValue("block_id", "head")
request.Header.Set("Accept", api.OctetStreamMediaType)
request.Header.Set("Accept", httputil.OctetStreamMediaType)
writer := httptest.NewRecorder()
writer.Body = &bytes.Buffer{}
s.GetBlockV2(writer, request)
require.Equal(t, http.StatusOK, writer.Code)
assert.Equal(t, version.String(version.Altair), writer.Header().Get(api.VersionHeader))
assert.Equal(t, version.String(version.Altair), writer.Header().Get(httputil.VersionHeader))
sszExpected, err := b.MarshalSSZ()
require.NoError(t, err)
assert.DeepEqual(t, sszExpected, writer.Body.Bytes())
@@ -470,13 +469,13 @@ func TestGetBlockSSZV2(t *testing.T) {
request := httptest.NewRequest(http.MethodGet, "http://foo.example/eth/v2/beacon/blocks/{block_id}", nil)
request.SetPathValue("block_id", "head")
request.Header.Set("Accept", api.OctetStreamMediaType)
request.Header.Set("Accept", httputil.OctetStreamMediaType)
writer := httptest.NewRecorder()
writer.Body = &bytes.Buffer{}
s.GetBlockV2(writer, request)
require.Equal(t, http.StatusOK, writer.Code)
assert.Equal(t, version.String(version.Bellatrix), writer.Header().Get(api.VersionHeader))
assert.Equal(t, version.String(version.Bellatrix), writer.Header().Get(httputil.VersionHeader))
sszExpected, err := b.MarshalSSZ()
require.NoError(t, err)
assert.DeepEqual(t, sszExpected, writer.Body.Bytes())
@@ -493,13 +492,13 @@ func TestGetBlockSSZV2(t *testing.T) {
request := httptest.NewRequest(http.MethodGet, "http://foo.example/eth/v2/beacon/blocks/{block_id}", nil)
request.SetPathValue("block_id", "head")
request.Header.Set("Accept", api.OctetStreamMediaType)
request.Header.Set("Accept", httputil.OctetStreamMediaType)
writer := httptest.NewRecorder()
writer.Body = &bytes.Buffer{}
s.GetBlockV2(writer, request)
require.Equal(t, http.StatusOK, writer.Code)
assert.Equal(t, version.String(version.Capella), writer.Header().Get(api.VersionHeader))
assert.Equal(t, version.String(version.Capella), writer.Header().Get(httputil.VersionHeader))
sszExpected, err := b.MarshalSSZ()
require.NoError(t, err)
assert.DeepEqual(t, sszExpected, writer.Body.Bytes())
@@ -516,13 +515,13 @@ func TestGetBlockSSZV2(t *testing.T) {
request := httptest.NewRequest(http.MethodGet, "http://foo.example/eth/v2/beacon/blocks/{block_id}", nil)
request.SetPathValue("block_id", "head")
request.Header.Set("Accept", api.OctetStreamMediaType)
request.Header.Set("Accept", httputil.OctetStreamMediaType)
writer := httptest.NewRecorder()
writer.Body = &bytes.Buffer{}
s.GetBlockV2(writer, request)
require.Equal(t, http.StatusOK, writer.Code)
assert.Equal(t, version.String(version.Deneb), writer.Header().Get(api.VersionHeader))
assert.Equal(t, version.String(version.Deneb), writer.Header().Get(httputil.VersionHeader))
sszExpected, err := b.MarshalSSZ()
require.NoError(t, err)
assert.DeepEqual(t, sszExpected, writer.Body.Bytes())
@@ -539,13 +538,13 @@ func TestGetBlockSSZV2(t *testing.T) {
request := httptest.NewRequest(http.MethodGet, "http://foo.example/eth/v2/beacon/blocks/{block_id}", nil)
request.SetPathValue("block_id", "head")
request.Header.Set("Accept", api.OctetStreamMediaType)
request.Header.Set("Accept", httputil.OctetStreamMediaType)
writer := httptest.NewRecorder()
writer.Body = &bytes.Buffer{}
s.GetBlockV2(writer, request)
require.Equal(t, http.StatusOK, writer.Code)
assert.Equal(t, version.String(version.Electra), writer.Header().Get(api.VersionHeader))
assert.Equal(t, version.String(version.Electra), writer.Header().Get(httputil.VersionHeader))
sszExpected, err := b.MarshalSSZ()
require.NoError(t, err)
assert.DeepEqual(t, sszExpected, writer.Body.Bytes())
@@ -562,13 +561,13 @@ func TestGetBlockSSZV2(t *testing.T) {
request := httptest.NewRequest(http.MethodGet, "http://foo.example/eth/v2/beacon/blocks/{block_id}", nil)
request.SetPathValue("block_id", "head")
request.Header.Set("Accept", api.OctetStreamMediaType)
request.Header.Set("Accept", httputil.OctetStreamMediaType)
writer := httptest.NewRecorder()
writer.Body = &bytes.Buffer{}
s.GetBlockV2(writer, request)
require.Equal(t, http.StatusOK, writer.Code)
assert.Equal(t, version.String(version.Fulu), writer.Header().Get(api.VersionHeader))
assert.Equal(t, version.String(version.Fulu), writer.Header().Get(httputil.VersionHeader))
sszExpected, err := b.MarshalSSZ()
require.NoError(t, err)
assert.DeepEqual(t, sszExpected, writer.Body.Bytes())
@@ -1212,13 +1211,13 @@ func TestGetBlindedBlockSSZ(t *testing.T) {
request := httptest.NewRequest(http.MethodGet, "http://foo.example/eth/v1/beacon/blinded_blocks/{block_id}", nil)
request.SetPathValue("block_id", "head")
request.Header.Set("Accept", api.OctetStreamMediaType)
request.Header.Set("Accept", httputil.OctetStreamMediaType)
writer := httptest.NewRecorder()
writer.Body = &bytes.Buffer{}
s.GetBlindedBlock(writer, request)
require.Equal(t, http.StatusOK, writer.Code)
assert.Equal(t, version.String(version.Phase0), writer.Header().Get(api.VersionHeader))
assert.Equal(t, version.String(version.Phase0), writer.Header().Get(httputil.VersionHeader))
sszExpected, err := b.MarshalSSZ()
require.NoError(t, err)
assert.DeepEqual(t, sszExpected, writer.Body.Bytes())
@@ -1234,13 +1233,13 @@ func TestGetBlindedBlockSSZ(t *testing.T) {
request := httptest.NewRequest(http.MethodGet, "http://foo.example/eth/v1/beacon/blinded_blocks/{block_id}", nil)
request.SetPathValue("block_id", "head")
request.Header.Set("Accept", api.OctetStreamMediaType)
request.Header.Set("Accept", httputil.OctetStreamMediaType)
writer := httptest.NewRecorder()
writer.Body = &bytes.Buffer{}
s.GetBlindedBlock(writer, request)
require.Equal(t, http.StatusOK, writer.Code)
assert.Equal(t, version.String(version.Altair), writer.Header().Get(api.VersionHeader))
assert.Equal(t, version.String(version.Altair), writer.Header().Get(httputil.VersionHeader))
sszExpected, err := b.MarshalSSZ()
require.NoError(t, err)
assert.DeepEqual(t, sszExpected, writer.Body.Bytes())
@@ -1256,13 +1255,13 @@ func TestGetBlindedBlockSSZ(t *testing.T) {
request := httptest.NewRequest(http.MethodGet, "http://foo.example/eth/v1/beacon/blinded_blocks/{block_id}", nil)
request.SetPathValue("block_id", "head")
request.Header.Set("Accept", api.OctetStreamMediaType)
request.Header.Set("Accept", httputil.OctetStreamMediaType)
writer := httptest.NewRecorder()
writer.Body = &bytes.Buffer{}
s.GetBlindedBlock(writer, request)
require.Equal(t, http.StatusOK, writer.Code)
assert.Equal(t, version.String(version.Bellatrix), writer.Header().Get(api.VersionHeader))
assert.Equal(t, version.String(version.Bellatrix), writer.Header().Get(httputil.VersionHeader))
sszExpected, err := b.MarshalSSZ()
require.NoError(t, err)
assert.DeepEqual(t, sszExpected, writer.Body.Bytes())
@@ -1278,13 +1277,13 @@ func TestGetBlindedBlockSSZ(t *testing.T) {
request := httptest.NewRequest(http.MethodGet, "http://foo.example/eth/v1/beacon/blinded_blocks/{block_id}", nil)
request.SetPathValue("block_id", "head")
request.Header.Set("Accept", api.OctetStreamMediaType)
request.Header.Set("Accept", httputil.OctetStreamMediaType)
writer := httptest.NewRecorder()
writer.Body = &bytes.Buffer{}
s.GetBlindedBlock(writer, request)
require.Equal(t, http.StatusOK, writer.Code)
assert.Equal(t, version.String(version.Capella), writer.Header().Get(api.VersionHeader))
assert.Equal(t, version.String(version.Capella), writer.Header().Get(httputil.VersionHeader))
sszExpected, err := b.MarshalSSZ()
require.NoError(t, err)
assert.DeepEqual(t, sszExpected, writer.Body.Bytes())
@@ -1300,13 +1299,13 @@ func TestGetBlindedBlockSSZ(t *testing.T) {
request := httptest.NewRequest(http.MethodGet, "http://foo.example/eth/v1/beacon/blinded_blocks/{block_id}", nil)
request.SetPathValue("block_id", "head")
request.Header.Set("Accept", api.OctetStreamMediaType)
request.Header.Set("Accept", httputil.OctetStreamMediaType)
writer := httptest.NewRecorder()
writer.Body = &bytes.Buffer{}
s.GetBlindedBlock(writer, request)
require.Equal(t, http.StatusOK, writer.Code)
assert.Equal(t, version.String(version.Deneb), writer.Header().Get(api.VersionHeader))
assert.Equal(t, version.String(version.Deneb), writer.Header().Get(httputil.VersionHeader))
sszExpected, err := b.MarshalSSZ()
require.NoError(t, err)
assert.DeepEqual(t, sszExpected, writer.Body.Bytes())
@@ -1331,7 +1330,7 @@ func TestPublishBlock(t *testing.T) {
}
request := httptest.NewRequest(http.MethodPost, "http://foo.example", bytes.NewReader([]byte(rpctesting.Phase0Block)))
request.Header.Set(api.VersionHeader, version.String(version.Phase0))
request.Header.Set(httputil.VersionHeader, version.String(version.Phase0))
writer := httptest.NewRecorder()
writer.Body = &bytes.Buffer{}
server.PublishBlock(writer, request)
@@ -1353,7 +1352,7 @@ func TestPublishBlock(t *testing.T) {
}
request := httptest.NewRequest(http.MethodPost, "http://foo.example", bytes.NewReader([]byte(rpctesting.AltairBlock)))
request.Header.Set(api.VersionHeader, version.String(version.Altair))
request.Header.Set(httputil.VersionHeader, version.String(version.Altair))
writer := httptest.NewRecorder()
writer.Body = &bytes.Buffer{}
server.PublishBlock(writer, request)
@@ -1377,7 +1376,7 @@ func TestPublishBlock(t *testing.T) {
}
request := httptest.NewRequest(http.MethodPost, "http://foo.example", bytes.NewReader([]byte(rpctesting.BellatrixBlock)))
request.Header.Set(api.VersionHeader, version.String(version.Bellatrix))
request.Header.Set(httputil.VersionHeader, version.String(version.Bellatrix))
writer := httptest.NewRecorder()
writer.Body = &bytes.Buffer{}
server.PublishBlock(writer, request)
@@ -1401,7 +1400,7 @@ func TestPublishBlock(t *testing.T) {
}
request := httptest.NewRequest(http.MethodPost, "http://foo.example", bytes.NewReader([]byte(rpctesting.CapellaBlock)))
request.Header.Set(api.VersionHeader, version.String(version.Capella))
request.Header.Set(httputil.VersionHeader, version.String(version.Capella))
writer := httptest.NewRecorder()
writer.Body = &bytes.Buffer{}
server.PublishBlock(writer, request)
@@ -1456,7 +1455,7 @@ func TestPublishBlock(t *testing.T) {
SyncChecker: &mockSync.Sync{IsSyncing: false},
}
request := httptest.NewRequest(http.MethodPost, "http://foo.example", bytes.NewReader([]byte(rpctesting.DenebBlockContents)))
request.Header.Set(api.VersionHeader, version.String(version.Deneb))
request.Header.Set(httputil.VersionHeader, version.String(version.Deneb))
writer := httptest.NewRecorder()
writer.Body = &bytes.Buffer{}
server.PublishBlock(writer, request)
@@ -1479,7 +1478,7 @@ func TestPublishBlock(t *testing.T) {
SyncChecker: &mockSync.Sync{IsSyncing: false},
}
request := httptest.NewRequest(http.MethodPost, "http://foo.example", bytes.NewReader([]byte(rpctesting.ElectraBlockContents)))
request.Header.Set(api.VersionHeader, version.String(version.Electra))
request.Header.Set(httputil.VersionHeader, version.String(version.Electra))
writer := httptest.NewRecorder()
writer.Body = &bytes.Buffer{}
server.PublishBlock(writer, request)
@@ -1547,7 +1546,7 @@ func TestPublishBlock(t *testing.T) {
SyncChecker: &mockSync.Sync{IsSyncing: false},
}
request := httptest.NewRequest(http.MethodPost, "http://foo.example", bytes.NewReader([]byte(rpctesting.FuluBlockContents)))
request.Header.Set(api.VersionHeader, version.String(version.Fulu))
request.Header.Set(httputil.VersionHeader, version.String(version.Fulu))
writer := httptest.NewRecorder()
writer.Body = &bytes.Buffer{}
server.PublishBlock(writer, request)
@@ -1559,7 +1558,7 @@ func TestPublishBlock(t *testing.T) {
}
request := httptest.NewRequest(http.MethodPost, "http://foo.example", bytes.NewReader([]byte(rpctesting.BlindedBellatrixBlock)))
request.Header.Set(api.VersionHeader, version.String(version.Bellatrix))
request.Header.Set(httputil.VersionHeader, version.String(version.Bellatrix))
writer := httptest.NewRecorder()
writer.Body = &bytes.Buffer{}
server.PublishBlock(writer, request)
@@ -1572,7 +1571,7 @@ func TestPublishBlock(t *testing.T) {
}
request := httptest.NewRequest(http.MethodPost, "http://foo.example", bytes.NewReader([]byte(rpctesting.BellatrixBlock)))
request.Header.Set(api.VersionHeader, version.String(version.Capella))
request.Header.Set(httputil.VersionHeader, version.String(version.Capella))
writer := httptest.NewRecorder()
writer.Body = &bytes.Buffer{}
server.PublishBlock(writer, request)
@@ -1793,8 +1792,8 @@ func TestPublishBlockSSZ(t *testing.T) {
ssz, err := genericBlock.GetPhase0().MarshalSSZ()
require.NoError(t, err)
request := httptest.NewRequest(http.MethodPost, "http://foo.example", bytes.NewReader(ssz))
request.Header.Set("Content-Type", api.OctetStreamMediaType)
request.Header.Set(api.VersionHeader, version.String(version.Phase0))
request.Header.Set("Content-Type", httputil.OctetStreamMediaType)
request.Header.Set(httputil.VersionHeader, version.String(version.Phase0))
writer := httptest.NewRecorder()
writer.Body = &bytes.Buffer{}
server.PublishBlock(writer, request)
@@ -1823,8 +1822,8 @@ func TestPublishBlockSSZ(t *testing.T) {
ssz, err := genericBlock.GetAltair().MarshalSSZ()
require.NoError(t, err)
request := httptest.NewRequest(http.MethodPost, "http://foo.example", bytes.NewReader(ssz))
request.Header.Set("Content-Type", api.OctetStreamMediaType)
request.Header.Set(api.VersionHeader, version.String(version.Altair))
request.Header.Set("Content-Type", httputil.OctetStreamMediaType)
request.Header.Set(httputil.VersionHeader, version.String(version.Altair))
writer := httptest.NewRecorder()
writer.Body = &bytes.Buffer{}
server.PublishBlock(writer, request)
@@ -1848,8 +1847,8 @@ func TestPublishBlockSSZ(t *testing.T) {
ssz, err := genericBlock.GetBellatrix().MarshalSSZ()
require.NoError(t, err)
request := httptest.NewRequest(http.MethodPost, "http://foo.example", bytes.NewReader(ssz))
request.Header.Set("Content-Type", api.OctetStreamMediaType)
request.Header.Set(api.VersionHeader, version.String(version.Bellatrix))
request.Header.Set("Content-Type", httputil.OctetStreamMediaType)
request.Header.Set(httputil.VersionHeader, version.String(version.Bellatrix))
writer := httptest.NewRecorder()
writer.Body = &bytes.Buffer{}
server.PublishBlock(writer, request)
@@ -1874,8 +1873,8 @@ func TestPublishBlockSSZ(t *testing.T) {
ssz, err := genericBlock.GetCapella().MarshalSSZ()
require.NoError(t, err)
request := httptest.NewRequest(http.MethodPost, "http://foo.example", bytes.NewReader(ssz))
request.Header.Set("Content-Type", api.OctetStreamMediaType)
request.Header.Set(api.VersionHeader, version.String(version.Capella))
request.Header.Set("Content-Type", httputil.OctetStreamMediaType)
request.Header.Set(httputil.VersionHeader, version.String(version.Capella))
writer := httptest.NewRecorder()
writer.Body = &bytes.Buffer{}
server.PublishBlock(writer, request)
@@ -1900,8 +1899,8 @@ func TestPublishBlockSSZ(t *testing.T) {
ssz, err := genericBlock.GetDeneb().MarshalSSZ()
require.NoError(t, err)
request := httptest.NewRequest(http.MethodPost, "http://foo.example", bytes.NewReader(ssz))
request.Header.Set("Content-Type", api.OctetStreamMediaType)
request.Header.Set(api.VersionHeader, version.String(version.Deneb))
request.Header.Set("Content-Type", httputil.OctetStreamMediaType)
request.Header.Set(httputil.VersionHeader, version.String(version.Deneb))
writer := httptest.NewRecorder()
writer.Body = &bytes.Buffer{}
server.PublishBlock(writer, request)
@@ -1926,8 +1925,8 @@ func TestPublishBlockSSZ(t *testing.T) {
ssz, err := genericBlock.GetElectra().MarshalSSZ()
require.NoError(t, err)
request := httptest.NewRequest(http.MethodPost, "http://foo.example", bytes.NewReader(ssz))
request.Header.Set("Content-Type", api.OctetStreamMediaType)
request.Header.Set(api.VersionHeader, version.String(version.Electra))
request.Header.Set("Content-Type", httputil.OctetStreamMediaType)
request.Header.Set(httputil.VersionHeader, version.String(version.Electra))
writer := httptest.NewRecorder()
writer.Body = &bytes.Buffer{}
server.PublishBlock(writer, request)
@@ -1952,8 +1951,8 @@ func TestPublishBlockSSZ(t *testing.T) {
ssz, err := genericBlock.GetFulu().MarshalSSZ()
require.NoError(t, err)
request := httptest.NewRequest(http.MethodPost, "http://foo.example", bytes.NewReader(ssz))
request.Header.Set("Content-Type", api.OctetStreamMediaType)
request.Header.Set(api.VersionHeader, version.String(version.Fulu))
request.Header.Set("Content-Type", httputil.OctetStreamMediaType)
request.Header.Set(httputil.VersionHeader, version.String(version.Fulu))
writer := httptest.NewRecorder()
writer.Body = &bytes.Buffer{}
server.PublishBlock(writer, request)
@@ -1972,8 +1971,8 @@ func TestPublishBlockSSZ(t *testing.T) {
ssz, err := genericBlock.GetBlindedBellatrix().MarshalSSZ()
require.NoError(t, err)
request := httptest.NewRequest(http.MethodPost, "http://foo.example", bytes.NewReader(ssz))
request.Header.Set("Content-Type", api.OctetStreamMediaType)
request.Header.Set(api.VersionHeader, version.String(version.Bellatrix))
request.Header.Set("Content-Type", httputil.OctetStreamMediaType)
request.Header.Set(httputil.VersionHeader, version.String(version.Bellatrix))
writer := httptest.NewRecorder()
writer.Body = &bytes.Buffer{}
server.PublishBlock(writer, request)
@@ -1993,8 +1992,8 @@ func TestPublishBlockSSZ(t *testing.T) {
ssz, err := genericBlock.GetBellatrix().MarshalSSZ()
require.NoError(t, err)
request := httptest.NewRequest(http.MethodPost, "http://foo.example", bytes.NewReader(ssz))
request.Header.Set("Content-Type", api.OctetStreamMediaType)
request.Header.Set(api.VersionHeader, version.String(version.Capella))
request.Header.Set("Content-Type", httputil.OctetStreamMediaType)
request.Header.Set(httputil.VersionHeader, version.String(version.Capella))
writer := httptest.NewRecorder()
writer.Body = &bytes.Buffer{}
server.PublishBlock(writer, request)
@@ -2011,7 +2010,7 @@ func TestPublishBlockSSZ(t *testing.T) {
}
request := httptest.NewRequest(http.MethodPost, "http://foo.example", bytes.NewReader([]byte("foo")))
request.Header.Set("Content-Type", api.OctetStreamMediaType)
request.Header.Set("Content-Type", httputil.OctetStreamMediaType)
writer := httptest.NewRecorder()
writer.Body = &bytes.Buffer{}
server.PublishBlock(writer, request)
@@ -2038,7 +2037,7 @@ func TestPublishBlindedBlock(t *testing.T) {
}
request := httptest.NewRequest(http.MethodPost, "http://foo.example", bytes.NewReader([]byte(rpctesting.Phase0Block)))
request.Header.Set(api.VersionHeader, version.String(version.Phase0))
request.Header.Set(httputil.VersionHeader, version.String(version.Phase0))
writer := httptest.NewRecorder()
writer.Body = &bytes.Buffer{}
server.PublishBlindedBlock(writer, request)
@@ -2060,7 +2059,7 @@ func TestPublishBlindedBlock(t *testing.T) {
}
request := httptest.NewRequest(http.MethodPost, "http://foo.example", bytes.NewReader([]byte(rpctesting.AltairBlock)))
request.Header.Set(api.VersionHeader, version.String(version.Altair))
request.Header.Set(httputil.VersionHeader, version.String(version.Altair))
writer := httptest.NewRecorder()
writer.Body = &bytes.Buffer{}
server.PublishBlindedBlock(writer, request)
@@ -2084,7 +2083,7 @@ func TestPublishBlindedBlock(t *testing.T) {
}
request := httptest.NewRequest(http.MethodPost, "http://foo.example", bytes.NewReader([]byte(rpctesting.BlindedBellatrixBlock)))
request.Header.Set(api.VersionHeader, version.String(version.Bellatrix))
request.Header.Set(httputil.VersionHeader, version.String(version.Bellatrix))
writer := httptest.NewRecorder()
writer.Body = &bytes.Buffer{}
server.PublishBlindedBlock(writer, request)
@@ -2108,7 +2107,7 @@ func TestPublishBlindedBlock(t *testing.T) {
}
request := httptest.NewRequest(http.MethodPost, "http://foo.example", bytes.NewReader([]byte(rpctesting.BlindedCapellaBlock)))
request.Header.Set(api.VersionHeader, version.String(version.Capella))
request.Header.Set(httputil.VersionHeader, version.String(version.Capella))
writer := httptest.NewRecorder()
writer.Body = &bytes.Buffer{}
server.PublishBlindedBlock(writer, request)
@@ -2132,7 +2131,7 @@ func TestPublishBlindedBlock(t *testing.T) {
}
request := httptest.NewRequest(http.MethodPost, "http://foo.example", bytes.NewReader([]byte(rpctesting.BlindedDenebBlock)))
request.Header.Set(api.VersionHeader, version.String(version.Deneb))
request.Header.Set(httputil.VersionHeader, version.String(version.Deneb))
writer := httptest.NewRecorder()
writer.Body = &bytes.Buffer{}
server.PublishBlindedBlock(writer, request)
@@ -2156,7 +2155,7 @@ func TestPublishBlindedBlock(t *testing.T) {
}
request := httptest.NewRequest(http.MethodPost, "http://foo.example", bytes.NewReader([]byte(rpctesting.BlindedElectraBlock)))
request.Header.Set(api.VersionHeader, version.String(version.Electra))
request.Header.Set(httputil.VersionHeader, version.String(version.Electra))
writer := httptest.NewRecorder()
writer.Body = &bytes.Buffer{}
server.PublishBlindedBlock(writer, request)
@@ -2226,7 +2225,7 @@ func TestPublishBlindedBlock(t *testing.T) {
}
request := httptest.NewRequest(http.MethodPost, "http://foo.example", bytes.NewReader([]byte(rpctesting.BlindedFuluBlock)))
request.Header.Set(api.VersionHeader, version.String(version.Fulu))
request.Header.Set(httputil.VersionHeader, version.String(version.Fulu))
writer := httptest.NewRecorder()
writer.Body = &bytes.Buffer{}
server.PublishBlindedBlock(writer, request)
@@ -2238,7 +2237,7 @@ func TestPublishBlindedBlock(t *testing.T) {
}
request := httptest.NewRequest(http.MethodPost, "http://foo.example", bytes.NewReader([]byte(rpctesting.BellatrixBlock)))
request.Header.Set(api.VersionHeader, version.String(version.Bellatrix))
request.Header.Set(httputil.VersionHeader, version.String(version.Bellatrix))
writer := httptest.NewRecorder()
writer.Body = &bytes.Buffer{}
server.PublishBlindedBlock(writer, request)
@@ -2251,7 +2250,7 @@ func TestPublishBlindedBlock(t *testing.T) {
}
request := httptest.NewRequest(http.MethodPost, "http://foo.example", bytes.NewReader([]byte(rpctesting.BlindedBellatrixBlock)))
request.Header.Set(api.VersionHeader, version.String(version.Capella))
request.Header.Set(httputil.VersionHeader, version.String(version.Capella))
writer := httptest.NewRecorder()
writer.Body = &bytes.Buffer{}
server.PublishBlindedBlock(writer, request)
@@ -2301,8 +2300,8 @@ func TestPublishBlindedBlockSSZ(t *testing.T) {
ssz, err := genericBlock.GetPhase0().MarshalSSZ()
require.NoError(t, err)
request := httptest.NewRequest(http.MethodPost, "http://foo.example", bytes.NewReader(ssz))
request.Header.Set("Content-Type", api.OctetStreamMediaType)
request.Header.Set(api.VersionHeader, version.String(version.Phase0))
request.Header.Set("Content-Type", httputil.OctetStreamMediaType)
request.Header.Set(httputil.VersionHeader, version.String(version.Phase0))
writer := httptest.NewRecorder()
writer.Body = &bytes.Buffer{}
server.PublishBlindedBlock(writer, request)
@@ -2331,8 +2330,8 @@ func TestPublishBlindedBlockSSZ(t *testing.T) {
ssz, err := genericBlock.GetAltair().MarshalSSZ()
require.NoError(t, err)
request := httptest.NewRequest(http.MethodPost, "http://foo.example", bytes.NewReader(ssz))
request.Header.Set("Content-Type", api.OctetStreamMediaType)
request.Header.Set(api.VersionHeader, version.String(version.Altair))
request.Header.Set("Content-Type", httputil.OctetStreamMediaType)
request.Header.Set(httputil.VersionHeader, version.String(version.Altair))
writer := httptest.NewRecorder()
writer.Body = &bytes.Buffer{}
server.PublishBlindedBlock(writer, request)
@@ -2357,8 +2356,8 @@ func TestPublishBlindedBlockSSZ(t *testing.T) {
ssz, err := genericBlock.GetBlindedBellatrix().MarshalSSZ()
require.NoError(t, err)
request := httptest.NewRequest(http.MethodPost, "http://foo.example", bytes.NewReader(ssz))
request.Header.Set("Content-Type", api.OctetStreamMediaType)
request.Header.Set(api.VersionHeader, version.String(version.Bellatrix))
request.Header.Set("Content-Type", httputil.OctetStreamMediaType)
request.Header.Set(httputil.VersionHeader, version.String(version.Bellatrix))
writer := httptest.NewRecorder()
writer.Body = &bytes.Buffer{}
server.PublishBlindedBlock(writer, request)
@@ -2383,8 +2382,8 @@ func TestPublishBlindedBlockSSZ(t *testing.T) {
ssz, err := genericBlock.GetBlindedCapella().MarshalSSZ()
require.NoError(t, err)
request := httptest.NewRequest(http.MethodPost, "http://foo.example", bytes.NewReader(ssz))
request.Header.Set("Content-Type", api.OctetStreamMediaType)
request.Header.Set(api.VersionHeader, version.String(version.Capella))
request.Header.Set("Content-Type", httputil.OctetStreamMediaType)
request.Header.Set(httputil.VersionHeader, version.String(version.Capella))
writer := httptest.NewRecorder()
writer.Body = &bytes.Buffer{}
server.PublishBlindedBlock(writer, request)
@@ -2409,8 +2408,8 @@ func TestPublishBlindedBlockSSZ(t *testing.T) {
ssz, err := genericBlock.GetBlindedDeneb().MarshalSSZ()
require.NoError(t, err)
request := httptest.NewRequest(http.MethodPost, "http://foo.example", bytes.NewReader(ssz))
request.Header.Set("Content-Type", api.OctetStreamMediaType)
request.Header.Set(api.VersionHeader, version.String(version.Deneb))
request.Header.Set("Content-Type", httputil.OctetStreamMediaType)
request.Header.Set(httputil.VersionHeader, version.String(version.Deneb))
writer := httptest.NewRecorder()
writer.Body = &bytes.Buffer{}
server.PublishBlindedBlock(writer, request)
@@ -2435,8 +2434,8 @@ func TestPublishBlindedBlockSSZ(t *testing.T) {
ssz, err := genericBlock.GetBlindedElectra().MarshalSSZ()
require.NoError(t, err)
request := httptest.NewRequest(http.MethodPost, "http://foo.example", bytes.NewReader(ssz))
request.Header.Set("Content-Type", api.OctetStreamMediaType)
request.Header.Set(api.VersionHeader, version.String(version.Electra))
request.Header.Set("Content-Type", httputil.OctetStreamMediaType)
request.Header.Set(httputil.VersionHeader, version.String(version.Electra))
writer := httptest.NewRecorder()
writer.Body = &bytes.Buffer{}
server.PublishBlindedBlock(writer, request)
@@ -2461,8 +2460,8 @@ func TestPublishBlindedBlockSSZ(t *testing.T) {
ssz, err := genericBlock.GetBlindedFulu().MarshalSSZ()
require.NoError(t, err)
request := httptest.NewRequest(http.MethodPost, "http://foo.example", bytes.NewReader(ssz))
request.Header.Set("Content-Type", api.OctetStreamMediaType)
request.Header.Set(api.VersionHeader, version.String(version.Fulu))
request.Header.Set("Content-Type", httputil.OctetStreamMediaType)
request.Header.Set(httputil.VersionHeader, version.String(version.Fulu))
writer := httptest.NewRecorder()
writer.Body = &bytes.Buffer{}
server.PublishBlindedBlock(writer, request)
@@ -2474,7 +2473,7 @@ func TestPublishBlindedBlockSSZ(t *testing.T) {
}
request := httptest.NewRequest(http.MethodPost, "http://foo.example", bytes.NewReader([]byte(rpctesting.BellatrixBlock)))
request.Header.Set(api.VersionHeader, version.String(version.Bellatrix))
request.Header.Set(httputil.VersionHeader, version.String(version.Bellatrix))
writer := httptest.NewRecorder()
writer.Body = &bytes.Buffer{}
server.PublishBlindedBlock(writer, request)
@@ -2494,8 +2493,8 @@ func TestPublishBlindedBlockSSZ(t *testing.T) {
ssz, err := genericBlock.GetBlindedBellatrix().MarshalSSZ()
require.NoError(t, err)
request := httptest.NewRequest(http.MethodPost, "http://foo.example", bytes.NewReader(ssz))
request.Header.Set("Content-Type", api.OctetStreamMediaType)
request.Header.Set(api.VersionHeader, version.String(version.Capella))
request.Header.Set("Content-Type", httputil.OctetStreamMediaType)
request.Header.Set(httputil.VersionHeader, version.String(version.Capella))
writer := httptest.NewRecorder()
writer.Body = &bytes.Buffer{}
server.PublishBlindedBlock(writer, request)
@@ -2512,7 +2511,7 @@ func TestPublishBlindedBlockSSZ(t *testing.T) {
}
request := httptest.NewRequest(http.MethodPost, "http://foo.example", bytes.NewReader([]byte("foo")))
request.Header.Set("Content-Type", api.OctetStreamMediaType)
request.Header.Set("Content-Type", httputil.OctetStreamMediaType)
writer := httptest.NewRecorder()
writer.Body = &bytes.Buffer{}
server.PublishBlindedBlock(writer, request)
@@ -2539,7 +2538,7 @@ func TestPublishBlockV2(t *testing.T) {
}
request := httptest.NewRequest(http.MethodPost, "http://foo.example", bytes.NewReader([]byte(rpctesting.Phase0Block)))
request.Header.Set(api.VersionHeader, version.String(version.Phase0))
request.Header.Set(httputil.VersionHeader, version.String(version.Phase0))
writer := httptest.NewRecorder()
writer.Body = &bytes.Buffer{}
server.PublishBlockV2(writer, request)
@@ -2561,7 +2560,7 @@ func TestPublishBlockV2(t *testing.T) {
}
request := httptest.NewRequest(http.MethodPost, "http://foo.example", bytes.NewReader([]byte(rpctesting.AltairBlock)))
request.Header.Set(api.VersionHeader, version.String(version.Altair))
request.Header.Set(httputil.VersionHeader, version.String(version.Altair))
writer := httptest.NewRecorder()
writer.Body = &bytes.Buffer{}
server.PublishBlockV2(writer, request)
@@ -2585,7 +2584,7 @@ func TestPublishBlockV2(t *testing.T) {
}
request := httptest.NewRequest(http.MethodPost, "http://foo.example", bytes.NewReader([]byte(rpctesting.BellatrixBlock)))
request.Header.Set(api.VersionHeader, version.String(version.Bellatrix))
request.Header.Set(httputil.VersionHeader, version.String(version.Bellatrix))
writer := httptest.NewRecorder()
writer.Body = &bytes.Buffer{}
server.PublishBlockV2(writer, request)
@@ -2609,7 +2608,7 @@ func TestPublishBlockV2(t *testing.T) {
}
request := httptest.NewRequest(http.MethodPost, "http://foo.example", bytes.NewReader([]byte(rpctesting.CapellaBlock)))
request.Header.Set(api.VersionHeader, version.String(version.Capella))
request.Header.Set(httputil.VersionHeader, version.String(version.Capella))
writer := httptest.NewRecorder()
writer.Body = &bytes.Buffer{}
server.PublishBlockV2(writer, request)
@@ -2633,7 +2632,7 @@ func TestPublishBlockV2(t *testing.T) {
}
request := httptest.NewRequest(http.MethodPost, "http://foo.example", bytes.NewReader([]byte(rpctesting.DenebBlockContents)))
request.Header.Set(api.VersionHeader, version.String(version.Deneb))
request.Header.Set(httputil.VersionHeader, version.String(version.Deneb))
writer := httptest.NewRecorder()
writer.Body = &bytes.Buffer{}
server.PublishBlockV2(writer, request)
@@ -2657,7 +2656,7 @@ func TestPublishBlockV2(t *testing.T) {
}
request := httptest.NewRequest(http.MethodPost, "http://foo.example", bytes.NewReader([]byte(rpctesting.ElectraBlockContents)))
request.Header.Set(api.VersionHeader, version.String(version.Electra))
request.Header.Set(httputil.VersionHeader, version.String(version.Electra))
writer := httptest.NewRecorder()
writer.Body = &bytes.Buffer{}
server.PublishBlockV2(writer, request)
@@ -2681,7 +2680,7 @@ func TestPublishBlockV2(t *testing.T) {
}
request := httptest.NewRequest(http.MethodPost, "http://foo.example", bytes.NewReader([]byte(rpctesting.FuluBlockContents)))
request.Header.Set(api.VersionHeader, version.String(version.Fulu))
request.Header.Set(httputil.VersionHeader, version.String(version.Fulu))
writer := httptest.NewRecorder()
writer.Body = &bytes.Buffer{}
server.PublishBlockV2(writer, request)
@@ -2693,7 +2692,7 @@ func TestPublishBlockV2(t *testing.T) {
}
request := httptest.NewRequest(http.MethodPost, "http://foo.example", bytes.NewReader([]byte(rpctesting.BlindedBellatrixBlock)))
request.Header.Set(api.VersionHeader, version.String(version.Bellatrix))
request.Header.Set(httputil.VersionHeader, version.String(version.Bellatrix))
writer := httptest.NewRecorder()
writer.Body = &bytes.Buffer{}
server.PublishBlockV2(writer, request)
@@ -2706,7 +2705,7 @@ func TestPublishBlockV2(t *testing.T) {
}
request := httptest.NewRequest(http.MethodPost, "http://foo.example", bytes.NewReader([]byte(rpctesting.BellatrixBlock)))
request.Header.Set(api.VersionHeader, version.String(version.Capella))
request.Header.Set(httputil.VersionHeader, version.String(version.Capella))
writer := httptest.NewRecorder()
writer.Body = &bytes.Buffer{}
server.PublishBlockV2(writer, request)
@@ -2723,7 +2722,7 @@ func TestPublishBlockV2(t *testing.T) {
writer.Body = &bytes.Buffer{}
server.PublishBlockV2(writer, request)
assert.Equal(t, http.StatusBadRequest, writer.Code)
assert.StringContains(t, api.VersionHeader+" header is required", writer.Body.String())
assert.StringContains(t, httputil.VersionHeader+" header is required", writer.Body.String())
})
t.Run("syncing", func(t *testing.T) {
chainService := &chainMock.ChainService{}
@@ -2735,7 +2734,7 @@ func TestPublishBlockV2(t *testing.T) {
}
request := httptest.NewRequest(http.MethodPost, "http://foo.example", bytes.NewReader([]byte("foo")))
request.Header.Set(api.VersionHeader, version.String(version.Capella))
request.Header.Set(httputil.VersionHeader, version.String(version.Capella))
writer := httptest.NewRecorder()
writer.Body = &bytes.Buffer{}
server.PublishBlockV2(writer, request)
@@ -2769,8 +2768,8 @@ func TestPublishBlockV2SSZ(t *testing.T) {
ssz, err := genericBlock.GetPhase0().MarshalSSZ()
require.NoError(t, err)
request := httptest.NewRequest(http.MethodPost, "http://foo.example", bytes.NewReader(ssz))
request.Header.Set("Content-Type", api.OctetStreamMediaType)
request.Header.Set(api.VersionHeader, version.String(version.Phase0))
request.Header.Set("Content-Type", httputil.OctetStreamMediaType)
request.Header.Set(httputil.VersionHeader, version.String(version.Phase0))
writer := httptest.NewRecorder()
writer.Body = &bytes.Buffer{}
server.PublishBlockV2(writer, request)
@@ -2799,8 +2798,8 @@ func TestPublishBlockV2SSZ(t *testing.T) {
ssz, err := genericBlock.GetAltair().MarshalSSZ()
require.NoError(t, err)
request := httptest.NewRequest(http.MethodPost, "http://foo.example", bytes.NewReader(ssz))
request.Header.Set("Content-Type", api.OctetStreamMediaType)
request.Header.Set(api.VersionHeader, version.String(version.Altair))
request.Header.Set("Content-Type", httputil.OctetStreamMediaType)
request.Header.Set(httputil.VersionHeader, version.String(version.Altair))
writer := httptest.NewRecorder()
writer.Body = &bytes.Buffer{}
server.PublishBlockV2(writer, request)
@@ -2824,8 +2823,8 @@ func TestPublishBlockV2SSZ(t *testing.T) {
ssz, err := genericBlock.GetBellatrix().MarshalSSZ()
require.NoError(t, err)
request := httptest.NewRequest(http.MethodPost, "http://foo.example", bytes.NewReader(ssz))
request.Header.Set("Content-Type", api.OctetStreamMediaType)
request.Header.Set(api.VersionHeader, version.String(version.Bellatrix))
request.Header.Set("Content-Type", httputil.OctetStreamMediaType)
request.Header.Set(httputil.VersionHeader, version.String(version.Bellatrix))
writer := httptest.NewRecorder()
writer.Body = &bytes.Buffer{}
server.PublishBlockV2(writer, request)
@@ -2850,8 +2849,8 @@ func TestPublishBlockV2SSZ(t *testing.T) {
ssz, err := genericBlock.GetCapella().MarshalSSZ()
require.NoError(t, err)
request := httptest.NewRequest(http.MethodPost, "http://foo.example", bytes.NewReader(ssz))
request.Header.Set("Content-Type", api.OctetStreamMediaType)
request.Header.Set(api.VersionHeader, version.String(version.Capella))
request.Header.Set("Content-Type", httputil.OctetStreamMediaType)
request.Header.Set(httputil.VersionHeader, version.String(version.Capella))
writer := httptest.NewRecorder()
writer.Body = &bytes.Buffer{}
server.PublishBlockV2(writer, request)
@@ -2876,8 +2875,8 @@ func TestPublishBlockV2SSZ(t *testing.T) {
ssz, err := genericBlock.GetDeneb().MarshalSSZ()
require.NoError(t, err)
request := httptest.NewRequest(http.MethodPost, "http://foo.example", bytes.NewReader(ssz))
request.Header.Set("Content-Type", api.OctetStreamMediaType)
request.Header.Set(api.VersionHeader, version.String(version.Deneb))
request.Header.Set("Content-Type", httputil.OctetStreamMediaType)
request.Header.Set(httputil.VersionHeader, version.String(version.Deneb))
writer := httptest.NewRecorder()
writer.Body = &bytes.Buffer{}
server.PublishBlockV2(writer, request)
@@ -2902,8 +2901,8 @@ func TestPublishBlockV2SSZ(t *testing.T) {
ssz, err := genericBlock.GetElectra().MarshalSSZ()
require.NoError(t, err)
request := httptest.NewRequest(http.MethodPost, "http://foo.example", bytes.NewReader(ssz))
request.Header.Set("Content-Type", api.OctetStreamMediaType)
request.Header.Set(api.VersionHeader, version.String(version.Electra))
request.Header.Set("Content-Type", httputil.OctetStreamMediaType)
request.Header.Set(httputil.VersionHeader, version.String(version.Electra))
writer := httptest.NewRecorder()
writer.Body = &bytes.Buffer{}
server.PublishBlockV2(writer, request)
@@ -2928,8 +2927,8 @@ func TestPublishBlockV2SSZ(t *testing.T) {
ssz, err := genericBlock.GetFulu().MarshalSSZ()
require.NoError(t, err)
request := httptest.NewRequest(http.MethodPost, "http://foo.example", bytes.NewReader(ssz))
request.Header.Set("Content-Type", api.OctetStreamMediaType)
request.Header.Set(api.VersionHeader, version.String(version.Fulu))
request.Header.Set("Content-Type", httputil.OctetStreamMediaType)
request.Header.Set(httputil.VersionHeader, version.String(version.Fulu))
writer := httptest.NewRecorder()
writer.Body = &bytes.Buffer{}
server.PublishBlockV2(writer, request)
@@ -2948,8 +2947,8 @@ func TestPublishBlockV2SSZ(t *testing.T) {
ssz, err := genericBlock.GetBlindedBellatrix().MarshalSSZ()
require.NoError(t, err)
request := httptest.NewRequest(http.MethodPost, "http://foo.example", bytes.NewReader(ssz))
request.Header.Set("Content-Type", api.OctetStreamMediaType)
request.Header.Set(api.VersionHeader, version.String(version.Bellatrix))
request.Header.Set("Content-Type", httputil.OctetStreamMediaType)
request.Header.Set(httputil.VersionHeader, version.String(version.Bellatrix))
writer := httptest.NewRecorder()
writer.Body = &bytes.Buffer{}
server.PublishBlockV2(writer, request)
@@ -2969,8 +2968,8 @@ func TestPublishBlockV2SSZ(t *testing.T) {
ssz, err := genericBlock.GetBellatrix().MarshalSSZ()
require.NoError(t, err)
request := httptest.NewRequest(http.MethodPost, "http://foo.example", bytes.NewReader(ssz))
request.Header.Set("Content-Type", api.OctetStreamMediaType)
request.Header.Set(api.VersionHeader, version.String(version.Capella))
request.Header.Set("Content-Type", httputil.OctetStreamMediaType)
request.Header.Set(httputil.VersionHeader, version.String(version.Capella))
writer := httptest.NewRecorder()
writer.Body = &bytes.Buffer{}
server.PublishBlockV2(writer, request)
@@ -2983,12 +2982,12 @@ func TestPublishBlockV2SSZ(t *testing.T) {
}
request := httptest.NewRequest(http.MethodPost, "http://foo.example", bytes.NewReader([]byte(rpctesting.CapellaBlock)))
request.Header.Set("Content-Type", api.OctetStreamMediaType)
request.Header.Set("Content-Type", httputil.OctetStreamMediaType)
writer := httptest.NewRecorder()
writer.Body = &bytes.Buffer{}
server.PublishBlockV2(writer, request)
assert.Equal(t, http.StatusBadRequest, writer.Code)
assert.StringContains(t, api.VersionHeader+" header is required", writer.Body.String())
assert.StringContains(t, httputil.VersionHeader+" header is required", writer.Body.String())
})
t.Run("syncing", func(t *testing.T) {
chainService := &chainMock.ChainService{}
@@ -3000,7 +2999,7 @@ func TestPublishBlockV2SSZ(t *testing.T) {
}
request := httptest.NewRequest(http.MethodPost, "http://foo.example", bytes.NewReader([]byte("foo")))
request.Header.Set("Content-Type", api.OctetStreamMediaType)
request.Header.Set("Content-Type", httputil.OctetStreamMediaType)
writer := httptest.NewRecorder()
writer.Body = &bytes.Buffer{}
server.PublishBlockV2(writer, request)
@@ -3027,7 +3026,7 @@ func TestPublishBlindedBlockV2(t *testing.T) {
}
request := httptest.NewRequest(http.MethodPost, "http://foo.example", bytes.NewReader([]byte(rpctesting.Phase0Block)))
request.Header.Set(api.VersionHeader, version.String(version.Phase0))
request.Header.Set(httputil.VersionHeader, version.String(version.Phase0))
writer := httptest.NewRecorder()
writer.Body = &bytes.Buffer{}
server.PublishBlindedBlockV2(writer, request)
@@ -3049,7 +3048,7 @@ func TestPublishBlindedBlockV2(t *testing.T) {
}
request := httptest.NewRequest(http.MethodPost, "http://foo.example", bytes.NewReader([]byte(rpctesting.AltairBlock)))
request.Header.Set(api.VersionHeader, version.String(version.Altair))
request.Header.Set(httputil.VersionHeader, version.String(version.Altair))
writer := httptest.NewRecorder()
writer.Body = &bytes.Buffer{}
server.PublishBlindedBlockV2(writer, request)
@@ -3073,7 +3072,7 @@ func TestPublishBlindedBlockV2(t *testing.T) {
}
request := httptest.NewRequest(http.MethodPost, "http://foo.example", bytes.NewReader([]byte(rpctesting.BlindedBellatrixBlock)))
request.Header.Set(api.VersionHeader, version.String(version.Bellatrix))
request.Header.Set(httputil.VersionHeader, version.String(version.Bellatrix))
writer := httptest.NewRecorder()
writer.Body = &bytes.Buffer{}
server.PublishBlindedBlockV2(writer, request)
@@ -3097,7 +3096,7 @@ func TestPublishBlindedBlockV2(t *testing.T) {
}
request := httptest.NewRequest(http.MethodPost, "http://foo.example", bytes.NewReader([]byte(rpctesting.BlindedCapellaBlock)))
request.Header.Set(api.VersionHeader, version.String(version.Capella))
request.Header.Set(httputil.VersionHeader, version.String(version.Capella))
writer := httptest.NewRecorder()
writer.Body = &bytes.Buffer{}
server.PublishBlindedBlockV2(writer, request)
@@ -3121,7 +3120,7 @@ func TestPublishBlindedBlockV2(t *testing.T) {
}
request := httptest.NewRequest(http.MethodPost, "http://foo.example", bytes.NewReader([]byte(rpctesting.BlindedDenebBlock)))
request.Header.Set(api.VersionHeader, version.String(version.Deneb))
request.Header.Set(httputil.VersionHeader, version.String(version.Deneb))
writer := httptest.NewRecorder()
writer.Body = &bytes.Buffer{}
server.PublishBlindedBlockV2(writer, request)
@@ -3145,7 +3144,7 @@ func TestPublishBlindedBlockV2(t *testing.T) {
}
request := httptest.NewRequest(http.MethodPost, "http://foo.example", bytes.NewReader([]byte(rpctesting.BlindedElectraBlock)))
request.Header.Set(api.VersionHeader, version.String(version.Electra))
request.Header.Set(httputil.VersionHeader, version.String(version.Electra))
writer := httptest.NewRecorder()
writer.Body = &bytes.Buffer{}
server.PublishBlindedBlockV2(writer, request)
@@ -3169,7 +3168,7 @@ func TestPublishBlindedBlockV2(t *testing.T) {
}
request := httptest.NewRequest(http.MethodPost, "http://foo.example", bytes.NewReader([]byte(rpctesting.BlindedFuluBlock)))
request.Header.Set(api.VersionHeader, version.String(version.Fulu))
request.Header.Set(httputil.VersionHeader, version.String(version.Fulu))
writer := httptest.NewRecorder()
writer.Body = &bytes.Buffer{}
server.PublishBlindedBlockV2(writer, request)
@@ -3181,7 +3180,7 @@ func TestPublishBlindedBlockV2(t *testing.T) {
}
request := httptest.NewRequest(http.MethodPost, "http://foo.example", bytes.NewReader([]byte(rpctesting.BellatrixBlock)))
request.Header.Set(api.VersionHeader, version.String(version.Bellatrix))
request.Header.Set(httputil.VersionHeader, version.String(version.Bellatrix))
writer := httptest.NewRecorder()
writer.Body = &bytes.Buffer{}
server.PublishBlindedBlockV2(writer, request)
@@ -3194,7 +3193,7 @@ func TestPublishBlindedBlockV2(t *testing.T) {
}
request := httptest.NewRequest(http.MethodPost, "http://foo.example", bytes.NewReader([]byte(rpctesting.BlindedBellatrixBlock)))
request.Header.Set(api.VersionHeader, version.String(version.Capella))
request.Header.Set(httputil.VersionHeader, version.String(version.Capella))
writer := httptest.NewRecorder()
writer.Body = &bytes.Buffer{}
server.PublishBlindedBlockV2(writer, request)
@@ -3211,7 +3210,7 @@ func TestPublishBlindedBlockV2(t *testing.T) {
writer.Body = &bytes.Buffer{}
server.PublishBlockV2(writer, request)
assert.Equal(t, http.StatusBadRequest, writer.Code)
assert.StringContains(t, api.VersionHeader+" header is required", writer.Body.String())
assert.StringContains(t, httputil.VersionHeader+" header is required", writer.Body.String())
})
t.Run("syncing", func(t *testing.T) {
chainService := &chainMock.ChainService{}
@@ -3256,8 +3255,8 @@ func TestPublishBlindedBlockV2SSZ(t *testing.T) {
ssz, err := genericBlock.GetPhase0().MarshalSSZ()
require.NoError(t, err)
request := httptest.NewRequest(http.MethodPost, "http://foo.example", bytes.NewReader(ssz))
request.Header.Set("Content-Type", api.OctetStreamMediaType)
request.Header.Set(api.VersionHeader, version.String(version.Phase0))
request.Header.Set("Content-Type", httputil.OctetStreamMediaType)
request.Header.Set(httputil.VersionHeader, version.String(version.Phase0))
writer := httptest.NewRecorder()
writer.Body = &bytes.Buffer{}
server.PublishBlindedBlockV2(writer, request)
@@ -3286,8 +3285,8 @@ func TestPublishBlindedBlockV2SSZ(t *testing.T) {
ssz, err := genericBlock.GetAltair().MarshalSSZ()
require.NoError(t, err)
request := httptest.NewRequest(http.MethodPost, "http://foo.example", bytes.NewReader(ssz))
request.Header.Set("Content-Type", api.OctetStreamMediaType)
request.Header.Set(api.VersionHeader, version.String(version.Altair))
request.Header.Set("Content-Type", httputil.OctetStreamMediaType)
request.Header.Set(httputil.VersionHeader, version.String(version.Altair))
writer := httptest.NewRecorder()
writer.Body = &bytes.Buffer{}
server.PublishBlindedBlockV2(writer, request)
@@ -3312,8 +3311,8 @@ func TestPublishBlindedBlockV2SSZ(t *testing.T) {
ssz, err := genericBlock.GetBlindedBellatrix().MarshalSSZ()
require.NoError(t, err)
request := httptest.NewRequest(http.MethodPost, "http://foo.example", bytes.NewReader(ssz))
request.Header.Set("Content-Type", api.OctetStreamMediaType)
request.Header.Set(api.VersionHeader, version.String(version.Bellatrix))
request.Header.Set("Content-Type", httputil.OctetStreamMediaType)
request.Header.Set(httputil.VersionHeader, version.String(version.Bellatrix))
writer := httptest.NewRecorder()
writer.Body = &bytes.Buffer{}
server.PublishBlindedBlockV2(writer, request)
@@ -3338,8 +3337,8 @@ func TestPublishBlindedBlockV2SSZ(t *testing.T) {
ssz, err := genericBlock.GetBlindedCapella().MarshalSSZ()
require.NoError(t, err)
request := httptest.NewRequest(http.MethodPost, "http://foo.example", bytes.NewReader(ssz))
request.Header.Set("Content-Type", api.OctetStreamMediaType)
request.Header.Set(api.VersionHeader, version.String(version.Capella))
request.Header.Set("Content-Type", httputil.OctetStreamMediaType)
request.Header.Set(httputil.VersionHeader, version.String(version.Capella))
writer := httptest.NewRecorder()
writer.Body = &bytes.Buffer{}
server.PublishBlindedBlockV2(writer, request)
@@ -3364,8 +3363,8 @@ func TestPublishBlindedBlockV2SSZ(t *testing.T) {
ssz, err := genericBlock.GetBlindedDeneb().MarshalSSZ()
require.NoError(t, err)
request := httptest.NewRequest(http.MethodPost, "http://foo.example", bytes.NewReader(ssz))
request.Header.Set("Content-Type", api.OctetStreamMediaType)
request.Header.Set(api.VersionHeader, version.String(version.Deneb))
request.Header.Set("Content-Type", httputil.OctetStreamMediaType)
request.Header.Set(httputil.VersionHeader, version.String(version.Deneb))
writer := httptest.NewRecorder()
writer.Body = &bytes.Buffer{}
server.PublishBlindedBlock(writer, request)
@@ -3390,8 +3389,8 @@ func TestPublishBlindedBlockV2SSZ(t *testing.T) {
ssz, err := genericBlock.GetBlindedElectra().MarshalSSZ()
require.NoError(t, err)
request := httptest.NewRequest(http.MethodPost, "http://foo.example", bytes.NewReader(ssz))
request.Header.Set("Content-Type", api.OctetStreamMediaType)
request.Header.Set(api.VersionHeader, version.String(version.Electra))
request.Header.Set("Content-Type", httputil.OctetStreamMediaType)
request.Header.Set(httputil.VersionHeader, version.String(version.Electra))
writer := httptest.NewRecorder()
writer.Body = &bytes.Buffer{}
server.PublishBlindedBlock(writer, request)
@@ -3416,8 +3415,8 @@ func TestPublishBlindedBlockV2SSZ(t *testing.T) {
ssz, err := genericBlock.GetBlindedFulu().MarshalSSZ()
require.NoError(t, err)
request := httptest.NewRequest(http.MethodPost, "http://foo.example", bytes.NewReader(ssz))
request.Header.Set("Content-Type", api.OctetStreamMediaType)
request.Header.Set(api.VersionHeader, version.String(version.Fulu))
request.Header.Set("Content-Type", httputil.OctetStreamMediaType)
request.Header.Set(httputil.VersionHeader, version.String(version.Fulu))
writer := httptest.NewRecorder()
writer.Body = &bytes.Buffer{}
server.PublishBlindedBlock(writer, request)
@@ -3429,7 +3428,7 @@ func TestPublishBlindedBlockV2SSZ(t *testing.T) {
}
request := httptest.NewRequest(http.MethodPost, "http://foo.example", bytes.NewReader([]byte(rpctesting.BellatrixBlock)))
request.Header.Set(api.VersionHeader, version.String(version.Bellatrix))
request.Header.Set(httputil.VersionHeader, version.String(version.Bellatrix))
writer := httptest.NewRecorder()
writer.Body = &bytes.Buffer{}
server.PublishBlindedBlockV2(writer, request)
@@ -3449,8 +3448,8 @@ func TestPublishBlindedBlockV2SSZ(t *testing.T) {
ssz, err := genericBlock.GetBlindedBellatrix().MarshalSSZ()
require.NoError(t, err)
request := httptest.NewRequest(http.MethodPost, "http://foo.example", bytes.NewReader(ssz))
request.Header.Set("Content-Type", api.OctetStreamMediaType)
request.Header.Set(api.VersionHeader, version.String(version.Capella))
request.Header.Set("Content-Type", httputil.OctetStreamMediaType)
request.Header.Set(httputil.VersionHeader, version.String(version.Capella))
writer := httptest.NewRecorder()
writer.Body = &bytes.Buffer{}
server.PublishBlindedBlockV2(writer, request)
@@ -3463,12 +3462,12 @@ func TestPublishBlindedBlockV2SSZ(t *testing.T) {
}
request := httptest.NewRequest(http.MethodPost, "http://foo.example", bytes.NewReader([]byte(rpctesting.BlindedCapellaBlock)))
request.Header.Set("Content-Type", api.OctetStreamMediaType)
request.Header.Set("Content-Type", httputil.OctetStreamMediaType)
writer := httptest.NewRecorder()
writer.Body = &bytes.Buffer{}
server.PublishBlockV2(writer, request)
assert.Equal(t, http.StatusBadRequest, writer.Code)
assert.StringContains(t, api.VersionHeader+" header is required", writer.Body.String())
assert.StringContains(t, httputil.VersionHeader+" header is required", writer.Body.String())
})
t.Run("syncing", func(t *testing.T) {
chainService := &chainMock.ChainService{}
@@ -3480,7 +3479,7 @@ func TestPublishBlindedBlockV2SSZ(t *testing.T) {
}
request := httptest.NewRequest(http.MethodPost, "http://foo.example", bytes.NewReader([]byte("foo")))
request.Header.Set("Content-Type", api.OctetStreamMediaType)
request.Header.Set("Content-Type", httputil.OctetStreamMediaType)
writer := httptest.NewRecorder()
writer.Body = &bytes.Buffer{}
server.PublishBlindedBlockV2(writer, request)
@@ -4697,7 +4696,7 @@ func TestGetDepositSnapshot(t *testing.T) {
})
t.Run("SSZ response", func(t *testing.T) {
writer.Body = &bytes.Buffer{}
request.Header.Set("Accept", api.OctetStreamMediaType)
request.Header.Set("Accept", httputil.OctetStreamMediaType)
s.GetDepositSnapshot(writer, request)
assert.Equal(t, http.StatusOK, writer.Code)
resp := &eth.DepositSnapshot{}
@@ -4795,7 +4794,7 @@ func TestGetPendingDeposits(t *testing.T) {
server.GetPendingDeposits(rec, req)
require.Equal(t, http.StatusOK, rec.Code)
require.Equal(t, "electra", rec.Header().Get(api.VersionHeader))
require.Equal(t, "electra", rec.Header().Get(httputil.VersionHeader))
var resp structs.GetPendingDepositsResponse
require.NoError(t, json.Unmarshal(rec.Body.Bytes(), &resp))
@@ -4818,7 +4817,7 @@ func TestGetPendingDeposits(t *testing.T) {
server.GetPendingDeposits(rec, req)
require.Equal(t, http.StatusOK, rec.Code)
require.Equal(t, "electra", rec.Header().Get(api.VersionHeader))
require.Equal(t, "electra", rec.Header().Get(httputil.VersionHeader))
responseBytes := rec.Body.Bytes()
var recoveredDeposits []*eth.PendingDeposit
@@ -4982,7 +4981,7 @@ func TestGetPendingPartialWithdrawals(t *testing.T) {
server.GetPendingPartialWithdrawals(rec, req)
require.Equal(t, http.StatusOK, rec.Code)
require.Equal(t, "electra", rec.Header().Get(api.VersionHeader))
require.Equal(t, "electra", rec.Header().Get(httputil.VersionHeader))
var resp structs.GetPendingPartialWithdrawalsResponse
require.NoError(t, json.Unmarshal(rec.Body.Bytes(), &resp))
@@ -5006,7 +5005,7 @@ func TestGetPendingPartialWithdrawals(t *testing.T) {
server.GetPendingPartialWithdrawals(rec, req)
require.Equal(t, http.StatusOK, rec.Code)
require.Equal(t, "electra", rec.Header().Get(api.VersionHeader))
require.Equal(t, "electra", rec.Header().Get(httputil.VersionHeader))
responseBytes := rec.Body.Bytes()
var recoveredWithdrawals []*eth.PendingPartialWithdrawal

View File

@@ -1,6 +1,7 @@
package beacon
import (
"context"
"encoding/json"
"fmt"
"io"
@@ -10,6 +11,7 @@ import (
"github.com/ethereum/go-ethereum/common/hexutil"
"github.com/pkg/errors"
httputil2 "github.com/prysmaticlabs/prysm/v5/api/httputil"
"github.com/prysmaticlabs/prysm/v5/api/server/structs"
"github.com/prysmaticlabs/prysm/v5/beacon-chain/rpc/eth/helpers"
"github.com/prysmaticlabs/prysm/v5/beacon-chain/rpc/eth/shared"
@@ -20,7 +22,7 @@ import (
"github.com/prysmaticlabs/prysm/v5/consensus-types/validator"
"github.com/prysmaticlabs/prysm/v5/encoding/bytesutil"
"github.com/prysmaticlabs/prysm/v5/monitoring/tracing/trace"
"github.com/prysmaticlabs/prysm/v5/network/httputil"
eth "github.com/prysmaticlabs/prysm/v5/proto/prysm/v1alpha1"
"github.com/prysmaticlabs/prysm/v5/time/slots"
)
@@ -31,7 +33,7 @@ func (s *Server) GetValidators(w http.ResponseWriter, r *http.Request) {
stateId := r.PathValue("state_id")
if stateId == "" {
httputil.HandleError(w, "state_id is required in URL params", http.StatusBadRequest)
httputil2.HandleError(w, "state_id is required in URL params", http.StatusBadRequest)
return
}
st, err := s.Stater.State(ctx, []byte(stateId))
@@ -42,12 +44,12 @@ func (s *Server) GetValidators(w http.ResponseWriter, r *http.Request) {
isOptimistic, err := helpers.IsOptimistic(ctx, []byte(stateId), s.OptimisticModeFetcher, s.Stater, s.ChainInfoFetcher, s.BeaconDB)
if err != nil {
httputil.HandleError(w, "Could not check optimistic status: "+err.Error(), http.StatusInternalServerError)
httputil2.HandleError(w, "Could not check optimistic status: "+err.Error(), http.StatusInternalServerError)
return
}
blockRoot, err := st.LatestBlockHeader().HashTreeRoot()
if err != nil {
httputil.HandleError(w, "Could not calculate root of latest block header: "+err.Error(), http.StatusInternalServerError)
httputil2.HandleError(w, "Could not calculate root of latest block header: "+err.Error(), http.StatusInternalServerError)
return
}
isFinalized := s.FinalizationFetcher.IsFinalized(ctx, blockRoot)
@@ -57,10 +59,10 @@ func (s *Server) GetValidators(w http.ResponseWriter, r *http.Request) {
err = json.NewDecoder(r.Body).Decode(&req)
switch {
case errors.Is(err, io.EOF):
httputil.HandleError(w, "No data submitted", http.StatusBadRequest)
httputil2.HandleError(w, "No data submitted", http.StatusBadRequest)
return
case err != nil:
httputil.HandleError(w, "Could not decode request body: "+err.Error(), http.StatusBadRequest)
httputil2.HandleError(w, "Could not decode request body: "+err.Error(), http.StatusBadRequest)
return
}
}
@@ -89,7 +91,7 @@ func (s *Server) GetValidators(w http.ResponseWriter, r *http.Request) {
ExecutionOptimistic: isOptimistic,
Finalized: isFinalized,
}
httputil.WriteJson(w, resp)
httputil2.WriteJson(w, resp)
return
}
@@ -105,7 +107,7 @@ func (s *Server) GetValidators(w http.ResponseWriter, r *http.Request) {
for i, val := range readOnlyVals {
valStatus, err := helpers.ValidatorSubStatus(val, epoch)
if err != nil {
httputil.HandleError(w, "Could not get validator status: "+err.Error(), http.StatusInternalServerError)
httputil2.HandleError(w, "Could not get validator status: "+err.Error(), http.StatusInternalServerError)
return
}
id := primitives.ValidatorIndex(i)
@@ -114,7 +116,7 @@ func (s *Server) GetValidators(w http.ResponseWriter, r *http.Request) {
}
balance, err := st.BalanceAtIndex(id)
if err != nil {
httputil.HandleError(w, "Could not get validator balance: "+err.Error(), http.StatusInternalServerError)
httputil2.HandleError(w, "Could not get validator balance: "+err.Error(), http.StatusInternalServerError)
return
}
containers[i] = valContainerFromReadOnlyVal(val, id, balance, valStatus)
@@ -124,7 +126,7 @@ func (s *Server) GetValidators(w http.ResponseWriter, r *http.Request) {
ExecutionOptimistic: isOptimistic,
Finalized: isFinalized,
}
httputil.WriteJson(w, resp)
httputil2.WriteJson(w, resp)
return
}
@@ -132,7 +134,7 @@ func (s *Server) GetValidators(w http.ResponseWriter, r *http.Request) {
for _, ss := range statuses {
ok, vs := validator.StatusFromString(ss)
if !ok {
httputil.HandleError(w, "Invalid status "+ss, http.StatusBadRequest)
httputil2.HandleError(w, "Invalid status "+ss, http.StatusBadRequest)
return
}
filteredStatuses[vs] = true
@@ -141,12 +143,12 @@ func (s *Server) GetValidators(w http.ResponseWriter, r *http.Request) {
for i, val := range readOnlyVals {
valStatus, err := helpers.ValidatorStatus(val, epoch)
if err != nil {
httputil.HandleError(w, "Could not get validator status: "+err.Error(), http.StatusInternalServerError)
httputil2.HandleError(w, "Could not get validator status: "+err.Error(), http.StatusInternalServerError)
return
}
valSubStatus, err := helpers.ValidatorSubStatus(val, epoch)
if err != nil {
httputil.HandleError(w, "Could not get validator status: "+err.Error(), http.StatusInternalServerError)
httputil2.HandleError(w, "Could not get validator status: "+err.Error(), http.StatusInternalServerError)
return
}
if filteredStatuses[valStatus] || filteredStatuses[valSubStatus] {
@@ -157,7 +159,7 @@ func (s *Server) GetValidators(w http.ResponseWriter, r *http.Request) {
}
balance, err := st.BalanceAtIndex(id)
if err != nil {
httputil.HandleError(w, "Could not get validator balance: "+err.Error(), http.StatusInternalServerError)
httputil2.HandleError(w, "Could not get validator balance: "+err.Error(), http.StatusInternalServerError)
return
}
container = valContainerFromReadOnlyVal(val, id, balance, valSubStatus)
@@ -170,7 +172,7 @@ func (s *Server) GetValidators(w http.ResponseWriter, r *http.Request) {
ExecutionOptimistic: isOptimistic,
Finalized: isFinalized,
}
httputil.WriteJson(w, resp)
httputil2.WriteJson(w, resp)
}
// GetValidator returns a validator specified by state and id or public key along with status and balance.
@@ -180,12 +182,12 @@ func (s *Server) GetValidator(w http.ResponseWriter, r *http.Request) {
stateId := r.PathValue("state_id")
if stateId == "" {
httputil.HandleError(w, "state_id is required in URL params", http.StatusBadRequest)
httputil2.HandleError(w, "state_id is required in URL params", http.StatusBadRequest)
return
}
valId := r.PathValue("validator_id")
if valId == "" {
httputil.HandleError(w, "validator_id is required in URL params", http.StatusBadRequest)
httputil2.HandleError(w, "validator_id is required in URL params", http.StatusBadRequest)
return
}
@@ -203,29 +205,29 @@ func (s *Server) GetValidator(w http.ResponseWriter, r *http.Request) {
return
}
if len(ids) == 0 || len(readOnlyVals) == 0 {
httputil.HandleError(w, "No validator returned for the given ID", http.StatusInternalServerError)
httputil2.HandleError(w, "No validator returned for the given ID", http.StatusInternalServerError)
return
}
valSubStatus, err := helpers.ValidatorSubStatus(readOnlyVals[0], slots.ToEpoch(st.Slot()))
if err != nil {
httputil.HandleError(w, "Could not get validator status: "+err.Error(), http.StatusInternalServerError)
httputil2.HandleError(w, "Could not get validator status: "+err.Error(), http.StatusInternalServerError)
return
}
bal, err := st.BalanceAtIndex(ids[0])
if err != nil {
httputil.HandleError(w, "Could not get validator balance: "+err.Error(), http.StatusInternalServerError)
httputil2.HandleError(w, "Could not get validator balance: "+err.Error(), http.StatusInternalServerError)
return
}
container := valContainerFromReadOnlyVal(readOnlyVals[0], ids[0], bal, valSubStatus)
isOptimistic, err := helpers.IsOptimistic(ctx, []byte(stateId), s.OptimisticModeFetcher, s.Stater, s.ChainInfoFetcher, s.BeaconDB)
if err != nil {
httputil.HandleError(w, "Could not check optimistic status: "+err.Error(), http.StatusInternalServerError)
httputil2.HandleError(w, "Could not check optimistic status: "+err.Error(), http.StatusInternalServerError)
return
}
blockRoot, err := st.LatestBlockHeader().HashTreeRoot()
if err != nil {
httputil.HandleError(w, "Could not calculate root of latest block header: "+err.Error(), http.StatusInternalServerError)
httputil2.HandleError(w, "Could not calculate root of latest block header: "+err.Error(), http.StatusInternalServerError)
return
}
isFinalized := s.FinalizationFetcher.IsFinalized(ctx, blockRoot)
@@ -235,7 +237,7 @@ func (s *Server) GetValidator(w http.ResponseWriter, r *http.Request) {
ExecutionOptimistic: isOptimistic,
Finalized: isFinalized,
}
httputil.WriteJson(w, resp)
httputil2.WriteJson(w, resp)
}
// GetValidatorBalances returns a filterable list of validator balances.
@@ -245,7 +247,7 @@ func (s *Server) GetValidatorBalances(w http.ResponseWriter, r *http.Request) {
stateId := r.PathValue("state_id")
if stateId == "" {
httputil.HandleError(w, "state_id is required in URL params", http.StatusBadRequest)
httputil2.HandleError(w, "state_id is required in URL params", http.StatusBadRequest)
return
}
st, err := s.Stater.State(ctx, []byte(stateId))
@@ -256,12 +258,12 @@ func (s *Server) GetValidatorBalances(w http.ResponseWriter, r *http.Request) {
isOptimistic, err := helpers.IsOptimistic(ctx, []byte(stateId), s.OptimisticModeFetcher, s.Stater, s.ChainInfoFetcher, s.BeaconDB)
if err != nil {
httputil.HandleError(w, "Could not check optimistic status: "+err.Error(), http.StatusInternalServerError)
httputil2.HandleError(w, "Could not check optimistic status: "+err.Error(), http.StatusInternalServerError)
return
}
blockRoot, err := st.LatestBlockHeader().HashTreeRoot()
if err != nil {
httputil.HandleError(w, "Could not calculate root of latest block header: "+err.Error(), http.StatusInternalServerError)
httputil2.HandleError(w, "Could not calculate root of latest block header: "+err.Error(), http.StatusInternalServerError)
return
}
isFinalized := s.FinalizationFetcher.IsFinalized(ctx, blockRoot)
@@ -273,10 +275,10 @@ func (s *Server) GetValidatorBalances(w http.ResponseWriter, r *http.Request) {
err = json.NewDecoder(r.Body).Decode(&rawIds)
switch {
case errors.Is(err, io.EOF):
httputil.HandleError(w, "No data submitted", http.StatusBadRequest)
httputil2.HandleError(w, "No data submitted", http.StatusBadRequest)
return
case err != nil:
httputil.HandleError(w, "Could not decode request body: "+err.Error(), http.StatusBadRequest)
httputil2.HandleError(w, "Could not decode request body: "+err.Error(), http.StatusBadRequest)
return
}
}
@@ -292,7 +294,7 @@ func (s *Server) GetValidatorBalances(w http.ResponseWriter, r *http.Request) {
ExecutionOptimistic: isOptimistic,
Finalized: isFinalized,
}
httputil.WriteJson(w, resp)
httputil2.WriteJson(w, resp)
return
}
@@ -321,7 +323,153 @@ func (s *Server) GetValidatorBalances(w http.ResponseWriter, r *http.Request) {
ExecutionOptimistic: isOptimistic,
Finalized: isFinalized,
}
httputil.WriteJson(w, resp)
httputil2.WriteJson(w, resp)
}
// GetValidatorIdentities returns a filterable list of validators identities.
func (s *Server) GetValidatorIdentities(w http.ResponseWriter, r *http.Request) {
ctx, span := trace.StartSpan(r.Context(), "beacon.GetValidatorIdentities")
defer span.End()
stateId := r.PathValue("state_id")
if stateId == "" {
httputil2.HandleError(w, "state_id is required in URL params", http.StatusBadRequest)
return
}
st, err := s.Stater.State(ctx, []byte(stateId))
if err != nil {
shared.WriteStateFetchError(w, err)
return
}
var rawIds []string
err = json.NewDecoder(r.Body).Decode(&rawIds)
switch {
case errors.Is(err, io.EOF):
httputil2.HandleError(w, "No data submitted", http.StatusBadRequest)
return
case err != nil:
httputil2.HandleError(w, "Could not decode request body: "+err.Error(), http.StatusBadRequest)
return
}
ids, ok := decodeIds(w, st, rawIds, true /* ignore unknown */)
if !ok {
return
}
if httputil2.RespondWithSsz(r) {
s.getValidatorIdentitiesSSZ(w, st, rawIds, ids)
} else {
s.getValidatorIdentitiesJSON(r.Context(), w, st, stateId, rawIds, ids)
}
}
func (s *Server) getValidatorIdentitiesSSZ(w http.ResponseWriter, st state.BeaconState, rawIds []string, ids []primitives.ValidatorIndex) {
// return no data if all IDs are ignored
if len(rawIds) > 0 && len(ids) == 0 {
httputil2.WriteSsz(w, []byte{})
return
}
vals := st.ValidatorsReadOnly()
var identities []*eth.ValidatorIdentity
if len(ids) == 0 {
identities = make([]*eth.ValidatorIdentity, len(vals))
for i, v := range vals {
pubkey := v.PublicKey()
identities[i] = &eth.ValidatorIdentity{
Index: primitives.ValidatorIndex(i),
Pubkey: pubkey[:],
ActivationEpoch: v.ActivationEpoch(),
}
}
} else {
identities = make([]*eth.ValidatorIdentity, len(ids))
for i, id := range ids {
pubkey := vals[id].PublicKey()
identities[i] = &eth.ValidatorIdentity{
Index: id,
Pubkey: pubkey[:],
ActivationEpoch: vals[id].ActivationEpoch(),
}
}
}
sszLen := (&eth.ValidatorIdentity{}).SizeSSZ()
resp := make([]byte, len(identities)*sszLen)
for i, vi := range identities {
ssz, err := vi.MarshalSSZ()
if err != nil {
httputil2.HandleError(w, "Could not marshal validator identity to SSZ: "+err.Error(), http.StatusInternalServerError)
return
}
copy(resp[i*sszLen:(i+1)*sszLen], ssz)
}
httputil2.WriteSsz(w, resp)
}
func (s *Server) getValidatorIdentitiesJSON(
ctx context.Context,
w http.ResponseWriter,
st state.BeaconState,
stateId string,
rawIds []string,
ids []primitives.ValidatorIndex,
) {
isOptimistic, err := helpers.IsOptimistic(ctx, []byte(stateId), s.OptimisticModeFetcher, s.Stater, s.ChainInfoFetcher, s.BeaconDB)
if err != nil {
httputil2.HandleError(w, "Could not check optimistic status: "+err.Error(), http.StatusInternalServerError)
return
}
blockRoot, err := st.LatestBlockHeader().HashTreeRoot()
if err != nil {
httputil2.HandleError(w, "Could not calculate root of latest block header: "+err.Error(), http.StatusInternalServerError)
return
}
isFinalized := s.FinalizationFetcher.IsFinalized(ctx, blockRoot)
// return no data if all IDs are ignored
if len(rawIds) > 0 && len(ids) == 0 {
resp := &structs.GetValidatorIdentitiesResponse{
Data: []*structs.ValidatorIdentity{},
ExecutionOptimistic: isOptimistic,
Finalized: isFinalized,
}
httputil2.WriteJson(w, resp)
return
}
vals := st.ValidatorsReadOnly()
var identities []*structs.ValidatorIdentity
if len(ids) == 0 {
identities = make([]*structs.ValidatorIdentity, len(vals))
for i, v := range vals {
pubkey := v.PublicKey()
identities[i] = &structs.ValidatorIdentity{
Index: strconv.FormatUint(uint64(i), 10),
Pubkey: hexutil.Encode(pubkey[:]),
ActivationEpoch: strconv.FormatUint(uint64(v.ActivationEpoch()), 10),
}
}
} else {
identities = make([]*structs.ValidatorIdentity, len(ids))
for i, id := range ids {
pubkey := vals[id].PublicKey()
identities[i] = &structs.ValidatorIdentity{
Index: strconv.FormatUint(uint64(id), 10),
Pubkey: hexutil.Encode(pubkey[:]),
ActivationEpoch: strconv.FormatUint(uint64(vals[id].ActivationEpoch()), 10),
}
}
}
resp := &structs.GetValidatorIdentitiesResponse{
Data: identities,
ExecutionOptimistic: isOptimistic,
Finalized: isFinalized,
}
httputil2.WriteJson(w, resp)
}
// decodeIds takes in a list of validator ID strings (as either a pubkey or a validator index)
@@ -333,7 +481,7 @@ func decodeIds(w http.ResponseWriter, st state.BeaconState, rawIds []string, ign
pubkey, err := hexutil.Decode(rawId)
if err == nil {
if len(pubkey) != fieldparams.BLSPubkeyLength {
httputil.HandleError(w, fmt.Sprintf("Pubkey length is %d instead of %d", len(pubkey), fieldparams.BLSPubkeyLength), http.StatusBadRequest)
httputil2.HandleError(w, fmt.Sprintf("Pubkey length is %d instead of %d", len(pubkey), fieldparams.BLSPubkeyLength), http.StatusBadRequest)
return nil, false
}
valIndex, ok := st.ValidatorIndexByPubkey(bytesutil.ToBytes48(pubkey))
@@ -341,7 +489,7 @@ func decodeIds(w http.ResponseWriter, st state.BeaconState, rawIds []string, ign
if ignoreUnknown {
continue
}
httputil.HandleError(w, fmt.Sprintf("Unknown validator: %s", hexutil.Encode(pubkey)), http.StatusNotFound)
httputil2.HandleError(w, fmt.Sprintf("Unknown validator: %s", hexutil.Encode(pubkey)), http.StatusNotFound)
return nil, false
}
ids = append(ids, valIndex)
@@ -350,14 +498,14 @@ func decodeIds(w http.ResponseWriter, st state.BeaconState, rawIds []string, ign
index, err := strconv.ParseUint(rawId, 10, 64)
if err != nil {
httputil.HandleError(w, fmt.Sprintf("Invalid validator index %s", rawId), http.StatusBadRequest)
httputil2.HandleError(w, fmt.Sprintf("Invalid validator index %s", rawId), http.StatusBadRequest)
return nil, false
}
if index >= numVals {
if ignoreUnknown {
continue
}
httputil.HandleError(w, fmt.Sprintf("Invalid validator index %d", index), http.StatusBadRequest)
httputil2.HandleError(w, fmt.Sprintf("Invalid validator index %d", index), http.StatusBadRequest)
return nil, false
}
ids = append(ids, primitives.ValidatorIndex(index))
@@ -375,13 +523,13 @@ func valsFromIds(w http.ResponseWriter, st state.BeaconState, ids []primitives.V
for _, id := range ids {
val, err := st.ValidatorAtIndex(id)
if err != nil {
httputil.HandleError(w, fmt.Sprintf("Could not get validator at index %d: %s", id, err.Error()), http.StatusInternalServerError)
httputil2.HandleError(w, fmt.Sprintf("Could not get validator at index %d: %s", id, err.Error()), http.StatusInternalServerError)
return nil, false
}
readOnlyVal, err := statenative.NewValidator(val)
if err != nil {
httputil.HandleError(w, "Could not convert validator: "+err.Error(), http.StatusInternalServerError)
httputil2.HandleError(w, "Could not convert validator: "+err.Error(), http.StatusInternalServerError)
return nil, false
}
vals = append(vals, readOnlyVal)

View File

@@ -11,6 +11,7 @@ import (
"testing"
"github.com/ethereum/go-ethereum/common/hexutil"
"github.com/prysmaticlabs/prysm/v5/api/httputil"
"github.com/prysmaticlabs/prysm/v5/api/server/structs"
chainMock "github.com/prysmaticlabs/prysm/v5/beacon-chain/blockchain/testing"
"github.com/prysmaticlabs/prysm/v5/beacon-chain/rpc/lookup"
@@ -19,7 +20,6 @@ import (
fieldparams "github.com/prysmaticlabs/prysm/v5/config/fieldparams"
"github.com/prysmaticlabs/prysm/v5/config/params"
"github.com/prysmaticlabs/prysm/v5/consensus-types/primitives"
"github.com/prysmaticlabs/prysm/v5/network/httputil"
eth "github.com/prysmaticlabs/prysm/v5/proto/prysm/v1alpha1"
"github.com/prysmaticlabs/prysm/v5/testing/assert"
"github.com/prysmaticlabs/prysm/v5/testing/require"
@@ -946,16 +946,16 @@ func TestGetValidatorBalances(t *testing.T) {
hexPubkey := hexutil.Encode(pubkey[:])
request := httptest.NewRequest(
http.MethodGet,
fmt.Sprintf("http://example.com/eth/v1/beacon/states/{state_id}/validators?id=%s&id=1", hexPubkey),
fmt.Sprintf("http://example.com/eth/v1/beacon/states/{state_id}/validator_balances?id=%s&id=1", hexPubkey),
nil,
)
request.SetPathValue("state_id", "head")
writer := httptest.NewRecorder()
writer.Body = &bytes.Buffer{}
s.GetValidators(writer, request)
s.GetValidatorBalances(writer, request)
assert.Equal(t, http.StatusOK, writer.Code)
resp := &structs.GetValidatorsResponse{}
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)
@@ -1025,7 +1025,7 @@ func TestGetValidatorBalances(t *testing.T) {
writer := httptest.NewRecorder()
writer.Body = &bytes.Buffer{}
s.GetValidator(writer, request)
s.GetValidatorBalances(writer, request)
assert.Equal(t, http.StatusBadRequest, writer.Code)
e := &httputil.DefaultJsonError{}
require.NoError(t, json.Unmarshal(writer.Body.Bytes(), e))
@@ -1183,3 +1183,478 @@ func TestGetValidatorBalances(t *testing.T) {
assert.StringContains(t, "Could not decode request body", e.Message)
})
}
func TestGetValidatorIdentities(t *testing.T) {
count := uint64(4)
genesisState, _ := util.DeterministicGenesisState(t, count)
st := genesisState.ToProtoUnsafe().(*eth.BeaconState)
for i := uint64(0); i < count; i++ {
st.Validators[i].ActivationEpoch = primitives.Epoch(i)
}
t.Run("json", func(t *testing.T) {
t.Run("get all", func(t *testing.T) {
chainService := &chainMock.ChainService{}
s := Server{
Stater: &testutil.MockStater{
BeaconState: genesisState,
},
HeadFetcher: chainService,
OptimisticModeFetcher: chainService,
FinalizationFetcher: chainService,
}
body := bytes.Buffer{}
_, err := body.WriteString("[]")
require.NoError(t, err)
request := httptest.NewRequest(http.MethodPost, "http://example.com/eth/v1/beacon/states/{state_id}/validator_identities", &body)
request.SetPathValue("state_id", "head")
writer := httptest.NewRecorder()
writer.Body = &bytes.Buffer{}
s.GetValidatorIdentities(writer, request)
assert.Equal(t, http.StatusOK, writer.Code)
resp := &structs.GetValidatorIdentitiesResponse{}
require.NoError(t, json.Unmarshal(writer.Body.Bytes(), resp))
require.Equal(t, 4, len(resp.Data))
for i := uint64(0); i < count; i++ {
assert.Equal(t, fmt.Sprintf("%d", i), resp.Data[i].Index)
assert.DeepEqual(t, hexutil.Encode(st.Validators[i].PublicKey), resp.Data[i].Pubkey)
assert.Equal(t, fmt.Sprintf("%d", st.Validators[i].ActivationEpoch), resp.Data[i].ActivationEpoch)
}
})
t.Run("get by index", func(t *testing.T) {
chainService := &chainMock.ChainService{}
s := Server{
Stater: &testutil.MockStater{
BeaconState: genesisState,
},
HeadFetcher: chainService,
OptimisticModeFetcher: chainService,
FinalizationFetcher: chainService,
}
body := bytes.Buffer{}
_, err := body.WriteString("[\"0\",\"1\"]")
require.NoError(t, err)
request := httptest.NewRequest(http.MethodPost, "http://example.com/eth/v1/beacon/states/{state_id}/validator_identities", &body)
request.SetPathValue("state_id", "head")
writer := httptest.NewRecorder()
writer.Body = &bytes.Buffer{}
s.GetValidatorIdentities(writer, request)
assert.Equal(t, http.StatusOK, writer.Code)
resp := &structs.GetValidatorIdentitiesResponse{}
require.NoError(t, json.Unmarshal(writer.Body.Bytes(), resp))
require.Equal(t, 2, len(resp.Data))
assert.Equal(t, "0", resp.Data[0].Index)
assert.Equal(t, "1", resp.Data[1].Index)
})
t.Run("get by pubkey", func(t *testing.T) {
chainService := &chainMock.ChainService{}
s := Server{
Stater: &testutil.MockStater{
BeaconState: genesisState,
},
HeadFetcher: chainService,
OptimisticModeFetcher: chainService,
FinalizationFetcher: chainService,
}
pubkey1 := st.Validators[0].PublicKey
pubkey2 := st.Validators[1].PublicKey
hexPubkey1 := hexutil.Encode(pubkey1)
hexPubkey2 := hexutil.Encode(pubkey2)
body := bytes.Buffer{}
_, err := body.WriteString(fmt.Sprintf("[\"%s\",\"%s\"]", hexPubkey1, hexPubkey2))
require.NoError(t, err)
request := httptest.NewRequest(http.MethodPost, "http://example.com/eth/v1/beacon/states/{state_id}/validator_identities", &body)
request.SetPathValue("state_id", "head")
writer := httptest.NewRecorder()
writer.Body = &bytes.Buffer{}
s.GetValidatorIdentities(writer, request)
assert.Equal(t, http.StatusOK, writer.Code)
resp := &structs.GetValidatorIdentitiesResponse{}
require.NoError(t, json.Unmarshal(writer.Body.Bytes(), resp))
require.Equal(t, 2, len(resp.Data))
assert.Equal(t, "0", resp.Data[0].Index)
assert.Equal(t, "1", resp.Data[1].Index)
})
t.Run("get by both index and pubkey", func(t *testing.T) {
chainService := &chainMock.ChainService{}
s := Server{
Stater: &testutil.MockStater{
BeaconState: genesisState,
},
HeadFetcher: chainService,
OptimisticModeFetcher: chainService,
FinalizationFetcher: chainService,
}
pubkey := st.Validators[0].PublicKey
hexPubkey := hexutil.Encode(pubkey)
body := bytes.Buffer{}
_, err := body.WriteString(fmt.Sprintf("[\"%s\",\"1\"]", hexPubkey))
require.NoError(t, err)
request := httptest.NewRequest(http.MethodPost, "http://example.com/eth/v1/beacon/states/{state_id}/validator_identities", &body)
request.SetPathValue("state_id", "head")
writer := httptest.NewRecorder()
writer.Body = &bytes.Buffer{}
s.GetValidatorIdentities(writer, request)
assert.Equal(t, http.StatusOK, writer.Code)
resp := &structs.GetValidatorIdentitiesResponse{}
require.NoError(t, json.Unmarshal(writer.Body.Bytes(), resp))
require.Equal(t, 2, len(resp.Data))
assert.Equal(t, "0", resp.Data[0].Index)
assert.Equal(t, "1", resp.Data[1].Index)
})
t.Run("unknown pubkey is ignored", func(t *testing.T) {
chainService := &chainMock.ChainService{}
s := Server{
Stater: &testutil.MockStater{
BeaconState: genesisState,
},
HeadFetcher: chainService,
OptimisticModeFetcher: chainService,
FinalizationFetcher: chainService,
}
pubkey := st.Validators[1].PublicKey
hexPubkey := hexutil.Encode(pubkey)
body := bytes.Buffer{}
_, err := body.WriteString(fmt.Sprintf("[\"%s\",\"%s\"]", hexPubkey, hexutil.Encode([]byte(strings.Repeat("x", fieldparams.BLSPubkeyLength)))))
require.NoError(t, err)
request := httptest.NewRequest(http.MethodPost, "http://example.com/eth/v1/beacon/states/{state_id}/validator_identities", &body)
request.SetPathValue("state_id", "head")
writer := httptest.NewRecorder()
writer.Body = &bytes.Buffer{}
s.GetValidatorIdentities(writer, request)
assert.Equal(t, http.StatusOK, writer.Code)
resp := &structs.GetValidatorIdentitiesResponse{}
require.NoError(t, json.Unmarshal(writer.Body.Bytes(), resp))
require.Equal(t, 1, len(resp.Data))
assert.Equal(t, "1", resp.Data[0].Index)
})
t.Run("unknown index is ignored", func(t *testing.T) {
chainService := &chainMock.ChainService{}
s := Server{
Stater: &testutil.MockStater{
BeaconState: genesisState,
},
HeadFetcher: chainService,
OptimisticModeFetcher: chainService,
FinalizationFetcher: chainService,
}
body := bytes.Buffer{}
_, err := body.WriteString("[\"1\",\"99999\"]")
require.NoError(t, err)
request := httptest.NewRequest(http.MethodPost, "http://example.com/eth/v1/beacon/states/{state_id}/validator_identities", &body)
request.SetPathValue("state_id", "head")
writer := httptest.NewRecorder()
writer.Body = &bytes.Buffer{}
s.GetValidatorIdentities(writer, request)
assert.Equal(t, http.StatusOK, writer.Code)
resp := &structs.GetValidatorIdentitiesResponse{}
require.NoError(t, json.Unmarshal(writer.Body.Bytes(), resp))
require.Equal(t, 1, len(resp.Data))
assert.Equal(t, "1", resp.Data[0].Index)
})
t.Run("execution optimistic", func(t *testing.T) {
chainService := &chainMock.ChainService{Optimistic: true}
s := Server{
Stater: &testutil.MockStater{
BeaconState: genesisState,
},
HeadFetcher: chainService,
OptimisticModeFetcher: chainService,
FinalizationFetcher: chainService,
}
body := bytes.Buffer{}
_, err := body.WriteString("[]")
require.NoError(t, err)
request := httptest.NewRequest(http.MethodPost, "http://example.com/eth/v1/beacon/states/{state_id}/validator_identities", &body)
request.SetPathValue("state_id", "head")
writer := httptest.NewRecorder()
writer.Body = &bytes.Buffer{}
s.GetValidatorIdentities(writer, request)
assert.Equal(t, http.StatusOK, writer.Code)
resp := &structs.GetValidatorIdentitiesResponse{}
require.NoError(t, json.Unmarshal(writer.Body.Bytes(), resp))
assert.Equal(t, true, resp.ExecutionOptimistic)
})
t.Run("finalized", func(t *testing.T) {
headerRoot, err := genesisState.LatestBlockHeader().HashTreeRoot()
require.NoError(t, err)
chainService := &chainMock.ChainService{
FinalizedRoots: map[[32]byte]bool{
headerRoot: true,
},
}
s := Server{
Stater: &testutil.MockStater{
BeaconState: genesisState,
},
HeadFetcher: chainService,
OptimisticModeFetcher: chainService,
FinalizationFetcher: chainService,
}
body := bytes.Buffer{}
_, err = body.WriteString("[]")
require.NoError(t, err)
request := httptest.NewRequest(http.MethodPost, "http://example.com/eth/v1/beacon/states/{state_id}/validator_identities", &body)
request.SetPathValue("state_id", "head")
writer := httptest.NewRecorder()
writer.Body = &bytes.Buffer{}
s.GetValidatorIdentities(writer, request)
assert.Equal(t, http.StatusOK, writer.Code)
resp := &structs.GetValidatorIdentitiesResponse{}
require.NoError(t, json.Unmarshal(writer.Body.Bytes(), resp))
assert.Equal(t, true, resp.Finalized)
})
})
t.Run("ssz", func(t *testing.T) {
size := uint64((&eth.ValidatorIdentity{}).SizeSSZ())
t.Run("get all", func(t *testing.T) {
chainService := &chainMock.ChainService{}
s := Server{
Stater: &testutil.MockStater{
BeaconState: genesisState,
},
HeadFetcher: chainService,
OptimisticModeFetcher: chainService,
FinalizationFetcher: chainService,
}
body := bytes.Buffer{}
_, err := body.WriteString("[]")
require.NoError(t, err)
request := httptest.NewRequest(http.MethodPost, "http://example.com/eth/v1/beacon/states/{state_id}/validator_identities", &body)
request.Header.Set("Accept", httputil.OctetStreamMediaType)
request.SetPathValue("state_id", "head")
writer := httptest.NewRecorder()
writer.Body = &bytes.Buffer{}
s.GetValidatorIdentities(writer, request)
assert.Equal(t, http.StatusOK, writer.Code)
assert.Equal(t, size*count, uint64(len(writer.Body.Bytes())))
})
t.Run("get by index", func(t *testing.T) {
chainService := &chainMock.ChainService{}
s := Server{
Stater: &testutil.MockStater{
BeaconState: genesisState,
},
HeadFetcher: chainService,
OptimisticModeFetcher: chainService,
FinalizationFetcher: chainService,
}
body := bytes.Buffer{}
_, err := body.WriteString("[\"0\",\"1\"]")
require.NoError(t, err)
request := httptest.NewRequest(http.MethodPost, "http://example.com/eth/v1/beacon/states/{state_id}/validator_identities", &body)
request.Header.Set("Accept", httputil.OctetStreamMediaType)
request.SetPathValue("state_id", "head")
writer := httptest.NewRecorder()
writer.Body = &bytes.Buffer{}
s.GetValidatorIdentities(writer, request)
assert.Equal(t, http.StatusOK, writer.Code)
assert.Equal(t, size*2, uint64(len(writer.Body.Bytes())))
})
t.Run("get by pubkey", func(t *testing.T) {
chainService := &chainMock.ChainService{}
s := Server{
Stater: &testutil.MockStater{
BeaconState: genesisState,
},
HeadFetcher: chainService,
OptimisticModeFetcher: chainService,
FinalizationFetcher: chainService,
}
pubkey1 := st.Validators[0].PublicKey
pubkey2 := st.Validators[1].PublicKey
hexPubkey1 := hexutil.Encode(pubkey1)
hexPubkey2 := hexutil.Encode(pubkey2)
body := bytes.Buffer{}
_, err := body.WriteString(fmt.Sprintf("[\"%s\",\"%s\"]", hexPubkey1, hexPubkey2))
require.NoError(t, err)
request := httptest.NewRequest(http.MethodPost, "http://example.com/eth/v1/beacon/states/{state_id}/validator_identities", &body)
request.Header.Set("Accept", httputil.OctetStreamMediaType)
request.SetPathValue("state_id", "head")
writer := httptest.NewRecorder()
writer.Body = &bytes.Buffer{}
s.GetValidatorIdentities(writer, request)
assert.Equal(t, http.StatusOK, writer.Code)
assert.Equal(t, size*2, uint64(len(writer.Body.Bytes())))
})
t.Run("get by both index and pubkey", func(t *testing.T) {
chainService := &chainMock.ChainService{}
s := Server{
Stater: &testutil.MockStater{
BeaconState: genesisState,
},
HeadFetcher: chainService,
OptimisticModeFetcher: chainService,
FinalizationFetcher: chainService,
}
pubkey := st.Validators[0].PublicKey
hexPubkey := hexutil.Encode(pubkey)
body := bytes.Buffer{}
_, err := body.WriteString(fmt.Sprintf("[\"%s\",\"1\"]", hexPubkey))
require.NoError(t, err)
request := httptest.NewRequest(http.MethodPost, "http://example.com/eth/v1/beacon/states/{state_id}/validator_identities", &body)
request.Header.Set("Accept", httputil.OctetStreamMediaType)
request.SetPathValue("state_id", "head")
writer := httptest.NewRecorder()
writer.Body = &bytes.Buffer{}
s.GetValidatorIdentities(writer, request)
assert.Equal(t, http.StatusOK, writer.Code)
assert.Equal(t, size*2, uint64(len(writer.Body.Bytes())))
})
t.Run("unknown pubkey is ignored", func(t *testing.T) {
chainService := &chainMock.ChainService{}
s := Server{
Stater: &testutil.MockStater{
BeaconState: genesisState,
},
HeadFetcher: chainService,
OptimisticModeFetcher: chainService,
FinalizationFetcher: chainService,
}
pubkey := st.Validators[1].PublicKey
hexPubkey := hexutil.Encode(pubkey)
body := bytes.Buffer{}
_, err := body.WriteString(fmt.Sprintf("[\"%s\",\"%s\"]", hexPubkey, hexutil.Encode([]byte(strings.Repeat("x", fieldparams.BLSPubkeyLength)))))
require.NoError(t, err)
request := httptest.NewRequest(http.MethodPost, "http://example.com/eth/v1/beacon/states/{state_id}/validator_identities", &body)
request.Header.Set("Accept", httputil.OctetStreamMediaType)
request.SetPathValue("state_id", "head")
writer := httptest.NewRecorder()
writer.Body = &bytes.Buffer{}
s.GetValidatorIdentities(writer, request)
assert.Equal(t, http.StatusOK, writer.Code)
assert.Equal(t, size, uint64(len(writer.Body.Bytes())))
})
t.Run("unknown index is ignored", func(t *testing.T) {
chainService := &chainMock.ChainService{}
s := Server{
Stater: &testutil.MockStater{
BeaconState: genesisState,
},
HeadFetcher: chainService,
OptimisticModeFetcher: chainService,
FinalizationFetcher: chainService,
}
body := bytes.Buffer{}
_, err := body.WriteString("[\"1\",\"99999\"]")
require.NoError(t, err)
request := httptest.NewRequest(http.MethodPost, "http://example.com/eth/v1/beacon/states/{state_id}/validator_identities", &body)
request.Header.Set("Accept", httputil.OctetStreamMediaType)
request.SetPathValue("state_id", "head")
writer := httptest.NewRecorder()
writer.Body = &bytes.Buffer{}
s.GetValidatorIdentities(writer, request)
assert.Equal(t, http.StatusOK, writer.Code)
assert.Equal(t, size, uint64(len(writer.Body.Bytes())))
})
})
t.Run("errors", func(t *testing.T) {
t.Run("state ID required", func(t *testing.T) {
s := Server{
Stater: &testutil.MockStater{
BeaconState: genesisState,
},
HeadFetcher: &chainMock.ChainService{},
}
body := bytes.Buffer{}
_, err := body.WriteString("[]")
require.NoError(t, err)
request := httptest.NewRequest(http.MethodPost, "http://example.com/eth/v1/beacon/states/{state_id}/validator_identities", &body)
writer := httptest.NewRecorder()
writer.Body = &bytes.Buffer{}
s.GetValidatorIdentities(writer, request)
assert.Equal(t, http.StatusBadRequest, writer.Code)
e := &httputil.DefaultJsonError{}
require.NoError(t, json.Unmarshal(writer.Body.Bytes(), e))
assert.Equal(t, http.StatusBadRequest, e.Code)
assert.StringContains(t, "state_id is required in URL params", e.Message)
})
t.Run("empty body", func(t *testing.T) {
chainService := &chainMock.ChainService{}
s := Server{
Stater: &testutil.MockStater{
BeaconState: genesisState,
},
HeadFetcher: chainService,
OptimisticModeFetcher: chainService,
FinalizationFetcher: chainService,
}
body := bytes.Buffer{}
_, err := body.WriteString("")
require.NoError(t, err)
request := httptest.NewRequest(http.MethodPost, "http://example.com/eth/v1/beacon/states/{state_id}/validator_identities", nil)
request.SetPathValue("state_id", "head")
writer := httptest.NewRecorder()
writer.Body = &bytes.Buffer{}
s.GetValidatorIdentities(writer, request)
assert.Equal(t, http.StatusBadRequest, writer.Code)
e := &httputil.DefaultJsonError{}
require.NoError(t, json.Unmarshal(writer.Body.Bytes(), e))
assert.Equal(t, http.StatusBadRequest, e.Code)
assert.StringContains(t, "No data submitted", e.Message)
})
t.Run("invalid body", func(t *testing.T) {
chainService := &chainMock.ChainService{}
s := Server{
Stater: &testutil.MockStater{
BeaconState: genesisState,
},
HeadFetcher: chainService,
OptimisticModeFetcher: chainService,
FinalizationFetcher: chainService,
}
body := bytes.Buffer{}
_, err := body.WriteString("foo")
require.NoError(t, err)
request := httptest.NewRequest(http.MethodPost, "http://example.com/eth/v1/beacon/states/{state_id}/validator_identities", &body)
request.SetPathValue("state_id", "head")
writer := httptest.NewRecorder()
writer.Body = &bytes.Buffer{}
s.GetValidatorIdentities(writer, request)
assert.Equal(t, http.StatusBadRequest, writer.Code)
e := &httputil.DefaultJsonError{}
require.NoError(t, json.Unmarshal(writer.Body.Bytes(), e))
assert.Equal(t, http.StatusBadRequest, e.Code)
assert.StringContains(t, "Could not decode request body", e.Message)
})
})
}

View File

@@ -9,7 +9,7 @@ go_library(
importpath = "github.com/prysmaticlabs/prysm/v5/beacon-chain/rpc/eth/blob",
visibility = ["//visibility:public"],
deps = [
"//api:go_default_library",
"//api/httputil:go_default_library",
"//api/server/structs:go_default_library",
"//beacon-chain/blockchain:go_default_library",
"//beacon-chain/rpc/core:go_default_library",
@@ -19,7 +19,6 @@ go_library(
"//consensus-types/blocks:go_default_library",
"//consensus-types/primitives:go_default_library",
"//monitoring/tracing/trace:go_default_library",
"//network/httputil:go_default_library",
"//runtime/version:go_default_library",
"@com_github_ethereum_go_ethereum//common/hexutil:go_default_library",
"@com_github_pkg_errors//:go_default_library",
@@ -31,7 +30,7 @@ go_test(
srcs = ["handlers_test.go"],
embed = [":go_default_library"],
deps = [
"//api:go_default_library",
"//api/httputil:go_default_library",
"//api/server/structs:go_default_library",
"//beacon-chain/blockchain/testing:go_default_library",
"//beacon-chain/db/filesystem:go_default_library",
@@ -41,7 +40,6 @@ go_test(
"//beacon-chain/verification:go_default_library",
"//config/fieldparams:go_default_library",
"//config/params:go_default_library",
"//network/httputil:go_default_library",
"//proto/prysm/v1alpha1:go_default_library",
"//runtime/version:go_default_library",
"//testing/assert:go_default_library",

View File

@@ -9,7 +9,7 @@ import (
"github.com/ethereum/go-ethereum/common/hexutil"
"github.com/pkg/errors"
"github.com/prysmaticlabs/prysm/v5/api"
httputil2 "github.com/prysmaticlabs/prysm/v5/api/httputil"
"github.com/prysmaticlabs/prysm/v5/api/server/structs"
"github.com/prysmaticlabs/prysm/v5/beacon-chain/rpc/core"
field_params "github.com/prysmaticlabs/prysm/v5/config/fieldparams"
@@ -17,7 +17,6 @@ import (
"github.com/prysmaticlabs/prysm/v5/consensus-types/blocks"
"github.com/prysmaticlabs/prysm/v5/consensus-types/primitives"
"github.com/prysmaticlabs/prysm/v5/monitoring/tracing/trace"
"github.com/prysmaticlabs/prysm/v5/network/httputil"
"github.com/prysmaticlabs/prysm/v5/runtime/version"
)
@@ -28,7 +27,7 @@ func (s *Server) Blobs(w http.ResponseWriter, r *http.Request) {
indices, err := parseIndices(r.URL, s.TimeFetcher.CurrentSlot())
if err != nil {
httputil.HandleError(w, err.Error(), http.StatusBadRequest)
httputil2.HandleError(w, err.Error(), http.StatusBadRequest)
return
}
segments := strings.Split(r.URL.Path, "/")
@@ -39,49 +38,49 @@ func (s *Server) Blobs(w http.ResponseWriter, r *http.Request) {
code := core.ErrorReasonToHTTP(rpcErr.Reason)
switch code {
case http.StatusBadRequest:
httputil.HandleError(w, "Invalid block ID: "+rpcErr.Err.Error(), code)
httputil2.HandleError(w, "Invalid block ID: "+rpcErr.Err.Error(), code)
return
case http.StatusNotFound:
httputil.HandleError(w, "Block not found: "+rpcErr.Err.Error(), code)
httputil2.HandleError(w, "Block not found: "+rpcErr.Err.Error(), code)
return
case http.StatusInternalServerError:
httputil.HandleError(w, "Internal server error: "+rpcErr.Err.Error(), code)
httputil2.HandleError(w, "Internal server error: "+rpcErr.Err.Error(), code)
return
default:
httputil.HandleError(w, rpcErr.Err.Error(), code)
httputil2.HandleError(w, rpcErr.Err.Error(), code)
return
}
}
blk, err := s.Blocker.Block(ctx, []byte(blockId))
if err != nil {
httputil.HandleError(w, "Could not fetch block: "+err.Error(), http.StatusInternalServerError)
httputil2.HandleError(w, "Could not fetch block: "+err.Error(), http.StatusInternalServerError)
return
}
if blk == nil {
httputil.HandleError(w, "Block not found", http.StatusNotFound)
httputil2.HandleError(w, "Block not found", http.StatusNotFound)
return
}
if httputil.RespondWithSsz(r) {
if httputil2.RespondWithSsz(r) {
sszResp, err := buildSidecarsSSZResponse(verifiedBlobs)
if err != nil {
httputil.HandleError(w, err.Error(), http.StatusInternalServerError)
httputil2.HandleError(w, err.Error(), http.StatusInternalServerError)
return
}
w.Header().Set(api.VersionHeader, version.String(blk.Version()))
httputil.WriteSsz(w, sszResp, "blob_sidecars.ssz")
w.Header().Set(httputil2.VersionHeader, version.String(blk.Version()))
httputil2.WriteSsz(w, sszResp)
return
}
blkRoot, err := blk.Block().HashTreeRoot()
if err != nil {
httputil.HandleError(w, "Could not hash block: "+err.Error(), http.StatusInternalServerError)
httputil2.HandleError(w, "Could not hash block: "+err.Error(), http.StatusInternalServerError)
return
}
isOptimistic, err := s.OptimisticModeFetcher.IsOptimisticForRoot(ctx, blkRoot)
if err != nil {
httputil.HandleError(w, "Could not check if block is optimistic: "+err.Error(), http.StatusInternalServerError)
httputil2.HandleError(w, "Could not check if block is optimistic: "+err.Error(), http.StatusInternalServerError)
return
}
@@ -92,8 +91,8 @@ func (s *Server) Blobs(w http.ResponseWriter, r *http.Request) {
ExecutionOptimistic: isOptimistic,
Finalized: s.FinalizationFetcher.IsFinalized(ctx, blkRoot),
}
w.Header().Set(api.VersionHeader, version.String(blk.Version()))
httputil.WriteJson(w, resp)
w.Header().Set(httputil2.VersionHeader, version.String(blk.Version()))
httputil2.WriteJson(w, resp)
}
// parseIndices filters out invalid and duplicate blob indices

View File

@@ -14,7 +14,7 @@ import (
"time"
"github.com/ethereum/go-ethereum/common/hexutil"
"github.com/prysmaticlabs/prysm/v5/api"
"github.com/prysmaticlabs/prysm/v5/api/httputil"
"github.com/prysmaticlabs/prysm/v5/api/server/structs"
mockChain "github.com/prysmaticlabs/prysm/v5/beacon-chain/blockchain/testing"
"github.com/prysmaticlabs/prysm/v5/beacon-chain/db/filesystem"
@@ -24,7 +24,6 @@ import (
"github.com/prysmaticlabs/prysm/v5/beacon-chain/verification"
fieldparams "github.com/prysmaticlabs/prysm/v5/config/fieldparams"
"github.com/prysmaticlabs/prysm/v5/config/params"
"github.com/prysmaticlabs/prysm/v5/network/httputil"
eth "github.com/prysmaticlabs/prysm/v5/proto/prysm/v1alpha1"
"github.com/prysmaticlabs/prysm/v5/runtime/version"
"github.com/prysmaticlabs/prysm/v5/testing/assert"
@@ -223,7 +222,7 @@ func TestBlobs(t *testing.T) {
}
s.Blobs(writer, request)
assert.Equal(t, version.String(version.Deneb), writer.Header().Get(api.VersionHeader))
assert.Equal(t, version.String(version.Deneb), writer.Header().Get(httputil.VersionHeader))
assert.Equal(t, http.StatusOK, writer.Code)
resp := &structs.SidecarsResponse{}
require.NoError(t, json.Unmarshal(writer.Body.Bytes(), resp))
@@ -377,7 +376,7 @@ func TestBlobs(t *testing.T) {
BlobStorage: bs,
}
s.Blobs(writer, request)
assert.Equal(t, version.String(version.Deneb), writer.Header().Get(api.VersionHeader))
assert.Equal(t, version.String(version.Deneb), writer.Header().Get(httputil.VersionHeader))
assert.Equal(t, http.StatusOK, writer.Code)
require.Equal(t, len(writer.Body.Bytes()), fieldparams.BlobSidecarSize) // size of each sidecar
// can directly unmarshal to sidecar since there's only 1
@@ -446,7 +445,7 @@ func TestBlobs_Electra(t *testing.T) {
}
s.Blobs(writer, request)
assert.Equal(t, version.String(version.Electra), writer.Header().Get(api.VersionHeader))
assert.Equal(t, version.String(version.Electra), writer.Header().Get(httputil.VersionHeader))
assert.Equal(t, http.StatusOK, writer.Code)
resp := &structs.SidecarsResponse{}
require.NoError(t, json.Unmarshal(writer.Body.Bytes(), resp))
@@ -478,7 +477,7 @@ func TestBlobs_Electra(t *testing.T) {
}
s.Blobs(writer, request)
assert.Equal(t, version.String(version.Electra), writer.Header().Get(api.VersionHeader))
assert.Equal(t, version.String(version.Electra), writer.Header().Get(httputil.VersionHeader))
assert.Equal(t, http.StatusOK, writer.Code)
resp := &structs.SidecarsResponse{}
require.NoError(t, json.Unmarshal(writer.Body.Bytes(), resp))

View File

@@ -9,6 +9,7 @@ go_library(
importpath = "github.com/prysmaticlabs/prysm/v5/beacon-chain/rpc/eth/builder",
visibility = ["//visibility:public"],
deps = [
"//api/httputil:go_default_library",
"//api/server/structs:go_default_library",
"//beacon-chain/blockchain:go_default_library",
"//beacon-chain/core/helpers:go_default_library",
@@ -16,7 +17,6 @@ go_library(
"//beacon-chain/rpc/lookup:go_default_library",
"//config/params:go_default_library",
"//consensus-types/primitives:go_default_library",
"//network/httputil:go_default_library",
"//proto/engine/v1:go_default_library",
"//time/slots:go_default_library",
"@com_github_ethereum_go_ethereum//common/hexutil:go_default_library",
@@ -29,6 +29,7 @@ go_test(
srcs = ["handlers_test.go"],
embed = [":go_default_library"],
deps = [
"//api/httputil:go_default_library",
"//api/server/structs:go_default_library",
"//beacon-chain/blockchain/testing:go_default_library",
"//beacon-chain/rpc/testutil:go_default_library",
@@ -36,7 +37,6 @@ go_test(
"//config/params:go_default_library",
"//consensus-types/primitives:go_default_library",
"//crypto/bls:go_default_library",
"//network/httputil:go_default_library",
"//proto/prysm/v1alpha1:go_default_library",
"//testing/assert:go_default_library",
"//testing/require:go_default_library",

View File

@@ -7,12 +7,12 @@ import (
"github.com/ethereum/go-ethereum/common/hexutil"
"github.com/pkg/errors"
"github.com/prysmaticlabs/prysm/v5/api/httputil"
"github.com/prysmaticlabs/prysm/v5/api/server/structs"
"github.com/prysmaticlabs/prysm/v5/beacon-chain/core/helpers"
"github.com/prysmaticlabs/prysm/v5/beacon-chain/core/transition"
"github.com/prysmaticlabs/prysm/v5/config/params"
"github.com/prysmaticlabs/prysm/v5/consensus-types/primitives"
"github.com/prysmaticlabs/prysm/v5/network/httputil"
enginev1 "github.com/prysmaticlabs/prysm/v5/proto/engine/v1"
"github.com/prysmaticlabs/prysm/v5/time/slots"
)

View File

@@ -9,6 +9,7 @@ import (
"testing"
"github.com/ethereum/go-ethereum/common/hexutil"
"github.com/prysmaticlabs/prysm/v5/api/httputil"
"github.com/prysmaticlabs/prysm/v5/api/server/structs"
mock "github.com/prysmaticlabs/prysm/v5/beacon-chain/blockchain/testing"
"github.com/prysmaticlabs/prysm/v5/beacon-chain/rpc/testutil"
@@ -16,7 +17,6 @@ import (
"github.com/prysmaticlabs/prysm/v5/config/params"
"github.com/prysmaticlabs/prysm/v5/consensus-types/primitives"
"github.com/prysmaticlabs/prysm/v5/crypto/bls"
"github.com/prysmaticlabs/prysm/v5/network/httputil"
eth "github.com/prysmaticlabs/prysm/v5/proto/prysm/v1alpha1"
"github.com/prysmaticlabs/prysm/v5/testing/assert"
"github.com/prysmaticlabs/prysm/v5/testing/require"

View File

@@ -6,11 +6,11 @@ go_library(
importpath = "github.com/prysmaticlabs/prysm/v5/beacon-chain/rpc/eth/config",
visibility = ["//visibility:public"],
deps = [
"//api/httputil:go_default_library",
"//api/server/structs:go_default_library",
"//config/params:go_default_library",
"//monitoring/tracing/trace:go_default_library",
"//network/forks:go_default_library",
"//network/httputil:go_default_library",
"@com_github_ethereum_go_ethereum//common/hexutil:go_default_library",
],
)

View File

@@ -8,11 +8,11 @@ import (
"strings"
"github.com/ethereum/go-ethereum/common/hexutil"
httputil2 "github.com/prysmaticlabs/prysm/v5/api/httputil"
"github.com/prysmaticlabs/prysm/v5/api/server/structs"
"github.com/prysmaticlabs/prysm/v5/config/params"
"github.com/prysmaticlabs/prysm/v5/monitoring/tracing/trace"
"github.com/prysmaticlabs/prysm/v5/network/forks"
"github.com/prysmaticlabs/prysm/v5/network/httputil"
)
// GetDepositContract retrieves deposit contract address and genesis fork version.
@@ -20,7 +20,7 @@ func GetDepositContract(w http.ResponseWriter, r *http.Request) {
_, span := trace.StartSpan(r.Context(), "config.GetDepositContract")
defer span.End()
httputil.WriteJson(w, &structs.GetDepositContractResponse{
httputil2.WriteJson(w, &structs.GetDepositContractResponse{
Data: &structs.DepositContractData{
ChainId: strconv.FormatUint(params.BeaconConfig().DepositChainID, 10),
Address: params.BeaconConfig().DepositContractAddress,
@@ -35,7 +35,7 @@ func GetForkSchedule(w http.ResponseWriter, r *http.Request) {
schedule := params.BeaconConfig().ForkVersionSchedule
if len(schedule) == 0 {
httputil.WriteJson(w, &structs.GetForkScheduleResponse{
httputil2.WriteJson(w, &structs.GetForkScheduleResponse{
Data: make([]*structs.Fork, 0),
})
return
@@ -59,7 +59,7 @@ func GetForkSchedule(w http.ResponseWriter, r *http.Request) {
}
}
httputil.WriteJson(w, &structs.GetForkScheduleResponse{
httputil2.WriteJson(w, &structs.GetForkScheduleResponse{
Data: chainForks,
})
}
@@ -74,10 +74,10 @@ func GetSpec(w http.ResponseWriter, r *http.Request) {
data, err := prepareConfigSpec()
if err != nil {
httputil.HandleError(w, "Could not prepare config spec: "+err.Error(), http.StatusInternalServerError)
httputil2.HandleError(w, "Could not prepare config spec: "+err.Error(), http.StatusInternalServerError)
return
}
httputil.WriteJson(w, &structs.GetSpecResponse{Data: data})
httputil2.WriteJson(w, &structs.GetSpecResponse{Data: data})
}
func prepareConfigSpec() (map[string]string, error) {

View File

@@ -9,7 +9,7 @@ go_library(
importpath = "github.com/prysmaticlabs/prysm/v5/beacon-chain/rpc/eth/debug",
visibility = ["//visibility:public"],
deps = [
"//api:go_default_library",
"//api/httputil:go_default_library",
"//api/server/structs:go_default_library",
"//beacon-chain/blockchain:go_default_library",
"//beacon-chain/db:go_default_library",
@@ -17,7 +17,6 @@ go_library(
"//beacon-chain/rpc/eth/shared:go_default_library",
"//beacon-chain/rpc/lookup:go_default_library",
"//monitoring/tracing/trace:go_default_library",
"//network/httputil:go_default_library",
"//runtime/version:go_default_library",
"@com_github_ethereum_go_ethereum//common/hexutil:go_default_library",
],
@@ -28,7 +27,7 @@ go_test(
srcs = ["handlers_test.go"],
embed = [":go_default_library"],
deps = [
"//api:go_default_library",
"//api/httputil:go_default_library",
"//api/server/structs:go_default_library",
"//beacon-chain/blockchain/testing:go_default_library",
"//beacon-chain/db/testing:go_default_library",

View File

@@ -7,12 +7,11 @@ import (
"net/http"
"github.com/ethereum/go-ethereum/common/hexutil"
"github.com/prysmaticlabs/prysm/v5/api"
httputil2 "github.com/prysmaticlabs/prysm/v5/api/httputil"
"github.com/prysmaticlabs/prysm/v5/api/server/structs"
"github.com/prysmaticlabs/prysm/v5/beacon-chain/rpc/eth/helpers"
"github.com/prysmaticlabs/prysm/v5/beacon-chain/rpc/eth/shared"
"github.com/prysmaticlabs/prysm/v5/monitoring/tracing/trace"
"github.com/prysmaticlabs/prysm/v5/network/httputil"
"github.com/prysmaticlabs/prysm/v5/runtime/version"
)
@@ -25,11 +24,11 @@ func (s *Server) GetBeaconStateV2(w http.ResponseWriter, r *http.Request) {
stateId := r.PathValue("state_id")
if stateId == "" {
httputil.HandleError(w, "state_id is required in URL params", http.StatusBadRequest)
httputil2.HandleError(w, "state_id is required in URL params", http.StatusBadRequest)
return
}
if httputil.RespondWithSsz(r) {
if httputil2.RespondWithSsz(r) {
s.getBeaconStateSSZV2(ctx, w, []byte(stateId))
} else {
s.getBeaconStateV2(ctx, w, []byte(stateId))
@@ -46,12 +45,12 @@ func (s *Server) getBeaconStateV2(ctx context.Context, w http.ResponseWriter, id
isOptimistic, err := helpers.IsOptimistic(ctx, id, s.OptimisticModeFetcher, s.Stater, s.ChainInfoFetcher, s.BeaconDB)
if err != nil {
httputil.HandleError(w, "Could not check if state is optimistic: "+err.Error(), http.StatusInternalServerError)
httputil2.HandleError(w, "Could not check if state is optimistic: "+err.Error(), http.StatusInternalServerError)
return
}
blockRoot, err := st.LatestBlockHeader().HashTreeRoot()
if err != nil {
httputil.HandleError(w, "Could not calculate root of latest block header: "+err.Error(), http.StatusInternalServerError)
httputil2.HandleError(w, "Could not calculate root of latest block header: "+err.Error(), http.StatusInternalServerError)
return
}
isFinalized := s.FinalizationFetcher.IsFinalized(ctx, blockRoot)
@@ -61,53 +60,53 @@ func (s *Server) getBeaconStateV2(ctx context.Context, w http.ResponseWriter, id
case version.Phase0:
respSt, err = structs.BeaconStateFromConsensus(st)
if err != nil {
httputil.HandleError(w, errMsgStateFromConsensus+": "+err.Error(), http.StatusInternalServerError)
httputil2.HandleError(w, errMsgStateFromConsensus+": "+err.Error(), http.StatusInternalServerError)
return
}
case version.Altair:
respSt, err = structs.BeaconStateAltairFromConsensus(st)
if err != nil {
httputil.HandleError(w, errMsgStateFromConsensus+": "+err.Error(), http.StatusInternalServerError)
httputil2.HandleError(w, errMsgStateFromConsensus+": "+err.Error(), http.StatusInternalServerError)
return
}
case version.Bellatrix:
respSt, err = structs.BeaconStateBellatrixFromConsensus(st)
if err != nil {
httputil.HandleError(w, errMsgStateFromConsensus+": "+err.Error(), http.StatusInternalServerError)
httputil2.HandleError(w, errMsgStateFromConsensus+": "+err.Error(), http.StatusInternalServerError)
return
}
case version.Capella:
respSt, err = structs.BeaconStateCapellaFromConsensus(st)
if err != nil {
httputil.HandleError(w, errMsgStateFromConsensus+": "+err.Error(), http.StatusInternalServerError)
httputil2.HandleError(w, errMsgStateFromConsensus+": "+err.Error(), http.StatusInternalServerError)
return
}
case version.Deneb:
respSt, err = structs.BeaconStateDenebFromConsensus(st)
if err != nil {
httputil.HandleError(w, errMsgStateFromConsensus+": "+err.Error(), http.StatusInternalServerError)
httputil2.HandleError(w, errMsgStateFromConsensus+": "+err.Error(), http.StatusInternalServerError)
return
}
case version.Electra:
respSt, err = structs.BeaconStateElectraFromConsensus(st)
if err != nil {
httputil.HandleError(w, errMsgStateFromConsensus+": "+err.Error(), http.StatusInternalServerError)
httputil2.HandleError(w, errMsgStateFromConsensus+": "+err.Error(), http.StatusInternalServerError)
return
}
case version.Fulu:
respSt, err = structs.BeaconStateFuluFromConsensus(st)
if err != nil {
httputil.HandleError(w, errMsgStateFromConsensus+": "+err.Error(), http.StatusInternalServerError)
httputil2.HandleError(w, errMsgStateFromConsensus+": "+err.Error(), http.StatusInternalServerError)
return
}
default:
httputil.HandleError(w, "Unsupported state version", http.StatusInternalServerError)
httputil2.HandleError(w, "Unsupported state version", http.StatusInternalServerError)
return
}
jsonBytes, err := json.Marshal(respSt)
if err != nil {
httputil.HandleError(w, "Could not marshal state into JSON: "+err.Error(), http.StatusInternalServerError)
httputil2.HandleError(w, "Could not marshal state into JSON: "+err.Error(), http.StatusInternalServerError)
return
}
ver := version.String(st.Version())
@@ -117,8 +116,8 @@ func (s *Server) getBeaconStateV2(ctx context.Context, w http.ResponseWriter, id
Finalized: isFinalized,
Data: jsonBytes,
}
w.Header().Set(api.VersionHeader, ver)
httputil.WriteJson(w, resp)
w.Header().Set(httputil2.VersionHeader, ver)
httputil2.WriteJson(w, resp)
}
// getBeaconStateSSZV2 returns the SSZ-serialized version of the full beacon state object for given state ID.
@@ -130,11 +129,11 @@ func (s *Server) getBeaconStateSSZV2(ctx context.Context, w http.ResponseWriter,
}
sszState, err := st.MarshalSSZ()
if err != nil {
httputil.HandleError(w, "Could not marshal state into SSZ: "+err.Error(), http.StatusInternalServerError)
httputil2.HandleError(w, "Could not marshal state into SSZ: "+err.Error(), http.StatusInternalServerError)
return
}
w.Header().Set(api.VersionHeader, version.String(st.Version()))
httputil.WriteSsz(w, sszState, "beacon_state.ssz")
w.Header().Set(httputil2.VersionHeader, version.String(st.Version()))
httputil2.WriteSsz(w, sszState)
}
// GetForkChoiceHeadsV2 retrieves the leaves of the current fork choice tree.
@@ -149,7 +148,7 @@ func (s *Server) GetForkChoiceHeadsV2(w http.ResponseWriter, r *http.Request) {
for i := range headRoots {
isOptimistic, err := s.OptimisticModeFetcher.IsOptimisticForRoot(ctx, headRoots[i])
if err != nil {
httputil.HandleError(w, "Could not check if head is optimistic: "+err.Error(), http.StatusInternalServerError)
httputil2.HandleError(w, "Could not check if head is optimistic: "+err.Error(), http.StatusInternalServerError)
return
}
resp.Data[i] = &structs.ForkChoiceHead{
@@ -159,7 +158,7 @@ func (s *Server) GetForkChoiceHeadsV2(w http.ResponseWriter, r *http.Request) {
}
}
httputil.WriteJson(w, resp)
httputil2.WriteJson(w, resp)
}
// GetForkChoice returns a dump fork choice store.
@@ -169,7 +168,7 @@ func (s *Server) GetForkChoice(w http.ResponseWriter, r *http.Request) {
dump, err := s.ForkchoiceFetcher.ForkChoiceDump(ctx)
if err != nil {
httputil.HandleError(w, "Could not get forkchoice dump: "+err.Error(), http.StatusInternalServerError)
httputil2.HandleError(w, "Could not get forkchoice dump: "+err.Error(), http.StatusInternalServerError)
return
}
@@ -206,5 +205,5 @@ func (s *Server) GetForkChoice(w http.ResponseWriter, r *http.Request) {
HeadRoot: hexutil.Encode(dump.HeadRoot),
},
}
httputil.WriteJson(w, resp)
httputil2.WriteJson(w, resp)
}

View File

@@ -9,7 +9,7 @@ import (
"testing"
"github.com/ethereum/go-ethereum/common/hexutil"
"github.com/prysmaticlabs/prysm/v5/api"
"github.com/prysmaticlabs/prysm/v5/api/httputil"
"github.com/prysmaticlabs/prysm/v5/api/server/structs"
blockchainmock "github.com/prysmaticlabs/prysm/v5/beacon-chain/blockchain/testing"
dbtest "github.com/prysmaticlabs/prysm/v5/beacon-chain/db/testing"
@@ -311,13 +311,13 @@ func TestGetBeaconStateSSZV2(t *testing.T) {
request := httptest.NewRequest(http.MethodGet, "http://example.com/eth/v2/debug/beacon/states/{state_id}", nil)
request.SetPathValue("state_id", "head")
request.Header.Set("Accept", api.OctetStreamMediaType)
request.Header.Set("Accept", httputil.OctetStreamMediaType)
writer := httptest.NewRecorder()
writer.Body = &bytes.Buffer{}
s.GetBeaconStateV2(writer, request)
require.Equal(t, http.StatusOK, writer.Code)
assert.Equal(t, version.String(version.Phase0), writer.Header().Get(api.VersionHeader))
assert.Equal(t, version.String(version.Phase0), writer.Header().Get(httputil.VersionHeader))
sszExpected, err := fakeState.MarshalSSZ()
require.NoError(t, err)
assert.DeepEqual(t, sszExpected, writer.Body.Bytes())
@@ -335,13 +335,13 @@ func TestGetBeaconStateSSZV2(t *testing.T) {
request := httptest.NewRequest(http.MethodGet, "http://example.com/eth/v2/debug/beacon/states/{state_id}", nil)
request.SetPathValue("state_id", "head")
request.Header.Set("Accept", api.OctetStreamMediaType)
request.Header.Set("Accept", httputil.OctetStreamMediaType)
writer := httptest.NewRecorder()
writer.Body = &bytes.Buffer{}
s.GetBeaconStateV2(writer, request)
require.Equal(t, http.StatusOK, writer.Code)
assert.Equal(t, version.String(version.Altair), writer.Header().Get(api.VersionHeader))
assert.Equal(t, version.String(version.Altair), writer.Header().Get(httputil.VersionHeader))
sszExpected, err := fakeState.MarshalSSZ()
require.NoError(t, err)
assert.DeepEqual(t, sszExpected, writer.Body.Bytes())
@@ -359,13 +359,13 @@ func TestGetBeaconStateSSZV2(t *testing.T) {
request := httptest.NewRequest(http.MethodGet, "http://example.com/eth/v2/debug/beacon/states/{state_id}", nil)
request.SetPathValue("state_id", "head")
request.Header.Set("Accept", api.OctetStreamMediaType)
request.Header.Set("Accept", httputil.OctetStreamMediaType)
writer := httptest.NewRecorder()
writer.Body = &bytes.Buffer{}
s.GetBeaconStateV2(writer, request)
require.Equal(t, http.StatusOK, writer.Code)
assert.Equal(t, version.String(version.Bellatrix), writer.Header().Get(api.VersionHeader))
assert.Equal(t, version.String(version.Bellatrix), writer.Header().Get(httputil.VersionHeader))
sszExpected, err := fakeState.MarshalSSZ()
require.NoError(t, err)
assert.DeepEqual(t, sszExpected, writer.Body.Bytes())
@@ -383,13 +383,13 @@ func TestGetBeaconStateSSZV2(t *testing.T) {
request := httptest.NewRequest(http.MethodGet, "http://example.com/eth/v2/debug/beacon/states/{state_id}", nil)
request.SetPathValue("state_id", "head")
request.Header.Set("Accept", api.OctetStreamMediaType)
request.Header.Set("Accept", httputil.OctetStreamMediaType)
writer := httptest.NewRecorder()
writer.Body = &bytes.Buffer{}
s.GetBeaconStateV2(writer, request)
require.Equal(t, http.StatusOK, writer.Code)
assert.Equal(t, version.String(version.Capella), writer.Header().Get(api.VersionHeader))
assert.Equal(t, version.String(version.Capella), writer.Header().Get(httputil.VersionHeader))
sszExpected, err := fakeState.MarshalSSZ()
require.NoError(t, err)
assert.DeepEqual(t, sszExpected, writer.Body.Bytes())
@@ -407,13 +407,13 @@ func TestGetBeaconStateSSZV2(t *testing.T) {
request := httptest.NewRequest(http.MethodGet, "http://example.com/eth/v2/debug/beacon/states/{state_id}", nil)
request.SetPathValue("state_id", "head")
request.Header.Set("Accept", api.OctetStreamMediaType)
request.Header.Set("Accept", httputil.OctetStreamMediaType)
writer := httptest.NewRecorder()
writer.Body = &bytes.Buffer{}
s.GetBeaconStateV2(writer, request)
require.Equal(t, http.StatusOK, writer.Code)
assert.Equal(t, version.String(version.Deneb), writer.Header().Get(api.VersionHeader))
assert.Equal(t, version.String(version.Deneb), writer.Header().Get(httputil.VersionHeader))
sszExpected, err := fakeState.MarshalSSZ()
require.NoError(t, err)
assert.DeepEqual(t, sszExpected, writer.Body.Bytes())

View File

@@ -10,7 +10,7 @@ go_library(
importpath = "github.com/prysmaticlabs/prysm/v5/beacon-chain/rpc/eth/events",
visibility = ["//visibility:public"],
deps = [
"//api:go_default_library",
"//api/httputil:go_default_library",
"//api/server/structs:go_default_library",
"//beacon-chain/blockchain:go_default_library",
"//beacon-chain/cache:go_default_library",
@@ -25,7 +25,6 @@ go_library(
"//consensus-types/payload-attribute:go_default_library",
"//consensus-types/primitives:go_default_library",
"//monitoring/tracing/trace:go_default_library",
"//network/httputil:go_default_library",
"//proto/engine/v1:go_default_library",
"//proto/eth/v1:go_default_library",
"//proto/prysm/v1alpha1:go_default_library",

View File

@@ -15,7 +15,7 @@ import (
"github.com/pkg/errors"
"github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/client_golang/prometheus/promauto"
"github.com/prysmaticlabs/prysm/v5/api"
"github.com/prysmaticlabs/prysm/v5/api/httputil"
"github.com/prysmaticlabs/prysm/v5/api/server/structs"
"github.com/prysmaticlabs/prysm/v5/beacon-chain/core/feed"
"github.com/prysmaticlabs/prysm/v5/beacon-chain/core/feed/operation"
@@ -28,7 +28,6 @@ import (
payloadattribute "github.com/prysmaticlabs/prysm/v5/consensus-types/payload-attribute"
"github.com/prysmaticlabs/prysm/v5/consensus-types/primitives"
"github.com/prysmaticlabs/prysm/v5/monitoring/tracing/trace"
"github.com/prysmaticlabs/prysm/v5/network/httputil"
engine "github.com/prysmaticlabs/prysm/v5/proto/engine/v1"
ethpb "github.com/prysmaticlabs/prysm/v5/proto/eth/v1"
eth "github.com/prysmaticlabs/prysm/v5/proto/prysm/v1alpha1"
@@ -193,7 +192,7 @@ func (s *Server) StreamEvents(w http.ResponseWriter, r *http.Request) {
buffSize = DefaultEventFeedDepth
}
api.SetSSEHeaders(w)
httputil.SetSSEHeaders(w)
sw := newStreamingResponseController(w, timeout)
ctx, cancel := context.WithCancel(ctx)
defer cancel()

View File

@@ -53,7 +53,7 @@ func IsOptimistic(
}
return optimisticModeFetcher.IsOptimisticForRoot(ctx, bytesutil.ToBytes32(jcp.Root))
default:
if len(stateIdString) >= 2 && stateIdString[:2] == "0x" {
if bytesutil.IsHex(stateId) {
id, err := hexutil.Decode(stateIdString)
if err != nil {
return false, err

View File

@@ -9,22 +9,25 @@ go_library(
importpath = "github.com/prysmaticlabs/prysm/v5/beacon-chain/rpc/eth/light-client",
visibility = ["//beacon-chain:__subpackages__"],
deps = [
"//api:go_default_library",
"//api/httputil:go_default_library",
"//api/server/structs:go_default_library",
"//beacon-chain/blockchain:go_default_library",
"//beacon-chain/core/light-client:go_default_library",
"//beacon-chain/core/signing:go_default_library",
"//beacon-chain/db:go_default_library",
"//beacon-chain/rpc/eth/shared:go_default_library",
"//beacon-chain/rpc/lookup:go_default_library",
"//config/features:go_default_library",
"//config/params:go_default_library",
"//consensus-types/interfaces:go_default_library",
"//encoding/bytesutil:go_default_library",
"//monitoring/tracing/trace:go_default_library",
"//network/httputil:go_default_library",
"//network/forks:go_default_library",
"//runtime/version:go_default_library",
"//time/slots:go_default_library",
"@com_github_ethereum_go_ethereum//common/hexutil:go_default_library",
"@com_github_pkg_errors//:go_default_library",
"@com_github_wealdtech_go_bytesutil//:go_default_library",
"@com_github_prysmaticlabs_fastssz//:go_default_library",
],
)
@@ -56,5 +59,6 @@ go_test(
"//testing/require:go_default_library",
"//testing/util:go_default_library",
"@com_github_ethereum_go_ethereum//common/hexutil:go_default_library",
"@com_github_prysmaticlabs_fastssz//:go_default_library",
],
)

View File

@@ -8,23 +8,26 @@ import (
"github.com/ethereum/go-ethereum/common/hexutil"
"github.com/pkg/errors"
"github.com/prysmaticlabs/prysm/v5/api"
ssz "github.com/prysmaticlabs/fastssz"
httputil2 "github.com/prysmaticlabs/prysm/v5/api/httputil"
"github.com/prysmaticlabs/prysm/v5/api/server/structs"
lightclient "github.com/prysmaticlabs/prysm/v5/beacon-chain/core/light-client"
"github.com/prysmaticlabs/prysm/v5/beacon-chain/core/signing"
"github.com/prysmaticlabs/prysm/v5/beacon-chain/rpc/eth/shared"
"github.com/prysmaticlabs/prysm/v5/config/features"
"github.com/prysmaticlabs/prysm/v5/config/params"
"github.com/prysmaticlabs/prysm/v5/consensus-types/interfaces"
"github.com/prysmaticlabs/prysm/v5/encoding/bytesutil"
"github.com/prysmaticlabs/prysm/v5/monitoring/tracing/trace"
"github.com/prysmaticlabs/prysm/v5/network/httputil"
"github.com/prysmaticlabs/prysm/v5/network/forks"
"github.com/prysmaticlabs/prysm/v5/runtime/version"
"github.com/wealdtech/go-bytesutil"
"github.com/prysmaticlabs/prysm/v5/time/slots"
)
// GetLightClientBootstrap - implements https://github.com/ethereum/beacon-APIs/blob/263f4ed6c263c967f13279c7a9f5629b51c5fc55/apis/beacon/light_client/bootstrap.yaml
func (s *Server) GetLightClientBootstrap(w http.ResponseWriter, req *http.Request) {
if !features.Get().EnableLightClient {
httputil.HandleError(w, "Light client feature flag is not enabled", http.StatusNotFound)
httputil2.HandleError(w, "Light client feature flag is not enabled", http.StatusNotFound)
return
}
@@ -35,48 +38,48 @@ func (s *Server) GetLightClientBootstrap(w http.ResponseWriter, req *http.Reques
// Get the block
blockRootParam, err := hexutil.Decode(req.PathValue("block_root"))
if err != nil {
httputil.HandleError(w, "Invalid block root: "+err.Error(), http.StatusBadRequest)
httputil2.HandleError(w, "Invalid block root: "+err.Error(), http.StatusBadRequest)
return
}
blockRoot := bytesutil.ToBytes32(blockRootParam)
bootstrap, err := s.BeaconDB.LightClientBootstrap(ctx, blockRoot[:])
if err != nil {
httputil.HandleError(w, "Could not get light client bootstrap: "+err.Error(), http.StatusInternalServerError)
httputil2.HandleError(w, "Could not get light client bootstrap: "+err.Error(), http.StatusInternalServerError)
return
}
if bootstrap == nil {
httputil.HandleError(w, "Light client bootstrap not found", http.StatusNotFound)
httputil2.HandleError(w, "Light client bootstrap not found", http.StatusNotFound)
return
}
w.Header().Set(api.VersionHeader, version.String(bootstrap.Version()))
w.Header().Set(httputil2.VersionHeader, version.String(bootstrap.Version()))
if httputil.RespondWithSsz(req) {
if httputil2.RespondWithSsz(req) {
ssz, err := bootstrap.MarshalSSZ()
if err != nil {
httputil.HandleError(w, "Could not marshal bootstrap to SSZ: "+err.Error(), http.StatusInternalServerError)
httputil2.HandleError(w, "Could not marshal bootstrap to SSZ: "+err.Error(), http.StatusInternalServerError)
return
}
httputil.WriteSsz(w, ssz, "light_client_bootstrap.ssz")
httputil2.WriteSsz(w, ssz)
} else {
data, err := structs.LightClientBootstrapFromConsensus(bootstrap)
if err != nil {
httputil.HandleError(w, "Could not marshal bootstrap to JSON: "+err.Error(), http.StatusInternalServerError)
httputil2.HandleError(w, "Could not marshal bootstrap to JSON: "+err.Error(), http.StatusInternalServerError)
return
}
response := &structs.LightClientBootstrapResponse{
Version: version.String(bootstrap.Version()),
Data: data,
}
httputil.WriteJson(w, response)
httputil2.WriteJson(w, response)
}
}
// GetLightClientUpdatesByRange - implements https://github.com/ethereum/beacon-APIs/blob/263f4ed6c263c967f13279c7a9f5629b51c5fc55/apis/beacon/light_client/updates.yaml
func (s *Server) GetLightClientUpdatesByRange(w http.ResponseWriter, req *http.Request) {
if !features.Get().EnableLightClient {
httputil.HandleError(w, "Light client feature flag is not enabled", http.StatusNotFound)
httputil2.HandleError(w, "Light client feature flag is not enabled", http.StatusNotFound)
return
}
@@ -89,7 +92,7 @@ func (s *Server) GetLightClientUpdatesByRange(w http.ResponseWriter, req *http.R
if !gotCount {
return
} else if count == 0 {
httputil.HandleError(w, fmt.Sprintf("Got invalid 'count' query variable '%d': count must be greater than 0", count), http.StatusBadRequest)
httputil2.HandleError(w, fmt.Sprintf("Got invalid 'count' query variable '%d': count must be greater than 0", count), http.StatusBadRequest)
return
}
@@ -107,37 +110,89 @@ func (s *Server) GetLightClientUpdatesByRange(w http.ResponseWriter, req *http.R
// get updates
updatesMap, err := s.BeaconDB.LightClientUpdates(ctx, startPeriod, endPeriod)
if err != nil {
httputil.HandleError(w, "Could not get light client updates from DB: "+err.Error(), http.StatusInternalServerError)
httputil2.HandleError(w, "Could not get light client updates from DB: "+err.Error(), http.StatusInternalServerError)
return
}
updates := make([]*structs.LightClientUpdateResponse, 0, len(updatesMap))
if httputil2.RespondWithSsz(req) {
w.Header().Set("Content-Type", "application/octet-stream")
for i := startPeriod; i <= endPeriod; i++ {
update, ok := updatesMap[i]
if !ok {
// Only return the first contiguous range of updates
break
for i := startPeriod; i <= endPeriod; i++ {
if ctx.Err() != nil {
httputil2.HandleError(w, "Context error: "+ctx.Err().Error(), http.StatusInternalServerError)
}
update, ok := updatesMap[i]
if !ok {
// Only return the first contiguous range of updates
break
}
updateSlot := update.AttestedHeader().Beacon().Slot
updateEpoch := slots.ToEpoch(updateSlot)
updateFork, err := forks.Fork(updateEpoch)
if err != nil {
httputil2.HandleError(w, "Could not get fork Version: "+err.Error(), http.StatusInternalServerError)
return
}
forkDigest, err := signing.ComputeForkDigest(updateFork.CurrentVersion, params.BeaconConfig().GenesisValidatorsRoot[:])
if err != nil {
httputil2.HandleError(w, "Could not compute fork digest: "+err.Error(), http.StatusInternalServerError)
return
}
updateSSZ, err := update.MarshalSSZ()
if err != nil {
httputil2.HandleError(w, "Could not marshal update to SSZ: "+err.Error(), http.StatusInternalServerError)
return
}
var chunkLength []byte
chunkLength = ssz.MarshalUint64(chunkLength, uint64(len(updateSSZ)+4))
if _, err := w.Write(chunkLength); err != nil {
httputil2.HandleError(w, "Could not write chunk length: "+err.Error(), http.StatusInternalServerError)
}
if _, err := w.Write(forkDigest[:]); err != nil {
httputil2.HandleError(w, "Could not write fork digest: "+err.Error(), http.StatusInternalServerError)
}
if _, err := w.Write(updateSSZ); err != nil {
httputil2.HandleError(w, "Could not write update SSZ: "+err.Error(), http.StatusInternalServerError)
}
}
} else {
updates := make([]*structs.LightClientUpdateResponse, 0, len(updatesMap))
for i := startPeriod; i <= endPeriod; i++ {
if ctx.Err() != nil {
httputil2.HandleError(w, "Context error: "+ctx.Err().Error(), http.StatusInternalServerError)
}
update, ok := updatesMap[i]
if !ok {
// Only return the first contiguous range of updates
break
}
updateJson, err := structs.LightClientUpdateFromConsensus(update)
if err != nil {
httputil2.HandleError(w, "Could not convert light client update: "+err.Error(), http.StatusInternalServerError)
return
}
updateResponse := &structs.LightClientUpdateResponse{
Version: version.String(update.Version()),
Data: updateJson,
}
updates = append(updates, updateResponse)
}
updateJson, err := structs.LightClientUpdateFromConsensus(update)
if err != nil {
httputil.HandleError(w, "Could not convert light client update: "+err.Error(), http.StatusInternalServerError)
return
}
updateResponse := &structs.LightClientUpdateResponse{
Version: version.String(update.Version()),
Data: updateJson,
}
updates = append(updates, updateResponse)
httputil2.WriteJson(w, updates)
}
httputil.WriteJson(w, updates)
}
// GetLightClientFinalityUpdate - implements https://github.com/ethereum/beacon-APIs/blob/263f4ed6c263c967f13279c7a9f5629b51c5fc55/apis/beacon/light_client/finality_update.yaml
func (s *Server) GetLightClientFinalityUpdate(w http.ResponseWriter, req *http.Request) {
if !features.Get().EnableLightClient {
httputil.HandleError(w, "Light client feature flag is not enabled", http.StatusNotFound)
httputil2.HandleError(w, "Light client feature flag is not enabled", http.StatusNotFound)
return
}
@@ -155,7 +210,7 @@ func (s *Server) GetLightClientFinalityUpdate(w http.ResponseWriter, req *http.R
st, err := s.Stater.StateBySlot(ctx, block.Block().Slot())
if err != nil {
httputil.HandleError(w, "Could not get state: "+err.Error(), http.StatusInternalServerError)
httputil2.HandleError(w, "Could not get state: "+err.Error(), http.StatusInternalServerError)
return
}
@@ -167,14 +222,14 @@ func (s *Server) GetLightClientFinalityUpdate(w http.ResponseWriter, req *http.R
attestedSlot := attestedBlock.Block().Slot()
attestedState, err := s.Stater.StateBySlot(ctx, attestedSlot)
if err != nil {
httputil.HandleError(w, "Could not get attested state: "+err.Error(), http.StatusInternalServerError)
httputil2.HandleError(w, "Could not get attested state: "+err.Error(), http.StatusInternalServerError)
return
}
var finalizedBlock interfaces.ReadOnlySignedBeaconBlock
finalizedCheckpoint := attestedState.FinalizedCheckpoint()
if finalizedCheckpoint == nil {
httputil.HandleError(w, "Attested state does not have a finalized checkpoint", http.StatusInternalServerError)
httputil2.HandleError(w, "Attested state does not have a finalized checkpoint", http.StatusInternalServerError)
return
}
finalizedRoot := bytesutil.ToBytes32(finalizedCheckpoint.Root)
@@ -185,35 +240,35 @@ func (s *Server) GetLightClientFinalityUpdate(w http.ResponseWriter, req *http.R
update, err := lightclient.NewLightClientFinalityUpdateFromBeaconState(ctx, s.ChainInfoFetcher.CurrentSlot(), st, block, attestedState, attestedBlock, finalizedBlock)
if err != nil {
httputil.HandleError(w, "Could not get light client finality update: "+err.Error(), http.StatusInternalServerError)
httputil2.HandleError(w, "Could not get light client finality update: "+err.Error(), http.StatusInternalServerError)
return
}
if httputil.RespondWithSsz(req) {
if httputil2.RespondWithSsz(req) {
ssz, err := update.MarshalSSZ()
if err != nil {
httputil.HandleError(w, "Could not marshal finality update to SSZ: "+err.Error(), http.StatusInternalServerError)
httputil2.HandleError(w, "Could not marshal finality update to SSZ: "+err.Error(), http.StatusInternalServerError)
return
}
httputil.WriteSsz(w, ssz, "light_client_finality_update.ssz")
httputil2.WriteSsz(w, ssz)
} else {
updateStruct, err := structs.LightClientFinalityUpdateFromConsensus(update)
if err != nil {
httputil.HandleError(w, "Could not convert light client finality update to API struct: "+err.Error(), http.StatusInternalServerError)
httputil2.HandleError(w, "Could not convert light client finality update to API struct: "+err.Error(), http.StatusInternalServerError)
return
}
response := &structs.LightClientFinalityUpdateResponse{
Version: version.String(attestedState.Version()),
Data: updateStruct,
}
httputil.WriteJson(w, response)
httputil2.WriteJson(w, response)
}
}
// GetLightClientOptimisticUpdate - implements https://github.com/ethereum/beacon-APIs/blob/263f4ed6c263c967f13279c7a9f5629b51c5fc55/apis/beacon/light_client/optimistic_update.yaml
func (s *Server) GetLightClientOptimisticUpdate(w http.ResponseWriter, req *http.Request) {
if !features.Get().EnableLightClient {
httputil.HandleError(w, "Light client feature flag is not enabled", http.StatusNotFound)
httputil2.HandleError(w, "Light client feature flag is not enabled", http.StatusNotFound)
return
}
@@ -226,50 +281,50 @@ func (s *Server) GetLightClientOptimisticUpdate(w http.ResponseWriter, req *http
}
st, err := s.Stater.StateBySlot(ctx, block.Block().Slot())
if err != nil {
httputil.HandleError(w, "could not get state: "+err.Error(), http.StatusInternalServerError)
httputil2.HandleError(w, "could not get state: "+err.Error(), http.StatusInternalServerError)
return
}
attestedRoot := block.Block().ParentRoot()
attestedBlock, err := s.Blocker.Block(ctx, attestedRoot[:])
if err != nil {
httputil.HandleError(w, "Could not get attested block: "+err.Error(), http.StatusInternalServerError)
httputil2.HandleError(w, "Could not get attested block: "+err.Error(), http.StatusInternalServerError)
return
}
if attestedBlock == nil {
httputil.HandleError(w, "Attested block is nil", http.StatusInternalServerError)
httputil2.HandleError(w, "Attested block is nil", http.StatusInternalServerError)
return
}
attestedSlot := attestedBlock.Block().Slot()
attestedState, err := s.Stater.StateBySlot(ctx, attestedSlot)
if err != nil {
httputil.HandleError(w, "Could not get attested state: "+err.Error(), http.StatusInternalServerError)
httputil2.HandleError(w, "Could not get attested state: "+err.Error(), http.StatusInternalServerError)
return
}
update, err := lightclient.NewLightClientOptimisticUpdateFromBeaconState(ctx, s.ChainInfoFetcher.CurrentSlot(), st, block, attestedState, attestedBlock)
if err != nil {
httputil.HandleError(w, "Could not get light client optimistic update: "+err.Error(), http.StatusInternalServerError)
httputil2.HandleError(w, "Could not get light client optimistic update: "+err.Error(), http.StatusInternalServerError)
return
}
if httputil.RespondWithSsz(req) {
if httputil2.RespondWithSsz(req) {
ssz, err := update.MarshalSSZ()
if err != nil {
httputil.HandleError(w, "Could not marshal optimistic update to SSZ: "+err.Error(), http.StatusInternalServerError)
httputil2.HandleError(w, "Could not marshal optimistic update to SSZ: "+err.Error(), http.StatusInternalServerError)
return
}
httputil.WriteSsz(w, ssz, "light_client_optimistic_update.ssz")
httputil2.WriteSsz(w, ssz)
} else {
updateStruct, err := structs.LightClientOptimisticUpdateFromConsensus(update)
if err != nil {
httputil.HandleError(w, "Could not convert light client optimistic update to API struct: "+err.Error(), http.StatusInternalServerError)
httputil2.HandleError(w, "Could not convert light client optimistic update to API struct: "+err.Error(), http.StatusInternalServerError)
return
}
response := &structs.LightClientOptimisticUpdateResponse{
Version: version.String(attestedState.Version()),
Data: updateStruct,
}
httputil.WriteJson(w, response)
httputil2.WriteJson(w, response)
}
}

View File

@@ -12,6 +12,7 @@ import (
"testing"
"github.com/ethereum/go-ethereum/common/hexutil"
ssz "github.com/prysmaticlabs/fastssz"
"github.com/prysmaticlabs/prysm/v5/api/server/structs"
mock "github.com/prysmaticlabs/prysm/v5/beacon-chain/blockchain/testing"
"github.com/prysmaticlabs/prysm/v5/beacon-chain/core/helpers"
@@ -511,6 +512,44 @@ func TestLightClientHandler_GetLightClientByRange(t *testing.T) {
require.DeepEqual(t, updateJson, resp.Updates[0].Data)
})
t.Run("altair ssz", func(t *testing.T) {
slot := primitives.Slot(config.AltairForkEpoch * primitives.Epoch(config.SlotsPerEpoch)).Add(1)
st, err := util.NewBeaconStateAltair()
require.NoError(t, err)
err = st.SetSlot(slot)
require.NoError(t, err)
db := dbtesting.SetupDB(t)
updatePeriod := uint64(slot.Div(uint64(config.EpochsPerSyncCommitteePeriod)).Div(uint64(config.SlotsPerEpoch)))
update, err := createUpdate(t, version.Altair)
require.NoError(t, err)
err = db.SaveLightClientUpdate(ctx, updatePeriod, update)
require.NoError(t, err)
mockChainService := &mock.ChainService{State: st}
s := &Server{
HeadFetcher: mockChainService,
BeaconDB: db,
}
startPeriod := slot.Div(uint64(config.EpochsPerSyncCommitteePeriod)).Div(uint64(config.SlotsPerEpoch))
url := fmt.Sprintf("http://foo.com/?count=1&start_period=%d", startPeriod)
request := httptest.NewRequest("GET", url, nil)
request.Header.Add("Accept", "application/octet-stream")
writer := httptest.NewRecorder()
writer.Body = &bytes.Buffer{}
s.GetLightClientUpdatesByRange(writer, request)
require.Equal(t, http.StatusOK, writer.Code)
var resp pb.LightClientUpdateAltair
err = resp.UnmarshalSSZ(writer.Body.Bytes()[12:]) // skip the length and fork digest prefixes
require.NoError(t, err)
require.DeepEqual(t, resp.AttestedHeader, update.AttestedHeader().Proto())
})
t.Run("capella", func(t *testing.T) {
slot := primitives.Slot(config.CapellaForkEpoch * primitives.Epoch(config.SlotsPerEpoch)).Add(1)
@@ -553,6 +592,45 @@ func TestLightClientHandler_GetLightClientByRange(t *testing.T) {
require.DeepEqual(t, updateJson, resp.Updates[0].Data)
})
t.Run("capella ssz", func(t *testing.T) {
slot := primitives.Slot(config.CapellaForkEpoch * primitives.Epoch(config.SlotsPerEpoch)).Add(1)
st, err := util.NewBeaconStateCapella()
require.NoError(t, err)
err = st.SetSlot(slot)
require.NoError(t, err)
db := dbtesting.SetupDB(t)
updatePeriod := uint64(slot.Div(uint64(config.EpochsPerSyncCommitteePeriod)).Div(uint64(config.SlotsPerEpoch)))
update, err := createUpdate(t, version.Capella)
require.NoError(t, err)
err = db.SaveLightClientUpdate(ctx, updatePeriod, update)
require.NoError(t, err)
mockChainService := &mock.ChainService{State: st}
s := &Server{
HeadFetcher: mockChainService,
BeaconDB: db,
}
startPeriod := slot.Div(uint64(config.EpochsPerSyncCommitteePeriod)).Div(uint64(config.SlotsPerEpoch))
url := fmt.Sprintf("http://foo.com/?count=1&start_period=%d", startPeriod)
request := httptest.NewRequest("GET", url, nil)
request.Header.Add("Accept", "application/octet-stream")
writer := httptest.NewRecorder()
writer.Body = &bytes.Buffer{}
s.GetLightClientUpdatesByRange(writer, request)
require.Equal(t, http.StatusOK, writer.Code)
var resp pb.LightClientUpdateCapella
err = resp.UnmarshalSSZ(writer.Body.Bytes()[12:]) // skip the length and fork digest prefixes
require.NoError(t, err)
require.DeepEqual(t, resp.AttestedHeader, update.AttestedHeader().Proto())
})
t.Run("deneb", func(t *testing.T) {
slot := primitives.Slot(config.DenebForkEpoch * primitives.Epoch(config.SlotsPerEpoch)).Add(1)
@@ -594,6 +672,44 @@ func TestLightClientHandler_GetLightClientByRange(t *testing.T) {
require.DeepEqual(t, updateJson, resp.Updates[0].Data)
})
t.Run("deneb ssz", func(t *testing.T) {
slot := primitives.Slot(config.DenebForkEpoch * primitives.Epoch(config.SlotsPerEpoch)).Add(1)
st, err := util.NewBeaconStateDeneb()
require.NoError(t, err)
err = st.SetSlot(slot)
require.NoError(t, err)
db := dbtesting.SetupDB(t)
updatePeriod := uint64(slot.Div(uint64(config.EpochsPerSyncCommitteePeriod)).Div(uint64(config.SlotsPerEpoch)))
update, err := createUpdate(t, version.Deneb)
require.NoError(t, err)
err = db.SaveLightClientUpdate(ctx, updatePeriod, update)
require.NoError(t, err)
mockChainService := &mock.ChainService{State: st}
s := &Server{
HeadFetcher: mockChainService,
BeaconDB: db,
}
startPeriod := slot.Div(uint64(config.EpochsPerSyncCommitteePeriod)).Div(uint64(config.SlotsPerEpoch))
url := fmt.Sprintf("http://foo.com/?count=1&start_period=%d", startPeriod)
request := httptest.NewRequest("GET", url, nil)
request.Header.Add("Accept", "application/octet-stream")
writer := httptest.NewRecorder()
writer.Body = &bytes.Buffer{}
s.GetLightClientUpdatesByRange(writer, request)
require.Equal(t, http.StatusOK, writer.Code)
var resp pb.LightClientUpdateDeneb
err = resp.UnmarshalSSZ(writer.Body.Bytes()[12:]) // skip the length and fork digest prefixes
require.NoError(t, err)
require.DeepEqual(t, resp.AttestedHeader, update.AttestedHeader().Proto())
})
t.Run("altair Multiple", func(t *testing.T) {
slot := primitives.Slot(config.AltairForkEpoch * primitives.Epoch(config.SlotsPerEpoch)).Add(1)
@@ -646,6 +762,60 @@ func TestLightClientHandler_GetLightClientByRange(t *testing.T) {
}
})
t.Run("altair Multiple ssz", func(t *testing.T) {
slot := primitives.Slot(config.AltairForkEpoch * primitives.Epoch(config.SlotsPerEpoch)).Add(1)
st, err := util.NewBeaconStateAltair()
require.NoError(t, err)
headSlot := slot.Add(2 * uint64(config.SlotsPerEpoch) * uint64(config.EpochsPerSyncCommitteePeriod)) // 2 periods
err = st.SetSlot(headSlot)
require.NoError(t, err)
db := dbtesting.SetupDB(t)
updatePeriod := slot.Div(uint64(config.EpochsPerSyncCommitteePeriod)).Div(uint64(config.SlotsPerEpoch))
updates := make([]interfaces.LightClientUpdate, 0)
for i := 1; i <= 2; i++ {
update, err := createUpdate(t, version.Altair)
require.NoError(t, err)
updates = append(updates, update)
}
for _, update := range updates {
err := db.SaveLightClientUpdate(ctx, uint64(updatePeriod), update)
require.NoError(t, err)
updatePeriod++
}
mockChainService := &mock.ChainService{State: st}
s := &Server{
HeadFetcher: mockChainService,
BeaconDB: db,
}
startPeriod := slot.Sub(1).Div(uint64(config.EpochsPerSyncCommitteePeriod)).Div(uint64(config.SlotsPerEpoch))
url := fmt.Sprintf("http://foo.com/?count=100&start_period=%d", startPeriod)
request := httptest.NewRequest("GET", url, nil)
request.Header.Add("Accept", "application/octet-stream")
writer := httptest.NewRecorder()
writer.Body = &bytes.Buffer{}
s.GetLightClientUpdatesByRange(writer, request)
require.Equal(t, http.StatusOK, writer.Code)
offset := 0
for i := 0; offset < writer.Body.Len(); i++ {
updateLen := int(ssz.UnmarshallUint64(writer.Body.Bytes()[offset:offset+8]) - 4)
offset += 12
var resp pb.LightClientUpdateAltair
err = resp.UnmarshalSSZ(writer.Body.Bytes()[offset : offset+updateLen])
require.NoError(t, err)
require.DeepEqual(t, resp.AttestedHeader, updates[i].AttestedHeader().Proto())
offset += updateLen
}
})
t.Run("capella Multiple", func(t *testing.T) {
slot := primitives.Slot(config.CapellaForkEpoch * primitives.Epoch(config.SlotsPerEpoch)).Add(1)
@@ -698,6 +868,60 @@ func TestLightClientHandler_GetLightClientByRange(t *testing.T) {
}
})
t.Run("capella Multiple ssz", func(t *testing.T) {
slot := primitives.Slot(config.CapellaForkEpoch * primitives.Epoch(config.SlotsPerEpoch)).Add(1)
st, err := util.NewBeaconStateAltair()
require.NoError(t, err)
headSlot := slot.Add(2 * uint64(config.SlotsPerEpoch) * uint64(config.EpochsPerSyncCommitteePeriod)) // 2 periods
err = st.SetSlot(headSlot)
require.NoError(t, err)
db := dbtesting.SetupDB(t)
updatePeriod := slot.Div(uint64(config.EpochsPerSyncCommitteePeriod)).Div(uint64(config.SlotsPerEpoch))
updates := make([]interfaces.LightClientUpdate, 0)
for i := 0; i < 2; i++ {
update, err := createUpdate(t, version.Capella)
require.NoError(t, err)
updates = append(updates, update)
}
for _, update := range updates {
err := db.SaveLightClientUpdate(ctx, uint64(updatePeriod), update)
require.NoError(t, err)
updatePeriod++
}
mockChainService := &mock.ChainService{State: st}
s := &Server{
HeadFetcher: mockChainService,
BeaconDB: db,
}
startPeriod := slot.Sub(1).Div(uint64(config.EpochsPerSyncCommitteePeriod)).Div(uint64(config.SlotsPerEpoch))
url := fmt.Sprintf("http://foo.com/?count=100&start_period=%d", startPeriod)
request := httptest.NewRequest("GET", url, nil)
request.Header.Add("Accept", "application/octet-stream")
writer := httptest.NewRecorder()
writer.Body = &bytes.Buffer{}
s.GetLightClientUpdatesByRange(writer, request)
require.Equal(t, http.StatusOK, writer.Code)
offset := 0
for i := 0; offset < writer.Body.Len(); i++ {
updateLen := int(ssz.UnmarshallUint64(writer.Body.Bytes()[offset:offset+8]) - 4)
offset += 12
var resp pb.LightClientUpdateCapella
err = resp.UnmarshalSSZ(writer.Body.Bytes()[offset : offset+updateLen])
require.NoError(t, err)
require.DeepEqual(t, resp.AttestedHeader, updates[i].AttestedHeader().Proto())
offset += updateLen
}
})
t.Run("deneb Multiple", func(t *testing.T) {
slot := primitives.Slot(config.DenebForkEpoch * primitives.Epoch(config.SlotsPerEpoch)).Add(1)
@@ -749,6 +973,59 @@ func TestLightClientHandler_GetLightClientByRange(t *testing.T) {
}
})
t.Run("deneb Multiple", func(t *testing.T) {
slot := primitives.Slot(config.DenebForkEpoch * primitives.Epoch(config.SlotsPerEpoch)).Add(1)
st, err := util.NewBeaconStateAltair()
require.NoError(t, err)
headSlot := slot.Add(2 * uint64(config.SlotsPerEpoch) * uint64(config.EpochsPerSyncCommitteePeriod))
err = st.SetSlot(headSlot)
require.NoError(t, err)
db := dbtesting.SetupDB(t)
updatePeriod := slot.Div(uint64(config.EpochsPerSyncCommitteePeriod)).Div(uint64(config.SlotsPerEpoch))
updates := make([]interfaces.LightClientUpdate, 0)
for i := 0; i < 2; i++ {
update, err := createUpdate(t, version.Deneb)
require.NoError(t, err)
updates = append(updates, update)
}
for _, update := range updates {
err := db.SaveLightClientUpdate(ctx, uint64(updatePeriod), update)
require.NoError(t, err)
updatePeriod++
}
mockChainService := &mock.ChainService{State: st}
s := &Server{
HeadFetcher: mockChainService,
BeaconDB: db,
}
startPeriod := slot.Sub(1).Div(uint64(config.EpochsPerSyncCommitteePeriod)).Div(uint64(config.SlotsPerEpoch))
url := fmt.Sprintf("http://foo.com/?count=100&start_period=%d", startPeriod)
request := httptest.NewRequest("GET", url, nil)
request.Header.Add("Accept", "application/octet-stream")
writer := httptest.NewRecorder()
writer.Body = &bytes.Buffer{}
s.GetLightClientUpdatesByRange(writer, request)
require.Equal(t, http.StatusOK, writer.Code)
offset := 0
for i := 0; offset < writer.Body.Len(); i++ {
updateLen := int(ssz.UnmarshallUint64(writer.Body.Bytes()[offset:offset+8]) - 4)
offset += 12
var resp pb.LightClientUpdateDeneb
err = resp.UnmarshalSSZ(writer.Body.Bytes()[offset : offset+updateLen])
require.NoError(t, err)
require.DeepEqual(t, resp.AttestedHeader, updates[i].AttestedHeader().Proto())
offset += updateLen
}
})
t.Run("multiple forks - altair, capella", func(t *testing.T) {
slotCapella := primitives.Slot(config.CapellaForkEpoch * primitives.Epoch(config.SlotsPerEpoch)).Add(1)
slotAltair := primitives.Slot(config.AltairForkEpoch * primitives.Epoch(config.SlotsPerEpoch)).Add(1)
@@ -809,6 +1086,68 @@ func TestLightClientHandler_GetLightClientByRange(t *testing.T) {
}
})
t.Run("multiple forks - altair, capella - ssz", func(t *testing.T) {
slotCapella := primitives.Slot(config.CapellaForkEpoch * primitives.Epoch(config.SlotsPerEpoch)).Add(1)
slotAltair := primitives.Slot(config.AltairForkEpoch * primitives.Epoch(config.SlotsPerEpoch)).Add(1)
st, err := util.NewBeaconStateAltair()
require.NoError(t, err)
headSlot := slotCapella.Add(1)
err = st.SetSlot(headSlot)
require.NoError(t, err)
db := dbtesting.SetupDB(t)
updates := make([]interfaces.LightClientUpdate, 2)
updatePeriod := slotAltair.Div(uint64(config.EpochsPerSyncCommitteePeriod)).Div(uint64(config.SlotsPerEpoch))
updates[0], err = createUpdate(t, version.Altair)
require.NoError(t, err)
err = db.SaveLightClientUpdate(ctx, uint64(updatePeriod), updates[0])
require.NoError(t, err)
updatePeriod = slotCapella.Div(uint64(config.EpochsPerSyncCommitteePeriod)).Div(uint64(config.SlotsPerEpoch))
updates[1], err = createUpdate(t, version.Capella)
require.NoError(t, err)
err = db.SaveLightClientUpdate(ctx, uint64(updatePeriod), updates[1])
require.NoError(t, err)
mockChainService := &mock.ChainService{State: st}
s := &Server{
HeadFetcher: mockChainService,
BeaconDB: db,
}
startPeriod := 0
url := fmt.Sprintf("http://foo.com/?count=100&start_period=%d", startPeriod)
request := httptest.NewRequest("GET", url, nil)
request.Header.Add("Accept", "application/octet-stream")
writer := httptest.NewRecorder()
writer.Body = &bytes.Buffer{}
s.GetLightClientUpdatesByRange(writer, request)
require.Equal(t, http.StatusOK, writer.Code)
offset := 0
updateLen := int(ssz.UnmarshallUint64(writer.Body.Bytes()[offset:offset+8]) - 4)
offset += 12
var resp pb.LightClientUpdateAltair
err = resp.UnmarshalSSZ(writer.Body.Bytes()[offset : offset+updateLen])
require.NoError(t, err)
require.DeepEqual(t, resp.AttestedHeader, updates[0].AttestedHeader().Proto())
offset += updateLen
updateLen = int(ssz.UnmarshallUint64(writer.Body.Bytes()[offset:offset+8]) - 4)
offset += 12
var resp1 pb.LightClientUpdateCapella
err = resp1.UnmarshalSSZ(writer.Body.Bytes()[offset : offset+updateLen])
require.NoError(t, err)
require.DeepEqual(t, resp1.AttestedHeader, updates[1].AttestedHeader().Proto())
})
t.Run("multiple forks - capella, deneb", func(t *testing.T) {
slotDeneb := primitives.Slot(config.DenebForkEpoch * primitives.Epoch(config.SlotsPerEpoch)).Add(1)
slotCapella := primitives.Slot(config.CapellaForkEpoch * primitives.Epoch(config.SlotsPerEpoch)).Add(1)
@@ -869,6 +1208,68 @@ func TestLightClientHandler_GetLightClientByRange(t *testing.T) {
}
})
t.Run("multiple forks - capella, deneb - ssz", func(t *testing.T) {
slotDeneb := primitives.Slot(config.DenebForkEpoch * primitives.Epoch(config.SlotsPerEpoch)).Add(1)
slotCapella := primitives.Slot(config.CapellaForkEpoch * primitives.Epoch(config.SlotsPerEpoch)).Add(1)
st, err := util.NewBeaconStateAltair()
require.NoError(t, err)
headSlot := slotDeneb.Add(1)
err = st.SetSlot(headSlot)
require.NoError(t, err)
db := dbtesting.SetupDB(t)
updates := make([]interfaces.LightClientUpdate, 2)
updatePeriod := slotCapella.Div(uint64(config.EpochsPerSyncCommitteePeriod)).Div(uint64(config.SlotsPerEpoch))
updates[0], err = createUpdate(t, version.Capella)
require.NoError(t, err)
err = db.SaveLightClientUpdate(ctx, uint64(updatePeriod), updates[0])
require.NoError(t, err)
updatePeriod = slotDeneb.Div(uint64(config.EpochsPerSyncCommitteePeriod)).Div(uint64(config.SlotsPerEpoch))
updates[1], err = createUpdate(t, version.Deneb)
require.NoError(t, err)
err = db.SaveLightClientUpdate(ctx, uint64(updatePeriod), updates[1])
require.NoError(t, err)
mockChainService := &mock.ChainService{State: st}
s := &Server{
HeadFetcher: mockChainService,
BeaconDB: db,
}
startPeriod := 1
url := fmt.Sprintf("http://foo.com/?count=100&start_period=%d", startPeriod)
request := httptest.NewRequest("GET", url, nil)
request.Header.Add("Accept", "application/octet-stream")
writer := httptest.NewRecorder()
writer.Body = &bytes.Buffer{}
s.GetLightClientUpdatesByRange(writer, request)
require.Equal(t, http.StatusOK, writer.Code)
offset := 0
updateLen := int(ssz.UnmarshallUint64(writer.Body.Bytes()[offset:offset+8]) - 4)
offset += 12
var resp pb.LightClientUpdateCapella
err = resp.UnmarshalSSZ(writer.Body.Bytes()[offset : offset+updateLen])
require.NoError(t, err)
require.DeepEqual(t, resp.AttestedHeader, updates[0].AttestedHeader().Proto())
offset += updateLen
updateLen = int(ssz.UnmarshallUint64(writer.Body.Bytes()[offset:offset+8]) - 4)
offset += 12
var resp1 pb.LightClientUpdateDeneb
err = resp1.UnmarshalSSZ(writer.Body.Bytes()[offset : offset+updateLen])
require.NoError(t, err)
require.DeepEqual(t, resp1.AttestedHeader, updates[1].AttestedHeader().Proto())
})
t.Run("count bigger than limit", func(t *testing.T) {
config.MaxRequestLightClientUpdates = 2
params.OverrideBeaconConfig(config)

View File

@@ -10,6 +10,7 @@ go_library(
importpath = "github.com/prysmaticlabs/prysm/v5/beacon-chain/rpc/eth/node",
visibility = ["//visibility:public"],
deps = [
"//api/httputil:go_default_library",
"//api/server/structs:go_default_library",
"//beacon-chain/blockchain:go_default_library",
"//beacon-chain/db:go_default_library",
@@ -20,7 +21,6 @@ go_library(
"//beacon-chain/rpc/eth/shared:go_default_library",
"//beacon-chain/sync:go_default_library",
"//monitoring/tracing/trace:go_default_library",
"//network/httputil:go_default_library",
"//proto/eth/v1:go_default_library",
"//proto/migration:go_default_library",
"//proto/prysm/v1alpha1:go_default_library",
@@ -40,6 +40,7 @@ go_test(
],
embed = [":go_default_library"],
deps = [
"//api/httputil:go_default_library",
"//api/server/structs:go_default_library",
"//beacon-chain/blockchain/testing:go_default_library",
"//beacon-chain/p2p:go_default_library",
@@ -49,7 +50,6 @@ go_test(
"//beacon-chain/sync/initial-sync/testing:go_default_library",
"//consensus-types/primitives:go_default_library",
"//consensus-types/wrapper:go_default_library",
"//network/httputil:go_default_library",
"//proto/prysm/v1alpha1:go_default_library",
"//runtime/version:go_default_library",
"//testing/assert:go_default_library",

View File

@@ -7,11 +7,11 @@ import (
"strconv"
"github.com/ethereum/go-ethereum/common/hexutil"
httputil2 "github.com/prysmaticlabs/prysm/v5/api/httputil"
"github.com/prysmaticlabs/prysm/v5/api/server/structs"
"github.com/prysmaticlabs/prysm/v5/beacon-chain/p2p"
"github.com/prysmaticlabs/prysm/v5/beacon-chain/rpc/eth/shared"
"github.com/prysmaticlabs/prysm/v5/monitoring/tracing/trace"
"github.com/prysmaticlabs/prysm/v5/network/httputil"
ethpb "github.com/prysmaticlabs/prysm/v5/proto/eth/v1"
"github.com/prysmaticlabs/prysm/v5/runtime/version"
)
@@ -33,7 +33,7 @@ func (s *Server) GetSyncStatus(w http.ResponseWriter, r *http.Request) {
isOptimistic, err := s.OptimisticModeFetcher.IsOptimistic(ctx)
if err != nil {
httputil.HandleError(w, "Could not check optimistic status: "+err.Error(), http.StatusInternalServerError)
httputil2.HandleError(w, "Could not check optimistic status: "+err.Error(), http.StatusInternalServerError)
return
}
@@ -47,7 +47,7 @@ func (s *Server) GetSyncStatus(w http.ResponseWriter, r *http.Request) {
ElOffline: !s.ExecutionChainInfoFetcher.ExecutionClientConnected(),
},
}
httputil.WriteJson(w, response)
httputil2.WriteJson(w, response)
}
// GetIdentity retrieves data about the node's network presence.
@@ -63,7 +63,7 @@ func (s *Server) GetIdentity(w http.ResponseWriter, r *http.Request) {
}
sourceDisc, err := s.PeerManager.DiscoveryAddresses()
if err != nil {
httputil.HandleError(w, "Could not obtain discovery address: "+err.Error(), http.StatusInternalServerError)
httputil2.HandleError(w, "Could not obtain discovery address: "+err.Error(), http.StatusInternalServerError)
return
}
discoveryAddresses := make([]string, len(sourceDisc))
@@ -72,7 +72,7 @@ func (s *Server) GetIdentity(w http.ResponseWriter, r *http.Request) {
}
serializedEnr, err := p2p.SerializeENR(s.PeerManager.ENR())
if err != nil {
httputil.HandleError(w, "Could not obtain enr: "+err.Error(), http.StatusInternalServerError)
httputil2.HandleError(w, "Could not obtain enr: "+err.Error(), http.StatusInternalServerError)
return
}
@@ -88,7 +88,7 @@ func (s *Server) GetIdentity(w http.ResponseWriter, r *http.Request) {
},
},
}
httputil.WriteJson(w, resp)
httputil2.WriteJson(w, resp)
}
// GetVersion requests that the beacon node identify information about its implementation in a
@@ -103,7 +103,7 @@ func (*Server) GetVersion(w http.ResponseWriter, r *http.Request) {
Version: v,
},
}
httputil.WriteJson(w, resp)
httputil2.WriteJson(w, resp)
}
// GetHealth returns node health status in http status codes. Useful for load balancers.
@@ -115,13 +115,13 @@ func (s *Server) GetHealth(w http.ResponseWriter, r *http.Request) {
// lint:ignore uintcast -- custom syncing status being outside of range is harmless
intSyncingStatus := int(syncingStatus)
if !ok || (rawSyncingStatus != "" && http.StatusText(intSyncingStatus) == "") {
httputil.HandleError(w, "syncing_status is not a valid HTTP status code", http.StatusBadRequest)
httputil2.HandleError(w, "syncing_status is not a valid HTTP status code", http.StatusBadRequest)
return
}
optimistic, err := s.OptimisticModeFetcher.IsOptimistic(ctx)
if err != nil {
httputil.HandleError(w, "Could not check optimistic status: "+err.Error(), http.StatusInternalServerError)
httputil2.HandleError(w, "Could not check optimistic status: "+err.Error(), http.StatusInternalServerError)
}
if s.SyncChecker.Synced() && !optimistic {
return

View File

@@ -7,12 +7,12 @@ import (
"github.com/libp2p/go-libp2p/core/peer"
"github.com/pkg/errors"
httputil2 "github.com/prysmaticlabs/prysm/v5/api/httputil"
"github.com/prysmaticlabs/prysm/v5/api/server/structs"
"github.com/prysmaticlabs/prysm/v5/beacon-chain/p2p"
"github.com/prysmaticlabs/prysm/v5/beacon-chain/p2p/peers"
"github.com/prysmaticlabs/prysm/v5/beacon-chain/p2p/peers/peerdata"
"github.com/prysmaticlabs/prysm/v5/monitoring/tracing/trace"
"github.com/prysmaticlabs/prysm/v5/network/httputil"
"github.com/prysmaticlabs/prysm/v5/proto/migration"
eth "github.com/prysmaticlabs/prysm/v5/proto/prysm/v1alpha1"
)
@@ -24,54 +24,54 @@ func (s *Server) GetPeer(w http.ResponseWriter, r *http.Request) {
rawId := r.PathValue("peer_id")
if rawId == "" {
httputil.HandleError(w, "peer_id is required in URL params", http.StatusBadRequest)
httputil2.HandleError(w, "peer_id is required in URL params", http.StatusBadRequest)
return
}
peerStatus := s.PeersFetcher.Peers()
id, err := peer.Decode(rawId)
if err != nil {
httputil.HandleError(w, "Invalid peer ID: "+err.Error(), http.StatusBadRequest)
httputil2.HandleError(w, "Invalid peer ID: "+err.Error(), http.StatusBadRequest)
return
}
enr, err := peerStatus.ENR(id)
if err != nil {
if errors.Is(err, peerdata.ErrPeerUnknown) {
httputil.HandleError(w, "Peer not found: "+err.Error(), http.StatusNotFound)
httputil2.HandleError(w, "Peer not found: "+err.Error(), http.StatusNotFound)
return
}
httputil.HandleError(w, "Could not obtain ENR: "+err.Error(), http.StatusInternalServerError)
httputil2.HandleError(w, "Could not obtain ENR: "+err.Error(), http.StatusInternalServerError)
return
}
serializedEnr, err := p2p.SerializeENR(enr)
if err != nil {
httputil.HandleError(w, "Could not obtain ENR: "+err.Error(), http.StatusInternalServerError)
httputil2.HandleError(w, "Could not obtain ENR: "+err.Error(), http.StatusInternalServerError)
return
}
p2pAddress, err := peerStatus.Address(id)
if err != nil {
httputil.HandleError(w, "Could not obtain address: "+err.Error(), http.StatusInternalServerError)
httputil2.HandleError(w, "Could not obtain address: "+err.Error(), http.StatusInternalServerError)
return
}
state, err := peerStatus.ConnectionState(id)
if err != nil {
httputil.HandleError(w, "Could not obtain connection state: "+err.Error(), http.StatusInternalServerError)
httputil2.HandleError(w, "Could not obtain connection state: "+err.Error(), http.StatusInternalServerError)
return
}
direction, err := peerStatus.Direction(id)
if err != nil {
httputil.HandleError(w, "Could not obtain direction: "+err.Error(), http.StatusInternalServerError)
httputil2.HandleError(w, "Could not obtain direction: "+err.Error(), http.StatusInternalServerError)
return
}
if eth.PeerDirection(direction) == eth.PeerDirection_UNKNOWN {
httputil.HandleError(w, "Peer not found", http.StatusNotFound)
httputil2.HandleError(w, "Peer not found", http.StatusNotFound)
return
}
v1ConnState := migration.V1Alpha1ConnectionStateToV1(eth.ConnectionState(state))
v1PeerDirection, err := migration.V1Alpha1PeerDirectionToV1(eth.PeerDirection(direction))
if err != nil {
httputil.HandleError(w, "Could not handle peer direction: "+err.Error(), http.StatusInternalServerError)
httputil2.HandleError(w, "Could not handle peer direction: "+err.Error(), http.StatusInternalServerError)
return
}
@@ -84,7 +84,7 @@ func (s *Server) GetPeer(w http.ResponseWriter, r *http.Request) {
Direction: strings.ToLower(v1PeerDirection.String()),
},
}
httputil.WriteJson(w, resp)
httputil2.WriteJson(w, resp)
}
// GetPeers retrieves data about the node's network peers.
@@ -104,7 +104,7 @@ func (s *Server) GetPeers(w http.ResponseWriter, r *http.Request) {
for _, id := range allIds {
p, err := peerInfo(peerStatus, id)
if err != nil {
httputil.HandleError(w, "Could not get peer info: "+err.Error(), http.StatusInternalServerError)
httputil2.HandleError(w, "Could not get peer info: "+err.Error(), http.StatusInternalServerError)
return
}
if p == nil {
@@ -113,7 +113,7 @@ func (s *Server) GetPeers(w http.ResponseWriter, r *http.Request) {
allPeers = append(allPeers, p)
}
resp := &structs.GetPeersResponse{Data: allPeers}
httputil.WriteJson(w, resp)
httputil2.WriteJson(w, resp)
return
}
@@ -168,7 +168,7 @@ func (s *Server) GetPeers(w http.ResponseWriter, r *http.Request) {
for _, id := range filteredIds {
p, err := peerInfo(peerStatus, id)
if err != nil {
httputil.HandleError(w, "Could not get peer info: "+err.Error(), http.StatusInternalServerError)
httputil2.HandleError(w, "Could not get peer info: "+err.Error(), http.StatusInternalServerError)
return
}
if p == nil {
@@ -178,7 +178,7 @@ func (s *Server) GetPeers(w http.ResponseWriter, r *http.Request) {
}
resp := &structs.GetPeersResponse{Data: filteredPeers}
httputil.WriteJson(w, resp)
httputil2.WriteJson(w, resp)
}
// GetPeerCount retrieves number of known peers.
@@ -196,7 +196,7 @@ func (s *Server) GetPeerCount(w http.ResponseWriter, r *http.Request) {
Disconnecting: strconv.FormatInt(int64(len(peerStatus.Disconnecting())), 10),
},
}
httputil.WriteJson(w, resp)
httputil2.WriteJson(w, resp)
}
func handleEmptyFilters(states []string, directions []string) (emptyState, emptyDirection bool) {

View File

@@ -14,11 +14,11 @@ 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/v5/api/httputil"
"github.com/prysmaticlabs/prysm/v5/api/server/structs"
"github.com/prysmaticlabs/prysm/v5/beacon-chain/p2p"
"github.com/prysmaticlabs/prysm/v5/beacon-chain/p2p/peers"
mockp2p "github.com/prysmaticlabs/prysm/v5/beacon-chain/p2p/testing"
"github.com/prysmaticlabs/prysm/v5/network/httputil"
"github.com/prysmaticlabs/prysm/v5/testing/assert"
"github.com/prysmaticlabs/prysm/v5/testing/require"
)

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/v5/api/httputil"
"github.com/prysmaticlabs/prysm/v5/api/server/structs"
mock "github.com/prysmaticlabs/prysm/v5/beacon-chain/blockchain/testing"
"github.com/prysmaticlabs/prysm/v5/beacon-chain/p2p"
@@ -22,7 +23,6 @@ import (
syncmock "github.com/prysmaticlabs/prysm/v5/beacon-chain/sync/initial-sync/testing"
"github.com/prysmaticlabs/prysm/v5/consensus-types/primitives"
"github.com/prysmaticlabs/prysm/v5/consensus-types/wrapper"
"github.com/prysmaticlabs/prysm/v5/network/httputil"
pb "github.com/prysmaticlabs/prysm/v5/proto/prysm/v1alpha1"
"github.com/prysmaticlabs/prysm/v5/runtime/version"
"github.com/prysmaticlabs/prysm/v5/testing/assert"

View File

@@ -10,6 +10,7 @@ go_library(
importpath = "github.com/prysmaticlabs/prysm/v5/beacon-chain/rpc/eth/rewards",
visibility = ["//visibility:public"],
deps = [
"//api/httputil:go_default_library",
"//api/server/structs:go_default_library",
"//beacon-chain/blockchain:go_default_library",
"//beacon-chain/core/altair:go_default_library",
@@ -28,7 +29,6 @@ go_library(
"//consensus-types/interfaces:go_default_library",
"//consensus-types/primitives:go_default_library",
"//monitoring/tracing/trace:go_default_library",
"//network/httputil:go_default_library",
"//runtime/version:go_default_library",
"//time/slots:go_default_library",
"@com_github_wealdtech_go_bytesutil//:go_default_library",
@@ -43,6 +43,7 @@ go_test(
],
embed = [":go_default_library"],
deps = [
"//api/httputil:go_default_library",
"//api/server/structs:go_default_library",
"//beacon-chain/blockchain/testing:go_default_library",
"//beacon-chain/core/altair:go_default_library",
@@ -61,7 +62,6 @@ go_test(
"//crypto/bls:go_default_library",
"//crypto/bls/blst:go_default_library",
"//encoding/bytesutil:go_default_library",
"//network/httputil:go_default_library",
"//proto/prysm/v1alpha1:go_default_library",
"//runtime/version:go_default_library",
"//testing/assert:go_default_library",

View File

@@ -7,6 +7,7 @@ import (
"strconv"
"strings"
httputil2 "github.com/prysmaticlabs/prysm/v5/api/httputil"
"github.com/prysmaticlabs/prysm/v5/api/server/structs"
"github.com/prysmaticlabs/prysm/v5/beacon-chain/core/altair"
"github.com/prysmaticlabs/prysm/v5/beacon-chain/core/epoch/precompute"
@@ -17,7 +18,6 @@ import (
"github.com/prysmaticlabs/prysm/v5/consensus-types/blocks"
"github.com/prysmaticlabs/prysm/v5/consensus-types/primitives"
"github.com/prysmaticlabs/prysm/v5/monitoring/tracing/trace"
"github.com/prysmaticlabs/prysm/v5/network/httputil"
"github.com/prysmaticlabs/prysm/v5/runtime/version"
"github.com/prysmaticlabs/prysm/v5/time/slots"
"github.com/wealdtech/go-bytesutil"
@@ -36,28 +36,28 @@ func (s *Server) BlockRewards(w http.ResponseWriter, r *http.Request) {
}
if err := blocks.BeaconBlockIsNil(blk); err != nil {
httputil.HandleError(w, fmt.Sprintf("block id %s was not found", blockId), http.StatusNotFound)
httputil2.HandleError(w, fmt.Sprintf("block id %s was not found", blockId), http.StatusNotFound)
return
}
if blk.Version() == version.Phase0 {
httputil.HandleError(w, "Block rewards are not supported for Phase 0 blocks", http.StatusBadRequest)
httputil2.HandleError(w, "Block rewards are not supported for Phase 0 blocks", http.StatusBadRequest)
return
}
optimistic, err := s.OptimisticModeFetcher.IsOptimistic(r.Context())
if err != nil {
httputil.HandleError(w, "Could not get optimistic mode info: "+err.Error(), http.StatusInternalServerError)
httputil2.HandleError(w, "Could not get optimistic mode info: "+err.Error(), http.StatusInternalServerError)
return
}
blkRoot, err := blk.Block().HashTreeRoot()
if err != nil {
httputil.HandleError(w, "Could not get block root: "+err.Error(), http.StatusInternalServerError)
httputil2.HandleError(w, "Could not get block root: "+err.Error(), http.StatusInternalServerError)
return
}
blockRewards, httpError := s.BlockRewardFetcher.GetBlockRewardsData(ctx, blk.Block())
if httpError != nil {
httputil.WriteError(w, httpError)
httputil2.WriteError(w, httpError)
return
}
response := &structs.BlockRewardsResponse{
@@ -65,7 +65,7 @@ func (s *Server) BlockRewards(w http.ResponseWriter, r *http.Request) {
ExecutionOptimistic: optimistic,
Finalized: s.FinalizationFetcher.IsFinalized(ctx, blkRoot),
}
httputil.WriteJson(w, response)
httputil2.WriteJson(w, response)
}
// AttestationRewards retrieves attestation reward info for validators specified by array of public keys or validator index.
@@ -90,12 +90,12 @@ func (s *Server) AttestationRewards(w http.ResponseWriter, r *http.Request) {
optimistic, err := s.OptimisticModeFetcher.IsOptimistic(r.Context())
if err != nil {
httputil.HandleError(w, "Could not get optimistic mode info: "+err.Error(), http.StatusInternalServerError)
httputil2.HandleError(w, "Could not get optimistic mode info: "+err.Error(), http.StatusInternalServerError)
return
}
blkRoot, err := st.LatestBlockHeader().HashTreeRoot()
if err != nil {
httputil.HandleError(w, "Could not get block root: "+err.Error(), http.StatusInternalServerError)
httputil2.HandleError(w, "Could not get block root: "+err.Error(), http.StatusInternalServerError)
return
}
@@ -107,7 +107,7 @@ func (s *Server) AttestationRewards(w http.ResponseWriter, r *http.Request) {
ExecutionOptimistic: optimistic,
Finalized: s.FinalizationFetcher.IsFinalized(r.Context(), blkRoot),
}
httputil.WriteJson(w, resp)
httputil2.WriteJson(w, resp)
}
// SyncCommitteeRewards retrieves rewards info for sync committee members specified by array of public keys or validator index.
@@ -123,18 +123,18 @@ func (s *Server) SyncCommitteeRewards(w http.ResponseWriter, r *http.Request) {
return
}
if blk.Version() == version.Phase0 {
httputil.HandleError(w, "Sync committee rewards are not supported for Phase 0", http.StatusBadRequest)
httputil2.HandleError(w, "Sync committee rewards are not supported for Phase 0", http.StatusBadRequest)
return
}
st, httpErr := s.BlockRewardFetcher.GetStateForRewards(ctx, blk.Block())
if httpErr != nil {
httputil.WriteError(w, httpErr)
httputil2.WriteError(w, httpErr)
return
}
sa, err := blk.Block().Body().SyncAggregate()
if err != nil {
httputil.HandleError(w, "Could not get sync aggregate: "+err.Error(), http.StatusInternalServerError)
httputil2.HandleError(w, "Could not get sync aggregate: "+err.Error(), http.StatusInternalServerError)
return
}
@@ -146,14 +146,14 @@ func (s *Server) SyncCommitteeRewards(w http.ResponseWriter, r *http.Request) {
for i, valIdx := range valIndices {
preProcessBals[i], err = st.BalanceAtIndex(valIdx)
if err != nil {
httputil.HandleError(w, "Could not get validator's balance: "+err.Error(), http.StatusInternalServerError)
httputil2.HandleError(w, "Could not get validator's balance: "+err.Error(), http.StatusInternalServerError)
return
}
}
_, proposerReward, err := altair.ProcessSyncAggregate(r.Context(), st, sa)
if err != nil {
httputil.HandleError(w, "Could not get sync aggregate rewards: "+err.Error(), http.StatusInternalServerError)
httputil2.HandleError(w, "Could not get sync aggregate rewards: "+err.Error(), http.StatusInternalServerError)
return
}
@@ -162,7 +162,7 @@ func (s *Server) SyncCommitteeRewards(w http.ResponseWriter, r *http.Request) {
for i, valIdx := range valIndices {
bal, err := st.BalanceAtIndex(valIdx)
if err != nil {
httputil.HandleError(w, "Could not get validator's balance: "+err.Error(), http.StatusInternalServerError)
httputil2.HandleError(w, "Could not get validator's balance: "+err.Error(), http.StatusInternalServerError)
return
}
rewards[i] = int(bal - preProcessBals[i]) // lint:ignore uintcast
@@ -173,12 +173,12 @@ func (s *Server) SyncCommitteeRewards(w http.ResponseWriter, r *http.Request) {
optimistic, err := s.OptimisticModeFetcher.IsOptimistic(r.Context())
if err != nil {
httputil.HandleError(w, "Could not get optimistic mode info: "+err.Error(), http.StatusInternalServerError)
httputil2.HandleError(w, "Could not get optimistic mode info: "+err.Error(), http.StatusInternalServerError)
return
}
blkRoot, err := blk.Block().HashTreeRoot()
if err != nil {
httputil.HandleError(w, "Could not get block root: "+err.Error(), http.StatusInternalServerError)
httputil2.HandleError(w, "Could not get block root: "+err.Error(), http.StatusInternalServerError)
return
}
@@ -194,35 +194,35 @@ func (s *Server) SyncCommitteeRewards(w http.ResponseWriter, r *http.Request) {
ExecutionOptimistic: optimistic,
Finalized: s.FinalizationFetcher.IsFinalized(r.Context(), blkRoot),
}
httputil.WriteJson(w, response)
httputil2.WriteJson(w, response)
}
func (s *Server) attRewardsState(w http.ResponseWriter, r *http.Request) (state.BeaconState, bool) {
segments := strings.Split(r.URL.Path, "/")
requestedEpoch, err := strconv.ParseUint(segments[len(segments)-1], 10, 64)
if err != nil {
httputil.HandleError(w, "Could not decode epoch: "+err.Error(), http.StatusBadRequest)
httputil2.HandleError(w, "Could not decode epoch: "+err.Error(), http.StatusBadRequest)
return nil, false
}
if primitives.Epoch(requestedEpoch) < params.BeaconConfig().AltairForkEpoch {
httputil.HandleError(w, "Attestation rewards are not supported for Phase 0", http.StatusNotFound)
httputil2.HandleError(w, "Attestation rewards are not supported for Phase 0", http.StatusNotFound)
return nil, false
}
currentEpoch := uint64(slots.ToEpoch(s.TimeFetcher.CurrentSlot()))
if requestedEpoch+1 >= currentEpoch {
httputil.HandleError(w,
httputil2.HandleError(w,
"Attestation rewards are available after two epoch transitions to ensure all attestations have a chance of inclusion",
http.StatusNotFound)
return nil, false
}
nextEpochEnd, err := slots.EpochEnd(primitives.Epoch(requestedEpoch + 1))
if err != nil {
httputil.HandleError(w, "Could not get next epoch's ending slot: "+err.Error(), http.StatusInternalServerError)
httputil2.HandleError(w, "Could not get next epoch's ending slot: "+err.Error(), http.StatusInternalServerError)
return nil, false
}
st, err := s.Stater.StateBySlot(r.Context(), nextEpochEnd)
if err != nil {
httputil.HandleError(w, "Could not get state for epoch's starting slot: "+err.Error(), http.StatusInternalServerError)
httputil2.HandleError(w, "Could not get state for epoch's starting slot: "+err.Error(), http.StatusInternalServerError)
return nil, false
}
return st, true
@@ -235,12 +235,12 @@ func attRewardsBalancesAndVals(
) (*precompute.Balance, []*precompute.Validator, []primitives.ValidatorIndex, bool) {
allVals, bal, err := altair.InitializePrecomputeValidators(r.Context(), st)
if err != nil {
httputil.HandleError(w, "Could not initialize precompute validators: "+err.Error(), http.StatusBadRequest)
httputil2.HandleError(w, "Could not initialize precompute validators: "+err.Error(), http.StatusBadRequest)
return nil, nil, nil, false
}
allVals, bal, err = altair.ProcessEpochParticipation(r.Context(), st, bal, allVals)
if err != nil {
httputil.HandleError(w, "Could not process epoch participation: "+err.Error(), http.StatusBadRequest)
httputil2.HandleError(w, "Could not process epoch participation: "+err.Error(), http.StatusBadRequest)
return nil, nil, nil, false
}
valIndices, ok := requestedValIndices(w, r, st, allVals)
@@ -294,7 +294,7 @@ func idealAttRewards(
}
deltas, err := altair.AttestationsDelta(st, bal, idealVals)
if err != nil {
httputil.HandleError(w, "Could not get attestations delta: "+err.Error(), http.StatusInternalServerError)
httputil2.HandleError(w, "Could not get attestations delta: "+err.Error(), http.StatusInternalServerError)
return nil, false
}
for i, d := range deltas {
@@ -331,7 +331,7 @@ func totalAttRewards(
}
deltas, err := altair.AttestationsDelta(st, bal, vals)
if err != nil {
httputil.HandleError(w, "Could not get attestations delta: "+err.Error(), http.StatusInternalServerError)
httputil2.HandleError(w, "Could not get attestations delta: "+err.Error(), http.StatusInternalServerError)
return nil, false
}
for i, d := range deltas {
@@ -362,7 +362,7 @@ func syncRewardsVals(
) ([]*precompute.Validator, []primitives.ValidatorIndex, bool) {
allVals, _, err := altair.InitializePrecomputeValidators(r.Context(), st)
if err != nil {
httputil.HandleError(w, "Could not initialize precompute validators: "+err.Error(), http.StatusBadRequest)
httputil2.HandleError(w, "Could not initialize precompute validators: "+err.Error(), http.StatusBadRequest)
return nil, nil, false
}
valIndices, ok := requestedValIndices(w, r, st, allVals)
@@ -372,14 +372,14 @@ func syncRewardsVals(
sc, err := st.CurrentSyncCommittee()
if err != nil {
httputil.HandleError(w, "Could not get current sync committee: "+err.Error(), http.StatusBadRequest)
httputil2.HandleError(w, "Could not get current sync committee: "+err.Error(), http.StatusBadRequest)
return nil, nil, false
}
allScIndices := make([]primitives.ValidatorIndex, len(sc.Pubkeys))
for i, pk := range sc.Pubkeys {
valIdx, ok := st.ValidatorIndexByPubkey(bytesutil.ToBytes48(pk))
if !ok {
httputil.HandleError(w, fmt.Sprintf("No validator index found for pubkey %#x", pk), http.StatusBadRequest)
httputil2.HandleError(w, fmt.Sprintf("No validator index found for pubkey %#x", pk), http.StatusBadRequest)
return nil, nil, false
}
allScIndices[i] = valIdx
@@ -404,7 +404,7 @@ func requestedValIndices(w http.ResponseWriter, r *http.Request, st state.Beacon
var rawValIds []string
if r.Body != http.NoBody {
if err := json.NewDecoder(r.Body).Decode(&rawValIds); err != nil {
httputil.HandleError(w, "Could not decode validators: "+err.Error(), http.StatusBadRequest)
httputil2.HandleError(w, "Could not decode validators: "+err.Error(), http.StatusBadRequest)
return nil, false
}
}
@@ -414,18 +414,18 @@ func requestedValIndices(w http.ResponseWriter, r *http.Request, st state.Beacon
if err != nil {
pubkey, err := bytesutil.FromHexString(v)
if err != nil || len(pubkey) != fieldparams.BLSPubkeyLength {
httputil.HandleError(w, fmt.Sprintf("%s is not a validator index or pubkey", v), http.StatusBadRequest)
httputil2.HandleError(w, fmt.Sprintf("%s is not a validator index or pubkey", v), http.StatusBadRequest)
return nil, false
}
var ok bool
valIndices[i], ok = st.ValidatorIndexByPubkey(bytesutil.ToBytes48(pubkey))
if !ok {
httputil.HandleError(w, fmt.Sprintf("No validator index found for pubkey %#x", pubkey), http.StatusBadRequest)
httputil2.HandleError(w, fmt.Sprintf("No validator index found for pubkey %#x", pubkey), http.StatusBadRequest)
return nil, false
}
} else {
if index >= uint64(st.NumValidators()) {
httputil.HandleError(w, fmt.Sprintf("Validator index %d is too large. Maximum allowed index is %d", index, st.NumValidators()-1), http.StatusBadRequest)
httputil2.HandleError(w, fmt.Sprintf("Validator index %d is too large. Maximum allowed index is %d", index, st.NumValidators()-1), http.StatusBadRequest)
return nil, false
}
valIndices[i] = primitives.ValidatorIndex(index)

View File

@@ -13,6 +13,7 @@ import (
"github.com/pkg/errors"
"github.com/prysmaticlabs/go-bitfield"
"github.com/prysmaticlabs/prysm/v5/api/httputil"
"github.com/prysmaticlabs/prysm/v5/api/server/structs"
mock "github.com/prysmaticlabs/prysm/v5/beacon-chain/blockchain/testing"
"github.com/prysmaticlabs/prysm/v5/beacon-chain/core/altair"
@@ -30,7 +31,6 @@ import (
"github.com/prysmaticlabs/prysm/v5/crypto/bls"
"github.com/prysmaticlabs/prysm/v5/crypto/bls/blst"
"github.com/prysmaticlabs/prysm/v5/encoding/bytesutil"
"github.com/prysmaticlabs/prysm/v5/network/httputil"
eth "github.com/prysmaticlabs/prysm/v5/proto/prysm/v1alpha1"
"github.com/prysmaticlabs/prysm/v5/runtime/version"
"github.com/prysmaticlabs/prysm/v5/testing/assert"

View File

@@ -5,6 +5,7 @@ import (
"net/http"
"strconv"
"github.com/prysmaticlabs/prysm/v5/api/httputil"
"github.com/prysmaticlabs/prysm/v5/api/server/structs"
"github.com/prysmaticlabs/prysm/v5/beacon-chain/core/altair"
coreblocks "github.com/prysmaticlabs/prysm/v5/beacon-chain/core/blocks"
@@ -15,7 +16,6 @@ import (
"github.com/prysmaticlabs/prysm/v5/beacon-chain/state/stategen"
consensusblocks "github.com/prysmaticlabs/prysm/v5/consensus-types/blocks"
"github.com/prysmaticlabs/prysm/v5/consensus-types/interfaces"
"github.com/prysmaticlabs/prysm/v5/network/httputil"
"github.com/prysmaticlabs/prysm/v5/time/slots"
)

View File

@@ -6,9 +6,9 @@ go_library(
importpath = "github.com/prysmaticlabs/prysm/v5/beacon-chain/rpc/eth/rewards/testing",
visibility = ["//visibility:public"],
deps = [
"//api/httputil: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,10 +3,10 @@ package testing
import (
"context"
"github.com/prysmaticlabs/prysm/v5/api/httputil"
"github.com/prysmaticlabs/prysm/v5/api/server/structs"
"github.com/prysmaticlabs/prysm/v5/beacon-chain/state"
"github.com/prysmaticlabs/prysm/v5/consensus-types/interfaces"
"github.com/prysmaticlabs/prysm/v5/network/httputil"
)
type MockBlockRewardFetcher struct {

View File

@@ -9,13 +9,13 @@ go_library(
importpath = "github.com/prysmaticlabs/prysm/v5/beacon-chain/rpc/eth/shared",
visibility = ["//visibility:public"],
deps = [
"//api/httputil:go_default_library",
"//api/server/structs:go_default_library",
"//beacon-chain/blockchain:go_default_library",
"//beacon-chain/rpc/lookup:go_default_library",
"//beacon-chain/sync:go_default_library",
"//consensus-types/blocks:go_default_library",
"//consensus-types/interfaces:go_default_library",
"//network/httputil:go_default_library",
"@com_github_ethereum_go_ethereum//common/hexutil:go_default_library",
"@com_github_pkg_errors//:go_default_library",
],
@@ -29,8 +29,8 @@ go_test(
],
embed = [":go_default_library"],
deps = [
"//api/httputil:go_default_library",
"//beacon-chain/rpc/lookup:go_default_library",
"//network/httputil:go_default_library",
"//testing/assert:go_default_library",
"@com_github_pkg_errors//:go_default_library",
],

View File

@@ -4,10 +4,10 @@ import (
"net/http"
"github.com/pkg/errors"
"github.com/prysmaticlabs/prysm/v5/api/httputil"
"github.com/prysmaticlabs/prysm/v5/beacon-chain/rpc/lookup"
"github.com/prysmaticlabs/prysm/v5/consensus-types/blocks"
"github.com/prysmaticlabs/prysm/v5/consensus-types/interfaces"
"github.com/prysmaticlabs/prysm/v5/network/httputil"
)
// WriteStateFetchError writes an appropriate error based on the supplied argument.

View File

@@ -7,8 +7,8 @@ import (
"testing"
"github.com/pkg/errors"
"github.com/prysmaticlabs/prysm/v5/api/httputil"
"github.com/prysmaticlabs/prysm/v5/beacon-chain/rpc/lookup"
"github.com/prysmaticlabs/prysm/v5/network/httputil"
"github.com/prysmaticlabs/prysm/v5/testing/assert"
)

View File

@@ -9,10 +9,10 @@ import (
"strings"
"github.com/ethereum/go-ethereum/common/hexutil"
httputil2 "github.com/prysmaticlabs/prysm/v5/api/httputil"
"github.com/prysmaticlabs/prysm/v5/api/server/structs"
"github.com/prysmaticlabs/prysm/v5/beacon-chain/blockchain"
"github.com/prysmaticlabs/prysm/v5/beacon-chain/sync"
"github.com/prysmaticlabs/prysm/v5/network/httputil"
)
func UintFromQuery(w http.ResponseWriter, r *http.Request, name string, required bool) (string, uint64, bool) {
@@ -59,24 +59,24 @@ func HexFromRoute(w http.ResponseWriter, r *http.Request, name string, length in
func ValidateHex(w http.ResponseWriter, name, s string, length int) ([]byte, bool) {
if s == "" {
errJson := &httputil.DefaultJsonError{
errJson := &httputil2.DefaultJsonError{
Message: name + " is required",
Code: http.StatusBadRequest,
}
httputil.WriteError(w, errJson)
httputil2.WriteError(w, errJson)
return nil, false
}
hexBytes, err := hexutil.Decode(s)
if err != nil {
errJson := &httputil.DefaultJsonError{
errJson := &httputil2.DefaultJsonError{
Message: name + " is invalid: " + err.Error(),
Code: http.StatusBadRequest,
}
httputil.WriteError(w, errJson)
httputil2.WriteError(w, errJson)
return nil, false
}
if len(hexBytes) != length {
httputil.HandleError(w, fmt.Sprintf("Invalid %s: %s is not length %d", name, s, length), http.StatusBadRequest)
httputil2.HandleError(w, fmt.Sprintf("Invalid %s: %s is not length %d", name, s, length), http.StatusBadRequest)
return nil, false
}
return hexBytes, true
@@ -84,20 +84,20 @@ func ValidateHex(w http.ResponseWriter, name, s string, length int) ([]byte, boo
func ValidateUint(w http.ResponseWriter, name, s string) (uint64, bool) {
if s == "" {
errJson := &httputil.DefaultJsonError{
errJson := &httputil2.DefaultJsonError{
Message: name + " is required",
Code: http.StatusBadRequest,
}
httputil.WriteError(w, errJson)
httputil2.WriteError(w, errJson)
return 0, false
}
v, err := strconv.ParseUint(s, 10, 64)
if err != nil {
errJson := &httputil.DefaultJsonError{
errJson := &httputil2.DefaultJsonError{
Message: name + " is invalid: " + err.Error(),
Code: http.StatusBadRequest,
}
httputil.WriteError(w, errJson)
httputil2.WriteError(w, errJson)
return 0, false
}
return v, true
@@ -119,11 +119,11 @@ func IsSyncing(
headSlot := headFetcher.HeadSlot()
isOptimistic, err := optimisticModeFetcher.IsOptimistic(ctx)
if err != nil {
errJson := &httputil.DefaultJsonError{
errJson := &httputil2.DefaultJsonError{
Message: "Could not check optimistic status: " + err.Error(),
Code: http.StatusInternalServerError,
}
httputil.WriteError(w, errJson)
httputil2.WriteError(w, errJson)
return true
}
syncDetails := &structs.SyncDetailsContainer{
@@ -140,10 +140,10 @@ func IsSyncing(
if err == nil {
msg += " Details: " + string(details)
}
errJson := &httputil.DefaultJsonError{
errJson := &httputil2.DefaultJsonError{
Message: msg,
Code: http.StatusServiceUnavailable}
httputil.WriteError(w, errJson)
httputil2.WriteError(w, errJson)
return true
}
@@ -155,20 +155,20 @@ func IsOptimistic(
) (bool, error) {
isOptimistic, err := optimisticModeFetcher.IsOptimistic(ctx)
if err != nil {
errJson := &httputil.DefaultJsonError{
errJson := &httputil2.DefaultJsonError{
Message: "Could not check optimistic status: " + err.Error(),
Code: http.StatusInternalServerError,
}
httputil.WriteError(w, errJson)
httputil2.WriteError(w, errJson)
return true, err
}
if !isOptimistic {
return false, nil
}
errJson := &httputil.DefaultJsonError{
errJson := &httputil2.DefaultJsonError{
Code: http.StatusServiceUnavailable,
Message: "Beacon node is currently optimistic and not serving validators",
}
httputil.WriteError(w, errJson)
httputil2.WriteError(w, errJson)
return true, nil
}

View File

@@ -11,7 +11,7 @@ go_library(
importpath = "github.com/prysmaticlabs/prysm/v5/beacon-chain/rpc/eth/validator",
visibility = ["//visibility:public"],
deps = [
"//api:go_default_library",
"//api/httputil:go_default_library",
"//api/server/structs:go_default_library",
"//beacon-chain/blockchain:go_default_library",
"//beacon-chain/builder:go_default_library",
@@ -40,7 +40,6 @@ go_library(
"//crypto/bls/common:go_default_library",
"//encoding/bytesutil:go_default_library",
"//monitoring/tracing/trace:go_default_library",
"//network/httputil:go_default_library",
"//proto/prysm/v1alpha1:go_default_library",
"//proto/prysm/v1alpha1/attestation/aggregation/attestations:go_default_library",
"//runtime/version:go_default_library",
@@ -62,7 +61,7 @@ go_test(
],
embed = [":go_default_library"],
deps = [
"//api:go_default_library",
"//api/httputil:go_default_library",
"//api/server/structs:go_default_library",
"//beacon-chain/blockchain/testing:go_default_library",
"//beacon-chain/builder/testing:go_default_library",
@@ -87,7 +86,6 @@ go_test(
"//crypto/bls:go_default_library",
"//crypto/bls/common:go_default_library",
"//encoding/bytesutil:go_default_library",
"//network/httputil:go_default_library",
"//proto/prysm/v1alpha1:go_default_library",
"//runtime/version:go_default_library",
"//testing/assert:go_default_library",

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