github.com/zhiqiangxu/go-ethereum@v1.9.16-0.20210824055606-be91cfdebc48/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  	"context"
    21  	"encoding/json"
    22  	"fmt"
    23  	"math"
    24  	"strings"
    25  
    26  	"github.com/zhiqiangxu/go-ethereum/common"
    27  	"github.com/zhiqiangxu/go-ethereum/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  // Error wraps RPC errors, which contain an error code in addition to the message.
    39  type Error interface {
    40  	Error() string  // returns the message
    41  	ErrorCode() int // returns the code
    42  }
    43  
    44  // A DataError contains some data in addition to the error message.
    45  type DataError interface {
    46  	Error() string          // returns the message
    47  	ErrorData() interface{} // returns the error data
    48  }
    49  
    50  // ServerCodec implements reading, parsing and writing RPC messages for the server side of
    51  // a RPC session. Implementations must be go-routine safe since the codec can be called in
    52  // multiple go-routines concurrently.
    53  type ServerCodec interface {
    54  	readBatch() (msgs []*jsonrpcMessage, isBatch bool, err error)
    55  	close()
    56  	jsonWriter
    57  }
    58  
    59  // jsonWriter can write JSON messages to its underlying connection.
    60  // Implementations must be safe for concurrent use.
    61  type jsonWriter interface {
    62  	writeJSON(context.Context, interface{}) error
    63  	// Closed returns a channel which is closed when the connection is closed.
    64  	closed() <-chan interface{}
    65  	// RemoteAddr returns the peer address of the connection.
    66  	remoteAddr() string
    67  }
    68  
    69  type BlockNumber int64
    70  
    71  const (
    72  	PendingBlockNumber  = BlockNumber(-2)
    73  	LatestBlockNumber   = BlockNumber(-1)
    74  	EarliestBlockNumber = BlockNumber(0)
    75  )
    76  
    77  // UnmarshalJSON parses the given JSON fragment into a BlockNumber. It supports:
    78  // - "latest", "earliest" or "pending" as string arguments
    79  // - the block number
    80  // Returned errors:
    81  // - an invalid block number error when the given argument isn't a known strings
    82  // - an out of range error when the given block number is either too little or too large
    83  func (bn *BlockNumber) UnmarshalJSON(data []byte) error {
    84  	input := strings.TrimSpace(string(data))
    85  	if len(input) >= 2 && input[0] == '"' && input[len(input)-1] == '"' {
    86  		input = input[1 : len(input)-1]
    87  	}
    88  
    89  	switch input {
    90  	case "earliest":
    91  		*bn = EarliestBlockNumber
    92  		return nil
    93  	case "latest":
    94  		*bn = LatestBlockNumber
    95  		return nil
    96  	case "pending":
    97  		*bn = PendingBlockNumber
    98  		return nil
    99  	}
   100  
   101  	blckNum, err := hexutil.DecodeUint64(input)
   102  	if err != nil {
   103  		return err
   104  	}
   105  	if blckNum > math.MaxInt64 {
   106  		return fmt.Errorf("block number larger than int64")
   107  	}
   108  	*bn = BlockNumber(blckNum)
   109  	return nil
   110  }
   111  
   112  func (bn BlockNumber) Int64() int64 {
   113  	return (int64)(bn)
   114  }
   115  
   116  type BlockNumberOrHash struct {
   117  	BlockNumber      *BlockNumber `json:"blockNumber,omitempty"`
   118  	BlockHash        *common.Hash `json:"blockHash,omitempty"`
   119  	RequireCanonical bool         `json:"requireCanonical,omitempty"`
   120  }
   121  
   122  func (bnh *BlockNumberOrHash) UnmarshalJSON(data []byte) error {
   123  	type erased BlockNumberOrHash
   124  	e := erased{}
   125  	err := json.Unmarshal(data, &e)
   126  	if err == nil {
   127  		if e.BlockNumber != nil && e.BlockHash != nil {
   128  			return fmt.Errorf("cannot specify both BlockHash and BlockNumber, choose one or the other")
   129  		}
   130  		bnh.BlockNumber = e.BlockNumber
   131  		bnh.BlockHash = e.BlockHash
   132  		bnh.RequireCanonical = e.RequireCanonical
   133  		return nil
   134  	}
   135  	var input string
   136  	err = json.Unmarshal(data, &input)
   137  	if err != nil {
   138  		return err
   139  	}
   140  	switch input {
   141  	case "earliest":
   142  		bn := EarliestBlockNumber
   143  		bnh.BlockNumber = &bn
   144  		return nil
   145  	case "latest":
   146  		bn := LatestBlockNumber
   147  		bnh.BlockNumber = &bn
   148  		return nil
   149  	case "pending":
   150  		bn := PendingBlockNumber
   151  		bnh.BlockNumber = &bn
   152  		return nil
   153  	default:
   154  		if len(input) == 66 {
   155  			hash := common.Hash{}
   156  			err := hash.UnmarshalText([]byte(input))
   157  			if err != nil {
   158  				return err
   159  			}
   160  			bnh.BlockHash = &hash
   161  			return nil
   162  		} else {
   163  			blckNum, err := hexutil.DecodeUint64(input)
   164  			if err != nil {
   165  				return err
   166  			}
   167  			if blckNum > math.MaxInt64 {
   168  				return fmt.Errorf("blocknumber too high")
   169  			}
   170  			bn := BlockNumber(blckNum)
   171  			bnh.BlockNumber = &bn
   172  			return nil
   173  		}
   174  	}
   175  }
   176  
   177  func (bnh *BlockNumberOrHash) Number() (BlockNumber, bool) {
   178  	if bnh.BlockNumber != nil {
   179  		return *bnh.BlockNumber, true
   180  	}
   181  	return BlockNumber(0), false
   182  }
   183  
   184  func (bnh *BlockNumberOrHash) Hash() (common.Hash, bool) {
   185  	if bnh.BlockHash != nil {
   186  		return *bnh.BlockHash, true
   187  	}
   188  	return common.Hash{}, false
   189  }
   190  
   191  func BlockNumberOrHashWithNumber(blockNr BlockNumber) BlockNumberOrHash {
   192  	return BlockNumberOrHash{
   193  		BlockNumber:      &blockNr,
   194  		BlockHash:        nil,
   195  		RequireCanonical: false,
   196  	}
   197  }
   198  
   199  func BlockNumberOrHashWithHash(hash common.Hash, canonical bool) BlockNumberOrHash {
   200  	return BlockNumberOrHash{
   201  		BlockNumber:      nil,
   202  		BlockHash:        &hash,
   203  		RequireCanonical: canonical,
   204  	}
   205  }