jsonrpc

package
v1.2.5 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jun 20, 2023 License: Apache-2.0 Imports: 32 Imported by: 0

Documentation

Index

Constants

View Source
const (
	PendingBlockFlag  = "pending"
	LatestBlockFlag   = "latest"
	EarliestBlockFlag = "earliest"
)
View Source
const (
	PendingBlockNumber  = BlockNumber(-3)
	LatestBlockNumber   = BlockNumber(-2)
	EarliestBlockNumber = BlockNumber(-1)
)
View Source
const (
	// DefaultJSONRPCBatchRequestLimit maximum length allowed for json_rpc batch requests
	DefaultJSONRPCBatchRequestLimit uint64 = 1
	// DefaultJSONRPCBlockRangeLimit maximum block range allowed for json_rpc
	// requests with fromBlock/toBlock values (e.g. eth_getLogs)
	DefaultJSONRPCBlockRangeLimit uint64 = 100
)
View Source
const (
	// The index in heap which is indicating the element is not in the heap
	NoIndexInHeap = -1
)

Variables

View Source
var (
	ErrTransactionNotSeal         = errors.New("transaction not sealed")
	ErrGenesisNotTracable         = errors.New("genesis is not traceable")
	ErrTransactionNotFoundInBlock = errors.New("transaction not found in block")
)
View Source
var (
	ErrInsufficientFunds = errors.New("insufficient funds for execution")
	ErrGasCapOverflow    = errors.New("unable to apply transaction for the highest gas limit")
)
View Source
var (
	ErrFilterDoesNotExists              = errors.New("filter does not exists")
	ErrWSFilterDoesNotSupportGetChanges = errors.New("web socket Filter doesn't support to return a batch of the changes")
	ErrCastingFilterToLogFilter         = errors.New("casting filter object to logFilter error")
	ErrBlockNotFound                    = errors.New("block not found")
	ErrIncorrectBlockRange              = errors.New("incorrect range")
	ErrBlockRangeTooHigh                = errors.New("block range too high")
	ErrPendingBlockNumber               = errors.New("pending block number is not supported")
	ErrNoWSConnection                   = errors.New("no websocket connection")
)
View Source
var (
	EthBlockNumberLabel      = EthAPILabels{"method": "eth_blockNumber"}
	EthCallLabel             = EthAPILabels{"method": "eth_call"}
	EthChainIDLabel          = EthAPILabels{"method": "eth_chainId"}
	EthEstimateGasLabel      = EthAPILabels{"method": "eth_estimateGas"}
	EthGasPriceLabel         = EthAPILabels{"method": "eth_gasPrice"}
	EthGetBalanceLabel       = EthAPILabels{"method": "eth_getBalance"}
	EthGetBlockByHashLabel   = EthAPILabels{"method": "eth_getBlockByHash"}
	EthGetBlockByNumberLabel = EthAPILabels{"method": "eth_getBlockByNumber"}

	EthGetBlockTransactionCountByNumberLabel = EthAPILabels{"method": "eth_getBlockTransactionCountByNumber"}

	EthGetCodeLabel          = EthAPILabels{"method": "eth_getCode"}
	EthGetFilterChangesLabel = EthAPILabels{"method": "eth_getFilterChanges"}
	EthGetFilterLogsLabel    = EthAPILabels{"method": "eth_getFilterLogs"}
	EthGetLogsLabel          = EthAPILabels{"method": "eth_getLogs"}
	EthGetStorageAtLabel     = EthAPILabels{"method": "eth_getStorageAt"}

	EthGetTransactionByHashLabel  = EthAPILabels{"method": "eth_getTransactionByHash"}
	EthGetTransactionCountLabel   = EthAPILabels{"method": "eth_getTransactionCount"}
	EthGetTransactionReceiptLabel = EthAPILabels{"method": "eth_getTransactionReceipt"}

	EthNewBlockFilterLabel = EthAPILabels{"method": "eth_newBlockFilter"}
	EthNewFilterLabel      = EthAPILabels{"method": "eth_newFilter"}

	EthSendRawTransactionLabel = EthAPILabels{"method": "eth_sendRawTransaction"}
	EthSyncingLabel            = EthAPILabels{"method": "eth_syncing"}

	EthUninstallFilterLabel = EthAPILabels{"method": "eth_uninstallFilter"}
	EthUnsubscribeLabel     = EthAPILabels{"method": "eth_unsubscribe"}
)
View Source
var (
	NetVersionLabel   = NetAPILabels{"method": "net_version"}
	NetListeningLabel = NetAPILabels{"method": "net_listening"}
	NetPeerCountLabel = NetAPILabels{"method": "net_peerCount"}
)
View Source
var (
	Web3ClientVersionLabel = Web3APILabels{"method": "web3_clientVersion"}
	Web3Sha3Label          = Web3APILabels{"method": "web3_sha3"}
)
View Source
var (
	TxPoolContentLabel = TxPoolAPILabels{"method": "txpool_content"}
	TxPoolInspectLabel = TxPoolAPILabels{"method": "txpool_inspect"}
	TxPoolStatusLabel  = TxPoolAPILabels{"method": "txpool_status"}
)
View Source
var (
	DebugTraceTransactionLabel = DebugAPILabels{"method": "debug_traceTransaction"}
)
View Source
var (
	ErrStateNotFound = errors.New("given root and slot not found in storage")
)

