v0.0.1 Latest Latest

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

Go to latest
Published: Jan 25, 2016 License: GPL-3.0 Imports: 31 Imported by: 24



Package rpc provides access to the exported methods of an object across a network or other I/O connection. After creating a server instance objects can be registered, making it visible from the outside. Exported methods that follow specific conventions can be called remotely. It also has support for the publish/subscribe pattern.

Methods that satisfy the following criteria are made available for remote access:

  • object must be exported
  • method must be exported
  • method returns 0, 1 (response or error) or 2 (response and error) values
  • method argument(s) must be exported or builtin types
  • method returned value(s) must be exported or builtin types

An example method:

func (s *CalcService) Div(a, b int) (int, error)

When the returned error isn't nil the returned integer is ignored and the error is send back to the client. Otherwise the returned integer is send back to the client.

The server offers the ServeCodec method which accepts a ServerCodec instance. It will read requests from the codec, process the request and sends the response back to the client using the codec. The server can execute requests concurrently. Responses can be send back to the client out of order.

An example server which uses the JSON codec:

 type CalculatorService struct {}

 func (s *CalculatorService) Add(a, b int) int {
	return a + b

 func (s *CalculatorService Div(a, b int) (int, error) {
	if b == 0 {
		return 0, errors.New("divide by zero")
	return a/b, nil

 calculator := new(CalculatorService)
 server := NewServer()
 server.RegisterName("calculator", calculator")

 l, _ := net.ListenUnix("unix", &net.UnixAddr{Net: "unix", Name: "/tmp/calculator.sock"})
 for {
	c, _ := l.AcceptUnix()
	codec := v2.NewJSONCodec(c)
	go server.ServeCodec(codec)

The package also supports the publish subscribe pattern through the use of subscriptions. A method that is considered eligible for notifications must satisfy the following criteria:

  • object must be exported
  • method must be exported
  • method argument(s) must be exported or builtin types
  • method must return the tuple Subscription, error

An example method:

 func (s *BlockChainService) Head() (Subscription, error) {
 	sub := s.bc.eventMux.Subscribe(ChainHeadEvent{})
	return v2.NewSubscription(sub), nil

This method will push all raised ChainHeadEvents to subscribed clients. If the client is only interested in every N'th block it is possible to add a criteria.

 func (s *BlockChainService) HeadFiltered(nth uint64) (Subscription, error) {
 	sub := s.bc.eventMux.Subscribe(ChainHeadEvent{})

	criteria := func(event interface{}) bool {
		chainHeadEvent := event.(ChainHeadEvent)
		if chainHeadEvent.Block.NumberU64() % nth == 0 {
			return true
		return false

	return v2.NewSubscriptionFiltered(sub, criteria), nil

Subscriptions are deleted when:

  • the user sends an unsubscribe request
  • the connection which was used to create the subscription is closed



View Source
const (
	DefaultIpcApis     = "admin,eth,debug,miner,net,shh,txpool,personal,web3"
	DefaultHttpRpcApis = "eth,net,web3"
View Source
const (
	PendingBlockNumber = BlockNumber(-2)
	LatestBlockNumber  = BlockNumber(-1)
View Source
const Admin_JS = `` /* 2369-byte string literal not displayed */
View Source
const Db_JS = `
	property: 'db',
View Source
const Debug_JS = `` /* 756-byte string literal not displayed */
View Source
const Eth_JS = `` /* 1075-byte string literal not displayed */
View Source
const Miner_JS = `` /* 1235-byte string literal not displayed */
View Source
const Net_JS = `` /* 244-byte string literal not displayed */
View Source
const Personal_JS = `` /* 538-byte string literal not displayed */
View Source
const Shh_JS = `` /* 155-byte string literal not displayed */
View Source
const TimeFormat = "Mon, 02 Jan 2006 15:04:05 GMT"

TimeFormat is the time format to use with time.Parse and time.Time.Format when parsing or generating times in HTTP headers. It is like time.RFC1123 but hard codes GMT as the time zone.

View Source
const TxPool_JS = `` /* 353-byte string literal not displayed */


View Source
var (
	// Mapping between the different methods each api supports
	AutoCompletion = map[string][]string{
		"admin": []string{
		"db": []string{
		"debug": []string{
		"eth": []string{
		"miner": []string{
		"net": []string{
		"personal": []string{
		"shh": []string{
		"txpool": []string{
		"web3": []string{
View Source
var (
	// Holds geth specific RPC extends which can be used to extend web3
	WEB3Extensions = map[string]string{
		"personal": Personal_JS,
		"txpool":   TxPool_JS,
		"admin":    Admin_JS,
		"db":       Db_JS,
		"eth":      Eth_JS,
		"miner":    Miner_JS,
		"debug":    Debug_JS,
		"net":      Net_JS,


func CreateIPCListener

func CreateIPCListener(endpoint string) (net.Listener, error)

CreateIPCListener creates an listener, on Unix platforms this is a unix socket, on Windows this is a named pipe

func NewHTTPClient

func NewHTTPClient(endpoint string) (*httpClient, error)

NewHTTPClient create a new RPC clients that connection to a geth RPC server over HTTP.

func NewHTTPMessageStream

func NewHTTPMessageStream(c net.Conn, rwbuf *bufio.ReadWriter, initialReq *http.Request, allowdOrigins []string) *httpMessageStream

NewHttpMessageStream will create a new http message stream parser that can be used by the codes in the RPC package. It will take full control of the given connection and thus needs to be hijacked. It will read and write HTTP messages from the passed rwbuf. The allowed origins are the RPC CORS domains the user has supplied.

func NewIPCClient

func NewIPCClient(endpoint string) (*ipcClient, error)

NewIPCClient create a new IPC client that will connect on the given endpoint. Messages are JSON encoded and encoded. On Unix it assumes the endpoint is the full path to a unix socket, and Windows the endpoint is an identifier for a named pipe.

func NewWSClient

func NewWSClient(endpoint string) (*wsClient, error)

NewWSClientj creates a new RPC client that communicates with a RPC server that is listening on the given endpoint using JSON encoding.

func StartHTTP

func StartHTTP(address string, port int, corsdomains []string, apis []API) error

StartHTTP will start the JSONRPC HTTP RPC interface when its not yet running.

func StartWS

func StartWS(address string, port int, corsdomains []string, apis []API) error

StartWS will start a websocket RPC server on the given address and port.

func StopHTTP

func StopHTTP() error

StopHTTP will stop the running HTTP interface. If it is not running an error will be returned.

func StopWS

func StopWS() error

StopWS stops the running websocket RPC server.

func SupportedModules

func SupportedModules(client Client) (map[string]string, error)

SupportedModules returns the collection of API's that the RPC server offers on which the given client connects.


type API

type API struct {
	Namespace string      // namespace under which the rpc methods of Service are exposed
	Version   string      // api version for DApp's
	Service   interface{} // receiver instance which holds the methods
	Public    bool        // indication if the methods must be considered safe for public use

API describes the set of methods offered over the RPC interface

type BlockNumber

type BlockNumber int64

func (*BlockNumber) Int64

func (bn *BlockNumber) Int64() int64

func (*BlockNumber) UnmarshalJSON

func (bn *BlockNumber) UnmarshalJSON(data []byte) error

UnmarshalJSON parses the given JSON fragement into a BlockNumber. It supports: - "latest" or "earliest" as string arguments - the block number Returned errors: - an unsupported error when "pending" is specified (not yet implemented) - an invalid block number error when the given argument isn't a known strings - an out of range error when the given block number is either too little or too large

type Client

type Client interface {
	// SupportedModules returns the collection of API's the server offers
	SupportedModules() (map[string]string, error)

	Send(req interface{}) error
	Recv(msg interface{}) error


Client defines the interface for go client that wants to connect to a geth RPC endpoint

type HexNumber

type HexNumber big.Int

HexNumber serializes a number to hex format using the "%#x" format

func NewHexNumber

func NewHexNumber(val interface{}) *HexNumber

NewHexNumber creates a new hex number instance which will serialize the given val with `%#x` on marshal.

func (*HexNumber) BigInt

func (h *HexNumber) BigInt() *big.Int

func (*HexNumber) Int

func (h *HexNumber) Int() int

func (*HexNumber) Int64

func (h *HexNumber) Int64() int64

func (*HexNumber) MarshalJSON

func (h *HexNumber) MarshalJSON() ([]byte, error)

MarshalJSON serialize the hex number instance to a hex representation.

func (*HexNumber) Uint

func (h *HexNumber) Uint() uint

func (*HexNumber) Uint64

func (h *HexNumber) Uint64() uint64

func (*HexNumber) UnmarshalJSON

func (h *HexNumber) UnmarshalJSON(input []byte) error

type JSONErrResponse

type JSONErrResponse struct {
	Version string    `json:"jsonrpc"`
	Id      *int64    `json:"id,omitempty"`
	Error   JSONError `json:"error"`

JSON-RPC error response

type JSONError

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

JSON-RPC error object

type JSONRequest

type JSONRequest struct {
	Method  string          `json:"method"`
	Version string          `json:"jsonrpc"`
	Id      *int64          `json:"id,omitempty"`
	Payload json.RawMessage `json:"params"`

JSON-RPC request

type JSONSuccessResponse

type JSONSuccessResponse struct {
	Version string      `json:"jsonrpc"`
	Id      int64       `json:"id"`
	Result  interface{} `json:"result,omitempty"`

JSON-RPC response

type Number

type Number int64

func (*Number) BigInt

func (n *Number) BigInt() *big.Int

func (*Number) Int64

func (n *Number) Int64() int64

func (*Number) UnmarshalJSON

func (n *Number) UnmarshalJSON(data []byte) error

type RPCError

type RPCError interface {
	// RPC error code
	Code() int
	// Error message
	Error() string

RPCError implements RPC error, is add support for error codec over regular go errors

type RPCService

type RPCService struct {
	// contains filtered or unexported fields

RPCService gives meta information about the server. e.g. gives information about the loaded modules.

func (*RPCService) Modules

func (s *RPCService) Modules() map[string]string

Modules returns the list of RPC services with their version number

type Server

type Server struct {
	// contains filtered or unexported fields

Server represents a RPC server

func NewServer

func NewServer() *Server

NewServer will create a new server instance with no registered handlers.

func (*Server) RegisterName

func (s *Server) RegisterName(name string, rcvr interface{}) error

RegisterName will create an service for the given rcvr type under the given name. When no methods on the given rcvr match the criteria to be either a RPC method or a subscription an error is returned. Otherwise a new service is created and added to the service collection this server instance serves.

func (*Server) ServeCodec

func (s *Server) ServeCodec(codec ServerCodec)

ServeCodec reads incoming requests from codec, calls the appropriate callback and writes the response back using the given codec. It will block until the codec is closed.

This server will: 1. allow for asynchronous and parallel request execution 2. supports notifications (pub/sub) 3. supports request batches

func (*Server) Stop

func (s *Server) Stop()

Stop will stop reading new requests, wait for stopPendingRequestTimeout to allow pending requests to finish, close all codecs which will cancels pending requests/subscriptions.

type ServerCodec

type ServerCodec interface {
	// Read next request
	ReadRequestHeaders() ([]rpcRequest, bool, RPCError)
	// Parse request argument to the given types
	ParseRequestArguments([]reflect.Type, interface{}) ([]reflect.Value, RPCError)
	// Assemble success response
	CreateResponse(int64, interface{}) interface{}
	// Assemble error response
	CreateErrorResponse(*int64, RPCError) interface{}
	// Assemble error response with extra information about the error through info
	CreateErrorResponseWithInfo(id *int64, err RPCError, info interface{}) interface{}
	// Create notification response
	CreateNotification(string, interface{}) interface{}
	// Write msg to client.
	Write(interface{}) error
	// Close underlying data stream
	// Closed when underlying connection is closed
	Closed() <-chan interface{}

ServerCodec implements reading, parsing and writing RPC messages for the server side of a RPC session. Implementations must be go-routine safe since the codec can be called in multiple go-routines concurrently.

func NewJSONCodec

func NewJSONCodec(rwc io.ReadWriteCloser) ServerCodec

NewJSONCodec creates a new RPC server codec with support for JSON-RPC 2.0

type Subscription

type Subscription struct {
	// contains filtered or unexported fields

Subscription is used by the server to send notifications to the client

func NewSubscription

func NewSubscription(sub event.Subscription) Subscription

NewSubscription create a new RPC subscription

func NewSubscriptionFiltered

func NewSubscriptionFiltered(sub event.Subscription, match SubscriptionMatcher) Subscription

NewSubscriptionFiltered will create a new subscription. For each raised event the given matcher is called. If it returns true the event is send as notification to the client, otherwise it is ignored.

func NewSubscriptionWithOutputFormat

func NewSubscriptionWithOutputFormat(sub event.Subscription, formatter SubscriptionOutputFormat) Subscription

NewSubscriptionWithOutputFormat create a new RPC subscription which a custom notification output format

func (*Subscription) Chan

func (s *Subscription) Chan() <-chan *event.Event

Chan returns the channel where new events will be published. It's up the user to call the matcher to determine if the events are interesting for the client.

func (*Subscription) Unsubscribe

func (s *Subscription) Unsubscribe()

Unsubscribe will end the subscription and closes the event channel

type SubscriptionMatcher

type SubscriptionMatcher func(interface{}) bool

SubscriptionMatcher returns true if the given value matches the criteria specified by the user

type SubscriptionOutputFormat

type SubscriptionOutputFormat func(interface{}) interface{}

SubscriptionOutputFormat accepts event data and has the ability to format the data before it is send to the client

Jump to

Keyboard shortcuts

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