forked from erigontech/erigon
-
Notifications
You must be signed in to change notification settings - Fork 53
/
Copy pathbackend.go
2182 lines (1903 loc) · 72.7 KB
/
backend.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
// Copyright 2014 The go-ethereum Authors
// This file is part of the go-ethereum library.
//
// The go-ethereum library is free software: you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// The go-ethereum library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>.
// Package eth implements the Ethereum protocol.
package eth
import (
"context"
"errors"
"fmt"
"io/fs"
"math/big"
"net"
"os"
"path/filepath"
"slices"
"strconv"
"strings"
"sync"
"sync/atomic"
"time"
"github.com/ledgerwatch/erigon-lib/common/dir"
"github.com/ledgerwatch/erigon-lib/common/disk"
"github.com/ledgerwatch/erigon-lib/common/mem"
"github.com/ledgerwatch/erigon-lib/diagnostics"
"github.com/0xPolygonHermez/zkevm-data-streamer/datastreamer"
"github.com/ledgerwatch/erigon/zk/sequencer"
"github.com/ledgerwatch/erigon/zk/txpool"
"github.com/erigontech/mdbx-go/mdbx"
lru "github.com/hashicorp/golang-lru/arc/v2"
"github.com/holiman/uint256"
"github.com/ledgerwatch/erigon-lib/config3"
"github.com/ledgerwatch/erigon-lib/kv/temporal"
"github.com/ledgerwatch/log/v3"
"google.golang.org/grpc"
"google.golang.org/grpc/credentials"
"google.golang.org/protobuf/types/known/emptypb"
"net/url"
"path"
log2 "github.com/0xPolygonHermez/zkevm-data-streamer/log"
"github.com/ledgerwatch/erigon-lib/chain"
"github.com/ledgerwatch/erigon-lib/chain/networkname"
"github.com/ledgerwatch/erigon-lib/chain/snapcfg"
libcommon "github.com/ledgerwatch/erigon-lib/common"
"github.com/ledgerwatch/erigon-lib/common/datadir"
"github.com/ledgerwatch/erigon-lib/direct"
"github.com/ledgerwatch/erigon-lib/downloader"
"github.com/ledgerwatch/erigon-lib/downloader/downloadercfg"
"github.com/ledgerwatch/erigon-lib/downloader/downloadergrpc"
"github.com/ledgerwatch/erigon-lib/downloader/snaptype"
protodownloader "github.com/ledgerwatch/erigon-lib/gointerfaces/downloader"
"github.com/ledgerwatch/erigon-lib/gointerfaces/grpcutil"
"github.com/ledgerwatch/erigon-lib/gointerfaces/remote"
rpcsentinel "github.com/ledgerwatch/erigon-lib/gointerfaces/sentinel"
protosentry "github.com/ledgerwatch/erigon-lib/gointerfaces/sentry"
txpoolproto "github.com/ledgerwatch/erigon-lib/gointerfaces/txpool"
prototypes "github.com/ledgerwatch/erigon-lib/gointerfaces/types"
"github.com/ledgerwatch/erigon-lib/kv"
"github.com/ledgerwatch/erigon-lib/kv/kvcache"
"github.com/ledgerwatch/erigon-lib/kv/kvcfg"
"github.com/ledgerwatch/erigon-lib/kv/remotedbserver"
libstate "github.com/ledgerwatch/erigon-lib/state"
"github.com/ledgerwatch/erigon-lib/txpool/txpoolcfg"
libtypes "github.com/ledgerwatch/erigon-lib/types"
"github.com/ledgerwatch/erigon-lib/wrap"
"github.com/ledgerwatch/erigon/cmd/rpcdaemon/cli"
"github.com/ledgerwatch/erigon/common/debug"
"github.com/ledgerwatch/erigon/consensus"
"github.com/ledgerwatch/erigon/consensus/clique"
"github.com/ledgerwatch/erigon/consensus/ethash"
"github.com/ledgerwatch/erigon/consensus/merge"
"github.com/ledgerwatch/erigon/core"
"github.com/ledgerwatch/erigon/core/rawdb"
"github.com/ledgerwatch/erigon/core/rawdb/blockio"
"github.com/ledgerwatch/erigon/core/types"
"github.com/ledgerwatch/erigon/core/vm"
"github.com/ledgerwatch/erigon/crypto"
"github.com/ledgerwatch/erigon/eth/ethconfig"
"github.com/ledgerwatch/erigon/eth/ethconsensusconfig"
"github.com/ledgerwatch/erigon/eth/ethutils"
"github.com/ledgerwatch/erigon/eth/protocols/eth"
"github.com/ledgerwatch/erigon/eth/stagedsync"
"github.com/ledgerwatch/erigon/eth/stagedsync/stages"
"github.com/ledgerwatch/erigon/ethdb/privateapi"
"github.com/ledgerwatch/erigon/ethdb/prune"
"github.com/ledgerwatch/erigon/node"
"github.com/ledgerwatch/erigon/p2p"
"github.com/ledgerwatch/erigon/p2p/enode"
"github.com/ledgerwatch/erigon/p2p/sentry"
"github.com/ledgerwatch/erigon/p2p/sentry/sentry_multi_client"
"github.com/ledgerwatch/erigon/params"
"github.com/ledgerwatch/erigon/polygon/bor"
"github.com/ledgerwatch/erigon/polygon/bor/finality/flags"
"github.com/ledgerwatch/erigon/polygon/bor/valset"
"github.com/ledgerwatch/erigon/polygon/heimdall"
polygonsync "github.com/ledgerwatch/erigon/polygon/sync"
"github.com/ledgerwatch/erigon/rpc"
"github.com/ledgerwatch/erigon/smt/pkg/db"
"github.com/ledgerwatch/erigon/turbo/builder"
"github.com/ledgerwatch/erigon/turbo/engineapi"
"github.com/ledgerwatch/erigon/turbo/engineapi/engine_block_downloader"
"github.com/ledgerwatch/erigon/turbo/engineapi/engine_helpers"
"github.com/ledgerwatch/erigon/turbo/execution/eth1"
"github.com/ledgerwatch/erigon/turbo/jsonrpc"
"github.com/ledgerwatch/erigon/turbo/services"
"github.com/ledgerwatch/erigon/turbo/shards"
"github.com/ledgerwatch/erigon/turbo/silkworm"
"github.com/ledgerwatch/erigon/turbo/snapshotsync/freezeblocks"
"github.com/ledgerwatch/erigon/turbo/snapshotsync/snap"
stages2 "github.com/ledgerwatch/erigon/turbo/stages"
"github.com/ledgerwatch/erigon/turbo/stages/headerdownload"
"github.com/ledgerwatch/erigon/zk/contracts"
"github.com/ledgerwatch/erigon/zk/datastream/client"
"github.com/ledgerwatch/erigon/zk/datastream/server"
"github.com/ledgerwatch/erigon/zk/hermez_db"
"github.com/ledgerwatch/erigon/zk/l1_cache"
"github.com/ledgerwatch/erigon/zk/l1infotree"
"github.com/ledgerwatch/erigon/zk/legacy_executor_verifier"
zkStages "github.com/ledgerwatch/erigon/zk/stages"
"github.com/ledgerwatch/erigon/zk/syncer"
txpool2 "github.com/ledgerwatch/erigon/zk/txpool"
"github.com/ledgerwatch/erigon/zk/txpool/txpooluitl"
"github.com/ledgerwatch/erigon/zk/utils"
"github.com/ledgerwatch/erigon/zk/witness"
"github.com/ledgerwatch/erigon/zkevm/etherman"
)
var dataStreamServerFactory = server.NewZkEVMDataStreamServerFactory()
// Config contains the configuration options of the ETH protocol.
// Deprecated: use ethconfig.Config instead.
type Config = ethconfig.Config
type PreStartTasks struct {
WarmUpDataStream bool
}
// Ethereum implements the Ethereum full node service.
type Ethereum struct {
config *ethconfig.Config
// DB interfaces
chainDB kv.RwDB
privateAPI *grpc.Server
engine consensus.Engine
gasPrice *uint256.Int
etherbase libcommon.Address
networkID uint64
lock sync.RWMutex // Protects the variadic fields (e.g. gas price and etherbase)
chainConfig *chain.Config
apiList []rpc.API
genesisBlock *types.Block
genesisHash libcommon.Hash
eth1ExecutionServer *eth1.EthereumExecutionModule
ethBackendRPC *privateapi.EthBackendServer
engineBackendRPC *engineapi.EngineServer
miningRPC txpoolproto.MiningServer
stateChangesClient txpool2.StateChangesClient
miningSealingQuit chan struct{}
pendingBlocks chan *types.Block
minedBlocks chan *types.Block
sentryCtx context.Context
sentryCancel context.CancelFunc
sentriesClient *sentry_multi_client.MultiClient
sentryServers []*sentry.GrpcServer
stagedSync *stagedsync.Sync
pipelineStagedSync *stagedsync.Sync
syncStages []*stagedsync.Stage
syncUnwindOrder stagedsync.UnwindOrder
syncPruneOrder stagedsync.PruneOrder
downloaderClient protodownloader.DownloaderClient
notifications *shards.Notifications
unsubscribeEthstat func()
waitForStageLoopStop chan struct{}
waitForMiningStop chan struct{}
txPool2DB kv.RwDB
txPool2 *txpool2.TxPool
newTxs2 chan libtypes.Announcements
txPool2Fetch *txpool2.Fetch
txPool2Send *txpool2.Send
txPool2GrpcServer txpoolproto.TxpoolServer
notifyMiningAboutNewTxs chan struct{}
forkValidator *engine_helpers.ForkValidator
downloader *downloader.Downloader
agg *libstate.Aggregator
blockSnapshots *freezeblocks.RoSnapshots
blockReader services.FullBlockReader
blockWriter *blockio.BlockWriter
kvRPC *remotedbserver.KvServer
logger log.Logger
// zk
streamServer server.StreamServer
l1Syncer *syncer.L1Syncer
etherManClients []*etherman.Client
l1Cache *l1_cache.L1Cache
preStartTasks *PreStartTasks
sentinel rpcsentinel.SentinelClient
silkworm *silkworm.Silkworm
silkwormRPCDaemonService *silkworm.RpcDaemonService
silkwormSentryService *silkworm.SentryService
polygonSyncService polygonsync.Service
stopNode func() error
}
func splitAddrIntoHostAndPort(addr string) (host string, port int, err error) {
idx := strings.LastIndexByte(addr, ':')
if idx < 0 {
return "", 0, errors.New("invalid address format")
}
host = addr[:idx]
port, err = strconv.Atoi(addr[idx+1:])
return
}
const blockBufferSize = 128
// New creates a new Ethereum object (including the
// initialisation of the common Ethereum object)
func New(ctx context.Context, stack *node.Node, config *ethconfig.Config, logger log.Logger) (*Ethereum, error) {
config.Snapshot.Enabled = config.Sync.UseSnapshots
if config.Miner.GasPrice == nil || config.Miner.GasPrice.Cmp(libcommon.Big0) <= 0 {
logger.Warn("Sanitizing invalid miner gas price", "provided", config.Miner.GasPrice, "updated", ethconfig.Defaults.Miner.GasPrice)
config.Miner.GasPrice = new(big.Int).Set(ethconfig.Defaults.Miner.GasPrice)
}
dirs := stack.Config().Dirs
tmpdir := dirs.Tmp
if err := RemoveContents(tmpdir); err != nil { // clean it on startup
return nil, fmt.Errorf("clean tmp dir: %s, %w", tmpdir, err)
}
// Assemble the Ethereum object
chainKv, err := node.OpenDatabase(ctx, stack.Config(), kv.ChainDB, "", false, logger)
if err != nil {
return nil, err
}
latestBlockBuiltStore := builder.NewLatestBlockBuiltStore()
if err := chainKv.Update(context.Background(), func(tx kv.RwTx) error {
if err = stages.UpdateMetrics(tx); err != nil {
return err
}
config.Prune, err = prune.EnsureNotChanged(tx, config.Prune)
if err != nil {
return err
}
config.HistoryV3, err = kvcfg.HistoryV3.WriteOnce(tx, config.HistoryV3)
return err
}); err != nil {
return nil, err
}
if config.HistoryV3 {
return nil, errors.New("seems you using erigon2 git branch on erigon3 DB")
}
ctx, ctxCancel := context.WithCancel(context.Background())
// kv_remote architecture does blocks on stream.Send - means current architecture require unlimited amount of txs to provide good throughput
backend := &Ethereum{
sentryCtx: ctx,
sentryCancel: ctxCancel,
config: config,
chainDB: chainKv,
networkID: config.NetworkID,
etherbase: config.Miner.Etherbase,
waitForStageLoopStop: make(chan struct{}),
waitForMiningStop: make(chan struct{}),
notifications: &shards.Notifications{
Events: shards.NewEvents(),
Accumulator: shards.NewAccumulator(),
},
preStartTasks: &PreStartTasks{},
logger: logger,
stopNode: func() error {
return stack.Close()
},
}
var chainConfig *chain.Config
var genesis *types.Block
if err := backend.chainDB.Update(context.Background(), func(tx kv.RwTx) error {
h, err := rawdb.ReadCanonicalHash(tx, 0)
if err != nil {
panic(err)
}
genesisSpec := config.Genesis
if h != (libcommon.Hash{}) { // fallback to db content
genesisSpec = nil
}
var genesisErr error
chainConfig, genesis, genesisErr = core.WriteGenesisBlock(tx, genesisSpec, config.OverridePragueTime, tmpdir, logger)
if _, ok := genesisErr.(*chain.ConfigCompatError); genesisErr != nil && !ok {
return genesisErr
}
return nil
}); err != nil {
panic(err)
}
backend.chainConfig = chainConfig
backend.genesisBlock = genesis
backend.genesisHash = genesis.Hash()
setBorDefaultMinerGasPrice(chainConfig, config, logger)
setBorDefaultTxPoolPriceLimit(chainConfig, config.TxPool, logger)
if err := chainKv.Update(context.Background(), func(tx kv.RwTx) error {
isCorrectSync, useSnapshots, err := snap.EnsureNotChanged(tx, config.Snapshot)
if err != nil {
return err
}
// if we are in the incorrect syncmode then we change it to the appropriate one
if !isCorrectSync {
log.Warn("Incorrect snapshot enablement", "got", config.Sync.UseSnapshots, "change_to", useSnapshots)
config.Sync.UseSnapshots = useSnapshots
config.Snapshot.Enabled = ethconfig.UseSnapshotsByChainName(chainConfig.ChainName) && useSnapshots
}
log.Info("Effective", "prune_flags", config.Prune.String(), "snapshot_flags", config.Snapshot.String(), "history.v3", config.HistoryV3)
return nil
}); err != nil {
return nil, err
}
logger.Info("Initialised chain configuration", "config", chainConfig, "genesis", genesis.Hash())
// Check if we have an already initialized chain and fall back to
// that if so. Otherwise we need to generate a new genesis spec.
blockReader, blockWriter, allSnapshots, allBorSnapshots, agg, err := setUpBlockReader(ctx, chainKv, config.Dirs, config, config.HistoryV3, chainConfig.Bor != nil, logger)
if err != nil {
return nil, err
}
backend.agg, backend.blockSnapshots, backend.blockReader, backend.blockWriter = agg, allSnapshots, blockReader, blockWriter
if config.HistoryV3 {
backend.chainDB, err = temporal.New(backend.chainDB, agg)
if err != nil {
return nil, err
}
chainKv = backend.chainDB //nolint
}
if err := backend.setUpSnapDownloader(ctx, config.Downloader); err != nil {
return nil, err
}
kvRPC := remotedbserver.NewKvServer(ctx, backend.chainDB, allSnapshots, allBorSnapshots, agg, logger)
backend.notifications.StateChangesConsumer = kvRPC
backend.kvRPC = kvRPC
backend.gasPrice, _ = uint256.FromBig(config.Miner.GasPrice)
if config.SilkwormExecution || config.SilkwormRpcDaemon || config.SilkwormSentry {
logLevel, err := log.LvlFromString(config.SilkwormVerbosity)
if err != nil {
return nil, err
}
backend.silkworm, err = silkworm.New(config.Dirs.DataDir, mdbx.Version(), config.SilkwormNumContexts, logLevel)
if err != nil {
return nil, err
}
}
p2pConfig := stack.Config().P2P
var sentries []direct.SentryClient
if len(p2pConfig.SentryAddr) > 0 {
for _, addr := range p2pConfig.SentryAddr {
sentryClient, err := sentry_multi_client.GrpcClient(backend.sentryCtx, addr)
if err != nil {
return nil, err
}
sentries = append(sentries, sentryClient)
}
} else if config.SilkwormSentry {
apiPort := 53774
apiAddr := fmt.Sprintf("127.0.0.1:%d", apiPort)
collectNodeURLs := func(nodes []*enode.Node) []string {
var urls []string
for _, n := range nodes {
urls = append(urls, n.URLv4())
}
return urls
}
settings := silkworm.SentrySettings{
ClientId: p2pConfig.Name,
ApiPort: apiPort,
Port: p2pConfig.ListenPort(),
Nat: p2pConfig.NATSpec,
NetworkId: config.NetworkID,
NodeKey: crypto.FromECDSA(p2pConfig.PrivateKey),
StaticPeers: collectNodeURLs(p2pConfig.StaticNodes),
Bootnodes: collectNodeURLs(p2pConfig.BootstrapNodes),
NoDiscover: p2pConfig.NoDiscovery,
MaxPeers: p2pConfig.MaxPeers,
}
silkwormSentryService := silkworm.NewSentryService(backend.silkworm, settings)
backend.silkwormSentryService = &silkwormSentryService
sentryClient, err := sentry_multi_client.GrpcClient(backend.sentryCtx, apiAddr)
if err != nil {
return nil, err
}
sentries = append(sentries, sentryClient)
} else {
var readNodeInfo = func() *eth.NodeInfo {
var res *eth.NodeInfo
_ = backend.chainDB.View(context.Background(), func(tx kv.Tx) error {
res = eth.ReadNodeInfo(tx, backend.chainConfig, backend.genesisHash, backend.networkID)
return nil
})
return res
}
discovery := func() enode.Iterator {
d, err := setupDiscovery(backend.config.EthDiscoveryURLs)
if err != nil {
panic(err)
}
return d
}
listenHost, listenPort, err := splitAddrIntoHostAndPort(p2pConfig.ListenAddr)
if err != nil {
return nil, err
}
var pi int // points to next port to be picked from refCfg.AllowedPorts
for _, protocol := range p2pConfig.ProtocolVersion {
cfg := p2pConfig
cfg.NodeDatabase = filepath.Join(stack.Config().Dirs.Nodes, eth.ProtocolToString[protocol])
// pick port from allowed list
var picked bool
for ; pi < len(cfg.AllowedPorts) && !picked; pi++ {
pc := int(cfg.AllowedPorts[pi])
if pc == 0 {
// For ephemeral ports probing to see if the port is taken does not
// make sense.
picked = true
break
}
if !checkPortIsFree(fmt.Sprintf("%s:%d", listenHost, pc)) {
logger.Warn("bind protocol to port has failed: port is busy", "protocols", fmt.Sprintf("eth/%d", cfg.ProtocolVersion), "port", pc)
continue
}
if listenPort != pc {
listenPort = pc
}
pi++
picked = true
break
}
if !picked {
return nil, fmt.Errorf("run out of allowed ports for p2p eth protocols %v. Extend allowed port list via --p2p.allowed-ports", cfg.AllowedPorts)
}
cfg.ListenAddr = fmt.Sprintf("%s:%d", listenHost, listenPort)
server := sentry.NewGrpcServer(backend.sentryCtx, discovery, readNodeInfo, &cfg, protocol, logger)
backend.sentryServers = append(backend.sentryServers, server)
sentries = append(sentries, direct.NewSentryClientDirect(protocol, server))
}
go func() {
logEvery := time.NewTicker(180 * time.Second)
defer logEvery.Stop()
var logItems []interface{}
for {
select {
case <-backend.sentryCtx.Done():
return
case <-logEvery.C:
logItems = logItems[:0]
peerCountMap := map[uint]int{}
for _, srv := range backend.sentryServers {
counts := srv.SimplePeerCount()
for protocol, count := range counts {
peerCountMap[protocol] += count
}
}
for protocol, count := range peerCountMap {
logItems = append(logItems, eth.ProtocolToString[protocol], strconv.Itoa(count))
}
logger.Info("[p2p] GoodPeers", logItems...)
}
}
}()
}
// setup periodic logging and prometheus updates
go mem.LogMemStats(ctx, logger)
go disk.UpdateDiskStats(ctx, logger)
var currentBlock *types.Block
if err := chainKv.View(context.Background(), func(tx kv.Tx) error {
currentBlock, err = blockReader.CurrentBlock(tx)
return err
}); err != nil {
panic(err)
}
currentBlockNumber := uint64(0)
if currentBlock != nil {
currentBlockNumber = currentBlock.NumberU64()
}
logger.Info("Initialising Ethereum protocol", "network", config.NetworkID)
var consensusConfig interface{}
if chainConfig.Clique != nil {
consensusConfig = &config.Clique
} else if chainConfig.Aura != nil {
consensusConfig = &config.Aura
} else if chainConfig.Bor != nil {
consensusConfig = chainConfig.Bor
} else {
consensusConfig = &config.Ethash
}
var heimdallClient heimdall.HeimdallClient
if chainConfig.Bor != nil {
if !config.WithoutHeimdall {
heimdallClient = heimdall.NewHeimdallClient(config.HeimdallURL, logger)
}
flags.Milestone = config.WithHeimdallMilestones
}
backend.engine = ethconsensusconfig.CreateConsensusEngine(ctx, stack.Config(), chainConfig, consensusConfig, config.Miner.Notify, config.Miner.Noverify, heimdallClient, config.WithoutHeimdall, blockReader, false /* readonly */, logger)
inMemoryExecution := func(txc wrap.TxContainer, header *types.Header, body *types.RawBody, unwindPoint uint64, headersChain []*types.Header, bodiesChain []*types.RawBody,
notifications *shards.Notifications) error {
terseLogger := log.New()
terseLogger.SetHandler(log.LvlFilterHandler(log.LvlWarn, log.StderrHandler))
// Needs its own notifications to not update RPC daemon and txpool about pending blocks
stateSync := stages2.NewInMemoryExecution(backend.sentryCtx, backend.chainDB, config, backend.sentriesClient,
dirs, notifications, blockReader, blockWriter, backend.agg, backend.silkworm, terseLogger)
chainReader := stagedsync.NewChainReaderImpl(chainConfig, txc.Tx, blockReader, logger)
// We start the mining step
if err := stages2.StateStep(ctx, chainReader, backend.engine, txc, stateSync, header, body, unwindPoint, headersChain, bodiesChain, config.HistoryV3); err != nil {
logger.Warn("Could not validate block", "err", err)
return err
}
progress, err := stages.GetStageProgress(txc.Tx, stages.IntermediateHashes)
if err != nil {
return err
}
if progress < header.Number.Uint64() {
return fmt.Errorf("unsuccessful execution, progress %d < expected %d", progress, header.Number.Uint64())
}
return nil
}
backend.forkValidator = engine_helpers.NewForkValidator(ctx, currentBlockNumber, inMemoryExecution, tmpdir, backend.blockReader)
statusDataProvider := sentry.NewStatusDataProvider(
chainKv,
chainConfig,
genesis,
backend.config.NetworkID,
logger,
)
// limit "new block" broadcasts to at most 10 random peers at time
maxBlockBroadcastPeers := func(header *types.Header) uint { return 10 }
// unlimited "new block" broadcasts to all peers for blocks announced by Bor validators
if borEngine, ok := backend.engine.(*bor.Bor); ok {
defaultValue := maxBlockBroadcastPeers(nil)
maxBlockBroadcastPeers = func(header *types.Header) uint {
isValidator, err := borEngine.IsValidator(header)
if err != nil {
logger.Warn("maxBlockBroadcastPeers: borEngine.IsValidator has failed", "err", err)
return defaultValue
}
if isValidator {
// 0 means send to all
return 0
}
return defaultValue
}
}
sentryMcDisableBlockDownload := config.PolygonSync
backend.sentriesClient, err = sentry_multi_client.NewMultiClient(
chainKv,
chainConfig,
backend.engine,
sentries,
config.Sync,
blockReader,
blockBufferSize,
statusDataProvider,
stack.Config().SentryLogPeerInfo,
maxBlockBroadcastPeers,
sentryMcDisableBlockDownload,
logger,
)
if err != nil {
return nil, err
}
config.TxPool.NoGossip = config.DisableTxPoolGossip
var miningRPC txpoolproto.MiningServer
stateDiffClient := direct.NewStateDiffClientDirect(kvRPC)
if config.DeprecatedTxPool.Disable {
backend.txPool2GrpcServer = &txpool2.GrpcDisabled{}
} else {
//cacheConfig := kvcache.DefaultCoherentCacheConfig
//cacheConfig.MetricsLabel = "txpool"
backend.newTxs2 = make(chan libtypes.Announcements, 1024)
//defer close(newTxs)
backend.txPool2DB, backend.txPool2, backend.txPool2Fetch, backend.txPool2Send, backend.txPool2GrpcServer, err = txpooluitl.AllComponents(
ctx, config.TxPool, config, kvcache.NewDummy(), backend.newTxs2, backend.chainDB, backend.sentriesClient.Sentries(), stateDiffClient,
)
if err != nil {
return nil, err
}
}
backend.notifyMiningAboutNewTxs = make(chan struct{}, 1)
backend.miningSealingQuit = make(chan struct{})
backend.pendingBlocks = make(chan *types.Block, 1)
backend.minedBlocks = make(chan *types.Block, 1)
miner := stagedsync.NewMiningState(&config.Miner)
backend.pendingBlocks = miner.PendingResultCh
var (
snapDb kv.RwDB
recents *lru.ARCCache[libcommon.Hash, *bor.Snapshot]
signatures *lru.ARCCache[libcommon.Hash, libcommon.Address]
)
if bor, ok := backend.engine.(*bor.Bor); ok {
snapDb = bor.DB
recents = bor.Recents
signatures = bor.Signatures
}
// proof-of-work mining
mining := stagedsync.New(
config.Sync,
stagedsync.MiningStages(backend.sentryCtx,
stagedsync.StageMiningCreateBlockCfg(backend.chainDB, miner, *backend.chainConfig, backend.engine, backend.txPool2DB, nil, tmpdir, backend.blockReader),
stagedsync.StageBorHeimdallCfg(backend.chainDB, snapDb, miner, *backend.chainConfig, heimdallClient, backend.blockReader, nil, nil, nil, recents, signatures, false, nil),
stagedsync.StageMiningExecCfg(backend.chainDB, miner, backend.notifications.Events, *backend.chainConfig, backend.engine, &vm.Config{}, tmpdir, nil, 0, backend.txPool2, backend.txPool2DB, blockReader),
stagedsync.StageHashStateCfg(backend.chainDB, dirs, config.HistoryV3, agg),
stagedsync.StageTrieCfg(backend.chainDB, false, true, true, tmpdir, blockReader, nil, config.HistoryV3, backend.agg),
stagedsync.StageMiningFinishCfg(backend.chainDB, *backend.chainConfig, backend.engine, miner, backend.miningSealingQuit, backend.blockReader, latestBlockBuiltStore),
), stagedsync.MiningUnwindOrder, stagedsync.MiningPruneOrder,
logger)
var ethashApi *ethash.API
if casted, ok := backend.engine.(*ethash.Ethash); ok {
ethashApi = casted.APIs(nil)[1].Service.(*ethash.API)
}
// proof-of-stake mining
assembleBlockPOS := func(param *core.BlockBuilderParameters, interrupt *int32) (*types.BlockWithReceipts, error) {
miningStatePos := stagedsync.NewProposingState(&config.Miner)
miningStatePos.MiningConfig.Etherbase = param.SuggestedFeeRecipient
proposingSync := stagedsync.New(
config.Sync,
stagedsync.MiningStages(backend.sentryCtx,
stagedsync.StageMiningCreateBlockCfg(backend.chainDB, miningStatePos, *backend.chainConfig, backend.engine, backend.txPool2DB, param, tmpdir, backend.blockReader),
stagedsync.StageBorHeimdallCfg(backend.chainDB, snapDb, miningStatePos, *backend.chainConfig, heimdallClient, backend.blockReader, nil, nil, nil, recents, signatures, false, nil),
stagedsync.StageMiningExecCfg(backend.chainDB, miningStatePos, backend.notifications.Events, *backend.chainConfig, backend.engine, &vm.Config{}, tmpdir, interrupt, param.PayloadId, backend.txPool2, backend.txPool2DB, blockReader),
stagedsync.StageHashStateCfg(backend.chainDB, dirs, config.HistoryV3, agg),
stagedsync.StageTrieCfg(backend.chainDB, false, true, true, tmpdir, blockReader, nil, config.HistoryV3, backend.agg),
stagedsync.StageMiningFinishCfg(backend.chainDB, *backend.chainConfig, backend.engine, miningStatePos, backend.miningSealingQuit, backend.blockReader, latestBlockBuiltStore),
), stagedsync.MiningUnwindOrder, stagedsync.MiningPruneOrder,
logger)
// We start the mining step
if err := stages2.MiningStep(ctx, backend.chainDB, proposingSync, tmpdir, logger); err != nil {
return nil, err
}
block := <-miningStatePos.MiningResultPOSCh
return block, nil
}
// Initialize ethbackend
ethBackendRPC := privateapi.NewEthBackendServer(ctx, backend, backend.chainDB, backend.notifications.Events, blockReader, logger, latestBlockBuiltStore)
// initialize engine backend
blockRetire := freezeblocks.NewBlockRetire(1, dirs, blockReader, blockWriter, backend.chainDB, backend.chainConfig, backend.notifications.Events, logger)
miningRPC = privateapi.NewMiningServer(ctx, backend, ethashApi, logger)
var creds credentials.TransportCredentials
if stack.Config().PrivateApiAddr != "" {
if stack.Config().TLSConnection {
creds, err = grpcutil.TLS(stack.Config().TLSCACert, stack.Config().TLSCertFile, stack.Config().TLSKeyFile)
if err != nil {
return nil, err
}
}
backend.privateAPI, err = privateapi.StartGrpc(
kvRPC,
ethBackendRPC,
backend.txPool2GrpcServer,
miningRPC,
stack.Config().PrivateApiAddr,
stack.Config().PrivateApiRateLimit,
creds,
stack.Config().HealthCheck,
logger)
if err != nil {
return nil, fmt.Errorf("private api: %w", err)
}
}
if currentBlock == nil {
currentBlock = genesis
}
// We start the transaction pool on startup, for a couple of reasons:
// 1) Hive tests requires us to do so and starting it from eth_sendRawTransaction is not viable as we have not enough data
// to initialize it properly.
// 2) we cannot propose for block 1 regardless.
tx, err := backend.chainDB.BeginRw(ctx)
if err != nil {
return nil, err
}
defer tx.Rollback()
if !config.DeprecatedTxPool.Disable {
// we need to start the pool before stage loop itself
// the pool holds the info about how execution stage should work - as regular or as limbo recovery
if err := backend.txPool2.StartIfNotStarted(ctx, backend.txPool2DB, tx); err != nil {
return nil, err
}
backend.txPool2Fetch.ConnectCore()
backend.txPool2Fetch.ConnectSentries()
var newTxsBroadcaster *txpool2.NewSlotsStreams
if casted, ok := backend.txPool2GrpcServer.(*txpool2.GrpcServer); ok {
newTxsBroadcaster = casted.NewSlotsStreams
}
go txpool2.MainLoop(backend.sentryCtx,
backend.txPool2DB, backend.chainDB, backend.txPool2, backend.newTxs2, backend.txPool2Send, newTxsBroadcaster,
func() {
select {
case backend.notifyMiningAboutNewTxs <- struct{}{}:
default:
}
},
)
}
go func() {
defer debug.LogPanic()
for {
select {
case b := <-backend.minedBlocks:
// Add mined header and block body before broadcast. This is because the broadcast call
// will trigger the staged sync which will require headers and blocks to be available
// in their respective cache in the download stage. If not found, it would cause a
// liveness issue for the chain.
if err := backend.sentriesClient.Hd.AddMinedHeader(b.Header()); err != nil {
logger.Error("add mined block to header downloader", "err", err)
}
backend.sentriesClient.Bd.AddToPrefetch(b.Header(), b.RawBody())
//p2p
//backend.sentriesClient.BroadcastNewBlock(context.Background(), b, b.Difficulty())
//rpcdaemon
if err := miningRPC.(*privateapi.MiningServer).BroadcastMinedBlock(b); err != nil {
logger.Error("txpool rpc mined block broadcast", "err", err)
}
logger.Trace("BroadcastMinedBlock successful", "number", b.Number(), "GasUsed", b.GasUsed(), "txn count", b.Transactions().Len())
backend.sentriesClient.PropagateNewBlockHashes(ctx, []headerdownload.Announce{
{
Number: b.NumberU64(),
Hash: b.Hash(),
},
})
case b := <-backend.pendingBlocks:
if err := miningRPC.(*privateapi.MiningServer).BroadcastPendingBlock(b); err != nil {
logger.Error("txpool rpc pending block broadcast", "err", err)
}
case <-backend.sentriesClient.Hd.QuitPoWMining:
return
}
}
}()
if err := backend.StartMining(context.Background(), backend.chainDB, stateDiffClient, mining, miner, backend.gasPrice, backend.sentriesClient.Hd.QuitPoWMining, tmpdir, logger); err != nil {
return nil, err
}
backend.ethBackendRPC, backend.miningRPC, backend.stateChangesClient = ethBackendRPC, miningRPC, stateDiffClient
// backend.syncStages = stages2.NewDefaultStages(backend.sentryCtx, backend.chainDB, snapDb, p2pConfig, config, backend.sentriesClient, backend.notifications, backend.downloaderClient,
// blockReader, blockRetire, backend.agg, backend.silkworm, backend.forkValidator, heimdallClient, recents, signatures, logger)
// backend.syncUnwindOrder = stagedsync.DefaultUnwindOrder
// backend.syncPruneOrder = stagedsync.DefaultPruneOrder
// backend.stagedSync = stagedsync.New(config.Sync, backend.syncStages, backend.syncUnwindOrder, backend.syncPruneOrder, logger)
hook := stages2.NewHook(backend.sentryCtx, backend.chainDB, backend.notifications, backend.stagedSync, backend.blockReader, backend.chainConfig, backend.logger, backend.sentriesClient.SetStatus)
if !config.Sync.UseSnapshots && backend.downloaderClient != nil {
for _, p := range blockReader.AllTypes() {
backend.downloaderClient.ProhibitNewDownloads(ctx, &protodownloader.ProhibitNewDownloadsRequest{
Type: p.Name(),
})
}
for _, p := range snaptype.CaplinSnapshotTypes {
backend.downloaderClient.ProhibitNewDownloads(ctx, &protodownloader.ProhibitNewDownloadsRequest{
Type: p.Name(),
})
}
}
checkStateRoot := true
pipelineStages := stages2.NewPipelineStages(ctx, chainKv, config, p2pConfig, backend.sentriesClient, backend.notifications, backend.downloaderClient, blockReader, blockRetire, backend.agg, backend.silkworm, backend.forkValidator, logger, checkStateRoot)
backend.pipelineStagedSync = stagedsync.New(config.Sync, pipelineStages, stagedsync.PipelineUnwindOrder, stagedsync.PipelinePruneOrder, logger)
backend.eth1ExecutionServer = eth1.NewEthereumExecutionModule(blockReader, chainKv, backend.pipelineStagedSync, backend.forkValidator, chainConfig, assembleBlockPOS, hook, backend.notifications.Accumulator, backend.notifications.StateChangesConsumer, logger, backend.engine, config.HistoryV3, ctx)
executionRpc := direct.NewExecutionClientDirect(backend.eth1ExecutionServer)
engineBackendRPC := engineapi.NewEngineServer(
logger,
chainConfig,
executionRpc,
backend.sentriesClient.Hd,
engine_block_downloader.NewEngineBlockDownloader(ctx,
logger, backend.sentriesClient.Hd, executionRpc,
backend.sentriesClient.Bd, backend.sentriesClient.BroadcastNewBlock, backend.sentriesClient.SendBodyRequest, blockReader,
chainKv, chainConfig, tmpdir, config.Sync.BodyDownloadTimeoutSeconds),
false,
config.Miner.EnabledPOS)
backend.engineBackendRPC = engineBackendRPC
// var executionEngine executionclient.ExecutionEngine
// // Gnosis has too few blocks on his network for phase2 to work. Once we have proper snapshot automation, it can go back to normal.
// if config.NetworkID == uint64(clparams.GnosisNetwork) || config.NetworkID == uint64(clparams.HoleskyNetwork) || config.NetworkID == uint64(clparams.GoerliNetwork) {
// // Read the jwt secret
// jwtSecret, err := cli.ObtainJWTSecret(&stack.Config().Http, logger)
// if err != nil {
// return nil, err
// }
// executionEngine, err = executionclient.NewExecutionClientRPC(jwtSecret, stack.Config().Http.AuthRpcHTTPListenAddress, stack.Config().Http.AuthRpcPort)
// if err != nil {
// return nil, err
// }
// } else {
// executionEngine, err = executionclient.NewExecutionClientDirect(eth1_chain_reader.NewChainReaderEth1(chainConfig, executionRpc, 1000))
// if err != nil {
// return nil, err
// }
// }
// // If we choose not to run a consensus layer, run our embedded.
// if config.InternalCL && clparams.EmbeddedSupported(config.NetworkID) {
// genesisCfg, networkCfg, beaconCfg := clparams.GetConfigsByNetwork(clparams.NetworkType(config.NetworkID))
// if err != nil {
// return nil, err
// }
// state, err := clcore.RetrieveBeaconState(ctx, beaconCfg, genesisCfg,
// clparams.GetCheckpointSyncEndpoint(clparams.NetworkType(config.NetworkID)))
// if err != nil {
// return nil, err
// }
// pruneBlobDistance := uint64(128600)
// if config.CaplinConfig.BlobBackfilling || config.CaplinConfig.BlobPruningDisabled {
// pruneBlobDistance = math.MaxUint64
// }
// indiciesDB, blobStorage, err := caplin1.OpenCaplinDatabase(ctx, db_config.DefaultDatabaseConfiguration, beaconCfg, genesisCfg, dirs.CaplinIndexing, dirs.CaplinBlobs, executionEngine, false, pruneBlobDistance)
// if err != nil {
// return nil, err
// }
// go func() {
// eth1Getter := getters.NewExecutionSnapshotReader(ctx, beaconCfg, blockReader, backend.chainDB)
// if err := caplin1.RunCaplinPhase1(ctx, executionEngine, config, networkCfg, beaconCfg, genesisCfg, state, dirs, eth1Getter, backend.downloaderClient, config.CaplinConfig.Backfilling, config.CaplinConfig.BlobBackfilling, config.CaplinConfig.Archive, indiciesDB, blobStorage, creds); err != nil {
// logger.Error("could not start caplin", "err", err)
// }
// ctxCancel()
// }()
// }
// if config.PolygonSync {
// // TODO - pending sentry multi client refactor
// // - sentry multi client should conform to the SentryClient interface and internally
// // multiplex
// // - for now we just use 1 sentry
// var sentryClient direct.SentryClient
// for _, client := range sentries {
// if client.Protocol() == direct.ETH68 {
// sentryClient = client
// break
// }
// }
// if sentryClient == nil {
// return nil, errors.New("nil sentryClient for polygon sync")
// }
// backend.polygonSyncService = polygonsync.NewService(
// logger,
// chainConfig,
// sentryClient,
// p2pConfig.MaxPeers,
// statusDataProvider,
// config.HeimdallURL,
// executionEngine,
// )
// }
// create buckets
if err := createBuckets(tx); err != nil {
return nil, err
}
// record erigon version
err = recordStartupVersionInDb(tx)
if err != nil {
log.Warn("failed to record erigon version in db", "err", err)
}
executionProgress, err := stages.GetStageProgress(tx, stages.Execution)
if err != nil {
return nil, err
}
if backend.config.Zk != nil {
// zkevm: create a data stream server if we have the appropriate config for one. This will be started on the call to Init
// alongside the http server
httpCfg := stack.Config().Http
if httpCfg.DataStreamPort > 0 && httpCfg.DataStreamHost != "" {
file := stack.Config().Dirs.DataDir + "/data-stream"
logConfig := &log2.Config{
Environment: "production",
Level: "warn",
Outputs: nil,
}
// todo [zkevm] read the stream version from config and figure out what system id is used for
backend.streamServer, err = dataStreamServerFactory.CreateStreamServer(uint16(httpCfg.DataStreamPort), uint8(backend.config.DatastreamVersion), 1, datastreamer.StreamType(1), file, httpCfg.DataStreamWriteTimeout, httpCfg.DataStreamInactivityTimeout, httpCfg.DataStreamInactivityCheckInterval, logConfig)
if err != nil {
return nil, err
}
// recovery here now, if the stream got into a bad state we want to be able to delete the file and have
// the stream re-populated from scratch. So we check the stream for the latest header and if it is
// 0 we can just set the datastream progress to 0 also which will force a re-population of the stream
latestHeader := backend.streamServer.GetHeader()
if latestHeader.TotalEntries == 0 {
log.Info("[dataStream] setting the stream progress to 0")
backend.preStartTasks.WarmUpDataStream = true
}
}
// entering ZK territory!