jsonrpc

package
v0.0.3-RC4 Latest Latest
Warning

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

Go to latest
Published: Feb 22, 2023 License: GPL-3.0 Imports: 31 Imported by: 2

Documentation

Index

Constants

View Source
const (
	// PendingBlockNumber represents the pending block number
	PendingBlockNumber = BlockNumber(-3)
	// LatestBlockNumber represents the latest block number
	LatestBlockNumber = BlockNumber(-2)
	// EarliestBlockNumber represents the earliest block number
	EarliestBlockNumber = BlockNumber(-1)

	// LatestBatchNumber represents the latest batch number
	LatestBatchNumber = BatchNumber(-2)
	// EarliestBatchNumber represents the earliest batch number
	EarliestBatchNumber = BatchNumber(-1)

	// Earliest contains the string to represent the earliest block known.
	Earliest = "earliest"
	// Latest contains the string to represent the latest block known.
	Latest = "latest"
	// Pending contains the string to represent pending blocks.
	Pending = "pending"
)
View Source
const (
	// FilterTypeLog represents a filter of type log.
	FilterTypeLog = "log"
	// FilterTypeBlock represents a filter of type block.
	FilterTypeBlock = "block"
	// FilterTypePendingTx represent a filter of type pending Tx.
	FilterTypePendingTx = "pendingTx"
)
View Source
const (
	// APIEth represents the eth API prefix.
	APIEth = "eth"
	// APINet represents the net API prefix.
	APINet = "net"
	// APIDebug represents the debug API prefix.
	APIDebug = "debug"
	// APIZKEVM represents the zkevm API prefix.
	APIZKEVM = "zkevm"
	// APITxPool represents the txpool API prefix.
	APITxPool = "txpool"
	// APIWeb3 represents the web3 API prefix.
	APIWeb3 = "web3"
)

Variables

View Source
var ErrFilterInvalidPayload = errors.New("invalid argument 0: cannot specify both BlockHash and FromBlock/ToBlock, choose one or the other")

ErrFilterInvalidPayload indicates there is an invalid payload when creating a filter

View Source
var ErrNotFound = errors.New("object not found")

ErrNotFound represent a not found error.

Functions

This section is empty.

Types

type BatchNumber

type BatchNumber int64

BatchNumber is the number of a ethereum block

func (*BatchNumber) UnmarshalJSON

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

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

type BlockNumber

type BlockNumber int64

BlockNumber is the number of a ethereum block

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 Config

type Config struct {
	Host              string        `mapstructure:"Host"`
	Port              int           `mapstructure:"Port"`
	ReadTimeoutInSec  time.Duration `mapstructure:"ReadTimeoutInSec"`
	WriteTimeoutInSec time.Duration `mapstructure:"WriteTimeoutInSec"`

	MaxRequestsPerIPAndSecond float64 `mapstructure:"MaxRequestsPerIPAndSecond"`

	// SequencerNodeURI is used allow Non-Sequencer nodes
	// to relay transactions to the Sequencer node
	SequencerNodeURI string `mapstructure:"SequencerNodeURI"`

	// BroadcastURI is the URL of the Trusted State broadcast service
	BroadcastURI string `mapstructure:"BroadcastURI"`

	// DefaultSenderAddress is the address that jRPC will use
	// to communicate with the state for eth_EstimateGas and eth_Call when
	// the From field is not specified because it is optional
	DefaultSenderAddress string `mapstructure:"DefaultSenderAddress"`

	// MaxCumulativeGasUsed is the max gas allowed per batch
	MaxCumulativeGasUsed uint64

	// ChainID is the L2 ChainID provided by the Network Config
	ChainID uint64

	// Websockets
	WebSockets WebSocketsConfig `mapstructure:"WebSockets"`
}

Config represents the configuration of the json rpc

type DebugEndpoints

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

DebugEndpoints is the debug jsonrpc endpoint

