api.go 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657
  1. // Copyright 2015 The go-ethereum Authors
  2. // This file is part of the go-ethereum library.
  3. //
  4. // The go-ethereum library is free software: you can redistribute it and/or modify
  5. // it under the terms of the GNU Lesser 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. // The go-ethereum library 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 Lesser General Public License for more details.
  13. //
  14. // You should have received a copy of the GNU Lesser General Public License
  15. // along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>.
  16. package eth
  17. import (
  18. "bytes"
  19. "compress/gzip"
  20. "context"
  21. "fmt"
  22. "io"
  23. "io/ioutil"
  24. "math/big"
  25. "os"
  26. "strings"
  27. "time"
  28. "github.com/ethereum/go-ethereum/common"
  29. "github.com/ethereum/go-ethereum/common/hexutil"
  30. "github.com/ethereum/go-ethereum/core"
  31. "github.com/ethereum/go-ethereum/core/state"
  32. "github.com/ethereum/go-ethereum/core/types"
  33. "github.com/ethereum/go-ethereum/core/vm"
  34. "github.com/ethereum/go-ethereum/internal/ethapi"
  35. "github.com/ethereum/go-ethereum/log"
  36. "github.com/ethereum/go-ethereum/miner"
  37. "github.com/ethereum/go-ethereum/params"
  38. "github.com/ethereum/go-ethereum/rlp"
  39. "github.com/ethereum/go-ethereum/rpc"
  40. "github.com/ethereum/go-ethereum/trie"
  41. )
  42. const defaultTraceTimeout = 5 * time.Second
  43. // PublicEthereumAPI provides an API to access Ethereum full node-related
  44. // information.
  45. type PublicEthereumAPI struct {
  46. e *Ethereum
  47. }
  48. // NewPublicEthereumAPI creates a new Etheruem protocol API for full nodes.
  49. func NewPublicEthereumAPI(e *Ethereum) *PublicEthereumAPI {
  50. return &PublicEthereumAPI{e}
  51. }
  52. // Etherbase is the address that mining rewards will be send to
  53. func (api *PublicEthereumAPI) Etherbase() (common.Address, error) {
  54. return api.e.Etherbase()
  55. }
  56. // Coinbase is the address that mining rewards will be send to (alias for Etherbase)
  57. func (api *PublicEthereumAPI) Coinbase() (common.Address, error) {
  58. return api.Etherbase()
  59. }
  60. // Hashrate returns the POW hashrate
  61. func (api *PublicEthereumAPI) Hashrate() hexutil.Uint64 {
  62. return hexutil.Uint64(api.e.Miner().HashRate())
  63. }
  64. // PublicMinerAPI provides an API to control the miner.
  65. // It offers only methods that operate on data that pose no security risk when it is publicly accessible.
  66. type PublicMinerAPI struct {
  67. e *Ethereum
  68. agent *miner.RemoteAgent
  69. }
  70. // NewPublicMinerAPI create a new PublicMinerAPI instance.
  71. func NewPublicMinerAPI(e *Ethereum) *PublicMinerAPI {
  72. agent := miner.NewRemoteAgent(e.BlockChain(), e.Engine())
  73. e.Miner().Register(agent)
  74. return &PublicMinerAPI{e, agent}
  75. }
  76. // Mining returns an indication if this node is currently mining.
  77. func (api *PublicMinerAPI) Mining() bool {
  78. return api.e.IsMining()
  79. }
  80. // SubmitWork can be used by external miner to submit their POW solution. It returns an indication if the work was
  81. // accepted. Note, this is not an indication if the provided work was valid!
  82. func (api *PublicMinerAPI) SubmitWork(nonce types.BlockNonce, solution, digest common.Hash) bool {
  83. return api.agent.SubmitWork(nonce, digest, solution)
  84. }
  85. // GetWork returns a work package for external miner. The work package consists of 3 strings
  86. // result[0], 32 bytes hex encoded current block header pow-hash
  87. // result[1], 32 bytes hex encoded seed hash used for DAG
  88. // result[2], 32 bytes hex encoded boundary condition ("target"), 2^256/difficulty
  89. func (api *PublicMinerAPI) GetWork() ([3]string, error) {
  90. if !api.e.IsMining() {
  91. if err := api.e.StartMining(false); err != nil {
  92. return [3]string{}, err
  93. }
  94. }
  95. work, err := api.agent.GetWork()
  96. if err != nil {
  97. return work, fmt.Errorf("mining not ready: %v", err)
  98. }
  99. return work, nil
  100. }
  101. // SubmitHashrate can be used for remote miners to submit their hash rate. This enables the node to report the combined
  102. // hash rate of all miners which submit work through this node. It accepts the miner hash rate and an identifier which
  103. // must be unique between nodes.
  104. func (api *PublicMinerAPI) SubmitHashrate(hashrate hexutil.Uint64, id common.Hash) bool {
  105. api.agent.SubmitHashrate(id, uint64(hashrate))
  106. return true
  107. }
  108. // PrivateMinerAPI provides private RPC methods to control the miner.
  109. // These methods can be abused by external users and must be considered insecure for use by untrusted users.
  110. type PrivateMinerAPI struct {
  111. e *Ethereum
  112. }
  113. // NewPrivateMinerAPI create a new RPC service which controls the miner of this node.
  114. func NewPrivateMinerAPI(e *Ethereum) *PrivateMinerAPI {
  115. return &PrivateMinerAPI{e: e}
  116. }
  117. // Start the miner with the given number of threads. If threads is nil the number
  118. // of workers started is equal to the number of logical CPUs that are usable by
  119. // this process. If mining is already running, this method adjust the number of
  120. // threads allowed to use.
  121. func (api *PrivateMinerAPI) Start(threads *int) error {
  122. // Set the number of threads if the seal engine supports it
  123. if threads == nil {
  124. threads = new(int)
  125. } else if *threads == 0 {
  126. *threads = -1 // Disable the miner from within
  127. }
  128. type threaded interface {
  129. SetThreads(threads int)
  130. }
  131. if th, ok := api.e.engine.(threaded); ok {
  132. log.Info("Updated mining threads", "threads", *threads)
  133. th.SetThreads(*threads)
  134. }
  135. // Start the miner and return
  136. if !api.e.IsMining() {
  137. // Propagate the initial price point to the transaction pool
  138. api.e.lock.RLock()
  139. price := api.e.gasPrice
  140. api.e.lock.RUnlock()
  141. api.e.txPool.SetGasPrice(price)
  142. return api.e.StartMining(true)
  143. }
  144. return nil
  145. }
  146. // Stop the miner
  147. func (api *PrivateMinerAPI) Stop() bool {
  148. type threaded interface {
  149. SetThreads(threads int)
  150. }
  151. if th, ok := api.e.engine.(threaded); ok {
  152. th.SetThreads(-1)
  153. }
  154. api.e.StopMining()
  155. return true
  156. }
  157. // SetExtra sets the extra data string that is included when this miner mines a block.
  158. func (api *PrivateMinerAPI) SetExtra(extra string) (bool, error) {
  159. if err := api.e.Miner().SetExtra([]byte(extra)); err != nil {
  160. return false, err
  161. }
  162. return true, nil
  163. }
  164. // SetGasPrice sets the minimum accepted gas price for the miner.
  165. func (api *PrivateMinerAPI) SetGasPrice(gasPrice hexutil.Big) bool {
  166. api.e.lock.Lock()
  167. api.e.gasPrice = (*big.Int)(&gasPrice)
  168. api.e.lock.Unlock()
  169. api.e.txPool.SetGasPrice((*big.Int)(&gasPrice))
  170. return true
  171. }
  172. // SetEtherbase sets the etherbase of the miner
  173. func (api *PrivateMinerAPI) SetEtherbase(etherbase common.Address) bool {
  174. api.e.SetEtherbase(etherbase)
  175. return true
  176. }
  177. // GetHashrate returns the current hashrate of the miner.
  178. func (api *PrivateMinerAPI) GetHashrate() uint64 {
  179. return uint64(api.e.miner.HashRate())
  180. }
  181. // PrivateAdminAPI is the collection of Etheruem full node-related APIs
  182. // exposed over the private admin endpoint.
  183. type PrivateAdminAPI struct {
  184. eth *Ethereum
  185. }
  186. // NewPrivateAdminAPI creates a new API definition for the full node private
  187. // admin methods of the Ethereum service.
  188. func NewPrivateAdminAPI(eth *Ethereum) *PrivateAdminAPI {
  189. return &PrivateAdminAPI{eth: eth}
  190. }
  191. // ExportChain exports the current blockchain into a local file.
  192. func (api *PrivateAdminAPI) ExportChain(file string) (bool, error) {
  193. // Make sure we can create the file to export into
  194. out, err := os.OpenFile(file, os.O_CREATE|os.O_WRONLY|os.O_TRUNC, os.ModePerm)
  195. if err != nil {
  196. return false, err
  197. }
  198. defer out.Close()
  199. var writer io.Writer = out
  200. if strings.HasSuffix(file, ".gz") {
  201. writer = gzip.NewWriter(writer)
  202. defer writer.(*gzip.Writer).Close()
  203. }
  204. // Export the blockchain
  205. if err := api.eth.BlockChain().Export(writer); err != nil {
  206. return false, err
  207. }
  208. return true, nil
  209. }
  210. func hasAllBlocks(chain *core.BlockChain, bs []*types.Block) bool {
  211. for _, b := range bs {
  212. if !chain.HasBlock(b.Hash()) {
  213. return false
  214. }
  215. }
  216. return true
  217. }
  218. // ImportChain imports a blockchain from a local file.
  219. func (api *PrivateAdminAPI) ImportChain(file string) (bool, error) {
  220. // Make sure the can access the file to import
  221. in, err := os.Open(file)
  222. if err != nil {
  223. return false, err
  224. }
  225. defer in.Close()
  226. var reader io.Reader = in
  227. if strings.HasSuffix(file, ".gz") {
  228. if reader, err = gzip.NewReader(reader); err != nil {
  229. return false, err
  230. }
  231. }
  232. // Run actual the import in pre-configured batches
  233. stream := rlp.NewStream(reader, 0)
  234. blocks, index := make([]*types.Block, 0, 2500), 0
  235. for batch := 0; ; batch++ {
  236. // Load a batch of blocks from the input file
  237. for len(blocks) < cap(blocks) {
  238. block := new(types.Block)
  239. if err := stream.Decode(block); err == io.EOF {
  240. break
  241. } else if err != nil {
  242. return false, fmt.Errorf("block %d: failed to parse: %v", index, err)
  243. }
  244. blocks = append(blocks, block)
  245. index++
  246. }
  247. if len(blocks) == 0 {
  248. break
  249. }
  250. if hasAllBlocks(api.eth.BlockChain(), blocks) {
  251. blocks = blocks[:0]
  252. continue
  253. }
  254. // Import the batch and reset the buffer
  255. if _, err := api.eth.BlockChain().InsertChain(blocks); err != nil {
  256. return false, fmt.Errorf("batch %d: failed to insert: %v", batch, err)
  257. }
  258. blocks = blocks[:0]
  259. }
  260. return true, nil
  261. }
  262. // PublicDebugAPI is the collection of Etheruem full node APIs exposed
  263. // over the public debugging endpoint.
  264. type PublicDebugAPI struct {
  265. eth *Ethereum
  266. }
  267. // NewPublicDebugAPI creates a new API definition for the full node-
  268. // related public debug methods of the Ethereum service.
  269. func NewPublicDebugAPI(eth *Ethereum) *PublicDebugAPI {
  270. return &PublicDebugAPI{eth: eth}
  271. }
  272. // DumpBlock retrieves the entire state of the database at a given block.
  273. func (api *PublicDebugAPI) DumpBlock(blockNr rpc.BlockNumber) (state.Dump, error) {
  274. if blockNr == rpc.PendingBlockNumber {
  275. // If we're dumping the pending state, we need to request
  276. // both the pending block as well as the pending state from
  277. // the miner and operate on those
  278. _, stateDb := api.eth.miner.Pending()
  279. return stateDb.RawDump(), nil
  280. }
  281. var block *types.Block
  282. if blockNr == rpc.LatestBlockNumber {
  283. block = api.eth.blockchain.CurrentBlock()
  284. } else {
  285. block = api.eth.blockchain.GetBlockByNumber(uint64(blockNr))
  286. }
  287. if block == nil {
  288. return state.Dump{}, fmt.Errorf("block #%d not found", blockNr)
  289. }
  290. stateDb, err := api.eth.BlockChain().StateAt(block.Root())
  291. if err != nil {
  292. return state.Dump{}, err
  293. }
  294. return stateDb.RawDump(), nil
  295. }
  296. // PrivateDebugAPI is the collection of Etheruem full node APIs exposed over
  297. // the private debugging endpoint.
  298. type PrivateDebugAPI struct {
  299. config *params.ChainConfig
  300. eth *Ethereum
  301. }
  302. // NewPrivateDebugAPI creates a new API definition for the full node-related
  303. // private debug methods of the Ethereum service.
  304. func NewPrivateDebugAPI(config *params.ChainConfig, eth *Ethereum) *PrivateDebugAPI {
  305. return &PrivateDebugAPI{config: config, eth: eth}
  306. }
  307. // BlockTraceResult is the returned value when replaying a block to check for
  308. // consensus results and full VM trace logs for all included transactions.
  309. type BlockTraceResult struct {
  310. Validated bool `json:"validated"`
  311. StructLogs []ethapi.StructLogRes `json:"structLogs"`
  312. Error string `json:"error"`
  313. }
  314. // TraceArgs holds extra parameters to trace functions
  315. type TraceArgs struct {
  316. *vm.LogConfig
  317. Tracer *string
  318. Timeout *string
  319. }
  320. // TraceBlock processes the given block'api RLP but does not import the block in to
  321. // the chain.
  322. func (api *PrivateDebugAPI) TraceBlock(blockRlp []byte, config *vm.LogConfig) BlockTraceResult {
  323. var block types.Block
  324. err := rlp.Decode(bytes.NewReader(blockRlp), &block)
  325. if err != nil {
  326. return BlockTraceResult{Error: fmt.Sprintf("could not decode block: %v", err)}
  327. }
  328. validated, logs, err := api.traceBlock(&block, config)
  329. return BlockTraceResult{
  330. Validated: validated,
  331. StructLogs: ethapi.FormatLogs(logs),
  332. Error: formatError(err),
  333. }
  334. }
  335. // TraceBlockFromFile loads the block'api RLP from the given file name and attempts to
  336. // process it but does not import the block in to the chain.
  337. func (api *PrivateDebugAPI) TraceBlockFromFile(file string, config *vm.LogConfig) BlockTraceResult {
  338. blockRlp, err := ioutil.ReadFile(file)
  339. if err != nil {
  340. return BlockTraceResult{Error: fmt.Sprintf("could not read file: %v", err)}
  341. }
  342. return api.TraceBlock(blockRlp, config)
  343. }
  344. // TraceBlockByNumber processes the block by canonical block number.
  345. func (api *PrivateDebugAPI) TraceBlockByNumber(blockNr rpc.BlockNumber, config *vm.LogConfig) BlockTraceResult {
  346. // Fetch the block that we aim to reprocess
  347. var block *types.Block
  348. switch blockNr {
  349. case rpc.PendingBlockNumber:
  350. // Pending block is only known by the miner
  351. block = api.eth.miner.PendingBlock()
  352. case rpc.LatestBlockNumber:
  353. block = api.eth.blockchain.CurrentBlock()
  354. default:
  355. block = api.eth.blockchain.GetBlockByNumber(uint64(blockNr))
  356. }
  357. if block == nil {
  358. return BlockTraceResult{Error: fmt.Sprintf("block #%d not found", blockNr)}
  359. }
  360. validated, logs, err := api.traceBlock(block, config)
  361. return BlockTraceResult{
  362. Validated: validated,
  363. StructLogs: ethapi.FormatLogs(logs),
  364. Error: formatError(err),
  365. }
  366. }
  367. // TraceBlockByHash processes the block by hash.
  368. func (api *PrivateDebugAPI) TraceBlockByHash(hash common.Hash, config *vm.LogConfig) BlockTraceResult {
  369. // Fetch the block that we aim to reprocess
  370. block := api.eth.BlockChain().GetBlockByHash(hash)
  371. if block == nil {
  372. return BlockTraceResult{Error: fmt.Sprintf("block #%x not found", hash)}
  373. }
  374. validated, logs, err := api.traceBlock(block, config)
  375. return BlockTraceResult{
  376. Validated: validated,
  377. StructLogs: ethapi.FormatLogs(logs),
  378. Error: formatError(err),
  379. }
  380. }
  381. // traceBlock processes the given block but does not save the state.
  382. func (api *PrivateDebugAPI) traceBlock(block *types.Block, logConfig *vm.LogConfig) (bool, []vm.StructLog, error) {
  383. // Validate and reprocess the block
  384. var (
  385. blockchain = api.eth.BlockChain()
  386. validator = blockchain.Validator()
  387. processor = blockchain.Processor()
  388. )
  389. structLogger := vm.NewStructLogger(logConfig)
  390. config := vm.Config{
  391. Debug: true,
  392. Tracer: structLogger,
  393. }
  394. if err := api.eth.engine.VerifyHeader(blockchain, block.Header(), true); err != nil {
  395. return false, structLogger.StructLogs(), err
  396. }
  397. statedb, err := blockchain.StateAt(blockchain.GetBlock(block.ParentHash(), block.NumberU64()-1).Root())
  398. if err != nil {
  399. return false, structLogger.StructLogs(), err
  400. }
  401. receipts, _, usedGas, err := processor.Process(block, statedb, config)
  402. if err != nil {
  403. return false, structLogger.StructLogs(), err
  404. }
  405. if err := validator.ValidateState(block, blockchain.GetBlock(block.ParentHash(), block.NumberU64()-1), statedb, receipts, usedGas); err != nil {
  406. return false, structLogger.StructLogs(), err
  407. }
  408. return true, structLogger.StructLogs(), nil
  409. }
  410. // callmsg is the message type used for call transitions.
  411. type callmsg struct {
  412. addr common.Address
  413. to *common.Address
  414. gas, gasPrice *big.Int
  415. value *big.Int
  416. data []byte
  417. }
  418. // accessor boilerplate to implement core.Message
  419. func (m callmsg) From() (common.Address, error) { return m.addr, nil }
  420. func (m callmsg) FromFrontier() (common.Address, error) { return m.addr, nil }
  421. func (m callmsg) Nonce() uint64 { return 0 }
  422. func (m callmsg) CheckNonce() bool { return false }
  423. func (m callmsg) To() *common.Address { return m.to }
  424. func (m callmsg) GasPrice() *big.Int { return m.gasPrice }
  425. func (m callmsg) Gas() *big.Int { return m.gas }
  426. func (m callmsg) Value() *big.Int { return m.value }
  427. func (m callmsg) Data() []byte { return m.data }
  428. // formatError formats a Go error into either an empty string or the data content
  429. // of the error itself.
  430. func formatError(err error) string {
  431. if err == nil {
  432. return ""
  433. }
  434. return err.Error()
  435. }
  436. type timeoutError struct{}
  437. func (t *timeoutError) Error() string {
  438. return "Execution time exceeded"
  439. }
  440. // TraceTransaction returns the structured logs created during the execution of EVM
  441. // and returns them as a JSON object.
  442. func (api *PrivateDebugAPI) TraceTransaction(ctx context.Context, txHash common.Hash, config *TraceArgs) (interface{}, error) {
  443. var tracer vm.Tracer
  444. if config != nil && config.Tracer != nil {
  445. timeout := defaultTraceTimeout
  446. if config.Timeout != nil {
  447. var err error
  448. if timeout, err = time.ParseDuration(*config.Timeout); err != nil {
  449. return nil, err
  450. }
  451. }
  452. var err error
  453. if tracer, err = ethapi.NewJavascriptTracer(*config.Tracer); err != nil {
  454. return nil, err
  455. }
  456. // Handle timeouts and RPC cancellations
  457. deadlineCtx, cancel := context.WithTimeout(ctx, timeout)
  458. go func() {
  459. <-deadlineCtx.Done()
  460. tracer.(*ethapi.JavascriptTracer).Stop(&timeoutError{})
  461. }()
  462. defer cancel()
  463. } else if config == nil {
  464. tracer = vm.NewStructLogger(nil)
  465. } else {
  466. tracer = vm.NewStructLogger(config.LogConfig)
  467. }
  468. // Retrieve the tx from the chain and the containing block
  469. tx, blockHash, _, txIndex := core.GetTransaction(api.eth.ChainDb(), txHash)
  470. if tx == nil {
  471. return nil, fmt.Errorf("transaction %x not found", txHash)
  472. }
  473. msg, context, statedb, err := api.computeTxEnv(blockHash, int(txIndex))
  474. if err != nil {
  475. return nil, err
  476. }
  477. // Run the transaction with tracing enabled.
  478. vmenv := vm.NewEVM(context, statedb, api.config, vm.Config{Debug: true, Tracer: tracer})
  479. ret, gas, err := core.ApplyMessage(vmenv, msg, new(core.GasPool).AddGas(tx.Gas()))
  480. if err != nil {
  481. return nil, fmt.Errorf("tracing failed: %v", err)
  482. }
  483. switch tracer := tracer.(type) {
  484. case *vm.StructLogger:
  485. return &ethapi.ExecutionResult{
  486. Gas: gas,
  487. ReturnValue: fmt.Sprintf("%x", ret),
  488. StructLogs: ethapi.FormatLogs(tracer.StructLogs()),
  489. }, nil
  490. case *ethapi.JavascriptTracer:
  491. return tracer.GetResult()
  492. default:
  493. panic(fmt.Sprintf("bad tracer type %T", tracer))
  494. }
  495. }
  496. // computeTxEnv returns the execution environment of a certain transaction.
  497. func (api *PrivateDebugAPI) computeTxEnv(blockHash common.Hash, txIndex int) (core.Message, vm.Context, *state.StateDB, error) {
  498. // Create the parent state.
  499. block := api.eth.BlockChain().GetBlockByHash(blockHash)
  500. if block == nil {
  501. return nil, vm.Context{}, nil, fmt.Errorf("block %x not found", blockHash)
  502. }
  503. parent := api.eth.BlockChain().GetBlock(block.ParentHash(), block.NumberU64()-1)
  504. if parent == nil {
  505. return nil, vm.Context{}, nil, fmt.Errorf("block parent %x not found", block.ParentHash())
  506. }
  507. statedb, err := api.eth.BlockChain().StateAt(parent.Root())
  508. if err != nil {
  509. return nil, vm.Context{}, nil, err
  510. }
  511. txs := block.Transactions()
  512. // Recompute transactions up to the target index.
  513. signer := types.MakeSigner(api.config, block.Number())
  514. for idx, tx := range txs {
  515. // Assemble the transaction call message
  516. msg, _ := tx.AsMessage(signer)
  517. context := core.NewEVMContext(msg, block.Header(), api.eth.BlockChain(), nil)
  518. if idx == txIndex {
  519. return msg, context, statedb, nil
  520. }
  521. vmenv := vm.NewEVM(context, statedb, api.config, vm.Config{})
  522. gp := new(core.GasPool).AddGas(tx.Gas())
  523. _, _, err := core.ApplyMessage(vmenv, msg, gp)
  524. if err != nil {
  525. return nil, vm.Context{}, nil, fmt.Errorf("tx %x failed: %v", tx.Hash(), err)
  526. }
  527. statedb.DeleteSuicides()
  528. }
  529. return nil, vm.Context{}, nil, fmt.Errorf("tx index %d out of range for block %x", txIndex, blockHash)
  530. }
  531. // Preimage is a debug API function that returns the preimage for a sha3 hash, if known.
  532. func (api *PrivateDebugAPI) Preimage(ctx context.Context, hash common.Hash) (hexutil.Bytes, error) {
  533. db := core.PreimageTable(api.eth.ChainDb())
  534. return db.Get(hash.Bytes())
  535. }
  536. // GetBadBLocks returns a list of the last 'bad blocks' that the client has seen on the network
  537. // and returns them as a JSON list of block-hashes
  538. func (api *PrivateDebugAPI) GetBadBlocks(ctx context.Context) ([]core.BadBlockArgs, error) {
  539. return api.eth.BlockChain().BadBlocks()
  540. }
  541. // StorageRangeResult is the result of a debug_storageRangeAt API call.
  542. type StorageRangeResult struct {
  543. Storage storageMap `json:"storage"`
  544. NextKey *common.Hash `json:"nextKey"` // nil if Storage includes the last key in the trie.
  545. }
  546. type storageMap map[common.Hash]storageEntry
  547. type storageEntry struct {
  548. Key *common.Hash `json:"key"`
  549. Value common.Hash `json:"value"`
  550. }
  551. // StorageRangeAt returns the storage at the given block height and transaction index.
  552. func (api *PrivateDebugAPI) StorageRangeAt(ctx context.Context, blockHash common.Hash, txIndex int, contractAddress common.Address, keyStart hexutil.Bytes, maxResult int) (StorageRangeResult, error) {
  553. _, _, statedb, err := api.computeTxEnv(blockHash, txIndex)
  554. if err != nil {
  555. return StorageRangeResult{}, err
  556. }
  557. st := statedb.StorageTrie(contractAddress)
  558. if st == nil {
  559. return StorageRangeResult{}, fmt.Errorf("account %x doesn't exist", contractAddress)
  560. }
  561. return storageRangeAt(st, keyStart, maxResult), nil
  562. }
  563. func storageRangeAt(st *trie.SecureTrie, start []byte, maxResult int) StorageRangeResult {
  564. it := trie.NewIterator(st.NodeIterator(start))
  565. result := StorageRangeResult{Storage: storageMap{}}
  566. for i := 0; i < maxResult && it.Next(); i++ {
  567. e := storageEntry{Value: common.BytesToHash(it.Value)}
  568. if preimage := st.GetKey(it.Key); preimage != nil {
  569. preimage := common.BytesToHash(preimage)
  570. e.Key = &preimage
  571. }
  572. result.Storage[common.BytesToHash(it.Key)] = e
  573. }
  574. // Add the 'next key' so clients can continue downloading.
  575. if it.Next() {
  576. next := common.BytesToHash(it.Key)
  577. result.NextKey = &next
  578. }
  579. return result
  580. }