Skip to content

Commit 379d42b

Browse files
authored
Merge pull request #881 from gobitfly/staging
merge staging->main
2 parents 09e60e8 + cdb15a7 commit 379d42b

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

58 files changed

+3060
-2590
lines changed

backend/cmd/blobindexer/main.go

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,7 @@ import (
1616
func Run() {
1717
fs := flag.NewFlagSet("fs", flag.ExitOnError)
1818

19-
configFlag := fs.String("config", "config.yml", "path to config")
19+
configFlag := fs.String("config", "", "path to config")
2020
versionFlag := fs.Bool("version", false, "print version and exit")
2121
_ = fs.Parse(os.Args[2:])
2222
if *versionFlag {

backend/cmd/misc/main.go

Lines changed: 65 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,7 @@ import (
1818
"time"
1919

2020
"github.com/coocood/freecache"
21+
"github.com/davecgh/go-spew/spew"
2122
"github.com/ethereum/go-ethereum/common"
2223
"github.com/go-redis/redis/v8"
2324
"github.com/gobitfly/beaconchain/cmd/misc/commands"
@@ -32,6 +33,7 @@ import (
3233
edb "github.com/gobitfly/beaconchain/pkg/exporter/db"
3334
"github.com/gobitfly/beaconchain/pkg/exporter/modules"
3435
"github.com/gobitfly/beaconchain/pkg/exporter/services"
36+
"github.com/gobitfly/beaconchain/pkg/notification"
3537
_ "github.com/jackc/pgx/v5/stdlib"
3638
"github.com/pkg/errors"
3739
utilMath "github.com/protolambda/zrnt/eth2/util/math"
@@ -75,7 +77,7 @@ func Run() {
7577
}
7678

7779
configPath := fs.String("config", "config/default.config.yml", "Path to the config file")
78-
fs.StringVar(&opts.Command, "command", "", "command to run, available: updateAPIKey, applyDbSchema, initBigtableSchema, epoch-export, debug-rewards, debug-blocks, clear-bigtable, index-old-eth1-blocks, update-aggregation-bits, historic-prices-export, index-missing-blocks, export-epoch-missed-slots, migrate-last-attestation-slot-bigtable, export-genesis-validators, update-block-finalization-sequentially, nameValidatorsByRanges, export-stats-totals, export-sync-committee-periods, export-sync-committee-validator-stats, partition-validator-stats, migrate-app-purchases")
80+
fs.StringVar(&opts.Command, "command", "", "command to run, available: updateAPIKey, applyDbSchema, initBigtableSchema, epoch-export, debug-rewards, debug-blocks, clear-bigtable, index-old-eth1-blocks, update-aggregation-bits, historic-prices-export, index-missing-blocks, export-epoch-missed-slots, migrate-last-attestation-slot-bigtable, export-genesis-validators, update-block-finalization-sequentially, nameValidatorsByRanges, export-stats-totals, export-sync-committee-periods, export-sync-committee-validator-stats, partition-validator-stats, migrate-app-purchases, collect-notifications, collect-user-db-notifications")
7981
fs.Uint64Var(&opts.StartEpoch, "start-epoch", 0, "start epoch")
8082
fs.Uint64Var(&opts.EndEpoch, "end-epoch", 0, "end epoch")
8183
fs.Uint64Var(&opts.User, "user", 0, "user id")
@@ -181,27 +183,27 @@ func Run() {
181183
defer db.FrontendWriterDB.Close()
182184

183185
// clickhouse
184-
db.ClickHouseWriter, db.ClickHouseReader = db.MustInitDB(&types.DatabaseConfig{
185-
Username: cfg.ClickHouse.WriterDatabase.Username,
186-
Password: cfg.ClickHouse.WriterDatabase.Password,
187-
Name: cfg.ClickHouse.WriterDatabase.Name,
188-
Host: cfg.ClickHouse.WriterDatabase.Host,
189-
Port: cfg.ClickHouse.WriterDatabase.Port,
190-
MaxOpenConns: cfg.ClickHouse.WriterDatabase.MaxOpenConns,
191-
SSL: true,
192-
MaxIdleConns: cfg.ClickHouse.WriterDatabase.MaxIdleConns,
193-
}, &types.DatabaseConfig{
194-
Username: cfg.ClickHouse.ReaderDatabase.Username,
195-
Password: cfg.ClickHouse.ReaderDatabase.Password,
196-
Name: cfg.ClickHouse.ReaderDatabase.Name,
197-
Host: cfg.ClickHouse.ReaderDatabase.Host,
198-
Port: cfg.ClickHouse.ReaderDatabase.Port,
199-
MaxOpenConns: cfg.ClickHouse.ReaderDatabase.MaxOpenConns,
200-
SSL: true,
201-
MaxIdleConns: cfg.ClickHouse.ReaderDatabase.MaxIdleConns,
202-
}, "clickhouse", "clickhouse")
203-
defer db.ClickHouseReader.Close()
204-
defer db.ClickHouseWriter.Close()
186+
// db.ClickHouseWriter, db.ClickHouseReader = db.MustInitDB(&types.DatabaseConfig{
187+
// Username: cfg.ClickHouse.WriterDatabase.Username,
188+
// Password: cfg.ClickHouse.WriterDatabase.Password,
189+
// Name: cfg.ClickHouse.WriterDatabase.Name,
190+
// Host: cfg.ClickHouse.WriterDatabase.Host,
191+
// Port: cfg.ClickHouse.WriterDatabase.Port,
192+
// MaxOpenConns: cfg.ClickHouse.WriterDatabase.MaxOpenConns,
193+
// SSL: true,
194+
// MaxIdleConns: cfg.ClickHouse.WriterDatabase.MaxIdleConns,
195+
// }, &types.DatabaseConfig{
196+
// Username: cfg.ClickHouse.ReaderDatabase.Username,
197+
// Password: cfg.ClickHouse.ReaderDatabase.Password,
198+
// Name: cfg.ClickHouse.ReaderDatabase.Name,
199+
// Host: cfg.ClickHouse.ReaderDatabase.Host,
200+
// Port: cfg.ClickHouse.ReaderDatabase.Port,
201+
// MaxOpenConns: cfg.ClickHouse.ReaderDatabase.MaxOpenConns,
202+
// SSL: true,
203+
// MaxIdleConns: cfg.ClickHouse.ReaderDatabase.MaxIdleConns,
204+
// }, "clickhouse", "clickhouse")
205+
// defer db.ClickHouseReader.Close()
206+
// defer db.ClickHouseWriter.Close()
205207

206208
// Initialize the persistent redis client
207209
rdc := redis.NewClient(&redis.Options{
@@ -216,6 +218,14 @@ func Run() {
216218
db.PersistentRedisDbClient = rdc
217219
defer db.PersistentRedisDbClient.Close()
218220

221+
if utils.Config.TieredCacheProvider != "redis" {
222+
log.Fatal(nil, "no cache provider set, please set TierdCacheProvider (redis)", 0)
223+
}
224+
if utils.Config.TieredCacheProvider == "redis" || len(utils.Config.RedisCacheEndpoint) != 0 {
225+
cache.MustInitTieredCache(utils.Config.RedisCacheEndpoint)
226+
log.Infof("tiered Cache initialized, latest finalized epoch: %v", cache.LatestFinalizedEpoch.Get())
227+
}
228+
219229
switch opts.Command {
220230
case "nameValidatorsByRanges":
221231
err := nameValidatorsByRanges(opts.ValidatorNameRanges)
@@ -456,6 +466,10 @@ func Run() {
456466
err = fixEns(erigonClient)
457467
case "fix-ens-addresses":
458468
err = fixEnsAddresses(erigonClient)
469+
case "collect-notifications":
470+
err = collectNotifications(opts.StartEpoch)
471+
case "collect-user-db-notifications":
472+
err = collectUserDbNotifications(opts.StartEpoch)
459473
default:
460474
log.Fatal(nil, fmt.Sprintf("unknown command %s", opts.Command), 0)
461475
}
@@ -467,6 +481,35 @@ func Run() {
467481
}
468482
}
469483

484+
func collectNotifications(startEpoch uint64) error {
485+
epoch := startEpoch
486+
487+
log.Infof("collecting notifications for epoch %v", epoch)
488+
notifications, err := notification.GetNotificationsForEpoch(utils.Config.Notifications.PubkeyCachePath, epoch)
489+
if err != nil {
490+
return err
491+
}
492+
493+
log.Infof("found %v notifications for epoch %v with %v notifications for user 0", len(notifications), epoch, len(notifications[0]))
494+
if len(notifications[0]) > 0 {
495+
spew.Dump(notifications[0])
496+
}
497+
return nil
498+
}
499+
500+
func collectUserDbNotifications(startEpoch uint64) error {
501+
epoch := startEpoch
502+
503+
log.Infof("collecting notifications for epoch %v", epoch)
504+
notifications, err := notification.GetUserNotificationsForEpoch(utils.Config.Notifications.PubkeyCachePath, epoch)
505+
if err != nil {
506+
return err
507+
}
508+
509+
log.Infof("found %v notifications for epoch %v", len(notifications), epoch)
510+
return nil
511+
}
512+
470513
func fixEns(erigonClient *rpc.ErigonClient) error {
471514
log.Infof("command: fix-ens")
472515
addrs := []struct {

backend/cmd/monitoring/main.go

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@ import (
66

77
"github.com/gobitfly/beaconchain/pkg/commons/db"
88
"github.com/gobitfly/beaconchain/pkg/commons/log"
9+
"github.com/gobitfly/beaconchain/pkg/commons/metrics"
910
"github.com/gobitfly/beaconchain/pkg/commons/types"
1011
"github.com/gobitfly/beaconchain/pkg/commons/utils"
1112
"github.com/gobitfly/beaconchain/pkg/commons/version"
@@ -31,6 +32,15 @@ func Run() {
3132
}
3233
utils.Config = cfg
3334

35+
if utils.Config.Metrics.Enabled {
36+
go func() {
37+
log.Infof("serving metrics on %v", utils.Config.Metrics.Address)
38+
if err := metrics.Serve(utils.Config.Metrics.Address, utils.Config.Metrics.Pprof, utils.Config.Metrics.PprofExtra); err != nil {
39+
log.Fatal(err, "error serving metrics", 0)
40+
}
41+
}()
42+
}
43+
3444
db.ClickHouseWriter, db.ClickHouseReader = db.MustInitDB(&types.DatabaseConfig{
3545
Username: cfg.ClickHouse.WriterDatabase.Username,
3646
Password: cfg.ClickHouse.WriterDatabase.Password,

backend/cmd/typescript_converter/main.go

Lines changed: 69 additions & 53 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@ package typescript_converter
33
import (
44
"flag"
55
"go/ast"
6+
"iter"
67
"os"
78
"path/filepath"
89
"slices"
@@ -18,6 +19,8 @@ const (
1819
fallbackType = "any"
1920
commonFileName = "common"
2021
lintDisable = "/* eslint-disable */\n"
22+
goFileSuffix = ".go"
23+
tsFileSuffix = ".ts"
2124
)
2225

2326
// Files that should not be converted to TypeScript
@@ -65,24 +68,23 @@ func Run() {
6568
log.Fatal(nil, "Failed to load package", 0)
6669
}
6770

68-
// Find all common types
71+
// Find all common types, i.e. types that are used in multiple files and must be imported in ts
6972
commonTypes := getCommonTypes(pkgs)
70-
// Find all usages of common types
71-
usage := getCommonUsages(pkgs, commonTypes)
72-
73-
// Generate Tygo for common.go
74-
tygos := []*tygo.Tygo{tygo.New(getTygoConfig(out, commonFileName, ""))}
75-
// Generate Tygo for each file
76-
for file, typesUsed := range usage {
77-
importStr := ""
73+
// Find imports (usages of common types) for each file
74+
imports := getImports(pkgs, commonTypes)
75+
76+
var configs []*tygo.Tygo
77+
// Generate Tygo config for each file
78+
for fileName, typesUsed := range imports {
79+
var importStr string
7880
if len(typesUsed) > 0 {
7981
importStr = "import type { " + strings.Join(typesUsed, ", ") + " } from './" + commonFileName + "'\n"
8082
}
81-
tygos = append(tygos, tygo.New(getTygoConfig(out, file, importStr)))
83+
configs = append(configs, tygo.New(getTygoConfig(out, fileName, importStr)))
8284
}
8385

8486
// Generate TypeScript
85-
for _, tygo := range tygos {
87+
for _, tygo := range configs {
8688
err := tygo.Generate()
8789
if err != nil {
8890
log.Fatal(err, "Failed to generate TypeScript", 0)
@@ -93,7 +95,7 @@ func Run() {
9395
}
9496

9597
func deleteFiles(out string) error {
96-
files, err := filepath.Glob(out + "*.ts")
98+
files, err := filepath.Glob(out + "*" + tsFileSuffix)
9799
if err != nil {
98100
return err
99101
}
@@ -106,68 +108,82 @@ func deleteFiles(out string) error {
106108
return nil
107109
}
108110

109-
func getTygoConfig(out, file, frontmatter string) *tygo.Config {
111+
func getTygoConfig(outDir, fileName, frontmatter string) *tygo.Config {
110112
return &tygo.Config{
111113
Packages: []*tygo.PackageConfig{
112114
{
113115
Path: packagePath,
114116
TypeMappings: typeMappings,
115117
FallbackType: fallbackType,
116-
IncludeFiles: []string{file + ".go"},
117-
OutputPath: out + file + ".ts",
118+
IncludeFiles: []string{fileName + goFileSuffix},
119+
OutputPath: outDir + fileName + tsFileSuffix,
118120
Frontmatter: lintDisable + frontmatter,
119121
},
120122
},
121123
}
122124
}
123125

124-
// Parse common.go to find all common types
125-
func getCommonTypes(pkgs []*packages.Package) map[string]bool {
126-
commonTypes := make(map[string]bool)
127-
for _, pkg := range pkgs {
128-
for _, file := range pkg.Syntax {
129-
filename := strings.TrimSuffix(filepath.Base(pkg.Fset.File(file.Pos()).Name()), ".go")
130-
if filepath.Base(filename) != commonFileName {
131-
continue
132-
}
133-
ast.Inspect(file, func(n ast.Node) bool {
134-
if typeSpec, ok := n.(*ast.TypeSpec); ok {
135-
commonTypes[typeSpec.Name.Name] = true
126+
// Iterate over all file names and files in the packages
127+
func allFiles(pkgs []*packages.Package) iter.Seq2[string, *ast.File] {
128+
return func(yield func(string, *ast.File) bool) {
129+
for _, pkg := range pkgs {
130+
for _, file := range pkg.Syntax {
131+
fileName := filepath.Base(pkg.Fset.File(file.Pos()).Name())
132+
if !yield(fileName, file) {
133+
return
136134
}
137-
return true
138-
})
139-
return commonTypes
135+
}
140136
}
141137
}
142-
return nil
138+
}
139+
140+
// Parse common.go to find all common types
141+
func getCommonTypes(pkgs []*packages.Package) map[string]struct{} {
142+
var commonFile *ast.File
143+
// find common file
144+
for fileName, file := range allFiles(pkgs) {
145+
fileName = strings.TrimSuffix(fileName, goFileSuffix)
146+
if filepath.Base(fileName) == commonFileName {
147+
commonFile = file
148+
break
149+
}
150+
}
151+
if commonFile == nil {
152+
log.Fatal(nil, "common.go not found", 0)
153+
}
154+
commonTypes := make(map[string]struct{})
155+
// iterate over all types in common file and add them to the map
156+
for node := range ast.Preorder(commonFile) {
157+
if typeSpec, ok := node.(*ast.TypeSpec); ok {
158+
commonTypes[typeSpec.Name.Name] = struct{}{}
159+
}
160+
}
161+
return commonTypes
143162
}
144163

145164
// Parse all files to find used common types for each file
146-
func getCommonUsages(pkgs []*packages.Package, commonTypes map[string]bool) map[string][]string {
147-
usage := make(map[string][]string) // Map from file to list of commonTypes used
148-
for _, pkg := range pkgs {
149-
for _, file := range pkg.Syntax {
150-
filename := strings.TrimSuffix(filepath.Base(pkg.Fset.File(file.Pos()).Name()), ".go")
151-
if filepath.Base(filename) == commonFileName || slices.Contains(ignoredFiles, filename) {
165+
// Returns a map with file name as key and a set of common types used in the file as value
166+
func getImports(pkgs []*packages.Package, commonTypes map[string]struct{}) map[string][]string {
167+
imports := make(map[string][]string) // Map from file to set of commonTypes used
168+
imports[commonFileName] = []string{} // Add common file to map with empty set
169+
for fileName, file := range allFiles(pkgs) {
170+
fileName = strings.TrimSuffix(fileName, goFileSuffix)
171+
if filepath.Base(fileName) == commonFileName || slices.Contains(ignoredFiles, fileName) {
172+
continue
173+
}
174+
var currentFileImports []string
175+
// iterate over all struct fields in the file
176+
for node := range ast.Preorder(file) {
177+
ident, ok := node.(*ast.Ident)
178+
if !ok {
152179
continue
153180
}
154-
if _, exists := usage[filename]; !exists {
155-
usage[filename] = make([]string, 0)
181+
_, isCommonType := commonTypes[ident.Name]
182+
if isCommonType && !slices.Contains(currentFileImports, ident.Name) {
183+
currentFileImports = append(currentFileImports, ident.Name)
156184
}
157-
ast.Inspect(file, func(n ast.Node) bool {
158-
ident, ok := n.(*ast.Ident)
159-
if !ok {
160-
return true
161-
}
162-
if !commonTypes[ident.Name] {
163-
return true
164-
}
165-
if !slices.Contains(usage[filename], ident.Name) {
166-
usage[filename] = append(usage[filename], ident.Name)
167-
}
168-
return true
169-
})
170185
}
186+
imports[fileName] = currentFileImports
171187
}
172-
return usage
188+
return imports
173189
}

0 commit comments

Comments
 (0)