github.com/simplechain-org/go-simplechain@v1.0.6/rpc/types.go (about)

     1  // Copyright 2015 The go-simplechain Authors
     2  // This file is part of the go-simplechain library.
     3  //
     4  // The go-simplechain 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-simplechain 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-simplechain 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/simplechain-org/go-simplechain/common"
    27  	"github.com/simplechain-org/go-simplechain/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  // ServerCodec implements reading, parsing and writing RPC messages for the server side of
    45  // a RPC session. Implementations must be go-routine safe since the codec can be called in
    46  // multiple go-routines concurrently.
    47  type ServerCodec interface {
    48  	readBatch() (msgs []*jsonrpcMessage, isBatch bool, err error)
    49  	close()
    50  	jsonWriter
    51  }
    52  
    53  // jsonWriter can write JSON messages to its underlying connection.
    54  // Implementations must be safe for concurrent use.
    55  type jsonWriter interface {
    56  	writeJSON(context.Context, interface{}) error
    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  	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  func (bn BlockNumber) Int64() int64 {
   107  	return (int64)(bn)
   108  }
   109  
   110  type BlockNumberOrHash struct {
   111  	BlockNumber      *BlockNumber `json:"blockNumber,omitempty"`
   112  	BlockHash        *common.Hash `json:"blockHash,omitempty"`
   113  	RequireCanonical bool         `json:"requireCanonical,omitempty"`
   114  }
   115  
   116  func (bnh *BlockNumberOrHash) UnmarshalJSON(data []byte) error {
   117  	type erased BlockNumberOrHash
   118  	e := erased{}
   119  	err := json.Unmarshal(data, &e)
   120  	if err == nil {
   121  		if e.BlockNumber != nil && e.BlockHash != nil {
   122  			return fmt.Errorf("cannot specify both BlockHash and BlockNumber, choose one or the other")
   123  		}
   124  		bnh.BlockNumber = e.BlockNumber
   125  		bnh.BlockHash = e.BlockHash
   126  		bnh.RequireCanonical = e.RequireCanonical
   127  		return nil
   128  	}
   129  	var input string
   130  	err = json.Unmarshal(data, &input)
   131  	if err != nil {
   132  		return err
   133  	}
   134  	switch input {
   135  	case "earliest":
   136  		bn := EarliestBlockNumber
   137  		bnh.BlockNumber = &bn
   138  		return nil
   139  	case "latest":
   140  		bn := LatestBlockNumber
   141  		bnh.BlockNumber = &bn
   142  		return nil
   143  	case "pending":
   144  		bn := PendingBlockNumber
   145  		bnh.BlockNumber = &bn
   146  		return nil
   147  	default:
   148  		if len(input) == 66 {
   149  			hash := common.Hash{}
   150  			err := hash.UnmarshalText([]byte(input))
   151  			if err != nil {
   152  				return err
   153  			}
   154  			bnh.BlockHash = &hash
   155  			return nil
   156  		} else {
   157  			blckNum, err := hexutil.DecodeUint64(input)
   158  			if err != nil {
   159  				return err
   160  			}
   161  			if blckNum > math.MaxInt64 {
   162  				return fmt.Errorf("blocknumber too high")
   163  			}
   164  			bn := BlockNumber(blckNum)
   165  			bnh.BlockNumber = &bn
   166  			return nil
   167  		}
   168  	}
   169  }
   170  
   171  func (bnh *BlockNumberOrHash) Number() (BlockNumber, bool) {
   172  	if bnh.BlockNumber != nil {
   173  		return *bnh.BlockNumber, true
   174  	}
   175  	return BlockNumber(0), false
   176  }
   177  
   178  func (bnh *BlockNumberOrHash) Hash() (common.Hash, bool) {
   179  	if bnh.BlockHash != nil {
   180  		return *bnh.BlockHash, true
   181  	}
   182  	return common.Hash{}, false
   183  }
   184  
   185  func BlockNumberOrHashWithNumber(blockNr BlockNumber) BlockNumberOrHash {
   186  	return BlockNumberOrHash{
   187  		BlockNumber:      &blockNr,
   188  		BlockHash:        nil,
   189  		RequireCanonical: false,
   190  	}
   191  }
   192  
   193  func BlockNumberOrHashWithHash(hash common.Hash, canonical bool) BlockNumberOrHash {
   194  	return BlockNumberOrHash{
   195  		BlockNumber:      nil,
   196  		BlockHash:        &hash,
   197  		RequireCanonical: canonical,
   198  	}
   199  }