github.com/myafeier/go-ethereum@v1.6.8-0.20170719123245-3e0dbe0eaa72/rpc/types.go (about)

     1  // Copyright 2015 The go-ethereum Authors
     2  // This file is part of the go-ethereum library.
     3  //
     4  // The go-ethereum library is free software: you can redistribute it and/or modify
     5  // it under the terms of the GNU Lesser General Public License as published by
     6  // the Free Software Foundation, either version 3 of the License, or
     7  // (at your option) any later version.
     8  //
     9  // The go-ethereum library is distributed in the hope that it will be useful,
    10  // but WITHOUT ANY WARRANTY; without even the implied warranty of
    11  // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
    12  // GNU Lesser General Public License for more details.
    13  //
    14  // You should have received a copy of the GNU Lesser General Public License
    15  // along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>.
    16  
    17  package rpc
    18  
    19  import (
    20  	"fmt"
    21  	"math"
    22  	"reflect"
    23  	"strings"
    24  	"sync"
    25  
    26  	"github.com/ethereum/go-ethereum/common/hexutil"
    27  	"gopkg.in/fatih/set.v0"
    28  )
    29  
    30  // API describes the set of methods offered over the RPC interface
    31  type API struct {
    32  	Namespace string      // namespace under which the rpc methods of Service are exposed
    33  	Version   string      // api version for DApp's
    34  	Service   interface{} // receiver instance which holds the methods
    35  	Public    bool        // indication if the methods must be considered safe for public use
    36  }
    37  
    38  // callback is a method callback which was registered in the server
    39  type callback struct {
    40  	rcvr        reflect.Value  // receiver of method
    41  	method      reflect.Method // callback
    42  	argTypes    []reflect.Type // input argument types
    43  	hasCtx      bool           // method's first argument is a context (not included in argTypes)
    44  	errPos      int            // err return idx, of -1 when method cannot return error
    45  	isSubscribe bool           // indication if the callback is a subscription
    46  }
    47  
    48  // service represents a registered object
    49  type service struct {
    50  	name          string        // name for service
    51  	rcvr          reflect.Value // receiver of methods for the service
    52  	typ           reflect.Type  // receiver type
    53  	callbacks     callbacks     // registered handlers
    54  	subscriptions subscriptions // available subscriptions/notifications
    55  }
    56  
    57  // serverRequest is an incoming request
    58  type serverRequest struct {
    59  	id            interface{}
    60  	svcname       string
    61  	rcvr          reflect.Value
    62  	callb         *callback
    63  	args          []reflect.Value
    64  	isUnsubscribe bool
    65  	err           Error
    66  }
    67  
    68  type serviceRegistry map[string]*service       // collection of services
    69  type callbacks map[string]*callback            // collection of RPC callbacks
    70  type subscriptions map[string]*callback        // collection of subscription callbacks
    71  type subscriptionRegistry map[string]*callback // collection of subscription callbacks
    72  
    73  // Server represents a RPC server
    74  type Server struct {
    75  	services       serviceRegistry
    76  	muSubcriptions sync.Mutex // protects subscriptions
    77  	subscriptions  subscriptionRegistry
    78  
    79  	run      int32
    80  	codecsMu sync.Mutex
    81  	codecs   *set.Set
    82  }
    83  
    84  // rpcRequest represents a raw incoming RPC request
    85  type rpcRequest struct {
    86  	service  string
    87  	method   string
    88  	id       interface{}
    89  	isPubSub bool
    90  	params   interface{}
    91  	err      Error // invalid batch element
    92  }
    93  
    94  // Error wraps RPC errors, which contain an error code in addition to the message.
    95  type Error interface {
    96  	Error() string  // returns the message
    97  	ErrorCode() int // returns the code
    98  }
    99  
   100  // ServerCodec implements reading, parsing and writing RPC messages for the server side of
   101  // a RPC session. Implementations must be go-routine safe since the codec can be called in
   102  // multiple go-routines concurrently.
   103  type ServerCodec interface {
   104  	// Read next request
   105  	ReadRequestHeaders() ([]rpcRequest, bool, Error)
   106  	// Parse request argument to the given types
   107  	ParseRequestArguments(argTypes []reflect.Type, params interface{}) ([]reflect.Value, Error)
   108  	// Assemble success response, expects response id and payload
   109  	CreateResponse(id interface{}, reply interface{}) interface{}
   110  	// Assemble error response, expects response id and error
   111  	CreateErrorResponse(id interface{}, err Error) interface{}
   112  	// Assemble error response with extra information about the error through info
   113  	CreateErrorResponseWithInfo(id interface{}, err Error, info interface{}) interface{}
   114  	// Create notification response
   115  	CreateNotification(id, namespace string, event interface{}) interface{}
   116  	// Write msg to client.
   117  	Write(msg interface{}) error
   118  	// Close underlying data stream
   119  	Close()
   120  	// Closed when underlying connection is closed
   121  	Closed() <-chan interface{}
   122  }
   123  
   124  type BlockNumber int64
   125  
   126  const (
   127  	PendingBlockNumber  = BlockNumber(-2)
   128  	LatestBlockNumber   = BlockNumber(-1)
   129  	EarliestBlockNumber = BlockNumber(0)
   130  )
   131  
   132  // UnmarshalJSON parses the given JSON fragment into a BlockNumber. It supports:
   133  // - "latest", "earliest" or "pending" as string arguments
   134  // - the block number
   135  // Returned errors:
   136  // - an invalid block number error when the given argument isn't a known strings
   137  // - an out of range error when the given block number is either too little or too large
   138  func (bn *BlockNumber) UnmarshalJSON(data []byte) error {
   139  	input := strings.TrimSpace(string(data))
   140  	if len(input) >= 2 && input[0] == '"' && input[len(input)-1] == '"' {
   141  		input = input[1 : len(input)-1]
   142  	}
   143  
   144  	switch input {
   145  	case "earliest":
   146  		*bn = EarliestBlockNumber
   147  		return nil
   148  	case "latest":
   149  		*bn = LatestBlockNumber
   150  		return nil
   151  	case "pending":
   152  		*bn = PendingBlockNumber
   153  		return nil
   154  	}
   155  
   156  	blckNum, err := hexutil.DecodeUint64(input)
   157  	if err != nil {
   158  		return err
   159  	}
   160  	if blckNum > math.MaxInt64 {
   161  		return fmt.Errorf("Blocknumber too high")
   162  	}
   163  
   164  	*bn = BlockNumber(blckNum)
   165  	return nil
   166  }
   167  
   168  func (bn BlockNumber) Int64() int64 {
   169  	return (int64)(bn)
   170  }