Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Evm/third #84

Closed
wants to merge 3 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 11 additions & 0 deletions execution/evm/common.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
package evm
import(
"github.com/BlocSoc-iitr/selene/common"
Common "github.com/ethereum/go-ethereum/common"
"math/big"
)
type BlockTag = common.BlockTag
type U256 = *big.Int
type B256 = Common.Hash
type Address = common.Address
type Bytes=[]byte
136 changes: 136 additions & 0 deletions execution/evm/context.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,136 @@
package evm
import (
"math/big"
)
var BLOCK_HASH_HISTORY = big.NewInt(256)
type Context[EXT interface{}, DB Database] struct {
Evm EvmContext[DB]
External interface{}
}
func DefaultContext[EXT interface{}]() Context[EXT, *EmptyDB] {
return Context[EXT, *EmptyDB]{
Evm: NewEvmContext(new(EmptyDB)),
External: nil,
}
}
func NewContext[EXT interface{}, DB Database](evm EvmContext[DB], external EXT) Context[EXT, DB] {
return Context[EXT, DB]{
Evm: evm,
External: external,
}
}
type ContextWithHandlerCfg[EXT interface{}, DB Database] struct {
Context Context[EXT, DB]
Cfg HandlerCfg
}
func (js JournaledState) SetSpecId(spec SpecId) {
js.Spec = spec
}
//Not being used
func (c EvmContext[DB]) WithDB(db DB) EvmContext[DB] {
return EvmContext[DB]{
Inner: c.Inner.WithDB(db),
Precompiles: DefaultContextPrecompiles[DB](),
}
}
////////////////////////////////////
/// impl Host for Context /////////
////////////////////////////////////

// func (c *Context[EXT, DB]) Env() *Env {
// return c.Evm.Inner.Env
// }

// func (c *Context[EXT, DB]) EnvMut() *Env {
// return c.Evm.Inner.Env
// }

// func (c *Context[EXT, DB]) LoadAccount(address Address) (LoadAccountResult, bool) {
// res, err := c.Evm.Inner.LoadAccountExist(address)
// if err != nil {
// c.Evm.Inner.Error = err
// return LoadAccountResult{}, false
// }
// return res, true
// }

// //Get the block hash of the given block `number`.
// func (c *Context[EXT, DB]) BlockHash(number uint64) (B256, bool) {
// blockNumber := c.Evm.Inner.Env.Block.Number
// requestedNumber := big.NewInt(int64(number))

// diff := new(big.Int).Sub(blockNumber, requestedNumber)

// if diff.Cmp(big.NewInt(0)) == 0 {
// return common.Hash{}, true
// }

// if diff.Cmp(BLOCK_HASH_HISTORY) <= 0 {
// hash, err := c.Evm.Inner.DB.BlockHash(number)
// if err != nil {
// c.Evm.Inner.Error = err
// return common.Hash{}, false
// }
// return hash, true
// }

// return common.Hash{}, true
// }

// // Get balance of `address` and if the account is cold.
// func (c *Context[EXT, DB]) Balance(address Address) (U256, bool, bool)

// // Get code of `address` and if the account is cold.
// func (c *Context[EXT, DB]) Code(address Address) (Bytes, bool, bool)

// // Get code hash of `address` and if the account is cold.
// func (c *Context[EXT, DB]) CodeHash(address Address) (B256, bool, bool)

// // Get storage value of `address` at `index` and if the account is cold.
// func (c *Context[EXT, DB]) SLoad(address Address, index U256) (U256, bool, bool)

// // Set storage value of account address at index.
// // Returns (original, present, new, is_cold).
// func (c *Context[EXT, DB]) SStore(address Address, index U256, value U256) (SStoreResult, bool)

// // Get the transient storage value of `address` at `index`.
// func (c *Context[EXT, DB]) TLoad(address Address, index U256) U256

// // Set the transient storage value of `address` at `index`.
// func (c *Context[EXT, DB]) TStore(address Address, index U256, value U256)

// // Emit a log owned by `address` with given `LogData`.
// func (c *Context[EXT, DB]) Log(log Log [any])

// // Mark `address` to be deleted, with funds transferred to `target`.
// func (c *Context[EXT, DB]) SelfDestruct(address Address, target Address) (SelfDestructResult, bool)

