eth/catalyst: implement EIP-8161 SSZ-REST Engine API transport

Add SSZ-REST as an alternative Engine API transport alongside JSON-RPC.
When enabled via --authrpc.ssz-rest (alias: --rest), Geth starts an
additional HTTP server that accepts SSZ-encoded payloads over REST,
cutting wire size ~50% and eliminating JSON encode/decode overhead.

New files:
- beacon/engine/ssz.go: SSZ encoding/decoding for all Engine API types
- beacon/engine/ssz_test.go: round-trip tests for SSZ codecs
- eth/catalyst/ssz_rest.go: SSZ-REST HTTP server with JWT auth
- eth/catalyst/ssz_rest_test.go: server unit tests

Modified files:
- beacon/engine/types.go: CommunicationChannel, ExchangeCapabilitiesV2Response
- eth/catalyst/api.go: ExchangeCapabilitiesV2, getSupportedProtocols, server wiring
- node/config.go, defaults.go: SszRestEnabled, SszRestPort config
- node/jwt_handler.go: exported NewJWTHandler for reuse
- cmd/utils/flags.go, cmd/geth/main.go: CLI flags

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
This commit is contained in:
Giulio 2026-03-02 18:40:37 +01:00
parent 5695fbc156
commit 2e357729a3
11 changed files with 2732 additions and 5 deletions

1370
beacon/engine/ssz.go Normal file

File diff suppressed because it is too large Load diff

448
beacon/engine/ssz_test.go Normal file
View file