Functions

func GetNumericBlockNumber

func GetNumericBlockNumber(number BlockNumber, e *Eth) (uint64, error)

func NewInternalError

func NewInternalError(msg string) *internalError

func NewInvalidParamsError

func NewInvalidParamsError(msg string) *invalidParamsError

func NewInvalidRequestError

func NewInvalidRequestError(msg string) *invalidRequestError

func NewMethodNotFoundError

func NewMethodNotFoundError(method string) *methodNotFoundError

func NewSubscriptionNotFoundError

func NewSubscriptionNotFoundError(method string) *subscriptionNotFoundError

Types

type BlockNumber

type BlockNumber int64

func CreateBlockNumberPointer added in v0.5.3

func CreateBlockNumberPointer(str string) (*BlockNumber, error)

func StringToBlockNumber added in v0.5.3

func StringToBlockNumber(str string) (BlockNumber, error)

func (*BlockNumber) UnmarshalJSON

func (b *BlockNumber) UnmarshalJSON(buffer []byte) error

UnmarshalJSON automatically decodes the user input for the block number, when a JSON RPC method is called

type BlockNumberOrHash

type BlockNumberOrHash struct {
	BlockNumber *BlockNumber `json:"blockNumber,omitempty"`
	BlockHash   *types.Hash  `json:"blockHash,omitempty"`
}

func (*BlockNumberOrHash) UnmarshalJSON

func (bnh *BlockNumberOrHash) UnmarshalJSON(data []byte) error

UnmarshalJSON will try to extract the filter's data. Here are the possible input formats :

1 - "latest", "pending" or "earliest" - self-explaining keywords 2 - "0x2" - block number #2 (EIP-1898 backward compatible) 3 - {blockNumber: "0x2"} - EIP-1898 compliant block number #2 4 - {blockHash: "0xe0e..."} - EIP-1898 compliant block hash 0xe0e...

type Config

type Config struct {
	Store                    JSONRPCStore
	Addr                     *net.TCPAddr
	ChainID                  uint64
	AccessControlAllowOrigin []string
	BatchLengthLimit         uint64
	BlockRangeLimit          uint64
	JSONNamespaces           []Namespace
	EnableWS                 bool
	PriceLimit               uint64
	EnablePProf              bool // whether pprof enable or not
	EnableJaeger             bool // whether jaeger enable or not
	Metrics                  *Metrics
}

type ContentResponse

type ContentResponse struct {
	Pending map[types.Address]map[uint64]*txpoolTransaction `json:"pending"`
	Queued  map[types.Address]map[uint64]*txpoolTransaction `json:"queued"`
}

type Debug added in v1.1.4

type Debug struct {
	// contains filtered or unexported fields
}

func (*Debug) TraceTransaction added in v1.1.4

func (d *Debug) TraceTransaction(hash types.Hash) (interface{}, error)

type DebugAPILabels added in v1.2.2

type DebugAPILabels prometheus.Labels

type Dispatcher

type Dispatcher struct {
	// contains filtered or unexported fields
}

