2019-09-24 21:38:58 +00:00
|
|
|
package rpc
|
|
|
|
|
|
|
|
import (
|
|
|
|
"fmt"
|
|
|
|
"math"
|
2020-04-13 19:18:50 +00:00
|
|
|
"math/big"
|
2019-09-24 21:38:58 +00:00
|
|
|
"strings"
|
|
|
|
|
|
|
|
"github.com/ethereum/go-ethereum/common/hexutil"
|
|
|
|
)
|
|
|
|
|
|
|
|
// BlockNumber represents decoding hex string to block values
|
|
|
|
type BlockNumber int64
|
|
|
|
|
|
|
|
const (
|
|
|
|
// LatestBlockNumber mapping from "latest" to 0 for tm query
|
|
|
|
LatestBlockNumber = BlockNumber(0)
|
|
|
|
|
|
|
|
// EarliestBlockNumber mapping from "earliest" to 1 for tm query (earliest query not supported)
|
|
|
|
EarliestBlockNumber = BlockNumber(1)
|
|
|
|
)
|
|
|
|
|
2020-04-13 19:18:50 +00:00
|
|
|
func NewBlockNumber(n *big.Int) BlockNumber {
|
|
|
|
return BlockNumber(n.Int64())
|
|
|
|
}
|
|
|
|
|
2019-09-24 21:38:58 +00:00
|
|
|
// UnmarshalJSON parses the given JSON fragment into a BlockNumber. It supports:
|
|
|
|
// - "latest", "earliest" or "pending" as string arguments
|
|
|
|
// - the block number
|
|
|
|
// Returned errors:
|
|
|
|
// - an invalid block number error when the given argument isn't a known strings
|
|
|
|
// - an out of range error when the given block number is either too little or too large
|
|
|
|
func (bn *BlockNumber) UnmarshalJSON(data []byte) error {
|
|
|
|
input := strings.TrimSpace(string(data))
|
|
|
|
if len(input) >= 2 && input[0] == '"' && input[len(input)-1] == '"' {
|
|
|
|
input = input[1 : len(input)-1]
|
|
|
|
}
|
|
|
|
|
|
|
|
switch input {
|
|
|
|
case "earliest":
|
|
|
|
*bn = EarliestBlockNumber
|
|
|
|
return nil
|
|
|
|
case "latest":
|
|
|
|
*bn = LatestBlockNumber
|
|
|
|
return nil
|
|
|
|
case "pending":
|
2020-05-15 02:08:13 +00:00
|
|
|
*bn = LatestBlockNumber
|
|
|
|
return nil
|
2019-09-24 21:38:58 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
blckNum, err := hexutil.DecodeUint64(input)
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
if blckNum > math.MaxInt64 {
|
2020-01-07 20:56:49 +00:00
|
|
|
return fmt.Errorf("blocknumber too high")
|
2019-09-24 21:38:58 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
*bn = BlockNumber(blckNum)
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
// Int64 converts block number to primitive type
|
|
|
|
func (bn BlockNumber) Int64() int64 {
|
|
|
|
return (int64)(bn)
|
|
|
|
}
|