all: Remove concept of public/private API definitions #25053 (#1141)

This commit is contained in:
JukLee0ira 2025-06-24 15:15:25 +08:00 committed by GitHub
parent a74b87307c
commit 5ad950ea51
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
8 changed files with 256 additions and 315 deletions

View file

@ -40,55 +40,39 @@ import (
"github.com/XinFinOrg/XDPoSChain/trie" "github.com/XinFinOrg/XDPoSChain/trie"
) )
// PublicEthereumAPI provides an API to access Ethereum full node-related // EthereumAPI provides an API to access Ethereum full node-related information.
// information. type EthereumAPI struct {
type PublicEthereumAPI struct {
e *Ethereum e *Ethereum
} }
// NewPublicEthereumAPI creates a new Ethereum protocol API for full nodes. // NewPublicEthereumAPI creates a new Ethereum protocol API for full nodes.
func NewPublicEthereumAPI(e *Ethereum) *PublicEthereumAPI { func NewEthereumAPI(e *Ethereum) *EthereumAPI {
return &PublicEthereumAPI{e} return &EthereumAPI{e}
} }
// Etherbase is the address that mining rewards will be send to // Etherbase is the address that mining rewards will be send to
func (api *PublicEthereumAPI) Etherbase() (common.Address, error) { func (api *EthereumAPI) Etherbase() (common.Address, error) {
return api.e.Etherbase() return api.e.Etherbase()
} }
// Coinbase is the address that mining rewards will be send to (alias for Etherbase) // Coinbase is the address that mining rewards will be send to (alias for Etherbase)
func (api *PublicEthereumAPI) Coinbase() (common.Address, error) { func (api *EthereumAPI) Coinbase() (common.Address, error) {
return api.Etherbase() return api.Etherbase()
} }
// Hashrate returns the POW hashrate // Hashrate returns the POW hashrate
func (api *PublicEthereumAPI) Hashrate() hexutil.Uint64 { func (api *EthereumAPI) Hashrate() hexutil.Uint64 {
return hexutil.Uint64(api.e.Miner().HashRate()) return hexutil.Uint64(api.e.Miner().HashRate())
} }
// PublicMinerAPI provides an API to control the miner.
// It offers only methods that operate on data that pose no security risk when it is publicly accessible.
type PublicMinerAPI struct {
e *Ethereum
agent *miner.RemoteAgent
}
// NewPublicMinerAPI create a new PublicMinerAPI instance.
func NewPublicMinerAPI(e *Ethereum) *PublicMinerAPI {
agent := miner.NewRemoteAgent(e.BlockChain(), e.Engine())
e.Miner().Register(agent)
return &PublicMinerAPI{e, agent}
}
// Mining returns an indication if this node is currently mining. // Mining returns an indication if this node is currently mining.
func (api *PublicMinerAPI) Mining() bool { func (api *EthereumAPI) Mining() bool {
return api.e.IsStaking() return api.e.IsStaking()
} }
// SubmitWork can be used by external miner to submit their POW solution. It returns an indication if the work was // SubmitWork can be used by external miner to submit their POW solution. It returns an indication if the work was
// accepted. Note, this is not an indication if the provided work was valid! // accepted. Note, this is not an indication if the provided work was valid!
func (api *PublicMinerAPI) SubmitWork(nonce types.BlockNonce, solution, digest common.Hash) bool { func (api *MinerAPI) SubmitWork(nonce types.BlockNonce, solution, digest common.Hash) bool {
return api.agent.SubmitWork(nonce, digest, solution) return api.agent.SubmitWork(nonce, digest, solution)
} }
@ -96,7 +80,7 @@ func (api *PublicMinerAPI) SubmitWork(nonce types.BlockNonce, solution, digest c
// result[0], 32 bytes hex encoded current block header pow-hash // result[0], 32 bytes hex encoded current block header pow-hash
// result[1], 32 bytes hex encoded seed hash used for DAG // result[1], 32 bytes hex encoded seed hash used for DAG
// result[2], 32 bytes hex encoded boundary condition ("target"), 2^256/difficulty // result[2], 32 bytes hex encoded boundary condition ("target"), 2^256/difficulty
func (api *PublicMinerAPI) GetWork() ([3]string, error) { func (api *MinerAPI) GetWork() ([3]string, error) {
if !api.e.IsStaking() { if !api.e.IsStaking() {
if err := api.e.StartStaking(false); err != nil { if err := api.e.StartStaking(false); err != nil {
return [3]string{}, err return [3]string{}, err
@ -112,27 +96,29 @@ func (api *PublicMinerAPI) GetWork() ([3]string, error) {
// SubmitHashrate can be used for remote miners to submit their hash rate. This enables the node to report the combined // SubmitHashrate can be used for remote miners to submit their hash rate. This enables the node to report the combined
// hash rate of all miners which submit work through this node. It accepts the miner hash rate and an identifier which // hash rate of all miners which submit work through this node. It accepts the miner hash rate and an identifier which
// must be unique between nodes. // must be unique between nodes.
func (api *PublicMinerAPI) SubmitHashrate(hashrate hexutil.Uint64, id common.Hash) bool { func (api *MinerAPI) SubmitHashrate(hashrate hexutil.Uint64, id common.Hash) bool {
api.agent.SubmitHashrate(id, uint64(hashrate)) api.agent.SubmitHashrate(id, uint64(hashrate))
return true return true
} }
// PrivateMinerAPI provides private RPC methods to control the miner. // MinerAPI provides an API to control the miner.
// These methods can be abused by external users and must be considered insecure for use by untrusted users. type MinerAPI struct {
type PrivateMinerAPI struct { e *Ethereum
e *Ethereum agent *miner.RemoteAgent
} }
// NewPrivateMinerAPI create a new RPC service which controls the miner of this node. // NewMinerAPI create a new RPC service which controls the miner of this node.
func NewPrivateMinerAPI(e *Ethereum) *PrivateMinerAPI { func NewMinerAPI(e *Ethereum) *MinerAPI {
return &PrivateMinerAPI{e: e} agent := miner.NewRemoteAgent(e.BlockChain(), e.Engine())
e.Miner().Register(agent)
return &MinerAPI{e, agent}
} }
// Start the miner with the given number of threads. If threads is nil the number // Start the miner with the given number of threads. If threads is nil the number
// of workers started is equal to the number of logical CPUs that are usable by // of workers started is equal to the number of logical CPUs that are usable by
// this process. If mining is already running, this method adjust the number of // this process. If mining is already running, this method adjust the number of
// threads allowed to use. // threads allowed to use.
func (api *PrivateMinerAPI) Start(threads *int) error { func (api *MinerAPI) Start(threads *int) error {
// Set the number of threads if the seal engine supports it // Set the number of threads if the seal engine supports it
if threads == nil { if threads == nil {
threads = new(int) threads = new(int)
@ -160,7 +146,7 @@ func (api *PrivateMinerAPI) Start(threads *int) error {
} }
// Stop the miner // Stop the miner
func (api *PrivateMinerAPI) Stop() bool { func (api *MinerAPI) Stop() bool {
type threaded interface { type threaded interface {
SetThreads(threads int) SetThreads(threads int)
} }
@ -172,7 +158,7 @@ func (api *PrivateMinerAPI) Stop() bool {
} }
// SetExtra sets the extra data string that is included when this miner mines a block. // SetExtra sets the extra data string that is included when this miner mines a block.
func (api *PrivateMinerAPI) SetExtra(extra string) (bool, error) { func (api *MinerAPI) SetExtra(extra string) (bool, error) {
if err := api.e.Miner().SetExtra([]byte(extra)); err != nil { if err := api.e.Miner().SetExtra([]byte(extra)); err != nil {
return false, err return false, err
} }
@ -180,7 +166,7 @@ func (api *PrivateMinerAPI) SetExtra(extra string) (bool, error) {
} }
// SetGasPrice sets the minimum accepted gas price for the miner. // SetGasPrice sets the minimum accepted gas price for the miner.
func (api *PrivateMinerAPI) SetGasPrice(gasPrice hexutil.Big) bool { func (api *MinerAPI) SetGasPrice(gasPrice hexutil.Big) bool {
api.e.lock.Lock() api.e.lock.Lock()
api.e.gasPrice = (*big.Int)(&gasPrice) api.e.gasPrice = (*big.Int)(&gasPrice)
api.e.lock.Unlock() api.e.lock.Unlock()
@ -190,31 +176,30 @@ func (api *PrivateMinerAPI) SetGasPrice(gasPrice hexutil.Big) bool {
} }
// SetEtherbase sets the etherbase of the miner // SetEtherbase sets the etherbase of the miner
func (api *PrivateMinerAPI) SetEtherbase(etherbase common.Address) bool { func (api *MinerAPI) SetEtherbase(etherbase common.Address) bool {
log.Info("[PrivateMinerAPI] SetEtherbase", "addr", etherbase) log.Info("[MinerAPI] SetEtherbase", "addr", etherbase)
api.e.SetEtherbase(etherbase) api.e.SetEtherbase(etherbase)
return true return true
} }
// GetHashrate returns the current hashrate of the miner. // GetHashrate returns the current hashrate of the miner.
func (api *PrivateMinerAPI) GetHashrate() uint64 { func (api *MinerAPI) GetHashrate() uint64 {
return uint64(api.e.miner.HashRate()) return uint64(api.e.miner.HashRate())
} }
// PrivateAdminAPI is the collection of Ethereum full node-related APIs // AdminAPI is the collection of Ethereum full node related APIs for node
// exposed over the private admin endpoint. // administration.
type PrivateAdminAPI struct { type AdminAPI struct {
eth *Ethereum eth *Ethereum
} }
// NewPrivateAdminAPI creates a new API definition for the full node private // NewAdminAPI creates a new instance of AdminAPI.
// admin methods of the Ethereum service. func NewAdminAPI(eth *Ethereum) *AdminAPI {
func NewPrivateAdminAPI(eth *Ethereum) *PrivateAdminAPI { return &AdminAPI{eth: eth}
return &PrivateAdminAPI{eth: eth}
} }
// ExportChain exports the current blockchain into a local file. // ExportChain exports the current blockchain into a local file.
func (api *PrivateAdminAPI) ExportChain(file string) (bool, error) { func (api *AdminAPI) ExportChain(file string) (bool, error) {
// Make sure we can create the file to export into // Make sure we can create the file to export into
out, err := os.OpenFile(file, os.O_CREATE|os.O_WRONLY|os.O_TRUNC, os.ModePerm) out, err := os.OpenFile(file, os.O_CREATE|os.O_WRONLY|os.O_TRUNC, os.ModePerm)
if err != nil { if err != nil {
@ -246,7 +231,7 @@ func hasAllBlocks(chain *core.BlockChain, bs []*types.Block) bool {
} }
// ImportChain imports a blockchain from a local file. // ImportChain imports a blockchain from a local file.
func (api *PrivateAdminAPI) ImportChain(file string) (bool, error) { func (api *AdminAPI) ImportChain(file string) (bool, error) {
// Make sure the can access the file to import // Make sure the can access the file to import
in, err := os.Open(file) in, err := os.Open(file)
if err != nil { if err != nil {
@ -294,20 +279,8 @@ func (api *PrivateAdminAPI) ImportChain(file string) (bool, error) {
return true, nil return true, nil
} }
// PublicDebugAPI is the collection of Ethereum full node APIs exposed
// over the public debugging endpoint.
type PublicDebugAPI struct {
eth *Ethereum
}
// NewPublicDebugAPI creates a new API definition for the full node-
// related public debug methods of the Ethereum service.
func NewPublicDebugAPI(eth *Ethereum) *PublicDebugAPI {
return &PublicDebugAPI{eth: eth}
}
// DumpBlock retrieves the entire state of the database at a given block. // DumpBlock retrieves the entire state of the database at a given block.
func (api *PublicDebugAPI) DumpBlock(blockNr rpc.BlockNumber) (state.Dump, error) { func (api *DebugAPI) DumpBlock(blockNr rpc.BlockNumber) (state.Dump, error) {
if blockNr == rpc.PendingBlockNumber { if blockNr == rpc.PendingBlockNumber {
blockNr = rpc.LatestBlockNumber blockNr = rpc.LatestBlockNumber
} }
@ -327,21 +300,21 @@ func (api *PublicDebugAPI) DumpBlock(blockNr rpc.BlockNumber) (state.Dump, error
return stateDb.RawDump(), nil return stateDb.RawDump(), nil
} }
// PrivateDebugAPI is the collection of Ethereum full node APIs exposed over // DebugAPI is the collection of Ethereum full node APIs exposed over
// the private debugging endpoint. // the private debugging endpoint.
type PrivateDebugAPI struct { type DebugAPI struct {
config *params.ChainConfig config *params.ChainConfig
eth *Ethereum eth *Ethereum
} }
// NewPrivateDebugAPI creates a new API definition for the full node-related // NewDebugAPI creates a new API definition for the full node-related
// private debug methods of the Ethereum service. // private debug methods of the Ethereum service.
func NewPrivateDebugAPI(config *params.ChainConfig, eth *Ethereum) *PrivateDebugAPI { func NewDebugAPI(config *params.ChainConfig, eth *Ethereum) *DebugAPI {
return &PrivateDebugAPI{config: config, eth: eth} return &DebugAPI{config: config, eth: eth}
} }
// Preimage is a debug API function that returns the preimage for a sha3 hash, if known. // Preimage is a debug API function that returns the preimage for a sha3 hash, if known.
func (api *PrivateDebugAPI) Preimage(ctx context.Context, hash common.Hash) (hexutil.Bytes, error) { func (api *DebugAPI) Preimage(ctx context.Context, hash common.Hash) (hexutil.Bytes, error) {
if preimage := rawdb.ReadPreimage(api.eth.ChainDb(), hash); preimage != nil { if preimage := rawdb.ReadPreimage(api.eth.ChainDb(), hash); preimage != nil {
return preimage, nil return preimage, nil
} }
@ -350,7 +323,7 @@ func (api *PrivateDebugAPI) Preimage(ctx context.Context, hash common.Hash) (hex
// GetBadBLocks returns a list of the last 'bad blocks' that the client has seen on the network // GetBadBLocks returns a list of the last 'bad blocks' that the client has seen on the network
// and returns them as a JSON list of block-hashes // and returns them as a JSON list of block-hashes
func (api *PrivateDebugAPI) GetBadBlocks(ctx context.Context) ([]core.BadBlockArgs, error) { func (api *DebugAPI) GetBadBlocks(ctx context.Context) ([]core.BadBlockArgs, error) {
return api.eth.BlockChain().BadBlocks() return api.eth.BlockChain().BadBlocks()
} }
@ -368,7 +341,7 @@ type storageEntry struct {
} }
// StorageRangeAt returns the storage at the given block height and transaction index. // StorageRangeAt returns the storage at the given block height and transaction index.
func (api *PrivateDebugAPI) StorageRangeAt(ctx context.Context, blockHash common.Hash, txIndex int, contractAddress common.Address, keyStart hexutil.Bytes, maxResult int) (StorageRangeResult, error) { func (api *DebugAPI) StorageRangeAt(ctx context.Context, blockHash common.Hash, txIndex int, contractAddress common.Address, keyStart hexutil.Bytes, maxResult int) (StorageRangeResult, error) {
_, _, statedb, err := api.computeTxEnv(blockHash, txIndex, 0) _, _, statedb, err := api.computeTxEnv(blockHash, txIndex, 0)
if err != nil { if err != nil {
return StorageRangeResult{}, err return StorageRangeResult{}, err
@ -408,7 +381,7 @@ func storageRangeAt(st state.Trie, start []byte, maxResult int) (StorageRangeRes
// code hash, or storage hash. // code hash, or storage hash.
// //
// With one parameter, returns the list of accounts modified in the specified block. // With one parameter, returns the list of accounts modified in the specified block.
func (api *PrivateDebugAPI) GetModifiedAccountsByNumber(startNum uint64, endNum *uint64) ([]common.Address, error) { func (api *DebugAPI) GetModifiedAccountsByNumber(startNum uint64, endNum *uint64) ([]common.Address, error) {
var startBlock, endBlock *types.Block var startBlock, endBlock *types.Block
startBlock = api.eth.blockchain.GetBlockByNumber(startNum) startBlock = api.eth.blockchain.GetBlockByNumber(startNum)
@ -436,7 +409,7 @@ func (api *PrivateDebugAPI) GetModifiedAccountsByNumber(startNum uint64, endNum
// code hash, or storage hash. // code hash, or storage hash.
// //
// With one parameter, returns the list of accounts modified in the specified block. // With one parameter, returns the list of accounts modified in the specified block.
func (api *PrivateDebugAPI) GetModifiedAccountsByHash(startHash common.Hash, endHash *common.Hash) ([]common.Address, error) { func (api *DebugAPI) GetModifiedAccountsByHash(startHash common.Hash, endHash *common.Hash) ([]common.Address, error) {
var startBlock, endBlock *types.Block var startBlock, endBlock *types.Block
startBlock = api.eth.blockchain.GetBlockByHash(startHash) startBlock = api.eth.blockchain.GetBlockByHash(startHash)
if startBlock == nil { if startBlock == nil {
@ -458,7 +431,7 @@ func (api *PrivateDebugAPI) GetModifiedAccountsByHash(startHash common.Hash, end
return api.getModifiedAccounts(startBlock, endBlock) return api.getModifiedAccounts(startBlock, endBlock)
} }
func (api *PrivateDebugAPI) getModifiedAccounts(startBlock, endBlock *types.Block) ([]common.Address, error) { func (api *DebugAPI) getModifiedAccounts(startBlock, endBlock *types.Block) ([]common.Address, error) {
if startBlock.Number().Uint64() >= endBlock.Number().Uint64() { if startBlock.Number().Uint64() >= endBlock.Number().Uint64() {
return nil, fmt.Errorf("start block height (%d) must be less than end block height (%d)", startBlock.Number().Uint64(), endBlock.Number().Uint64()) return nil, fmt.Errorf("start block height (%d) must be less than end block height (%d)", startBlock.Number().Uint64(), endBlock.Number().Uint64())
} }
@ -487,7 +460,7 @@ func (api *PrivateDebugAPI) getModifiedAccounts(startBlock, endBlock *types.Bloc
return dirty, nil return dirty, nil
} }
func (api *PublicEthereumAPI) ChainId() hexutil.Uint64 { func (api *EthereumAPI) ChainId() hexutil.Uint64 {
chainID := new(big.Int) chainID := new(big.Int)
if config := api.e.chainConfig; config.IsEIP155(api.e.blockchain.CurrentBlock().Number()) { if config := api.e.chainConfig; config.IsEIP155(api.e.blockchain.CurrentBlock().Number()) {
chainID = config.ChainId chainID = config.ChainId
@ -496,7 +469,7 @@ func (api *PublicEthereumAPI) ChainId() hexutil.Uint64 {
} }
// GetOwner return masternode owner of the given coinbase address // GetOwner return masternode owner of the given coinbase address
func (api *PublicEthereumAPI) GetOwnerByCoinbase(ctx context.Context, coinbase common.Address, blockNr rpc.BlockNumber) (common.Address, error) { func (api *EthereumAPI) GetOwnerByCoinbase(ctx context.Context, coinbase common.Address, blockNr rpc.BlockNumber) (common.Address, error) {
statedb, _, err := api.e.ApiBackend.StateAndHeaderByNumber(ctx, blockNr) statedb, _, err := api.e.ApiBackend.StateAndHeaderByNumber(ctx, blockNr)
if err != nil { if err != nil {
return common.Address{}, err return common.Address{}, err

View file

@ -105,7 +105,7 @@ type txTraceTask struct {
// blockByNumber is the wrapper of the chain access function offered by the backend. // blockByNumber is the wrapper of the chain access function offered by the backend.
// It will return an error if the block is not found. // It will return an error if the block is not found.
func (api *PrivateDebugAPI) blockByNumber(ctx context.Context, number rpc.BlockNumber) (*types.Block, error) { func (api *DebugAPI) blockByNumber(ctx context.Context, number rpc.BlockNumber) (*types.Block, error) {
block, err := api.eth.ApiBackend.BlockByNumber(ctx, number) block, err := api.eth.ApiBackend.BlockByNumber(ctx, number)
if err != nil { if err != nil {
return nil, err return nil, err
@ -118,7 +118,7 @@ func (api *PrivateDebugAPI) blockByNumber(ctx context.Context, number rpc.BlockN
// blockByHash is the wrapper of the chain access function offered by the backend. // blockByHash is the wrapper of the chain access function offered by the backend.
// It will return an error if the block is not found. // It will return an error if the block is not found.
func (api *PrivateDebugAPI) blockByHash(ctx context.Context, hash common.Hash) (*types.Block, error) { func (api *DebugAPI) blockByHash(ctx context.Context, hash common.Hash) (*types.Block, error) {
block, err := api.eth.ApiBackend.BlockByHash(ctx, hash) block, err := api.eth.ApiBackend.BlockByHash(ctx, hash)
if err != nil { if err != nil {
return nil, err return nil, err
@ -131,7 +131,7 @@ func (api *PrivateDebugAPI) blockByHash(ctx context.Context, hash common.Hash) (
// TraceChain returns the structured logs created during the execution of EVM // TraceChain returns the structured logs created during the execution of EVM
// between two blocks (excluding start) and returns them as a JSON object. // between two blocks (excluding start) and returns them as a JSON object.
func (api *PrivateDebugAPI) TraceChain(ctx context.Context, start, end rpc.BlockNumber, config *TraceConfig) (*rpc.Subscription, error) { func (api *DebugAPI) TraceChain(ctx context.Context, start, end rpc.BlockNumber, config *TraceConfig) (*rpc.Subscription, error) {
// Fetch the block interval that we want to trace // Fetch the block interval that we want to trace
var from, to *types.Block var from, to *types.Block
@ -167,7 +167,7 @@ func (api *PrivateDebugAPI) TraceChain(ctx context.Context, start, end rpc.Block
// traceChain configures a new tracer according to the provided configuration, and // traceChain configures a new tracer according to the provided configuration, and
// executes all the transactions contained within. The return value will be one item // executes all the transactions contained within. The return value will be one item
// per transaction, dependent on the requestd tracer. // per transaction, dependent on the requestd tracer.
func (api *PrivateDebugAPI) traceChain(ctx context.Context, start, end *types.Block, config *TraceConfig) (*rpc.Subscription, error) { func (api *DebugAPI) traceChain(ctx context.Context, start, end *types.Block, config *TraceConfig) (*rpc.Subscription, error) {
// Tracing a chain is a **long** operation, only do with subscriptions // Tracing a chain is a **long** operation, only do with subscriptions
notifier, supported := rpc.NotifierFromContext(ctx) notifier, supported := rpc.NotifierFromContext(ctx)
if !supported { if !supported {
@ -379,7 +379,7 @@ func (api *PrivateDebugAPI) traceChain(ctx context.Context, start, end *types.Bl
// TraceBlockByNumber returns the structured logs created during the execution of // TraceBlockByNumber returns the structured logs created during the execution of
// EVM and returns them as a JSON object. // EVM and returns them as a JSON object.
func (api *PrivateDebugAPI) TraceBlockByNumber(ctx context.Context, number rpc.BlockNumber, config *TraceConfig) ([]*txTraceResult, error) { func (api *DebugAPI) TraceBlockByNumber(ctx context.Context, number rpc.BlockNumber, config *TraceConfig) ([]*txTraceResult, error) {
// Fetch the block that we want to trace // Fetch the block that we want to trace
var block *types.Block var block *types.Block
@ -400,7 +400,7 @@ func (api *PrivateDebugAPI) TraceBlockByNumber(ctx context.Context, number rpc.B
// TraceBlockByHash returns the structured logs created during the execution of // TraceBlockByHash returns the structured logs created during the execution of
// EVM and returns them as a JSON object. // EVM and returns them as a JSON object.
func (api *PrivateDebugAPI) TraceBlockByHash(ctx context.Context, hash common.Hash, config *TraceConfig) ([]*txTraceResult, error) { func (api *DebugAPI) TraceBlockByHash(ctx context.Context, hash common.Hash, config *TraceConfig) ([]*txTraceResult, error) {
block := api.eth.blockchain.GetBlockByHash(hash) block := api.eth.blockchain.GetBlockByHash(hash)
if block == nil { if block == nil {
return nil, fmt.Errorf("block #%x not found", hash) return nil, fmt.Errorf("block #%x not found", hash)
@ -410,7 +410,7 @@ func (api *PrivateDebugAPI) TraceBlockByHash(ctx context.Context, hash common.Ha
// TraceBlock returns the structured logs created during the execution of EVM // TraceBlock returns the structured logs created during the execution of EVM
// and returns them as a JSON object. // and returns them as a JSON object.
func (api *PrivateDebugAPI) TraceBlock(ctx context.Context, blob []byte, config *TraceConfig) ([]*txTraceResult, error) { func (api *DebugAPI) TraceBlock(ctx context.Context, blob []byte, config *TraceConfig) ([]*txTraceResult, error) {
block := new(types.Block) block := new(types.Block)
if err := rlp.Decode(bytes.NewReader(blob), block); err != nil { if err := rlp.Decode(bytes.NewReader(blob), block); err != nil {
return nil, fmt.Errorf("could not decode block: %v", err) return nil, fmt.Errorf("could not decode block: %v", err)
@ -420,7 +420,7 @@ func (api *PrivateDebugAPI) TraceBlock(ctx context.Context, blob []byte, config
// TraceBlockFromFile returns the structured logs created during the execution of // TraceBlockFromFile returns the structured logs created during the execution of
// EVM and returns them as a JSON object. // EVM and returns them as a JSON object.
func (api *PrivateDebugAPI) TraceBlockFromFile(ctx context.Context, file string, config *TraceConfig) ([]*txTraceResult, error) { func (api *DebugAPI) TraceBlockFromFile(ctx context.Context, file string, config *TraceConfig) ([]*txTraceResult, error) {
blob, err := os.ReadFile(file) blob, err := os.ReadFile(file)
if err != nil { if err != nil {
return nil, fmt.Errorf("could not read file: %v", err) return nil, fmt.Errorf("could not read file: %v", err)
@ -431,7 +431,7 @@ func (api *PrivateDebugAPI) TraceBlockFromFile(ctx context.Context, file string,
// traceBlock configures a new tracer according to the provided configuration, and // traceBlock configures a new tracer according to the provided configuration, and
// executes all the transactions contained within. The return value will be one item // executes all the transactions contained within. The return value will be one item
// per transaction, dependent on the requestd tracer. // per transaction, dependent on the requestd tracer.
func (api *PrivateDebugAPI) traceBlock(ctx context.Context, block *types.Block, config *TraceConfig) ([]*txTraceResult, error) { func (api *DebugAPI) traceBlock(ctx context.Context, block *types.Block, config *TraceConfig) ([]*txTraceResult, error) {
// Create the parent state database // Create the parent state database
if err := api.eth.engine.VerifyHeader(api.eth.blockchain, block.Header(), true); err != nil { if err := api.eth.engine.VerifyHeader(api.eth.blockchain, block.Header(), true); err != nil {
return nil, err return nil, err
@ -537,7 +537,7 @@ func (api *PrivateDebugAPI) traceBlock(ctx context.Context, block *types.Block,
// computeStateDB retrieves the state database associated with a certain block. // computeStateDB retrieves the state database associated with a certain block.
// If no state is locally available for the given block, a number of blocks are // If no state is locally available for the given block, a number of blocks are
// attempted to be reexecuted to generate the desired state. // attempted to be reexecuted to generate the desired state.
func (api *PrivateDebugAPI) computeStateDB(block *types.Block, reexec uint64) (*state.StateDB, *tradingstate.TradingStateDB, error) { func (api *DebugAPI) computeStateDB(block *types.Block, reexec uint64) (*state.StateDB, *tradingstate.TradingStateDB, error) {
// If we have the state fully available, use that // If we have the state fully available, use that
statedb, err := api.eth.blockchain.StateAt(block.Root()) statedb, err := api.eth.blockchain.StateAt(block.Root())
XDCxState := &tradingstate.TradingStateDB{} XDCxState := &tradingstate.TradingStateDB{}
@ -615,7 +615,7 @@ func (api *PrivateDebugAPI) computeStateDB(block *types.Block, reexec uint64) (*
// TraceTransaction returns the structured logs created during the execution of EVM // TraceTransaction returns the structured logs created during the execution of EVM
// and returns them as a JSON object. // and returns them as a JSON object.
func (api *PrivateDebugAPI) TraceTransaction(ctx context.Context, hash common.Hash, config *TraceConfig) (interface{}, error) { func (api *DebugAPI) TraceTransaction(ctx context.Context, hash common.Hash, config *TraceConfig) (interface{}, error) {
// Retrieve the transaction and assemble its EVM context // Retrieve the transaction and assemble its EVM context
tx, blockHash, _, index := rawdb.ReadTransaction(api.eth.ChainDb(), hash) tx, blockHash, _, index := rawdb.ReadTransaction(api.eth.ChainDb(), hash)
if tx == nil { if tx == nil {
@ -642,7 +642,7 @@ func (api *PrivateDebugAPI) TraceTransaction(ctx context.Context, hash common.Ha
// created during the execution of EVM if the given transaction was added on // created during the execution of EVM if the given transaction was added on
// top of the provided block and returns them as a JSON object. // top of the provided block and returns them as a JSON object.
// You can provide -2 as a block number to trace on top of the pending block. // You can provide -2 as a block number to trace on top of the pending block.
func (api *PrivateDebugAPI) TraceCall(ctx context.Context, args ethapi.TransactionArgs, blockNrOrHash rpc.BlockNumberOrHash, config *TraceCallConfig) (interface{}, error) { func (api *DebugAPI) TraceCall(ctx context.Context, args ethapi.TransactionArgs, blockNrOrHash rpc.BlockNumberOrHash, config *TraceCallConfig) (interface{}, error) {
// Try to retrieve the specified block // Try to retrieve the specified block
var ( var (
err error err error
@ -699,7 +699,7 @@ func (api *PrivateDebugAPI) TraceCall(ctx context.Context, args ethapi.Transacti
// traceTx configures a new tracer according to the provided configuration, and // traceTx configures a new tracer according to the provided configuration, and
// executes the given message in the provided environment. The return value will // executes the given message in the provided environment. The return value will
// be tracer dependent. // be tracer dependent.
func (api *PrivateDebugAPI) traceTx(ctx context.Context, message core.Message, txctx *tracers.Context, vmctx vm.BlockContext, statedb *state.StateDB, config *TraceConfig) (interface{}, error) { func (api *DebugAPI) traceTx(ctx context.Context, message core.Message, txctx *tracers.Context, vmctx vm.BlockContext, statedb *state.StateDB, config *TraceConfig) (interface{}, error) {
// Assemble the structured logger or the JavaScript tracer // Assemble the structured logger or the JavaScript tracer
var ( var (
tracer vm.EVMLogger tracer vm.EVMLogger
@ -764,7 +764,7 @@ func (api *PrivateDebugAPI) traceTx(ctx context.Context, message core.Message, t
} }
// computeTxEnv returns the execution environment of a certain transaction. // computeTxEnv returns the execution environment of a certain transaction.
func (api *PrivateDebugAPI) computeTxEnv(blockHash common.Hash, txIndex int, reexec uint64) (core.Message, vm.BlockContext, *state.StateDB, error) { func (api *DebugAPI) computeTxEnv(blockHash common.Hash, txIndex int, reexec uint64) (core.Message, vm.BlockContext, *state.StateDB, error) {
// Create the parent state database // Create the parent state database
block := api.eth.blockchain.GetBlockByHash(blockHash) block := api.eth.blockchain.GetBlockByHash(blockHash)
if block == nil { if block == nil {

View file

@ -91,7 +91,7 @@ type Ethereum struct {
etherbase common.Address etherbase common.Address
networkId uint64 networkId uint64
netRPCService *ethapi.PublicNetAPI netRPCService *ethapi.NetAPI
p2pServer *p2p.Server p2pServer *p2p.Server
@ -341,7 +341,7 @@ func New(stack *node.Node, config *ethconfig.Config, XDCXServ *XDCx.XDCX, lendin
} }
// Start the RPC service // Start the RPC service
eth.netRPCService = ethapi.NewPublicNetAPI(eth.p2pServer, eth.NetVersion()) eth.netRPCService = ethapi.NewNetAPI(eth.p2pServer, eth.NetVersion())
// Register the backend on the node // Register the backend on the node
stack.RegisterAPIs(eth.APIs()) stack.RegisterAPIs(eth.APIs())
@ -411,28 +411,22 @@ func (e *Ethereum) APIs() []rpc.API {
return append(apis, []rpc.API{ return append(apis, []rpc.API{
{ {
Namespace: "eth", Namespace: "eth",
Service: NewPublicEthereumAPI(e), Service: NewEthereumAPI(e),
}, {
Namespace: "eth",
Service: NewPublicMinerAPI(e),
}, {
Namespace: "eth",
Service: downloader.NewPublicDownloaderAPI(e.protocolManager.downloader, e.eventMux),
}, { }, {
Namespace: "miner", Namespace: "miner",
Service: NewPrivateMinerAPI(e), Service: NewMinerAPI(e),
}, {
Namespace: "eth",
Service: downloader.NewDownloaderAPI(e.protocolManager.downloader, e.eventMux),
}, { }, {
Namespace: "eth", Namespace: "eth",
Service: filters.NewFilterAPI(filters.NewFilterSystem(e.ApiBackend, filters.Config{LogCacheSize: e.config.FilterLogCacheSize}), false), Service: filters.NewFilterAPI(filters.NewFilterSystem(e.ApiBackend, filters.Config{LogCacheSize: e.config.FilterLogCacheSize}), false),
}, { }, {
Namespace: "admin", Namespace: "admin",
Service: NewPrivateAdminAPI(e), Service: NewAdminAPI(e),
}, { }, {
Namespace: "debug", Namespace: "debug",
Service: NewPublicDebugAPI(e), Service: NewDebugAPI(e.chainConfig, e),
}, {
Namespace: "debug",
Service: NewPrivateDebugAPI(e.chainConfig, e),
}, { }, {
Namespace: "net", Namespace: "net",
Service: e.netRPCService, Service: e.netRPCService,

View file

@ -25,21 +25,21 @@ import (
"github.com/XinFinOrg/XDPoSChain/rpc" "github.com/XinFinOrg/XDPoSChain/rpc"
) )
// PublicDownloaderAPI provides an API which gives information about the current synchronisation status. // DownloaderAPI provides an API which gives information about the current synchronisation status.
// It offers only methods that operates on data that can be available to anyone without security risks. // It offers only methods that operates on data that can be available to anyone without security risks.
type PublicDownloaderAPI struct { type DownloaderAPI struct {
d *Downloader d *Downloader
mux *event.TypeMux mux *event.TypeMux
installSyncSubscription chan chan interface{} installSyncSubscription chan chan interface{}
uninstallSyncSubscription chan *uninstallSyncSubscriptionRequest uninstallSyncSubscription chan *uninstallSyncSubscriptionRequest
} }
// NewPublicDownloaderAPI create a new PublicDownloaderAPI. The API has an internal event loop that // NewDownloaderAPI create a new DownloaderAPI. The API has an internal event loop that
// listens for events from the downloader through the global event mux. In case it receives one of // listens for events from the downloader through the global event mux. In case it receives one of
// these events it broadcasts it to all syncing subscriptions that are installed through the // these events it broadcasts it to all syncing subscriptions that are installed through the
// installSyncSubscription channel. // installSyncSubscription channel.
func NewPublicDownloaderAPI(d *Downloader, m *event.TypeMux) *PublicDownloaderAPI { func NewDownloaderAPI(d *Downloader, m *event.TypeMux) *DownloaderAPI {
api := &PublicDownloaderAPI{ api := &DownloaderAPI{
d: d, d: d,
mux: m, mux: m,
installSyncSubscription: make(chan chan interface{}), installSyncSubscription: make(chan chan interface{}),
@ -53,7 +53,7 @@ func NewPublicDownloaderAPI(d *Downloader, m *event.TypeMux) *PublicDownloaderAP
// eventLoop runs an loop until the event mux closes. It will install and uninstall new // eventLoop runs an loop until the event mux closes. It will install and uninstall new
// sync subscriptions and broadcasts sync status updates to the installed sync subscriptions. // sync subscriptions and broadcasts sync status updates to the installed sync subscriptions.
func (api *PublicDownloaderAPI) eventLoop() { func (api *DownloaderAPI) eventLoop() {
var ( var (
sub = api.mux.Subscribe(StartEvent{}, DoneEvent{}, FailedEvent{}) sub = api.mux.Subscribe(StartEvent{}, DoneEvent{}, FailedEvent{})
syncSubscriptions = make(map[chan interface{}]struct{}) syncSubscriptions = make(map[chan interface{}]struct{})
@ -90,7 +90,7 @@ func (api *PublicDownloaderAPI) eventLoop() {
} }
// Syncing provides information when this nodes starts synchronising with the Ethereum network and when it's finished. // Syncing provides information when this nodes starts synchronising with the Ethereum network and when it's finished.
func (api *PublicDownloaderAPI) Syncing(ctx context.Context) (*rpc.Subscription, error) { func (api *DownloaderAPI) Syncing(ctx context.Context) (*rpc.Subscription, error) {
notifier, supported := rpc.NotifierFromContext(ctx) notifier, supported := rpc.NotifierFromContext(ctx)
if !supported { if !supported {
return &rpc.Subscription{}, rpc.ErrNotificationsUnsupported return &rpc.Subscription{}, rpc.ErrNotificationsUnsupported
@ -130,9 +130,9 @@ type uninstallSyncSubscriptionRequest struct {
// SyncStatusSubscription represents a syncing subscription. // SyncStatusSubscription represents a syncing subscription.
type SyncStatusSubscription struct { type SyncStatusSubscription struct {
api *PublicDownloaderAPI // register subscription in event loop of this api instance api *DownloaderAPI // register subscription in event loop of this api instance
c chan interface{} // channel where events are broadcasted to c chan interface{} // channel where events are broadcasted to
unsubOnce sync.Once // make sure unsubscribe logic is executed once unsubOnce sync.Once // make sure unsubscribe logic is executed once
} }
// Unsubscribe uninstalls the subscription from the DownloadAPI event loop. // Unsubscribe uninstalls the subscription from the DownloadAPI event loop.
@ -157,7 +157,7 @@ func (s *SyncStatusSubscription) Unsubscribe() {
// SubscribeSyncStatus creates a subscription that will broadcast new synchronisation updates. // SubscribeSyncStatus creates a subscription that will broadcast new synchronisation updates.
// The given channel must receive interface values, the result can either // The given channel must receive interface values, the result can either
func (api *PublicDownloaderAPI) SubscribeSyncStatus(status chan interface{}) *SyncStatusSubscription { func (api *DownloaderAPI) SubscribeSyncStatus(status chan interface{}) *SyncStatusSubscription {
api.installSyncSubscription <- status api.installSyncSubscription <- status
return &SyncStatusSubscription{api: api, c: status} return &SyncStatusSubscription{api: api, c: status}
} }

View file

@ -72,19 +72,19 @@ const (
var errEmptyHeader = errors.New("empty header") var errEmptyHeader = errors.New("empty header")
// PublicEthereumAPI provides an API to access Ethereum related information. // EthereumAPI provides an API to access Ethereum related information.
// It offers only methods that operate on public data that is freely available to anyone. // It offers only methods that operate on public data that is freely available to anyone.
type PublicEthereumAPI struct { type EthereumAPI struct {
b Backend b Backend
} }
// NewPublicEthereumAPI creates a new Ethereum protocol API. // NewEthereumAPI creates a new Ethereum protocol API.
func NewPublicEthereumAPI(b Backend) *PublicEthereumAPI { func NewEthereumAPI(b Backend) *EthereumAPI {
return &PublicEthereumAPI{b} return &EthereumAPI{b}
} }
// GasPrice returns a suggestion for a gas price for legacy transactions. // GasPrice returns a suggestion for a gas price for legacy transactions.
func (s *PublicEthereumAPI) GasPrice(ctx context.Context) (*hexutil.Big, error) { func (s *EthereumAPI) GasPrice(ctx context.Context) (*hexutil.Big, error) {
tipcap, err := s.b.SuggestGasTipCap(ctx) tipcap, err := s.b.SuggestGasTipCap(ctx)
if err != nil { if err != nil {
return nil, err return nil, err
@ -96,7 +96,7 @@ func (s *PublicEthereumAPI) GasPrice(ctx context.Context) (*hexutil.Big, error)
} }
// MaxPriorityFeePerGas returns a suggestion for a gas tip cap for dynamic transactions. // MaxPriorityFeePerGas returns a suggestion for a gas tip cap for dynamic transactions.
func (s *PublicEthereumAPI) MaxPriorityFeePerGas(ctx context.Context) (*hexutil.Big, error) { func (s *EthereumAPI) MaxPriorityFeePerGas(ctx context.Context) (*hexutil.Big, error) {
tipcap, err := s.b.SuggestGasTipCap(ctx) tipcap, err := s.b.SuggestGasTipCap(ctx)
if err != nil { if err != nil {
return nil, err return nil, err
@ -112,7 +112,7 @@ type feeHistoryResult struct {
} }
// FeeHistory returns the fee market history. // FeeHistory returns the fee market history.
func (s *PublicEthereumAPI) FeeHistory(ctx context.Context, blockCount math.HexOrDecimal64, lastBlock rpc.BlockNumber, rewardPercentiles []float64) (*feeHistoryResult, error) { func (s *EthereumAPI) FeeHistory(ctx context.Context, blockCount math.HexOrDecimal64, lastBlock rpc.BlockNumber, rewardPercentiles []float64) (*feeHistoryResult, error) {
oldest, reward, baseFee, gasUsed, err := s.b.FeeHistory(ctx, uint64(blockCount), lastBlock, rewardPercentiles) oldest, reward, baseFee, gasUsed, err := s.b.FeeHistory(ctx, uint64(blockCount), lastBlock, rewardPercentiles)
if err != nil { if err != nil {
return nil, err return nil, err
@ -140,12 +140,12 @@ func (s *PublicEthereumAPI) FeeHistory(ctx context.Context, blockCount math.HexO
} }
// BlobBaseFee returns the base fee for blob gas at the current head. // BlobBaseFee returns the base fee for blob gas at the current head.
func (s *PublicEthereumAPI) BlobBaseFee(ctx context.Context) *hexutil.Big { func (s *EthereumAPI) BlobBaseFee(ctx context.Context) *hexutil.Big {
return (*hexutil.Big)(new(big.Int)) return (*hexutil.Big)(new(big.Int))
} }
// ProtocolVersion returns the current Ethereum protocol version this node supports // ProtocolVersion returns the current Ethereum protocol version this node supports
func (s *PublicEthereumAPI) ProtocolVersion() hexutil.Uint { func (s *EthereumAPI) ProtocolVersion() hexutil.Uint {
return hexutil.Uint(s.b.ProtocolVersion()) return hexutil.Uint(s.b.ProtocolVersion())
} }
@ -156,7 +156,7 @@ func (s *PublicEthereumAPI) ProtocolVersion() hexutil.Uint {
// - highestBlock: block number of the highest block header this node has received from peers // - highestBlock: block number of the highest block header this node has received from peers
// - pulledStates: number of state entries processed until now // - pulledStates: number of state entries processed until now
// - knownStates: number of known state entries that still need to be pulled // - knownStates: number of known state entries that still need to be pulled
func (s *PublicEthereumAPI) Syncing() (interface{}, error) { func (s *EthereumAPI) Syncing() (interface{}, error) {
progress := s.b.Downloader().Progress() progress := s.b.Downloader().Progress()
// Return not syncing if the synchronisation already completed // Return not syncing if the synchronisation already completed
@ -173,18 +173,18 @@ func (s *PublicEthereumAPI) Syncing() (interface{}, error) {
}, nil }, nil
} }
// PublicTxPoolAPI offers and API for the transaction pool. It only operates on data that is non confidential. // TxPoolAPI offers and API for the transaction pool. It only operates on data that is non confidential.
type PublicTxPoolAPI struct { type TxPoolAPI struct {
b Backend b Backend
} }
// NewPublicTxPoolAPI creates a new tx pool service that gives information about the transaction pool. // NewTxPoolAPI creates a new tx pool service that gives information about the transaction pool.
func NewPublicTxPoolAPI(b Backend) *PublicTxPoolAPI { func NewTxPoolAPI(b Backend) *TxPoolAPI {
return &PublicTxPoolAPI{b} return &TxPoolAPI{b}
} }
// Content returns the transactions contained within the transaction pool. // Content returns the transactions contained within the transaction pool.
func (s *PublicTxPoolAPI) Content() map[string]map[string]map[string]*RPCTransaction { func (s *TxPoolAPI) Content() map[string]map[string]map[string]*RPCTransaction {
content := map[string]map[string]map[string]*RPCTransaction{ content := map[string]map[string]map[string]*RPCTransaction{
"pending": make(map[string]map[string]*RPCTransaction), "pending": make(map[string]map[string]*RPCTransaction),
"queued": make(map[string]map[string]*RPCTransaction), "queued": make(map[string]map[string]*RPCTransaction),
@ -211,7 +211,7 @@ func (s *PublicTxPoolAPI) Content() map[string]map[string]map[string]*RPCTransac
} }
// ContentFrom returns the transactions contained within the transaction pool. // ContentFrom returns the transactions contained within the transaction pool.
func (s *PublicTxPoolAPI) ContentFrom(addr common.Address) map[string]map[string]*RPCTransaction { func (s *TxPoolAPI) ContentFrom(addr common.Address) map[string]map[string]*RPCTransaction {
content := make(map[string]map[string]*RPCTransaction, 2) content := make(map[string]map[string]*RPCTransaction, 2)
pending, queue := s.b.TxPoolContentFrom(addr) pending, queue := s.b.TxPoolContentFrom(addr)
curHeader := s.b.CurrentHeader() curHeader := s.b.CurrentHeader()
@ -234,7 +234,7 @@ func (s *PublicTxPoolAPI) ContentFrom(addr common.Address) map[string]map[string
} }
// Status returns the number of pending and queued transaction in the pool. // Status returns the number of pending and queued transaction in the pool.
func (s *PublicTxPoolAPI) Status() map[string]hexutil.Uint { func (s *TxPoolAPI) Status() map[string]hexutil.Uint {
pending, queue := s.b.Stats() pending, queue := s.b.Stats()
return map[string]hexutil.Uint{ return map[string]hexutil.Uint{
"pending": hexutil.Uint(pending), "pending": hexutil.Uint(pending),
@ -244,7 +244,7 @@ func (s *PublicTxPoolAPI) Status() map[string]hexutil.Uint {
// Inspect retrieves the content of the transaction pool and flattens it into an // Inspect retrieves the content of the transaction pool and flattens it into an
// easily inspectable list. // easily inspectable list.
func (s *PublicTxPoolAPI) Inspect() map[string]map[string]map[string]string { func (s *TxPoolAPI) Inspect() map[string]map[string]map[string]string {
content := map[string]map[string]map[string]string{ content := map[string]map[string]map[string]string{
"pending": make(map[string]map[string]string), "pending": make(map[string]map[string]string),
"queued": make(map[string]map[string]string), "queued": make(map[string]map[string]string),
@ -277,34 +277,34 @@ func (s *PublicTxPoolAPI) Inspect() map[string]map[string]map[string]string {
return content return content
} }
// PublicAccountAPI provides an API to access accounts managed by this node. // EthereumAccountAPI provides an API to access accounts managed by this node.
// It offers only methods that can retrieve accounts. // It offers only methods that can retrieve accounts.
type PublicAccountAPI struct { type EthereumAccountAPI struct {
am *accounts.Manager am *accounts.Manager
} }
// NewPublicAccountAPI creates a new PublicAccountAPI. // NewEthereumAccountAPI creates a new EthereumAccountAPI.
func NewPublicAccountAPI(am *accounts.Manager) *PublicAccountAPI { func NewEthereumAccountAPI(am *accounts.Manager) *EthereumAccountAPI {
return &PublicAccountAPI{am: am} return &EthereumAccountAPI{am: am}
} }
// Accounts returns the collection of accounts this node manages // Accounts returns the collection of accounts this node manages
func (s *PublicAccountAPI) Accounts() []common.Address { func (s *EthereumAccountAPI) Accounts() []common.Address {
return s.am.Accounts() return s.am.Accounts()
} }
// PrivateAccountAPI provides an API to access accounts managed by this node. // PersonalAccountAPI provides an API to access accounts managed by this node.
// It offers methods to create, (un)lock en list accounts. Some methods accept // It offers methods to create, (un)lock en list accounts. Some methods accept
// passwords and are therefore considered private by default. // passwords and are therefore considered private by default.
type PrivateAccountAPI struct { type PersonalAccountAPI struct {
am *accounts.Manager am *accounts.Manager
nonceLock *AddrLocker nonceLock *AddrLocker
b Backend b Backend
} }
// NewPrivateAccountAPI create a new PrivateAccountAPI. // NewPersonalAccountAPI create a new PersonalAccountAPI.
func NewPrivateAccountAPI(b Backend, nonceLock *AddrLocker) *PrivateAccountAPI { func NewPersonalAccountAPI(b Backend, nonceLock *AddrLocker) *PersonalAccountAPI {
return &PrivateAccountAPI{ return &PersonalAccountAPI{
am: b.AccountManager(), am: b.AccountManager(),
nonceLock: nonceLock, nonceLock: nonceLock,
b: b, b: b,
@ -312,7 +312,7 @@ func NewPrivateAccountAPI(b Backend, nonceLock *AddrLocker) *PrivateAccountAPI {
} }
// ListAccounts will return a list of addresses for accounts this node manages. // ListAccounts will return a list of addresses for accounts this node manages.
func (s *PrivateAccountAPI) ListAccounts() []common.Address { func (s *PersonalAccountAPI) ListAccounts() []common.Address {
return s.am.Accounts() return s.am.Accounts()
} }
@ -326,7 +326,7 @@ type rawWallet struct {
} }
// ListWallets will return a list of wallets this node manages. // ListWallets will return a list of wallets this node manages.
func (s *PrivateAccountAPI) ListWallets() []rawWallet { func (s *PersonalAccountAPI) ListWallets() []rawWallet {
wallets := make([]rawWallet, 0) // return [] instead of nil if empty wallets := make([]rawWallet, 0) // return [] instead of nil if empty
for _, wallet := range s.am.Wallets() { for _, wallet := range s.am.Wallets() {
status, failure := wallet.Status() status, failure := wallet.Status()
@ -348,7 +348,7 @@ func (s *PrivateAccountAPI) ListWallets() []rawWallet {
// connection and attempting to authenticate via the provided passphrase. Note, // connection and attempting to authenticate via the provided passphrase. Note,
// the method may return an extra challenge requiring a second open (e.g. the // the method may return an extra challenge requiring a second open (e.g. the
// Trezor PIN matrix challenge). // Trezor PIN matrix challenge).
func (s *PrivateAccountAPI) OpenWallet(url string, passphrase *string) error { func (s *PersonalAccountAPI) OpenWallet(url string, passphrase *string) error {
wallet, err := s.am.Wallet(url) wallet, err := s.am.Wallet(url)
if err != nil { if err != nil {
return err return err
@ -362,7 +362,7 @@ func (s *PrivateAccountAPI) OpenWallet(url string, passphrase *string) error {
// DeriveAccount requests a HD wallet to derive a new account, optionally pinning // DeriveAccount requests a HD wallet to derive a new account, optionally pinning
// it for later reuse. // it for later reuse.
func (s *PrivateAccountAPI) DeriveAccount(url string, path string, pin *bool) (accounts.Account, error) { func (s *PersonalAccountAPI) DeriveAccount(url string, path string, pin *bool) (accounts.Account, error) {
wallet, err := s.am.Wallet(url) wallet, err := s.am.Wallet(url)
if err != nil { if err != nil {
return accounts.Account{}, err return accounts.Account{}, err
@ -378,7 +378,7 @@ func (s *PrivateAccountAPI) DeriveAccount(url string, path string, pin *bool) (a
} }
// NewAccount will create a new account and returns the address for the new account. // NewAccount will create a new account and returns the address for the new account.
func (s *PrivateAccountAPI) NewAccount(password string) (common.AddressEIP55, error) { func (s *PersonalAccountAPI) NewAccount(password string) (common.AddressEIP55, error) {
acc, err := fetchKeystore(s.am).NewAccount(password) acc, err := fetchKeystore(s.am).NewAccount(password)
if err == nil { if err == nil {
addrEIP55 := common.AddressEIP55(acc.Address) addrEIP55 := common.AddressEIP55(acc.Address)
@ -397,7 +397,7 @@ func fetchKeystore(am *accounts.Manager) *keystore.KeyStore {
// ImportRawKey stores the given hex encoded ECDSA key into the key directory, // ImportRawKey stores the given hex encoded ECDSA key into the key directory,
// encrypting it with the passphrase. // encrypting it with the passphrase.
func (s *PrivateAccountAPI) ImportRawKey(privkey string, password string) (common.Address, error) { func (s *PersonalAccountAPI) ImportRawKey(privkey string, password string) (common.Address, error) {
key, err := crypto.HexToECDSA(privkey) key, err := crypto.HexToECDSA(privkey)
if err != nil { if err != nil {
return common.Address{}, err return common.Address{}, err
@ -409,7 +409,7 @@ func (s *PrivateAccountAPI) ImportRawKey(privkey string, password string) (commo
// UnlockAccount will unlock the account associated with the given address with // UnlockAccount will unlock the account associated with the given address with
// the given password for duration seconds. If duration is nil it will use a // the given password for duration seconds. If duration is nil it will use a
// default of 300 seconds. It returns an indication if the account was unlocked. // default of 300 seconds. It returns an indication if the account was unlocked.
func (s *PrivateAccountAPI) UnlockAccount(addr common.Address, password string, duration *uint64) (bool, error) { func (s *PersonalAccountAPI) UnlockAccount(addr common.Address, password string, duration *uint64) (bool, error) {
const max = uint64(time.Duration(gomath.MaxInt64) / time.Second) const max = uint64(time.Duration(gomath.MaxInt64) / time.Second)
var d time.Duration var d time.Duration
if duration == nil { if duration == nil {
@ -424,14 +424,14 @@ func (s *PrivateAccountAPI) UnlockAccount(addr common.Address, password string,
} }
// LockAccount will lock the account associated with the given address when it's unlocked. // LockAccount will lock the account associated with the given address when it's unlocked.
func (s *PrivateAccountAPI) LockAccount(addr common.Address) bool { func (s *PersonalAccountAPI) LockAccount(addr common.Address) bool {
return fetchKeystore(s.am).Lock(addr) == nil return fetchKeystore(s.am).Lock(addr) == nil
} }
// signTransactions sets defaults and signs the given transaction // signTransactions sets defaults and signs the given transaction
// NOTE: the caller needs to ensure that the nonceLock is held, if applicable, // NOTE: the caller needs to ensure that the nonceLock is held, if applicable,
// and release it after the transaction has been submitted to the tx pool // and release it after the transaction has been submitted to the tx pool
func (s *PrivateAccountAPI) signTransaction(ctx context.Context, args *TransactionArgs, passwd string) (*types.Transaction, error) { func (s *PersonalAccountAPI) signTransaction(ctx context.Context, args *TransactionArgs, passwd string) (*types.Transaction, error) {
// Look up the wallet containing the requested signer // Look up the wallet containing the requested signer
account := accounts.Account{Address: args.from()} account := accounts.Account{Address: args.from()}
wallet, err := s.am.Find(account) wallet, err := s.am.Find(account)
@ -455,7 +455,7 @@ func (s *PrivateAccountAPI) signTransaction(ctx context.Context, args *Transacti
// SendTransaction will create a transaction from the given arguments and // SendTransaction will create a transaction from the given arguments and
// tries to sign it with the key associated with args.From. If the given // tries to sign it with the key associated with args.From. If the given
// passwd isn't able to decrypt the key it fails. // passwd isn't able to decrypt the key it fails.
func (s *PrivateAccountAPI) SendTransaction(ctx context.Context, args TransactionArgs, passwd string) (common.Hash, error) { func (s *PersonalAccountAPI) SendTransaction(ctx context.Context, args TransactionArgs, passwd string) (common.Hash, error) {
if args.Nonce == nil { if args.Nonce == nil {
// Hold the addresse's mutex around signing to prevent concurrent assignment of // Hold the addresse's mutex around signing to prevent concurrent assignment of
// the same nonce to multiple accounts. // the same nonce to multiple accounts.
@ -474,7 +474,7 @@ func (s *PrivateAccountAPI) SendTransaction(ctx context.Context, args Transactio
// tries to sign it with the key associated with args.To. If the given passwd isn't // tries to sign it with the key associated with args.To. If the given passwd isn't
// able to decrypt the key it fails. The transaction is returned in RLP-form, not broadcast // able to decrypt the key it fails. The transaction is returned in RLP-form, not broadcast
// to other nodes // to other nodes
func (s *PrivateAccountAPI) SignTransaction(ctx context.Context, args TransactionArgs, passwd string) (*SignTransactionResult, error) { func (s *PersonalAccountAPI) SignTransaction(ctx context.Context, args TransactionArgs, passwd string) (*SignTransactionResult, error) {
// No need to obtain the noncelock mutex, since we won't be sending this // No need to obtain the noncelock mutex, since we won't be sending this
// tx into the transaction pool, but right back to the user // tx into the transaction pool, but right back to the user
if args.From == nil { if args.From == nil {
@ -515,7 +515,7 @@ func (s *PrivateAccountAPI) SignTransaction(ctx context.Context, args Transactio
// The key used to calculate the signature is decrypted with the given password. // The key used to calculate the signature is decrypted with the given password.
// //
// https://github.com/XinFinOrg/XDPoSChain/wiki/Management-APIs#personal_sign // https://github.com/XinFinOrg/XDPoSChain/wiki/Management-APIs#personal_sign
func (s *PrivateAccountAPI) Sign(ctx context.Context, data hexutil.Bytes, addr common.Address, passwd string) (hexutil.Bytes, error) { func (s *PersonalAccountAPI) Sign(ctx context.Context, data hexutil.Bytes, addr common.Address, passwd string) (hexutil.Bytes, error) {
// Look up the wallet containing the requested signer // Look up the wallet containing the requested signer
account := accounts.Account{Address: addr} account := accounts.Account{Address: addr}
@ -542,7 +542,7 @@ func (s *PrivateAccountAPI) Sign(ctx context.Context, data hexutil.Bytes, addr c
// the V value must be be 27 or 28 for legacy reasons. // the V value must be be 27 or 28 for legacy reasons.
// //
// https://github.com/XinFinOrg/XDPoSChain/wiki/Management-APIs#personal_ecRecover // https://github.com/XinFinOrg/XDPoSChain/wiki/Management-APIs#personal_ecRecover
func (s *PrivateAccountAPI) EcRecover(ctx context.Context, data, sig hexutil.Bytes) (common.Address, error) { func (s *PersonalAccountAPI) EcRecover(ctx context.Context, data, sig hexutil.Bytes) (common.Address, error) {
if len(sig) != crypto.SignatureLength { if len(sig) != crypto.SignatureLength {
return common.Address{}, fmt.Errorf("signature must be %d bytes long", crypto.SignatureLength) return common.Address{}, fmt.Errorf("signature must be %d bytes long", crypto.SignatureLength)
} }
@ -560,40 +560,39 @@ func (s *PrivateAccountAPI) EcRecover(ctx context.Context, data, sig hexutil.Byt
// SignAndSendTransaction was renamed to SendTransaction. This method is deprecated // SignAndSendTransaction was renamed to SendTransaction. This method is deprecated
// and will be removed in the future. It primary goal is to give clients time to update. // and will be removed in the future. It primary goal is to give clients time to update.
func (s *PrivateAccountAPI) SignAndSendTransaction(ctx context.Context, args TransactionArgs, passwd string) (common.Hash, error) { func (s *PersonalAccountAPI) SignAndSendTransaction(ctx context.Context, args TransactionArgs, passwd string) (common.Hash, error) {
return s.SendTransaction(ctx, args, passwd) return s.SendTransaction(ctx, args, passwd)
} }
// PublicBlockChainAPI provides an API to access the Ethereum blockchain. // BlockChainAPI provides an API to access Ethereum blockchain data.
// It offers only methods that operate on public data that is freely available to anyone. type BlockChainAPI struct {
type PublicBlockChainAPI struct {
b Backend b Backend
chainReader consensus.ChainReader chainReader consensus.ChainReader
} }
// NewPublicBlockChainAPI creates a new Ethereum blockchain API. // NewBlockChainAPI creates a new Ethereum blockchain API.
func NewPublicBlockChainAPI(b Backend, chainReader consensus.ChainReader) *PublicBlockChainAPI { func NewBlockChainAPI(b Backend, chainReader consensus.ChainReader) *BlockChainAPI {
return &PublicBlockChainAPI{ return &BlockChainAPI{
b, b,
chainReader, chainReader,
} }
} }
// BlockNumber returns the block number of the chain head. // BlockNumber returns the block number of the chain head.
func (s *PublicBlockChainAPI) BlockNumber() hexutil.Uint64 { func (s *BlockChainAPI) BlockNumber() hexutil.Uint64 {
header, _ := s.b.HeaderByNumber(context.Background(), rpc.LatestBlockNumber) // latest header should always be available header, _ := s.b.HeaderByNumber(context.Background(), rpc.LatestBlockNumber) // latest header should always be available
return hexutil.Uint64(header.Number.Uint64()) return hexutil.Uint64(header.Number.Uint64())
} }
// BlockNumber returns the block number of the chain head. // BlockNumber returns the block number of the chain head.
func (s *PublicBlockChainAPI) GetRewardByHash(hash common.Hash) map[string]map[string]map[string]*big.Int { func (s *BlockChainAPI) GetRewardByHash(hash common.Hash) map[string]map[string]map[string]*big.Int {
return s.b.GetRewardByHash(hash) return s.b.GetRewardByHash(hash)
} }
// GetBalance returns the amount of wei for the given address in the state of the // GetBalance returns the amount of wei for the given address in the state of the
// given block number. The rpc.LatestBlockNumber and rpc.PendingBlockNumber meta // given block number. The rpc.LatestBlockNumber and rpc.PendingBlockNumber meta
// block numbers are also allowed. // block numbers are also allowed.
func (s *PublicBlockChainAPI) GetBalance(ctx context.Context, address common.Address, blockNrOrHash rpc.BlockNumberOrHash) (*hexutil.Big, error) { func (s *BlockChainAPI) GetBalance(ctx context.Context, address common.Address, blockNrOrHash rpc.BlockNumberOrHash) (*hexutil.Big, error) {
state, _, err := s.b.StateAndHeaderByNumberOrHash(ctx, blockNrOrHash) state, _, err := s.b.StateAndHeaderByNumberOrHash(ctx, blockNrOrHash)
if state == nil || err != nil { if state == nil || err != nil {
return nil, err return nil, err
@ -602,7 +601,7 @@ func (s *PublicBlockChainAPI) GetBalance(ctx context.Context, address common.Add
} }
// GetTransactionAndReceiptProof returns the Trie transaction and receipt proof of the given transaction hash. // GetTransactionAndReceiptProof returns the Trie transaction and receipt proof of the given transaction hash.
func (s *PublicBlockChainAPI) GetTransactionAndReceiptProof(ctx context.Context, hash common.Hash) (map[string]interface{}, error) { func (s *BlockChainAPI) GetTransactionAndReceiptProof(ctx context.Context, hash common.Hash) (map[string]interface{}, error) {
tx, blockHash, _, index := rawdb.ReadTransaction(s.b.ChainDb(), hash) tx, blockHash, _, index := rawdb.ReadTransaction(s.b.ChainDb(), hash)
if tx == nil { if tx == nil {
return nil, nil return nil, nil
@ -646,7 +645,7 @@ func (s *PublicBlockChainAPI) GetTransactionAndReceiptProof(ctx context.Context,
// GetBlockByNumber returns the requested block. When blockNr is -1 the chain head is returned. When fullTx is true all // GetBlockByNumber returns the requested block. When blockNr is -1 the chain head is returned. When fullTx is true all
// transactions in the block are returned in full detail, otherwise only the transaction hash is returned. // transactions in the block are returned in full detail, otherwise only the transaction hash is returned.
func (s *PublicBlockChainAPI) GetBlockByNumber(ctx context.Context, blockNr rpc.BlockNumber, fullTx bool) (map[string]interface{}, error) { func (s *BlockChainAPI) GetBlockByNumber(ctx context.Context, blockNr rpc.BlockNumber, fullTx bool) (map[string]interface{}, error) {
block, err := s.b.BlockByNumber(ctx, blockNr) block, err := s.b.BlockByNumber(ctx, blockNr)
if block != nil { if block != nil {
response, err := s.rpcOutputBlock(block, true, fullTx, ctx) response, err := s.rpcOutputBlock(block, true, fullTx, ctx)
@ -663,7 +662,7 @@ func (s *PublicBlockChainAPI) GetBlockByNumber(ctx context.Context, blockNr rpc.
// GetBlockByHash returns the requested block. When fullTx is true all transactions in the block are returned in full // GetBlockByHash returns the requested block. When fullTx is true all transactions in the block are returned in full
// detail, otherwise only the transaction hash is returned. // detail, otherwise only the transaction hash is returned.
func (s *PublicBlockChainAPI) GetBlockByHash(ctx context.Context, blockHash common.Hash, fullTx bool) (map[string]interface{}, error) { func (s *BlockChainAPI) GetBlockByHash(ctx context.Context, blockHash common.Hash, fullTx bool) (map[string]interface{}, error) {
block, err := s.b.GetBlock(ctx, blockHash) block, err := s.b.GetBlock(ctx, blockHash)
if block != nil { if block != nil {
return s.rpcOutputBlock(block, true, fullTx, ctx) return s.rpcOutputBlock(block, true, fullTx, ctx)
@ -673,7 +672,7 @@ func (s *PublicBlockChainAPI) GetBlockByHash(ctx context.Context, blockHash comm
// GetUncleByBlockNumberAndIndex returns the uncle block for the given block hash and index. When fullTx is true // GetUncleByBlockNumberAndIndex returns the uncle block for the given block hash and index. When fullTx is true
// all transactions in the block are returned in full detail, otherwise only the transaction hash is returned. // all transactions in the block are returned in full detail, otherwise only the transaction hash is returned.
func (s *PublicBlockChainAPI) GetUncleByBlockNumberAndIndex(ctx context.Context, blockNr rpc.BlockNumber, index hexutil.Uint) (map[string]interface{}, error) { func (s *BlockChainAPI) GetUncleByBlockNumberAndIndex(ctx context.Context, blockNr rpc.BlockNumber, index hexutil.Uint) (map[string]interface{}, error) {
block, err := s.b.BlockByNumber(ctx, blockNr) block, err := s.b.BlockByNumber(ctx, blockNr)
if block != nil { if block != nil {
uncles := block.Uncles() uncles := block.Uncles()
@ -690,7 +689,7 @@ func (s *PublicBlockChainAPI) GetUncleByBlockNumberAndIndex(ctx context.Context,
// GetUncleByBlockHashAndIndex returns the uncle block for the given block hash and index. When fullTx is true // GetUncleByBlockHashAndIndex returns the uncle block for the given block hash and index. When fullTx is true
// all transactions in the block are returned in full detail, otherwise only the transaction hash is returned. // all transactions in the block are returned in full detail, otherwise only the transaction hash is returned.
// DEPRECATED SINCE 1.0 // DEPRECATED SINCE 1.0
func (s *PublicBlockChainAPI) GetUncleByBlockHashAndIndex(ctx context.Context, blockHash common.Hash, index hexutil.Uint) (map[string]interface{}, error) { func (s *BlockChainAPI) GetUncleByBlockHashAndIndex(ctx context.Context, blockHash common.Hash, index hexutil.Uint) (map[string]interface{}, error) {
block, err := s.b.GetBlock(ctx, blockHash) block, err := s.b.GetBlock(ctx, blockHash)
if block != nil { if block != nil {
uncles := block.Uncles() uncles := block.Uncles()
@ -706,7 +705,7 @@ func (s *PublicBlockChainAPI) GetUncleByBlockHashAndIndex(ctx context.Context, b
// GetUncleCountByBlockNumber returns number of uncles in the block for the given block number // GetUncleCountByBlockNumber returns number of uncles in the block for the given block number
// DEPRECATED SINCE 1.0 // DEPRECATED SINCE 1.0
func (s *PublicBlockChainAPI) GetUncleCountByBlockNumber(ctx context.Context, blockNr rpc.BlockNumber) *hexutil.Uint { func (s *BlockChainAPI) GetUncleCountByBlockNumber(ctx context.Context, blockNr rpc.BlockNumber) *hexutil.Uint {
if block, _ := s.b.BlockByNumber(ctx, blockNr); block != nil { if block, _ := s.b.BlockByNumber(ctx, blockNr); block != nil {
n := hexutil.Uint(len(block.Uncles())) n := hexutil.Uint(len(block.Uncles()))
return &n return &n
@ -716,7 +715,7 @@ func (s *PublicBlockChainAPI) GetUncleCountByBlockNumber(ctx context.Context, bl
// GetUncleCountByBlockHash returns number of uncles in the block for the given block hash // GetUncleCountByBlockHash returns number of uncles in the block for the given block hash
// DEPRECATED SINCE 1.0 // DEPRECATED SINCE 1.0
func (s *PublicBlockChainAPI) GetUncleCountByBlockHash(ctx context.Context, blockHash common.Hash) *hexutil.Uint { func (s *BlockChainAPI) GetUncleCountByBlockHash(ctx context.Context, blockHash common.Hash) *hexutil.Uint {
if block, _ := s.b.GetBlock(ctx, blockHash); block != nil { if block, _ := s.b.GetBlock(ctx, blockHash); block != nil {
n := hexutil.Uint(len(block.Uncles())) n := hexutil.Uint(len(block.Uncles()))
return &n return &n
@ -725,7 +724,7 @@ func (s *PublicBlockChainAPI) GetUncleCountByBlockHash(ctx context.Context, bloc
} }
// GetCode returns the code stored at the given address in the state for the given block number. // GetCode returns the code stored at the given address in the state for the given block number.
func (s *PublicBlockChainAPI) GetCode(ctx context.Context, address common.Address, blockNrOrHash rpc.BlockNumberOrHash) (hexutil.Bytes, error) { func (s *BlockChainAPI) GetCode(ctx context.Context, address common.Address, blockNrOrHash rpc.BlockNumberOrHash) (hexutil.Bytes, error) {
state, _, err := s.b.StateAndHeaderByNumberOrHash(ctx, blockNrOrHash) state, _, err := s.b.StateAndHeaderByNumberOrHash(ctx, blockNrOrHash)
if state == nil || err != nil { if state == nil || err != nil {
return nil, err return nil, err
@ -735,7 +734,7 @@ func (s *PublicBlockChainAPI) GetCode(ctx context.Context, address common.Addres
} }
// GetAccountInfo returns the information at the given address in the state for the given block number. // GetAccountInfo returns the information at the given address in the state for the given block number.
func (s *PublicBlockChainAPI) GetAccountInfo(ctx context.Context, address common.Address, blockNrOrHash rpc.BlockNumberOrHash) (map[string]interface{}, error) { func (s *BlockChainAPI) GetAccountInfo(ctx context.Context, address common.Address, blockNrOrHash rpc.BlockNumberOrHash) (map[string]interface{}, error) {
state, _, err := s.b.StateAndHeaderByNumberOrHash(ctx, blockNrOrHash) state, _, err := s.b.StateAndHeaderByNumberOrHash(ctx, blockNrOrHash)
if state == nil || err != nil { if state == nil || err != nil {
return nil, err return nil, err
@ -755,7 +754,7 @@ func (s *PublicBlockChainAPI) GetAccountInfo(ctx context.Context, address common
// GetStorageAt returns the storage from the state at the given address, key and // GetStorageAt returns the storage from the state at the given address, key and
// block number. The rpc.LatestBlockNumber and rpc.PendingBlockNumber meta block // block number. The rpc.LatestBlockNumber and rpc.PendingBlockNumber meta block
// numbers are also allowed. // numbers are also allowed.
func (s *PublicBlockChainAPI) GetStorageAt(ctx context.Context, address common.Address, key string, blockNrOrHash rpc.BlockNumberOrHash) (hexutil.Bytes, error) { func (s *BlockChainAPI) GetStorageAt(ctx context.Context, address common.Address, key string, blockNrOrHash rpc.BlockNumberOrHash) (hexutil.Bytes, error) {
state, _, err := s.b.StateAndHeaderByNumberOrHash(ctx, blockNrOrHash) state, _, err := s.b.StateAndHeaderByNumberOrHash(ctx, blockNrOrHash)
if state == nil || err != nil { if state == nil || err != nil {
return nil, err return nil, err
@ -765,7 +764,7 @@ func (s *PublicBlockChainAPI) GetStorageAt(ctx context.Context, address common.A
} }
// GetBlockReceipts returns the block receipts for the given block hash or number or tag. // GetBlockReceipts returns the block receipts for the given block hash or number or tag.
func (s *PublicBlockChainAPI) GetBlockReceipts(ctx context.Context, blockNrOrHash rpc.BlockNumberOrHash) ([]map[string]interface{}, error) { func (s *BlockChainAPI) GetBlockReceipts(ctx context.Context, blockNrOrHash rpc.BlockNumberOrHash) ([]map[string]interface{}, error) {
block, err := s.b.BlockByNumberOrHash(ctx, blockNrOrHash) block, err := s.b.BlockByNumberOrHash(ctx, blockNrOrHash)
if block == nil || err != nil { if block == nil || err != nil {
// When the block doesn't exist, the RPC method should return JSON null // When the block doesn't exist, the RPC method should return JSON null
@ -844,7 +843,7 @@ func (diff *StateOverride) Apply(state *state.StateDB) error {
return nil return nil
} }
func (s *PublicBlockChainAPI) GetBlockSignersByHash(ctx context.Context, blockHash common.Hash) ([]common.Address, error) { func (s *BlockChainAPI) GetBlockSignersByHash(ctx context.Context, blockHash common.Hash) ([]common.Address, error) {
block, err := s.b.GetBlock(ctx, blockHash) block, err := s.b.GetBlock(ctx, blockHash)
if err != nil || block == nil { if err != nil || block == nil {
return []common.Address{}, err return []common.Address{}, err
@ -857,7 +856,7 @@ func (s *PublicBlockChainAPI) GetBlockSignersByHash(ctx context.Context, blockHa
return s.rpcOutputBlockSigners(block, ctx, masternodes) return s.rpcOutputBlockSigners(block, ctx, masternodes)
} }
func (s *PublicBlockChainAPI) GetBlockSignersByNumber(ctx context.Context, blockNumber rpc.BlockNumber) ([]common.Address, error) { func (s *BlockChainAPI) GetBlockSignersByNumber(ctx context.Context, blockNumber rpc.BlockNumber) ([]common.Address, error) {
block, err := s.b.BlockByNumber(ctx, blockNumber) block, err := s.b.BlockByNumber(ctx, blockNumber)
if err != nil || block == nil { if err != nil || block == nil {
return []common.Address{}, err return []common.Address{}, err
@ -870,7 +869,7 @@ func (s *PublicBlockChainAPI) GetBlockSignersByNumber(ctx context.Context, block
return s.rpcOutputBlockSigners(block, ctx, masternodes) return s.rpcOutputBlockSigners(block, ctx, masternodes)
} }
func (s *PublicBlockChainAPI) GetBlockFinalityByHash(ctx context.Context, blockHash common.Hash) (uint, error) { func (s *BlockChainAPI) GetBlockFinalityByHash(ctx context.Context, blockHash common.Hash) (uint, error) {
block, err := s.b.GetBlock(ctx, blockHash) block, err := s.b.GetBlock(ctx, blockHash)
if err != nil || block == nil { if err != nil || block == nil {
return uint(0), err return uint(0), err
@ -883,7 +882,7 @@ func (s *PublicBlockChainAPI) GetBlockFinalityByHash(ctx context.Context, blockH
return s.findFinalityOfBlock(ctx, block, masternodes) return s.findFinalityOfBlock(ctx, block, masternodes)
} }
func (s *PublicBlockChainAPI) GetBlockFinalityByNumber(ctx context.Context, blockNumber rpc.BlockNumber) (uint, error) { func (s *BlockChainAPI) GetBlockFinalityByNumber(ctx context.Context, blockNumber rpc.BlockNumber) (uint, error) {
block, err := s.b.BlockByNumber(ctx, blockNumber) block, err := s.b.BlockByNumber(ctx, blockNumber)
if err != nil || block == nil { if err != nil || block == nil {
return uint(0), err return uint(0), err
@ -897,7 +896,7 @@ func (s *PublicBlockChainAPI) GetBlockFinalityByNumber(ctx context.Context, bloc
} }
// GetMasternodes returns masternodes set at the starting block of epoch of the given block // GetMasternodes returns masternodes set at the starting block of epoch of the given block
func (s *PublicBlockChainAPI) GetMasternodes(ctx context.Context, b *types.Block) ([]common.Address, error) { func (s *BlockChainAPI) GetMasternodes(ctx context.Context, b *types.Block) ([]common.Address, error) {
var masternodes []common.Address var masternodes []common.Address
if b.Number().Int64() >= 0 { if b.Number().Int64() >= 0 {
curBlockNumber := b.Number().Uint64() curBlockNumber := b.Number().Uint64()
@ -917,7 +916,7 @@ func (s *PublicBlockChainAPI) GetMasternodes(ctx context.Context, b *types.Block
} }
// GetCandidateStatus returns status of the given candidate at a specified epochNumber // GetCandidateStatus returns status of the given candidate at a specified epochNumber
func (s *PublicBlockChainAPI) GetCandidateStatus(ctx context.Context, coinbaseAddress common.Address, epoch rpc.EpochNumber) (map[string]interface{}, error) { func (s *BlockChainAPI) GetCandidateStatus(ctx context.Context, coinbaseAddress common.Address, epoch rpc.EpochNumber) (map[string]interface{}, error) {
var ( var (
block *types.Block block *types.Block
header *types.Header header *types.Header
@ -1080,7 +1079,7 @@ func (s *PublicBlockChainAPI) GetCandidateStatus(ctx context.Context, coinbaseAd
} }
// GetCandidates returns status of all candidates at a specified epochNumber // GetCandidates returns status of all candidates at a specified epochNumber
func (s *PublicBlockChainAPI) GetCandidates(ctx context.Context, epoch rpc.EpochNumber) (map[string]interface{}, error) { func (s *BlockChainAPI) GetCandidates(ctx context.Context, epoch rpc.EpochNumber) (map[string]interface{}, error) {
var ( var (
block *types.Block block *types.Block
header *types.Header header *types.Header
@ -1246,7 +1245,7 @@ func (s *PublicBlockChainAPI) GetCandidates(ctx context.Context, epoch rpc.Epoch
} }
// GetCheckpointFromEpoch returns header of the previous checkpoint // GetCheckpointFromEpoch returns header of the previous checkpoint
func (s *PublicBlockChainAPI) GetCheckpointFromEpoch(ctx context.Context, epochNum rpc.EpochNumber) (rpc.BlockNumber, rpc.EpochNumber) { func (s *BlockChainAPI) GetCheckpointFromEpoch(ctx context.Context, epochNum rpc.EpochNumber) (rpc.BlockNumber, rpc.EpochNumber) {
var checkpointNumber uint64 var checkpointNumber uint64
epoch := s.b.ChainConfig().XDPoS.Epoch epoch := s.b.ChainConfig().XDPoS.Epoch
@ -1274,7 +1273,7 @@ func (s *PublicBlockChainAPI) GetCheckpointFromEpoch(ctx context.Context, epochN
} }
// getCandidatesFromSmartContract returns all candidates with their capacities at the current time // getCandidatesFromSmartContract returns all candidates with their capacities at the current time
func (s *PublicBlockChainAPI) getCandidatesFromSmartContract() ([]utils.Masternode, error) { func (s *BlockChainAPI) getCandidatesFromSmartContract() ([]utils.Masternode, error) {
client, err := s.b.GetIPCClient() client, err := s.b.GetIPCClient()
if err != nil { if err != nil {
return []utils.Masternode{}, err return []utils.Masternode{}, err
@ -1420,7 +1419,7 @@ func (e *revertError) ErrorData() interface{} {
// Call executes the given transaction on the state for the given block number. // Call executes the given transaction on the state for the given block number.
// It doesn't make and changes in the state/blockchain and is useful to execute and retrieve values. // It doesn't make and changes in the state/blockchain and is useful to execute and retrieve values.
func (s *PublicBlockChainAPI) Call(ctx context.Context, args TransactionArgs, blockNrOrHash *rpc.BlockNumberOrHash, overrides *StateOverride) (hexutil.Bytes, error) { func (s *BlockChainAPI) Call(ctx context.Context, args TransactionArgs, blockNrOrHash *rpc.BlockNumberOrHash, overrides *StateOverride) (hexutil.Bytes, error) {
if blockNrOrHash == nil { if blockNrOrHash == nil {
latest := rpc.BlockNumberOrHashWithNumber(rpc.LatestBlockNumber) latest := rpc.BlockNumberOrHashWithNumber(rpc.LatestBlockNumber)
blockNrOrHash = &latest blockNrOrHash = &latest
@ -1566,7 +1565,7 @@ func DoEstimateGas(ctx context.Context, b Backend, args TransactionArgs, blockNr
// EstimateGas returns an estimate of the amount of gas needed to execute the // EstimateGas returns an estimate of the amount of gas needed to execute the
// given transaction against the current pending block. // given transaction against the current pending block.
func (s *PublicBlockChainAPI) EstimateGas(ctx context.Context, args TransactionArgs, blockNrOrHash *rpc.BlockNumberOrHash, overrides *StateOverride) (hexutil.Uint64, error) { func (s *BlockChainAPI) EstimateGas(ctx context.Context, args TransactionArgs, blockNrOrHash *rpc.BlockNumberOrHash, overrides *StateOverride) (hexutil.Uint64, error) {
bNrOrHash := rpc.BlockNumberOrHashWithNumber(rpc.LatestBlockNumber) bNrOrHash := rpc.BlockNumberOrHashWithNumber(rpc.LatestBlockNumber)
if blockNrOrHash != nil { if blockNrOrHash != nil {
bNrOrHash = *blockNrOrHash bNrOrHash = *blockNrOrHash
@ -1670,7 +1669,7 @@ func RPCMarshalHeader(head *types.Header) map[string]interface{} {
// rpcOutputBlock converts the given block to the RPC output which depends on fullTx. If inclTx is true transactions are // rpcOutputBlock converts the given block to the RPC output which depends on fullTx. If inclTx is true transactions are
// returned. When fullTx is true the returned block contains full transaction details, otherwise it will only contain // returned. When fullTx is true the returned block contains full transaction details, otherwise it will only contain
// transaction hashes. // transaction hashes.
func (s *PublicBlockChainAPI) rpcOutputBlock(b *types.Block, inclTx bool, fullTx bool, ctx context.Context) (map[string]interface{}, error) { func (s *BlockChainAPI) rpcOutputBlock(b *types.Block, inclTx bool, fullTx bool, ctx context.Context) (map[string]interface{}, error) {
fields := RPCMarshalHeader(b.Header()) fields := RPCMarshalHeader(b.Header())
fields["size"] = hexutil.Uint64(b.Size()) fields["size"] = hexutil.Uint64(b.Size())
fields["totalDifficulty"] = (*hexutil.Big)(s.b.GetTd(context.Background(), b.Hash())) fields["totalDifficulty"] = (*hexutil.Big)(s.b.GetTd(context.Background(), b.Hash()))
@ -1707,7 +1706,7 @@ func (s *PublicBlockChainAPI) rpcOutputBlock(b *types.Block, inclTx bool, fullTx
} }
// findNearestSignedBlock finds the nearest checkpoint from input block // findNearestSignedBlock finds the nearest checkpoint from input block
func (s *PublicBlockChainAPI) findNearestSignedBlock(ctx context.Context, b *types.Block) *types.Block { func (s *BlockChainAPI) findNearestSignedBlock(ctx context.Context, b *types.Block) *types.Block {
if b.Number().Int64() <= 0 { if b.Number().Int64() <= 0 {
return nil return nil
} }
@ -1740,7 +1739,7 @@ func (s *PublicBlockChainAPI) findNearestSignedBlock(ctx context.Context, b *typ
findFinalityOfBlock return finality of a block findFinalityOfBlock return finality of a block
Use blocksHashCache for to keep track - refer core/blockchain.go for more detail Use blocksHashCache for to keep track - refer core/blockchain.go for more detail
*/ */
func (s *PublicBlockChainAPI) findFinalityOfBlock(ctx context.Context, b *types.Block, masternodes []common.Address) (uint, error) { func (s *BlockChainAPI) findFinalityOfBlock(ctx context.Context, b *types.Block, masternodes []common.Address) (uint, error) {
engine, _ := s.b.Engine().(*XDPoS.XDPoS) engine, _ := s.b.Engine().(*XDPoS.XDPoS)
signedBlock := s.findNearestSignedBlock(ctx, b) signedBlock := s.findNearestSignedBlock(ctx, b)
@ -1805,7 +1804,7 @@ func (s *PublicBlockChainAPI) findFinalityOfBlock(ctx context.Context, b *types.
/* /*
Extract signers from block Extract signers from block
*/ */
func (s *PublicBlockChainAPI) getSigners(ctx context.Context, block *types.Block, engine *XDPoS.XDPoS) ([]common.Address, error) { func (s *BlockChainAPI) getSigners(ctx context.Context, block *types.Block, engine *XDPoS.XDPoS) ([]common.Address, error) {
var err error var err error
var filterSigners []common.Address var filterSigners []common.Address
var signers []common.Address var signers []common.Address
@ -1833,7 +1832,7 @@ func (s *PublicBlockChainAPI) getSigners(ctx context.Context, block *types.Block
return filterSigners, nil return filterSigners, nil
} }
func (s *PublicBlockChainAPI) rpcOutputBlockSigners(b *types.Block, ctx context.Context, masternodes []common.Address) ([]common.Address, error) { func (s *BlockChainAPI) rpcOutputBlockSigners(b *types.Block, ctx context.Context, masternodes []common.Address) ([]common.Address, error) {
_, err := s.b.GetIPCClient() _, err := s.b.GetIPCClient()
if err != nil { if err != nil {
log.Error("Fail to connect IPC client for block status", "error", err) log.Error("Fail to connect IPC client for block status", "error", err)
@ -1987,7 +1986,7 @@ type accessListResult struct {
// CreateAccessList creates a EIP-2930 type AccessList for the given transaction. // CreateAccessList creates a EIP-2930 type AccessList for the given transaction.
// Reexec and BlockNrOrHash can be specified to create the accessList on top of a certain state. // Reexec and BlockNrOrHash can be specified to create the accessList on top of a certain state.
func (s *PublicBlockChainAPI) CreateAccessList(ctx context.Context, args TransactionArgs, blockNrOrHash *rpc.BlockNumberOrHash) (*accessListResult, error) { func (s *BlockChainAPI) CreateAccessList(ctx context.Context, args TransactionArgs, blockNrOrHash *rpc.BlockNumberOrHash) (*accessListResult, error) {
bNrOrHash := rpc.BlockNumberOrHashWithNumber(rpc.PendingBlockNumber) bNrOrHash := rpc.BlockNumberOrHashWithNumber(rpc.PendingBlockNumber)
if blockNrOrHash != nil { if blockNrOrHash != nil {
bNrOrHash = *blockNrOrHash bNrOrHash = *blockNrOrHash
@ -2087,8 +2086,8 @@ func AccessList(ctx context.Context, b Backend, blockNrOrHash rpc.BlockNumberOrH
} }
} }
// PublicTransactionPoolAPI exposes methods for the RPC interface // TransactionAPI exposes methods for reading and creating transaction data.
type PublicTransactionPoolAPI struct { type TransactionAPI struct {
b Backend b Backend
nonceLock *AddrLocker nonceLock *AddrLocker
signer types.Signer signer types.Signer
@ -2100,12 +2099,12 @@ type PublicXDCXTransactionPoolAPI struct {
nonceLock *AddrLocker nonceLock *AddrLocker
} }
// NewPublicTransactionPoolAPI creates a new RPC service with methods specific for the transaction pool. // NewTransactionAPI creates a new RPC service with methods specific for the transaction pool.
func NewPublicTransactionPoolAPI(b Backend, nonceLock *AddrLocker) *PublicTransactionPoolAPI { func NewTransactionAPI(b Backend, nonceLock *AddrLocker) *TransactionAPI {
// The signer used by the API should always be the 'latest' known one because we expect // The signer used by the API should always be the 'latest' known one because we expect
// signers to be backwards-compatible with old transactions. // signers to be backwards-compatible with old transactions.
signer := types.LatestSigner(b.ChainConfig()) signer := types.LatestSigner(b.ChainConfig())
return &PublicTransactionPoolAPI{b, nonceLock, signer} return &TransactionAPI{b, nonceLock, signer}
} }
// NewPublicTransactionPoolAPI creates a new RPC service with methods specific for the transaction pool. // NewPublicTransactionPoolAPI creates a new RPC service with methods specific for the transaction pool.
@ -2114,7 +2113,7 @@ func NewPublicXDCXTransactionPoolAPI(b Backend, nonceLock *AddrLocker) *PublicXD
} }
// GetBlockTransactionCountByNumber returns the number of transactions in the block with the given block number. // GetBlockTransactionCountByNumber returns the number of transactions in the block with the given block number.
func (s *PublicTransactionPoolAPI) GetBlockTransactionCountByNumber(ctx context.Context, blockNr rpc.BlockNumber) *hexutil.Uint { func (s *TransactionAPI) GetBlockTransactionCountByNumber(ctx context.Context, blockNr rpc.BlockNumber) *hexutil.Uint {
if block, _ := s.b.BlockByNumber(ctx, blockNr); block != nil { if block, _ := s.b.BlockByNumber(ctx, blockNr); block != nil {
n := hexutil.Uint(len(block.Transactions())) n := hexutil.Uint(len(block.Transactions()))
return &n return &n
@ -2123,7 +2122,7 @@ func (s *PublicTransactionPoolAPI) GetBlockTransactionCountByNumber(ctx context.
} }
// GetBlockTransactionCountByHash returns the number of transactions in the block with the given hash. // GetBlockTransactionCountByHash returns the number of transactions in the block with the given hash.
func (s *PublicTransactionPoolAPI) GetBlockTransactionCountByHash(ctx context.Context, blockHash common.Hash) *hexutil.Uint { func (s *TransactionAPI) GetBlockTransactionCountByHash(ctx context.Context, blockHash common.Hash) *hexutil.Uint {
if block, _ := s.b.GetBlock(ctx, blockHash); block != nil { if block, _ := s.b.GetBlock(ctx, blockHash); block != nil {
n := hexutil.Uint(len(block.Transactions())) n := hexutil.Uint(len(block.Transactions()))
return &n return &n
@ -2132,7 +2131,7 @@ func (s *PublicTransactionPoolAPI) GetBlockTransactionCountByHash(ctx context.Co
} }
// GetTransactionByBlockNumberAndIndex returns the transaction for the given block number and index. // GetTransactionByBlockNumberAndIndex returns the transaction for the given block number and index.
func (s *PublicTransactionPoolAPI) GetTransactionByBlockNumberAndIndex(ctx context.Context, blockNr rpc.BlockNumber, index hexutil.Uint) *RPCTransaction { func (s *TransactionAPI) GetTransactionByBlockNumberAndIndex(ctx context.Context, blockNr rpc.BlockNumber, index hexutil.Uint) *RPCTransaction {
if block, _ := s.b.BlockByNumber(ctx, blockNr); block != nil { if block, _ := s.b.BlockByNumber(ctx, blockNr); block != nil {
return newRPCTransactionFromBlockIndex(block, uint64(index)) return newRPCTransactionFromBlockIndex(block, uint64(index))
} }
@ -2140,7 +2139,7 @@ func (s *PublicTransactionPoolAPI) GetTransactionByBlockNumberAndIndex(ctx conte
} }
// GetTransactionByBlockHashAndIndex returns the transaction for the given block hash and index. // GetTransactionByBlockHashAndIndex returns the transaction for the given block hash and index.
func (s *PublicTransactionPoolAPI) GetTransactionByBlockHashAndIndex(ctx context.Context, blockHash common.Hash, index hexutil.Uint) *RPCTransaction { func (s *TransactionAPI) GetTransactionByBlockHashAndIndex(ctx context.Context, blockHash common.Hash, index hexutil.Uint) *RPCTransaction {
if block, _ := s.b.GetBlock(ctx, blockHash); block != nil { if block, _ := s.b.GetBlock(ctx, blockHash); block != nil {
return newRPCTransactionFromBlockIndex(block, uint64(index)) return newRPCTransactionFromBlockIndex(block, uint64(index))
} }
@ -2148,7 +2147,7 @@ func (s *PublicTransactionPoolAPI) GetTransactionByBlockHashAndIndex(ctx context
} }
// GetRawTransactionByBlockNumberAndIndex returns the bytes of the transaction for the given block number and index. // GetRawTransactionByBlockNumberAndIndex returns the bytes of the transaction for the given block number and index.
func (s *PublicTransactionPoolAPI) GetRawTransactionByBlockNumberAndIndex(ctx context.Context, blockNr rpc.BlockNumber, index hexutil.Uint) hexutil.Bytes { func (s *TransactionAPI) GetRawTransactionByBlockNumberAndIndex(ctx context.Context, blockNr rpc.BlockNumber, index hexutil.Uint) hexutil.Bytes {
if block, _ := s.b.BlockByNumber(ctx, blockNr); block != nil { if block, _ := s.b.BlockByNumber(ctx, blockNr); block != nil {
return newRPCRawTransactionFromBlockIndex(block, uint64(index)) return newRPCRawTransactionFromBlockIndex(block, uint64(index))
} }
@ -2156,7 +2155,7 @@ func (s *PublicTransactionPoolAPI) GetRawTransactionByBlockNumberAndIndex(ctx co
} }
// GetRawTransactionByBlockHashAndIndex returns the bytes of the transaction for the given block hash and index. // GetRawTransactionByBlockHashAndIndex returns the bytes of the transaction for the given block hash and index.
func (s *PublicTransactionPoolAPI) GetRawTransactionByBlockHashAndIndex(ctx context.Context, blockHash common.Hash, index hexutil.Uint) hexutil.Bytes { func (s *TransactionAPI) GetRawTransactionByBlockHashAndIndex(ctx context.Context, blockHash common.Hash, index hexutil.Uint) hexutil.Bytes {
if block, _ := s.b.GetBlock(ctx, blockHash); block != nil { if block, _ := s.b.GetBlock(ctx, blockHash); block != nil {
return newRPCRawTransactionFromBlockIndex(block, uint64(index)) return newRPCRawTransactionFromBlockIndex(block, uint64(index))
} }
@ -2164,7 +2163,7 @@ func (s *PublicTransactionPoolAPI) GetRawTransactionByBlockHashAndIndex(ctx cont
} }
// GetTransactionCount returns the number of transactions the given address has sent for the given block number // GetTransactionCount returns the number of transactions the given address has sent for the given block number
func (s *PublicTransactionPoolAPI) GetTransactionCount(ctx context.Context, address common.Address, blockNrOrHash rpc.BlockNumberOrHash) (*hexutil.Uint64, error) { func (s *TransactionAPI) GetTransactionCount(ctx context.Context, address common.Address, blockNrOrHash rpc.BlockNumberOrHash) (*hexutil.Uint64, error) {
// Ask transaction pool for the nonce which includes pending transactions // Ask transaction pool for the nonce which includes pending transactions
if blockNr, ok := blockNrOrHash.Number(); ok && blockNr == rpc.PendingBlockNumber { if blockNr, ok := blockNrOrHash.Number(); ok && blockNr == rpc.PendingBlockNumber {
nonce, err := s.b.GetPoolNonce(ctx, address) nonce, err := s.b.GetPoolNonce(ctx, address)
@ -2183,7 +2182,7 @@ func (s *PublicTransactionPoolAPI) GetTransactionCount(ctx context.Context, addr
} }
// GetTransactionByHash returns the transaction for the given hash // GetTransactionByHash returns the transaction for the given hash
func (s *PublicTransactionPoolAPI) GetTransactionByHash(ctx context.Context, hash common.Hash) (*RPCTransaction, error) { func (s *TransactionAPI) GetTransactionByHash(ctx context.Context, hash common.Hash) (*RPCTransaction, error) {
// Try to return an already finalized transaction // Try to return an already finalized transaction
tx, blockHash, blockNumber, index := rawdb.ReadTransaction(s.b.ChainDb(), hash) tx, blockHash, blockNumber, index := rawdb.ReadTransaction(s.b.ChainDb(), hash)
if tx != nil { if tx != nil {
@ -2203,7 +2202,7 @@ func (s *PublicTransactionPoolAPI) GetTransactionByHash(ctx context.Context, has
} }
// GetRawTransactionByHash returns the bytes of the transaction for the given hash. // GetRawTransactionByHash returns the bytes of the transaction for the given hash.
func (s *PublicTransactionPoolAPI) GetRawTransactionByHash(ctx context.Context, hash common.Hash) (hexutil.Bytes, error) { func (s *TransactionAPI) GetRawTransactionByHash(ctx context.Context, hash common.Hash) (hexutil.Bytes, error) {
// Retrieve a finalized transaction, or a pooled otherwise // Retrieve a finalized transaction, or a pooled otherwise
tx, _, _, _ := rawdb.ReadTransaction(s.b.ChainDb(), hash) tx, _, _, _ := rawdb.ReadTransaction(s.b.ChainDb(), hash)
if tx == nil { if tx == nil {
@ -2217,7 +2216,7 @@ func (s *PublicTransactionPoolAPI) GetRawTransactionByHash(ctx context.Context,
} }
// GetTransactionReceipt returns the transaction receipt for the given transaction hash. // GetTransactionReceipt returns the transaction receipt for the given transaction hash.
func (s *PublicTransactionPoolAPI) GetTransactionReceipt(ctx context.Context, hash common.Hash) (map[string]interface{}, error) { func (s *TransactionAPI) GetTransactionReceipt(ctx context.Context, hash common.Hash) (map[string]interface{}, error) {
tx, blockHash, blockNumber, index := rawdb.ReadTransaction(s.b.ChainDb(), hash) tx, blockHash, blockNumber, index := rawdb.ReadTransaction(s.b.ChainDb(), hash)
if tx == nil { if tx == nil {
// When the transaction doesn't exist, the RPC method should return JSON null // When the transaction doesn't exist, the RPC method should return JSON null
@ -2277,7 +2276,7 @@ func marshalReceipt(receipt *types.Receipt, blockHash common.Hash, blockNumber u
} }
// sign is a helper function that signs a transaction with the private key of the given address. // sign is a helper function that signs a transaction with the private key of the given address.
func (s *PublicTransactionPoolAPI) sign(addr common.Address, tx *types.Transaction) (*types.Transaction, error) { func (s *TransactionAPI) sign(addr common.Address, tx *types.Transaction) (*types.Transaction, error) {
// Look up the wallet containing the requested signer // Look up the wallet containing the requested signer
account := accounts.Account{Address: addr} account := accounts.Account{Address: addr}
@ -2348,7 +2347,7 @@ func submitLendingTransaction(ctx context.Context, b Backend, tx *types.LendingT
// SendTransaction creates a transaction for the given argument, sign it and submit it to the // SendTransaction creates a transaction for the given argument, sign it and submit it to the
// transaction pool. // transaction pool.
func (s *PublicTransactionPoolAPI) SendTransaction(ctx context.Context, args TransactionArgs) (common.Hash, error) { func (s *TransactionAPI) SendTransaction(ctx context.Context, args TransactionArgs) (common.Hash, error) {
// Look up the wallet containing the requested signer // Look up the wallet containing the requested signer
account := accounts.Account{Address: args.from()} account := accounts.Account{Address: args.from()}
@ -2386,7 +2385,7 @@ func (s *PublicTransactionPoolAPI) SendTransaction(ctx context.Context, args Tra
// FillTransaction fills the defaults (nonce, gas, gasPrice or 1559 fields) // FillTransaction fills the defaults (nonce, gas, gasPrice or 1559 fields)
// on a given unsigned transaction, and returns it to the caller for further // on a given unsigned transaction, and returns it to the caller for further
// processing (signing + broadcast). // processing (signing + broadcast).
func (s *PublicTransactionPoolAPI) FillTransaction(ctx context.Context, args TransactionArgs) (*SignTransactionResult, error) { func (s *TransactionAPI) FillTransaction(ctx context.Context, args TransactionArgs) (*SignTransactionResult, error) {
// Set some sanity defaults and terminate on failure // Set some sanity defaults and terminate on failure
if err := args.setDefaults(ctx, s.b, false); err != nil { if err := args.setDefaults(ctx, s.b, false); err != nil {
return nil, err return nil, err
@ -2402,7 +2401,7 @@ func (s *PublicTransactionPoolAPI) FillTransaction(ctx context.Context, args Tra
// SendRawTransaction will add the signed transaction to the transaction pool. // SendRawTransaction will add the signed transaction to the transaction pool.
// The sender is responsible for signing the transaction and using the correct nonce. // The sender is responsible for signing the transaction and using the correct nonce.
func (s *PublicTransactionPoolAPI) SendRawTransaction(ctx context.Context, input hexutil.Bytes) (common.Hash, error) { func (s *TransactionAPI) SendRawTransaction(ctx context.Context, input hexutil.Bytes) (common.Hash, error) {
tx := new(types.Transaction) tx := new(types.Transaction)
if err := tx.UnmarshalBinary(input); err != nil { if err := tx.UnmarshalBinary(input); err != nil {
return common.Hash{}, err return common.Hash{}, err
@ -3258,7 +3257,7 @@ func (s *PublicXDCXTransactionPoolAPI) GetLendingTradeById(ctx context.Context,
// The account associated with addr must be unlocked. // The account associated with addr must be unlocked.
// //
// https://github.com/ethereum/wiki/wiki/JSON-RPC#eth_sign // https://github.com/ethereum/wiki/wiki/JSON-RPC#eth_sign
func (s *PublicTransactionPoolAPI) Sign(addr common.Address, data hexutil.Bytes) (hexutil.Bytes, error) { func (s *TransactionAPI) Sign(addr common.Address, data hexutil.Bytes) (hexutil.Bytes, error) {
// Look up the wallet containing the requested signer // Look up the wallet containing the requested signer
account := accounts.Account{Address: addr} account := accounts.Account{Address: addr}
@ -3283,7 +3282,7 @@ type SignTransactionResult struct {
// SignTransaction will sign the given transaction with the from account. // SignTransaction will sign the given transaction with the from account.
// The node needs to have the private key of the account corresponding with // The node needs to have the private key of the account corresponding with
// the given from address and it needs to be unlocked. // the given from address and it needs to be unlocked.
func (s *PublicTransactionPoolAPI) SignTransaction(ctx context.Context, args TransactionArgs) (*SignTransactionResult, error) { func (s *TransactionAPI) SignTransaction(ctx context.Context, args TransactionArgs) (*SignTransactionResult, error) {
if args.Gas == nil { if args.Gas == nil {
return nil, errors.New("not specify Gas") return nil, errors.New("not specify Gas")
} }
@ -3314,7 +3313,7 @@ func (s *PublicTransactionPoolAPI) SignTransaction(ctx context.Context, args Tra
// PendingTransactions returns the transactions that are in the transaction pool // PendingTransactions returns the transactions that are in the transaction pool
// and have a from address that is one of the accounts this node manages. // and have a from address that is one of the accounts this node manages.
func (s *PublicTransactionPoolAPI) PendingTransactions() ([]*RPCTransaction, error) { func (s *TransactionAPI) PendingTransactions() ([]*RPCTransaction, error) {
pending, err := s.b.GetPoolTransactions() pending, err := s.b.GetPoolTransactions()
if err != nil { if err != nil {
return nil, err return nil, err
@ -3338,7 +3337,7 @@ func (s *PublicTransactionPoolAPI) PendingTransactions() ([]*RPCTransaction, err
// Resend accepts an existing transaction and a new gas price and limit. It will remove // Resend accepts an existing transaction and a new gas price and limit. It will remove
// the given transaction from the pool and reinsert it with the new gas price and limit. // the given transaction from the pool and reinsert it with the new gas price and limit.
func (s *PublicTransactionPoolAPI) Resend(ctx context.Context, sendArgs TransactionArgs, gasPrice *hexutil.Big, gasLimit *hexutil.Uint64) (common.Hash, error) { func (s *TransactionAPI) Resend(ctx context.Context, sendArgs TransactionArgs, gasPrice *hexutil.Big, gasLimit *hexutil.Uint64) (common.Hash, error) {
if sendArgs.Nonce == nil { if sendArgs.Nonce == nil {
return common.Hash{}, errors.New("missing transaction nonce in transaction spec") return common.Hash{}, errors.New("missing transaction nonce in transaction spec")
} }
@ -3389,20 +3388,19 @@ func (s *PublicTransactionPoolAPI) Resend(ctx context.Context, sendArgs Transact
return common.Hash{}, fmt.Errorf("transaction %#x not found", matchTx.Hash()) return common.Hash{}, fmt.Errorf("transaction %#x not found", matchTx.Hash())
} }
// PublicDebugAPI is the collection of Ethereum APIs exposed over the public // DebugAPI is the collection of Ethereum APIs exposed over the debugging
// debugging endpoint. // namespace.
type PublicDebugAPI struct { type DebugAPI struct {
b Backend b Backend
} }
// NewPublicDebugAPI creates a new API definition for the public debug methods // NewDebugAPI creates a new instance of DebugAPI.
// of the Ethereum service. func NewDebugAPI(b Backend) *DebugAPI {
func NewPublicDebugAPI(b Backend) *PublicDebugAPI { return &DebugAPI{b: b}
return &PublicDebugAPI{b: b}
} }
// GetBlockRlp retrieves the RLP encoded for of a single block. // GetBlockRlp retrieves the RLP encoded for of a single block.
func (api *PublicDebugAPI) GetBlockRlp(ctx context.Context, number uint64) (string, error) { func (api *DebugAPI) GetBlockRlp(ctx context.Context, number uint64) (string, error) {
block, _ := api.b.BlockByNumber(ctx, rpc.BlockNumber(number)) block, _ := api.b.BlockByNumber(ctx, rpc.BlockNumber(number))
if block == nil { if block == nil {
return "", fmt.Errorf("block #%d not found", number) return "", fmt.Errorf("block #%d not found", number)
@ -3415,7 +3413,7 @@ func (api *PublicDebugAPI) GetBlockRlp(ctx context.Context, number uint64) (stri
} }
// PrintBlock retrieves a block and returns its pretty printed form. // PrintBlock retrieves a block and returns its pretty printed form.
func (api *PublicDebugAPI) PrintBlock(ctx context.Context, number uint64) (string, error) { func (api *DebugAPI) PrintBlock(ctx context.Context, number uint64) (string, error) {
block, _ := api.b.BlockByNumber(ctx, rpc.BlockNumber(number)) block, _ := api.b.BlockByNumber(ctx, rpc.BlockNumber(number))
if block == nil { if block == nil {
return "", fmt.Errorf("block #%d not found", number) return "", fmt.Errorf("block #%d not found", number)
@ -3424,7 +3422,7 @@ func (api *PublicDebugAPI) PrintBlock(ctx context.Context, number uint64) (strin
} }
// SeedHash retrieves the seed hash of a block. // SeedHash retrieves the seed hash of a block.
func (api *PublicDebugAPI) SeedHash(ctx context.Context, number uint64) (string, error) { func (api *DebugAPI) SeedHash(ctx context.Context, number uint64) (string, error) {
block, _ := api.b.BlockByNumber(ctx, rpc.BlockNumber(number)) block, _ := api.b.BlockByNumber(ctx, rpc.BlockNumber(number))
if block == nil { if block == nil {
return "", fmt.Errorf("block #%d not found", number) return "", fmt.Errorf("block #%d not found", number)
@ -3432,20 +3430,8 @@ func (api *PublicDebugAPI) SeedHash(ctx context.Context, number uint64) (string,
return fmt.Sprintf("%#x", ethash.SeedHash(number)), nil return fmt.Sprintf("%#x", ethash.SeedHash(number)), nil
} }
// PrivateDebugAPI is the collection of Ethereum APIs exposed over the private
// debugging endpoint.
type PrivateDebugAPI struct {
b Backend
}
// NewPrivateDebugAPI creates a new API definition for the private debug methods
// of the Ethereum service.
func NewPrivateDebugAPI(b Backend) *PrivateDebugAPI {
return &PrivateDebugAPI{b: b}
}
// ChaindbProperty returns leveldb properties of the chain database. // ChaindbProperty returns leveldb properties of the chain database.
func (api *PrivateDebugAPI) ChaindbProperty(property string) (string, error) { func (api *DebugAPI) ChaindbProperty(property string) (string, error) {
ldb, ok := api.b.ChainDb().(interface { ldb, ok := api.b.ChainDb().(interface {
LDB() *leveldb.DB LDB() *leveldb.DB
}) })
@ -3460,7 +3446,7 @@ func (api *PrivateDebugAPI) ChaindbProperty(property string) (string, error) {
return ldb.LDB().GetProperty(property) return ldb.LDB().GetProperty(property)
} }
func (api *PrivateDebugAPI) ChaindbCompact() error { func (api *DebugAPI) ChaindbCompact() error {
ldb, ok := api.b.ChainDb().(interface { ldb, ok := api.b.ChainDb().(interface {
LDB() *leveldb.DB LDB() *leveldb.DB
}) })
@ -3479,12 +3465,12 @@ func (api *PrivateDebugAPI) ChaindbCompact() error {
} }
// SetHead rewinds the head of the blockchain to a previous block. // SetHead rewinds the head of the blockchain to a previous block.
func (api *PrivateDebugAPI) SetHead(number hexutil.Uint64) { func (api *DebugAPI) SetHead(number hexutil.Uint64) {
api.b.SetHead(uint64(number)) api.b.SetHead(uint64(number))
} }
// DbGet returns the raw value of a key stored in the database. // DbGet returns the raw value of a key stored in the database.
func (api *PrivateDebugAPI) DbGet(key string) (hexutil.Bytes, error) { func (api *DebugAPI) DbGet(key string) (hexutil.Bytes, error) {
blob, err := common.ParseHexOrString(key) blob, err := common.ParseHexOrString(key)
if err != nil { if err != nil {
return nil, err return nil, err
@ -3492,29 +3478,29 @@ func (api *PrivateDebugAPI) DbGet(key string) (hexutil.Bytes, error) {
return api.b.ChainDb().Get(blob) return api.b.ChainDb().Get(blob)
} }
// PublicNetAPI offers network related RPC methods // NetAPI offers network related RPC methods
type PublicNetAPI struct { type NetAPI struct {
net *p2p.Server net *p2p.Server
networkVersion uint64 networkVersion uint64
} }
// NewPublicNetAPI creates a new net API instance. // NewNetAPI creates a new net API instance.
func NewPublicNetAPI(net *p2p.Server, networkVersion uint64) *PublicNetAPI { func NewNetAPI(net *p2p.Server, networkVersion uint64) *NetAPI {
return &PublicNetAPI{net, networkVersion} return &NetAPI{net, networkVersion}
} }
// Listening returns an indication if the node is listening for network connections. // Listening returns an indication if the node is listening for network connections.
func (s *PublicNetAPI) Listening() bool { func (s *NetAPI) Listening() bool {
return true // always listening return true // always listening
} }
// PeerCount returns the number of connected peers // PeerCount returns the number of connected peers
func (s *PublicNetAPI) PeerCount() hexutil.Uint { func (s *NetAPI) PeerCount() hexutil.Uint {
return hexutil.Uint(s.net.PeerCount()) return hexutil.Uint(s.net.PeerCount())
} }
// Version returns the current ethereum protocol version. // Version returns the current ethereum protocol version.
func (s *PublicNetAPI) Version() string { func (s *NetAPI) Version() string {
return fmt.Sprintf("%d", s.networkVersion) return fmt.Sprintf("%d", s.networkVersion)
} }
@ -3583,7 +3569,7 @@ func GetSignersFromBlocks(b Backend, blockNumber uint64, blockHash common.Hash,
// Formular: // Formular:
// //
// ROI = average_latest_epoch_reward_for_voters*number_of_epoch_per_year/latest_total_cap*100 // ROI = average_latest_epoch_reward_for_voters*number_of_epoch_per_year/latest_total_cap*100
func (s *PublicBlockChainAPI) GetStakerROI() float64 { func (s *BlockChainAPI) GetStakerROI() float64 {
blockNumber := s.b.CurrentBlock().Number().Uint64() blockNumber := s.b.CurrentBlock().Number().Uint64()
lastCheckpointNumber := blockNumber - (blockNumber % s.b.ChainConfig().XDPoS.Epoch) - s.b.ChainConfig().XDPoS.Epoch // calculate for 2 epochs ago lastCheckpointNumber := blockNumber - (blockNumber % s.b.ChainConfig().XDPoS.Epoch) - s.b.ChainConfig().XDPoS.Epoch // calculate for 2 epochs ago
totalCap := new(big.Int).SetUint64(0) totalCap := new(big.Int).SetUint64(0)
@ -3610,7 +3596,7 @@ func (s *PublicBlockChainAPI) GetStakerROI() float64 {
// Formular: // Formular:
// //
// ROI = latest_epoch_reward_for_voters*number_of_epoch_per_year/latest_total_cap*100 // ROI = latest_epoch_reward_for_voters*number_of_epoch_per_year/latest_total_cap*100
func (s *PublicBlockChainAPI) GetStakerROIMasternode(masternode common.Address) float64 { func (s *BlockChainAPI) GetStakerROIMasternode(masternode common.Address) float64 {
votersReward := s.b.GetVotersRewards(masternode) votersReward := s.b.GetVotersRewards(masternode)
if votersReward == nil { if votersReward == nil {
return 0 return 0
@ -3647,7 +3633,7 @@ type currentTotalMinted struct {
BlockNumber *hexutil.Big `json:"blockNumber"` BlockNumber *hexutil.Big `json:"blockNumber"`
} }
func (s *PublicBlockChainAPI) GetCurrentTotalMinted(ctx context.Context) (*currentTotalMinted, error) { func (s *BlockChainAPI) GetCurrentTotalMinted(ctx context.Context) (*currentTotalMinted, error) {
statedb, header, err := s.b.StateAndHeaderByNumber(ctx, rpc.LatestBlockNumber) statedb, header, err := s.b.StateAndHeaderByNumber(ctx, rpc.LatestBlockNumber)
if err != nil { if err != nil {
return nil, err return nil, err

View file

@ -126,31 +126,28 @@ func GetAPIs(apiBackend Backend, chainReader consensus.ChainReader) []rpc.API {
return []rpc.API{ return []rpc.API{
{ {
Namespace: "eth", Namespace: "eth",
Service: NewPublicEthereumAPI(apiBackend), Service: NewEthereumAPI(apiBackend),
}, { }, {
Namespace: "eth", Namespace: "eth",
Service: NewPublicBlockChainAPI(apiBackend, chainReader), Service: NewBlockChainAPI(apiBackend, chainReader),
}, { }, {
Namespace: "eth", Namespace: "eth",
Service: NewPublicTransactionPoolAPI(apiBackend, nonceLock), Service: NewTransactionAPI(apiBackend, nonceLock),
}, { }, {
Namespace: "XDCx", Namespace: "XDCx",
Service: NewPublicXDCXTransactionPoolAPI(apiBackend, nonceLock), Service: NewPublicXDCXTransactionPoolAPI(apiBackend, nonceLock),
}, { }, {
Namespace: "txpool", Namespace: "txpool",
Service: NewPublicTxPoolAPI(apiBackend), Service: NewTxPoolAPI(apiBackend),
}, { }, {
Namespace: "debug", Namespace: "debug",
Service: NewPublicDebugAPI(apiBackend), Service: NewDebugAPI(apiBackend),
}, {
Namespace: "debug",
Service: NewPrivateDebugAPI(apiBackend),
}, { }, {
Namespace: "eth", Namespace: "eth",
Service: NewPublicAccountAPI(apiBackend.AccountManager()), Service: NewEthereumAccountAPI(apiBackend.AccountManager()),
}, { }, {
Namespace: "personal", Namespace: "personal",
Service: NewPrivateAccountAPI(apiBackend, nonceLock), Service: NewPersonalAccountAPI(apiBackend, nonceLock),
}, },
} }
} }

View file

@ -35,29 +35,26 @@ func (n *Node) apis() []rpc.API {
return []rpc.API{ return []rpc.API{
{ {
Namespace: "admin", Namespace: "admin",
Service: &privateAdminAPI{n}, Service: &adminAPI{n},
}, {
Namespace: "admin",
Service: &publicAdminAPI{n},
}, { }, {
Namespace: "debug", Namespace: "debug",
Service: debug.Handler, Service: debug.Handler,
}, { }, {
Namespace: "web3", Namespace: "web3",
Service: &publicWeb3API{n}, Service: &web3API{n},
}, },
} }
} }
// privateAdminAPI is the collection of administrative API methods exposed only // adminAPI is the collection of administrative API methods exposed over
// over a secure RPC channel. // both secure and unsecure RPC channels.
type privateAdminAPI struct { type adminAPI struct {
node *Node // Node interfaced by this API node *Node // Node interfaced by this API
} }
// AddPeer requests connecting to a remote node, and also maintaining the new // AddPeer requests connecting to a remote node, and also maintaining the new
// connection at all times, even reconnecting if it is lost. // connection at all times, even reconnecting if it is lost.
func (api *privateAdminAPI) AddPeer(url string) (bool, error) { func (api *adminAPI) AddPeer(url string) (bool, error) {
// Make sure the server is running, fail otherwise // Make sure the server is running, fail otherwise
server := api.node.Server() server := api.node.Server()
if server == nil { if server == nil {
@ -73,7 +70,7 @@ func (api *privateAdminAPI) AddPeer(url string) (bool, error) {
} }
// RemovePeer disconnects from a remote node if the connection exists // RemovePeer disconnects from a remote node if the connection exists
func (api *privateAdminAPI) RemovePeer(url string) (bool, error) { func (api *adminAPI) RemovePeer(url string) (bool, error) {
// Make sure the server is running, fail otherwise // Make sure the server is running, fail otherwise
server := api.node.Server() server := api.node.Server()
if server == nil { if server == nil {
@ -89,7 +86,7 @@ func (api *privateAdminAPI) RemovePeer(url string) (bool, error) {
} }
// AddTrustedPeer allows a remote node to always connect, even if slots are full // AddTrustedPeer allows a remote node to always connect, even if slots are full
func (api *privateAdminAPI) AddTrustedPeer(url string) (bool, error) { func (api *adminAPI) AddTrustedPeer(url string) (bool, error) {
// Make sure the server is running, fail otherwise // Make sure the server is running, fail otherwise
server := api.node.Server() server := api.node.Server()
if server == nil { if server == nil {
@ -105,7 +102,7 @@ func (api *privateAdminAPI) AddTrustedPeer(url string) (bool, error) {
// RemoveTrustedPeer removes a remote node from the trusted peer set, but it // RemoveTrustedPeer removes a remote node from the trusted peer set, but it
// does not disconnect it automatically. // does not disconnect it automatically.
func (api *privateAdminAPI) RemoveTrustedPeer(url string) (bool, error) { func (api *adminAPI) RemoveTrustedPeer(url string) (bool, error) {
// Make sure the server is running, fail otherwise // Make sure the server is running, fail otherwise
server := api.node.Server() server := api.node.Server()
if server == nil { if server == nil {
@ -121,7 +118,7 @@ func (api *privateAdminAPI) RemoveTrustedPeer(url string) (bool, error) {
// PeerEvents creates an RPC subscription which receives peer events from the // PeerEvents creates an RPC subscription which receives peer events from the
// node's p2p.Server // node's p2p.Server
func (api *privateAdminAPI) PeerEvents(ctx context.Context) (*rpc.Subscription, error) { func (api *adminAPI) PeerEvents(ctx context.Context) (*rpc.Subscription, error) {
// Make sure the server is running, fail otherwise // Make sure the server is running, fail otherwise
server := api.node.Server() server := api.node.Server()
if server == nil { if server == nil {
@ -156,7 +153,7 @@ func (api *privateAdminAPI) PeerEvents(ctx context.Context) (*rpc.Subscription,
} }
// StartHTTP starts the HTTP RPC API server. // StartHTTP starts the HTTP RPC API server.
func (api *privateAdminAPI) StartHTTP(host *string, port *int, cors *string, apis *string, vhosts *string) (bool, error) { func (api *adminAPI) StartHTTP(host *string, port *int, cors *string, apis *string, vhosts *string) (bool, error) {
api.node.lock.Lock() api.node.lock.Lock()
defer api.node.lock.Unlock() defer api.node.lock.Unlock()
@ -215,26 +212,26 @@ func (api *privateAdminAPI) StartHTTP(host *string, port *int, cors *string, api
// StartRPC starts the HTTP RPC API server. // StartRPC starts the HTTP RPC API server.
// This method is deprecated. Use StartHTTP instead. // This method is deprecated. Use StartHTTP instead.
func (api *privateAdminAPI) StartRPC(host *string, port *int, cors *string, apis *string, vhosts *string) (bool, error) { func (api *adminAPI) StartRPC(host *string, port *int, cors *string, apis *string, vhosts *string) (bool, error) {
log.Warn("Deprecation warning", "method", "admin.StartRPC", "use-instead", "admin.StartHTTP") log.Warn("Deprecation warning", "method", "admin.StartRPC", "use-instead", "admin.StartHTTP")
return api.StartHTTP(host, port, cors, apis, vhosts) return api.StartHTTP(host, port, cors, apis, vhosts)
} }
// StopHTTP shuts down the HTTP server. // StopHTTP shuts down the HTTP server.
func (api *privateAdminAPI) StopHTTP() (bool, error) { func (api *adminAPI) StopHTTP() (bool, error) {
api.node.http.stop() api.node.http.stop()
return true, nil return true, nil
} }
// StopRPC shuts down the HTTP server. // StopRPC shuts down the HTTP server.
// This method is deprecated. Use StopHTTP instead. // This method is deprecated. Use StopHTTP instead.
func (api *privateAdminAPI) StopRPC() (bool, error) { func (api *adminAPI) StopRPC() (bool, error) {
log.Warn("Deprecation warning", "method", "admin.StopRPC", "use-instead", "admin.StopHTTP") log.Warn("Deprecation warning", "method", "admin.StopRPC", "use-instead", "admin.StopHTTP")
return api.StopHTTP() return api.StopHTTP()
} }
// StartWS starts the websocket RPC API server. // StartWS starts the websocket RPC API server.
func (api *privateAdminAPI) StartWS(host *string, port *int, allowedOrigins *string, apis *string) (bool, error) { func (api *adminAPI) StartWS(host *string, port *int, allowedOrigins *string, apis *string) (bool, error) {
api.node.lock.Lock() api.node.lock.Lock()
defer api.node.lock.Unlock() defer api.node.lock.Unlock()
@ -290,21 +287,15 @@ func (api *privateAdminAPI) StartWS(host *string, port *int, allowedOrigins *str
} }
// StopWS terminates all WebSocket servers. // StopWS terminates all WebSocket servers.
func (api *privateAdminAPI) StopWS() (bool, error) { func (api *adminAPI) StopWS() (bool, error) {
api.node.http.stopWS() api.node.http.stopWS()
api.node.ws.stop() api.node.ws.stop()
return true, nil return true, nil
} }
// publicAdminAPI is the collection of administrative API methods exposed over
// both secure and unsecure RPC channels.
type publicAdminAPI struct {
node *Node // Node interfaced by this API
}
// Peers retrieves all the information we know about each individual peer at the // Peers retrieves all the information we know about each individual peer at the
// protocol granularity. // protocol granularity.
func (api *publicAdminAPI) Peers() ([]*p2p.PeerInfo, error) { func (api *adminAPI) Peers() ([]*p2p.PeerInfo, error) {
server := api.node.Server() server := api.node.Server()
if server == nil { if server == nil {
return nil, ErrNodeStopped return nil, ErrNodeStopped
@ -314,7 +305,7 @@ func (api *publicAdminAPI) Peers() ([]*p2p.PeerInfo, error) {
// NodeInfo retrieves all the information we know about the host node at the // NodeInfo retrieves all the information we know about the host node at the
// protocol granularity. // protocol granularity.
func (api *publicAdminAPI) NodeInfo() (*p2p.NodeInfo, error) { func (api *adminAPI) NodeInfo() (*p2p.NodeInfo, error) {
server := api.node.Server() server := api.node.Server()
if server == nil { if server == nil {
return nil, ErrNodeStopped return nil, ErrNodeStopped
@ -323,22 +314,22 @@ func (api *publicAdminAPI) NodeInfo() (*p2p.NodeInfo, error) {
} }
// Datadir retrieves the current data directory the node is using. // Datadir retrieves the current data directory the node is using.
func (api *publicAdminAPI) Datadir() string { func (api *adminAPI) Datadir() string {
return api.node.DataDir() return api.node.DataDir()
} }
// publicWeb3API offers helper utils // web3API offers helper utils
type publicWeb3API struct { type web3API struct {
stack *Node stack *Node
} }
// ClientVersion returns the node name // ClientVersion returns the node name
func (s *publicWeb3API) ClientVersion() string { func (s *web3API) ClientVersion() string {
return s.stack.Server().Name return s.stack.Server().Name
} }
// Sha3 applies the ethereum sha3 implementation on the input. // Sha3 applies the ethereum sha3 implementation on the input.
// It assumes the input is hex encoded. // It assumes the input is hex encoded.
func (s *publicWeb3API) Sha3(input hexutil.Bytes) hexutil.Bytes { func (s *web3API) Sha3(input hexutil.Bytes) hexutil.Bytes {
return crypto.Keccak256(input) return crypto.Keccak256(input)
} }

View file

@ -35,7 +35,7 @@ func TestStartRPC(t *testing.T) {
type test struct { type test struct {
name string name string
cfg Config cfg Config
fn func(*testing.T, *Node, *privateAdminAPI) fn func(*testing.T, *Node, *adminAPI)
// Checks. These run after the node is configured and all API calls have been made. // Checks. These run after the node is configured and all API calls have been made.
wantReachable bool // whether the HTTP server should be reachable at all wantReachable bool // whether the HTTP server should be reachable at all
@ -48,7 +48,7 @@ func TestStartRPC(t *testing.T) {
{ {
name: "all off", name: "all off",
cfg: Config{}, cfg: Config{},
fn: func(t *testing.T, n *Node, api *privateAdminAPI) { fn: func(t *testing.T, n *Node, api *adminAPI) {
}, },
wantReachable: false, wantReachable: false,
wantHandlers: false, wantHandlers: false,
@ -58,7 +58,7 @@ func TestStartRPC(t *testing.T) {
{ {
name: "rpc enabled through config", name: "rpc enabled through config",
cfg: Config{HTTPHost: "127.0.0.1"}, cfg: Config{HTTPHost: "127.0.0.1"},
fn: func(t *testing.T, n *Node, api *privateAdminAPI) { fn: func(t *testing.T, n *Node, api *adminAPI) {
}, },
wantReachable: true, wantReachable: true,
wantHandlers: true, wantHandlers: true,
@ -68,7 +68,7 @@ func TestStartRPC(t *testing.T) {
{ {
name: "rpc enabled through API", name: "rpc enabled through API",
cfg: Config{}, cfg: Config{},
fn: func(t *testing.T, n *Node, api *privateAdminAPI) { fn: func(t *testing.T, n *Node, api *adminAPI) {
_, err := api.StartHTTP(sp("127.0.0.1"), ip(0), nil, nil, nil) _, err := api.StartHTTP(sp("127.0.0.1"), ip(0), nil, nil, nil)
assert.NoError(t, err) assert.NoError(t, err)
}, },
@ -80,7 +80,7 @@ func TestStartRPC(t *testing.T) {
{ {
name: "rpc start again after failure", name: "rpc start again after failure",
cfg: Config{}, cfg: Config{},
fn: func(t *testing.T, n *Node, api *privateAdminAPI) { fn: func(t *testing.T, n *Node, api *adminAPI) {
// Listen on a random port. // Listen on a random port.
listener, err := net.Listen("tcp", "127.0.0.1:0") listener, err := net.Listen("tcp", "127.0.0.1:0")
if err != nil { if err != nil {
@ -108,7 +108,7 @@ func TestStartRPC(t *testing.T) {
{ {
name: "rpc stopped through API", name: "rpc stopped through API",
cfg: Config{HTTPHost: "127.0.0.1"}, cfg: Config{HTTPHost: "127.0.0.1"},
fn: func(t *testing.T, n *Node, api *privateAdminAPI) { fn: func(t *testing.T, n *Node, api *adminAPI) {
_, err := api.StopHTTP() _, err := api.StopHTTP()
assert.NoError(t, err) assert.NoError(t, err)
}, },
@ -120,7 +120,7 @@ func TestStartRPC(t *testing.T) {
{ {
name: "rpc stopped twice", name: "rpc stopped twice",
cfg: Config{HTTPHost: "127.0.0.1"}, cfg: Config{HTTPHost: "127.0.0.1"},
fn: func(t *testing.T, n *Node, api *privateAdminAPI) { fn: func(t *testing.T, n *Node, api *adminAPI) {
_, err := api.StopHTTP() _, err := api.StopHTTP()
assert.NoError(t, err) assert.NoError(t, err)
@ -143,7 +143,7 @@ func TestStartRPC(t *testing.T) {
{ {
name: "ws enabled through API", name: "ws enabled through API",
cfg: Config{}, cfg: Config{},
fn: func(t *testing.T, n *Node, api *privateAdminAPI) { fn: func(t *testing.T, n *Node, api *adminAPI) {
_, err := api.StartWS(sp("127.0.0.1"), ip(0), nil, nil) _, err := api.StartWS(sp("127.0.0.1"), ip(0), nil, nil)
assert.NoError(t, err) assert.NoError(t, err)
}, },
@ -155,7 +155,7 @@ func TestStartRPC(t *testing.T) {
{ {
name: "ws stopped through API", name: "ws stopped through API",
cfg: Config{WSHost: "127.0.0.1"}, cfg: Config{WSHost: "127.0.0.1"},
fn: func(t *testing.T, n *Node, api *privateAdminAPI) { fn: func(t *testing.T, n *Node, api *adminAPI) {
_, err := api.StopWS() _, err := api.StopWS()
assert.NoError(t, err) assert.NoError(t, err)
}, },
@ -167,7 +167,7 @@ func TestStartRPC(t *testing.T) {
{ {
name: "ws stopped twice", name: "ws stopped twice",
cfg: Config{WSHost: "127.0.0.1"}, cfg: Config{WSHost: "127.0.0.1"},
fn: func(t *testing.T, n *Node, api *privateAdminAPI) { fn: func(t *testing.T, n *Node, api *adminAPI) {
_, err := api.StopWS() _, err := api.StopWS()
assert.NoError(t, err) assert.NoError(t, err)
@ -182,7 +182,7 @@ func TestStartRPC(t *testing.T) {
{ {
name: "ws enabled after RPC", name: "ws enabled after RPC",
cfg: Config{HTTPHost: "127.0.0.1"}, cfg: Config{HTTPHost: "127.0.0.1"},
fn: func(t *testing.T, n *Node, api *privateAdminAPI) { fn: func(t *testing.T, n *Node, api *adminAPI) {
wsport := n.http.port wsport := n.http.port
_, err := api.StartWS(sp("127.0.0.1"), ip(wsport), nil, nil) _, err := api.StartWS(sp("127.0.0.1"), ip(wsport), nil, nil)
assert.NoError(t, err) assert.NoError(t, err)
@ -195,7 +195,7 @@ func TestStartRPC(t *testing.T) {
{ {
name: "ws enabled after RPC then stopped", name: "ws enabled after RPC then stopped",
cfg: Config{HTTPHost: "127.0.0.1"}, cfg: Config{HTTPHost: "127.0.0.1"},
fn: func(t *testing.T, n *Node, api *privateAdminAPI) { fn: func(t *testing.T, n *Node, api *adminAPI) {
wsport := n.http.port wsport := n.http.port
_, err := api.StartWS(sp("127.0.0.1"), ip(wsport), nil, nil) _, err := api.StartWS(sp("127.0.0.1"), ip(wsport), nil, nil)
assert.NoError(t, err) assert.NoError(t, err)
@ -210,7 +210,7 @@ func TestStartRPC(t *testing.T) {
}, },
{ {
name: "rpc stopped with ws enabled", name: "rpc stopped with ws enabled",
fn: func(t *testing.T, n *Node, api *privateAdminAPI) { fn: func(t *testing.T, n *Node, api *adminAPI) {
_, err := api.StartHTTP(sp("127.0.0.1"), ip(0), nil, nil, nil) _, err := api.StartHTTP(sp("127.0.0.1"), ip(0), nil, nil, nil)
assert.NoError(t, err) assert.NoError(t, err)
@ -228,7 +228,7 @@ func TestStartRPC(t *testing.T) {
}, },
{ {
name: "rpc enabled after ws", name: "rpc enabled after ws",
fn: func(t *testing.T, n *Node, api *privateAdminAPI) { fn: func(t *testing.T, n *Node, api *adminAPI) {
_, err := api.StartWS(sp("127.0.0.1"), ip(0), nil, nil) _, err := api.StartWS(sp("127.0.0.1"), ip(0), nil, nil)
assert.NoError(t, err) assert.NoError(t, err)
@ -274,7 +274,7 @@ func TestStartRPC(t *testing.T) {
// Run the API call hook. // Run the API call hook.
if test.fn != nil { if test.fn != nil {
test.fn(t, stack, &privateAdminAPI{stack}) test.fn(t, stack, &adminAPI{stack})
} }
// Check if the HTTP endpoints are available. // Check if the HTTP endpoints are available.