@ -0,0 +1,448 @@
// Copyright 2025 The go-ethereum Authors
// This file is part of the go-ethereum library.
//
// The go-ethereum library is free software: you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// The go-ethereum library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>.
package engine
import (
"bytes"
"math/big"
"testing"
"github.com/ethereum/go-ethereum/common"
"github.com/ethereum/go-ethereum/core/types"
)
func TestPayloadStatusSSZRoundTrip(t *testing.T) {
hash := common.HexToHash("0x1234567890abcdef1234567890abcdef1234567890abcdef1234567890abcdef")
errMsg := "something went wrong"
tests := []struct {
name string
ps PayloadStatusV1
}{
{
name: "valid with hash",
ps: PayloadStatusV1{
Status: VALID,
LatestValidHash: &hash,
},
},
{
name: "invalid with error",
ps: PayloadStatusV1{
Status: INVALID,
LatestValidHash: &hash,
ValidationError: &errMsg,
},
},
{
name: "syncing no hash",
ps: PayloadStatusV1{
Status: SYNCING,
},
},
{
name: "accepted",
ps: PayloadStatusV1{
Status: ACCEPTED,
},
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
encoded := EncodePayloadStatusSSZ(&tt.ps)
decoded, err := DecodePayloadStatusSSZ(encoded)
if err != nil {
t.Fatalf("decode error: %v", err)
}
if decoded.Status != tt.ps.Status {
t.Errorf("status mismatch: got %s, want %s", decoded.Status, tt.ps.Status)
}
if (decoded.LatestValidHash == nil) != (tt.ps.LatestValidHash == nil) {
t.Errorf("hash nil mismatch")
}
if decoded.LatestValidHash != nil && *decoded.LatestValidHash != *tt.ps.LatestValidHash {
t.Errorf("hash mismatch")
}
if tt.ps.ValidationError != nil {
if decoded.ValidationError == nil || *decoded.ValidationError != *tt.ps.ValidationError {
t.Errorf("validation error mismatch")
}
}
})
}
}
func TestForkchoiceStateSSZRoundTrip(t *testing.T) {
fcs := &ForkchoiceStateV1{
HeadBlockHash: common.HexToHash("0xaaaa"),
SafeBlockHash: common.HexToHash("0xbbbb"),
FinalizedBlockHash: common.HexToHash("0xcccc"),
}
encoded := EncodeForkchoiceStateSSZ(fcs)
if len(encoded) != 96 {
t.Fatalf("expected 96 bytes, got %d", len(encoded))
}
decoded, err := DecodeForkchoiceStateSSZ(encoded)
if err != nil {
t.Fatalf("decode error: %v", err)
}
if decoded.HeadBlockHash != fcs.HeadBlockHash {
t.Errorf("head hash mismatch")
}
if decoded.SafeBlockHash != fcs.SafeBlockHash {
t.Errorf("safe hash mismatch")
}
if decoded.FinalizedBlockHash != fcs.FinalizedBlockHash {
t.Errorf("finalized hash mismatch")
}
}
func TestForkChoiceResponseSSZRoundTrip(t *testing.T) {
hash := common.HexToHash("0x1234")
pid := PayloadID{0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08}
tests := []struct {
name string
resp ForkChoiceResponse
}{
{
name: "with payload id",
resp: ForkChoiceResponse{
PayloadStatus: PayloadStatusV1{
Status: VALID,
LatestValidHash: &hash,
},
PayloadID: &pid,
},
},
{
name: "without payload id",
resp: ForkChoiceResponse{
PayloadStatus: PayloadStatusV1{
Status: SYNCING,
},
},
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
encoded := EncodeForkChoiceResponseSSZ(&tt.resp)
decoded, err := DecodeForkChoiceResponseSSZ(encoded)
if err != nil {
t.Fatalf("decode error: %v", err)
}
if decoded.PayloadStatus.Status != tt.resp.PayloadStatus.Status {
t.Errorf("status mismatch: got %s, want %s", decoded.PayloadStatus.Status, tt.resp.PayloadStatus.Status)
}
if (decoded.PayloadID == nil) != (tt.resp.PayloadID == nil) {
t.Errorf("payloadID nil mismatch: got %v, want %v", decoded.PayloadID, tt.resp.PayloadID)
}
if decoded.PayloadID != nil && *decoded.PayloadID != *tt.resp.PayloadID {
t.Errorf("payloadID mismatch: got %x, want %x", decoded.PayloadID, tt.resp.PayloadID)
}
})
}
}
func TestCapabilitiesSSZRoundTrip(t *testing.T) {
caps := []string{"engine_newPayloadV1", "engine_forkchoiceUpdatedV1", "engine_getPayloadV1"}
encoded := EncodeCapabilitiesSSZ(caps)
decoded, err := DecodeCapabilitiesSSZ(encoded)
if err != nil {
t.Fatalf("decode error: %v", err)
}
if len(decoded) != len(caps) {
t.Fatalf("length mismatch: got %d, want %d", len(decoded), len(caps))
}
for i, c := range caps {
if decoded[i] != c {
t.Errorf("capability[%d] mismatch: got %s, want %s", i, decoded[i], c)
}
}
}
func TestCommunicationChannelsSSZRoundTrip(t *testing.T) {
channels := []CommunicationChannel{
{Protocol: "json_rpc", URL: "localhost:8551"},
{Protocol: "ssz_rest", URL: "http://localhost:8552"},
}
encoded := EncodeCommunicationChannelsSSZ(channels)
decoded, err := DecodeCommunicationChannelsSSZ(encoded)
if err != nil {
t.Fatalf("decode error: %v", err)
}
if len(decoded) != len(channels) {
t.Fatalf("length mismatch: got %d, want %d", len(decoded), len(channels))
}
for i, ch := range channels {
if decoded[i].Protocol != ch.Protocol {
t.Errorf("channel[%d].Protocol mismatch: got %s, want %s", i, decoded[i].Protocol, ch.Protocol)
}
if decoded[i].URL != ch.URL {
t.Errorf("channel[%d].URL mismatch: got %s, want %s", i, decoded[i].URL, ch.URL)
}
}
}
func TestClientVersionSSZRoundTrip(t *testing.T) {
cv := &ClientVersionV1{
Code: "GE",
Name: "go-ethereum",
Version: "1.14.0",
Commit: "0xdeadbeef",
}
encoded := EncodeClientVersionSSZ(cv)
decoded, err := DecodeClientVersionSSZ(encoded)
if err != nil {
t.Fatalf("decode error: %v", err)
}
if decoded.Code != cv.Code || decoded.Name != cv.Name || decoded.Version != cv.Version || decoded.Commit != cv.Commit {
t.Errorf("mismatch: got %+v, want %+v", decoded, cv)
}
}
func TestClientVersionsSSZRoundTrip(t *testing.T) {
versions := []ClientVersionV1{
{Code: "GE", Name: "go-ethereum", Version: "1.14.0", Commit: "0xabcd"},
{Code: "ER", Name: "erigon", Version: "2.59.0", Commit: "0x1234"},
}
encoded := EncodeClientVersionsSSZ(versions)
decoded, err := DecodeClientVersionsSSZ(encoded)
if err != nil {
t.Fatalf("decode error: %v", err)
}
if len(decoded) != len(versions) {
t.Fatalf("length mismatch")
}
for i := range versions {
if decoded[i].Code != versions[i].Code || decoded[i].Name != versions[i].Name {
t.Errorf("version[%d] mismatch", i)
}
}
}
func TestExecutableDataSSZRoundTripV1(t *testing.T) {
baseFee := big.NewInt(7)
ed := &ExecutableData{
ParentHash: common.HexToHash("0x1111"),
FeeRecipient: common.HexToAddress("0x2222"),
StateRoot: common.HexToHash("0x3333"),
ReceiptsRoot: common.HexToHash("0x4444"),
LogsBloom: make([]byte, 256),
Random: common.HexToHash("0x5555"),
Number: 100,
GasLimit: 30000000,
GasUsed: 21000,
Timestamp: 1700000000,
ExtraData: []byte("hello"),
BaseFeePerGas: baseFee,
BlockHash: common.HexToHash("0x6666"),
Transactions: [][]byte{{0x01, 0x02}, {0x03, 0x04, 0x05}},
}
encoded := EncodeExecutableDataSSZ(ed, 1)
decoded, err := DecodeExecutableDataSSZ(encoded, 1)
if err != nil {
t.Fatalf("decode error: %v", err)
}
if decoded.ParentHash != ed.ParentHash {
t.Errorf("ParentHash mismatch")
}
if decoded.Number != ed.Number {
t.Errorf("Number mismatch: got %d, want %d", decoded.Number, ed.Number)
}
if decoded.BaseFeePerGas.Cmp(ed.BaseFeePerGas) != 0 {
t.Errorf("BaseFeePerGas mismatch: got %v, want %v", decoded.BaseFeePerGas, ed.BaseFeePerGas)
}
if len(decoded.Transactions) != len(ed.Transactions) {
t.Fatalf("Transactions length mismatch: got %d, want %d", len(decoded.Transactions), len(ed.Transactions))
}
for i := range ed.Transactions {
if !bytes.Equal(decoded.Transactions[i], ed.Transactions[i]) {
t.Errorf("Transaction[%d] mismatch", i)
}
}
if !bytes.Equal(decoded.ExtraData, ed.ExtraData) {
t.Errorf("ExtraData mismatch")
}
}
func TestExecutableDataSSZRoundTripV3(t *testing.T) {
baseFee := big.NewInt(1000000000)
blobGasUsed := uint64(131072)
excessBlobGas := uint64(262144)
addr := common.HexToAddress("0xdead")
ed := &ExecutableData{
ParentHash: common.HexToHash("0xaa"),
FeeRecipient: addr,
StateRoot: common.HexToHash("0xbb"),
ReceiptsRoot: common.HexToHash("0xcc"),
LogsBloom: make([]byte, 256),
Random: common.HexToHash("0xdd"),
Number: 200,
GasLimit: 30000000,
GasUsed: 42000,
Timestamp: 1700000001,
ExtraData: []byte{},
BaseFeePerGas: baseFee,
BlockHash: common.HexToHash("0xee"),
Transactions: [][]byte{},
Withdrawals: []*types.Withdrawal{
{Index: 0, Validator: 1, Address: addr, Amount: 1000},
{Index: 1, Validator: 2, Address: addr, Amount: 2000},
},
BlobGasUsed: &blobGasUsed,
ExcessBlobGas: &excessBlobGas,
}
encoded := EncodeExecutableDataSSZ(ed, 3)
decoded, err := DecodeExecutableDataSSZ(encoded, 3)
if err != nil {
t.Fatalf("decode error: %v", err)
}
if decoded.Number != ed.Number {
t.Errorf("Number mismatch")
}
if *decoded.BlobGasUsed != *ed.BlobGasUsed {
t.Errorf("BlobGasUsed mismatch")
}
if *decoded.ExcessBlobGas != *ed.ExcessBlobGas {
t.Errorf("ExcessBlobGas mismatch")
}
if len(decoded.Withdrawals) != len(ed.Withdrawals) {
t.Fatalf("Withdrawals length mismatch")
}
for i := range ed.Withdrawals {
if decoded.Withdrawals[i].Index != ed.Withdrawals[i].Index {
t.Errorf("Withdrawal[%d].Index mismatch", i)
}
if decoded.Withdrawals[i].Amount != ed.Withdrawals[i].Amount {
t.Errorf("Withdrawal[%d].Amount mismatch", i)
}
}
}
func TestNewPayloadRequestSSZRoundTripV4(t *testing.T) {
baseFee := big.NewInt(1000000000)
blobGasUsed := uint64(131072)
excessBlobGas := uint64(0)
addr := common.HexToAddress("0xbeef")
ep := &ExecutableData{
ParentHash: common.HexToHash("0x01"),
FeeRecipient: addr,
StateRoot: common.HexToHash("0x02"),
ReceiptsRoot: common.HexToHash("0x03"),
LogsBloom: make([]byte, 256),
Random: common.HexToHash("0x04"),
Number: 300,
GasLimit: 30000000,
GasUsed: 63000,
Timestamp: 1700000002,
ExtraData: []byte("test"),
BaseFeePerGas: baseFee,
BlockHash: common.HexToHash("0x05"),
Transactions: [][]byte{{0xf8}},
Withdrawals: []*types.Withdrawal{},
BlobGasUsed: &blobGasUsed,
ExcessBlobGas: &excessBlobGas,
}
blobHashes := []common.Hash{common.HexToHash("0xb10b")}
beaconRoot := common.HexToHash("0xbeac")
execRequests := [][]byte{
{0x00, 0x01, 0x02}, // deposits
{0x01, 0x03, 0x04}, // withdrawals
}
encoded := EncodeNewPayloadRequestSSZ(ep, blobHashes, &beaconRoot, execRequests, 4)
decEp, decHashes, decRoot, decReqs, err := DecodeNewPayloadRequestSSZ(encoded, 4)
if err != nil {
t.Fatalf("decode error: %v", err)
}
if decEp.Number != ep.Number {
t.Errorf("Number mismatch")
}
if len(decHashes) != 1 || decHashes[0] != blobHashes[0] {
t.Errorf("blob hashes mismatch")
}
if *decRoot != beaconRoot {
t.Errorf("beacon root mismatch")
}
// Structured requests: deposits and withdrawals should be present
if len(decReqs) < 2 {
t.Fatalf("expected at least 2 execution requests, got %d", len(decReqs))
}
}
func TestGetBlobsRequestSSZRoundTrip(t *testing.T) {
hashes := []common.Hash{
common.HexToHash("0x1111"),
common.HexToHash("0x2222"),
common.HexToHash("0x3333"),
}
encoded := EncodeGetBlobsRequestSSZ(hashes)
decoded, err := DecodeGetBlobsRequestSSZ(encoded)
if err != nil {
t.Fatalf("decode error: %v", err)
}
if len(decoded) != len(hashes) {
t.Fatalf("length mismatch")
}
for i := range hashes {
if decoded[i] != hashes[i] {
t.Errorf("hash[%d] mismatch", i)
}
}
}
func TestUint256SSZRoundTrip(t *testing.T) {
tests := []*big.Int{
big.NewInt(0),
big.NewInt(1),
big.NewInt(1000000000),
new(big.Int).SetBytes(common.Hex2Bytes("ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff")),
}
for _, val := range tests {
encoded := uint256ToSSZBytes(val)
decoded := sszBytesToUint256(encoded)
if decoded.Cmp(val) != 0 {
t.Errorf("uint256 roundtrip failed for %v: got %v", val, decoded)
}
}
}
func TestEngineStatusSSZConversion(t *testing.T) {
statuses := []string{VALID, INVALID, SYNCING, ACCEPTED, "INVALID_BLOCK_HASH"}
for _, s := range statuses {
ssz := EngineStatusToSSZ(s)
back := SSZToEngineStatus(ssz)
if back != s {
t.Errorf("status roundtrip failed: %s -> %d -> %s", s, ssz, back)
}
}
}

