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