-
Notifications
You must be signed in to change notification settings - Fork 1.2k
/
Copy pathmain.go
701 lines (632 loc) · 23.3 KB
/
main.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
// Copyright 2024 The Erigon Authors
// 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 main
import (
"context"
"errors"
"fmt"
"io/fs"
"net"
"net/url"
"os"
"path/filepath"
"sort"
"strings"
"time"
"github.com/erigontech/erigon-lib/common/dbg"
_ "github.com/erigontech/erigon/core/snaptype" //hack
_ "github.com/erigontech/erigon/polygon/heimdall" //hack
"github.com/anacrolix/torrent/metainfo"
"github.com/c2h5oh/datasize"
grpc_middleware "github.com/grpc-ecosystem/go-grpc-middleware"
grpc_recovery "github.com/grpc-ecosystem/go-grpc-middleware/recovery"
"github.com/pelletier/go-toml/v2"
"github.com/spf13/cobra"
"google.golang.org/grpc"
"google.golang.org/grpc/credentials"
"google.golang.org/grpc/health"
"google.golang.org/grpc/health/grpc_health_v1"
"google.golang.org/grpc/keepalive"
"google.golang.org/grpc/reflection"
"github.com/erigontech/erigon-lib/chain/snapcfg"
"github.com/erigontech/erigon-lib/common"
"github.com/erigontech/erigon-lib/common/datadir"
"github.com/erigontech/erigon-lib/common/dir"
"github.com/erigontech/erigon-lib/downloader"
"github.com/erigontech/erigon-lib/downloader/downloadercfg"
"github.com/erigontech/erigon-lib/downloader/downloadergrpc"
proto_downloader "github.com/erigontech/erigon-lib/gointerfaces/downloaderproto"
"github.com/erigontech/erigon-lib/kv"
"github.com/erigontech/erigon-lib/kv/mdbx"
"github.com/erigontech/erigon-lib/log/v3"
"github.com/erigontech/erigon/cmd/downloader/downloadernat"
"github.com/erigontech/erigon/cmd/hack/tool"
"github.com/erigontech/erigon/cmd/utils"
"github.com/erigontech/erigon/common/paths"
"github.com/erigontech/erigon/p2p/nat"
"github.com/erigontech/erigon/params"
"github.com/erigontech/erigon/turbo/debug"
"github.com/erigontech/erigon/turbo/logging"
)
func main() {
ctx, cancel := common.RootContext()
defer cancel()
if err := rootCmd.ExecuteContext(ctx); err != nil {
fmt.Println(err)
os.Exit(1)
}
}
var (
webseeds string
datadirCli, chain string
filePath string
forceRebuild bool
verify bool
verifyFailfast bool
_verifyFiles string
verifyFiles []string
downloaderApiAddr string
natSetting string
torrentVerbosity int
downloadRateStr, uploadRateStr string
torrentDownloadSlots int
staticPeersStr string
torrentPort int
torrentMaxPeers int
torrentConnsPerFile int
targetFile string
disableIPV6 bool
disableIPV4 bool
seedbox bool
dbWritemap bool
all bool
)
func init() {
utils.CobraFlags(rootCmd, debug.Flags, utils.MetricFlags, logging.Flags)
withDataDir(rootCmd)
withChainFlag(rootCmd)
rootCmd.Flags().StringVar(&webseeds, utils.WebSeedsFlag.Name, utils.WebSeedsFlag.Value, utils.WebSeedsFlag.Usage)
rootCmd.Flags().StringVar(&natSetting, "nat", utils.NATFlag.Value, utils.NATFlag.Usage)
rootCmd.Flags().StringVar(&downloaderApiAddr, "downloader.api.addr", "127.0.0.1:9093", "external downloader api network address, for example: 127.0.0.1:9093 serves remote downloader interface")
rootCmd.Flags().StringVar(&downloadRateStr, "torrent.download.rate", utils.TorrentDownloadRateFlag.Value, utils.TorrentDownloadRateFlag.Usage)
rootCmd.Flags().StringVar(&uploadRateStr, "torrent.upload.rate", utils.TorrentUploadRateFlag.Value, utils.TorrentUploadRateFlag.Usage)
rootCmd.Flags().IntVar(&torrentVerbosity, "torrent.verbosity", utils.TorrentVerbosityFlag.Value, utils.TorrentVerbosityFlag.Usage)
rootCmd.Flags().IntVar(&torrentPort, "torrent.port", utils.TorrentPortFlag.Value, utils.TorrentPortFlag.Usage)
rootCmd.Flags().IntVar(&torrentMaxPeers, "torrent.maxpeers", utils.TorrentMaxPeersFlag.Value, utils.TorrentMaxPeersFlag.Usage)
rootCmd.Flags().IntVar(&torrentConnsPerFile, "torrent.conns.perfile", utils.TorrentConnsPerFileFlag.Value, utils.TorrentConnsPerFileFlag.Usage)
rootCmd.Flags().IntVar(&torrentDownloadSlots, "torrent.download.slots", utils.TorrentDownloadSlotsFlag.Value, utils.TorrentDownloadSlotsFlag.Usage)
rootCmd.Flags().StringVar(&staticPeersStr, utils.TorrentStaticPeersFlag.Name, utils.TorrentStaticPeersFlag.Value, utils.TorrentStaticPeersFlag.Usage)
rootCmd.Flags().BoolVar(&disableIPV6, "downloader.disable.ipv6", utils.DisableIPV6.Value, utils.DisableIPV6.Usage)
rootCmd.Flags().BoolVar(&disableIPV4, "downloader.disable.ipv4", utils.DisableIPV4.Value, utils.DisableIPV6.Usage)
rootCmd.Flags().BoolVar(&seedbox, "seedbox", false, "Turns downloader into independent (doesn't need Erigon) software which discover/download/seed new files - useful for Erigon network, and can work on very cheap hardware. It will: 1) download .torrent from webseed 2) download new files after upgrade 3) we planing add discovery of new files soon")
rootCmd.Flags().BoolVar(&dbWritemap, utils.DbWriteMapFlag.Name, utils.DbWriteMapFlag.Value, utils.DbWriteMapFlag.Usage)
rootCmd.PersistentFlags().BoolVar(&verify, "verify", false, utils.DownloaderVerifyFlag.Usage)
rootCmd.PersistentFlags().StringVar(&_verifyFiles, "verify.files", "", "Limit list of files to verify")
rootCmd.PersistentFlags().BoolVar(&verifyFailfast, "verify.failfast", false, "Stop on first found error. Report it and exit")
withDataDir(createTorrent)
withFile(createTorrent)
withChainFlag(createTorrent)
rootCmd.AddCommand(createTorrent)
createTorrent.Flags().BoolVar(&all, "all", false, "Produce all possible .torrent files")
rootCmd.AddCommand(torrentCat)
rootCmd.AddCommand(torrentMagnet)
withDataDir(torrentClean)
rootCmd.AddCommand(torrentClean)
withDataDir(manifestCmd)
withChainFlag(manifestCmd)
rootCmd.AddCommand(manifestCmd)
manifestCmd.Flags().BoolVar(&all, "all", false, "Produce all possible .torrent files")
manifestVerifyCmd.Flags().StringVar(&webseeds, utils.WebSeedsFlag.Name, utils.WebSeedsFlag.Value, utils.WebSeedsFlag.Usage)
manifestVerifyCmd.PersistentFlags().BoolVar(&verifyFailfast, "verify.failfast", false, "Stop on first found error. Report it and exit")
withChainFlag(manifestVerifyCmd)
rootCmd.AddCommand(manifestVerifyCmd)
withDataDir(printTorrentHashes)
withChainFlag(printTorrentHashes)
printTorrentHashes.Flags().BoolVar(&all, "all", false, "Produce all possible .torrent files")
printTorrentHashes.PersistentFlags().BoolVar(&forceRebuild, "rebuild", false, "Force re-create .torrent files")
printTorrentHashes.Flags().StringVar(&targetFile, "targetfile", "", "write output to file")
if err := printTorrentHashes.MarkFlagFilename("targetfile"); err != nil {
panic(err)
}
rootCmd.AddCommand(printTorrentHashes)
}
func withDataDir(cmd *cobra.Command) {
cmd.Flags().StringVar(&datadirCli, utils.DataDirFlag.Name, paths.DefaultDataDir(), utils.DataDirFlag.Usage)
must(cmd.MarkFlagRequired(utils.DataDirFlag.Name))
must(cmd.MarkFlagDirname(utils.DataDirFlag.Name))
}
func withChainFlag(cmd *cobra.Command) {
cmd.Flags().StringVar(&chain, utils.ChainFlag.Name, utils.ChainFlag.Value, utils.ChainFlag.Usage)
must(cmd.MarkFlagRequired(utils.ChainFlag.Name))
}
func withFile(cmd *cobra.Command) {
cmd.Flags().StringVar(&filePath, "file", "", "")
if err := cmd.MarkFlagFilename(utils.DataDirFlag.Name); err != nil {
panic(err)
}
}
func must(err error) {
if err != nil {
panic(err)
}
}
var logger log.Logger
var rootCmd = &cobra.Command{
Use: "",
Short: "snapshot downloader",
Example: "go run ./cmd/downloader --datadir <your_datadir> --downloader.api.addr 127.0.0.1:9093",
PersistentPostRun: func(cmd *cobra.Command, args []string) {
debug.Exit()
},
PersistentPreRun: func(cmd *cobra.Command, args []string) {
if cmd.Name() != "torrent_cat" {
logger = debug.SetupCobra(cmd, "downloader")
logger.Info("Build info", "git_branch", params.GitBranch, "git_tag", params.GitTag, "git_commit", params.GitCommit)
}
},
Run: func(cmd *cobra.Command, args []string) {
if err := Downloader(cmd.Context(), logger); err != nil {
if !errors.Is(err, context.Canceled) {
logger.Error(err.Error())
}
return
}
},
}
func Downloader(ctx context.Context, logger log.Logger) error {
dirs := datadir.New(datadirCli)
if err := datadir.ApplyMigrations(dirs); err != nil {
return err
}
if err := checkChainName(ctx, dirs, chain); err != nil {
return err
}
torrentLogLevel, _, err := downloadercfg.Int2LogLevel(torrentVerbosity)
if err != nil {
return err
}
var downloadRate, uploadRate datasize.ByteSize
if err := downloadRate.UnmarshalText([]byte(downloadRateStr)); err != nil {
return err
}
if err := uploadRate.UnmarshalText([]byte(uploadRateStr)); err != nil {
return err
}
logger.Info("[snapshots] cli flags", "chain", chain, "addr", downloaderApiAddr, "datadir", dirs.DataDir, "ipv6-enabled", !disableIPV6, "ipv4-enabled", !disableIPV4, "download.rate", downloadRate.String(), "upload.rate", uploadRate.String(), "webseed", webseeds)
staticPeers := common.CliString2Array(staticPeersStr)
version := "erigon: " + params.VersionWithCommit(params.GitCommit)
webseedsList := common.CliString2Array(webseeds)
if known, ok := snapcfg.KnownWebseeds[chain]; ok {
webseedsList = append(webseedsList, known...)
}
if seedbox {
_, err = downloadercfg.LoadSnapshotsHashes(ctx, dirs, chain)
if err != nil {
return err
}
}
cfg, err := downloadercfg.New(ctx, dirs, version, torrentLogLevel, downloadRate, uploadRate, torrentPort, torrentConnsPerFile, torrentDownloadSlots, staticPeers, webseedsList, chain, true, dbWritemap)
if err != nil {
return err
}
cfg.ClientConfig.PieceHashersPerTorrent = dbg.EnvInt("DL_HASHERS", 32)
cfg.ClientConfig.DisableIPv6 = disableIPV6
cfg.ClientConfig.DisableIPv4 = disableIPV4
natif, err := nat.Parse(natSetting)
if err != nil {
return fmt.Errorf("invalid nat option %s: %w", natSetting, err)
}
downloadernat.DoNat(natif, cfg.ClientConfig, logger)
cfg.AddTorrentsFromDisk = true // always true unless using uploader - which wants control of torrent files
d, err := downloader.New(ctx, cfg, logger, log.LvlInfo, seedbox)
if err != nil {
return err
}
defer d.Close()
logger.Info("[snapshots] Start bittorrent server", "my_peer_id", fmt.Sprintf("%x", d.TorrentClient().PeerID()))
if len(_verifyFiles) > 0 {
verifyFiles = strings.Split(_verifyFiles, ",")
}
if verify || verifyFailfast || len(verifyFiles) > 0 { // remove and create .torrent files (will re-read all snapshots)
if err = d.VerifyData(ctx, verifyFiles, verifyFailfast); err != nil {
return err
}
}
bittorrentServer, err := downloader.NewGrpcServer(d)
if err != nil {
return fmt.Errorf("new server: %w", err)
}
d.MainLoopInBackground(false)
if seedbox {
var downloadItems []*proto_downloader.AddItem
for _, it := range snapcfg.KnownCfg(chain).Preverified {
downloadItems = append(downloadItems, &proto_downloader.AddItem{
Path: it.Name,
TorrentHash: downloadergrpc.String2Proto(it.Hash),
})
}
if _, err := bittorrentServer.Add(ctx, &proto_downloader.AddRequest{Items: downloadItems}); err != nil {
return err
}
}
grpcServer, err := StartGrpc(bittorrentServer, downloaderApiAddr, nil /* transportCredentials */, logger)
if err != nil {
return err
}
defer grpcServer.GracefulStop()
<-ctx.Done()
return nil
}
var createTorrent = &cobra.Command{
Use: "torrent_create",
Example: "go run ./cmd/downloader torrent_create --datadir=<your_datadir> --file=<relative_file_path> ",
RunE: func(cmd *cobra.Command, args []string) error {
dirs := datadir.New(datadirCli)
if err := checkChainName(cmd.Context(), dirs, chain); err != nil {
return err
}
createdAmount, err := downloader.BuildTorrentFilesIfNeed(cmd.Context(), dirs, downloader.NewAtomicTorrentFS(dirs.Snap), chain, nil, all)
if err != nil {
return err
}
log.Info("created .torrent files", "amount", createdAmount)
return nil
},
}
var printTorrentHashes = &cobra.Command{
Use: "torrent_hashes",
Example: "go run ./cmd/downloader torrent_hashes --datadir <your_datadir>",
RunE: func(cmd *cobra.Command, args []string) error {
logger := debug.SetupCobra(cmd, "downloader")
if err := doPrintTorrentHashes(cmd.Context(), logger); err != nil {
log.Error(err.Error())
}
return nil
},
}
var manifestCmd = &cobra.Command{
Use: "manifest",
Example: "go run ./cmd/downloader manifest --datadir <your_datadir>",
RunE: func(cmd *cobra.Command, args []string) error {
logger := debug.SetupCobra(cmd, "downloader")
if err := manifest(cmd.Context(), logger); err != nil {
log.Error(err.Error())
}
return nil
},
}
var manifestVerifyCmd = &cobra.Command{
Use: "manifest-verify",
Example: "go run ./cmd/downloader manifest-verify --chain <chain> [--webseed 'a','b','c']",
RunE: func(cmd *cobra.Command, args []string) error {
logger := debug.SetupCobra(cmd, "downloader")
if err := manifestVerify(cmd.Context(), logger); err != nil {
log.Error(err.Error())
os.Exit(1) // to mark CI as failed
}
return nil
},
}
var torrentCat = &cobra.Command{
Use: "torrent_cat",
Example: "go run ./cmd/downloader torrent_cat <path_to_torrent_file>",
RunE: func(cmd *cobra.Command, args []string) error {
if len(args) == 0 {
return errors.New("please pass .torrent file path by first argument")
}
fPath := args[0]
mi, err := metainfo.LoadFromFile(fPath)
if err != nil {
return fmt.Errorf("LoadFromFile: %w, file=%s", err, fPath)
}
fmt.Printf("InfoHash = '%x'\n", mi.HashInfoBytes())
mi.InfoBytes = nil
bytes, err := toml.Marshal(mi)
if err != nil {
return err
}
fmt.Printf("%s\n", string(bytes))
return nil
},
}
var torrentClean = &cobra.Command{
Use: "torrent_clean",
Short: "Remove all .torrent files from datadir directory",
Example: "go run ./cmd/downloader torrent_clean --datadir=<datadir>",
RunE: func(cmd *cobra.Command, args []string) error {
dirs := datadir.New(datadirCli)
logger.Info("[snapshots.webseed] processing local file etags")
removedTorrents := 0
walker := func(path string, de fs.DirEntry, err error) error {
if err != nil || de.IsDir() {
if err != nil {
logger.Warn("[snapshots.torrent] walk and cleanup", "err", err, "path", path)
}
return nil //nolint
}
if !strings.HasSuffix(de.Name(), ".torrent") || strings.HasPrefix(de.Name(), ".") {
return nil
}
err = os.Remove(filepath.Join(dirs.Snap, path))
if err != nil {
logger.Warn("[snapshots.torrent] remove", "err", err, "path", path)
return err
}
removedTorrents++
return nil
}
sfs := os.DirFS(dirs.Snap)
if err := fs.WalkDir(sfs, ".", walker); err != nil {
return err
}
logger.Info("[snapshots.torrent] cleanup finished", "count", removedTorrents)
return nil
},
}
var torrentMagnet = &cobra.Command{
Use: "torrent_magnet",
Example: "go run ./cmd/downloader torrent_magnet <path_to_torrent_file>",
RunE: func(cmd *cobra.Command, args []string) error {
if len(args) == 0 {
return errors.New("please pass .torrent file path by first argument")
}
fPath := args[0]
mi, err := metainfo.LoadFromFile(fPath)
if err != nil {
return fmt.Errorf("LoadFromFile: %w, file=%s", err, fPath)
}
fmt.Printf("%s\n", mi.Magnet(nil, nil).String())
return nil
},
}
func manifestVerify(ctx context.Context, logger log.Logger) error {
webseedsList := common.CliString2Array(webseeds)
if len(webseedsList) == 0 { // fallback to default if exact list not passed
if known, ok := snapcfg.KnownWebseeds[chain]; ok {
for _, s := range known {
//TODO: enable validation of this buckets also. skipping to make CI useful.k
if strings.Contains(s, "erigon2-v2") {
continue
}
webseedsList = append(webseedsList, s)
}
}
}
webseedUrlsOrFiles := webseedsList
webseedHttpProviders := make([]*url.URL, 0, len(webseedUrlsOrFiles))
webseedFileProviders := make([]string, 0, len(webseedUrlsOrFiles))
for _, webseed := range webseedUrlsOrFiles {
if !strings.HasPrefix(webseed, "v") { // has marker v1/v2/...
uri, err := url.ParseRequestURI(webseed)
if err != nil {
exists, existsErr := dir.FileExist(webseed)
if existsErr != nil {
log.Warn("[webseed] FileExist error", "err", err)
continue
}
if strings.HasSuffix(webseed, ".toml") && exists {
webseedFileProviders = append(webseedFileProviders, webseed)
}
continue
}
webseedHttpProviders = append(webseedHttpProviders, uri)
continue
}
if strings.HasPrefix(webseed, "v1:") {
withoutVerisonPrefix := webseed[3:]
if !strings.HasPrefix(withoutVerisonPrefix, "https:") {
continue
}
uri, err := url.ParseRequestURI(withoutVerisonPrefix)
if err != nil {
log.Warn("[webseed] can't parse url", "err", err, "url", withoutVerisonPrefix)
continue
}
webseedHttpProviders = append(webseedHttpProviders, uri)
} else {
continue
}
}
if len(webseedFileProviders) > 0 {
logger.Warn("file providers are not supported yet", "fileProviders", webseedFileProviders)
}
wseed := downloader.NewWebSeeds(webseedHttpProviders, log.LvlDebug, logger)
return wseed.VerifyManifestedBuckets(ctx, verifyFailfast)
}
func manifest(ctx context.Context, logger log.Logger) error {
dirs := datadir.New(datadirCli)
files, err := downloader.SeedableFiles(dirs, chain, all)
if err != nil {
return err
}
extList := []string{
".torrent",
//".seg", ".idx", // e2
//".kv", ".kvi", ".bt", ".kvei", // e3 domain
//".v", ".vi", //e3 hist
//".ef", ".efi", //e3 idx
".txt", //salt-state.txt, salt-blocks.txt, manifest.txt
}
l, _ := dir.ListFiles(dirs.Snap, extList...)
for _, fPath := range l {
_, fName := filepath.Split(fPath)
files = append(files, fName)
}
l, _ = dir.ListFiles(dirs.SnapDomain, extList...)
for _, fPath := range l {
_, fName := filepath.Split(fPath)
files = append(files, "domain/"+fName)
}
l, _ = dir.ListFiles(dirs.SnapHistory, extList...)
for _, fPath := range l {
_, fName := filepath.Split(fPath)
if strings.Contains(fName, "commitment") {
continue
}
files = append(files, "history/"+fName)
}
l, _ = dir.ListFiles(dirs.SnapIdx, extList...)
for _, fPath := range l {
_, fName := filepath.Split(fPath)
if strings.Contains(fName, "commitment") {
continue
}
files = append(files, "idx/"+fName)
}
sort.Strings(files)
for _, f := range files {
fmt.Printf("%s\n", f)
}
return nil
}
func doPrintTorrentHashes(ctx context.Context, logger log.Logger) error {
dirs := datadir.New(datadirCli)
if err := datadir.ApplyMigrations(dirs); err != nil {
return err
}
tf := downloader.NewAtomicTorrentFS(dirs.Snap)
if forceRebuild { // remove and create .torrent files (will re-read all snapshots)
//removePieceCompletionStorage(snapDir)
files, err := downloader.AllTorrentPaths(dirs)
if err != nil {
return err
}
for _, filePath := range files {
if err := os.Remove(filePath); err != nil {
return err
}
}
createdAmount, err := downloader.BuildTorrentFilesIfNeed(ctx, dirs, tf, chain, nil, all)
if err != nil {
return fmt.Errorf("BuildTorrentFilesIfNeed: %w", err)
}
log.Info("created .torrent files", "amount", createdAmount)
}
res := map[string]string{}
torrents, err := downloader.AllTorrentSpecs(dirs, tf)
if err != nil {
return err
}
for _, t := range torrents {
// we don't release commitment history in this time. let's skip it here.
if strings.Contains(t.DisplayName, "history") && strings.Contains(t.DisplayName, "commitment") {
continue
}
if strings.Contains(t.DisplayName, "idx") && strings.Contains(t.DisplayName, "commitment") {
continue
}
res[t.DisplayName] = t.InfoHash.String()
}
serialized, err := toml.Marshal(res)
if err != nil {
return err
}
if targetFile == "" {
fmt.Printf("%s\n", serialized)
return nil
}
oldContent, err := os.ReadFile(targetFile)
if err != nil {
return err
}
oldLines := map[string]string{}
if err := toml.Unmarshal(oldContent, &oldLines); err != nil {
return fmt.Errorf("unmarshal: %w", err)
}
if len(oldLines) >= len(res) {
logger.Info("amount of lines in target file is equal or greater than amount of lines in snapshot dir", "old", len(oldLines), "new", len(res))
return nil
}
if err := os.WriteFile(targetFile, serialized, 0644); err != nil { // nolint
return err
}
return nil
}
func StartGrpc(snServer *downloader.GrpcServer, addr string, creds *credentials.TransportCredentials, logger log.Logger) (*grpc.Server, error) {
lis, err := net.Listen("tcp", addr)
if err != nil {
return nil, fmt.Errorf("could not create listener: %w, addr=%s", err, addr)
}
var (
streamInterceptors []grpc.StreamServerInterceptor
unaryInterceptors []grpc.UnaryServerInterceptor
)
streamInterceptors = append(streamInterceptors, grpc_recovery.StreamServerInterceptor())
unaryInterceptors = append(unaryInterceptors, grpc_recovery.UnaryServerInterceptor())
//if metrics.Enabled {
// streamInterceptors = append(streamInterceptors, grpc_prometheus.StreamServerInterceptor)
// unaryInterceptors = append(unaryInterceptors, grpc_prometheus.UnaryServerInterceptor)
//}
opts := []grpc.ServerOption{
// https://github.com/grpc/grpc-go/issues/3171#issuecomment-552796779
grpc.KeepaliveEnforcementPolicy(keepalive.EnforcementPolicy{
MinTime: 10 * time.Second,
PermitWithoutStream: true,
}),
grpc.StreamInterceptor(grpc_middleware.ChainStreamServer(streamInterceptors...)),
grpc.UnaryInterceptor(grpc_middleware.ChainUnaryServer(unaryInterceptors...)),
}
if creds == nil {
// no specific opts
} else {
opts = append(opts, grpc.Creds(*creds))
}
grpcServer := grpc.NewServer(opts...)
reflection.Register(grpcServer) // Register reflection service on gRPC server.
if snServer != nil {
proto_downloader.RegisterDownloaderServer(grpcServer, snServer)
}
//if metrics.Enabled {
// grpc_prometheus.Register(grpcServer)
//}
healthServer := health.NewServer()
grpc_health_v1.RegisterHealthServer(grpcServer, healthServer)
go func() {
defer healthServer.Shutdown()
if err := grpcServer.Serve(lis); err != nil {
logger.Error("gRPC server stop", "err", err)
}
}()
logger.Info("Started gRPC server", "on", addr)
return grpcServer, nil
}
func checkChainName(ctx context.Context, dirs datadir.Dirs, chainName string) error {
exists, err := dir.FileExist(filepath.Join(dirs.Chaindata, "mdbx.dat"))
if err != nil {
return err
}
if !exists {
return nil
}
db, err := mdbx.NewMDBX(log.New()).
Path(dirs.Chaindata).Label(kv.ChainDB).
Accede().
Open(ctx)
if err != nil {
return err
}
defer db.Close()
if cc := tool.ChainConfigFromDB(db); cc != nil {
chainConfig := params.ChainConfigByChainName(chainName)
if chainConfig == nil {
return fmt.Errorf("unknown chain: %s", chainName)
}
if chainConfig.ChainID.Uint64() != cc.ChainID.Uint64() {
return fmt.Errorf("datadir already was configured with --chain=%s. can't change to '%s'", cc.ChainName, chainName)
}
}
return nil
}