Dispatcher handles all json rpc requests by delegating the execution flow to the corresponding service

func (*Dispatcher) Handle

func (d *Dispatcher) Handle(reqBody []byte) ([]byte, error)

func (*Dispatcher) HandleWs

func (d *Dispatcher) HandleWs(reqBody []byte, conn wsConn) ([]byte, error)

func (*Dispatcher) RemoveFilterByWs added in v1.1.3

func (d *Dispatcher) RemoveFilterByWs(conn wsConn)

type Error

type Error interface {
	Error() string
	ErrorCode() int
}

type ErrorResponse

type ErrorResponse struct {
	JSONRPC string       `json:"jsonrpc"`
	ID      interface{}  `json:"id,omitempty"`
	Error   *ObjectError `json:"error"`
}

ErrorResponse is a jsonrpc error response

func (*ErrorResponse) Bytes

func (e *ErrorResponse) Bytes() ([]byte, error)

Bytes return the serialized response

func (*ErrorResponse) Data

func (e *ErrorResponse) Data() json.RawMessage

Data returns ObjectError

func (*ErrorResponse) GetID

func (e *ErrorResponse) GetID() interface{}

GetID returns error response id

type Eth

type Eth struct {
	// contains filtered or unexported fields
}

Eth is the eth jsonrpc endpoint

func (*Eth) BlockNumber

func (e *Eth) BlockNumber() (interface{}, error)

BlockNumber returns current block number

func (*Eth) Call

func (e *Eth) Call(arg *txnArgs, filter BlockNumberOrHash) (interface{}, error)

Call executes a smart contract call using the transaction object data

func (*Eth) ChainId

func (e *Eth) ChainId() (interface{}, error)

ChainId returns the chain id of the client

func (*Eth) EstimateGas

func (e *Eth) EstimateGas(arg *txnArgs, rawNum *BlockNumber) (interface{}, error)

EstimateGas estimates the gas needed to execute a transaction

func (*Eth) GasPrice

func (e *Eth) GasPrice() (interface{}, error)

GasPrice returns the average gas price based on the last x blocks

func (*Eth) GetBalance

func (e *Eth) GetBalance(address types.Address, filter BlockNumberOrHash) (interface{}, error)

GetBalance returns the account's balance at the referenced block.

func (*Eth) GetBlockByHash

func (e *Eth) GetBlockByHash(hash types.Hash, fullTx bool) (interface{}, error)

GetBlockByHash returns information about a block by hash

func (*Eth) GetBlockByNumber

func (e *Eth) GetBlockByNumber(number BlockNumber, fullTx bool) (interface{}, error)

GetBlockByNumber returns information about a block by block number

func (*Eth) GetBlockTransactionCountByNumber

func (e *Eth) GetBlockTransactionCountByNumber(number BlockNumber) (interface{}, error)

func (*Eth) GetCode

func (e *Eth) GetCode(address types.Address, filter BlockNumberOrHash) (interface{}, error)

GetCode returns account code at given block number

func (*Eth) GetFilterChanges

func (e *Eth) GetFilterChanges(id string) (interface{}, error)

GetFilterChanges is a polling method for a filter, which returns an array of logs which occurred since last poll. WebSocket polling log filter changes would not be accepted anymore.

func (*Eth) GetFilterLogs added in v0.5.3

func (e *Eth) GetFilterLogs(id string) (interface{}, error)

GetFilterLogs returns an array of logs for the specified filter

func (*Eth) GetLogs

func (e *Eth) GetLogs(query *LogQuery) (interface{}, error)

GetLogs returns an array of logs matching the filter options

func (*Eth) GetStorageAt

func (e *Eth) GetStorageAt(
	address types.Address,
	index types.Hash,
	filter BlockNumberOrHash,
) (interface{}, error)

GetStorageAt returns the contract storage at the index position

func (*Eth) GetTransactionByHash

func (e *Eth) GetTransactionByHash(hash types.Hash) (interface{}, error)

GetTransactionByHash returns a transaction by its hash. If the transaction is still pending -> return the txn with some fields omitted If the transaction is sealed into a block -> return the whole txn with all fields

func (*Eth) GetTransactionCount

func (e *Eth) GetTransactionCount(address types.Address, filter BlockNumberOrHash) (interface{}, error)

