github.com/Unheilbar/quorum@v1.0.0/eth/api.go (about)

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