-
Notifications
You must be signed in to change notification settings - Fork 179
/
block.go
81 lines (68 loc) · 2.01 KB
/
block.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
package types
import (
"fmt"
"math"
"math/big"
"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)
// PendingBlockNumber mapping from "pending" to -1 for tm query
PendingBlockNumber = BlockNumber(-1)
)
// NewBlockNumber creates a new BlockNumber instance.
func NewBlockNumber(n *big.Int) BlockNumber {
return BlockNumber(n.Int64())
}
// 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":
*bn = PendingBlockNumber
return nil
}
blckNum, err := hexutil.DecodeUint64(input)
if err != nil {
return err
}
if blckNum > math.MaxInt64 {
return fmt.Errorf("blocknumber too high")
}
*bn = BlockNumber(blckNum)
return nil
}
// Int64 converts block number to primitive type
func (bn BlockNumber) Int64() int64 {
return int64(bn)
}
// TmHeight is a util function used for the Tendermint RPC client. It returns
// nil if the block number is "latest". Otherwise, it returns the pointer of the
// int64 value of the height.
func (bn BlockNumber) TmHeight() *int64 {
if bn == LatestBlockNumber {
return nil
}
height := bn.Int64()
return &height
}