/
hashfetcher.go
275 lines (209 loc) · 6.62 KB
/
hashfetcher.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
package syncer
import (
"sync"
"time"
"github.com/aergoio/aergo/v2/internal/enc/base58"
"github.com/aergoio/aergo/v2/pkg/component"
"github.com/aergoio/aergo/v2/types"
"github.com/aergoio/aergo/v2/types/message"
"github.com/pkg/errors"
)
type HashFetcher struct {
compRequester component.IComponentRequester //for communicate with other service
ctx *types.SyncContext
responseCh chan *message.GetHashesRsp //HashSet response channel (<- Syncer)
resultCh chan *HashSet //BlockFetcher input channel (-> BlockFetcher)
//HashFetcher can wait in resultCh
quitCh chan interface{}
lastBlockInfo *types.BlockInfo
reqCount uint64
reqTime time.Time
isRequesting bool
maxHashReq uint64
name string
timeout time.Duration
debug bool
isRunning bool
waitGroup *sync.WaitGroup
}
type HashSet struct {
Count int
Hashes []message.BlockHash
StartNo types.BlockNo
}
type HashRequest struct {
prevInfo *types.BlockInfo
count uint64
}
var (
dfltTimeout = time.Second * 180
DfltHashReqSize = uint64(1000)
)
var (
ErrQuitHashFetcher = errors.New("Hashfetcher quit")
ErrInvalidHashSet = errors.New("Invalid hash set reply")
ErrHashFetcherTimeout = errors.New("HashFetcher response timeout")
)
func newHashFetcher(ctx *types.SyncContext, compRequester component.IComponentRequester, bfCh chan *HashSet, cfg *SyncerConfig) *HashFetcher {
hf := &HashFetcher{ctx: ctx, compRequester: compRequester, name: NameHashFetcher}
hf.quitCh = make(chan interface{})
hf.responseCh = make(chan *message.GetHashesRsp)
hf.resultCh = bfCh
hf.lastBlockInfo = &types.BlockInfo{Hash: ctx.CommonAncestor.GetHash(), No: ctx.CommonAncestor.BlockNo()}
hf.maxHashReq = cfg.maxHashReqSize
hf.timeout = dfltTimeout
return hf
}
func (hf *HashFetcher) setTimeout(timeout time.Duration) {
hf.timeout = timeout
}
func (hf *HashFetcher) recover() {
}
func (hf *HashFetcher) Start() {
hf.waitGroup = &sync.WaitGroup{}
hf.waitGroup.Add(1)
hf.isRunning = true
run := func() {
defer RecoverSyncer(NameHashFetcher, hf.GetSeq(), hf.compRequester, func() { hf.waitGroup.Done() })
logger.Debug().Msg("start hash fetcher")
timer := time.NewTimer(hf.timeout)
hf.requestHashSet()
for {
select {
case msg, ok := <-hf.responseCh:
if !ok {
logger.Error().Msg("HashFetcher responseCh is closed. Syncer is stopping now")
return
}
logger.Debug().Msg("process GetHashesRsp")
timer.Stop()
res, err := hf.isValidResponse(msg)
if res {
HashSet := &HashSet{Count: len(msg.Hashes), Hashes: msg.Hashes, StartNo: msg.PrevInfo.No + 1}
if err := hf.processHashSet(HashSet); err != nil {
//TODO send errmsg to syncer & stop sync
logger.Error().Err(err).Msg("error! process hash chunk, HashFetcher exited")
if err != ErrQuitHashFetcher {
stopSyncer(hf.compRequester, hf.GetSeq(), hf.name, err)
}
return
}
if hf.isFinished(HashSet) {
closeFetcher(hf.compRequester, hf.GetSeq(), hf.name)
logger.Info().Msg("HashFetcher finished")
return
}
hf.requestHashSet()
} else if err != nil {
stopSyncer(hf.compRequester, hf.GetSeq(), hf.name, err)
}
//timer restart
timer.Reset(hf.timeout)
case <-timer.C:
if hf.requestTimeout() {
logger.Error().Msg("HashFetcher response timeout.")
stopSyncer(hf.compRequester, hf.GetSeq(), hf.name, ErrHashFetcherTimeout)
}
case <-hf.quitCh:
logger.Info().Msg("HashFetcher exited")
return
}
}
}
go run()
}
func (hf *HashFetcher) GetSeq() uint64 {
return hf.ctx.Seq
}
func (hf *HashFetcher) isFinished(HashSet *HashSet) bool {
return (hf.lastBlockInfo.No == hf.ctx.TargetNo)
}
func (hf *HashFetcher) requestTimeout() bool {
return hf.isRequesting && time.Now().Sub(hf.reqTime) > hf.timeout
}
func (hf *HashFetcher) requestHashSet() {
count := hf.maxHashReq
if hf.ctx.TargetNo < hf.lastBlockInfo.No+hf.maxHashReq {
count = hf.ctx.TargetNo - hf.lastBlockInfo.No
}
hf.reqCount = count
hf.reqTime = time.Now()
hf.isRequesting = true
logger.Debug().Uint64("prev", hf.lastBlockInfo.No).Str("prevhash", base58.Encode(hf.lastBlockInfo.Hash)).Uint64("count", count).Msg("request hashset to peer")
hf.compRequester.TellTo(message.P2PSvc, &message.GetHashes{Seq: hf.GetSeq(), ToWhom: hf.ctx.PeerID, PrevInfo: hf.lastBlockInfo, Count: count})
}
func (hf *HashFetcher) processHashSet(hashSet *HashSet) error {
//get HashSet reply
lastHash := hashSet.Hashes[len(hashSet.Hashes)-1]
lastHashNo := hashSet.StartNo + uint64(hashSet.Count) - 1
if lastHashNo > hf.ctx.TargetNo {
logger.Error().Uint64("target", hf.ctx.TargetNo).Uint64("last", lastHashNo).Msg("invalid hashset reponse")
return ErrInvalidHashSet
}
hf.lastBlockInfo = &types.BlockInfo{Hash: lastHash, No: lastHashNo}
//total HashSet in memory can be 3 (network + resultCh + blockFetcher)
select {
case hf.resultCh <- hashSet:
case <-hf.quitCh:
logger.Info().Msg("hash fetcher quit while pushing result")
return ErrQuitHashFetcher
}
hf.isRequesting = false
logger.Debug().Uint64("target", hf.ctx.TargetNo).Uint64("start", hashSet.StartNo).Uint64("last", lastHashNo).Int("count", len(hashSet.Hashes)).Msg("push hashset to BlockFetcher")
return nil
}
func (hf *HashFetcher) stop() {
if hf == nil {
return
}
if hf.isRunning {
logger.Info().Msg("HashFetcher stop#1")
close(hf.quitCh)
logger.Info().Msg("HashFetcher close quitCh")
close(hf.responseCh)
hf.waitGroup.Wait()
hf.isRunning = false
}
logger.Info().Msg("HashFetcher stopped")
}
func (hf *HashFetcher) isValidResponse(msg *message.GetHashesRsp) (bool, error) {
isValid := true
var err error
if msg == nil {
panic("nil message error")
}
if msg.Err != nil {
logger.Error().Err(msg.Err).Msg("receive GetHashesRsp with error")
err = msg.Err
isValid = false
}
if !hf.lastBlockInfo.Equal(msg.PrevInfo) || hf.reqCount != msg.Count {
isValid = false
}
if !isValid {
logger.Error().Str("req prev", base58.Encode(hf.lastBlockInfo.Hash)).
Str("msg prev", base58.Encode(msg.PrevInfo.Hash)).
Uint64("req count", hf.reqCount).
Uint64("msg count", msg.Count).
Msg("invalid GetHashesRsp")
return false, err
}
return true, nil
}
func (hf *HashFetcher) GetHahsesRsp(msg *message.GetHashesRsp) {
if hf == nil {
return
}
count := len(msg.Hashes)
if count == 0 {
logger.Error().Int("count", count).
Uint64("prev", msg.PrevInfo.No).Msg("receive empty GetHashesRsp")
return
}
logger.Debug().Int("count", count).
Uint64("prev", msg.PrevInfo.No).
Str("start", base58.Encode(msg.Hashes[0])).
Str("end", base58.Encode(msg.Hashes[count-1])).Msg("receive GetHashesRsp")
hf.responseCh <- msg
return
}