/
client.go
executable file
·182 lines (163 loc) · 5.89 KB
/
client.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
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
package blockwatch
import (
"context"
"fmt"
"math/big"
"time"
"github.com/ethereum/go-ethereum"
"github.com/ethereum/go-ethereum/common"
"github.com/ethereum/go-ethereum/common/hexutil"
"github.com/ethereum/go-ethereum/common/math"
ethtypes "github.com/ethereum/go-ethereum/core/types"
"github.com/map-bgp/browserbook/browserbook-mesh/common/types"
"github.com/map-bgp/browserbook/browserbook-mesh/constants"
"github.com/map-bgp/browserbook/browserbook-mesh/ethereum/ethrpcclient"
)
const (
// We give up on ETH RPC requests sent for the purpose of block watching after 10 seconds
requestTimeout = 10 * time.Second
bigIntParsingErrorString = "Failed to parse big.Int value from hex-encoded %s returned from %s"
)
// Client defines the methods needed to satisfy the client expected when
// instantiating a Watcher instance.
type Client interface {
HeaderByNumber(number *big.Int) (*types.MiniHeader, error)
HeaderByHash(hash common.Hash) (*types.MiniHeader, error)
FilterLogs(q ethereum.FilterQuery) ([]ethtypes.Log, error)
}
// Ensure that RpcClient is compliant with the Client interface.
var _ Client = &RpcClient{}
// RpcClient is a Client for fetching Ethereum blocks from a specific JSON-RPC endpoint.
type RpcClient struct {
ctx context.Context
ethRPCClient ethrpcclient.Client
}
// NewRpcClient returns a new Client for fetching Ethereum blocks using the given
// ethclient.Client.
func NewRpcClient(ctx context.Context, ethRPCClient ethrpcclient.Client) *RpcClient {
return &RpcClient{
ctx: ctx,
ethRPCClient: ethRPCClient,
}
}
type GetBlockByNumberResponse struct {
Hash common.Hash `json:"hash"`
ParentHash common.Hash `json:"parentHash"`
Number string `json:"number"`
Timestamp string `json:"timestamp"`
}
// UnknownBlockNumberError is the error returned from a filter logs RPC call when the block number
// specified is not recognized.
type UnknownBlockNumberError struct {
Message string
BlockNumber *big.Int
}
func (e UnknownBlockNumberError) Error() string {
return fmt.Sprintf("%s: %s", e.Message, e.BlockNumber)
}
// HeaderByNumber fetches a block header by its number. If no `number` is supplied,
// it will return the latest block header. If no block exists with this number it
// will return a `ethereum.NotFound` error.
func (rc *RpcClient) HeaderByNumber(number *big.Int) (*types.MiniHeader, error) {
var blockParam string
if number == nil {
blockParam = "latest"
} else {
blockParam = hexutil.EncodeBig(number)
}
shouldIncludeTransactions := false
// Note(fabio): We use a raw RPC call here instead of `EthClient`'s
// `BlockByNumber()` method because block hashes are computed differently
// on Kovan vs. mainnet, resulting in the wrong block hash being returned
// by `BlockByNumber` when using Kovan. By doing a raw RPC call, we can
// simply use the blockHash returned in the RPC response rather than
// re-compute it from the block header.
// Source: https://github.com/ethereum/go-ethereum/pull/18166
var header GetBlockByNumberResponse
ctx, cancel := context.WithTimeout(rc.ctx, requestTimeout)
defer cancel()
err := rc.ethRPCClient.CallContext(ctx, &header, "eth_getBlockByNumber", blockParam, shouldIncludeTransactions)
if err != nil {
return nil, err
}
// If it returned an empty struct
if header.Number == "" {
// Add block number to error so it gets logged
return nil, UnknownBlockNumberError{
Message: ethereum.NotFound.Error(),
BlockNumber: number,
}
}
blockNum, ok := math.ParseBig256(header.Number)
if !ok {
return nil, fmt.Errorf(bigIntParsingErrorString, "block timestamp", "eth_getBlockByNumber")
}
blockTimestamp, ok := math.ParseBig256(header.Timestamp)
if !ok {
return nil, fmt.Errorf(bigIntParsingErrorString, "block timestamp", "eth_getBlockByNumber")
}
miniHeader := &types.MiniHeader{
Hash: header.Hash,
Parent: header.ParentHash,
Number: blockNum,
Timestamp: time.Unix(blockTimestamp.Int64(), 0),
}
return miniHeader, nil
}
// UnknownBlockHashError is the error returned from a filter logs RPC call when
// the blockHash specified is not recognized.
type UnknownBlockHashError struct {
BlockHash common.Hash
}
func (e UnknownBlockHashError) Error() string {
return fmt.Sprintf("%s: %s", ethereum.NotFound.Error(), e.BlockHash)
}
// HeaderByHash fetches a block header by its block hash. If no block exists with
// this hash it will return a `ethereum.NotFound` error.
func (rc *RpcClient) HeaderByHash(hash common.Hash) (*types.MiniHeader, error) {
ctx, cancel := context.WithTimeout(rc.ctx, requestTimeout)
defer cancel()
header, err := rc.ethRPCClient.HeaderByHash(ctx, hash)
if err != nil {
// Add blockHash to error so it gets logged
if err.Error() == ethereum.NotFound.Error() {
err = UnknownBlockHashError{
BlockHash: hash,
}
}
return nil, err
}
miniHeader := &types.MiniHeader{
Hash: header.Hash(),
Parent: header.ParentHash,
Number: header.Number,
Timestamp: time.Unix(int64(header.Time), 0),
}
return miniHeader, nil
}
// FilterUnknownBlockError is the error returned from a filter logs RPC call when
// the blockHash specified is not recognized.
type FilterUnknownBlockError struct {
Message string
FilterQuery ethereum.FilterQuery
}
func (e FilterUnknownBlockError) Error() string {
return fmt.Sprintf("%s: %+v", e.Message, e.FilterQuery)
}
// FilterLogs returns the logs that satisfy the supplied filter query.
func (rc *RpcClient) FilterLogs(q ethereum.FilterQuery) ([]ethtypes.Log, error) {
ctx, cancel := context.WithTimeout(rc.ctx, requestTimeout)
defer cancel()
logs, err := rc.ethRPCClient.FilterLogs(ctx, q)
if err != nil {
// Add the query filter to the error so that it gets logged
if err.Error() == constants.ParityFilterUnknownBlock || err.Error() == constants.GethFilterUnknownBlock {
err = FilterUnknownBlockError{
Message: err.Error(),
FilterQuery: q,
}
}
return nil, err
}
return logs, nil
}