View file

@ -412,3 +412,15 @@ type ClientVersionV1 struct {
func (v *ClientVersionV1) String() string {
return fmt.Sprintf("%s-%s-%s-%s", v.Code, v.Name, v.Version, v.Commit)
}
// CommunicationChannel represents a communication protocol supported by the EL (EIP-8160).
type CommunicationChannel struct {
Protocol string `json:"protocol"`
URL string `json:"url"`
}
// ExchangeCapabilitiesV2Response is the response to engine_exchangeCapabilitiesV2 (EIP-8160).
type ExchangeCapabilitiesV2Response struct {
Capabilities []string `json:"capabilities"`
SupportedProtocols []CommunicationChannel `json:"supportedProtocols"`
}

View file

@ -171,6 +171,8 @@ var (
utils.AuthPortFlag,
utils.AuthVirtualHostsFlag,
utils.JWTSecretFlag,
utils.AuthRpcSszRestFlag,
utils.AuthRpcSszRestPortFlag,
utils.HTTPVirtualHostsFlag,
utils.GraphQLEnabledFlag,
utils.GraphQLCORSDomainFlag,

View file

@ -688,6 +688,18 @@ var (
Usage: "Path to a JWT secret to use for authenticated RPC endpoints",
Category: flags.APICategory,
}
AuthRpcSszRestFlag = &cli.BoolFlag{
Name: "authrpc.ssz-rest",
Aliases: []string{"rest"},
Usage: "Enable the SSZ-REST Engine API transport (EIP-8161)",
Category: flags.APICategory,
}
AuthRpcSszRestPortFlag = &cli.IntFlag{
Name: "authrpc.ssz-rest.port",
Usage: "SSZ-REST Engine API listening port",
Value: node.DefaultSszRestPort,
Category: flags.APICategory,
}
// Logging and debug settings
EthStatsURLFlag = &cli.StringFlag{
@ -1346,6 +1358,17 @@ func setHTTP(ctx *cli.Context, cfg *node.Config) {
if ctx.IsSet(BatchResponseMaxSize.Name) {
cfg.BatchResponseMaxSize = ctx.Int(BatchResponseMaxSize.Name)
}
// SSZ-REST Engine API (EIP-8161)
if ctx.Bool(AuthRpcSszRestFlag.Name) {
cfg.SszRestEnabled = true
}
if ctx.IsSet(AuthRpcSszRestPortFlag.Name) {
cfg.SszRestPort = ctx.Int(AuthRpcSszRestPortFlag.Name)
}
if cfg.SszRestEnabled && cfg.SszRestPort == 0 {
cfg.SszRestPort = node.DefaultSszRestPort
}
}
// setGraphQL creates the GraphQL listener interface string from the set

View file

@ -48,15 +48,37 @@ import (
)
// Register adds the engine API and related APIs to the full node.
// If SSZ-REST is enabled in the node config, it also starts the SSZ-REST server.
func Register(stack *node.Node, backend *eth.Ethereum) error {
api := NewConsensusAPI(backend)
// Configure SSZ-REST fields from the node config
cfg := stack.Config()
api.authAddr = cfg.AuthAddr
api.authPort = cfg.AuthPort
api.sszRestEnabled = cfg.SszRestEnabled
api.sszRestPort = cfg.SszRestPort
stack.RegisterAPIs([]rpc.API{
newTestingAPI(backend),
{
Namespace: "engine",
Service: NewConsensusAPI(backend),
Service: api,
Authenticated: true,
},
})
// Start SSZ-REST server if enabled
if cfg.SszRestEnabled {
jwtSecret, err := node.ObtainJWTSecret(cfg.JWTSecret)
if err != nil {
return fmt.Errorf("SSZ-REST: failed to obtain JWT secret: %w", err)
}
sszServer := NewSszRestServer(api, jwtSecret, cfg.AuthAddr, cfg.SszRestPort)
stack.RegisterLifecycle(sszServer)
log.Info("[SSZ-REST] Server registered", "addr", cfg.AuthAddr, "port", cfg.SszRestPort)
}
return nil
}
@ -122,6 +144,12 @@ type ConsensusAPI struct {
forkchoiceLock sync.Mutex // Lock for the forkChoiceUpdated method
newPayloadLock sync.Mutex // Lock for the NewPayload method
// SSZ-REST server config (EIP-8161)
sszRestEnabled bool
sszRestPort int
authAddr string
authPort int
}
// NewConsensusAPI creates a new consensus api for the given backend.
@ -1078,14 +1106,21 @@ func (api *ConsensusAPI) checkFork(timestamp uint64, forks ...forks.Fork) bool {
// ExchangeCapabilities returns the current methods provided by this node.
func (api *ConsensusAPI) ExchangeCapabilities([]string) []string {
// Methods that should not be advertised via V1 capabilities
skip := map[string]bool{
"ExchangeCapabilities": true,
"ExchangeCapabilitiesV2": true,
"GetClientCommunicationChannelsV1": true,
}
valueT := reflect.TypeOf(api)
caps := make([]string, 0, valueT.NumMethod())
for i := 0; i < valueT.NumMethod(); i++ {
name := []rune(valueT.Method(i).Name)
if string(name) == "ExchangeCapabilities" {
name := valueT.Method(i).Name
if skip[name] {
continue
}
caps = append(caps, "engine_"+string(unicode.ToLower(name[0]))+string(name[1:]))
runes := []rune(name)
caps = append(caps, "engine_"+string(unicode.ToLower(runes[0]))+string(runes[1:]))
}
return caps
}
@ -1107,6 +1142,37 @@ func (api *ConsensusAPI) GetClientVersionV1(info engine.ClientVersionV1) []engin
}
}
// ExchangeCapabilitiesV2 extends ExchangeCapabilities with supported protocols (EIP-8160).
func (api *ConsensusAPI) ExchangeCapabilitiesV2(fromCl []string) engine.ExchangeCapabilitiesV2Response {
capabilities := api.ExchangeCapabilities(fromCl)
return engine.ExchangeCapabilitiesV2Response{
Capabilities: capabilities,
SupportedProtocols: api.getSupportedProtocols(),
}
}
// GetClientCommunicationChannelsV1 returns the communication protocols supported by this EL (EIP-8160).
func (api *ConsensusAPI) GetClientCommunicationChannelsV1() []engine.CommunicationChannel {
return api.getSupportedProtocols()
}
// getSupportedProtocols returns the list of communication protocols supported by this EL.
func (api *ConsensusAPI) getSupportedProtocols() []engine.CommunicationChannel {
channels := []engine.CommunicationChannel{
{
Protocol: "json_rpc",
URL: fmt.Sprintf("%s:%d", api.authAddr, api.authPort),
},
}
if api.sszRestEnabled && api.sszRestPort > 0 {
channels = append(channels, engine.CommunicationChannel{
Protocol: "ssz_rest",
URL: fmt.Sprintf("http://%s:%d", api.authAddr, api.sszRestPort),
})
}
return channels
}
// GetPayloadBodiesByHashV1 implements engine_getPayloadBodiesByHashV1 which allows for retrieval of a list
// of block bodies by the engine api.
func (api *ConsensusAPI) GetPayloadBodiesByHashV1(hashes []common.Hash) []*engine.ExecutionPayloadBody {

565
eth/catalyst/ssz_rest.go Normal file
View file

@ -0,0 +1,565 @@
// Copyright 2025 The go-ethereum Authors
// This file is part of the go-ethereum library.
//
// The go-ethereum library is free software: you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// The go-ethereum library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>.
package catalyst
import (
"encoding/binary"
"encoding/json"
"fmt"
"io"
"net"
"net/http"
"github.com/ethereum/go-ethereum/beacon/engine"
"github.com/ethereum/go-ethereum/common/hexutil"
"github.com/ethereum/go-ethereum/log"
"github.com/ethereum/go-ethereum/node"
)
// SszRestServer implements the EIP-8161 SSZ-REST Engine API transport.
// It runs alongside the JSON-RPC Engine API and shares the same ConsensusAPI.
type SszRestServer struct {
api *ConsensusAPI
jwtSecret []byte
addr string
port int
server *http.Server
}
// NewSszRestServer creates a new SSZ-REST server.
func NewSszRestServer(api *ConsensusAPI, jwtSecret []byte, addr string, port int) *SszRestServer {
return &SszRestServer{
api: api,
jwtSecret: jwtSecret,
addr: addr,
port: port,
}
}
// Start implements node.Lifecycle. It starts the SSZ-REST HTTP server.
func (s *SszRestServer) Start() error {
mux := http.NewServeMux()
s.registerRoutes(mux)
handler := node.NewJWTHandler(s.jwtSecret, s.panicRecovery(mux))
listenAddr := fmt.Sprintf("%s:%d", s.addr, s.port)
listener, err := net.Listen("tcp", listenAddr)
if err != nil {
return fmt.Errorf("[SSZ-REST] failed to listen on %s: %w", listenAddr, err)
}
s.server = &http.Server{Handler: handler}
log.Info("[SSZ-REST] Engine API server started", "addr", listenAddr)
go func() {
if err := s.server.Serve(listener); err != nil && err != http.ErrServerClosed {
log.Error("[SSZ-REST] Server error", "err", err)
}
}()
return nil
}
// Stop implements node.Lifecycle. It stops the SSZ-REST HTTP server.
func (s *SszRestServer) Stop() error {
if s.server != nil {
log.Info("[SSZ-REST] Stopping server")
return s.server.Close()
}
return nil
}
// panicRecovery wraps a handler with panic recovery.
func (s *SszRestServer) panicRecovery(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
defer func() {
if rec := recover(); rec != nil {
log.Error("[SSZ-REST] panic in handler", "panic", rec, "path", r.URL.Path)
sszErrorResponse(w, http.StatusInternalServerError, -32603, fmt.Sprintf("internal error: %v", rec))
}
}()
next.ServeHTTP(w, r)
})
}
// sszErrorResponse writes a JSON error response for non-200 status codes per EIP-8161.
func sszErrorResponse(w http.ResponseWriter, code int, jsonRpcCode int, message string) {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(code)
resp := struct {
Code int `json:"code"`
Message string `json:"message"`
}{
Code: jsonRpcCode,
Message: message,
}
json.NewEncoder(w).Encode(resp) //nolint:errcheck
}
// sszResponse writes a successful SSZ-encoded response.
func sszResponse(w http.ResponseWriter, data []byte) {
w.Header().Set("Content-Type", "application/octet-stream")
w.WriteHeader(http.StatusOK)
w.Write(data) //nolint:errcheck
}
// readBody reads the request body with a size limit.
func readBody(r *http.Request, maxSize int64) ([]byte, error) {
return io.ReadAll(io.LimitReader(r.Body, maxSize))
}
// registerRoutes registers all SSZ-REST endpoint routes per EIP-8161.
func (s *SszRestServer) registerRoutes(mux *http.ServeMux) {
// newPayload versions
mux.HandleFunc("POST /engine/v1/new_payload", s.handleNewPayloadV1)
mux.HandleFunc("POST /engine/v2/new_payload", s.handleNewPayloadV2)
mux.HandleFunc("POST /engine/v3/new_payload", s.handleNewPayloadV3)
mux.HandleFunc("POST /engine/v4/new_payload", s.handleNewPayloadV4)
mux.HandleFunc("POST /engine/v5/new_payload", s.handleNewPayloadV5)
// forkchoiceUpdated versions
mux.HandleFunc("POST /engine/v1/forkchoice_updated", s.handleForkchoiceUpdatedV1)
mux.HandleFunc("POST /engine/v2/forkchoice_updated", s.handleForkchoiceUpdatedV2)
mux.HandleFunc("POST /engine/v3/forkchoice_updated", s.handleForkchoiceUpdatedV3)
// getPayload versions
mux.HandleFunc("POST /engine/v1/get_payload", s.handleGetPayloadV1)
mux.HandleFunc("POST /engine/v2/get_payload", s.handleGetPayloadV2)
mux.HandleFunc("POST /engine/v3/get_payload", s.handleGetPayloadV3)
mux.HandleFunc("POST /engine/v4/get_payload", s.handleGetPayloadV4)
mux.HandleFunc("POST /engine/v5/get_payload", s.handleGetPayloadV5)
// getBlobs
mux.HandleFunc("POST /engine/v1/get_blobs", s.handleGetBlobsV1)
// exchangeCapabilities
mux.HandleFunc("POST /engine/v1/exchange_capabilities", s.handleExchangeCapabilities)
// getClientVersion
mux.HandleFunc("POST /engine/v1/get_client_version", s.handleGetClientVersion)
// getClientCommunicationChannels (deprecated, kept for backward compat)
mux.HandleFunc("POST /engine/v1/get_client_communication_channels", s.handleGetClientCommunicationChannels)
// exchangeCapabilitiesV2 (EIP-8160)
mux.HandleFunc("POST /engine/v2/exchange_capabilities", s.handleExchangeCapabilitiesV2)
}
// --- newPayload handlers ---
func (s *SszRestServer) handleNewPayloadV1(w http.ResponseWriter, r *http.Request) {
s.handleNewPayload(w, r, 1)
}
func (s *SszRestServer) handleNewPayloadV2(w http.ResponseWriter, r *http.Request) {
s.handleNewPayload(w, r, 2)
}
func (s *SszRestServer) handleNewPayloadV3(w http.ResponseWriter, r *http.Request) {
s.handleNewPayload(w, r, 3)
}
func (s *SszRestServer) handleNewPayloadV4(w http.ResponseWriter, r *http.Request) {
s.handleNewPayload(w, r, 4)
}
func (s *SszRestServer) handleNewPayloadV5(w http.ResponseWriter, r *http.Request) {
s.handleNewPayload(w, r, 5)
}
func (s *SszRestServer) handleNewPayload(w http.ResponseWriter, r *http.Request, version int) {
log.Info("[SSZ-REST] Received NewPayload", "version", version)
body, err := readBody(r, 16*1024*1024) // 16 MB max
if err != nil {
sszErrorResponse(w, http.StatusBadRequest, -32602, "failed to read request body")
return
}
if len(body) == 0 {
sszErrorResponse(w, http.StatusBadRequest, -32602, "empty request body")
return
}
ep, versionedHashes, parentBeaconBlockRoot, executionRequests, err := engine.DecodeNewPayloadRequestSSZ(body, version)
if err != nil {
sszErrorResponse(w, http.StatusBadRequest, -32602, fmt.Sprintf("SSZ decode error: %v", err))
return
}
ctx := r.Context()
var result engine.PayloadStatusV1
switch version {
case 1:
result, err = s.api.NewPayloadV1(ctx, *ep)
case 2:
result, err = s.api.NewPayloadV2(ctx, *ep)
case 3:
result, err = s.api.NewPayloadV3(ctx, *ep, versionedHashes, parentBeaconBlockRoot)
case 4:
hexReqs := make([]hexutil.Bytes, len(executionRequests))
for i, r := range executionRequests {
hexReqs[i] = hexutil.Bytes(r)
}
result, err = s.api.NewPayloadV4(ctx, *ep, versionedHashes, parentBeaconBlockRoot, hexReqs)
case 5:
hexReqs := make([]hexutil.Bytes, len(executionRequests))
for i, r := range executionRequests {
hexReqs[i] = hexutil.Bytes(r)
}
result, err = s.api.NewPayloadV5(ctx, *ep, versionedHashes, parentBeaconBlockRoot, hexReqs)
default:
sszErrorResponse(w, http.StatusBadRequest, -32601, fmt.Sprintf("unsupported newPayload version: %d", version))
return
}
if err != nil {
s.handleEngineError(w, err)
return
}
sszResponse(w, engine.EncodePayloadStatusSSZ(&result))
}
// --- forkchoiceUpdated handlers ---
func (s *SszRestServer) handleForkchoiceUpdatedV1(w http.ResponseWriter, r *http.Request) {
s.handleForkchoiceUpdated(w, r, 1)
}
func (s *SszRestServer) handleForkchoiceUpdatedV2(w http.ResponseWriter, r *http.Request) {
s.handleForkchoiceUpdated(w, r, 2)
}
func (s *SszRestServer) handleForkchoiceUpdatedV3(w http.ResponseWriter, r *http.Request) {
s.handleForkchoiceUpdated(w, r, 3)
}
func (s *SszRestServer) handleForkchoiceUpdated(w http.ResponseWriter, r *http.Request, version int) {
log.Info("[SSZ-REST] Received ForkchoiceUpdated", "version", version)
body, err := readBody(r, 1024*1024) // 1 MB max
if err != nil {
sszErrorResponse(w, http.StatusBadRequest, -32602, "failed to read request body")
return
}
const fixedSize = 100 // forkchoice_state(96) + attributes_offset(4)
if len(body) < 96 {
sszErrorResponse(w, http.StatusBadRequest, -32602, "request body too short for ForkchoiceState")
return
}
fcs, err := engine.DecodeForkchoiceStateSSZ(body[:96])
if err != nil {
sszErrorResponse(w, http.StatusBadRequest, -32602, err.Error())
return
}
var payloadAttributes *engine.PayloadAttributes
if len(body) >= fixedSize {
attrOffset := binary.LittleEndian.Uint32(body[96:100])
if attrOffset <= uint32(len(body)) && attrOffset < uint32(len(body)) {
unionData := body[attrOffset:]
if len(unionData) > 0 {
selector := unionData[0]
if selector == 1 && len(unionData) > 1 {
pa, err := engine.DecodePayloadAttributesSSZ(unionData[1:], version)
if err != nil {
sszErrorResponse(w, http.StatusBadRequest, -32602, err.Error())
return
}
payloadAttributes = pa
}
}
}
}
ctx := r.Context()
var resp engine.ForkChoiceResponse
switch version {
case 1:
resp, err = s.api.ForkchoiceUpdatedV1(*fcs, payloadAttributes)
case 2:
resp, err = s.api.ForkchoiceUpdatedV2(*fcs, payloadAttributes)
case 3:
resp, err = s.api.ForkchoiceUpdatedV3(*fcs, payloadAttributes)
default:
sszErrorResponse(w, http.StatusBadRequest, -32601, fmt.Sprintf("unsupported forkchoiceUpdated version: %d", version))
return
}
_ = ctx // context used by api methods internally
if err != nil {
s.handleEngineError(w, err)
return
}
sszResponse(w, engine.EncodeForkChoiceResponseSSZ(&resp))
}
// --- getPayload handlers ---
func (s *SszRestServer) handleGetPayloadV1(w http.ResponseWriter, r *http.Request) {
s.handleGetPayload(w, r, 1)
}
func (s *SszRestServer) handleGetPayloadV2(w http.ResponseWriter, r *http.Request) {
s.handleGetPayload(w, r, 2)
}
func (s *SszRestServer) handleGetPayloadV3(w http.ResponseWriter, r *http.Request) {
s.handleGetPayload(w, r, 3)
}
func (s *SszRestServer) handleGetPayloadV4(w http.ResponseWriter, r *http.Request) {
s.handleGetPayload(w, r, 4)
}
func (s *SszRestServer) handleGetPayloadV5(w http.ResponseWriter, r *http.Request) {
s.handleGetPayload(w, r, 5)
}
func (s *SszRestServer) handleGetPayload(w http.ResponseWriter, r *http.Request, version int) {
log.Info("[SSZ-REST] Received GetPayload", "version", version)
body, err := readBody(r, 64)
if err != nil {
sszErrorResponse(w, http.StatusBadRequest, -32602, "failed to read request body")
return
}
if len(body) != 8 {
sszErrorResponse(w, http.StatusBadRequest, -32602, fmt.Sprintf("expected 8 bytes for payload ID, got %d", len(body)))
return
}
var payloadID engine.PayloadID
copy(payloadID[:], body)
switch version {
case 1:
result, err := s.api.GetPayloadV1(payloadID)
if err != nil {
s.handleEngineError(w, err)
return
}
envelope := &engine.ExecutionPayloadEnvelope{ExecutionPayload: result}
sszResponse(w, engine.EncodeExecutionPayloadEnvelopeSSZ(envelope, 1))
case 2:
result, err := s.api.GetPayloadV2(payloadID)
if err != nil {
s.handleEngineError(w, err)
return
}
sszResponse(w, engine.EncodeExecutionPayloadEnvelopeSSZ(result, 2))
case 3:
result, err := s.api.GetPayloadV3(payloadID)
if err != nil {
s.handleEngineError(w, err)
return
}
sszResponse(w, engine.EncodeExecutionPayloadEnvelopeSSZ(result, 3))
case 4:
result, err := s.api.GetPayloadV4(payloadID)
if err != nil {
s.handleEngineError(w, err)
return
}
sszResponse(w, engine.EncodeExecutionPayloadEnvelopeSSZ(result, 4))
case 5:
result, err := s.api.GetPayloadV5(payloadID)
if err != nil {
s.handleEngineError(w, err)
return
}
// V5 uses same payload format as V4 for SSZ encoding
sszResponse(w, engine.EncodeExecutionPayloadEnvelopeSSZ(result, 4))
default:
sszErrorResponse(w, http.StatusBadRequest, -32601, fmt.Sprintf("unsupported getPayload version: %d", version))
}
}
// --- getBlobs handler ---
func (s *SszRestServer) handleGetBlobsV1(w http.ResponseWriter, r *http.Request) {
log.Info("[SSZ-REST] Received GetBlobsV1")
body, err := readBody(r, 1024*1024)
if err != nil {
sszErrorResponse(w, http.StatusBadRequest, -32602, "failed to read request body")
return
}
hashes, err := engine.DecodeGetBlobsRequestSSZ(body)
if err != nil {
sszErrorResponse(w, http.StatusBadRequest, -32602, err.Error())
return
}
result, err := s.api.GetBlobsV1(hashes)
if err != nil {
s.handleEngineError(w, err)
return
}
sszResponse(w, encodeGetBlobsV1Response(result))
}
func encodeGetBlobsV1Response(blobs []*engine.BlobAndProofV1) []byte {
const blobAndProofSize = 131072 + 48
var count int
for _, b := range blobs {
if b != nil {
count++
}
}
fixedSize := 4 // list_offset
listSize := count * blobAndProofSize
buf := make([]byte, fixedSize+listSize)
binary.LittleEndian.PutUint32(buf[0:4], uint32(fixedSize))
pos := fixedSize
for _, b := range blobs {
if b == nil {
continue
}
copy(buf[pos:pos+131072], b.Blob)
pos += 131072
copy(buf[pos:pos+48], b.Proof)
pos += 48
}
return buf
}
// --- exchangeCapabilities handler ---
func (s *SszRestServer) handleExchangeCapabilities(w http.ResponseWriter, r *http.Request) {
log.Info("[SSZ-REST] Received ExchangeCapabilities")
body, err := readBody(r, 1024*1024)
if err != nil {
sszErrorResponse(w, http.StatusBadRequest, -32602, "failed to read request body")
return
}
capabilities, err := engine.DecodeCapabilitiesSSZ(body)
if err != nil {
sszErrorResponse(w, http.StatusBadRequest, -32602, err.Error())
return
}
result := s.api.ExchangeCapabilities(capabilities)
sszResponse(w, engine.EncodeCapabilitiesSSZ(result))
}
// --- getClientVersion handler ---
func (s *SszRestServer) handleGetClientVersion(w http.ResponseWriter, r *http.Request) {
log.Info("[SSZ-REST] Received GetClientVersion")
body, err := readBody(r, 1024*1024)
if err != nil {
sszErrorResponse(w, http.StatusBadRequest, -32602, "failed to read request body")
return
}
var callerVersion engine.ClientVersionV1
if len(body) > 0 {
cv, err := engine.DecodeClientVersionSSZ(body)
if err != nil {
sszErrorResponse(w, http.StatusBadRequest, -32602, err.Error())
return
}
callerVersion = *cv
}
result := s.api.GetClientVersionV1(callerVersion)
sszResponse(w, engine.EncodeClientVersionsSSZ(result))
}
// --- exchangeCapabilitiesV2 handler (EIP-8160) ---
func (s *SszRestServer) handleExchangeCapabilitiesV2(w http.ResponseWriter, r *http.Request) {
log.Info("[SSZ-REST] Received ExchangeCapabilitiesV2")
body, err := readBody(r, 1024*1024)
if err != nil {
sszErrorResponse(w, http.StatusBadRequest, -32602, "failed to read request body")
return
}
capabilities, err := engine.DecodeCapabilitiesSSZ(body)
if err != nil {
sszErrorResponse(w, http.StatusBadRequest, -32602, err.Error())
return
}
result := s.api.ExchangeCapabilitiesV2(capabilities)
capBuf := engine.EncodeCapabilitiesSSZ(result.Capabilities)
chanBuf := engine.EncodeCommunicationChannelsSSZ(result.SupportedProtocols)
// SSZ Container: capabilities_offset(4) + channels_offset(4) + data
fixedSize := uint32(8)
buf := make([]byte, 8+len(capBuf)+len(chanBuf))
binary.LittleEndian.PutUint32(buf[0:4], fixedSize)
binary.LittleEndian.PutUint32(buf[4:8], fixedSize+uint32(len(capBuf)))
copy(buf[8:], capBuf)
copy(buf[8+len(capBuf):], chanBuf)
sszResponse(w, buf)
}
// --- getClientCommunicationChannels handler ---
func (s *SszRestServer) handleGetClientCommunicationChannels(w http.ResponseWriter, r *http.Request) {
log.Info("[SSZ-REST] Received GetClientCommunicationChannels")
result := s.api.GetClientCommunicationChannelsV1()
sszResponse(w, engine.EncodeCommunicationChannelsSSZ(result))
}
// handleEngineError converts engine errors to appropriate HTTP error responses.
func (s *SszRestServer) handleEngineError(w http.ResponseWriter, err error) {
log.Warn("[SSZ-REST] Engine error", "err", err)
if engineErr, ok := err.(*engine.EngineAPIError); ok {
code := engineErr.ErrorCode()
switch {
case code == -32602: // InvalidParams
sszErrorResponse(w, http.StatusBadRequest, code, err.Error())
case code == -38005: // UnsupportedFork
sszErrorResponse(w, http.StatusBadRequest, code, err.Error())
default:
sszErrorResponse(w, http.StatusInternalServerError, code, err.Error())
}
return
}
sszErrorResponse(w, http.StatusInternalServerError, -32603, err.Error())
}
// Port returns the configured port for this SSZ-REST server.
func (s *SszRestServer) Port() int {
return s.port
}

View file

@ -0,0 +1,227 @@
// Copyright 2025 The go-ethereum Authors
// This file is part of the go-ethereum library.
//
// The go-ethereum library is free software: you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// The go-ethereum library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>.
package catalyst
import (
"bytes"
"crypto/rand"
"encoding/json"
"net/http"
"testing"
"time"
"github.com/ethereum/go-ethereum/beacon/engine"
"github.com/ethereum/go-ethereum/node"
"github.com/golang-jwt/jwt/v4"
)
func makeJWTToken(secret []byte) string {
token := jwt.NewWithClaims(jwt.SigningMethodHS256, jwt.MapClaims{
"iat": time.Now().Unix(),
})
ss, _ := token.SignedString(secret)
return ss
}
type testResponseWriter struct {
code int
headers http.Header
body bytes.Buffer
}
func (w *testResponseWriter) Header() http.Header { return w.headers }
func (w *testResponseWriter) Write(b []byte) (int, error) { return w.body.Write(b) }
func (w *testResponseWriter) WriteHeader(code int) { w.code = code }
// TestSszRestJWTAuth tests that JWT auth is enforced.
func TestSszRestJWTAuth(t *testing.T) {
secret := make([]byte, 32)
rand.Read(secret)
mux := http.NewServeMux()
mux.HandleFunc("POST /test", func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusOK)
w.Write([]byte("ok"))
})
handler := node.NewJWTHandler(secret, mux)
// Test with valid token
token := makeJWTToken(secret)
req, _ := http.NewRequest("POST", "/test", nil)
req.Header.Set("Authorization", "Bearer "+token)
rr := &testResponseWriter{headers: make(http.Header)}
handler.ServeHTTP(rr, req)
if rr.code != http.StatusOK {
t.Errorf("expected 200 with valid JWT, got %d", rr.code)
}
// Test without token
req2, _ := http.NewRequest("POST", "/test", nil)
rr2 := &testResponseWriter{headers: make(http.Header)}
handler.ServeHTTP(rr2, req2)
if rr2.code != http.StatusUnauthorized {
t.Errorf("expected 401 without JWT, got %d", rr2.code)
}
}
// TestSszRestCapabilities tests the exchange_capabilities SSZ encoding.
func TestSszRestCapabilities(t *testing.T) {
caps := []string{"engine_newPayloadV4", "engine_forkchoiceUpdatedV3"}
encoded := engine.EncodeCapabilitiesSSZ(caps)
decoded, err := engine.DecodeCapabilitiesSSZ(encoded)
if err != nil {
t.Fatal(err)
}
if len(decoded) != 2 {
t.Fatalf("expected 2 caps, got %d", len(decoded))
}
if decoded[0] != "engine_newPayloadV4" {
t.Errorf("unexpected cap: %s", decoded[0])
}
}
// TestSszRestErrorFormat tests that error responses are JSON per EIP-8161.
func TestSszRestErrorFormat(t *testing.T) {
rr := &testResponseWriter{headers: make(http.Header), code: 200}
sszErrorResponse(rr, http.StatusBadRequest, -32602, "test error")
if rr.code != http.StatusBadRequest {
t.Errorf("expected 400, got %d", rr.code)
}
if rr.headers.Get("Content-Type") != "application/json" {
t.Errorf("expected application/json, got %s", rr.headers.Get("Content-Type"))
}
var errResp struct {
Code int `json:"code"`
Message string `json:"message"`
}
if err := json.Unmarshal(rr.body.Bytes(), &errResp); err != nil {
t.Fatal(err)
}
if errResp.Code != -32602 {
t.Errorf("expected -32602, got %d", errResp.Code)
}
if errResp.Message != "test error" {
t.Errorf("expected 'test error', got '%s'", errResp.Message)
}
}
// TestSszRestSuccessFormat tests that success responses are SSZ per EIP-8161.
func TestSszRestSuccessFormat(t *testing.T) {
rr := &testResponseWriter{headers: make(http.Header), code: 200}
data := []byte{0x01, 0x02, 0x03}
sszResponse(rr, data)
if rr.code != http.StatusOK {
t.Errorf("expected 200, got %d", rr.code)
}
if rr.headers.Get("Content-Type") != "application/octet-stream" {
t.Errorf("expected application/octet-stream, got %s", rr.headers.Get("Content-Type"))
}
if !bytes.Equal(rr.body.Bytes(), data) {
t.Errorf("body mismatch")
}
}
// TestSszRestExchangeCapabilitiesV2Format tests the V2 response container format.
func TestSszRestExchangeCapabilitiesV2Format(t *testing.T) {
caps := []string{"engine_newPayloadV4", "engine_getPayloadV4"}
channels := []engine.CommunicationChannel{
{Protocol: "json_rpc", URL: "localhost:8551"},
{Protocol: "ssz_rest", URL: "http://localhost:8552"},
}
capBuf := engine.EncodeCapabilitiesSSZ(caps)
chanBuf := engine.EncodeCommunicationChannelsSSZ(channels)
// Build the V2 response container: offset(4) + offset(4) + data
fixedSize := uint32(8)
buf := make([]byte, 8+len(capBuf)+len(chanBuf))
le32(buf[0:4], fixedSize)
le32(buf[4:8], fixedSize+uint32(len(capBuf)))
copy(buf[8:], capBuf)
copy(buf[8+len(capBuf):], chanBuf)
// Decode
capOffset := rd32(buf[0:4])
chanOffset := rd32(buf[4:8])
decodedCaps, err := engine.DecodeCapabilitiesSSZ(buf[capOffset:chanOffset])
if err != nil {
t.Fatal(err)
}
decodedChannels, err := engine.DecodeCommunicationChannelsSSZ(buf[chanOffset:])
if err != nil {
t.Fatal(err)
}
if len(decodedCaps) != 2 || decodedCaps[0] != "engine_newPayloadV4" {
t.Errorf("caps mismatch: %v", decodedCaps)
}
if len(decodedChannels) != 2 || decodedChannels[1].Protocol != "ssz_rest" {
t.Errorf("channels mismatch: %v", decodedChannels)
}
}
// TestSszRestGetSupportedProtocols tests the getSupportedProtocols helper.
func TestSszRestGetSupportedProtocols(t *testing.T) {
api := &ConsensusAPI{
sszRestEnabled: true,
sszRestPort: 8552,
authAddr: "127.0.0.1",
authPort: 8551,
}
channels := api.getSupportedProtocols()
if len(channels) != 2 {
t.Fatalf("expected 2 channels, got %d", len(channels))
}
if channels[0].Protocol != "json_rpc" {
t.Errorf("first channel should be json_rpc, got %s", channels[0].Protocol)
}
if channels[1].Protocol != "ssz_rest" {
t.Errorf("second channel should be ssz_rest, got %s", channels[1].Protocol)
}
if channels[1].URL != "http://127.0.0.1:8552" {
t.Errorf("unexpected URL: %s", channels[1].URL)
}
// Without SSZ-REST
api2 := &ConsensusAPI{
sszRestEnabled: false,
authAddr: "127.0.0.1",
authPort: 8551,
}
channels2 := api2.getSupportedProtocols()
if len(channels2) != 1 {
t.Fatalf("expected 1 channel without SSZ-REST, got %d", len(channels2))
}
}
func le32(buf []byte, v uint32) {
buf[0] = byte(v)
buf[1] = byte(v >> 8)
buf[2] = byte(v >> 16)
buf[3] = byte(v >> 24)
}
func rd32(buf []byte) uint32 {
return uint32(buf[0]) | uint32(buf[1])<<8 | uint32(buf[2])<<16 | uint32(buf[3])<<24
}

