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

* internal/ethapi: rename PublicEthereumAPI to EthereumAPI

* eth: rename PublicEthereumAPI to EthereumAPI

* internal/ethapi: rename PublicTxPoolAPI to TxPoolAPI

* internal/ethapi: rename PublicAccountAPI to EthereumAccountAPI

* internal/ethapi: rename PrivateAccountAPI to PersonalAccountAPI

* internal/ethapi: rename PublicBlockChainAPI to BlockChainAPI

* internal/ethapi: rename PublicTransactionPoolAPI to TransactionAPI

* internal/ethapi: rename PublicDebugAPI to DebugAPI

* internal/ethapi: move PrivateDebugAPI methods to DebugAPI

* internal/ethapi: rename PublicNetAPI to NetAPI

* les: rename PrivateLightServerAPI to LightServerAPI

* les: rename PrivateLightAPI to LightAPI

* les: rename PrivateDebugAPI to DebugAPI

* les: rename PublicDownloaderAPI to DownloaderAPI

* eth,les: rename PublicFilterAPI to FilterAPI

* eth: rename PublicMinerAPI to MinerAPI

* eth: rename PublicDownloaderAPI to DownloaderAPI

* eth: move PrivateMinerAPI methods to MinerAPI

* eth: rename PrivateAdminAPI to AdminAPI

* eth: rename PublicDebugAPI to DebugAPI

* eth: move PrivateDebugAPI methods to DebugAPI

* node: rename publicAdminAPI to adminAPI

* node: move privateAdminAPI methods to adminAPI

* node: rename publicWeb3API to web3API

* eth,internal/ethapi: sync comments with previous renamings
This commit is contained in:
lightclient 2022-06-21 11:05:43 +02:00 committed by GitHub
parent 241dd27300
commit 10dc5dce08
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
14 changed files with 305 additions and 370 deletions

