gitlab.com/aquachain/aquachain@v1.17.16-rc3.0.20221018032414-e3ddf1e1c055/rpc/types.go (about)

     1  // Copyright 2018 The aquachain Authors
     2  // This file is part of the aquachain library.
     3  //
     4  // The aquachain 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 aquachain 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 aquachain 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  	set "github.com/deckarep/golang-set"
    27  	"gitlab.com/aquachain/aquachain/common/hexutil"
    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  	typ           reflect.Type  // receiver type
    52  	callbacks     callbacks     // registered handlers
    53  	subscriptions subscriptions // available subscriptions/notifications
    54  }
    55  
    56  // serverRequest is an incoming request
    57  type serverRequest struct {
    58  	id            interface{}
    59  	svcname       string
    60  	callb         *callback
    61  	args          []reflect.Value
    62  	isUnsubscribe bool
    63  	err           Error
    64  }
    65  
    66  type serviceRegistry map[string]*service // collection of services
    67  type callbacks map[string]*callback      // collection of RPC callbacks
    68  type subscriptions map[string]*callback  // collection of subscription callbacks
    69  
    70  // Server represents a RPC server
    71  type Server struct {
    72  	services serviceRegistry
    73  
    74  	run          int32
    75  	codecsMu     sync.Mutex
    76  	codecs       set.Set
    77  	reverseproxy bool // if true, check X-FORWARDED-FOR header
    78  
    79  }
    80  
    81  // rpcRequest represents a raw incoming RPC request
    82  type rpcRequest struct {
    83  	service  string
    84  	method   string
    85  	id       interface{}
    86  	isPubSub bool
    87  	params   interface{}
    88  	err      Error // invalid batch element
    89  }
    90  
    91  // Error wraps RPC errors, which contain an error code in addition to the message.
    92  type Error interface {
    93  	Error() string  // returns the message
    94  	ErrorCode() int // returns the code
    95  }
    96  
    97  // ServerCodec implements reading, parsing and writing RPC messages for the server side of
    98  // a RPC session. Implementations must be go-routine safe since the codec can be called in
    99  // multiple go-routines concurrently.
   100  type ServerCodec interface {
   101  	// Read next request
   102  	ReadRequestHeaders() ([]rpcRequest, bool, Error)
   103  	// Parse request argument to the given types
   104  	ParseRequestArguments(argTypes []reflect.Type, params interface{}) ([]reflect.Value, Error)
   105  	// Assemble success response, expects response id and payload
   106  	CreateResponse(id interface{}, reply interface{}) interface{}
   107  	// Assemble error response, expects response id and error
   108  	CreateErrorResponse(id interface{}, err Error) interface{}
   109  	// Assemble error response with extra information about the error through info
   110  	CreateErrorResponseWithInfo(id interface{}, err Error, info interface{}) interface{}
   111  	// Create notification response
   112  	CreateNotification(id, namespace string, event interface{}) interface{}
   113  	// Write msg to client.
   114  	Write(msg interface{}) error
   115  	// Close underlying data stream
   116  	Close()
   117  	// Closed when underlying connection is closed
   118  	Closed() <-chan interface{}
   119  }
   120  
   121  type BlockNumber int64
   122  
   123  const (
   124  	PendingBlockNumber  = BlockNumber(-2)
   125  	LatestBlockNumber   = BlockNumber(-1)
   126  	EarliestBlockNumber = BlockNumber(0)
   127  )
   128  
   129  // UnmarshalJSON parses the given JSON fragment into a BlockNumber. It supports:
   130  // - "latest", "earliest" or "pending" as string arguments
   131  // - the block number
   132  // Returned errors:
   133  // - an invalid block number error when the given argument isn't a known strings
   134  // - an out of range error when the given block number is either too little or too large
   135  func (bn *BlockNumber) UnmarshalJSON(data []byte) error {
   136  	input := strings.TrimSpace(string(data))
   137  	if len(input) >= 2 && input[0] == '"' && input[len(input)-1] == '"' {
   138  		input = input[1 : len(input)-1]
   139  	}
   140  
   141  	switch input {
   142  	case "earliest":
   143  		*bn = EarliestBlockNumber
   144  		return nil
   145  	case "latest":
   146  		*bn = LatestBlockNumber
   147  		return nil
   148  	case "pending":
   149  		*bn = PendingBlockNumber
   150  		return nil
   151  	}
   152  
   153  	blckNum, err := hexutil.DecodeUint64(input)
   154  	if err != nil {
   155  		return err
   156  	}
   157  	if blckNum > math.MaxInt64 {
   158  		return fmt.Errorf("Blocknumber too high")
   159  	}
   160  
   161  	*bn = BlockNumber(blckNum)
   162  	return nil
   163  }
   164  
   165  func (bn BlockNumber) Int64() int64 {
   166  	return (int64)(bn)
   167  }