Skip to content

Commit

Permalink
refactor(config): consolidate scroll flags (#262)
Browse files Browse the repository at this point in the history
  • Loading branch information
HAOYUatHZ committed Apr 17, 2023
1 parent 909fe1d commit df1d37e
Show file tree
Hide file tree
Showing 19 changed files with 108 additions and 68 deletions.
2 changes: 1 addition & 1 deletion cmd/evm/internal/t8ntool/transition.go
Original file line number Diff line number Diff line change
Expand Up @@ -248,7 +248,7 @@ func Transition(ctx *cli.Context) error {
}
// Sanity check, to not `panic` in state_transition
if chainConfig.IsLondon(big.NewInt(int64(prestate.Env.Number))) {
if prestate.Env.BaseFee == nil && chainConfig.EnableEIP2718 && chainConfig.EnableEIP1559 {
if prestate.Env.BaseFee == nil && chainConfig.Scroll.BaseFeeEnabled() {
return NewError(ErrorConfig, errors.New("EIP-1559 config but missing 'currentBaseFee' in env section"))
}
}
Expand Down
8 changes: 4 additions & 4 deletions consensus/misc/eip1559.go
Original file line number Diff line number Diff line change
Expand Up @@ -39,10 +39,10 @@ func VerifyEip1559Header(config *params.ChainConfig, parent, header *types.Heade
return err
}
// Verify the header is not malformed
if header.BaseFee == nil && (config.EnableEIP2718 && config.EnableEIP1559) {
if header.BaseFee == nil && config.Scroll.BaseFeeEnabled() {
return fmt.Errorf("header is missing baseFee")
}
// Now BaseFee can be nil, because !(config.EnableEIP2718 && config.EnableEIP1559)
// Now BaseFee can be nil, because !config.Scroll.BaseFeeEnabled()
if header.BaseFee == nil {
return nil
}
Expand All @@ -51,7 +51,7 @@ func VerifyEip1559Header(config *params.ChainConfig, parent, header *types.Heade
var expectedBaseFee *big.Int

// compatible check with the logic in commitNewWork
if config.Clique == nil || (config.EnableEIP2718 && config.EnableEIP1559) {
if config.Clique == nil || config.Scroll.BaseFeeEnabled() {
expectedBaseFee = CalcBaseFee(config, parent)
} else {
expectedBaseFee = big.NewInt(0)
Expand All @@ -76,7 +76,7 @@ func CalcBaseFee(config *params.ChainConfig, parent *types.Header) *big.Int {
parentGasTargetBig = new(big.Int).SetUint64(parentGasTarget)
baseFeeChangeDenominator = new(big.Int).SetUint64(params.BaseFeeChangeDenominator)
)
if !config.EnableEIP2718 || !config.EnableEIP1559 {
if !config.Scroll.BaseFeeEnabled() {
return nil
}
// If the parent gasUsed is the same as the target, the baseFee remains unchanged.
Expand Down
2 changes: 1 addition & 1 deletion core/block_validator.go
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,7 @@ func (v *BlockValidator) ValidateBody(block *types.Block) error {
if v.bc.HasBlockAndState(block.Hash(), block.NumberU64()) {
return ErrKnownBlock
}
if !v.config.IsValidTxCount(len(block.Transactions())) {
if !v.config.Scroll.IsValidTxCount(len(block.Transactions())) {
return consensus.ErrInvalidTxCount
}
// Header validity is known at this point, check the uncles and transactions
Expand Down
8 changes: 4 additions & 4 deletions core/blockchain.go
Original file line number Diff line number Diff line change
Expand Up @@ -231,13 +231,13 @@ func NewBlockChain(db ethdb.Database, cacheConfig *CacheConfig, chainConfig *par
txLookupCache, _ := lru.New(txLookupCacheLimit)
futureBlocks, _ := lru.New(maxFutureBlocks)
// override snapshot setting
if chainConfig.Zktrie && cacheConfig.SnapshotLimit > 0 {
if chainConfig.Scroll.ZktrieEnabled() && cacheConfig.SnapshotLimit > 0 {
log.Warn("Snapshot has been disabled by zktrie")
cacheConfig.SnapshotLimit = 0
}

if chainConfig.FeeVaultAddress != nil {
log.Warn("Using fee vault address", "FeeVaultAddress", *chainConfig.FeeVaultAddress)
if chainConfig.Scroll.L1FeeEnabled() {
log.Warn("Using fee vault address", "FeeVaultAddress", *chainConfig.Scroll.FeeVaultAddress)
}

bc := &BlockChain{
Expand All @@ -249,7 +249,7 @@ func NewBlockChain(db ethdb.Database, cacheConfig *CacheConfig, chainConfig *par
Cache: cacheConfig.TrieCleanLimit,
Journal: cacheConfig.TrieCleanJournal,
Preimages: cacheConfig.Preimages,
Zktrie: chainConfig.Zktrie,
Zktrie: chainConfig.Scroll.ZktrieEnabled(),
}),
quit: make(chan struct{}),
chainmu: syncx.NewClosableMutex(),
Expand Down
6 changes: 3 additions & 3 deletions core/blockchain_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -3170,7 +3170,7 @@ func TestFeeVault(t *testing.T) {
}

// Ensure that the fee vault received all tx fees
actual = state.GetBalance(*params.TestChainConfig.FeeVaultAddress)
actual = state.GetBalance(*params.TestChainConfig.Scroll.FeeVaultAddress)
expected = new(big.Int).SetUint64(block.GasUsed() * block.Transactions()[0].GasTipCap().Uint64())

if actual.Cmp(expected) != 0 {
Expand All @@ -3182,8 +3182,8 @@ func TestFeeVault(t *testing.T) {
func TestTransactionCountLimit(t *testing.T) {
// Create config that allows at most 1 transaction per block
config := params.TestChainConfig
config.MaxTxPerBlock = new(int)
*config.MaxTxPerBlock = 1
config.Scroll.MaxTxPerBlock = new(int)
*config.Scroll.MaxTxPerBlock = 1

var (
engine = ethash.NewFaker()
Expand Down
8 changes: 4 additions & 4 deletions core/genesis.go
Original file line number Diff line number Diff line change
Expand Up @@ -188,10 +188,10 @@ func SetupGenesisBlockWithOverride(db ethdb.Database, genesis *Genesis, override
if storedcfg == nil {
log.Warn("Found genesis block without chain config")
} else {
trieCfg = &trie.Config{Zktrie: storedcfg.Zktrie}
trieCfg = &trie.Config{Zktrie: storedcfg.Scroll.ZktrieEnabled()}
}
} else {
trieCfg = &trie.Config{Zktrie: genesis.Config.Zktrie}
trieCfg = &trie.Config{Zktrie: genesis.Config.Scroll.ZktrieEnabled()}
}

if _, err := state.New(header.Root, state.NewDatabaseWithConfig(db, trieCfg), nil); err != nil {
Expand Down Expand Up @@ -277,7 +277,7 @@ func (g *Genesis) ToBlock(db ethdb.Database) *types.Block {
}
var trieCfg *trie.Config
if g.Config != nil {
trieCfg = &trie.Config{Zktrie: g.Config.Zktrie}
trieCfg = &trie.Config{Zktrie: g.Config.Scroll.ZktrieEnabled()}
}
statedb, err := state.New(common.Hash{}, state.NewDatabaseWithConfig(db, trieCfg), nil)
if err != nil {
Expand Down Expand Up @@ -315,7 +315,7 @@ func (g *Genesis) ToBlock(db ethdb.Database) *types.Block {
if g.Config != nil && g.Config.IsLondon(common.Big0) {
if g.BaseFee != nil {
head.BaseFee = g.BaseFee
} else if g.Config.EnableEIP2718 && g.Config.EnableEIP1559 {
} else if g.Config.Scroll.BaseFeeEnabled() {
head.BaseFee = new(big.Int).SetUint64(params.InitialBaseFee)
} else {
head.BaseFee = nil
Expand Down
8 changes: 4 additions & 4 deletions core/state_transition.go
Original file line number Diff line number Diff line change
Expand Up @@ -166,7 +166,7 @@ func IntrinsicGas(data []byte, accessList types.AccessList, isContractCreation b
// NewStateTransition initialises and returns a new state transition object.
func NewStateTransition(evm *vm.EVM, msg Message, gp *GasPool) *StateTransition {
l1Fee := new(big.Int)
if evm.ChainConfig().UsingScroll {
if evm.ChainConfig().Scroll.L1FeeEnabled() {
l1Fee, _ = fees.CalculateL1MsgFee(msg, evm.StateDB)
}

Expand Down Expand Up @@ -207,7 +207,7 @@ func (st *StateTransition) buyGas() error {
mgval := new(big.Int).SetUint64(st.msg.Gas())
mgval = mgval.Mul(mgval, st.gasPrice)

if st.evm.ChainConfig().UsingScroll {
if st.evm.ChainConfig().Scroll.L1FeeEnabled() {
// always add l1fee, because all tx are L2-to-L1 ATM
log.Debug("Adding L1 fee", "l1_fee", st.l1Fee)
mgval = mgval.Add(mgval, st.l1Fee)
Expand All @@ -218,7 +218,7 @@ func (st *StateTransition) buyGas() error {
balanceCheck = new(big.Int).SetUint64(st.msg.Gas())
balanceCheck = balanceCheck.Mul(balanceCheck, st.gasFeeCap)
balanceCheck.Add(balanceCheck, st.value)
if st.evm.ChainConfig().UsingScroll {
if st.evm.ChainConfig().Scroll.L1FeeEnabled() {
// always add l1fee, because all tx are L2-to-L1 ATM
balanceCheck.Add(balanceCheck, st.l1Fee)
}
Expand Down Expand Up @@ -370,7 +370,7 @@ func (st *StateTransition) TransitionDb() (*ExecutionResult, error) {
}
}

if st.evm.ChainConfig().UsingScroll {
if st.evm.ChainConfig().Scroll.L1FeeEnabled() {
// The L2 Fee is the same as the fee that is charged in the normal geth
// codepath. Add the L1 fee to the L2 fee for the total fee that is sent
// to the sequencer.
Expand Down
7 changes: 4 additions & 3 deletions core/tx_pool.go
Original file line number Diff line number Diff line change
Expand Up @@ -682,7 +682,7 @@ func (pool *TxPool) add(tx *types.Transaction, local bool) (replaced bool, err e
// the sender is marked as local previously, treat it as the local transaction.
isLocal := local || pool.locals.containsTx(tx)

if pool.chainconfig.UsingScroll {
if pool.chainconfig.Scroll.L1FeeEnabled() {
if err := fees.VerifyFee(pool.signer, tx, pool.currentState); err != nil {
log.Trace("Discarding insufficient l1fee transaction", "hash", hash, "err", err)
invalidTxMeter.Mark(1)
Expand Down Expand Up @@ -1329,8 +1329,9 @@ func (pool *TxPool) reset(oldHead, newHead *types.Header) {
// Update all fork indicator by next pending block number.
next := new(big.Int).Add(newHead.Number, big.NewInt(1))
pool.istanbul = pool.chainconfig.IsIstanbul(next)
pool.eip2718 = pool.chainconfig.EnableEIP2718 && pool.chainconfig.IsBerlin(next)
pool.eip1559 = pool.chainconfig.EnableEIP1559 && pool.chainconfig.IsLondon(next)

pool.eip2718 = pool.chainconfig.Scroll.EnableEIP2718 && pool.chainconfig.IsBerlin(next)
pool.eip1559 = pool.chainconfig.Scroll.EnableEIP1559 && pool.chainconfig.IsLondon(next)
}

// promoteExecutables moves transactions that have become processable from the
Expand Down
4 changes: 2 additions & 2 deletions core/vm/evm.go
Original file line number Diff line number Diff line change
Expand Up @@ -535,8 +535,8 @@ func (evm *EVM) ChainConfig() *params.ChainConfig { return evm.chainConfig }

// FeeRecipient returns the environment's transaction fee recipient address.
func (evm *EVM) FeeRecipient() common.Address {
if evm.ChainConfig().FeeVaultAddress != nil {
return *evm.chainConfig.FeeVaultAddress
if evm.ChainConfig().Scroll.L1FeeEnabled() {
return *evm.chainConfig.Scroll.FeeVaultAddress
} else {
return evm.Context.Coinbase
}
Expand Down
2 changes: 1 addition & 1 deletion eth/backend.go
Original file line number Diff line number Diff line change
Expand Up @@ -516,7 +516,7 @@ func (s *Ethereum) BloomIndexer() *core.ChainIndexer { return s.bloomIndexer }
// network protocols to start.
func (s *Ethereum) Protocols() []p2p.Protocol {
protos := eth.MakeProtocols((*ethHandler)(s.handler), s.networkID, s.ethDialCandidates)
if !s.blockchain.Config().Zktrie && s.config.SnapshotCache > 0 {
if !s.blockchain.Config().Scroll.ZktrieEnabled() && s.config.SnapshotCache > 0 {
protos = append(protos, snap.MakeProtocols((*snapHandler)(s.handler), s.snapDialCandidates)...)
}
return protos
Expand Down
2 changes: 1 addition & 1 deletion eth/tracers/api.go
Original file line number Diff line number Diff line change
Expand Up @@ -900,7 +900,7 @@ func (api *API) traceTx(ctx context.Context, message core.Message, txctx *Contex
vmenv := vm.NewEVM(vmctx, txContext, statedb, api.backend.ChainConfig(), vm.Config{Debug: true, Tracer: tracer, NoBaseFee: true})

// If gasPrice is 0, make sure that the account has sufficient balance to cover `l1Fee`.
if api.backend.ChainConfig().UsingScroll && message.GasPrice().Cmp(big.NewInt(0)) == 0 {
if api.backend.ChainConfig().Scroll.L1FeeEnabled() && message.GasPrice().Cmp(big.NewInt(0)) == 0 {
l1Fee, err := fees.CalculateL1MsgFee(message, vmenv.StateDB)
if err != nil {
return nil, err
Expand Down
10 changes: 4 additions & 6 deletions eth/tracers/api_blocktrace.go
Original file line number Diff line number Diff line change
Expand Up @@ -98,8 +98,8 @@ func (api *API) createTraceEnv(ctx context.Context, config *TraceConfig, block *

// get coinbase
var coinbase common.Address
if api.backend.ChainConfig().FeeVaultAddress != nil {
coinbase = *api.backend.ChainConfig().FeeVaultAddress
if api.backend.ChainConfig().Scroll.L1FeeEnabled() {
coinbase = *api.backend.ChainConfig().Scroll.FeeVaultAddress
} else {
coinbase, err = api.backend.Engine().Author(block.Header())
if err != nil {
Expand Down Expand Up @@ -391,15 +391,13 @@ func (api *API) fillBlockTrace(env *traceEnv, block *types.Block) (*types.BlockT
}

// only zktrie model has the ability to get `mptwitness`.
if api.backend.ChainConfig().Zktrie {
if api.backend.ChainConfig().Scroll.ZktrieEnabled() {
if err := zkproof.FillBlockTraceForMPTWitness(zkproof.MPTWitnessType(api.backend.CacheConfig().MPTWitness), blockTrace); err != nil {
log.Error("fill mpt witness fail", "error", err)
}
}

if api.backend.ChainConfig().UsingScroll {
blockTrace.WithdrawTrieRoot = withdrawtrie.ReadWTRSlot(rcfg.L2MessageQueueAddress, env.state)
}
blockTrace.WithdrawTrieRoot = withdrawtrie.ReadWTRSlot(rcfg.L2MessageQueueAddress, env.state)

return blockTrace, nil
}
4 changes: 2 additions & 2 deletions eth/tracers/api_blocktrace_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -181,8 +181,8 @@ func checkStructLogs(t *testing.T, expect []*txTraceResult, actual []*types.Exec

func checkCoinbase(t *testing.T, b *testBackend, wrapper *types.AccountWrapper) {
var coinbase common.Address
if b.chainConfig.FeeVaultAddress != nil {
coinbase = *b.chainConfig.FeeVaultAddress
if b.chainConfig.Scroll.L1FeeEnabled() {
coinbase = *b.chainConfig.Scroll.FeeVaultAddress
} else {
header, err := b.HeaderByNumber(context.Background(), 1)
assert.NoError(t, err)
Expand Down
8 changes: 4 additions & 4 deletions internal/ethapi/api.go
Original file line number Diff line number Diff line change
Expand Up @@ -661,7 +661,7 @@ func (s *PublicBlockChainAPI) GetProof(ctx context.Context, address common.Addre
return nil, err
}

zktrie := s.b.ChainConfig().Zktrie
zktrie := s.b.ChainConfig().Scroll.ZktrieEnabled()

storageTrie := state.StorageTrie(address)
var storageHash common.Hash
Expand Down Expand Up @@ -908,7 +908,7 @@ func newRPCBalance(balance *big.Int) **hexutil.Big {
}

func CalculateL1MsgFee(ctx context.Context, b Backend, args TransactionArgs, blockNrOrHash rpc.BlockNumberOrHash, overrides *StateOverride, timeout time.Duration, globalGasCap uint64, config *params.ChainConfig) (*big.Int, error) {
if !config.UsingScroll {
if !config.Scroll.L1FeeEnabled() {
return big.NewInt(0), nil
}

Expand Down Expand Up @@ -1249,7 +1249,7 @@ func RPCMarshalHeader(head *types.Header, enableBaseFee bool) map[string]interfa
// returned. When fullTx is true the returned block contains full transaction details, otherwise it will only contain
// transaction hashes.
func RPCMarshalBlock(block *types.Block, inclTx bool, fullTx bool, config *params.ChainConfig) (map[string]interface{}, error) {
fields := RPCMarshalHeader(block.Header(), config.EnableEIP2718 && config.EnableEIP1559)
fields := RPCMarshalHeader(block.Header(), config.Scroll.BaseFeeEnabled())
fields["size"] = hexutil.Uint64(block.Size())

if inclTx {
Expand Down Expand Up @@ -1284,7 +1284,7 @@ func RPCMarshalBlock(block *types.Block, inclTx bool, fullTx bool, config *param
// rpcMarshalHeader uses the generalized output filler, then adds the total difficulty field, which requires
// a `PublicBlockchainAPI`.
func (s *PublicBlockChainAPI) rpcMarshalHeader(ctx context.Context, header *types.Header) map[string]interface{} {
fields := RPCMarshalHeader(header, s.b.ChainConfig().EnableEIP2718 && s.b.ChainConfig().EnableEIP1559)
fields := RPCMarshalHeader(header, s.b.ChainConfig().Scroll.BaseFeeEnabled())
fields["totalDifficulty"] = (*hexutil.Big)(s.b.GetTd(ctx, header.Hash()))
return fields
}
Expand Down
2 changes: 1 addition & 1 deletion les/server.go
Original file line number Diff line number Diff line change
Expand Up @@ -83,7 +83,7 @@ func NewLesServer(node *node.Node, e ethBackend, config *ethconfig.Config) (*Les
return nil, err
}
// Now disable for zktrie
if e.BlockChain().Config().Zktrie {
if e.BlockChain().Config().Scroll.ZktrieEnabled() {
return nil, errors.New("light server not work with zktrie storage")
}

Expand Down
2 changes: 1 addition & 1 deletion light/txpool.go
Original file line number Diff line number Diff line change
Expand Up @@ -405,7 +405,7 @@ func (pool *TxPool) add(ctx context.Context, tx *types.Transaction) error {
return fmt.Errorf("Known transaction (%x)", hash[:4])
}

if pool.config.UsingScroll {
if pool.config.Scroll.L1FeeEnabled() {
if err := fees.VerifyFee(pool.signer, tx, pool.currentState(ctx)); err != nil {
return err
}
Expand Down
6 changes: 3 additions & 3 deletions miner/worker.go
Original file line number Diff line number Diff line change
Expand Up @@ -819,8 +819,8 @@ func (w *worker) commitTransactions(txs *types.TransactionsByPriceAndNonce, coin
return atomic.LoadInt32(interrupt) == commitInterruptNewHead
}
// If we have collected enough transactions then we're done
if !w.chainConfig.IsValidTxCount(w.current.tcount + 1) {
log.Trace("Transaction count limit reached", "have", w.current.tcount, "want", w.chainConfig.MaxTxPerBlock)
if !w.chainConfig.Scroll.IsValidTxCount(w.current.tcount + 1) {
log.Trace("Transaction count limit reached", "have", w.current.tcount, "want", w.chainConfig.Scroll.MaxTxPerBlock)
break
}
// If we don't have enough gas for any further transactions then we're done
Expand Down Expand Up @@ -929,7 +929,7 @@ func (w *worker) commitNewWork(interrupt *int32, noempty bool, timestamp int64)
}
// Set baseFee and GasLimit if we are on an EIP-1559 chain
if w.chainConfig.IsLondon(header.Number) {
if w.chainConfig.EnableEIP2718 && w.chainConfig.EnableEIP1559 {
if w.chainConfig.Scroll.BaseFeeEnabled() {
header.BaseFee = misc.CalcBaseFee(w.chainConfig, parent.Header())
} else {
// When disabling EIP-2718 or EIP-1559, we do not set baseFeePerGas in RPC response.
Expand Down

0 comments on commit df1d37e

Please sign in to comment.