func (*DebugEndpoints) TraceTransaction

func (d *DebugEndpoints) TraceTransaction(hash common.Hash, cfg *traceConfig) (interface{}, rpcError)

TraceTransaction creates a response for debug_traceTransaction request. See https://geth.ethereum.org/docs/rpc/ns-debug#debug_tracetransaction

type ErrorObject

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

ErrorObject is a jsonrpc error

type EthEndpoints

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

EthEndpoints contains implementations for the "eth" RPC endpoints

func (*EthEndpoints) BlockNumber

func (e *EthEndpoints) BlockNumber() (interface{}, rpcError)

BlockNumber returns current block number

func (*EthEndpoints) Call

func (e *EthEndpoints) Call(arg *txnArgs, number *BlockNumber) (interface{}, rpcError)

Call executes a new message call immediately and returns the value of executed contract and potential error. Note, this function doesn't make any changes in the state/blockchain and is useful to execute view/pure methods and retrieve values.

func (*EthEndpoints) ChainId

func (e *EthEndpoints) ChainId() (interface{}, rpcError)

ChainId returns the chain id of the client

func (*EthEndpoints) EstimateGas

func (e *EthEndpoints) EstimateGas(arg *txnArgs, number *BlockNumber) (interface{}, rpcError)

EstimateGas generates and returns an estimate of how much gas is necessary to allow the transaction to complete. The transaction will not be added to the blockchain. Note that the estimate may be significantly more than the amount of gas actually used by the transaction, for a variety of reasons including EVM mechanics and node performance.

func (*EthEndpoints) GasPrice

func (e *EthEndpoints) GasPrice() (interface{}, rpcError)

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

func (*EthEndpoints) GetBalance

func (e *EthEndpoints) GetBalance(address common.Address, number *BlockNumber) (interface{}, rpcError)

GetBalance returns the account's balance at the referenced block

func (*EthEndpoints) GetBlockByHash

func (e *EthEndpoints) GetBlockByHash(hash common.Hash, fullTx bool) (interface{}, rpcError)

GetBlockByHash returns information about a block by hash

func (*EthEndpoints) GetBlockByNumber

func (e *EthEndpoints) GetBlockByNumber(number BlockNumber, fullTx bool) (interface{}, rpcError)

GetBlockByNumber returns information about a block by block number

func (*EthEndpoints) GetBlockTransactionCountByHash

func (e *EthEndpoints) GetBlockTransactionCountByHash(hash common.Hash) (interface{}, rpcError)

GetBlockTransactionCountByHash returns the number of transactions in a block from a block matching the given block hash.

func (*EthEndpoints) GetBlockTransactionCountByNumber

func (e *EthEndpoints) GetBlockTransactionCountByNumber(number *BlockNumber) (interface{}, rpcError)

GetBlockTransactionCountByNumber returns the number of transactions in a block from a block matching the given block number.

func (*EthEndpoints) GetCode

func (e *EthEndpoints) GetCode(address common.Address, number *BlockNumber) (interface{}, rpcError)

GetCode returns account code at given block number

func (*EthEndpoints) GetCompilers

func (e *EthEndpoints) GetCompilers() (interface{}, rpcError)

GetCompilers eth_getCompilers

func (*EthEndpoints) GetFilterChanges

func (e *EthEndpoints) GetFilterChanges(filterID string) (interface{}, rpcError)

GetFilterChanges polling method for a filter, which returns an array of logs which occurred since last poll.

func (*EthEndpoints) GetFilterLogs

func (e *EthEndpoints) GetFilterLogs(filterID string) (interface{}, rpcError)

GetFilterLogs returns an array of all logs matching filter with given id.

func (*EthEndpoints) GetLogs

func (e *EthEndpoints) GetLogs(filter LogFilter) (interface{}, rpcError)

GetLogs returns a list of logs accordingly to the provided filter

func (*EthEndpoints) GetStorageAt

