transition.go 8.4 KB

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