github.com/codysnider/go-ethereum@v1.10.18-0.20220420071915-14f4ae99222a/cmd/evm/internal/t8ntool/transition.go (about) 1 // Copyright 2020 The go-ethereum Authors 2 // This file is part of go-ethereum. 3 // 4 // go-ethereum is free software: you can redistribute it and/or modify 5 // it under the terms of the GNU 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 // go-ethereum 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 General Public License for more details. 13 // 14 // You should have received a copy of the GNU General Public License 15 // along with go-ethereum. If not, see <http://www.gnu.org/licenses/>. 16 17 package t8ntool 18 19 import ( 20 "crypto/ecdsa" 21 "encoding/json" 22 "errors" 23 "fmt" 24 "io/ioutil" 25 "math/big" 26 "os" 27 "path" 28 "strings" 29 30 "github.com/ethereum/go-ethereum/common" 31 "github.com/ethereum/go-ethereum/common/hexutil" 32 "github.com/ethereum/go-ethereum/core" 33 "github.com/ethereum/go-ethereum/core/state" 34 "github.com/ethereum/go-ethereum/core/types" 35 "github.com/ethereum/go-ethereum/core/vm" 36 "github.com/ethereum/go-ethereum/crypto" 37 "github.com/ethereum/go-ethereum/eth/tracers/logger" 38 "github.com/ethereum/go-ethereum/log" 39 "github.com/ethereum/go-ethereum/params" 40 "github.com/ethereum/go-ethereum/rlp" 41 "github.com/ethereum/go-ethereum/tests" 42 "gopkg.in/urfave/cli.v1" 43 ) 44 45 const ( 46 ErrorEVM = 2 47 ErrorConfig = 3 48 ErrorMissingBlockhash = 4 49 50 ErrorJson = 10 51 ErrorIO = 11 52 ErrorRlp = 12 53 54 stdinSelector = "stdin" 55 ) 56 57 type NumberedError struct { 58 errorCode int 59 err error 60 } 61 62 func NewError(errorCode int, err error) *NumberedError { 63 return &NumberedError{errorCode, err} 64 } 65 66 func (n *NumberedError) Error() string { 67 return fmt.Sprintf("ERROR(%d): %v", n.errorCode, n.err.Error()) 68 } 69 70 func (n *NumberedError) ExitCode() int { 71 return n.errorCode 72 } 73 74 // compile-time conformance test 75 var ( 76 _ cli.ExitCoder = (*NumberedError)(nil) 77 ) 78 79 type input struct { 80 Alloc core.GenesisAlloc `json:"alloc,omitempty"` 81 Env *stEnv `json:"env,omitempty"` 82 Txs []*txWithKey `json:"txs,omitempty"` 83 TxRlp string `json:"txsRlp,omitempty"` 84 } 85 86 func Transition(ctx *cli.Context) error { 87 // Configure the go-ethereum logger 88 glogger := log.NewGlogHandler(log.StreamHandler(os.Stderr, log.TerminalFormat(false))) 89 glogger.Verbosity(log.Lvl(ctx.Int(VerbosityFlag.Name))) 90 log.Root().SetHandler(glogger) 91 92 var ( 93 err error 94 tracer vm.EVMLogger 95 ) 96 var getTracer func(txIndex int, txHash common.Hash) (vm.EVMLogger, error) 97 98 baseDir, err := createBasedir(ctx) 99 if err != nil { 100 return NewError(ErrorIO, fmt.Errorf("failed creating output basedir: %v", err)) 101 } 102 if ctx.Bool(TraceFlag.Name) { 103 if ctx.IsSet(TraceDisableMemoryFlag.Name) && ctx.IsSet(TraceEnableMemoryFlag.Name) { 104 return NewError(ErrorConfig, fmt.Errorf("can't use both flags --%s and --%s", TraceDisableMemoryFlag.Name, TraceEnableMemoryFlag.Name)) 105 } 106 if ctx.IsSet(TraceDisableReturnDataFlag.Name) && ctx.IsSet(TraceEnableReturnDataFlag.Name) { 107 return NewError(ErrorConfig, fmt.Errorf("can't use both flags --%s and --%s", TraceDisableReturnDataFlag.Name, TraceEnableReturnDataFlag.Name)) 108 } 109 if ctx.IsSet(TraceDisableMemoryFlag.Name) { 110 log.Warn(fmt.Sprintf("--%s has been deprecated in favour of --%s", TraceDisableMemoryFlag.Name, TraceEnableMemoryFlag.Name)) 111 } 112 if ctx.IsSet(TraceDisableReturnDataFlag.Name) { 113 log.Warn(fmt.Sprintf("--%s has been deprecated in favour of --%s", TraceDisableReturnDataFlag.Name, TraceEnableReturnDataFlag.Name)) 114 } 115 // Configure the EVM logger 116 logConfig := &logger.Config{ 117 DisableStack: ctx.Bool(TraceDisableStackFlag.Name), 118 EnableMemory: !ctx.Bool(TraceDisableMemoryFlag.Name) || ctx.Bool(TraceEnableMemoryFlag.Name), 119 EnableReturnData: !ctx.Bool(TraceDisableReturnDataFlag.Name) || ctx.Bool(TraceEnableReturnDataFlag.Name), 120 Debug: true, 121 } 122 var prevFile *os.File 123 // This one closes the last file 124 defer func() { 125 if prevFile != nil { 126 prevFile.Close() 127 } 128 }() 129 getTracer = func(txIndex int, txHash common.Hash) (vm.EVMLogger, error) { 130 if prevFile != nil { 131 prevFile.Close() 132 } 133 traceFile, err := os.Create(path.Join(baseDir, fmt.Sprintf("trace-%d-%v.jsonl", txIndex, txHash.String()))) 134 if err != nil { 135 return nil, NewError(ErrorIO, fmt.Errorf("failed creating trace-file: %v", err)) 136 } 137 prevFile = traceFile 138 return logger.NewJSONLogger(logConfig, traceFile), nil 139 } 140 } else { 141 getTracer = func(txIndex int, txHash common.Hash) (tracer vm.EVMLogger, err error) { 142 return nil, nil 143 } 144 } 145 // We need to load three things: alloc, env and transactions. May be either in 146 // stdin input or in files. 147 // Check if anything needs to be read from stdin 148 var ( 149 prestate Prestate 150 txs types.Transactions // txs to apply 151 allocStr = ctx.String(InputAllocFlag.Name) 152 153 envStr = ctx.String(InputEnvFlag.Name) 154 txStr = ctx.String(InputTxsFlag.Name) 155 inputData = &input{} 156 ) 157 // Figure out the prestate alloc 158 if allocStr == stdinSelector || envStr == stdinSelector || txStr == stdinSelector { 159 decoder := json.NewDecoder(os.Stdin) 160 if err := decoder.Decode(inputData); err != nil { 161 return NewError(ErrorJson, fmt.Errorf("failed unmarshaling stdin: %v", err)) 162 } 163 } 164 if allocStr != stdinSelector { 165 if err := readFile(allocStr, "alloc", &inputData.Alloc); err != nil { 166 return err 167 } 168 } 169 prestate.Pre = inputData.Alloc 170 171 // Set the block environment 172 if envStr != stdinSelector { 173 var env stEnv 174 if err := readFile(envStr, "env", &env); err != nil { 175 return err 176 } 177 inputData.Env = &env 178 } 179 prestate.Env = *inputData.Env 180 181 vmConfig := vm.Config{ 182 Tracer: tracer, 183 Debug: (tracer != nil), 184 } 185 // Construct the chainconfig 186 var chainConfig *params.ChainConfig 187 if cConf, extraEips, err := tests.GetChainConfig(ctx.String(ForknameFlag.Name)); err != nil { 188 return NewError(ErrorConfig, fmt.Errorf("failed constructing chain configuration: %v", err)) 189 } else { 190 chainConfig = cConf 191 vmConfig.ExtraEips = extraEips 192 } 193 // Set the chain id 194 chainConfig.ChainID = big.NewInt(ctx.Int64(ChainIDFlag.Name)) 195 196 var txsWithKeys []*txWithKey 197 if txStr != stdinSelector { 198 inFile, err := os.Open(txStr) 199 if err != nil { 200 return NewError(ErrorIO, fmt.Errorf("failed reading txs file: %v", err)) 201 } 202 defer inFile.Close() 203 decoder := json.NewDecoder(inFile) 204 if strings.HasSuffix(txStr, ".rlp") { 205 var body hexutil.Bytes 206 if err := decoder.Decode(&body); err != nil { 207 return err 208 } 209 var txs types.Transactions 210 if err := rlp.DecodeBytes(body, &txs); err != nil { 211 return err 212 } 213 for _, tx := range txs { 214 txsWithKeys = append(txsWithKeys, &txWithKey{ 215 key: nil, 216 tx: tx, 217 }) 218 } 219 } else { 220 if err := decoder.Decode(&txsWithKeys); err != nil { 221 return NewError(ErrorJson, fmt.Errorf("failed unmarshaling txs-file: %v", err)) 222 } 223 } 224 } else { 225 if len(inputData.TxRlp) > 0 { 226 // Decode the body of already signed transactions 227 body := common.FromHex(inputData.TxRlp) 228 var txs types.Transactions 229 if err := rlp.DecodeBytes(body, &txs); err != nil { 230 return err 231 } 232 for _, tx := range txs { 233 txsWithKeys = append(txsWithKeys, &txWithKey{ 234 key: nil, 235 tx: tx, 236 }) 237 } 238 } else { 239 // JSON encoded transactions 240 txsWithKeys = inputData.Txs 241 } 242 } 243 // We may have to sign the transactions. 244 signer := types.MakeSigner(chainConfig, big.NewInt(int64(prestate.Env.Number))) 245 246 if txs, err = signUnsignedTransactions(txsWithKeys, signer); err != nil { 247 return NewError(ErrorJson, fmt.Errorf("failed signing transactions: %v", err)) 248 } 249 // Sanity check, to not `panic` in state_transition 250 if chainConfig.IsLondon(big.NewInt(int64(prestate.Env.Number))) { 251 if prestate.Env.BaseFee == nil { 252 return NewError(ErrorConfig, errors.New("EIP-1559 config but missing 'currentBaseFee' in env section")) 253 } 254 } 255 // Sanity check, to not `panic` in state_transition 256 if prestate.Env.Random != nil && !chainConfig.IsLondon(big.NewInt(int64(prestate.Env.Number))) { 257 return NewError(ErrorConfig, errors.New("can only apply RANDOM on top of London chainrules")) 258 } 259 if env := prestate.Env; env.Difficulty == nil { 260 // If difficulty was not provided by caller, we need to calculate it. 261 switch { 262 case env.ParentDifficulty == nil: 263 return NewError(ErrorConfig, errors.New("currentDifficulty was not provided, and cannot be calculated due to missing parentDifficulty")) 264 case env.Number == 0: 265 return NewError(ErrorConfig, errors.New("currentDifficulty needs to be provided for block number 0")) 266 case env.Timestamp <= env.ParentTimestamp: 267 return NewError(ErrorConfig, fmt.Errorf("currentDifficulty cannot be calculated -- currentTime (%d) needs to be after parent time (%d)", 268 env.Timestamp, env.ParentTimestamp)) 269 } 270 prestate.Env.Difficulty = calcDifficulty(chainConfig, env.Number, env.Timestamp, 271 env.ParentTimestamp, env.ParentDifficulty, env.ParentUncleHash) 272 } 273 // Run the test and aggregate the result 274 s, result, err := prestate.Apply(vmConfig, chainConfig, txs, ctx.Int64(RewardFlag.Name), getTracer) 275 if err != nil { 276 return err 277 } 278 body, _ := rlp.EncodeToBytes(txs) 279 // Dump the excution result 280 collector := make(Alloc) 281 s.DumpToCollector(collector, nil) 282 return dispatchOutput(ctx, baseDir, result, collector, body) 283 } 284 285 // txWithKey is a helper-struct, to allow us to use the types.Transaction along with 286 // a `secretKey`-field, for input 287 type txWithKey struct { 288 key *ecdsa.PrivateKey 289 tx *types.Transaction 290 protected bool 291 } 292 293 func (t *txWithKey) UnmarshalJSON(input []byte) error { 294 // Read the metadata, if present 295 type txMetadata struct { 296 Key *common.Hash `json:"secretKey"` 297 Protected *bool `json:"protected"` 298 } 299 var data txMetadata 300 if err := json.Unmarshal(input, &data); err != nil { 301 return err 302 } 303 if data.Key != nil { 304 k := data.Key.Hex()[2:] 305 if ecdsaKey, err := crypto.HexToECDSA(k); err != nil { 306 return err 307 } else { 308 t.key = ecdsaKey 309 } 310 } 311 if data.Protected != nil { 312 t.protected = *data.Protected 313 } else { 314 t.protected = true 315 } 316 // Now, read the transaction itself 317 var tx types.Transaction 318 if err := json.Unmarshal(input, &tx); err != nil { 319 return err 320 } 321 t.tx = &tx 322 return nil 323 } 324 325 // signUnsignedTransactions converts the input txs to canonical transactions. 326 // 327 // The transactions can have two forms, either 328 // 1. unsigned or 329 // 2. signed 330 // For (1), r, s, v, need so be zero, and the `secretKey` needs to be set. 331 // If so, we sign it here and now, with the given `secretKey` 332 // If the condition above is not met, then it's considered a signed transaction. 333 // 334 // To manage this, we read the transactions twice, first trying to read the secretKeys, 335 // and secondly to read them with the standard tx json format 336 func signUnsignedTransactions(txs []*txWithKey, signer types.Signer) (types.Transactions, error) { 337 var signedTxs []*types.Transaction 338 for i, txWithKey := range txs { 339 tx := txWithKey.tx 340 key := txWithKey.key 341 v, r, s := tx.RawSignatureValues() 342 if key != nil && v.BitLen()+r.BitLen()+s.BitLen() == 0 { 343 // This transaction needs to be signed 344 var ( 345 signed *types.Transaction 346 err error 347 ) 348 if txWithKey.protected { 349 signed, err = types.SignTx(tx, signer, key) 350 } else { 351 signed, err = types.SignTx(tx, types.FrontierSigner{}, key) 352 } 353 if err != nil { 354 return nil, NewError(ErrorJson, fmt.Errorf("tx %d: failed to sign tx: %v", i, err)) 355 } 356 signedTxs = append(signedTxs, signed) 357 } else { 358 // Already signed 359 signedTxs = append(signedTxs, tx) 360 } 361 } 362 return signedTxs, nil 363 } 364 365 type Alloc map[common.Address]core.GenesisAccount 366 367 func (g Alloc) OnRoot(common.Hash) {} 368 369 func (g Alloc) OnAccount(addr common.Address, dumpAccount state.DumpAccount) { 370 balance, _ := new(big.Int).SetString(dumpAccount.Balance, 10) 371 var storage map[common.Hash]common.Hash 372 if dumpAccount.Storage != nil { 373 storage = make(map[common.Hash]common.Hash) 374 for k, v := range dumpAccount.Storage { 375 storage[k] = common.HexToHash(v) 376 } 377 } 378 genesisAccount := core.GenesisAccount{ 379 Code: dumpAccount.Code, 380 Storage: storage, 381 Balance: balance, 382 Nonce: dumpAccount.Nonce, 383 } 384 g[addr] = genesisAccount 385 } 386 387 // saveFile marshalls the object to the given file 388 func saveFile(baseDir, filename string, data interface{}) error { 389 b, err := json.MarshalIndent(data, "", " ") 390 if err != nil { 391 return NewError(ErrorJson, fmt.Errorf("failed marshalling output: %v", err)) 392 } 393 location := path.Join(baseDir, filename) 394 if err = ioutil.WriteFile(location, b, 0644); err != nil { 395 return NewError(ErrorIO, fmt.Errorf("failed writing output: %v", err)) 396 } 397 log.Info("Wrote file", "file", location) 398 return nil 399 } 400 401 // dispatchOutput writes the output data to either stderr or stdout, or to the specified 402 // files 403 func dispatchOutput(ctx *cli.Context, baseDir string, result *ExecutionResult, alloc Alloc, body hexutil.Bytes) error { 404 stdOutObject := make(map[string]interface{}) 405 stdErrObject := make(map[string]interface{}) 406 dispatch := func(baseDir, fName, name string, obj interface{}) error { 407 switch fName { 408 case "stdout": 409 stdOutObject[name] = obj 410 case "stderr": 411 stdErrObject[name] = obj 412 case "": 413 // don't save 414 default: // save to file 415 if err := saveFile(baseDir, fName, obj); err != nil { 416 return err 417 } 418 } 419 return nil 420 } 421 if err := dispatch(baseDir, ctx.String(OutputAllocFlag.Name), "alloc", alloc); err != nil { 422 return err 423 } 424 if err := dispatch(baseDir, ctx.String(OutputResultFlag.Name), "result", result); err != nil { 425 return err 426 } 427 if err := dispatch(baseDir, ctx.String(OutputBodyFlag.Name), "body", body); err != nil { 428 return err 429 } 430 if len(stdOutObject) > 0 { 431 b, err := json.MarshalIndent(stdOutObject, "", " ") 432 if err != nil { 433 return NewError(ErrorJson, fmt.Errorf("failed marshalling output: %v", err)) 434 } 435 os.Stdout.Write(b) 436 os.Stdout.WriteString("\n") 437 } 438 if len(stdErrObject) > 0 { 439 b, err := json.MarshalIndent(stdErrObject, "", " ") 440 if err != nil { 441 return NewError(ErrorJson, fmt.Errorf("failed marshalling output: %v", err)) 442 } 443 os.Stderr.Write(b) 444 os.Stderr.WriteString("\n") 445 } 446 return nil 447 }