api.go 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640
  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. "compress/gzip"
  19. "context"
  20. "errors"
  21. "fmt"
  22. "io"
  23. "math/big"
  24. "os"
  25. "runtime"
  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/rawdb"
  32. "github.com/ethereum/go-ethereum/core/state"
  33. "github.com/ethereum/go-ethereum/core/types"
  34. "github.com/ethereum/go-ethereum/internal/ethapi"
  35. "github.com/ethereum/go-ethereum/rlp"
  36. "github.com/ethereum/go-ethereum/rpc"
  37. "github.com/ethereum/go-ethereum/trie"
  38. )
  39. // PublicEthereumAPI provides an API to access Ethereum full node-related
  40. // information.
  41. type PublicEthereumAPI struct {
  42. e *Ethereum
  43. }
  44. // NewPublicEthereumAPI creates a new Ethereum protocol API for full nodes.
  45. func NewPublicEthereumAPI(e *Ethereum) *PublicEthereumAPI {
  46. return &PublicEthereumAPI{e}
  47. }
  48. // Etherbase is the address that mining rewards will be send to
  49. func (api *PublicEthereumAPI) Etherbase() (common.Address, error) {
  50. return api.e.Etherbase()
  51. }
  52. // Coinbase is the address that mining rewards will be send to (alias for Etherbase)
  53. func (api *PublicEthereumAPI) Coinbase() (common.Address, error) {
  54. return api.Etherbase()
  55. }
  56. // Hashrate returns the POW hashrate
  57. func (api *PublicEthereumAPI) Hashrate() hexutil.Uint64 {
  58. return hexutil.Uint64(api.e.Miner().Hashrate())
  59. }
  60. // PublicMinerAPI provides an API to control the miner.
  61. // It offers only methods that operate on data that pose no security risk when it is publicly accessible.
  62. type PublicMinerAPI struct {
  63. e *Ethereum
  64. }
  65. // NewPublicMinerAPI create a new PublicMinerAPI instance.
  66. func NewPublicMinerAPI(e *Ethereum) *PublicMinerAPI {
  67. return &PublicMinerAPI{e}
  68. }
  69. // Mining returns an indication if this node is currently mining.
  70. func (api *PublicMinerAPI) Mining() bool {
  71. return api.e.IsMining()
  72. }
  73. // PrivateMinerAPI provides private RPC methods to control the miner.
  74. // These methods can be abused by external users and must be considered insecure for use by untrusted users.
  75. type PrivateMinerAPI struct {
  76. e *Ethereum
  77. }
  78. // NewPrivateMinerAPI create a new RPC service which controls the miner of this node.
  79. func NewPrivateMinerAPI(e *Ethereum) *PrivateMinerAPI {
  80. return &PrivateMinerAPI{e: e}
  81. }
  82. // Start starts the miner with the given number of threads. If threads is nil,
  83. // the number of workers started is equal to the number of logical CPUs that are
  84. // usable by this process. If mining is already running, this method adjust the
  85. // number of threads allowed to use and updates the minimum price required by the
  86. // transaction pool.
  87. func (api *PrivateMinerAPI) Start(threads *int) error {
  88. if threads == nil {
  89. return api.e.StartMining(runtime.NumCPU())
  90. }
  91. return api.e.StartMining(*threads)
  92. }
  93. // Stop terminates the miner, both at the consensus engine level as well as at
  94. // the block creation level.
  95. func (api *PrivateMinerAPI) Stop() {
  96. api.e.StopMining()
  97. }
  98. // SetExtra sets the extra data string that is included when this miner mines a block.
  99. func (api *PrivateMinerAPI) SetExtra(extra string) (bool, error) {
  100. if err := api.e.Miner().SetExtra([]byte(extra)); err != nil {
  101. return false, err
  102. }
  103. return true, nil
  104. }
  105. // SetGasPrice sets the minimum accepted gas price for the miner.
  106. func (api *PrivateMinerAPI) SetGasPrice(gasPrice hexutil.Big) bool {
  107. api.e.lock.Lock()
  108. api.e.gasPrice = (*big.Int)(&gasPrice)
  109. api.e.lock.Unlock()
  110. api.e.txPool.SetGasPrice((*big.Int)(&gasPrice))
  111. return true
  112. }
  113. // SetEtherbase sets the etherbase of the miner
  114. func (api *PrivateMinerAPI) SetEtherbase(etherbase common.Address) bool {
  115. // Quorum: Set return value, so user can be notified if it is disallowed.
  116. return api.e.SetEtherbase(etherbase)
  117. }
  118. // SetRecommitInterval updates the interval for miner sealing work recommitting.
  119. func (api *PrivateMinerAPI) SetRecommitInterval(interval int) {
  120. api.e.Miner().SetRecommitInterval(time.Duration(interval) * time.Millisecond)
  121. }
  122. // PrivateAdminAPI is the collection of Ethereum full node-related APIs
  123. // exposed over the private admin endpoint.
  124. type PrivateAdminAPI struct {
  125. eth *Ethereum
  126. }
  127. // NewPrivateAdminAPI creates a new API definition for the full node private
  128. // admin methods of the Ethereum service.
  129. func NewPrivateAdminAPI(eth *Ethereum) *PrivateAdminAPI {
  130. return &PrivateAdminAPI{eth: eth}
  131. }
  132. // ExportChain exports the current blockchain into a local file,
  133. // or a range of blocks if first and last are non-nil
  134. func (api *PrivateAdminAPI) ExportChain(file string, first *uint64, last *uint64) (bool, error) {
  135. if first == nil && last != nil {
  136. return false, errors.New("last cannot be specified without first")
  137. }
  138. if first != nil && last == nil {
  139. head := api.eth.BlockChain().CurrentHeader().Number.Uint64()
  140. last = &head
  141. }
  142. if _, err := os.Stat(file); err == nil {
  143. // File already exists. Allowing overwrite could be a DoS vecotor,
  144. // since the 'file' may point to arbitrary paths on the drive
  145. return false, errors.New("location would overwrite an existing file")
  146. }
  147. // Make sure we can create the file to export into
  148. out, err := os.OpenFile(file, os.O_CREATE|os.O_WRONLY|os.O_TRUNC, os.ModePerm)
  149. if err != nil {
  150. return false, err
  151. }
  152. defer out.Close()
  153. var writer io.Writer = out
  154. if strings.HasSuffix(file, ".gz") {
  155. writer = gzip.NewWriter(writer)
  156. defer writer.(*gzip.Writer).Close()
  157. }
  158. // Export the blockchain
  159. if first != nil {
  160. if err := api.eth.BlockChain().ExportN(writer, *first, *last); err != nil {
  161. return false, err
  162. }
  163. } else if err := api.eth.BlockChain().Export(writer); err != nil {
  164. return false, err
  165. }
  166. return true, nil
  167. }
  168. func hasAllBlocks(chain *core.BlockChain, bs []*types.Block) bool {
  169. for _, b := range bs {
  170. if !chain.HasBlock(b.Hash(), b.NumberU64()) {
  171. return false
  172. }
  173. }
  174. return true
  175. }
  176. // ImportChain imports a blockchain from a local file.
  177. func (api *PrivateAdminAPI) ImportChain(file string) (bool, error) {
  178. // Make sure the can access the file to import
  179. in, err := os.Open(file)
  180. if err != nil {
  181. return false, err
  182. }
  183. defer in.Close()
  184. var reader io.Reader = in
  185. if strings.HasSuffix(file, ".gz") {
  186. if reader, err = gzip.NewReader(reader); err != nil {
  187. return false, err
  188. }
  189. }
  190. // Run actual the import in pre-configured batches
  191. stream := rlp.NewStream(reader, 0)
  192. blocks, index := make([]*types.Block, 0, 2500), 0
  193. for batch := 0; ; batch++ {
  194. // Load a batch of blocks from the input file
  195. for len(blocks) < cap(blocks) {
  196. block := new(types.Block)
  197. if err := stream.Decode(block); err == io.EOF {
  198. break
  199. } else if err != nil {
  200. return false, fmt.Errorf("block %d: failed to parse: %v", index, err)
  201. }
  202. blocks = append(blocks, block)
  203. index++
  204. }
  205. if len(blocks) == 0 {
  206. break
  207. }
  208. if hasAllBlocks(api.eth.BlockChain(), blocks) {
  209. blocks = blocks[:0]
  210. continue
  211. }
  212. // Import the batch and reset the buffer
  213. if _, err := api.eth.BlockChain().InsertChain(blocks); err != nil {
  214. return false, fmt.Errorf("batch %d: failed to insert: %v", batch, err)
  215. }
  216. blocks = blocks[:0]
  217. }
  218. return true, nil
  219. }
  220. // PublicDebugAPI is the collection of Ethereum full node APIs exposed
  221. // over the public debugging endpoint.
  222. type PublicDebugAPI struct {
  223. eth *Ethereum
  224. }
  225. // NewPublicDebugAPI creates a new API definition for the full node-
  226. // related public debug methods of the Ethereum service.
  227. func NewPublicDebugAPI(eth *Ethereum) *PublicDebugAPI {
  228. return &PublicDebugAPI{eth: eth}
  229. }
  230. // DumpBlock retrieves the entire state of the database at a given block.
  231. // Quorum adds an additional parameter to support private state dump
  232. func (api *PublicDebugAPI) DumpBlock(ctx context.Context, blockNr rpc.BlockNumber, typ *string) (state.Dump, error) {
  233. publicState, privateState, err := api.getStateDbsFromBlockNumber(ctx, blockNr)
  234. if err != nil {
  235. return state.Dump{}, err
  236. }
  237. if typ != nil && *typ == "private" {
  238. return privateState.RawDump(false, false, true), nil
  239. }
  240. return publicState.RawDump(false, false, true), nil
  241. }
  242. func (api *PublicDebugAPI) PrivateStateRoot(ctx context.Context, blockNr rpc.BlockNumber) (common.Hash, error) {
  243. _, privateState, err := api.getStateDbsFromBlockNumber(ctx, blockNr)
  244. if err != nil {
  245. return common.Hash{}, err
  246. }
  247. return privateState.IntermediateRoot(true), nil
  248. }
  249. func (api *PublicDebugAPI) DefaultStateRoot(ctx context.Context, blockNr rpc.BlockNumber) (common.Hash, error) {
  250. psm, err := api.eth.blockchain.PrivateStateManager().StateRepository(api.eth.blockchain.CurrentBlock().Hash())
  251. if err != nil {
  252. return common.Hash{}, err
  253. }
  254. defaultPSM := psm.DefaultStateMetadata()
  255. var privateState *state.StateDB
  256. if blockNr == rpc.PendingBlockNumber {
  257. // If we're dumping the pending state, we need to request
  258. // both the pending block as well as the pending state from
  259. // the miner and operate on those
  260. _, _, privateState = api.eth.miner.Pending(defaultPSM.ID)
  261. // this is a copy of the private state so it is OK to do IntermediateRoot
  262. return privateState.IntermediateRoot(true), nil
  263. }
  264. var block *types.Block
  265. if blockNr == rpc.LatestBlockNumber {
  266. block = api.eth.blockchain.CurrentBlock()
  267. } else {
  268. block = api.eth.blockchain.GetBlockByNumber(uint64(blockNr))
  269. }
  270. if block == nil {
  271. return common.Hash{}, fmt.Errorf("block #%d not found", blockNr)
  272. }
  273. _, privateState, err = api.eth.BlockChain().StateAtPSI(block.Root(), defaultPSM.ID)
  274. if err != nil {
  275. return common.Hash{}, err
  276. }
  277. return privateState.IntermediateRoot(true), nil
  278. }
  279. // PrivateDebugAPI is the collection of Ethereum full node APIs exposed over
  280. // the private debugging endpoint.
  281. type PrivateDebugAPI struct {
  282. eth *Ethereum
  283. }
  284. // NewPrivateDebugAPI creates a new API definition for the full node-related
  285. // private debug methods of the Ethereum service.
  286. func NewPrivateDebugAPI(eth *Ethereum) *PrivateDebugAPI {
  287. return &PrivateDebugAPI{eth: eth}
  288. }
  289. // Preimage is a debug API function that returns the preimage for a sha3 hash, if known.
  290. func (api *PrivateDebugAPI) Preimage(ctx context.Context, hash common.Hash) (hexutil.Bytes, error) {
  291. if preimage := rawdb.ReadPreimage(api.eth.ChainDb(), hash); preimage != nil {
  292. return preimage, nil
  293. }
  294. return nil, errors.New("unknown preimage")
  295. }
  296. // BadBlockArgs represents the entries in the list returned when bad blocks are queried.
  297. type BadBlockArgs struct {
  298. Hash common.Hash `json:"hash"`
  299. Block map[string]interface{} `json:"block"`
  300. RLP string `json:"rlp"`
  301. }
  302. // GetBadBlocks returns a list of the last 'bad blocks' that the client has seen on the network
  303. // and returns them as a JSON list of block-hashes
  304. func (api *PrivateDebugAPI) GetBadBlocks(ctx context.Context) ([]*BadBlockArgs, error) {
  305. var (
  306. err error
  307. blocks = rawdb.ReadAllBadBlocks(api.eth.chainDb)
  308. results = make([]*BadBlockArgs, 0, len(blocks))
  309. )
  310. for _, block := range blocks {
  311. var (
  312. blockRlp string
  313. blockJSON map[string]interface{}
  314. )
  315. if rlpBytes, err := rlp.EncodeToBytes(block); err != nil {
  316. blockRlp = err.Error() // Hacky, but hey, it works
  317. } else {
  318. blockRlp = fmt.Sprintf("0x%x", rlpBytes)
  319. }
  320. if blockJSON, err = ethapi.RPCMarshalBlock(block, true, true); err != nil {
  321. blockJSON = map[string]interface{}{"error": err.Error()}
  322. }
  323. results = append(results, &BadBlockArgs{
  324. Hash: block.Hash(),
  325. RLP: blockRlp,
  326. Block: blockJSON,
  327. })
  328. }
  329. return results, nil
  330. }
  331. // AccountRangeMaxResults is the maximum number of results to be returned per call
  332. const AccountRangeMaxResults = 256
  333. // AccountRange enumerates all accounts in the given block and start point in paging request
  334. func (api *PublicDebugAPI) AccountRange(ctx context.Context, blockNrOrHash rpc.BlockNumberOrHash, start []byte, maxResults int, nocode, nostorage, incompletes bool) (state.IteratorDump, error) {
  335. psm, err := api.eth.blockchain.PrivateStateManager().ResolveForUserContext(ctx)
  336. if err != nil {
  337. return state.IteratorDump{}, err
  338. }
  339. var stateDb *state.StateDB
  340. if number, ok := blockNrOrHash.Number(); ok {
  341. if number == rpc.PendingBlockNumber {
  342. // If we're dumping the pending state, we need to request
  343. // both the pending block as well as the pending state from
  344. // the miner and operate on those
  345. _, stateDb, _ = api.eth.miner.Pending(psm.ID)
  346. } else {
  347. var block *types.Block
  348. if number == rpc.LatestBlockNumber {
  349. block = api.eth.blockchain.CurrentBlock()
  350. } else {
  351. block = api.eth.blockchain.GetBlockByNumber(uint64(number))
  352. }
  353. if block == nil {
  354. return state.IteratorDump{}, fmt.Errorf("block #%d not found", number)
  355. }
  356. stateDb, _, err = api.eth.BlockChain().StateAtPSI(block.Root(), psm.ID)
  357. if err != nil {
  358. return state.IteratorDump{}, err
  359. }
  360. }
  361. } else if hash, ok := blockNrOrHash.Hash(); ok {
  362. block := api.eth.blockchain.GetBlockByHash(hash)
  363. if block == nil {
  364. return state.IteratorDump{}, fmt.Errorf("block %s not found", hash.Hex())
  365. }
  366. stateDb, _, err = api.eth.BlockChain().StateAtPSI(block.Root(), psm.ID)
  367. if err != nil {
  368. return state.IteratorDump{}, err
  369. }
  370. } else {
  371. return state.IteratorDump{}, errors.New("either block number or block hash must be specified")
  372. }
  373. if maxResults > AccountRangeMaxResults || maxResults <= 0 {
  374. maxResults = AccountRangeMaxResults
  375. }
  376. return stateDb.IteratorDump(nocode, nostorage, incompletes, start, maxResults), nil
  377. }
  378. // StorageRangeResult is the result of a debug_storageRangeAt API call.
  379. type StorageRangeResult struct {
  380. Storage storageMap `json:"storage"`
  381. NextKey *common.Hash `json:"nextKey"` // nil if Storage includes the last key in the trie.
  382. }
  383. type storageMap map[common.Hash]storageEntry
  384. type storageEntry struct {
  385. Key *common.Hash `json:"key"`
  386. Value common.Hash `json:"value"`
  387. }
  388. // StorageRangeAt returns the storage at the given block height and transaction index.
  389. func (api *PrivateDebugAPI) StorageRangeAt(ctx context.Context, blockHash common.Hash, txIndex int, contractAddress common.Address, keyStart hexutil.Bytes, maxResult int) (StorageRangeResult, error) {
  390. // Retrieve the block
  391. block := api.eth.blockchain.GetBlockByHash(blockHash)
  392. if block == nil {
  393. return StorageRangeResult{}, fmt.Errorf("block %#x not found", blockHash)
  394. }
  395. _, _, statedb, _, _, err := api.eth.stateAtTransaction(ctx, block, txIndex, 0)
  396. if err != nil {
  397. return StorageRangeResult{}, err
  398. }
  399. st := statedb.StorageTrie(contractAddress)
  400. if st == nil {
  401. return StorageRangeResult{}, fmt.Errorf("account %x doesn't exist", contractAddress)
  402. }
  403. return storageRangeAt(st, keyStart, maxResult)
  404. }
  405. func storageRangeAt(st state.Trie, start []byte, maxResult int) (StorageRangeResult, error) {
  406. it := trie.NewIterator(st.NodeIterator(start))
  407. result := StorageRangeResult{Storage: storageMap{}}
  408. for i := 0; i < maxResult && it.Next(); i++ {
  409. _, content, _, err := rlp.Split(it.Value)
  410. if err != nil {
  411. return StorageRangeResult{}, err
  412. }
  413. e := storageEntry{Value: common.BytesToHash(content)}
  414. if preimage := st.GetKey(it.Key); preimage != nil {
  415. preimage := common.BytesToHash(preimage)
  416. e.Key = &preimage
  417. }
  418. result.Storage[common.BytesToHash(it.Key)] = e
  419. }
  420. // Add the 'next key' so clients can continue downloading.
  421. if it.Next() {
  422. next := common.BytesToHash(it.Key)
  423. result.NextKey = &next
  424. }
  425. return result, nil
  426. }
  427. // GetModifiedAccountsByNumber returns all accounts that have changed between the
  428. // two blocks specified. A change is defined as a difference in nonce, balance,
  429. // code hash, or storage hash.
  430. //
  431. // With one parameter, returns the list of accounts modified in the specified block.
  432. func (api *PrivateDebugAPI) GetModifiedAccountsByNumber(startNum uint64, endNum *uint64) ([]common.Address, error) {
  433. var startBlock, endBlock *types.Block
  434. startBlock = api.eth.blockchain.GetBlockByNumber(startNum)
  435. if startBlock == nil {
  436. return nil, fmt.Errorf("start block %x not found", startNum)
  437. }
  438. if endNum == nil {
  439. endBlock = startBlock
  440. startBlock = api.eth.blockchain.GetBlockByHash(startBlock.ParentHash())
  441. if startBlock == nil {
  442. return nil, fmt.Errorf("block %x has no parent", endBlock.Number())
  443. }
  444. } else {
  445. endBlock = api.eth.blockchain.GetBlockByNumber(*endNum)
  446. if endBlock == nil {
  447. return nil, fmt.Errorf("end block %d not found", *endNum)
  448. }
  449. }
  450. return api.getModifiedAccounts(startBlock, endBlock)
  451. }
  452. // GetModifiedAccountsByHash returns all accounts that have changed between the
  453. // two blocks specified. A change is defined as a difference in nonce, balance,
  454. // code hash, or storage hash.
  455. //
  456. // With one parameter, returns the list of accounts modified in the specified block.
  457. func (api *PrivateDebugAPI) GetModifiedAccountsByHash(startHash common.Hash, endHash *common.Hash) ([]common.Address, error) {
  458. var startBlock, endBlock *types.Block
  459. startBlock = api.eth.blockchain.GetBlockByHash(startHash)
  460. if startBlock == nil {
  461. return nil, fmt.Errorf("start block %x not found", startHash)
  462. }
  463. if endHash == nil {
  464. endBlock = startBlock
  465. startBlock = api.eth.blockchain.GetBlockByHash(startBlock.ParentHash())
  466. if startBlock == nil {
  467. return nil, fmt.Errorf("block %x has no parent", endBlock.Number())
  468. }
  469. } else {
  470. endBlock = api.eth.blockchain.GetBlockByHash(*endHash)
  471. if endBlock == nil {
  472. return nil, fmt.Errorf("end block %x not found", *endHash)
  473. }
  474. }
  475. return api.getModifiedAccounts(startBlock, endBlock)
  476. }
  477. func (api *PrivateDebugAPI) getModifiedAccounts(startBlock, endBlock *types.Block) ([]common.Address, error) {
  478. if startBlock.Number().Uint64() >= endBlock.Number().Uint64() {
  479. return nil, fmt.Errorf("start block height (%d) must be less than end block height (%d)", startBlock.Number().Uint64(), endBlock.Number().Uint64())
  480. }
  481. triedb := api.eth.BlockChain().StateCache().TrieDB()
  482. oldTrie, err := trie.NewSecure(startBlock.Root(), triedb)
  483. if err != nil {
  484. return nil, err
  485. }
  486. newTrie, err := trie.NewSecure(endBlock.Root(), triedb)
  487. if err != nil {
  488. return nil, err
  489. }
  490. diff, _ := trie.NewDifferenceIterator(oldTrie.NodeIterator([]byte{}), newTrie.NodeIterator([]byte{}))
  491. iter := trie.NewIterator(diff)
  492. var dirty []common.Address
  493. for iter.Next() {
  494. key := newTrie.GetKey(iter.Key)
  495. if key == nil {
  496. return nil, fmt.Errorf("no preimage found for hash %x", iter.Key)
  497. }
  498. dirty = append(dirty, common.BytesToAddress(key))
  499. }
  500. return dirty, nil
  501. }
  502. // Quorum
  503. // StorageRoot returns the storage root of an account on the the given (optional) block height.
  504. // If block number is not given the latest block is used.
  505. func (s *PublicEthereumAPI) StorageRoot(ctx context.Context, addr common.Address, blockNr *rpc.BlockNumber) (common.Hash, error) {
  506. var (
  507. pub, priv *state.StateDB
  508. err error
  509. )
  510. psm, err := s.e.blockchain.PrivateStateManager().ResolveForUserContext(ctx)
  511. if err != nil {
  512. return common.Hash{}, err
  513. }
  514. if blockNr == nil || blockNr.Int64() == rpc.LatestBlockNumber.Int64() {
  515. pub, priv, err = s.e.blockchain.StatePSI(psm.ID)
  516. } else {
  517. if ch := s.e.blockchain.GetHeaderByNumber(uint64(blockNr.Int64())); ch != nil {
  518. pub, priv, err = s.e.blockchain.StateAtPSI(ch.Root, psm.ID)
  519. } else {
  520. return common.Hash{}, fmt.Errorf("invalid block number")
  521. }
  522. }
  523. if err != nil {
  524. return common.Hash{}, err
  525. }
  526. if priv.Exist(addr) {
  527. return priv.GetStorageRoot(addr)
  528. }
  529. return pub.GetStorageRoot(addr)
  530. }
  531. // DumpAddress retrieves the state of an address at a given block.
  532. // Quorum adds an additional parameter to support private state dump
  533. func (api *PublicDebugAPI) DumpAddress(ctx context.Context, address common.Address, blockNr rpc.BlockNumber) (state.DumpAccount, error) {
  534. publicState, privateState, err := api.getStateDbsFromBlockNumber(ctx, blockNr)
  535. if err != nil {
  536. return state.DumpAccount{}, err
  537. }
  538. if accountDump, ok := privateState.DumpAddress(address); ok {
  539. return accountDump, nil
  540. }
  541. if accountDump, ok := publicState.DumpAddress(address); ok {
  542. return accountDump, nil
  543. }
  544. return state.DumpAccount{}, errors.New("error retrieving state")
  545. }
  546. //Taken from DumpBlock, as it was reused in DumpAddress.
  547. //Contains modifications from the original to return the private state db, as well as public.
  548. func (api *PublicDebugAPI) getStateDbsFromBlockNumber(ctx context.Context, blockNr rpc.BlockNumber) (*state.StateDB, *state.StateDB, error) {
  549. psm, err := api.eth.blockchain.PrivateStateManager().ResolveForUserContext(ctx)
  550. if err != nil {
  551. return nil, nil, err
  552. }
  553. if blockNr == rpc.PendingBlockNumber {
  554. // If we're dumping the pending state, we need to request
  555. // both the pending block as well as the pending state from
  556. // the miner and operate on those
  557. _, publicState, privateState := api.eth.miner.Pending(psm.ID)
  558. return publicState, privateState, nil
  559. }
  560. var block *types.Block
  561. if blockNr == rpc.LatestBlockNumber {
  562. block = api.eth.blockchain.CurrentBlock()
  563. } else {
  564. block = api.eth.blockchain.GetBlockByNumber(uint64(blockNr))
  565. }
  566. if block == nil {
  567. return nil, nil, fmt.Errorf("block #%d not found", blockNr)
  568. }
  569. return api.eth.BlockChain().StateAtPSI(block.Root(), psm.ID)
  570. }