Skip to content

Commit

Permalink
all: simplify_function TransitionDb (20830)
Browse files Browse the repository at this point in the history
  • Loading branch information
JukLee0ira committed Dec 23, 2024
1 parent 82ff8c1 commit d7f4e47
Show file tree
Hide file tree
Showing 11 changed files with 43 additions and 44 deletions.
3 changes: 1 addition & 2 deletions accounts/abi/bind/backends/simulated.go
Original file line number Diff line number Diff line change
Expand Up @@ -478,8 +478,7 @@ func (b *SimulatedBackend) callContract(ctx context.Context, call XDPoSChain.Cal
vmenv := vm.NewEVM(evmContext, txContext, statedb, nil, b.config, vm.Config{NoBaseFee: true})
gaspool := new(core.GasPool).AddGas(math.MaxUint64)
owner := common.Address{}
res, err, _ := core.NewStateTransition(vmenv, msg, gaspool).TransitionDb(owner)
return res, err
return core.NewStateTransition(vmenv, msg, gaspool).TransitionDb(owner)
}

// SendTransaction updates the pending block to include the given transaction.
Expand Down
2 changes: 1 addition & 1 deletion core/state_processor.go
Original file line number Diff line number Diff line change
Expand Up @@ -403,7 +403,7 @@ func applyTransaction(config *params.ChainConfig, tokensFee map[common.Address]*
// End Bypass blacklist address

// Apply the transaction to the current state (included in the env)
result, err, _ := ApplyMessage(evm, msg, gp, coinbaseOwner)
result, err := ApplyMessage(evm, msg, gp, coinbaseOwner)

if err != nil {
return nil, 0, err, false
Expand Down
18 changes: 9 additions & 9 deletions core/state_transition.go
Original file line number Diff line number Diff line change
Expand Up @@ -194,7 +194,7 @@ func NewStateTransition(evm *vm.EVM, msg Message, gp *GasPool) *StateTransition
// the gas used (which includes gas refunds) and an error if it failed. An error always
// indicates a core error meaning that the message would always fail for that particular
// state and would never be accepted within a block.
func ApplyMessage(evm *vm.EVM, msg Message, gp *GasPool, owner common.Address) (*ExecutionResult, error, error) {
func ApplyMessage(evm *vm.EVM, msg Message, gp *GasPool, owner common.Address) (*ExecutionResult, error) {
return NewStateTransition(evm, msg, gp).TransitionDb(owner)
}

Expand Down Expand Up @@ -317,7 +317,7 @@ func (st *StateTransition) preCheck() error {
//
// However if any consensus issue encountered, return the error directly with
// nil evm execution result.
func (st *StateTransition) TransitionDb(owner common.Address) (*ExecutionResult, error, error) {
func (st *StateTransition) TransitionDb(owner common.Address) (*ExecutionResult, error) {
// First check this message satisfies all consensus rules before
// applying the message. The rules include these clauses
//
Expand All @@ -330,7 +330,7 @@ func (st *StateTransition) TransitionDb(owner common.Address) (*ExecutionResult,

// Check clauses 1-3, buy gas if everything is correct
if err := st.preCheck(); err != nil {
return nil, err, nil
return nil, err
}

var (
Expand All @@ -345,16 +345,16 @@ func (st *StateTransition) TransitionDb(owner common.Address) (*ExecutionResult,
// Check clauses 4-5, subtract intrinsic gas if everything is correct
gas, err := IntrinsicGas(st.data, st.msg.AccessList(), contractCreation, homestead, rules.IsEIP1559)
if err != nil {
return nil, err, nil
return nil, err
}
if st.gas < gas {
return nil, fmt.Errorf("%w: have %d, want %d", ErrIntrinsicGas, st.gas, gas), nil
return nil, fmt.Errorf("%w: have %d, want %d", ErrIntrinsicGas, st.gas, gas)
}
st.gas -= gas

// Check whether the init code size has been exceeded.
if rules.IsEIP1559 && contractCreation && len(st.data) > params.MaxInitCodeSize {
return nil, fmt.Errorf("%w: code size %v limit %v", ErrMaxInitCodeSizeExceeded, len(st.data), params.MaxInitCodeSize), nil
return nil, fmt.Errorf("%w: code size %v limit %v", ErrMaxInitCodeSizeExceeded, len(st.data), params.MaxInitCodeSize)
}

// Execute the preparatory steps for state transition which includes:
Expand All @@ -365,10 +365,10 @@ func (st *StateTransition) TransitionDb(owner common.Address) (*ExecutionResult,
// Check clause 6
value, overflow := uint256.FromBig(msg.Value())
if overflow {
return nil, fmt.Errorf("%w: address %v", ErrInsufficientFundsForTransfer, msg.From().Hex()), nil
return nil, fmt.Errorf("%w: address %v", ErrInsufficientFundsForTransfer, msg.From().Hex())
}
if !value.IsZero() && !st.evm.Context.CanTransfer(st.state, msg.From(), value.ToBig()) {
return nil, fmt.Errorf("%w: address %v", ErrInsufficientFundsForTransfer, msg.From().Hex()), nil
return nil, fmt.Errorf("%w: address %v", ErrInsufficientFundsForTransfer, msg.From().Hex())
}

var (
Expand Down Expand Up @@ -406,7 +406,7 @@ func (st *StateTransition) TransitionDb(owner common.Address) (*ExecutionResult,
UsedGas: st.gasUsed(),
Err: vmerr,
ReturnData: ret,
}, nil, vmerr
}, nil
}

func (st *StateTransition) refundGas(refundQuotient uint64) {
Expand Down
2 changes: 1 addition & 1 deletion core/token_validator.go
Original file line number Diff line number Diff line change
Expand Up @@ -117,7 +117,7 @@ func CallContractWithState(call ethereum.CallMsg, chain consensus.ChainContext,
vmenv := vm.NewEVM(evmContext, txContext, statedb, nil, chain.Config(), vm.Config{})
gaspool := new(GasPool).AddGas(1000000)
owner := common.Address{}
result, err, _ := NewStateTransition(vmenv, msg, gaspool).TransitionDb(owner)
result, err := NewStateTransition(vmenv, msg, gaspool).TransitionDb(owner)
if err != nil {
return nil, err
}
Expand Down
4 changes: 2 additions & 2 deletions eth/api_tracer.go
Original file line number Diff line number Diff line change
Expand Up @@ -526,7 +526,7 @@ func (api *PrivateDebugAPI) traceBlock(ctx context.Context, block *types.Block,

vmenv := vm.NewEVM(blockCtx, txContext, statedb, XDCxState, api.config, vm.Config{})
owner := common.Address{}
if _, err, _ := core.ApplyMessage(vmenv, msg, new(core.GasPool).AddGas(msg.Gas()), owner); err != nil {
if _, err := core.ApplyMessage(vmenv, msg, new(core.GasPool).AddGas(msg.Gas()), owner); err != nil {
failed = err
break
}
Expand Down Expand Up @@ -750,7 +750,7 @@ func (api *PrivateDebugAPI) traceTx(ctx context.Context, message core.Message, t
statedb.SetTxContext(txctx.TxHash, txctx.TxIndex)

owner := common.Address{}
result, err, _ := core.ApplyMessage(vmenv, message, new(core.GasPool).AddGas(message.Gas()), owner)
result, err := core.ApplyMessage(vmenv, message, new(core.GasPool).AddGas(message.Gas()), owner)
if err != nil {
return nil, fmt.Errorf("tracing failed: %v", err)
}
Expand Down
4 changes: 2 additions & 2 deletions eth/tracers/testing/calltrace_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -120,7 +120,7 @@ func testCallTracer(tracerName string, dirPath string, t *testing.T) {
t.Fatalf("failed to prepare transaction for tracing: %v", err)
}
st := core.NewStateTransition(evm, msg, new(core.GasPool).AddGas(tx.Gas()))
if _, err, _ = st.TransitionDb(common.Address{}); err != nil {
if _, err = st.TransitionDb(common.Address{}); err != nil {
t.Fatalf("failed to execute transaction: %v", err)
}
// Retrieve the trace result and compare against the etalon
Expand Down Expand Up @@ -231,7 +231,7 @@ func benchTracer(tracerName string, test *callTracerTest, b *testing.B) {
evm := vm.NewEVM(context, txContext, statedb, nil, test.Genesis.Config, vm.Config{Debug: true, Tracer: tracer})
snap := statedb.Snapshot()
st := core.NewStateTransition(evm, msg, new(core.GasPool).AddGas(tx.Gas()))
if _, err, _ = st.TransitionDb(common.Address{}); err != nil {
if _, err = st.TransitionDb(common.Address{}); err != nil {
b.Fatalf("failed to execute transaction: %v", err)
}
if _, err = tracer.GetResult(); err != nil {
Expand Down
6 changes: 3 additions & 3 deletions eth/tracers/tracers_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -158,7 +158,7 @@ func TestZeroValueToNotExitCall(t *testing.T) {
t.Fatalf("failed to prepare transaction for tracing: %v", err)
}
st := core.NewStateTransition(evm, msg, new(core.GasPool).AddGas(tx.Gas()))
if _, err, _ = st.TransitionDb(common.Address{}); err != nil {
if _, err = st.TransitionDb(common.Address{}); err != nil {
t.Fatalf("failed to execute transaction: %v", err)
}
// Retrieve the trace result and compare against the etalon
Expand Down Expand Up @@ -244,7 +244,7 @@ func TestPrestateTracerCreate2(t *testing.T) {
t.Fatalf("failed to prepare transaction for tracing: %v", err)
}
st := core.NewStateTransition(evm, msg, new(core.GasPool).AddGas(tx.Gas()))
if _, err, _ = st.TransitionDb(common.Address{}); err != nil {
if _, err = st.TransitionDb(common.Address{}); err != nil {
t.Fatalf("failed to execute transaction: %v", err)
}
// Retrieve the trace result and compare against the etalon
Expand Down Expand Up @@ -346,7 +346,7 @@ func BenchmarkTransactionTrace(b *testing.B) {
for i := 0; i < b.N; i++ {
snap := statedb.Snapshot()
st := core.NewStateTransition(evm, msg, new(core.GasPool).AddGas(tx.Gas()))
_, err, _ = st.TransitionDb(common.Address{})
_, err = st.TransitionDb(common.Address{})
if err != nil {
b.Fatal(err)
}
Expand Down
40 changes: 20 additions & 20 deletions internal/ethapi/api.go
Original file line number Diff line number Diff line change
Expand Up @@ -1322,18 +1322,18 @@ func (s *PublicBlockChainAPI) getCandidatesFromSmartContract() ([]utils.Masterno
return candidatesWithStakeInfo, nil
}

func DoCall(ctx context.Context, b Backend, args TransactionArgs, blockNrOrHash rpc.BlockNumberOrHash, overrides *StateOverride, timeout time.Duration, globalGasCap uint64) (*core.ExecutionResult, error, error) {
func DoCall(ctx context.Context, b Backend, args TransactionArgs, blockNrOrHash rpc.BlockNumberOrHash, overrides *StateOverride, timeout time.Duration, globalGasCap uint64) (*core.ExecutionResult, error) {
defer func(start time.Time) { log.Debug("Executing EVM call finished", "runtime", time.Since(start)) }(time.Now())

statedb, header, err := b.StateAndHeaderByNumberOrHash(ctx, blockNrOrHash)
if statedb == nil || err != nil {
return nil, err, nil
return nil, err
}
if header == nil {
return nil, errors.New("nil header in DoCall"), nil
return nil, errors.New("nil header in DoCall")
}
if err := overrides.Apply(statedb); err != nil {
return nil, err, nil
return nil, err
}

// Setup context so it may be cancelled the call has completed
Expand All @@ -1350,32 +1350,32 @@ func DoCall(ctx context.Context, b Backend, args TransactionArgs, blockNrOrHash

block, err := b.BlockByNumberOrHash(ctx, blockNrOrHash)
if err != nil {
return nil, err, nil
return nil, err
}
if block == nil {
return nil, fmt.Errorf("nil block in DoCall: number=%d, hash=%s", header.Number.Uint64(), header.Hash().Hex()), nil
return nil, fmt.Errorf("nil block in DoCall: number=%d, hash=%s", header.Number.Uint64(), header.Hash().Hex())
}
author, err := b.GetEngine().Author(block.Header())
if err != nil {
return nil, err, nil
return nil, err
}
XDCxState, err := b.XDCxService().GetTradingState(block, author)
if err != nil {
return nil, err, nil
return nil, err
}

// TODO: replace header.BaseFee with blockCtx.BaseFee
// reference: https://github.com/ethereum/go-ethereum/pull/29051
msg, err := args.ToMessage(b, header.Number, globalGasCap, header.BaseFee)
if err != nil {
return nil, err, nil
return nil, err
}
msg.SetBalanceTokenFeeForCall()

// Get a new instance of the EVM.
evm, vmError, err := b.GetEVM(ctx, msg, statedb, XDCxState, header, &vm.Config{NoBaseFee: true})
if err != nil {
return nil, err, nil
return nil, err
}
// Wait for the context to be done and cancel the evm. Even if the
// EVM has finished, cancelling may be done (repeatedly)
Expand All @@ -1387,19 +1387,19 @@ func DoCall(ctx context.Context, b Backend, args TransactionArgs, blockNrOrHash
// Execute the message.
gp := new(core.GasPool).AddGas(math.MaxUint64)
owner := common.Address{}
result, err, vmErr := core.ApplyMessage(evm, msg, gp, owner)
result, err := core.ApplyMessage(evm, msg, gp, owner)
if err := vmError(); err != nil {
return nil, err, nil
return nil, err
}

// If the timer caused an abort, return an appropriate error message
if evm.Cancelled() {
return nil, fmt.Errorf("execution aborted (timeout = %v)", timeout), nil
return nil, fmt.Errorf("execution aborted (timeout = %v)", timeout)
}
if err != nil {
return result, fmt.Errorf("err: %w (supplied gas %d)", err, msg.Gas()), nil
return result, fmt.Errorf("err: %w (supplied gas %d)", err, msg.Gas())
}
return result, err, vmErr
return result, err
}

func newRevertError(res []byte) *revertError {
Expand Down Expand Up @@ -1443,15 +1443,15 @@ func (s *PublicBlockChainAPI) Call(ctx context.Context, args TransactionArgs, bl
if args.To != nil && *args.To == common.MasternodeVotingSMCBinary {
timeout = 0
}
result, err, vmErr := DoCall(ctx, s.b, args, *blockNrOrHash, overrides, timeout, s.b.RPCGasCap())
result, err := DoCall(ctx, s.b, args, *blockNrOrHash, overrides, timeout, s.b.RPCGasCap())
if err != nil {
return nil, err
}
// If the result contains a revert reason, try to unpack and return it.
if result.Failed() && len(result.Return()) > 0 {
if result.Failed() {
return nil, newRevertError(result.Return())
}
return result.Return(), vmErr
return result.Return(), nil
}

type estimateGasError struct {
Expand Down Expand Up @@ -1515,7 +1515,7 @@ func DoEstimateGas(ctx context.Context, b Backend, args TransactionArgs, blockNr
executable := func(gas uint64) (bool, *core.ExecutionResult, error) {
args.Gas = (*hexutil.Uint64)(&gas)

result, err, _ := DoCall(ctx, b, args, blockNrOrHash, nil, 0, gasCap)
result, err := DoCall(ctx, b, args, blockNrOrHash, nil, 0, gasCap)
if err != nil {
if errors.Is(err, vm.ErrOutOfGas) || errors.Is(err, core.ErrIntrinsicGas) {
return true, nil, nil // Special case, raise gas limit
Expand Down Expand Up @@ -2096,7 +2096,7 @@ func AccessList(ctx context.Context, b Backend, blockNrOrHash rpc.BlockNumberOrH
return nil, 0, nil, err
}
// TODO: determine the value of owner
res, err, _ := core.ApplyMessage(vmenv, msg, new(core.GasPool).AddGas(msg.Gas()), owner)
res, err := core.ApplyMessage(vmenv, msg, new(core.GasPool).AddGas(msg.Gas()), owner)
if err != nil {
return nil, 0, nil, fmt.Errorf("failed to apply transaction: %v err: %v", args.toTransaction().Hash(), err)
}
Expand Down
4 changes: 2 additions & 2 deletions les/odr_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -142,7 +142,7 @@ func odrContractCall(ctx context.Context, db ethdb.Database, config *params.Chai
//vmenv := core.NewEnv(statedb, config, bc, msg, header, vm.Config{})
gp := new(core.GasPool).AddGas(math.MaxUint64)
owner := common.Address{}
result, _, _ := core.ApplyMessage(vmenv, msg, gp, owner)
result, _ := core.ApplyMessage(vmenv, msg, gp, owner)
res = append(res, result.Return()...)
}
} else {
Expand All @@ -160,7 +160,7 @@ func odrContractCall(ctx context.Context, db ethdb.Database, config *params.Chai
vmenv := vm.NewEVM(context, txContext, statedb, nil, config, vm.Config{NoBaseFee: true})
gp := new(core.GasPool).AddGas(math.MaxUint64)
owner := common.Address{}
result, _, _ := core.ApplyMessage(vmenv, msg, gp, owner)
result, _ := core.ApplyMessage(vmenv, msg, gp, owner)
if statedb.Error() == nil {
res = append(res, result.Return()...)
}
Expand Down
2 changes: 1 addition & 1 deletion light/odr_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -191,7 +191,7 @@ func odrContractCall(ctx context.Context, db ethdb.Database, bc *core.BlockChain
vmenv := vm.NewEVM(context, txContext, st, nil, config, vm.Config{NoBaseFee: true})
gp := new(core.GasPool).AddGas(math.MaxUint64)
owner := common.Address{}
result, _, _ := core.ApplyMessage(vmenv, msg, gp, owner)
result, _ := core.ApplyMessage(vmenv, msg, gp, owner)
res = append(res, result.Return()...)
if st.Error() != nil {
return res, st.Error()
Expand Down
2 changes: 1 addition & 1 deletion tests/state_test_util.go
Original file line number Diff line number Diff line change
Expand Up @@ -166,7 +166,7 @@ func (t *StateTest) Run(subtest StateSubtest, vmconfig vm.Config) (*state.StateD
gaspool.AddGas(block.GasLimit())

coinbase := &t.json.Env.Coinbase
if _, err, _ := core.ApplyMessage(evm, msg, gaspool, *coinbase); err != nil {
if _, err := core.ApplyMessage(evm, msg, gaspool, *coinbase); err != nil {
statedb.RevertToSnapshot(snapshot)
}
if logs := rlpHash(statedb.Logs()); logs != common.Hash(post.Logs) {
Expand Down

0 comments on commit d7f4e47

Please sign in to comment.