////////////////////////////////////
////////////////////////////////////
////////////////////////////////////

/*
func (c EvmContext[DB1]) WithNewEvmDB[DB2 Database](db DB2) *EvmContext[ DB2] {
return &EvmContext[DB2]{
Inner: c.Inner.WithDB(db),
context: NewContext[EXT, DB2](
eb.context.Evm.WithNewDB(db),
eb.context.External.(EXT),
),
handler: Handler[Context[EXT, DB2], EXT, DB2]{Cfg: eb.handler.Cfg},
phantom: struct{}{},
}
}*/













37 changes: 37 additions & 0 deletions execution/evm/database.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
package evm
import(
"errors"
"math/big"
)
type Database interface {
Basic(address Address) (AccountInfo, error)

Check failure on line 7 in execution/evm/database.go

View workflow job for this annotation

GitHub Actions / test

undefined: AccountInfo

Check failure on line 7 in execution/evm/database.go

View workflow job for this annotation

GitHub Actions / build (1.22.3)

undefined: AccountInfo

Check failure on line 7 in execution/evm/database.go

View workflow job for this annotation

GitHub Actions / golangci-lint (/home/runner/work/selene/selene)

undefined: AccountInfo
BlockHash(number uint64) (B256, error)
Storage(address Address, index U256) (U256, error)
CodeByHash(codeHash B256) (Bytecode, error)

Check failure on line 10 in execution/evm/database.go

View workflow job for this annotation

GitHub Actions / test

undefined: Bytecode

Check failure on line 10 in execution/evm/database.go

View workflow job for this annotation

GitHub Actions / build (1.22.3)

undefined: Bytecode

Check failure on line 10 in execution/evm/database.go

View workflow job for this annotation

GitHub Actions / golangci-lint (/home/runner/work/selene/selene)

undefined: Bytecode
}
type EmptyDB struct{}
func (db *EmptyDB) Basic(address Address) (AccountInfo, error) {
return AccountInfo{}, errors.New("EmptyDB: Basic not implemented")
}
func (db *EmptyDB) BlockHash(number uint64) (B256, error) {
return B256{}, errors.New("EmptyDB: BlockHash not implemented")
}
func (db *EmptyDB) Storage(address Address, index U256) (U256, error) {
return big.NewInt(0), errors.New("EmptyDB: Storage not implemented")
}
func (db *EmptyDB) CodeByHash(codeHash B256) (Bytecode, error) {
return Bytecode{}, errors.New("EmptyDB: CodeByHash not implemented")
}
func NewEmptyDB() *EmptyDB {
return &EmptyDB{}
}
type DatabaseError struct {
msg string
err error
}
func (e *DatabaseError) Error() string {
if e.err != nil {
return e.err.Error()
}
return e.msg
}
180 changes: 180 additions & 0 deletions execution/evm/env.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,180 @@
package evm

import (
"encoding/json"
"fmt"
"math/big"
)
type Env struct{
Cfg CfgEnv
Block BlockEnv
Tx TxEnv
}
func NewEnv() *Env {
return &Env{}
}

type AccessListItem struct {
Address Address
StorageKeys []B256
}
type Signature struct {
V uint8 // Recovery ID
R *big.Int // R component of signature
S *big.Int // S component of signature
}
type AuthorizationListType int
const (
Signed AuthorizationListType = iota
Recovered
)
type AuthorizationList struct {
Type AuthorizationListType
SignedAuthorizations []SignedAuthorization
RecoveredAuthorizations []RecoveredAuthorization
}
type ChainID uint64
type OptionalNonce struct {
Nonce *uint64 // nil if no nonce is provided
}
type Authorization struct {
ChainID ChainID // The chain ID of the authorization
Address Address // The address of the authorization
Nonce OptionalNonce // The nonce for the authorization
}
type SignedAuthorization struct {
Inner Authorization // Embedded authorization data
Signature Signature // Signature associated with authorization
}

