github.com/calmw/ethereum@v0.1.1/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/calmw/ethereum/common"
    28  	"github.com/calmw/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      // deprecated - this field is no longer used, but retained for compatibility
    35  	Service       interface{} // receiver instance which holds the methods
    36  	Public        bool        // deprecated - this field is no longer used, but retained for compatibility
    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 writes a message to the connection.
    55  	writeJSON(ctx context.Context, msg interface{}, isError bool) error
    56  
    57  	// Closed returns a channel which is closed when the connection is closed.
    58  	closed() <-chan interface{}
    59  	// RemoteAddr returns the peer address of the connection.
    60  	remoteAddr() string
    61  }
    62  
    63  type BlockNumber int64
    64  
    65  const (
    66  	SafeBlockNumber      = BlockNumber(-4)
    67  	FinalizedBlockNumber = BlockNumber(-3)
    68  	PendingBlockNumber   = BlockNumber(-2)
    69  	LatestBlockNumber    = BlockNumber(-1)
    70  	EarliestBlockNumber  = BlockNumber(0)
    71  )
    72  
    73  // UnmarshalJSON parses the given JSON fragment into a BlockNumber. It supports:
    74  // - "safe", "finalized", "latest", "earliest" or "pending" as string arguments
    75  // - the block number
    76  // Returned errors:
    77  // - an invalid block number error when the given argument isn't a known strings
    78  // - an out of range error when the given block number is either too little or too large
    79  func (bn *BlockNumber) UnmarshalJSON(data []byte) error {
    80  	input := strings.TrimSpace(string(data))
    81  	if len(input) >= 2 && input[0] == '"' && input[len(input)-1] == '"' {
    82  		input = input[1 : len(input)-1]
    83  	}
    84  
    85  	switch input {
    86  	case "earliest":
    87  		*bn = EarliestBlockNumber
    88  		return nil
    89  	case "latest":
    90  		*bn = LatestBlockNumber
    91  		return nil
    92  	case "pending":
    93  		*bn = PendingBlockNumber
    94  		return nil
    95  	case "finalized":
    96  		*bn = FinalizedBlockNumber
    97  		return nil
    98  	case "safe":
    99  		*bn = SafeBlockNumber
   100  		return nil
   101  	}
   102  
   103  	blckNum, err := hexutil.DecodeUint64(input)
   104  	if err != nil {
   105  		return err
   106  	}
   107  	if blckNum > math.MaxInt64 {
   108  		return fmt.Errorf("block number larger than int64")
   109  	}
   110  	*bn = BlockNumber(blckNum)
   111  	return nil
   112  }
   113  
   114  // MarshalText implements encoding.TextMarshaler. It marshals:
   115  // - "safe", "finalized", "latest", "earliest" or "pending" as strings
   116  // - other numbers as hex
   117  func (bn BlockNumber) MarshalText() ([]byte, error) {
   118  	switch bn {
   119  	case EarliestBlockNumber:
   120  		return []byte("earliest"), nil
   121  	case LatestBlockNumber:
   122  		return []byte("latest"), nil
   123  	case PendingBlockNumber:
   124  		return []byte("pending"), nil
   125  	case FinalizedBlockNumber:
   126  		return []byte("finalized"), nil
   127  	case SafeBlockNumber:
   128  		return []byte("safe"), nil
   129  	default:
   130  		return hexutil.Uint64(bn).MarshalText()
   131  	}
   132  }
   133  
   134  func (bn BlockNumber) Int64() int64 {
   135  	return (int64)(bn)
   136  }
   137  
   138  type BlockNumberOrHash struct {
   139  	BlockNumber      *BlockNumber `json:"blockNumber,omitempty"`
   140  	BlockHash        *common.Hash `json:"blockHash,omitempty"`
   141  	RequireCanonical bool         `json:"requireCanonical,omitempty"`
   142  }
   143  
   144  func (bnh *BlockNumberOrHash) UnmarshalJSON(data []byte) error {
   145  	type erased BlockNumberOrHash
   146  	e := erased{}
   147  	err := json.Unmarshal(data, &e)
   148  	if err == nil {
   149  		if e.BlockNumber != nil && e.BlockHash != nil {
   150  			return fmt.Errorf("cannot specify both BlockHash and BlockNumber, choose one or the other")
   151  		}
   152  		bnh.BlockNumber = e.BlockNumber
   153  		bnh.BlockHash = e.BlockHash
   154  		bnh.RequireCanonical = e.RequireCanonical
   155  		return nil
   156  	}
   157  	var input string
   158  	err = json.Unmarshal(data, &input)
   159  	if err != nil {
   160  		return err
   161  	}
   162  	switch input {
   163  	case "earliest":
   164  		bn := EarliestBlockNumber
   165  		bnh.BlockNumber = &bn
   166  		return nil
   167  	case "latest":
   168  		bn := LatestBlockNumber
   169  		bnh.BlockNumber = &bn
   170  		return nil
   171  	case "pending":
   172  		bn := PendingBlockNumber
   173  		bnh.BlockNumber = &bn
   174  		return nil
   175  	case "finalized":
   176  		bn := FinalizedBlockNumber
   177  		bnh.BlockNumber = &bn
   178  		return nil
   179  	case "safe":
   180  		bn := SafeBlockNumber
   181  		bnh.BlockNumber = &bn
   182  		return nil
   183  	default:
   184  		if len(input) == 66 {
   185  			hash := common.Hash{}
   186  			err := hash.UnmarshalText([]byte(input))
   187  			if err != nil {
   188  				return err
   189  			}
   190  			bnh.BlockHash = &hash
   191  			return nil
   192  		} else {
   193  			blckNum, err := hexutil.DecodeUint64(input)
   194  			if err != nil {
   195  				return err
   196  			}
   197  			if blckNum > math.MaxInt64 {
   198  				return fmt.Errorf("blocknumber too high")
   199  			}
   200  			bn := BlockNumber(blckNum)
   201  			bnh.BlockNumber = &bn
   202  			return nil
   203  		}
   204  	}
   205  }
   206  
   207  func (bnh *BlockNumberOrHash) Number() (BlockNumber, bool) {
   208  	if bnh.BlockNumber != nil {
   209  		return *bnh.BlockNumber, true
   210  	}
   211  	return BlockNumber(0), false
   212  }
   213  
   214  func (bnh *BlockNumberOrHash) String() string {
   215  	if bnh.BlockNumber != nil {
   216  		return strconv.Itoa(int(*bnh.BlockNumber))
   217  	}
   218  	if bnh.BlockHash != nil {
   219  		return bnh.BlockHash.String()
   220  	}
   221  	return "nil"
   222  }
   223  
   224  func (bnh *BlockNumberOrHash) Hash() (common.Hash, bool) {
   225  	if bnh.BlockHash != nil {
   226  		return *bnh.BlockHash, true
   227  	}
   228  	return common.Hash{}, false
   229  }
   230  
   231  func BlockNumberOrHashWithNumber(blockNr BlockNumber) BlockNumberOrHash {
   232  	return BlockNumberOrHash{
   233  		BlockNumber:      &blockNr,
   234  		BlockHash:        nil,
   235  		RequireCanonical: false,
   236  	}
   237  }
   238  
   239  func BlockNumberOrHashWithHash(hash common.Hash, canonical bool) BlockNumberOrHash {
   240  	return BlockNumberOrHash{
   241  		BlockNumber:      nil,
   242  		BlockHash:        &hash,
   243  		RequireCanonical: canonical,
   244  	}
   245  }