From 5ee6a4f1eb2ae1e8659f13bdc6c9131bd26150df Mon Sep 17 00:00:00 2001 From: Haaai <55118568+Liuhaai@users.noreply.github.com> Date: Fri, 1 Jul 2022 01:58:48 -0700 Subject: [PATCH] [api] Separate Server and Server Handler (#3485) * fix #3372 --- api/grpcserver.go | 96 +++++++++------- api/grpcserver_integrity_test.go | 188 ++++++++++++++++++------------- api/grpcserver_test.go | 7 +- api/http.go | 33 ++++-- api/http_test.go | 4 +- api/serverV2.go | 7 +- api/serverV2_test.go | 4 +- api/web3server_test.go | 5 +- api/websocket.go | 43 ++----- 9 files changed, 208 insertions(+), 179 deletions(-) diff --git a/api/grpcserver.go b/api/grpcserver.go index 1a1b21ad29..1a7ca92703 100644 --- a/api/grpcserver.go +++ b/api/grpcserver.go @@ -49,12 +49,18 @@ import ( "github.com/iotexproject/iotex-core/pkg/tracer" ) -// GRPCServer contains grpc server and the pointer to api coreservice -type GRPCServer struct { - port string - grpcServer *grpc.Server - coreService CoreService -} +type ( + // GRPCServer contains grpc server + GRPCServer struct { + port string + svr *grpc.Server + } + + // GRPCHandler contains the pointer to api coreservice + gRPCHandler struct { + coreService CoreService + } +) // TODO: move this into config var ( @@ -116,23 +122,21 @@ func NewGRPCServer(core CoreService, grpcPort int) *GRPCServer { grpc.KeepaliveEnforcementPolicy(kaep), grpc.KeepaliveParams(kasp), ) - svr := &GRPCServer{ - port: ":" + strconv.Itoa(grpcPort), - grpcServer: gSvr, - coreService: core, - } //serviceName: grpc.health.v1.Health grpc_health_v1.RegisterHealthServer(gSvr, health.NewServer()) - iotexapi.RegisterAPIServiceServer(gSvr, svr) + iotexapi.RegisterAPIServiceServer(gSvr, newGRPCHandler(core)) grpc_prometheus.Register(gSvr) reflection.Register(gSvr) - return svr + return &GRPCServer{ + port: ":" + strconv.Itoa(grpcPort), + svr: gSvr, + } } // Start starts the GRPC server -func (svr *GRPCServer) Start(_ context.Context) error { - lis, err := net.Listen("tcp", svr.port) +func (grpc *GRPCServer) Start(_ context.Context) error { + lis, err := net.Listen("tcp", grpc.port) if err != nil { log.L().Error("grpc server failed to listen.", zap.Error(err)) return errors.Wrap(err, "grpc server failed to listen") @@ -140,7 +144,7 @@ func (svr *GRPCServer) Start(_ context.Context) error { log.L().Info("grpc server is listening.", zap.String("addr", lis.Addr().String())) go func() { defer recovery.Recover() - if err := svr.grpcServer.Serve(lis); err != nil { + if err := grpc.svr.Serve(lis); err != nil { log.L().Fatal("grpc failed to serve.", zap.Error(err)) } }() @@ -148,13 +152,19 @@ func (svr *GRPCServer) Start(_ context.Context) error { } // Stop stops the GRPC server -func (svr *GRPCServer) Stop(_ context.Context) error { - svr.grpcServer.Stop() +func (grpc *GRPCServer) Stop(_ context.Context) error { + grpc.svr.Stop() return nil } +func newGRPCHandler(core CoreService) *gRPCHandler { + return &gRPCHandler{ + coreService: core, + } +} + // SuggestGasPrice suggests gas price -func (svr *GRPCServer) SuggestGasPrice(ctx context.Context, in *iotexapi.SuggestGasPriceRequest) (*iotexapi.SuggestGasPriceResponse, error) { +func (svr *gRPCHandler) SuggestGasPrice(ctx context.Context, in *iotexapi.SuggestGasPriceRequest) (*iotexapi.SuggestGasPriceResponse, error) { suggestPrice, err := svr.coreService.SuggestGasPrice() if err != nil { return nil, status.Error(codes.Internal, err.Error()) @@ -163,7 +173,7 @@ func (svr *GRPCServer) SuggestGasPrice(ctx context.Context, in *iotexapi.Suggest } // GetAccount returns the metadata of an account -func (svr *GRPCServer) GetAccount(ctx context.Context, in *iotexapi.GetAccountRequest) (*iotexapi.GetAccountResponse, error) { +func (svr *gRPCHandler) GetAccount(ctx context.Context, in *iotexapi.GetAccountRequest) (*iotexapi.GetAccountResponse, error) { span := tracer.SpanFromContext(ctx) defer span.End() addr, err := address.FromString(in.Address) @@ -183,7 +193,7 @@ func (svr *GRPCServer) GetAccount(ctx context.Context, in *iotexapi.GetAccountRe } // GetActions returns actions -func (svr *GRPCServer) GetActions(ctx context.Context, in *iotexapi.GetActionsRequest) (*iotexapi.GetActionsResponse, error) { +func (svr *gRPCHandler) GetActions(ctx context.Context, in *iotexapi.GetActionsRequest) (*iotexapi.GetActionsResponse, error) { var ( ret []*iotexapi.ActionInfo err error @@ -279,7 +289,7 @@ func actionsInBlock(blk *block.Block, receipts []*action.Receipt, start, count u } // GetBlockMetas returns block metadata -func (svr *GRPCServer) GetBlockMetas(ctx context.Context, in *iotexapi.GetBlockMetasRequest) (*iotexapi.GetBlockMetasResponse, error) { +func (svr *gRPCHandler) GetBlockMetas(ctx context.Context, in *iotexapi.GetBlockMetasRequest) (*iotexapi.GetBlockMetasResponse, error) { var ( ret []*iotextypes.BlockMeta err error @@ -306,7 +316,7 @@ func (svr *GRPCServer) GetBlockMetas(ctx context.Context, in *iotexapi.GetBlockM } // GetChainMeta returns blockchain metadata -func (svr *GRPCServer) GetChainMeta(ctx context.Context, in *iotexapi.GetChainMetaRequest) (*iotexapi.GetChainMetaResponse, error) { +func (svr *gRPCHandler) GetChainMeta(ctx context.Context, in *iotexapi.GetChainMetaRequest) (*iotexapi.GetChainMetaResponse, error) { chainMeta, syncStatus, err := svr.coreService.ChainMeta() if err != nil { return nil, err @@ -315,7 +325,7 @@ func (svr *GRPCServer) GetChainMeta(ctx context.Context, in *iotexapi.GetChainMe } // GetServerMeta gets the server metadata -func (svr *GRPCServer) GetServerMeta(ctx context.Context, in *iotexapi.GetServerMetaRequest) (*iotexapi.GetServerMetaResponse, error) { +func (svr *gRPCHandler) GetServerMeta(ctx context.Context, in *iotexapi.GetServerMetaRequest) (*iotexapi.GetServerMetaResponse, error) { packageVersion, packageCommitID, gitStatus, goVersion, buildTime := svr.coreService.ServerMeta() return &iotexapi.GetServerMetaResponse{ServerMeta: &iotextypes.ServerMeta{ PackageVersion: packageVersion, @@ -327,7 +337,7 @@ func (svr *GRPCServer) GetServerMeta(ctx context.Context, in *iotexapi.GetServer } // SendAction is the API to send an action to blockchain. -func (svr *GRPCServer) SendAction(ctx context.Context, in *iotexapi.SendActionRequest) (*iotexapi.SendActionResponse, error) { +func (svr *gRPCHandler) SendAction(ctx context.Context, in *iotexapi.SendActionRequest) (*iotexapi.SendActionResponse, error) { span := tracer.SpanFromContext(ctx) // tags output span.SetAttributes(attribute.String("actType", fmt.Sprintf("%T", in.GetAction().GetCore()))) @@ -356,7 +366,7 @@ func (svr *GRPCServer) SendAction(ctx context.Context, in *iotexapi.SendActionRe } // GetReceiptByAction gets receipt with corresponding action hash -func (svr *GRPCServer) GetReceiptByAction(ctx context.Context, in *iotexapi.GetReceiptByActionRequest) (*iotexapi.GetReceiptByActionResponse, error) { +func (svr *gRPCHandler) GetReceiptByAction(ctx context.Context, in *iotexapi.GetReceiptByActionRequest) (*iotexapi.GetReceiptByActionResponse, error) { actHash, err := hash.HexStringToHash256(in.ActionHash) if err != nil { return nil, status.Error(codes.InvalidArgument, err.Error()) @@ -379,7 +389,7 @@ func (svr *GRPCServer) GetReceiptByAction(ctx context.Context, in *iotexapi.GetR } // ReadContract reads the state in a contract address specified by the slot -func (svr *GRPCServer) ReadContract(ctx context.Context, in *iotexapi.ReadContractRequest) (*iotexapi.ReadContractResponse, error) { +func (svr *gRPCHandler) ReadContract(ctx context.Context, in *iotexapi.ReadContractRequest) (*iotexapi.ReadContractResponse, error) { from := in.CallerAddress if from == action.EmptyAddress { from = address.ZeroAddress @@ -405,12 +415,12 @@ func (svr *GRPCServer) ReadContract(ctx context.Context, in *iotexapi.ReadContra } // ReadState reads state on blockchain -func (svr *GRPCServer) ReadState(ctx context.Context, in *iotexapi.ReadStateRequest) (*iotexapi.ReadStateResponse, error) { +func (svr *gRPCHandler) ReadState(ctx context.Context, in *iotexapi.ReadStateRequest) (*iotexapi.ReadStateResponse, error) { return svr.coreService.ReadState(string(in.ProtocolID), in.GetHeight(), in.MethodName, in.Arguments) } // EstimateGasForAction estimates gas for action -func (svr *GRPCServer) EstimateGasForAction(ctx context.Context, in *iotexapi.EstimateGasForActionRequest) (*iotexapi.EstimateGasForActionResponse, error) { +func (svr *gRPCHandler) EstimateGasForAction(ctx context.Context, in *iotexapi.EstimateGasForActionRequest) (*iotexapi.EstimateGasForActionResponse, error) { estimateGas, err := svr.coreService.EstimateGasForAction(ctx, in.Action) if err != nil { return nil, err @@ -419,7 +429,7 @@ func (svr *GRPCServer) EstimateGasForAction(ctx context.Context, in *iotexapi.Es } // EstimateActionGasConsumption estimate gas consume for action without signature -func (svr *GRPCServer) EstimateActionGasConsumption(ctx context.Context, in *iotexapi.EstimateActionGasConsumptionRequest) (*iotexapi.EstimateActionGasConsumptionResponse, error) { +func (svr *gRPCHandler) EstimateActionGasConsumption(ctx context.Context, in *iotexapi.EstimateActionGasConsumptionRequest) (*iotexapi.EstimateActionGasConsumptionResponse, error) { if in.GetExecution() != nil { callerAddr, err := address.FromString(in.GetCallerAddress()) if err != nil { @@ -508,7 +518,7 @@ func (svr *GRPCServer) EstimateActionGasConsumption(ctx context.Context, in *iot } // GetEpochMeta gets epoch metadata -func (svr *GRPCServer) GetEpochMeta(ctx context.Context, in *iotexapi.GetEpochMetaRequest) (*iotexapi.GetEpochMetaResponse, error) { +func (svr *gRPCHandler) GetEpochMeta(ctx context.Context, in *iotexapi.GetEpochMetaRequest) (*iotexapi.GetEpochMetaResponse, error) { epochData, numBlks, blockProducersInfo, err := svr.coreService.EpochMeta(in.EpochNumber) if err != nil { return nil, err @@ -521,7 +531,7 @@ func (svr *GRPCServer) GetEpochMeta(ctx context.Context, in *iotexapi.GetEpochMe } // GetRawBlocks gets raw block data -func (svr *GRPCServer) GetRawBlocks(ctx context.Context, in *iotexapi.GetRawBlocksRequest) (*iotexapi.GetRawBlocksResponse, error) { +func (svr *gRPCHandler) GetRawBlocks(ctx context.Context, in *iotexapi.GetRawBlocksRequest) (*iotexapi.GetRawBlocksResponse, error) { ret, err := svr.coreService.RawBlocks(in.StartHeight, in.Count, in.WithReceipts, in.WithTransactionLogs) if err != nil { return nil, err @@ -530,7 +540,7 @@ func (svr *GRPCServer) GetRawBlocks(ctx context.Context, in *iotexapi.GetRawBloc } // GetLogs get logs filtered by contract address and topics -func (svr *GRPCServer) GetLogs(ctx context.Context, in *iotexapi.GetLogsRequest) (*iotexapi.GetLogsResponse, error) { +func (svr *gRPCHandler) GetLogs(ctx context.Context, in *iotexapi.GetLogsRequest) (*iotexapi.GetLogsResponse, error) { if in.GetFilter() == nil { return nil, status.Error(codes.InvalidArgument, "empty filter") } @@ -569,7 +579,7 @@ func toLogPb(lg *action.Log, blkHash hash.Hash256) *iotextypes.Log { } // StreamBlocks streams blocks -func (svr *GRPCServer) StreamBlocks(_ *iotexapi.StreamBlocksRequest, stream iotexapi.APIService_StreamBlocksServer) error { +func (svr *gRPCHandler) StreamBlocks(_ *iotexapi.StreamBlocksRequest, stream iotexapi.APIService_StreamBlocksServer) error { errChan := make(chan error) defer close(errChan) chainListener := svr.coreService.ChainListener() @@ -589,7 +599,7 @@ func (svr *GRPCServer) StreamBlocks(_ *iotexapi.StreamBlocksRequest, stream iote } // StreamLogs streams logs that match the filter condition -func (svr *GRPCServer) StreamLogs(in *iotexapi.StreamLogsRequest, stream iotexapi.APIService_StreamLogsServer) error { +func (svr *gRPCHandler) StreamLogs(in *iotexapi.StreamLogsRequest, stream iotexapi.APIService_StreamLogsServer) error { if in.GetFilter() == nil { return status.Error(codes.InvalidArgument, "empty filter") } @@ -613,7 +623,7 @@ func (svr *GRPCServer) StreamLogs(in *iotexapi.StreamLogsRequest, stream iotexap } // GetElectionBuckets returns the native election buckets. -func (svr *GRPCServer) GetElectionBuckets(ctx context.Context, in *iotexapi.GetElectionBucketsRequest) (*iotexapi.GetElectionBucketsResponse, error) { +func (svr *gRPCHandler) GetElectionBuckets(ctx context.Context, in *iotexapi.GetElectionBucketsRequest) (*iotexapi.GetElectionBucketsResponse, error) { ret, err := svr.coreService.ElectionBuckets(in.GetEpochNum()) if err != nil { return nil, err @@ -622,17 +632,17 @@ func (svr *GRPCServer) GetElectionBuckets(ctx context.Context, in *iotexapi.GetE } // GetEvmTransfersByActionHash returns evm transfers by action hash -func (svr *GRPCServer) GetEvmTransfersByActionHash(ctx context.Context, in *iotexapi.GetEvmTransfersByActionHashRequest) (*iotexapi.GetEvmTransfersByActionHashResponse, error) { +func (svr *gRPCHandler) GetEvmTransfersByActionHash(ctx context.Context, in *iotexapi.GetEvmTransfersByActionHashRequest) (*iotexapi.GetEvmTransfersByActionHashResponse, error) { return nil, status.Error(codes.Unimplemented, "evm transfer index is deprecated, call GetSystemLogByActionHash instead") } // GetEvmTransfersByBlockHeight returns evm transfers by block height -func (svr *GRPCServer) GetEvmTransfersByBlockHeight(ctx context.Context, in *iotexapi.GetEvmTransfersByBlockHeightRequest) (*iotexapi.GetEvmTransfersByBlockHeightResponse, error) { +func (svr *gRPCHandler) GetEvmTransfersByBlockHeight(ctx context.Context, in *iotexapi.GetEvmTransfersByBlockHeightRequest) (*iotexapi.GetEvmTransfersByBlockHeightResponse, error) { return nil, status.Error(codes.Unimplemented, "evm transfer index is deprecated, call GetSystemLogByBlockHeight instead") } // GetTransactionLogByActionHash returns transaction log by action hash -func (svr *GRPCServer) GetTransactionLogByActionHash(ctx context.Context, in *iotexapi.GetTransactionLogByActionHashRequest) (*iotexapi.GetTransactionLogByActionHashResponse, error) { +func (svr *gRPCHandler) GetTransactionLogByActionHash(ctx context.Context, in *iotexapi.GetTransactionLogByActionHashRequest) (*iotexapi.GetTransactionLogByActionHashResponse, error) { ret, err := svr.coreService.TransactionLogByActionHash(in.ActionHash) if err != nil { return nil, err @@ -643,7 +653,7 @@ func (svr *GRPCServer) GetTransactionLogByActionHash(ctx context.Context, in *io } // GetTransactionLogByBlockHeight returns transaction log by block height -func (svr *GRPCServer) GetTransactionLogByBlockHeight(ctx context.Context, in *iotexapi.GetTransactionLogByBlockHeightRequest) (*iotexapi.GetTransactionLogByBlockHeightResponse, error) { +func (svr *gRPCHandler) GetTransactionLogByBlockHeight(ctx context.Context, in *iotexapi.GetTransactionLogByBlockHeightRequest) (*iotexapi.GetTransactionLogByBlockHeightResponse, error) { blockIdentifier, transactionLogs, err := svr.coreService.TransactionLogByBlockHeight(in.BlockHeight) if err != nil { return nil, err @@ -655,7 +665,7 @@ func (svr *GRPCServer) GetTransactionLogByBlockHeight(ctx context.Context, in *i } // GetActPoolActions returns the all Transaction Identifiers in the mempool -func (svr *GRPCServer) GetActPoolActions(ctx context.Context, in *iotexapi.GetActPoolActionsRequest) (*iotexapi.GetActPoolActionsResponse, error) { +func (svr *gRPCHandler) GetActPoolActions(ctx context.Context, in *iotexapi.GetActPoolActionsRequest) (*iotexapi.GetActPoolActionsResponse, error) { acts, err := svr.coreService.ActionsInActPool(in.ActionHashes) if err != nil { return nil, status.Error(codes.NotFound, err.Error()) @@ -670,7 +680,7 @@ func (svr *GRPCServer) GetActPoolActions(ctx context.Context, in *iotexapi.GetAc } // ReadContractStorage reads contract's storage -func (svr *GRPCServer) ReadContractStorage(ctx context.Context, in *iotexapi.ReadContractStorageRequest) (*iotexapi.ReadContractStorageResponse, error) { +func (svr *gRPCHandler) ReadContractStorage(ctx context.Context, in *iotexapi.ReadContractStorageRequest) (*iotexapi.ReadContractStorageResponse, error) { addr, err := address.FromString(in.GetContract()) if err != nil { return nil, status.Error(codes.InvalidArgument, err.Error()) @@ -683,7 +693,7 @@ func (svr *GRPCServer) ReadContractStorage(ctx context.Context, in *iotexapi.Rea } // TraceTransactionStructLogs get trace transaction struct logs -func (svr *GRPCServer) TraceTransactionStructLogs(ctx context.Context, in *iotexapi.TraceTransactionStructLogsRequest) (*iotexapi.TraceTransactionStructLogsResponse, error) { +func (svr *gRPCHandler) TraceTransactionStructLogs(ctx context.Context, in *iotexapi.TraceTransactionStructLogsRequest) (*iotexapi.TraceTransactionStructLogsResponse, error) { actInfo, err := svr.coreService.Action(util.Remove0xPrefix(in.GetActionHash()), false) if err != nil { return nil, err diff --git a/api/grpcserver_integrity_test.go b/api/grpcserver_integrity_test.go index 5f260803a0..5ea1787bc9 100644 --- a/api/grpcserver_integrity_test.go +++ b/api/grpcserver_integrity_test.go @@ -823,6 +823,7 @@ func TestGrpcServer_GetAccountIntegrity(t *testing.T) { svr, bc, dao, _, _, actPool, bfIndexFile, err := createServerV2(cfg, true) require.NoError(err) + grpcHandler := newGRPCHandler(svr.core) defer func() { testutil.CleanupPath(bfIndexFile) }() @@ -835,7 +836,7 @@ func TestGrpcServer_GetAccountIntegrity(t *testing.T) { // read contract address request := &iotexapi.GetAccountRequest{Address: contract} - res, err := svr.grpcServer.GetAccount(context.Background(), request) + res, err := grpcHandler.GetAccount(context.Background(), request) require.NoError(err) accountMeta := res.AccountMeta require.Equal(contract, accountMeta.Address) @@ -850,7 +851,7 @@ func TestGrpcServer_GetAccountIntegrity(t *testing.T) { // success for _, test := range _getAccountTests { request := &iotexapi.GetAccountRequest{Address: test.in} - res, err := svr.grpcServer.GetAccount(context.Background(), request) + res, err := grpcHandler.GetAccount(context.Background(), request) require.NoError(err) accountMeta := res.AccountMeta require.Equal(test.address, accountMeta.Address) @@ -862,14 +863,14 @@ func TestGrpcServer_GetAccountIntegrity(t *testing.T) { require.NotZero(res.BlockIdentifier.Hash) } // failure - _, err = svr.grpcServer.GetAccount(context.Background(), &iotexapi.GetAccountRequest{}) + _, err = grpcHandler.GetAccount(context.Background(), &iotexapi.GetAccountRequest{}) require.Error(err) // error account - _, err = svr.grpcServer.GetAccount(context.Background(), &iotexapi.GetAccountRequest{Address: "io3fn88lge6hyzmruh40cn6l3e49dfkqzqk3lgtq3"}) + _, err = grpcHandler.GetAccount(context.Background(), &iotexapi.GetAccountRequest{Address: "io3fn88lge6hyzmruh40cn6l3e49dfkqzqk3lgtq3"}) require.Error(err) // success: reward pool - res, err = svr.grpcServer.GetAccount(context.Background(), &iotexapi.GetAccountRequest{Address: address.RewardingPoolAddr}) + res, err = grpcHandler.GetAccount(context.Background(), &iotexapi.GetAccountRequest{Address: address.RewardingPoolAddr}) require.NoError(err) require.Equal(address.RewardingPoolAddr, res.AccountMeta.Address) require.Equal("200000000000000000000101000", res.AccountMeta.Balance) @@ -877,7 +878,7 @@ func TestGrpcServer_GetAccountIntegrity(t *testing.T) { require.NotZero(res.BlockIdentifier.Hash) //failure: protocol staking isn't registered - res, err = svr.grpcServer.GetAccount(context.Background(), &iotexapi.GetAccountRequest{Address: address.StakingBucketPoolAddr}) + res, err = grpcHandler.GetAccount(context.Background(), &iotexapi.GetAccountRequest{Address: address.StakingBucketPoolAddr}) require.Contains(err.Error(), "protocol staking isn't registered") } @@ -886,6 +887,7 @@ func TestGrpcServer_GetActionsIntegrity(t *testing.T) { cfg := newConfig() svr, _, _, _, _, _, bfIndexFile, err := createServerV2(cfg, false) require.NoError(err) + grpcHandler := newGRPCHandler(svr.core) defer func() { testutil.CleanupPath(bfIndexFile) }() @@ -900,7 +902,7 @@ func TestGrpcServer_GetActionsIntegrity(t *testing.T) { }, } - res, err := svr.grpcServer.GetActions(context.Background(), request) + res, err := grpcHandler.GetActions(context.Background(), request) if test.count == 0 { require.Error(err) } else { @@ -912,11 +914,11 @@ func TestGrpcServer_GetActionsIntegrity(t *testing.T) { } // failure: empty request - _, err = svr.grpcServer.GetActions(context.Background(), &iotexapi.GetActionsRequest{}) + _, err = grpcHandler.GetActions(context.Background(), &iotexapi.GetActionsRequest{}) require.Error(err) // failure: range exceed limit - _, err = svr.grpcServer.GetActions(context.Background(), + _, err = grpcHandler.GetActions(context.Background(), &iotexapi.GetActionsRequest{ Lookup: &iotexapi.GetActionsRequest_ByIndex{ ByIndex: &iotexapi.GetActionsByIndexRequest{ @@ -928,7 +930,7 @@ func TestGrpcServer_GetActionsIntegrity(t *testing.T) { require.Error(err) // failure: start exceed limit - _, err = svr.grpcServer.GetActions(context.Background(), + _, err = grpcHandler.GetActions(context.Background(), &iotexapi.GetActionsRequest{ Lookup: &iotexapi.GetActionsRequest_ByIndex{ ByIndex: &iotexapi.GetActionsByIndexRequest{ @@ -946,6 +948,7 @@ func TestGrpcServer_GetActionIntegrity(t *testing.T) { svr, _, dao, _, _, _, bfIndexFile, err := createServerV2(cfg, true) require.NoError(err) + grpcHandler := newGRPCHandler(svr.core) defer func() { testutil.CleanupPath(bfIndexFile) }() @@ -959,7 +962,7 @@ func TestGrpcServer_GetActionIntegrity(t *testing.T) { }, }, } - res, err := svr.grpcServer.GetActions(context.Background(), request) + res, err := grpcHandler.GetActions(context.Background(), request) require.NoError(err) require.Equal(1, len(res.ActionInfo)) act := res.ActionInfo[0] @@ -981,7 +984,7 @@ func TestGrpcServer_GetActionIntegrity(t *testing.T) { } // failure: invalid hash - _, err = svr.grpcServer.GetActions(context.Background(), + _, err = grpcHandler.GetActions(context.Background(), &iotexapi.GetActionsRequest{ Lookup: &iotexapi.GetActionsRequest_ByHash{ ByHash: &iotexapi.GetActionByHashRequest{ @@ -999,6 +1002,7 @@ func TestGrpcServer_GetActionsByAddressIntegrity(t *testing.T) { svr, _, _, _, _, _, bfIndexFile, err := createServerV2(cfg, false) require.NoError(err) + grpcHandler := newGRPCHandler(svr.core) defer func() { testutil.CleanupPath(bfIndexFile) }() @@ -1013,7 +1017,7 @@ func TestGrpcServer_GetActionsByAddressIntegrity(t *testing.T) { }, }, } - res, err := svr.grpcServer.GetActions(context.Background(), request) + res, err := grpcHandler.GetActions(context.Background(), request) require.NoError(err) require.Equal(test.numActions, len(res.ActionInfo)) if test.numActions == 0 { @@ -1037,7 +1041,7 @@ func TestGrpcServer_GetActionsByAddressIntegrity(t *testing.T) { }, }, } - prevRes, err := svr.grpcServer.GetActions(context.Background(), request) + prevRes, err := grpcHandler.GetActions(context.Background(), request) require.NoError(err) require.True(prevRes.ActionInfo[len(prevRes.ActionInfo)-1].Timestamp.GetSeconds() <= res.ActionInfo[0].Timestamp.GetSeconds()) } @@ -1050,6 +1054,7 @@ func TestGrpcServer_GetUnconfirmedActionsByAddressIntegrity(t *testing.T) { svr, _, _, _, _, _, bfIndexFile, err := createServerV2(cfg, true) require.NoError(err) + grpcHandler := newGRPCHandler(svr.core) defer func() { testutil.CleanupPath(bfIndexFile) }() @@ -1064,7 +1069,7 @@ func TestGrpcServer_GetUnconfirmedActionsByAddressIntegrity(t *testing.T) { }, }, } - res, err := svr.grpcServer.GetActions(context.Background(), request) + res, err := grpcHandler.GetActions(context.Background(), request) if test.count == 0 { require.Error(err) continue @@ -1081,6 +1086,7 @@ func TestGrpcServer_GetActionsByBlockIntegrity(t *testing.T) { svr, _, _, _, _, _, bfIndexFile, err := createServerV2(cfg, false) require.NoError(err) + grpcHandler := newGRPCHandler(svr.core) defer func() { testutil.CleanupPath(bfIndexFile) }() @@ -1095,7 +1101,7 @@ func TestGrpcServer_GetActionsByBlockIntegrity(t *testing.T) { }, }, } - res, err := svr.grpcServer.GetActions(context.Background(), request) + res, err := grpcHandler.GetActions(context.Background(), request) if test.count == 0 { require.Error(err) continue @@ -1120,6 +1126,7 @@ func TestGrpcServer_GetBlockMetasIntegrity(t *testing.T) { block.LoadGenesisHash(&cfg.Genesis) svr, _, _, _, _, _, bfIndexFile, err := createServerV2(cfg, false) require.NoError(err) + grpcHandler := newGRPCHandler(svr.core) defer func() { testutil.CleanupPath(bfIndexFile) }() @@ -1133,7 +1140,7 @@ func TestGrpcServer_GetBlockMetasIntegrity(t *testing.T) { }, }, } - res, err := svr.grpcServer.GetBlockMetas(context.Background(), request) + res, err := grpcHandler.GetBlockMetas(context.Background(), request) if test.count == 0 { require.Error(err) continue @@ -1157,17 +1164,17 @@ func TestGrpcServer_GetBlockMetasIntegrity(t *testing.T) { } } // failure: empty request - _, err = svr.grpcServer.GetBlockMetas(context.Background(), &iotexapi.GetBlockMetasRequest{}) + _, err = grpcHandler.GetBlockMetas(context.Background(), &iotexapi.GetBlockMetasRequest{}) require.Error(err) - _, err = svr.grpcServer.GetBlockMetas(context.Background(), &iotexapi.GetBlockMetasRequest{ + _, err = grpcHandler.GetBlockMetas(context.Background(), &iotexapi.GetBlockMetasRequest{ Lookup: &iotexapi.GetBlockMetasRequest_ByIndex{ ByIndex: &iotexapi.GetBlockMetasByIndexRequest{Start: 10, Count: 1}, }, }) require.Error(err) - _, err = svr.grpcServer.GetBlockMetas(context.Background(), &iotexapi.GetBlockMetasRequest{ + _, err = grpcHandler.GetBlockMetas(context.Background(), &iotexapi.GetBlockMetasRequest{ Lookup: &iotexapi.GetBlockMetasRequest_ByHash{ ByHash: &iotexapi.GetBlockMetaByHashRequest{BlkHash: "0xa2e8e0c9cafbe93f2b7f7c9d32534bc6fde95f2185e5f2aaa6bf7ebdf1a6610a"}, }, @@ -1181,6 +1188,7 @@ func TestGrpcServer_GetBlockMetaIntegrity(t *testing.T) { svr, bc, _, _, _, _, bfIndexFile, err := createServerV2(cfg, false) require.NoError(err) + grpcHandler := newGRPCHandler(svr.core) defer func() { testutil.CleanupPath(bfIndexFile) }() @@ -1196,7 +1204,7 @@ func TestGrpcServer_GetBlockMetaIntegrity(t *testing.T) { }, }, } - res, err := svr.grpcServer.GetBlockMetas(context.Background(), request) + res, err := grpcHandler.GetBlockMetas(context.Background(), request) require.NoError(err) require.Equal(1, len(res.BlkMetas)) blkPb := res.BlkMetas[0] @@ -1248,6 +1256,7 @@ func TestGrpcServer_GetChainMetaIntegrity(t *testing.T) { cfg.API.TpsWindow = test.tpsWindow svr, _, _, _, registry, _, bfIndexFile, err := createServerV2(cfg, false) require.NoError(err) + grpcHandler := newGRPCHandler(svr.core) defer func() { testutil.CleanupPath(bfIndexFile) }() @@ -1263,7 +1272,7 @@ func TestGrpcServer_GetChainMetaIntegrity(t *testing.T) { // TODO: create a core service with empty chain to test coreService.bc = mbc } - res, err := svr.grpcServer.GetChainMeta(context.Background(), &iotexapi.GetChainMetaRequest{}) + res, err := grpcHandler.GetChainMeta(context.Background(), &iotexapi.GetChainMetaRequest{}) require.NoError(err) chainMetaPb := res.ChainMeta require.Equal(test.height, chainMetaPb.Height) @@ -1281,6 +1290,7 @@ func TestGrpcServer_SendActionIntegrity(t *testing.T) { cfg.Genesis.MidwayBlockHeight = 10 svr, _, _, _, _, _, bfIndexFile, err := createServerV2(cfg, true) require.NoError(err) + grpcHandler := newGRPCHandler(svr.core) defer func() { testutil.CleanupPath(bfIndexFile) }() @@ -1295,7 +1305,7 @@ func TestGrpcServer_SendActionIntegrity(t *testing.T) { for i, test := range _sendActionTests { request := &iotexapi.SendActionRequest{Action: test.actionPb} - res, err := svr.grpcServer.SendAction(context.Background(), request) + res, err := grpcHandler.SendAction(context.Background(), request) require.NoError(err) require.Equal(i+1, broadcastHandlerCount) require.Equal(test.actionHash, res.ActionHash) @@ -1360,11 +1370,12 @@ func TestGrpcServer_SendActionIntegrity(t *testing.T) { request := &iotexapi.SendActionRequest{Action: test.action} svr, _, _, _, _, _, file, err := createServerV2(test.cfg(), true) require.NoError(err) + grpcHandler := newGRPCHandler(svr.core) defer func() { testutil.CleanupPath(file) }() - _, err = svr.grpcServer.SendAction(ctx, request) + _, err = grpcHandler.SendAction(ctx, request) require.Contains(err.Error(), test.err) } } @@ -1375,11 +1386,12 @@ func TestGrpcServer_StreamLogsIntegrity(t *testing.T) { svr, _, _, _, _, _, bfIndexFile, err := createServerV2(cfg, true) require.NoError(err) + grpcHandler := newGRPCHandler(svr.core) defer func() { testutil.CleanupPath(bfIndexFile) }() - err = svr.grpcServer.StreamLogs(&iotexapi.StreamLogsRequest{}, nil) + err = grpcHandler.StreamLogs(&iotexapi.StreamLogsRequest{}, nil) require.Error(err) } @@ -1389,13 +1401,14 @@ func TestGrpcServer_GetReceiptByActionIntegrity(t *testing.T) { svr, _, _, _, _, _, bfIndexFile, err := createServerV2(cfg, false) require.NoError(err) + grpcHandler := newGRPCHandler(svr.core) defer func() { testutil.CleanupPath(bfIndexFile) }() for _, test := range _getReceiptByActionTests { request := &iotexapi.GetReceiptByActionRequest{ActionHash: test.in} - res, err := svr.grpcServer.GetReceiptByAction(context.Background(), request) + res, err := grpcHandler.GetReceiptByAction(context.Background(), request) require.NoError(err) receiptPb := res.ReceiptInfo.Receipt require.Equal(test.status, receiptPb.Status) @@ -1404,10 +1417,10 @@ func TestGrpcServer_GetReceiptByActionIntegrity(t *testing.T) { } // failure: empty request - _, err = svr.grpcServer.GetReceiptByAction(context.Background(), &iotexapi.GetReceiptByActionRequest{ActionHash: "0x"}) + _, err = grpcHandler.GetReceiptByAction(context.Background(), &iotexapi.GetReceiptByActionRequest{ActionHash: "0x"}) require.Error(err) // failure: wrong hash - _, err = svr.grpcServer.GetReceiptByAction(context.Background(), &iotexapi.GetReceiptByActionRequest{ActionHash: "b7faffcb8b01fa9f32112155bcb93d714f599eab3178e577e88dafd2140bfc5a"}) + _, err = grpcHandler.GetReceiptByAction(context.Background(), &iotexapi.GetReceiptByActionRequest{ActionHash: "b7faffcb8b01fa9f32112155bcb93d714f599eab3178e577e88dafd2140bfc5a"}) require.Error(err) } @@ -1418,11 +1431,12 @@ func TestGrpcServer_GetServerMetaIntegrity(t *testing.T) { svr, _, _, _, _, _, bfIndexFile, err := createServerV2(cfg, false) require.NoError(err) + grpcHandler := newGRPCHandler(svr.core) defer func() { testutil.CleanupPath(bfIndexFile) }() - resProto, err := svr.grpcServer.GetServerMeta(context.Background(), &iotexapi.GetServerMetaRequest{}) + resProto, err := grpcHandler.GetServerMeta(context.Background(), &iotexapi.GetServerMetaRequest{}) res := resProto.GetServerMeta() require.Equal(res.BuildTime, version.BuildTime) require.Equal(res.GoVersion, version.GoVersion) @@ -1437,6 +1451,7 @@ func TestGrpcServer_ReadContractIntegrity(t *testing.T) { svr, _, dao, indexer, _, _, bfIndexFile, err := createServerV2(cfg, false) require.NoError(err) + grpcHandler := newGRPCHandler(svr.core) defer func() { testutil.CleanupPath(bfIndexFile) }() @@ -1455,7 +1470,7 @@ func TestGrpcServer_ReadContractIntegrity(t *testing.T) { GasPrice: big.NewInt(unit.Qev).String(), } - res, err := svr.grpcServer.ReadContract(context.Background(), request) + res, err := grpcHandler.ReadContract(context.Background(), request) require.NoError(err) require.Equal(test.retValue, res.Data) require.EqualValues(1, res.Receipt.Status) @@ -1472,10 +1487,11 @@ func TestGrpcServer_SuggestGasPriceIntegrity(t *testing.T) { cfg.API.GasStation.DefaultGas = test.defaultGasPrice svr, _, _, _, _, _, bfIndexFile, err := createServerV2(cfg, false) require.NoError(err) + grpcHandler := newGRPCHandler(svr.core) defer func() { testutil.CleanupPath(bfIndexFile) }() - res, err := svr.grpcServer.SuggestGasPrice(context.Background(), &iotexapi.SuggestGasPriceRequest{}) + res, err := grpcHandler.SuggestGasPrice(context.Background(), &iotexapi.SuggestGasPriceRequest{}) require.NoError(err) require.Equal(test.suggestedGasPrice, res.GasPrice) } @@ -1487,6 +1503,7 @@ func TestGrpcServer_EstimateGasForActionIntegrity(t *testing.T) { svr, _, dao, indexer, _, _, bfIndexFile, err := createServerV2(cfg, false) require.NoError(err) + grpcHandler := newGRPCHandler(svr.core) defer func() { testutil.CleanupPath(bfIndexFile) }() @@ -1500,7 +1517,7 @@ func TestGrpcServer_EstimateGasForActionIntegrity(t *testing.T) { require.NoError(err) request := &iotexapi.EstimateGasForActionRequest{Action: act.Proto()} - res, err := svr.grpcServer.EstimateGasForAction(context.Background(), request) + res, err := grpcHandler.EstimateGasForAction(context.Background(), request) require.NoError(err) require.Equal(test.estimatedGas, res.Gas) } @@ -1511,6 +1528,7 @@ func TestGrpcServer_EstimateActionGasConsumptionIntegrity(t *testing.T) { cfg := newConfig() svr, _, _, _, _, _, bfIndexFile, err := createServerV2(cfg, false) require.NoError(err) + grpcHandler := newGRPCHandler(svr.core) defer func() { testutil.CleanupPath(bfIndexFile) }() @@ -1527,7 +1545,7 @@ func TestGrpcServer_EstimateActionGasConsumptionIntegrity(t *testing.T) { }, CallerAddress: identityset.Address(0).String(), } - res, err := svr.grpcServer.EstimateActionGasConsumption(context.Background(), request) + res, err := grpcHandler.EstimateActionGasConsumption(context.Background(), request) require.NoError(err) require.Equal(uint64(286579), res.Gas) @@ -1540,7 +1558,7 @@ func TestGrpcServer_EstimateActionGasConsumptionIntegrity(t *testing.T) { }, CallerAddress: identityset.Address(0).String(), } - res, err = svr.grpcServer.EstimateActionGasConsumption(context.Background(), request) + res, err = grpcHandler.EstimateActionGasConsumption(context.Background(), request) require.NoError(err) require.Equal(uint64(10300), res.Gas) @@ -1566,7 +1584,7 @@ func TestGrpcServer_EstimateActionGasConsumptionIntegrity(t *testing.T) { }, CallerAddress: identityset.Address(0).String(), } - res, err = svr.grpcServer.EstimateActionGasConsumption(context.Background(), request) + res, err = grpcHandler.EstimateActionGasConsumption(context.Background(), request) require.NoError(err) require.Equal(uint64(10300), res.Gas) @@ -1579,7 +1597,7 @@ func TestGrpcServer_EstimateActionGasConsumptionIntegrity(t *testing.T) { }, CallerAddress: identityset.Address(0).String(), } - res, err = svr.grpcServer.EstimateActionGasConsumption(context.Background(), request) + res, err = grpcHandler.EstimateActionGasConsumption(context.Background(), request) require.NoError(err) require.Equal(uint64(10300), res.Gas) @@ -1592,7 +1610,7 @@ func TestGrpcServer_EstimateActionGasConsumptionIntegrity(t *testing.T) { }, CallerAddress: identityset.Address(0).String(), } - res, err = svr.grpcServer.EstimateActionGasConsumption(context.Background(), request) + res, err = grpcHandler.EstimateActionGasConsumption(context.Background(), request) require.NoError(err) require.Equal(uint64(10300), res.Gas) @@ -1605,7 +1623,7 @@ func TestGrpcServer_EstimateActionGasConsumptionIntegrity(t *testing.T) { }, CallerAddress: identityset.Address(0).String(), } - res, err = svr.grpcServer.EstimateActionGasConsumption(context.Background(), request) + res, err = grpcHandler.EstimateActionGasConsumption(context.Background(), request) require.NoError(err) require.Equal(uint64(10300), res.Gas) @@ -1618,7 +1636,7 @@ func TestGrpcServer_EstimateActionGasConsumptionIntegrity(t *testing.T) { }, CallerAddress: identityset.Address(0).String(), } - res, err = svr.grpcServer.EstimateActionGasConsumption(context.Background(), request) + res, err = grpcHandler.EstimateActionGasConsumption(context.Background(), request) require.NoError(err) require.Equal(uint64(10300), res.Gas) @@ -1631,7 +1649,7 @@ func TestGrpcServer_EstimateActionGasConsumptionIntegrity(t *testing.T) { }, CallerAddress: identityset.Address(0).String(), } - res, err = svr.grpcServer.EstimateActionGasConsumption(context.Background(), request) + res, err = grpcHandler.EstimateActionGasConsumption(context.Background(), request) require.NoError(err) require.Equal(uint64(10300), res.Gas) @@ -1644,7 +1662,7 @@ func TestGrpcServer_EstimateActionGasConsumptionIntegrity(t *testing.T) { }, CallerAddress: identityset.Address(0).String(), } - res, err = svr.grpcServer.EstimateActionGasConsumption(context.Background(), request) + res, err = grpcHandler.EstimateActionGasConsumption(context.Background(), request) require.NoError(err) require.Equal(uint64(10300), res.Gas) @@ -1657,7 +1675,7 @@ func TestGrpcServer_EstimateActionGasConsumptionIntegrity(t *testing.T) { }, CallerAddress: identityset.Address(0).String(), } - res, err = svr.grpcServer.EstimateActionGasConsumption(context.Background(), request) + res, err = grpcHandler.EstimateActionGasConsumption(context.Background(), request) require.NoError(err) require.Equal(uint64(10300), res.Gas) @@ -1670,7 +1688,7 @@ func TestGrpcServer_EstimateActionGasConsumptionIntegrity(t *testing.T) { }, CallerAddress: identityset.Address(0).String(), } - res, err = svr.grpcServer.EstimateActionGasConsumption(context.Background(), request) + res, err = grpcHandler.EstimateActionGasConsumption(context.Background(), request) require.NoError(err) require.Equal(uint64(10000), res.Gas) @@ -1679,7 +1697,7 @@ func TestGrpcServer_EstimateActionGasConsumptionIntegrity(t *testing.T) { Action: nil, CallerAddress: identityset.Address(0).String(), } - _, err = svr.grpcServer.EstimateActionGasConsumption(context.Background(), request) + _, err = grpcHandler.EstimateActionGasConsumption(context.Background(), request) require.Error(err) } @@ -1689,12 +1707,13 @@ func TestGrpcServer_ReadUnclaimedBalanceIntegrity(t *testing.T) { cfg.Consensus.Scheme = config.RollDPoSScheme svr, _, _, _, _, _, bfIndexFile, err := createServerV2(cfg, false) require.NoError(err) + grpcHandler := newGRPCHandler(svr.core) defer func() { testutil.CleanupPath(bfIndexFile) }() for _, test := range _readUnclaimedBalanceTests { - out, err := svr.grpcServer.ReadState(context.Background(), &iotexapi.ReadStateRequest{ + out, err := grpcHandler.ReadState(context.Background(), &iotexapi.ReadStateRequest{ ProtocolID: []byte(test.protocolID), MethodName: []byte(test.methodName), Arguments: [][]byte{[]byte(test.addr)}, @@ -1716,11 +1735,12 @@ func TestGrpcServer_TotalBalanceIntegrity(t *testing.T) { svr, _, _, _, _, _, bfIndexFile, err := createServerV2(cfg, false) require.NoError(err) + grpcHandler := newGRPCHandler(svr.core) defer func() { testutil.CleanupPath(bfIndexFile) }() - out, err := svr.grpcServer.ReadState(context.Background(), &iotexapi.ReadStateRequest{ + out, err := grpcHandler.ReadState(context.Background(), &iotexapi.ReadStateRequest{ ProtocolID: []byte("rewarding"), MethodName: []byte("TotalBalance"), Arguments: nil, @@ -1737,11 +1757,12 @@ func TestGrpcServer_AvailableBalanceIntegrity(t *testing.T) { cfg.Consensus.Scheme = config.RollDPoSScheme svr, _, _, _, _, _, bfIndexFile, err := createServerV2(cfg, false) require.NoError(err) + grpcHandler := newGRPCHandler(svr.core) defer func() { testutil.CleanupPath(bfIndexFile) }() - out, err := svr.grpcServer.ReadState(context.Background(), &iotexapi.ReadStateRequest{ + out, err := grpcHandler.ReadState(context.Background(), &iotexapi.ReadStateRequest{ ProtocolID: []byte("rewarding"), MethodName: []byte("AvailableBalance"), Arguments: nil, @@ -1806,12 +1827,13 @@ func TestGrpcServer_ReadCandidatesByEpochIntegrity(t *testing.T) { } svr, _, _, _, registry, _, bfIndexFile, err := createServerV2(cfg, false) require.NoError(err) + grpcHandler := newGRPCHandler(svr.core) defer func() { testutil.CleanupPath(bfIndexFile) }() require.NoError(pol.ForceRegister(registry)) - res, err := svr.grpcServer.ReadState(context.Background(), &iotexapi.ReadStateRequest{ + res, err := grpcHandler.ReadState(context.Background(), &iotexapi.ReadStateRequest{ ProtocolID: []byte(test.protocolID), MethodName: []byte(test.methodName), Arguments: [][]byte{[]byte(strconv.FormatUint(test.epoch, 10))}, @@ -1878,11 +1900,12 @@ func TestGrpcServer_ReadBlockProducersByEpochIntegrity(t *testing.T) { } svr, _, _, _, registry, _, bfIndexFile, err := createServerV2(cfg, false) require.NoError(err) + grpcHandler := newGRPCHandler(svr.core) defer func() { testutil.CleanupPath(bfIndexFile) }() require.NoError(pol.ForceRegister(registry)) - res, err := svr.grpcServer.ReadState(context.Background(), &iotexapi.ReadStateRequest{ + res, err := grpcHandler.ReadState(context.Background(), &iotexapi.ReadStateRequest{ ProtocolID: []byte(test.protocolID), MethodName: []byte(test.methodName), Arguments: [][]byte{[]byte(strconv.FormatUint(test.epoch, 10))}, @@ -1948,12 +1971,13 @@ func TestGrpcServer_ReadActiveBlockProducersByEpochIntegrity(t *testing.T) { } svr, _, _, _, registry, _, bfIndexFile, err := createServerV2(cfg, false) require.NoError(err) + grpcHandler := newGRPCHandler(svr.core) defer func() { testutil.CleanupPath(bfIndexFile) }() require.NoError(pol.ForceRegister(registry)) - res, err := svr.grpcServer.ReadState(context.Background(), &iotexapi.ReadStateRequest{ + res, err := grpcHandler.ReadState(context.Background(), &iotexapi.ReadStateRequest{ ProtocolID: []byte(test.protocolID), MethodName: []byte(test.methodName), Arguments: [][]byte{[]byte(strconv.FormatUint(test.epoch, 10))}, @@ -1972,10 +1996,11 @@ func TestGrpcServer_ReadRollDPoSMetaIntegrity(t *testing.T) { for _, test := range _readRollDPoSMetaTests { svr, _, _, _, _, _, bfIndexFile, err := createServerV2(cfg, false) require.NoError(err) + grpcHandler := newGRPCHandler(svr.core) defer func() { testutil.CleanupPath(bfIndexFile) }() - res, err := svr.grpcServer.ReadState(context.Background(), &iotexapi.ReadStateRequest{ + res, err := grpcHandler.ReadState(context.Background(), &iotexapi.ReadStateRequest{ ProtocolID: []byte(test.protocolID), MethodName: []byte(test.methodName), }) @@ -1993,10 +2018,11 @@ func TestGrpcServer_ReadEpochCtxIntegrity(t *testing.T) { for _, test := range _readEpochCtxTests { svr, _, _, _, _, _, bfIndexFile, err := createServerV2(cfg, false) require.NoError(err) + grpcHandler := newGRPCHandler(svr.core) defer func() { testutil.CleanupPath(bfIndexFile) }() - res, err := svr.grpcServer.ReadState(context.Background(), &iotexapi.ReadStateRequest{ + res, err := grpcHandler.ReadState(context.Background(), &iotexapi.ReadStateRequest{ ProtocolID: []byte(test.protocolID), MethodName: []byte(test.methodName), Arguments: [][]byte{[]byte(strconv.FormatUint(test.argument, 10))}, @@ -2016,6 +2042,7 @@ func TestGrpcServer_GetEpochMetaIntegrity(t *testing.T) { svr, _, _, _, registry, _, bfIndexFile, err := createServerV2(cfg, false) require.NoError(err) + grpcHandler := newGRPCHandler(svr.core) defer func() { testutil.CleanupPath(bfIndexFile) }() @@ -2113,7 +2140,7 @@ func TestGrpcServer_GetEpochMetaIntegrity(t *testing.T) { coreService, ok := svr.core.(*coreService) require.True(ok) coreService.readCache.Clear() - res, err := svr.grpcServer.GetEpochMeta(context.Background(), &iotexapi.GetEpochMetaRequest{EpochNumber: test.EpochNumber}) + res, err := grpcHandler.GetEpochMeta(context.Background(), &iotexapi.GetEpochMetaRequest{EpochNumber: test.EpochNumber}) require.NoError(err) require.Equal(test.epochData.Num, res.EpochData.Num) require.Equal(test.epochData.Height, res.EpochData.Height) @@ -2137,7 +2164,7 @@ func TestGrpcServer_GetEpochMetaIntegrity(t *testing.T) { } // failure: epoch number - _, err = svr.grpcServer.GetEpochMeta(context.Background(), &iotexapi.GetEpochMetaRequest{EpochNumber: 0}) + _, err = grpcHandler.GetEpochMeta(context.Background(), &iotexapi.GetEpochMetaRequest{EpochNumber: 0}) require.Error(err) } @@ -2147,6 +2174,7 @@ func TestGrpcServer_GetRawBlocksIntegrity(t *testing.T) { svr, _, _, _, _, _, bfIndexFile, err := createServerV2(cfg, false) require.NoError(err) + grpcHandler := newGRPCHandler(svr.core) defer func() { testutil.CleanupPath(bfIndexFile) }() @@ -2157,7 +2185,7 @@ func TestGrpcServer_GetRawBlocksIntegrity(t *testing.T) { Count: test.count, WithReceipts: test.withReceipts, } - res, err := svr.grpcServer.GetRawBlocks(context.Background(), request) + res, err := grpcHandler.GetRawBlocks(context.Background(), request) require.NoError(err) blkInfos := res.Blocks require.Equal(test.numBlks, len(blkInfos)) @@ -2183,7 +2211,7 @@ func TestGrpcServer_GetRawBlocksIntegrity(t *testing.T) { } // failure: invalid count - _, err = svr.grpcServer.GetRawBlocks(context.Background(), &iotexapi.GetRawBlocksRequest{ + _, err = grpcHandler.GetRawBlocks(context.Background(), &iotexapi.GetRawBlocksRequest{ StartHeight: 1, Count: 0, WithReceipts: true, @@ -2191,7 +2219,7 @@ func TestGrpcServer_GetRawBlocksIntegrity(t *testing.T) { require.Error(err) // failure: invalid startHeight - _, err = svr.grpcServer.GetRawBlocks(context.Background(), &iotexapi.GetRawBlocksRequest{ + _, err = grpcHandler.GetRawBlocks(context.Background(), &iotexapi.GetRawBlocksRequest{ StartHeight: 1000000, Count: 10, WithReceipts: true, @@ -2199,7 +2227,7 @@ func TestGrpcServer_GetRawBlocksIntegrity(t *testing.T) { require.Error(err) // failure: invalid endHeight - _, err = svr.grpcServer.GetRawBlocks(context.Background(), &iotexapi.GetRawBlocksRequest{ + _, err = grpcHandler.GetRawBlocks(context.Background(), &iotexapi.GetRawBlocksRequest{ StartHeight: 3, Count: 1000, WithReceipts: true, @@ -2214,6 +2242,7 @@ func TestGrpcServer_GetLogsIntegrity(t *testing.T) { svr, _, _, _, _, _, bfIndexFile, err := createServerV2(cfg, false) require.NoError(err) + grpcHandler := newGRPCHandler(svr.core) defer func() { testutil.CleanupPath(bfIndexFile) }() @@ -2231,7 +2260,7 @@ func TestGrpcServer_GetLogsIntegrity(t *testing.T) { }, }, } - res, err := svr.grpcServer.GetLogs(context.Background(), request) + res, err := grpcHandler.GetLogs(context.Background(), request) require.NoError(err) logs := res.Logs require.Equal(test.numLogs, len(logs)) @@ -2250,20 +2279,20 @@ func TestGrpcServer_GetLogsIntegrity(t *testing.T) { }, }, } - res, err := svr.grpcServer.GetLogs(context.Background(), request) + res, err := grpcHandler.GetLogs(context.Background(), request) require.NoError(err) logs := res.Logs require.Equal(1, len(logs)) } // failure: empty request - _, err = svr.grpcServer.GetLogs(context.Background(), &iotexapi.GetLogsRequest{ + _, err = grpcHandler.GetLogs(context.Background(), &iotexapi.GetLogsRequest{ Filter: &iotexapi.LogsFilter{}, }) require.Error(err) // failure: empty filter - _, err = svr.grpcServer.GetLogs(context.Background(), &iotexapi.GetLogsRequest{}) + _, err = grpcHandler.GetLogs(context.Background(), &iotexapi.GetLogsRequest{}) require.Error(err) } @@ -2273,6 +2302,7 @@ func TestGrpcServer_GetElectionBucketsIntegrity(t *testing.T) { svr, _, _, _, _, _, bfIndexFile, err := createServerV2(cfg, false) require.NoError(err) + grpcHandler := newGRPCHandler(svr.core) defer func() { testutil.CleanupPath(bfIndexFile) }() @@ -2281,7 +2311,7 @@ func TestGrpcServer_GetElectionBucketsIntegrity(t *testing.T) { request := &iotexapi.GetElectionBucketsRequest{ EpochNum: 0, } - _, err = svr.grpcServer.GetElectionBuckets(context.Background(), request) + _, err = grpcHandler.GetElectionBuckets(context.Background(), request) require.Error(err) } @@ -2307,6 +2337,7 @@ func TestGrpcServer_GetTransactionLogByActionHashIntegrity(t *testing.T) { svr, _, _, _, _, _, bfIndexFile, err := createServerV2(cfg, false) require.NoError(err) + grpcHandler := newGRPCHandler(svr.core) defer func() { testutil.CleanupPath(bfIndexFile) }() @@ -2314,7 +2345,7 @@ func TestGrpcServer_GetTransactionLogByActionHashIntegrity(t *testing.T) { request := &iotexapi.GetTransactionLogByActionHashRequest{ ActionHash: hex.EncodeToString(hash.ZeroHash256[:]), } - _, err = svr.grpcServer.GetTransactionLogByActionHash(context.Background(), request) + _, err = grpcHandler.GetTransactionLogByActionHash(context.Background(), request) require.Error(err) sta, ok := status.FromError(err) require.Equal(true, ok) @@ -2322,7 +2353,7 @@ func TestGrpcServer_GetTransactionLogByActionHashIntegrity(t *testing.T) { for h, log := range _implicitLogs { request.ActionHash = hex.EncodeToString(h[:]) - res, err := svr.grpcServer.GetTransactionLogByActionHash(context.Background(), request) + res, err := grpcHandler.GetTransactionLogByActionHash(context.Background(), request) require.NoError(err) require.Equal(log.Proto(), res.TransactionLog) } @@ -2342,6 +2373,7 @@ func TestGrpcServer_GetEvmTransfersByBlockHeightIntegrity(t *testing.T) { svr, _, _, _, _, _, bfIndexFile, err := createServerV2(cfg, false) require.NoError(err) + grpcHandler := newGRPCHandler(svr.core) defer func() { testutil.CleanupPath(bfIndexFile) }() @@ -2349,7 +2381,7 @@ func TestGrpcServer_GetEvmTransfersByBlockHeightIntegrity(t *testing.T) { request := &iotexapi.GetTransactionLogByBlockHeightRequest{} for _, test := range _getImplicitLogByBlockHeightTest { request.BlockHeight = test.height - res, err := svr.grpcServer.GetTransactionLogByBlockHeight(context.Background(), request) + res, err := grpcHandler.GetTransactionLogByBlockHeight(context.Background(), request) if test.code != codes.OK { require.Error(err) sta, ok := status.FromError(err) @@ -2376,11 +2408,12 @@ func TestGrpcServer_GetActPoolActionsIntegrity(t *testing.T) { svr, _, _, _, _, actPool, bfIndexFile, err := createServerV2(cfg, false) require.NoError(err) + grpcHandler := newGRPCHandler(svr.core) defer func() { testutil.CleanupPath(bfIndexFile) }() - res, err := svr.grpcServer.GetActPoolActions(ctx, &iotexapi.GetActPoolActionsRequest{}) + res, err := grpcHandler.GetActPoolActions(ctx, &iotexapi.GetActPoolActionsRequest{}) require.NoError(err) require.Equal(len(actPool.PendingActionMap()[identityset.Address(27).String()]), len(res.Actions)) @@ -2406,24 +2439,24 @@ func TestGrpcServer_GetActPoolActionsIntegrity(t *testing.T) { require.NoError(err) requests = append(requests, hex.EncodeToString(h1[:])) - res, err = svr.grpcServer.GetActPoolActions(context.Background(), &iotexapi.GetActPoolActionsRequest{}) + res, err = grpcHandler.GetActPoolActions(context.Background(), &iotexapi.GetActPoolActionsRequest{}) require.NoError(err) require.Equal(len(actPool.PendingActionMap()[identityset.Address(27).String()]), len(res.Actions)) - res, err = svr.grpcServer.GetActPoolActions(context.Background(), &iotexapi.GetActPoolActionsRequest{ActionHashes: requests}) + res, err = grpcHandler.GetActPoolActions(context.Background(), &iotexapi.GetActPoolActionsRequest{ActionHashes: requests}) require.NoError(err) require.Equal(1, len(res.Actions)) h2, err := tsf2.Hash() require.NoError(err) requests = append(requests, hex.EncodeToString(h2[:])) - res, err = svr.grpcServer.GetActPoolActions(context.Background(), &iotexapi.GetActPoolActionsRequest{ActionHashes: requests}) + res, err = grpcHandler.GetActPoolActions(context.Background(), &iotexapi.GetActPoolActionsRequest{ActionHashes: requests}) require.NoError(err) require.Equal(2, len(res.Actions)) h3, err := tsf3.Hash() require.NoError(err) - _, err = svr.grpcServer.GetActPoolActions(context.Background(), &iotexapi.GetActPoolActionsRequest{ActionHashes: []string{hex.EncodeToString(h3[:])}}) + _, err = grpcHandler.GetActPoolActions(context.Background(), &iotexapi.GetActPoolActionsRequest{ActionHashes: []string{hex.EncodeToString(h3[:])}}) require.Error(err) } @@ -2433,6 +2466,7 @@ func TestGrpcServer_GetEstimateGasSpecialIntegrity(t *testing.T) { svr, bc, dao, _, _, actPool, bfIndexFile, err := createServerV2(cfg, true) require.NoError(err) + grpcHandler := newGRPCHandler(svr.core) defer func() { testutil.CleanupPath(bfIndexFile) }() @@ -2456,7 +2490,7 @@ func TestGrpcServer_GetEstimateGasSpecialIntegrity(t *testing.T) { }, CallerAddress: identityset.Address(13).String(), } - res, err := svr.grpcServer.EstimateActionGasConsumption(context.Background(), request) + res, err := grpcHandler.EstimateActionGasConsumption(context.Background(), request) require.NoError(err) require.Equal(uint64(10777), res.Gas) } @@ -2551,12 +2585,13 @@ func TestChainlinkErrIntegrity(t *testing.T) { t.Run(strconv.Itoa(i), func(t *testing.T) { svr, _, _, _, _, _, file, err := createServerV2(test.cfg(), true) require.NoError(err) + grpcHandler := newGRPCHandler(svr.core) defer func() { testutil.CleanupPath(file) }() for _, action := range test.actions { - _, err = svr.grpcServer.SendAction(context.Background(), &iotexapi.SendActionRequest{Action: action}) + _, err = grpcHandler.SendAction(context.Background(), &iotexapi.SendActionRequest{Action: action}) if err != nil { break } @@ -2574,6 +2609,7 @@ func TestGrpcServer_TraceTransactionStructLogsIntegrity(t *testing.T) { svr, bc, _, _, _, actPool, bfIndexFile, err := createServerV2(cfg, true) require.NoError(err) + grpcHandler := newGRPCHandler(svr.core) defer func() { testutil.CleanupPath(bfIndexFile) }() @@ -2581,12 +2617,12 @@ func TestGrpcServer_TraceTransactionStructLogsIntegrity(t *testing.T) { request := &iotexapi.TraceTransactionStructLogsRequest{ ActionHash: hex.EncodeToString(hash.ZeroHash256[:]), } - _, err = svr.grpcServer.TraceTransactionStructLogs(context.Background(), request) + _, err = grpcHandler.TraceTransactionStructLogs(context.Background(), request) require.Error(err) //unsupport type request.ActionHash = hex.EncodeToString(_transferHash1[:]) - _, err = svr.grpcServer.TraceTransactionStructLogs(context.Background(), request) + _, err = grpcHandler.TraceTransactionStructLogs(context.Background(), request) require.Error(err) // deploy a contract @@ -2604,7 +2640,7 @@ func TestGrpcServer_TraceTransactionStructLogsIntegrity(t *testing.T) { actPool.Reset() ex1Hash, _ := ex1.Hash() request.ActionHash = hex.EncodeToString(ex1Hash[:]) - ret, err := svr.grpcServer.TraceTransactionStructLogs(context.Background(), request) + ret, err := grpcHandler.TraceTransactionStructLogs(context.Background(), request) require.NoError(err) require.Equal(len(ret.StructLogs), 17) log := ret.StructLogs[0] diff --git a/api/grpcserver_test.go b/api/grpcserver_test.go index 084a65f390..e91dbeedaa 100644 --- a/api/grpcserver_test.go +++ b/api/grpcserver_test.go @@ -20,7 +20,6 @@ import ( "github.com/iotexproject/iotex-core/pkg/version" "github.com/iotexproject/iotex-core/test/identityset" "github.com/iotexproject/iotex-core/test/mock/mock_apicoreservice" - "github.com/iotexproject/iotex-core/testutil" ) func TestGrpcServer_GetAccount(t *testing.T) { @@ -64,7 +63,7 @@ func TestGrpcServer_SendAction(t *testing.T) { ctrl := gomock.NewController(t) defer ctrl.Finish() core := mock_apicoreservice.NewMockCoreService(ctrl) - grpcSvr := NewGRPCServer(core, testutil.RandomPort()) + grpcSvr := newGRPCHandler(core) for _, test := range _sendActionTests { core.EXPECT().EVMNetworkID().Return(uint32(1)) @@ -97,7 +96,7 @@ func TestGrpcServer_SuggestGasPrice(t *testing.T) { ctrl := gomock.NewController(t) defer ctrl.Finish() core := mock_apicoreservice.NewMockCoreService(ctrl) - grpcSvr := NewGRPCServer(core, testutil.RandomPort()) + grpcSvr := newGRPCHandler(core) core.EXPECT().SuggestGasPrice().Return(uint64(1), nil) res, err := grpcSvr.SuggestGasPrice(context.Background(), &iotexapi.SuggestGasPriceRequest{}) @@ -114,7 +113,7 @@ func TestGrpcServer_EstimateGasForAction(t *testing.T) { ctrl := gomock.NewController(t) defer ctrl.Finish() core := mock_apicoreservice.NewMockCoreService(ctrl) - grpcSvr := NewGRPCServer(core, testutil.RandomPort()) + grpcSvr := newGRPCHandler(core) core.EXPECT().EstimateGasForAction(gomock.Any(), gomock.Any()).Return(uint64(10000), nil) resp, err := grpcSvr.EstimateGasForAction(context.Background(), &iotexapi.EstimateGasForActionRequest{Action: getAction()}) diff --git a/api/http.go b/api/http.go index 7cf73cc94e..b7d67824d9 100644 --- a/api/http.go +++ b/api/http.go @@ -13,15 +13,21 @@ import ( "github.com/iotexproject/iotex-core/pkg/log" ) -// HTTPServer handles requests from http protocol -type HTTPServer struct { - svr *http.Server - msgHandler Web3Handler -} +type ( + // HTTPServer crates a http server + HTTPServer struct { + svr *http.Server + } + + // hTTPHandler handles requests from http protocol + hTTPHandler struct { + msgHandler Web3Handler + } +) // NewHTTPServer creates a new http server // TODO: move timeout into config -func NewHTTPServer(route string, port int, handler Web3Handler) *HTTPServer { +func NewHTTPServer(route string, port int, handler http.Handler) *HTTPServer { if port == 0 { return nil } @@ -30,11 +36,9 @@ func NewHTTPServer(route string, port int, handler Web3Handler) *HTTPServer { Addr: ":" + strconv.Itoa(port), WriteTimeout: 30 * time.Second, }, - msgHandler: handler, } - mux := http.NewServeMux() - mux.Handle("/"+route, svr) + mux.Handle("/"+route, handler) svr.svr.Handler = mux return svr } @@ -54,13 +58,20 @@ func (hSvr *HTTPServer) Stop(ctx context.Context) error { return hSvr.svr.Shutdown(ctx) } -func (hSvr *HTTPServer) ServeHTTP(w http.ResponseWriter, req *http.Request) { +// newHTTPHandler creates a new http handler +func newHTTPHandler(web3Handler Web3Handler) *hTTPHandler { + return &hTTPHandler{ + msgHandler: web3Handler, + } +} + +func (handler *hTTPHandler) ServeHTTP(w http.ResponseWriter, req *http.Request) { if req.Method != "POST" { w.WriteHeader(http.StatusMethodNotAllowed) return } - if err := hSvr.msgHandler.HandlePOSTReq(req.Body, + if err := handler.msgHandler.HandlePOSTReq(req.Body, apitypes.NewResponseWriter( func(resp interface{}) error { w.Header().Set("Access-Control-Allow-Origin", "*") diff --git a/api/http_test.go b/api/http_test.go index 6a49f24233..23b7824270 100644 --- a/api/http_test.go +++ b/api/http_test.go @@ -21,7 +21,7 @@ func TestServeHTTP(t *testing.T) { defer ctrl.Finish() handler := mock_web3server.NewMockWeb3Handler(ctrl) handler.EXPECT().HandlePOSTReq(gomock.Any(), gomock.Any()).Return(nil) - svr := NewHTTPServer("", testutil.RandomPort(), handler) + svr := newHTTPHandler(handler) t.Run("WrongHTTPMethod", func(t *testing.T) { req, _ := http.NewRequest(http.MethodGet, "http://url.com", nil) @@ -45,7 +45,7 @@ func TestServerStartStop(t *testing.T) { ctrl := gomock.NewController(t) defer ctrl.Finish() handler := mock_web3server.NewMockWeb3Handler(ctrl) - svr := NewHTTPServer("", testutil.RandomPort(), handler) + svr := NewHTTPServer("", testutil.RandomPort(), newHTTPHandler(handler)) err := svr.Start(context.Background()) require.NoError(err) diff --git a/api/serverV2.go b/api/serverV2.go index 7d48a9df97..2a8cc05baa 100644 --- a/api/serverV2.go +++ b/api/serverV2.go @@ -29,7 +29,7 @@ type ServerV2 struct { core CoreService grpcServer *GRPCServer httpSvr *HTTPServer - websocketSvr *WebsocketServer + websocketSvr *HTTPServer tracer *tracesdk.TracerProvider } @@ -61,11 +61,12 @@ func NewServerV2( if err != nil { return nil, errors.Wrapf(err, "cannot config tracer provider") } + return &ServerV2{ core: coreAPI, grpcServer: NewGRPCServer(coreAPI, cfg.GRPCPort), - httpSvr: NewHTTPServer("", cfg.HTTPPort, web3Handler), - websocketSvr: NewWebSocketServer("", cfg.WebSocketPort, web3Handler), + httpSvr: NewHTTPServer("", cfg.HTTPPort, newHTTPHandler(web3Handler)), + websocketSvr: NewHTTPServer("", cfg.WebSocketPort, NewWebsocketHandler(web3Handler)), tracer: tp, }, nil } diff --git a/api/serverV2_test.go b/api/serverV2_test.go index 03a88cac87..0727ce1cd9 100644 --- a/api/serverV2_test.go +++ b/api/serverV2_test.go @@ -23,8 +23,8 @@ func TestServerV2(t *testing.T) { svr := &ServerV2{ core: core, grpcServer: NewGRPCServer(core, testutil.RandomPort()), - httpSvr: NewHTTPServer("", testutil.RandomPort(), web3Handler), - websocketSvr: NewWebSocketServer("", testutil.RandomPort(), web3Handler), + httpSvr: NewHTTPServer("", testutil.RandomPort(), newHTTPHandler(web3Handler)), + websocketSvr: NewHTTPServer("", testutil.RandomPort(), NewWebsocketHandler(web3Handler)), } ctx := context.Background() diff --git a/api/web3server_test.go b/api/web3server_test.go index be7ba43c00..38b4897f61 100644 --- a/api/web3server_test.go +++ b/api/web3server_test.go @@ -16,7 +16,6 @@ import ( "github.com/tidwall/gjson" "github.com/iotexproject/iotex-core/test/mock/mock_apicoreservice" - "github.com/iotexproject/iotex-core/testutil" ) func TestGetWeb3Reqs(t *testing.T) { @@ -73,8 +72,8 @@ func TestHandlePost(t *testing.T) { ctrl := gomock.NewController(t) defer ctrl.Finish() core := mock_apicoreservice.NewMockCoreService(ctrl) - svr := NewHTTPServer("", testutil.RandomPort(), NewWeb3Handler(core, "")) - getServerResp := func(svr *HTTPServer, req *http.Request) *httptest.ResponseRecorder { + svr := newHTTPHandler(NewWeb3Handler(core, "")) + getServerResp := func(svr *hTTPHandler, req *http.Request) *httptest.ResponseRecorder { req.Header.Set("Content-Type", "application/json") resp := httptest.NewRecorder() svr.ServeHTTP(resp, req) diff --git a/api/websocket.go b/api/websocket.go index 30029d97b2..466b78f0e6 100644 --- a/api/websocket.go +++ b/api/websocket.go @@ -3,7 +3,6 @@ package api import ( "context" "net/http" - "strconv" "time" "github.com/gorilla/websocket" @@ -27,9 +26,8 @@ const ( maxMessageSize = 15 * 1024 * 1024 ) -// WebsocketServer handles requests from websocket protocol -type WebsocketServer struct { - svr *http.Server +// WebsocketHandler handles requests from websocket protocol +type WebsocketHandler struct { msgHandler Web3Handler } @@ -38,39 +36,14 @@ var upgrader = websocket.Upgrader{ WriteBufferSize: 1024, } -// NewWebSocketServer creates a new websocket server -func NewWebSocketServer(route string, port int, handler Web3Handler) *WebsocketServer { - if port == 0 { - return nil - } - svr := &WebsocketServer{ - svr: &http.Server{ - Addr: ":" + strconv.Itoa(port), - }, - msgHandler: handler, +// NewWebsocketHandler creates a new websocket handler +func NewWebsocketHandler(web3Handler Web3Handler) *WebsocketHandler { + return &WebsocketHandler{ + msgHandler: web3Handler, } - mux := http.NewServeMux() - mux.Handle("/"+route, svr) - svr.svr.Handler = mux - return svr -} - -// Start starts the websocket server -func (wsSvr *WebsocketServer) Start(_ context.Context) error { - go func() { - if err := wsSvr.svr.ListenAndServe(); err != nil && err != http.ErrServerClosed { - log.L().Fatal("Node failed to serve.", zap.Error(err)) - } - }() - return nil -} - -// Stop stops the websocket server -func (wsSvr *WebsocketServer) Stop(ctx context.Context) error { - return wsSvr.svr.Shutdown(ctx) } -func (wsSvr *WebsocketServer) ServeHTTP(w http.ResponseWriter, req *http.Request) { +func (wsSvr *WebsocketHandler) ServeHTTP(w http.ResponseWriter, req *http.Request) { upgrader.CheckOrigin = func(_ *http.Request) bool { return true } // upgrade this connection to a WebSocket connection @@ -83,7 +56,7 @@ func (wsSvr *WebsocketServer) ServeHTTP(w http.ResponseWriter, req *http.Request wsSvr.handleConnection(ws) } -func (wsSvr *WebsocketServer) handleConnection(ws *websocket.Conn) { +func (wsSvr *WebsocketHandler) handleConnection(ws *websocket.Conn) { defer ws.Close() ws.SetReadDeadline(time.Now().Add(pongWait)) ws.SetReadLimit(maxMessageSize)