Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

chore: fix linter issues #28

Merged
merged 5 commits into from
Nov 6, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 0 additions & 3 deletions .golangci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@ run:

linters:
enable:
- deadcode
- errcheck
- gofmt
- goimports
Expand All @@ -15,10 +14,8 @@ linters:
- misspell
- revive
- staticcheck
- structcheck
- typecheck
- unused
- varcheck

issues:
exclude-use-default: false
Expand Down
13 changes: 11 additions & 2 deletions proxy/grpc/client.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,47 +4,53 @@ import (
"context"
"time"

"github.com/rollkit/go-execution/types"
"google.golang.org/grpc"

"github.com/rollkit/go-execution/types"
pb "github.com/rollkit/go-execution/types/pb/execution"
)

// Client defines gRPC proxy client
type Client struct {
conn *grpc.ClientConn
client pb.ExecutionServiceClient
config *Config
}

// NewClient creates a new instance of Client with default configuration.
func NewClient() *Client {
return &Client{
config: DefaultConfig(),
}
}

// SetConfig sets the configuration for the Client instance.
func (c *Client) SetConfig(config *Config) {
if config != nil {
c.config = config
}
}

// Start initializes the Client by creating a new gRPC connection and storing the ExecutionServiceClient instance.
func (c *Client) Start(target string, opts ...grpc.DialOption) error {
var err error
c.conn, err = grpc.Dial(target, opts...) // Changed from grpc.NewClient to grpc.Dial
c.conn, err = grpc.NewClient(target, opts...)
if err != nil {
return err
}
c.client = pb.NewExecutionServiceClient(c.conn)
return nil
}

// Stop stops the client by closing the underlying gRPC connection if it exists.
func (c *Client) Stop() error {
if c.conn != nil {
return c.conn.Close()
}
return nil
}