GetTransactionCount returns account nonce

func (*Eth) GetTransactionReceipt

func (e *Eth) GetTransactionReceipt(hash types.Hash) (interface{}, error)

GetTransactionReceipt returns a transaction receipt by his hash

func (*Eth) NewBlockFilter

func (e *Eth) NewBlockFilter() (interface{}, error)

NewBlockFilter creates a filter in the node, to notify when a new block arrives

func (*Eth) NewFilter

func (e *Eth) NewFilter(filter *LogQuery) (interface{}, error)

NewFilter creates a filter object, based on filter options, to notify when the state changes (logs).

func (*Eth) SendRawTransaction

func (e *Eth) SendRawTransaction(input string) (interface{}, error)

SendRawTransaction sends a raw transaction

func (*Eth) SendTransaction

func (e *Eth) SendTransaction(arg *txnArgs) (interface{}, error)

Reject eth_sendTransaction json-rpc call as we don't support wallet management

func (*Eth) Syncing

func (e *Eth) Syncing() (interface{}, error)

func (*Eth) UninstallFilter

func (e *Eth) UninstallFilter(id string) (bool, error)

UninstallFilter uninstalls a filter with given ID

func (*Eth) Unsubscribe

func (e *Eth) Unsubscribe(id string) (bool, error)

Unsubscribe uninstalls a filter in a websocket

type EthAPILabels added in v1.2.2

type EthAPILabels prometheus.Labels

type ExecutionResult added in v1.1.4

type ExecutionResult struct {
	Gas         uint64         `json:"gas"`
	Failed      bool           `json:"failed"`
	ReturnValue string         `json:"returnValue"`
	StructLogs  []StructLogRes `json:"structLogs"`
}

ExecutionResult groups all structured logs emitted by the EVM while replaying a transaction in debug mode as well as transaction execution status, the amount of gas used and the return value

type FilterManager

type FilterManager struct {
	sync.RWMutex // provide basic r/w lock
	// contains filtered or unexported fields
}

FilterManager manages all running filters

func NewFilterManager

func NewFilterManager(logger hclog.Logger, store filterManagerStore, blockRangeLimit uint64) *FilterManager

func (*FilterManager) Close

func (f *FilterManager) Close()

Close closed closeCh so that terminate worker

func (*FilterManager) Exists

func (f *FilterManager) Exists(id string) bool

Exists checks the filter with given ID exists

func (*FilterManager) GetFilterChanges

func (f *FilterManager) GetFilterChanges(id string) (string, error)

GetFilterChanges returns the updates of the filter with given ID in string, and refreshes the timeout on the filter

func (*FilterManager) GetLogFilterFromID added in v0.5.3

func (f *FilterManager) GetLogFilterFromID(filterID string) (*logFilter, error)

GetLogFilterFromID return log filter for given filterID

func (*FilterManager) GetLogs added in v0.5.3

func (f *FilterManager) GetLogs(query *LogQuery) ([]*Log, error)

GetLogs return array of logs for given query

func (*FilterManager) NewBlockFilter

func (f *FilterManager) NewBlockFilter(ws wsConn) string

NewBlockFilter adds new BlockFilter

func (*FilterManager) NewLogFilter

func (f *FilterManager) NewLogFilter(logQuery *LogQuery, ws wsConn) string

NewLogFilter adds new LogFilter

func (*FilterManager) RemoveFilterByWs added in v1.1.3

func (f *FilterManager) RemoveFilterByWs(ws wsConn)

RemoveFilterByWs removes the filter with given WS [Thread safe]

func (*FilterManager) Run

func (f *FilterManager) Run()

Run starts worker process to handle events

func (*FilterManager) Uninstall

func (f *FilterManager) Uninstall(id string) bool

Uninstall removes the filter with given ID from list

type GetResponse added in v1.2.0

type GetResponse struct {
	Name    string `json:"name"`
	ChainID uint64 `json:"chain_id"`
	Version string `json:"version"`
}

type InspectResponse

type InspectResponse struct {
	Pending         map[string]map[string]string `json:"pending"`
	Queued          map[string]map[string]string `json:"queued"`
	CurrentCapacity uint64                       `json:"currentCapacity"`
	MaxCapacity     uint64                       `json:"maxCapacity"`
}

