Skip to content

Commit

Permalink
all: implement EIP-compliant verkle trees
Browse files Browse the repository at this point in the history
verkle: Implement Trie, NodeIterator and Database ifs

Fix crash in TestDump

Fix TestDump

Fix TrieCopy

remove unnecessary traces

fix: Error() returned errIteratorEnd in verkle node iterator

rewrite the iterator and change the signature of OpenStorageTrie

add the adapter to reuse the account trie for storage

don't try to deserialize a storage leaf into an account

Fix statedb unit tests (ethereum#14)

* debug code

* Fix more unit tests

* remove traces

* Go back to the full range

One tree to rule them all

remove updateRoot, there is no root to update

store code inside the account leaf

fix build

save current state for Sina

Update go-verkle to latest

Charge WITNESS_*_COST gas on storage loads

Add witness costs for SSTORE as well

Charge witness gas in the case of code execution

corresponding code deletion

add a --verkle flag to separate verkle experiments from regular geth operations

use the snapshot to get data

stateless execution from block witness

AccessWitness functions

Add block generation test + genesis snapshot generation

test stateless block execution (ethereum#18)

* test stateless block execution

* Force tree resolution before generating the proof

increased coverage in stateless test execution (ethereum#19)

* test stateless block execution

* Force tree resolution before generating the proof

* increase coverage in stateless test execution

ensure geth compiles

fix issues in tests with verkle trees deactivated

Ensure stateless data is available when executing statelessly (ethereum#20)

* Ensure stateless data is available when executing statelessly

* Actual execution of a statless block

* bugfixes in stateless block execution

* code cleanup

 - Reduce PR footprint by reverting NewEVM to its original signature
 - Move the access witness to the block context
 - prepare for a change in AW semantics
   Need to store the initial values.
 - Use the touch helper function, DRY

* revert the signature of MustCommit to its original form (ethereum#21)

fix leaf proofs in stateless execution (ethereum#22)

* Fixes in witness pre-state

* Add the recipient's nonce to the witness

* reduce PR footprint and investigate issue in root state calculation

* quick build fix

cleanup: Remove extra parameter in ToBlock

revert ToBlock to its older signature

fix import cycle in vm tests

fix linter issue

fix appveyor build

fix nil pointers in tests

Add indices, yis and Cis to the block's Verkle proof

upgrade geth dependency to drop geth's common dep

fix cmd/devp2p tests

fix rebase issues

quell an appveyor warning

fix address touching in SLOAD and SSTORE

fix access witness for code size

touch target account data before calling

make sure the proper locations get touched in (ext)codecopy

touch all code pages in execution

add pushdata to witness

remove useless code in genesis snapshot generation

testnet: fix some of the rebase/drift issues

Fix verkle proof generation in block

fix an issue occuring when chunking past the code size

fix: ensure the code copy doesn't extend past the code size

Upgrade go-verkle to its IPA version (ethereum#24)

fixes for the IPA testnet

upgrade to latest go-verkle

update go-verkle to get more fixes

simplify code by removing all stateless references (ethereum#25)

fix verkle proof test by enforcing values alignment to 32 bytes

remove unneeded KZG tag

fix the stateless test

Move AccessWitness into StateDB (ethereum#27)

* move AccessWitness into StateDB

* set Accesses in TxContext constructor

* Ensures that a statedb is initialized with a witness

* copy AccessWitness in StateDB.Copy.  use copied state in miner worker.commit.

* remove redundant line

Co-authored-by: Guillaume Ballet <3272758+gballet@users.noreply.github.com>

Fix contract creation issue

enable verkle on cancun block: take 2 (ethereum#28)

* enable verkle on cancun block: take 2

* fix typo.  make unreachable line panic message more clear

fix rebase issues

fix linter issue

merge undefined instead of panicking (ethereum#30)

initialize the new access witness if not already present

fix boundary check in PUSH

fix bound check in code chunking

fix boundary condition check in PUSH32

add circleci support (ethereum#32)

* add circleci support

* disable linter, which is broken again

* actually run tests

remove unnecessary cancun block declaration in tests (ethereum#33)

upgrade go version (ethereum#34)

fix calculation in get_tree_key_for_storage_slot (ethereum#35)

use the witness in statedb, revert applyTx signature (ethereum#36)

* use the witness in statedb, revert applyTx signature

* fix miner tests

* fix catalyst build

Remove access witness from the signature of Process (ethereum#38)

consensus/ethash: ensure uncle accounts are included in block witness (ethereum#40)

consensus/ethash: move accumulation of coinbase witness before coinbase account is credited (ethereum#41)

remove outdated comment

miner: embed verkle proof in sealing block (ethereum#39)

* miner: embed verkle proof in sealing block

* add test to ensure that verkle proof is present in mined blocks

Refactor witness-accumulation in EVM (ethereum#42)

* make push dynamically-charged.  charge witness gas costs for push.  refactor evm witness gas charging to move logic for touching a range of bytecode into a helper method 'touchEachChunksAndChargeGas'

* add witness gas calculation for CodeCopy, ExtCodeCopy, SLoad back to gas_table.go

* witness gas charging for CALL

* remove explicit reference to evm.TxContext

* core/vm: make touchEachChunksAndCharge gas handle nil code value

* core/vm: call implementation, separate out witnesses into touch/set

* some fixes

* remove witness touching from opCall: this will go in evm.go

* remove witness touching for call from gas_table.go

* (hopefully) fix tests

* add SSTORE witness charging that was removed mistakenly

* charge witness gas for call

* clean up and comment touchEachChunksAndChargeGas

* make suggested changes

* address remaining points

* fix build issues

* remove double-charging for contract creation witness gas charging

call onleaf in verkle commit (ethereum#45)

replace sha256 with pedersen_hash in get_key (ethereum#46)

* replace sha256 with pedersen_hash

* fix: prevent an OOB

* workaround timeout in unit test

* update go-ipa and reduce the timeout

* fix for unit tests: do not call NewAccessWitness in NewEVMTxContext (ethereum#49)

* potential fix: do not call NewAccessWitness in NewEVMTxContext

* more fixes: check for the existence of Accesses

* fix absence of witness in copy

* fix another witness issue

* workaround: ensure the prefetcher is off in verkle mode

* fix the remaining issues in tests

* review feedback

* fix witness allocation in stateless test

reactivate working lines in test

fix: don't create settings each time a key is calculated (ethereum#53)

fix: don't use rlp in the tree for slot values (ethereum#51)

* fix: don't use rlp in the tree for slot values

* fix timeout after rebase

core/vm: don't include contract deployer bytecode in AccessWitness or charge witness access costs for it (ethereum#54)

Verkle EXTCODECOPY implementation (ethereum#55)

* core/vm: verkle extcodecopy naive way (do jumpdest analysis on target contract every EXTCODECOPY)

* no double-charge

* address edge-case in touchEachChunksAndChargeGas

* simplify line

Co-authored-by: Guillaume Ballet <3272758+gballet@users.noreply.github.com>

Use IsCancun where applicable (ethereum#56)

* replace Accesses != nil with IsCancun(...)

* fix

Charge witness gas when calling/creating a contract (ethereum#60)

* Charge witness gas when calling/creating a contract

Co-authored-by: Jared Wasinger <j-wasinger@hotmail.com>

* gofmt

* replace checks with evm.Access!=nil with IsCancun

* remove double-charging of witness access costs for contract creation initialization

Co-authored-by: Jared Wasinger <j-wasinger@hotmail.com>

verkle proof deserialization (ethereum#61)

* use proof serialization

* remove cruft

* save current state

* fix most issues up to this point

* fix remaining build issues

* update the go.mod to use the right branch

* remove custom-defined set type

* update go-verkle to get merged PRs

* extract key, value data from proof

* only activate precomp calculations if this is a verkle chain

Co-authored-by: Jared Wasinger <j-wasinger@hotmail.com>

fix: build more than one block in stateless test (ethereum#66)

* reproduce the bug

* fix the nil AccessWitness when Resetting

* fix nonce management in blocks

* fix: make sure the snapshot is reused during the chain generation

Fix GetTreeKey (ethereum#65)

* trie/utils: fix GetTreeKey

* disable the faulty test, tracking issue opened

Co-authored-by: Guillaume Ballet <3272758+gballet@users.noreply.github.com>

Implement latest stateless gas charging spec (ethereum#63)

* latest stateless gas-charging spec: add write event charging

* rename gas calculation function so that it doesn't seem it's charging gas

Co-authored-by: Guillaume Ballet <3272758+gballet@users.noreply.github.com>

Various fixes for rust-verkle proof format compatibility (ethereum#67)

* code to extract the block

* separate proof from keys in block

* display state root of block 0

* change file name to reflect the correct block number

* use RLP instead of flat binary for keyvals in block

* update go-verkle to fix build

* fix rebase issues

* make test pass

* fix issue in map copy

Co-authored-by: Jared Wasinger <j-wasinger@hotmail.com>

Fix contract creation aw (ethereum#68)

* fix contract creation AccessWitness

* remove tracing

* remove tracing

* remove block2.rlp

* move repeated error message into its own error type

fix a couple linter issues

Sload fix (ethereum#69)

* move SLOAD gas calculation to gasSLoadEIP2929

* re-add gasSLoad, used by SSTORE

* make requested changes

fix: witness gas costs being charged more than once (ethereum#70)

* fix: witness gas costs being charged more than one

* update test case

Co-authored-by: Jared Wasinger <j-wasinger@hotmail.com>

re-enable VerkleTrie::ToDot

core/state: implement GetCodeSize for VerkleDB (ethereum#75)

implement core/state: implement GetCodeSize for VerkleDB

copy the pre-state, use an untouched copy for the proof (ethereum#72)

test to compare the proof format with that of rust verkle (ethereum#73)

* test to compare the proof format with that of rust verkle

* comment block extraction code

check proof in verkle tree test

don't delete from the trie when we encounter empty state object if verkle is enabled (ethereum#74)

core/state: write code to rawdb under codehash key when verkle is enabled (ethereum#76)

force the 32-byte alignment of nonce and balance (ethereum#71)

* force the 32-byte alignment of nonce and balance

* review feedback: fix endianness in output

core/state - ensure storage value is set properly in snapshot when verkle is enabled (ethereum#78)

fixes for the return type change in go-verkle (ethereum#77)

* fixes for the return type change in go-verkle

* update go-verkle

* fix endianness issue + workaround for witness fix

* add changes to miner

Co-authored-by: Jared Wasinger <j-wasinger@hotmail.com>

calculate tree index correctly for SLOAD access event (ethereum#79)

core/vm: witness write event for SSTORE (ethereum#80)

* core/vm: witness write event for SSTORE

* remove TODO that is addressed by this branch

fix estimateGas (handle ErrInsufficientBalanceWitness).  Return proper error message when ErrInsufficientBalanceWitness is encountered (ethereum#81)

Verkle/fix/perdersen hash (ethereum#84)

* remove ineffective statement

* fix endianness in pedersen_hash

refactor: set witness account values in getStateObject() (ethereum#83)

* enforce 32-byte alignment

* save current state

* write account values to witness from getObject

* code cleanup + sanity checks

* fix RLP serialization of missing keys

* remove code redundancy for GetTreeKeyCodeChunk

* fix stem calculation issue for code and storage

* remove redundant SetLeafValue calls

* Add a contract creation tx to the test

* fix botched module version update

* detail gas calculation cost in verkle contract deployment

fix verkle trie iterator to not miss leaf values in the first index of a leaf node (ethereum#88)

creation-time CODECOPY adds no code to the witness (ethereum#86)

* creation-time CODECOPY adds no code to the witness

* Add a more complex test to ensure EXTCODECOPY is called

* Fix offset calculations in the slot function

* minor tweaks

* fix initial value capture for storage

* fix build

* fix: get the proper byte in get_tree_key_for_storage_slot

* fix length calculation in getDataAndAdjustedBounds

* fix verkle test

small simplification in order to facilitate rebase

upgrade go-ipa + go-verkle: faster precomp loading

fix: place slot value, not its rlp encoding in witness

fix: code chunification with incorrect header (ethereum#89)

* fix: code chunification with incorrect header

* add a test from rust-verkle and fix offset bug

* fix ci build

* complete coverage of rust-verkle chunking tests

* fix: make sure the witness value is set

* add another code chunking test from rust-verkle

spec: don't add the trailing pushdata for a final PUSHn (ethereum#90)

cleanup: don't evaluate 0 coeffs in get_tree_key (ethereum#87)

ensure no overflow occurs in the chunk touch function

load the full coinbase account in reward

fix: previous commit broke stateless test

rework the way the gas is charged per code chunk

update go-verkle to grab the fix for ethereum#200

fix: don't add PUSH1-data during contract deployment (ethereum#91)

* fix: don't add PUSH1-data during contract deployment

* remove import cycle in tests (ethereum#92)

fix: redundant proof-of-absence stems (ethereum#93)

test: missing children of the same internal node produce a single extension status (ethereum#94)

ParseNode with commitment parameter (ethereum#95)

review feedback for rebase over kiln (ethereum#97)

safe gas add (ethereum#98)

* safe gas add

* fix build

ensure 10-byte addresses are right-aligned in pedersen_hash (ethereum#99)

Co-authored-by: Tanishq Jasoria <jasoriatanishq@gmail.com>

Remove the code analysis interface to reduce PR footprint (ethereum#100)

* Remove the code analysis interface to reduce PR footprint

* fix unit test

fix: set IsDeployment=false outside of contract creation (ethereum#101)

remove trailing line

verkle test: count the code chunks in the witness (ethereum#102)

temp fix: little endian pedersen_hash (ethereum#103)

factor the amount of polynomial evaluations in access witness (ethereum#106)

reuse polynomial evaluation in account update (ethereum#108)

fix: remove redundant balance touching in access witness (ethereum#107)

add github workflow

reuse address point evaluation in code chunking (ethereum#109)
  • Loading branch information
gballet committed Jul 7, 2022
1 parent e394d01 commit 46498e8
Show file tree
Hide file tree
Showing 47 changed files with 3,196 additions and 73 deletions.
57 changes: 57 additions & 0 deletions .github/workflows/go.yml
@@ -0,0 +1,57 @@
name: Go lint and test

on:
push:
branches: [ master ]
pull_request:
branches: [ master, verkle-trie-proof-in-block-rebased ]

jobs:

build:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2

- name: Set up Go
uses: actions/setup-go@v2
with:
go-version: 1.18

- name: Build
run: go build -v ./...

lint:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2

- name: Set up Go
uses: actions/setup-go@v2
with:
go-version: 1.18

- name: Download golangci-lint
run: wget -O- -nv https://raw.githubusercontent.com/golangci/golangci-lint/master/install.sh | sh -s latest

- name: Lint
run: ./bin/golangci-lint run

- name: Vet
run: go vet

test:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2

- name: Set up Go
uses: actions/setup-go@v2
with:
go-version: 1.18

- name: Download precomputed points
run: wget -nv https://github.com/gballet/go-verkle/releases/download/banderwagon/precomp

- name: Test
run: go test ./...
4 changes: 2 additions & 2 deletions cmd/geth/snapshot.go
Expand Up @@ -203,7 +203,7 @@ func verifyState(ctx *cli.Context) error {
log.Error("Failed to load head block")
return errors.New("no head block")
}
snaptree, err := snapshot.New(chaindb, trie.NewDatabase(chaindb), 256, headBlock.Root(), false, false, false)
snaptree, err := snapshot.New(chaindb, trie.NewDatabase(chaindb), 256, headBlock.Root(), false, false, false, false)
if err != nil {
log.Error("Failed to open snapshot tree", "err", err)
return err
Expand Down Expand Up @@ -478,7 +478,7 @@ func dumpState(ctx *cli.Context) error {
if err != nil {
return err
}
snaptree, err := snapshot.New(db, trie.NewDatabase(db), 256, root, false, false, false)
snaptree, err := snapshot.New(db, trie.NewDatabase(db), 256, root, false, false, false, false)
if err != nil {
return err
}
Expand Down
19 changes: 19 additions & 0 deletions consensus/ethash/consensus.go
Expand Up @@ -34,6 +34,7 @@ import (
"github.com/ethereum/go-ethereum/params"
"github.com/ethereum/go-ethereum/rlp"
"github.com/ethereum/go-ethereum/trie"
"github.com/ethereum/go-ethereum/trie/utils"
"golang.org/x/crypto/sha3"
)

Expand Down Expand Up @@ -666,10 +667,28 @@ func accumulateRewards(config *params.ChainConfig, state *state.StateDB, header
r.Sub(r, header.Number)
r.Mul(r, blockReward)
r.Div(r, big8)

if config.IsCancun(header.Number) {
uncleCoinbase := utils.GetTreeKeyBalance(uncle.Coinbase.Bytes())
state.Witness().TouchAddressOnReadAndComputeGas(uncleCoinbase)
state.Witness().SetLeafValue(uncleCoinbase, state.GetBalance(uncle.Coinbase).Bytes())
}
state.AddBalance(uncle.Coinbase, r)

r.Div(blockReward, big32)
reward.Add(reward, r)
}
if config.IsCancun(header.Number) {
coinbase := utils.GetTreeKeyBalance(header.Coinbase.Bytes())
state.Witness().TouchAddressOnReadAndComputeGas(coinbase)
coinbase[31] = 0 // mark version
state.Witness().TouchAddressOnReadAndComputeGas(coinbase)
coinbase[31] = 2 // mark nonce
state.Witness().TouchAddressOnReadAndComputeGas(coinbase)
coinbase[31] = 3 // mark code keccak
state.Witness().TouchAddressOnReadAndComputeGas(coinbase)
balance := state.GetBalance(header.Coinbase)
state.Witness().SetLeafValue(coinbase, balance.Bytes())
}
state.AddBalance(header.Coinbase, reward)
}
22 changes: 12 additions & 10 deletions core/blockchain.go
Expand Up @@ -228,15 +228,10 @@ func NewBlockChain(db ethdb.Database, cacheConfig *CacheConfig, chainConfig *par
futureBlocks, _ := lru.New(maxFutureBlocks)

bc := &BlockChain{
chainConfig: chainConfig,
cacheConfig: cacheConfig,
db: db,
triegc: prque.New(nil),
stateCache: state.NewDatabaseWithConfig(db, &trie.Config{
Cache: cacheConfig.TrieCleanLimit,
Journal: cacheConfig.TrieCleanJournal,
Preimages: cacheConfig.Preimages,
}),
chainConfig: chainConfig,
cacheConfig: cacheConfig,
db: db,
triegc: prque.New(nil),
quit: make(chan struct{}),
chainmu: syncx.NewClosableMutex(),
bodyCache: bodyCache,
Expand Down Expand Up @@ -286,6 +281,13 @@ func NewBlockChain(db ethdb.Database, cacheConfig *CacheConfig, chainConfig *par

// Make sure the state associated with the block is available
head := bc.CurrentBlock()
bc.stateCache = state.NewDatabaseWithConfig(db, &trie.Config{
Cache: cacheConfig.TrieCleanLimit,
Journal: cacheConfig.TrieCleanJournal,
Preimages: cacheConfig.Preimages,
UseVerkle: chainConfig.IsCancun(head.Header().Number),
})

if _, err := state.New(head.Root(), bc.stateCache, bc.snaps); err != nil {
// Head state is missing, before the state recovery, find out the
// disk layer point of snapshot(if it's enabled). Make sure the
Expand Down Expand Up @@ -378,7 +380,7 @@ func NewBlockChain(db ethdb.Database, cacheConfig *CacheConfig, chainConfig *par
log.Warn("Enabling snapshot recovery", "chainhead", head.NumberU64(), "diskbase", *layer)
recover = true
}
bc.snaps, _ = snapshot.New(bc.db, bc.stateCache.TrieDB(), bc.cacheConfig.SnapshotLimit, head.Root(), !bc.cacheConfig.SnapshotWait, true, recover)
bc.snaps, _ = snapshot.New(bc.db, bc.stateCache.TrieDB(), bc.cacheConfig.SnapshotLimit, head.Root(), !bc.cacheConfig.SnapshotWait, true, recover, chainConfig.IsCancun(head.Header().Number))
}

// Start future block processor.
Expand Down
102 changes: 102 additions & 0 deletions core/chain_makers.go
Expand Up @@ -24,10 +24,12 @@ import (
"github.com/ethereum/go-ethereum/consensus"
"github.com/ethereum/go-ethereum/consensus/misc"
"github.com/ethereum/go-ethereum/core/state"
"github.com/ethereum/go-ethereum/core/state/snapshot"
"github.com/ethereum/go-ethereum/core/types"
"github.com/ethereum/go-ethereum/core/vm"
"github.com/ethereum/go-ethereum/ethdb"
"github.com/ethereum/go-ethereum/params"
"github.com/ethereum/go-ethereum/trie"
)

// BlockGen creates blocks for testing.
Expand Down Expand Up @@ -284,6 +286,106 @@ func GenerateChain(config *params.ChainConfig, parent *types.Block, engine conse
return blocks, receipts
}

func GenerateVerkleChain(config *params.ChainConfig, parent *types.Block, engine consensus.Engine, db ethdb.Database, n int, gen func(int, *BlockGen)) ([]*types.Block, []types.Receipts) {
if config == nil {
config = params.TestChainConfig
}
blocks, receipts := make(types.Blocks, n), make([]types.Receipts, n)
chainreader := &fakeChainReader{config: config}
genblock := func(i int, parent *types.Block, statedb *state.StateDB) (*types.Block, types.Receipts) {
b := &BlockGen{i: i, chain: blocks, parent: parent, statedb: statedb, config: config, engine: engine}
b.header = makeHeader(chainreader, parent, statedb, b.engine)
preState := statedb.Copy()

// Mutate the state and block according to any hard-fork specs
if daoBlock := config.DAOForkBlock; daoBlock != nil {
limit := new(big.Int).Add(daoBlock, params.DAOForkExtraRange)
if b.header.Number.Cmp(daoBlock) >= 0 && b.header.Number.Cmp(limit) < 0 {
if config.DAOForkSupport {
b.header.Extra = common.CopyBytes(params.DAOForkBlockExtra)
}
}
}
if config.DAOForkSupport && config.DAOForkBlock != nil && config.DAOForkBlock.Cmp(b.header.Number) == 0 {
misc.ApplyDAOHardFork(statedb)
}
// Execute any user modifications to the block
if gen != nil {
gen(i, b)
}
if b.engine != nil {
// Finalize and seal the block
block, err := b.engine.FinalizeAndAssemble(chainreader, b.header, statedb, b.txs, b.uncles, b.receipts)
if err != nil {
panic(err)
}

// Write state changes to db
root, err := statedb.Commit(config.IsEIP158(b.header.Number))
if err != nil {
panic(fmt.Sprintf("state write error: %v", err))
}
if err := statedb.Database().TrieDB().Commit(root, false, nil); err != nil {
panic(fmt.Sprintf("trie write error: %v", err))
}

// Generate an associated verkle proof
tr := preState.GetTrie()
if !tr.IsVerkle() {
panic("tree should be verkle")
}

vtr := tr.(*trie.VerkleTrie)
// Make sure all keys are resolved before
// building the proof. Ultimately, node
// resolution can be done with a prefetcher
// or from GetCommitmentsAlongPath.
kvs := statedb.Witness().KeyVals()
keys := statedb.Witness().Keys()
for _, key := range keys {
_, err := vtr.TryGet(key)
if err != nil {
panic(err)
}

// Sanity check: ensure all flagged addresses have an associated
// value: keys is built from Chunks and kvs from InitialValue.
if _, exists := kvs[string(key)]; !exists {
panic(fmt.Sprintf("address not in access witness: %x", key))
}
}

// sanity check: ensure all values correspond to a flagged key by
// comparing the lengths of both structures: they should be equal
if len(kvs) != len(keys) {
panic("keys without a value in witness")
}

vtr.Hash()
p, k, err := vtr.ProveAndSerialize(keys, kvs)
block.SetVerkleProof(p, k)
if err != nil {
panic(err)
}
return block, b.receipts
}
return nil, nil
}
var snaps *snapshot.Tree
for i := 0; i < n; i++ {
statedb, err := state.New(parent.Root(), state.NewDatabaseWithConfig(db, &trie.Config{UseVerkle: true}), snaps)
if err != nil {
panic(err)
}
block, receipt := genblock(i, parent, statedb)
blocks[i] = block
receipts[i] = receipt
parent = block
snaps = statedb.Snaps()
}
return blocks, receipts
}

func makeHeader(chain consensus.ChainReader, parent *types.Block, state *state.StateDB, engine consensus.Engine) *types.Header {
var time uint64
if parent.Time() == 0 {
Expand Down
5 changes: 5 additions & 0 deletions core/error.go
Expand Up @@ -63,6 +63,11 @@ var (
// have enough funds for transfer(topmost call only).
ErrInsufficientFundsForTransfer = errors.New("insufficient funds for transfer")

// ErrInsufficientBalanceWitness is returned if the transaction sender has enough
// funds to cover the transfer, but not enough to pay for witness access/modification
// costs for the transaction
ErrInsufficientBalanceWitness = errors.New("insufficient funds to cover witness access costs for transaction")

// ErrInsufficientFunds is returned if the total cost of executing a transaction
// is higher than the balance of the user's account.
ErrInsufficientFunds = errors.New("insufficient funds for gas * price + value")
Expand Down
25 changes: 24 additions & 1 deletion core/genesis.go
Expand Up @@ -268,7 +268,25 @@ func SetupGenesisBlockWithOverride(db ethdb.Database, genesis *Genesis, override
// We have the genesis block in database(perhaps in ancient database)
// but the corresponding state is missing.
header := rawdb.ReadHeader(db, stored, 0)
if _, err := state.New(header.Root, state.NewDatabaseWithConfig(db, nil), nil); err != nil {

var trieCfg *trie.Config

if genesis == nil {
storedcfg := rawdb.ReadChainConfig(db, stored)
if storedcfg == nil {
panic("this should never be reached: if genesis is nil, the config is already present or 'geth init' is being called which created it (in the code above, which means genesis != nil)")
}

if storedcfg.CancunBlock != nil {
if storedcfg.CancunBlock.Cmp(big.NewInt(0)) != 0 {
panic("cancun block must be 0")
}

trieCfg = &trie.Config{UseVerkle: storedcfg.IsCancun(big.NewInt(header.Number.Int64()))}
}
}

if _, err := state.New(header.Root, state.NewDatabaseWithConfig(db, trieCfg), nil); err != nil {
if genesis == nil {
genesis = DefaultGenesisBlock()
}
Expand Down Expand Up @@ -353,6 +371,11 @@ func (g *Genesis) ToBlock(db ethdb.Database) *types.Block {
if db == nil {
db = rawdb.NewMemoryDatabase()
}
var trieCfg *trie.Config
if g.Config != nil {
trieCfg = &trie.Config{UseVerkle: g.Config.IsCancun(big.NewInt(int64(g.Number)))}
}
statedb, err := state.New(common.Hash{}, state.NewDatabaseWithConfig(db, trieCfg), nil)
root, err := g.Alloc.flush(db)
if err != nil {
panic(err)
Expand Down

0 comments on commit 46498e8

Please sign in to comment.