-
Notifications
You must be signed in to change notification settings - Fork 14
/
syncer.go
550 lines (523 loc) · 16.8 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
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
package ord
import (
"context"
"fmt"
"io/ioutil"
"os"
"os/signal"
"strconv"
"strings"
"sync"
"syscall"
"time"
"github.com/adshao/ordinals-indexer/internal/biz"
"github.com/adshao/ordinals-indexer/internal/conf"
"github.com/adshao/ordinals-indexer/internal/data"
"github.com/adshao/ordinals-indexer/internal/ord/page"
"github.com/adshao/ordinals-indexer/internal/ord/parser"
"github.com/adshao/go-brc721/sig"
"github.com/go-kratos/kratos/v2/log"
"github.com/google/wire"
)
var lastInscriptionIdFile = int64(0)
var ProviderSet = wire.NewSet(NewSyncer)
type result struct {
info *page.Inscription
err error
}
type uids []string
type Syncer struct {
c *conf.Ord
data *data.Data
collectionUc *biz.CollectionUsecase
tokenUc *biz.TokenUsecase
pageParser page.PageParser
logger *log.Helper
inscriptionUidChan chan string
resultChan chan *result
processChan chan uids
processFinishedChan chan error
eventChan chan Event
stopC chan struct{}
lastInscriptionIdChan chan int64
}
func NewSyncer(c *conf.Ord, data *data.Data, collectionUc *biz.CollectionUsecase, tokenUc *biz.TokenUsecase, logger log.Logger) (*Syncer, func(), error) {
cleanup := func() {
log.NewHelper(logger).Info("closing the syncer resources")
}
syncer := &Syncer{
c: c,
data: data,
collectionUc: collectionUc,
tokenUc: tokenUc,
pageParser: page.NewPageParser(c),
logger: log.NewHelper(logger),
}
concurrency := c.Worker.Concurrency
syncer.inscriptionUidChan = make(chan string, concurrency)
syncer.resultChan = make(chan *result, concurrency)
syncer.processChan = make(chan uids)
syncer.processFinishedChan = make(chan error)
syncer.eventChan = make(chan Event, concurrency)
syncer.stopC = make(chan struct{})
syncer.lastInscriptionIdChan = make(chan int64)
return syncer, cleanup, nil
}
func (s *Syncer) Run() error {
// TODO: we need to detect reorg and delete invalid data before we upsert new data
concurrency := s.c.Worker.Concurrency
workers := make([]*Worker, concurrency)
wg := &sync.WaitGroup{}
wg.Add(int(concurrency))
for i := 0; i < int(concurrency); i++ {
workers[i] = &Worker{
wid: i,
baseURL: s.c.Server.Addr,
pageParser: page.NewPageParser(s.c),
data: s.data,
uidChan: s.inscriptionUidChan,
resultChan: s.resultChan,
stopC: s.stopC,
logger: s.logger,
}
go func(worker *Worker) {
defer wg.Done()
worker.Start()
}(workers[i])
}
go func() {
s.receveResult()
}()
go func() {
for {
select {
case <-s.stopC:
s.logger.Infof("stopping inscriptions processor")
return
default:
lastInscriptionId, _ := s.getLastInscriptionId()
s.lastInscriptionIdChan <- lastInscriptionId
err := s.parseInscriptions(lastInscriptionId)
if err != nil {
s.logger.Errorf("failed to parse inscriptions: %v", err)
}
time.Sleep(60 * time.Second)
}
}
}()
terminateSignals := make(chan os.Signal, 1)
signal.Notify(terminateSignals, syscall.SIGINT, syscall.SIGKILL, syscall.SIGTERM, os.Interrupt)
signal := <-terminateSignals
s.logger.Infof("received signal %s, stopping workers...", signal)
close(s.inscriptionUidChan)
close(s.stopC)
wg.Wait()
s.logger.Info("all workers have been stopped")
return nil
}
func (s *Syncer) receveResult() {
insUids := make(uids, 0)
results := make(map[string]*result)
resultCount := 0
var lastInscriptionId int64
var stopped bool
for {
select {
case lastInscriptionId = <-s.lastInscriptionIdChan:
s.logger.Debugf("received lastInscriptionId: %d", lastInscriptionId)
case result := <-s.resultChan:
results[result.info.UID] = result
s.logger.Debugf("received result for inscription %d", result.info.ID)
resultCount++
case insUids = <-s.processChan:
s.logger.Debugf("receiving %d inscriptions", len(insUids))
case <-s.stopC:
stopped = true
default:
if resultCount == len(insUids) && len(insUids) > 0 {
if stopped {
s.logger.Infof("result processor stopped")
return
}
var err error
processedResultCount := 0
resultCount = 0
resultsInOrder := make([]*result, len(insUids))
for i := 0; i < len(insUids); i++ {
s.logger.Debugf("insUids[%d]: %s", i, insUids[i])
resultsInOrder[i] = results[insUids[len(insUids)-i-1]]
}
if len(resultsInOrder) != len(insUids) {
err = fmt.Errorf("resultsInOrder length %d != insUids length %d", len(resultsInOrder), len(insUids))
} else {
// make sure to process results in ascending order of inscriptionId
lastId := int64(0)
for _, result := range resultsInOrder {
if result.info.ID < lastId {
err = fmt.Errorf("results are not in order, lastId: %d, currentId: %d", lastId, result.info.ID)
break
}
lastId = result.info.ID
}
if err == nil {
processedResultCount, err = s.processResults(resultsInOrder, lastInscriptionId)
}
}
if err != nil {
s.logger.Errorf("failed to process results: %v", err)
s.processFinishedChan <- err
} else {
s.logger.Infof("processed %d results", processedResultCount)
s.processFinishedChan <- nil
}
}
time.Sleep(100 * time.Millisecond)
}
}
}
func (s *Syncer) saveLastInscriptionIdToFile(lastInscriptionId int64) error {
if lastInscriptionIdFile >= lastInscriptionId {
return nil
}
return ioutil.WriteFile(".last_inscription_id", []byte(strconv.FormatInt(lastInscriptionId, 10)), 0644)
}
func (s *Syncer) processResults(resultsInOrder []*result, lastInscriptionId int64) (int, error) {
count := 0
var lastSuccessInscriptionId int64
for _, result := range resultsInOrder {
if result.info.ID < lastInscriptionId {
s.logger.Debugf("inscription %d is less than lastInscriptionId %d, ignore", result.info.ID, lastInscriptionId)
continue
}
if result.err != nil {
return count, result.err
}
err := s.processResult(result)
if err != nil {
return count, err
}
s.logger.Infof("processed inscription %d", result.info.ID)
lastSuccessInscriptionId = result.info.ID
count++
}
if lastSuccessInscriptionId > 0 && lastSuccessInscriptionId > lastInscriptionId {
s.saveLastInscriptionIdToFile(lastSuccessInscriptionId)
}
return count, nil
}
func (s *Syncer) processResult(result *result) error {
info := result.info
if info.Content == nil {
return fmt.Errorf("content of inscription %d is nil", info.ID)
}
switch info.Content.Type {
case parser.NameBRC721Deploy:
err := s.processBRC721Deploy(info)
if err != nil {
return err
}
case parser.NameBRC721Mint:
err := s.processBRC721Mint(info)
if err != nil {
return err
}
case parser.NameBRC721Update:
// TODO: enable this after we have a way to identify the owner of the collection
// err := s.processBRC721Update(inscriptionId, info)
// if err != nil {
// return err
// }
default:
}
return nil
}
func (s *Syncer) processBRC721Deploy(info *page.Inscription) error {
o := info.Content.Data.(*parser.BRC721Deploy)
// check if the collection already exists
collection, err := s.collectionUc.GetCollectionByTick(context.Background(), biz.ProtocolTypeBRC721, o.Tick)
if err != nil {
return err
}
if collection != nil {
if collection.InscriptionID > info.ID {
// TODO: need to check if the collection is valid
s.logger.Warnf("collection %s already exists, but inscriptionId %d is greater than %d, ignore inscription %d", o.Tick, collection.InscriptionID, info.ID, info.ID)
} else {
s.logger.Infof("collection %s already exists, ignore inscription %d", o.Tick, info.ID)
}
return nil
}
// check deploy sig
if o.Sig != nil {
err = o.Sig.Validate()
if err != nil {
s.logger.Warnf("invalid deploy sig for collection %s, ignore inscription %d", o.Tick, info.ID)
return nil
}
}
// create the collection
collection = &biz.Collection{
P: biz.ProtocolTypeBRC721,
Tick: o.Tick,
Supply: 0,
}
max, err := strconv.ParseUint(o.Max, 10, 64)
if err != nil {
s.logger.Warnf("invalid max %s, ignore inscription %d", o.Max, info.ID)
return nil
}
collection.Max = max
if o.BaseURI != nil {
collection.BaseURI = *o.BaseURI
}
if o.Meta != nil {
collection.Name = o.Meta.Name
collection.Description = o.Meta.Description
collection.Image = o.Meta.Image
collection.Attributes = o.Meta.Attributes
}
collection.TxHash = info.GenesisTx
collection.BlockHeight = info.GenesisHeight
collection.BlockTime = info.Timestamp
collection.Address = info.Address
collection.InscriptionID = info.ID
collection.InscriptionUID = info.UID
if o.Sig != nil {
collection.Sig = *o.Sig
}
collection, err = s.collectionUc.CreateCollection(context.Background(), collection)
if err != nil {
return err
}
s.logger.Infof("created collection %s for inscription %d", o.Tick, info.ID)
return nil
}
func (s *Syncer) processBRC721Mint(info *page.Inscription) error {
inscriptionId := info.ID
o := info.Content.Data.(*parser.BRC721Mint)
// check if the collection exists
collection, err := s.collectionUc.GetCollectionByTick(context.Background(), biz.ProtocolTypeBRC721, o.Tick)
if err != nil {
return err
}
if collection == nil {
s.logger.Infof("collection %s not found, ignore mint inscription %d", o.Tick, inscriptionId)
return nil
}
if collection.InscriptionID >= inscriptionId {
s.logger.Warnf("collection %s inscriptionId %d is greater than %d, ignore mint inscription %d", o.Tick, collection.InscriptionID, inscriptionId, inscriptionId)
return nil
}
s.logger.Debugf("collection: %+v", collection)
// check if supply is full
if collection.Supply >= collection.Max {
s.logger.Infof("collection %s supply is full, ignore mint inscription %d", o.Tick, inscriptionId)
return nil
}
t, err := s.tokenUc.FindByInscriptionID(context.Background(), inscriptionId)
if err != nil {
return err
}
if len(t) > 0 {
s.logger.Infof("token with inscription %d already processed, ignore mint inscription", inscriptionId)
return nil
}
valid, mintSig, err := s.checkBRC721MintSig(info, collection, o)
if err != nil {
return err
}
if !valid {
return nil
}
// create token
token := &biz.Token{
Tick: o.Tick,
P: biz.ProtocolTypeBRC721,
TokenID: collection.Supply + 1,
TxHash: info.GenesisTx,
BlockHeight: info.GenesisHeight,
BlockTime: info.Timestamp,
Address: info.Address,
InscriptionID: inscriptionId,
InscriptionUID: info.UID,
CollectionID: collection.ID,
}
if mintSig != nil {
token.Sig = *mintSig
}
token, err = s.tokenUc.CreateToken(context.Background(), token)
if err != nil {
s.logger.Errorf("failed to create token: %T: %v", err, err)
return err
}
s.logger.Infof("created token %d for inscription %d", token.TokenID, inscriptionId)
collection.Supply++
collection, err = s.collectionUc.UpdateCollection(context.Background(), collection)
if err != nil {
return err
}
s.logger.Infof("updated collection %s supply to %d", o.Tick, collection.Supply)
return nil
}
func (s *Syncer) checkBRC721MintSig(info *page.Inscription, collection *biz.Collection, o *parser.BRC721Mint) (bool, *sig.MintSig, error) {
inscriptionId := info.ID
var mintSig *sig.MintSig
// check mint sig
if collection.Sig.PubKey == "" || len(collection.Sig.Fields) == 0 {
return true, nil, nil
}
// verify mint sig
if o.Sig == nil {
s.logger.Warnf("missing mint sig for collection %s, ignore mint inscription %d", o.Tick, inscriptionId)
return false, nil, nil
}
if o.Sig.Signature == "" {
s.logger.Warnf("missing mint sig.s for collection %s, ignore mint inscription %d", o.Tick, inscriptionId)
return false, nil, nil
}
mintSig = &sig.MintSig{
Signature: o.Sig.Signature,
}
for _, field := range collection.Sig.Fields {
switch field {
case sig.SigFieldReceiver:
mintSig.Receiver = info.Address
case sig.SigFieldUid:
if o.Sig.Uid == "" {
s.logger.Warnf("missing mint sig.uid for collection %s, ignore mint inscription %d", o.Tick, inscriptionId)
return false, nil, nil
}
utoken, err := s.tokenUc.FindByTickSigUID(context.Background(), biz.ProtocolTypeBRC721, o.Tick, o.Sig.Uid)
if err != nil {
s.logger.Errorf("failed to find token by tick %s and sig.uid %s: %v", o.Tick, o.Sig.Uid, err)
return false, nil, err
}
if utoken != nil {
s.logger.Warnf("mint sig.uid %s already exists for collection %s, ignore mint inscription %d", o.Sig.Uid, o.Tick, inscriptionId)
return false, nil, nil
}
mintSig.Uid = o.Sig.Uid
case sig.SigFieldExpiredTime:
if o.Sig.ExpiredTime == 0 {
s.logger.Warnf("missing mint sig.expt for collection %s, ignore mint inscription %d", o.Tick, inscriptionId)
return false, nil, nil
}
// parse '2023-07-27 12:51:49 UTC' to unix timestamp in seconds
if info.Timestamp.IsZero() {
s.logger.Errorf("Impossible! Invalid timestamp %s for collection %s, ignore mint inscription %d", info.Timestamp, o.Tick, inscriptionId)
return false, nil, fmt.Errorf("invalid timestamp %s for inscription %d", info.Timestamp, inscriptionId)
}
if uint64(info.Timestamp.Unix()) > o.Sig.ExpiredTime {
s.logger.Warnf("mint sig.expt %d is expired for collection %s, ignore mint inscription %d", o.Sig.ExpiredTime, o.Tick, inscriptionId)
return false, nil, nil
}
mintSig.ExpiredTime = o.Sig.ExpiredTime
case sig.SigFieldExpiredHeight:
if o.Sig.ExpiredHeight == 0 {
s.logger.Warnf("missing mint sig.exph for collection %s, ignore mint inscription %d", o.Tick, inscriptionId)
return false, nil, nil
}
if info.GenesisHeight > o.Sig.ExpiredHeight {
s.logger.Warnf("mint sig.exph %d is expired for collection %s, ignore mint inscription %d", o.Sig.ExpiredHeight, o.Tick, inscriptionId)
return false, nil, nil
}
mintSig.ExpiredHeight = o.Sig.ExpiredHeight
}
}
pubKey, err := sig.ParsePubKey(collection.Sig.PubKey)
if err != nil {
s.logger.Errorf("Impossible! Invalid public key %s for collection %s, ignore mint inscription %d", collection.Sig.PubKey, o.Tick, inscriptionId)
return false, nil, err
}
valid, err := mintSig.Verify(pubKey)
if err != nil {
s.logger.Warnf("failed to verify mint sig for collection %s, ignore mint inscription %d: %v", o.Tick, inscriptionId, err)
return false, nil, nil
}
if !valid {
s.logger.Warnf("invalid mint sig for collection %s, ignore mint inscription %d", o.Tick, inscriptionId)
return false, nil, nil
}
return true, mintSig, nil
}
func (s *Syncer) processBRC721Update(info *page.Inscription) error {
inscriptionId := info.ID
o := info.Content.Data.(*parser.BRC721Update)
// check if the collection exists
collection, err := s.collectionUc.GetCollectionByTick(context.Background(), biz.ProtocolTypeBRC721, o.Tick)
if err != nil {
return err
}
if collection == nil {
s.logger.Infof("collection %s not found, ignore inscription %d", o.Tick, inscriptionId)
return nil
}
// update collection
if o.BaseURI != nil {
collection.BaseURI = *o.BaseURI
}
_, err = s.collectionUc.UpdateCollection(context.Background(), collection)
if err != nil {
return err
}
s.logger.Infof("updated collection %s", o.Tick)
return nil
}
func (s *Syncer) getLastInscriptionId() (int64, error) {
lastInscriptionId, err := s.readLastInscriptionIdFromFile()
if err == nil {
s.logger.Infof("get lastInscriptionId from file: %d", lastInscriptionId)
return lastInscriptionId, nil
}
// lastInscriptionId, err := s.data.Rdb.GetUint64(ctx, lastInscriptionIdKey)
// if err != nil {
// s.logger.Warnf("failed to get lastInscriptionId from redis: %v", err)
// return 0, err
// }
// if lastInscriptionId != 0 {
// s.logger.Infof("get lastInscriptionId from redis: %d", lastInscriptionId)
// return lastInscriptionId, nil
// }
lastInscriptionId = s.c.Server.InscriptionIdStart
s.logger.Infof("get lastInscriptionId from config: %d", lastInscriptionId)
return lastInscriptionId, nil
}
func (s *Syncer) readLastInscriptionIdFromFile() (int64, error) {
b, err := ioutil.ReadFile(".last_inscription_id")
if err != nil {
return 0, err
}
id, err := strconv.ParseInt(strings.TrimSpace(string(b)), 10, 64)
if err != nil {
return 0, err
}
lastInscriptionIdFile = id
return id, nil
}
func (s *Syncer) parseInscriptions(inscriptionId int64) error {
inscriptionsPage := page.NewInscriptionsPage(inscriptionId)
s.logger.Infof("parsing inscriptions page %s", inscriptionsPage.URL())
data, err := s.pageParser.Parse(inscriptionsPage)
if err != nil {
return err
}
inscriptions, ok := data.(*page.Inscriptions)
if !ok {
return fmt.Errorf("invalid data type: %T for URL %s", data, inscriptionsPage.URL())
}
insUids := inscriptions.UIDs
s.processChan <- insUids
for _, insUid := range insUids {
s.inscriptionUidChan <- insUid
}
// wait for the process to finish
err = <-s.processFinishedChan
if err != nil {
return err
}
// check if there is a next page
if inscriptions.NextID != nil {
return s.parseInscriptions(*inscriptions.NextID)
}
return nil
}