transition.go 7.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276
  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. package t8ntool
  17. import (
  18. "encoding/json"
  19. "fmt"
  20. "io/ioutil"
  21. "math/big"
  22. "os"
  23. "github.com/ethereum/go-ethereum/common"
  24. "github.com/ethereum/go-ethereum/core"
  25. "github.com/ethereum/go-ethereum/core/state"
  26. "github.com/ethereum/go-ethereum/core/types"
  27. "github.com/ethereum/go-ethereum/core/vm"
  28. "github.com/ethereum/go-ethereum/log"
  29. "github.com/ethereum/go-ethereum/params"
  30. "github.com/ethereum/go-ethereum/tests"
  31. "gopkg.in/urfave/cli.v1"
  32. )
  33. const (
  34. ErrorEVM = 2
  35. ErrorVMConfig = 3
  36. ErrorMissingBlockhash = 4
  37. ErrorJson = 10
  38. ErrorIO = 11
  39. stdinSelector = "stdin"
  40. )
  41. type NumberedError struct {
  42. errorCode int
  43. err error
  44. }
  45. func NewError(errorCode int, err error) *NumberedError {
  46. return &NumberedError{errorCode, err}
  47. }
  48. func (n *NumberedError) Error() string {
  49. return fmt.Sprintf("ERROR(%d): %v", n.errorCode, n.err.Error())
  50. }
  51. func (n *NumberedError) Code() int {
  52. return n.errorCode
  53. }
  54. type input struct {
  55. Alloc core.GenesisAlloc `json:"alloc,omitempty"`
  56. Env *stEnv `json:"env,omitempty"`
  57. Txs types.Transactions `json:"txs,omitempty"`
  58. }
  59. func Main(ctx *cli.Context) error {
  60. // Configure the go-ethereum logger
  61. glogger := log.NewGlogHandler(log.StreamHandler(os.Stderr, log.TerminalFormat(false)))
  62. glogger.Verbosity(log.Lvl(ctx.Int(VerbosityFlag.Name)))
  63. log.Root().SetHandler(glogger)
  64. var (
  65. err error
  66. tracer vm.Tracer
  67. )
  68. var getTracer func(txIndex int) (vm.Tracer, error)
  69. if ctx.Bool(TraceFlag.Name) {
  70. // Configure the EVM logger
  71. logConfig := &vm.LogConfig{
  72. DisableStack: ctx.Bool(TraceDisableStackFlag.Name),
  73. DisableMemory: ctx.Bool(TraceDisableMemoryFlag.Name),
  74. Debug: true,
  75. }
  76. var prevFile *os.File
  77. // This one closes the last file
  78. defer func() {
  79. if prevFile != nil {
  80. prevFile.Close()
  81. }
  82. }()
  83. getTracer = func(txIndex int) (vm.Tracer, error) {
  84. if prevFile != nil {
  85. prevFile.Close()
  86. }
  87. traceFile, err := os.Create(fmt.Sprintf("trace-%d.jsonl", txIndex))
  88. if err != nil {
  89. return nil, NewError(ErrorIO, fmt.Errorf("failed creating trace-file: %v", err))
  90. }
  91. prevFile = traceFile
  92. return vm.NewJSONLogger(logConfig, traceFile), nil
  93. }
  94. } else {
  95. getTracer = func(txIndex int) (tracer vm.Tracer, err error) {
  96. return nil, nil
  97. }
  98. }
  99. // We need to load three things: alloc, env and transactions. May be either in
  100. // stdin input or in files.
  101. // Check if anything needs to be read from stdin
  102. var (
  103. prestate Prestate
  104. txs types.Transactions // txs to apply
  105. allocStr = ctx.String(InputAllocFlag.Name)
  106. envStr = ctx.String(InputEnvFlag.Name)
  107. txStr = ctx.String(InputTxsFlag.Name)
  108. inputData = &input{}
  109. )
  110. if allocStr == stdinSelector || envStr == stdinSelector || txStr == stdinSelector {
  111. decoder := json.NewDecoder(os.Stdin)
  112. decoder.Decode(inputData)
  113. }
  114. if allocStr != stdinSelector {
  115. inFile, err := os.Open(allocStr)
  116. if err != nil {
  117. return NewError(ErrorIO, fmt.Errorf("failed reading alloc file: %v", err))
  118. }
  119. defer inFile.Close()
  120. decoder := json.NewDecoder(inFile)
  121. if err := decoder.Decode(&inputData.Alloc); err != nil {
  122. return NewError(ErrorJson, fmt.Errorf("Failed unmarshaling alloc-file: %v", err))
  123. }
  124. }
  125. if envStr != stdinSelector {
  126. inFile, err := os.Open(envStr)
  127. if err != nil {
  128. return NewError(ErrorIO, fmt.Errorf("failed reading env file: %v", err))
  129. }
  130. defer inFile.Close()
  131. decoder := json.NewDecoder(inFile)
  132. var env stEnv
  133. if err := decoder.Decode(&env); err != nil {
  134. return NewError(ErrorJson, fmt.Errorf("Failed unmarshaling env-file: %v", err))
  135. }
  136. inputData.Env = &env
  137. }
  138. if txStr != stdinSelector {
  139. inFile, err := os.Open(txStr)
  140. if err != nil {
  141. return NewError(ErrorIO, fmt.Errorf("failed reading txs file: %v", err))
  142. }
  143. defer inFile.Close()
  144. decoder := json.NewDecoder(inFile)
  145. var txs types.Transactions
  146. if err := decoder.Decode(&txs); err != nil {
  147. return NewError(ErrorJson, fmt.Errorf("Failed unmarshaling txs-file: %v", err))
  148. }
  149. inputData.Txs = txs
  150. }
  151. prestate.Pre = inputData.Alloc
  152. prestate.Env = *inputData.Env
  153. txs = inputData.Txs
  154. // Iterate over all the tests, run them and aggregate the results
  155. vmConfig := vm.Config{
  156. Tracer: tracer,
  157. Debug: (tracer != nil),
  158. }
  159. // Construct the chainconfig
  160. var chainConfig *params.ChainConfig
  161. if cConf, extraEips, err := tests.GetChainConfig(ctx.String(ForknameFlag.Name)); err != nil {
  162. return NewError(ErrorVMConfig, fmt.Errorf("Failed constructing chain configuration: %v", err))
  163. } else {
  164. chainConfig = cConf
  165. vmConfig.ExtraEips = extraEips
  166. }
  167. // Set the chain id
  168. chainConfig.ChainID = big.NewInt(ctx.Int64(ChainIDFlag.Name))
  169. // Run the test and aggregate the result
  170. state, result, err := prestate.Apply(vmConfig, chainConfig, txs, ctx.Int64(RewardFlag.Name), getTracer)
  171. if err != nil {
  172. return err
  173. }
  174. // Dump the excution result
  175. //postAlloc := state.DumpGenesisFormat(false, false, false)
  176. collector := make(Alloc)
  177. state.DumpToCollector(collector, false, false, false, nil, -1)
  178. return dispatchOutput(ctx, result, collector)
  179. }
  180. type Alloc map[common.Address]core.GenesisAccount
  181. func (g Alloc) OnRoot(common.Hash) {}
  182. func (g Alloc) OnAccount(addr common.Address, dumpAccount state.DumpAccount) {
  183. balance, _ := new(big.Int).SetString(dumpAccount.Balance, 10)
  184. var storage map[common.Hash]common.Hash
  185. if dumpAccount.Storage != nil {
  186. storage = make(map[common.Hash]common.Hash)
  187. for k, v := range dumpAccount.Storage {
  188. storage[k] = common.HexToHash(v)
  189. }
  190. }
  191. genesisAccount := core.GenesisAccount{
  192. Code: common.FromHex(dumpAccount.Code),
  193. Storage: storage,
  194. Balance: balance,
  195. Nonce: dumpAccount.Nonce,
  196. }
  197. g[addr] = genesisAccount
  198. }
  199. // saveFile marshalls the object to the given file
  200. func saveFile(filename string, data interface{}) error {
  201. b, err := json.MarshalIndent(data, "", " ")
  202. if err != nil {
  203. return NewError(ErrorJson, fmt.Errorf("failed marshalling output: %v", err))
  204. }
  205. if err = ioutil.WriteFile(filename, b, 0644); err != nil {
  206. return NewError(ErrorIO, fmt.Errorf("failed writing output: %v", err))
  207. }
  208. return nil
  209. }
  210. // dispatchOutput writes the output data to either stderr or stdout, or to the specified
  211. // files
  212. func dispatchOutput(ctx *cli.Context, result *ExecutionResult, alloc Alloc) error {
  213. stdOutObject := make(map[string]interface{})
  214. stdErrObject := make(map[string]interface{})
  215. dispatch := func(fName, name string, obj interface{}) error {
  216. switch fName {
  217. case "stdout":
  218. stdOutObject[name] = obj
  219. case "stderr":
  220. stdErrObject[name] = obj
  221. default: // save to file
  222. if err := saveFile(fName, obj); err != nil {
  223. return err
  224. }
  225. }
  226. return nil
  227. }
  228. if err := dispatch(ctx.String(OutputAllocFlag.Name), "alloc", alloc); err != nil {
  229. return err
  230. }
  231. if err := dispatch(ctx.String(OutputResultFlag.Name), "result", result); err != nil {
  232. return err
  233. }
  234. if len(stdOutObject) > 0 {
  235. b, err := json.MarshalIndent(stdOutObject, "", " ")
  236. if err != nil {
  237. return NewError(ErrorJson, fmt.Errorf("failed marshalling output: %v", err))
  238. }
  239. os.Stdout.Write(b)
  240. }
  241. if len(stdErrObject) > 0 {
  242. b, err := json.MarshalIndent(stdErrObject, "", " ")
  243. if err != nil {
  244. return NewError(ErrorJson, fmt.Errorf("failed marshalling output: %v", err))
  245. }
  246. os.Stderr.Write(b)
  247. }
  248. return nil
  249. }