-
Notifications
You must be signed in to change notification settings - Fork 212
/
node.go
1880 lines (1725 loc) · 53.2 KB
/
node.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
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 node contains the main executable for go-spacemesh node
package node
import (
"bytes"
"context"
"encoding/hex"
"errors"
"fmt"
"net/http"
"net/url"
"os"
"os/signal"
"path/filepath"
"runtime"
"sort"
"syscall"
"time"
"github.com/gofrs/flock"
pyroscope "github.com/grafana/pyroscope-go"
grpc_logsettable "github.com/grpc-ecosystem/go-grpc-middleware/logging/settable"
grpczap "github.com/grpc-ecosystem/go-grpc-middleware/logging/zap"
"github.com/mitchellh/mapstructure"
"github.com/spacemeshos/poet/server"
"github.com/spacemeshos/post/verifying"
"github.com/spf13/afero"
"github.com/spf13/cobra"
"github.com/spf13/viper"
"go.uber.org/zap"
"go.uber.org/zap/zapcore"
"golang.org/x/sync/errgroup"
"github.com/spacemeshos/go-spacemesh/activation"
"github.com/spacemeshos/go-spacemesh/api/grpcserver"
"github.com/spacemeshos/go-spacemesh/atxsdata"
"github.com/spacemeshos/go-spacemesh/beacon"
"github.com/spacemeshos/go-spacemesh/blocks"
"github.com/spacemeshos/go-spacemesh/bootstrap"
"github.com/spacemeshos/go-spacemesh/checkpoint"
"github.com/spacemeshos/go-spacemesh/cmd"
"github.com/spacemeshos/go-spacemesh/codec"
"github.com/spacemeshos/go-spacemesh/common/types"
"github.com/spacemeshos/go-spacemesh/config"
"github.com/spacemeshos/go-spacemesh/config/presets"
"github.com/spacemeshos/go-spacemesh/datastore"
"github.com/spacemeshos/go-spacemesh/events"
"github.com/spacemeshos/go-spacemesh/fetch"
vm "github.com/spacemeshos/go-spacemesh/genvm"
"github.com/spacemeshos/go-spacemesh/hare/eligibility"
"github.com/spacemeshos/go-spacemesh/hare3"
"github.com/spacemeshos/go-spacemesh/hare3/compat"
"github.com/spacemeshos/go-spacemesh/hash"
"github.com/spacemeshos/go-spacemesh/layerpatrol"
"github.com/spacemeshos/go-spacemesh/log"
"github.com/spacemeshos/go-spacemesh/malfeasance"
"github.com/spacemeshos/go-spacemesh/mesh"
"github.com/spacemeshos/go-spacemesh/metrics"
"github.com/spacemeshos/go-spacemesh/metrics/public"
"github.com/spacemeshos/go-spacemesh/miner"
"github.com/spacemeshos/go-spacemesh/node/mapstructureutil"
"github.com/spacemeshos/go-spacemesh/p2p"
"github.com/spacemeshos/go-spacemesh/p2p/handshake"
"github.com/spacemeshos/go-spacemesh/p2p/pubsub"
"github.com/spacemeshos/go-spacemesh/proposals"
"github.com/spacemeshos/go-spacemesh/prune"
"github.com/spacemeshos/go-spacemesh/signing"
"github.com/spacemeshos/go-spacemesh/sql"
"github.com/spacemeshos/go-spacemesh/sql/activesets"
"github.com/spacemeshos/go-spacemesh/sql/layers"
"github.com/spacemeshos/go-spacemesh/sql/localsql"
dbmetrics "github.com/spacemeshos/go-spacemesh/sql/metrics"
"github.com/spacemeshos/go-spacemesh/syncer"
"github.com/spacemeshos/go-spacemesh/syncer/atxsync"
"github.com/spacemeshos/go-spacemesh/syncer/blockssync"
"github.com/spacemeshos/go-spacemesh/system"
"github.com/spacemeshos/go-spacemesh/timesync"
timeCfg "github.com/spacemeshos/go-spacemesh/timesync/config"
"github.com/spacemeshos/go-spacemesh/timesync/peersync"
"github.com/spacemeshos/go-spacemesh/tortoise"
"github.com/spacemeshos/go-spacemesh/txs"
)
const (
edKeyFileName = "key.bin"
genesisFileName = "genesis.json"
dbFile = "state.sql"
localDbFile = "node_state.sql"
)
// Logger names.
const (
ClockLogger = "clock"
P2PLogger = "p2p"
PostLogger = "post"
PostServiceLogger = "postService"
StateDbLogger = "stateDbStore"
BeaconLogger = "beacon"
CachedDBLogger = "cachedDB"
PoetDbLogger = "poetDb"
TrtlLogger = "trtl"
ATXHandlerLogger = "atxHandler"
MeshLogger = "mesh"
SyncLogger = "sync"
HareOracleLogger = "hareOracle"
HareLogger = "hare"
BlockCertLogger = "blockCert"
BlockGenLogger = "blockGenerator"
BlockHandlerLogger = "blockHandler"
TxHandlerLogger = "txHandler"
ProposalBuilderLogger = "proposalBuilder"
ProposalListenerLogger = "proposalListener"
NipostBuilderLogger = "nipostBuilder"
NipostValidatorLogger = "nipostValidator"
Fetcher = "fetcher"
TimeSyncLogger = "timesync"
VMLogger = "vm"
GRPCLogger = "grpc"
ConStateLogger = "conState"
ExecutorLogger = "executor"
MalfeasanceLogger = "malfeasance"
BootstrapLogger = "bootstrap"
)
func GetCommand() *cobra.Command {
c := &cobra.Command{
Use: "node",
Short: "start node",
Run: func(c *cobra.Command, args []string) {
conf, err := loadConfig(c)
if err != nil {
log.With().Fatal("failed to initialize config", log.Err(err))
}
if conf.LOGGING.Encoder == config.JSONLogEncoder {
log.JSONLog(true)
}
if cmd.NoMainNet && onMainNet(conf) && !conf.NoMainOverride {
log.With().Fatal("this is a testnet-only build not intended for mainnet")
}
app := New(
WithConfig(conf),
// NOTE(dshulyak) this needs to be max level so that child logger can can be current level or below.
// otherwise it will fail later when child logger will try to increase level.
WithLog(log.RegisterHooks(
log.NewWithLevel("node", zap.NewAtomicLevelAt(zap.DebugLevel)),
events.EventHook()),
),
)
run := func(ctx context.Context) error {
types.SetLayersPerEpoch(app.Config.LayersPerEpoch)
// ensure all data folders exist
if err := os.MkdirAll(app.Config.DataDir(), 0o700); err != nil {
return fmt.Errorf("ensure folders exist: %w", err)
}
if err := app.Lock(); err != nil {
return fmt.Errorf("failed to get exclusive file lock: %w", err)
}
defer app.Unlock()
if err := app.Initialize(); err != nil {
return err
}
/* Create or load miner identity */
if app.edSgn, err = app.LoadOrCreateEdSigner(); err != nil {
return fmt.Errorf("could not retrieve identity: %w", err)
}
app.preserve, err = app.LoadCheckpoint(ctx)
if err != nil {
return err
}
// This blocks until the context is finished or until an error is produced
err = app.Start(ctx)
cleanupCtx, cleanupCancel := context.WithTimeout(
context.Background(),
30*time.Second,
)
defer cleanupCancel()
done := make(chan struct{}, 1)
// FIXME: per https://github.com/spacemeshos/go-spacemesh/issues/3830
go func() {
app.Cleanup(cleanupCtx)
_ = app.eg.Wait()
close(done)
}()
select {
case <-done:
case <-cleanupCtx.Done():
app.log.With().Error("app failed to clean up in time")
}
return err
}
// os.Interrupt for all systems, especially windows, syscall.SIGTERM is mainly for docker.
ctx, cancel := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)
defer cancel()
if err := run(ctx); err != nil {
app.log.With().Fatal(err.Error())
}
},
}
cmd.AddCommands(c)
// versionCmd returns the current version of spacemesh.
versionCmd := cobra.Command{
Use: "version",
Short: "Show version info",
Run: func(c *cobra.Command, args []string) {
fmt.Print(cmd.Version)
if cmd.Commit != "" {
fmt.Printf("+%s", cmd.Commit)
}
fmt.Println()
},
}
c.AddCommand(&versionCmd)
return c
}
var (
appLog log.Log
grpclog grpc_logsettable.SettableLoggerV2
)
func init() {
appLog = log.NewNop()
grpclog = grpc_logsettable.ReplaceGrpcLoggerV2()
}
func loadConfig(c *cobra.Command) (*config.Config, error) {
conf, err := LoadConfigFromFile()
if err != nil {
return nil, err
}
if err := cmd.EnsureCLIFlags(c, conf); err != nil {
return nil, fmt.Errorf("mapping cli flags to config: %w", err)
}
return conf, nil
}
// LoadConfigFromFile tries to load configuration file if the config parameter was specified.
func LoadConfigFromFile() (*config.Config, error) {
// read in default config if passed as param using viper
if err := config.LoadConfig(viper.GetString("config"), viper.GetViper()); err != nil {
return nil, err
}
conf := config.MainnetConfig()
if name := viper.GetString("preset"); len(name) > 0 {
preset, err := presets.Get(name)
if err != nil {
return nil, err
}
conf = preset
}
hook := mapstructure.ComposeDecodeHookFunc(
mapstructure.StringToTimeDurationHookFunc(),
mapstructure.StringToSliceHookFunc(","),
mapstructureutil.AddressListDecodeFunc(),
mapstructureutil.BigRatDecodeFunc(),
mapstructureutil.PostProviderIDDecodeFunc(),
mapstructure.TextUnmarshallerHookFunc(),
)
// load config if it was loaded to the viper
if err := viper.Unmarshal(&conf, viper.DecodeHook(hook), withZeroFields()); err != nil {
return nil, fmt.Errorf("unmarshal viper: %w", err)
}
return &conf, nil
}
func withZeroFields() viper.DecoderConfigOption {
return func(cfg *mapstructure.DecoderConfig) {
cfg.ZeroFields = true
}
}
// Option to modify an App instance.
type Option func(app *App)
// WithLog enables logger for an App.
func WithLog(logger log.Log) Option {
return func(app *App) {
app.log = logger
}
}
// WithConfig overwrites default App config.
func WithConfig(conf *config.Config) Option {
return func(app *App) {
app.Config = conf
}
}
// New creates an instance of the spacemesh app.
func New(opts ...Option) *App {
defaultConfig := config.DefaultConfig()
app := &App{
Config: &defaultConfig,
log: appLog,
loggers: make(map[string]*zap.AtomicLevel),
started: make(chan struct{}),
eg: &errgroup.Group{},
}
for _, opt := range opts {
opt(app)
}
// TODO(mafa): this is a hack to suppress debugging logs on 0000.defaultLogger
// to fix this we should get rid of the global logger and pass app.log to all
// components that need it
lvl := zap.NewAtomicLevelAt(zap.InfoLevel)
log.SetupGlobal(app.log.SetLevel(&lvl))
types.SetNetworkHRP(app.Config.NetworkHRP)
return app
}
// App is the cli app singleton.
type App struct {
*cobra.Command
fileLock *flock.Flock
edSgn *signing.EdSigner
Config *config.Config
db *sql.Database
cachedDB *datastore.CachedDB
dbMetrics *dbmetrics.DBMetricsCollector
localDB *localsql.Database
grpcPublicServer *grpcserver.Server
grpcPrivateServer *grpcserver.Server
grpcTLSServer *grpcserver.Server
jsonAPIServer *grpcserver.JSONHTTPServer
grpcPostService *grpcserver.PostService
pprofService *http.Server
profilerService *pyroscope.Profiler
syncer *syncer.Syncer
proposalListener *proposals.Handler
proposalBuilder *miner.ProposalBuilder
mesh *mesh.Mesh
atxsdata *atxsdata.Data
clock *timesync.NodeClock
hare3 *hare3.Hare
hOracle *eligibility.Oracle
blockGen *blocks.Generator
certifier *blocks.Certifier
atxBuilder *activation.Builder
nipostBuilder *activation.NIPostBuilder
atxHandler *activation.Handler
txHandler *txs.TxHandler
validator *activation.Validator
edVerifier *signing.EdVerifier
beaconProtocol *beacon.ProtocolDriver
log log.Log
svm *vm.VM
conState *txs.ConservativeState
fetcher *fetch.Fetch
ptimesync *peersync.Sync
tortoise *tortoise.Tortoise
updater *bootstrap.Updater
poetDb *activation.PoetDb
postVerifier *activation.OffloadingPostVerifier
postSupervisor *activation.PostSupervisor
preserve *checkpoint.PreservedData
errCh chan error
host *p2p.Host
loggers map[string]*zap.AtomicLevel
started chan struct{} // this channel is closed once the app has finished starting
eg *errgroup.Group
}
func (app *App) LoadCheckpoint(ctx context.Context) (*checkpoint.PreservedData, error) {
checkpointFile := app.Config.Recovery.Uri
restore := types.LayerID(app.Config.Recovery.Restore)
if len(checkpointFile) == 0 {
return nil, nil
}
if restore == 0 {
return nil, fmt.Errorf("restore layer not set")
}
cfg := &checkpoint.RecoverConfig{
GoldenAtx: types.ATXID(app.Config.Genesis.GoldenATX()),
DataDir: app.Config.DataDir(),
DbFile: dbFile,
LocalDbFile: localDbFile,
PreserveOwnAtx: app.Config.Recovery.PreserveOwnAtx,
NodeID: app.edSgn.NodeID(),
Uri: checkpointFile,
Restore: restore,
}
app.log.WithContext(ctx).With().Info("recover from checkpoint",
log.String("url", checkpointFile),
log.Stringer("restore", restore),
)
return checkpoint.Recover(ctx, app.log, afero.NewOsFs(), cfg)
}
func (app *App) Started() <-chan struct{} {
return app.started
}
// Lock locks the app for exclusive use. It returns an error if the app is already locked.
func (app *App) Lock() error {
lockdir := filepath.Dir(app.Config.FileLock)
if _, err := os.Stat(lockdir); errors.Is(err, os.ErrNotExist) {
err := os.Mkdir(lockdir, os.ModePerm)
if err != nil {
return fmt.Errorf("creating dir %s for lock %s: %w", lockdir, app.Config.FileLock, err)
}
}
fl := flock.New(app.Config.FileLock)
locked, err := fl.TryLock()
if err != nil {
return fmt.Errorf("flock %s: %w", app.Config.FileLock, err)
} else if !locked {
return fmt.Errorf("only one spacemesh instance should be running (locking file %s)", fl.Path())
}
app.fileLock = fl
return nil
}
// Unlock unlocks the app. It is a no-op if the app is not locked.
func (app *App) Unlock() {
if app.fileLock == nil {
return
}
if err := app.fileLock.Unlock(); err != nil {
app.log.With().Error("failed to unlock file",
log.String("path", app.fileLock.Path()),
log.Err(err),
)
}
}
// Initialize parses and validates the node configuration and sets up logging.
func (app *App) Initialize() error {
gpath := filepath.Join(app.Config.DataDir(), genesisFileName)
var existing config.GenesisConfig
if err := existing.LoadFromFile(gpath); err != nil {
if !errors.Is(err, os.ErrNotExist) {
return fmt.Errorf("failed to load genesis config at %s: %w", gpath, err)
}
if err := app.Config.Genesis.Validate(); err != nil {
return err
}
if err := app.Config.Genesis.WriteToFile(gpath); err != nil {
return fmt.Errorf("failed to write genesis config to %s: %w", gpath, err)
}
} else {
diff := existing.Diff(app.Config.Genesis)
if len(diff) > 0 {
app.log.Error("genesis config updated after node initialization, if this update is required delete config"+
" at %s.\ndiff:\n%s", gpath, diff,
)
return fmt.Errorf("genesis config updated after node initialization")
}
}
// override default config in timesync since timesync is using TimeConfigValues
timeCfg.TimeConfigValues = app.Config.TIME
app.setupLogging()
app.log.Info("Welcome to Spacemesh. Spacemesh full node is starting...")
public.Version.WithLabelValues(cmd.Version).Set(1)
public.SmeshingOptsProvingNonces.Set(float64(app.Config.SMESHING.ProvingOpts.Nonces))
public.SmeshingOptsProvingThreads.Set(float64(app.Config.SMESHING.ProvingOpts.Threads))
return nil
}
// setupLogging configured the app logging system.
func (app *App) setupLogging() {
app.log.Info("%s", app.getAppInfo())
events.InitializeReporter()
}
func (app *App) getAppInfo() string {
return fmt.Sprintf(
"App version: %s. Git: %s - %s . Go Version: %s. OS: %s-%s . Genesis %s",
cmd.Version,
cmd.Branch,
cmd.Commit,
runtime.Version(),
runtime.GOOS,
runtime.GOARCH,
app.Config.Genesis.GenesisID().String(),
)
}
// Cleanup stops all app services.
func (app *App) Cleanup(ctx context.Context) {
app.log.Info("app cleanup starting...")
app.stopServices(ctx)
// add any other Cleanup tasks here....
app.log.Info("app cleanup completed")
}
// Wrap the top-level logger to add context info and set the level for a
// specific module.
func (app *App) addLogger(name string, logger log.Log) log.Log {
lvl := zap.NewAtomicLevel()
loggers, err := decodeLoggers(app.Config.LOGGING)
if err != nil {
app.log.With().Panic("unable to decode loggers into map[string]string", log.Err(err))
}
level, ok := loggers[name]
if ok {
if err := lvl.UnmarshalText([]byte(level)); err != nil {
app.log.Error("cannot parse logging for %v error %v", name, err)
lvl.SetLevel(log.DefaultLevel())
}
} else {
lvl.SetLevel(log.DefaultLevel())
}
if logger.Check(lvl.Level()) {
app.loggers[name] = &lvl
logger = logger.SetLevel(&lvl)
}
return logger.WithName(name).WithFields(log.String("module", name))
}
func (app *App) getLevel(name string) log.Level {
alvl, exist := app.loggers[name]
if !exist {
return 0
}
return alvl.Level()
}
// SetLogLevel updates the log level of an existing logger.
func (app *App) SetLogLevel(name, loglevel string) error {
lvl, ok := app.loggers[name]
if !ok {
return fmt.Errorf("cannot find logger %v", name)
}
if err := lvl.UnmarshalText([]byte(loglevel)); err != nil {
return fmt.Errorf("unmarshal text: %w", err)
}
return nil
}
func (app *App) initServices(ctx context.Context) error {
layerSize := app.Config.LayerAvgSize
layersPerEpoch := types.GetLayersPerEpoch()
lg := app.log.Named(app.edSgn.NodeID().ShortString()).WithFields(app.edSgn.NodeID())
poetDb := activation.NewPoetDb(app.db, app.addLogger(PoetDbLogger, lg))
nipostValidatorLogger := app.addLogger(NipostValidatorLogger, lg)
lg.Debug("creating post verifier")
verifier, err := activation.NewPostVerifier(
app.Config.POST,
nipostValidatorLogger.Zap(),
verifying.WithPowFlags(app.Config.SMESHING.VerifyingOpts.Flags.Value()),
)
lg.With().Debug("created post verifier", log.Err(err))
if err != nil {
return err
}
minWorkers := app.Config.SMESHING.VerifyingOpts.MinWorkers
workers := app.Config.SMESHING.VerifyingOpts.Workers
app.postVerifier = activation.NewOffloadingPostVerifier(verifier, workers, nipostValidatorLogger.Zap())
app.postVerifier.Autoscale(minWorkers, workers)
validator := activation.NewValidator(
poetDb,
app.Config.POST,
app.Config.SMESHING.Opts.Scrypt,
app.postVerifier,
)
app.validator = validator
cfg := vm.DefaultConfig()
cfg.GasLimit = app.Config.BlockGasLimit
cfg.GenesisID = app.Config.Genesis.GenesisID()
state := vm.New(app.db,
vm.WithConfig(cfg),
vm.WithLogger(app.addLogger(VMLogger, lg)))
app.conState = txs.NewConservativeState(state, app.db,
txs.WithCSConfig(txs.CSConfig{
BlockGasLimit: app.Config.BlockGasLimit,
NumTXsPerProposal: app.Config.TxsPerProposal,
}),
txs.WithLogger(app.addLogger(ConStateLogger, lg)))
genesisAccts := app.Config.Genesis.ToAccounts()
if len(genesisAccts) > 0 {
exists, err := state.AccountExists(genesisAccts[0].Address)
if err != nil {
return fmt.Errorf(
"failed to check genesis account %v: %w",
genesisAccts[0].Address,
err,
)
}
if !exists {
if err = state.ApplyGenesis(genesisAccts); err != nil {
return fmt.Errorf("setup genesis: %w", err)
}
}
}
goldenATXID := types.ATXID(app.Config.Genesis.GoldenATX())
if goldenATXID == types.EmptyATXID {
return errors.New("invalid golden atx id")
}
app.edVerifier = signing.NewEdVerifier(
signing.WithVerifierPrefix(app.Config.Genesis.GenesisID().Bytes()),
)
vrfVerifier := signing.NewVRFVerifier()
beaconProtocol := beacon.New(
app.host,
app.edVerifier,
vrfVerifier,
app.cachedDB,
app.clock,
beacon.WithContext(ctx),
beacon.WithConfig(app.Config.Beacon),
beacon.WithLogger(app.addLogger(BeaconLogger, lg)),
)
beaconProtocol.Register(app.edSgn)
trtlCfg := app.Config.Tortoise
trtlCfg.LayerSize = layerSize
if trtlCfg.BadBeaconVoteDelayLayers == 0 {
trtlCfg.BadBeaconVoteDelayLayers = app.Config.LayersPerEpoch
}
trtlopts := []tortoise.Opt{
tortoise.WithLogger(app.addLogger(TrtlLogger, lg)),
tortoise.WithConfig(trtlCfg),
}
if trtlCfg.EnableTracer {
app.log.With().Info("tortoise will trace execution")
trtlopts = append(trtlopts, tortoise.WithTracer())
}
start := time.Now()
trtl, err := tortoise.Recover(
ctx,
app.cachedDB,
app.clock.CurrentLayer(), trtlopts...,
)
if err != nil {
return fmt.Errorf("can't recover tortoise state: %w", err)
}
app.log.With().Info("tortoise initialized", log.Duration("duration", time.Since(start)))
app.eg.Go(func() error {
for rst := range beaconProtocol.Results() {
events.EmitBeacon(rst.Epoch, rst.Beacon)
trtl.OnBeacon(rst.Epoch, rst.Beacon)
}
app.log.Debug("beacon results watcher exited")
return nil
})
executor := mesh.NewExecutor(
app.cachedDB,
state,
app.conState,
app.addLogger(ExecutorLogger, lg),
)
mlog := app.addLogger(MeshLogger, lg)
msh, err := mesh.NewMesh(app.cachedDB, app.atxsdata, app.clock, trtl, executor, app.conState, mlog)
if err != nil {
return fmt.Errorf("create mesh: %w", err)
}
pruner := prune.New(app.db, app.Config.Tortoise.Hdist, app.Config.PruneActivesetsFrom, prune.WithLogger(mlog.Zap()))
if err := pruner.Prune(app.clock.CurrentLayer()); err != nil {
return fmt.Errorf("pruner %w", err)
}
app.eg.Go(func() error {
prune.Run(ctx, pruner, app.clock, app.Config.DatabasePruneInterval)
return nil
})
fetcherWrapped := &layerFetcher{}
atxHandler := activation.NewHandler(
app.host.ID(),
app.cachedDB,
app.atxsdata,
app.edVerifier,
app.clock,
app.host,
fetcherWrapped,
app.Config.TickSize,
goldenATXID,
validator,
beaconProtocol,
trtl,
app.addLogger(ATXHandlerLogger, lg),
app.Config.POET,
)
// we can't have an epoch offset which is greater/equal than the number of layers in an epoch
if app.Config.HareEligibility.ConfidenceParam >= app.Config.BaseConfig.LayersPerEpoch {
return fmt.Errorf(
"confidence param should be smaller than layers per epoch. eligibility-confidence-param: %d. layers-per-epoch: %d",
app.Config.HareEligibility.ConfidenceParam,
app.Config.BaseConfig.LayersPerEpoch,
)
}
proposalListener := proposals.NewHandler(
app.db,
app.atxsdata,
app.edVerifier,
app.host,
fetcherWrapped,
beaconProtocol,
msh,
trtl,
vrfVerifier,
app.clock,
proposals.WithLogger(app.addLogger(ProposalListenerLogger, lg)),
proposals.WithConfig(proposals.Config{
LayerSize: layerSize,
LayersPerEpoch: layersPerEpoch,
GoldenATXID: goldenATXID,
MaxExceptions: trtlCfg.MaxExceptions,
Hdist: trtlCfg.Hdist,
MinimalActiveSetWeight: trtlCfg.MinimalActiveSetWeight,
}),
)
blockHandler := blocks.NewHandler(fetcherWrapped, app.db, trtl, msh,
blocks.WithLogger(app.addLogger(BlockHandlerLogger, lg)))
app.txHandler = txs.NewTxHandler(
app.conState,
app.host.ID(),
app.addLogger(TxHandlerLogger, lg),
)
app.hOracle = eligibility.New(
beaconProtocol,
app.cachedDB,
vrfVerifier,
app.Config.LayersPerEpoch,
app.Config.HareEligibility,
app.addLogger(HareOracleLogger, lg),
)
// TODO: genesisMinerWeight is set to app.Config.SpaceToCommit, because PoET ticks are currently hardcoded to 1
bscfg := app.Config.Bootstrap
bscfg.DataDir = app.Config.DataDir()
bscfg.Interval = app.Config.LayerDuration / 5
app.updater = bootstrap.New(
app.clock,
bootstrap.WithConfig(bscfg),
bootstrap.WithLogger(app.addLogger(BootstrapLogger, lg)),
)
if app.Config.Certificate.CommitteeSize == 0 {
app.log.With().Warning("certificate committee size is not set, defaulting to hare committee size",
log.Uint16("size", app.Config.HARE3.Committee))
app.Config.Certificate.CommitteeSize = int(app.Config.HARE3.Committee)
}
app.Config.Certificate.CertifyThreshold = app.Config.Certificate.CommitteeSize/2 + 1
app.Config.Certificate.LayerBuffer = app.Config.Tortoise.Zdist
app.Config.Certificate.NumLayersToKeep = app.Config.Tortoise.Zdist * 2
app.certifier = blocks.NewCertifier(
app.cachedDB,
app.hOracle,
app.edVerifier,
app.host,
app.clock,
beaconProtocol,
trtl,
blocks.WithCertConfig(app.Config.Certificate),
blocks.WithCertifierLogger(app.addLogger(BlockCertLogger, lg)),
)
app.certifier.Register(app.edSgn)
flog := app.addLogger(Fetcher, lg)
fetcher := fetch.NewFetch(app.cachedDB, msh, beaconProtocol, app.host,
fetch.WithContext(ctx),
fetch.WithConfig(app.Config.FETCH),
fetch.WithLogger(flog),
)
fetcherWrapped.Fetcher = fetcher
app.eg.Go(func() error {
return blockssync.Sync(ctx, flog.Zap(), msh.MissingBlocks(), fetcher)
})
patrol := layerpatrol.New()
syncerConf := app.Config.Sync
syncerConf.HareDelayLayers = app.Config.Tortoise.Zdist
syncerConf.SyncCertDistance = app.Config.Tortoise.Hdist
syncerConf.Standalone = app.Config.Standalone
newSyncer := syncer.NewSyncer(
app.cachedDB,
app.clock,
beaconProtocol,
msh,
trtl,
fetcher,
patrol,
app.certifier,
syncer.WithConfig(syncerConf),
syncer.WithLogger(app.addLogger(SyncLogger, lg)),
)
// TODO(dshulyak) this needs to be improved, but dependency graph is a bit complicated
beaconProtocol.SetSyncState(newSyncer)
app.hOracle.SetSync(newSyncer)
if err := app.Config.HARE3.Validate(time.Duration(app.Config.Tortoise.Zdist) * app.Config.LayerDuration); err != nil {
return err
}
logger := app.addLogger(HareLogger, lg).Zap()
app.hare3 = hare3.New(
app.clock, app.host, app.cachedDB, app.edVerifier, app.hOracle, newSyncer, patrol,
hare3.WithLogger(logger),
hare3.WithConfig(app.Config.HARE3),
)
app.hare3.Register(app.edSgn)
app.hare3.Start()
app.eg.Go(func() error {
compat.ReportWeakcoin(
ctx,
logger,
app.hare3.Coins(),
tortoiseWeakCoin{db: app.cachedDB, tortoise: trtl},
)
return nil
})
app.blockGen = blocks.NewGenerator(
app.db,
app.atxsdata,
executor,
msh,
fetcherWrapped,
app.certifier,
patrol,
blocks.WithConfig(blocks.Config{
BlockGasLimit: app.Config.BlockGasLimit,
OptFilterThreshold: app.Config.OptFilterThreshold,
GenBlockInterval: 500 * time.Millisecond,
}),
blocks.WithHareOutputChan(app.hare3.Results()),
blocks.WithGeneratorLogger(app.addLogger(BlockGenLogger, lg)),
)
minerGoodAtxPct := 90
if app.Config.MinerGoodAtxsPercent > 0 {
minerGoodAtxPct = app.Config.MinerGoodAtxsPercent
}
proposalBuilder := miner.New(
app.clock,
app.cachedDB,
app.host,
trtl,
newSyncer,
app.conState,
miner.WithLayerSize(layerSize),
miner.WithLayerPerEpoch(layersPerEpoch),
miner.WithMinimalActiveSetWeight(app.Config.Tortoise.MinimalActiveSetWeight),
miner.WithHdist(app.Config.Tortoise.Hdist),
miner.WithNetworkDelay(app.Config.ATXGradeDelay),
miner.WithMinGoodAtxPercent(minerGoodAtxPct),
miner.WithLogger(app.addLogger(ProposalBuilderLogger, lg)),
)
proposalBuilder.Register(app.edSgn)
u := url.URL{
Scheme: "http",
Host: app.Config.API.PrivateListener,
}
app.Config.POSTService.NodeAddress = u.String()
postSetupMgr, err := activation.NewPostSetupManager(
app.edSgn.NodeID(),
app.Config.POST,
app.addLogger(PostLogger, lg).Zap(),
app.cachedDB, goldenATXID,
)
if err != nil {
return fmt.Errorf("create post setup manager: %v", err)
}
app.postSupervisor, err = activation.NewPostSupervisor(
app.log.Zap(),
app.Config.POSTService,
app.Config.POST,
app.Config.SMESHING.ProvingOpts,
postSetupMgr,
newSyncer,
)
if err != nil {
return fmt.Errorf("init post service: %w", err)
}
app.grpcPostService = grpcserver.NewPostService(app.addLogger(PostServiceLogger, lg).Zap())
nipostBuilder, err := activation.NewNIPostBuilder(
poetDb,
app.grpcPostService,
app.Config.PoETServers,
app.Config.SMESHING.Opts.DataDir,
app.addLogger(NipostBuilderLogger, lg).Zap(),
app.edSgn,
app.Config.POET,
app.clock,
)
if err != nil {
return fmt.Errorf("create nipost builder: %w", err)
}
builderConfig := activation.Config{
GoldenATXID: goldenATXID,
LayersPerEpoch: layersPerEpoch,
RegossipInterval: app.Config.RegossipAtxInterval,
}
atxBuilder := activation.NewBuilder(
builderConfig,
app.edSgn,
app.cachedDB,
app.localDB,
app.host,
app.grpcPostService,
nipostBuilder,
app.clock,
newSyncer,
app.addLogger("atxBuilder", lg).Zap(),
activation.WithContext(ctx),
activation.WithPoetConfig(app.Config.POET),
// TODO(dshulyak) makes no sense. how we ended using it?
activation.WithPoetRetryInterval(app.Config.HARE3.PreroundDelay),
activation.WithValidator(app.validator),
)
malfeasanceHandler := malfeasance.NewHandler(
app.cachedDB,
app.addLogger(MalfeasanceLogger, lg),
app.host.ID(),
app.edSgn.NodeID(),
app.edVerifier,
trtl,
)
fetcher.SetValidators(
fetch.ValidatorFunc(
pubsub.DropPeerOnSyncValidationReject(atxHandler.HandleSyncedAtx, app.host, lg),
),
fetch.ValidatorFunc(
pubsub.DropPeerOnSyncValidationReject(poetDb.ValidateAndStoreMsg, app.host, lg),
),
fetch.ValidatorFunc(
pubsub.DropPeerOnSyncValidationReject(
proposalListener.HandleSyncedBallot,
app.host,
lg,
),
),
fetch.ValidatorFunc(
pubsub.DropPeerOnSyncValidationReject(proposalListener.HandleActiveSet, app.host, lg),
),
fetch.ValidatorFunc(
pubsub.DropPeerOnSyncValidationReject(blockHandler.HandleSyncedBlock, app.host, lg),
),
fetch.ValidatorFunc(
pubsub.DropPeerOnSyncValidationReject(
proposalListener.HandleSyncedProposal,
app.host,
lg,
),
),
fetch.ValidatorFunc(
pubsub.DropPeerOnSyncValidationReject(
app.txHandler.HandleBlockTransaction,
app.host,
lg,
),
),
fetch.ValidatorFunc(
pubsub.DropPeerOnSyncValidationReject(
app.txHandler.HandleProposalTransaction,
app.host,
lg,
),
),
fetch.ValidatorFunc(
pubsub.DropPeerOnSyncValidationReject(
malfeasanceHandler.HandleSyncedMalfeasanceProof,
app.host,
lg,
),
),
)