-
Notifications
You must be signed in to change notification settings - Fork 15
/
shard_tracker.go
240 lines (221 loc) · 6.58 KB
/
shard_tracker.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
package blockchain
import (
"context"
"github.com/gobicycle/bicycle/core"
log "github.com/sirupsen/logrus"
"github.com/xssnick/tonutils-go/tlb"
"github.com/xssnick/tonutils-go/ton"
"math/bits"
"strings"
"time"
)
const ErrBlockNotApplied = "block is not applied"
type ShardTracker struct {
connection *Connection
shard byte
lastKnownShardBlock *ton.BlockIDExt
lastMasterBlock *ton.BlockIDExt
buffer []core.ShardBlockHeader
gracefulShutdown bool
infoCounter, infoStep int
infoLastTime time.Time
}
// NewShardTracker creates new tracker to get blocks with specific shard attribute
func NewShardTracker(shard byte, startBlock *ton.BlockIDExt, connection *Connection) *ShardTracker {
t := &ShardTracker{
connection: connection,
shard: shard,
lastKnownShardBlock: startBlock,
buffer: make([]core.ShardBlockHeader, 0),
infoCounter: 0,
infoStep: 1000,
infoLastTime: time.Now(),
}
return t
}
// NextBlock returns next block header and graceful shutdown flag.
// (ShardBlockHeader, false) for normal operation and (empty block header, true) for graceful shutdown.
func (s *ShardTracker) NextBlock() (core.ShardBlockHeader, bool, error) {
if s.gracefulShutdown {
return core.ShardBlockHeader{}, true, nil
}
h := s.getNext()
if h != nil {
return *h, false, nil
}
// the interval between blocks can be up to 40 seconds
ctx, cancel := context.WithTimeout(context.Background(), time.Second*60)
defer cancel()
masterBlockID, err := s.getNextMasterBlockID(ctx)
if err != nil {
return core.ShardBlockHeader{}, false, err
}
exit, err := s.loadShardBlocksBatch(masterBlockID)
if err != nil {
return core.ShardBlockHeader{}, false, err
}
if exit {
log.Printf("Shard tracker sync stopped")
return core.ShardBlockHeader{}, true, nil
}
return s.NextBlock()
}
// Stop initiates graceful shutdown
func (s *ShardTracker) Stop() {
s.gracefulShutdown = true
}
func (s *ShardTracker) getNext() *core.ShardBlockHeader {
if len(s.buffer) != 0 {
h := s.buffer[0]
s.buffer = s.buffer[1:]
return &h
}
return nil
}
func (s *ShardTracker) getNextMasterBlockID(ctx context.Context) (*ton.BlockIDExt, error) {
for {
masterBlockID, err := s.connection.client.GetMasterchainInfo(ctx)
if err != nil {
// exit by context timeout
return nil, err
}
if s.lastMasterBlock == nil {
s.lastMasterBlock = masterBlockID
return masterBlockID, nil
}
if masterBlockID.SeqNo == s.lastMasterBlock.SeqNo {
time.Sleep(time.Second)
continue
}
s.lastMasterBlock = masterBlockID
return masterBlockID, nil
}
}
func (s *ShardTracker) loadShardBlocksBatch(masterBlockID *ton.BlockIDExt) (bool, error) {
var (
shards []*ton.BlockIDExt
err error
)
ctx, cancel := context.WithTimeout(context.Background(), time.Second*20)
defer cancel()
for {
shards, err = s.connection.client.GetBlockShardsInfo(ctx, masterBlockID)
if err != nil && isNotReadyError(err) { // TODO: clarify error type
time.Sleep(time.Second)
continue
} else if err != nil {
return false, err
// exit by context timeout
}
break
}
s.infoCounter = 0
batch, exit, err := s.getShardBlocksRecursively(filterByShard(shards, s.shard), nil)
if err != nil {
return false, err
}
if exit {
return true, nil
}
if len(batch) != 0 {
s.lastKnownShardBlock = batch[0].BlockIDExt
for i := len(batch) - 1; i >= 0; i-- {
s.buffer = append(s.buffer, batch[i])
}
}
return false, nil
}
func (s *ShardTracker) getShardBlocksRecursively(i *ton.BlockIDExt, batch []core.ShardBlockHeader) ([]core.ShardBlockHeader, bool, error) {
if s.gracefulShutdown {
return nil, true, nil
}
if s.lastKnownShardBlock == nil {
s.lastKnownShardBlock = i
}
isKnown := (s.lastKnownShardBlock.Shard == i.Shard) && (s.lastKnownShardBlock.SeqNo == i.SeqNo)
if isKnown {
return batch, false, nil
}
// compare seqno with filtered shard block
// handle the case when a node may reference an old block
if s.lastKnownShardBlock.SeqNo > i.SeqNo {
return []core.ShardBlockHeader{}, false, nil
}
seqnoDiff := int(i.SeqNo - s.lastKnownShardBlock.SeqNo)
if seqnoDiff > s.infoStep {
if s.infoCounter%s.infoStep == 0 {
estimatedTime := time.Duration(seqnoDiff/s.infoStep) * time.Since(s.infoLastTime)
s.infoLastTime = time.Now()
if s.infoCounter == 0 {
log.Printf("Shard tracker syncing... Seqno diff: %v Estimated time: unknown\n", seqnoDiff)
} else {
log.Printf("Shard tracker syncing... Seqno diff: %v Estimated time: %v\n", seqnoDiff, estimatedTime)
}
}
s.infoCounter++
}
ctx, cancel := context.WithTimeout(context.Background(), time.Second*20)
defer cancel()
h, err := s.connection.getShardBlocksHeader(ctx, i, s.shard)
if err != nil {
return nil, false, err
}
batch = append(batch, h)
return s.getShardBlocksRecursively(h.Parent, batch)
}
func isInShard(blockShardPrefix uint64, shard byte) bool {
if blockShardPrefix == 0 {
log.Fatalf("invalid shard_prefix")
}
prefixLen := 64 - 1 - bits.TrailingZeros64(blockShardPrefix) // without one insignificant bit
if prefixLen > 8 {
log.Fatalf("more than 256 shards is not supported")
}
res := (uint64(shard) << (64 - 8)) ^ blockShardPrefix
return bits.LeadingZeros64(res) >= prefixLen
}
func filterByShard(headers []*ton.BlockIDExt, shard byte) *ton.BlockIDExt {
for _, h := range headers {
if isInShard(uint64(h.Shard), shard) {
return h
}
}
log.Fatalf("must be at least one suitable shard block")
return nil
}
func convertBlockToShardHeader(block *tlb.Block, info *ton.BlockIDExt, shard byte) (core.ShardBlockHeader, error) {
parents, err := block.BlockInfo.GetParentBlocks()
if err != nil {
return core.ShardBlockHeader{}, err
}
parent := filterByShard(parents, shard)
return core.ShardBlockHeader{
NotMaster: block.BlockInfo.NotMaster,
GenUtime: block.BlockInfo.GenUtime,
StartLt: block.BlockInfo.StartLt,
EndLt: block.BlockInfo.EndLt,
Parent: parent,
BlockIDExt: info,
}, nil
}
// get shard block header for specific shard attribute with one parent
func (c *Connection) getShardBlocksHeader(ctx context.Context, shardBlockID *ton.BlockIDExt, shard byte) (core.ShardBlockHeader, error) {
var (
err error
block *tlb.Block
)
for {
block, err = c.client.GetBlockData(ctx, shardBlockID)
if err != nil && isNotReadyError(err) {
continue
} else if err != nil {
return core.ShardBlockHeader{}, err
// exit by context timeout
}
break
}
return convertBlockToShardHeader(block, shardBlockID, shard)
}
func isNotReadyError(err error) bool {
return strings.Contains(err.Error(), ErrBlockNotApplied)
}