Skip to content

Commit

Permalink
[api] Remove ActionsByBlock() in coreService (#3432)
Browse files Browse the repository at this point in the history
* remove ActionsByBlock() in coreService
  • Loading branch information
Liuhaai authored and saitofun committed Jun 9, 2022
1 parent bab5af5 commit 8ac5045
Show file tree
Hide file tree
Showing 5 changed files with 86 additions and 117 deletions.
93 changes: 10 additions & 83 deletions api/coreservice.go
Original file line number Diff line number Diff line change
Expand Up @@ -58,8 +58,8 @@ import (
"github.com/iotexproject/iotex-core/state/factory"
)

var (
_workerNumbers int = 5
const (
_workerNumbers = 5
)

type (
Expand Down Expand Up @@ -106,10 +106,8 @@ type (
ActionsByAddress(addr address.Address, start uint64, count uint64) ([]*iotexapi.ActionInfo, error)
// ActionByActionHash returns action by action hash
ActionByActionHash(h hash.Hash256) (action.SealedEnvelope, hash.Hash256, uint64, uint32, error)
// ActionsByBlock returns all actions in a block
ActionsByBlock(blkHash string, start uint64, count uint64) ([]*iotexapi.ActionInfo, error)
// ActionsInBlockByHash returns all actions in a block
ActionsInBlockByHash(string) ([]action.SealedEnvelope, []*action.Receipt, error)
// BlockByHash returns the block and its receipt
BlockByHash(string) (*block.Store, error)
// ActPoolActions returns the all Transaction Identifiers in the mempool
ActPoolActions(actHashes []string) ([]*iotextypes.Action, error)
// UnconfirmedActionsByAddress returns all unconfirmed actions in actpool associated with an address
Expand Down Expand Up @@ -1010,48 +1008,24 @@ func (core *coreService) UnconfirmedActionsByAddress(address string, start uint6
return res, nil
}

// ActionsByBlock returns all actions in a block
func (core *coreService) ActionsByBlock(blkHash string, start uint64, count uint64) ([]*iotexapi.ActionInfo, error) {
// BlockByHash returns the block and its receipt
func (core *coreService) BlockByHash(blkHash string) (*block.Store, error) {
if err := core.checkActionIndex(); err != nil {
return nil, err
}
if count == 0 {
return nil, status.Error(codes.InvalidArgument, "count must be greater than zero")
}
if count > core.cfg.RangeQueryLimit && count != math.MaxUint64 {
return nil, status.Error(codes.InvalidArgument, "range exceeds the limit")
}
hash, err := hash.HexStringToHash256(blkHash)
if err != nil {
return nil, status.Error(codes.InvalidArgument, err.Error())
}
blk, err := core.dao.GetBlock(hash)
if err != nil {
return nil, status.Error(codes.NotFound, err.Error())
}
if start >= uint64(len(blk.Actions)) {
return nil, status.Error(codes.InvalidArgument, "start exceeds the limit")
}

return core.actionsInBlock(blk, start, count), nil
}

// TODO: replace ActionsByBlock with ActionsInBlockByHash
// ActionsInBlockByHash returns all sealedEnvelopes and receipts in the block
func (core *coreService) ActionsInBlockByHash(blkHash string) ([]action.SealedEnvelope, []*action.Receipt, error) {
hash, err := hash.HexStringToHash256(blkHash)
if err != nil {
return nil, nil, err
return nil, err
}
blk, err := core.dao.GetBlock(hash)
if err != nil {
return nil, nil, errors.Wrap(ErrNotFound, err.Error())
return nil, errors.Wrap(ErrNotFound, err.Error())
}
receipts, err := core.dao.GetReceipts(blk.Height())
if err != nil {
return nil, nil, errors.Wrap(ErrNotFound, err.Error())
return nil, errors.Wrap(ErrNotFound, err.Error())
}
return blk.Actions, receipts, nil
return &block.Store{blk, receipts}, nil
}

// BlockMetas returns blockmetas response within the height range
Expand Down Expand Up @@ -1248,53 +1222,6 @@ func (core *coreService) getAction(actHash hash.Hash256, checkPending bool) (*io
return core.pendingAction(selp)
}

func (core *coreService) actionsInBlock(blk *block.Block, start, count uint64) []*iotexapi.ActionInfo {
var res []*iotexapi.ActionInfo
if len(blk.Actions) == 0 || start >= uint64(len(blk.Actions)) {
return res
}

h := blk.HashBlock()
blkHash := hex.EncodeToString(h[:])
blkHeight := blk.Height()

lastAction := start + count
if count == math.MaxUint64 {
// count = -1 means to get all actions
lastAction = uint64(len(blk.Actions))
} else {
if lastAction >= uint64(len(blk.Actions)) {
lastAction = uint64(len(blk.Actions))
}
}
for i := start; i < lastAction; i++ {
selp := blk.Actions[i]
actHash, err := selp.Hash()
if err != nil {
log.Logger("api").Debug("Skipping action due to hash error", zap.Error(err))
continue
}
receipt, err := core.dao.GetReceiptByActionHash(actHash, blkHeight)
if err != nil {
log.Logger("api").Debug("Skipping action due to failing to get receipt", zap.Error(err))
continue
}
gas := new(big.Int).Mul(selp.GasPrice(), big.NewInt(int64(receipt.GasConsumed)))
sender := selp.SrcPubkey().Address()
res = append(res, &iotexapi.ActionInfo{
Action: selp.Proto(),
ActHash: hex.EncodeToString(actHash[:]),
BlkHash: blkHash,
Timestamp: blk.Header.BlockHeaderCoreProto().Timestamp,
BlkHeight: blkHeight,
Sender: sender.String(),
GasFee: gas.String(),
Index: uint32(i),
})
}
return res
}

func (core *coreService) reverseActionsInBlock(blk *block.Block, reverseStart, count uint64) []*iotexapi.ActionInfo {
h := blk.HashBlock()
blkHash := hex.EncodeToString(h[:])
Expand Down
62 changes: 60 additions & 2 deletions api/grpcserver.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,8 @@ import (
"context"
"encoding/hex"
"fmt"
"math"
"math/big"
"net"
"strconv"
"time"
Expand Down Expand Up @@ -37,6 +39,7 @@ import (
"github.com/iotexproject/iotex-core/action"
"github.com/iotexproject/iotex-core/action/protocol"
"github.com/iotexproject/iotex-core/api/logfilter"
"github.com/iotexproject/iotex-core/blockchain/block"
"github.com/iotexproject/iotex-core/pkg/log"
"github.com/iotexproject/iotex-core/pkg/tracer"
)
Expand Down Expand Up @@ -170,8 +173,15 @@ func (svr *GRPCServer) GetActions(ctx context.Context, in *iotexapi.GetActionsRe
request := in.GetUnconfirmedByAddr()
ret, err = svr.coreService.UnconfirmedActionsByAddress(request.Address, request.Start, request.Count)
case in.GetByBlk() != nil:
request := in.GetByBlk()
ret, err = svr.coreService.ActionsByBlock(request.BlkHash, request.Start, request.Count)
var (
request = in.GetByBlk()
blkStore *block.Store
)
blkStore, err = svr.coreService.BlockByHash(request.BlkHash)
if err != nil {
break
}
ret, err = actionsInBlock(blkStore.Block, blkStore.Receipts, request.Start, request.Count)
default:
return nil, status.Error(codes.NotFound, "invalid GetActionsRequest type")
}
Expand All @@ -184,6 +194,54 @@ func (svr *GRPCServer) GetActions(ctx context.Context, in *iotexapi.GetActionsRe
}, nil
}

func actionsInBlock(blk *block.Block, receipts []*action.Receipt, start, count uint64) ([]*iotexapi.ActionInfo, error) {
var res []*iotexapi.ActionInfo
if len(blk.Actions) == 0 {
return res, nil
}
if count == 0 {
return nil, status.Error(codes.InvalidArgument, "count must be greater than zero")
}
if start >= uint64(len(blk.Actions)) {
return nil, status.Error(codes.InvalidArgument, "start exceeds the limit")
}

h := blk.HashBlock()
blkHash := hex.EncodeToString(h[:])
blkHeight := blk.Height()

lastAction := start + count
if count == math.MaxUint64 {
// count = -1 means to get all actions
lastAction = uint64(len(blk.Actions))
} else {
if lastAction >= uint64(len(blk.Actions)) {
lastAction = uint64(len(blk.Actions))
}
}
for i := start; i < lastAction; i++ {
selp, receipt := blk.Actions[i], receipts[i]
actHash, err := selp.Hash()
if err != nil {
log.Logger("api").Debug("Skipping action due to hash error", zap.Error(err))
continue
}
gas := new(big.Int).Mul(selp.GasPrice(), big.NewInt(int64(receipt.GasConsumed)))
sender := selp.SrcPubkey().Address()
res = append(res, &iotexapi.ActionInfo{
Action: selp.Proto(),
ActHash: hex.EncodeToString(actHash[:]),
BlkHash: blkHash,
Timestamp: blk.Header.BlockHeaderCoreProto().Timestamp,
BlkHeight: blkHeight,
Sender: sender.String(),
GasFee: gas.String(),
Index: uint32(i),
})
}
return res, nil
}

// GetBlockMetas returns block metadata
func (svr *GRPCServer) GetBlockMetas(ctx context.Context, in *iotexapi.GetBlockMetasRequest) (*iotexapi.GetBlockMetasResponse, error) {
var (
Expand Down
12 changes: 6 additions & 6 deletions api/web3server.go
Original file line number Diff line number Diff line change
Expand Up @@ -590,14 +590,14 @@ func (svr *web3Handler) getTransactionByBlockHashAndIndex(in *gjson.Result) (int
return nil, err
}
blkHash := util.Remove0xPrefix(blkHashStr.String())
selps, receipts, err := svr.coreService.ActionsInBlockByHash(blkHash)
if errors.Cause(err) == ErrNotFound || idx >= uint64(len(receipts)) || len(receipts) == 0 {
blkStore, err := svr.coreService.BlockByHash(blkHash)
if errors.Cause(err) == ErrNotFound || idx >= uint64(len(blkStore.Receipts)) || len(blkStore.Receipts) == 0 {
return nil, nil
}
if err != nil {
return nil, err
}
return svr.getTransactionFromActionInfo(blkHash, selps[idx], receipts[idx])
return svr.getTransactionFromActionInfo(blkHash, blkStore.Block.Actions[idx], blkStore.Receipts[idx])
}

func (svr *web3Handler) getTransactionByBlockNumberAndIndex(in *gjson.Result) (interface{}, error) {
Expand All @@ -624,14 +624,14 @@ func (svr *web3Handler) getTransactionByBlockNumberAndIndex(in *gjson.Result) (i
if len(blkMetas) == 0 {
return nil, nil
}
selps, receipts, err := svr.coreService.ActionsInBlockByHash(blkMetas[0].Hash)
if errors.Cause(err) == ErrNotFound || idx >= uint64(len(receipts)) || len(receipts) == 0 {
blkStore, err := svr.coreService.BlockByHash(blkMetas[0].Hash)
if errors.Cause(err) == ErrNotFound || idx >= uint64(len(blkStore.Receipts)) || len(blkStore.Receipts) == 0 {
return nil, nil
}
if err != nil {
return nil, err
}
return svr.getTransactionFromActionInfo(blkMetas[0].Hash, selps[idx], receipts[idx])
return svr.getTransactionFromActionInfo(blkMetas[0].Hash, blkStore.Block.Actions[idx], blkStore.Receipts[idx])
}

func (svr *web3Handler) getStorageAt(in *gjson.Result) (interface{}, error) {
Expand Down
6 changes: 3 additions & 3 deletions api/web3server_utils.go
Original file line number Diff line number Diff line change
Expand Up @@ -65,13 +65,13 @@ func intStrToHex(str string) (string, error) {
func (svr *web3Handler) getBlockWithTransactions(blkMeta *iotextypes.BlockMeta, isDetailed bool) (*getBlockResult, error) {
transactions := make([]interface{}, 0)
if blkMeta.Height > 0 {
selps, receipts, err := svr.coreService.ActionsInBlockByHash(blkMeta.Hash)
blkStore, err := svr.coreService.BlockByHash(blkMeta.Hash)
if err != nil {
return nil, err
}
for i, selp := range selps {
for i, selp := range blkStore.Block.Actions {
if isDetailed {
tx, err := svr.getTransactionFromActionInfo(blkMeta.Hash, selp, receipts[i])
tx, err := svr.getTransactionFromActionInfo(blkMeta.Hash, selp, blkStore.Receipts[i])
if err != nil {
if errors.Cause(err) != errUnsupportedAction {
h, _ := selp.Hash()
Expand Down
30 changes: 7 additions & 23 deletions test/mock/mock_apicoreservice/mock_apicoreservice.go

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

0 comments on commit 8ac5045

Please sign in to comment.