This repository has been archived by the owner on Oct 15, 2024. It is now read-only.
forked from everFinance/arsyncer
-
Notifications
You must be signed in to change notification settings - Fork 1
/
syncer.go
401 lines (344 loc) · 9 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
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
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
package arsyncer
import (
"fmt"
"sync"
"sync/atomic"
"time"
"github.com/everFinance/goar"
"github.com/everFinance/goar/types"
"github.com/everFinance/goar/utils"
"github.com/go-co-op/gocron"
"github.com/panjf2000/ants/v2"
)
var log = NewLog("syncer")
const (
SubscribeTypeTx = "subscribe_tx"
SubscribeTypeBlock = "subscribe_block"
SubscribeTypeBlockAndTx = "subscribe_block_and_tx"
)
type Syncer struct {
curHeight int64
FilterParams
blockChan chan *types.Block
blockTxsChan chan []SubscribeTx
SubscribeChan chan []SubscribeTx
arClient *goar.Client
nextSubscribeTxBlock int64
conNum int64 // concurrency of number
stableDistance int64 // stable block distance
blockIdxs *BlockIdxs
scheduler *gocron.Scheduler
peers []string
subscribeType string
SubscribeBlockChan chan *types.Block
}
func New(startHeight int64, filterParams FilterParams, arNode string, conNum int, stableDistance int64, subscribeType string) *Syncer {
if conNum <= 0 {
conNum = 10 // default concurrency of number is 10
}
if stableDistance <= 0 {
stableDistance = 15 // suggest stable block distance is 15
}
arCli := goar.NewClient(arNode)
fmt.Println("Init arweave block indep hash_list, need to speed about 2 minutes...")
idxs, err := GetBlockIdxs(startHeight, arCli)
if err != nil {
panic(err)
}
fmt.Println("Init arweave block indep hash_list finished...")
peers, err := arCli.GetPeers()
if err != nil {
panic(err)
}
return &Syncer{
curHeight: startHeight,
FilterParams: filterParams,
blockChan: make(chan *types.Block, 5*conNum),
SubscribeBlockChan: make(chan *types.Block, 5*conNum),
blockTxsChan: make(chan []SubscribeTx, conNum),
SubscribeChan: make(chan []SubscribeTx, conNum),
arClient: arCli,
nextSubscribeTxBlock: startHeight,
conNum: int64(conNum),
stableDistance: stableDistance,
blockIdxs: idxs,
scheduler: gocron.NewScheduler(time.UTC),
peers: peers,
subscribeType: subscribeType,
}
}
func (s *Syncer) Run() {
go s.runJobs()
go s.pollingBlock()
go s.pollingTx()
go s.filterTx()
}
func (s *Syncer) Close() (subscribeHeight int64) {
close(s.blockChan)
close(s.blockTxsChan)
close(s.SubscribeChan)
close(s.SubscribeBlockChan)
return s.nextSubscribeTxBlock - 1
}
func (s *Syncer) SubscribeTxCh() <-chan []SubscribeTx {
return s.SubscribeChan
}
func (s *Syncer) SubscribeBlockCh() <-chan *types.Block {
return s.SubscribeBlockChan
}
func (s *Syncer) GetSyncedHeight() int64 {
return atomic.LoadInt64(&s.nextSubscribeTxBlock)
}
func (s *Syncer) pollingBlock() {
for {
info, err := s.arClient.GetInfo()
if err != nil {
log.Error("get info", "err", err)
time.Sleep(10 * time.Second)
continue
}
stableHeight := info.Height - s.stableDistance
log.Debug("stable block", "height", stableHeight)
if s.curHeight >= stableHeight {
log.Debug("synced curHeight must less than on chain stableHeight; please wait 2 minute", "curHeight", s.curHeight, "stableHeight", stableHeight)
time.Sleep(2 * time.Minute)
continue
}
for s.curHeight <= stableHeight {
start := s.curHeight
end := start + s.conNum
if end > stableHeight {
end = stableHeight
}
blocks := mustGetBlocks(start, end, s.arClient, s.blockIdxs, int(s.conNum), s.peers)
log.Info("get blocks success", "start", start, "end", end)
s.curHeight = end + 1
// add chan
for _, b := range blocks {
if s.subscribeType == SubscribeTypeTx || s.subscribeType == SubscribeTypeBlockAndTx {
s.blockChan <- b
}
if s.subscribeType == SubscribeTypeBlock || s.subscribeType == SubscribeTypeBlockAndTx {
s.SubscribeBlockChan <- b
}
}
}
}
}
func (s *Syncer) pollingTx() {
for {
select {
case b := <-s.blockChan:
bHeight := b.Height
for {
if bHeight-atomic.LoadInt64(&s.nextSubscribeTxBlock) < s.conNum {
break
}
// log.Debug("wait for pollingTxs", "wait block height", b.Height, "nextSubscribeTxBlock Height", s.nextSubscribeTxBlock)
time.Sleep(5 * time.Second)
}
go s.getTxs(*b)
}
}
}
func (s *Syncer) getTxs(b types.Block) {
txs := mustGetTxs(b.Height, b.Txs, s.arClient, int(s.conNum), s.peers)
// subscribe txs
for {
if b.Height == atomic.LoadInt64(&s.nextSubscribeTxBlock) {
txsChan := make([]SubscribeTx, 0, len(txs))
for _, tx := range txs {
sTx := SubscribeTx{
Transaction: tx,
BlockHeight: b.Height,
BlockId: b.IndepHash,
BlockTimestamp: b.Timestamp,
}
txsChan = append(txsChan, sTx)
}
if len(txsChan) > 0 {
s.blockTxsChan <- txsChan
}
log.Info("polling one block txs success", "height", b.Height, "txNum", len(txs))
atomic.AddInt64(&s.nextSubscribeTxBlock, 1)
break
}
time.Sleep(2 * time.Second)
}
}
func (s *Syncer) filterTx() {
for {
select {
case txs := <-s.blockTxsChan:
filterTxs := make([]SubscribeTx, 0, len(txs))
for _, tx := range txs {
if filter(s.FilterParams, tx.Transaction) {
continue
}
filterTxs = append(filterTxs, tx)
}
if len(filterTxs) > 0 {
s.SubscribeChan <- filterTxs
}
}
}
}
func mustGetTxs(blockHeight int64, blockTxs []string, arClient *goar.Client, conNum int, peers []string) (txs []types.Transaction) {
if len(blockTxs) == 0 {
return
}
var (
lock sync.Mutex
wg sync.WaitGroup
)
// for sort
txIdxMap := make(map[string]int)
for idx, txId := range blockTxs {
txIdxMap[txId] = idx
}
txs = make([]types.Transaction, len(blockTxs))
p, _ := ants.NewPoolWithFunc(conNum, func(i interface{}) {
txId := i.(string)
tx, err := getTxByIdRetry(blockHeight, arClient, txId, peers)
if err != nil {
log.Error("get tx by id error", "txId", txId, "err", err)
// notice: must return fetch failed tx
tx = types.Transaction{ID: txId}
}
lock.Lock()
idx := txIdxMap[tx.ID]
txs[idx] = tx
lock.Unlock()
wg.Done()
})
defer p.Release()
for _, txId := range blockTxs {
wg.Add(1)
_ = p.Invoke(txId)
}
wg.Wait()
return
}
func mustGetBlocks(start, end int64, arClient *goar.Client, blockIdxs *BlockIdxs, conNum int, peers []string) (blocks []*types.Block) {
if start > end {
return
}
blocks = make([]*types.Block, end-start+1)
var (
lock sync.Mutex
wg sync.WaitGroup
)
p, _ := ants.NewPoolWithFunc(conNum, func(i interface{}) {
height := i.(int64)
b, err := getBlockByHeightRetry(arClient, height, blockIdxs, peers)
if err != nil {
log.Error("getBlockByHeightRetry get block by height error", "height", height, "err", err)
panic(err)
}
lock.Lock()
blocks[height-start] = b
lock.Unlock()
wg.Done()
}, ants.WithPanicHandler(func(err interface{}) {
panic(err)
}))
defer p.Release()
for i := start; i <= end; i++ {
wg.Add(1)
_ = p.Invoke(i)
}
wg.Wait()
return
}
func getTxByIdRetry(blockHeight int64, arCli *goar.Client, txId string, peers []string) (types.Transaction, error) {
count := 0
for {
// get from trust node
tx, err := arCli.GetTransactionByID(txId)
if err == nil {
// verify tx, ignore genesis block txs
if blockHeight != 0 {
err = utils.VerifyTransaction(*tx)
}
}
if err != nil {
// get from non-trust nodes
tx, err = arCli.GetTxFromPeers(txId, peers...)
if err == nil {
// verify tx, ignore genesis block txs
if blockHeight != 0 {
err = utils.VerifyTransaction(*tx)
}
}
}
if err == nil {
return *tx, nil
}
if count == 5 {
return types.Transaction{}, err
}
count++
time.Sleep(2 * time.Second)
}
}
func getBlockByHeightRetry(arCli *goar.Client, height int64, blockIdxs *BlockIdxs, peers []string) (*types.Block, error) {
count := 0
for {
b, err := arCli.GetBlockByHeight(height)
if err == nil {
// verify block
err = blockIdxs.VerifyBlock(*b)
}
if err != nil {
b, err = arCli.GetBlockFromPeers(height, peers...)
if err == nil {
// verify block
err = blockIdxs.VerifyBlock(*b)
}
}
if err == nil {
return b, nil
}
if count == 5 {
return nil, err
}
count++
time.Sleep(2 * time.Second)
}
}
func filter(params FilterParams, tx types.Transaction) bool {
if tx.Owner == "" { // todo this tx is incorrect, need subscribe to coder debug
return false
}
if params.OwnerAddress != "" {
// filer owner address
addr, err := utils.OwnerToAddress(tx.Owner)
if err != nil {
log.Error("utils.OwnerToAddress(tx.Owner) err", "err", err, "owner", tx.Owner)
return true
}
if addr != params.OwnerAddress {
return true
}
}
if params.Target != "" {
if params.Target != tx.Target {
return true
}
}
if len(params.Tags) > 0 {
// filter tags
// Notice: exist same name tags
filterTags := utils.TagsEncode(params.Tags)
txTagsMap := make(map[string]struct{}) // key: name+value; value: {}
for _, tg := range tx.Tags {
txTagsMap[tg.Name+tg.Value] = struct{}{}
}
for _, ftg := range filterTags {
if _, ok := txTagsMap[ftg.Name+ftg.Value]; !ok {
return true
}
}
}
return false
}