github.com/murrekatt/go-ethereum@v1.5.8-0.20170123175102-fc52f2c007fb/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  	"math/big"
    23  	"reflect"
    24  	"strings"
    25  	"sync"
    26  
    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([]reflect.Type, interface{}) ([]reflect.Value, Error)
   108  	// Assemble success response, expects response id and payload
   109  	CreateResponse(interface{}, interface{}) interface{}
   110  	// Assemble error response, expects response id and error
   111  	CreateErrorResponse(interface{}, 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(string, interface{}) interface{}
   116  	// Write msg to client.
   117  	Write(interface{}) error
   118  	// Close underlying data stream
   119  	Close()
   120  	// Closed when underlying connection is closed
   121  	Closed() <-chan interface{}
   122  }
   123  
   124  var (
   125  	pendingBlockNumber  = big.NewInt(-2)
   126  	latestBlockNumber   = big.NewInt(-1)
   127  	earliestBlockNumber = big.NewInt(0)
   128  	maxBlockNumber      = big.NewInt(math.MaxInt64)
   129  )
   130  
   131  type BlockNumber int64
   132  
   133  const (
   134  	PendingBlockNumber = BlockNumber(-2)
   135  	LatestBlockNumber  = BlockNumber(-1)
   136  )
   137  
   138  // UnmarshalJSON parses the given JSON fragment into a BlockNumber. It supports:
   139  // - "latest", "earliest" or "pending" as string arguments
   140  // - the block number
   141  // Returned errors:
   142  // - an invalid block number error when the given argument isn't a known strings
   143  // - an out of range error when the given block number is either too little or too large
   144  func (bn *BlockNumber) UnmarshalJSON(data []byte) error {
   145  	input := strings.TrimSpace(string(data))
   146  
   147  	if len(input) >= 2 && input[0] == '"' && input[len(input)-1] == '"' {
   148  		input = input[1 : len(input)-1]
   149  	}
   150  
   151  	if len(input) == 0 {
   152  		*bn = BlockNumber(latestBlockNumber.Int64())
   153  		return nil
   154  	}
   155  
   156  	in := new(big.Int)
   157  	_, ok := in.SetString(input, 0)
   158  
   159  	if !ok { // test if user supplied string tag
   160  		strBlockNumber := input
   161  		if strBlockNumber == "latest" {
   162  			*bn = BlockNumber(latestBlockNumber.Int64())
   163  			return nil
   164  		}
   165  
   166  		if strBlockNumber == "earliest" {
   167  			*bn = BlockNumber(earliestBlockNumber.Int64())
   168  			return nil
   169  		}
   170  
   171  		if strBlockNumber == "pending" {
   172  			*bn = BlockNumber(pendingBlockNumber.Int64())
   173  			return nil
   174  		}
   175  
   176  		return fmt.Errorf(`invalid blocknumber %s`, data)
   177  	}
   178  
   179  	if in.Cmp(earliestBlockNumber) >= 0 && in.Cmp(maxBlockNumber) <= 0 {
   180  		*bn = BlockNumber(in.Int64())
   181  		return nil
   182  	}
   183  
   184  	return fmt.Errorf("blocknumber not in range [%d, %d]", earliestBlockNumber, maxBlockNumber)
   185  }
   186  
   187  func (bn BlockNumber) Int64() int64 {
   188  	return (int64)(bn)
   189  }