Skip to content
Closed
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
26 changes: 26 additions & 0 deletions action/protocol/context.go
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,8 @@ type (

vmConfigContextKey struct{}

consensusRoundContextKey struct{}

// TipInfo contains the tip block information
TipInfo struct {
Height uint64
Expand All @@ -54,6 +56,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 Expand Up @@ -162,6 +168,14 @@ type (
LoadCandidatesLegacy CheckFunc
CandCenterHasAlias CheckFunc
}

ConsensusRoundCtx struct {
Height uint64
Round uint32
StartTime time.Time
EncodedProposer string
PrevHash hash.Hash256
}
)

// WithRegistry adds registry to context
Expand Down Expand Up @@ -395,3 +409,15 @@ func GetVMConfigCtx(ctx context.Context) (vm.Config, bool) {
cfg, ok := ctx.Value(vmConfigContextKey{}).(vm.Config)
return cfg, ok
}

func WithConsensusRoundCtx(ctx context.Context, round ConsensusRoundCtx) context.Context {
return context.WithValue(ctx, consensusRoundContextKey{}, round)
}

func MustGetConsensusRoundCtx(ctx context.Context) ConsensusRoundCtx {
Comment on lines +413 to +417
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

if necessary, move to package rolldpos

round, ok := ctx.Value(consensusRoundContextKey{}).(ConsensusRoundCtx)
if !ok {
log.S().Panic("Miss consensus round context")
}
return round
}
2 changes: 2 additions & 0 deletions action/protocol/execution/evm/evm.go
Original file line number Diff line number Diff line change
Expand Up @@ -191,6 +191,8 @@ func newParams(
if err != nil {
return nil, err
}
isCancun := chainConfig.IsCancun(big.NewInt(int64(blkCtx.BlockHeight)), uint64(blkCtx.BlockTimeStamp.Unix()))
log.L().Info("check cancun", zap.Bool("isCancun", isCancun), zap.Uint64("height", blkCtx.BlockHeight), zap.Uint64("timestamp", uint64(blkCtx.BlockTimeStamp.Unix())), zap.Uint64("cancuntime", *chainConfig.CancunTime))
vmTxCtx := vm.TxContext{
Origin: executorAddr,
GasPrice: execution.GasPrice(),
Expand Down
14 changes: 7 additions & 7 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
// TODO: remove unused getBlockHash and getBlockTime
func NewProtocol(getBlockHash evm.GetBlockHash, depositGas protocol.DepositGas, getBlockTime 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: 5 additions & 2 deletions action/protocol/execution/protocol_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -474,15 +474,17 @@ func (sct *SmartContractTest) prepareBlockchain(
r.NoError(err)
dao := blockdao.NewBlockDAOWithIndexersAndCache(store, []blockdao.BlockIndexer{sf, indexer}, cfg.DB.MaxCacheSize)
r.NotNil(dao)
btcd := testutil.DummyBlockTimeBuilder()
bc := blockchain.NewBlockchain(
cfg.Chain,
cfg.Genesis,
dao,
factory.NewMinter(sf, ap),
factory.NewMinter(sf, ap, factory.WithPrivateKeyOption(cfg.Chain.ProducerPrivateKey())),
blockchain.BlockValidatorOption(block.NewValidator(
sf,
protocol.NewGenericValidator(sf, accountutil.AccountState),
)),
blockchain.BlockTimeCalculatorBuilderOption(btcd),
)
reward := rewarding.NewProtocol(cfg.Genesis.Rewarding)
r.NoError(reward.Register(registry))
Expand Down Expand Up @@ -730,11 +732,12 @@ func TestProtocol_Handle(t *testing.T) {
cfg.Chain,
cfg.Genesis,
dao,
factory.NewMinter(sf, ap),
factory.NewMinter(sf, ap, factory.WithPrivateKeyOption(cfg.Chain.ProducerPrivateKey())),
blockchain.BlockValidatorOption(block.NewValidator(
sf,
protocol.NewGenericValidator(sf, accountutil.AccountState),
)),
blockchain.BlockTimeCalculatorBuilderOption(testutil.DummyBlockTimeBuilder()),
)
exeProtocol := execution.NewProtocol(dao.GetBlockHash, rewarding.DepositGas, getBlockTimeForTest)
require.NoError(exeProtocol.Register(registry))
Expand Down
16 changes: 5 additions & 11 deletions action/protocol/poll/consortium.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@ import (
"context"
"math/big"
"strings"
"time"

"github.com/ethereum/go-ethereum/accounts/abi"
"github.com/ethereum/go-ethereum/common"
Expand Down Expand Up @@ -50,11 +49,10 @@ 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) {
func NewConsortiumCommittee(indexer *CandidateIndexer, readContract ReadContract) (Protocol, error) {
abi, err := abi.JSON(strings.NewReader(ConsortiumManagementABI))
if err != nil {
return nil, err
Expand All @@ -73,7 +71,6 @@ func NewConsortiumCommittee(indexer *CandidateIndexer, readContract ReadContract
abi: abi,
addr: addr,
indexer: indexer,
getBlockHash: getBlockHash,
}, nil
}

Expand Down Expand Up @@ -116,17 +113,14 @@ func (cc *consortiumCommittee) CreateGenesisStates(ctx context.Context, sm proto
if err != nil {
return err
}
bcCtx := protocol.MustGetBlockchainCtx(ctx)
ctx = protocol.WithActionCtx(ctx, actionCtx)
ctx = protocol.WithBlockCtx(ctx, blkCtx)
getBlockTime := func(u uint64) (time.Time, error) {
// make sure the returned timestamp is after the current block time so that evm upgrades based on timestamp (Shanghai and onwards) are disabled
return blkCtx.BlockTimeStamp.Add(5 * time.Second), nil
}
ctx = evm.WithHelperCtx(ctx, evm.HelperContext{
GetBlockHash: func(height uint64) (hash.Hash256, error) {
return hash.ZeroHash256, nil
},
GetBlockTime: getBlockTime,
GetBlockTime: bcCtx.GetBlockTime,
DepositGasFunc: func(context.Context, protocol.StateManager, *big.Int, ...protocol.DepositOption) ([]*action.TransactionLog, error) {
return nil, nil
},
Expand All @@ -143,8 +137,8 @@ func (cc *consortiumCommittee) CreateGenesisStates(ctx context.Context, sm proto
cc.contract = receipt.ContractAddress

ctx = evm.WithHelperCtx(ctx, evm.HelperContext{
GetBlockHash: cc.getBlockHash,
GetBlockTime: getBlockTime,
GetBlockHash: bcCtx.GetBlockHash,
GetBlockTime: bcCtx.GetBlockTime,
})
r := getContractReaderForGenesisStates(ctx, sm)
cands, err := cc.readDelegatesWithContractReader(ctx, r)
Expand Down
9 changes: 3 additions & 6 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,6 +34,7 @@ type governanceChainCommitteeProtocol struct {
}

// NewGovernanceChainCommitteeProtocol creates a Poll Protocol which fetch result from governance chain
// TODO: remove getBlockTime
func NewGovernanceChainCommitteeProtocol(
candidatesIndexer *CandidateIndexer,
electionCommittee committee.Committee,
Expand All @@ -46,9 +46,6 @@ func NewGovernanceChainCommitteeProtocol(
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)
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
Loading
Loading