-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathapp_gnomon.go
More file actions
1315 lines (1134 loc) · 37.1 KB
/
Copy pathapp_gnomon.go
File metadata and controls
1315 lines (1134 loc) · 37.1 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
// Copyright 2025 HOLOGRAM Project. All rights reserved.
// Gnomon & App Discovery - Extracted from app.go for organization
// Session 87: Domain splitting
package main
import (
"context"
"encoding/base64"
"encoding/hex"
"fmt"
"math/rand"
"os"
"sort"
"strings"
"time"
"github.com/wailsapp/wails/v2/pkg/runtime"
)
// Gnomon Functions
// isValidSCID checks if a string looks like a valid SCID (64 hex characters)
func isValidSCID(s string) bool {
s = strings.TrimSpace(s)
if len(s) != 64 {
return false
}
// Check if it's all hex characters
for _, c := range s {
if !((c >= '0' && c <= '9') || (c >= 'a' && c <= 'f') || (c >= 'A' && c <= 'F')) {
return false
}
}
return true
}
// isURL checks if a string looks like a URL (with or without protocol)
func isURL(s string) bool {
s = strings.TrimSpace(s)
// Check for explicit protocols
if strings.HasPrefix(s, "http://") || strings.HasPrefix(s, "https://") || strings.HasPrefix(s, "ipfs://") {
return true
}
// Check for URLs without protocol (www. or contains common TLDs with path)
if strings.HasPrefix(s, "www.") {
return true
}
// Check for domain patterns like example.com/path
if strings.Contains(s, ".") && strings.Contains(s, "/") && !strings.Contains(s, " ") {
parts := strings.Split(s, ".")
if len(parts) >= 2 {
// Likely a domain
return true
}
}
return false
}
// tryConvertRawBytesToSCID attempts to convert 32 raw bytes to a 64-char hex SCID
func tryConvertRawBytesToSCID(s string) string {
// If the string is exactly 32 bytes and contains non-printable characters,
// it might be raw SCID bytes that need to be converted to hex
if len(s) == 32 {
hasNonPrintable := false
for _, c := range s {
if c < 32 || c > 126 {
hasNonPrintable = true
break
}
}
if hasNonPrintable {
// Convert raw bytes to hex string
return hex.EncodeToString([]byte(s))
}
}
return s
}
// resolveIconSCID fetches an SVG icon from a DOC SCID and returns a data URL
// If the icon is already a URL, returns it as-is
// If the icon is a SCID but can't be resolved, returns empty string to trigger fallback
func (a *App) resolveIconSCID(iconValue string) string {
iconValue = strings.TrimSpace(iconValue)
if iconValue == "" {
return ""
}
// Try to convert raw bytes to SCID if needed
iconValue = tryConvertRawBytesToSCID(iconValue)
// If it's a URL with protocol, return as-is
if strings.HasPrefix(iconValue, "http://") || strings.HasPrefix(iconValue, "https://") || strings.HasPrefix(iconValue, "ipfs://") {
return iconValue
}
// If it's a URL without protocol (www. or domain/path), add https://
if isURL(iconValue) {
return "https://" + iconValue
}
// If it doesn't look like a SCID (64 hex chars), return empty to use fallback
if !isValidSCID(iconValue) {
// Only log if it's not empty and not too short (avoid logging noise)
if len(iconValue) > 3 {
// Truncate for logging to avoid binary spam
logVal := iconValue
if len(logVal) > 20 {
logVal = logVal[:20] + "..."
}
// Check if it's printable
isPrintable := true
for _, c := range logVal {
if c < 32 || c > 126 {
isPrintable = false
break
}
}
if isPrintable {
a.logToConsole(fmt.Sprintf("[ICON] Value is not a valid SCID or URL: %s", logVal))
} else {
a.logToConsole(fmt.Sprintf("[ICON] Value is binary data (len=%d), cannot use as icon", len(iconValue)))
}
}
return "" // Return empty to trigger fallback
}
a.logToConsole(fmt.Sprintf("[ICON] Resolving icon SCID: %s...", iconValue[:16]))
// Try to fetch the DOC content
scData, err := a.fetchSmartContract(iconValue, true, true)
if err != nil {
a.logToConsole(fmt.Sprintf("[ICON] Failed to fetch icon SCID %s: %v", iconValue[:16], err))
return "" // Return empty to trigger fallback icon
}
stringKeys, ok := scData["stringkeys"].(map[string]interface{})
if !ok {
a.logToConsole(fmt.Sprintf("[ICON] No stringkeys in SCID %s", iconValue[:16]))
return ""
}
// Verify it's an image DOC type
docTypeHex, _ := stringKeys["docType"].(string)
docType := ""
if docTypeHex != "" {
if decoded, err := hex.DecodeString(docTypeHex); err == nil {
docType = string(decoded)
} else {
docType = docTypeHex // Maybe it's not hex-encoded
}
}
a.logToConsole(fmt.Sprintf("[ICON] SCID %s docType: %s", iconValue[:16], docType))
// Only process SVG/STATIC types (be more lenient)
isImageType := strings.Contains(strings.ToUpper(docType), "STATIC") ||
strings.Contains(strings.ToLower(docType), "svg") ||
strings.Contains(strings.ToLower(docType), "image")
if docType != "" && !isImageType {
a.logToConsole(fmt.Sprintf("[ICON] SCID %s is not an image type: %s", iconValue[:16], docType))
return ""
}
// Get the code (actual file content)
code, ok := scData["code"].(string)
if !ok {
a.logToConsole(fmt.Sprintf("[ICON] No code in SCID %s", iconValue[:16]))
return ""
}
// Extract file content from smart contract comment block
fileContent := extractFileContentFromCode(code)
if fileContent == "" {
a.logToConsole(fmt.Sprintf("[ICON] Could not extract file content from SCID %s", iconValue[:16]))
return ""
}
a.logToConsole(fmt.Sprintf("[ICON] Extracted %d bytes from SCID %s", len(fileContent), iconValue[:16]))
// Check for gzip compression by looking at filename
fileNameHex, _ := stringKeys["var_header_name"].(string)
if fileNameHex == "" {
fileNameHex, _ = stringKeys["nameHdr"].(string)
}
fileName := ""
if fileNameHex != "" {
if decoded, err := hex.DecodeString(fileNameHex); err == nil {
fileName = string(decoded)
} else {
fileName = fileNameHex
}
}
// Decompress if needed
if strings.HasSuffix(fileName, ".gz") {
a.logToConsole(fmt.Sprintf("[ICON] Decompressing gzipped content from %s", iconValue[:16]))
decompressed, err := decompressGzip(fileContent)
if err == nil {
fileContent = decompressed
} else {
a.logToConsole(fmt.Sprintf("[ICON] Decompression failed for %s: %v", iconValue[:16], err))
}
}
// Validate it looks like SVG
trimmed := strings.TrimSpace(fileContent)
if !strings.HasPrefix(trimmed, "<?xml") && !strings.HasPrefix(trimmed, "<svg") {
a.logToConsole(fmt.Sprintf("[ICON] SCID %s content is not valid SVG (starts with: %.50s...)", iconValue[:16], trimmed))
return ""
}
// Validate SVG has required attributes
if !strings.Contains(trimmed, "xmlns") {
a.logToConsole(fmt.Sprintf("[ICON] SCID %s SVG missing xmlns attribute", iconValue[:16]))
return ""
}
// Success! Return as data URL
// Use URL-safe base64 and properly encode SVG
svgContent := strings.TrimSpace(fileContent)
encoded := base64.StdEncoding.EncodeToString([]byte(svgContent))
dataURL := fmt.Sprintf("data:image/svg+xml;base64,%s", encoded)
a.logToConsole(fmt.Sprintf("[ICON] Successfully resolved SCID %s to data URL (%d bytes encoded)", iconValue[:16], len(encoded)))
return dataURL
}
func (a *App) StartGnomon() map[string]interface{} {
a.logToConsole("[START] Starting Gnomon indexer...")
endpoint := "http://127.0.0.1:10102"
if ep, ok := a.settings["daemon_endpoint"].(string); ok && ep != "" {
endpoint = ep
}
network := "mainnet"
if net, ok := a.settings["network"].(string); ok && net != "" {
network = net
}
a.logToConsole(fmt.Sprintf("[Gnomon] Connecting to daemon: %s (network: %s)", endpoint, network))
// Privacy Mode: Gnomon's indexer dials the daemon over its own WebSocket (no
// dialer hook), so validate the endpoint before Start opens that socket.
if !a.checkDaemonEndpointPolicy(endpoint) {
return ErrorResponse(fmt.Errorf("daemon endpoint %s blocked by Privacy Mode (allowlist the host to permit it)", endpoint))
}
// One-time index migration: if the search-filter set changed since this DB was
// built (e.g. a build that widened discovery to include tokens/NFAs), the new
// filter would only apply to blocks indexed going forward — Gnomon never
// re-examines already-indexed history. Clean the existing DB so the upcoming
// Start re-fastsyncs the full SC snapshot under the new filter. Skipped on a
// fresh DB (nothing indexed yet) and when the version already matches.
a.migrateGnomonFilterVersionIfNeeded(network)
err := a.gnomonClient.Start(endpoint, network)
if err != nil {
a.logToConsole(fmt.Sprintf("[ERR] Gnomon start failed: %v", err))
return ErrorResponse(err)
}
a.logToConsole("[OK] Gnomon indexer started successfully")
a.settings["gnomon_enabled"] = true
// Record the filter version now that the index is (re)building under it, so the
// migration above fires at most once per filter change.
writeFilterVersion(network)
// Start a connection monitor goroutine to provide feedback
go a.monitorGnomonConnection(endpoint)
return map[string]interface{}{
"success": true,
"message": "Gnomon indexer started",
}
}
// migrateGnomonFilterVersionIfNeeded performs the one-time index reset when the
// active search-filter set differs from the one a network's existing index was
// built with. It cleans the DB so the next Start re-fastsyncs under the new
// filter; the new version is written by StartGnomon after a successful start.
// No-op on a fresh DB (no stored version) or when the version already matches.
func (a *App) migrateGnomonFilterVersionIfNeeded(network string) {
stored := readStoredFilterVersion(network)
if stored == "" {
// Fresh DB, or a pre-versioning index. For a pre-versioning index we DO
// want to migrate (its filter predates token discovery), but only if it
// actually holds data — otherwise there's nothing to re-index.
dir, err := gnomonDBDir(network)
if err != nil {
return
}
if _, statErr := os.Stat(dir); os.IsNotExist(statErr) {
return // truly fresh — nothing to migrate
}
} else if stored == currentFilterVersion() {
return // already on the current filter — nothing to do
}
a.logToConsole("[Gnomon] Token discovery filter changed — re-indexing once so held tokens/NFAs are detected...")
// Surface a one-time progress signal so the UI can show "Updating token index…"
// rather than appearing to hang during the re-fastsync.
if a.ctx != nil {
runtime.EventsEmit(a.ctx, "gnomon:reindexing", map[string]interface{}{
"reason": "filter-version-change",
"network": network,
})
}
if a.gnomonClient.IsRunning() {
a.StopGnomon()
}
if err := a.gnomonClient.CleanDB(network); err != nil {
// Non-fatal: if the clean fails the index just keeps its old coverage; the
// next start still proceeds. Log so it's visible.
a.logToConsole(fmt.Sprintf("[Gnomon] Filter-change re-index: clean failed (%v) — continuing with existing index", err))
}
}
// monitorGnomonConnection provides user feedback when Gnomon is stuck connecting
func (a *App) monitorGnomonConnection(endpoint string) {
connectionWarned := false
connectedLogged := false
checkInterval := 5 * time.Second
warningThreshold := 15 * time.Second
startTime := time.Now()
for {
time.Sleep(checkInterval)
// Check if Gnomon is still running
if !a.gnomonClient.IsRunning() {
return // Gnomon was stopped, exit monitor
}
status := a.gnomonClient.GetStatus()
chainHeight, _ := status["chain_height"].(int64)
connecting, _ := status["connecting"].(bool)
if connecting || chainHeight == 0 {
elapsed := time.Since(startTime)
if elapsed > warningThreshold && !connectionWarned {
a.logToConsole(fmt.Sprintf("[Gnomon] Still connecting to %s... (waiting %.0fs)", endpoint, elapsed.Seconds()))
connectionWarned = true
}
} else {
// Connected! Log once and exit monitor
if !connectedLogged {
a.logToConsole(fmt.Sprintf("[Gnomon] Connected to daemon, chain height: %d", chainHeight))
connectedLogged = true
}
return // Successfully connected, exit monitor
}
// Safety timeout - stop monitoring after 5 minutes
if time.Since(startTime) > 5*time.Minute {
if !connectedLogged {
a.logToConsole("[Gnomon] Connection monitor timeout - check if daemon endpoint is correct")
}
return
}
}
}
func (a *App) StopGnomon() map[string]interface{} {
a.logToConsole("[STOP] Stopping Gnomon indexer...")
a.gnomonClient.Stop()
a.settings["gnomon_enabled"] = false
a.logToConsole("[OK] Gnomon indexer stopped")
return map[string]interface{}{
"success": true,
"message": "Gnomon indexer stopped",
}
}
func (a *App) GetGnomonStatus() map[string]interface{} {
status := a.gnomonClient.GetStatus()
return map[string]interface{}{
"success": true,
"status": status,
}
}
// SetGnomonAutostart enables or disables automatic Gnomon startup
func (a *App) SetGnomonAutostart(enabled bool) map[string]interface{} {
a.settings["gnomon_autostart"] = enabled
if enabled {
a.logToConsole("[GNOMON] Auto-start enabled - Gnomon will start automatically on app launch")
} else {
a.logToConsole("[GNOMON] Auto-start disabled")
}
return map[string]interface{}{
"success": true,
"enabled": enabled,
"message": fmt.Sprintf("Gnomon auto-start %s", map[bool]string{true: "enabled", false: "disabled"}[enabled]),
}
}
// GetGnomonAutostart returns the current auto-start setting
func (a *App) GetGnomonAutostart() bool {
if autostart, ok := a.settings["gnomon_autostart"].(bool); ok {
return autostart
}
return false
}
// AddSCIDToIndex is the Wails-bound frontend entry point for Bug #1 resolution.
// Manually indexes a SCID that the default search filter didn't catch.
//
// This implements civilware's feat-addscidtoindex-wsserver feature. Typical flow:
// a developer deploys a TELA app, HOLOGRAM's fastsync misses it (deployed before
// Gnomon started), the dev pastes the SCID into Studio > Add SCID and hits
// "Add to Index" — this method fetches the SC via RPC, stores its variables,
// and makes it discoverable.
func (a *App) AddSCIDToIndex(scid string) map[string]interface{} {
if a.gnomonClient == nil || !a.gnomonClient.IsRunning() {
return map[string]interface{}{
"success": false,
"error": "Gnomon is not running — start it first",
}
}
scid = strings.TrimSpace(scid)
if !isValidSCID(scid) {
return map[string]interface{}{
"success": false,
"error": "Invalid SCID: expected 64 hex characters",
}
}
// varstoreonly=true is load-bearing: the indexer only stores a SCID's variables
// if its code matches the search filter OR varstoreonly is set. This button's
// whole purpose is indexing contracts the TELA filter didn't catch (NFAs, older
// deploys), and those fail the filter re-check too — with varstoreonly=false the
// add "succeeds" but stores zero variables. true bypasses the filter and stores
// vars directly, matching Engram's getContractHeader and the wallet add path.
// skipfsrecheck=false still fetches code+vars via RPC for validation.
err := a.gnomonClient.AddSCIDToIndex(scid, true, false)
if err != nil {
a.logToConsole(fmt.Sprintf("[GNOMON] AddSCIDToIndex failed: %v", err))
return map[string]interface{}{
"success": false,
"error": err.Error(),
}
}
a.logToConsole(fmt.Sprintf("[GNOMON] AddSCIDToIndex %s... success", scid[:16]))
// Fetch the newly indexed data to return useful info to the UI
vars := a.gnomonClient.GetAllSCIDVariableDetails(scid)
varCount := len(vars)
// Extract basic metadata from variables
result := map[string]interface{}{
"success": true,
"scid": scid,
"vars_count": varCount,
}
// A 0-var result with Gnomon still behind the chain tip usually means the
// fetch ran against a stale height, not that the contract is empty — the
// indexer reports success either way, so surface the distinction for the UI.
if varCount == 0 {
if status := a.gnomonClient.GetStatus(); status != nil {
indexed, _ := status["indexed_height"].(int64)
chain, _ := status["chain_height"].(int64)
if chain > 0 && indexed < chain-5 {
result["gnomonSyncing"] = true
result["syncProgress"] = status["progress"]
}
}
}
// Parse TELA metadata if available
data := map[string]any{"scid": scid}
app, isIndex, isDOC, _ := allocateData(vars, data)
if name, ok := app["name"].(string); ok && name != "" {
result["name"] = name
}
if desc, ok := app["description"].(string); ok && desc != "" {
result["description"] = desc
}
if durl, ok := app["durl"].(string); ok && durl != "" {
result["durl"] = durl
}
if owner, ok := app["owner"].(string); ok && owner != "" {
result["owner"] = owner
}
// Determine class/type
if isIndex {
result["class"] = "INDEX"
} else if isDOC {
result["class"] = "DOC"
} else {
result["class"] = "SC"
}
return result
}
// SearchByKey searches all indexed SCIDs for those containing a specific key
func (a *App) SearchByKey(key string) map[string]interface{} {
a.logToConsole(fmt.Sprintf("[...] Searching by key: %s", key))
if !a.gnomonClient.IsRunning() {
return map[string]interface{}{
"success": false,
"error": "Gnomon is not running. Start it in Settings to search.",
"results": []map[string]interface{}{},
}
}
if key == "" {
return map[string]interface{}{
"success": false,
"error": "Key cannot be empty",
"results": []map[string]interface{}{},
}
}
results := a.gnomonClient.SearchByKey(key)
a.logToConsole(fmt.Sprintf("[OK] Found %d SCIDs containing key '%s'", len(results), key))
return map[string]interface{}{
"success": true,
"key": key,
"results": results,
"count": len(results),
}
}
// SearchByValue searches all indexed SCIDs for those containing a specific value
func (a *App) SearchByValue(value string) map[string]interface{} {
a.logToConsole(fmt.Sprintf("[...] Searching by value: %s", value))
if !a.gnomonClient.IsRunning() {
return map[string]interface{}{
"success": false,
"error": "Gnomon is not running. Start it in Settings to search.",
"results": []map[string]interface{}{},
}
}
if value == "" {
return map[string]interface{}{
"success": false,
"error": "Value cannot be empty",
"results": []map[string]interface{}{},
}
}
results := a.gnomonClient.SearchByValue(value)
a.logToConsole(fmt.Sprintf("[OK] Found %d SCIDs containing value '%s'", len(results), value))
return map[string]interface{}{
"success": true,
"value": value,
"results": results,
"count": len(results),
}
}
// SearchCodeLine searches all indexed smart contracts for a specific line of code
func (a *App) SearchCodeLine(line string) map[string]interface{} {
result := a.searchCodeLineWrapper("code:" + line)
if result.Success {
return map[string]interface{}{
"success": true,
"line": line,
"results": result.Data["results"],
"count": result.Data["count"],
}
}
return map[string]interface{}{
"success": false,
"error": result.Error,
"results": []map[string]interface{}{},
}
}
// CleanGnomonDB deletes the Gnomon database for a specific network
func (a *App) CleanGnomonDB(network string) map[string]interface{} {
a.logToConsole(fmt.Sprintf("[Gnomon] Cleaning DB for network: %s", network))
if a.gnomonClient.IsRunning() {
return map[string]interface{}{
"success": false,
"error": "Gnomon must be stopped before cleaning the database. Stop it first.",
}
}
if network == "" {
return map[string]interface{}{
"success": false,
"error": "Network must be specified (mainnet or simulator)",
}
}
validNetworks := []string{"mainnet", "simulator"}
isValid := false
for _, n := range validNetworks {
if n == network {
isValid = true
break
}
}
if !isValid {
return map[string]interface{}{
"success": false,
"error": "Invalid network. Must be mainnet or simulator",
}
}
err := a.gnomonClient.CleanDB(network)
if err != nil {
a.logToConsole(fmt.Sprintf("[ERR] CleanGnomonDB failed: %v", err))
return ErrorResponse(err)
}
a.logToConsole(fmt.Sprintf("[OK] Gnomon DB cleaned for %s", network))
return map[string]interface{}{
"success": true,
"network": network,
"message": fmt.Sprintf("Gnomon database for %s has been deleted. Restart Gnomon to re-sync.", network),
}
}
// ResyncGnomon stops Gnomon, cleans the DB, and restarts it
// By default, uses fastsync to start from near the current height (fast)
// Use ResyncGnomonFromHeight for a specific starting block
func (a *App) ResyncGnomon() map[string]interface{} {
network := a.getNetworkName()
a.logToConsole(fmt.Sprintf("[Gnomon] Resyncing for %s...", network))
if a.gnomonClient.IsRunning() {
a.StopGnomon()
}
err := a.gnomonClient.CleanDB(network)
if err != nil {
a.logToConsole(fmt.Sprintf("[WARN] Could not clean DB: %v", err))
}
// Use fastsync by default for quick resync
// This starts from near the current chain height
a.logToConsole("[Gnomon] Using fastsync for quick resync")
result := a.StartGnomon()
if success, ok := result["success"].(bool); ok && success {
return map[string]interface{}{
"success": true,
"network": network,
"message": fmt.Sprintf("Gnomon resync started for %s (fastsync)", network),
}
}
return result
}
// ResyncGnomonFromHeight stops Gnomon, cleans the DB, and restarts from a specific block height
// This is useful for finding recently deployed contracts without indexing the entire chain
func (a *App) ResyncGnomonFromHeight(height int64) map[string]interface{} {
network := a.getNetworkName()
a.logToConsole(fmt.Sprintf("[Gnomon] Resyncing for %s from height %d...", network, height))
if a.gnomonClient.IsRunning() {
a.StopGnomon()
}
err := a.gnomonClient.CleanDB(network)
if err != nil {
a.logToConsole(fmt.Sprintf("[WARN] Could not clean DB: %v", err))
}
// Disable fastsync and set the specific start height
a.gnomonClient.SetDisableFastsync(true)
a.gnomonClient.SetStartFromHeight(height)
a.logToConsole(fmt.Sprintf("[Gnomon] Will start indexing from block %d", height))
result := a.StartGnomon()
if success, ok := result["success"].(bool); ok && success {
return map[string]interface{}{
"success": true,
"network": network,
"startHeight": height,
"message": fmt.Sprintf("Gnomon resync started for %s from block %d", network, height),
}
}
return result
}
// getNetworkName returns the current network name
func (a *App) getNetworkName() string {
if a.IsInSimulatorMode() {
return "simulator"
}
// A16: read the real settings key ("network"), which every writer uses — the old
// "network_mode" key is never written, so this branch was dead and the panel was
// pinned to mainnet even while a simulator index was live.
if net, ok := a.settings["network"].(string); ok {
if net == "simulator" {
return "simulator"
}
}
return "mainnet"
}
// EnsureGnomonRunning starts Gnomon if not already running
func (a *App) EnsureGnomonRunning() map[string]interface{} {
if a.gnomonClient.IsRunning() {
return map[string]interface{}{
"success": true,
"alreadyRunning": true,
"message": "Gnomon is already running",
}
}
a.logToConsole("[NET] Lazy-starting Gnomon indexer (on demand)...")
return a.StartGnomon()
}
func (a *App) GetDiscoveredApps() map[string]interface{} {
if !a.gnomonClient.IsRunning() {
return map[string]interface{}{
"success": false,
"error": "Gnomon is not running",
"apps": []map[string]interface{}{},
}
}
apps := a.gnomonClient.GetTELAApps()
tagStore := InitSCIDTagStore()
epochCount := 0
for i, app := range apps {
if scid, ok := app["scid"].(string); ok && scid != "" {
rating, err := a.gnomonClient.GetRating(scid)
if err == nil && rating != nil {
apps[i]["rating"] = map[string]interface{}{
"average": rating.Average,
"count": rating.Count,
"likes": rating.Likes,
"dislikes": rating.Dislikes,
}
}
supportsEpoch := a.gnomonClient.CheckAppSupportsEpoch(scid)
apps[i]["supports_epoch"] = supportsEpoch
if supportsEpoch {
apps[i]["epoch_badge"] = "EPOCH Enabled"
epochCount++
}
// Resolve SCID icons to data URLs
if icon, ok := app["icon"].(string); ok && icon != "" {
resolved := a.resolveIconSCID(icon)
apps[i]["icon"] = resolved
}
// Attach tag/class metadata from tag store (Simple-Gnomon feature)
if meta := tagStore.GetMetadata(scid); meta != nil {
apps[i]["class"] = meta.Class
apps[i]["tags"] = meta.Tags
}
}
}
a.logToConsole(fmt.Sprintf("[Gnomon] Found %d TELA apps (%d with EPOCH support)", len(apps), epochCount))
// Mark apps as loaded - this signals to the frontend that the expensive
// GetDiscoveredApps operation has completed at least once
a.gnomonClient.SetAppsLoaded(true)
return map[string]interface{}{
"success": true,
"apps": apps,
"count": len(apps),
}
}
// GetTELALibraries returns all TELA content tagged as libraries
func (a *App) GetTELALibraries() map[string]interface{} {
if !a.gnomonClient.IsRunning() {
return map[string]interface{}{
"success": false,
"error": "Gnomon is not running. Start it in Settings to discover libraries.",
"libraries": []map[string]interface{}{},
}
}
libs := a.gnomonClient.GetTELALibraries()
for i, lib := range libs {
if scid, ok := lib["scid"].(string); ok && scid != "" {
rating, err := a.gnomonClient.GetRating(scid)
if err == nil && rating != nil {
libs[i]["rating"] = map[string]interface{}{
"average": rating.Average,
"count": rating.Count,
"likes": rating.Likes,
"dislikes": rating.Dislikes,
}
}
// Resolve SCID icons to data URLs
if icon, ok := lib["icon"].(string); ok && icon != "" {
resolved := a.resolveIconSCID(icon)
libs[i]["icon"] = resolved
}
}
}
a.logToConsole(fmt.Sprintf("[Gnomon] Found %d TELA libraries", len(libs)))
return map[string]interface{}{
"success": true,
"libraries": libs,
"count": len(libs),
}
}
// GetRandomSmartContracts returns a random sample of smart contracts
func (a *App) GetRandomSmartContracts(limit int) map[string]interface{} {
if limit <= 0 {
limit = 10
}
if !a.gnomonClient.IsRunning() {
return map[string]interface{}{
"success": false,
"error": "Gnomon is not running. Start it in Settings to discover contracts.",
}
}
allSCs := a.gnomonClient.GetAllOwnersAndSCIDs()
if len(allSCs) == 0 {
return map[string]interface{}{
"success": false,
"error": "No smart contracts found in index.",
}
}
type scInfo struct {
scid string
owner string
}
scs := make([]scInfo, 0, len(allSCs))
for scid, owner := range allSCs {
scs = append(scs, scInfo{scid, owner})
}
rand.Seed(time.Now().UnixNano())
for i := len(scs) - 1; i > 0; i-- {
j := rand.Intn(i + 1)
scs[i], scs[j] = scs[j], scs[i]
}
if len(scs) > limit {
scs = scs[:limit]
}
results := make([]map[string]interface{}, len(scs))
for i, sc := range scs {
results[i] = map[string]interface{}{
"scid": sc.scid,
"owner": sc.owner,
}
}
a.logToConsole(fmt.Sprintf("[Gnomon] Random SC discovery: Found %d contracts (from %d total)", len(results), len(allSCs)))
return map[string]interface{}{
"success": true,
"contracts": results,
"total": len(allSCs),
}
}
func (a *App) SearchApps(query string) map[string]interface{} {
if !a.gnomonClient.IsRunning() {
return map[string]interface{}{
"success": false,
"error": "Gnomon is not running",
"apps": []map[string]interface{}{},
}
}
results := a.gnomonClient.SearchTELApps(query)
a.logToConsole(fmt.Sprintf("[...] Search for '%s' returned %d results", query, len(results)))
return map[string]interface{}{
"success": true,
"query": query,
"results": results,
"count": len(results),
}
}
func (a *App) GetAppDetails(scid string) map[string]interface{} {
if !a.gnomonClient.IsRunning() {
return map[string]interface{}{
"success": false,
"error": "Gnomon is not running",
}
}
vars := a.gnomonClient.GetAllSCIDVariableDetails(scid)
details := map[string]interface{}{
"scid": scid,
}
for _, v := range vars {
key := fmt.Sprintf("%v", v.Key)
value := fmt.Sprintf("%v", v.Value)
switch key {
// V2 headers (TELA standard) - check first
case "var_header_name":
details["name"] = decodeHexString(value)
case "var_header_description":
details["description"] = decodeHexString(value)
case "var_header_icon":
details["icon"] = decodeHexString(value)
// V1 headers (ART-NFA standard) - fallback if V2 not set
case "nameHdr":
if details["name"] == nil {
details["name"] = decodeHexString(value)
}
case "descrHdr":
if details["description"] == nil {
details["description"] = decodeHexString(value)
}
case "iconURLHdr":
if details["icon"] == nil {
details["icon"] = decodeHexString(value)
}
case "dURL":
du := decodeHexString(value)
details["url"] = du
details["durl"] = du
case "owner":
details["owner"] = value
}
}
return map[string]interface{}{
"success": true,
"details": details,
}
}
// GetAppRating fetches rating data for a SCID
func (a *App) GetAppRating(scid string) map[string]interface{} {
a.logToConsole(fmt.Sprintf("[STATS] Fetching rating for: %s", scid[:16]+"..."))
result, err := a.GetRatingResultForSCID(scid)
if err != nil {
a.logToConsole(fmt.Sprintf("[WARN] Rating fetch failed: %v", err))
return map[string]interface{}{
"success": false,
"error": err.Error(),
}
}
badge := GetRatingBadgeHTML(result)
category := ""
color := "#6b7280"
categoryNum := uint64(0)
if result.Count > 0 {
category, _, categoryNum, _ = ParseRating(uint64(result.Average * 10))
color = GetRatingColor(categoryNum)
}
a.logToConsole(fmt.Sprintf("[OK] Rating: %.1f/10 (%d ratings)", result.Average, result.Count))
return map[string]interface{}{
"success": true,
"scid": scid,
"average": result.Average,
"count": result.Count,