View file

@ -147,6 +147,13 @@ type Config struct {
// for the authenticated api. This is by default {'localhost'}.
AuthVirtualHosts []string `toml:",omitempty"`
// SszRestEnabled enables the SSZ-REST Engine API transport (EIP-8161).
SszRestEnabled bool `toml:",omitempty"`
// SszRestPort is the port for the SSZ-REST Engine API server.
// Defaults to 8552 if not specified.
SszRestPort int `toml:",omitempty"`
// WSHost is the host interface on which to start the websocket RPC server. If
// this field is empty, no websocket API endpoint will be started.
WSHost string

View file

@ -34,7 +34,8 @@ const (
DefaultWSHost = "localhost" // Default host interface for the websocket RPC server
DefaultWSPort = 8546 // Default TCP port for the websocket RPC server
DefaultAuthHost = "localhost" // Default host interface for the authenticated apis
DefaultAuthPort = 8551 // Default port for the authenticated apis
DefaultAuthPort = 8551 // Default port for the authenticated apis
DefaultSszRestPort = 8552 // Default port for the SSZ-REST Engine API (EIP-8161)
)
const (

View file

@ -31,6 +31,12 @@ type jwtHandler struct {
next http.Handler
}
// NewJWTHandler creates a http.Handler with jwt authentication support.
// This is the exported version for use by the SSZ-REST server (EIP-8161).
func NewJWTHandler(secret []byte, next http.Handler) http.Handler {
return newJWTHandler(secret, next)
}
// newJWTHandler creates a http.Handler with jwt authentication support.
func newJWTHandler(secret []byte, next http.Handler) http.Handler {
return &jwtHandler{