github.com/palisadeinc/bor@v0.0.0-20230615125219-ab7196213d15/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  	"strconv"
    25  	"strings"
    26  
    27  	"github.com/ethereum/go-ethereum/common"
    28  	"github.com/ethereum/go-ethereum/common/hexutil"
    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  	Authenticated bool        // whether the api should only be available behind authentication.
    38  }
    39  
    40  // ServerCodec implements reading, parsing and writing RPC messages for the server side of
    41  // a RPC session. Implementations must be go-routine safe since the codec can be called in
    42  // multiple go-routines concurrently.
    43  type ServerCodec interface {
    44  	peerInfo() PeerInfo
    45  	readBatch() (msgs []*jsonrpcMessage, isBatch bool, err error)
    46  	close()
    47  
    48  	jsonWriter
    49  }
    50  
    51  // jsonWriter can write JSON messages to its underlying connection.
    52  // Implementations must be safe for concurrent use.
    53  type jsonWriter interface {
    54  	writeJSON(context.Context, interface{}) error
    55  	// Closed returns a channel which is closed when the connection is closed.
    56  	closed() <-chan interface{}
    57  	// RemoteAddr returns the peer address of the connection.
    58  	remoteAddr() string
    59  }
    60  
    61  type BlockNumber int64
    62  
    63  const (
    64  	SafeBlockNumber      = BlockNumber(-4)
    65  	FinalizedBlockNumber = BlockNumber(-3)
    66  	PendingBlockNumber   = BlockNumber(-2)
    67  	LatestBlockNumber    = BlockNumber(-1)
    68  	EarliestBlockNumber  = BlockNumber(0)
    69  )
    70  
    71  // UnmarshalJSON parses the given JSON fragment into a BlockNumber. It supports:
    72  // - "latest", "earliest" or "pending" as string arguments
    73  // - the block number
    74  // Returned errors:
    75  // - an invalid block number error when the given argument isn't a known strings
    76  // - an out of range error when the given block number is either too little or too large
    77  func (bn *BlockNumber) UnmarshalJSON(data []byte) error {
    78  	input := strings.TrimSpace(string(data))
    79  	if len(input) >= 2 && input[0] == '"' && input[len(input)-1] == '"' {
    80  		input = input[1 : len(input)-1]
    81  	}
    82  
    83  	switch input {
    84  	case "earliest":
    85  		*bn = EarliestBlockNumber
    86  		return nil
    87  	case "latest":
    88  		*bn = LatestBlockNumber
    89  		return nil
    90  	case "pending":
    91  		*bn = PendingBlockNumber
    92  		return nil
    93  	}
    94  
    95  	blckNum, err := hexutil.DecodeUint64(input)
    96  	if err != nil {
    97  		return err
    98  	}
    99  	if blckNum > math.MaxInt64 {
   100  		return fmt.Errorf("block number larger than int64")
   101  	}
   102  	*bn = BlockNumber(blckNum)
   103  	return nil
   104  }
   105  
   106  // MarshalText implements encoding.TextMarshaler. It marshals:
   107  // - "latest", "earliest" or "pending" as strings
   108  // - other numbers as hex
   109  func (bn BlockNumber) MarshalText() ([]byte, error) {
   110  	switch bn {
   111  	case EarliestBlockNumber:
   112  		return []byte("earliest"), nil
   113  	case LatestBlockNumber:
   114  		return []byte("latest"), nil
   115  	case PendingBlockNumber:
   116  		return []byte("pending"), nil
   117  	default:
   118  		return hexutil.Uint64(bn).MarshalText()
   119  	}
   120  }
   121  
   122  func (bn BlockNumber) Int64() int64 {
   123  	return (int64)(bn)
   124  }
   125  
   126  type BlockNumberOrHash struct {
   127  	BlockNumber      *BlockNumber `json:"blockNumber,omitempty"`
   128  	BlockHash        *common.Hash `json:"blockHash,omitempty"`
   129  	RequireCanonical bool         `json:"requireCanonical,omitempty"`
   130  }
   131  
   132  func (bnh *BlockNumberOrHash) UnmarshalJSON(data []byte) error {
   133  	type erased BlockNumberOrHash
   134  	e := erased{}
   135  	err := json.Unmarshal(data, &e)
   136  	if err == nil {
   137  		if e.BlockNumber != nil && e.BlockHash != nil {
   138  			return fmt.Errorf("cannot specify both BlockHash and BlockNumber, choose one or the other")
   139  		}
   140  		bnh.BlockNumber = e.BlockNumber
   141  		bnh.BlockHash = e.BlockHash
   142  		bnh.RequireCanonical = e.RequireCanonical
   143  		return nil
   144  	}
   145  	var input string
   146  	err = json.Unmarshal(data, &input)
   147  	if err != nil {
   148  		return err
   149  	}
   150  	switch input {
   151  	case "earliest":
   152  		bn := EarliestBlockNumber
   153  		bnh.BlockNumber = &bn
   154  		return nil
   155  	case "latest":
   156  		bn := LatestBlockNumber
   157  		bnh.BlockNumber = &bn
   158  		return nil
   159  	case "pending":
   160  		bn := PendingBlockNumber
   161  		bnh.BlockNumber = &bn
   162  		return nil
   163  	default:
   164  		if len(input) == 66 {
   165  			hash := common.Hash{}
   166  			err := hash.UnmarshalText([]byte(input))
   167  			if err != nil {
   168  				return err
   169  			}
   170  			bnh.BlockHash = &hash
   171  			return nil
   172  		} else {
   173  			blckNum, err := hexutil.DecodeUint64(input)
   174  			if err != nil {
   175  				return err
   176  			}
   177  			if blckNum > math.MaxInt64 {
   178  				return fmt.Errorf("blocknumber too high")
   179  			}
   180  			bn := BlockNumber(blckNum)
   181  			bnh.BlockNumber = &bn
   182  			return nil
   183  		}
   184  	}
   185  }
   186  
   187  func (bnh *BlockNumberOrHash) Number() (BlockNumber, bool) {
   188  	if bnh.BlockNumber != nil {
   189  		return *bnh.BlockNumber, true
   190  	}
   191  	return BlockNumber(0), false
   192  }
   193  
   194  func (bnh *BlockNumberOrHash) String() string {
   195  	if bnh.BlockNumber != nil {
   196  		return strconv.Itoa(int(*bnh.BlockNumber))
   197  	}
   198  	if bnh.BlockHash != nil {
   199  		return bnh.BlockHash.String()
   200  	}
   201  	return "nil"
   202  }
   203  
   204  func (bnh *BlockNumberOrHash) Hash() (common.Hash, bool) {
   205  	if bnh.BlockHash != nil {
   206  		return *bnh.BlockHash, true
   207  	}
   208  	return common.Hash{}, false
   209  }
   210  
   211  func BlockNumberOrHashWithNumber(blockNr BlockNumber) BlockNumberOrHash {
   212  	return BlockNumberOrHash{
   213  		BlockNumber:      &blockNr,
   214  		BlockHash:        nil,
   215  		RequireCanonical: false,
   216  	}
   217  }
   218  
   219  func BlockNumberOrHashWithHash(hash common.Hash, canonical bool) BlockNumberOrHash {
   220  	return BlockNumberOrHash{
   221  		BlockNumber:      nil,
   222  		BlockHash:        &hash,
   223  		RequireCanonical: canonical,
   224  	}
   225  }
   226  
   227  // DecimalOrHex unmarshals a non-negative decimal or hex parameter into a uint64.
   228  type DecimalOrHex uint64
   229  
   230  // UnmarshalJSON implements json.Unmarshaler.
   231  func (dh *DecimalOrHex) UnmarshalJSON(data []byte) error {
   232  	input := strings.TrimSpace(string(data))
   233  	if len(input) >= 2 && input[0] == '"' && input[len(input)-1] == '"' {
   234  		input = input[1 : len(input)-1]
   235  	}
   236  
   237  	value, err := strconv.ParseUint(input, 10, 64)
   238  	if err != nil {
   239  		value, err = hexutil.DecodeUint64(input)
   240  	}
   241  	if err != nil {
   242  		return err
   243  	}
   244  	*dh = DecimalOrHex(value)
   245  	return nil
   246  }