forked from coinbase/mesh-sdk-go
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsyncer.go
324 lines (278 loc) · 7.36 KB
/
syncer.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
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
// Copyright 2020 Coinbase, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package syncer
import (
"context"
"errors"
"fmt"
"log"
"time"
"github.com/coinbase/rosetta-sdk-go/fetcher"
"github.com/coinbase/rosetta-sdk-go/types"
)
const (
// maxSync is the maximum number of blocks
// to try and sync in a given SyncCycle.
maxSync = 999
// PastBlockSize is the maximum number of previously
// processed blocks we keep in the syncer to handle
// reorgs correctly. If there is a reorg greater than
// PastBlockSize, it will not be handled correctly.
//
// TODO: make configurable
PastBlockSize = 20
)
var (
// defaultSyncSleep is the amount of time to sleep
// when we are at tip but want to keep syncing.
defaultSyncSleep = 5 * time.Second
)
// Handler is called at various times during the sync cycle
// to handle different events. It is common to write logs or
// perform reconciliation in the sync processor.
type Handler interface {
BlockAdded(
ctx context.Context,
block *types.Block,
) error
BlockRemoved(
ctx context.Context,
block *types.BlockIdentifier,
) error
}
// Syncer coordinates blockchain syncing without relying on
// a storage interface. Instead, it calls a provided Handler
// whenever a block is added or removed. This provides the client
// the opportunity to define the logic used to handle each new block.
// In the rosetta-cli, we handle reconciliation, state storage, and
// logging in the handler.
type Syncer struct {
network *types.NetworkIdentifier
fetcher *fetcher.Fetcher
handler Handler
cancel context.CancelFunc
// Used to keep track of sync state
genesisBlock *types.BlockIdentifier
nextIndex int64
// To ensure reorgs are handled correctly, the syncer must be able
// to observe blocks it has previously processed. Without this, the
// syncer may process an index that is not connected to previously added
// blocks (ParentBlockIdentifier != lastProcessedBlock.BlockIdentifier).
//
// If a blockchain does not have reorgs, it is not necessary to populate
// the blockCache on creation.
pastBlocks []*types.BlockIdentifier
}
// New creates a new Syncer. If pastBlocks is left nil, it will
// be set to an empty slice.
func New(
network *types.NetworkIdentifier,
fetcher *fetcher.Fetcher,
handler Handler,
cancel context.CancelFunc,
pastBlocks []*types.BlockIdentifier,
) *Syncer {
past := pastBlocks
if past == nil {
past = []*types.BlockIdentifier{}
}
return &Syncer{
network: network,
fetcher: fetcher,
handler: handler,
cancel: cancel,
pastBlocks: past,
}
}
func (s *Syncer) setStart(
ctx context.Context,
index int64,
) error {
networkStatus, err := s.fetcher.NetworkStatusRetry(
ctx,
s.network,
nil,
)
if err != nil {
return err
}
s.genesisBlock = networkStatus.GenesisBlockIdentifier
if index != -1 {
s.nextIndex = index
return nil
}
s.nextIndex = networkStatus.GenesisBlockIdentifier.Index
return nil
}
// nextSyncableRange returns the next range of indexes to sync
// based on what the last processed block in storage is and
// the contents of the network status response.
func (s *Syncer) nextSyncableRange(
ctx context.Context,
endIndex int64,
) (int64, bool, error) {
if s.nextIndex == -1 {
return -1, false, errors.New("unable to get current head")
}
// Always fetch network status to ensure endIndex is not
// past tip
networkStatus, err := s.fetcher.NetworkStatusRetry(
ctx,
s.network,
nil,
)
if err != nil {
return -1, false, fmt.Errorf("%w: unable to get network status", err)
}
if endIndex == -1 || endIndex > networkStatus.CurrentBlockIdentifier.Index {
endIndex = networkStatus.CurrentBlockIdentifier.Index
}
if s.nextIndex > endIndex {
return -1, true, nil
}
if endIndex-s.nextIndex > maxSync {
endIndex = s.nextIndex + maxSync
}
return endIndex, false, nil
}
func (s *Syncer) checkRemove(
block *types.Block,
) (bool, *types.BlockIdentifier, error) {
if len(s.pastBlocks) == 0 {
return false, nil, nil
}
// Ensure processing correct index
if block.BlockIdentifier.Index != s.nextIndex {
return false, nil, fmt.Errorf(
"Got block %d instead of %d",
block.BlockIdentifier.Index,
s.nextIndex,
)
}
// Check if block parent is head
lastBlock := s.pastBlocks[len(s.pastBlocks)-1]
if types.Hash(block.ParentBlockIdentifier) != types.Hash(lastBlock) {
if types.Hash(s.genesisBlock) == types.Hash(lastBlock) {
return false, nil, fmt.Errorf("cannot remove genesis block")
}
return true, lastBlock, nil
}
return false, lastBlock, nil
}
func (s *Syncer) processBlock(
ctx context.Context,
block *types.Block,
) error {
shouldRemove, lastBlock, err := s.checkRemove(block)
if err != nil {
return err
}
if shouldRemove {
err = s.handler.BlockRemoved(ctx, lastBlock)
if err != nil {
return err
}
s.pastBlocks = s.pastBlocks[:len(s.pastBlocks)-1]
s.nextIndex = lastBlock.Index
return nil
}
err = s.handler.BlockAdded(ctx, block)
if err != nil {
return err
}
s.pastBlocks = append(s.pastBlocks, block.BlockIdentifier)
if len(s.pastBlocks) > PastBlockSize {
s.pastBlocks = s.pastBlocks[1:]
}
s.nextIndex = block.BlockIdentifier.Index + 1
return nil
}
func (s *Syncer) syncRange(
ctx context.Context,
endIndex int64,
) error {
blockMap, err := s.fetcher.BlockRange(ctx, s.network, s.nextIndex, endIndex)
if err != nil {
return err
}
for s.nextIndex <= endIndex {
block, ok := blockMap[s.nextIndex]
if !ok { // could happen in a reorg
block, err = s.fetcher.BlockRetry(
ctx,
s.network,
&types.PartialBlockIdentifier{
Index: &s.nextIndex,
},
)
if err != nil {
return err
}
} else {
// Anytime we re-fetch an index, we
// will need to make another call to the node
// as it is likely in a reorg.
delete(blockMap, s.nextIndex)
}
if err = s.processBlock(ctx, block); err != nil {
return err
}
}
return nil
}
// Sync cycles endlessly until there is an error
// or the requested range is synced.
func (s *Syncer) Sync(
ctx context.Context,
startIndex int64,
endIndex int64,
) error {
defer s.cancel()
if err := s.setStart(ctx, startIndex); err != nil {
return fmt.Errorf("%w: unable to set start index", err)
}
for {
rangeEnd, halt, err := s.nextSyncableRange(
ctx,
endIndex,
)
if err != nil {
return fmt.Errorf("%w: unable to get next syncable range", err)
}
if halt {
if s.nextIndex > endIndex && endIndex != -1 {
break
}
time.Sleep(defaultSyncSleep)
continue
}
if s.nextIndex != rangeEnd {
log.Printf("Syncing %d-%d\n", s.nextIndex, rangeEnd)
} else {
log.Printf("Syncing %d\n", s.nextIndex)
}
err = s.syncRange(ctx, rangeEnd)
if err != nil {
return fmt.Errorf("%w: unable to sync to %d", err, rangeEnd)
}
if ctx.Err() != nil {
return ctx.Err()
}
}
if startIndex == -1 {
startIndex = s.genesisBlock.Index
}
log.Printf("Finished syncing %d-%d\n", startIndex, endIndex)
return nil
}