forked from erigontech/erigon
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbackend.go
1780 lines (1565 loc) · 59.2 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
// (original work)
// Copyright 2024 The Erigon Authors
// (modifications)
// This file is part of Erigon.
//
// Erigon 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.
//
// Erigon 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 Erigon. If not, see <http://www.gnu.org/licenses/>.
// Package eth implements the Ethereum protocol.
package eth
import (
"context"
"errors"
"fmt"
"io/fs"
"math"
"math/big"
"net"
"os"
"path/filepath"
"slices"
"strconv"
"strings"
"sync"
"sync/atomic"
"time"
"github.com/erigontech/erigon-lib/common/dir"
"github.com/erigontech/mdbx-go/mdbx"
lru "github.com/hashicorp/golang-lru/arc/v2"
"github.com/holiman/uint256"
"golang.org/x/sync/errgroup"
"golang.org/x/sync/semaphore"
"google.golang.org/grpc"
"google.golang.org/grpc/credentials"
"google.golang.org/protobuf/types/known/emptypb"
"github.com/erigontech/erigon-lib/chain"
"github.com/erigontech/erigon-lib/chain/networkname"
"github.com/erigontech/erigon-lib/chain/snapcfg"
libcommon "github.com/erigontech/erigon-lib/common"
"github.com/erigontech/erigon-lib/common/datadir"
"github.com/erigontech/erigon-lib/common/dbg"
"github.com/erigontech/erigon-lib/common/disk"
"github.com/erigontech/erigon-lib/common/mem"
"github.com/erigontech/erigon-lib/config3"
"github.com/erigontech/erigon-lib/diagnostics"
"github.com/erigontech/erigon-lib/direct"
"github.com/erigontech/erigon-lib/downloader"
"github.com/erigontech/erigon-lib/downloader/downloadercfg"
"github.com/erigontech/erigon-lib/downloader/downloadergrpc"
"github.com/erigontech/erigon-lib/downloader/snaptype"
protodownloader "github.com/erigontech/erigon-lib/gointerfaces/downloaderproto"
"github.com/erigontech/erigon-lib/gointerfaces/grpcutil"
remote "github.com/erigontech/erigon-lib/gointerfaces/remoteproto"
rpcsentinel "github.com/erigontech/erigon-lib/gointerfaces/sentinelproto"
protosentry "github.com/erigontech/erigon-lib/gointerfaces/sentryproto"
"github.com/erigontech/erigon-lib/gointerfaces/txpoolproto"
prototypes "github.com/erigontech/erigon-lib/gointerfaces/typesproto"
"github.com/erigontech/erigon-lib/kv"
"github.com/erigontech/erigon-lib/kv/kvcache"
"github.com/erigontech/erigon-lib/kv/remotedbserver"
"github.com/erigontech/erigon-lib/kv/temporal"
"github.com/erigontech/erigon-lib/log/v3"
libstate "github.com/erigontech/erigon-lib/state"
"github.com/erigontech/erigon-lib/txpool"
"github.com/erigontech/erigon-lib/txpool/txpoolcfg"
"github.com/erigontech/erigon-lib/txpool/txpoolutil"
libtypes "github.com/erigontech/erigon-lib/types"
"github.com/erigontech/erigon-lib/wrap"
"github.com/erigontech/erigon/cl/clparams"
"github.com/erigontech/erigon/cl/persistence/format/snapshot_format/getters"
"github.com/erigontech/erigon/cl/phase1/core/checkpoint_sync"
executionclient "github.com/erigontech/erigon/cl/phase1/execution_client"
"github.com/erigontech/erigon/cl/utils/eth_clock"
"github.com/erigontech/erigon/cmd/caplin/caplin1"
"github.com/erigontech/erigon/cmd/rpcdaemon/cli"
"github.com/erigontech/erigon/common/debug"
"github.com/erigontech/erigon/consensus"
"github.com/erigontech/erigon/consensus/clique"
"github.com/erigontech/erigon/consensus/mainnet"
"github.com/erigontech/erigon/consensus/merge"
"github.com/erigontech/erigon/consensus/misc"
"github.com/erigontech/erigon/core"
"github.com/erigontech/erigon/core/rawdb"
"github.com/erigontech/erigon/core/rawdb/blockio"
snaptype2 "github.com/erigontech/erigon/core/snaptype"
"github.com/erigontech/erigon/core/types"
"github.com/erigontech/erigon/core/vm"
"github.com/erigontech/erigon/crypto"
"github.com/erigontech/erigon/eth/consensuschain"
"github.com/erigontech/erigon/eth/ethconfig"
"github.com/erigontech/erigon/eth/ethconsensusconfig"
"github.com/erigontech/erigon/eth/ethutils"
"github.com/erigontech/erigon/eth/protocols/eth"
"github.com/erigontech/erigon/eth/stagedsync"
"github.com/erigontech/erigon/eth/stagedsync/stages"
"github.com/erigontech/erigon/ethdb/privateapi"
"github.com/erigontech/erigon/ethdb/prune"
"github.com/erigontech/erigon/ethstats"
"github.com/erigontech/erigon/node"
"github.com/erigontech/erigon/p2p"
"github.com/erigontech/erigon/p2p/enode"
"github.com/erigontech/erigon/p2p/sentry"
"github.com/erigontech/erigon/p2p/sentry/sentry_multi_client"
"github.com/erigontech/erigon/params"
"github.com/erigontech/erigon/polygon/bor"
"github.com/erigontech/erigon/polygon/bor/borcfg"
"github.com/erigontech/erigon/polygon/bor/finality/flags"
"github.com/erigontech/erigon/polygon/bor/valset"
"github.com/erigontech/erigon/polygon/bridge"
"github.com/erigontech/erigon/polygon/heimdall"
polygonsync "github.com/erigontech/erigon/polygon/sync"
"github.com/erigontech/erigon/rpc"
"github.com/erigontech/erigon/turbo/builder"
"github.com/erigontech/erigon/turbo/engineapi"
"github.com/erigontech/erigon/turbo/engineapi/engine_block_downloader"
"github.com/erigontech/erigon/turbo/engineapi/engine_helpers"
"github.com/erigontech/erigon/turbo/execution/eth1"
"github.com/erigontech/erigon/turbo/execution/eth1/eth1_chain_reader.go"
"github.com/erigontech/erigon/turbo/jsonrpc"
"github.com/erigontech/erigon/turbo/services"
"github.com/erigontech/erigon/turbo/shards"
"github.com/erigontech/erigon/turbo/silkworm"
"github.com/erigontech/erigon/turbo/snapshotsync/freezeblocks"
stages2 "github.com/erigontech/erigon/turbo/stages"
"github.com/erigontech/erigon/turbo/stages/headerdownload"
)
// Config contains the configuration options of the ETH protocol.
// Deprecated: use ethconfig.Config instead.
type Config = ethconfig.Config
// 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 txpool.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{}
txPoolDB kv.RwDB
txPool *txpool.TxPool
newTxs chan libtypes.Announcements
txPoolFetch *txpool.Fetch
txPoolSend *txpool.Send
txPoolGrpcServer 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
sentinel rpcsentinel.SentinelClient
silkworm *silkworm.Silkworm
silkwormRPCDaemonService *silkworm.RpcDaemonService
silkwormSentryService *silkworm.SentryService
polygonSyncService polygonsync.Service
polygonBridge bridge.PolygonBridge
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) {
if config.Miner.GasPrice == nil || config.Miner.GasPrice.Sign() <= 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
}
return nil
}); err != nil {
return nil, err
}
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(),
},
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 {
if config.Genesis == nil {
genesisConfig, err := rawdb.ReadGenesis(tx)
if err != nil {
return err
}
config.Genesis = genesisConfig
}
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, dirs, 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)
logger.Info("Initialised chain configuration", "config", chainConfig, "genesis", genesis.Hash())
if dbg.OnlyCreateDB {
logger.Info("done")
os.Exit(1)
}
// 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, chainConfig.Bor != nil, logger)
if err != nil {
return nil, err
}
backend.agg, backend.blockSnapshots, backend.blockReader, backend.blockWriter = agg, allSnapshots, blockReader, blockWriter
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); 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
}
}
if len(peerCountMap) == 0 {
logger.Warn("[p2p] No GoodPeers")
} else {
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 := backend.chainDB.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 = &mainnet.MainnetConfig{}
}
var heimdallClient heimdall.HeimdallClient
var polygonBridge bridge.Service
var heimdallService heimdall.Service
if chainConfig.Bor != nil {
if !config.WithoutHeimdall {
heimdallClient = heimdall.NewHeimdallClient(config.HeimdallURL, logger)
}
if config.PolygonSync {
polygonBridge = bridge.Assemble(config.Dirs.DataDir, logger, consensusConfig.(*borcfg.BorConfig), heimdallClient.FetchStateSyncEvents, bor.GenesisContractStateReceiverABI())
heimdallService = heimdall.AssembleService(consensusConfig.(*borcfg.BorConfig), config.HeimdallURL, dirs.DataDir, tmpdir, logger)
backend.polygonBridge = polygonBridge
}
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, polygonBridge, heimdallService)
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 := consensuschain.NewReader(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.ImportMode); err != nil {
logger.Warn("Could not validate block", "err", err)
return errors.Join(consensus.ErrInvalidBlock, err)
}
var progress uint64
progress, err = stages.GetStageProgress(txc.Tx, stages.Execution)
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 || config.PolygonSyncStage
backend.sentriesClient, err = sentry_multi_client.NewMultiClient(
backend.chainDB,
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.txPoolGrpcServer = &txpool.GrpcDisabled{}
} else {
//cacheConfig := kvcache.DefaultCoherentCacheConfig
//cacheConfig.MetricsLabel = "txpool"
//cacheConfig.StateV3 = config.HistoryV3w
backend.newTxs = make(chan libtypes.Announcements, 1024)
//defer close(newTxs)
backend.txPoolDB, backend.txPool, backend.txPoolFetch, backend.txPoolSend, backend.txPoolGrpcServer, err = txpoolutil.AllComponents(
ctx, config.TxPool, kvcache.NewDummy(), backend.newTxs, chainKv, backend.sentriesClient.Sentries(), stateDiffClient, misc.Eip1559FeeCalculator, logger,
)
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.txPoolDB, nil, tmpdir, backend.blockReader),
stagedsync.StageBorHeimdallCfg(backend.chainDB, snapDb, miner, *backend.chainConfig, heimdallClient, backend.blockReader, nil, nil, recents, signatures, false, nil), stagedsync.StageExecuteBlocksCfg(
backend.chainDB,
config.Prune,
config.BatchSize,
chainConfig,
backend.engine,
&vm.Config{},
backend.notifications.Accumulator,
config.StateStream,
/*stateStream=*/ false,
dirs,
blockReader,
backend.sentriesClient.Hd,
config.Genesis,
config.Sync,
stages2.SilkwormForExecutionStage(backend.silkworm, config),
),
stagedsync.StageSendersCfg(backend.chainDB, chainConfig, config.Sync, false, dirs.Tmp, config.Prune, blockReader, backend.sentriesClient.Hd),
stagedsync.StageMiningExecCfg(backend.chainDB, miner, backend.notifications.Events, *backend.chainConfig, backend.engine, &vm.Config{}, tmpdir, nil, 0, backend.txPool, backend.txPoolDB, blockReader),
stagedsync.StageMiningFinishCfg(backend.chainDB, *backend.chainConfig, backend.engine, miner, backend.miningSealingQuit, backend.blockReader, latestBlockBuiltStore),
), stagedsync.MiningUnwindOrder, stagedsync.MiningPruneOrder,
logger)
// setup snapcfg
if err := loadSnapshotsEitherFromDiskIfNeeded(dirs, chainConfig.ChainName); err != nil {
return nil, err
}
// 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.txPoolDB, param, tmpdir, backend.blockReader),
stagedsync.StageBorHeimdallCfg(backend.chainDB, snapDb, miningStatePos, *backend.chainConfig, heimdallClient, backend.blockReader, nil, nil, recents, signatures, false, nil),
stagedsync.StageExecuteBlocksCfg(
backend.chainDB,
config.Prune,
config.BatchSize,
chainConfig,
backend.engine,
&vm.Config{},
backend.notifications.Accumulator,
config.StateStream,
/*stateStream=*/ false,
dirs,
blockReader,
backend.sentriesClient.Hd,
config.Genesis,
config.Sync,
stages2.SilkwormForExecutionStage(backend.silkworm, config),
),
stagedsync.StageSendersCfg(backend.chainDB, chainConfig, config.Sync, false, dirs.Tmp, config.Prune, blockReader, backend.sentriesClient.Hd),
stagedsync.StageMiningExecCfg(backend.chainDB, miningStatePos, backend.notifications.Events, *backend.chainConfig, backend.engine, &vm.Config{}, tmpdir, interrupt, param.PayloadId, backend.txPool, backend.txPoolDB, blockReader),
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
blockSnapBuildSema := semaphore.NewWeighted(int64(dbg.BuildSnapshotAllowance))
agg.SetSnapshotBuildSema(blockSnapBuildSema)
blockRetire := freezeblocks.NewBlockRetire(1, dirs, blockReader, blockWriter, backend.chainDB, backend.chainConfig, backend.notifications.Events, blockSnapBuildSema, logger)
miningRPC = privateapi.NewMiningServer(ctx, backend, 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.txPoolGrpcServer,
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.
if !config.DeprecatedTxPool.Disable {
backend.txPoolFetch.ConnectCore()
backend.txPoolFetch.ConnectSentries()
var newTxsBroadcaster *txpool.NewSlotsStreams
if casted, ok := backend.txPoolGrpcServer.(*txpool.GrpcServer); ok {
newTxsBroadcaster = casted.NewSlotsStreams
}
go txpool.MainLoop(backend.sentryCtx,
backend.txPoolDB, backend.txPool, backend.newTxs, backend.txPoolSend, 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
if config.PolygonSyncStage {
backend.syncStages = stages2.NewPolygonSyncStages(
backend.sentryCtx,
logger,
backend.chainDB,
config,
backend.chainConfig,
backend.engine,
backend.notifications,
backend.downloaderClient,
blockReader,
blockRetire,
backend.agg,
backend.silkworm,
backend.forkValidator,
heimdallClient,
polygonSyncSentry(sentries),
p2pConfig.MaxPeers,
statusDataProvider,
backend.stopNode,
)
backend.syncUnwindOrder = stagedsync.PolygonSyncUnwindOrder
backend.syncPruneOrder = stagedsync.PolygonSyncPruneOrder
} else {
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)
useSnapshots := blockReader != nil && (blockReader.FreezingCfg().ProduceE2 || blockReader.FreezingCfg().ProduceE3)
if !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(),
})
}
for _, p := range snaptype2.E3StateTypes {
backend.downloaderClient.ProhibitNewDownloads(ctx, &protodownloader.ProhibitNewDownloadsRequest{
Type: p.Name(),
})
}
}
checkStateRoot := true
pipelineStages := stages2.NewPipelineStages(ctx, backend.chainDB, 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, backend.chainDB, backend.pipelineStagedSync, backend.forkValidator, chainConfig, assembleBlockPOS, hook, backend.notifications.Accumulator, backend.notifications.StateChangesConsumer, logger, backend.engine, config.Sync, ctx)
executionRpc := direct.NewExecutionClientDirect(backend.eth1ExecutionServer)
var executionEngine executionclient.ExecutionEngine
executionEngine, err = executionclient.NewExecutionClientDirect(eth1_chain_reader.NewChainReaderEth1(chainConfig, executionRpc, 1000))
if err != nil {
return nil, err
}
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,
backend.chainDB, chainConfig, tmpdir, config.Sync),
config.InternalCL, // If the chain supports the engine API, then we should not make the server fail.
false,
config.Miner.EnabledPOS)
backend.engineBackendRPC = engineBackendRPC
// If we choose not to run a consensus layer, run our embedded.
if config.InternalCL && clparams.EmbeddedSupported(config.NetworkID) {
networkCfg, beaconCfg := clparams.GetConfigsByNetwork(clparams.NetworkType(config.NetworkID))
if err != nil {
return nil, err
}
config.CaplinConfig.NetworkId = clparams.NetworkType(config.NetworkID)
state, err := checkpoint_sync.ReadOrFetchLatestBeaconState(ctx, dirs, beaconCfg, config.CaplinConfig)
if err != nil {
return nil, err
}
ethClock := eth_clock.NewEthereumClock(state.GenesisTime(), state.GenesisValidatorsRoot(), beaconCfg)
pruneBlobDistance := uint64(128600)
if config.CaplinConfig.BlobBackfilling || config.CaplinConfig.BlobPruningDisabled {
pruneBlobDistance = math.MaxUint64
}
indiciesDB, blobStorage, err := caplin1.OpenCaplinDatabase(ctx, beaconCfg, ethClock, dirs.CaplinIndexing, dirs.CaplinBlobs, executionEngine, false, pruneBlobDistance)
if err != nil {
return nil, err
}
go func() {
caplinOpt := []caplin1.CaplinOption{}
if config.BeaconRouter.Builder {
if config.CaplinConfig.RelayUrlExist() {
caplinOpt = append(caplinOpt, caplin1.WithBuilder(config.CaplinConfig.MevRelayUrl, beaconCfg))
} else {
log.Warn("builder api enable but relay url not set. Skipping builder mode")
config.BeaconRouter.Builder = false
}
}
log.Info("Starting caplin")
eth1Getter := getters.NewExecutionSnapshotReader(ctx, beaconCfg, blockReader, backend.chainDB)
if err := caplin1.RunCaplinPhase1(ctx, executionEngine, config, networkCfg, beaconCfg, ethClock,
state, dirs, eth1Getter, backend.downloaderClient, indiciesDB, blobStorage, creds,
blockSnapBuildSema, caplinOpt...); err != nil {
logger.Error("could not start caplin", "err", err)
}
ctxCancel()
}()
}
if config.PolygonSync {
backend.polygonSyncService = polygonsync.NewService(
logger,
chainConfig,
polygonSyncSentry(sentries),
p2pConfig.MaxPeers,
statusDataProvider,
executionRpc,
config.LoopBlockLimit,
polygonBridge,
heimdallService,
)
}
return backend, nil
}
func (s *Ethereum) Init(stack *node.Node, config *ethconfig.Config, chainConfig *chain.Config) error {
ethBackendRPC, miningRPC, stateDiffClient := s.ethBackendRPC, s.miningRPC, s.stateChangesClient
blockReader := s.blockReader