-
Notifications
You must be signed in to change notification settings - Fork 648
/
client.go
236 lines (204 loc) · 7.88 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
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
// Copyright (C) 2019-2023, Ava Labs, Inc. All rights reserved.
// See the file LICENSE for licensing terms.
package sync
import (
"context"
"errors"
"fmt"
"sync/atomic"
"time"
"go.uber.org/zap"
"google.golang.org/protobuf/proto"
"github.com/ava-labs/avalanchego/ids"
"github.com/ava-labs/avalanchego/utils/logging"
"github.com/ava-labs/avalanchego/version"
"github.com/ava-labs/avalanchego/x/merkledb"
syncpb "github.com/ava-labs/avalanchego/proto/pb/sync"
)
const (
failedRequestSleepInterval = 10 * time.Millisecond
epsilon = 1e-6 // small amount to add to time to avoid division by 0
)
var (
_ Client = (*client)(nil)
errInvalidRangeProof = errors.New("failed to verify range proof")
errTooManyKeys = errors.New("response contains more than requested keys")
errTooManyBytes = errors.New("response contains more than requested bytes")
)
// Client synchronously fetches data from the network to fulfill state sync requests.
// Repeatedly retries failed requests until the context is canceled.
type Client interface {
// GetRangeProof synchronously sends the given request, returning a parsed StateResponse or error
// Note: this verifies the response including the range proof.
GetRangeProof(ctx context.Context, request *syncpb.RangeProofRequest) (*merkledb.RangeProof, error)
// GetChangeProof synchronously sends the given request, returning a parsed ChangesResponse or error
// [verificationDB] is the local db that has all key/values in it for the proof's startroot within the proof's key range
// Note: this verifies the response including the change proof.
GetChangeProof(ctx context.Context, request *syncpb.ChangeProofRequest, verificationDB *merkledb.Database) (*merkledb.ChangeProof, error)
}
type client struct {
networkClient NetworkClient
stateSyncNodes []ids.NodeID
stateSyncNodeIdx uint32
stateSyncMinVersion *version.Application
log logging.Logger
metrics SyncMetrics
}
type ClientConfig struct {
NetworkClient NetworkClient
StateSyncNodeIDs []ids.NodeID
StateSyncMinVersion *version.Application
Log logging.Logger
Metrics SyncMetrics
}
func NewClient(config *ClientConfig) Client {
c := &client{
networkClient: config.NetworkClient,
stateSyncNodes: config.StateSyncNodeIDs,
stateSyncMinVersion: config.StateSyncMinVersion,
log: config.Log,
metrics: config.Metrics,
}
return c
}
// GetChangeProof synchronously retrieves the change proof given by [req].
// Upon failure, retries until the context is expired.
// The returned change proof is verified.
func (c *client) GetChangeProof(ctx context.Context, req *syncpb.ChangeProofRequest, db *merkledb.Database) (*merkledb.ChangeProof, error) {
parseFn := func(ctx context.Context, responseBytes []byte) (*merkledb.ChangeProof, error) {
if len(responseBytes) > int(req.BytesLimit) {
return nil, fmt.Errorf("%w: (%d) > %d)", errTooManyBytes, len(responseBytes), req.BytesLimit)
}
changeProof := &merkledb.ChangeProof{}
if _, err := merkledb.Codec.DecodeChangeProof(responseBytes, changeProof); err != nil {
return nil, err
}
// Ensure the response does not contain more than the requested number of leaves
// and the start and end roots match the requested roots.
if len(changeProof.KeyChanges) > int(req.KeyLimit) {
return nil, fmt.Errorf("%w: (%d) > %d)", errTooManyKeys, len(changeProof.KeyChanges), req.KeyLimit)
}
endRoot, err := ids.ToID(req.EndRoot)
if err != nil {
return nil, err
}
if err := changeProof.Verify(ctx, db, req.Start, req.End, endRoot); err != nil {
return nil, fmt.Errorf("%s due to %w", errInvalidRangeProof, err)
}
return changeProof, nil
}
reqBytes, err := proto.Marshal(&syncpb.Request{
Message: &syncpb.Request_ChangeProofRequest{
ChangeProofRequest: req,
},
})
if err != nil {
return nil, err
}
return getAndParse(ctx, c, reqBytes, parseFn)
}
// GetRangeProof synchronously retrieves the range proof given by [req].
// Upon failure, retries until the context is expired.
// The returned range proof is verified.
func (c *client) GetRangeProof(ctx context.Context, req *syncpb.RangeProofRequest) (*merkledb.RangeProof, error) {
parseFn := func(ctx context.Context, responseBytes []byte) (*merkledb.RangeProof, error) {
if len(responseBytes) > int(req.BytesLimit) {
return nil, fmt.Errorf("%w: (%d) > %d)", errTooManyBytes, len(responseBytes), req.BytesLimit)
}
rangeProof := &merkledb.RangeProof{}
if _, err := merkledb.Codec.DecodeRangeProof(responseBytes, rangeProof); err != nil {
return nil, err
}
// Ensure the response does not contain more than the maximum requested number of leaves.
if len(rangeProof.KeyValues) > int(req.KeyLimit) {
return nil, fmt.Errorf("%w: (%d) > %d)", errTooManyKeys, len(rangeProof.KeyValues), req.KeyLimit)
}
root, err := ids.ToID(req.Root)
if err != nil {
return nil, err
}
if err := rangeProof.Verify(
ctx,
req.Start,
req.End,
root,
); err != nil {
return nil, fmt.Errorf("%s due to %w", errInvalidRangeProof, err)
}
return rangeProof, nil
}
reqBytes, err := proto.Marshal(&syncpb.Request{
Message: &syncpb.Request_RangeProofRequest{
RangeProofRequest: req,
},
})
if err != nil {
return nil, err
}
return getAndParse(ctx, c, reqBytes, parseFn)
}
// getAndParse uses [client] to send [request] to an arbitrary peer. If the peer responds,
// [parseFn] is called with the raw response. If [parseFn] returns an error or the request
// times out, this function will retry the request to a different peer until [ctx] expires.
// If [parseFn] returns a nil error, the result is returned from getAndParse.
func getAndParse[T any](ctx context.Context, client *client, request []byte, parseFn func(context.Context, []byte) (*T, error)) (*T, error) {
var (
lastErr error
response *T
)
// Loop until the context is cancelled or we get a valid response.
for attempt := 0; ; attempt++ {
// If the context has finished, return the context error early.
if err := ctx.Err(); err != nil {
if lastErr != nil {
return nil, fmt.Errorf("request failed after %d attempts with last error %w and ctx error %s", attempt, lastErr, err)
}
return nil, err
}
responseBytes, nodeID, err := client.get(ctx, request)
if err == nil {
if response, err = parseFn(ctx, responseBytes); err == nil {
return response, nil
}
}
client.log.Debug("request failed, retrying",
zap.Stringer("nodeID", nodeID),
zap.Int("attempt", attempt),
zap.Error(err))
if err != ctx.Err() {
// if [err] is being propagated from [ctx], avoid overwriting [lastErr].
lastErr = err
time.Sleep(failedRequestSleepInterval)
}
}
}
// get sends [request] to an arbitrary peer and blocks until the node receives a response
// or [ctx] expires. Returns the raw response from the peer, the peer's NodeID, and an
// error if the request timed out. Thread safe.
func (c *client) get(ctx context.Context, requestBytes []byte) ([]byte, ids.NodeID, error) {
c.metrics.RequestMade()
var (
response []byte
nodeID ids.NodeID
err error
startTime = time.Now()
)
if len(c.stateSyncNodes) == 0 {
response, nodeID, err = c.networkClient.RequestAny(ctx, c.stateSyncMinVersion, requestBytes)
} else {
// get the next nodeID using the nodeIdx offset. If we're out of nodes, loop back to 0
// we do this every attempt to ensure we get a different node each time if possible.
nodeIdx := atomic.AddUint32(&c.stateSyncNodeIdx, 1)
nodeID = c.stateSyncNodes[nodeIdx%uint32(len(c.stateSyncNodes))]
response, err = c.networkClient.Request(ctx, nodeID, requestBytes)
}
if err != nil {
c.metrics.RequestFailed()
c.networkClient.TrackBandwidth(nodeID, 0)
return response, nodeID, err
}
bandwidth := float64(len(response)) / (time.Since(startTime).Seconds() + epsilon)
c.networkClient.TrackBandwidth(nodeID, bandwidth)
c.metrics.RequestSucceeded()
return response, nodeID, nil
}