mirror of
https://github.com/ethereum/go-ethereum.git
synced 2026-07-24 05:36:46 +00:00
restapi: implement trustless REST API
This commit is contained in:
parent
a3aae29845
commit
8708c2e1cc
6 changed files with 362 additions and 0 deletions
|
|
@ -28,7 +28,9 @@ import (
|
||||||
"github.com/ethereum/go-ethereum/ethdb/memorydb"
|
"github.com/ethereum/go-ethereum/ethdb/memorydb"
|
||||||
"github.com/ethereum/go-ethereum/event"
|
"github.com/ethereum/go-ethereum/event"
|
||||||
"github.com/ethereum/go-ethereum/log"
|
"github.com/ethereum/go-ethereum/log"
|
||||||
|
"github.com/ethereum/go-ethereum/restapi"
|
||||||
"github.com/ethereum/go-ethereum/rpc"
|
"github.com/ethereum/go-ethereum/rpc"
|
||||||
|
"github.com/gorilla/mux"
|
||||||
)
|
)
|
||||||
|
|
||||||
type Client struct {
|
type Client struct {
|
||||||
|
|
|
||||||
|
|
@ -44,6 +44,7 @@ import (
|
||||||
"github.com/ethereum/go-ethereum/log"
|
"github.com/ethereum/go-ethereum/log"
|
||||||
"github.com/ethereum/go-ethereum/metrics"
|
"github.com/ethereum/go-ethereum/metrics"
|
||||||
"github.com/ethereum/go-ethereum/node"
|
"github.com/ethereum/go-ethereum/node"
|
||||||
|
"github.com/ethereum/go-ethereum/restapi"
|
||||||
"github.com/ethereum/go-ethereum/rpc"
|
"github.com/ethereum/go-ethereum/rpc"
|
||||||
"github.com/naoina/toml"
|
"github.com/naoina/toml"
|
||||||
"github.com/urfave/cli/v2"
|
"github.com/urfave/cli/v2"
|
||||||
|
|
@ -259,6 +260,10 @@ func makeFullNode(ctx *cli.Context) *node.Node {
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Register REST API.
|
||||||
|
restServer := restapi.NewServer(stack)
|
||||||
|
restServer.Register(restapi.ExecutionAPI(restServer, backend))
|
||||||
|
|
||||||
// Configure log filter RPC API.
|
// Configure log filter RPC API.
|
||||||
filterSystem := utils.RegisterFilterAPI(stack, backend, &cfg.Eth)
|
filterSystem := utils.RegisterFilterAPI(stack, backend, &cfg.Eth)
|
||||||
|
|
||||||
|
|
@ -300,6 +305,7 @@ func makeFullNode(ctx *cli.Context) *node.Node {
|
||||||
srv.RegisterName("engine", catalyst.NewConsensusAPI(eth))
|
srv.RegisterName("engine", catalyst.NewConsensusAPI(eth))
|
||||||
blsyncer := blsync.NewClient(utils.MakeBeaconLightConfig(ctx))
|
blsyncer := blsync.NewClient(utils.MakeBeaconLightConfig(ctx))
|
||||||
blsyncer.SetEngineRPC(rpc.DialInProc(srv))
|
blsyncer.SetEngineRPC(rpc.DialInProc(srv))
|
||||||
|
restServer.Register(blsyncer.RestAPI())
|
||||||
stack.RegisterLifecycle(blsyncer)
|
stack.RegisterLifecycle(blsyncer)
|
||||||
} else {
|
} else {
|
||||||
// Launch the engine API for interacting with external consensus client.
|
// Launch the engine API for interacting with external consensus client.
|
||||||
|
|
|
||||||
2
go.mod
2
go.mod
|
|
@ -102,6 +102,7 @@ require (
|
||||||
github.com/cpuguy83/go-md2man/v2 v2.0.5 // indirect
|
github.com/cpuguy83/go-md2man/v2 v2.0.5 // indirect
|
||||||
github.com/deepmap/oapi-codegen v1.6.0 // indirect
|
github.com/deepmap/oapi-codegen v1.6.0 // indirect
|
||||||
github.com/dlclark/regexp2 v1.7.0 // indirect
|
github.com/dlclark/regexp2 v1.7.0 // indirect
|
||||||
|
github.com/elnormous/contenttype v1.0.4 // indirect
|
||||||
github.com/emicklei/dot v1.6.2 // indirect
|
github.com/emicklei/dot v1.6.2 // indirect
|
||||||
github.com/fjl/gencodec v0.1.0 // indirect
|
github.com/fjl/gencodec v0.1.0 // indirect
|
||||||
github.com/garslo/gogen v0.0.0-20170306192744-1d203ffc1f61 // indirect
|
github.com/garslo/gogen v0.0.0-20170306192744-1d203ffc1f61 // indirect
|
||||||
|
|
@ -113,6 +114,7 @@ require (
|
||||||
github.com/golang/protobuf v1.5.4 // indirect
|
github.com/golang/protobuf v1.5.4 // indirect
|
||||||
github.com/google/go-querystring v1.1.0 // indirect
|
github.com/google/go-querystring v1.1.0 // indirect
|
||||||
github.com/google/pprof v0.0.0-20230207041349-798e818bf904 // indirect
|
github.com/google/pprof v0.0.0-20230207041349-798e818bf904 // indirect
|
||||||
|
github.com/gorilla/mux v1.8.1 // indirect
|
||||||
github.com/influxdata/line-protocol v0.0.0-20200327222509-2487e7298839 // indirect
|
github.com/influxdata/line-protocol v0.0.0-20200327222509-2487e7298839 // indirect
|
||||||
github.com/jmespath/go-jmespath v0.4.0 // indirect
|
github.com/jmespath/go-jmespath v0.4.0 // indirect
|
||||||
github.com/kilic/bls12-381 v0.1.0 // indirect
|
github.com/kilic/bls12-381 v0.1.0 // indirect
|
||||||
|
|
|
||||||
4
go.sum
4
go.sum
|
|
@ -109,6 +109,8 @@ github.com/dop251/goja v0.0.0-20230605162241-28ee0ee714f3 h1:+3HCtB74++ClLy8GgjU
|
||||||
github.com/dop251/goja v0.0.0-20230605162241-28ee0ee714f3/go.mod h1:QMWlm50DNe14hD7t24KEqZuUdC9sOTy8W6XbCU1mlw4=
|
github.com/dop251/goja v0.0.0-20230605162241-28ee0ee714f3/go.mod h1:QMWlm50DNe14hD7t24KEqZuUdC9sOTy8W6XbCU1mlw4=
|
||||||
github.com/dop251/goja_nodejs v0.0.0-20210225215109-d91c329300e7/go.mod h1:hn7BA7c8pLvoGndExHudxTDKZ84Pyvv+90pbBjbTz0Y=
|
github.com/dop251/goja_nodejs v0.0.0-20210225215109-d91c329300e7/go.mod h1:hn7BA7c8pLvoGndExHudxTDKZ84Pyvv+90pbBjbTz0Y=
|
||||||
github.com/dop251/goja_nodejs v0.0.0-20211022123610-8dd9abb0616d/go.mod h1:DngW8aVqWbuLRMHItjPUyqdj+HWPvnQe8V8y1nDpIbM=
|
github.com/dop251/goja_nodejs v0.0.0-20211022123610-8dd9abb0616d/go.mod h1:DngW8aVqWbuLRMHItjPUyqdj+HWPvnQe8V8y1nDpIbM=
|
||||||
|
github.com/elnormous/contenttype v1.0.4 h1:FjmVNkvQOGqSX70yvocph7keC8DtmJaLzTTq6ZOQCI8=
|
||||||
|
github.com/elnormous/contenttype v1.0.4/go.mod h1:5KTOW8m1kdX1dLMiUJeN9szzR2xkngiv2K+RVZwWBbI=
|
||||||
github.com/emicklei/dot v1.6.2 h1:08GN+DD79cy/tzN6uLCT84+2Wk9u+wvqP+Hkx/dIR8A=
|
github.com/emicklei/dot v1.6.2 h1:08GN+DD79cy/tzN6uLCT84+2Wk9u+wvqP+Hkx/dIR8A=
|
||||||
github.com/emicklei/dot v1.6.2/go.mod h1:DeV7GvQtIw4h2u73RKBkkFdvVAz0D9fzeJrgPW6gy/s=
|
github.com/emicklei/dot v1.6.2/go.mod h1:DeV7GvQtIw4h2u73RKBkkFdvVAz0D9fzeJrgPW6gy/s=
|
||||||
github.com/ethereum/c-kzg-4844/v2 v2.1.3 h1:DQ21UU0VSsuGy8+pcMJHDS0CV1bKmJmxsJYK8l3MiLU=
|
github.com/ethereum/c-kzg-4844/v2 v2.1.3 h1:DQ21UU0VSsuGy8+pcMJHDS0CV1bKmJmxsJYK8l3MiLU=
|
||||||
|
|
@ -183,6 +185,8 @@ github.com/google/pprof v0.0.0-20230207041349-798e818bf904/go.mod h1:uglQLonpP8q
|
||||||
github.com/google/uuid v1.3.0 h1:t6JiXgmwXMjEs8VusXIJk2BXHsn+wx8BZdTaoZ5fu7I=
|
github.com/google/uuid v1.3.0 h1:t6JiXgmwXMjEs8VusXIJk2BXHsn+wx8BZdTaoZ5fu7I=
|
||||||
github.com/google/uuid v1.3.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
|
github.com/google/uuid v1.3.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
|
||||||
github.com/gorilla/mux v1.8.0/go.mod h1:DVbg23sWSpFRCP0SfiEN6jmj59UnW/n46BH5rLB71So=
|
github.com/gorilla/mux v1.8.0/go.mod h1:DVbg23sWSpFRCP0SfiEN6jmj59UnW/n46BH5rLB71So=
|
||||||
|
github.com/gorilla/mux v1.8.1 h1:TuBL49tXwgrFYWhqrNgrUNEY92u81SPhu7sTdzQEiWY=
|
||||||
|
github.com/gorilla/mux v1.8.1/go.mod h1:AKf9I4AEqPTmMytcMc0KkNouC66V3BtZ4qD5fmWSiMQ=
|
||||||
github.com/gorilla/websocket v1.4.2 h1:+/TMaTYc4QFitKJxsQ7Yye35DkWvkdLcvGKqM+x0Ufc=
|
github.com/gorilla/websocket v1.4.2 h1:+/TMaTYc4QFitKJxsQ7Yye35DkWvkdLcvGKqM+x0Ufc=
|
||||||
github.com/gorilla/websocket v1.4.2/go.mod h1:YR8l580nyteQvAITg2hZ9XVh4b55+EU/adAjf1fMHhE=
|
github.com/gorilla/websocket v1.4.2/go.mod h1:YR8l580nyteQvAITg2hZ9XVh4b55+EU/adAjf1fMHhE=
|
||||||
github.com/graph-gophers/graphql-go v1.3.0 h1:Eb9x/q6MFpCLz7jBCiP/WTxjSDrYLR1QY41SORZyNJ0=
|
github.com/graph-gophers/graphql-go v1.3.0 h1:Eb9x/q6MFpCLz7jBCiP/WTxjSDrYLR1QY41SORZyNJ0=
|
||||||
|
|
|
||||||
197
restapi/exec_api.go
Normal file
197
restapi/exec_api.go
Normal file
|
|
@ -0,0 +1,197 @@
|
||||||
|
// 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 restapi
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"errors"
|
||||||
|
"net/http"
|
||||||
|
"net/url"
|
||||||
|
"strconv"
|
||||||
|
"strings"
|
||||||
|
|
||||||
|
"github.com/ethereum/go-ethereum/common"
|
||||||
|
"github.com/ethereum/go-ethereum/common/hexutil"
|
||||||
|
"github.com/ethereum/go-ethereum/core/types"
|
||||||
|
"github.com/ethereum/go-ethereum/params/forks"
|
||||||
|
"github.com/ethereum/go-ethereum/rpc"
|
||||||
|
"github.com/gorilla/mux"
|
||||||
|
)
|
||||||
|
|
||||||
|
type execApiServer struct {
|
||||||
|
apiBackend backend
|
||||||
|
}
|
||||||
|
|
||||||
|
func ExecutionAPI(server *Server, backend backend) API {
|
||||||
|
api := execApiServer{apiBackend: backend}
|
||||||
|
return func(router *mux.Router) {
|
||||||
|
router.HandleFunc("/eth/v1/exec/headers/{blockid}", server.WrapHandler(api.handleHeaders, false, false, true)).Methods("GET")
|
||||||
|
router.HandleFunc("/eth/v1/exec/blocks", server.WrapHandler(api.handleBlocks, false, false, true)).Methods("GET")
|
||||||
|
router.HandleFunc("/eth/v1/exec/block_receipts", server.WrapHandler(api.handleBlockReceipts, false, false, true)).Methods("GET")
|
||||||
|
router.HandleFunc("/eth/v1/exec/transaction", server.WrapHandler(api.handleTransaction, false, false, true)).Methods("GET")
|
||||||
|
router.HandleFunc("/eth/v1/exec/transaction_by_index", server.WrapHandler(api.handleTxByIndex, false, false, true)).Methods("GET")
|
||||||
|
router.HandleFunc("/eth/v1/exec/receipt_by_index", server.WrapHandler(api.handleReceiptByIndex, false, false, true)).Methods("GET")
|
||||||
|
router.HandleFunc("/eth/v1/exec/state", server.WrapHandler(api.handleState, true, true, true)).Methods("POST")
|
||||||
|
router.HandleFunc("/eth/v1/exec/call", server.WrapHandler(api.handleCall, true, true, true)).Methods("POST")
|
||||||
|
router.HandleFunc("/eth/v1/exec/send_transaction", server.WrapHandler(api.handleSendTransaction, true, true, true)).Methods("POST")
|
||||||
|
router.HandleFunc("/eth/v1/exec/history", server.WrapHandler(api.handleHistory, false, false, true)).Methods("GET")
|
||||||
|
router.HandleFunc("/eth/v1/exec/transaction_position", server.WrapHandler(api.handleTxPosition, false, false, true)).Methods("GET")
|
||||||
|
router.HandleFunc("/eth/v1/exec/logs", server.WrapHandler(api.handleLogs, false, false, true)).Methods("GET")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
type blockId struct {
|
||||||
|
hash common.Hash
|
||||||
|
number uint64
|
||||||
|
}
|
||||||
|
|
||||||
|
func (b *blockId) isHash() bool {
|
||||||
|
return b.hash != (common.Hash{})
|
||||||
|
}
|
||||||
|
|
||||||
|
func getBlockId(id string) (blockId, bool) {
|
||||||
|
if hex, err := hexutil.Decode(id); err == nil {
|
||||||
|
if len(hex) != common.HashLength {
|
||||||
|
return blockId{}, false
|
||||||
|
}
|
||||||
|
var b blockId
|
||||||
|
copy(b.hash[:], hex)
|
||||||
|
return b, true
|
||||||
|
}
|
||||||
|
if number, err := strconv.ParseUint(id, 10, 64); err == nil {
|
||||||
|
return blockId{number: number}, true
|
||||||
|
}
|
||||||
|
return blockId{}, false
|
||||||
|
}
|
||||||
|
|
||||||
|
// forkId returns the fork corresponding to the given header.
|
||||||
|
// Note that frontier thawing and difficulty bomb adjustments are ignored according
|
||||||
|
// to the API specification as they do not affect the interpretation of the
|
||||||
|
// returned data structures.
|
||||||
|
func (s *execApiServer) forkId(header *types.Header) forks.Fork {
|
||||||
|
c := s.apiBackend.ChainConfig()
|
||||||
|
switch {
|
||||||
|
case header.Difficulty.Sign() == 0:
|
||||||
|
return c.LatestFork(header.Time)
|
||||||
|
case c.IsLondon(header.Number):
|
||||||
|
return forks.London
|
||||||
|
case c.IsBerlin(header.Number):
|
||||||
|
return forks.Berlin
|
||||||
|
case c.IsIstanbul(header.Number):
|
||||||
|
return forks.Istanbul
|
||||||
|
case c.IsPetersburg(header.Number):
|
||||||
|
return forks.Petersburg
|
||||||
|
case c.IsConstantinople(header.Number):
|
||||||
|
return forks.Constantinople
|
||||||
|
case c.IsByzantium(header.Number):
|
||||||
|
return forks.Byzantium
|
||||||
|
case c.IsEIP155(header.Number):
|
||||||
|
return forks.SpuriousDragon
|
||||||
|
case c.IsEIP150(header.Number):
|
||||||
|
return forks.TangerineWhistle
|
||||||
|
case c.IsDAOFork(header.Number):
|
||||||
|
return forks.DAO
|
||||||
|
case c.IsHomestead(header.Number):
|
||||||
|
return forks.Homestead
|
||||||
|
default:
|
||||||
|
return forks.Frontier
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *execApiServer) forkName(header *types.Header) string {
|
||||||
|
return strings.ToLower(s.forkId(header).String())
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *execApiServer) handleHeaders(ctx context.Context, values url.Values, vars map[string]string, decodeBody func(*any) error) (any, string, int) {
|
||||||
|
type headerResponse struct {
|
||||||
|
Version string `json:"version"`
|
||||||
|
Data *types.Header `json:"data"`
|
||||||
|
}
|
||||||
|
var (
|
||||||
|
amount int
|
||||||
|
response []headerResponse
|
||||||
|
err error
|
||||||
|
)
|
||||||
|
id, ok := getBlockId(vars["blockid"])
|
||||||
|
if !ok {
|
||||||
|
return nil, "invalid block id", http.StatusBadRequest
|
||||||
|
}
|
||||||
|
if s := values.Get("amount"); s != "" {
|
||||||
|
amount, err = strconv.Atoi(s)
|
||||||
|
if err != nil || amount <= 0 {
|
||||||
|
return nil, "invalid amount", http.StatusBadRequest
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
amount = 1
|
||||||
|
}
|
||||||
|
|
||||||
|
response = make([]headerResponse, amount)
|
||||||
|
for i := amount - 1; i >= 0; i-- {
|
||||||
|
if id.isHash() {
|
||||||
|
response[i].Data, err = s.apiBackend.HeaderByHash(ctx, id.hash)
|
||||||
|
} else {
|
||||||
|
response[i].Data, err = s.apiBackend.HeaderByNumber(ctx, rpc.BlockNumber(id.number))
|
||||||
|
}
|
||||||
|
if errors.Is(err, context.Canceled) {
|
||||||
|
return nil, "request timeout", http.StatusRequestTimeout
|
||||||
|
}
|
||||||
|
if response[i].Data == nil {
|
||||||
|
return nil, "not available", http.StatusNotFound
|
||||||
|
}
|
||||||
|
response[i].Version = s.forkName(response[i].Data)
|
||||||
|
if response[i].Data.Number.Uint64() == 0 {
|
||||||
|
response = response[i:]
|
||||||
|
break
|
||||||
|
}
|
||||||
|
id = blockId{hash: response[i].Data.ParentHash}
|
||||||
|
}
|
||||||
|
return response, "", 0
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *execApiServer) handleBlocks(ctx context.Context, values url.Values, vars map[string]string, decodeBody func(*any) error) (any, string, int) {
|
||||||
|
panic("TODO")
|
||||||
|
}
|
||||||
|
func (s *execApiServer) handleBlockReceipts(ctx context.Context, values url.Values, vars map[string]string, decodeBody func(*any) error) (any, string, int) {
|
||||||
|
panic("TODO")
|
||||||
|
}
|
||||||
|
func (s *execApiServer) handleTransaction(ctx context.Context, values url.Values, vars map[string]string, decodeBody func(*any) error) (any, string, int) {
|
||||||
|
panic("TODO")
|
||||||
|
}
|
||||||
|
func (s *execApiServer) handleTxByIndex(ctx context.Context, values url.Values, vars map[string]string, decodeBody func(*any) error) (any, string, int) {
|
||||||
|
panic("TODO")
|
||||||
|
}
|
||||||
|
func (s *execApiServer) handleReceiptByIndex(ctx context.Context, values url.Values, vars map[string]string, decodeBody func(*any) error) (any, string, int) {
|
||||||
|
panic("TODO")
|
||||||
|
}
|
||||||
|
func (s *execApiServer) handleState(ctx context.Context, values url.Values, vars map[string]string, decodeBody func(*any) error) (any, string, int) {
|
||||||
|
panic("TODO")
|
||||||
|
}
|
||||||
|
func (s *execApiServer) handleCall(ctx context.Context, values url.Values, vars map[string]string, decodeBody func(*any) error) (any, string, int) {
|
||||||
|
panic("TODO")
|
||||||
|
}
|
||||||
|
func (s *execApiServer) handleHistory(ctx context.Context, values url.Values, vars map[string]string, decodeBody func(*any) error) (any, string, int) {
|
||||||
|
panic("TODO")
|
||||||
|
} // Requires EIP-7745
|
||||||
|
func (s *execApiServer) handleTxPosition(ctx context.Context, values url.Values, vars map[string]string, decodeBody func(*any) error) (any, string, int) {
|
||||||
|
panic("TODO")
|
||||||
|
} // Requires EIP-7745
|
||||||
|
func (s *execApiServer) handleLogs(ctx context.Context, values url.Values, vars map[string]string, decodeBody func(*any) error) (any, string, int) {
|
||||||
|
panic("TODO")
|
||||||
|
} // Requires EIP-7745
|
||||||
|
func (s *execApiServer) handleSendTransaction(ctx context.Context, values url.Values, vars map[string]string, decodeBody func(*any) error) (any, string, int) {
|
||||||
|
panic("TODO")
|
||||||
|
}
|
||||||
151
restapi/server.go
Normal file
151
restapi/server.go
Normal file
|
|
@ -0,0 +1,151 @@
|
||||||
|
// 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 restapi
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"encoding/json"
|
||||||
|
"io/ioutil"
|
||||||
|
"net/http"
|
||||||
|
"net/url"
|
||||||
|
|
||||||
|
"github.com/elnormous/contenttype"
|
||||||
|
"github.com/ethereum/go-ethereum/common"
|
||||||
|
"github.com/ethereum/go-ethereum/core/types"
|
||||||
|
"github.com/ethereum/go-ethereum/node"
|
||||||
|
"github.com/ethereum/go-ethereum/params"
|
||||||
|
"github.com/ethereum/go-ethereum/rlp"
|
||||||
|
"github.com/ethereum/go-ethereum/rpc"
|
||||||
|
"github.com/gorilla/mux"
|
||||||
|
)
|
||||||
|
|
||||||
|
type Server struct {
|
||||||
|
router *mux.Router
|
||||||
|
}
|
||||||
|
|
||||||
|
type API func(*mux.Router)
|
||||||
|
|
||||||
|
type backend interface {
|
||||||
|
HeaderByNumber(ctx context.Context, number rpc.BlockNumber) (*types.Header, error)
|
||||||
|
HeaderByHash(ctx context.Context, hash common.Hash) (*types.Header, error)
|
||||||
|
ChainConfig() *params.ChainConfig
|
||||||
|
}
|
||||||
|
|
||||||
|
type WrappedHandler func(ctx context.Context, values url.Values, vars map[string]string, decodeBody func(*any) error) (any, string, int)
|
||||||
|
|
||||||
|
func NewServer(node *node.Node) *Server {
|
||||||
|
s := &Server{
|
||||||
|
router: mux.NewRouter(),
|
||||||
|
}
|
||||||
|
node.RegisterHandler("REST API", "/eth/", s.router)
|
||||||
|
return s
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *Server) Register(regAPI API) {
|
||||||
|
regAPI(s.router)
|
||||||
|
}
|
||||||
|
|
||||||
|
func mediaType(mt contenttype.MediaType, allowBinary bool) (binary, valid bool) {
|
||||||
|
switch {
|
||||||
|
case mt.Type == "" && mt.Subtype == "":
|
||||||
|
return false, true // if content type is not specified then assume JSON
|
||||||
|
case mt.Type == "application" && mt.Subtype == "json":
|
||||||
|
return false, true
|
||||||
|
case mt.Type == "application" && mt.Subtype == "octet-stream":
|
||||||
|
return allowBinary, allowBinary
|
||||||
|
default:
|
||||||
|
return false, false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
var allAvailableMediaTypes = []contenttype.MediaType{
|
||||||
|
contenttype.NewMediaType("application/json"),
|
||||||
|
contenttype.NewMediaType("application/octet-stream"),
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *Server) WrapHandler(handler WrappedHandler, expectBody, allowRlpBody, allowRlpResponse bool) func(resp http.ResponseWriter, req *http.Request) {
|
||||||
|
return func(resp http.ResponseWriter, req *http.Request) {
|
||||||
|
var decodeBody func(*any) error
|
||||||
|
if expectBody {
|
||||||
|
contentType, err := contenttype.GetMediaType(req)
|
||||||
|
if err != nil {
|
||||||
|
http.Error(resp, "invalid content type", http.StatusUnsupportedMediaType)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
binary, valid := mediaType(contentType, allowRlpBody)
|
||||||
|
if !valid {
|
||||||
|
http.Error(resp, "invalid content type", http.StatusUnsupportedMediaType)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if req.Body == nil {
|
||||||
|
http.Error(resp, "missing request body", http.StatusBadRequest)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
data, err := ioutil.ReadAll(req.Body)
|
||||||
|
if err != nil {
|
||||||
|
http.Error(resp, "could not read request body", http.StatusInternalServerError)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if binary {
|
||||||
|
decodeBody = func(body *any) error {
|
||||||
|
return rlp.DecodeBytes(data, body)
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
decodeBody = func(body *any) error {
|
||||||
|
return json.Unmarshal(data, body)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
availableMediaTypes := allAvailableMediaTypes
|
||||||
|
if !allowRlpResponse {
|
||||||
|
availableMediaTypes = availableMediaTypes[:1]
|
||||||
|
}
|
||||||
|
acceptType, _, err := contenttype.GetAcceptableMediaType(req, availableMediaTypes)
|
||||||
|
if err != nil {
|
||||||
|
http.Error(resp, "invalid accepted media type", http.StatusNotAcceptable)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
binary, valid := mediaType(acceptType, allowRlpResponse)
|
||||||
|
if !valid {
|
||||||
|
http.Error(resp, "invalid accepted media type", http.StatusNotAcceptable)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
response, errorStr, errorCode := handler(req.Context(), req.URL.Query(), mux.Vars(req), decodeBody)
|
||||||
|
if errorCode != 0 {
|
||||||
|
http.Error(resp, errorStr, errorCode)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if binary {
|
||||||
|
respRlp, err := rlp.EncodeToBytes(response)
|
||||||
|
if err != nil {
|
||||||
|
http.Error(resp, "response encoding error", http.StatusInternalServerError)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
resp.Header().Set("content-type", "application/octet-stream")
|
||||||
|
resp.Write(respRlp)
|
||||||
|
} else {
|
||||||
|
respJson, err := json.Marshal(response)
|
||||||
|
if err != nil {
|
||||||
|
http.Error(resp, "response encoding error", http.StatusInternalServerError)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
resp.Header().Set("content-type", "application/json")
|
||||||
|
resp.Write(respJson)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
Loading…
Reference in a new issue