func (e *EthEndpoints) GetStorageAt(address common.Address, position common.Hash, number *BlockNumber) (interface{}, rpcError)

GetStorageAt gets the value stored for an specific address and position

func (*EthEndpoints) GetTransactionByBlockHashAndIndex

func (e *EthEndpoints) GetTransactionByBlockHashAndIndex(hash common.Hash, index Index) (interface{}, rpcError)

GetTransactionByBlockHashAndIndex returns information about a transaction by block hash and transaction index position.

func (*EthEndpoints) GetTransactionByBlockNumberAndIndex

func (e *EthEndpoints) GetTransactionByBlockNumberAndIndex(number *BlockNumber, index Index) (interface{}, rpcError)

GetTransactionByBlockNumberAndIndex returns information about a transaction by block number and transaction index position.

func (*EthEndpoints) GetTransactionByHash

func (e *EthEndpoints) GetTransactionByHash(hash common.Hash) (interface{}, rpcError)

GetTransactionByHash returns a transaction by his hash

func (*EthEndpoints) GetTransactionCount

func (e *EthEndpoints) GetTransactionCount(address common.Address, number *BlockNumber) (interface{}, rpcError)

GetTransactionCount returns account nonce

func (*EthEndpoints) GetTransactionReceipt

func (e *EthEndpoints) GetTransactionReceipt(hash common.Hash) (interface{}, rpcError)

GetTransactionReceipt returns a transaction receipt by his hash

func (*EthEndpoints) GetUncleByBlockHashAndIndex

func (e *EthEndpoints) GetUncleByBlockHashAndIndex() (interface{}, rpcError)

GetUncleByBlockHashAndIndex returns information about a uncle of a block by hash and uncle index position

func (*EthEndpoints) GetUncleByBlockNumberAndIndex

func (e *EthEndpoints) GetUncleByBlockNumberAndIndex() (interface{}, rpcError)

GetUncleByBlockNumberAndIndex returns information about a uncle of a block by number and uncle index position

func (*EthEndpoints) GetUncleCountByBlockHash

func (e *EthEndpoints) GetUncleCountByBlockHash() (interface{}, rpcError)

GetUncleCountByBlockHash returns the number of uncles in a block matching the given block hash

func (*EthEndpoints) GetUncleCountByBlockNumber

func (e *EthEndpoints) GetUncleCountByBlockNumber() (interface{}, rpcError)

GetUncleCountByBlockNumber returns the number of uncles in a block matching the given block number

func (*EthEndpoints) NewBlockFilter

func (e *EthEndpoints) NewBlockFilter() (interface{}, rpcError)

NewBlockFilter creates a filter in the node, to notify when a new block arrives. To check if the state has changed, call eth_getFilterChanges.

func (*EthEndpoints) NewFilter

func (e *EthEndpoints) NewFilter(filter LogFilter) (interface{}, rpcError)

NewFilter creates a filter object, based on filter options, to notify when the state changes (logs). To check if the state has changed, call eth_getFilterChanges.

func (*EthEndpoints) NewPendingTransactionFilter

func (e *EthEndpoints) NewPendingTransactionFilter() (interface{}, rpcError)

NewPendingTransactionFilter creates a filter in the node, to notify when new pending transactions arrive. To check if the state has changed, call eth_getFilterChanges.

func (*EthEndpoints) ProtocolVersion

func (e *EthEndpoints) ProtocolVersion() (interface{}, rpcError)

ProtocolVersion returns the protocol version.

func (*EthEndpoints) SendRawTransaction

func (e *EthEndpoints) SendRawTransaction(input string) (interface{}, rpcError)

SendRawTransaction has two different ways to handle new transactions: - for Sequencer nodes it tries to add the tx to the pool - for Non-Sequencer nodes it relays the Tx to the Sequencer node

func (*EthEndpoints) Subscribe

func (e *EthEndpoints) Subscribe(wsConn *websocket.Conn, name string, logFilter *LogFilter) (interface{}, rpcError)

