api.go 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725
  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 Ethereum 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 Ethereum 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(), b.NumberU64()) {
  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 Ethereum 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 Ethereum 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. // formatError formats a Go error into either an empty string or the data content
  411. // of the error itself.
  412. func formatError(err error) string {
  413. if err == nil {
  414. return ""
  415. }
  416. return err.Error()
  417. }
  418. type timeoutError struct{}
  419. func (t *timeoutError) Error() string {
  420. return "Execution time exceeded"
  421. }
  422. // TraceTransaction returns the structured logs created during the execution of EVM
  423. // and returns them as a JSON object.
  424. func (api *PrivateDebugAPI) TraceTransaction(ctx context.Context, txHash common.Hash, config *TraceArgs) (interface{}, error) {
  425. var tracer vm.Tracer
  426. if config != nil && config.Tracer != nil {
  427. timeout := defaultTraceTimeout
  428. if config.Timeout != nil {
  429. var err error
  430. if timeout, err = time.ParseDuration(*config.Timeout); err != nil {
  431. return nil, err
  432. }
  433. }
  434. var err error
  435. if tracer, err = ethapi.NewJavascriptTracer(*config.Tracer); err != nil {
  436. return nil, err
  437. }
  438. // Handle timeouts and RPC cancellations
  439. deadlineCtx, cancel := context.WithTimeout(ctx, timeout)
  440. go func() {
  441. <-deadlineCtx.Done()
  442. tracer.(*ethapi.JavascriptTracer).Stop(&timeoutError{})
  443. }()
  444. defer cancel()
  445. } else if config == nil {
  446. tracer = vm.NewStructLogger(nil)
  447. } else {
  448. tracer = vm.NewStructLogger(config.LogConfig)
  449. }
  450. // Retrieve the tx from the chain and the containing block
  451. tx, blockHash, _, txIndex := core.GetTransaction(api.eth.ChainDb(), txHash)
  452. if tx == nil {
  453. return nil, fmt.Errorf("transaction %x not found", txHash)
  454. }
  455. msg, context, statedb, err := api.computeTxEnv(blockHash, int(txIndex))
  456. if err != nil {
  457. return nil, err
  458. }
  459. // Run the transaction with tracing enabled.
  460. vmenv := vm.NewEVM(context, statedb, api.config, vm.Config{Debug: true, Tracer: tracer})
  461. ret, gas, failed, err := core.ApplyMessage(vmenv, msg, new(core.GasPool).AddGas(tx.Gas()))
  462. if err != nil {
  463. return nil, fmt.Errorf("tracing failed: %v", err)
  464. }
  465. switch tracer := tracer.(type) {
  466. case *vm.StructLogger:
  467. return &ethapi.ExecutionResult{
  468. Gas: gas,
  469. Failed: failed,
  470. ReturnValue: fmt.Sprintf("%x", ret),
  471. StructLogs: ethapi.FormatLogs(tracer.StructLogs()),
  472. }, nil
  473. case *ethapi.JavascriptTracer:
  474. return tracer.GetResult()
  475. default:
  476. panic(fmt.Sprintf("bad tracer type %T", tracer))
  477. }
  478. }
  479. // computeTxEnv returns the execution environment of a certain transaction.
  480. func (api *PrivateDebugAPI) computeTxEnv(blockHash common.Hash, txIndex int) (core.Message, vm.Context, *state.StateDB, error) {
  481. // Create the parent state.
  482. block := api.eth.BlockChain().GetBlockByHash(blockHash)
  483. if block == nil {
  484. return nil, vm.Context{}, nil, fmt.Errorf("block %x not found", blockHash)
  485. }
  486. parent := api.eth.BlockChain().GetBlock(block.ParentHash(), block.NumberU64()-1)
  487. if parent == nil {
  488. return nil, vm.Context{}, nil, fmt.Errorf("block parent %x not found", block.ParentHash())
  489. }
  490. statedb, err := api.eth.BlockChain().StateAt(parent.Root())
  491. if err != nil {
  492. return nil, vm.Context{}, nil, err
  493. }
  494. txs := block.Transactions()
  495. // Recompute transactions up to the target index.
  496. signer := types.MakeSigner(api.config, block.Number())
  497. for idx, tx := range txs {
  498. // Assemble the transaction call message
  499. msg, _ := tx.AsMessage(signer)
  500. context := core.NewEVMContext(msg, block.Header(), api.eth.BlockChain(), nil)
  501. if idx == txIndex {
  502. return msg, context, statedb, nil
  503. }
  504. vmenv := vm.NewEVM(context, statedb, api.config, vm.Config{})
  505. gp := new(core.GasPool).AddGas(tx.Gas())
  506. _, _, _, err := core.ApplyMessage(vmenv, msg, gp)
  507. if err != nil {
  508. return nil, vm.Context{}, nil, fmt.Errorf("tx %x failed: %v", tx.Hash(), err)
  509. }
  510. statedb.DeleteSuicides()
  511. }
  512. return nil, vm.Context{}, nil, fmt.Errorf("tx index %d out of range for block %x", txIndex, blockHash)
  513. }
  514. // Preimage is a debug API function that returns the preimage for a sha3 hash, if known.
  515. func (api *PrivateDebugAPI) Preimage(ctx context.Context, hash common.Hash) (hexutil.Bytes, error) {
  516. db := core.PreimageTable(api.eth.ChainDb())
  517. return db.Get(hash.Bytes())
  518. }
  519. // GetBadBLocks returns a list of the last 'bad blocks' that the client has seen on the network
  520. // and returns them as a JSON list of block-hashes
  521. func (api *PrivateDebugAPI) GetBadBlocks(ctx context.Context) ([]core.BadBlockArgs, error) {
  522. return api.eth.BlockChain().BadBlocks()
  523. }
  524. // StorageRangeResult is the result of a debug_storageRangeAt API call.
  525. type StorageRangeResult struct {
  526. Storage storageMap `json:"storage"`
  527. NextKey *common.Hash `json:"nextKey"` // nil if Storage includes the last key in the trie.
  528. }
  529. type storageMap map[common.Hash]storageEntry
  530. type storageEntry struct {
  531. Key *common.Hash `json:"key"`
  532. Value common.Hash `json:"value"`
  533. }
  534. // StorageRangeAt returns the storage at the given block height and transaction index.
  535. func (api *PrivateDebugAPI) StorageRangeAt(ctx context.Context, blockHash common.Hash, txIndex int, contractAddress common.Address, keyStart hexutil.Bytes, maxResult int) (StorageRangeResult, error) {
  536. _, _, statedb, err := api.computeTxEnv(blockHash, txIndex)
  537. if err != nil {
  538. return StorageRangeResult{}, err
  539. }
  540. st := statedb.StorageTrie(contractAddress)
  541. if st == nil {
  542. return StorageRangeResult{}, fmt.Errorf("account %x doesn't exist", contractAddress)
  543. }
  544. return storageRangeAt(st, keyStart, maxResult)
  545. }
  546. func storageRangeAt(st state.Trie, start []byte, maxResult int) (StorageRangeResult, error) {
  547. it := trie.NewIterator(st.NodeIterator(start))
  548. result := StorageRangeResult{Storage: storageMap{}}
  549. for i := 0; i < maxResult && it.Next(); i++ {
  550. _, content, _, err := rlp.Split(it.Value)
  551. if err != nil {
  552. return StorageRangeResult{}, err
  553. }
  554. e := storageEntry{Value: common.BytesToHash(content)}
  555. if preimage := st.GetKey(it.Key); preimage != nil {
  556. preimage := common.BytesToHash(preimage)
  557. e.Key = &preimage
  558. }
  559. result.Storage[common.BytesToHash(it.Key)] = e
  560. }
  561. // Add the 'next key' so clients can continue downloading.
  562. if it.Next() {
  563. next := common.BytesToHash(it.Key)
  564. result.NextKey = &next
  565. }
  566. return result, nil
  567. }
  568. // GetModifiedAccountsByumber returns all accounts that have changed between the
  569. // two blocks specified. A change is defined as a difference in nonce, balance,
  570. // code hash, or storage hash.
  571. //
  572. // With one parameter, returns the list of accounts modified in the specified block.
  573. func (api *PrivateDebugAPI) GetModifiedAccountsByNumber(startNum uint64, endNum *uint64) ([]common.Address, error) {
  574. var startBlock, endBlock *types.Block
  575. startBlock = api.eth.blockchain.GetBlockByNumber(startNum)
  576. if startBlock == nil {
  577. return nil, fmt.Errorf("start block %x not found", startNum)
  578. }
  579. if endNum == nil {
  580. endBlock = startBlock
  581. startBlock = api.eth.blockchain.GetBlockByHash(startBlock.ParentHash())
  582. if startBlock == nil {
  583. return nil, fmt.Errorf("block %x has no parent", endBlock.Number())
  584. }
  585. } else {
  586. endBlock = api.eth.blockchain.GetBlockByNumber(*endNum)
  587. if endBlock == nil {
  588. return nil, fmt.Errorf("end block %d not found", *endNum)
  589. }
  590. }
  591. return api.getModifiedAccounts(startBlock, endBlock)
  592. }
  593. // GetModifiedAccountsByHash returns all accounts that have changed between the
  594. // two blocks specified. A change is defined as a difference in nonce, balance,
  595. // code hash, or storage hash.
  596. //
  597. // With one parameter, returns the list of accounts modified in the specified block.
  598. func (api *PrivateDebugAPI) GetModifiedAccountsByHash(startHash common.Hash, endHash *common.Hash) ([]common.Address, error) {
  599. var startBlock, endBlock *types.Block
  600. startBlock = api.eth.blockchain.GetBlockByHash(startHash)
  601. if startBlock == nil {
  602. return nil, fmt.Errorf("start block %x not found", startHash)
  603. }
  604. if endHash == nil {
  605. endBlock = startBlock
  606. startBlock = api.eth.blockchain.GetBlockByHash(startBlock.ParentHash())
  607. if startBlock == nil {
  608. return nil, fmt.Errorf("block %x has no parent", endBlock.Number())
  609. }
  610. } else {
  611. endBlock = api.eth.blockchain.GetBlockByHash(*endHash)
  612. if endBlock == nil {
  613. return nil, fmt.Errorf("end block %x not found", *endHash)
  614. }
  615. }
  616. return api.getModifiedAccounts(startBlock, endBlock)
  617. }
  618. func (api *PrivateDebugAPI) getModifiedAccounts(startBlock, endBlock *types.Block) ([]common.Address, error) {
  619. if startBlock.Number().Uint64() >= endBlock.Number().Uint64() {
  620. return nil, fmt.Errorf("start block height (%d) must be less than end block height (%d)", startBlock.Number().Uint64(), endBlock.Number().Uint64())
  621. }
  622. oldTrie, err := trie.NewSecure(startBlock.Root(), api.eth.chainDb, 0)
  623. if err != nil {
  624. return nil, err
  625. }
  626. newTrie, err := trie.NewSecure(endBlock.Root(), api.eth.chainDb, 0)
  627. if err != nil {
  628. return nil, err
  629. }
  630. diff, _ := trie.NewDifferenceIterator(oldTrie.NodeIterator([]byte{}), newTrie.NodeIterator([]byte{}))
  631. iter := trie.NewIterator(diff)
  632. var dirty []common.Address
  633. for iter.Next() {
  634. key := newTrie.GetKey(iter.Key)
  635. if key == nil {
  636. return nil, fmt.Errorf("no preimage found for hash %x", iter.Key)
  637. }
  638. dirty = append(dirty, common.BytesToAddress(key))
  639. }
  640. return dirty, nil
  641. }