Skip to content

[refactor] move getBlockTime and getBlockHash funcs into blockchain context #4590

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

Merged
merged 3 commits into from
Apr 1, 2025
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
4 changes: 4 additions & 0 deletions action/protocol/context.go
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,10 @@ type (
ChainID uint32
// EvmNetworkID is the EVM network ID
EvmNetworkID uint32
// GetBlockHash is the function to get block hash by height
GetBlockHash func(uint64) (hash.Hash256, error)
// GetBlockTime is the function to get block time by height
GetBlockTime func(uint64) (time.Time, error)
}

// BlockCtx provides block auxiliary information.
Expand Down
16 changes: 8 additions & 8 deletions action/protocol/execution/protocol.go
Original file line number Diff line number Diff line change
Expand Up @@ -29,20 +29,19 @@ const (

// Protocol defines the protocol of handling executions
type Protocol struct {
getBlockHash evm.GetBlockHash
getBlockTime evm.GetBlockTime
depositGas protocol.DepositGas
addr address.Address
depositGas protocol.DepositGas
addr address.Address
}

// NewProtocol instantiates the protocol of exeuction
func NewProtocol(getBlockHash evm.GetBlockHash, depositGas protocol.DepositGas, getBlockTime evm.GetBlockTime) *Protocol {
// TODO: remove unused getBlockHash and getBlockTime
func NewProtocol(_ evm.GetBlockHash, depositGas protocol.DepositGas, _ evm.GetBlockTime) *Protocol {
h := hash.Hash160b([]byte(_protocolID))
addr, err := address.FromBytes(h[:])
if err != nil {
log.L().Panic("Error when constructing the address of vote protocol", zap.Error(err))
}
return &Protocol{getBlockHash: getBlockHash, depositGas: depositGas, addr: addr, getBlockTime: getBlockTime}
return &Protocol{depositGas: depositGas, addr: addr}
}

// FindProtocol finds the registered protocol from registry
Expand All @@ -66,9 +65,10 @@ func (p *Protocol) Handle(ctx context.Context, elp action.Envelope, sm protocol.
if _, ok := elp.Action().(*action.Execution); !ok {
return nil, nil
}
bcCtx := protocol.MustGetBlockchainCtx(ctx)
ctx = evm.WithHelperCtx(ctx, evm.HelperContext{
GetBlockHash: p.getBlockHash,
GetBlockTime: p.getBlockTime,
GetBlockHash: bcCtx.GetBlockHash,
GetBlockTime: bcCtx.GetBlockTime,
DepositGasFunc: p.depositGas,
})
_, receipt, err := evm.ExecuteContract(ctx, sm, elp)
Expand Down
7 changes: 3 additions & 4 deletions action/protocol/poll/consortium.go
Original file line number Diff line number Diff line change
Expand Up @@ -50,11 +50,11 @@ type consortiumCommittee struct {
bufferResult state.CandidateList
indexer *CandidateIndexer
addr address.Address
getBlockHash evm.GetBlockHash
}

// NewConsortiumCommittee creates a committee for consorium chain
func NewConsortiumCommittee(indexer *CandidateIndexer, readContract ReadContract, getBlockHash evm.GetBlockHash) (Protocol, error) {
// TODO: remove unused getBlockHash
func NewConsortiumCommittee(indexer *CandidateIndexer, readContract ReadContract, _ evm.GetBlockHash) (Protocol, error) {
abi, err := abi.JSON(strings.NewReader(ConsortiumManagementABI))
if err != nil {
return nil, err
Expand All @@ -73,7 +73,6 @@ func NewConsortiumCommittee(indexer *CandidateIndexer, readContract ReadContract
abi: abi,
addr: addr,
indexer: indexer,
getBlockHash: getBlockHash,
}, nil
}

Expand Down Expand Up @@ -143,7 +142,7 @@ func (cc *consortiumCommittee) CreateGenesisStates(ctx context.Context, sm proto
cc.contract = receipt.ContractAddress

ctx = evm.WithHelperCtx(ctx, evm.HelperContext{
GetBlockHash: cc.getBlockHash,
GetBlockHash: protocol.MustGetBlockchainCtx(ctx).GetBlockHash,
GetBlockTime: getBlockTime,
})
r := getContractReaderForGenesisStates(ctx, sm)
Expand Down
11 changes: 4 additions & 7 deletions action/protocol/poll/governance_protocol.go
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,6 @@ import (
)

type governanceChainCommitteeProtocol struct {
getBlockTime GetBlockTime
electionCommittee committee.Committee
initGravityChainHeight uint64
addr address.Address
Expand All @@ -35,20 +34,18 @@ type governanceChainCommitteeProtocol struct {
}

// NewGovernanceChainCommitteeProtocol creates a Poll Protocol which fetch result from governance chain
// TODO: remove getBlockTime
func NewGovernanceChainCommitteeProtocol(
candidatesIndexer *CandidateIndexer,
electionCommittee committee.Committee,
initGravityChainHeight uint64,
getBlockTime GetBlockTime,
_ GetBlockTime,
initialCandidatesInterval time.Duration,
sh *Slasher,
) (Protocol, error) {
if electionCommittee == nil {
return nil, ErrNoElectionCommittee
}
if getBlockTime == nil {
return nil, errors.New("getBlockTime api is not provided")
}

h := hash.Hash160b([]byte(_protocolID))
addr, err := address.FromBytes(h[:])
Expand All @@ -59,7 +56,6 @@ func NewGovernanceChainCommitteeProtocol(
return &governanceChainCommitteeProtocol{
electionCommittee: electionCommittee,
initGravityChainHeight: initGravityChainHeight,
getBlockTime: getBlockTime,
addr: addr,
initialCandidatesInterval: initialCandidatesInterval,
sh: sh,
Expand Down Expand Up @@ -234,7 +230,8 @@ func (p *governanceChainCommitteeProtocol) getGravityHeight(ctx context.Context,
rp := rolldpos.MustGetProtocol(protocol.MustGetRegistry(ctx))
epochNumber := rp.GetEpochNum(height)
epochHeight := rp.GetEpochHeight(epochNumber)
blkTime, err := p.getBlockTime(epochHeight)
bcCtx := protocol.MustGetBlockchainCtx(ctx)
blkTime, err := bcCtx.GetBlockTime(epochHeight)
if err != nil {
return 0, err
}
Expand Down
6 changes: 6 additions & 0 deletions action/protocol/poll/governance_protocol_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -65,6 +65,12 @@ func initConstruct(ctrl *gomock.Controller) (Protocol, context.Context, protocol
Tip: protocol.TipInfo{
Height: epochStartHeight - 1,
},
GetBlockHash: func(u uint64) (hash.Hash256, error) {
return hash.Hash256b([]byte{0}), nil
},
GetBlockTime: func(h uint64) (time.Time, error) {
return time.Unix(1562382522, 0), nil
},
},
),
cfg.Genesis,
Expand Down
10 changes: 5 additions & 5 deletions action/protocol/poll/protocol.go
Original file line number Diff line number Diff line change
Expand Up @@ -133,10 +133,10 @@ func NewProtocol(
getUnproductiveDelegate GetUnproductiveDelegate,
electionCommittee committee.Committee,
stakingProto *staking.Protocol,
getBlockTimeFunc GetBlockTime,
_ GetBlockTime,
productivity Productivity,
getBlockHash evm.GetBlockHash,
getBlockTime evm.GetBlockTime,
_ evm.GetBlockHash,
_ evm.GetBlockTime,
) (Protocol, error) {
if scheme != _rollDPoSScheme {
return nil, nil
Expand Down Expand Up @@ -184,7 +184,7 @@ func NewProtocol(
candidateIndexer,
electionCommittee,
genesisConfig.GravityChainStartHeight,
getBlockTimeFunc,
nil,
chainConfig.PollInitialCandidatesInterval,
slasher,
)
Expand Down Expand Up @@ -220,7 +220,7 @@ func NewProtocol(
}
return NewStakingCommand(stakingV1, stakingV2)
case _modeConsortium:
return NewConsortiumCommittee(candidateIndexer, readContract, getBlockHash)
return NewConsortiumCommittee(candidateIndexer, readContract, nil)
default:
return nil, errors.Errorf("unsupported poll mode %s", genesisConfig.PollMode)
}
Expand Down
24 changes: 24 additions & 0 deletions action/protocol/poll/staking_committee_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -180,6 +180,14 @@ func TestCreatePostSystemActions_StakingCommittee(t *testing.T) {
psac, ok := p.(protocol.PostSystemActionsCreator)
require.True(ok)
ctx = protocol.WithFeatureWithHeightCtx(ctx)
ctx = protocol.WithBlockchainCtx(ctx, protocol.BlockchainCtx{
GetBlockHash: func(uint64) (hash.Hash256, error) {
return hash.ZeroHash256, nil
},
GetBlockTime: func(uint64) (time.Time, error) {
return time.Now(), nil
},
})
elp, err := psac.CreatePostSystemActions(ctx, sr)
require.NoError(err)
require.Equal(1, len(elp))
Expand Down Expand Up @@ -331,6 +339,14 @@ func TestHandle_StakingCommittee(t *testing.T) {
},
)
ctx4 = protocol.WithFeatureWithHeightCtx(ctx4)
ctx4 = protocol.WithBlockchainCtx(ctx4, protocol.BlockchainCtx{
GetBlockHash: func(uint64) (hash.Hash256, error) {
return hash.ZeroHash256, nil
},
GetBlockTime: func(uint64) (time.Time, error) {
return time.Now(), nil
},
})
err = p4.Validate(ctx4, elp4, sm4)
require.Contains(err.Error(), "the proposed delegate list length")
})
Expand Down Expand Up @@ -361,6 +377,14 @@ func TestHandle_StakingCommittee(t *testing.T) {
Caller: caller,
},
)
ctx5 = protocol.WithBlockchainCtx(ctx5, protocol.BlockchainCtx{
GetBlockHash: func(uint64) (hash.Hash256, error) {
return hash.ZeroHash256, nil
},
GetBlockTime: func(uint64) (time.Time, error) {
return time.Now(), nil
},
})
err = p5.Validate(ctx5, elp5, sm5)
require.Contains(err.Error(), "delegates are not as expected")
})
Expand Down
16 changes: 11 additions & 5 deletions api/coreservice.go
Original file line number Diff line number Diff line change
Expand Up @@ -211,7 +211,6 @@ type (
readCache *ReadCache
actionRadio *ActionRadio
apiStats *nodestats.APILocalStats
getBlockTime evm.GetBlockTime
}

// jobDesc provides a struct to get and store logs in core.LogsInRange
Expand Down Expand Up @@ -275,7 +274,6 @@ func newCoreService(
bfIndexer blockindex.BloomFilterIndexer,
actPool actpool.ActPool,
registry *protocol.Registry,
getBlockTime evm.GetBlockTime,
opts ...Option,
) (CoreService, error) {
if cfg == (Config{}) {
Expand All @@ -300,7 +298,6 @@ func newCoreService(
chainListener: NewChainListener(cfg.ListenerLimit),
gs: gasstation.NewGasStation(chain, dao, cfg.GasStation),
readCache: NewReadCache(),
getBlockTime: getBlockTime,
}

for _, opt := range opts {
Expand Down Expand Up @@ -953,6 +950,10 @@ func (core *coreService) readState(ctx context.Context, p protocol.Protocol, hei
}

// TODO: need to complete the context
ctx, err := core.bc.Context(ctx)
if err != nil {
return nil, 0, err
}
ctx = protocol.WithBlockCtx(ctx, protocol.BlockCtx{
BlockHeight: tipHeight,
})
Expand Down Expand Up @@ -2008,15 +2009,20 @@ func (core *coreService) simulateExecution(
ctx = protocol.WithFeatureCtx(protocol.WithBlockCtx(ctx, protocol.BlockCtx{
BlockHeight: height,
}))
ctx, err = core.bc.Context(ctx)
if err != nil {
return nil, nil, status.Error(codes.Internal, err.Error())
}
bcCtx := protocol.MustGetBlockchainCtx(ctx)
if protocol.MustGetFeatureCtx(ctx).UseZeroNonceForFreshAccount {
pendingNonce = state.PendingNonceConsideringFreshAccount()
} else {
pendingNonce = state.PendingNonce()
}
elp.SetNonce(pendingNonce)
ctx = evm.WithHelperCtx(ctx, evm.HelperContext{
GetBlockHash: core.dao.GetBlockHash,
GetBlockTime: core.getBlockTime,
GetBlockHash: bcCtx.GetBlockHash,
GetBlockTime: bcCtx.GetBlockTime,
DepositGasFunc: rewarding.DepositGas,
})
return evm.SimulateExecution(ctx, ws, addr, elp, opts...)
Expand Down
2 changes: 1 addition & 1 deletion api/coreservice_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -200,7 +200,7 @@ func setupTestCoreService() (CoreService, blockchain.Blockchain, blockdao.BlockD
opts := []Option{WithBroadcastOutbound(func(ctx context.Context, chainID uint32, msg proto.Message) error {
return nil
})}
svr, err := newCoreService(cfg.api, bc, nil, sf, dao, indexer, bfIndexer, ap, registry, func(u uint64) (time.Time, error) { return time.Time{}, nil }, opts...)
svr, err := newCoreService(cfg.api, bc, nil, sf, dao, indexer, bfIndexer, ap, registry, opts...)
if err != nil {
panic(err)
}
Expand Down
10 changes: 7 additions & 3 deletions api/grpcserver_integrity_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -2064,7 +2064,11 @@ func TestGrpcServer_GetEpochMetaIntegrity(t *testing.T) {
} else if test.pollProtocolType == "governanceChainCommittee" {
committee := mock_committee.NewMockCommittee(ctrl)
mbc := mock_blockchain.NewMockBlockchain(ctrl)
mbc.EXPECT().Genesis().Return(cfg.genesis).Times(3)
mbc.EXPECT().Genesis().Return(cfg.genesis).AnyTimes()
mbc.EXPECT().Context(gomock.Any()).Return(protocol.WithBlockchainCtx(context.Background(), protocol.BlockchainCtx{
GetBlockHash: func(uint64) (hash.Hash256, error) { return hash.ZeroHash256, nil },
GetBlockTime: func(uint64) (time.Time, error) { return time.Now(), nil },
}), nil).AnyTimes()
indexer, err := poll.NewCandidateIndexer(db.NewMemKVStore())
require.NoError(err)
slasher, _ := poll.NewSlasher(
Expand Down Expand Up @@ -2123,9 +2127,9 @@ func TestGrpcServer_GetEpochMetaIntegrity(t *testing.T) {
cfg.chain.PollInitialCandidatesInterval,
slasher)
require.NoError(pol.ForceRegister(registry))
committee.EXPECT().HeightByTime(gomock.Any()).Return(test.epochData.GravityChainStartHeight, nil)
committee.EXPECT().HeightByTime(gomock.Any()).Return(test.epochData.GravityChainStartHeight, nil).AnyTimes()

mbc.EXPECT().TipHeight().Return(uint64(4)).Times(4)
mbc.EXPECT().TipHeight().Return(uint64(4)).AnyTimes()
mbc.EXPECT().BlockHeaderByHeight(gomock.Any()).DoAndReturn(func(height uint64) (*block.Header, error) {
if height > 0 && height <= 4 {
pk := identityset.PrivateKey(int(height))
Expand Down
4 changes: 2 additions & 2 deletions api/serverV2.go
Original file line number Diff line number Diff line change
Expand Up @@ -45,10 +45,10 @@ func NewServerV2(
bfIndexer blockindex.BloomFilterIndexer,
actPool actpool.ActPool,
registry *protocol.Registry,
getBlockTime evm.GetBlockTime,
_ evm.GetBlockTime, // TODO: remove unused getBlockTime
opts ...Option,
) (*ServerV2, error) {
coreAPI, err := newCoreService(cfg, chain, bs, sf, dao, indexer, bfIndexer, actPool, registry, getBlockTime, opts...)
coreAPI, err := newCoreService(cfg, chain, bs, sf, dao, indexer, bfIndexer, actPool, registry, opts...)
if err != nil {
return nil, err
}
Expand Down
2 changes: 1 addition & 1 deletion api/serverV2_integrity_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -455,7 +455,7 @@ func createServerV2(cfg testConfig, needActPool bool) (*ServerV2, blockchain.Blo
opts := []Option{WithBroadcastOutbound(func(ctx context.Context, chainID uint32, msg proto.Message) error {
return nil
})}
svr, err := NewServerV2(cfg.api, bc, nil, sf, dao, indexer, bfIndexer, ap, registry, func(u uint64) (time.Time, error) { return time.Time{}, nil }, opts...)
svr, err := NewServerV2(cfg.api, bc, nil, sf, dao, indexer, bfIndexer, ap, registry, nil, opts...)
if err != nil {
return nil, nil, nil, nil, nil, nil, "", err
}
Expand Down
17 changes: 15 additions & 2 deletions blockchain/blockchain.go
Original file line number Diff line number Diff line change
Expand Up @@ -242,14 +242,15 @@ func (bc *blockchain) ChainAddress() string {
func (bc *blockchain) Start(ctx context.Context) error {
bc.mu.Lock()
defer bc.mu.Unlock()

// pass registry to be used by state factory's initialization
ctx = protocol.WithFeatureWithHeightCtx(genesis.WithGenesisContext(
protocol.WithBlockchainCtx(
ctx,
protocol.BlockchainCtx{
ChainID: bc.ChainID(),
EvmNetworkID: bc.EvmNetworkID(),
GetBlockHash: bc.dao.GetBlockHash,
GetBlockTime: bc.getBlockTime,
},
), bc.genesis))
return bc.lifecycle.OnStart(ctx)
Expand Down Expand Up @@ -406,14 +407,15 @@ func (bc *blockchain) context(ctx context.Context, height uint64) (context.Conte
if err != nil {
return nil, err
}

ctx = genesis.WithGenesisContext(
protocol.WithBlockchainCtx(
ctx,
protocol.BlockchainCtx{
Tip: *tip,
ChainID: bc.ChainID(),
EvmNetworkID: bc.EvmNetworkID(),
GetBlockHash: bc.dao.GetBlockHash,
GetBlockTime: bc.getBlockTime,
},
),
bc.genesis,
Expand Down Expand Up @@ -575,3 +577,14 @@ func (bc *blockchain) emitToSubscribers(blk *block.Block) {
}
bc.pubSubManager.SendBlockToSubscribers(blk)
}

func (bc *blockchain) getBlockTime(height uint64) (time.Time, error) {
if height == 0 {
return time.Unix(bc.genesis.Timestamp, 0), nil
}
header, err := bc.dao.HeaderByHeight(height)
if err != nil {
return time.Time{}, err
}
return header.Timestamp(), nil
}
Loading