all: simplify function TransitionDb (#20830)

This commit is contained in:
JukLee0ira 2024-12-23 17:53:28 +08:00 committed by Daniel Liu
parent 69bca27fed
commit 48d1f22fde
11 changed files with 42 additions and 43 deletions

View file

@ -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.

View file

@ -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

View file

@ -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)
}
@ -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
//
@ -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 (
@ -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:
@ -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 (
@ -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) {

View file

@ -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
}

View file

@ -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
}
@ -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)
}

View file

@ -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
@ -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 {

View file

@ -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
@ -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
@ -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)
}

View file

@ -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
@ -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)
@ -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 {
@ -1443,7 +1443,7 @@ 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
}
@ -1451,7 +1451,7 @@ func (s *PublicBlockChainAPI) Call(ctx context.Context, args TransactionArgs, bl
if result.Failed() && len(result.Return()) > 0 {
return nil, newRevertError(result.Return())
}
return result.Return(), vmErr
return result.Return(), nil
}
type estimateGasError struct {
@ -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
@ -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)
}

View file

@ -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 {
@ -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()...)
}

View file

@ -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()

View file

@ -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) {