Skip to content

Commit

Permalink
Fix issues for post-london hardforks
Browse files Browse the repository at this point in the history
  • Loading branch information
cffls committed Jul 23, 2024
1 parent 0c6a84a commit 8ffbaba
Show file tree
Hide file tree
Showing 16 changed files with 130 additions and 65 deletions.
5 changes: 2 additions & 3 deletions consensus/misc/eip1559.go
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,6 @@ import (

"github.com/ledgerwatch/erigon-lib/chain"
"github.com/ledgerwatch/erigon-lib/common"
libcommon "github.com/ledgerwatch/erigon-lib/common"
"github.com/ledgerwatch/erigon-lib/kv"
"github.com/ledgerwatch/erigon/polygon/bor/borcfg"

Expand Down Expand Up @@ -66,7 +65,7 @@ type eip1559Calculator struct{}
func (f eip1559Calculator) CurrentFees(chainConfig *chain.Config, db kv.Getter) (baseFee, blobFee, minBlobGasPrice, blockGasLimit uint64, err error) {
hash := rawdb.ReadHeadHeaderHash(db)

if hash == (libcommon.Hash{}) {
if hash == (common.Hash{}) {
return 0, 0, 0, 0, fmt.Errorf("can't get head header hash")
}

Expand All @@ -80,7 +79,7 @@ func (f eip1559Calculator) CurrentFees(chainConfig *chain.Config, db kv.Getter)

if chainConfig != nil {
if currentHeader.BaseFee != nil {
baseFee = CalcBaseFee(chainConfig, currentHeader).Uint64()
baseFee = CalcBaseFeeZk(chainConfig, currentHeader).Uint64()
}

if currentHeader.ExcessBlobGas != nil {
Expand Down
9 changes: 8 additions & 1 deletion consensus/misc/eip1559_zk.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,12 +5,19 @@ import (

"github.com/ledgerwatch/erigon-lib/chain"
"github.com/ledgerwatch/erigon/core/types"
"github.com/ledgerwatch/erigon/params"
)

func CalcBaseFeeZk(config *chain.Config, parent *types.Header) *big.Int {
if config.SupportGasless {
if config.SupportGasless || parent.Number.Cmp(big.NewInt(0)) == 0 {
// If the parent is the genesis block, the next block will include the initial batch transaction, which is a legacy transaction, so the basefee will be set to 0
return big.NewInt(0)
}

// If the parent block is injected block from L1 at block 1 (while block 0 is the genesis), it will have base fee of 0 so we will set the basefee of current block to the initial basefee
if parent.Number.Cmp(big.NewInt(1)) == 0 {
return new(big.Int).SetUint64(params.InitialBaseFee)
}

return CalcBaseFee(config, parent)
}
12 changes: 7 additions & 5 deletions core/genesis_write.go
Original file line number Diff line number Diff line change
Expand Up @@ -191,11 +191,13 @@ func WriteGenesisBlock(tx kv.RwTx, genesis *types.Genesis, overridePragueTime *b
}

// set unwanted forks block to max number, so they are not activated
maxInt := new(big.Int).SetUint64(math.MaxUint64)
newCfg.LondonBlock = maxInt
newCfg.ShanghaiTime = maxInt
newCfg.CancunTime = maxInt
newCfg.PragueTime = maxInt
if newCfg.NormalcyBlock != nil && newCfg.NormalcyBlock.Cmp(big.NewInt(0)) != 0 {
maxInt := new(big.Int).SetUint64(math.MaxUint64)
newCfg.LondonBlock = maxInt
newCfg.ShanghaiTime = maxInt
newCfg.CancunTime = maxInt
newCfg.PragueTime = maxInt
}

return newCfg, storedBlock, nil
}
Expand Down
2 changes: 1 addition & 1 deletion eth/ethconfig/config_zkevm.go
Original file line number Diff line number Diff line change
Expand Up @@ -72,7 +72,7 @@ type Zk struct {
var DefaultZkConfig = &Zk{}

func (c *Zk) ShouldCountersBeUnlimited(l1Recovery bool) bool {
return l1Recovery || (c.DisableVirtualCounters && !c.ExecutorStrictMode && len(c.ExecutorUrls) != 0)
return l1Recovery || (c.DisableVirtualCounters && !c.ExecutorStrictMode && !c.HasExecutors())
}

func (c *Zk) HasExecutors() bool {
Expand Down
9 changes: 9 additions & 0 deletions eth/stagedsync/stage_execute.go
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,7 @@ import (
"github.com/ledgerwatch/erigon/common/changeset"
"github.com/ledgerwatch/erigon/common/math"
"github.com/ledgerwatch/erigon/consensus"
"github.com/ledgerwatch/erigon/consensus/misc"
"github.com/ledgerwatch/erigon/core"
"github.com/ledgerwatch/erigon/core/rawdb"
"github.com/ledgerwatch/erigon/core/state"
Expand Down Expand Up @@ -513,6 +514,14 @@ Loop:
break
}

if cfg.chainConfig.IsLondon(blockNum) {
parentHeader, err := cfg.blockReader.Header(ctx, txc.Tx, header.ParentHash, blockNum-1)
if err != nil {
return err
}
header.BaseFee = misc.CalcBaseFeeZk(cfg.chainConfig, parentHeader)
}

lastLogTx += uint64(block.Transactions().Len())

// Incremental move of next stages depend on fully written ChangeSets, Receipts, CallTraceSet
Expand Down
9 changes: 9 additions & 0 deletions eth/stagedsync/stage_execute_zkevm.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ import (
"github.com/ledgerwatch/erigon-lib/kv/membatch"
"github.com/ledgerwatch/log/v3"

"github.com/ledgerwatch/erigon/consensus/misc"
"github.com/ledgerwatch/erigon/core"
"github.com/ledgerwatch/erigon/zk/erigon_db"
"github.com/ledgerwatch/erigon/zk/hermez_db"
Expand Down Expand Up @@ -303,6 +304,14 @@ func getPreexecuteValues(cfg ExecuteBlockCfg, ctx context.Context, tx kv.RwTx, b

block.HeaderNoCopy().ParentHash = prevBlockHash

if cfg.chainConfig.IsLondon(blockNum) {
parentHeader, err := cfg.blockReader.Header(ctx, tx, prevBlockHash, blockNum-1)
if err != nil {
return common.Hash{}, nil, nil, err
}
block.HeaderNoCopy().BaseFee = misc.CalcBaseFeeZk(cfg.chainConfig, parentHeader)
}

return preExecuteHeaderHash, block, senders, nil
}

Expand Down
2 changes: 1 addition & 1 deletion turbo/stages/stageloop.go
Original file line number Diff line number Diff line change
Expand Up @@ -308,7 +308,7 @@ func (h *Hook) sendNotifications(notifications *shards.Notifications, tx kv.Tx,
notifications.Accumulator.StartChange(0, currentHeader.Hash(), nil, false)
}

pendingBaseFee := misc.CalcBaseFee(h.chainConfig, currentHeader)
pendingBaseFee := misc.CalcBaseFeeZk(h.chainConfig, currentHeader)
pendingBlobFee := h.chainConfig.GetMinBlobGasPrice()
if currentHeader.ExcessBlobGas != nil {
excessBlobGas := misc.CalcExcessBlobGas(h.chainConfig, currentHeader)
Expand Down
3 changes: 2 additions & 1 deletion turbo/stages/zk_stages.go
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,7 @@ func NewDefaultZkStages(ctx context.Context,
return zkStages.DefaultZkStages(ctx,
zkStages.StageL1SyncerCfg(db, l1Syncer, cfg.Zk),
zkStages.StageL1InfoTreeCfg(db, cfg.Zk, l1InfoTreeSyncer),
zkStages.StageBatchesCfg(db, datastreamClient, cfg.Zk),
zkStages.StageBatchesCfg(db, datastreamClient, cfg.Zk, controlServer.ChainConfig, &cfg.Miner),
zkStages.StageDataStreamCatchupCfg(datastreamServer, db, cfg.Genesis.Config.ChainID.Uint64(), cfg.DatastreamVersion, cfg.HasExecutors()),
stagedsync.StageBlockHashesCfg(db, dirs.Tmp, controlServer.ChainConfig, blockWriter),
stagedsync.StageSendersCfg(db, controlServer.ChainConfig, false, dirs.Tmp, cfg.Prune, blockReader, controlServer.Hd, nil),
Expand Down Expand Up @@ -140,6 +140,7 @@ func NewSequencerZkStages(ctx context.Context,
agg,
datastreamServer,
cfg.Zk,
&cfg.Miner,
txPool,
txPoolDb,
),
Expand Down
35 changes: 23 additions & 12 deletions zk/erigon_db/db.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,9 +4,11 @@ import (
"fmt"
"math/big"

"github.com/ledgerwatch/erigon-lib/chain"
"github.com/ledgerwatch/erigon-lib/common"
"github.com/ledgerwatch/erigon-lib/kv"

"github.com/ledgerwatch/erigon/core"
"github.com/ledgerwatch/erigon/core/rawdb"
ethTypes "github.com/ledgerwatch/erigon/core/types"
)
Expand All @@ -28,19 +30,28 @@ func (db ErigonDb) WriteHeader(
blockHash common.Hash,
stateRoot, txHash, parentHash common.Hash,
coinbase common.Address,
ts, gasLimit uint64,
ts, gasLimit uint64, chainConfig *chain.Config,
) (*ethTypes.Header, error) {
h := &ethTypes.Header{
ParentHash: parentHash,
UncleHash: sha3UncleHash,
Coinbase: coinbase,
Root: stateRoot,
TxHash: txHash,
Difficulty: big.NewInt(0),
Number: blockNo,
GasLimit: gasLimit,
Time: ts,
Extra: make([]byte, 0),
parentHeader, err := db.GetHeader(blockNo.Uint64() - 1)
if err != nil {
return nil, fmt.Errorf("failed to get parent header: %w", err)
}

h := core.MakeEmptyHeader(parentHeader, chainConfig, ts, &gasLimit)

h.ParentHash = parentHash
h.Root = stateRoot
h.TxHash = txHash
h.Coinbase = coinbase
h.UncleHash = sha3UncleHash
h.Extra = make([]byte, 0)

if chainConfig.IsShanghai(blockNo.Uint64()) {
h.WithdrawalsHash = &ethTypes.EmptyRootHash
}

if !chainConfig.IsNormalcy(blockNo.Uint64()) {
h.GasLimit = gasLimit
}

if err := rawdb.WriteHeaderWithhash(db.tx, blockHash, h); err != nil {
Expand Down
24 changes: 18 additions & 6 deletions zk/stages/stage_batches.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,13 +7,15 @@ import (
"sync/atomic"
"time"

"github.com/ledgerwatch/erigon-lib/chain"
"github.com/ledgerwatch/erigon-lib/common"

"github.com/ledgerwatch/erigon-lib/kv"

ethTypes "github.com/ledgerwatch/erigon/core/types"
"github.com/ledgerwatch/erigon/eth/stagedsync"
"github.com/ledgerwatch/erigon/eth/stagedsync/stages"
"github.com/ledgerwatch/erigon/params"
"github.com/ledgerwatch/erigon/zk"
"github.com/ledgerwatch/erigon/zk/datastream/types"
"github.com/ledgerwatch/erigon/zk/erigon_db"
Expand All @@ -33,7 +35,7 @@ const (
)

type ErigonDb interface {
WriteHeader(batchNo *big.Int, blockHash common.Hash, stateRoot, txHash, parentHash common.Hash, coinbase common.Address, ts, gasLimit uint64) (*ethTypes.Header, error)
WriteHeader(batchNo *big.Int, blockHash common.Hash, stateRoot, txHash, parentHash common.Hash, coinbase common.Address, ts, gasLimit uint64, chainConfig *chain.Config) (*ethTypes.Header, error)
WriteBody(batchNo *big.Int, headerHash common.Hash, txs []ethTypes.Transaction) error
}

Expand Down Expand Up @@ -86,14 +88,18 @@ type BatchesCfg struct {
blockRoutineStarted bool
dsClient DatastreamClient
zkCfg *ethconfig.Zk
chainConfig *chain.Config
miningConfig *params.MiningConfig
}

func StageBatchesCfg(db kv.RwDB, dsClient DatastreamClient, zkCfg *ethconfig.Zk) BatchesCfg {
func StageBatchesCfg(db kv.RwDB, dsClient DatastreamClient, zkCfg *ethconfig.Zk, chainConfig *chain.Config, miningConfig *params.MiningConfig) BatchesCfg {
return BatchesCfg{
db: db,
blockRoutineStarted: false,
dsClient: dsClient,
zkCfg: zkCfg,
chainConfig: chainConfig,
miningConfig: miningConfig,
}
}

Expand Down Expand Up @@ -340,7 +346,7 @@ LOOP:
l2Block.ParentHash = previousHash
}

if err := writeL2Block(eriDb, hermezDb, &l2Block, highestL1InfoTreeIndex); err != nil {
if err := writeL2Block(eriDb, hermezDb, &l2Block, highestL1InfoTreeIndex, cfg.chainConfig, cfg.miningConfig); err != nil {
return fmt.Errorf("writeL2Block error: %v", err)
}
dsClientProgress.Store(l2Block.L2BlockNumber)
Expand Down Expand Up @@ -756,7 +762,7 @@ func PruneBatchesStage(s *stagedsync.PruneState, tx kv.RwTx, cfg BatchesCfg, ctx

// writeL2Block writes L2Block to ErigonDb and HermezDb
// writes header, body, forkId and blockBatch
func writeL2Block(eriDb ErigonDb, hermezDb HermezDb, l2Block *types.FullL2Block, highestL1InfoTreeIndex uint64) error {
func writeL2Block(eriDb ErigonDb, hermezDb HermezDb, l2Block *types.FullL2Block, highestL1InfoTreeIndex uint64, chainConfig *chain.Config, miningConfig *params.MiningConfig) error {
bn := new(big.Int).SetUint64(l2Block.L2BlockNumber)
txs := make([]ethTypes.Transaction, 0, len(l2Block.L2Txs))
for _, transaction := range l2Block.L2Txs {
Expand All @@ -781,9 +787,15 @@ func writeL2Block(eriDb ErigonDb, hermezDb HermezDb, l2Block *types.FullL2Block,
txCollection := ethTypes.Transactions(txs)
txHash := ethTypes.DeriveSha(txCollection)

gasLimit := utils.GetBlockGasLimitForFork(l2Block.ForkId)
var gasLimit uint64

_, err := eriDb.WriteHeader(bn, l2Block.L2Blockhash, l2Block.StateRoot, txHash, l2Block.ParentHash, l2Block.Coinbase, uint64(l2Block.Timestamp), gasLimit)
if !chainConfig.IsNormalcy(l2Block.L2BlockNumber) {
gasLimit = utils.GetBlockGasLimitForFork(l2Block.ForkId)
} else {
gasLimit = miningConfig.GasLimit
}

_, err := eriDb.WriteHeader(bn, l2Block.L2Blockhash, l2Block.StateRoot, txHash, l2Block.ParentHash, l2Block.Coinbase, uint64(l2Block.Timestamp), gasLimit, chainConfig)
if err != nil {
return fmt.Errorf("write header error: %v", err)
}
Expand Down
2 changes: 1 addition & 1 deletion zk/stages/stage_batches_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -72,7 +72,7 @@ func TestUnwindBatches(t *testing.T) {
require.NoError(t, err)

dsClient := NewTestDatastreamClient(fullL2Blocks, gerUpdates)
cfg := StageBatchesCfg(db1, dsClient, &ethconfig.Zk{})
cfg := StageBatchesCfg(db1, dsClient, &ethconfig.Zk{}, nil)

s := &stagedsync.StageState{ID: stages.Batches, BlockNumber: 0}
u := &stagedsync.Sync{}
Expand Down
21 changes: 12 additions & 9 deletions zk/stages/stage_sequence_execute.go
Original file line number Diff line number Diff line change
Expand Up @@ -80,7 +80,7 @@ func SpawnSequencingStage(
return err
}

header, parentBlock, err := prepareHeader(tx, executionAt, math.MaxUint64, math.MaxUint64, forkId, cfg.zk.AddressSequencer)
header, parentBlock, err := prepareHeader(tx, executionAt, math.MaxUint64, math.MaxUint64, forkId, cfg.zk.AddressSequencer, cfg.chainConfig, cfg.miningConfig)
if err != nil {
return err
}
Expand Down Expand Up @@ -247,7 +247,7 @@ func SpawnSequencingStage(
log.Info(fmt.Sprintf("[%s] Continuing unfinished batch %d from block %d", logPrefix, thisBatch, executionAt))
}

blockDataSizeChecker := NewBlockDataChecker()
blockDataSizeChecker := NewBlockDataChecker(cfg.zk.ShouldCountersBeUnlimited(l1Recovery))

prevHeader := rawdb.ReadHeaderByNumber(tx, executionAt)
batchDataOverflow := false
Expand Down Expand Up @@ -284,7 +284,7 @@ func SpawnSequencingStage(
addedReceipts = []*types.Receipt{}
addedExecutionResults = []*core.ExecutionResult{}
effectiveGases = []uint8{}
header, parentBlock, err = prepareHeader(tx, blockNumber, deltaTimestamp, limboHeaderTimestamp, forkId, nextBatchData.Coinbase)
header, parentBlock, err = prepareHeader(tx, blockNumber, deltaTimestamp, limboHeaderTimestamp, forkId, nextBatchData.Coinbase, cfg.chainConfig, cfg.miningConfig)
if err != nil {
return err
}
Expand All @@ -299,12 +299,15 @@ func SpawnSequencingStage(

// create a copy of the header otherwise the executor will return "state root mismatch error"
header = &types.Header{
ParentHash: header.ParentHash,
Coinbase: header.Coinbase,
Difficulty: header.Difficulty,
Number: header.Number,
GasLimit: header.GasLimit,
Time: header.Time,
ParentHash: header.ParentHash,
Coinbase: header.Coinbase,
Difficulty: header.Difficulty,
Number: header.Number,
GasLimit: header.GasLimit,
Time: header.Time,
BaseFee: header.BaseFee,
BlobGasUsed: header.BlobGasUsed,
ExcessBlobGas: header.ExcessBlobGas,
}
}

Expand Down
9 changes: 6 additions & 3 deletions zk/stages/stage_sequence_execute_blocks.go
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,6 @@ import (
"github.com/ledgerwatch/erigon/zk/erigon_db"
"github.com/ledgerwatch/erigon/zk/hermez_db"
zktypes "github.com/ledgerwatch/erigon/zk/types"
"github.com/ledgerwatch/erigon/zk/utils"
"github.com/ledgerwatch/secp256k1"
)

Expand Down Expand Up @@ -129,6 +128,11 @@ func finaliseBlock(
}
}

var withdrawals []*types.Withdrawal
if cfg.chainConfig.IsShanghai(newHeader.Number.Uint64()) {
withdrawals = []*types.Withdrawal{}
}

finalBlock, finalTransactions, finalReceipts, err := core.FinalizeBlockExecutionWithHistoryWrite(
cfg.engine,
sdb.stateReader,
Expand All @@ -139,7 +143,7 @@ func finaliseBlock(
cfg.chainConfig,
ibs,
receipts,
nil, // no withdrawals
withdrawals,
chainReader,
true,
excessBlobGas,
Expand All @@ -156,7 +160,6 @@ func finaliseBlock(
finalHeader := finalBlock.HeaderNoCopy()
finalHeader.Root = newRoot
finalHeader.Coinbase = cfg.zk.AddressSequencer
finalHeader.GasLimit = utils.GetBlockGasLimitForFork(forkId)
finalHeader.ReceiptHash = types.DeriveSha(receipts)
finalHeader.Bloom = types.CreateBloom(receipts)
newNum := finalBlock.Number()
Expand Down
Loading

0 comments on commit 8ffbaba

Please sign in to comment.