@ -41,57 +41,44 @@ import (
"github.com/ethereum/go-ethereum/trie" "github.com/ethereum/go-ethereum/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. // NewEthereumAPI 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
}
// NewPublicMinerAPI create a new PublicMinerAPI instance.
func NewPublicMinerAPI(e *Ethereum) *PublicMinerAPI {
return &PublicMinerAPI{e}
}
// 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.IsMining() return api.e.IsMining()
} }
// 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
} }
// NewPrivateMinerAPI create a new RPC service which controls the miner of this node. // NewMinerAPI create a new MinerAPI instance.
func NewPrivateMinerAPI(e *Ethereum) *PrivateMinerAPI { func NewMinerAPI(e *Ethereum) *MinerAPI {
return &PrivateMinerAPI{e: e} return &MinerAPI{e}
} }
// Start starts the miner with the given number of threads. If threads is nil, // Start starts the miner with the given number of threads. If threads is nil,
@ -99,7 +86,7 @@ func NewPrivateMinerAPI(e *Ethereum) *PrivateMinerAPI {
// usable by this process. If mining is already running, this method adjust the // usable by this process. If mining is already running, this method adjust the
// number of threads allowed to use and updates the minimum price required by the // number of threads allowed to use and updates the minimum price required by the
// transaction pool. // transaction pool.
func (api *PrivateMinerAPI) Start(threads *int) error { func (api *MinerAPI) Start(threads *int) error {
if threads == nil { if threads == nil {
return api.e.StartMining(runtime.NumCPU()) return api.e.StartMining(runtime.NumCPU())
} }
@ -108,12 +95,12 @@ func (api *PrivateMinerAPI) Start(threads *int) error {
// Stop terminates the miner, both at the consensus engine level as well as at // Stop terminates the miner, both at the consensus engine level as well as at
// the block creation level. // the block creation level.
func (api *PrivateMinerAPI) Stop() { func (api *MinerAPI) Stop() {
api.e.StopMining() api.e.StopMining()
} }
// 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
} }
@ -121,7 +108,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()
@ -131,37 +118,36 @@ func (api *PrivateMinerAPI) SetGasPrice(gasPrice hexutil.Big) bool {
} }
// SetGasLimit sets the gaslimit to target towards during mining. // SetGasLimit sets the gaslimit to target towards during mining.
func (api *PrivateMinerAPI) SetGasLimit(gasLimit hexutil.Uint64) bool { func (api *MinerAPI) SetGasLimit(gasLimit hexutil.Uint64) bool {
api.e.Miner().SetGasCeil(uint64(gasLimit)) api.e.Miner().SetGasCeil(uint64(gasLimit))
return true return true
} }
// 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 {
api.e.SetEtherbase(etherbase) api.e.SetEtherbase(etherbase)
return true return true
} }
// SetRecommitInterval updates the interval for miner sealing work recommitting. // SetRecommitInterval updates the interval for miner sealing work recommitting.
func (api *PrivateMinerAPI) SetRecommitInterval(interval int) { func (api *MinerAPI) SetRecommitInterval(interval int) {
api.e.Miner().SetRecommitInterval(time.Duration(interval) * time.Millisecond) api.e.Miner().SetRecommitInterval(time.Duration(interval) * time.Millisecond)
} }
// 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,
// or a range of blocks if first and last are non-nil. // or a range of blocks if first and last are non-nil.
func (api *PrivateAdminAPI) ExportChain(file string, first *uint64, last *uint64) (bool, error) { func (api *AdminAPI) ExportChain(file string, first *uint64, last *uint64) (bool, error) {
if first == nil && last != nil { if first == nil && last != nil {
return false, errors.New("last cannot be specified without first") return false, errors.New("last cannot be specified without first")
} }
@ -209,7 +195,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 {
@ -257,20 +243,19 @@ func (api *PrivateAdminAPI) ImportChain(file string) (bool, error) {
return true, nil return true, nil
} }
// PublicDebugAPI is the collection of Ethereum full node APIs exposed // DebugAPI is the collection of Ethereum full node APIs for debugging the
// over the public debugging endpoint. // protocol.
type PublicDebugAPI struct { type DebugAPI struct {
eth *Ethereum eth *Ethereum
} }
// NewPublicDebugAPI creates a new API definition for the full node- // NewDebugAPI creates a new DebugAPI instance.
// related public debug methods of the Ethereum service. func NewDebugAPI(eth *Ethereum) *DebugAPI {
func NewPublicDebugAPI(eth *Ethereum) *PublicDebugAPI { return &DebugAPI{eth: eth}
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) {
opts := &state.DumpConfig{ opts := &state.DumpConfig{
OnlyWithAddresses: true, OnlyWithAddresses: true,
Max: AccountRangeMaxResults, // Sanity limit over RPC Max: AccountRangeMaxResults, // Sanity limit over RPC
@ -300,20 +285,8 @@ func (api *PublicDebugAPI) DumpBlock(blockNr rpc.BlockNumber) (state.Dump, error
return stateDb.RawDump(opts), nil return stateDb.RawDump(opts), nil
} }
// PrivateDebugAPI is the collection of Ethereum full node APIs exposed over
// the private debugging endpoint.
type PrivateDebugAPI struct {
eth *Ethereum
}
// NewPrivateDebugAPI creates a new API definition for the full node-related
// private debug methods of the Ethereum service.
func NewPrivateDebugAPI(eth *Ethereum) *PrivateDebugAPI {
return &PrivateDebugAPI{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
} }
@ -329,7 +302,7 @@ type BadBlockArgs struct {
// 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) ([]*BadBlockArgs, error) { func (api *DebugAPI) GetBadBlocks(ctx context.Context) ([]*BadBlockArgs, error) {
var ( var (
err error err error
blocks = rawdb.ReadAllBadBlocks(api.eth.chainDb) blocks = rawdb.ReadAllBadBlocks(api.eth.chainDb)
@ -361,7 +334,7 @@ func (api *PrivateDebugAPI) GetBadBlocks(ctx context.Context) ([]*BadBlockArgs,
const AccountRangeMaxResults = 256 const AccountRangeMaxResults = 256
// AccountRange enumerates all accounts in the given block and start point in paging request // AccountRange enumerates all accounts in the given block and start point in paging request
func (api *PublicDebugAPI) AccountRange(blockNrOrHash rpc.BlockNumberOrHash, start hexutil.Bytes, maxResults int, nocode, nostorage, incompletes bool) (state.IteratorDump, error) { func (api *DebugAPI) AccountRange(blockNrOrHash rpc.BlockNumberOrHash, start hexutil.Bytes, maxResults int, nocode, nostorage, incompletes bool) (state.IteratorDump, error) {
var stateDb *state.StateDB var stateDb *state.StateDB
var err error var err error
@ -428,7 +401,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(blockHash common.Hash, txIndex int, contractAddress common.Address, keyStart hexutil.Bytes, maxResult int) (StorageRangeResult, error) { func (api *DebugAPI) StorageRangeAt(blockHash common.Hash, txIndex int, contractAddress common.Address, keyStart hexutil.Bytes, maxResult int) (StorageRangeResult, error) {
// Retrieve the block // Retrieve the block
block := api.eth.blockchain.GetBlockByHash(blockHash) block := api.eth.blockchain.GetBlockByHash(blockHash)
if block == nil { if block == nil {
@ -473,7 +446,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)
@ -501,7 +474,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 {
@ -523,7 +496,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())
} }
@ -556,7 +529,7 @@ func (api *PrivateDebugAPI) getModifiedAccounts(startBlock, endBlock *types.Bloc
// of the next block. // of the next block.
// The (from, to) parameters are the sequence of blocks to search, which can go // The (from, to) parameters are the sequence of blocks to search, which can go
// either forwards or backwards // either forwards or backwards
func (api *PrivateDebugAPI) GetAccessibleState(from, to rpc.BlockNumber) (uint64, error) { func (api *DebugAPI) GetAccessibleState(from, to rpc.BlockNumber) (uint64, error) {
db := api.eth.ChainDb() db := api.eth.ChainDb()
var pivot uint64 var pivot uint64
if p := rawdb.ReadLastPivotNumber(db); p != nil { if p := rawdb.ReadLastPivotNumber(db); p != nil {

@ -94,7 +94,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
@ -266,7 +266,7 @@ func New(stack *node.Node, config *ethconfig.Config) (*Ethereum, error) {
} }
// Start the RPC service // Start the RPC service
eth.netRPCService = ethapi.NewPublicNetAPI(eth.p2pServer, config.NetworkId) eth.netRPCService = ethapi.NewNetAPI(eth.p2pServer, config.NetworkId)
// Register the backend on the node // Register the backend on the node
stack.RegisterAPIs(eth.APIs()) stack.RegisterAPIs(eth.APIs())
@ -309,41 +309,32 @@ func (s *Ethereum) APIs() []rpc.API {
{ {
Namespace: "eth", Namespace: "eth",
Version: "1.0", Version: "1.0",
Service: NewPublicEthereumAPI(s), Service: NewEthereumAPI(s),
Public: true,
}, {
Namespace: "eth",
Version: "1.0",
Service: NewPublicMinerAPI(s),
Public: true,
}, {
Namespace: "eth",
Version: "1.0",
Service: downloader.NewPublicDownloaderAPI(s.handler.downloader, s.eventMux),
Public: true, Public: true,
}, { }, {
Namespace: "miner", Namespace: "miner",
Version: "1.0", Version: "1.0",
Service: NewPrivateMinerAPI(s), Service: NewMinerAPI(s),
Public: false, Public: true,
}, { }, {
Namespace: "eth", Namespace: "eth",
Version: "1.0", Version: "1.0",
Service: filters.NewPublicFilterAPI(s.APIBackend, false, 5*time.Minute), Service: downloader.NewDownloaderAPI(s.handler.downloader, s.eventMux),
Public: true,
}, {
Namespace: "eth",
Version: "1.0",
Service: filters.NewFilterAPI(s.APIBackend, false, 5*time.Minute),
Public: true, Public: true,
}, { }, {
Namespace: "admin", Namespace: "admin",
Version: "1.0", Version: "1.0",
Service: NewPrivateAdminAPI(s), Service: NewAdminAPI(s),
}, { }, {
Namespace: "debug", Namespace: "debug",
Version: "1.0", Version: "1.0",
Service: NewPublicDebugAPI(s), Service: NewDebugAPI(s),
Public: true, Public: true,
}, {
Namespace: "debug",
Version: "1.0",
Service: NewPrivateDebugAPI(s),
}, { }, {
Namespace: "net", Namespace: "net",
Version: "1.0", Version: "1.0",

@ -25,21 +25,21 @@ import (
"github.com/ethereum/go-ethereum/rpc" "github.com/ethereum/go-ethereum/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 a loop until the event mux closes. It will install and uninstall new // eventLoop runs a 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
@ -133,9 +133,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.
@ -160,7 +160,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}
} }

@ -43,9 +43,9 @@ type filter struct {
s *Subscription // associated subscription in event system s *Subscription // associated subscription in event system
} }
// PublicFilterAPI offers support to create and manage filters. This will allow external clients to retrieve various // FilterAPI offers support to create and manage filters. This will allow external clients to retrieve various
// information related to the Ethereum protocol such als blocks, transactions and logs. // information related to the Ethereum protocol such als blocks, transactions and logs.
type PublicFilterAPI struct { type FilterAPI struct {
backend Backend backend Backend
events *EventSystem events *EventSystem
filtersMu sync.Mutex filtersMu sync.Mutex
@ -53,9 +53,9 @@ type PublicFilterAPI struct {
timeout time.Duration timeout time.Duration
} }
// NewPublicFilterAPI returns a new PublicFilterAPI instance. // NewFilterAPI returns a new FilterAPI instance.
func NewPublicFilterAPI(backend Backend, lightMode bool, timeout time.Duration) *PublicFilterAPI { func NewFilterAPI(backend Backend, lightMode bool, timeout time.Duration) *FilterAPI {
api := &PublicFilterAPI{ api := &FilterAPI{
backend: backend, backend: backend,
events: NewEventSystem(backend, lightMode), events: NewEventSystem(backend, lightMode),
filters: make(map[rpc.ID]*filter), filters: make(map[rpc.ID]*filter),
@ -68,7 +68,7 @@ func NewPublicFilterAPI(backend Backend, lightMode bool, timeout time.Duration)
// timeoutLoop runs at the interval set by 'timeout' and deletes filters // timeoutLoop runs at the interval set by 'timeout' and deletes filters
// that have not been recently used. It is started when the API is created. // that have not been recently used. It is started when the API is created.
func (api *PublicFilterAPI) timeoutLoop(timeout time.Duration) { func (api *FilterAPI) timeoutLoop(timeout time.Duration) {
var toUninstall []*Subscription var toUninstall []*Subscription
ticker := time.NewTicker(timeout) ticker := time.NewTicker(timeout)
defer ticker.Stop() defer ticker.Stop()
@ -101,7 +101,7 @@ func (api *PublicFilterAPI) timeoutLoop(timeout time.Duration) {
// //
// It is part of the filter package because this filter can be used through the // It is part of the filter package because this filter can be used through the
// `eth_getFilterChanges` polling method that is also used for log filters. // `eth_getFilterChanges` polling method that is also used for log filters.
func (api *PublicFilterAPI) NewPendingTransactionFilter() rpc.ID { func (api *FilterAPI) NewPendingTransactionFilter() rpc.ID {
var ( var (
pendingTxs = make(chan []common.Hash) pendingTxs = make(chan []common.Hash)
pendingTxSub = api.events.SubscribePendingTxs(pendingTxs) pendingTxSub = api.events.SubscribePendingTxs(pendingTxs)
@ -134,7 +134,7 @@ func (api *PublicFilterAPI) NewPendingTransactionFilter() rpc.ID {
// NewPendingTransactions creates a subscription that is triggered each time a transaction // NewPendingTransactions creates a subscription that is triggered each time a transaction
// enters the transaction pool and was signed from one of the transactions this nodes manages. // enters the transaction pool and was signed from one of the transactions this nodes manages.
func (api *PublicFilterAPI) NewPendingTransactions(ctx context.Context) (*rpc.Subscription, error) { func (api *FilterAPI) NewPendingTransactions(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
@ -169,7 +169,7 @@ func (api *PublicFilterAPI) NewPendingTransactions(ctx context.Context) (*rpc.Su
// NewBlockFilter creates a filter that fetches blocks that are imported into the chain. // NewBlockFilter creates a filter that fetches blocks that are imported into the chain.
// It is part of the filter package since polling goes with eth_getFilterChanges. // It is part of the filter package since polling goes with eth_getFilterChanges.
func (api *PublicFilterAPI) NewBlockFilter() rpc.ID { func (api *FilterAPI) NewBlockFilter() rpc.ID {
var ( var (
headers = make(chan *types.Header) headers = make(chan *types.Header)
headerSub = api.events.SubscribeNewHeads(headers) headerSub = api.events.SubscribeNewHeads(headers)
@ -201,7 +201,7 @@ func (api *PublicFilterAPI) NewBlockFilter() rpc.ID {
} }
// NewHeads send a notification each time a new (header) block is appended to the chain. // NewHeads send a notification each time a new (header) block is appended to the chain.
func (api *PublicFilterAPI) NewHeads(ctx context.Context) (*rpc.Subscription, error) { func (api *FilterAPI) NewHeads(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
@ -231,7 +231,7 @@ func (api *PublicFilterAPI) NewHeads(ctx context.Context) (*rpc.Subscription, er
} }
// Logs creates a subscription that fires for all new log that match the given filter criteria. // Logs creates a subscription that fires for all new log that match the given filter criteria.
func (api *PublicFilterAPI) Logs(ctx context.Context, crit FilterCriteria) (*rpc.Subscription, error) { func (api *FilterAPI) Logs(ctx context.Context, crit FilterCriteria) (*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
@ -284,7 +284,7 @@ type FilterCriteria ethereum.FilterQuery
// again but with the removed property set to true. // again but with the removed property set to true.
// //
// In case "fromBlock" > "toBlock" an error is returned. // In case "fromBlock" > "toBlock" an error is returned.
func (api *PublicFilterAPI) NewFilter(crit FilterCriteria) (rpc.ID, error) { func (api *FilterAPI) NewFilter(crit FilterCriteria) (rpc.ID, error) {
logs := make(chan []*types.Log) logs := make(chan []*types.Log)
logsSub, err := api.events.SubscribeLogs(ethereum.FilterQuery(crit), logs) logsSub, err := api.events.SubscribeLogs(ethereum.FilterQuery(crit), logs)
if err != nil { if err != nil {
@ -317,7 +317,7 @@ func (api *PublicFilterAPI) NewFilter(crit FilterCriteria) (rpc.ID, error) {
} }
// GetLogs returns logs matching the given argument that are stored within the state. // GetLogs returns logs matching the given argument that are stored within the state.
func (api *PublicFilterAPI) GetLogs(ctx context.Context, crit FilterCriteria) ([]*types.Log, error) { func (api *FilterAPI) GetLogs(ctx context.Context, crit FilterCriteria) ([]*types.Log, error) {
var filter *Filter var filter *Filter
if crit.BlockHash != nil { if crit.BlockHash != nil {
// Block filter requested, construct a single-shot filter // Block filter requested, construct a single-shot filter
@ -344,7 +344,7 @@ func (api *PublicFilterAPI) GetLogs(ctx context.Context, crit FilterCriteria) ([
} }
// UninstallFilter removes the filter with the given filter id. // UninstallFilter removes the filter with the given filter id.
func (api *PublicFilterAPI) UninstallFilter(id rpc.ID) bool { func (api *FilterAPI) UninstallFilter(id rpc.ID) bool {
api.filtersMu.Lock() api.filtersMu.Lock()
f, found := api.filters[id] f, found := api.filters[id]
if found { if found {
@ -360,7 +360,7 @@ func (api *PublicFilterAPI) UninstallFilter(id rpc.ID) bool {
// GetFilterLogs returns the logs for the filter with the given id. // GetFilterLogs returns the logs for the filter with the given id.
// If the filter could not be found an empty array of logs is returned. // If the filter could not be found an empty array of logs is returned.
func (api *PublicFilterAPI) GetFilterLogs(ctx context.Context, id rpc.ID) ([]*types.Log, error) { func (api *FilterAPI) GetFilterLogs(ctx context.Context, id rpc.ID) ([]*types.Log, error) {
api.filtersMu.Lock() api.filtersMu.Lock()
f, found := api.filters[id] f, found := api.filters[id]
api.filtersMu.Unlock() api.filtersMu.Unlock()
@ -399,7 +399,7 @@ func (api *PublicFilterAPI) GetFilterLogs(ctx context.Context, id rpc.ID) ([]*ty
// //
// For pending transaction and block filters the result is []common.Hash. // For pending transaction and block filters the result is []common.Hash.
// (pending)Log filters return []Log. // (pending)Log filters return []Log.
func (api *PublicFilterAPI) GetFilterChanges(id rpc.ID) (interface{}, error) { func (api *FilterAPI) GetFilterChanges(id rpc.ID) (interface{}, error) {
api.filtersMu.Lock() api.filtersMu.Lock()
defer api.filtersMu.Unlock() defer api.filtersMu.Unlock()

@ -171,7 +171,7 @@ func TestBlockSubscription(t *testing.T) {
var ( var (
db = rawdb.NewMemoryDatabase() db = rawdb.NewMemoryDatabase()
backend = &testBackend{db: db} backend = &testBackend{db: db}
api = NewPublicFilterAPI(backend, false, deadline) api = NewFilterAPI(backend, false, deadline)
genesis = (&core.Genesis{BaseFee: big.NewInt(params.InitialBaseFee)}).MustCommit(db) genesis = (&core.Genesis{BaseFee: big.NewInt(params.InitialBaseFee)}).MustCommit(db)
chain, _ = core.GenerateChain(params.TestChainConfig, genesis, ethash.NewFaker(), db, 10, func(i int, gen *core.BlockGen) {}) chain, _ = core.GenerateChain(params.TestChainConfig, genesis, ethash.NewFaker(), db, 10, func(i int, gen *core.BlockGen) {})
chainEvents = []core.ChainEvent{} chainEvents = []core.ChainEvent{}
@ -223,7 +223,7 @@ func TestPendingTxFilter(t *testing.T) {
var ( var (
db = rawdb.NewMemoryDatabase() db = rawdb.NewMemoryDatabase()
backend = &testBackend{db: db} backend = &testBackend{db: db}
api = NewPublicFilterAPI(backend, false, deadline) api = NewFilterAPI(backend, false, deadline)
transactions = []*types.Transaction{ transactions = []*types.Transaction{
types.NewTransaction(0, common.HexToAddress("0xb794f5ea0ba39494ce83a213fffba74279579268"), new(big.Int), 0, new(big.Int), nil), types.NewTransaction(0, common.HexToAddress("0xb794f5ea0ba39494ce83a213fffba74279579268"), new(big.Int), 0, new(big.Int), nil),
@ -278,7 +278,7 @@ func TestLogFilterCreation(t *testing.T) {
var ( var (
db = rawdb.NewMemoryDatabase() db = rawdb.NewMemoryDatabase()
backend = &testBackend{db: db} backend = &testBackend{db: db}
api = NewPublicFilterAPI(backend, false, deadline) api = NewFilterAPI(backend, false, deadline)
testCases = []struct { testCases = []struct {
crit FilterCriteria crit FilterCriteria
@ -325,7 +325,7 @@ func TestInvalidLogFilterCreation(t *testing.T) {
var ( var (
db = rawdb.NewMemoryDatabase() db = rawdb.NewMemoryDatabase()
backend = &testBackend{db: db} backend = &testBackend{db: db}
api = NewPublicFilterAPI(backend, false, deadline) api = NewFilterAPI(backend, false, deadline)
) )
// different situations where log filter creation should fail. // different situations where log filter creation should fail.
@ -347,7 +347,7 @@ func TestInvalidGetLogsRequest(t *testing.T) {
var ( var (
db = rawdb.NewMemoryDatabase() db = rawdb.NewMemoryDatabase()
backend = &testBackend{db: db} backend = &testBackend{db: db}
api = NewPublicFilterAPI(backend, false, deadline) api = NewFilterAPI(backend, false, deadline)
blockHash = common.HexToHash("0x1111111111111111111111111111111111111111111111111111111111111111") blockHash = common.HexToHash("0x1111111111111111111111111111111111111111111111111111111111111111")
) )
@ -372,7 +372,7 @@ func TestLogFilter(t *testing.T) {
var ( var (
db = rawdb.NewMemoryDatabase() db = rawdb.NewMemoryDatabase()
backend = &testBackend{db: db} backend = &testBackend{db: db}
api = NewPublicFilterAPI(backend, false, deadline) api = NewFilterAPI(backend, false, deadline)
firstAddr = common.HexToAddress("0x1111111111111111111111111111111111111111") firstAddr = common.HexToAddress("0x1111111111111111111111111111111111111111")
secondAddr = common.HexToAddress("0x2222222222222222222222222222222222222222") secondAddr = common.HexToAddress("0x2222222222222222222222222222222222222222")
@ -486,7 +486,7 @@ func TestPendingLogsSubscription(t *testing.T) {
var ( var (
db = rawdb.NewMemoryDatabase() db = rawdb.NewMemoryDatabase()
backend = &testBackend{db: db} backend = &testBackend{db: db}
api = NewPublicFilterAPI(backend, false, deadline) api = NewFilterAPI(backend, false, deadline)
firstAddr = common.HexToAddress("0x1111111111111111111111111111111111111111") firstAddr = common.HexToAddress("0x1111111111111111111111111111111111111111")
secondAddr = common.HexToAddress("0x2222222222222222222222222222222222222222") secondAddr = common.HexToAddress("0x2222222222222222222222222222222222222222")
@ -670,7 +670,7 @@ func TestPendingTxFilterDeadlock(t *testing.T) {
var ( var (
db = rawdb.NewMemoryDatabase() db = rawdb.NewMemoryDatabase()
backend = &testBackend{db: db} backend = &testBackend{db: db}
api = NewPublicFilterAPI(backend, false, timeout) api = NewFilterAPI(backend, false, timeout)
done = make(chan struct{}) done = make(chan struct{})
) )

@ -48,19 +48,18 @@ import (
"github.com/tyler-smith/go-bip39" "github.com/tyler-smith/go-bip39"
) )
// 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. type EthereumAPI struct {
type PublicEthereumAPI 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
@ -72,7 +71,7 @@ func (s *PublicEthereumAPI) GasPrice(ctx context.Context) (*hexutil.Big, error)
} }
// MaxPriorityFeePerGas returns a suggestion for a gas tip cap for dynamic fee transactions. // MaxPriorityFeePerGas returns a suggestion for a gas tip cap for dynamic fee 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
@ -87,7 +86,7 @@ type feeHistoryResult struct {
GasUsedRatio []float64 `json:"gasUsedRatio"` GasUsedRatio []float64 `json:"gasUsedRatio"`
} }
func (s *PublicEthereumAPI) FeeHistory(ctx context.Context, blockCount rpc.DecimalOrHex, lastBlock rpc.BlockNumber, rewardPercentiles []float64) (*feeHistoryResult, error) { func (s *EthereumAPI) FeeHistory(ctx context.Context, blockCount rpc.DecimalOrHex, lastBlock rpc.BlockNumber, rewardPercentiles []float64) (*feeHistoryResult, error) {
oldest, reward, baseFee, gasUsed, err := s.b.FeeHistory(ctx, int(blockCount), lastBlock, rewardPercentiles) oldest, reward, baseFee, gasUsed, err := s.b.FeeHistory(ctx, int(blockCount), lastBlock, rewardPercentiles)
if err != nil { if err != nil {
return nil, err return nil, err
@ -121,7 +120,7 @@ func (s *PublicEthereumAPI) FeeHistory(ctx context.Context, blockCount rpc.Decim
// - 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.SyncProgress() progress := s.b.SyncProgress()
// Return not syncing if the synchronisation already completed // Return not syncing if the synchronisation already completed
@ -148,18 +147,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),
@ -186,7 +185,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()
@ -209,7 +208,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),
@ -219,7 +218,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),
@ -252,34 +251,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,
@ -287,7 +286,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()
} }
@ -301,7 +300,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()
@ -323,7 +322,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
@ -337,7 +336,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
@ -353,7 +352,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.Address, error) { func (s *PersonalAccountAPI) NewAccount(password string) (common.Address, error) {
ks, err := fetchKeystore(s.am) ks, err := fetchKeystore(s.am)
if err != nil { if err != nil {
return common.Address{}, err return common.Address{}, err
@ -378,7 +377,7 @@ func fetchKeystore(am *accounts.Manager) (*keystore.KeyStore, error) {
// 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
@ -394,7 +393,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(ctx context.Context, addr common.Address, password string, duration *uint64) (bool, error) { func (s *PersonalAccountAPI) UnlockAccount(ctx context.Context, addr common.Address, password string, duration *uint64) (bool, error) {
// When the API is exposed by external RPC(http, ws etc), unless the user // When the API is exposed by external RPC(http, ws etc), unless the user
// explicitly specifies to allow the insecure account unlocking, otherwise // explicitly specifies to allow the insecure account unlocking, otherwise
// it is disabled. // it is disabled.
@ -423,7 +422,7 @@ func (s *PrivateAccountAPI) UnlockAccount(ctx context.Context, addr common.Addre
} }
// 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 {
if ks, err := fetchKeystore(s.am); err == nil { if ks, err := fetchKeystore(s.am); err == nil {
return ks.Lock(addr) == nil return ks.Lock(addr) == nil
} }
@ -433,7 +432,7 @@ func (s *PrivateAccountAPI) LockAccount(addr common.Address) bool {
// signTransaction sets defaults and signs the given transaction // signTransaction 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)
@ -453,7 +452,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.
@ -472,7 +471,7 @@ func (s *PrivateAccountAPI) SendTransaction(ctx context.Context, args Transactio
// tries to sign it with the key associated with args.From. If the given passwd isn't // tries to sign it with the key associated with args.From. 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 {
@ -513,7 +512,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/ethereum/go-ethereum/wiki/Management-APIs#personal_sign // https://github.com/ethereum/go-ethereum/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}
@ -541,7 +540,7 @@ func (s *PrivateAccountAPI) Sign(ctx context.Context, data hexutil.Bytes, addr c
// the V value must be 27 or 28 for legacy reasons. // the V value must be 27 or 28 for legacy reasons.
// //
// https://github.com/ethereum/go-ethereum/wiki/Management-APIs#personal_ecRecover // https://github.com/ethereum/go-ethereum/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)
} }
@ -558,7 +557,7 @@ func (s *PrivateAccountAPI) EcRecover(ctx context.Context, data, sig hexutil.Byt
} }
// InitializeWallet initializes a new wallet at the provided URL, by generating and returning a new private key. // InitializeWallet initializes a new wallet at the provided URL, by generating and returning a new private key.
func (s *PrivateAccountAPI) InitializeWallet(ctx context.Context, url string) (string, error) { func (s *PersonalAccountAPI) InitializeWallet(ctx context.Context, url string) (string, error) {
wallet, err := s.am.Wallet(url) wallet, err := s.am.Wallet(url)
if err != nil { if err != nil {
return "", err return "", err
@ -585,7 +584,7 @@ func (s *PrivateAccountAPI) InitializeWallet(ctx context.Context, url string) (s
} }
// Unpair deletes a pairing between wallet and geth. // Unpair deletes a pairing between wallet and geth.
func (s *PrivateAccountAPI) Unpair(ctx context.Context, url string, pin string) error { func (s *PersonalAccountAPI) Unpair(ctx context.Context, url string, pin string) error {
wallet, err := s.am.Wallet(url) wallet, err := s.am.Wallet(url)
if err != nil { if err != nil {
return err return err
@ -599,19 +598,18 @@ func (s *PrivateAccountAPI) Unpair(ctx context.Context, url string, pin string)
} }
} }
// 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
} }
// NewPublicBlockChainAPI creates a new Ethereum blockchain API. // NewBlockChainAPI creates a new Ethereum blockchain API.
func NewPublicBlockChainAPI(b Backend) *PublicBlockChainAPI { func NewBlockChainAPI(b Backend) *BlockChainAPI {
return &PublicBlockChainAPI{b} return &BlockChainAPI{b}
} }
// ChainId is the EIP-155 replay-protection chain id for the current ethereum chain config. // ChainId is the EIP-155 replay-protection chain id for the current Ethereum chain config.
func (api *PublicBlockChainAPI) ChainId() (*hexutil.Big, error) { func (api *BlockChainAPI) ChainId() (*hexutil.Big, error) {
// if current block is at or past the EIP-155 replay-protection fork block, return chainID from config // if current block is at or past the EIP-155 replay-protection fork block, return chainID from config
if config := api.b.ChainConfig(); config.IsEIP155(api.b.CurrentBlock().Number()) { if config := api.b.ChainConfig(); config.IsEIP155(api.b.CurrentBlock().Number()) {
return (*hexutil.Big)(config.ChainID), nil return (*hexutil.Big)(config.ChainID), nil
@ -620,7 +618,7 @@ func (api *PublicBlockChainAPI) ChainId() (*hexutil.Big, error) {
} }
// 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())
} }
@ -628,7 +626,7 @@ func (s *PublicBlockChainAPI) BlockNumber() hexutil.Uint64 {
// 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
@ -654,7 +652,7 @@ type StorageResult struct {
} }
// GetProof returns the Merkle-proof for a given account and optionally some storage keys. // GetProof returns the Merkle-proof for a given account and optionally some storage keys.
func (s *PublicBlockChainAPI) GetProof(ctx context.Context, address common.Address, storageKeys []string, blockNrOrHash rpc.BlockNumberOrHash) (*AccountResult, error) { func (s *BlockChainAPI) GetProof(ctx context.Context, address common.Address, storageKeys []string, blockNrOrHash rpc.BlockNumberOrHash) (*AccountResult, 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
@ -706,7 +704,7 @@ func (s *PublicBlockChainAPI) GetProof(ctx context.Context, address common.Addre
// GetHeaderByNumber returns the requested canonical block header. // GetHeaderByNumber returns the requested canonical block header.
// * When blockNr is -1 the chain head is returned. // * When blockNr is -1 the chain head is returned.
// * When blockNr is -2 the pending chain head is returned. // * When blockNr is -2 the pending chain head is returned.
func (s *PublicBlockChainAPI) GetHeaderByNumber(ctx context.Context, number rpc.BlockNumber) (map[string]interface{}, error) { func (s *BlockChainAPI) GetHeaderByNumber(ctx context.Context, number rpc.BlockNumber) (map[string]interface{}, error) {
header, err := s.b.HeaderByNumber(ctx, number) header, err := s.b.HeaderByNumber(ctx, number)
if header != nil && err == nil { if header != nil && err == nil {
response := s.rpcMarshalHeader(ctx, header) response := s.rpcMarshalHeader(ctx, header)
@ -722,7 +720,7 @@ func (s *PublicBlockChainAPI) GetHeaderByNumber(ctx context.Context, number rpc.
} }
// GetHeaderByHash returns the requested header by hash. // GetHeaderByHash returns the requested header by hash.
func (s *PublicBlockChainAPI) GetHeaderByHash(ctx context.Context, hash common.Hash) map[string]interface{} { func (s *BlockChainAPI) GetHeaderByHash(ctx context.Context, hash common.Hash) map[string]interface{} {
header, _ := s.b.HeaderByHash(ctx, hash) header, _ := s.b.HeaderByHash(ctx, hash)
if header != nil { if header != nil {
return s.rpcMarshalHeader(ctx, header) return s.rpcMarshalHeader(ctx, header)
@ -735,7 +733,7 @@ func (s *PublicBlockChainAPI) GetHeaderByHash(ctx context.Context, hash common.H
// * When blockNr is -2 the pending chain head is returned. // * When blockNr is -2 the pending chain head is returned.
// * When fullTx is true all transactions in the block are returned, otherwise // * When fullTx is true all transactions in the block are returned, otherwise
// only the transaction hash is returned. // only the transaction hash is returned.
func (s *PublicBlockChainAPI) GetBlockByNumber(ctx context.Context, number rpc.BlockNumber, fullTx bool) (map[string]interface{}, error) { func (s *BlockChainAPI) GetBlockByNumber(ctx context.Context, number rpc.BlockNumber, fullTx bool) (map[string]interface{}, error) {
block, err := s.b.BlockByNumber(ctx, number) block, err := s.b.BlockByNumber(ctx, number)
if block != nil && err == nil { if block != nil && err == nil {
response, err := s.rpcMarshalBlock(ctx, block, true, fullTx) response, err := s.rpcMarshalBlock(ctx, block, true, fullTx)
@ -752,7 +750,7 @@ func (s *PublicBlockChainAPI) GetBlockByNumber(ctx context.Context, number rpc.B
// 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, hash common.Hash, fullTx bool) (map[string]interface{}, error) { func (s *BlockChainAPI) GetBlockByHash(ctx context.Context, hash common.Hash, fullTx bool) (map[string]interface{}, error) {
block, err := s.b.BlockByHash(ctx, hash) block, err := s.b.BlockByHash(ctx, hash)
if block != nil { if block != nil {
return s.rpcMarshalBlock(ctx, block, true, fullTx) return s.rpcMarshalBlock(ctx, block, true, fullTx)
@ -761,7 +759,7 @@ func (s *PublicBlockChainAPI) GetBlockByHash(ctx context.Context, hash common.Ha
} }
// GetUncleByBlockNumberAndIndex returns the uncle block for the given block hash and index. // GetUncleByBlockNumberAndIndex returns the uncle block for the given block hash and index.
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()
@ -776,7 +774,7 @@ func (s *PublicBlockChainAPI) GetUncleByBlockNumberAndIndex(ctx context.Context,
} }
// GetUncleByBlockHashAndIndex returns the uncle block for the given block hash and index. // GetUncleByBlockHashAndIndex returns the uncle block for the given block hash and index.
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.BlockByHash(ctx, blockHash) block, err := s.b.BlockByHash(ctx, blockHash)
if block != nil { if block != nil {
uncles := block.Uncles() uncles := block.Uncles()
@ -791,7 +789,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
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
@ -800,7 +798,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
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.BlockByHash(ctx, blockHash); block != nil { if block, _ := s.b.BlockByHash(ctx, blockHash); block != nil {
n := hexutil.Uint(len(block.Uncles())) n := hexutil.Uint(len(block.Uncles()))
return &n return &n
@ -809,7 +807,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
@ -821,7 +819,7 @@ func (s *PublicBlockChainAPI) GetCode(ctx context.Context, address common.Addres
// 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
@ -1008,7 +1006,7 @@ func (e *revertError) ErrorData() interface{} {
// //
// Note, this function doesn't make and changes in the state/blockchain and is // Note, this function doesn't make and changes in the state/blockchain and is
// useful to execute and retrieve values. // 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) {
result, err := DoCall(ctx, s.b, args, blockNrOrHash, overrides, s.b.RPCEVMTimeout(), s.b.RPCGasCap()) result, err := DoCall(ctx, s.b, args, blockNrOrHash, overrides, s.b.RPCEVMTimeout(), s.b.RPCGasCap())
if err != nil { if err != nil {
return nil, err return nil, err
@ -1142,7 +1140,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) (hexutil.Uint64, error) { func (s *BlockChainAPI) EstimateGas(ctx context.Context, args TransactionArgs, blockNrOrHash *rpc.BlockNumberOrHash) (hexutil.Uint64, error) {
bNrOrHash := rpc.BlockNumberOrHashWithNumber(rpc.PendingBlockNumber) bNrOrHash := rpc.BlockNumberOrHashWithNumber(rpc.PendingBlockNumber)
if blockNrOrHash != nil { if blockNrOrHash != nil {
bNrOrHash = *blockNrOrHash bNrOrHash = *blockNrOrHash
@ -1216,16 +1214,16 @@ func RPCMarshalBlock(block *types.Block, inclTx bool, fullTx bool, config *param
} }
// rpcMarshalHeader uses the generalized output filler, then adds the total difficulty field, which requires // rpcMarshalHeader uses the generalized output filler, then adds the total difficulty field, which requires
// a `PublicBlockchainAPI`. // a `BlockchainAPI`.
func (s *PublicBlockChainAPI) rpcMarshalHeader(ctx context.Context, header *types.Header) map[string]interface{} { func (s *BlockChainAPI) rpcMarshalHeader(ctx context.Context, header *types.Header) map[string]interface{} {
fields := RPCMarshalHeader(header) fields := RPCMarshalHeader(header)
fields["totalDifficulty"] = (*hexutil.Big)(s.b.GetTd(ctx, header.Hash())) fields["totalDifficulty"] = (*hexutil.Big)(s.b.GetTd(ctx, header.Hash()))
return fields return fields
} }
// rpcMarshalBlock uses the generalized output filler, then adds the total difficulty field, which requires // rpcMarshalBlock uses the generalized output filler, then adds the total difficulty field, which requires
// a `PublicBlockchainAPI`. // a `BlockchainAPI`.
func (s *PublicBlockChainAPI) rpcMarshalBlock(ctx context.Context, b *types.Block, inclTx bool, fullTx bool) (map[string]interface{}, error) { func (s *BlockChainAPI) rpcMarshalBlock(ctx context.Context, b *types.Block, inclTx bool, fullTx bool) (map[string]interface{}, error) {
fields, err := RPCMarshalBlock(b, inclTx, fullTx, s.b.ChainConfig()) fields, err := RPCMarshalBlock(b, inclTx, fullTx, s.b.ChainConfig())
if err != nil { if err != nil {
return nil, err return nil, err
@ -1358,7 +1356,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
@ -1447,23 +1445,23 @@ 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
} }
// NewPublicTransactionPoolAPI creates a new RPC service with methods specific for the transaction pool. // NewTransactionAPI creates a new RPC service with methods for interacting with transactions.
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}
} }
// 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
@ -1472,7 +1470,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.BlockByHash(ctx, blockHash); block != nil { if block, _ := s.b.BlockByHash(ctx, blockHash); block != nil {
n := hexutil.Uint(len(block.Transactions())) n := hexutil.Uint(len(block.Transactions()))
return &n return &n
@ -1481,7 +1479,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), s.b.ChainConfig()) return newRPCTransactionFromBlockIndex(block, uint64(index), s.b.ChainConfig())
} }
@ -1489,7 +1487,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.BlockByHash(ctx, blockHash); block != nil { if block, _ := s.b.BlockByHash(ctx, blockHash); block != nil {
return newRPCTransactionFromBlockIndex(block, uint64(index), s.b.ChainConfig()) return newRPCTransactionFromBlockIndex(block, uint64(index), s.b.ChainConfig())
} }
@ -1497,7 +1495,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))
} }
@ -1505,7 +1503,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.BlockByHash(ctx, blockHash); block != nil { if block, _ := s.b.BlockByHash(ctx, blockHash); block != nil {
return newRPCRawTransactionFromBlockIndex(block, uint64(index)) return newRPCRawTransactionFromBlockIndex(block, uint64(index))
} }
@ -1513,7 +1511,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)
@ -1532,7 +1530,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, err := s.b.GetTransaction(ctx, hash) tx, blockHash, blockNumber, index, err := s.b.GetTransaction(ctx, hash)
if err != nil { if err != nil {
@ -1555,7 +1553,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, _, _, _, err := s.b.GetTransaction(ctx, hash) tx, _, _, _, err := s.b.GetTransaction(ctx, hash)
if err != nil { if err != nil {
@ -1572,7 +1570,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, err := s.b.GetTransaction(ctx, hash) tx, blockHash, blockNumber, index, err := s.b.GetTransaction(ctx, hash)
if err != nil { if err != 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
@ -1635,7 +1633,7 @@ func (s *PublicTransactionPoolAPI) GetTransactionReceipt(ctx context.Context, ha
} }
// 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}
@ -1679,7 +1677,7 @@ func SubmitTransaction(ctx context.Context, b Backend, tx *types.Transaction) (c
// 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()}
@ -1712,7 +1710,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); err != nil { if err := args.setDefaults(ctx, s.b); err != nil {
return nil, err return nil, err
@ -1728,7 +1726,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
@ -1745,7 +1743,7 @@ func (s *PublicTransactionPoolAPI) SendRawTransaction(ctx context.Context, input
// 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}
@ -1770,7 +1768,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, fmt.Errorf("gas not specified") return nil, fmt.Errorf("gas not specified")
} }
@ -1801,7 +1799,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
@ -1825,7 +1823,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{}, fmt.Errorf("missing transaction nonce in transaction spec") return common.Hash{}, fmt.Errorf("missing transaction nonce in transaction spec")
} }
@ -1875,20 +1873,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}
} }
// GetHeaderRlp retrieves the RLP encoded for of a single header. // GetHeaderRlp retrieves the RLP encoded for of a single header.
func (api *PublicDebugAPI) GetHeaderRlp(ctx context.Context, number uint64) (hexutil.Bytes, error) { func (api *DebugAPI) GetHeaderRlp(ctx context.Context, number uint64) (hexutil.Bytes, error) {
header, _ := api.b.HeaderByNumber(ctx, rpc.BlockNumber(number)) header, _ := api.b.HeaderByNumber(ctx, rpc.BlockNumber(number))
if header == nil { if header == nil {
return nil, fmt.Errorf("header #%d not found", number) return nil, fmt.Errorf("header #%d not found", number)
@ -1897,7 +1894,7 @@ func (api *PublicDebugAPI) GetHeaderRlp(ctx context.Context, number uint64) (hex
} }
// 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) (hexutil.Bytes, error) { func (api *DebugAPI) GetBlockRlp(ctx context.Context, number uint64) (hexutil.Bytes, error) {
block, _ := api.b.BlockByNumber(ctx, rpc.BlockNumber(number)) block, _ := api.b.BlockByNumber(ctx, rpc.BlockNumber(number))
if block == nil { if block == nil {
return nil, fmt.Errorf("block #%d not found", number) return nil, fmt.Errorf("block #%d not found", number)
@ -1906,7 +1903,7 @@ func (api *PublicDebugAPI) GetBlockRlp(ctx context.Context, number uint64) (hexu
} }
// GetRawReceipts retrieves the binary-encoded raw receipts of a single block. // GetRawReceipts retrieves the binary-encoded raw receipts of a single block.
func (api *PublicDebugAPI) GetRawReceipts(ctx context.Context, blockNrOrHash rpc.BlockNumberOrHash) ([]hexutil.Bytes, error) { func (api *DebugAPI) GetRawReceipts(ctx context.Context, blockNrOrHash rpc.BlockNumberOrHash) ([]hexutil.Bytes, error) {
var hash common.Hash var hash common.Hash
if h, ok := blockNrOrHash.Hash(); ok { if h, ok := blockNrOrHash.Hash(); ok {
hash = h hash = h
@ -1933,7 +1930,7 @@ func (api *PublicDebugAPI) GetRawReceipts(ctx context.Context, blockNrOrHash rpc
} }
// 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)
@ -1942,7 +1939,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)
@ -1950,20 +1947,8 @@ func (api *PublicDebugAPI) SeedHash(ctx context.Context, number uint64) (string,
return fmt.Sprintf("0x%x", ethash.SeedHash(number)), nil return fmt.Sprintf("0x%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 key-value database. // ChaindbProperty returns leveldb properties of the key-value database.
func (api *PrivateDebugAPI) ChaindbProperty(property string) (string, error) { func (api *DebugAPI) ChaindbProperty(property string) (string, error) {
if property == "" { if property == "" {
property = "leveldb.stats" property = "leveldb.stats"
} else if !strings.HasPrefix(property, "leveldb.") { } else if !strings.HasPrefix(property, "leveldb.") {
@ -1974,7 +1959,7 @@ func (api *PrivateDebugAPI) ChaindbProperty(property string) (string, error) {
// ChaindbCompact flattens the entire key-value database into a single level, // ChaindbCompact flattens the entire key-value database into a single level,
// removing all unused slots and merging all keys. // removing all unused slots and merging all keys.
func (api *PrivateDebugAPI) ChaindbCompact() error { func (api *DebugAPI) ChaindbCompact() error {
for b := byte(0); b < 255; b++ { for b := byte(0); b < 255; b++ {
log.Info("Compacting chain database", "range", fmt.Sprintf("0x%0.2X-0x%0.2X", b, b+1)) log.Info("Compacting chain database", "range", fmt.Sprintf("0x%0.2X-0x%0.2X", b, b+1))
if err := api.b.ChainDb().Compact([]byte{b}, []byte{b + 1}); err != nil { if err := api.b.ChainDb().Compact([]byte{b}, []byte{b + 1}); err != nil {
@ -1986,33 +1971,33 @@ 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))
} }
// 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)
} }

@ -102,41 +102,37 @@ func GetAPIs(apiBackend Backend) []rpc.API {
{ {
Namespace: "eth", Namespace: "eth",
Version: "1.0", Version: "1.0",
Service: NewPublicEthereumAPI(apiBackend), Service: NewEthereumAPI(apiBackend),
Public: true, Public: true,
}, { }, {
Namespace: "eth", Namespace: "eth",
Version: "1.0", Version: "1.0",
Service: NewPublicBlockChainAPI(apiBackend), Service: NewBlockChainAPI(apiBackend),
Public: true, Public: true,
}, { }, {
Namespace: "eth", Namespace: "eth",
Version: "1.0", Version: "1.0",
Service: NewPublicTransactionPoolAPI(apiBackend, nonceLock), Service: NewTransactionAPI(apiBackend, nonceLock),
Public: true, Public: true,
}, { }, {
Namespace: "txpool", Namespace: "txpool",
Version: "1.0", Version: "1.0",
Service: NewPublicTxPoolAPI(apiBackend), Service: NewTxPoolAPI(apiBackend),
Public: true, Public: true,
}, { }, {
Namespace: "debug", Namespace: "debug",
Version: "1.0", Version: "1.0",
Service: NewPublicDebugAPI(apiBackend), Service: NewDebugAPI(apiBackend),
Public: true, Public: true,
}, {
Namespace: "debug",
Version: "1.0",
Service: NewPrivateDebugAPI(apiBackend),
}, { }, {
Namespace: "eth", Namespace: "eth",
Version: "1.0", Version: "1.0",
Service: NewPublicAccountAPI(apiBackend.AccountManager()), Service: NewEthereumAccountAPI(apiBackend.AccountManager()),
Public: true, Public: true,
}, { }, {
Namespace: "personal", Namespace: "personal",
Version: "1.0", Version: "1.0",
Service: NewPrivateAccountAPI(apiBackend, nonceLock), Service: NewPersonalAccountAPI(apiBackend, nonceLock),
Public: false, Public: false,
}, },
} }

@ -22,7 +22,7 @@ import (
) )
// 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
@ -32,12 +32,12 @@ func (api *PrivateDebugAPI) DbGet(key string) (hexutil.Bytes, error) {
// DbAncient retrieves an ancient binary blob from the append-only immutable files. // DbAncient retrieves an ancient binary blob from the append-only immutable files.
// It is a mapping to the `AncientReaderOp.Ancient` method // It is a mapping to the `AncientReaderOp.Ancient` method
func (api *PrivateDebugAPI) DbAncient(kind string, number uint64) (hexutil.Bytes, error) { func (api *DebugAPI) DbAncient(kind string, number uint64) (hexutil.Bytes, error) {
return api.b.ChainDb().Ancient(kind, number) return api.b.ChainDb().Ancient(kind, number)
} }
// DbAncients returns the ancient item numbers in the ancient store. // DbAncients returns the ancient item numbers in the ancient store.
// It is a mapping to the `AncientReaderOp.Ancients` method // It is a mapping to the `AncientReaderOp.Ancients` method
func (api *PrivateDebugAPI) DbAncients() (uint64, error) { func (api *DebugAPI) DbAncients() (uint64, error) {
return api.b.ChainDb().Ancients() return api.b.ChainDb().Ancients()
} }

@ -33,15 +33,15 @@ var (
errUnknownBenchmarkType = errors.New("unknown benchmark type") errUnknownBenchmarkType = errors.New("unknown benchmark type")
) )
// PrivateLightServerAPI provides an API to access the LES light server. // LightServerAPI provides an API to access the LES light server.
type PrivateLightServerAPI struct { type LightServerAPI struct {
server *LesServer server *LesServer
defaultPosFactors, defaultNegFactors vfs.PriceFactors defaultPosFactors, defaultNegFactors vfs.PriceFactors
} }
// NewPrivateLightServerAPI creates a new LES light server API. // NewLightServerAPI creates a new LES light server API.
func NewPrivateLightServerAPI(server *LesServer) *PrivateLightServerAPI { func NewLightServerAPI(server *LesServer) *LightServerAPI {
return &PrivateLightServerAPI{ return &LightServerAPI{
server: server, server: server,
defaultPosFactors: defaultPosFactors, defaultPosFactors: defaultPosFactors,
defaultNegFactors: defaultNegFactors, defaultNegFactors: defaultNegFactors,
@ -61,7 +61,7 @@ func parseNode(node string) (enode.ID, error) {
} }
// ServerInfo returns global server parameters // ServerInfo returns global server parameters
func (api *PrivateLightServerAPI) ServerInfo() map[string]interface{} { func (api *LightServerAPI) ServerInfo() map[string]interface{} {
res := make(map[string]interface{}) res := make(map[string]interface{})
res["minimumCapacity"] = api.server.minCapacity res["minimumCapacity"] = api.server.minCapacity
res["maximumCapacity"] = api.server.maxCapacity res["maximumCapacity"] = api.server.maxCapacity
@ -72,7 +72,7 @@ func (api *PrivateLightServerAPI) ServerInfo() map[string]interface{} {
} }
// ClientInfo returns information about clients listed in the ids list or matching the given tags // ClientInfo returns information about clients listed in the ids list or matching the given tags
func (api *PrivateLightServerAPI) ClientInfo(nodes []string) map[enode.ID]map[string]interface{} { func (api *LightServerAPI) ClientInfo(nodes []string) map[enode.ID]map[string]interface{} {
var ids []enode.ID var ids []enode.ID
for _, node := range nodes { for _, node := range nodes {
if id, err := parseNode(node); err == nil { if id, err := parseNode(node); err == nil {
@ -102,7 +102,7 @@ func (api *PrivateLightServerAPI) ClientInfo(nodes []string) map[enode.ID]map[st
// If maxCount limit is applied but there are more potential results then the ID // If maxCount limit is applied but there are more potential results then the ID
// of the next potential result is included in the map with an empty structure // of the next potential result is included in the map with an empty structure
// assigned to it. // assigned to it.
func (api *PrivateLightServerAPI) PriorityClientInfo(start, stop enode.ID, maxCount int) map[enode.ID]map[string]interface{} { func (api *LightServerAPI) PriorityClientInfo(start, stop enode.ID, maxCount int) map[enode.ID]map[string]interface{} {
res := make(map[enode.ID]map[string]interface{}) res := make(map[enode.ID]map[string]interface{})
ids := api.server.clientPool.GetPosBalanceIDs(start, stop, maxCount+1) ids := api.server.clientPool.GetPosBalanceIDs(start, stop, maxCount+1)
if len(ids) > maxCount { if len(ids) > maxCount {
@ -122,7 +122,7 @@ func (api *PrivateLightServerAPI) PriorityClientInfo(start, stop enode.ID, maxCo
} }
// clientInfo creates a client info data structure // clientInfo creates a client info data structure
func (api *PrivateLightServerAPI) clientInfo(peer *clientPeer, balance vfs.ReadOnlyBalance) map[string]interface{} { func (api *LightServerAPI) clientInfo(peer *clientPeer, balance vfs.ReadOnlyBalance) map[string]interface{} {
info := make(map[string]interface{}) info := make(map[string]interface{})
pb, nb := balance.GetBalance() pb, nb := balance.GetBalance()
info["isConnected"] = peer != nil info["isConnected"] = peer != nil
@ -140,7 +140,7 @@ func (api *PrivateLightServerAPI) clientInfo(peer *clientPeer, balance vfs.ReadO
// setParams either sets the given parameters for a single connected client (if specified) // setParams either sets the given parameters for a single connected client (if specified)
// or the default parameters applicable to clients connected in the future // or the default parameters applicable to clients connected in the future
func (api *PrivateLightServerAPI) setParams(params map[string]interface{}, client *clientPeer, posFactors, negFactors *vfs.PriceFactors) (updateFactors bool, err error) { func (api *LightServerAPI) setParams(params map[string]interface{}, client *clientPeer, posFactors, negFactors *vfs.PriceFactors) (updateFactors bool, err error) {
defParams := client == nil defParams := client == nil
for name, value := range params { for name, value := range params {
errValue := func() error { errValue := func() error {
@ -191,7 +191,7 @@ func (api *PrivateLightServerAPI) setParams(params map[string]interface{}, clien
// SetClientParams sets client parameters for all clients listed in the ids list // SetClientParams sets client parameters for all clients listed in the ids list
// or all connected clients if the list is empty // or all connected clients if the list is empty
func (api *PrivateLightServerAPI) SetClientParams(nodes []string, params map[string]interface{}) error { func (api *LightServerAPI) SetClientParams(nodes []string, params map[string]interface{}) error {
var err error var err error
for _, node := range nodes { for _, node := range nodes {
var id enode.ID var id enode.ID
@ -215,7 +215,7 @@ func (api *PrivateLightServerAPI) SetClientParams(nodes []string, params map[str
} }
// SetDefaultParams sets the default parameters applicable to clients connected in the future // SetDefaultParams sets the default parameters applicable to clients connected in the future
func (api *PrivateLightServerAPI) SetDefaultParams(params map[string]interface{}) error { func (api *LightServerAPI) SetDefaultParams(params map[string]interface{}) error {
update, err := api.setParams(params, nil, &api.defaultPosFactors, &api.defaultNegFactors) update, err := api.setParams(params, nil, &api.defaultPosFactors, &api.defaultNegFactors)
if update { if update {
api.server.clientPool.SetDefaultFactors(api.defaultPosFactors, api.defaultNegFactors) api.server.clientPool.SetDefaultFactors(api.defaultPosFactors, api.defaultNegFactors)
@ -227,7 +227,7 @@ func (api *PrivateLightServerAPI) SetDefaultParams(params map[string]interface{}
// So that already connected client won't be kicked out very soon and we can ensure all // So that already connected client won't be kicked out very soon and we can ensure all
// connected clients can have enough time to request or sync some data. // connected clients can have enough time to request or sync some data.
// When the input parameter `bias` < 0 (illegal), return error. // When the input parameter `bias` < 0 (illegal), return error.
func (api *PrivateLightServerAPI) SetConnectedBias(bias time.Duration) error { func (api *LightServerAPI) SetConnectedBias(bias time.Duration) error {
if bias < time.Duration(0) { if bias < time.Duration(0) {
return fmt.Errorf("bias illegal: %v less than 0", bias) return fmt.Errorf("bias illegal: %v less than 0", bias)
} }
@ -237,7 +237,7 @@ func (api *PrivateLightServerAPI) SetConnectedBias(bias time.Duration) error {
// AddBalance adds the given amount to the balance of a client if possible and returns // AddBalance adds the given amount to the balance of a client if possible and returns
// the balance before and after the operation // the balance before and after the operation
func (api *PrivateLightServerAPI) AddBalance(node string, amount int64) (balance [2]uint64, err error) { func (api *LightServerAPI) AddBalance(node string, amount int64) (balance [2]uint64, err error) {
var id enode.ID var id enode.ID
if id, err = parseNode(node); err != nil { if id, err = parseNode(node); err != nil {
return return
@ -254,7 +254,7 @@ func (api *PrivateLightServerAPI) AddBalance(node string, amount int64) (balance
// //
// Note: measurement time is adjusted for each pass depending on the previous ones. // Note: measurement time is adjusted for each pass depending on the previous ones.
// Therefore a controlled total measurement time is achievable in multiple passes. // Therefore a controlled total measurement time is achievable in multiple passes.
func (api *PrivateLightServerAPI) Benchmark(setups []map[string]interface{}, passCount, length int) ([]map[string]interface{}, error) { func (api *LightServerAPI) Benchmark(setups []map[string]interface{}, passCount, length int) ([]map[string]interface{}, error) {
benchmarks := make([]requestBenchmark, len(setups)) benchmarks := make([]requestBenchmark, len(setups))
for i, setup := range setups { for i, setup := range setups {
if t, ok := setup["type"].(string); ok { if t, ok := setup["type"].(string); ok {
@ -324,20 +324,20 @@ func (api *PrivateLightServerAPI) Benchmark(setups []map[string]interface{}, pas
return result, nil return result, nil
} }
// PrivateDebugAPI provides an API to debug LES light server functionality. // DebugAPI provides an API to debug LES light server functionality.
type PrivateDebugAPI struct { type DebugAPI struct {
server *LesServer server *LesServer
} }
// NewPrivateDebugAPI creates a new LES light server debug API. // NewDebugAPI creates a new LES light server debug API.
func NewPrivateDebugAPI(server *LesServer) *PrivateDebugAPI { func NewDebugAPI(server *LesServer) *DebugAPI {
return &PrivateDebugAPI{ return &DebugAPI{
server: server, server: server,
} }
} }
// FreezeClient forces a temporary client freeze which normally happens when the server is overloaded // FreezeClient forces a temporary client freeze which normally happens when the server is overloaded
func (api *PrivateDebugAPI) FreezeClient(node string) error { func (api *DebugAPI) FreezeClient(node string) error {
var ( var (
id enode.ID id enode.ID
err error err error
@ -353,14 +353,14 @@ func (api *PrivateDebugAPI) FreezeClient(node string) error {
} }
} }
// PrivateLightAPI provides an API to access the LES light server or light client. // LightAPI provides an API to access the LES light server or light client.
type PrivateLightAPI struct { type LightAPI struct {
backend *lesCommons backend *lesCommons
} }
// NewPrivateLightAPI creates a new LES service API. // NewLightAPI creates a new LES service API.
func NewPrivateLightAPI(backend *lesCommons) *PrivateLightAPI { func NewLightAPI(backend *lesCommons) *LightAPI {
return &PrivateLightAPI{backend: backend} return &LightAPI{backend: backend}
} }
// LatestCheckpoint returns the latest local checkpoint package. // LatestCheckpoint returns the latest local checkpoint package.
@ -370,7 +370,7 @@ func NewPrivateLightAPI(backend *lesCommons) *PrivateLightAPI {
// result[1], 32 bytes hex encoded latest section head hash // result[1], 32 bytes hex encoded latest section head hash
// result[2], 32 bytes hex encoded latest section canonical hash trie root hash // result[2], 32 bytes hex encoded latest section canonical hash trie root hash
// result[3], 32 bytes hex encoded latest section bloom trie root hash // result[3], 32 bytes hex encoded latest section bloom trie root hash
func (api *PrivateLightAPI) LatestCheckpoint() ([4]string, error) { func (api *LightAPI) LatestCheckpoint() ([4]string, error) {
var res [4]string var res [4]string
cp := api.backend.latestLocalCheckpoint() cp := api.backend.latestLocalCheckpoint()
if cp.Empty() { if cp.Empty() {
@ -387,7 +387,7 @@ func (api *PrivateLightAPI) LatestCheckpoint() ([4]string, error) {
// result[0], 32 bytes hex encoded latest section head hash // result[0], 32 bytes hex encoded latest section head hash
// result[1], 32 bytes hex encoded latest section canonical hash trie root hash // result[1], 32 bytes hex encoded latest section canonical hash trie root hash
// result[2], 32 bytes hex encoded latest section bloom trie root hash // result[2], 32 bytes hex encoded latest section bloom trie root hash
func (api *PrivateLightAPI) GetCheckpoint(index uint64) ([3]string, error) { func (api *LightAPI) GetCheckpoint(index uint64) ([3]string, error) {
var res [3]string var res [3]string
cp := api.backend.localCheckpoint(index) cp := api.backend.localCheckpoint(index)
if cp.Empty() { if cp.Empty() {
@ -398,7 +398,7 @@ func (api *PrivateLightAPI) GetCheckpoint(index uint64) ([3]string, error) {
} }
// GetCheckpointContractAddress returns the contract contract address in hex format. // GetCheckpointContractAddress returns the contract contract address in hex format.
func (api *PrivateLightAPI) GetCheckpointContractAddress() (string, error) { func (api *LightAPI) GetCheckpointContractAddress() (string, error) {
if api.backend.oracle == nil { if api.backend.oracle == nil {
return "", errNotActivated return "", errNotActivated
} }

@ -74,7 +74,7 @@ type LightEthereum struct {
eventMux *event.TypeMux eventMux *event.TypeMux
engine consensus.Engine engine consensus.Engine
accountManager *accounts.Manager accountManager *accounts.Manager
netRPCService *ethapi.PublicNetAPI netRPCService *ethapi.NetAPI
p2pServer *p2p.Server p2pServer *p2p.Server
p2pConfig *p2p.Config p2pConfig *p2p.Config
@ -189,7 +189,7 @@ func New(stack *node.Node, config *ethconfig.Config) (*LightEthereum, error) {
leth.blockchain.DisableCheckFreq() leth.blockchain.DisableCheckFreq()
} }
leth.netRPCService = ethapi.NewPublicNetAPI(leth.p2pServer, leth.config.NetworkId) leth.netRPCService = ethapi.NewNetAPI(leth.p2pServer, leth.config.NetworkId)
// Register the backend on the node // Register the backend on the node
stack.RegisterAPIs(leth.APIs()) stack.RegisterAPIs(leth.APIs())
@ -300,12 +300,12 @@ func (s *LightEthereum) APIs() []rpc.API {
}, { }, {
Namespace: "eth", Namespace: "eth",
Version: "1.0", Version: "1.0",
Service: downloader.NewPublicDownloaderAPI(s.handler.downloader, s.eventMux), Service: downloader.NewDownloaderAPI(s.handler.downloader, s.eventMux),
Public: true, Public: true,
}, { }, {
Namespace: "eth", Namespace: "eth",
Version: "1.0", Version: "1.0",
Service: filters.NewPublicFilterAPI(s.ApiBackend, true, 5*time.Minute), Service: filters.NewFilterAPI(s.ApiBackend, true, 5*time.Minute),
Public: true, Public: true,
}, { }, {
Namespace: "net", Namespace: "net",
@ -315,7 +315,7 @@ func (s *LightEthereum) APIs() []rpc.API {
}, { }, {
Namespace: "les", Namespace: "les",
Version: "1.0", Version: "1.0",
Service: NewPrivateLightAPI(&s.lesCommons), Service: NewLightAPI(&s.lesCommons),
Public: false, Public: false,
}, { }, {
Namespace: "vflux", Namespace: "vflux",

@ -25,21 +25,21 @@ import (
"github.com/ethereum/go-ethereum/rpc" "github.com/ethereum/go-ethereum/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 PublicDownloaderAPI. 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 a loop until the event mux closes. It will install and uninstall new // eventLoop runs a 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
@ -133,9 +133,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.
@ -160,7 +160,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}
} }

@ -160,19 +160,19 @@ func (s *LesServer) APIs() []rpc.API {
{ {
Namespace: "les", Namespace: "les",
Version: "1.0", Version: "1.0",
Service: NewPrivateLightAPI(&s.lesCommons), Service: NewLightAPI(&s.lesCommons),
Public: false, Public: false,
}, },
{ {
Namespace: "les", Namespace: "les",
Version: "1.0", Version: "1.0",
Service: NewPrivateLightServerAPI(s), Service: NewLightServerAPI(s),
Public: false, Public: false,
}, },
{ {
Namespace: "debug", Namespace: "debug",
Version: "1.0", Version: "1.0",
Service: NewPrivateDebugAPI(s), Service: NewDebugAPI(s),
Public: false, Public: false,
}, },
} }

@ -36,11 +36,7 @@ func (n *Node) apis() []rpc.API {
{ {
Namespace: "admin", Namespace: "admin",
Version: "1.0", Version: "1.0",
Service: &privateAdminAPI{n}, Service: &adminAPI{n},
}, {
Namespace: "admin",
Version: "1.0",
Service: &publicAdminAPI{n},
Public: true, Public: true,
}, { }, {
Namespace: "debug", Namespace: "debug",
@ -49,21 +45,21 @@ func (n *Node) apis() []rpc.API {
}, { }, {
Namespace: "web3", Namespace: "web3",
Version: "1.0", Version: "1.0",
Service: &publicWeb3API{n}, Service: &web3API{n},
Public: true, Public: true,
}, },
} }
} }
// 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 {
@ -79,7 +75,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 {
@ -95,7 +91,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 {
@ -111,7 +107,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 {
@ -127,7 +123,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 {
@ -164,7 +160,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()
@ -219,26 +215,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.
// Deprecated: use StartHTTP instead. // 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.
// Deprecated: use StopHTTP instead. // 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 +286,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 +304,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 +313,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)
} }

@ -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)
@ -271,7 +271,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.