Subscribe Creates a new subscription over particular events. The node will return a subscription id. For each event that matches the subscription a notification with relevant data is sent together with the subscription id.

func (*EthEndpoints) Syncing

func (e *EthEndpoints) Syncing() (interface{}, rpcError)

Syncing returns an object with data about the sync status or false. https://eth.wiki/json-rpc/API#eth_syncing

func (*EthEndpoints) UninstallFilter

func (e *EthEndpoints) UninstallFilter(filterID string) (interface{}, rpcError)

UninstallFilter uninstalls a filter with given id.

func (*EthEndpoints) Unsubscribe

func (e *EthEndpoints) Unsubscribe(wsConn *websocket.Conn, filterID string) (interface{}, rpcError)

Unsubscribe uninstalls the filter based on the provided filterID

type Filter

type Filter struct {
	ID         string
	Type       FilterType
	Parameters interface{}
	LastPoll   time.Time
	WsConn     *websocket.Conn
}

Filter represents a filter.

type FilterType

type FilterType string

FilterType express the type of the filter, block, logs, pending transactions

type Handler

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

Handler manage services to handle jsonrpc requests

Services are public structures containing public methods matching the name of the jsonrpc method.

Services must be registered with a prefix to identify the service and its methods, for example a service registered with a prefix `eth` will have all the public methods exposed as eth_<methodName> through the json rpc server.

Go public methods requires the first char of its name to be in uppercase, but the exposition of the method will consider it to lower case, for example a method `func MyMethod()` provided by the service registered with `eth` prefix will be triggered when the method eth_myMethod is specified

the public methods must follow the conventions: - return interface{}, rpcError - if the method depend on a Web Socket connection, it must be the first parameters as f(*websocket.Conn) - parameter types must match the type of the data provided for the method

check the `eth.go` file for more example on how the methods are implemented

func (*Handler) Handle

func (h *Handler) Handle(req handleRequest) Response

Handle is the function that knows which and how a function should be executed when a JSON RPC request is received

func (*Handler) HandleWs

func (h *Handler) HandleWs(reqBody []byte, wsConn *websocket.Conn) ([]byte, error)

HandleWs handle websocket requests

func (*Handler) RemoveFilterByWsConn

func (h *Handler) RemoveFilterByWsConn(wsConn *websocket.Conn)

RemoveFilterByWsConn uninstalls the filter attached to this websocket connection

type Index

type Index int64

Index of a item

func (*Index) UnmarshalJSON

func (i *Index) UnmarshalJSON(buffer []byte) error

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

type LogFilter

type LogFilter struct {
	BlockHash *common.Hash
	FromBlock *BlockNumber
	ToBlock   *BlockNumber
	Addresses []common.Address
	Topics    [][]common.Hash
	Since     *time.Time
}

LogFilter is a filter for logs

func (*LogFilter) MarshalJSON

func (f *LogFilter) MarshalJSON() ([]byte, error)

MarshalJSON allows to customize the JSON representation.

func (*LogFilter) Match

func (f *LogFilter) Match(log *types.Log) bool

Match returns whether the receipt includes topics for this filter

func (*LogFilter) UnmarshalJSON

func (f *LogFilter) UnmarshalJSON(data []byte) error

UnmarshalJSON decodes a json object

type LogFilterRequest

type LogFilterRequest struct {
	BlockHash *common.Hash  `json:"blockHash,omitempty"`
	FromBlock *string       `json:"fromBlock,omitempty"`
	ToBlock   *string       `json:"toBlock,omitempty"`
	Address   interface{}   `json:"address,omitempty"`
	Topics    []interface{} `json:"topics,omitempty"`
}

LogFilterRequest represents a log filter request.

type NetEndpoints

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

NetEndpoints contains implementations for the "net" RPC endpoints

func (*NetEndpoints) Version

func (n *NetEndpoints) Version() (interface{}, rpcError)

