erigon-pulse/turbo/transactions/call.go

174 lines
5.4 KiB
Go
Raw Normal View History

package transactions
import (
"context"
"fmt"
"math/big"
"time"
"github.com/holiman/uint256"
"github.com/ledgerwatch/erigon/cmd/rpcdaemon/filters"
"github.com/ledgerwatch/erigon/common"
"github.com/ledgerwatch/erigon/core"
"github.com/ledgerwatch/erigon/core/rawdb"
"github.com/ledgerwatch/erigon/core/state"
"github.com/ledgerwatch/erigon/core/types"
"github.com/ledgerwatch/erigon/core/vm"
"github.com/ledgerwatch/erigon/ethdb/kv"
"github.com/ledgerwatch/erigon/internal/ethapi"
"github.com/ledgerwatch/erigon/params"
"github.com/ledgerwatch/erigon/rpc"
"github.com/ledgerwatch/erigon/turbo/rpchelper"
2021-07-29 10:23:23 +00:00
"github.com/ledgerwatch/log/v3"
)
const callTimeout = 5 * time.Minute
func DoCall(ctx context.Context, args ethapi.CallArgs, tx kv.Tx, blockNrOrHash rpc.BlockNumberOrHash, overrides *map[common.Address]ethapi.Account, gasCap uint64, chainConfig *params.ChainConfig, filters *filters.Filters) (*core.ExecutionResult, error) {
// todo: Pending state is only known by the miner
/*
if blockNrOrHash.BlockNumber != nil && *blockNrOrHash.BlockNumber == rpc.PendingBlockNumber {
block, state, _ := b.eth.miner.Pending()
return state, block.Header(), nil
}
*/
blockNrOrHash.RequireCanonical = true // DoCall cannot be executed on non-canonical blocks
blockNumber, hash, err := rpchelper.GetBlockNumber(blockNrOrHash, tx, filters)
if err != nil {
return nil, err
}
var stateReader state.StateReader
if num, ok := blockNrOrHash.Number(); ok && num == rpc.LatestBlockNumber {
stateReader = state.NewPlainStateReader(tx)
} else {
stateReader = state.NewPlainState(tx, blockNumber)
}
state := state.New(stateReader)
header := rawdb.ReadHeader(tx, hash, blockNumber)
if header == nil {
return nil, fmt.Errorf("block %d(%x) not found", blockNumber, hash)
}
// Override the fields of specified contracts before execution.
if overrides != nil {
for addr, account := range *overrides {
// Override account nonce.
if account.Nonce != nil {
state.SetNonce(addr, uint64(*account.Nonce))
}
// Override account(contract) code.
if account.Code != nil {
state.SetCode(addr, *account.Code)
}
// Override account balance.
if account.Balance != nil {
balance, overflow := uint256.FromBig((*big.Int)(*account.Balance))
if overflow {
return nil, fmt.Errorf("account.Balance higher than 2^256-1")
}
state.SetBalance(addr, balance)
}
if account.State != nil && account.StateDiff != nil {
return nil, fmt.Errorf("account %s has both 'state' and 'stateDiff'", addr.Hex())
}
// Replace entire state if caller requires.
if account.State != nil {
state.SetStorage(addr, *account.State)
}
// Apply state diff into specified accounts.
if account.StateDiff != nil {
for key, value := range *account.StateDiff {
key := key
state.SetState(addr, &key, value)
}
}
}
}
// Setup context so it may be cancelled the call has completed
// or, in case of unmetered gas, setup a context with a timeout.
var cancel context.CancelFunc
if callTimeout > 0 {
ctx, cancel = context.WithTimeout(ctx, callTimeout)
} else {
ctx, cancel = context.WithCancel(ctx)
}
// Make sure the context is cancelled when the call has completed
// this makes sure resources are cleaned up.
defer cancel()
// Get a new instance of the EVM.
2021-07-11 04:05:56 +00:00
var baseFee *uint256.Int
if header != nil && header.BaseFee != nil {
var overflow bool
baseFee, overflow = uint256.FromBig(header.BaseFee)
if overflow {
return nil, fmt.Errorf("header.BaseFee uint256 overflow")
}
}
2021-07-17 02:09:56 +00:00
msg, err := args.ToMessage(gasCap, baseFee)
2021-07-11 04:05:56 +00:00
if err != nil {
return nil, err
}
2021-03-14 18:52:15 +00:00
blockCtx, txCtx := GetEvmContext(msg, header, blockNrOrHash.RequireCanonical, tx)
2021-07-11 04:05:56 +00:00
evm := vm.NewEVM(blockCtx, txCtx, state, chainConfig, vm.Config{NoBaseFee: true})
// Wait for the context to be done and cancel the evm. Even if the
// EVM has finished, cancelling may be done (repeatedly)
go func() {
<-ctx.Done()
evm.Cancel()
}()
gp := new(core.GasPool).AddGas(msg.Gas())
result, err := core.ApplyMessage(evm, msg, gp, true /* refunds */, false /* gasBailout */)
if 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)", callTimeout)
}
return result, nil
}
func GetEvmContext(msg core.Message, header *types.Header, requireCanonical bool, tx kv.Tx) (vm.BlockContext, vm.TxContext) {
2021-07-08 17:04:31 +00:00
var baseFee uint256.Int
if header.Eip1559 {
overflow := baseFee.SetFromBig(header.BaseFee)
if overflow {
panic(fmt.Errorf("header.BaseFee higher than 2^256-1"))
}
}
2021-03-14 18:52:15 +00:00
return vm.BlockContext{
CanTransfer: core.CanTransfer,
Transfer: core.Transfer,
2021-03-30 09:53:54 +00:00
GetHash: getHashGetter(requireCanonical, tx),
CheckTEVM: func(common.Hash) (bool, error) { return false, nil },
2021-03-14 18:52:15 +00:00
Coinbase: header.Coinbase,
Aleut support (Eip1559) (#1704) * Where I am at * Refactoring of transaction types * More refactoring * Use Homested signer in rpc daemon * Unified signer * Continue unified signer * A bit more * Fixes and down the rabbit hole... * More tx pool fixes * More refactoring fixes * More fixes' * more fixes * More fixes * More compile fixes * More RLP hand-writing * Finish RLP encoding/decoding of transactions * Fixes to header encoding, start on protocol packets * Transaction decoding * Use DecodeTransaction function * Decoding BlockBodyPacket * Encode and decode for pool txs * Start fixing tests * Introduce SigningHash * Fixes to SignHash * RLP encoding fixes * Fixes for encoding/decoding * More test fixes * Fix more tests * More test fixes * More test fixes * Fix core tests * More fixes for signer * Fix for tx * Fixes to string encoding/size * Fix eip2930 test * Fix rest of ./tests * More fixes * Fix compilation * More test fixes * More test fixes * Test fixes * More fixes * Reuse EncodingSize in EncodeRLP for accessList * Rearrange things in dynamic fee tx * Add MarshalBinary * More fixes * Make V,R,S non-pointers * More NPE fixes * More fixes * Receipt fixes * Fix core/types * Fix ./eth * More compile fixes for tests * More test fixes * More test fixes * Try to see lint errors better * Try to see lint errors better * Fix lint * Debugging eip1559 test * Fix TestEIP1559Transition test * Fix NewBlockPacket encoding/decoding * Fix calculation of TxHash * Fix perf problem with senders * Update aleut config values * Try adding static peers * Add staticpeers to defaul flags * Change aleut networkID * Fix test Co-authored-by: Alex Sharp <alexsharp@Alexs-MacBook-Pro.local> Co-authored-by: Alexey Sharp <alexeysharp@Alexeys-iMac.local>
2021-04-22 17:11:37 +00:00
BlockNumber: header.Number.Uint64(),
Time: header.Time,
2021-03-14 18:52:15 +00:00
Difficulty: new(big.Int).Set(header.Difficulty),
GasLimit: header.GasLimit,
2021-07-08 17:04:31 +00:00
BaseFee: &baseFee,
2021-03-14 18:52:15 +00:00
},
vm.TxContext{
Origin: msg.From(),
GasPrice: msg.GasPrice().ToBig(),
}
}
func getHashGetter(requireCanonical bool, tx kv.Tx) func(uint64) common.Hash {
return func(n uint64) common.Hash {
2021-04-15 05:23:10 +00:00
hash, err := rawdb.ReadCanonicalHash(tx, n)
if err != nil {
log.Debug("can't get block hash by number", "number", n, "only-canonical", requireCanonical)
}
return hash
}
}