github.com/calmw/ethereum@v0.1.1/eth/tracers/native/prestate.go (about)

     1  // Copyright 2022 The go-ethereum Authors
     2  // This file is part of the go-ethereum library.
     3  //
     4  // The go-ethereum library is free software: you can redistribute it and/or modify
     5  // it under the terms of the GNU Lesser General Public License as published by
     6  // the Free Software Foundation, either version 3 of the License, or
     7  // (at your option) any later version.
     8  //
     9  // The go-ethereum library is distributed in the hope that it will be useful,
    10  // but WITHOUT ANY WARRANTY; without even the implied warranty of
    11  // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
    12  // GNU Lesser General Public License for more details.
    13  //
    14  // You should have received a copy of the GNU Lesser General Public License
    15  // along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>.
    16  
    17  package native
    18  
    19  import (
    20  	"bytes"
    21  	"encoding/json"
    22  	"math/big"
    23  	"sync/atomic"
    24  
    25  	"github.com/calmw/ethereum/common"
    26  	"github.com/calmw/ethereum/common/hexutil"
    27  	"github.com/calmw/ethereum/core/vm"
    28  	"github.com/calmw/ethereum/crypto"
    29  	"github.com/calmw/ethereum/eth/tracers"
    30  )
    31  
    32  //go:generate go run github.com/fjl/gencodec -type account -field-override accountMarshaling -out gen_account_json.go
    33  
    34  func init() {
    35  	tracers.DefaultDirectory.Register("prestateTracer", newPrestateTracer, false)
    36  }
    37  
    38  type state = map[common.Address]*account
    39  
    40  type account struct {
    41  	Balance *big.Int                    `json:"balance,omitempty"`
    42  	Code    []byte                      `json:"code,omitempty"`
    43  	Nonce   uint64                      `json:"nonce,omitempty"`
    44  	Storage map[common.Hash]common.Hash `json:"storage,omitempty"`
    45  }
    46  
    47  func (a *account) exists() bool {
    48  	return a.Nonce > 0 || len(a.Code) > 0 || len(a.Storage) > 0 || (a.Balance != nil && a.Balance.Sign() != 0)
    49  }
    50  
    51  type accountMarshaling struct {
    52  	Balance *hexutil.Big
    53  	Code    hexutil.Bytes
    54  }
    55  
    56  type prestateTracer struct {
    57  	noopTracer
    58  	env       *vm.EVM
    59  	pre       state
    60  	post      state
    61  	create    bool
    62  	to        common.Address
    63  	gasLimit  uint64 // Amount of gas bought for the whole tx
    64  	config    prestateTracerConfig
    65  	interrupt atomic.Bool // Atomic flag to signal execution interruption
    66  	reason    error       // Textual reason for the interruption
    67  	created   map[common.Address]bool
    68  	deleted   map[common.Address]bool
    69  }
    70  
    71  type prestateTracerConfig struct {
    72  	DiffMode bool `json:"diffMode"` // If true, this tracer will return state modifications
    73  }
    74  
    75  func newPrestateTracer(ctx *tracers.Context, cfg json.RawMessage) (tracers.Tracer, error) {
    76  	var config prestateTracerConfig
    77  	if cfg != nil {
    78  		if err := json.Unmarshal(cfg, &config); err != nil {
    79  			return nil, err
    80  		}
    81  	}
    82  	return &prestateTracer{
    83  		pre:     state{},
    84  		post:    state{},
    85  		config:  config,
    86  		created: make(map[common.Address]bool),
    87  		deleted: make(map[common.Address]bool),
    88  	}, nil
    89  }
    90  
    91  // CaptureStart implements the EVMLogger interface to initialize the tracing operation.
    92  func (t *prestateTracer) CaptureStart(env *vm.EVM, from common.Address, to common.Address, create bool, input []byte, gas uint64, value *big.Int) {
    93  	t.env = env
    94  	t.create = create
    95  	t.to = to
    96  
    97  	t.lookupAccount(from)
    98  	t.lookupAccount(to)
    99  	t.lookupAccount(env.Context.Coinbase)
   100  
   101  	// The recipient balance includes the value transferred.
   102  	toBal := new(big.Int).Sub(t.pre[to].Balance, value)
   103  	t.pre[to].Balance = toBal
   104  
   105  	// The sender balance is after reducing: value and gasLimit.
   106  	// We need to re-add them to get the pre-tx balance.
   107  	fromBal := new(big.Int).Set(t.pre[from].Balance)
   108  	gasPrice := env.TxContext.GasPrice
   109  	consumedGas := new(big.Int).Mul(gasPrice, new(big.Int).SetUint64(t.gasLimit))
   110  	fromBal.Add(fromBal, new(big.Int).Add(value, consumedGas))
   111  	t.pre[from].Balance = fromBal
   112  	t.pre[from].Nonce--
   113  
   114  	if create && t.config.DiffMode {
   115  		t.created[to] = true
   116  	}
   117  }
   118  
   119  // CaptureEnd is called after the call finishes to finalize the tracing.
   120  func (t *prestateTracer) CaptureEnd(output []byte, gasUsed uint64, err error) {
   121  	if t.config.DiffMode {
   122  		return
   123  	}
   124  
   125  	if t.create {
   126  		// Keep existing account prior to contract creation at that address
   127  		if s := t.pre[t.to]; s != nil && !s.exists() {
   128  			// Exclude newly created contract.
   129  			delete(t.pre, t.to)
   130  		}
   131  	}
   132  }
   133  
   134  // CaptureState implements the EVMLogger interface to trace a single step of VM execution.
   135  func (t *prestateTracer) CaptureState(pc uint64, op vm.OpCode, gas, cost uint64, scope *vm.ScopeContext, rData []byte, depth int, err error) {
   136  	if err != nil {
   137  		return
   138  	}
   139  	// Skip if tracing was interrupted
   140  	if t.interrupt.Load() {
   141  		return
   142  	}
   143  	stack := scope.Stack
   144  	stackData := stack.Data()
   145  	stackLen := len(stackData)
   146  	caller := scope.Contract.Address()
   147  	switch {
   148  	case stackLen >= 1 && (op == vm.SLOAD || op == vm.SSTORE):
   149  		slot := common.Hash(stackData[stackLen-1].Bytes32())
   150  		t.lookupStorage(caller, slot)
   151  	case stackLen >= 1 && (op == vm.EXTCODECOPY || op == vm.EXTCODEHASH || op == vm.EXTCODESIZE || op == vm.BALANCE || op == vm.SELFDESTRUCT):
   152  		addr := common.Address(stackData[stackLen-1].Bytes20())
   153  		t.lookupAccount(addr)
   154  		if op == vm.SELFDESTRUCT {
   155  			t.deleted[caller] = true
   156  		}
   157  	case stackLen >= 5 && (op == vm.DELEGATECALL || op == vm.CALL || op == vm.STATICCALL || op == vm.CALLCODE):
   158  		addr := common.Address(stackData[stackLen-2].Bytes20())
   159  		t.lookupAccount(addr)
   160  	case op == vm.CREATE:
   161  		nonce := t.env.StateDB.GetNonce(caller)
   162  		addr := crypto.CreateAddress(caller, nonce)
   163  		t.lookupAccount(addr)
   164  		t.created[addr] = true
   165  	case stackLen >= 4 && op == vm.CREATE2:
   166  		offset := stackData[stackLen-2]
   167  		size := stackData[stackLen-3]
   168  		init := scope.Memory.GetCopy(int64(offset.Uint64()), int64(size.Uint64()))
   169  		inithash := crypto.Keccak256(init)
   170  		salt := stackData[stackLen-4]
   171  		addr := crypto.CreateAddress2(caller, salt.Bytes32(), inithash)
   172  		t.lookupAccount(addr)
   173  		t.created[addr] = true
   174  	}
   175  }
   176  
   177  func (t *prestateTracer) CaptureTxStart(gasLimit uint64) {
   178  	t.gasLimit = gasLimit
   179  }
   180  
   181  func (t *prestateTracer) CaptureTxEnd(restGas uint64) {
   182  	if !t.config.DiffMode {
   183  		return
   184  	}
   185  
   186  	for addr, state := range t.pre {
   187  		// The deleted account's state is pruned from `post` but kept in `pre`
   188  		if _, ok := t.deleted[addr]; ok {
   189  			continue
   190  		}
   191  		modified := false
   192  		postAccount := &account{Storage: make(map[common.Hash]common.Hash)}
   193  		newBalance := t.env.StateDB.GetBalance(addr)
   194  		newNonce := t.env.StateDB.GetNonce(addr)
   195  		newCode := t.env.StateDB.GetCode(addr)
   196  
   197  		if newBalance.Cmp(t.pre[addr].Balance) != 0 {
   198  			modified = true
   199  			postAccount.Balance = newBalance
   200  		}
   201  		if newNonce != t.pre[addr].Nonce {
   202  			modified = true
   203  			postAccount.Nonce = newNonce
   204  		}
   205  		if !bytes.Equal(newCode, t.pre[addr].Code) {
   206  			modified = true
   207  			postAccount.Code = newCode
   208  		}
   209  
   210  		for key, val := range state.Storage {
   211  			// don't include the empty slot
   212  			if val == (common.Hash{}) {
   213  				delete(t.pre[addr].Storage, key)
   214  			}
   215  
   216  			newVal := t.env.StateDB.GetState(addr, key)
   217  			if val == newVal {
   218  				// Omit unchanged slots
   219  				delete(t.pre[addr].Storage, key)
   220  			} else {
   221  				modified = true
   222  				if newVal != (common.Hash{}) {
   223  					postAccount.Storage[key] = newVal
   224  				}
   225  			}
   226  		}
   227  
   228  		if modified {
   229  			t.post[addr] = postAccount
   230  		} else {
   231  			// if state is not modified, then no need to include into the pre state
   232  			delete(t.pre, addr)
   233  		}
   234  	}
   235  	// the new created contracts' prestate were empty, so delete them
   236  	for a := range t.created {
   237  		// the created contract maybe exists in statedb before the creating tx
   238  		if s := t.pre[a]; s != nil && !s.exists() {
   239  			delete(t.pre, a)
   240  		}
   241  	}
   242  }
   243  
   244  // GetResult returns the json-encoded nested list of call traces, and any
   245  // error arising from the encoding or forceful termination (via `Stop`).
   246  func (t *prestateTracer) GetResult() (json.RawMessage, error) {
   247  	var res []byte
   248  	var err error
   249  	if t.config.DiffMode {
   250  		res, err = json.Marshal(struct {
   251  			Post state `json:"post"`
   252  			Pre  state `json:"pre"`
   253  		}{t.post, t.pre})
   254  	} else {
   255  		res, err = json.Marshal(t.pre)
   256  	}
   257  	if err != nil {
   258  		return nil, err
   259  	}
   260  	return json.RawMessage(res), t.reason
   261  }
   262  
   263  // Stop terminates execution of the tracer at the first opportune moment.
   264  func (t *prestateTracer) Stop(err error) {
   265  	t.reason = err
   266  	t.interrupt.Store(true)
   267  }
   268  
   269  // lookupAccount fetches details of an account and adds it to the prestate
   270  // if it doesn't exist there.
   271  func (t *prestateTracer) lookupAccount(addr common.Address) {
   272  	if _, ok := t.pre[addr]; ok {
   273  		return
   274  	}
   275  
   276  	t.pre[addr] = &account{
   277  		Balance: t.env.StateDB.GetBalance(addr),
   278  		Nonce:   t.env.StateDB.GetNonce(addr),
   279  		Code:    t.env.StateDB.GetCode(addr),
   280  		Storage: make(map[common.Hash]common.Hash),
   281  	}
   282  }
   283  
   284  // lookupStorage fetches the requested storage slot and adds
   285  // it to the prestate of the given contract. It assumes `lookupAccount`
   286  // has been performed on the contract before.
   287  func (t *prestateTracer) lookupStorage(addr common.Address, key common.Hash) {
   288  	if _, ok := t.pre[addr].Storage[key]; ok {
   289  		return
   290  	}
   291  	t.pre[addr].Storage[key] = t.env.StateDB.GetState(addr, key)
   292  }