Version returns the current network id

type RPCError

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

RPCError represents an RPC error.

func (*RPCError) Error

func (e *RPCError) Error() string

Error returns the error message.

func (*RPCError) ErrorCode

func (e *RPCError) ErrorCode() int

ErrorCode returns the error code.

type Request

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

Request is a jsonrpc request

type Response

type Response struct {
	JSONRPC string
	ID      interface{}
	Result  json.RawMessage
	Error   *ErrorObject
}

Response is a jsonrpc success response

func JSONRPCCall

func JSONRPCCall(url, method string, parameters ...interface{}) (Response, error)

JSONRPCCall executes a 2.0 JSON RPC HTTP Post Request to the provided URL with the provided method and parameters, which is compatible with the Ethereum JSON RPC Server.

func NewResponse

func NewResponse(req Request, reply []byte, err rpcError) Response

NewResponse returns Success/Error response object

func (Response) Bytes

func (s Response) Bytes() ([]byte, error)

Bytes return the serialized response

func (Response) MarshalJSON

func (r Response) MarshalJSON() ([]byte, error)

MarshalJSON customizes the JSON representation of the response.

type Server

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

Server is an API backend to handle RPC requests

func NewServer

func NewServer(
	cfg Config,
	p jsonRPCTxPool,
	s stateInterface,
	storage storageInterface,
	apis map[string]bool,
) *Server

NewServer returns the JsonRPC server

func (*Server) Start

func (s *Server) Start() error

Start initializes the JSON RPC server to listen for request

func (*Server) Stop

func (s *Server) Stop() error

Stop shutdown the rpc server

type Storage

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

Storage uses memory to store the data related to the json rpc server

func NewStorage

func NewStorage() *Storage

NewStorage creates and initializes an instance of Storage

func (*Storage) GetAllBlockFiltersWithWSConn

func (s *Storage) GetAllBlockFiltersWithWSConn() ([]*Filter, error)

GetAllBlockFiltersWithWSConn returns an array with all filter that have a web socket connection and are filtering by new blocks

func (*Storage) GetAllLogFiltersWithWSConn

func (s *Storage) GetAllLogFiltersWithWSConn() ([]*Filter, error)

GetAllLogFiltersWithWSConn returns an array with all filter that have a web socket connection and are filtering by new logs

func (*Storage) GetFilter

func (s *Storage) GetFilter(filterID string) (*Filter, error)

GetFilter gets a filter by its id

func (*Storage) NewBlockFilter

func (s *Storage) NewBlockFilter(wsConn *websocket.Conn) (string, error)

NewBlockFilter persists a new block log filter

func (*Storage) NewLogFilter

func (s *Storage) NewLogFilter(wsConn *websocket.Conn, filter LogFilter) (string, error)

NewLogFilter persists a new log filter

func (*Storage) NewPendingTransactionFilter

func (s *Storage) NewPendingTransactionFilter(wsConn *websocket.Conn) (string, error)

NewPendingTransactionFilter persists a new pending transaction filter

func (*Storage) UninstallFilter

func (s *Storage) UninstallFilter(filterID string) error

UninstallFilter deletes a filter by its id

func (*Storage) UninstallFilterByWSConn

func (s *Storage) UninstallFilterByWSConn(wsConn *websocket.Conn) error

UninstallFilterByWSConn deletes all filters connected to the provided web socket connection

func (*Storage) UpdateFilterLastPoll

func (s *Storage) UpdateFilterLastPoll(filterID string) error

UpdateFilterLastPoll updates the last poll to now

type StructLogRes

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         *[]argBig          `json:"stack,omitempty"`
	Memory        *argBytes          `json:"memory,omitempty"`
	Storage       *map[string]string `json:"storage,omitempty"`
	RefundCounter uint64             `json:"refund,omitempty"`
}

StructLogRes represents a log response.

type SubscriptionResponse

