-
Notifications
You must be signed in to change notification settings - Fork 199
/
shardblock.go
364 lines (304 loc) · 11.6 KB
/
shardblock.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
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
package sync
import (
"context"
"math"
"strings"
"github.com/ElrondNetwork/elrond-go-core/core"
"github.com/ElrondNetwork/elrond-go-core/core/check"
"github.com/ElrondNetwork/elrond-go-core/data"
"github.com/ElrondNetwork/elrond-go-core/data/block"
"github.com/ElrondNetwork/elrond-go/common"
"github.com/ElrondNetwork/elrond-go/dataRetriever"
"github.com/ElrondNetwork/elrond-go/errors"
"github.com/ElrondNetwork/elrond-go/process"
"github.com/ElrondNetwork/elrond-go/storage"
)
// ShardBootstrap implements the bootstrap mechanism
type ShardBootstrap struct {
*baseBootstrap
}
// NewShardBootstrap creates a new Bootstrap object
func NewShardBootstrap(arguments ArgShardBootstrapper) (*ShardBootstrap, error) {
if check.IfNil(arguments.PoolsHolder) {
return nil, process.ErrNilPoolsHolder
}
if check.IfNil(arguments.PoolsHolder.Headers()) {
return nil, process.ErrNilHeadersDataPool
}
if check.IfNil(arguments.PoolsHolder.MiniBlocks()) {
return nil, process.ErrNilTxBlockBody
}
err := checkBaseBootstrapParameters(arguments.ArgBaseBootstrapper)
if err != nil {
return nil, err
}
base := &baseBootstrap{
chainHandler: arguments.ChainHandler,
blockProcessor: arguments.BlockProcessor,
store: arguments.Store,
headers: arguments.PoolsHolder.Headers(),
roundHandler: arguments.RoundHandler,
waitTime: arguments.WaitTime,
hasher: arguments.Hasher,
marshalizer: arguments.Marshalizer,
forkDetector: arguments.ForkDetector,
requestHandler: arguments.RequestHandler,
shardCoordinator: arguments.ShardCoordinator,
accounts: arguments.Accounts,
blackListHandler: arguments.BlackListHandler,
networkWatcher: arguments.NetworkWatcher,
bootStorer: arguments.BootStorer,
storageBootstrapper: arguments.StorageBootstrapper,
epochHandler: arguments.EpochHandler,
miniBlocksProvider: arguments.MiniblocksProvider,
uint64Converter: arguments.Uint64Converter,
poolsHolder: arguments.PoolsHolder,
statusHandler: arguments.AppStatusHandler,
outportHandler: arguments.OutportHandler,
accountsDBSyncer: arguments.AccountsDBSyncer,
currentEpochProvider: arguments.CurrentEpochProvider,
isInImportMode: arguments.IsInImportMode,
historyRepo: arguments.HistoryRepo,
scheduledTxsExecutionHandler: arguments.ScheduledTxsExecutionHandler,
processWaitTime: arguments.ProcessWaitTime,
}
if base.isInImportMode {
log.Warn("using always-not-synced status because the node is running in import-db")
}
boot := ShardBootstrap{
baseBootstrap: base,
}
base.blockBootstrapper = &boot
base.syncStarter = &boot
base.getHeaderFromPool = boot.getShardHeaderFromPool
base.requestMiniBlocks = boot.requestMiniBlocksFromHeaderWithNonceIfMissing
// placed in struct fields for performance reasons
base.headerStore, err = boot.store.GetStorer(dataRetriever.BlockHeaderUnit)
if err != nil {
return nil, err
}
hdrNonceHashDataUnit := dataRetriever.ShardHdrNonceHashDataUnit + dataRetriever.UnitType(boot.shardCoordinator.SelfId())
base.headerNonceHashStore, err = boot.store.GetStorer(hdrNonceHashDataUnit)
if err != nil {
return nil, err
}
base.init()
return &boot, nil
}
func (boot *ShardBootstrap) getBlockBody(headerHandler data.HeaderHandler) (data.BodyHandler, error) {
header, ok := headerHandler.(data.ShardHeaderHandler)
if !ok {
return nil, process.ErrWrongTypeAssertion
}
hashes := make([][]byte, len(header.GetMiniBlockHeaderHandlers()))
for i := 0; i < len(header.GetMiniBlockHeaderHandlers()); i++ {
hashes[i] = header.GetMiniBlockHeaderHandlers()[i].GetHash()
}
miniBlocksAndHashes, missingMiniBlocksHashes := boot.miniBlocksProvider.GetMiniBlocks(hashes)
if len(missingMiniBlocksHashes) > 0 {
return nil, process.ErrMissingBody
}
miniBlocks := make([]*block.MiniBlock, len(miniBlocksAndHashes))
for index, miniBlockAndHash := range miniBlocksAndHashes {
miniBlocks[index] = miniBlockAndHash.Miniblock
}
return &block.Body{MiniBlocks: miniBlocks}, nil
}
// StartSyncingBlocks method will start syncing blocks as a go routine
func (boot *ShardBootstrap) StartSyncingBlocks() {
errNotCritical := boot.storageBootstrapper.LoadFromStorage()
if errNotCritical != nil {
log.Debug("boot.syncFromStorer",
"error", errNotCritical.Error(),
)
}
var ctx context.Context
ctx, boot.cancelFunc = context.WithCancel(context.Background())
go boot.syncBlocks(ctx)
}
// SyncBlock method actually does the synchronization. It requests the next block header from the pool
// and if it is not found there it will be requested from the network. After the header is received,
// it requests the block body in the same way(pool and then, if it is not found in the pool, from network).
// If either header and body are received the ProcessBlock and CommitBlock method will be called successively.
// These methods will execute the block and its transactions. Finally, if everything works, the block will be committed
// in the blockchain, and all this mechanism will be reiterated for the next block.
func (boot *ShardBootstrap) SyncBlock(ctx context.Context) error {
err := boot.syncBlock()
if isErrGetNodeFromDB(err) {
errSync := boot.syncUserAccountsState()
boot.handleTrieSyncError(errSync, ctx)
}
return err
}
func isErrGetNodeFromDB(err error) bool {
if err == nil {
return false
}
if strings.Contains(err.Error(), storage.ErrDBIsClosed.Error()) {
return false
}
if strings.Contains(err.Error(), errors.ErrContextClosing.Error()) {
return false
}
if strings.Contains(err.Error(), common.GetNodeFromDBErrorString) {
return true
}
return false
}
// Close closes the synchronization loop
func (boot *ShardBootstrap) Close() error {
if check.IfNil(boot.baseBootstrap) {
return nil
}
return boot.baseBootstrap.Close()
}
// requestHeaderWithNonce method requests a block header from network when it is not found in the pool
func (boot *ShardBootstrap) requestHeaderWithNonce(nonce uint64) {
boot.setRequestedHeaderNonce(&nonce)
log.Debug("requesting shard header from network",
"nonce", nonce,
"probable highest nonce", boot.forkDetector.ProbableHighestNonce(),
)
boot.requestHandler.RequestShardHeaderByNonce(boot.shardCoordinator.SelfId(), nonce)
}
// requestHeaderWithHash method requests a block header from network when it is not found in the pool
func (boot *ShardBootstrap) requestHeaderWithHash(hash []byte) {
boot.setRequestedHeaderHash(hash)
log.Debug("requesting shard header from network",
"hash", hash,
"probable highest nonce", boot.forkDetector.ProbableHighestNonce(),
)
boot.requestHandler.RequestShardHeader(boot.shardCoordinator.SelfId(), hash)
}
// getHeaderWithNonceRequestingIfMissing method gets the header with a given nonce from pool. If it is not found there, it will
// be requested from network
func (boot *ShardBootstrap) getHeaderWithNonceRequestingIfMissing(nonce uint64) (data.HeaderHandler, error) {
hdr, _, err := process.GetShardHeaderFromPoolWithNonce(
nonce,
boot.shardCoordinator.SelfId(),
boot.headers)
if err != nil {
_ = core.EmptyChannel(boot.chRcvHdrNonce)
boot.requestHeaderWithNonce(nonce)
err = boot.waitForHeaderNonce()
if err != nil {
return nil, err
}
hdr, _, err = process.GetShardHeaderFromPoolWithNonce(
nonce,
boot.shardCoordinator.SelfId(),
boot.headers)
if err != nil {
return nil, err
}
}
return hdr, nil
}
// getHeaderWithHashRequestingIfMissing method gets the header with a given hash from pool. If it is not found there,
// it will be requested from network
func (boot *ShardBootstrap) getHeaderWithHashRequestingIfMissing(hash []byte) (data.HeaderHandler, error) {
hdr, err := process.GetShardHeader(hash, boot.headers, boot.marshalizer, boot.store)
if err != nil {
_ = core.EmptyChannel(boot.chRcvHdrHash)
boot.requestHeaderWithHash(hash)
err = boot.waitForHeaderHash()
if err != nil {
return nil, err
}
hdr, err = process.GetShardHeaderFromPool(hash, boot.headers)
if err != nil {
return nil, err
}
}
return hdr, nil
}
func (boot *ShardBootstrap) getPrevHeader(
header data.HeaderHandler,
headerStore storage.Storer,
) (data.HeaderHandler, error) {
prevHash := header.GetPrevHash()
buffHeader, err := headerStore.Get(prevHash)
if err != nil {
return nil, err
}
prevHeader, err := process.UnmarshalShardHeader(boot.marshalizer, buffHeader)
if err != nil {
return nil, err
}
return prevHeader, nil
}
func (boot *ShardBootstrap) getCurrHeader() (data.HeaderHandler, error) {
blockHeader := boot.chainHandler.GetCurrentBlockHeader()
if check.IfNil(blockHeader) {
return nil, process.ErrNilBlockHeader
}
header, ok := blockHeader.(data.ShardHeaderHandler)
if !ok {
return nil, process.ErrWrongTypeAssertion
}
return header, nil
}
func (boot *ShardBootstrap) haveHeaderInPoolWithNonce(nonce uint64) bool {
_, _, err := process.GetShardHeaderFromPoolWithNonce(
nonce,
boot.shardCoordinator.SelfId(),
boot.headers)
return err == nil
}
func (boot *ShardBootstrap) getShardHeaderFromPool(headerHash []byte) (data.HeaderHandler, error) {
return process.GetShardHeaderFromPool(headerHash, boot.headers)
}
func (boot *ShardBootstrap) requestMiniBlocksFromHeaderWithNonceIfMissing(headerHandler data.HeaderHandler) {
nextBlockNonce := boot.getNonceForNextBlock()
maxNonce := core.MinUint64(nextBlockNonce+process.MaxHeadersToRequestInAdvance-1, boot.forkDetector.ProbableHighestNonce())
if headerHandler.GetNonce() < nextBlockNonce || headerHandler.GetNonce() > maxNonce {
return
}
header, ok := headerHandler.(data.ShardHeaderHandler)
if !ok {
log.Warn("cannot convert headerHandler in block.Header")
return
}
hashes := make([][]byte, 0, len(header.GetMiniBlockHeaderHandlers()))
for i := 0; i < len(header.GetMiniBlockHeaderHandlers()); i++ {
hashes = append(hashes, header.GetMiniBlockHeaderHandlers()[i].GetHash())
}
_, missingMiniBlocksHashes := boot.miniBlocksProvider.GetMiniBlocksFromPool(hashes)
if len(missingMiniBlocksHashes) > 0 {
log.Trace("requesting in advance mini blocks",
"num miniblocks", len(missingMiniBlocksHashes),
"header nonce", header.GetNonce(),
)
boot.requestHandler.RequestMiniBlocks(boot.shardCoordinator.SelfId(), missingMiniBlocksHashes)
}
}
func (boot *ShardBootstrap) getBlockBodyRequestingIfMissing(headerHandler data.HeaderHandler) (data.BodyHandler, error) {
header, ok := headerHandler.(data.ShardHeaderHandler)
if !ok {
return nil, process.ErrWrongTypeAssertion
}
hashes := make([][]byte, len(header.GetMiniBlockHeaderHandlers()))
for i := 0; i < len(header.GetMiniBlockHeaderHandlers()); i++ {
hashes[i] = header.GetMiniBlockHeaderHandlers()[i].GetHash()
}
boot.setRequestedMiniBlocks(nil)
miniBlockSlice, err := boot.getMiniBlocksRequestingIfMissing(hashes)
if err != nil {
return nil, err
}
blockBody := &block.Body{MiniBlocks: miniBlockSlice}
return blockBody, nil
}
func (boot *ShardBootstrap) isForkTriggeredByMeta() bool {
return boot.forkInfo.IsDetected &&
boot.forkInfo.Nonce != math.MaxUint64 &&
boot.forkInfo.Round == process.MinForkRound &&
boot.forkInfo.Hash != nil
}
func (boot *ShardBootstrap) requestHeaderByNonce(nonce uint64) {
boot.requestHandler.RequestShardHeaderByNonce(boot.shardCoordinator.SelfId(), nonce)
}
// IsInterfaceNil returns true if there is no value under the interface
func (boot *ShardBootstrap) IsInterfaceNil() bool {
return boot == nil
}