type JSONRPC

type JSONRPC struct {
	// contains filtered or unexported fields
}

JSONRPC is an API backend

func NewJSONRPC

func NewJSONRPC(logger hclog.Logger, config *Config) (*JSONRPC, error)

NewJSONRPC returns the JSONRPC http server

type JSONRPCStore

type JSONRPCStore interface {
	// contains filtered or unexported methods
}

JSONRPCStore defines all the methods required by all the JSON RPC endpoints

type Log

type Log struct {
	Address     types.Address `json:"address"`
	Topics      []types.Hash  `json:"topics"`
	Data        argBytes      `json:"data"`
	BlockNumber argUint64     `json:"blockNumber"`
	TxHash      types.Hash    `json:"transactionHash"`
	TxIndex     argUint64     `json:"transactionIndex"`
	BlockHash   types.Hash    `json:"blockHash"`
	LogIndex    argUint64     `json:"logIndex"`
	Removed     bool          `json:"removed"`
}

type LogQuery

type LogQuery struct {
	BlockHash *types.Hash

	FromBlock BlockNumber
	ToBlock   BlockNumber

	Addresses []types.Address
	Topics    [][]types.Hash
}

LogQuery is a query to filter logs

func (*LogQuery) Match

func (q *LogQuery) Match(log *types.Log) bool

Match returns whether the receipt includes topics for this filter

func (*LogQuery) UnmarshalJSON

func (q *LogQuery) UnmarshalJSON(data []byte) error

UnmarshalJSON decodes a json object

type Metrics added in v1.2.0

type Metrics struct {
	// contains filtered or unexported fields
}

Metrics represents the jsonrpc metrics

func GetPrometheusMetrics added in v1.2.0

func GetPrometheusMetrics(namespace string, labelsWithValues ...string) *Metrics

GetPrometheusMetrics return the blockchain metrics instance

func NewDummyMetrics added in v1.2.0

func NewDummyMetrics(metrics *Metrics) *Metrics

NewDummyMetrics will return the no nil jsonrpc metrics TODO: use generic replace this in golang 1.18

func NilMetrics added in v1.2.0

func NilMetrics() *Metrics

NilMetrics will return the non operational jsonrpc metrics

func (*Metrics) DebugAPICounterInc added in v1.2.2

func (m *Metrics) DebugAPICounterInc(label DebugAPILabels)

func (*Metrics) ErrorsCounterInc added in v1.2.2

func (m *Metrics) ErrorsCounterInc()

func (*Metrics) EthAPICounterInc added in v1.2.2

func (m *Metrics) EthAPICounterInc(label EthAPILabels)

func (*Metrics) NetAPICounterInc added in v1.2.2

func (m *Metrics) NetAPICounterInc(label NetAPILabels)

func (*Metrics) RequestsCounterInc added in v1.2.2

func (m *Metrics) RequestsCounterInc()

func (*Metrics) ResponseTimeObserve added in v1.2.2

func (m *Metrics) ResponseTimeObserve(duration float64)

func (*Metrics) TxPoolAPICounterInc added in v1.2.2

func (m *Metrics) TxPoolAPICounterInc(label TxPoolAPILabels)

func (*Metrics) Web3APICounterInc added in v1.2.2

func (m *Metrics) Web3APICounterInc(label Web3APILabels)

type Namespace added in v1.2.0

type Namespace string
const (
	NamespaceEth    Namespace = "eth"
	NamespaceNet    Namespace = "net"
	NamespaceWeb3   Namespace = "web3"
	NamespaceTxpool Namespace = "txpool"
	NamespaceDebug  Namespace = "debug"
	NamespaceAll    Namespace = "*"
)

type Net

type Net struct {
	// contains filtered or unexported fields
}

Net is the net jsonrpc endpoint

func (*Net) Listening

func (n *Net) Listening() (interface{}, error)

Listening returns true if client is actively listening for network connections

func (*Net) PeerCount

func (n *Net) PeerCount() (interface{}, error)

PeerCount returns number of peers currently connected to the client

func (*Net) Version

func (n *Net) Version() (interface{}, error)

Version returns the current network id

