forked from DHEBP/HOLOGRAM
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgnomon.go
More file actions
1449 lines (1242 loc) · 38.9 KB
/
Copy pathgnomon.go
File metadata and controls
1449 lines (1242 loc) · 38.9 KB
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
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package main
import (
"bytes"
"crypto/sha256"
"encoding/hex"
"encoding/json"
"fmt"
"io"
"log"
"os"
"path/filepath"
"sort"
"strconv"
"strings"
"time"
"github.com/civilware/Gnomon/indexer"
"github.com/civilware/Gnomon/storage"
"github.com/civilware/Gnomon/structures"
"github.com/deroproject/derohe/globals"
)
const gnomonSCID = "bb43c3eb626ee767c9f305772a6666f7c7300441a0ad8538a0799eb4f12ebcd2"
// GnomonClient manages the Gnomon indexer for TELA content discovery
type GnomonClient struct {
Indexer *indexer.Indexer
fastsync bool
parallelBlocks int
dbPath string
dbType string
running bool
disableFastsync bool // Temporary flag to disable fastsync for next start (used after resync)
startFromHeight int64 // If > 0, start indexing from this height instead of 0 or current
appsLoaded bool // True when GetDiscoveredApps() has completed at least once
}
const maxParallelBlocks = 10
// TELA search filter - matches the canonical TELA-INDEX-1/TELA-DOC-1 init() snippet
// verbatim, so TELA app discovery only indexes those contracts.
const gnomonSearchFilter = `Function init() Uint64
10 IF EXISTS("owner") == 0 THEN GOTO 30
20 RETURN 1
30 STORE("owner", address())`
// tokenSearchFilter is the broader entry that lets the token auto-scan discover
// held tokens/NFAs. Gnomon OR-matches every filter substring (strings.Contains),
// so adding "Function Initialize" indexes the standard token + Artificer NFA
// (ART-NFA-MS1) families, whose initializer is "Function InitializePrivate()" —
// the strict TELA snippet above never matches them. This is the same substring
// Engram filters on. Curated TELA consumers re-filter at query time (isIndex), so
// the wider index does not pollute app discovery.
const tokenSearchFilter = `Function Initialize`
// gnomonFilters is the active filter set passed to the indexer. Changing this set
// requires a one-time resync (see migrateGnomonFilterVersionIfNeeded) because
// Gnomon never re-examines already-indexed blocks against a new filter — only a
// fresh fastsync applies it to the full SC snapshot.
var gnomonFilters = []string{gnomonSearchFilter, tokenSearchFilter}
// NewGnomonClient creates a new Gnomon client
func NewGnomonClient(dbType string) *GnomonClient {
if dbType == "" {
dbType = "gravdb" // Default to GravDB
}
return &GnomonClient{
fastsync: true,
parallelBlocks: 5,
dbType: dbType,
running: false,
}
}
// Start initializes and starts the Gnomon indexer
func (g *GnomonClient) Start(endpoint string, network string) error {
if g.running {
return fmt.Errorf("gnomon already running")
}
// Strip http:// or https:// prefix - Gnomon's indexer.Connect() adds "ws://" internally
// So we need to pass just "host:port" to avoid "ws://http://host:port/ws"
endpoint = strings.TrimPrefix(endpoint, "http://")
endpoint = strings.TrimPrefix(endpoint, "https://")
// Determine data path based on network
// Use UserHomeDir instead of Getwd for packaged macOS apps
homeDir, err := os.UserHomeDir()
if err != nil {
return fmt.Errorf("failed to get home directory: %w", err)
}
// Create network-specific path in ~/.dero/hologram/datashards/
baseDir := filepath.Join(homeDir, ".dero", "hologram", "datashards")
basePath := filepath.Join(baseDir, "gnomon")
switch network {
case "simulator":
basePath = filepath.Join(baseDir, "gnomon_simulator")
case "mainnet":
basePath = filepath.Join(baseDir, "gnomon_mainnet")
}
g.dbPath = basePath
// Ensure directory exists
if err := os.MkdirAll(basePath, 0755); err != nil {
return fmt.Errorf("failed to create gnomon directory: %w", err)
}
// Initialize storage backends
boltDB, boltErr := storage.NewBBoltDB(basePath, "gnomon")
gravDB, gravErr := storage.NewGravDB(basePath, "25ms")
var height int64
switch g.dbType {
case "boltdb":
if boltErr != nil {
if !strings.HasPrefix(boltErr.Error(), "[") {
boltErr = fmt.Errorf("[NewBBoltDB] %s", boltErr)
}
return boltErr
}
height, err = boltDB.GetLastIndexHeight()
if err != nil {
// Gnomon DB is a rebuildable cache; if it is unreadable, reset it now to
// avoid StartDaemonMode hitting logger.Fatalf() on the same path.
g.log(fmt.Sprintf("[Gnomon] BoltDB read failed (%v). Resetting cache at %s", err, basePath))
g.cleanDBPath(basePath)
boltDB, boltErr = storage.NewBBoltDB(basePath, "gnomon")
if boltErr != nil {
if !strings.HasPrefix(boltErr.Error(), "[") {
boltErr = fmt.Errorf("[NewBBoltDB] %s", boltErr)
}
return boltErr
}
height, err = boltDB.GetLastIndexHeight()
if err != nil {
return fmt.Errorf("[Gnomon] BoltDB recovery failed: %w", err)
}
}
default: // gravdb
if gravErr != nil {
return fmt.Errorf("[NewGravDB] %s", gravErr)
}
height, err = gravDB.GetLastIndexHeight()
if err != nil {
// Gnomon DB is a rebuildable cache; if it is unreadable, reset it now to
// avoid StartDaemonMode hitting logger.Fatalf() on the same path.
g.log(fmt.Sprintf("[Gnomon] GravDB read failed (%v). Resetting cache at %s", err, basePath))
g.cleanDBPath(basePath)
gravDB, gravErr = storage.NewGravDB(basePath, "25ms")
if gravErr != nil {
return fmt.Errorf("[NewGravDB] %s", gravErr)
}
height, err = gravDB.GetLastIndexHeight()
if err != nil {
return fmt.Errorf("[Gnomon] GravDB recovery failed: %w", err)
}
}
}
// Sanity check: if the stored height is beyond the daemon's chain height
// the chain was reset (e.g. simulator restart). Clean the DB and start
// from 0 so Gnomon doesn't sit idle waiting for blocks that will never come.
if height > 0 {
if chainHeight := queryDaemonHeight(endpoint); chainHeight >= 0 && height > chainHeight {
g.log(fmt.Sprintf("[Gnomon] Stored height %d exceeds chain height %d — resetting DB", height, chainHeight))
g.cleanDBPath(basePath)
height = 0
// Re-open storage after clean
switch g.dbType {
case "boltdb":
boltDB, boltErr = storage.NewBBoltDB(basePath, "gnomon")
if boltErr != nil {
return fmt.Errorf("[NewBBoltDB] %s", boltErr)
}
default:
gravDB, gravErr = storage.NewGravDB(basePath, "25ms")
if gravErr != nil {
return fmt.Errorf("[NewGravDB] %s", gravErr)
}
}
}
}
// Known exclusions (if any)
exclusions := []string{gnomonSCID}
// Search filter set: the strict TELA snippet (app discovery) plus the broader
// token/NFA entry (auto-scan discovery). See gnomonFilters.
filter := gnomonFilters
// Fastsync configuration
// For simulator mode, disable fastsync to ensure we index from block 0
// This is important because simulator chains are small and we need to find
// all deployed contracts, not just new ones
useFastsync := g.fastsync
forceFastsync := true
if network == "simulator" {
useFastsync = false
forceFastsync = false
}
// If disableFastsync flag is set (e.g., after a resync), disable fastsync
// This ensures we index from the stored height (or 0 if DB was cleaned)
if g.disableFastsync {
useFastsync = false
forceFastsync = false
g.disableFastsync = false // Reset the flag after use
}
// If a specific start height is set, use it instead of the stored height
if g.startFromHeight > 0 {
height = g.startFromHeight
g.startFromHeight = 0 // Reset after use
}
config := &structures.FastSyncConfig{
Enabled: useFastsync,
SkipFSRecheck: false,
ForceFastSync: forceFastsync,
ForceFastSyncDiff: 100,
NoCode: false,
}
// Create indexer
g.Indexer = indexer.NewIndexer(
gravDB,
boltDB,
g.dbType,
filter,
height,
endpoint,
"daemon",
false, // mbllookup
false, // closeondisconnect
config,
exclusions,
false, // storeintegrators (new in feat-addscidtoindex-wsserver)
)
// Initialize logging
indexer.InitLog(globals.Arguments, os.Stdout)
// Start indexer in background
go g.Indexer.StartDaemonMode(g.parallelBlocks)
g.running = true
return nil
}
// Stop closes the Gnomon indexer
func (g *GnomonClient) Stop() {
if g.Indexer != nil {
g.Indexer.Close()
g.Indexer = nil
g.running = false
g.appsLoaded = false // Reset apps loaded state
}
}
// SetDisableFastsync sets a flag to disable fastsync on the next start
// This is used after a resync to ensure we index from block 0
func (g *GnomonClient) SetDisableFastsync(disable bool) { g.disableFastsync = disable }
// SetStartFromHeight sets a specific height to start indexing from
// This is useful for resyncing recent contracts without indexing the entire chain
func (g *GnomonClient) SetStartFromHeight(height int64) { g.startFromHeight = height }
// SetAppsLoaded sets the appsLoaded flag (called by App.GetDiscoveredApps)
func (g *GnomonClient) SetAppsLoaded(loaded bool) { g.appsLoaded = loaded }
// IsAppsLoaded returns whether apps have been loaded at least once
func (g *GnomonClient) IsAppsLoaded() bool { return g.appsLoaded }
// IsRunning returns whether Gnomon is running
func (g *GnomonClient) IsRunning() bool { return g.running && g.Indexer != nil }
// GetStatus returns the current indexing status
func (g *GnomonClient) GetStatus() map[string]any {
if !g.IsRunning() {
return map[string]any{
"running": false,
"connecting": false,
"indexed_height": 0,
"chain_height": 0,
"progress": 0.0,
}
}
var (
indexed, chain = g.Indexer.LastIndexedHeight, g.Indexer.ChainHeight
// If chain height is 0, Gnomon is still trying to connect to the daemon
// This happens when the connection loop in StartDaemonMode is retrying
connecting = chain == 0
progress = 0.0
)
if chain > 0 {
progress = (float64(indexed) / float64(chain)) * 100.0
}
return map[string]any{
"running": true,
"connecting": connecting,
"indexed_height": indexed,
"chain_height": chain,
"progress": progress,
"db_type": g.dbType,
"db_path": g.dbPath,
"apps_loaded": g.appsLoaded,
// Indexer lifecycle: initializing|fastsyncing|indexing|indexed.
"indexer_status": g.Indexer.Status,
}
}
// GetAllOwnersAndSCIDs returns all indexed smart contracts
func (g *GnomonClient) GetAllOwnersAndSCIDs() map[string]string {
if !g.IsRunning() {
return make(map[string]string)
}
switch g.Indexer.DBType {
case "gravdb":
return g.Indexer.GravDBBackend.GetAllOwnersAndSCIDs()
case "boltdb":
return g.Indexer.BBSBackend.GetAllOwnersAndSCIDs()
default:
return make(map[string]string)
}
}
// GetAllSCIDVariableDetails returns all variables for a smart contract
func (g *GnomonClient) GetAllSCIDVariableDetails(scid string) []*structures.SCIDVariable {
if !g.IsRunning() {
return nil
}
switch g.Indexer.DBType {
case "gravdb":
return g.Indexer.GravDBBackend.GetAllSCIDVariableDetails(scid)
case "boltdb":
return g.Indexer.BBSBackend.GetAllSCIDVariableDetails(scid)
default:
return nil
}
}
// GetSCIDValuesByKey returns values for a specific key in a smart contract
func (g *GnomonClient) GetSCIDValuesByKey(scid string, key any) (valuesstring []string, valuesuint64 []uint64) {
if !g.IsRunning() {
return nil, nil
}
switch g.Indexer.DBType {
case "gravdb":
return g.Indexer.GravDBBackend.GetSCIDValuesByKey(scid, key, g.Indexer.ChainHeight, true)
case "boltdb":
return g.Indexer.BBSBackend.GetSCIDValuesByKey(scid, key, g.Indexer.ChainHeight, true)
default:
return nil, nil
}
}
// GetSCIDKeysByValue returns keys for a specific value in a smart contract
func (g *GnomonClient) GetSCIDKeysByValue(scid string, value any) (valuesstring []string, valuesuint64 []uint64) {
if !g.IsRunning() {
return nil, nil
}
switch g.Indexer.DBType {
case "gravdb":
return g.Indexer.GravDBBackend.GetSCIDKeysByValue(scid, value, g.Indexer.ChainHeight, true)
case "boltdb":
return g.Indexer.BBSBackend.GetSCIDKeysByValue(scid, value, g.Indexer.ChainHeight, true)
default:
return nil, nil
}
}
// GetTELAApps returns all discovered TELA INDEX applications (filters out DOCs)
func (g *GnomonClient) GetTELAApps() []map[string]any {
apps := make([]map[string]any, 0)
if !g.IsRunning() {
return apps
}
// Get all SCIDs
scids := g.GetAllOwnersAndSCIDs()
for scid, owner := range scids {
var (
// Get variables for this SCID
vars = g.GetAllSCIDVariableDetails(scid)
data = map[string]any{"scid": scid, "owner": owner, "is_index": false}
// Extract TELA-specific variables
app, isIndex, _, _ = allocateData(vars, data)
)
// Only include INDEX contracts (apps with DOC references)
// This filters out individual DOC files which can't be rendered standalone
if isIndex {
var (
// Generate clean display name (prefer dURL when present)
displayName = ""
// Get fields
name, hasName = app["name"].(string)
description, hasDesc = app["description"].(string)
url, hasURL = app["url"].(string)
// Helper function to check if a string is a URL/file path
isURLFunc = func(s string) bool {
if s == "" {
return false
}
for _, substr := range []string{
"http",
"://",
".png",
".jpg",
".jpeg",
".svg",
".gif",
".ico",
"/ipfs/",
"/images/",
"/icons/",
"/assets/",
"gateway.",
"blob/",
"i.ibb.",
"bafybeih",
"avatars.",
"raw.github",
".world/",
".com/",
".org/",
".io/",
} {
if strings.Contains(strings.ToLower(s), substr) {
return true
}
}
return false
}
// Check both description and name for URLs
isDescURL = hasDesc && isURLFunc(description)
isNameURL = hasName && isURLFunc(name)
)
// Decision tree - prefer dURL if present
if du, hasDU := app["durl"].(string); hasDU && du != "" {
displayName = du
} else if hasDesc && description != "" && !isDescURL {
// Use description if it's NOT a URL
displayName = description
} else if hasName && name != "" && !isNameURL {
// Use name if description was URL/empty and name is clean
displayName = name
} else if hasURL && url != "" {
// Use cleaned dURL domain
displayName = cleanupAppName(url)
} else {
// Nothing usable - generic name
displayName = "TELA App"
}
// Limit to 40 characters for uniformity
displayName = strings.TrimSpace(displayName)
if len(displayName) > 40 {
displayName = displayName[:37] + "..."
}
// Final paranoid safety check - if result still looks like URL, replace it
if isURLFunc(displayName) {
// It's STILL a URL after all that - use generic name
if hasURL && url != "" {
cleaned := cleanupAppName(url)
// Triple-check the cleaned version
if !isURLFunc(cleaned) && !strings.Contains(cleaned, "/") {
displayName = cleaned
} else {
displayName = "TELA App"
}
} else {
displayName = "TELA App"
}
}
app["display_name"] = displayName
apps = append(apps, app)
}
}
return apps
}
// GetTELALibraries returns all TELA content tagged as libraries (.lib suffix in dURL)
func (g *GnomonClient) GetTELALibraries() []map[string]any {
libs := make([]map[string]any, 0)
if !g.IsRunning() {
return libs
}
// Get all SCIDs
scids := g.GetAllOwnersAndSCIDs()
for scid, owner := range scids {
var (
vars = g.GetAllSCIDVariableDetails(scid)
params = map[string]any{"scid": scid, "owner": owner, "is_index": false, "doc_count": 0}
lib, _, _, hasLibTag = allocateData(vars, params)
)
// Only include content tagged as library
if hasLibTag {
libs = append(libs, lib)
}
}
return libs
}
// SearchTELApps searches for TELA apps by name or description
func (g *GnomonClient) SearchTELApps(query string) []map[string]any {
var (
allApps = g.GetTELAApps()
results = make([]map[string]any, 0)
q = strings.ToLower(query)
has = strings.Contains
)
for _, app := range allApps {
name := ""
if n, ok := app["name"].(string); ok {
name = strings.ToLower(n)
}
description := ""
if d, ok := app["description"].(string); ok {
description = strings.ToLower(d)
}
if has(name, q) || has(description, q) {
results = append(results, app)
}
}
return results
}
// LatestInteractionHeight returns the most recent interaction height for a SCID
func (g *GnomonClient) LatestInteractionHeight(scid string) int64 {
if !g.IsRunning() {
return 0
}
heights := g.Indexer.GravDBBackend.GetSCIDInteractionHeight(scid)
var max int64 = 0
for _, h := range heights {
if h > max {
max = h
}
}
return max
}
// AddSCIDToIndex manually indexes a SCID that doesn't match the default search filter.
// Implements civilware's feat-addscidtoindex-wsserver feature — the official fix for
// Bug #1 (Gnomon fastsync: historical SCID data missing).
//
// Parameters:
// - scid: 64-char hex SCID to index
// - varstoreonly: if true, skips SC-code fetch (faster, but less classifier signal)
// - skipfsrecheck: if true, short-circuits if SCID is already indexed
//
// Returns error on failure, nil on success. After success, the SCID's current
// variable state is stored and it becomes discoverable via GetAllOwnersAndSCIDs.
func (g *GnomonClient) AddSCIDToIndex(scid string, varstoreonly, skipfsrecheck bool) error {
if !g.IsRunning() {
return fmt.Errorf("gnomon not running")
}
if len(strings.TrimSpace(scid)) != 64 {
return fmt.Errorf("invalid scid: expected 64 hex chars")
}
// Pre-fill the existing owner row: the indexer unconditionally stages
// StoreOwner(scid, fsi.Owner) on this path, so an empty FastSyncImport would
// blank a previously-stored owner on every re-index (varstoreonly bypasses
// the already-validated early-return). Passing the current value through
// makes re-indexing owner-preserving; a first-time index writes "" as before.
owner := ""
switch g.Indexer.DBType {
case "gravdb":
owner = g.Indexer.GravDBBackend.GetOwner(scid)
case "boltdb":
owner = g.Indexer.BBSBackend.GetOwner(scid)
}
scidsToAdd := make(map[string]*structures.FastSyncImport)
scidsToAdd[scid] = &structures.FastSyncImport{Owner: owner}
return g.Indexer.AddSCIDToIndex(scidsToAdd, skipfsrecheck, varstoreonly)
}
// CheckAppSupportsEpoch determines if a TELA app supports EPOCH crowd mining
// Looks for EPOCH-related variables or functions in the smart contract
func (g *GnomonClient) CheckAppSupportsEpoch(scid string) bool {
if !g.IsRunning() {
return false
}
vars := g.GetAllSCIDVariableDetails(scid)
if vars == nil {
return false
}
// Check for EPOCH-related variables
epochKeywords := []string{
"epoch",
"EPOCH",
"epochEnabled",
"epoch_enabled",
"epochSupport",
"crowd_mining",
"crowdMining",
}
for _, v := range vars {
key := fmt.Sprintf("%v", v.Key)
keyLower := strings.ToLower(key)
for _, keyword := range epochKeywords {
if strings.Contains(keyLower, strings.ToLower(keyword)) {
return true
}
}
}
return false
}
// GetTELAAppsWithEpochInfo returns all TELA apps with EPOCH support information
func (g *GnomonClient) GetTELAAppsWithEpochInfo() []map[string]any {
apps := g.GetTELAApps()
for i, app := range apps {
if scid, ok := app["scid"].(string); ok {
supportsEpoch := g.CheckAppSupportsEpoch(scid)
apps[i]["supports_epoch"] = supportsEpoch
if supportsEpoch {
apps[i]["epoch_badge"] = "EPOCH Enabled"
}
}
}
return apps
}
// ResolveName tries to resolve a human-friendly TELA app name to a SCID using the Gnomon index.
// Matching strategy (strict first, then relaxed):
// 1) Exact match on display_name (case-insensitive)
// 2) Exact match on name (case-insensitive)
// 3) Prefix match on display_name/name if unique
func (g *GnomonClient) ResolveName(name string) (string, bool) {
if !g.IsRunning() {
return "", false
}
target := strings.ToLower(strings.TrimSpace(name))
if target == "" {
return "", false
}
apps := g.GetTELAApps()
// exact matches first (pick newest if multiple)
exactCandidates := make([]string, 0)
for _, app := range apps {
if dn, ok := app["display_name"].(string); ok && strings.ToLower(dn) == target {
if scid, ok := app["scid"].(string); ok && scid != "" {
exactCandidates = append(exactCandidates, scid)
}
}
if n, ok := app["name"].(string); ok && strings.ToLower(n) == target {
if scid, ok := app["scid"].(string); ok && scid != "" {
exactCandidates = append(exactCandidates, scid)
}
}
}
if scid, ok := g.pickNewestSCID(exactCandidates); ok {
return scid, true
}
// prefix match (collect candidates and pick newest)
candidates := make([]string, 0)
for _, app := range apps {
if dn, ok := app["display_name"].(string); ok && strings.HasPrefix(strings.ToLower(dn), target) {
if scid, ok := app["scid"].(string); ok && scid != "" {
candidates = append(candidates, scid)
}
} else if n, ok := app["name"].(string); ok && strings.HasPrefix(strings.ToLower(n), target) {
if scid, ok := app["scid"].(string); ok && scid != "" {
candidates = append(candidates, scid)
}
}
}
if scid, ok := g.pickNewestSCID(candidates); ok {
return scid, true
}
return "", false
}
// ResolveDURL resolves an exact dURL (case-insensitive) to a SCID, or returns false
// Handles both with and without "dero://" prefix
func (g *GnomonClient) ResolveDURL(durl string) (string, bool) {
candidates := g.ResolveDURLAll(durl)
if len(candidates) == 0 {
return "", false
}
return candidates[0], true
}
// ResolveDURLAll returns every SCID published under a dURL, best-first by the
// same ranking ResolveDURL uses.
//
// A name is not unique on chain: telatomicswaps.tela alone has 13 deployments.
// Callers that can tell a servable contract from an unservable one should walk
// this list rather than take only the top entry - see pickServableSCID.
func (g *GnomonClient) ResolveDURLAll(durl string) []string {
if !g.IsRunning() {
return nil
}
target := strings.ToLower(strings.TrimSpace(durl))
if target == "" {
return nil
}
// Normalize: remove dero:// prefix if present
targetNorm := target
targetNorm = strings.TrimPrefix(targetNorm, "dero://")
apps := g.GetTELAApps()
candidates := make([]string, 0)
for _, app := range apps {
if du, ok := app["durl"].(string); ok {
// Normalize stored dURL too
duNorm := strings.ToLower(strings.TrimSpace(du))
duNorm = strings.TrimPrefix(duNorm, "dero://")
if duNorm == targetNorm {
if scid, ok := app["scid"].(string); ok && scid != "" {
candidates = append(candidates, scid)
}
}
}
}
// Same ordering pickNewestSCID applied: highest interaction height first,
// larger SCID breaking ties so the result stays deterministic.
sort.Slice(candidates, func(i, j int) bool {
hi, hj := g.LatestInteractionHeight(candidates[i]), g.LatestInteractionHeight(candidates[j])
if hi != hj {
return hi > hj
}
return candidates[i] > candidates[j]
})
return candidates
}
// pickNewestSCID returns the candidate with the highest interaction height.
// Ties fall back to lexicographical SCID order for deterministic results.
func (g *GnomonClient) pickNewestSCID(candidates []string) (string, bool) {
if len(candidates) == 0 {
return "", false
}
best := candidates[0]
bestHeight := g.LatestInteractionHeight(best)
for _, scid := range candidates[1:] {
h := g.LatestInteractionHeight(scid)
if h > bestHeight || (h == bestHeight && scid > best) {
best = scid
bestHeight = h
}
}
return best, true
}
// GetRating fetches rating data for a SCID from Gnomon indexed data
func (g *GnomonClient) GetRating(scid string) (*RatingResult, error) {
if !g.IsRunning() {
return nil, fmt.Errorf("gnomon is not running")
}
// Get all variables for this SCID
vars := g.GetAllSCIDVariableDetails(scid)
if len(vars) == 0 {
// No data indexed yet, return empty result
return &RatingResult{
SCID: scid,
Ratings: make([]Rating, 0),
Likes: 0,
Dislikes: 0,
Average: 0.0,
Count: 0,
}, nil
}
result := &RatingResult{
SCID: scid,
Ratings: make([]Rating, 0),
Likes: 0,
Dislikes: 0,
Average: 0.0,
Count: 0,
}
// Parse variables
for _, v := range vars {
var (
key, _, value = parseVars(v)
decoded = decodeHexIfNeeded(value)
)
switch key {
case "likes":
// Parse likes count
if val, err := parseUint64Safe(decoded); err == nil {
result.Likes = val
}
case "dislikes":
// Parse dislikes count
if val, err := parseUint64Safe(decoded); err == nil {
result.Dislikes = val
}
default:
// Check if this is a rating (key is a DERO address)
if strings.HasPrefix(strings.ToLower(key), "dero") {
// Parse rating string (format: "rating_height")
parts := strings.Split(decoded, "_")
if len(parts) < 2 {
continue
}
ratingNum, err := parseUint64Safe(parts[0])
if err != nil || ratingNum > 99 {
continue
}
heightNum, err := parseUint64Safe(parts[1])
if err != nil {
continue
}
result.Ratings = append(result.Ratings, Rating{
Address: key,
Rating: ratingNum,
Height: heightNum,
})
}
}
}
// Calculate average from categories (first digit of rating)
if len(result.Ratings) > 0 {
var sum uint64
for _, r := range result.Ratings {
category := r.Rating / 10 // Extract category (0-9)
sum += category
}
result.Average = float64(sum) / float64(len(result.Ratings))
result.Count = len(result.Ratings)
}
return result, nil
}
// decodeHexIfNeeded decodes a hex string if it looks like hex, otherwise returns as-is
func decodeHexIfNeeded(s string) string {
// If already a number string, return it
if _, err := parseUint64Safe(s); err == nil {
return s
}
// Try hex decoding
return decodeHexString(s)
}
// parseUint64Safe safely parses a string to uint64
func parseUint64Safe(s string) (uint64, error) {
s = strings.TrimSpace(s)
if s == "" {
return 0, fmt.Errorf("empty string")
}
return strconv.ParseUint(s, 10, 64)
}
// SearchByKey searches all indexed SCIDs for those containing a specific key store
// Returns SCIDs with the key's values
func (g *GnomonClient) SearchByKey(key string) []map[string]any {
results := make([]map[string]any, 0)
if !g.IsRunning() {
return results
}
// Get all SCIDs
scids := g.GetAllOwnersAndSCIDs()
for scid, owner := range scids {
// Check if this SCID has the key
valuesString, valuesUint64 := g.GetSCIDValuesByKey(scid, key)
if len(valuesString) > 0 || len(valuesUint64) > 0 {
var (
// Get additional info (dURL, name)
vars = g.GetAllSCIDVariableDetails(scid)
params = map[string]any{"scid": scid, "owner": owner, "key": key}
result, _, _, _ = allocateData(vars, params)
)
// Add found values
if len(valuesString) > 0 {
result["values_string"] = valuesString
}
if len(valuesUint64) > 0 {
result["values_uint64"] = valuesUint64
}
results = append(results, result)
}
}
return results
}
// SearchByValue searches all indexed SCIDs for those containing a specific value store
// Returns SCIDs with the value's keys
func (g *GnomonClient) SearchByValue(value any) []map[string]any {
results := make([]map[string]any, 0)
if !g.IsRunning() {
return results
}
// Get all SCIDs
scids := g.GetAllOwnersAndSCIDs()
for scid, owner := range scids {
// Check if this SCID has the value
keysString, keysUint64 := g.GetSCIDKeysByValue(scid, value)
if len(keysString) > 0 || len(keysUint64) > 0 {
var (
params = map[string]any{"scid": scid, "owner": owner, "value": value}
// Get additional info (dURL, name)
vars = g.GetAllSCIDVariableDetails(scid)
result, _, _, _ = allocateData(vars, params)
)
// Add found keys
if len(keysString) > 0 {
result["keys_string"] = keysString
}
if len(keysUint64) > 0 {
result["keys_uint64"] = keysUint64
}
results = append(results, result)
}
}
return results
}
// SearchCodeLine returns all indexed SCIDs for code searching
// Note: Code search requires daemon calls - this just returns SCIDs for the caller to check