// InitChain initializes the blockchain with genesis information.
func (c *Client) InitChain(genesisTime time.Time, initialHeight uint64, chainID string) (types.Hash, uint64, error) {
ctx, cancel := context.WithTimeout(context.Background(), c.config.DefaultTimeout)
defer cancel()
Expand All @@ -64,6 +70,7 @@ func (c *Client) InitChain(genesisTime time.Time, initialHeight uint64, chainID
return stateRoot, resp.MaxBytes, nil
}

// GetTxs retrieves all available transactions from the execution client's mempool.
func (c *Client) GetTxs() ([]types.Tx, error) {
ctx, cancel := context.WithTimeout(context.Background(), c.config.DefaultTimeout)
defer cancel()
Expand All @@ -81,6 +88,7 @@ func (c *Client) GetTxs() ([]types.Tx, error) {
return txs, nil
}

// ExecuteTxs executes a set of transactions to produce a new block header.
func (c *Client) ExecuteTxs(txs []types.Tx, blockHeight uint64, timestamp time.Time, prevStateRoot types.Hash) (types.Hash, uint64, error) {
ctx, cancel := context.WithTimeout(context.Background(), c.config.DefaultTimeout)
defer cancel()
Expand All @@ -106,6 +114,7 @@ func (c *Client) ExecuteTxs(txs []types.Tx, blockHeight uint64, timestamp time.T
return updatedStateRoot, resp.MaxBytes, nil
}

// SetFinal marks a block at the given height as final.
func (c *Client) SetFinal(blockHeight uint64) error {
ctx, cancel := context.WithTimeout(context.Background(), c.config.DefaultTimeout)
defer cancel()
Expand Down
4 changes: 2 additions & 2 deletions proxy/grpc/client_server_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -38,12 +38,12 @@ func TestClientServer(t *testing.T) {
client := grpcproxy.NewClient()
client.SetConfig(config)

err := client.Start("bufnet",
err := client.Start("passthrough://bufnet",
grpc.WithContextDialer(dialer(listener)),
grpc.WithTransportCredentials(insecure.NewCredentials()),
)
require.NoError(t, err)
defer client.Stop()
defer func() { _ = client.Stop() }()

mockExec.On("GetTxs").Return([]types.Tx{}, nil).Maybe()

Expand Down
2 changes: 2 additions & 0 deletions proxy/grpc/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,12 +2,14 @@ package grpc

import "time"

// Config holds configuration settings for the gRPC proxy.
type Config struct {
JWTSecret []byte
DefaultTimeout time.Duration
MaxRequestSize int
}

// DefaultConfig returns a Config instance populated with default settings.
func DefaultConfig() *Config {
return &Config{
DefaultTimeout: time.Second,
Expand Down
22 changes: 9 additions & 13 deletions proxy/grpc/errors.go
Original file line number Diff line number Diff line change
@@ -1,15 +1,11 @@
package grpc

import (
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
)

var (
ErrUnknownPayload = status.Error(codes.NotFound, "payload does not exist")
ErrInvalidForkchoice = status.Error(codes.InvalidArgument, "invalid forkchoice state")
ErrInvalidPayloadAttrs = status.Error(codes.InvalidArgument, "invalid payload attributes")
ErrTooLargeRequest = status.Error(codes.ResourceExhausted, "request too large")
ErrUnsupportedFork = status.Error(codes.Unimplemented, "unsupported fork")
ErrInvalidJWT = status.Error(codes.Unauthenticated, "invalid JWT token")
)
// TODO(tzdybal): do we need this?
//var (
// ErrUnknownPayload = status.Error(codes.NotFound, "payload does not exist")
// ErrInvalidForkchoice = status.Error(codes.InvalidArgument, "invalid forkchoice state")
// ErrInvalidPayloadAttrs = status.Error(codes.InvalidArgument, "invalid payload attributes")
// ErrTooLargeRequest = status.Error(codes.ResourceExhausted, "request too large")
// ErrUnsupportedFork = status.Error(codes.Unimplemented, "unsupported fork")
// ErrInvalidJWT = status.Error(codes.Unauthenticated, "invalid JWT token")
//)
4 changes: 2 additions & 2 deletions proxy/grpc/proxy_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -61,7 +61,7 @@ func (s *ProxyTestSuite) SetupTest() {
grpc.WithTransportCredentials(insecure.NewCredentials()),
}

err := client.Start("bufnet", opts...)
err := client.Start("passthrough://bufnet", opts...)
require.NoError(s.T(), err)

for i := 0; i < 10; i++ {
Expand All @@ -74,7 +74,7 @@ func (s *ProxyTestSuite) SetupTest() {
s.client = client
s.Exec = client
s.cleanup = func() {
client.Stop()
_ = client.Stop()
s.server.Stop()
}
}
Expand Down
6 changes: 6 additions & 0 deletions proxy/grpc/server.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,12 +9,14 @@ import (
pb "github.com/rollkit/go-execution/types/pb/execution"
)

// Server defines a gRPC proxy server
type Server struct {
pb.UnimplementedExecutionServiceServer
exec execution.Execute
config *Config
}

// NewServer creates a new ExecutionService gRPC server with the given execution client and configuration.
func NewServer(exec execution.Execute, config *Config) pb.ExecutionServiceServer {
if config == nil {
config = DefaultConfig()
Expand All @@ -37,6 +39,7 @@ func (s *Server) validateJWT(_ context.Context) error {
return nil
}

// InitChain handles InitChain method call from execution API.
func (s *Server) InitChain(ctx context.Context, req *pb.InitChainRequest) (*pb.InitChainResponse, error) {
if err := s.validateAuth(ctx); err != nil {
return nil, err
Expand All @@ -60,6 +63,7 @@ func (s *Server) InitChain(ctx context.Context, req *pb.InitChainRequest) (*pb.I
}, nil
}

// GetTxs handles GetTxs method call from execution API.
func (s *Server) GetTxs(ctx context.Context, req *pb.GetTxsRequest) (*pb.GetTxsResponse, error) {
txs, err := s.exec.GetTxs()
if err != nil {
Expand All @@ -76,6 +80,7 @@ func (s *Server) GetTxs(ctx context.Context, req *pb.GetTxsRequest) (*pb.GetTxsR
}, nil
}

// ExecuteTxs handles ExecuteTxs method call from execution API.
func (s *Server) ExecuteTxs(ctx context.Context, req *pb.ExecuteTxsRequest) (*pb.ExecuteTxsResponse, error) {
txs := make([]types.Tx, len(req.Txs))
for i, tx := range req.Txs {
Expand All @@ -101,6 +106,7 @@ func (s *Server) ExecuteTxs(ctx context.Context, req *pb.ExecuteTxsRequest) (*pb
}, nil
}

// SetFinal handles SetFinal method call from execution API.
func (s *Server) SetFinal(ctx context.Context, req *pb.SetFinalRequest) (*pb.SetFinalResponse, error) {
err := s.exec.SetFinal(req.BlockHeight)
if err != nil {
Expand Down
11 changes: 10 additions & 1 deletion proxy/jsonrpc/client.go
Original file line number Diff line number Diff line change
Expand Up @@ -12,35 +12,41 @@ import (
"github.com/rollkit/go-execution/types"
)

// Client defines JSON-RPC proxy client of execution API.
type Client struct {
endpoint string
client *http.Client
config *Config
}

// NewClient creates new proxy client with default config.
func NewClient() *Client {
return &Client{
config: DefaultConfig(),
client: &http.Client{},
}
}

tzdybal marked this conversation as resolved.
Show resolved Hide resolved
// SetConfig updates the client's configuration with the provided config.
func (c *Client) SetConfig(config *Config) {
if config != nil {
c.config = config
c.client.Timeout = config.DefaultTimeout
}
}

// Start is used to start the client.
func (c *Client) Start(endpoint string) error {
c.endpoint = endpoint
return nil
}

// Stop method is used to stop the client.
func (c *Client) Stop() error {
return nil
}

// InitChain initializes the blockchain with genesis information.
func (c *Client) InitChain(genesisTime time.Time, initialHeight uint64, chainID string) (types.Hash, uint64, error) {
params := map[string]interface{}{
"genesis_time": genesisTime.Unix(),
Expand Down Expand Up @@ -68,6 +74,7 @@ func (c *Client) InitChain(genesisTime time.Time, initialHeight uint64, chainID
return stateRoot, result.MaxBytes, nil
}

// GetTxs retrieves all available transactions from the execution client's mempool.
func (c *Client) GetTxs() ([]types.Tx, error) {
var result struct {
Txs []string `json:"txs"`
Expand All @@ -89,6 +96,7 @@ func (c *Client) GetTxs() ([]types.Tx, error) {
return txs, nil
}

// ExecuteTxs executes a set of transactions to produce a new block header.
func (c *Client) ExecuteTxs(txs []types.Tx, blockHeight uint64, timestamp time.Time, prevStateRoot types.Hash) (types.Hash, uint64, error) {
// Encode txs to base64
encodedTxs := make([]string, len(txs))
Expand Down Expand Up @@ -123,6 +131,7 @@ func (c *Client) ExecuteTxs(txs []types.Tx, blockHeight uint64, timestamp time.T
return updatedStateRoot, result.MaxBytes, nil
}

// SetFinal marks a block at the given height as final.
func (c *Client) SetFinal(blockHeight uint64) error {
params := map[string]interface{}{
"block_height": blockHeight,
Expand Down Expand Up @@ -160,7 +169,7 @@ func (c *Client) call(method string, params interface{}, result interface{}) err
if err != nil {
return fmt.Errorf("failed to send request: %w", err)
}
defer resp.Body.Close()
defer func() { _ = resp.Body.Close() }()

if resp.StatusCode != http.StatusOK {
return fmt.Errorf("unexpected status code: %d", resp.StatusCode)
Expand Down
2 changes: 1 addition & 1 deletion proxy/jsonrpc/client_server_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ func TestClientServer(t *testing.T) {

err := client.Start(testServer.URL)
require.NoError(t, err)
defer client.Stop()
defer func() { _ = client.Stop() }()

t.Run("InitChain", func(t *testing.T) {
genesisTime := time.Now().UTC().Truncate(time.Second)
Expand Down
2 changes: 2 additions & 0 deletions proxy/jsonrpc/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,13 @@ package jsonrpc

import "time"

// Config represents configuration settings for server/client.
type Config struct {
DefaultTimeout time.Duration
MaxRequestSize int64
}

// DefaultConfig returns Config struct initialized with default settings.
func DefaultConfig() *Config {
return &Config{
DefaultTimeout: time.Second,
Expand Down
27 changes: 21 additions & 6 deletions proxy/jsonrpc/errors.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,17 +6,32 @@ type jsonRPCError struct {
}

const (
ErrCodeParse = -32700
// ErrCodeParse is a reserved JSON-RPC error code
ErrCodeParse = -32700
// ErrCodeInvalidRequest is a reserved JSON-RPC error code
ErrCodeInvalidRequest = -32600
// ErrCodeMethodNotFound is a reserved JSON-RPC error code
ErrCodeMethodNotFound = -32601
ErrCodeInvalidParams = -32602
ErrCodeInternal = -32603
// ErrCodeInvalidParams is a reserved JSON-RPC error code
ErrCodeInvalidParams = -32602
// ErrCodeInternal is a reserved JSON-RPC error code
ErrCodeInternal = -32603
)

var (
ErrParse = &jsonRPCError{Code: ErrCodeParse, Message: "Parse error"}

// ErrParse represents a JSON-RPC error indicating a problem with parsing the JSON request payload.
ErrParse = &jsonRPCError{Code: ErrCodeParse, Message: "Parse error"}

// ErrInvalidRequest represents a JSON-RPC error indicating an invalid JSON request payload.
ErrInvalidRequest = &jsonRPCError{Code: ErrCodeInvalidRequest, Message: "Invalid request"}

// ErrMethodNotFound represents a JSON-RPC error indicating that the requested method could not be found.
ErrMethodNotFound = &jsonRPCError{Code: ErrCodeMethodNotFound, Message: "Method not found"}
ErrInvalidParams = &jsonRPCError{Code: ErrCodeInvalidParams, Message: "Invalid params"}
ErrInternal = &jsonRPCError{Code: ErrCodeInternal, Message: "Internal error"}

// ErrInvalidParams represents a JSON-RPC error indicating invalid parameters in the request.
ErrInvalidParams = &jsonRPCError{Code: ErrCodeInvalidParams, Message: "Invalid params"}

// ErrInternal represents a JSON-RPC error indicating an unspecified internal error within the server.
ErrInternal = &jsonRPCError{Code: ErrCodeInternal, Message: "Internal error"}
)
2 changes: 1 addition & 1 deletion proxy/jsonrpc/proxy_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@ func (s *ProxyTestSuite) SetupTest() {
s.client = client
s.Exec = client
s.cleanup = func() {
client.Stop()
_ = client.Stop()
s.server.Close()
}
}
Expand Down
4 changes: 3 additions & 1 deletion proxy/jsonrpc/server.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,11 +10,13 @@ import (
"github.com/rollkit/go-execution/types"
)

// Server defines JSON-RPC proxy server for execution API.
type Server struct {
exec execution.Execute
config *Config
}

// NewServer initializes and returns a new Server instance with the given execution interface and configuration.
func NewServer(exec execution.Execute, config *Config) *Server {
if config == nil {
config = DefaultConfig()
Expand Down Expand Up @@ -200,5 +202,5 @@ func writeResponse(w http.ResponseWriter, id interface{}, result interface{}, er
}

w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(response)
_ = json.NewEncoder(w).Encode(response) // TODO(tzdybal): add proper error handling
tzdybal marked this conversation as resolved.
Show resolved Hide resolved
}
Loading
Loading