retesteth.go 32 KB

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