github.com/calmw/ethereum@v0.1.1/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 "math/big" 25 "os" 26 "path" 27 "strings" 28 29 "github.com/calmw/ethereum/common" 30 "github.com/calmw/ethereum/common/hexutil" 31 "github.com/calmw/ethereum/consensus/misc" 32 "github.com/calmw/ethereum/core" 33 "github.com/calmw/ethereum/core/state" 34 "github.com/calmw/ethereum/core/types" 35 "github.com/calmw/ethereum/core/vm" 36 "github.com/calmw/ethereum/crypto" 37 "github.com/calmw/ethereum/eth/tracers/logger" 38 "github.com/calmw/ethereum/log" 39 "github.com/calmw/ethereum/params" 40 "github.com/calmw/ethereum/rlp" 41 "github.com/calmw/ethereum/tests" 42 "github.com/urfave/cli/v2" 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 } 184 // Construct the chainconfig 185 var chainConfig *params.ChainConfig 186 if cConf, extraEips, err := tests.GetChainConfig(ctx.String(ForknameFlag.Name)); err != nil { 187 return NewError(ErrorConfig, fmt.Errorf("failed constructing chain configuration: %v", err)) 188 } else { 189 chainConfig = cConf 190 vmConfig.ExtraEips = extraEips 191 } 192 // Set the chain id 193 chainConfig.ChainID = big.NewInt(ctx.Int64(ChainIDFlag.Name)) 194 195 var txsWithKeys []*txWithKey 196 if txStr != stdinSelector { 197 inFile, err := os.Open(txStr) 198 if err != nil { 199 return NewError(ErrorIO, fmt.Errorf("failed reading txs file: %v", err)) 200 } 201 defer inFile.Close() 202 decoder := json.NewDecoder(inFile) 203 if strings.HasSuffix(txStr, ".rlp") { 204 var body hexutil.Bytes 205 if err := decoder.Decode(&body); err != nil { 206 return err 207 } 208 var txs types.Transactions 209 if err := rlp.DecodeBytes(body, &txs); err != nil { 210 return err 211 } 212 for _, tx := range txs { 213 txsWithKeys = append(txsWithKeys, &txWithKey{ 214 key: nil, 215 tx: tx, 216 }) 217 } 218 } else { 219 if err := decoder.Decode(&txsWithKeys); err != nil { 220 return NewError(ErrorJson, fmt.Errorf("failed unmarshaling txs-file: %v", err)) 221 } 222 } 223 } else { 224 if len(inputData.TxRlp) > 0 { 225 // Decode the body of already signed transactions 226 body := common.FromHex(inputData.TxRlp) 227 var txs types.Transactions 228 if err := rlp.DecodeBytes(body, &txs); err != nil { 229 return err 230 } 231 for _, tx := range txs { 232 txsWithKeys = append(txsWithKeys, &txWithKey{ 233 key: nil, 234 tx: tx, 235 }) 236 } 237 } else { 238 // JSON encoded transactions 239 txsWithKeys = inputData.Txs 240 } 241 } 242 // We may have to sign the transactions. 243 signer := types.MakeSigner(chainConfig, big.NewInt(int64(prestate.Env.Number)), prestate.Env.Timestamp) 244 245 if txs, err = signUnsignedTransactions(txsWithKeys, signer); err != nil { 246 return NewError(ErrorJson, fmt.Errorf("failed signing transactions: %v", err)) 247 } 248 // Sanity check, to not `panic` in state_transition 249 if chainConfig.IsLondon(big.NewInt(int64(prestate.Env.Number))) { 250 if prestate.Env.BaseFee != nil { 251 // Already set, base fee has precedent over parent base fee. 252 } else if prestate.Env.ParentBaseFee != nil && prestate.Env.Number != 0 { 253 parent := &types.Header{ 254 Number: new(big.Int).SetUint64(prestate.Env.Number - 1), 255 BaseFee: prestate.Env.ParentBaseFee, 256 GasUsed: prestate.Env.ParentGasUsed, 257 GasLimit: prestate.Env.ParentGasLimit, 258 } 259 prestate.Env.BaseFee = misc.CalcBaseFee(chainConfig, parent) 260 } else { 261 return NewError(ErrorConfig, errors.New("EIP-1559 config but missing 'currentBaseFee' in env section")) 262 } 263 } 264 if chainConfig.IsShanghai(prestate.Env.Number) && prestate.Env.Withdrawals == nil { 265 return NewError(ErrorConfig, errors.New("Shanghai config but missing 'withdrawals' in env section")) 266 } 267 isMerged := chainConfig.TerminalTotalDifficulty != nil && chainConfig.TerminalTotalDifficulty.BitLen() == 0 268 env := prestate.Env 269 if isMerged { 270 // post-merge: 271 // - random must be supplied 272 // - difficulty must be zero 273 switch { 274 case env.Random == nil: 275 return NewError(ErrorConfig, errors.New("post-merge requires currentRandom to be defined in env")) 276 case env.Difficulty != nil && env.Difficulty.BitLen() != 0: 277 return NewError(ErrorConfig, errors.New("post-merge difficulty must be zero (or omitted) in env")) 278 } 279 prestate.Env.Difficulty = nil 280 } else if env.Difficulty == nil { 281 // pre-merge: 282 // If difficulty was not provided by caller, we need to calculate it. 283 switch { 284 case env.ParentDifficulty == nil: 285 return NewError(ErrorConfig, errors.New("currentDifficulty was not provided, and cannot be calculated due to missing parentDifficulty")) 286 case env.Number == 0: 287 return NewError(ErrorConfig, errors.New("currentDifficulty needs to be provided for block number 0")) 288 case env.Timestamp <= env.ParentTimestamp: 289 return NewError(ErrorConfig, fmt.Errorf("currentDifficulty cannot be calculated -- currentTime (%d) needs to be after parent time (%d)", 290 env.Timestamp, env.ParentTimestamp)) 291 } 292 prestate.Env.Difficulty = calcDifficulty(chainConfig, env.Number, env.Timestamp, 293 env.ParentTimestamp, env.ParentDifficulty, env.ParentUncleHash) 294 } 295 // Run the test and aggregate the result 296 s, result, err := prestate.Apply(vmConfig, chainConfig, txs, ctx.Int64(RewardFlag.Name), getTracer) 297 if err != nil { 298 return err 299 } 300 body, _ := rlp.EncodeToBytes(txs) 301 // Dump the excution result 302 collector := make(Alloc) 303 s.DumpToCollector(collector, nil) 304 return dispatchOutput(ctx, baseDir, result, collector, body) 305 } 306 307 // txWithKey is a helper-struct, to allow us to use the types.Transaction along with 308 // a `secretKey`-field, for input 309 type txWithKey struct { 310 key *ecdsa.PrivateKey 311 tx *types.Transaction 312 protected bool 313 } 314 315 func (t *txWithKey) UnmarshalJSON(input []byte) error { 316 // Read the metadata, if present 317 type txMetadata struct { 318 Key *common.Hash `json:"secretKey"` 319 Protected *bool `json:"protected"` 320 } 321 var data txMetadata 322 if err := json.Unmarshal(input, &data); err != nil { 323 return err 324 } 325 if data.Key != nil { 326 k := data.Key.Hex()[2:] 327 if ecdsaKey, err := crypto.HexToECDSA(k); err != nil { 328 return err 329 } else { 330 t.key = ecdsaKey 331 } 332 } 333 if data.Protected != nil { 334 t.protected = *data.Protected 335 } else { 336 t.protected = true 337 } 338 // Now, read the transaction itself 339 var tx types.Transaction 340 if err := json.Unmarshal(input, &tx); err != nil { 341 return err 342 } 343 t.tx = &tx 344 return nil 345 } 346 347 // signUnsignedTransactions converts the input txs to canonical transactions. 348 // 349 // The transactions can have two forms, either 350 // 1. unsigned or 351 // 2. signed 352 // 353 // For (1), r, s, v, need so be zero, and the `secretKey` needs to be set. 354 // If so, we sign it here and now, with the given `secretKey` 355 // If the condition above is not met, then it's considered a signed transaction. 356 // 357 // To manage this, we read the transactions twice, first trying to read the secretKeys, 358 // and secondly to read them with the standard tx json format 359 func signUnsignedTransactions(txs []*txWithKey, signer types.Signer) (types.Transactions, error) { 360 var signedTxs []*types.Transaction 361 for i, txWithKey := range txs { 362 tx := txWithKey.tx 363 key := txWithKey.key 364 v, r, s := tx.RawSignatureValues() 365 if key != nil && v.BitLen()+r.BitLen()+s.BitLen() == 0 { 366 // This transaction needs to be signed 367 var ( 368 signed *types.Transaction 369 err error 370 ) 371 if txWithKey.protected { 372 signed, err = types.SignTx(tx, signer, key) 373 } else { 374 signed, err = types.SignTx(tx, types.FrontierSigner{}, key) 375 } 376 if err != nil { 377 return nil, NewError(ErrorJson, fmt.Errorf("tx %d: failed to sign tx: %v", i, err)) 378 } 379 signedTxs = append(signedTxs, signed) 380 } else { 381 // Already signed 382 signedTxs = append(signedTxs, tx) 383 } 384 } 385 return signedTxs, nil 386 } 387 388 type Alloc map[common.Address]core.GenesisAccount 389 390 func (g Alloc) OnRoot(common.Hash) {} 391 392 func (g Alloc) OnAccount(addr common.Address, dumpAccount state.DumpAccount) { 393 balance, _ := new(big.Int).SetString(dumpAccount.Balance, 10) 394 var storage map[common.Hash]common.Hash 395 if dumpAccount.Storage != nil { 396 storage = make(map[common.Hash]common.Hash) 397 for k, v := range dumpAccount.Storage { 398 storage[k] = common.HexToHash(v) 399 } 400 } 401 genesisAccount := core.GenesisAccount{ 402 Code: dumpAccount.Code, 403 Storage: storage, 404 Balance: balance, 405 Nonce: dumpAccount.Nonce, 406 } 407 g[addr] = genesisAccount 408 } 409 410 // saveFile marshals the object to the given file 411 func saveFile(baseDir, filename string, data interface{}) error { 412 b, err := json.MarshalIndent(data, "", " ") 413 if err != nil { 414 return NewError(ErrorJson, fmt.Errorf("failed marshalling output: %v", err)) 415 } 416 location := path.Join(baseDir, filename) 417 if err = os.WriteFile(location, b, 0644); err != nil { 418 return NewError(ErrorIO, fmt.Errorf("failed writing output: %v", err)) 419 } 420 log.Info("Wrote file", "file", location) 421 return nil 422 } 423 424 // dispatchOutput writes the output data to either stderr or stdout, or to the specified 425 // files 426 func dispatchOutput(ctx *cli.Context, baseDir string, result *ExecutionResult, alloc Alloc, body hexutil.Bytes) error { 427 stdOutObject := make(map[string]interface{}) 428 stdErrObject := make(map[string]interface{}) 429 dispatch := func(baseDir, fName, name string, obj interface{}) error { 430 switch fName { 431 case "stdout": 432 stdOutObject[name] = obj 433 case "stderr": 434 stdErrObject[name] = obj 435 case "": 436 // don't save 437 default: // save to file 438 if err := saveFile(baseDir, fName, obj); err != nil { 439 return err 440 } 441 } 442 return nil 443 } 444 if err := dispatch(baseDir, ctx.String(OutputAllocFlag.Name), "alloc", alloc); err != nil { 445 return err 446 } 447 if err := dispatch(baseDir, ctx.String(OutputResultFlag.Name), "result", result); err != nil { 448 return err 449 } 450 if err := dispatch(baseDir, ctx.String(OutputBodyFlag.Name), "body", body); err != nil { 451 return err 452 } 453 if len(stdOutObject) > 0 { 454 b, err := json.MarshalIndent(stdOutObject, "", " ") 455 if err != nil { 456 return NewError(ErrorJson, fmt.Errorf("failed marshalling output: %v", err)) 457 } 458 os.Stdout.Write(b) 459 os.Stdout.WriteString("\n") 460 } 461 if len(stdErrObject) > 0 { 462 b, err := json.MarshalIndent(stdErrObject, "", " ") 463 if err != nil { 464 return NewError(ErrorJson, fmt.Errorf("failed marshalling output: %v", err)) 465 } 466 os.Stderr.Write(b) 467 os.Stderr.WriteString("\n") 468 } 469 return nil 470 }