type RecoveredAuthorization struct {
Inner Authorization // Embedded authorization data
Authority *Address // Optional authority address
}
type TransactTo = TxKind;
type TxKind struct {
Type TxKindType
Address *Address // Address is nil for Create type
}
type TxKindType int
const (
Create2 TxKindType = iota
Call2
)
type CfgEnv struct {
ChainID uint64 `json:"chain_id"`
KzgSettings *EnvKzgSettings `json:"kzg_settings,omitempty"`
PerfAnalyseCreatedBytecodes AnalysisKind `json:"perf_analyse_created_bytecodes"`
LimitContractCodeSize *uint64 `json:"limit_contract_code_size,omitempty"`
MemoryLimit uint64 `json:"memory_limit,omitempty"` // Consider using a pointer if optional
DisableBalanceCheck bool `json:"disable_balance_check,omitempty"`
DisableBlockGasLimit bool `json:"disable_block_gas_limit,omitempty"`
DisableEIP3607 bool `json:"disable_eip3607,omitempty"`
DisableGasRefund bool `json:"disable_gas_refund,omitempty"`
DisableBaseFee bool `json:"disable_base_fee,omitempty"`
DisableBeneficiaryReward bool `json:"disable_beneficiary_reward,omitempty"`
}
type BlockEnv struct {
Number U256 `json:"number"`
Coinbase Address `json:"coinbase"`
Timestamp U256 `json:"timestamp"`
GasLimit U256 `json:"gas_limit"`
BaseFee U256 `json:"basefee"`
Difficulty U256 `json:"difficulty"`
Prevrandao *B256 `json:"prevrandao,omitempty"`
BlobExcessGasAndPrice *BlobExcessGasAndPrice `json:"blob_excess_gas_and_price,omitempty"`
}
type BlobExcessGasAndPrice struct {
ExcessGas uint64 `json:"excess_gas"`
BlobGasPrice uint64 `json:"blob_gas_price"`
}
type EnvKzgSettings struct {
Mode string `json:"mode"`
Custom *KzgSettings `json:"custom,omitempty"`
}
// KzgSettings represents custom KZG settings.
type KzgSettings struct {
// Define fields for KzgSettings based on your requirements.
}
// AnalysisKind represents the type of analysis for created bytecodes.
type AnalysisKind int
const (
Raw AnalysisKind = iota
Analyse
)

// MarshalJSON customizes the JSON marshalling for AnalysisKind.
func (ak AnalysisKind) MarshalJSON() ([]byte, error) {
switch ak {
case Raw:
return json.Marshal("raw")
case Analyse:
return json.Marshal("analyse")
default:
return json.Marshal("unknown")
}
}

// UnmarshalJSON customizes the JSON unmarshalling for AnalysisKind.
func (ak *AnalysisKind) UnmarshalJSON(data []byte) error {
var s string
if err := json.Unmarshal(data, &s); err != nil {
return err
}
switch s {
case "raw":
*ak = Raw
case "analyse":
*ak = Analyse
default:
return fmt.Errorf("unknown AnalysisKind: %s", s)
}
return nil
}
//Not in use : To be verified
func NewSignature(v uint8, r, s *big.Int) *Signature {
return &Signature{
V: v,
R: new(big.Int).Set(r),
S: new(big.Int).Set(s),
}
}
//Not in use : To be verified
func (s *Signature) ToRawSignature() []byte {
rBytes := s.R.Bytes()
sBytes := s.S.Bytes()
signature := make([]byte, 64)
copy(signature[32-len(rBytes):32], rBytes)
copy(signature[64-len(sBytes):], sBytes)
return signature
}
//Not in use : To be verified
func FromRawSignature(data []byte, v uint8) (*Signature, error) {
if len(data) != 64 {
return nil, fmt.Errorf("invalid signature length: got %d, want 64", len(data))
}

r := new(big.Int).SetBytes(data[:32])
s := new(big.Int).SetBytes(data[32:])

return &Signature{
V: v,
R: r,
S: s,
}, nil
}

// Verify verifies the signature against a message hash and public key
/*
func (s *Signature) Verify(pubKey *ecdsa.PublicKey, hash []byte) bool {
// Check if r and s are in the valid range
if s.R.Sign() <= 0 || s.S.Sign() <= 0 {
return false
}
if s.R.Cmp(pubKey.Params().N) >= 0 || s.S.Cmp(pubKey.Params().N) >= 0 {
return false
}

// Verify the signature
return ecdsa.Verify(pubKey, hash, s.R, s.S)
}*/
Loading
Loading