gitlab.com/lightnet1/go-ethereum@v1.9.30/cmd/evm/internal/t8ntool/execution.go (about) 1 // Copyright 2020 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 t8ntool 18 19 import ( 20 "fmt" 21 "math/big" 22 "os" 23 24 "gitlab.com/lightnet1/go-ethereum/common" 25 "gitlab.com/lightnet1/go-ethereum/common/math" 26 "gitlab.com/lightnet1/go-ethereum/consensus/misc" 27 "gitlab.com/lightnet1/go-ethereum/core" 28 "gitlab.com/lightnet1/go-ethereum/core/rawdb" 29 "gitlab.com/lightnet1/go-ethereum/core/state" 30 "gitlab.com/lightnet1/go-ethereum/core/types" 31 "gitlab.com/lightnet1/go-ethereum/core/vm" 32 "gitlab.com/lightnet1/go-ethereum/crypto" 33 "gitlab.com/lightnet1/go-ethereum/ethdb" 34 "gitlab.com/lightnet1/go-ethereum/log" 35 "gitlab.com/lightnet1/go-ethereum/params" 36 "gitlab.com/lightnet1/go-ethereum/rlp" 37 "gitlab.com/lightnet1/go-ethereum/trie" 38 "golang.org/x/crypto/sha3" 39 ) 40 41 type Prestate struct { 42 Env stEnv `json:"env"` 43 Pre core.GenesisAlloc `json:"pre"` 44 } 45 46 // ExecutionResult contains the execution status after running a state test, any 47 // error that might have occurred and a dump of the final state if requested. 48 type ExecutionResult struct { 49 StateRoot common.Hash `json:"stateRoot"` 50 TxRoot common.Hash `json:"txRoot"` 51 ReceiptRoot common.Hash `json:"receiptRoot"` 52 LogsHash common.Hash `json:"logsHash"` 53 Bloom types.Bloom `json:"logsBloom" gencodec:"required"` 54 Receipts types.Receipts `json:"receipts"` 55 Rejected []int `json:"rejected,omitempty"` 56 } 57 58 type ommer struct { 59 Delta uint64 `json:"delta"` 60 Address common.Address `json:"address"` 61 } 62 63 //go:generate gencodec -type stEnv -field-override stEnvMarshaling -out gen_stenv.go 64 type stEnv struct { 65 Coinbase common.Address `json:"currentCoinbase" gencodec:"required"` 66 Difficulty *big.Int `json:"currentDifficulty" gencodec:"required"` 67 GasLimit uint64 `json:"currentGasLimit" gencodec:"required"` 68 Number uint64 `json:"currentNumber" gencodec:"required"` 69 Timestamp uint64 `json:"currentTimestamp" gencodec:"required"` 70 BlockHashes map[math.HexOrDecimal64]common.Hash `json:"blockHashes,omitempty"` 71 Ommers []ommer `json:"ommers,omitempty"` 72 } 73 74 type stEnvMarshaling struct { 75 Coinbase common.UnprefixedAddress 76 Difficulty *math.HexOrDecimal256 77 GasLimit math.HexOrDecimal64 78 Number math.HexOrDecimal64 79 Timestamp math.HexOrDecimal64 80 } 81 82 // Apply applies a set of transactions to a pre-state 83 func (pre *Prestate) Apply(vmConfig vm.Config, chainConfig *params.ChainConfig, 84 txs types.Transactions, miningReward int64, 85 getTracerFn func(txIndex int, txHash common.Hash) (tracer vm.Tracer, err error)) (*state.StateDB, *ExecutionResult, error) { 86 87 // Capture errors for BLOCKHASH operation, if we haven't been supplied the 88 // required blockhashes 89 var hashError error 90 getHash := func(num uint64) common.Hash { 91 if pre.Env.BlockHashes == nil { 92 hashError = fmt.Errorf("getHash(%d) invoked, no blockhashes provided", num) 93 return common.Hash{} 94 } 95 h, ok := pre.Env.BlockHashes[math.HexOrDecimal64(num)] 96 if !ok { 97 hashError = fmt.Errorf("getHash(%d) invoked, blockhash for that block not provided", num) 98 } 99 return h 100 } 101 var ( 102 statedb = MakePreState(rawdb.NewMemoryDatabase(), pre.Pre) 103 signer = types.MakeSigner(chainConfig, new(big.Int).SetUint64(pre.Env.Number)) 104 gaspool = new(core.GasPool) 105 blockHash = common.Hash{0x13, 0x37} 106 rejectedTxs []int 107 includedTxs types.Transactions 108 gasUsed = uint64(0) 109 receipts = make(types.Receipts, 0) 110 txIndex = 0 111 ) 112 gaspool.AddGas(pre.Env.GasLimit) 113 vmContext := vm.Context{ 114 CanTransfer: core.CanTransfer, 115 Transfer: core.Transfer, 116 Coinbase: pre.Env.Coinbase, 117 BlockNumber: new(big.Int).SetUint64(pre.Env.Number), 118 Time: new(big.Int).SetUint64(pre.Env.Timestamp), 119 Difficulty: pre.Env.Difficulty, 120 GasLimit: pre.Env.GasLimit, 121 GetHash: getHash, 122 // GasPrice and Origin needs to be set per transaction 123 } 124 // If DAO is supported/enabled, we need to handle it here. In geth 'proper', it's 125 // done in StateProcessor.Process(block, ...), right before transactions are applied. 126 if chainConfig.DAOForkSupport && 127 chainConfig.DAOForkBlock != nil && 128 chainConfig.DAOForkBlock.Cmp(new(big.Int).SetUint64(pre.Env.Number)) == 0 { 129 misc.ApplyDAOHardFork(statedb) 130 } 131 132 for i, tx := range txs { 133 msg, err := tx.AsMessage(signer) 134 if err != nil { 135 log.Info("rejected tx", "index", i, "hash", tx.Hash(), "error", err) 136 rejectedTxs = append(rejectedTxs, i) 137 continue 138 } 139 tracer, err := getTracerFn(txIndex, tx.Hash()) 140 if err != nil { 141 return nil, nil, err 142 } 143 vmConfig.Tracer = tracer 144 vmConfig.Debug = (tracer != nil) 145 statedb.Prepare(tx.Hash(), blockHash, txIndex) 146 vmContext.GasPrice = msg.GasPrice() 147 vmContext.Origin = msg.From() 148 149 evm := vm.NewEVM(vmContext, statedb, chainConfig, vmConfig) 150 snapshot := statedb.Snapshot() 151 // (ret []byte, usedGas uint64, failed bool, err error) 152 msgResult, err := core.ApplyMessage(evm, msg, gaspool) 153 if err != nil { 154 statedb.RevertToSnapshot(snapshot) 155 log.Info("rejected tx", "index", i, "hash", tx.Hash(), "from", msg.From(), "error", err) 156 rejectedTxs = append(rejectedTxs, i) 157 continue 158 } 159 includedTxs = append(includedTxs, tx) 160 if hashError != nil { 161 return nil, nil, NewError(ErrorMissingBlockhash, hashError) 162 } 163 gasUsed += msgResult.UsedGas 164 // Create a new receipt for the transaction, storing the intermediate root and gas used by the tx 165 { 166 var root []byte 167 if chainConfig.IsByzantium(vmContext.BlockNumber) { 168 statedb.Finalise(true) 169 } else { 170 root = statedb.IntermediateRoot(chainConfig.IsEIP158(vmContext.BlockNumber)).Bytes() 171 } 172 173 receipt := types.NewReceipt(root, msgResult.Failed(), gasUsed) 174 receipt.TxHash = tx.Hash() 175 receipt.GasUsed = msgResult.UsedGas 176 // if the transaction created a contract, store the creation address in the receipt. 177 if msg.To() == nil { 178 receipt.ContractAddress = crypto.CreateAddress(evm.Context.Origin, tx.Nonce()) 179 } 180 // Set the receipt logs and create a bloom for filtering 181 receipt.Logs = statedb.GetLogs(tx.Hash()) 182 receipt.Bloom = types.CreateBloom(types.Receipts{receipt}) 183 // These three are non-consensus fields 184 //receipt.BlockHash 185 //receipt.BlockNumber = 186 receipt.TransactionIndex = uint(txIndex) 187 receipts = append(receipts, receipt) 188 } 189 txIndex++ 190 } 191 statedb.IntermediateRoot(chainConfig.IsEIP158(vmContext.BlockNumber)) 192 // Add mining reward? 193 if miningReward > 0 { 194 // Add mining reward. The mining reward may be `0`, which only makes a difference in the cases 195 // where 196 // - the coinbase suicided, or 197 // - there are only 'bad' transactions, which aren't executed. In those cases, 198 // the coinbase gets no txfee, so isn't created, and thus needs to be touched 199 var ( 200 blockReward = big.NewInt(miningReward) 201 minerReward = new(big.Int).Set(blockReward) 202 perOmmer = new(big.Int).Div(blockReward, big.NewInt(32)) 203 ) 204 for _, ommer := range pre.Env.Ommers { 205 // Add 1/32th for each ommer included 206 minerReward.Add(minerReward, perOmmer) 207 // Add (8-delta)/8 208 reward := big.NewInt(8) 209 reward.Sub(reward, big.NewInt(0).SetUint64(ommer.Delta)) 210 reward.Mul(reward, blockReward) 211 reward.Div(reward, big.NewInt(8)) 212 statedb.AddBalance(ommer.Address, reward) 213 } 214 statedb.AddBalance(pre.Env.Coinbase, minerReward) 215 } 216 // Commit block 217 root, err := statedb.Commit(chainConfig.IsEIP158(vmContext.BlockNumber)) 218 if err != nil { 219 fmt.Fprintf(os.Stderr, "Could not commit state: %v", err) 220 return nil, nil, NewError(ErrorEVM, fmt.Errorf("could not commit state: %v", err)) 221 } 222 execRs := &ExecutionResult{ 223 StateRoot: root, 224 TxRoot: types.DeriveSha(includedTxs, new(trie.Trie)), 225 ReceiptRoot: types.DeriveSha(receipts, new(trie.Trie)), 226 Bloom: types.CreateBloom(receipts), 227 LogsHash: rlpHash(statedb.Logs()), 228 Receipts: receipts, 229 Rejected: rejectedTxs, 230 } 231 return statedb, execRs, nil 232 } 233 234 func MakePreState(db ethdb.Database, accounts core.GenesisAlloc) *state.StateDB { 235 sdb := state.NewDatabase(db) 236 statedb, _ := state.New(common.Hash{}, sdb, nil) 237 for addr, a := range accounts { 238 statedb.SetCode(addr, a.Code) 239 statedb.SetNonce(addr, a.Nonce) 240 statedb.SetBalance(addr, a.Balance) 241 for k, v := range a.Storage { 242 statedb.SetState(addr, k, v) 243 } 244 } 245 // Commit and re-open to start with a clean state. 246 root, _ := statedb.Commit(false) 247 statedb, _ = state.New(root, sdb, nil) 248 return statedb 249 } 250 251 func rlpHash(x interface{}) (h common.Hash) { 252 hw := sha3.NewLegacyKeccak256() 253 rlp.Encode(hw, x) 254 hw.Sum(h[:0]) 255 return h 256 }