api.go 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647
  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. return api.e.StartMining(true)
  138. }
  139. return nil
  140. }
  141. // Stop the miner
  142. func (api *PrivateMinerAPI) Stop() bool {
  143. type threaded interface {
  144. SetThreads(threads int)
  145. }
  146. if th, ok := api.e.engine.(threaded); ok {
  147. th.SetThreads(-1)
  148. }
  149. api.e.StopMining()
  150. return true
  151. }
  152. // SetExtra sets the extra data string that is included when this miner mines a block.
  153. func (api *PrivateMinerAPI) SetExtra(extra string) (bool, error) {
  154. if err := api.e.Miner().SetExtra([]byte(extra)); err != nil {
  155. return false, err
  156. }
  157. return true, nil
  158. }
  159. // SetGasPrice sets the minimum accepted gas price for the miner.
  160. func (api *PrivateMinerAPI) SetGasPrice(gasPrice hexutil.Big) bool {
  161. api.e.Miner().SetGasPrice((*big.Int)(&gasPrice))
  162. return true
  163. }
  164. // SetEtherbase sets the etherbase of the miner
  165. func (api *PrivateMinerAPI) SetEtherbase(etherbase common.Address) bool {
  166. api.e.SetEtherbase(etherbase)
  167. return true
  168. }
  169. // GetHashrate returns the current hashrate of the miner.
  170. func (api *PrivateMinerAPI) GetHashrate() uint64 {
  171. return uint64(api.e.miner.HashRate())
  172. }
  173. // PrivateAdminAPI is the collection of Etheruem full node-related APIs
  174. // exposed over the private admin endpoint.
  175. type PrivateAdminAPI struct {
  176. eth *Ethereum
  177. }
  178. // NewPrivateAdminAPI creates a new API definition for the full node private
  179. // admin methods of the Ethereum service.
  180. func NewPrivateAdminAPI(eth *Ethereum) *PrivateAdminAPI {
  181. return &PrivateAdminAPI{eth: eth}
  182. }
  183. // ExportChain exports the current blockchain into a local file.
  184. func (api *PrivateAdminAPI) ExportChain(file string) (bool, error) {
  185. // Make sure we can create the file to export into
  186. out, err := os.OpenFile(file, os.O_CREATE|os.O_WRONLY|os.O_TRUNC, os.ModePerm)
  187. if err != nil {
  188. return false, err
  189. }
  190. defer out.Close()
  191. var writer io.Writer = out
  192. if strings.HasSuffix(file, ".gz") {
  193. writer = gzip.NewWriter(writer)
  194. defer writer.(*gzip.Writer).Close()
  195. }
  196. // Export the blockchain
  197. if err := api.eth.BlockChain().Export(writer); err != nil {
  198. return false, err
  199. }
  200. return true, nil
  201. }
  202. func hasAllBlocks(chain *core.BlockChain, bs []*types.Block) bool {
  203. for _, b := range bs {
  204. if !chain.HasBlock(b.Hash()) {
  205. return false
  206. }
  207. }
  208. return true
  209. }
  210. // ImportChain imports a blockchain from a local file.
  211. func (api *PrivateAdminAPI) ImportChain(file string) (bool, error) {
  212. // Make sure the can access the file to import
  213. in, err := os.Open(file)
  214. if err != nil {
  215. return false, err
  216. }
  217. defer in.Close()
  218. var reader io.Reader = in
  219. if strings.HasSuffix(file, ".gz") {
  220. if reader, err = gzip.NewReader(reader); err != nil {
  221. return false, err
  222. }
  223. }
  224. // Run actual the import in pre-configured batches
  225. stream := rlp.NewStream(reader, 0)
  226. blocks, index := make([]*types.Block, 0, 2500), 0
  227. for batch := 0; ; batch++ {
  228. // Load a batch of blocks from the input file
  229. for len(blocks) < cap(blocks) {
  230. block := new(types.Block)
  231. if err := stream.Decode(block); err == io.EOF {
  232. break
  233. } else if err != nil {
  234. return false, fmt.Errorf("block %d: failed to parse: %v", index, err)
  235. }
  236. blocks = append(blocks, block)
  237. index++
  238. }
  239. if len(blocks) == 0 {
  240. break
  241. }
  242. if hasAllBlocks(api.eth.BlockChain(), blocks) {
  243. blocks = blocks[:0]
  244. continue
  245. }
  246. // Import the batch and reset the buffer
  247. if _, err := api.eth.BlockChain().InsertChain(blocks); err != nil {
  248. return false, fmt.Errorf("batch %d: failed to insert: %v", batch, err)
  249. }
  250. blocks = blocks[:0]
  251. }
  252. return true, nil
  253. }
  254. // PublicDebugAPI is the collection of Etheruem full node APIs exposed
  255. // over the public debugging endpoint.
  256. type PublicDebugAPI struct {
  257. eth *Ethereum
  258. }
  259. // NewPublicDebugAPI creates a new API definition for the full node-
  260. // related public debug methods of the Ethereum service.
  261. func NewPublicDebugAPI(eth *Ethereum) *PublicDebugAPI {
  262. return &PublicDebugAPI{eth: eth}
  263. }
  264. // DumpBlock retrieves the entire state of the database at a given block.
  265. func (api *PublicDebugAPI) DumpBlock(blockNr rpc.BlockNumber) (state.Dump, error) {
  266. if blockNr == rpc.PendingBlockNumber {
  267. // If we're dumping the pending state, we need to request
  268. // both the pending block as well as the pending state from
  269. // the miner and operate on those
  270. _, stateDb := api.eth.miner.Pending()
  271. return stateDb.RawDump(), nil
  272. }
  273. var block *types.Block
  274. if blockNr == rpc.LatestBlockNumber {
  275. block = api.eth.blockchain.CurrentBlock()
  276. } else {
  277. block = api.eth.blockchain.GetBlockByNumber(uint64(blockNr))
  278. }
  279. if block == nil {
  280. return state.Dump{}, fmt.Errorf("block #%d not found", blockNr)
  281. }
  282. stateDb, err := api.eth.BlockChain().StateAt(block.Root())
  283. if err != nil {
  284. return state.Dump{}, err
  285. }
  286. return stateDb.RawDump(), nil
  287. }
  288. // PrivateDebugAPI is the collection of Etheruem full node APIs exposed over
  289. // the private debugging endpoint.
  290. type PrivateDebugAPI struct {
  291. config *params.ChainConfig
  292. eth *Ethereum
  293. }
  294. // NewPrivateDebugAPI creates a new API definition for the full node-related
  295. // private debug methods of the Ethereum service.
  296. func NewPrivateDebugAPI(config *params.ChainConfig, eth *Ethereum) *PrivateDebugAPI {
  297. return &PrivateDebugAPI{config: config, eth: eth}
  298. }
  299. // BlockTraceResult is the returned value when replaying a block to check for
  300. // consensus results and full VM trace logs for all included transactions.
  301. type BlockTraceResult struct {
  302. Validated bool `json:"validated"`
  303. StructLogs []ethapi.StructLogRes `json:"structLogs"`
  304. Error string `json:"error"`
  305. }
  306. // TraceArgs holds extra parameters to trace functions
  307. type TraceArgs struct {
  308. *vm.LogConfig
  309. Tracer *string
  310. Timeout *string
  311. }
  312. // TraceBlock processes the given block'api RLP but does not import the block in to
  313. // the chain.
  314. func (api *PrivateDebugAPI) TraceBlock(blockRlp []byte, config *vm.LogConfig) BlockTraceResult {
  315. var block types.Block
  316. err := rlp.Decode(bytes.NewReader(blockRlp), &block)
  317. if err != nil {
  318. return BlockTraceResult{Error: fmt.Sprintf("could not decode block: %v", err)}
  319. }
  320. validated, logs, err := api.traceBlock(&block, config)
  321. return BlockTraceResult{
  322. Validated: validated,
  323. StructLogs: ethapi.FormatLogs(logs),
  324. Error: formatError(err),
  325. }
  326. }
  327. // TraceBlockFromFile loads the block'api RLP from the given file name and attempts to
  328. // process it but does not import the block in to the chain.
  329. func (api *PrivateDebugAPI) TraceBlockFromFile(file string, config *vm.LogConfig) BlockTraceResult {
  330. blockRlp, err := ioutil.ReadFile(file)
  331. if err != nil {
  332. return BlockTraceResult{Error: fmt.Sprintf("could not read file: %v", err)}
  333. }
  334. return api.TraceBlock(blockRlp, config)
  335. }
  336. // TraceBlockByNumber processes the block by canonical block number.
  337. func (api *PrivateDebugAPI) TraceBlockByNumber(blockNr rpc.BlockNumber, config *vm.LogConfig) BlockTraceResult {
  338. // Fetch the block that we aim to reprocess
  339. var block *types.Block
  340. switch blockNr {
  341. case rpc.PendingBlockNumber:
  342. // Pending block is only known by the miner
  343. block = api.eth.miner.PendingBlock()
  344. case rpc.LatestBlockNumber:
  345. block = api.eth.blockchain.CurrentBlock()
  346. default:
  347. block = api.eth.blockchain.GetBlockByNumber(uint64(blockNr))
  348. }
  349. if block == nil {
  350. return BlockTraceResult{Error: fmt.Sprintf("block #%d not found", blockNr)}
  351. }
  352. validated, logs, err := api.traceBlock(block, config)
  353. return BlockTraceResult{
  354. Validated: validated,
  355. StructLogs: ethapi.FormatLogs(logs),
  356. Error: formatError(err),
  357. }
  358. }
  359. // TraceBlockByHash processes the block by hash.
  360. func (api *PrivateDebugAPI) TraceBlockByHash(hash common.Hash, config *vm.LogConfig) BlockTraceResult {
  361. // Fetch the block that we aim to reprocess
  362. block := api.eth.BlockChain().GetBlockByHash(hash)
  363. if block == nil {
  364. return BlockTraceResult{Error: fmt.Sprintf("block #%x not found", hash)}
  365. }
  366. validated, logs, err := api.traceBlock(block, config)
  367. return BlockTraceResult{
  368. Validated: validated,
  369. StructLogs: ethapi.FormatLogs(logs),
  370. Error: formatError(err),
  371. }
  372. }
  373. // traceBlock processes the given block but does not save the state.
  374. func (api *PrivateDebugAPI) traceBlock(block *types.Block, logConfig *vm.LogConfig) (bool, []vm.StructLog, error) {
  375. // Validate and reprocess the block
  376. var (
  377. blockchain = api.eth.BlockChain()
  378. validator = blockchain.Validator()
  379. processor = blockchain.Processor()
  380. )
  381. structLogger := vm.NewStructLogger(logConfig)
  382. config := vm.Config{
  383. Debug: true,
  384. Tracer: structLogger,
  385. }
  386. if err := api.eth.engine.VerifyHeader(blockchain, block.Header(), true); err != nil {
  387. return false, structLogger.StructLogs(), err
  388. }
  389. statedb, err := blockchain.StateAt(blockchain.GetBlock(block.ParentHash(), block.NumberU64()-1).Root())
  390. if err != nil {
  391. return false, structLogger.StructLogs(), err
  392. }
  393. receipts, _, usedGas, err := processor.Process(block, statedb, config)
  394. if err != nil {
  395. return false, structLogger.StructLogs(), err
  396. }
  397. if err := validator.ValidateState(block, blockchain.GetBlock(block.ParentHash(), block.NumberU64()-1), statedb, receipts, usedGas); err != nil {
  398. return false, structLogger.StructLogs(), err
  399. }
  400. return true, structLogger.StructLogs(), nil
  401. }
  402. // callmsg is the message type used for call transitions.
  403. type callmsg struct {
  404. addr common.Address
  405. to *common.Address
  406. gas, gasPrice *big.Int
  407. value *big.Int
  408. data []byte
  409. }
  410. // accessor boilerplate to implement core.Message
  411. func (m callmsg) From() (common.Address, error) { return m.addr, nil }
  412. func (m callmsg) FromFrontier() (common.Address, error) { return m.addr, nil }
  413. func (m callmsg) Nonce() uint64 { return 0 }
  414. func (m callmsg) CheckNonce() bool { return false }
  415. func (m callmsg) To() *common.Address { return m.to }
  416. func (m callmsg) GasPrice() *big.Int { return m.gasPrice }
  417. func (m callmsg) Gas() *big.Int { return m.gas }
  418. func (m callmsg) Value() *big.Int { return m.value }
  419. func (m callmsg) Data() []byte { return m.data }
  420. // formatError formats a Go error into either an empty string or the data content
  421. // of the error itself.
  422. func formatError(err error) string {
  423. if err == nil {
  424. return ""
  425. }
  426. return err.Error()
  427. }
  428. type timeoutError struct{}
  429. func (t *timeoutError) Error() string {
  430. return "Execution time exceeded"
  431. }
  432. // TraceTransaction returns the structured logs created during the execution of EVM
  433. // and returns them as a JSON object.
  434. func (api *PrivateDebugAPI) TraceTransaction(ctx context.Context, txHash common.Hash, config *TraceArgs) (interface{}, error) {
  435. var tracer vm.Tracer
  436. if config != nil && config.Tracer != nil {
  437. timeout := defaultTraceTimeout
  438. if config.Timeout != nil {
  439. var err error
  440. if timeout, err = time.ParseDuration(*config.Timeout); err != nil {
  441. return nil, err
  442. }
  443. }
  444. var err error
  445. if tracer, err = ethapi.NewJavascriptTracer(*config.Tracer); err != nil {
  446. return nil, err
  447. }
  448. // Handle timeouts and RPC cancellations
  449. deadlineCtx, cancel := context.WithTimeout(ctx, timeout)
  450. go func() {
  451. <-deadlineCtx.Done()
  452. tracer.(*ethapi.JavascriptTracer).Stop(&timeoutError{})
  453. }()
  454. defer cancel()
  455. } else if config == nil {
  456. tracer = vm.NewStructLogger(nil)
  457. } else {
  458. tracer = vm.NewStructLogger(config.LogConfig)
  459. }
  460. // Retrieve the tx from the chain and the containing block
  461. tx, blockHash, _, txIndex := core.GetTransaction(api.eth.ChainDb(), txHash)
  462. if tx == nil {
  463. return nil, fmt.Errorf("transaction %x not found", txHash)
  464. }
  465. msg, context, statedb, err := api.computeTxEnv(blockHash, int(txIndex))
  466. if err != nil {
  467. return nil, err
  468. }
  469. // Run the transaction with tracing enabled.
  470. vmenv := vm.NewEVM(context, statedb, api.config, vm.Config{Debug: true, Tracer: tracer})
  471. ret, gas, err := core.ApplyMessage(vmenv, msg, new(core.GasPool).AddGas(tx.Gas()))
  472. if err != nil {
  473. return nil, fmt.Errorf("tracing failed: %v", err)
  474. }
  475. switch tracer := tracer.(type) {
  476. case *vm.StructLogger:
  477. return &ethapi.ExecutionResult{
  478. Gas: gas,
  479. ReturnValue: fmt.Sprintf("%x", ret),
  480. StructLogs: ethapi.FormatLogs(tracer.StructLogs()),
  481. }, nil
  482. case *ethapi.JavascriptTracer:
  483. return tracer.GetResult()
  484. default:
  485. panic(fmt.Sprintf("bad tracer type %T", tracer))
  486. }
  487. }
  488. // computeTxEnv returns the execution environment of a certain transaction.
  489. func (api *PrivateDebugAPI) computeTxEnv(blockHash common.Hash, txIndex int) (core.Message, vm.Context, *state.StateDB, error) {
  490. // Create the parent state.
  491. block := api.eth.BlockChain().GetBlockByHash(blockHash)
  492. if block == nil {
  493. return nil, vm.Context{}, nil, fmt.Errorf("block %x not found", blockHash)
  494. }
  495. parent := api.eth.BlockChain().GetBlock(block.ParentHash(), block.NumberU64()-1)
  496. if parent == nil {
  497. return nil, vm.Context{}, nil, fmt.Errorf("block parent %x not found", block.ParentHash())
  498. }
  499. statedb, err := api.eth.BlockChain().StateAt(parent.Root())
  500. if err != nil {
  501. return nil, vm.Context{}, nil, err
  502. }
  503. txs := block.Transactions()
  504. // Recompute transactions up to the target index.
  505. signer := types.MakeSigner(api.config, block.Number())
  506. for idx, tx := range txs {
  507. // Assemble the transaction call message
  508. msg, _ := tx.AsMessage(signer)
  509. context := core.NewEVMContext(msg, block.Header(), api.eth.BlockChain(), nil)
  510. if idx == txIndex {
  511. return msg, context, statedb, nil
  512. }
  513. vmenv := vm.NewEVM(context, statedb, api.config, vm.Config{})
  514. gp := new(core.GasPool).AddGas(tx.Gas())
  515. _, _, err := core.ApplyMessage(vmenv, msg, gp)
  516. if err != nil {
  517. return nil, vm.Context{}, nil, fmt.Errorf("tx %x failed: %v", tx.Hash(), err)
  518. }
  519. statedb.DeleteSuicides()
  520. }
  521. return nil, vm.Context{}, nil, fmt.Errorf("tx index %d out of range for block %x", txIndex, blockHash)
  522. }
  523. // Preimage is a debug API function that returns the preimage for a sha3 hash, if known.
  524. func (api *PrivateDebugAPI) Preimage(ctx context.Context, hash common.Hash) (hexutil.Bytes, error) {
  525. db := core.PreimageTable(api.eth.ChainDb())
  526. return db.Get(hash.Bytes())
  527. }
  528. // GetBadBLocks returns a list of the last 'bad blocks' that the client has seen on the network
  529. // and returns them as a JSON list of block-hashes
  530. func (api *PrivateDebugAPI) GetBadBlocks(ctx context.Context) ([]core.BadBlockArgs, error) {
  531. return api.eth.BlockChain().BadBlocks()
  532. }
  533. // StorageRangeResult is the result of a debug_storageRangeAt API call.
  534. type StorageRangeResult struct {
  535. Storage storageMap `json:"storage"`
  536. NextKey *common.Hash `json:"nextKey"` // nil if Storage includes the last key in the trie.
  537. }
  538. type storageMap map[common.Hash]storageEntry
  539. type storageEntry struct {
  540. Key *common.Hash `json:"key"`
  541. Value common.Hash `json:"value"`
  542. }
  543. // StorageRangeAt returns the storage at the given block height and transaction index.
  544. func (api *PrivateDebugAPI) StorageRangeAt(ctx context.Context, blockHash common.Hash, txIndex int, contractAddress common.Address, keyStart hexutil.Bytes, maxResult int) (StorageRangeResult, error) {
  545. _, _, statedb, err := api.computeTxEnv(blockHash, txIndex)
  546. if err != nil {
  547. return StorageRangeResult{}, err
  548. }
  549. st := statedb.StorageTrie(contractAddress)
  550. if st == nil {
  551. return StorageRangeResult{}, fmt.Errorf("account %x doesn't exist", contractAddress)
  552. }
  553. return storageRangeAt(st, keyStart, maxResult), nil
  554. }
  555. func storageRangeAt(st *trie.SecureTrie, start []byte, maxResult int) StorageRangeResult {
  556. it := trie.NewIterator(st.NodeIterator(start))
  557. result := StorageRangeResult{Storage: storageMap{}}
  558. for i := 0; i < maxResult && it.Next(); i++ {
  559. e := storageEntry{Value: common.BytesToHash(it.Value)}
  560. if preimage := st.GetKey(it.Key); preimage != nil {
  561. preimage := common.BytesToHash(preimage)
  562. e.Key = &preimage
  563. }
  564. result.Storage[common.BytesToHash(it.Key)] = e
  565. }
  566. // Add the 'next key' so clients can continue downloading.
  567. if it.Next() {
  568. next := common.BytesToHash(it.Key)
  569. result.NextKey = &next
  570. }
  571. return result
  572. }