retesteth.go 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927
  1. // Copyright 2019 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 main
  17. import (
  18. "bytes"
  19. "context"
  20. "fmt"
  21. "math/big"
  22. "os"
  23. "os/signal"
  24. "strings"
  25. "time"
  26. "github.com/ethereum/go-ethereum/cmd/utils"
  27. "github.com/ethereum/go-ethereum/common"
  28. "github.com/ethereum/go-ethereum/common/hexutil"
  29. "github.com/ethereum/go-ethereum/common/math"
  30. "github.com/ethereum/go-ethereum/consensus"
  31. "github.com/ethereum/go-ethereum/consensus/ethash"
  32. "github.com/ethereum/go-ethereum/consensus/misc"
  33. "github.com/ethereum/go-ethereum/core"
  34. "github.com/ethereum/go-ethereum/core/rawdb"
  35. "github.com/ethereum/go-ethereum/core/state"
  36. "github.com/ethereum/go-ethereum/core/types"
  37. "github.com/ethereum/go-ethereum/core/vm"
  38. "github.com/ethereum/go-ethereum/crypto"
  39. "github.com/ethereum/go-ethereum/ethdb"
  40. "github.com/ethereum/go-ethereum/log"
  41. "github.com/ethereum/go-ethereum/node"
  42. "github.com/ethereum/go-ethereum/params"
  43. "github.com/ethereum/go-ethereum/rlp"
  44. "github.com/ethereum/go-ethereum/rpc"
  45. "github.com/ethereum/go-ethereum/trie"
  46. cli "gopkg.in/urfave/cli.v1"
  47. )
  48. var (
  49. rpcPortFlag = cli.IntFlag{
  50. Name: "rpcport",
  51. Usage: "HTTP-RPC server listening port",
  52. Value: node.DefaultHTTPPort,
  53. }
  54. retestethCommand = cli.Command{
  55. Action: utils.MigrateFlags(retesteth),
  56. Name: "retesteth",
  57. Usage: "Launches geth in retesteth mode",
  58. ArgsUsage: "",
  59. Flags: []cli.Flag{rpcPortFlag},
  60. Category: "MISCELLANEOUS COMMANDS",
  61. Description: `Launches geth in retesteth mode (no database, no network, only retesteth RPC interface)`,
  62. }
  63. )
  64. type RetestethTestAPI interface {
  65. SetChainParams(ctx context.Context, chainParams ChainParams) (bool, error)
  66. MineBlocks(ctx context.Context, number uint64) (bool, error)
  67. ModifyTimestamp(ctx context.Context, interval uint64) (bool, error)
  68. ImportRawBlock(ctx context.Context, rawBlock hexutil.Bytes) (common.Hash, error)
  69. RewindToBlock(ctx context.Context, number uint64) (bool, error)
  70. GetLogHash(ctx context.Context, txHash common.Hash) (common.Hash, error)
  71. }
  72. type RetestethEthAPI interface {
  73. SendRawTransaction(ctx context.Context, rawTx hexutil.Bytes) (common.Hash, error)
  74. BlockNumber(ctx context.Context) (uint64, error)
  75. GetBlockByNumber(ctx context.Context, blockNr math.HexOrDecimal64, fullTx bool) (map[string]interface{}, error)
  76. GetBlockByHash(ctx context.Context, blockHash common.Hash, fullTx bool) (map[string]interface{}, error)
  77. GetBalance(ctx context.Context, address common.Address, blockNr math.HexOrDecimal64) (*math.HexOrDecimal256, error)
  78. GetCode(ctx context.Context, address common.Address, blockNr math.HexOrDecimal64) (hexutil.Bytes, error)
  79. GetTransactionCount(ctx context.Context, address common.Address, blockNr math.HexOrDecimal64) (uint64, error)
  80. }
  81. type RetestethDebugAPI interface {
  82. AccountRange(ctx context.Context,
  83. blockHashOrNumber *math.HexOrDecimal256, txIndex uint64,
  84. addressHash *math.HexOrDecimal256, maxResults uint64,
  85. ) (AccountRangeResult, error)
  86. StorageRangeAt(ctx context.Context,
  87. blockHashOrNumber *math.HexOrDecimal256, txIndex uint64,
  88. address common.Address,
  89. begin *math.HexOrDecimal256, maxResults uint64,
  90. ) (StorageRangeResult, error)
  91. }
  92. type RetestWeb3API interface {
  93. ClientVersion(ctx context.Context) (string, error)
  94. }
  95. type RetestethAPI struct {
  96. ethDb ethdb.Database
  97. db state.Database
  98. chainConfig *params.ChainConfig
  99. author common.Address
  100. extraData []byte
  101. genesisHash common.Hash
  102. engine *NoRewardEngine
  103. blockchain *core.BlockChain
  104. txMap map[common.Address]map[uint64]*types.Transaction // Sender -> Nonce -> Transaction
  105. txSenders map[common.Address]struct{} // Set of transaction senders
  106. blockInterval uint64
  107. }
  108. type ChainParams struct {
  109. SealEngine string `json:"sealEngine"`
  110. Params CParamsParams `json:"params"`
  111. Genesis CParamsGenesis `json:"genesis"`
  112. Accounts map[common.Address]CParamsAccount `json:"accounts"`
  113. }
  114. type CParamsParams struct {
  115. AccountStartNonce math.HexOrDecimal64 `json:"accountStartNonce"`
  116. HomesteadForkBlock *math.HexOrDecimal64 `json:"homesteadForkBlock"`
  117. EIP150ForkBlock *math.HexOrDecimal64 `json:"EIP150ForkBlock"`
  118. EIP158ForkBlock *math.HexOrDecimal64 `json:"EIP158ForkBlock"`
  119. DaoHardforkBlock *math.HexOrDecimal64 `json:"daoHardforkBlock"`
  120. ByzantiumForkBlock *math.HexOrDecimal64 `json:"byzantiumForkBlock"`
  121. ConstantinopleForkBlock *math.HexOrDecimal64 `json:"constantinopleForkBlock"`
  122. ConstantinopleFixForkBlock *math.HexOrDecimal64 `json:"constantinopleFixForkBlock"`
  123. IstanbulBlock *math.HexOrDecimal64 `json:"istanbulForkBlock"`
  124. ChainID *math.HexOrDecimal256 `json:"chainID"`
  125. MaximumExtraDataSize math.HexOrDecimal64 `json:"maximumExtraDataSize"`
  126. TieBreakingGas bool `json:"tieBreakingGas"`
  127. MinGasLimit math.HexOrDecimal64 `json:"minGasLimit"`
  128. MaxGasLimit math.HexOrDecimal64 `json:"maxGasLimit"`
  129. GasLimitBoundDivisor math.HexOrDecimal64 `json:"gasLimitBoundDivisor"`
  130. MinimumDifficulty math.HexOrDecimal256 `json:"minimumDifficulty"`
  131. DifficultyBoundDivisor math.HexOrDecimal256 `json:"difficultyBoundDivisor"`
  132. DurationLimit math.HexOrDecimal256 `json:"durationLimit"`
  133. BlockReward math.HexOrDecimal256 `json:"blockReward"`
  134. NetworkID math.HexOrDecimal256 `json:"networkID"`
  135. }
  136. type CParamsGenesis struct {
  137. Nonce math.HexOrDecimal64 `json:"nonce"`
  138. Difficulty *math.HexOrDecimal256 `json:"difficulty"`
  139. MixHash *math.HexOrDecimal256 `json:"mixHash"`
  140. Author common.Address `json:"author"`
  141. Timestamp math.HexOrDecimal64 `json:"timestamp"`
  142. ParentHash common.Hash `json:"parentHash"`
  143. ExtraData hexutil.Bytes `json:"extraData"`
  144. GasLimit math.HexOrDecimal64 `json:"gasLimit"`
  145. }
  146. type CParamsAccount struct {
  147. Balance *math.HexOrDecimal256 `json:"balance"`
  148. Precompiled *CPAccountPrecompiled `json:"precompiled"`
  149. Code hexutil.Bytes `json:"code"`
  150. Storage map[string]string `json:"storage"`
  151. Nonce *math.HexOrDecimal64 `json:"nonce"`
  152. }
  153. type CPAccountPrecompiled struct {
  154. Name string `json:"name"`
  155. StartingBlock math.HexOrDecimal64 `json:"startingBlock"`
  156. Linear *CPAPrecompiledLinear `json:"linear"`
  157. }
  158. type CPAPrecompiledLinear struct {
  159. Base uint64 `json:"base"`
  160. Word uint64 `json:"word"`
  161. }
  162. type AccountRangeResult struct {
  163. AddressMap map[common.Hash]common.Address `json:"addressMap"`
  164. NextKey common.Hash `json:"nextKey"`
  165. }
  166. type StorageRangeResult struct {
  167. Complete bool `json:"complete"`
  168. Storage map[common.Hash]SRItem `json:"storage"`
  169. }
  170. type SRItem struct {
  171. Key string `json:"key"`
  172. Value string `json:"value"`
  173. }
  174. type NoRewardEngine struct {
  175. inner consensus.Engine
  176. rewardsOn bool
  177. }
  178. func (e *NoRewardEngine) Author(header *types.Header) (common.Address, error) {
  179. return e.inner.Author(header)
  180. }
  181. func (e *NoRewardEngine) VerifyHeader(chain consensus.ChainReader, header *types.Header, seal bool) error {
  182. return e.inner.VerifyHeader(chain, header, seal)
  183. }
  184. func (e *NoRewardEngine) VerifyHeaders(chain consensus.ChainReader, headers []*types.Header, seals []bool) (chan<- struct{}, <-chan error) {
  185. return e.inner.VerifyHeaders(chain, headers, seals)
  186. }
  187. func (e *NoRewardEngine) VerifyUncles(chain consensus.ChainReader, block *types.Block) error {
  188. return e.inner.VerifyUncles(chain, block)
  189. }
  190. func (e *NoRewardEngine) VerifySeal(chain consensus.ChainReader, header *types.Header) error {
  191. return e.inner.VerifySeal(chain, header)
  192. }
  193. func (e *NoRewardEngine) Prepare(chain consensus.ChainReader, header *types.Header) error {
  194. return e.inner.Prepare(chain, header)
  195. }
  196. func (e *NoRewardEngine) accumulateRewards(config *params.ChainConfig, state *state.StateDB, header *types.Header, uncles []*types.Header) {
  197. // Simply touch miner and uncle coinbase accounts
  198. reward := big.NewInt(0)
  199. for _, uncle := range uncles {
  200. state.AddBalance(uncle.Coinbase, reward)
  201. }
  202. state.AddBalance(header.Coinbase, reward)
  203. }
  204. func (e *NoRewardEngine) Finalize(chain consensus.ChainReader, header *types.Header, statedb *state.StateDB, txs []*types.Transaction,
  205. uncles []*types.Header) {
  206. if e.rewardsOn {
  207. e.inner.Finalize(chain, header, statedb, txs, uncles)
  208. } else {
  209. e.accumulateRewards(chain.Config(), statedb, header, uncles)
  210. header.Root = statedb.IntermediateRoot(chain.Config().IsEIP158(header.Number))
  211. }
  212. }
  213. func (e *NoRewardEngine) FinalizeAndAssemble(chain consensus.ChainReader, header *types.Header, statedb *state.StateDB, txs []*types.Transaction,
  214. uncles []*types.Header, receipts []*types.Receipt) (*types.Block, error) {
  215. if e.rewardsOn {
  216. return e.inner.FinalizeAndAssemble(chain, header, statedb, txs, uncles, receipts)
  217. } else {
  218. e.accumulateRewards(chain.Config(), statedb, header, uncles)
  219. header.Root = statedb.IntermediateRoot(chain.Config().IsEIP158(header.Number))
  220. // Header seems complete, assemble into a block and return
  221. return types.NewBlock(header, txs, uncles, receipts), nil
  222. }
  223. }
  224. func (e *NoRewardEngine) Seal(chain consensus.ChainReader, block *types.Block, results chan<- *types.Block, stop <-chan struct{}) error {
  225. return e.inner.Seal(chain, block, results, stop)
  226. }
  227. func (e *NoRewardEngine) SealHash(header *types.Header) common.Hash {
  228. return e.inner.SealHash(header)
  229. }
  230. func (e *NoRewardEngine) CalcDifficulty(chain consensus.ChainReader, time uint64, parent *types.Header) *big.Int {
  231. return e.inner.CalcDifficulty(chain, time, parent)
  232. }
  233. func (e *NoRewardEngine) APIs(chain consensus.ChainReader) []rpc.API {
  234. return e.inner.APIs(chain)
  235. }
  236. func (e *NoRewardEngine) Close() error {
  237. return e.inner.Close()
  238. }
  239. func (api *RetestethAPI) SetChainParams(ctx context.Context, chainParams ChainParams) (bool, error) {
  240. // Clean up
  241. if api.blockchain != nil {
  242. api.blockchain.Stop()
  243. }
  244. if api.engine != nil {
  245. api.engine.Close()
  246. }
  247. if api.ethDb != nil {
  248. api.ethDb.Close()
  249. }
  250. ethDb := rawdb.NewMemoryDatabase()
  251. accounts := make(core.GenesisAlloc)
  252. for address, account := range chainParams.Accounts {
  253. balance := big.NewInt(0)
  254. if account.Balance != nil {
  255. balance.Set((*big.Int)(account.Balance))
  256. }
  257. var nonce uint64
  258. if account.Nonce != nil {
  259. nonce = uint64(*account.Nonce)
  260. }
  261. if account.Precompiled == nil || account.Balance != nil {
  262. storage := make(map[common.Hash]common.Hash)
  263. for k, v := range account.Storage {
  264. storage[common.HexToHash(k)] = common.HexToHash(v)
  265. }
  266. accounts[address] = core.GenesisAccount{
  267. Balance: balance,
  268. Code: account.Code,
  269. Nonce: nonce,
  270. Storage: storage,
  271. }
  272. }
  273. }
  274. chainId := big.NewInt(1)
  275. if chainParams.Params.ChainID != nil {
  276. chainId.Set((*big.Int)(chainParams.Params.ChainID))
  277. }
  278. var (
  279. homesteadBlock *big.Int
  280. daoForkBlock *big.Int
  281. eip150Block *big.Int
  282. eip155Block *big.Int
  283. eip158Block *big.Int
  284. byzantiumBlock *big.Int
  285. constantinopleBlock *big.Int
  286. petersburgBlock *big.Int
  287. istanbulBlock *big.Int
  288. )
  289. if chainParams.Params.HomesteadForkBlock != nil {
  290. homesteadBlock = big.NewInt(int64(*chainParams.Params.HomesteadForkBlock))
  291. }
  292. if chainParams.Params.DaoHardforkBlock != nil {
  293. daoForkBlock = big.NewInt(int64(*chainParams.Params.DaoHardforkBlock))
  294. }
  295. if chainParams.Params.EIP150ForkBlock != nil {
  296. eip150Block = big.NewInt(int64(*chainParams.Params.EIP150ForkBlock))
  297. }
  298. if chainParams.Params.EIP158ForkBlock != nil {
  299. eip158Block = big.NewInt(int64(*chainParams.Params.EIP158ForkBlock))
  300. eip155Block = eip158Block
  301. }
  302. if chainParams.Params.ByzantiumForkBlock != nil {
  303. byzantiumBlock = big.NewInt(int64(*chainParams.Params.ByzantiumForkBlock))
  304. }
  305. if chainParams.Params.ConstantinopleForkBlock != nil {
  306. constantinopleBlock = big.NewInt(int64(*chainParams.Params.ConstantinopleForkBlock))
  307. }
  308. if chainParams.Params.ConstantinopleFixForkBlock != nil {
  309. petersburgBlock = big.NewInt(int64(*chainParams.Params.ConstantinopleFixForkBlock))
  310. }
  311. if constantinopleBlock != nil && petersburgBlock == nil {
  312. petersburgBlock = big.NewInt(100000000000)
  313. }
  314. if chainParams.Params.IstanbulBlock != nil {
  315. istanbulBlock = big.NewInt(int64(*chainParams.Params.IstanbulBlock))
  316. }
  317. genesis := &core.Genesis{
  318. Config: &params.ChainConfig{
  319. ChainID: chainId,
  320. HomesteadBlock: homesteadBlock,
  321. DAOForkBlock: daoForkBlock,
  322. DAOForkSupport: true,
  323. EIP150Block: eip150Block,
  324. EIP155Block: eip155Block,
  325. EIP158Block: eip158Block,
  326. ByzantiumBlock: byzantiumBlock,
  327. ConstantinopleBlock: constantinopleBlock,
  328. PetersburgBlock: petersburgBlock,
  329. IstanbulBlock: istanbulBlock,
  330. },
  331. Nonce: uint64(chainParams.Genesis.Nonce),
  332. Timestamp: uint64(chainParams.Genesis.Timestamp),
  333. ExtraData: chainParams.Genesis.ExtraData,
  334. GasLimit: uint64(chainParams.Genesis.GasLimit),
  335. Difficulty: big.NewInt(0).Set((*big.Int)(chainParams.Genesis.Difficulty)),
  336. Mixhash: common.BigToHash((*big.Int)(chainParams.Genesis.MixHash)),
  337. Coinbase: chainParams.Genesis.Author,
  338. ParentHash: chainParams.Genesis.ParentHash,
  339. Alloc: accounts,
  340. }
  341. chainConfig, genesisHash, err := core.SetupGenesisBlock(ethDb, genesis)
  342. if err != nil {
  343. return false, err
  344. }
  345. fmt.Printf("Chain config: %v\n", chainConfig)
  346. var inner consensus.Engine
  347. switch chainParams.SealEngine {
  348. case "NoProof", "NoReward":
  349. inner = ethash.NewFaker()
  350. case "Ethash":
  351. inner = ethash.New(ethash.Config{
  352. CacheDir: "ethash",
  353. CachesInMem: 2,
  354. CachesOnDisk: 3,
  355. CachesLockMmap: false,
  356. DatasetsInMem: 1,
  357. DatasetsOnDisk: 2,
  358. DatasetsLockMmap: false,
  359. }, nil, false)
  360. default:
  361. return false, fmt.Errorf("unrecognised seal engine: %s", chainParams.SealEngine)
  362. }
  363. engine := &NoRewardEngine{inner: inner, rewardsOn: chainParams.SealEngine != "NoReward"}
  364. blockchain, err := core.NewBlockChain(ethDb, nil, chainConfig, engine, vm.Config{}, nil, nil)
  365. if err != nil {
  366. return false, err
  367. }
  368. api.chainConfig = chainConfig
  369. api.genesisHash = genesisHash
  370. api.author = chainParams.Genesis.Author
  371. api.extraData = chainParams.Genesis.ExtraData
  372. api.ethDb = ethDb
  373. api.engine = engine
  374. api.blockchain = blockchain
  375. api.db = state.NewDatabase(api.ethDb)
  376. api.txMap = make(map[common.Address]map[uint64]*types.Transaction)
  377. api.txSenders = make(map[common.Address]struct{})
  378. api.blockInterval = 0
  379. return true, nil
  380. }
  381. func (api *RetestethAPI) SendRawTransaction(ctx context.Context, rawTx hexutil.Bytes) (common.Hash, error) {
  382. tx := new(types.Transaction)
  383. if err := rlp.DecodeBytes(rawTx, tx); err != nil {
  384. // Return nil is not by mistake - some tests include sending transaction where gasLimit overflows uint64
  385. return common.Hash{}, nil
  386. }
  387. signer := types.MakeSigner(api.chainConfig, big.NewInt(int64(api.currentNumber())))
  388. sender, err := types.Sender(signer, tx)
  389. if err != nil {
  390. return common.Hash{}, err
  391. }
  392. if nonceMap, ok := api.txMap[sender]; ok {
  393. nonceMap[tx.Nonce()] = tx
  394. } else {
  395. nonceMap = make(map[uint64]*types.Transaction)
  396. nonceMap[tx.Nonce()] = tx
  397. api.txMap[sender] = nonceMap
  398. }
  399. api.txSenders[sender] = struct{}{}
  400. return tx.Hash(), nil
  401. }
  402. func (api *RetestethAPI) MineBlocks(ctx context.Context, number uint64) (bool, error) {
  403. for i := 0; i < int(number); i++ {
  404. if err := api.mineBlock(); err != nil {
  405. return false, err
  406. }
  407. }
  408. fmt.Printf("Mined %d blocks\n", number)
  409. return true, nil
  410. }
  411. func (api *RetestethAPI) currentNumber() uint64 {
  412. if current := api.blockchain.CurrentBlock(); current != nil {
  413. return current.NumberU64()
  414. }
  415. return 0
  416. }
  417. func (api *RetestethAPI) mineBlock() error {
  418. number := api.currentNumber()
  419. parentHash := rawdb.ReadCanonicalHash(api.ethDb, number)
  420. parent := rawdb.ReadBlock(api.ethDb, parentHash, number)
  421. var timestamp uint64
  422. if api.blockInterval == 0 {
  423. timestamp = uint64(time.Now().Unix())
  424. } else {
  425. timestamp = parent.Time() + api.blockInterval
  426. }
  427. gasLimit := core.CalcGasLimit(parent, 9223372036854775807, 9223372036854775807)
  428. header := &types.Header{
  429. ParentHash: parent.Hash(),
  430. Number: big.NewInt(int64(number + 1)),
  431. GasLimit: gasLimit,
  432. Extra: api.extraData,
  433. Time: timestamp,
  434. }
  435. header.Coinbase = api.author
  436. if api.engine != nil {
  437. api.engine.Prepare(api.blockchain, header)
  438. }
  439. // If we are care about TheDAO hard-fork check whether to override the extra-data or not
  440. if daoBlock := api.chainConfig.DAOForkBlock; daoBlock != nil {
  441. // Check whether the block is among the fork extra-override range
  442. limit := new(big.Int).Add(daoBlock, params.DAOForkExtraRange)
  443. if header.Number.Cmp(daoBlock) >= 0 && header.Number.Cmp(limit) < 0 {
  444. // Depending whether we support or oppose the fork, override differently
  445. if api.chainConfig.DAOForkSupport {
  446. header.Extra = common.CopyBytes(params.DAOForkBlockExtra)
  447. } else if bytes.Equal(header.Extra, params.DAOForkBlockExtra) {
  448. header.Extra = []byte{} // If miner opposes, don't let it use the reserved extra-data
  449. }
  450. }
  451. }
  452. statedb, err := api.blockchain.StateAt(parent.Root())
  453. if err != nil {
  454. return err
  455. }
  456. if api.chainConfig.DAOForkSupport && api.chainConfig.DAOForkBlock != nil && api.chainConfig.DAOForkBlock.Cmp(header.Number) == 0 {
  457. misc.ApplyDAOHardFork(statedb)
  458. }
  459. gasPool := new(core.GasPool).AddGas(header.GasLimit)
  460. txCount := 0
  461. var txs []*types.Transaction
  462. var receipts []*types.Receipt
  463. var blockFull = gasPool.Gas() < params.TxGas
  464. for address := range api.txSenders {
  465. if blockFull {
  466. break
  467. }
  468. m := api.txMap[address]
  469. for nonce := statedb.GetNonce(address); ; nonce++ {
  470. if tx, ok := m[nonce]; ok {
  471. // Try to apply transactions to the state
  472. statedb.Prepare(tx.Hash(), common.Hash{}, txCount)
  473. snap := statedb.Snapshot()
  474. receipt, err := core.ApplyTransaction(
  475. api.chainConfig,
  476. api.blockchain,
  477. &api.author,
  478. gasPool,
  479. statedb,
  480. header, tx, &header.GasUsed, *api.blockchain.GetVMConfig(),
  481. )
  482. if err != nil {
  483. statedb.RevertToSnapshot(snap)
  484. break
  485. }
  486. txs = append(txs, tx)
  487. receipts = append(receipts, receipt)
  488. delete(m, nonce)
  489. if len(m) == 0 {
  490. // Last tx for the sender
  491. delete(api.txMap, address)
  492. delete(api.txSenders, address)
  493. }
  494. txCount++
  495. if gasPool.Gas() < params.TxGas {
  496. blockFull = true
  497. break
  498. }
  499. } else {
  500. break // Gap in the nonces
  501. }
  502. }
  503. }
  504. block, err := api.engine.FinalizeAndAssemble(api.blockchain, header, statedb, txs, []*types.Header{}, receipts)
  505. if err != nil {
  506. return err
  507. }
  508. return api.importBlock(block)
  509. }
  510. func (api *RetestethAPI) importBlock(block *types.Block) error {
  511. if _, err := api.blockchain.InsertChain([]*types.Block{block}); err != nil {
  512. return err
  513. }
  514. fmt.Printf("Imported block %d, head is %d\n", block.NumberU64(), api.currentNumber())
  515. return nil
  516. }
  517. func (api *RetestethAPI) ModifyTimestamp(ctx context.Context, interval uint64) (bool, error) {
  518. api.blockInterval = interval
  519. return true, nil
  520. }
  521. func (api *RetestethAPI) ImportRawBlock(ctx context.Context, rawBlock hexutil.Bytes) (common.Hash, error) {
  522. block := new(types.Block)
  523. if err := rlp.DecodeBytes(rawBlock, block); err != nil {
  524. return common.Hash{}, err
  525. }
  526. fmt.Printf("Importing block %d with parent hash: %x, genesisHash: %x\n", block.NumberU64(), block.ParentHash(), api.genesisHash)
  527. if err := api.importBlock(block); err != nil {
  528. return common.Hash{}, err
  529. }
  530. return block.Hash(), nil
  531. }
  532. func (api *RetestethAPI) RewindToBlock(ctx context.Context, newHead uint64) (bool, error) {
  533. if err := api.blockchain.SetHead(newHead); err != nil {
  534. return false, err
  535. }
  536. // When we rewind, the transaction pool should be cleaned out.
  537. api.txMap = make(map[common.Address]map[uint64]*types.Transaction)
  538. api.txSenders = make(map[common.Address]struct{})
  539. return true, nil
  540. }
  541. var emptyListHash common.Hash = common.HexToHash("0x1dcc4de8dec75d7aab85b567b6ccd41ad312451b948a7413f0a142fd40d49347")
  542. func (api *RetestethAPI) GetLogHash(ctx context.Context, txHash common.Hash) (common.Hash, error) {
  543. receipt, _, _, _ := rawdb.ReadReceipt(api.ethDb, txHash, api.chainConfig)
  544. if receipt == nil {
  545. return emptyListHash, nil
  546. } else {
  547. if logListRlp, err := rlp.EncodeToBytes(receipt.Logs); err != nil {
  548. return common.Hash{}, err
  549. } else {
  550. return common.BytesToHash(crypto.Keccak256(logListRlp)), nil
  551. }
  552. }
  553. }
  554. func (api *RetestethAPI) BlockNumber(ctx context.Context) (uint64, error) {
  555. return api.currentNumber(), nil
  556. }
  557. func (api *RetestethAPI) GetBlockByNumber(ctx context.Context, blockNr math.HexOrDecimal64, fullTx bool) (map[string]interface{}, error) {
  558. block := api.blockchain.GetBlockByNumber(uint64(blockNr))
  559. if block != nil {
  560. response, err := RPCMarshalBlock(block, true, fullTx)
  561. if err != nil {
  562. return nil, err
  563. }
  564. response["author"] = response["miner"]
  565. response["totalDifficulty"] = (*hexutil.Big)(api.blockchain.GetTd(block.Hash(), uint64(blockNr)))
  566. return response, err
  567. }
  568. return nil, fmt.Errorf("block %d not found", blockNr)
  569. }
  570. func (api *RetestethAPI) GetBlockByHash(ctx context.Context, blockHash common.Hash, fullTx bool) (map[string]interface{}, error) {
  571. block := api.blockchain.GetBlockByHash(blockHash)
  572. if block != nil {
  573. response, err := RPCMarshalBlock(block, true, fullTx)
  574. if err != nil {
  575. return nil, err
  576. }
  577. response["author"] = response["miner"]
  578. response["totalDifficulty"] = (*hexutil.Big)(api.blockchain.GetTd(block.Hash(), block.Number().Uint64()))
  579. return response, err
  580. }
  581. return nil, fmt.Errorf("block 0x%x not found", blockHash)
  582. }
  583. func (api *RetestethAPI) AccountRange(ctx context.Context,
  584. blockHashOrNumber *math.HexOrDecimal256, txIndex uint64,
  585. addressHash *math.HexOrDecimal256, maxResults uint64,
  586. ) (AccountRangeResult, error) {
  587. var (
  588. header *types.Header
  589. block *types.Block
  590. )
  591. if (*big.Int)(blockHashOrNumber).Cmp(big.NewInt(math.MaxInt64)) > 0 {
  592. blockHash := common.BigToHash((*big.Int)(blockHashOrNumber))
  593. header = api.blockchain.GetHeaderByHash(blockHash)
  594. block = api.blockchain.GetBlockByHash(blockHash)
  595. //fmt.Printf("Account range: %x, txIndex %d, start: %x, maxResults: %d\n", blockHash, txIndex, common.BigToHash((*big.Int)(addressHash)), maxResults)
  596. } else {
  597. blockNumber := (*big.Int)(blockHashOrNumber).Uint64()
  598. header = api.blockchain.GetHeaderByNumber(blockNumber)
  599. block = api.blockchain.GetBlockByNumber(blockNumber)
  600. //fmt.Printf("Account range: %d, txIndex %d, start: %x, maxResults: %d\n", blockNumber, txIndex, common.BigToHash((*big.Int)(addressHash)), maxResults)
  601. }
  602. parentHeader := api.blockchain.GetHeaderByHash(header.ParentHash)
  603. var root common.Hash
  604. var statedb *state.StateDB
  605. var err error
  606. if parentHeader == nil || int(txIndex) >= len(block.Transactions()) {
  607. root = header.Root
  608. statedb, err = api.blockchain.StateAt(root)
  609. if err != nil {
  610. return AccountRangeResult{}, err
  611. }
  612. } else {
  613. root = parentHeader.Root
  614. statedb, err = api.blockchain.StateAt(root)
  615. if err != nil {
  616. return AccountRangeResult{}, err
  617. }
  618. // Recompute transactions up to the target index.
  619. signer := types.MakeSigner(api.blockchain.Config(), block.Number())
  620. for idx, tx := range block.Transactions() {
  621. // Assemble the transaction call message and return if the requested offset
  622. msg, _ := tx.AsMessage(signer)
  623. context := core.NewEVMContext(msg, block.Header(), api.blockchain, nil)
  624. // Not yet the searched for transaction, execute on top of the current state
  625. vmenv := vm.NewEVM(context, statedb, api.blockchain.Config(), vm.Config{})
  626. if _, err := core.ApplyMessage(vmenv, msg, new(core.GasPool).AddGas(tx.Gas())); err != nil {
  627. return AccountRangeResult{}, fmt.Errorf("transaction %#x failed: %v", tx.Hash(), err)
  628. }
  629. // Ensure any modifications are committed to the state
  630. // Only delete empty objects if EIP158/161 (a.k.a Spurious Dragon) is in effect
  631. root = statedb.IntermediateRoot(vmenv.ChainConfig().IsEIP158(block.Number()))
  632. if idx == int(txIndex) {
  633. // This is to make sure root can be opened by OpenTrie
  634. root, err = statedb.Commit(api.chainConfig.IsEIP158(block.Number()))
  635. if err != nil {
  636. return AccountRangeResult{}, err
  637. }
  638. break
  639. }
  640. }
  641. }
  642. accountTrie, err := statedb.Database().OpenTrie(root)
  643. if err != nil {
  644. return AccountRangeResult{}, err
  645. }
  646. it := trie.NewIterator(accountTrie.NodeIterator(common.BigToHash((*big.Int)(addressHash)).Bytes()))
  647. result := AccountRangeResult{AddressMap: make(map[common.Hash]common.Address)}
  648. for i := 0; i < int(maxResults) && it.Next(); i++ {
  649. if preimage := accountTrie.GetKey(it.Key); preimage != nil {
  650. result.AddressMap[common.BytesToHash(it.Key)] = common.BytesToAddress(preimage)
  651. }
  652. }
  653. //fmt.Printf("Number of entries returned: %d\n", len(result.AddressMap))
  654. // Add the 'next key' so clients can continue downloading.
  655. if it.Next() {
  656. next := common.BytesToHash(it.Key)
  657. result.NextKey = next
  658. }
  659. return result, nil
  660. }
  661. func (api *RetestethAPI) GetBalance(ctx context.Context, address common.Address, blockNr math.HexOrDecimal64) (*math.HexOrDecimal256, error) {
  662. //fmt.Printf("GetBalance %x, block %d\n", address, blockNr)
  663. header := api.blockchain.GetHeaderByNumber(uint64(blockNr))
  664. statedb, err := api.blockchain.StateAt(header.Root)
  665. if err != nil {
  666. return nil, err
  667. }
  668. return (*math.HexOrDecimal256)(statedb.GetBalance(address)), nil
  669. }
  670. func (api *RetestethAPI) GetCode(ctx context.Context, address common.Address, blockNr math.HexOrDecimal64) (hexutil.Bytes, error) {
  671. header := api.blockchain.GetHeaderByNumber(uint64(blockNr))
  672. statedb, err := api.blockchain.StateAt(header.Root)
  673. if err != nil {
  674. return nil, err
  675. }
  676. return statedb.GetCode(address), nil
  677. }
  678. func (api *RetestethAPI) GetTransactionCount(ctx context.Context, address common.Address, blockNr math.HexOrDecimal64) (uint64, error) {
  679. header := api.blockchain.GetHeaderByNumber(uint64(blockNr))
  680. statedb, err := api.blockchain.StateAt(header.Root)
  681. if err != nil {
  682. return 0, err
  683. }
  684. return statedb.GetNonce(address), nil
  685. }
  686. func (api *RetestethAPI) StorageRangeAt(ctx context.Context,
  687. blockHashOrNumber *math.HexOrDecimal256, txIndex uint64,
  688. address common.Address,
  689. begin *math.HexOrDecimal256, maxResults uint64,
  690. ) (StorageRangeResult, error) {
  691. var (
  692. header *types.Header
  693. block *types.Block
  694. )
  695. if (*big.Int)(blockHashOrNumber).Cmp(big.NewInt(math.MaxInt64)) > 0 {
  696. blockHash := common.BigToHash((*big.Int)(blockHashOrNumber))
  697. header = api.blockchain.GetHeaderByHash(blockHash)
  698. block = api.blockchain.GetBlockByHash(blockHash)
  699. //fmt.Printf("Storage range: %x, txIndex %d, addr: %x, start: %x, maxResults: %d\n",
  700. // blockHash, txIndex, address, common.BigToHash((*big.Int)(begin)), maxResults)
  701. } else {
  702. blockNumber := (*big.Int)(blockHashOrNumber).Uint64()
  703. header = api.blockchain.GetHeaderByNumber(blockNumber)
  704. block = api.blockchain.GetBlockByNumber(blockNumber)
  705. //fmt.Printf("Storage range: %d, txIndex %d, addr: %x, start: %x, maxResults: %d\n",
  706. // blockNumber, txIndex, address, common.BigToHash((*big.Int)(begin)), maxResults)
  707. }
  708. parentHeader := api.blockchain.GetHeaderByHash(header.ParentHash)
  709. var root common.Hash
  710. var statedb *state.StateDB
  711. var err error
  712. if parentHeader == nil || int(txIndex) >= len(block.Transactions()) {
  713. root = header.Root
  714. statedb, err = api.blockchain.StateAt(root)
  715. if err != nil {
  716. return StorageRangeResult{}, err
  717. }
  718. } else {
  719. root = parentHeader.Root
  720. statedb, err = api.blockchain.StateAt(root)
  721. if err != nil {
  722. return StorageRangeResult{}, err
  723. }
  724. // Recompute transactions up to the target index.
  725. signer := types.MakeSigner(api.blockchain.Config(), block.Number())
  726. for idx, tx := range block.Transactions() {
  727. // Assemble the transaction call message and return if the requested offset
  728. msg, _ := tx.AsMessage(signer)
  729. context := core.NewEVMContext(msg, block.Header(), api.blockchain, nil)
  730. // Not yet the searched for transaction, execute on top of the current state
  731. vmenv := vm.NewEVM(context, statedb, api.blockchain.Config(), vm.Config{})
  732. if _, err := core.ApplyMessage(vmenv, msg, new(core.GasPool).AddGas(tx.Gas())); err != nil {
  733. return StorageRangeResult{}, fmt.Errorf("transaction %#x failed: %v", tx.Hash(), err)
  734. }
  735. // Ensure any modifications are committed to the state
  736. // Only delete empty objects if EIP158/161 (a.k.a Spurious Dragon) is in effect
  737. _ = statedb.IntermediateRoot(vmenv.ChainConfig().IsEIP158(block.Number()))
  738. if idx == int(txIndex) {
  739. // This is to make sure root can be opened by OpenTrie
  740. _, err = statedb.Commit(vmenv.ChainConfig().IsEIP158(block.Number()))
  741. if err != nil {
  742. return StorageRangeResult{}, err
  743. }
  744. }
  745. }
  746. }
  747. storageTrie := statedb.StorageTrie(address)
  748. it := trie.NewIterator(storageTrie.NodeIterator(common.BigToHash((*big.Int)(begin)).Bytes()))
  749. result := StorageRangeResult{Storage: make(map[common.Hash]SRItem)}
  750. for i := 0; /*i < int(maxResults) && */ it.Next(); i++ {
  751. if preimage := storageTrie.GetKey(it.Key); preimage != nil {
  752. key := (*math.HexOrDecimal256)(big.NewInt(0).SetBytes(preimage))
  753. v, _, err := rlp.SplitString(it.Value)
  754. if err != nil {
  755. return StorageRangeResult{}, err
  756. }
  757. value := (*math.HexOrDecimal256)(big.NewInt(0).SetBytes(v))
  758. ks, _ := key.MarshalText()
  759. vs, _ := value.MarshalText()
  760. if len(ks)%2 != 0 {
  761. ks = append(append(append([]byte{}, ks[:2]...), byte('0')), ks[2:]...)
  762. }
  763. if len(vs)%2 != 0 {
  764. vs = append(append(append([]byte{}, vs[:2]...), byte('0')), vs[2:]...)
  765. }
  766. result.Storage[common.BytesToHash(it.Key)] = SRItem{
  767. Key: string(ks),
  768. Value: string(vs),
  769. }
  770. }
  771. }
  772. if it.Next() {
  773. result.Complete = false
  774. } else {
  775. result.Complete = true
  776. }
  777. return result, nil
  778. }
  779. func (api *RetestethAPI) ClientVersion(ctx context.Context) (string, error) {
  780. return "Geth-" + params.VersionWithCommit(gitCommit, gitDate), nil
  781. }
  782. // splitAndTrim splits input separated by a comma
  783. // and trims excessive white space from the substrings.
  784. func splitAndTrim(input string) []string {
  785. result := strings.Split(input, ",")
  786. for i, r := range result {
  787. result[i] = strings.TrimSpace(r)
  788. }
  789. return result
  790. }
  791. func retesteth(ctx *cli.Context) error {
  792. log.Info("Welcome to retesteth!")
  793. // register signer API with server
  794. var (
  795. extapiURL string
  796. )
  797. apiImpl := &RetestethAPI{}
  798. var testApi RetestethTestAPI = apiImpl
  799. var ethApi RetestethEthAPI = apiImpl
  800. var debugApi RetestethDebugAPI = apiImpl
  801. var web3Api RetestWeb3API = apiImpl
  802. rpcAPI := []rpc.API{
  803. {
  804. Namespace: "test",
  805. Public: true,
  806. Service: testApi,
  807. Version: "1.0",
  808. },
  809. {
  810. Namespace: "eth",
  811. Public: true,
  812. Service: ethApi,
  813. Version: "1.0",
  814. },
  815. {
  816. Namespace: "debug",
  817. Public: true,
  818. Service: debugApi,
  819. Version: "1.0",
  820. },
  821. {
  822. Namespace: "web3",
  823. Public: true,
  824. Service: web3Api,
  825. Version: "1.0",
  826. },
  827. }
  828. vhosts := splitAndTrim(ctx.GlobalString(utils.HTTPVirtualHostsFlag.Name))
  829. cors := splitAndTrim(ctx.GlobalString(utils.HTTPCORSDomainFlag.Name))
  830. // register apis and create handler stack
  831. srv := rpc.NewServer()
  832. err := node.RegisterApisFromWhitelist(rpcAPI, []string{"test", "eth", "debug", "web3"}, srv, false)
  833. if err != nil {
  834. utils.Fatalf("Could not register RPC apis: %w", err)
  835. }
  836. handler := node.NewHTTPHandlerStack(srv, cors, vhosts)
  837. // start http server
  838. var RetestethHTTPTimeouts = rpc.HTTPTimeouts{
  839. ReadTimeout: 120 * time.Second,
  840. WriteTimeout: 120 * time.Second,
  841. IdleTimeout: 120 * time.Second,
  842. }
  843. httpEndpoint := fmt.Sprintf("%s:%d", ctx.GlobalString(utils.HTTPListenAddrFlag.Name), ctx.Int(rpcPortFlag.Name))
  844. httpServer, _, err := node.StartHTTPEndpoint(httpEndpoint, RetestethHTTPTimeouts, handler)
  845. if err != nil {
  846. utils.Fatalf("Could not start RPC api: %v", err)
  847. }
  848. extapiURL = fmt.Sprintf("http://%s", httpEndpoint)
  849. log.Info("HTTP endpoint opened", "url", extapiURL)
  850. defer func() {
  851. // Don't bother imposing a timeout here.
  852. httpServer.Shutdown(context.Background())
  853. log.Info("HTTP endpoint closed", "url", httpEndpoint)
  854. }()
  855. abortChan := make(chan os.Signal, 11)
  856. signal.Notify(abortChan, os.Interrupt)
  857. sig := <-abortChan
  858. log.Info("Exiting...", "signal", sig)
  859. return nil
  860. }