github.com/n1ghtfa1l/go-vnt@v0.6.4-alpha.6/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/vntchain/go-vnt/common"
    27  	"github.com/vntchain/go-vnt/common/hexutil"
    28  	set "gopkg.in/fatih/set.v0"
    29  )
    30  
    31  // API describes the set of methods offered over the RPC interface
    32  type API struct {
    33  	Namespace string      // namespace under which the rpc methods of Service are exposed
    34  	Version   string      // api version for DApp's
    35  	Service   interface{} // receiver instance which holds the methods
    36  	Public    bool        // indication if the methods must be considered safe for public use
    37  }
    38  
    39  // callback is a method callback which was registered in the server
    40  type callback struct {
    41  	rcvr        reflect.Value  // receiver of method
    42  	method      reflect.Method // callback
    43  	argTypes    []reflect.Type // input argument types
    44  	hasCtx      bool           // method's first argument is a context (not included in argTypes)
    45  	errPos      int            // err return idx, of -1 when method cannot return error
    46  	isSubscribe bool           // indication if the callback is a subscription
    47  }
    48  
    49  // service represents a registered object
    50  type service struct {
    51  	name          string        // name for 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  	callb         *callback
    62  	args          []reflect.Value
    63  	isUnsubscribe bool
    64  	err           Error
    65  }
    66  
    67  type serviceRegistry map[string]*service // collection of services
    68  type callbacks map[string]*callback      // collection of RPC callbacks
    69  type subscriptions map[string]*callback  // collection of subscription callbacks
    70  
    71  // Server represents a RPC server
    72  type Server struct {
    73  	services serviceRegistry
    74  
    75  	run      int32
    76  	codecsMu sync.Mutex
    77  	codecs   *set.Set
    78  }
    79  
    80  // rpcRequest represents a raw incoming RPC request
    81  type rpcRequest struct {
    82  	service  string
    83  	method   string
    84  	id       interface{}
    85  	isPubSub bool
    86  	params   interface{}
    87  	err      Error // invalid batch element
    88  }
    89  
    90  // Error wraps RPC errors, which contain an error code in addition to the message.
    91  type Error interface {
    92  	Error() string  // returns the message
    93  	ErrorCode() int // returns the code
    94  }
    95  
    96  // ServerCodec implements reading, parsing and writing RPC messages for the server side of
    97  // a RPC session. Implementations must be go-routine safe since the codec can be called in
    98  // multiple go-routines concurrently.
    99  type ServerCodec interface {
   100  	// Read next request
   101  	ReadRequestHeaders() ([]rpcRequest, bool, Error)
   102  	// Parse request argument to the given types
   103  	ParseRequestArguments(argTypes []reflect.Type, params interface{}) ([]reflect.Value, Error)
   104  	// Assemble success response, expects response id and payload
   105  	CreateResponse(id interface{}, reply interface{}) interface{}
   106  	// Assemble error response, expects response id and error
   107  	CreateErrorResponse(id interface{}, err Error) interface{}
   108  	// Assemble error response with extra information about the error through info
   109  	CreateErrorResponseWithInfo(id interface{}, err Error, info interface{}) interface{}
   110  	// Create notification response
   111  	CreateNotification(id, namespace string, event interface{}) interface{}
   112  	// Write msg to client.
   113  	Write(msg interface{}) error
   114  	// Close underlying data stream
   115  	Close()
   116  	// Closed when underlying connection is closed
   117  	Closed() <-chan interface{}
   118  }
   119  
   120  type BlockNumber int64
   121  
   122  const (
   123  	PendingBlockNumber  = BlockNumber(-2)
   124  	LatestBlockNumber   = BlockNumber(-1)
   125  	EarliestBlockNumber = BlockNumber(0)
   126  )
   127  
   128  // UnmarshalJSON parses the given JSON fragment into a BlockNumber. It supports:
   129  // - "latest", "earliest" or "pending" as string arguments
   130  // - the block number
   131  // Returned errors:
   132  // - an invalid block number error when the given argument isn't a known strings
   133  // - an out of range error when the given block number is either too little or too large
   134  func (bn *BlockNumber) UnmarshalJSON(data []byte) error {
   135  	input := strings.TrimSpace(string(data))
   136  	if len(input) >= 2 && input[0] == '"' && input[len(input)-1] == '"' {
   137  		input = input[1 : len(input)-1]
   138  	}
   139  
   140  	switch input {
   141  	case "earliest":
   142  		*bn = EarliestBlockNumber
   143  		return nil
   144  	case "latest":
   145  		*bn = LatestBlockNumber
   146  		return nil
   147  	case "pending":
   148  		*bn = PendingBlockNumber
   149  		return nil
   150  	}
   151  
   152  	blckNum, err := hexutil.DecodeUint64(input)
   153  	if err != nil {
   154  		return err
   155  	}
   156  	if blckNum > math.MaxInt64 {
   157  		return fmt.Errorf("Blocknumber too high")
   158  	}
   159  
   160  	*bn = BlockNumber(blckNum)
   161  	return nil
   162  }
   163  
   164  func (bn BlockNumber) Int64() int64 {
   165  	return (int64)(bn)
   166  }
   167  
   168  // Candidate is the information of a witness candidate
   169  // Using hexutil.Big to replace big.Int for client
   170  // can read the value as string
   171  type Candidate struct {
   172  	Owner       string       `json:"owner"`       // 候选人地址
   173  	Name        string       `json:"name"`        // 候选人名称
   174  	Registered  bool         `json:"registered"`  // 是否为注册状态
   175  	Website     string       `json:"website"`     // 见证人网站
   176  	Url         string       `json:"url"`         // 节点的URL
   177  	VoteCount   *hexutil.Big `json:"voteCount"`   // 收到的票数
   178  	Binder      string       `json:"binder"`      // 锁仓人/绑定人
   179  	Beneficiary string       `json:"beneficiary"` // 收益受益人
   180  	Bind        bool         `json:"bind"`        // 是否被绑定
   181  }
   182  
   183  // Voter is the information of who has vote witness candidate
   184  type Voter struct {
   185  	Owner             common.Address   `json:"owner"`             // 投票人的地址
   186  	IsProxy           bool             `json:"isProxy"`           // 是否是代理人
   187  	ProxyVoteCount    *hexutil.Big     `json:"proxyVoteCount"`    // 收到的代理的票数
   188  	Proxy             common.Address   `json:"proxy"`             // 该节点设置的代理人
   189  	LastStakeCount    *hexutil.Big     `json:"lastStakeCount"`    // 上次投票是抵押的代币数
   190  	LastVoteCount     *hexutil.Big     `json:"lastVoteCount"`     // 上次投的票数
   191  	LastVoteTimeStamp *hexutil.Big     `json:"lastVoteTimeStamp"` // 上次投票时间戳
   192  	VoteCandidates    []common.Address `json:"voteCandidates"`    // 投了哪些人
   193  }
   194  
   195  // Stake is the information of a user
   196  type Stake struct {
   197  	Owner              common.Address `json:"owner"`              // 抵押代币的所有人
   198  	StakeCount         *hexutil.Big   `json:"stakeCount"`         // 会被计入票数的VNT数量,取整
   199  	Vnt                *hexutil.Big   `json:"vnt"`                // 抵押的代币数量
   200  	LastStakeTimeStamp *hexutil.Big   `json:"lastStakeTimeStamp"` // 上次抵押时间戳
   201  }