Compare commits
12 Commits
952a28b720
...
27d0bf7cff
Author | SHA1 | Date |
---|---|---|
|
27d0bf7cff | |
|
dab746b3ef | |
|
ef00a6e9a2 | |
|
32c6aa8a1a | |
|
7332a1bc0a | |
|
68d477670c | |
|
3adfa1fbeb | |
|
aec1964410 | |
|
c8c62dafc7 | |
|
d37a0b8cd0 | |
|
c113e3b5b1 | |
|
e5bc789185 |
|
@ -262,7 +262,7 @@ var (
|
||||||
}
|
}
|
||||||
StateHistoryFlag = &cli.Uint64Flag{
|
StateHistoryFlag = &cli.Uint64Flag{
|
||||||
Name: "history.state",
|
Name: "history.state",
|
||||||
Usage: "Number of recent blocks to retain state history for (default = 90,000 blocks, 0 = entire chain)",
|
Usage: "Number of recent blocks to retain state history for, only relevant in state.scheme=path (default = 90,000 blocks, 0 = entire chain)",
|
||||||
Value: ethconfig.Defaults.StateHistory,
|
Value: ethconfig.Defaults.StateHistory,
|
||||||
Category: flags.StateCategory,
|
Category: flags.StateCategory,
|
||||||
}
|
}
|
||||||
|
|
|
@ -75,9 +75,11 @@ func New(ethone consensus.Engine) *Beacon {
|
||||||
// isPostMerge reports whether the given block number is assumed to be post-merge.
|
// isPostMerge reports whether the given block number is assumed to be post-merge.
|
||||||
// Here we check the MergeNetsplitBlock to allow configuring networks with a PoW or
|
// Here we check the MergeNetsplitBlock to allow configuring networks with a PoW or
|
||||||
// PoA chain for unit testing purposes.
|
// PoA chain for unit testing purposes.
|
||||||
func isPostMerge(config *params.ChainConfig, block uint64) bool {
|
func isPostMerge(config *params.ChainConfig, blockNum uint64, timestamp uint64) bool {
|
||||||
mergedAtGenesis := config.TerminalTotalDifficulty != nil && config.TerminalTotalDifficulty.Sign() == 0
|
mergedAtGenesis := config.TerminalTotalDifficulty != nil && config.TerminalTotalDifficulty.Sign() == 0
|
||||||
return mergedAtGenesis || config.MergeNetsplitBlock != nil && block >= config.MergeNetsplitBlock.Uint64()
|
return mergedAtGenesis ||
|
||||||
|
config.MergeNetsplitBlock != nil && blockNum >= config.MergeNetsplitBlock.Uint64() ||
|
||||||
|
config.ShanghaiTime != nil && timestamp >= *config.ShanghaiTime
|
||||||
}
|
}
|
||||||
|
|
||||||
// Author implements consensus.Engine, returning the verified author of the block.
|
// Author implements consensus.Engine, returning the verified author of the block.
|
||||||
|
@ -327,7 +329,7 @@ func (beacon *Beacon) verifyHeaders(chain consensus.ChainHeaderReader, headers [
|
||||||
// Prepare implements consensus.Engine, initializing the difficulty field of a
|
// Prepare implements consensus.Engine, initializing the difficulty field of a
|
||||||
// header to conform to the beacon protocol. The changes are done inline.
|
// header to conform to the beacon protocol. The changes are done inline.
|
||||||
func (beacon *Beacon) Prepare(chain consensus.ChainHeaderReader, header *types.Header) error {
|
func (beacon *Beacon) Prepare(chain consensus.ChainHeaderReader, header *types.Header) error {
|
||||||
if !isPostMerge(chain.Config(), header.Number.Uint64()) {
|
if !isPostMerge(chain.Config(), header.Number.Uint64(), header.Time) {
|
||||||
return beacon.ethone.Prepare(chain, header)
|
return beacon.ethone.Prepare(chain, header)
|
||||||
}
|
}
|
||||||
header.Difficulty = beaconDifficulty
|
header.Difficulty = beaconDifficulty
|
||||||
|
@ -437,7 +439,7 @@ func (beacon *Beacon) SealHash(header *types.Header) common.Hash {
|
||||||
// the difficulty that a new block should have when created at time
|
// the difficulty that a new block should have when created at time
|
||||||
// given the parent block's time and difficulty.
|
// given the parent block's time and difficulty.
|
||||||
func (beacon *Beacon) CalcDifficulty(chain consensus.ChainHeaderReader, time uint64, parent *types.Header) *big.Int {
|
func (beacon *Beacon) CalcDifficulty(chain consensus.ChainHeaderReader, time uint64, parent *types.Header) *big.Int {
|
||||||
if !isPostMerge(chain.Config(), parent.Number.Uint64()+1) {
|
if !isPostMerge(chain.Config(), parent.Number.Uint64()+1, time) {
|
||||||
return beacon.ethone.CalcDifficulty(chain, time, parent)
|
return beacon.ethone.CalcDifficulty(chain, time, parent)
|
||||||
}
|
}
|
||||||
return beaconDifficulty
|
return beaconDifficulty
|
||||||
|
|
|
@ -83,6 +83,8 @@ func CalcExcessBlobGas(config *params.ChainConfig, parent *types.Header, headTim
|
||||||
func CalcBlobFee(config *params.ChainConfig, header *types.Header) *big.Int {
|
func CalcBlobFee(config *params.ChainConfig, header *types.Header) *big.Int {
|
||||||
var frac uint64
|
var frac uint64
|
||||||
switch config.LatestFork(header.Time) {
|
switch config.LatestFork(header.Time) {
|
||||||
|
case forks.Osaka:
|
||||||
|
frac = config.BlobScheduleConfig.Osaka.UpdateFraction
|
||||||
case forks.Prague:
|
case forks.Prague:
|
||||||
frac = config.BlobScheduleConfig.Prague.UpdateFraction
|
frac = config.BlobScheduleConfig.Prague.UpdateFraction
|
||||||
case forks.Cancun:
|
case forks.Cancun:
|
||||||
|
@ -103,6 +105,8 @@ func MaxBlobsPerBlock(cfg *params.ChainConfig, time uint64) int {
|
||||||
s = cfg.BlobScheduleConfig
|
s = cfg.BlobScheduleConfig
|
||||||
)
|
)
|
||||||
switch {
|
switch {
|
||||||
|
case cfg.IsOsaka(london, time) && s.Osaka != nil:
|
||||||
|
return s.Osaka.Max
|
||||||
case cfg.IsPrague(london, time) && s.Prague != nil:
|
case cfg.IsPrague(london, time) && s.Prague != nil:
|
||||||
return s.Prague.Max
|
return s.Prague.Max
|
||||||
case cfg.IsCancun(london, time) && s.Cancun != nil:
|
case cfg.IsCancun(london, time) && s.Cancun != nil:
|
||||||
|
@ -125,6 +129,8 @@ func LatestMaxBlobsPerBlock(cfg *params.ChainConfig) int {
|
||||||
return 0
|
return 0
|
||||||
}
|
}
|
||||||
switch {
|
switch {
|
||||||
|
case s.Osaka != nil:
|
||||||
|
return s.Osaka.Max
|
||||||
case s.Prague != nil:
|
case s.Prague != nil:
|
||||||
return s.Prague.Max
|
return s.Prague.Max
|
||||||
case s.Cancun != nil:
|
case s.Cancun != nil:
|
||||||
|
@ -144,6 +150,8 @@ func targetBlobsPerBlock(cfg *params.ChainConfig, time uint64) int {
|
||||||
s = cfg.BlobScheduleConfig
|
s = cfg.BlobScheduleConfig
|
||||||
)
|
)
|
||||||
switch {
|
switch {
|
||||||
|
case cfg.IsOsaka(london, time) && s.Osaka != nil:
|
||||||
|
return s.Osaka.Target
|
||||||
case cfg.IsPrague(london, time) && s.Prague != nil:
|
case cfg.IsPrague(london, time) && s.Prague != nil:
|
||||||
return s.Prague.Target
|
return s.Prague.Target
|
||||||
case cfg.IsCancun(london, time) && s.Cancun != nil:
|
case cfg.IsCancun(london, time) && s.Cancun != nil:
|
||||||
|
|
|
@ -281,6 +281,7 @@ func TestVerkleGenesisCommit(t *testing.T) {
|
||||||
BlobScheduleConfig: ¶ms.BlobScheduleConfig{
|
BlobScheduleConfig: ¶ms.BlobScheduleConfig{
|
||||||
Cancun: params.DefaultCancunBlobConfig,
|
Cancun: params.DefaultCancunBlobConfig,
|
||||||
Prague: params.DefaultPragueBlobConfig,
|
Prague: params.DefaultPragueBlobConfig,
|
||||||
|
Osaka: params.DefaultOsakaBlobConfig,
|
||||||
Verkle: params.DefaultPragueBlobConfig,
|
Verkle: params.DefaultPragueBlobConfig,
|
||||||
},
|
},
|
||||||
}
|
}
|
||||||
|
|
|
@ -229,7 +229,7 @@ func ProcessBeaconBlockRoot(beaconRoot common.Hash, evm *vm.EVM) {
|
||||||
}
|
}
|
||||||
evm.SetTxContext(NewEVMTxContext(msg))
|
evm.SetTxContext(NewEVMTxContext(msg))
|
||||||
evm.StateDB.AddAddressToAccessList(params.BeaconRootsAddress)
|
evm.StateDB.AddAddressToAccessList(params.BeaconRootsAddress)
|
||||||
_, _, _ = evm.Call(vm.AccountRef(msg.From), *msg.To, msg.Data, 30_000_000, common.U2560)
|
_, _, _ = evm.Call(msg.From, *msg.To, msg.Data, 30_000_000, common.U2560)
|
||||||
evm.StateDB.Finalise(true)
|
evm.StateDB.Finalise(true)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -253,7 +253,7 @@ func ProcessParentBlockHash(prevHash common.Hash, evm *vm.EVM) {
|
||||||
}
|
}
|
||||||
evm.SetTxContext(NewEVMTxContext(msg))
|
evm.SetTxContext(NewEVMTxContext(msg))
|
||||||
evm.StateDB.AddAddressToAccessList(params.HistoryStorageAddress)
|
evm.StateDB.AddAddressToAccessList(params.HistoryStorageAddress)
|
||||||
_, _, err := evm.Call(vm.AccountRef(msg.From), *msg.To, msg.Data, 30_000_000, common.U2560)
|
_, _, err := evm.Call(msg.From, *msg.To, msg.Data, 30_000_000, common.U2560)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
panic(err)
|
panic(err)
|
||||||
}
|
}
|
||||||
|
@ -292,7 +292,7 @@ func processRequestsSystemCall(requests *[][]byte, evm *vm.EVM, requestType byte
|
||||||
}
|
}
|
||||||
evm.SetTxContext(NewEVMTxContext(msg))
|
evm.SetTxContext(NewEVMTxContext(msg))
|
||||||
evm.StateDB.AddAddressToAccessList(addr)
|
evm.StateDB.AddAddressToAccessList(addr)
|
||||||
ret, _, _ := evm.Call(vm.AccountRef(msg.From), *msg.To, msg.Data, 30_000_000, common.U2560)
|
ret, _, _ := evm.Call(msg.From, *msg.To, msg.Data, 30_000_000, common.U2560)
|
||||||
evm.StateDB.Finalise(true)
|
evm.StateDB.Finalise(true)
|
||||||
if len(ret) == 0 {
|
if len(ret) == 0 {
|
||||||
return // skip empty output
|
return // skip empty output
|
||||||
|
|
|
@ -423,7 +423,6 @@ func (st *stateTransition) execute() (*ExecutionResult, error) {
|
||||||
|
|
||||||
var (
|
var (
|
||||||
msg = st.msg
|
msg = st.msg
|
||||||
sender = vm.AccountRef(msg.From)
|
|
||||||
rules = st.evm.ChainConfig().Rules(st.evm.Context.BlockNumber, st.evm.Context.Random != nil, st.evm.Context.Time)
|
rules = st.evm.ChainConfig().Rules(st.evm.Context.BlockNumber, st.evm.Context.Random != nil, st.evm.Context.Time)
|
||||||
contractCreation = msg.To == nil
|
contractCreation = msg.To == nil
|
||||||
floorDataGas uint64
|
floorDataGas uint64
|
||||||
|
@ -484,7 +483,7 @@ func (st *stateTransition) execute() (*ExecutionResult, error) {
|
||||||
vmerr error // vm errors do not effect consensus and are therefore not assigned to err
|
vmerr error // vm errors do not effect consensus and are therefore not assigned to err
|
||||||
)
|
)
|
||||||
if contractCreation {
|
if contractCreation {
|
||||||
ret, _, st.gasRemaining, vmerr = st.evm.Create(sender, msg.Data, st.gasRemaining, value)
|
ret, _, st.gasRemaining, vmerr = st.evm.Create(msg.From, msg.Data, st.gasRemaining, value)
|
||||||
} else {
|
} else {
|
||||||
// Increment the nonce for the next transaction.
|
// Increment the nonce for the next transaction.
|
||||||
st.state.SetNonce(msg.From, st.state.GetNonce(msg.From)+1, tracing.NonceChangeEoACall)
|
st.state.SetNonce(msg.From, st.state.GetNonce(msg.From)+1, tracing.NonceChangeEoACall)
|
||||||
|
@ -507,7 +506,7 @@ func (st *stateTransition) execute() (*ExecutionResult, error) {
|
||||||
}
|
}
|
||||||
|
|
||||||
// Execute the transaction's call.
|
// Execute the transaction's call.
|
||||||
ret, st.gasRemaining, vmerr = st.evm.Call(sender, st.to(), msg.Data, st.gasRemaining, value)
|
ret, st.gasRemaining, vmerr = st.evm.Call(msg.From, st.to(), msg.Data, st.gasRemaining, value)
|
||||||
}
|
}
|
||||||
|
|
||||||
// Compute refund counter, capped to a refund quotient.
|
// Compute refund counter, capped to a refund quotient.
|
||||||
|
|
|
@ -22,39 +22,20 @@ import (
|
||||||
"github.com/holiman/uint256"
|
"github.com/holiman/uint256"
|
||||||
)
|
)
|
||||||
|
|
||||||
// ContractRef is a reference to the contract's backing object
|
|
||||||
type ContractRef interface {
|
|
||||||
Address() common.Address
|
|
||||||
}
|
|
||||||
|
|
||||||
// AccountRef implements ContractRef.
|
|
||||||
//
|
|
||||||
// Account references are used during EVM initialisation and
|
|
||||||
// its primary use is to fetch addresses. Removing this object
|
|
||||||
// proves difficult because of the cached jump destinations which
|
|
||||||
// are fetched from the parent contract (i.e. the caller), which
|
|
||||||
// is a ContractRef.
|
|
||||||
type AccountRef common.Address
|
|
||||||
|
|
||||||
// Address casts AccountRef to an Address
|
|
||||||
func (ar AccountRef) Address() common.Address { return (common.Address)(ar) }
|
|
||||||
|
|
||||||
// Contract represents an ethereum contract in the state database. It contains
|
// Contract represents an ethereum contract in the state database. It contains
|
||||||
// the contract code, calling arguments. Contract implements ContractRef
|
// the contract code, calling arguments. Contract implements ContractRef
|
||||||
type Contract struct {
|
type Contract struct {
|
||||||
// CallerAddress is the result of the caller which initialised this
|
// caller is the result of the caller which initialised this
|
||||||
// contract. However when the "call method" is delegated this value
|
// contract. However, when the "call method" is delegated this
|
||||||
// needs to be initialised to that of the caller's caller.
|
// value needs to be initialised to that of the caller's caller.
|
||||||
CallerAddress common.Address
|
caller common.Address
|
||||||
caller ContractRef
|
address common.Address
|
||||||
self ContractRef
|
|
||||||
|
|
||||||
jumpdests map[common.Hash]bitvec // Aggregated result of JUMPDEST analysis.
|
jumpdests map[common.Hash]bitvec // Aggregated result of JUMPDEST analysis.
|
||||||
analysis bitvec // Locally cached result of JUMPDEST analysis
|
analysis bitvec // Locally cached result of JUMPDEST analysis
|
||||||
|
|
||||||
Code []byte
|
Code []byte
|
||||||
CodeHash common.Hash
|
CodeHash common.Hash
|
||||||
CodeAddr *common.Address
|
|
||||||
Input []byte
|
Input []byte
|
||||||
|
|
||||||
// is the execution frame represented by this object a contract deployment
|
// is the execution frame represented by this object a contract deployment
|
||||||
|
@ -66,23 +47,18 @@ type Contract struct {
|
||||||
}
|
}
|
||||||
|
|
||||||
// NewContract returns a new contract environment for the execution of EVM.
|
// NewContract returns a new contract environment for the execution of EVM.
|
||||||
func NewContract(caller ContractRef, object ContractRef, value *uint256.Int, gas uint64) *Contract {
|
func NewContract(caller common.Address, address common.Address, value *uint256.Int, gas uint64, jumpDests map[common.Hash]bitvec) *Contract {
|
||||||
c := &Contract{CallerAddress: caller.Address(), caller: caller, self: object}
|
// Initialize the jump analysis map if it's nil, mostly for tests
|
||||||
|
if jumpDests == nil {
|
||||||
if parent, ok := caller.(*Contract); ok {
|
jumpDests = make(map[common.Hash]bitvec)
|
||||||
// Reuse JUMPDEST analysis from parent context if available.
|
}
|
||||||
c.jumpdests = parent.jumpdests
|
return &Contract{
|
||||||
} else {
|
caller: caller,
|
||||||
c.jumpdests = make(map[common.Hash]bitvec)
|
address: address,
|
||||||
|
jumpdests: jumpDests,
|
||||||
|
Gas: gas,
|
||||||
|
value: value,
|
||||||
}
|
}
|
||||||
|
|
||||||
// Gas should be a pointer so it can safely be reduced through the run
|
|
||||||
// This pointer will be off the state transition
|
|
||||||
c.Gas = gas
|
|
||||||
// ensures a value is set
|
|
||||||
c.value = value
|
|
||||||
|
|
||||||
return c
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func (c *Contract) validJumpdest(dest *uint256.Int) bool {
|
func (c *Contract) validJumpdest(dest *uint256.Int) bool {
|
||||||
|
@ -132,18 +108,6 @@ func (c *Contract) isCode(udest uint64) bool {
|
||||||
return c.analysis.codeSegment(udest)
|
return c.analysis.codeSegment(udest)
|
||||||
}
|
}
|
||||||
|
|
||||||
// AsDelegate sets the contract to be a delegate call and returns the current
|
|
||||||
// contract (for chaining calls)
|
|
||||||
func (c *Contract) AsDelegate() *Contract {
|
|
||||||
// NOTE: caller must, at all times be a contract. It should never happen
|
|
||||||
// that caller is something other than a Contract.
|
|
||||||
parent := c.caller.(*Contract)
|
|
||||||
c.CallerAddress = parent.CallerAddress
|
|
||||||
c.value = parent.value
|
|
||||||
|
|
||||||
return c
|
|
||||||
}
|
|
||||||
|
|
||||||
// GetOp returns the n'th element in the contract's byte array
|
// GetOp returns the n'th element in the contract's byte array
|
||||||
func (c *Contract) GetOp(n uint64) OpCode {
|
func (c *Contract) GetOp(n uint64) OpCode {
|
||||||
if n < uint64(len(c.Code)) {
|
if n < uint64(len(c.Code)) {
|
||||||
|
@ -158,7 +122,7 @@ func (c *Contract) GetOp(n uint64) OpCode {
|
||||||
// Caller will recursively call caller when the contract is a delegate
|
// Caller will recursively call caller when the contract is a delegate
|
||||||
// call, including that of caller's caller.
|
// call, including that of caller's caller.
|
||||||
func (c *Contract) Caller() common.Address {
|
func (c *Contract) Caller() common.Address {
|
||||||
return c.CallerAddress
|
return c.caller
|
||||||
}
|
}
|
||||||
|
|
||||||
// UseGas attempts the use gas and subtracts it and returns true on success
|
// UseGas attempts the use gas and subtracts it and returns true on success
|
||||||
|
@ -186,7 +150,7 @@ func (c *Contract) RefundGas(gas uint64, logger *tracing.Hooks, reason tracing.G
|
||||||
|
|
||||||
// Address returns the contracts address
|
// Address returns the contracts address
|
||||||
func (c *Contract) Address() common.Address {
|
func (c *Contract) Address() common.Address {
|
||||||
return c.self.Address()
|
return c.address
|
||||||
}
|
}
|
||||||
|
|
||||||
// Value returns the contract's value (sent to it from it's caller)
|
// Value returns the contract's value (sent to it from it's caller)
|
||||||
|
@ -194,18 +158,8 @@ func (c *Contract) Value() *uint256.Int {
|
||||||
return c.value
|
return c.value
|
||||||
}
|
}
|
||||||
|
|
||||||
// SetCallCode sets the code of the contract and address of the backing data
|
// SetCallCode sets the code of the contract,
|
||||||
// object
|
func (c *Contract) SetCallCode(hash common.Hash, code []byte) {
|
||||||
func (c *Contract) SetCallCode(addr *common.Address, hash common.Hash, code []byte) {
|
|
||||||
c.Code = code
|
c.Code = code
|
||||||
c.CodeHash = hash
|
c.CodeHash = hash
|
||||||
c.CodeAddr = addr
|
|
||||||
}
|
|
||||||
|
|
||||||
// SetCodeOptionalHash can be used to provide code, but it's optional to provide hash.
|
|
||||||
// In case hash is not provided, the jumpdest analysis will not be saved to the parent context
|
|
||||||
func (c *Contract) SetCodeOptionalHash(addr *common.Address, codeAndHash *codeAndHash) {
|
|
||||||
c.Code = codeAndHash.code
|
|
||||||
c.CodeHash = codeAndHash.hash
|
|
||||||
c.CodeAddr = addr
|
|
||||||
}
|
}
|
||||||
|
|
|
@ -338,13 +338,9 @@ func opExtCodeCopyEIP4762(pc *uint64, interpreter *EVMInterpreter, scope *ScopeC
|
||||||
}
|
}
|
||||||
addr := common.Address(a.Bytes20())
|
addr := common.Address(a.Bytes20())
|
||||||
code := interpreter.evm.StateDB.GetCode(addr)
|
code := interpreter.evm.StateDB.GetCode(addr)
|
||||||
contract := &Contract{
|
|
||||||
Code: code,
|
|
||||||
self: AccountRef(addr),
|
|
||||||
}
|
|
||||||
paddedCodeCopy, copyOffset, nonPaddedCopyLength := getDataAndAdjustedBounds(code, uint64CodeOffset, length.Uint64())
|
paddedCodeCopy, copyOffset, nonPaddedCopyLength := getDataAndAdjustedBounds(code, uint64CodeOffset, length.Uint64())
|
||||||
if !contract.IsSystemCall {
|
if !scope.Contract.IsSystemCall {
|
||||||
statelessGas := interpreter.evm.AccessEvents.CodeChunksRangeGas(addr, copyOffset, nonPaddedCopyLength, uint64(len(contract.Code)), false)
|
statelessGas := interpreter.evm.AccessEvents.CodeChunksRangeGas(addr, copyOffset, nonPaddedCopyLength, uint64(len(code)), false)
|
||||||
if !scope.Contract.UseGas(statelessGas, interpreter.evm.Config.Tracer, tracing.GasChangeUnspecified) {
|
if !scope.Contract.UseGas(statelessGas, interpreter.evm.Config.Tracer, tracing.GasChangeUnspecified) {
|
||||||
scope.Contract.Gas = 0
|
scope.Contract.Gas = 0
|
||||||
return nil, ErrOutOfGas
|
return nil, ErrOutOfGas
|
||||||
|
|
130
core/vm/evm.go
130
core/vm/evm.go
|
@ -91,29 +91,40 @@ type EVM struct {
|
||||||
// Context provides auxiliary blockchain related information
|
// Context provides auxiliary blockchain related information
|
||||||
Context BlockContext
|
Context BlockContext
|
||||||
TxContext
|
TxContext
|
||||||
|
|
||||||
// StateDB gives access to the underlying state
|
// StateDB gives access to the underlying state
|
||||||
StateDB StateDB
|
StateDB StateDB
|
||||||
// Depth is the current call stack
|
|
||||||
|
// depth is the current call stack
|
||||||
depth int
|
depth int
|
||||||
|
|
||||||
// chainConfig contains information about the current chain
|
// chainConfig contains information about the current chain
|
||||||
chainConfig *params.ChainConfig
|
chainConfig *params.ChainConfig
|
||||||
|
|
||||||
// chain rules contains the chain rules for the current epoch
|
// chain rules contains the chain rules for the current epoch
|
||||||
chainRules params.Rules
|
chainRules params.Rules
|
||||||
// virtual machine configuration options used to initialise the
|
|
||||||
// evm.
|
// virtual machine configuration options used to initialise the evm
|
||||||
Config Config
|
Config Config
|
||||||
// global (to this context) ethereum virtual machine
|
|
||||||
// used throughout the execution of the tx.
|
// global (to this context) ethereum virtual machine used throughout
|
||||||
|
// the execution of the tx
|
||||||
interpreter *EVMInterpreter
|
interpreter *EVMInterpreter
|
||||||
|
|
||||||
// abort is used to abort the EVM calling operations
|
// abort is used to abort the EVM calling operations
|
||||||
abort atomic.Bool
|
abort atomic.Bool
|
||||||
|
|
||||||
// callGasTemp holds the gas available for the current call. This is needed because the
|
// callGasTemp holds the gas available for the current call. This is needed because the
|
||||||
// available gas is calculated in gasCall* according to the 63/64 rule and later
|
// available gas is calculated in gasCall* according to the 63/64 rule and later
|
||||||
// applied in opCall*.
|
// applied in opCall*.
|
||||||
callGasTemp uint64
|
callGasTemp uint64
|
||||||
|
|
||||||
// precompiles holds the precompiled contracts for the current epoch
|
// precompiles holds the precompiled contracts for the current epoch
|
||||||
precompiles map[common.Address]PrecompiledContract
|
precompiles map[common.Address]PrecompiledContract
|
||||||
|
|
||||||
|
// jumpDests is the aggregated result of JUMPDEST analysis made through
|
||||||
|
// the life cycle of EVM.
|
||||||
|
jumpDests map[common.Hash]bitvec
|
||||||
}
|
}
|
||||||
|
|
||||||
// NewEVM constructs an EVM instance with the supplied block context, state
|
// NewEVM constructs an EVM instance with the supplied block context, state
|
||||||
|
@ -127,6 +138,7 @@ func NewEVM(blockCtx BlockContext, statedb StateDB, chainConfig *params.ChainCon
|
||||||
Config: config,
|
Config: config,
|
||||||
chainConfig: chainConfig,
|
chainConfig: chainConfig,
|
||||||
chainRules: chainConfig.Rules(blockCtx.BlockNumber, blockCtx.Random != nil, blockCtx.Time),
|
chainRules: chainConfig.Rules(blockCtx.BlockNumber, blockCtx.Random != nil, blockCtx.Time),
|
||||||
|
jumpDests: make(map[common.Hash]bitvec),
|
||||||
}
|
}
|
||||||
evm.precompiles = activePrecompiledContracts(evm.chainRules)
|
evm.precompiles = activePrecompiledContracts(evm.chainRules)
|
||||||
evm.interpreter = NewEVMInterpreter(evm)
|
evm.interpreter = NewEVMInterpreter(evm)
|
||||||
|
@ -165,18 +177,18 @@ func (evm *EVM) Interpreter() *EVMInterpreter {
|
||||||
return evm.interpreter
|
return evm.interpreter
|
||||||
}
|
}
|
||||||
|
|
||||||
func isSystemCall(caller ContractRef) bool {
|
func isSystemCall(caller common.Address) bool {
|
||||||
return caller.Address() == params.SystemAddress
|
return caller == params.SystemAddress
|
||||||
}
|
}
|
||||||
|
|
||||||
// Call executes the contract associated with the addr with the given input as
|
// Call executes the contract associated with the addr with the given input as
|
||||||
// parameters. It also handles any necessary value transfer required and takse
|
// parameters. It also handles any necessary value transfer required and takse
|
||||||
// the necessary steps to create accounts and reverses the state in case of an
|
// the necessary steps to create accounts and reverses the state in case of an
|
||||||
// execution error or failed value transfer.
|
// execution error or failed value transfer.
|
||||||
func (evm *EVM) Call(caller ContractRef, addr common.Address, input []byte, gas uint64, value *uint256.Int) (ret []byte, leftOverGas uint64, err error) {
|
func (evm *EVM) Call(caller common.Address, addr common.Address, input []byte, gas uint64, value *uint256.Int) (ret []byte, leftOverGas uint64, err error) {
|
||||||
// Capture the tracer start/end events in debug mode
|
// Capture the tracer start/end events in debug mode
|
||||||
if evm.Config.Tracer != nil {
|
if evm.Config.Tracer != nil {
|
||||||
evm.captureBegin(evm.depth, CALL, caller.Address(), addr, input, gas, value.ToBig())
|
evm.captureBegin(evm.depth, CALL, caller, addr, input, gas, value.ToBig())
|
||||||
defer func(startGas uint64) {
|
defer func(startGas uint64) {
|
||||||
evm.captureEnd(evm.depth, startGas, leftOverGas, ret, err)
|
evm.captureEnd(evm.depth, startGas, leftOverGas, ret, err)
|
||||||
}(gas)
|
}(gas)
|
||||||
|
@ -186,7 +198,7 @@ func (evm *EVM) Call(caller ContractRef, addr common.Address, input []byte, gas
|
||||||
return nil, gas, ErrDepth
|
return nil, gas, ErrDepth
|
||||||
}
|
}
|
||||||
// Fail if we're trying to transfer more than the available balance
|
// Fail if we're trying to transfer more than the available balance
|
||||||
if !value.IsZero() && !evm.Context.CanTransfer(evm.StateDB, caller.Address(), value) {
|
if !value.IsZero() && !evm.Context.CanTransfer(evm.StateDB, caller, value) {
|
||||||
return nil, gas, ErrInsufficientBalance
|
return nil, gas, ErrInsufficientBalance
|
||||||
}
|
}
|
||||||
snapshot := evm.StateDB.Snapshot()
|
snapshot := evm.StateDB.Snapshot()
|
||||||
|
@ -209,23 +221,20 @@ func (evm *EVM) Call(caller ContractRef, addr common.Address, input []byte, gas
|
||||||
}
|
}
|
||||||
evm.StateDB.CreateAccount(addr)
|
evm.StateDB.CreateAccount(addr)
|
||||||
}
|
}
|
||||||
evm.Context.Transfer(evm.StateDB, caller.Address(), addr, value)
|
evm.Context.Transfer(evm.StateDB, caller, addr, value)
|
||||||
|
|
||||||
if isPrecompile {
|
if isPrecompile {
|
||||||
ret, gas, err = RunPrecompiledContract(p, input, gas, evm.Config.Tracer)
|
ret, gas, err = RunPrecompiledContract(p, input, gas, evm.Config.Tracer)
|
||||||
} else {
|
} else {
|
||||||
// Initialise a new contract and set the code that is to be used by the EVM.
|
// Initialise a new contract and set the code that is to be used by the EVM.
|
||||||
// The contract is a scoped environment for this execution context only.
|
|
||||||
code := evm.resolveCode(addr)
|
code := evm.resolveCode(addr)
|
||||||
if len(code) == 0 {
|
if len(code) == 0 {
|
||||||
ret, err = nil, nil // gas is unchanged
|
ret, err = nil, nil // gas is unchanged
|
||||||
} else {
|
} else {
|
||||||
addrCopy := addr
|
// The contract is a scoped environment for this execution context only.
|
||||||
// If the account has no code, we can abort here
|
contract := NewContract(caller, addr, value, gas, evm.jumpDests)
|
||||||
// The depth-check is already done, and precompiles handled above
|
|
||||||
contract := NewContract(caller, AccountRef(addrCopy), value, gas)
|
|
||||||
contract.IsSystemCall = isSystemCall(caller)
|
contract.IsSystemCall = isSystemCall(caller)
|
||||||
contract.SetCallCode(&addrCopy, evm.resolveCodeHash(addrCopy), code)
|
contract.SetCallCode(evm.resolveCodeHash(addr), code)
|
||||||
ret, err = evm.interpreter.Run(contract, input, false)
|
ret, err = evm.interpreter.Run(contract, input, false)
|
||||||
gas = contract.Gas
|
gas = contract.Gas
|
||||||
}
|
}
|
||||||
|
@ -256,10 +265,10 @@ func (evm *EVM) Call(caller ContractRef, addr common.Address, input []byte, gas
|
||||||
//
|
//
|
||||||
// CallCode differs from Call in the sense that it executes the given address'
|
// CallCode differs from Call in the sense that it executes the given address'
|
||||||
// code with the caller as context.
|
// code with the caller as context.
|
||||||
func (evm *EVM) CallCode(caller ContractRef, addr common.Address, input []byte, gas uint64, value *uint256.Int) (ret []byte, leftOverGas uint64, err error) {
|
func (evm *EVM) CallCode(caller common.Address, addr common.Address, input []byte, gas uint64, value *uint256.Int) (ret []byte, leftOverGas uint64, err error) {
|
||||||
// Invoke tracer hooks that signal entering/exiting a call frame
|
// Invoke tracer hooks that signal entering/exiting a call frame
|
||||||
if evm.Config.Tracer != nil {
|
if evm.Config.Tracer != nil {
|
||||||
evm.captureBegin(evm.depth, CALLCODE, caller.Address(), addr, input, gas, value.ToBig())
|
evm.captureBegin(evm.depth, CALLCODE, caller, addr, input, gas, value.ToBig())
|
||||||
defer func(startGas uint64) {
|
defer func(startGas uint64) {
|
||||||
evm.captureEnd(evm.depth, startGas, leftOverGas, ret, err)
|
evm.captureEnd(evm.depth, startGas, leftOverGas, ret, err)
|
||||||
}(gas)
|
}(gas)
|
||||||
|
@ -272,7 +281,7 @@ func (evm *EVM) CallCode(caller ContractRef, addr common.Address, input []byte,
|
||||||
// Note although it's noop to transfer X ether to caller itself. But
|
// Note although it's noop to transfer X ether to caller itself. But
|
||||||
// if caller doesn't have enough balance, it would be an error to allow
|
// if caller doesn't have enough balance, it would be an error to allow
|
||||||
// over-charging itself. So the check here is necessary.
|
// over-charging itself. So the check here is necessary.
|
||||||
if !evm.Context.CanTransfer(evm.StateDB, caller.Address(), value) {
|
if !evm.Context.CanTransfer(evm.StateDB, caller, value) {
|
||||||
return nil, gas, ErrInsufficientBalance
|
return nil, gas, ErrInsufficientBalance
|
||||||
}
|
}
|
||||||
var snapshot = evm.StateDB.Snapshot()
|
var snapshot = evm.StateDB.Snapshot()
|
||||||
|
@ -281,11 +290,10 @@ func (evm *EVM) CallCode(caller ContractRef, addr common.Address, input []byte,
|
||||||
if p, isPrecompile := evm.precompile(addr); isPrecompile {
|
if p, isPrecompile := evm.precompile(addr); isPrecompile {
|
||||||
ret, gas, err = RunPrecompiledContract(p, input, gas, evm.Config.Tracer)
|
ret, gas, err = RunPrecompiledContract(p, input, gas, evm.Config.Tracer)
|
||||||
} else {
|
} else {
|
||||||
addrCopy := addr
|
|
||||||
// Initialise a new contract and set the code that is to be used by the EVM.
|
// Initialise a new contract and set the code that is to be used by the EVM.
|
||||||
// The contract is a scoped environment for this execution context only.
|
// The contract is a scoped environment for this execution context only.
|
||||||
contract := NewContract(caller, AccountRef(caller.Address()), value, gas)
|
contract := NewContract(caller, caller, value, gas, evm.jumpDests)
|
||||||
contract.SetCallCode(&addrCopy, evm.resolveCodeHash(addrCopy), evm.resolveCode(addrCopy))
|
contract.SetCallCode(evm.resolveCodeHash(addr), evm.resolveCode(addr))
|
||||||
ret, err = evm.interpreter.Run(contract, input, false)
|
ret, err = evm.interpreter.Run(contract, input, false)
|
||||||
gas = contract.Gas
|
gas = contract.Gas
|
||||||
}
|
}
|
||||||
|
@ -295,7 +303,6 @@ func (evm *EVM) CallCode(caller ContractRef, addr common.Address, input []byte,
|
||||||
if evm.Config.Tracer != nil && evm.Config.Tracer.OnGasChange != nil {
|
if evm.Config.Tracer != nil && evm.Config.Tracer.OnGasChange != nil {
|
||||||
evm.Config.Tracer.OnGasChange(gas, 0, tracing.GasChangeCallFailedExecution)
|
evm.Config.Tracer.OnGasChange(gas, 0, tracing.GasChangeCallFailedExecution)
|
||||||
}
|
}
|
||||||
|
|
||||||
gas = 0
|
gas = 0
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -307,14 +314,11 @@ func (evm *EVM) CallCode(caller ContractRef, addr common.Address, input []byte,
|
||||||
//
|
//
|
||||||
// DelegateCall differs from CallCode in the sense that it executes the given address'
|
// DelegateCall differs from CallCode in the sense that it executes the given address'
|
||||||
// code with the caller as context and the caller is set to the caller of the caller.
|
// code with the caller as context and the caller is set to the caller of the caller.
|
||||||
func (evm *EVM) DelegateCall(caller ContractRef, addr common.Address, input []byte, gas uint64) (ret []byte, leftOverGas uint64, err error) {
|
func (evm *EVM) DelegateCall(originCaller common.Address, caller common.Address, addr common.Address, input []byte, gas uint64, value *uint256.Int) (ret []byte, leftOverGas uint64, err error) {
|
||||||
// Invoke tracer hooks that signal entering/exiting a call frame
|
// Invoke tracer hooks that signal entering/exiting a call frame
|
||||||
if evm.Config.Tracer != nil {
|
if evm.Config.Tracer != nil {
|
||||||
// NOTE: caller must, at all times be a contract. It should never happen
|
|
||||||
// that caller is something other than a Contract.
|
|
||||||
parent := caller.(*Contract)
|
|
||||||
// DELEGATECALL inherits value from parent call
|
// DELEGATECALL inherits value from parent call
|
||||||
evm.captureBegin(evm.depth, DELEGATECALL, caller.Address(), addr, input, gas, parent.value.ToBig())
|
evm.captureBegin(evm.depth, DELEGATECALL, caller, addr, input, gas, value.ToBig())
|
||||||
defer func(startGas uint64) {
|
defer func(startGas uint64) {
|
||||||
evm.captureEnd(evm.depth, startGas, leftOverGas, ret, err)
|
evm.captureEnd(evm.depth, startGas, leftOverGas, ret, err)
|
||||||
}(gas)
|
}(gas)
|
||||||
|
@ -329,10 +333,11 @@ func (evm *EVM) DelegateCall(caller ContractRef, addr common.Address, input []by
|
||||||
if p, isPrecompile := evm.precompile(addr); isPrecompile {
|
if p, isPrecompile := evm.precompile(addr); isPrecompile {
|
||||||
ret, gas, err = RunPrecompiledContract(p, input, gas, evm.Config.Tracer)
|
ret, gas, err = RunPrecompiledContract(p, input, gas, evm.Config.Tracer)
|
||||||
} else {
|
} else {
|
||||||
addrCopy := addr
|
|
||||||
// Initialise a new contract and make initialise the delegate values
|
// Initialise a new contract and make initialise the delegate values
|
||||||
contract := NewContract(caller, AccountRef(caller.Address()), nil, gas).AsDelegate()
|
//
|
||||||
contract.SetCallCode(&addrCopy, evm.resolveCodeHash(addrCopy), evm.resolveCode(addrCopy))
|
// Note: The value refers to the original value from the parent call.
|
||||||
|
contract := NewContract(originCaller, caller, value, gas, evm.jumpDests)
|
||||||
|
contract.SetCallCode(evm.resolveCodeHash(addr), evm.resolveCode(addr))
|
||||||
ret, err = evm.interpreter.Run(contract, input, false)
|
ret, err = evm.interpreter.Run(contract, input, false)
|
||||||
gas = contract.Gas
|
gas = contract.Gas
|
||||||
}
|
}
|
||||||
|
@ -352,10 +357,10 @@ func (evm *EVM) DelegateCall(caller ContractRef, addr common.Address, input []by
|
||||||
// as parameters while disallowing any modifications to the state during the call.
|
// as parameters while disallowing any modifications to the state during the call.
|
||||||
// Opcodes that attempt to perform such modifications will result in exceptions
|
// Opcodes that attempt to perform such modifications will result in exceptions
|
||||||
// instead of performing the modifications.
|
// instead of performing the modifications.
|
||||||
func (evm *EVM) StaticCall(caller ContractRef, addr common.Address, input []byte, gas uint64) (ret []byte, leftOverGas uint64, err error) {
|
func (evm *EVM) StaticCall(caller common.Address, addr common.Address, input []byte, gas uint64) (ret []byte, leftOverGas uint64, err error) {
|
||||||
// Invoke tracer hooks that signal entering/exiting a call frame
|
// Invoke tracer hooks that signal entering/exiting a call frame
|
||||||
if evm.Config.Tracer != nil {
|
if evm.Config.Tracer != nil {
|
||||||
evm.captureBegin(evm.depth, STATICCALL, caller.Address(), addr, input, gas, nil)
|
evm.captureBegin(evm.depth, STATICCALL, caller, addr, input, gas, nil)
|
||||||
defer func(startGas uint64) {
|
defer func(startGas uint64) {
|
||||||
evm.captureEnd(evm.depth, startGas, leftOverGas, ret, err)
|
evm.captureEnd(evm.depth, startGas, leftOverGas, ret, err)
|
||||||
}(gas)
|
}(gas)
|
||||||
|
@ -380,14 +385,11 @@ func (evm *EVM) StaticCall(caller ContractRef, addr common.Address, input []byte
|
||||||
if p, isPrecompile := evm.precompile(addr); isPrecompile {
|
if p, isPrecompile := evm.precompile(addr); isPrecompile {
|
||||||
ret, gas, err = RunPrecompiledContract(p, input, gas, evm.Config.Tracer)
|
ret, gas, err = RunPrecompiledContract(p, input, gas, evm.Config.Tracer)
|
||||||
} else {
|
} else {
|
||||||
// At this point, we use a copy of address. If we don't, the go compiler will
|
|
||||||
// leak the 'contract' to the outer scope, and make allocation for 'contract'
|
|
||||||
// even if the actual execution ends on RunPrecompiled above.
|
|
||||||
addrCopy := addr
|
|
||||||
// Initialise a new contract and set the code that is to be used by the EVM.
|
// Initialise a new contract and set the code that is to be used by the EVM.
|
||||||
// The contract is a scoped environment for this execution context only.
|
// The contract is a scoped environment for this execution context only.
|
||||||
contract := NewContract(caller, AccountRef(addrCopy), new(uint256.Int), gas)
|
contract := NewContract(caller, addr, new(uint256.Int), gas, evm.jumpDests)
|
||||||
contract.SetCallCode(&addrCopy, evm.resolveCodeHash(addrCopy), evm.resolveCode(addrCopy))
|
contract.SetCallCode(evm.resolveCodeHash(addr), evm.resolveCode(addr))
|
||||||
|
|
||||||
// When an error was returned by the EVM or when setting the creation code
|
// When an error was returned by the EVM or when setting the creation code
|
||||||
// above we revert to the snapshot and consume any gas remaining. Additionally
|
// above we revert to the snapshot and consume any gas remaining. Additionally
|
||||||
// when we're in Homestead this also counts for code storage gas errors.
|
// when we're in Homestead this also counts for code storage gas errors.
|
||||||
|
@ -407,22 +409,10 @@ func (evm *EVM) StaticCall(caller ContractRef, addr common.Address, input []byte
|
||||||
return ret, gas, err
|
return ret, gas, err
|
||||||
}
|
}
|
||||||
|
|
||||||
type codeAndHash struct {
|
|
||||||
code []byte
|
|
||||||
hash common.Hash
|
|
||||||
}
|
|
||||||
|
|
||||||
func (c *codeAndHash) Hash() common.Hash {
|
|
||||||
if c.hash == (common.Hash{}) {
|
|
||||||
c.hash = crypto.Keccak256Hash(c.code)
|
|
||||||
}
|
|
||||||
return c.hash
|
|
||||||
}
|
|
||||||
|
|
||||||
// create creates a new contract using code as deployment code.
|
// create creates a new contract using code as deployment code.
|
||||||
func (evm *EVM) create(caller ContractRef, codeAndHash *codeAndHash, gas uint64, value *uint256.Int, address common.Address, typ OpCode) (ret []byte, createAddress common.Address, leftOverGas uint64, err error) {
|
func (evm *EVM) create(caller common.Address, code []byte, gas uint64, value *uint256.Int, address common.Address, typ OpCode) (ret []byte, createAddress common.Address, leftOverGas uint64, err error) {
|
||||||
if evm.Config.Tracer != nil {
|
if evm.Config.Tracer != nil {
|
||||||
evm.captureBegin(evm.depth, typ, caller.Address(), address, codeAndHash.code, gas, value.ToBig())
|
evm.captureBegin(evm.depth, typ, caller, address, code, gas, value.ToBig())
|
||||||
defer func(startGas uint64) {
|
defer func(startGas uint64) {
|
||||||
evm.captureEnd(evm.depth, startGas, leftOverGas, ret, err)
|
evm.captureEnd(evm.depth, startGas, leftOverGas, ret, err)
|
||||||
}(gas)
|
}(gas)
|
||||||
|
@ -432,14 +422,14 @@ func (evm *EVM) create(caller ContractRef, codeAndHash *codeAndHash, gas uint64,
|
||||||
if evm.depth > int(params.CallCreateDepth) {
|
if evm.depth > int(params.CallCreateDepth) {
|
||||||
return nil, common.Address{}, gas, ErrDepth
|
return nil, common.Address{}, gas, ErrDepth
|
||||||
}
|
}
|
||||||
if !evm.Context.CanTransfer(evm.StateDB, caller.Address(), value) {
|
if !evm.Context.CanTransfer(evm.StateDB, caller, value) {
|
||||||
return nil, common.Address{}, gas, ErrInsufficientBalance
|
return nil, common.Address{}, gas, ErrInsufficientBalance
|
||||||
}
|
}
|
||||||
nonce := evm.StateDB.GetNonce(caller.Address())
|
nonce := evm.StateDB.GetNonce(caller)
|
||||||
if nonce+1 < nonce {
|
if nonce+1 < nonce {
|
||||||
return nil, common.Address{}, gas, ErrNonceUintOverflow
|
return nil, common.Address{}, gas, ErrNonceUintOverflow
|
||||||
}
|
}
|
||||||
evm.StateDB.SetNonce(caller.Address(), nonce+1, tracing.NonceChangeContractCreator)
|
evm.StateDB.SetNonce(caller, nonce+1, tracing.NonceChangeContractCreator)
|
||||||
|
|
||||||
// Charge the contract creation init gas in verkle mode
|
// Charge the contract creation init gas in verkle mode
|
||||||
if evm.chainRules.IsEIP4762 {
|
if evm.chainRules.IsEIP4762 {
|
||||||
|
@ -500,15 +490,18 @@ func (evm *EVM) create(caller ContractRef, codeAndHash *codeAndHash, gas uint64,
|
||||||
}
|
}
|
||||||
gas = gas - statelessGas
|
gas = gas - statelessGas
|
||||||
}
|
}
|
||||||
evm.Context.Transfer(evm.StateDB, caller.Address(), address, value)
|
evm.Context.Transfer(evm.StateDB, caller, address, value)
|
||||||
|
|
||||||
// Initialise a new contract and set the code that is to be used by the EVM.
|
// Initialise a new contract and set the code that is to be used by the EVM.
|
||||||
// The contract is a scoped environment for this execution context only.
|
// The contract is a scoped environment for this execution context only.
|
||||||
contract := NewContract(caller, AccountRef(address), value, gas)
|
contract := NewContract(caller, address, value, gas, evm.jumpDests)
|
||||||
contract.SetCodeOptionalHash(&address, codeAndHash)
|
|
||||||
|
// Explicitly set the code to a null hash to prevent caching of jump analysis
|
||||||
|
// for the initialization code.
|
||||||
|
contract.SetCallCode(common.Hash{}, code)
|
||||||
contract.IsDeployment = true
|
contract.IsDeployment = true
|
||||||
|
|
||||||
ret, err = evm.initNewContract(contract, address, value)
|
ret, err = evm.initNewContract(contract, address)
|
||||||
if err != nil && (evm.chainRules.IsHomestead || err != ErrCodeStoreOutOfGas) {
|
if err != nil && (evm.chainRules.IsHomestead || err != ErrCodeStoreOutOfGas) {
|
||||||
evm.StateDB.RevertToSnapshot(snapshot)
|
evm.StateDB.RevertToSnapshot(snapshot)
|
||||||
if err != ErrExecutionReverted {
|
if err != ErrExecutionReverted {
|
||||||
|
@ -520,7 +513,7 @@ func (evm *EVM) create(caller ContractRef, codeAndHash *codeAndHash, gas uint64,
|
||||||
|
|
||||||
// initNewContract runs a new contract's creation code, performs checks on the
|
// initNewContract runs a new contract's creation code, performs checks on the
|
||||||
// resulting code that is to be deployed, and consumes necessary gas.
|
// resulting code that is to be deployed, and consumes necessary gas.
|
||||||
func (evm *EVM) initNewContract(contract *Contract, address common.Address, value *uint256.Int) ([]byte, error) {
|
func (evm *EVM) initNewContract(contract *Contract, address common.Address) ([]byte, error) {
|
||||||
ret, err := evm.interpreter.Run(contract, nil, false)
|
ret, err := evm.interpreter.Run(contract, nil, false)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return ret, err
|
return ret, err
|
||||||
|
@ -552,19 +545,18 @@ func (evm *EVM) initNewContract(contract *Contract, address common.Address, valu
|
||||||
}
|
}
|
||||||
|
|
||||||
// Create creates a new contract using code as deployment code.
|
// Create creates a new contract using code as deployment code.
|
||||||
func (evm *EVM) Create(caller ContractRef, code []byte, gas uint64, value *uint256.Int) (ret []byte, contractAddr common.Address, leftOverGas uint64, err error) {
|
func (evm *EVM) Create(caller common.Address, code []byte, gas uint64, value *uint256.Int) (ret []byte, contractAddr common.Address, leftOverGas uint64, err error) {
|
||||||
contractAddr = crypto.CreateAddress(caller.Address(), evm.StateDB.GetNonce(caller.Address()))
|
contractAddr = crypto.CreateAddress(caller, evm.StateDB.GetNonce(caller))
|
||||||
return evm.create(caller, &codeAndHash{code: code}, gas, value, contractAddr, CREATE)
|
return evm.create(caller, code, gas, value, contractAddr, CREATE)
|
||||||
}
|
}
|
||||||
|
|
||||||
// Create2 creates a new contract using code as deployment code.
|
// Create2 creates a new contract using code as deployment code.
|
||||||
//
|
//
|
||||||
// The different between Create2 with Create is Create2 uses keccak256(0xff ++ msg.sender ++ salt ++ keccak256(init_code))[12:]
|
// The different between Create2 with Create is Create2 uses keccak256(0xff ++ msg.sender ++ salt ++ keccak256(init_code))[12:]
|
||||||
// instead of the usual sender-and-nonce-hash as the address where the contract is initialized at.
|
// instead of the usual sender-and-nonce-hash as the address where the contract is initialized at.
|
||||||
func (evm *EVM) Create2(caller ContractRef, code []byte, gas uint64, endowment *uint256.Int, salt *uint256.Int) (ret []byte, contractAddr common.Address, leftOverGas uint64, err error) {
|
func (evm *EVM) Create2(caller common.Address, code []byte, gas uint64, endowment *uint256.Int, salt *uint256.Int) (ret []byte, contractAddr common.Address, leftOverGas uint64, err error) {
|
||||||
codeAndHash := &codeAndHash{code: code}
|
contractAddr = crypto.CreateAddress2(caller, salt.Bytes32(), crypto.Keccak256(code))
|
||||||
contractAddr = crypto.CreateAddress2(caller.Address(), salt.Bytes32(), codeAndHash.Hash().Bytes())
|
return evm.create(caller, code, gas, endowment, contractAddr, CREATE2)
|
||||||
return evm.create(caller, codeAndHash, gas, endowment, contractAddr, CREATE2)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// resolveCode returns the code associated with the provided account. After
|
// resolveCode returns the code associated with the provided account. After
|
||||||
|
|
|
@ -97,7 +97,7 @@ func TestEIP2200(t *testing.T) {
|
||||||
}
|
}
|
||||||
evm := NewEVM(vmctx, statedb, params.AllEthashProtocolChanges, Config{ExtraEips: []int{2200}})
|
evm := NewEVM(vmctx, statedb, params.AllEthashProtocolChanges, Config{ExtraEips: []int{2200}})
|
||||||
|
|
||||||
_, gas, err := evm.Call(AccountRef(common.Address{}), address, nil, tt.gaspool, new(uint256.Int))
|
_, gas, err := evm.Call(common.Address{}, address, nil, tt.gaspool, new(uint256.Int))
|
||||||
if !errors.Is(err, tt.failure) {
|
if !errors.Is(err, tt.failure) {
|
||||||
t.Errorf("test %d: failure mismatch: have %v, want %v", i, err, tt.failure)
|
t.Errorf("test %d: failure mismatch: have %v, want %v", i, err, tt.failure)
|
||||||
}
|
}
|
||||||
|
@ -153,7 +153,7 @@ func TestCreateGas(t *testing.T) {
|
||||||
|
|
||||||
evm := NewEVM(vmctx, statedb, params.AllEthashProtocolChanges, config)
|
evm := NewEVM(vmctx, statedb, params.AllEthashProtocolChanges, config)
|
||||||
var startGas = uint64(testGas)
|
var startGas = uint64(testGas)
|
||||||
ret, gas, err := evm.Call(AccountRef(common.Address{}), address, nil, startGas, new(uint256.Int))
|
ret, gas, err := evm.Call(common.Address{}, address, nil, startGas, new(uint256.Int))
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return false
|
return false
|
||||||
}
|
}
|
||||||
|
|
|
@ -677,7 +677,7 @@ func opCreate(pc *uint64, interpreter *EVMInterpreter, scope *ScopeContext) ([]b
|
||||||
|
|
||||||
scope.Contract.UseGas(gas, interpreter.evm.Config.Tracer, tracing.GasChangeCallContractCreation)
|
scope.Contract.UseGas(gas, interpreter.evm.Config.Tracer, tracing.GasChangeCallContractCreation)
|
||||||
|
|
||||||
res, addr, returnGas, suberr := interpreter.evm.Create(scope.Contract, input, gas, &value)
|
res, addr, returnGas, suberr := interpreter.evm.Create(scope.Contract.Address(), input, gas, &value)
|
||||||
// Push item on the stack based on the returned error. If the ruleset is
|
// Push item on the stack based on the returned error. If the ruleset is
|
||||||
// homestead we must check for CodeStoreOutOfGasError (homestead only
|
// homestead we must check for CodeStoreOutOfGasError (homestead only
|
||||||
// rule) and treat as an error, if the ruleset is frontier we must
|
// rule) and treat as an error, if the ruleset is frontier we must
|
||||||
|
@ -718,7 +718,7 @@ func opCreate2(pc *uint64, interpreter *EVMInterpreter, scope *ScopeContext) ([]
|
||||||
scope.Contract.UseGas(gas, interpreter.evm.Config.Tracer, tracing.GasChangeCallContractCreation2)
|
scope.Contract.UseGas(gas, interpreter.evm.Config.Tracer, tracing.GasChangeCallContractCreation2)
|
||||||
// reuse size int for stackvalue
|
// reuse size int for stackvalue
|
||||||
stackvalue := size
|
stackvalue := size
|
||||||
res, addr, returnGas, suberr := interpreter.evm.Create2(scope.Contract, input, gas,
|
res, addr, returnGas, suberr := interpreter.evm.Create2(scope.Contract.Address(), input, gas,
|
||||||
&endowment, &salt)
|
&endowment, &salt)
|
||||||
// Push item on the stack based on the returned error.
|
// Push item on the stack based on the returned error.
|
||||||
if suberr != nil {
|
if suberr != nil {
|
||||||
|
@ -755,7 +755,7 @@ func opCall(pc *uint64, interpreter *EVMInterpreter, scope *ScopeContext) ([]byt
|
||||||
if !value.IsZero() {
|
if !value.IsZero() {
|
||||||
gas += params.CallStipend
|
gas += params.CallStipend
|
||||||
}
|
}
|
||||||
ret, returnGas, err := interpreter.evm.Call(scope.Contract, toAddr, args, gas, &value)
|
ret, returnGas, err := interpreter.evm.Call(scope.Contract.Address(), toAddr, args, gas, &value)
|
||||||
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
temp.Clear()
|
temp.Clear()
|
||||||
|
@ -789,7 +789,7 @@ func opCallCode(pc *uint64, interpreter *EVMInterpreter, scope *ScopeContext) ([
|
||||||
gas += params.CallStipend
|
gas += params.CallStipend
|
||||||
}
|
}
|
||||||
|
|
||||||
ret, returnGas, err := interpreter.evm.CallCode(scope.Contract, toAddr, args, gas, &value)
|
ret, returnGas, err := interpreter.evm.CallCode(scope.Contract.Address(), toAddr, args, gas, &value)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
temp.Clear()
|
temp.Clear()
|
||||||
} else {
|
} else {
|
||||||
|
@ -818,7 +818,7 @@ func opDelegateCall(pc *uint64, interpreter *EVMInterpreter, scope *ScopeContext
|
||||||
// Get arguments from the memory.
|
// Get arguments from the memory.
|
||||||
args := scope.Memory.GetPtr(inOffset.Uint64(), inSize.Uint64())
|
args := scope.Memory.GetPtr(inOffset.Uint64(), inSize.Uint64())
|
||||||
|
|
||||||
ret, returnGas, err := interpreter.evm.DelegateCall(scope.Contract, toAddr, args, gas)
|
ret, returnGas, err := interpreter.evm.DelegateCall(scope.Contract.Caller(), scope.Contract.Address(), toAddr, args, gas, scope.Contract.value)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
temp.Clear()
|
temp.Clear()
|
||||||
} else {
|
} else {
|
||||||
|
@ -847,7 +847,7 @@ func opStaticCall(pc *uint64, interpreter *EVMInterpreter, scope *ScopeContext)
|
||||||
// Get arguments from the memory.
|
// Get arguments from the memory.
|
||||||
args := scope.Memory.GetPtr(inOffset.Uint64(), inSize.Uint64())
|
args := scope.Memory.GetPtr(inOffset.Uint64(), inSize.Uint64())
|
||||||
|
|
||||||
ret, returnGas, err := interpreter.evm.StaticCall(scope.Contract, toAddr, args, gas)
|
ret, returnGas, err := interpreter.evm.StaticCall(scope.Contract.Address(), toAddr, args, gas)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
temp.Clear()
|
temp.Clear()
|
||||||
} else {
|
} else {
|
||||||
|
|
|
@ -49,14 +49,6 @@ var alphabetSoup = "ABCDEF090807060504030201ffffffffffffffffffffffffffffffffffff
|
||||||
var commonParams []*twoOperandParams
|
var commonParams []*twoOperandParams
|
||||||
var twoOpMethods map[string]executionFunc
|
var twoOpMethods map[string]executionFunc
|
||||||
|
|
||||||
type contractRef struct {
|
|
||||||
addr common.Address
|
|
||||||
}
|
|
||||||
|
|
||||||
func (c contractRef) Address() common.Address {
|
|
||||||
return c.addr
|
|
||||||
}
|
|
||||||
|
|
||||||
func init() {
|
func init() {
|
||||||
// Params is a list of common edgecases that should be used for some common tests
|
// Params is a list of common edgecases that should be used for some common tests
|
||||||
params := []string{
|
params := []string{
|
||||||
|
@ -575,8 +567,7 @@ func TestOpTstore(t *testing.T) {
|
||||||
mem = NewMemory()
|
mem = NewMemory()
|
||||||
caller = common.Address{}
|
caller = common.Address{}
|
||||||
to = common.Address{1}
|
to = common.Address{1}
|
||||||
contractRef = contractRef{caller}
|
contract = NewContract(caller, to, new(uint256.Int), 0, nil)
|
||||||
contract = NewContract(contractRef, AccountRef(to), new(uint256.Int), 0)
|
|
||||||
scopeContext = ScopeContext{mem, stack, contract}
|
scopeContext = ScopeContext{mem, stack, contract}
|
||||||
value = common.Hex2Bytes("abcdef00000000000000abba000000000deaf000000c0de00100000000133700")
|
value = common.Hex2Bytes("abcdef00000000000000abba000000000deaf000000c0de00100000000133700")
|
||||||
)
|
)
|
||||||
|
|
|
@ -17,8 +17,6 @@
|
||||||
package vm
|
package vm
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"math/big"
|
|
||||||
|
|
||||||
"github.com/ethereum/go-ethereum/common"
|
"github.com/ethereum/go-ethereum/common"
|
||||||
"github.com/ethereum/go-ethereum/core/state"
|
"github.com/ethereum/go-ethereum/core/state"
|
||||||
"github.com/ethereum/go-ethereum/core/stateless"
|
"github.com/ethereum/go-ethereum/core/stateless"
|
||||||
|
@ -104,16 +102,3 @@ type StateDB interface {
|
||||||
// Finalise must be invoked at the end of a transaction
|
// Finalise must be invoked at the end of a transaction
|
||||||
Finalise(bool)
|
Finalise(bool)
|
||||||
}
|
}
|
||||||
|
|
||||||
// CallContext provides a basic interface for the EVM calling conventions. The EVM
|
|
||||||
// depends on this context being implemented for doing subcalls and initialising new EVM contracts.
|
|
||||||
type CallContext interface {
|
|
||||||
// Call calls another contract.
|
|
||||||
Call(env *EVM, me ContractRef, addr common.Address, data []byte, gas, value *big.Int) ([]byte, error)
|
|
||||||
// CallCode takes another contracts code and execute within our own context
|
|
||||||
CallCode(env *EVM, me ContractRef, addr common.Address, data []byte, gas, value *big.Int) ([]byte, error)
|
|
||||||
// DelegateCall is same as CallCode except sender and value is propagated from parent to child scope
|
|
||||||
DelegateCall(env *EVM, me ContractRef, addr common.Address, data []byte, gas *big.Int) ([]byte, error)
|
|
||||||
// Create creates a new contract
|
|
||||||
Create(env *EVM, me ContractRef, data []byte, gas, value *big.Int) ([]byte, common.Address, error)
|
|
||||||
}
|
|
||||||
|
|
|
@ -53,7 +53,7 @@ func TestLoopInterrupt(t *testing.T) {
|
||||||
timeout := make(chan bool)
|
timeout := make(chan bool)
|
||||||
|
|
||||||
go func(evm *EVM) {
|
go func(evm *EVM) {
|
||||||
_, _, err := evm.Call(AccountRef(common.Address{}), address, nil, math.MaxUint64, new(uint256.Int))
|
_, _, err := evm.Call(common.Address{}, address, nil, math.MaxUint64, new(uint256.Int))
|
||||||
errChannel <- err
|
errChannel <- err
|
||||||
}(evm)
|
}(evm)
|
||||||
|
|
||||||
|
|
|
@ -128,7 +128,6 @@ func Execute(code, input []byte, cfg *Config) ([]byte, *state.StateDB, error) {
|
||||||
var (
|
var (
|
||||||
address = common.BytesToAddress([]byte("contract"))
|
address = common.BytesToAddress([]byte("contract"))
|
||||||
vmenv = NewEnv(cfg)
|
vmenv = NewEnv(cfg)
|
||||||
sender = vm.AccountRef(cfg.Origin)
|
|
||||||
rules = cfg.ChainConfig.Rules(vmenv.Context.BlockNumber, vmenv.Context.Random != nil, vmenv.Context.Time)
|
rules = cfg.ChainConfig.Rules(vmenv.Context.BlockNumber, vmenv.Context.Random != nil, vmenv.Context.Time)
|
||||||
)
|
)
|
||||||
if cfg.EVMConfig.Tracer != nil && cfg.EVMConfig.Tracer.OnTxStart != nil {
|
if cfg.EVMConfig.Tracer != nil && cfg.EVMConfig.Tracer.OnTxStart != nil {
|
||||||
|
@ -143,7 +142,7 @@ func Execute(code, input []byte, cfg *Config) ([]byte, *state.StateDB, error) {
|
||||||
cfg.State.SetCode(address, code)
|
cfg.State.SetCode(address, code)
|
||||||
// Call the code with the given configuration.
|
// Call the code with the given configuration.
|
||||||
ret, leftOverGas, err := vmenv.Call(
|
ret, leftOverGas, err := vmenv.Call(
|
||||||
sender,
|
cfg.Origin,
|
||||||
common.BytesToAddress([]byte("contract")),
|
common.BytesToAddress([]byte("contract")),
|
||||||
input,
|
input,
|
||||||
cfg.GasLimit,
|
cfg.GasLimit,
|
||||||
|
@ -167,7 +166,6 @@ func Create(input []byte, cfg *Config) ([]byte, common.Address, uint64, error) {
|
||||||
}
|
}
|
||||||
var (
|
var (
|
||||||
vmenv = NewEnv(cfg)
|
vmenv = NewEnv(cfg)
|
||||||
sender = vm.AccountRef(cfg.Origin)
|
|
||||||
rules = cfg.ChainConfig.Rules(vmenv.Context.BlockNumber, vmenv.Context.Random != nil, vmenv.Context.Time)
|
rules = cfg.ChainConfig.Rules(vmenv.Context.BlockNumber, vmenv.Context.Random != nil, vmenv.Context.Time)
|
||||||
)
|
)
|
||||||
if cfg.EVMConfig.Tracer != nil && cfg.EVMConfig.Tracer.OnTxStart != nil {
|
if cfg.EVMConfig.Tracer != nil && cfg.EVMConfig.Tracer.OnTxStart != nil {
|
||||||
|
@ -179,7 +177,7 @@ func Create(input []byte, cfg *Config) ([]byte, common.Address, uint64, error) {
|
||||||
cfg.State.Prepare(rules, cfg.Origin, cfg.Coinbase, nil, vm.ActivePrecompiles(rules), nil)
|
cfg.State.Prepare(rules, cfg.Origin, cfg.Coinbase, nil, vm.ActivePrecompiles(rules), nil)
|
||||||
// Call the code with the given configuration.
|
// Call the code with the given configuration.
|
||||||
code, address, leftOverGas, err := vmenv.Create(
|
code, address, leftOverGas, err := vmenv.Create(
|
||||||
sender,
|
cfg.Origin,
|
||||||
input,
|
input,
|
||||||
cfg.GasLimit,
|
cfg.GasLimit,
|
||||||
uint256.MustFromBig(cfg.Value),
|
uint256.MustFromBig(cfg.Value),
|
||||||
|
@ -200,7 +198,6 @@ func Call(address common.Address, input []byte, cfg *Config) ([]byte, uint64, er
|
||||||
|
|
||||||
var (
|
var (
|
||||||
vmenv = NewEnv(cfg)
|
vmenv = NewEnv(cfg)
|
||||||
sender = vm.AccountRef(cfg.Origin)
|
|
||||||
statedb = cfg.State
|
statedb = cfg.State
|
||||||
rules = cfg.ChainConfig.Rules(vmenv.Context.BlockNumber, vmenv.Context.Random != nil, vmenv.Context.Time)
|
rules = cfg.ChainConfig.Rules(vmenv.Context.BlockNumber, vmenv.Context.Random != nil, vmenv.Context.Time)
|
||||||
)
|
)
|
||||||
|
@ -214,7 +211,7 @@ func Call(address common.Address, input []byte, cfg *Config) ([]byte, uint64, er
|
||||||
|
|
||||||
// Call the code with the given configuration.
|
// Call the code with the given configuration.
|
||||||
ret, leftOverGas, err := vmenv.Call(
|
ret, leftOverGas, err := vmenv.Call(
|
||||||
sender,
|
cfg.Origin,
|
||||||
address,
|
address,
|
||||||
input,
|
input,
|
||||||
cfg.GasLimit,
|
cfg.GasLimit,
|
||||||
|
|
|
@ -33,6 +33,8 @@ import (
|
||||||
"github.com/ethereum/go-ethereum/event"
|
"github.com/ethereum/go-ethereum/event"
|
||||||
"github.com/ethereum/go-ethereum/log"
|
"github.com/ethereum/go-ethereum/log"
|
||||||
"github.com/ethereum/go-ethereum/node"
|
"github.com/ethereum/go-ethereum/node"
|
||||||
|
"github.com/ethereum/go-ethereum/params"
|
||||||
|
"github.com/ethereum/go-ethereum/params/forks"
|
||||||
"github.com/ethereum/go-ethereum/rpc"
|
"github.com/ethereum/go-ethereum/rpc"
|
||||||
)
|
)
|
||||||
|
|
||||||
|
@ -95,6 +97,16 @@ type SimulatedBeacon struct {
|
||||||
lastBlockTime uint64
|
lastBlockTime uint64
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func payloadVersion(config *params.ChainConfig, time uint64) engine.PayloadVersion {
|
||||||
|
switch config.LatestFork(time) {
|
||||||
|
case forks.Prague, forks.Cancun:
|
||||||
|
return engine.PayloadV3
|
||||||
|
case forks.Paris, forks.Shanghai:
|
||||||
|
return engine.PayloadV2
|
||||||
|
}
|
||||||
|
panic("invalid fork, simulated beacon needs to be started post-merge")
|
||||||
|
}
|
||||||
|
|
||||||
// NewSimulatedBeacon constructs a new simulated beacon chain.
|
// NewSimulatedBeacon constructs a new simulated beacon chain.
|
||||||
func NewSimulatedBeacon(period uint64, eth *eth.Ethereum) (*SimulatedBeacon, error) {
|
func NewSimulatedBeacon(period uint64, eth *eth.Ethereum) (*SimulatedBeacon, error) {
|
||||||
block := eth.BlockChain().CurrentBlock()
|
block := eth.BlockChain().CurrentBlock()
|
||||||
|
@ -107,7 +119,8 @@ func NewSimulatedBeacon(period uint64, eth *eth.Ethereum) (*SimulatedBeacon, err
|
||||||
|
|
||||||
// if genesis block, send forkchoiceUpdated to trigger transition to PoS
|
// if genesis block, send forkchoiceUpdated to trigger transition to PoS
|
||||||
if block.Number.Sign() == 0 {
|
if block.Number.Sign() == 0 {
|
||||||
if _, err := engineAPI.ForkchoiceUpdatedV3(current, nil); err != nil {
|
version := payloadVersion(eth.BlockChain().Config(), block.Time)
|
||||||
|
if _, err := engineAPI.forkchoiceUpdated(current, nil, version, false); err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -171,6 +184,8 @@ func (c *SimulatedBeacon) sealBlock(withdrawals []*types.Withdrawal, timestamp u
|
||||||
return fmt.Errorf("failed to sync txpool: %w", err)
|
return fmt.Errorf("failed to sync txpool: %w", err)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
version := payloadVersion(c.eth.BlockChain().Config(), timestamp)
|
||||||
|
|
||||||
var random [32]byte
|
var random [32]byte
|
||||||
rand.Read(random[:])
|
rand.Read(random[:])
|
||||||
fcResponse, err := c.engineAPI.forkchoiceUpdated(c.curForkchoiceState, &engine.PayloadAttributes{
|
fcResponse, err := c.engineAPI.forkchoiceUpdated(c.curForkchoiceState, &engine.PayloadAttributes{
|
||||||
|
@ -179,7 +194,7 @@ func (c *SimulatedBeacon) sealBlock(withdrawals []*types.Withdrawal, timestamp u
|
||||||
Withdrawals: withdrawals,
|
Withdrawals: withdrawals,
|
||||||
Random: random,
|
Random: random,
|
||||||
BeaconRoot: &common.Hash{},
|
BeaconRoot: &common.Hash{},
|
||||||
}, engine.PayloadV3, false)
|
}, version, false)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
@ -204,8 +219,15 @@ func (c *SimulatedBeacon) sealBlock(withdrawals []*types.Withdrawal, timestamp u
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
var (
|
||||||
|
blobHashes []common.Hash
|
||||||
|
beaconRoot *common.Hash
|
||||||
|
requests [][]byte
|
||||||
|
)
|
||||||
|
// Compute post-shanghai fields
|
||||||
|
if version > engine.PayloadV2 {
|
||||||
// Independently calculate the blob hashes from sidecars.
|
// Independently calculate the blob hashes from sidecars.
|
||||||
blobHashes := make([]common.Hash, 0)
|
blobHashes = make([]common.Hash, 0)
|
||||||
if envelope.BlobsBundle != nil {
|
if envelope.BlobsBundle != nil {
|
||||||
hasher := sha256.New()
|
hasher := sha256.New()
|
||||||
for _, commit := range envelope.BlobsBundle.Commitments {
|
for _, commit := range envelope.BlobsBundle.Commitments {
|
||||||
|
@ -217,15 +239,19 @@ func (c *SimulatedBeacon) sealBlock(withdrawals []*types.Withdrawal, timestamp u
|
||||||
blobHashes = append(blobHashes, kzg4844.CalcBlobHashV1(hasher, &c))
|
blobHashes = append(blobHashes, kzg4844.CalcBlobHashV1(hasher, &c))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
beaconRoot = &common.Hash{}
|
||||||
|
requests = envelope.Requests
|
||||||
|
}
|
||||||
|
|
||||||
// Mark the payload as canon
|
// Mark the payload as canon
|
||||||
_, err = c.engineAPI.newPayload(*payload, blobHashes, &common.Hash{}, envelope.Requests, false)
|
_, err = c.engineAPI.newPayload(*payload, blobHashes, beaconRoot, requests, false)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
c.setCurrentState(payload.BlockHash, finalizedHash)
|
c.setCurrentState(payload.BlockHash, finalizedHash)
|
||||||
|
|
||||||
// Mark the block containing the payload as canonical
|
// Mark the block containing the payload as canonical
|
||||||
if _, err = c.engineAPI.ForkchoiceUpdatedV3(c.curForkchoiceState, nil); err != nil {
|
if _, err = c.engineAPI.forkchoiceUpdated(c.curForkchoiceState, nil, version, false); err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
c.lastBlockTime = payload.Timestamp
|
c.lastBlockTime = payload.Timestamp
|
||||||
|
|
|
@ -89,7 +89,7 @@ type TxPool interface {
|
||||||
}
|
}
|
||||||
|
|
||||||
// MakeProtocols constructs the P2P protocol definitions for `eth`.
|
// MakeProtocols constructs the P2P protocol definitions for `eth`.
|
||||||
func MakeProtocols(backend Backend, network uint64, dnsdisc enode.Iterator) []p2p.Protocol {
|
func MakeProtocols(backend Backend, network uint64, disc enode.Iterator) []p2p.Protocol {
|
||||||
protocols := make([]p2p.Protocol, 0, len(ProtocolVersions))
|
protocols := make([]p2p.Protocol, 0, len(ProtocolVersions))
|
||||||
for _, version := range ProtocolVersions {
|
for _, version := range ProtocolVersions {
|
||||||
protocols = append(protocols, p2p.Protocol{
|
protocols = append(protocols, p2p.Protocol{
|
||||||
|
@ -110,6 +110,7 @@ func MakeProtocols(backend Backend, network uint64, dnsdisc enode.Iterator) []p2
|
||||||
PeerInfo: func(id enode.ID) interface{} {
|
PeerInfo: func(id enode.ID) interface{} {
|
||||||
return backend.PeerInfo(id)
|
return backend.PeerInfo(id)
|
||||||
},
|
},
|
||||||
|
DialCandidates: disc,
|
||||||
Attributes: []enr.Entry{currentENREntry(backend.Chain())},
|
Attributes: []enr.Entry{currentENREntry(backend.Chain())},
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
|
@ -33,19 +33,6 @@ import (
|
||||||
"github.com/holiman/uint256"
|
"github.com/holiman/uint256"
|
||||||
)
|
)
|
||||||
|
|
||||||
type account struct{}
|
|
||||||
|
|
||||||
func (account) SubBalance(amount *big.Int) {}
|
|
||||||
func (account) AddBalance(amount *big.Int) {}
|
|
||||||
func (account) SetAddress(common.Address) {}
|
|
||||||
func (account) Value() *big.Int { return nil }
|
|
||||||
func (account) SetBalance(*uint256.Int) {}
|
|
||||||
func (account) SetNonce(uint64) {}
|
|
||||||
func (account) Balance() *uint256.Int { return nil }
|
|
||||||
func (account) Address() common.Address { return common.Address{} }
|
|
||||||
func (account) SetCode(common.Hash, []byte) {}
|
|
||||||
func (account) ForEachStorage(cb func(key, value common.Hash) bool) {}
|
|
||||||
|
|
||||||
type dummyStatedb struct {
|
type dummyStatedb struct {
|
||||||
state.StateDB
|
state.StateDB
|
||||||
}
|
}
|
||||||
|
@ -68,7 +55,7 @@ func runTrace(tracer *tracers.Tracer, vmctx *vmContext, chaincfg *params.ChainCo
|
||||||
gasLimit uint64 = 31000
|
gasLimit uint64 = 31000
|
||||||
startGas uint64 = 10000
|
startGas uint64 = 10000
|
||||||
value = uint256.NewInt(0)
|
value = uint256.NewInt(0)
|
||||||
contract = vm.NewContract(account{}, account{}, value, startGas)
|
contract = vm.NewContract(common.Address{}, common.Address{}, value, startGas, nil)
|
||||||
)
|
)
|
||||||
evm.SetTxContext(vmctx.txCtx)
|
evm.SetTxContext(vmctx.txCtx)
|
||||||
contract.Code = []byte{byte(vm.PUSH1), 0x1, byte(vm.PUSH1), 0x1, 0x0}
|
contract.Code = []byte{byte(vm.PUSH1), 0x1, byte(vm.PUSH1), 0x1, 0x0}
|
||||||
|
@ -190,7 +177,7 @@ func TestHaltBetweenSteps(t *testing.T) {
|
||||||
t.Fatal(err)
|
t.Fatal(err)
|
||||||
}
|
}
|
||||||
scope := &vm.ScopeContext{
|
scope := &vm.ScopeContext{
|
||||||
Contract: vm.NewContract(&account{}, &account{}, uint256.NewInt(0), 0),
|
Contract: vm.NewContract(common.Address{}, common.Address{}, uint256.NewInt(0), 0, nil),
|
||||||
}
|
}
|
||||||
evm := vm.NewEVM(vm.BlockContext{BlockNumber: big.NewInt(1)}, &dummyStatedb{}, chainConfig, vm.Config{Tracer: tracer.Hooks})
|
evm := vm.NewEVM(vm.BlockContext{BlockNumber: big.NewInt(1)}, &dummyStatedb{}, chainConfig, vm.Config{Tracer: tracer.Hooks})
|
||||||
evm.SetTxContext(vm.TxContext{GasPrice: big.NewInt(1)})
|
evm.SetTxContext(vm.TxContext{GasPrice: big.NewInt(1)})
|
||||||
|
@ -288,7 +275,7 @@ func TestEnterExit(t *testing.T) {
|
||||||
t.Fatal(err)
|
t.Fatal(err)
|
||||||
}
|
}
|
||||||
scope := &vm.ScopeContext{
|
scope := &vm.ScopeContext{
|
||||||
Contract: vm.NewContract(&account{}, &account{}, uint256.NewInt(0), 0),
|
Contract: vm.NewContract(common.Address{}, common.Address{}, uint256.NewInt(0), 0, nil),
|
||||||
}
|
}
|
||||||
tracer.OnEnter(1, byte(vm.CALL), scope.Contract.Caller(), scope.Contract.Address(), []byte{}, 1000, new(big.Int))
|
tracer.OnEnter(1, byte(vm.CALL), scope.Contract.Caller(), scope.Contract.Address(), []byte{}, 1000, new(big.Int))
|
||||||
tracer.OnExit(1, []byte{}, 400, nil, false)
|
tracer.OnExit(1, []byte{}, 400, nil, false)
|
||||||
|
|
|
@ -29,22 +29,6 @@ import (
|
||||||
"github.com/holiman/uint256"
|
"github.com/holiman/uint256"
|
||||||
)
|
)
|
||||||
|
|
||||||
type dummyContractRef struct {
|
|
||||||
calledForEach bool
|
|
||||||
}
|
|
||||||
|
|
||||||
func (dummyContractRef) Address() common.Address { return common.Address{} }
|
|
||||||
func (dummyContractRef) Value() *big.Int { return new(big.Int) }
|
|
||||||
func (dummyContractRef) SetCode(common.Hash, []byte) {}
|
|
||||||
func (d *dummyContractRef) ForEachStorage(callback func(key, value common.Hash) bool) {
|
|
||||||
d.calledForEach = true
|
|
||||||
}
|
|
||||||
func (d *dummyContractRef) SubBalance(amount *big.Int) {}
|
|
||||||
func (d *dummyContractRef) AddBalance(amount *big.Int) {}
|
|
||||||
func (d *dummyContractRef) SetBalance(*big.Int) {}
|
|
||||||
func (d *dummyContractRef) SetNonce(uint64) {}
|
|
||||||
func (d *dummyContractRef) Balance() *big.Int { return new(big.Int) }
|
|
||||||
|
|
||||||
type dummyStatedb struct {
|
type dummyStatedb struct {
|
||||||
state.StateDB
|
state.StateDB
|
||||||
}
|
}
|
||||||
|
@ -59,7 +43,7 @@ func TestStoreCapture(t *testing.T) {
|
||||||
var (
|
var (
|
||||||
logger = NewStructLogger(nil)
|
logger = NewStructLogger(nil)
|
||||||
evm = vm.NewEVM(vm.BlockContext{}, &dummyStatedb{}, params.TestChainConfig, vm.Config{Tracer: logger.Hooks()})
|
evm = vm.NewEVM(vm.BlockContext{}, &dummyStatedb{}, params.TestChainConfig, vm.Config{Tracer: logger.Hooks()})
|
||||||
contract = vm.NewContract(&dummyContractRef{}, &dummyContractRef{}, new(uint256.Int), 100000)
|
contract = vm.NewContract(common.Address{}, common.Address{}, new(uint256.Int), 100000, nil)
|
||||||
)
|
)
|
||||||
contract.Code = []byte{byte(vm.PUSH1), 0x1, byte(vm.PUSH1), 0x0, byte(vm.SSTORE)}
|
contract.Code = []byte{byte(vm.PUSH1), 0x1, byte(vm.PUSH1), 0x0, byte(vm.SSTORE)}
|
||||||
var index common.Hash
|
var index common.Hash
|
||||||
|
|
|
@ -85,11 +85,23 @@ func (ec *Client) BlockByHash(ctx context.Context, hash common.Hash) (*types.Blo
|
||||||
return ec.getBlock(ctx, "eth_getBlockByHash", hash, true)
|
return ec.getBlock(ctx, "eth_getBlockByHash", hash, true)
|
||||||
}
|
}
|
||||||
|
|
||||||
// BlockByNumber returns a block from the current canonical chain. If number is nil, the
|
// BlockByNumber returns a block from the current canonical chain.
|
||||||
// latest known block is returned.
|
// If `number` is nil, the latest known block is returned.
|
||||||
//
|
//
|
||||||
// Note that loading full blocks requires two requests. Use HeaderByNumber
|
// Use `HeaderByNumber` if you don't need full transaction data or uncle headers.
|
||||||
// if you don't need all transactions or uncle headers.
|
//
|
||||||
|
// Supported special block number tags:
|
||||||
|
// - `earliest` : The genesis (earliest) block
|
||||||
|
// - `latest` : The most recently included block
|
||||||
|
// - `safe` : The latest safe head block
|
||||||
|
// - `finalized` : The latest finalized block
|
||||||
|
// - `pending` : The pending block
|
||||||
|
//
|
||||||
|
// Example usage:
|
||||||
|
//
|
||||||
|
// ```go
|
||||||
|
// BlockByNumber(context.Background(), big.NewInt(int64(rpc.LatestBlockNumber)))
|
||||||
|
// ```
|
||||||
func (ec *Client) BlockByNumber(ctx context.Context, number *big.Int) (*types.Block, error) {
|
func (ec *Client) BlockByNumber(ctx context.Context, number *big.Int) (*types.Block, error) {
|
||||||
return ec.getBlock(ctx, "eth_getBlockByNumber", toBlockNumArg(number), true)
|
return ec.getBlock(ctx, "eth_getBlockByNumber", toBlockNumArg(number), true)
|
||||||
}
|
}
|
||||||
|
@ -210,8 +222,21 @@ func (ec *Client) HeaderByHash(ctx context.Context, hash common.Hash) (*types.He
|
||||||
return head, err
|
return head, err
|
||||||
}
|
}
|
||||||
|
|
||||||
// HeaderByNumber returns a block header from the current canonical chain. If number is
|
// HeaderByNumber returns a block header from the current canonical chain.
|
||||||
// nil, the latest known header is returned.
|
// If `number` is nil, the latest known block header is returned.
|
||||||
|
//
|
||||||
|
// Supported special block number tags:
|
||||||
|
// - `earliest` : The genesis (earliest) block
|
||||||
|
// - `latest` : The most recently included block
|
||||||
|
// - `safe` : The latest safe head block
|
||||||
|
// - `finalized` : The latest finalized block
|
||||||
|
// - `pending` : The pending block
|
||||||
|
//
|
||||||
|
// Example usage:
|
||||||
|
//
|
||||||
|
// ```go
|
||||||
|
// HeaderByNumber(context.Background(), big.NewInt(int64(rpc.LatestBlockNumber)))
|
||||||
|
// ```
|
||||||
func (ec *Client) HeaderByNumber(ctx context.Context, number *big.Int) (*types.Header, error) {
|
func (ec *Client) HeaderByNumber(ctx context.Context, number *big.Int) (*types.Header, error) {
|
||||||
var head *types.Header
|
var head *types.Header
|
||||||
err := ec.c.CallContext(ctx, &head, "eth_getBlockByNumber", toBlockNumArg(number), false)
|
err := ec.c.CallContext(ctx, &head, "eth_getBlockByNumber", toBlockNumArg(number), false)
|
||||||
|
|
|
@ -18,6 +18,7 @@ package p2p
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"crypto/ecdsa"
|
"crypto/ecdsa"
|
||||||
|
"encoding"
|
||||||
"fmt"
|
"fmt"
|
||||||
|
|
||||||
"github.com/ethereum/go-ethereum/common/mclock"
|
"github.com/ethereum/go-ethereum/common/mclock"
|
||||||
|
@ -135,6 +136,13 @@ type configNAT struct {
|
||||||
nat.Interface
|
nat.Interface
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func (w *configNAT) MarshalText() ([]byte, error) {
|
||||||
|
if tm, ok := w.Interface.(encoding.TextMarshaler); ok {
|
||||||
|
return tm.MarshalText()
|
||||||
|
}
|
||||||
|
return nil, fmt.Errorf("NAT specification %#v cannot be marshaled", w.Interface)
|
||||||
|
}
|
||||||
|
|
||||||
func (w *configNAT) UnmarshalText(input []byte) error {
|
func (w *configNAT) UnmarshalText(input []byte) error {
|
||||||
n, err := nat.Parse(string(input))
|
n, err := nat.Parse(string(input))
|
||||||
if err != nil {
|
if err != nil {
|
||||||
|
|
|
@ -317,10 +317,17 @@ var (
|
||||||
Max: 9,
|
Max: 9,
|
||||||
UpdateFraction: 5007716,
|
UpdateFraction: 5007716,
|
||||||
}
|
}
|
||||||
|
// DefaultOsakaBlobConfig is the default blob configuration for the Osaka fork.
|
||||||
|
DefaultOsakaBlobConfig = &BlobConfig{
|
||||||
|
Target: 6,
|
||||||
|
Max: 9,
|
||||||
|
UpdateFraction: 5007716,
|
||||||
|
}
|
||||||
// DefaultBlobSchedule is the latest configured blob schedule for test chains.
|
// DefaultBlobSchedule is the latest configured blob schedule for test chains.
|
||||||
DefaultBlobSchedule = &BlobScheduleConfig{
|
DefaultBlobSchedule = &BlobScheduleConfig{
|
||||||
Cancun: DefaultCancunBlobConfig,
|
Cancun: DefaultCancunBlobConfig,
|
||||||
Prague: DefaultPragueBlobConfig,
|
Prague: DefaultPragueBlobConfig,
|
||||||
|
Osaka: DefaultOsakaBlobConfig,
|
||||||
}
|
}
|
||||||
)
|
)
|
||||||
|
|
||||||
|
@ -501,6 +508,7 @@ type BlobConfig struct {
|
||||||
type BlobScheduleConfig struct {
|
type BlobScheduleConfig struct {
|
||||||
Cancun *BlobConfig `json:"cancun,omitempty"`
|
Cancun *BlobConfig `json:"cancun,omitempty"`
|
||||||
Prague *BlobConfig `json:"prague,omitempty"`
|
Prague *BlobConfig `json:"prague,omitempty"`
|
||||||
|
Osaka *BlobConfig `json:"osaka,omitempty"`
|
||||||
Verkle *BlobConfig `json:"verkle,omitempty"`
|
Verkle *BlobConfig `json:"verkle,omitempty"`
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -732,6 +740,7 @@ func (c *ChainConfig) CheckConfigForkOrder() error {
|
||||||
}{
|
}{
|
||||||
{name: "cancun", timestamp: c.CancunTime, config: bsc.Cancun},
|
{name: "cancun", timestamp: c.CancunTime, config: bsc.Cancun},
|
||||||
{name: "prague", timestamp: c.PragueTime, config: bsc.Prague},
|
{name: "prague", timestamp: c.PragueTime, config: bsc.Prague},
|
||||||
|
{name: "osaka", timestamp: c.OsakaTime, config: bsc.Osaka},
|
||||||
} {
|
} {
|
||||||
if cur.config != nil {
|
if cur.config != nil {
|
||||||
if err := cur.config.validate(); err != nil {
|
if err := cur.config.validate(); err != nil {
|
||||||
|
|
|
@ -431,6 +431,11 @@ var Forks = map[string]*params.ChainConfig{
|
||||||
PragueTime: u64(0),
|
PragueTime: u64(0),
|
||||||
OsakaTime: u64(0),
|
OsakaTime: u64(0),
|
||||||
DepositContractAddress: params.MainnetChainConfig.DepositContractAddress,
|
DepositContractAddress: params.MainnetChainConfig.DepositContractAddress,
|
||||||
|
BlobScheduleConfig: ¶ms.BlobScheduleConfig{
|
||||||
|
Cancun: params.DefaultCancunBlobConfig,
|
||||||
|
Prague: params.DefaultPragueBlobConfig,
|
||||||
|
Osaka: params.DefaultOsakaBlobConfig,
|
||||||
|
},
|
||||||
},
|
},
|
||||||
"PragueToOsakaAtTime15k": {
|
"PragueToOsakaAtTime15k": {
|
||||||
ChainID: big.NewInt(1),
|
ChainID: big.NewInt(1),
|
||||||
|
@ -453,6 +458,11 @@ var Forks = map[string]*params.ChainConfig{
|
||||||
PragueTime: u64(0),
|
PragueTime: u64(0),
|
||||||
OsakaTime: u64(15_000),
|
OsakaTime: u64(15_000),
|
||||||
DepositContractAddress: params.MainnetChainConfig.DepositContractAddress,
|
DepositContractAddress: params.MainnetChainConfig.DepositContractAddress,
|
||||||
|
BlobScheduleConfig: ¶ms.BlobScheduleConfig{
|
||||||
|
Cancun: params.DefaultCancunBlobConfig,
|
||||||
|
Prague: params.DefaultPragueBlobConfig,
|
||||||
|
Osaka: params.DefaultOsakaBlobConfig,
|
||||||
|
},
|
||||||
},
|
},
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
|
@ -310,8 +310,7 @@ func runBenchmark(b *testing.B, t *StateTest) {
|
||||||
evm.SetTxContext(txContext)
|
evm.SetTxContext(txContext)
|
||||||
|
|
||||||
// Create "contract" for sender to cache code analysis.
|
// Create "contract" for sender to cache code analysis.
|
||||||
sender := vm.NewContract(vm.AccountRef(msg.From), vm.AccountRef(msg.From),
|
sender := vm.NewContract(msg.From, msg.From, nil, 0, nil)
|
||||||
nil, 0)
|
|
||||||
|
|
||||||
var (
|
var (
|
||||||
gasUsed uint64
|
gasUsed uint64
|
||||||
|
@ -326,7 +325,7 @@ func runBenchmark(b *testing.B, t *StateTest) {
|
||||||
start := time.Now()
|
start := time.Now()
|
||||||
|
|
||||||
// Execute the message.
|
// Execute the message.
|
||||||
_, leftOverGas, err := evm.Call(sender, *msg.To, msg.Data, msg.GasLimit, uint256.MustFromBig(msg.Value))
|
_, leftOverGas, err := evm.Call(sender.Address(), *msg.To, msg.Data, msg.GasLimit, uint256.MustFromBig(msg.Value))
|
||||||
if err != nil {
|
if err != nil {
|
||||||
b.Error(err)
|
b.Error(err)
|
||||||
return
|
return
|
||||||
|
|
|
@ -37,16 +37,13 @@ func FuzzStackTrie(f *testing.F) {
|
||||||
}
|
}
|
||||||
|
|
||||||
func fuzz(data []byte, debugging bool) {
|
func fuzz(data []byte, debugging bool) {
|
||||||
// This spongeDb is used to check the sequence of disk-db-writes
|
|
||||||
var (
|
var (
|
||||||
input = bytes.NewReader(data)
|
input = bytes.NewReader(data)
|
||||||
spongeA = &spongeDb{sponge: crypto.NewKeccakState()}
|
dbA = newTestDatabase(rawdb.NewMemoryDatabase(), rawdb.HashScheme)
|
||||||
dbA = newTestDatabase(rawdb.NewDatabase(spongeA), rawdb.HashScheme)
|
|
||||||
trieA = NewEmpty(dbA)
|
trieA = NewEmpty(dbA)
|
||||||
spongeB = &spongeDb{sponge: crypto.NewKeccakState()}
|
memDB = rawdb.NewMemoryDatabase()
|
||||||
dbB = newTestDatabase(rawdb.NewDatabase(spongeB), rawdb.HashScheme)
|
|
||||||
trieB = NewStackTrie(func(path []byte, hash common.Hash, blob []byte) {
|
trieB = NewStackTrie(func(path []byte, hash common.Hash, blob []byte) {
|
||||||
rawdb.WriteTrieNode(spongeB, common.Hash{}, path, hash, blob, dbB.Scheme())
|
rawdb.WriteTrieNode(memDB, common.Hash{}, path, hash, blob, rawdb.HashScheme)
|
||||||
})
|
})
|
||||||
vals []*kv
|
vals []*kv
|
||||||
maxElements = 10000
|
maxElements = 10000
|
||||||
|
@ -55,13 +52,17 @@ func fuzz(data []byte, debugging bool) {
|
||||||
)
|
)
|
||||||
// Fill the trie with elements
|
// Fill the trie with elements
|
||||||
for i := 0; input.Len() > 0 && i < maxElements; i++ {
|
for i := 0; input.Len() > 0 && i < maxElements; i++ {
|
||||||
|
// Build the key
|
||||||
k := make([]byte, 32)
|
k := make([]byte, 32)
|
||||||
input.Read(k)
|
input.Read(k)
|
||||||
|
|
||||||
|
// Build the val
|
||||||
var a uint16
|
var a uint16
|
||||||
binary.Read(input, binary.LittleEndian, &a)
|
binary.Read(input, binary.LittleEndian, &a)
|
||||||
a = 1 + a%100
|
a = 1 + a%100
|
||||||
v := make([]byte, a)
|
v := make([]byte, a)
|
||||||
input.Read(v)
|
input.Read(v)
|
||||||
|
|
||||||
if input.Len() == 0 {
|
if input.Len() == 0 {
|
||||||
// If it was exhausted while reading, the value may be all zeroes,
|
// If it was exhausted while reading, the value may be all zeroes,
|
||||||
// thus 'deletion' which is not supported on stacktrie
|
// thus 'deletion' which is not supported on stacktrie
|
||||||
|
@ -73,6 +74,7 @@ func fuzz(data []byte, debugging bool) {
|
||||||
}
|
}
|
||||||
keys[string(k)] = struct{}{}
|
keys[string(k)] = struct{}{}
|
||||||
vals = append(vals, &kv{k: k, v: v})
|
vals = append(vals, &kv{k: k, v: v})
|
||||||
|
|
||||||
trieA.MustUpdate(k, v)
|
trieA.MustUpdate(k, v)
|
||||||
}
|
}
|
||||||
if len(vals) == 0 {
|
if len(vals) == 0 {
|
||||||
|
@ -99,11 +101,6 @@ func fuzz(data []byte, debugging bool) {
|
||||||
if rootA != rootB {
|
if rootA != rootB {
|
||||||
panic(fmt.Sprintf("roots differ: (trie) %x != %x (stacktrie)", rootA, rootB))
|
panic(fmt.Sprintf("roots differ: (trie) %x != %x (stacktrie)", rootA, rootB))
|
||||||
}
|
}
|
||||||
sumA := spongeA.sponge.Sum(nil)
|
|
||||||
sumB := spongeB.sponge.Sum(nil)
|
|
||||||
if !bytes.Equal(sumA, sumB) {
|
|
||||||
panic(fmt.Sprintf("sequence differ: (trie) %x != %x (stacktrie)", sumA, sumB))
|
|
||||||
}
|
|
||||||
|
|
||||||
// Ensure all the nodes are persisted correctly
|
// Ensure all the nodes are persisted correctly
|
||||||
var (
|
var (
|
||||||
|
|
|
@ -779,6 +779,7 @@ func TestCommitAfterHash(t *testing.T) {
|
||||||
func makeAccounts(size int) (addresses [][20]byte, accounts [][]byte) {
|
func makeAccounts(size int) (addresses [][20]byte, accounts [][]byte) {
|
||||||
// Make the random benchmark deterministic
|
// Make the random benchmark deterministic
|
||||||
random := rand.New(rand.NewSource(0))
|
random := rand.New(rand.NewSource(0))
|
||||||
|
|
||||||
// Create a realistic account trie to hash
|
// Create a realistic account trie to hash
|
||||||
addresses = make([][20]byte, size)
|
addresses = make([][20]byte, size)
|
||||||
for i := 0; i < len(addresses); i++ {
|
for i := 0; i < len(addresses); i++ {
|
||||||
|
@ -795,13 +796,18 @@ func makeAccounts(size int) (addresses [][20]byte, accounts [][]byte) {
|
||||||
)
|
)
|
||||||
// The big.Rand function is not deterministic with regards to 64 vs 32 bit systems,
|
// The big.Rand function is not deterministic with regards to 64 vs 32 bit systems,
|
||||||
// and will consume different amount of data from the rand source.
|
// and will consume different amount of data from the rand source.
|
||||||
//balance = new(big.Int).Rand(random, new(big.Int).Exp(common.Big2, common.Big256, nil))
|
// balance = new(big.Int).Rand(random, new(big.Int).Exp(common.Big2, common.Big256, nil))
|
||||||
// Therefore, we instead just read via byte buffer
|
// Therefore, we instead just read via byte buffer
|
||||||
numBytes := random.Uint32() % 33 // [0, 32] bytes
|
numBytes := random.Uint32() % 33 // [0, 32] bytes
|
||||||
balanceBytes := make([]byte, numBytes)
|
balanceBytes := make([]byte, numBytes)
|
||||||
random.Read(balanceBytes)
|
random.Read(balanceBytes)
|
||||||
balance := new(uint256.Int).SetBytes(balanceBytes)
|
balance := new(uint256.Int).SetBytes(balanceBytes)
|
||||||
data, _ := rlp.EncodeToBytes(&types.StateAccount{Nonce: nonce, Balance: balance, Root: root, CodeHash: code})
|
data, _ := rlp.EncodeToBytes(&types.StateAccount{
|
||||||
|
Nonce: nonce,
|
||||||
|
Balance: balance,
|
||||||
|
Root: root,
|
||||||
|
CodeHash: code,
|
||||||
|
})
|
||||||
accounts[i] = data
|
accounts[i] = data
|
||||||
}
|
}
|
||||||
return addresses, accounts
|
return addresses, accounts
|
||||||
|
@ -856,6 +862,7 @@ func (s *spongeDb) Flush() {
|
||||||
s.sponge.Write([]byte(key))
|
s.sponge.Write([]byte(key))
|
||||||
s.sponge.Write([]byte(s.values[key]))
|
s.sponge.Write([]byte(s.values[key]))
|
||||||
}
|
}
|
||||||
|
fmt.Println(len(s.keys))
|
||||||
}
|
}
|
||||||
|
|
||||||
// spongeBatch is a dummy batch which immediately writes to the underlying spongedb
|
// spongeBatch is a dummy batch which immediately writes to the underlying spongedb
|
||||||
|
@ -873,10 +880,12 @@ func (b *spongeBatch) Write() error { return nil }
|
||||||
func (b *spongeBatch) Reset() {}
|
func (b *spongeBatch) Reset() {}
|
||||||
func (b *spongeBatch) Replay(w ethdb.KeyValueWriter) error { return nil }
|
func (b *spongeBatch) Replay(w ethdb.KeyValueWriter) error { return nil }
|
||||||
|
|
||||||
// TestCommitSequence tests that the trie.Commit operation writes the elements of the trie
|
// TestCommitSequence tests that the trie.Commit operation writes the elements
|
||||||
// in the expected order.
|
// of the trie in the expected order.
|
||||||
// The test data was based on the 'master' code, and is basically random. It can be used
|
//
|
||||||
// to check whether changes to the trie modifies the write order or data in any way.
|
// The test data was based on the 'master' code, and is basically random.
|
||||||
|
// It can be used to check whether changes to the trie modifies the write order
|
||||||
|
// or data in any way.
|
||||||
func TestCommitSequence(t *testing.T) {
|
func TestCommitSequence(t *testing.T) {
|
||||||
for i, tc := range []struct {
|
for i, tc := range []struct {
|
||||||
count int
|
count int
|
||||||
|
@ -887,19 +896,23 @@ func TestCommitSequence(t *testing.T) {
|
||||||
{2000, common.FromHex("4574cd8e6b17f3fe8ad89140d1d0bf4f1bd7a87a8ac3fb623b33550544c77635")},
|
{2000, common.FromHex("4574cd8e6b17f3fe8ad89140d1d0bf4f1bd7a87a8ac3fb623b33550544c77635")},
|
||||||
} {
|
} {
|
||||||
addresses, accounts := makeAccounts(tc.count)
|
addresses, accounts := makeAccounts(tc.count)
|
||||||
|
|
||||||
// This spongeDb is used to check the sequence of disk-db-writes
|
// This spongeDb is used to check the sequence of disk-db-writes
|
||||||
s := &spongeDb{sponge: crypto.NewKeccakState()}
|
s := &spongeDb{sponge: crypto.NewKeccakState()}
|
||||||
db := newTestDatabase(rawdb.NewDatabase(s), rawdb.HashScheme)
|
db := newTestDatabase(rawdb.NewDatabase(s), rawdb.HashScheme)
|
||||||
trie := NewEmpty(db)
|
|
||||||
// Fill the trie with elements
|
// Fill the trie with elements
|
||||||
|
trie := NewEmpty(db)
|
||||||
for i := 0; i < tc.count; i++ {
|
for i := 0; i < tc.count; i++ {
|
||||||
trie.MustUpdate(crypto.Keccak256(addresses[i][:]), accounts[i])
|
trie.MustUpdate(crypto.Keccak256(addresses[i][:]), accounts[i])
|
||||||
}
|
}
|
||||||
// Flush trie -> database
|
// Flush trie -> database
|
||||||
root, nodes := trie.Commit(false)
|
root, nodes := trie.Commit(false)
|
||||||
db.Update(root, types.EmptyRootHash, trienode.NewWithNodeSet(nodes))
|
db.Update(root, types.EmptyRootHash, trienode.NewWithNodeSet(nodes))
|
||||||
|
|
||||||
// Flush memdb -> disk (sponge)
|
// Flush memdb -> disk (sponge)
|
||||||
db.Commit(root)
|
db.Commit(root)
|
||||||
|
|
||||||
if got, exp := s.sponge.Sum(nil), tc.expWriteSeqHash; !bytes.Equal(got, exp) {
|
if got, exp := s.sponge.Sum(nil), tc.expWriteSeqHash; !bytes.Equal(got, exp) {
|
||||||
t.Errorf("test %d, disk write sequence wrong:\ngot %x exp %x\n", i, got, exp)
|
t.Errorf("test %d, disk write sequence wrong:\ngot %x exp %x\n", i, got, exp)
|
||||||
}
|
}
|
||||||
|
@ -917,12 +930,13 @@ func TestCommitSequenceRandomBlobs(t *testing.T) {
|
||||||
{200, common.FromHex("dde92ca9812e068e6982d04b40846dc65a61a9fd4996fc0f55f2fde172a8e13c")},
|
{200, common.FromHex("dde92ca9812e068e6982d04b40846dc65a61a9fd4996fc0f55f2fde172a8e13c")},
|
||||||
{2000, common.FromHex("ab553a7f9aff82e3929c382908e30ef7dd17a332933e92ba3fe873fc661ef382")},
|
{2000, common.FromHex("ab553a7f9aff82e3929c382908e30ef7dd17a332933e92ba3fe873fc661ef382")},
|
||||||
} {
|
} {
|
||||||
prng := rand.New(rand.NewSource(int64(i)))
|
|
||||||
// This spongeDb is used to check the sequence of disk-db-writes
|
// This spongeDb is used to check the sequence of disk-db-writes
|
||||||
|
prng := rand.New(rand.NewSource(int64(i)))
|
||||||
s := &spongeDb{sponge: crypto.NewKeccakState()}
|
s := &spongeDb{sponge: crypto.NewKeccakState()}
|
||||||
db := newTestDatabase(rawdb.NewDatabase(s), rawdb.HashScheme)
|
db := newTestDatabase(rawdb.NewDatabase(s), rawdb.HashScheme)
|
||||||
trie := NewEmpty(db)
|
|
||||||
// Fill the trie with elements
|
// Fill the trie with elements
|
||||||
|
trie := NewEmpty(db)
|
||||||
for i := 0; i < tc.count; i++ {
|
for i := 0; i < tc.count; i++ {
|
||||||
key := make([]byte, 32)
|
key := make([]byte, 32)
|
||||||
var val []byte
|
var val []byte
|
||||||
|
@ -939,6 +953,7 @@ func TestCommitSequenceRandomBlobs(t *testing.T) {
|
||||||
// Flush trie -> database
|
// Flush trie -> database
|
||||||
root, nodes := trie.Commit(false)
|
root, nodes := trie.Commit(false)
|
||||||
db.Update(root, types.EmptyRootHash, trienode.NewWithNodeSet(nodes))
|
db.Update(root, types.EmptyRootHash, trienode.NewWithNodeSet(nodes))
|
||||||
|
|
||||||
// Flush memdb -> disk (sponge)
|
// Flush memdb -> disk (sponge)
|
||||||
db.Commit(root)
|
db.Commit(root)
|
||||||
if got, exp := s.sponge.Sum(nil), tc.expWriteSeqHash; !bytes.Equal(got, exp) {
|
if got, exp := s.sponge.Sum(nil), tc.expWriteSeqHash; !bytes.Equal(got, exp) {
|
||||||
|
@ -974,19 +989,22 @@ func TestCommitSequenceStackTrie(t *testing.T) {
|
||||||
// For the stack trie, we need to do inserts in proper order
|
// For the stack trie, we need to do inserts in proper order
|
||||||
key := make([]byte, 32)
|
key := make([]byte, 32)
|
||||||
binary.BigEndian.PutUint64(key, uint64(i))
|
binary.BigEndian.PutUint64(key, uint64(i))
|
||||||
var val []byte
|
|
||||||
// 50% short elements, 50% large elements
|
// 50% short elements, 50% large elements
|
||||||
|
var val []byte
|
||||||
if prng.Intn(2) == 0 {
|
if prng.Intn(2) == 0 {
|
||||||
val = make([]byte, 1+prng.Intn(32))
|
val = make([]byte, 1+prng.Intn(32))
|
||||||
} else {
|
} else {
|
||||||
val = make([]byte, 1+prng.Intn(1024))
|
val = make([]byte, 1+prng.Intn(1024))
|
||||||
}
|
}
|
||||||
prng.Read(val)
|
prng.Read(val)
|
||||||
|
|
||||||
trie.Update(key, val)
|
trie.Update(key, val)
|
||||||
stTrie.Update(key, val)
|
stTrie.Update(key, val)
|
||||||
}
|
}
|
||||||
// Flush trie -> database
|
// Flush trie -> database
|
||||||
root, nodes := trie.Commit(false)
|
root, nodes := trie.Commit(false)
|
||||||
|
|
||||||
// Flush memdb -> disk (sponge)
|
// Flush memdb -> disk (sponge)
|
||||||
db.Update(root, types.EmptyRootHash, trienode.NewWithNodeSet(nodes))
|
db.Update(root, types.EmptyRootHash, trienode.NewWithNodeSet(nodes))
|
||||||
db.Commit(root)
|
db.Commit(root)
|
||||||
|
@ -1045,6 +1063,7 @@ func TestCommitSequenceSmallRoot(t *testing.T) {
|
||||||
|
|
||||||
// Flush trie -> database
|
// Flush trie -> database
|
||||||
root, nodes := trie.Commit(false)
|
root, nodes := trie.Commit(false)
|
||||||
|
|
||||||
// Flush memdb -> disk (sponge)
|
// Flush memdb -> disk (sponge)
|
||||||
db.Update(root, types.EmptyRootHash, trienode.NewWithNodeSet(nodes))
|
db.Update(root, types.EmptyRootHash, trienode.NewWithNodeSet(nodes))
|
||||||
db.Commit(root)
|
db.Commit(root)
|
||||||
|
|
|
@ -19,6 +19,6 @@ package version
|
||||||
const (
|
const (
|
||||||
Major = 1 // Major version component of the current release
|
Major = 1 // Major version component of the current release
|
||||||
Minor = 15 // Minor version component of the current release
|
Minor = 15 // Minor version component of the current release
|
||||||
Patch = 2 // Patch version component of the current release
|
Patch = 3 // Patch version component of the current release
|
||||||
Meta = "unstable" // Version metadata to append to the version string
|
Meta = "unstable" // Version metadata to append to the version string
|
||||||
)
|
)
|
||||||
|
|
Loading…
Reference in New Issue