transition.go 7.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277
  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. DisableReturnData: ctx.Bool(TraceDisableReturnDataFlag.Name),
  75. Debug: true,
  76. }
  77. var prevFile *os.File
  78. // This one closes the last file
  79. defer func() {
  80. if prevFile != nil {
  81. prevFile.Close()
  82. }
  83. }()
  84. getTracer = func(txIndex int) (vm.Tracer, error) {
  85. if prevFile != nil {
  86. prevFile.Close()
  87. }
  88. traceFile, err := os.Create(fmt.Sprintf("trace-%d.jsonl", txIndex))
  89. if err != nil {
  90. return nil, NewError(ErrorIO, fmt.Errorf("failed creating trace-file: %v", err))
  91. }
  92. prevFile = traceFile
  93. return vm.NewJSONLogger(logConfig, traceFile), nil
  94. }
  95. } else {
  96. getTracer = func(txIndex int) (tracer vm.Tracer, err error) {
  97. return nil, nil
  98. }
  99. }
  100. // We need to load three things: alloc, env and transactions. May be either in
  101. // stdin input or in files.
  102. // Check if anything needs to be read from stdin
  103. var (
  104. prestate Prestate
  105. txs types.Transactions // txs to apply
  106. allocStr = ctx.String(InputAllocFlag.Name)
  107. envStr = ctx.String(InputEnvFlag.Name)
  108. txStr = ctx.String(InputTxsFlag.Name)
  109. inputData = &input{}
  110. )
  111. if allocStr == stdinSelector || envStr == stdinSelector || txStr == stdinSelector {
  112. decoder := json.NewDecoder(os.Stdin)
  113. decoder.Decode(inputData)
  114. }
  115. if allocStr != stdinSelector {
  116. inFile, err := os.Open(allocStr)
  117. if err != nil {
  118. return NewError(ErrorIO, fmt.Errorf("failed reading alloc file: %v", err))
  119. }
  120. defer inFile.Close()
  121. decoder := json.NewDecoder(inFile)
  122. if err := decoder.Decode(&inputData.Alloc); err != nil {
  123. return NewError(ErrorJson, fmt.Errorf("Failed unmarshaling alloc-file: %v", err))
  124. }
  125. }
  126. if envStr != stdinSelector {
  127. inFile, err := os.Open(envStr)
  128. if err != nil {
  129. return NewError(ErrorIO, fmt.Errorf("failed reading env file: %v", err))
  130. }
  131. defer inFile.Close()
  132. decoder := json.NewDecoder(inFile)
  133. var env stEnv
  134. if err := decoder.Decode(&env); err != nil {
  135. return NewError(ErrorJson, fmt.Errorf("Failed unmarshaling env-file: %v", err))
  136. }
  137. inputData.Env = &env
  138. }
  139. if txStr != stdinSelector {
  140. inFile, err := os.Open(txStr)
  141. if err != nil {
  142. return NewError(ErrorIO, fmt.Errorf("failed reading txs file: %v", err))
  143. }
  144. defer inFile.Close()
  145. decoder := json.NewDecoder(inFile)
  146. var txs types.Transactions
  147. if err := decoder.Decode(&txs); err != nil {
  148. return NewError(ErrorJson, fmt.Errorf("Failed unmarshaling txs-file: %v", err))
  149. }
  150. inputData.Txs = txs
  151. }
  152. prestate.Pre = inputData.Alloc
  153. prestate.Env = *inputData.Env
  154. txs = inputData.Txs
  155. // Iterate over all the tests, run them and aggregate the results
  156. vmConfig := vm.Config{
  157. Tracer: tracer,
  158. Debug: (tracer != nil),
  159. }
  160. // Construct the chainconfig
  161. var chainConfig *params.ChainConfig
  162. if cConf, extraEips, err := tests.GetChainConfig(ctx.String(ForknameFlag.Name)); err != nil {
  163. return NewError(ErrorVMConfig, fmt.Errorf("Failed constructing chain configuration: %v", err))
  164. } else {
  165. chainConfig = cConf
  166. vmConfig.ExtraEips = extraEips
  167. }
  168. // Set the chain id
  169. chainConfig.ChainID = big.NewInt(ctx.Int64(ChainIDFlag.Name))
  170. // Run the test and aggregate the result
  171. state, result, err := prestate.Apply(vmConfig, chainConfig, txs, ctx.Int64(RewardFlag.Name), getTracer)
  172. if err != nil {
  173. return err
  174. }
  175. // Dump the excution result
  176. //postAlloc := state.DumpGenesisFormat(false, false, false)
  177. collector := make(Alloc)
  178. state.DumpToCollector(collector, false, false, false, nil, -1)
  179. return dispatchOutput(ctx, result, collector)
  180. }
  181. type Alloc map[common.Address]core.GenesisAccount
  182. func (g Alloc) OnRoot(common.Hash) {}
  183. func (g Alloc) OnAccount(addr common.Address, dumpAccount state.DumpAccount) {
  184. balance, _ := new(big.Int).SetString(dumpAccount.Balance, 10)
  185. var storage map[common.Hash]common.Hash
  186. if dumpAccount.Storage != nil {
  187. storage = make(map[common.Hash]common.Hash)
  188. for k, v := range dumpAccount.Storage {
  189. storage[k] = common.HexToHash(v)
  190. }
  191. }
  192. genesisAccount := core.GenesisAccount{
  193. Code: common.FromHex(dumpAccount.Code),
  194. Storage: storage,
  195. Balance: balance,
  196. Nonce: dumpAccount.Nonce,
  197. }
  198. g[addr] = genesisAccount
  199. }
  200. // saveFile marshalls the object to the given file
  201. func saveFile(filename string, data interface{}) error {
  202. b, err := json.MarshalIndent(data, "", " ")
  203. if err != nil {
  204. return NewError(ErrorJson, fmt.Errorf("failed marshalling output: %v", err))
  205. }
  206. if err = ioutil.WriteFile(filename, b, 0644); err != nil {
  207. return NewError(ErrorIO, fmt.Errorf("failed writing output: %v", err))
  208. }
  209. return nil
  210. }
  211. // dispatchOutput writes the output data to either stderr or stdout, or to the specified
  212. // files
  213. func dispatchOutput(ctx *cli.Context, result *ExecutionResult, alloc Alloc) error {
  214. stdOutObject := make(map[string]interface{})
  215. stdErrObject := make(map[string]interface{})
  216. dispatch := func(fName, name string, obj interface{}) error {
  217. switch fName {
  218. case "stdout":
  219. stdOutObject[name] = obj
  220. case "stderr":
  221. stdErrObject[name] = obj
  222. default: // save to file
  223. if err := saveFile(fName, obj); err != nil {
  224. return err
  225. }
  226. }
  227. return nil
  228. }
  229. if err := dispatch(ctx.String(OutputAllocFlag.Name), "alloc", alloc); err != nil {
  230. return err
  231. }
  232. if err := dispatch(ctx.String(OutputResultFlag.Name), "result", result); err != nil {
  233. return err
  234. }
  235. if len(stdOutObject) > 0 {
  236. b, err := json.MarshalIndent(stdOutObject, "", " ")
  237. if err != nil {
  238. return NewError(ErrorJson, fmt.Errorf("failed marshalling output: %v", err))
  239. }
  240. os.Stdout.Write(b)
  241. }
  242. if len(stdErrObject) > 0 {
  243. b, err := json.MarshalIndent(stdErrObject, "", " ")
  244. if err != nil {
  245. return NewError(ErrorJson, fmt.Errorf("failed marshalling output: %v", err))
  246. }
  247. os.Stderr.Write(b)
  248. }
  249. return nil
  250. }