type SubscriptionResponse struct {
	JSONRPC string                     `json:"jsonrpc"`
	Method  string                     `json:"method"`
	Params  SubscriptionResponseParams `json:"params"`
}

SubscriptionResponse used to push response for filters that have an active web socket connection

func (SubscriptionResponse) Bytes

func (s SubscriptionResponse) Bytes() ([]byte, error)

Bytes return the serialized response

type SubscriptionResponseParams

type SubscriptionResponseParams struct {
	Subscription string          `json:"subscription"`
	Result       json.RawMessage `json:"result"`
}

SubscriptionResponseParams parameters for subscription responses

type TxPoolEndpoints

type TxPoolEndpoints struct{}

TxPoolEndpoints is the txpool jsonrpc endpoint

func (*TxPoolEndpoints) Content

func (e *TxPoolEndpoints) Content() (interface{}, rpcError)

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

type Web3Endpoints

type Web3Endpoints struct {
}

Web3Endpoints contains implementations for the "web3" RPC endpoints

func (*Web3Endpoints) ClientVersion

func (e *Web3Endpoints) ClientVersion() (interface{}, rpcError)

ClientVersion returns the client version.

func (*Web3Endpoints) Sha3

func (e *Web3Endpoints) Sha3(data argBig) (interface{}, rpcError)

Sha3 returns the keccak256 hash of the given data.

type WebSocketsConfig

type WebSocketsConfig struct {
	Enabled bool `mapstructure:"Enabled"`
	Port    int  `mapstructure:"Port"`
}

WebSocketsConfig has parameters to config the rpc websocket support

type ZKEVMEndpoints

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

ZKEVMEndpoints contains implementations for the "zkevm" RPC endpoints

func (*ZKEVMEndpoints) BatchNumber

func (z *ZKEVMEndpoints) BatchNumber() (interface{}, rpcError)

BatchNumber returns the latest virtualized batch number

func (*ZKEVMEndpoints) BatchNumberByBlockNumber

func (z *ZKEVMEndpoints) BatchNumberByBlockNumber(blockNumber argUint64) (interface{}, rpcError)

BatchNumberByBlockNumber returns the batch number from which the passed block number is created

func (*ZKEVMEndpoints) ConsolidatedBlockNumber

func (z *ZKEVMEndpoints) ConsolidatedBlockNumber() (interface{}, rpcError)

ConsolidatedBlockNumber returns current block number for consolidated blocks

func (*ZKEVMEndpoints) GetBatchByNumber

func (z *ZKEVMEndpoints) GetBatchByNumber(batchNumber BatchNumber, fullTx bool) (interface{}, rpcError)

GetBatchByNumber returns information about a batch by batch number

func (*ZKEVMEndpoints) GetBroadcastURI

func (z *ZKEVMEndpoints) GetBroadcastURI() (interface{}, rpcError)

GetBroadcastURI returns the IP:PORT of the broadcast service provided by the Trusted Sequencer JSON RPC server

func (*ZKEVMEndpoints) IsBlockConsolidated

func (z *ZKEVMEndpoints) IsBlockConsolidated(blockNumber argUint64) (interface{}, rpcError)

IsBlockConsolidated returns the consolidation status of a provided block number

func (*ZKEVMEndpoints) IsBlockVirtualized

func (z *ZKEVMEndpoints) IsBlockVirtualized(blockNumber argUint64) (interface{}, rpcError)

IsBlockVirtualized returns the virtualization status of a provided block number

func (*ZKEVMEndpoints) VerifiedBatchNumber

func (z *ZKEVMEndpoints) VerifiedBatchNumber() (interface{}, rpcError)

VerifiedBatchNumber returns the latest verified batch number

func (*ZKEVMEndpoints) VirtualBatchNumber

func (z *ZKEVMEndpoints) VirtualBatchNumber() (interface{}, rpcError)

VirtualBatchNumber returns the latest virtualized batch number

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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