type NetAPILabels added in v1.2.2

type NetAPILabels prometheus.Labels

type ObjectError

type ObjectError struct {
	Code    int         `json:"code"`
	Message string      `json:"message"`
	Data    interface{} `json:"data,omitempty"`
}

ObjectError is a jsonrpc error

func (*ObjectError) Error

func (e *ObjectError) Error() string

Error implements error interface

func (*ObjectError) MarshalJSON added in v1.2.5

func (e *ObjectError) MarshalJSON() ([]byte, error)

type Request

type Request struct {
	ID     interface{}     `json:"id"`
	Method string          `json:"method"`
	Params json.RawMessage `json:"params,omitempty"`
}

Request is a jsonrpc request

type Response

type Response interface {
	GetID() interface{}
	Data() json.RawMessage
	Bytes() ([]byte, error)
}

Response is a jsonrpc response interface

func NewRPCErrorResponse

func NewRPCErrorResponse(id interface{}, errCode int, err string, data []byte, jsonrpcver string) Response

NewRPCErrorResponse is used to create a custom error response

func NewRPCResponse

func NewRPCResponse(id interface{}, jsonrpcver string, reply []byte, err Error) Response

NewRPCResponse returns Success/Error response object

type StatusResponse

type StatusResponse struct {
	Pending uint64 `json:"pending"`
	Queued  uint64 `json:"queued"`
}

type StructLogRes added in v1.1.4

type StructLogRes struct {
	Pc      uint64             `json:"pc"`
	Op      string             `json:"op"`
	Gas     uint64             `json:"gas"`
	GasCost uint64             `json:"gasCost"`
	Depth   int                `json:"depth"`
	Error   string             `json:"error,omitempty"`
	Stack   *[]string          `json:"stack,omitempty"`
	Memory  *[]string          `json:"memory,omitempty"`
	Storage *map[string]string `json:"storage,omitempty"`
}

StructLogRes stores a structured log emitted by the EVM while replaying a transaction in debug mode

type SuccessResponse

type SuccessResponse struct {
	JSONRPC string          `json:"jsonrpc"`
	ID      interface{}     `json:"id"`
	Result  json.RawMessage `json:"result"`
	Error   *ObjectError    `json:"error,omitempty"`
}

SuccessResponse is a jsonrpc success response

func (*SuccessResponse) Bytes

func (s *SuccessResponse) Bytes() ([]byte, error)

Bytes return the serialized response

func (*SuccessResponse) Data

func (s *SuccessResponse) Data() json.RawMessage

Data returns the result

func (*SuccessResponse) GetID

func (s *SuccessResponse) GetID() interface{}

GetID returns success response id

type TxPool

type TxPool struct {
	// contains filtered or unexported fields
}

TxPool is the txpool jsonrpc endpoint

func (*TxPool) Content

func (t *TxPool) Content() (interface{}, error)

Create response for txpool_content request. See https://geth.ethereum.org/docs/rpc/ns-txpool#txpool_content.

func (*TxPool) DdosList added in v1.2.2

func (t *TxPool) DdosList() (interface{}, error)

DdosList Create response for txpool_ddosList request.

it should go back some contract black/white list of current node.

func (*TxPool) Inspect

func (t *TxPool) Inspect() (interface{}, error)

Create response for txpool_inspect request. See https://geth.ethereum.org/docs/rpc/ns-txpool#txpool_inspect.

func (*TxPool) Status

func (t *TxPool) Status() (interface{}, error)

Create response for txpool_status request. See https://geth.ethereum.org/docs/rpc/ns-txpool#txpool_status.

type TxPoolAPILabels added in v1.2.2

type TxPoolAPILabels prometheus.Labels

type Web3

type Web3 struct {
	// contains filtered or unexported fields
}

Web3 is the web3 jsonrpc endpoint

func (*Web3) ClientVersion

func (w *Web3) ClientVersion() (interface{}, error)

ClientVersion returns the version of the web3 client (web3_clientVersion)

func (*Web3) Sha3

func (w *Web3) Sha3(val string) (interface{}, error)

Sha3 returns Keccak-256 (not the standardized SHA3-256) of the given data

type Web3APILabels added in v1.2.2

type Web3APILabels prometheus.Labels

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL