-
Notifications
You must be signed in to change notification settings - Fork 18
/
addressbook.go
412 lines (367 loc) · 11.2 KB
/
addressbook.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
package addressbook
import (
"context"
"encoding/json"
"fmt"
"io"
"net/http"
"sort"
"sync"
"time"
"github.com/shopspring/decimal"
"github.com/shurcooL/graphql"
"github.com/tonkeeper/tongo"
"go.uber.org/zap"
"golang.org/x/exp/maps"
"golang.org/x/exp/slices"
"github.com/tonkeeper/opentonapi/pkg/cache"
"github.com/tonkeeper/opentonapi/pkg/oas"
"github.com/tonkeeper/opentonapi/pkg/references"
)
// KnownAddress represents additional manually crafted information about a particular account in the blockchain.
type KnownAddress struct {
IsScam bool `json:"is_scam,omitempty"`
RequireMemo bool `json:"require_memo,omitempty"`
Name string `json:"name"`
Address string `json:"address"`
Image string `json:"image,omitempty"`
}
// AttachedAccount represents domains, nft collections for quick search by name are presented
type AttachedAccount struct {
Name string `json:"name"`
Preview string `json:"preview"`
Wallet string `json:"wallet"`
Symbol string `json:"-"`
Normalized string `json:"-"`
}
type JettonVerificationType string
const (
Whitelist JettonVerificationType = "whitelist"
Blacklist JettonVerificationType = "blacklist"
None JettonVerificationType = "none"
)
// KnownJetton represents additional manually crafted information about a particular jetton in the blockchain.
type KnownJetton struct {
Name string `json:"name"`
Verification JettonVerificationType `json:"verification"`
Description string `json:"description"`
Image string `json:"image"`
Address string `json:"address"`
Symbol string `json:"symbol"`
MaxSupply decimal.Decimal `json:"max_supply"`
Websites []string `json:"websites,omitempty"`
Social []string `json:"social,omitempty"`
Coinmarketcap string `json:"coinmarketcap,omitempty"`
Coingecko string `json:"coingecko,omitempty"`
}
// KnownCollection represents additional manually crafted information about a particular NFT collection in the blockchain.
type KnownCollection struct {
Name string `json:"name"`
Description string `json:"description"`
Address string `json:"address"`
MaxItems int64 `json:"max_items"`
Websites []string `json:"websites,omitempty"`
Social []string `json:"social,omitempty"`
Approvers []oas.NftApprovedByItem
}
type Option func(o *Options)
type Options struct {
addressers []addresser
}
type addresser interface {
IsWallet(a tongo.AccountID) (bool, error)
GetAddress(a tongo.AccountID) (KnownAddress, bool)
SearchAttachedAccounts(prefix string) []AttachedAccount
}
func WithAdditionalAddressesSource(a addresser) Option {
return func(o *Options) {
o.addressers = append(o.addressers, a)
}
}
// Book holds information about known accounts, jettons, NFT collections manually crafted by the tonkeeper team and the community.
type Book struct {
addressers []addresser
mu sync.RWMutex
addresses map[tongo.AccountID]KnownAddress
collections map[tongo.AccountID]KnownCollection
jettons map[tongo.AccountID]KnownJetton
tfPools map[tongo.AccountID]TFPoolInfo
walletsResolved cache.Cache[tongo.AccountID, bool]
}
type TFPoolInfo struct {
Name string `json:"name"`
GroupName string `json:"groupName"`
Address string `json:"address"`
}
func (b *Book) GetAddressInfoByAddress(a tongo.AccountID) (KnownAddress, bool) {
b.mu.RLock()
defer b.mu.RUnlock()
if a1, ok := b.addresses[a]; ok {
return a1, ok
}
for i := range b.addressers {
if a1, ok := b.addressers[i].GetAddress(a); ok {
return a1, ok
}
}
return KnownAddress{}, false
}
func (b *Book) SearchAttachedAccountsByPrefix(prefix string) []AttachedAccount {
b.mu.RLock()
defer b.mu.RUnlock()
for i := range b.addressers {
foundAccounts := b.addressers[i].SearchAttachedAccounts(prefix)
if len(foundAccounts) > 0 {
return foundAccounts
}
}
return []AttachedAccount{}
}
func (b *Book) GetTFPoolInfo(a tongo.AccountID) (TFPoolInfo, bool) {
b.mu.RLock()
defer b.mu.RUnlock()
info, ok := b.tfPools[a]
return info, ok
}
func (b *Book) GetKnownCollections() map[tongo.AccountID]KnownCollection {
b.mu.RLock()
defer b.mu.RUnlock()
collections := make(map[tongo.AccountID]KnownCollection, len(b.collections))
for accountID, collection := range b.collections {
collections[accountID] = collection
}
return collections
}
func (b *Book) GetCollectionInfoByAddress(a tongo.AccountID) (KnownCollection, bool) {
b.mu.RLock()
defer b.mu.RUnlock()
c, ok := b.collections[a]
return c, ok
}
func (b *Book) GetKnownJettons() map[tongo.AccountID]KnownJetton {
b.mu.RLock()
defer b.mu.RUnlock()
return maps.Clone(b.jettons)
}
func (b *Book) GetJettonInfoByAddress(a tongo.AccountID) (KnownJetton, bool) {
b.mu.RLock()
defer b.mu.RUnlock()
j, ok := b.jettons[a]
if ok {
j.Verification = Whitelist
} else {
j.Verification = None
}
return j, ok
}
func (b *Book) TFPools() []tongo.AccountID {
b.mu.RLock()
defer b.mu.RUnlock()
return maps.Keys(b.tfPools)
}
// IsWallet returns true if the given address is a wallet.
func (b *Book) IsWallet(addr tongo.AccountID) (bool, error) {
if wallet, ok := b.walletsResolved.Get(addr); ok {
return wallet, nil
}
for _, privateBook := range b.addressers {
isWallet, err := privateBook.IsWallet(addr)
if err != nil {
continue
}
b.walletsResolved.Set(addr, isWallet, cache.WithExpiration(time.Minute*15))
return isWallet, nil
}
return false, fmt.Errorf("failed to figure out if %v is a wallet", addr)
}
func NewAddressBook(logger *zap.Logger, addressPath, jettonPath, collectionPath string, opts ...Option) *Book {
var options Options
for _, opt := range opts {
opt(&options)
}
addresses := make(map[tongo.AccountID]KnownAddress)
collections := make(map[tongo.AccountID]KnownCollection)
jettons := make(map[tongo.AccountID]KnownJetton)
tfPools := make(map[tongo.AccountID]TFPoolInfo)
book := &Book{
addresses: addresses,
collections: collections,
jettons: jettons,
tfPools: tfPools,
addressers: options.addressers,
walletsResolved: cache.NewLRUCache[tongo.AccountID, bool](200_000, "is_wallet"),
}
go func() {
for {
book.refresh(logger, addressPath, jettonPath, collectionPath)
time.Sleep(time.Minute * 10)
}
}()
go book.getGGWhitelist(logger)
go book.getTonDiamondsWhitelist()
return book
}
func (b *Book) refresh(logger *zap.Logger, addressPath, jettonPath, collectionPath string) {
go b.refreshAddresses(logger, addressPath)
go b.refreshJettons(logger, jettonPath)
go b.refreshCollections(logger, collectionPath)
go b.refreshTfPools(logger)
}
func (b *Book) refreshAddresses(logger *zap.Logger, addressPath string) {
addresses, err := downloadJson[KnownAddress](addressPath)
if err != nil {
logger.Warn("failed to load accounts.json")
return
}
b.mu.Lock()
defer b.mu.Unlock()
for _, item := range addresses {
account, err := tongo.ParseAddress(item.Address)
if err != nil {
continue
}
item.Address = account.ID.ToRaw()
b.addresses[account.ID] = item
}
}
func (b *Book) refreshJettons(logger *zap.Logger, jettonPath string) {
jettons, err := downloadJson[KnownJetton](jettonPath)
if err != nil {
logger.Warn("failed to load jettons.json")
return
}
b.mu.Lock()
defer b.mu.Unlock()
for _, item := range jettons {
account, err := tongo.ParseAddress(item.Address)
if err != nil {
continue
}
item.Address = account.ID.ToRaw()
b.jettons[account.ID] = item
}
}
func unique(approvers []oas.NftApprovedByItem) []oas.NftApprovedByItem {
sort.Slice(approvers, func(i, j int) bool {
return approvers[i] < approvers[j]
})
return slices.Compact(approvers)
}
func (b *Book) refreshCollections(logger *zap.Logger, collectionPath string) {
collections, err := downloadJson[KnownCollection](collectionPath)
if err != nil {
logger.Warn("fail to load collections.json")
return
}
b.mu.Lock()
defer b.mu.Unlock()
for _, item := range collections {
// TODO: remove items that were previously added but aren't present in the current list.
account, err := tongo.ParseAddress(item.Address)
if err != nil {
continue
}
currentCollection, ok := b.collections[account.ID]
if !ok {
// this is a new item, so we only add tonkeeper as approver.
item.Address = account.ID.ToRaw()
item.Approvers = unique(append(item.Approvers, oas.NftApprovedByItemTonkeeper))
b.collections[account.ID] = item
continue
}
// this is an existing item, so we merge approvers and remove duplicates adding tonkeeper.
item.Approvers = unique(append(append(currentCollection.Approvers, item.Approvers...), oas.NftApprovedByItemTonkeeper))
b.collections[account.ID] = item
}
}
func (b *Book) refreshTfPools(logger *zap.Logger) {
b.mu.Lock()
defer b.mu.Unlock()
for _, pool := range getPools(logger) {
account, err := tongo.ParseAddress(pool.Address)
if err != nil {
logger.Error("failed to parse account in pools", zap.Error(err))
continue
}
pool.Address = account.ID.ToRaw()
b.tfPools[account.ID] = pool
}
}
func downloadJson[T any](url string) ([]T, error) {
response, err := http.Get(url)
if err != nil {
return nil, err
}
defer response.Body.Close()
if response.StatusCode >= 300 {
return nil, fmt.Errorf("invalid status code %v", response.StatusCode)
}
content, err := io.ReadAll(response.Body)
if err != nil {
return nil, err
}
var data []T
if err = json.Unmarshal(content, &data); err != nil {
return nil, err
}
return data, nil
}
func (b *Book) getGGWhitelist(logger *zap.Logger) {
for {
if len(b.GetKnownCollections()) == 0 {
time.Sleep(time.Second * 10)
continue
}
addresses, err := FetchGetGemsVerifiedCollections()
if err != nil {
logger.Warn(fmt.Sprintf("get nft collection whitelist: %v", err))
time.Sleep(time.Minute * 3)
continue
}
b.mu.Lock()
for _, account := range addresses {
collection := b.collections[account]
collection.Approvers = unique(append(collection.Approvers, oas.NftApprovedByItemGetgems))
b.collections[account] = collection
}
b.mu.Unlock()
return
}
}
func (b *Book) getTonDiamondsWhitelist() {
for {
if len(b.GetKnownCollections()) == 0 {
time.Sleep(time.Second * 10)
continue
}
b.mu.Lock()
for _, account := range references.TonDiamondsCollections {
collection := b.collections[account]
collection.Approvers = unique(append(collection.Approvers, oas.NftApprovedByItemTonDiamonds))
b.collections[account] = collection
}
b.mu.Unlock()
return
}
}
func FetchGetGemsVerifiedCollections() ([]tongo.AccountID, error) {
client := graphql.NewClient("https://api.getgems.io/graphql", nil)
ctx, cancel := context.WithTimeout(context.Background(), time.Minute)
defer cancel()
var q struct {
GetAddressesOfVerifiedCollections []graphql.String `graphql:"getAddressesOfVerifiedCollections"`
}
err := client.Query(ctx, &q, nil)
if err != nil {
return nil, err
}
accountIDs := make([]tongo.AccountID, 0, len(q.GetAddressesOfVerifiedCollections))
for _, collection := range q.GetAddressesOfVerifiedCollections {
account, err := tongo.ParseAddress(string(collection))
if err != nil {
return nil, err
}
accountIDs = append(accountIDs, account.ID)
}
return accountIDs, nil
}