-
Notifications
You must be signed in to change notification settings - Fork 162
Expand file tree
/
Copy pathservice.go
More file actions
1815 lines (1538 loc) · 73.1 KB
/
service.go
File metadata and controls
1815 lines (1538 loc) · 73.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package service
import (
"fmt"
"os"
"os/exec"
"path/filepath"
"regexp"
"strings"
"time"
"github.com/hashicorp/go-version"
"github.com/mitchellh/go-homedir"
"github.com/rivo/tview"
"github.com/urfave/cli"
"gopkg.in/yaml.v2"
"github.com/dustin/go-humanize"
cliconfig "github.com/rocket-pool/smartnode/rocketpool-cli/service/config"
"github.com/rocket-pool/smartnode/shared"
"github.com/rocket-pool/smartnode/shared/services/config"
"github.com/rocket-pool/smartnode/shared/services/rocketpool"
cfgtypes "github.com/rocket-pool/smartnode/shared/types/config"
cliutils "github.com/rocket-pool/smartnode/shared/utils/cli"
"github.com/rocket-pool/smartnode/shared/utils/sys"
"github.com/shirou/gopsutil/v3/disk"
)
// Settings
const (
ExporterContainerSuffix string = "_exporter"
ValidatorContainerSuffix string = "_validator"
BeaconContainerSuffix string = "_eth2"
ExecutionContainerSuffix string = "_eth1"
NodeContainerSuffix string = "_node"
ApiContainerSuffix string = "_api"
WatchtowerContainerSuffix string = "_watchtower"
PruneProvisionerContainerSuffix string = "_prune_provisioner"
EcMigratorContainerSuffix string = "_ec_migrator"
clientDataVolumeName string = "/ethclient"
dataFolderVolumeName string = "/.rocketpool/data"
PruneFreeSpaceRequired uint64 = 50 * 1024 * 1024 * 1024
dockerImageRegex string = ".*/(?P<image>.*):.*"
colorReset string = "\033[0m"
colorBold string = "\033[1m"
colorRed string = "\033[31m"
colorYellow string = "\033[33m"
colorGreen string = "\033[32m"
colorLightBlue string = "\033[36m"
clearLine string = "\033[2K"
)
// Install the Rocket Pool service
func installService(c *cli.Context) error {
dataPath := ""
if c.String("network") != "" {
fmt.Printf("%sNOTE: The --network flag is deprecated. You no longer need to specify it.%s\n\n", colorLightBlue, colorReset)
}
// Prompt for confirmation
if !(c.Bool("yes") || cliutils.Confirm(fmt.Sprintf(
"The Rocket Pool service will be installed --Version: %s\n\n%sIf you're upgrading, your existing configuration will be backed up and preserved.\nAll of your previous settings will be migrated automatically.%s\nAre you sure you want to continue?",
c.String("version"), colorGreen, colorReset,
))) {
fmt.Println("Cancelled.")
return nil
}
// Get RP client
rp := rocketpool.NewClientFromCtx(c)
defer rp.Close()
// Attempt to load the config to see if any settings need to be passed along to the install script
cfg, isNew, err := rp.LoadConfig()
if err != nil {
return fmt.Errorf("error loading old configuration: %w", err)
}
if !isNew {
dataPath = cfg.Smartnode.DataPath.Value.(string)
dataPath, err = homedir.Expand(dataPath)
if err != nil {
return fmt.Errorf("error getting data path from old configuration: %w", err)
}
}
// Install service
err = rp.InstallService(c.Bool("verbose"), c.Bool("no-deps"), c.String("network"), c.String("version"), c.String("path"), dataPath)
if err != nil {
return err
}
// Print success message & return
fmt.Println("")
fmt.Println("The Rocket Pool service was successfully installed!")
printPatchNotes(c)
// Reload the config after installation
_, isNew, err = rp.LoadConfig()
if err != nil {
return fmt.Errorf("error loading new configuration: %w", err)
}
// Report next steps
fmt.Printf("%s\n=== Next Steps ===\n", colorLightBlue)
fmt.Printf("Run 'rocketpool service config' to review the settings changes for this update, or to continue setting up your node.%s\n", colorReset)
// Print the docker permissions notice
if isNew {
fmt.Printf("\n%sNOTE:\nSince this is your first time installing Rocket Pool, please start a new shell session by logging out and back in or restarting the machine.\n", colorYellow)
fmt.Printf("This is necessary for your user account to have permissions to use Docker.%s", colorReset)
}
return nil
}
// Print the latest patch notes for this release
// TODO: get this from an external source and don't hardcode it into the CLI
func printPatchNotes(c *cli.Context) {
fmt.Print(`
______ _ _ ______ _
| ___ \ | | | | | ___ \ | |
| |_/ /___ ___| | _____| |_ | |_/ /__ ___ | |
| // _ \ / __| |/ / _ \ __| | __/ _ \ / _ \| |
| |\ \ (_) | (__| < __/ |_ | | | (_) | (_) | |
\_| \_\___/ \___|_|\_\___|\__| \_| \___/ \___/|_|
`)
fmt.Printf("%s=== Smartnode v%s ===%s\n\n", colorGreen, shared.RocketPoolVersion, colorReset)
fmt.Printf("Changes you should be aware of before starting:\n\n")
fmt.Printf("%s=== BREAKING CHANGE from v1.9.x to v1.10.x: Port Forwarding ===%s\n", colorGreen, colorReset)
fmt.Println("The \"Expose Port\" options for your Execution Client, Consensus Client, MEV-Boost, and Prometheus have changed from the v1.9 series. Instead of being a simple checkbox, they are now a dropdown: \"Closed\" (previously unchecked), \"Open to Localhost\" (will only be accessible via your local machine, useful for people running on the Cloud / a VPS), and \"Open to External Hosts\" (previously checked). If you previously had your ports opened, you will need to go into the `service config` TUI and reopen them with the appropriate dropdown option after upgrading.\n")
fmt.Printf("%s=== Rolling Records ===%s\n", colorGreen, colorReset)
fmt.Println("The Smartnode now has experimental support for Rolling Records, which capture snapshots of the entire Rocket Pool network's attestation performance in real time. This makes generating rewards trees at the end of the interval almost instantaneous, rather than taking hours. To learn more about Rolling Records, please visit the release notes for Smartnode v1.10.0.\n")
fmt.Printf("%s=== MEV-Boost Changes ===%s\n", colorGreen, colorReset)
fmt.Println("The \"bloXroute Ethical\" relay has been shut down, so we have removed it (and the corresponding \"No Sandwiching\" profiles) from the MEV-Boost relay options. The other relays are still available.")
}
// Install the Rocket Pool update tracker for the metrics dashboard
func installUpdateTracker(c *cli.Context) error {
// Prompt for confirmation
if !(c.Bool("yes") || cliutils.Confirm(
"This will add the ability to display any available Operating System updates or new Rocket Pool versions on the metrics dashboard. "+
"Are you sure you want to install the update tracker?")) {
fmt.Println("Cancelled.")
return nil
}
// Get RP client
rp := rocketpool.NewClientFromCtx(c)
defer rp.Close()
// Install service
err := rp.InstallUpdateTracker(c.Bool("verbose"), c.String("version"))
if err != nil {
return err
}
// Print success message & return
colorReset := "\033[0m"
colorYellow := "\033[33m"
fmt.Println("")
fmt.Println("The Rocket Pool update tracker service was successfully installed!")
fmt.Println("")
fmt.Printf("%sNOTE:\nPlease restart the Smartnode stack to enable update tracking on the metrics dashboard.%s\n", colorYellow, colorReset)
fmt.Println("")
return nil
}
// View the Rocket Pool service status
func serviceStatus(c *cli.Context) error {
// Get RP client
rp := rocketpool.NewClientFromCtx(c)
defer rp.Close()
// Print what network we're on
err := cliutils.PrintNetwork(rp)
if err != nil {
return err
}
// Print service status
return rp.PrintServiceStatus(getComposeFiles(c))
}
// Configure the service
func configureService(c *cli.Context) error {
// Make sure the config directory exists first
configPath := c.GlobalString("config-path")
path, err := homedir.Expand(configPath)
if err != nil {
return fmt.Errorf("error expanding config path [%s]: %w", configPath, err)
}
_, err = os.Stat(path)
if os.IsNotExist(err) {
fmt.Printf("%sYour configured Rocket Pool directory of [%s] does not exist.\nPlease follow the instructions at https://docs.rocketpool.net/guides/node/docker.html to install the Smartnode.%s\n", colorYellow, path, colorReset)
return nil
}
// Get RP client
rp := rocketpool.NewClientFromCtx(c)
defer rp.Close()
// Load the config, checking to see if it's new (hasn't been installed before)
var oldCfg *config.RocketPoolConfig
cfg, isNew, err := rp.LoadConfig()
if err != nil {
return fmt.Errorf("error loading user settings: %w", err)
}
// Check if this is a new install
isUpdate, err := rp.IsFirstRun()
if err != nil {
return fmt.Errorf("error checking for first-run status: %w", err)
}
// For upgrades, move the config to the old one and create a new upgraded copy
if isUpdate {
oldCfg = cfg
cfg = cfg.CreateCopy()
err = cfg.UpdateDefaults()
if err != nil {
return fmt.Errorf("error upgrading configuration with the latest parameters: %w", err)
}
}
// Save the config and exit in headless mode
if c.NumFlags() > 0 {
err := configureHeadless(c, cfg)
if err != nil {
return fmt.Errorf("error updating config from provided arguments: %w", err)
}
return rp.SaveConfig(cfg)
}
// Check for native mode
isNative := c.GlobalIsSet("daemon-path")
app := tview.NewApplication()
md := cliconfig.NewMainDisplay(app, oldCfg, cfg, isNew, isUpdate, isNative)
err = app.Run()
if err != nil {
return err
}
// Deal with saving the config and printing the changes
if md.ShouldSave {
// Save the config
err = rp.SaveConfig(md.Config)
if err != nil {
return fmt.Errorf("error saving config: %w", err)
}
fmt.Println("Your changes have been saved!")
// Exit immediately if we're in native mode
if isNative {
fmt.Println("Please restart your daemon service for them to take effect.")
return nil
}
// Handle network changes
prefix := fmt.Sprint(md.PreviousConfig.Smartnode.ProjectName.Value)
if md.ChangeNetworks {
// Remove the checkpoint sync provider
md.Config.ConsensusCommon.CheckpointSyncProvider.Value = ""
err = rp.SaveConfig(md.Config)
if err != nil {
return fmt.Errorf("error saving config: %w", err)
}
fmt.Printf("%sWARNING: You have requested to change networks.\n\nAll of your existing chain data, your node wallet, and your validator keys will be removed. If you had a Checkpoint Sync URL provided for your Consensus client, it will be removed and you will need to specify a different one that supports the new network.\n\nPlease confirm you have backed up everything you want to keep, because it will be deleted if you answer `y` to the prompt below.\n\n%s", colorYellow, colorReset)
if !cliutils.Confirm("Would you like the Smartnode to automatically switch networks for you? This will destroy and rebuild your `data` folder and all of Rocket Pool's Docker containers.") {
fmt.Println("To change networks manually, please follow the steps laid out in the Node Operator's guide (https://docs.rocketpool.net/guides/node/mainnet.html).")
return nil
}
err = changeNetworks(c, rp, fmt.Sprintf("%s%s", prefix, ApiContainerSuffix))
if err != nil {
fmt.Printf("%s%s%s\nThe Smartnode could not automatically change networks for you, so you will have to run the steps manually. Please follow the steps laid out in the Node Operator's guide (https://docs.rocketpool.net/guides/node/mainnet.html).\n", colorRed, err.Error(), colorReset)
}
return nil
}
// Query for service start if this is a new installation
if isNew {
if !cliutils.Confirm("Would you like to start the Smartnode services automatically now?") {
fmt.Println("Please run `rocketpool service start` when you are ready to launch.")
return nil
}
return startService(c, true)
}
// Query for service start if this is old and there are containers to change
if len(md.ContainersToRestart) > 0 {
fmt.Println("The following containers must be restarted for the changes to take effect:")
for _, container := range md.ContainersToRestart {
fmt.Printf("\t%s_%s\n", prefix, container)
}
if !cliutils.Confirm("Would you like to restart them automatically now?") {
fmt.Println("Please run `rocketpool service start` when you are ready to apply the changes.")
return nil
}
fmt.Println()
for _, container := range md.ContainersToRestart {
fullName := fmt.Sprintf("%s_%s", prefix, container)
fmt.Printf("Stopping %s... ", fullName)
rp.StopContainer(fullName)
fmt.Print("done!\n")
}
fmt.Println()
fmt.Println("Applying changes and restarting containers...")
return startService(c, true)
}
} else {
fmt.Println("Your changes have not been saved. Your Smartnode configuration is the same as it was before.")
return nil
}
return err
}
// Updates a configuration from the provided CLI arguments headlessly
func configureHeadless(c *cli.Context, cfg *config.RocketPoolConfig) error {
// Root params
for _, param := range cfg.GetParameters() {
err := updateConfigParamFromCliArg(c, "", param, cfg)
if err != nil {
return err
}
}
// Subconfigs
for sectionName, subconfig := range cfg.GetSubconfigs() {
for _, param := range subconfig.GetParameters() {
err := updateConfigParamFromCliArg(c, sectionName, param, cfg)
if err != nil {
return err
}
}
}
return nil
}
// Updates a config parameter from a CLI flag
func updateConfigParamFromCliArg(c *cli.Context, sectionName string, param *cfgtypes.Parameter, cfg *config.RocketPoolConfig) error {
var paramName string
if sectionName == "" {
paramName = param.ID
} else {
paramName = fmt.Sprintf("%s-%s", sectionName, param.ID)
}
if c.IsSet(paramName) {
switch param.Type {
case cfgtypes.ParameterType_Bool:
param.Value = c.Bool(paramName)
case cfgtypes.ParameterType_Int:
param.Value = c.Int(paramName)
case cfgtypes.ParameterType_Float:
param.Value = c.Float64(paramName)
case cfgtypes.ParameterType_String:
setting := c.String(paramName)
if param.MaxLength > 0 && len(setting) > param.MaxLength {
return fmt.Errorf("error setting value for %s: [%s] is too long (max length %d)", paramName, setting, param.MaxLength)
}
param.Value = c.String(paramName)
case cfgtypes.ParameterType_Uint:
param.Value = c.Uint(paramName)
case cfgtypes.ParameterType_Uint16:
param.Value = uint16(c.Uint(paramName))
case cfgtypes.ParameterType_Choice:
selection := c.String(paramName)
found := false
for _, option := range param.Options {
if fmt.Sprint(option.Value) == selection {
param.Value = option.Value
found = true
break
}
}
if !found {
return fmt.Errorf("error setting value for %s: [%s] is not one of the valid options", paramName, selection)
}
}
}
return nil
}
// Handle a network change by terminating the service, deleting everything, and starting over
func changeNetworks(c *cli.Context, rp *rocketpool.Client, apiContainerName string) error {
// Stop all of the containers
fmt.Print("Stopping containers... ")
err := rp.PauseService(getComposeFiles(c))
if err != nil {
return fmt.Errorf("error stopping service: %w", err)
}
fmt.Println("done")
// Restart the API container
fmt.Print("Starting API container... ")
output, err := rp.StartContainer(apiContainerName)
if err != nil {
return fmt.Errorf("error starting API container: %w", err)
}
if output != apiContainerName {
return fmt.Errorf("starting API container had unexpected output: %s", output)
}
fmt.Println("done")
// Get the path of the user's data folder
fmt.Print("Retrieving data folder path... ")
volumePath, err := rp.GetClientVolumeSource(apiContainerName, dataFolderVolumeName)
if err != nil {
return fmt.Errorf("error getting data folder path: %w", err)
}
fmt.Printf("done, data folder = %s\n", volumePath)
// Delete the data folder
fmt.Print("Removing data folder... ")
_, err = rp.TerminateDataFolder()
if err != nil {
return err
}
fmt.Println("done")
// Terminate the current setup
fmt.Print("Removing old installation... ")
err = rp.StopService(getComposeFiles(c))
if err != nil {
return fmt.Errorf("error terminating old installation: %w", err)
}
fmt.Println("done")
// Create new validator folder
fmt.Print("Recreating data folder... ")
err = os.MkdirAll(filepath.Join(volumePath, "validators"), 0775)
if err != nil {
return fmt.Errorf("error recreating data folder: %w", err)
}
// Start the service
fmt.Print("Starting Rocket Pool... ")
err = rp.StartService(getComposeFiles(c))
if err != nil {
return fmt.Errorf("error starting service: %w", err)
}
fmt.Println("done")
return nil
}
// Start the Rocket Pool service
func startService(c *cli.Context, ignoreConfigSuggestion bool) error {
// Get RP client
rp := rocketpool.NewClientFromCtx(c)
defer rp.Close()
// Update the Prometheus template with the assigned ports
cfg, isNew, err := rp.LoadConfig()
if err != nil {
return fmt.Errorf("Error loading user settings: %w", err)
}
// Check for unsupported clients
if cfg.ExecutionClientMode.Value.(cfgtypes.Mode) == cfgtypes.Mode_Local {
selectedEc := cfg.ExecutionClient.Value.(cfgtypes.ExecutionClient)
switch selectedEc {
case cfgtypes.ExecutionClient_Obs_Infura:
fmt.Printf("%sYou currently have Infura configured as your primary Execution client, but it is no longer supported because it is not compatible with the upcoming Ethereum Merge.\nPlease run `rocketpool service config` and select a full Execution client.%s\n", colorRed, colorReset)
return nil
case cfgtypes.ExecutionClient_Obs_Pocket:
fmt.Printf("%sYou currently have Pocket configured as your primary Execution client, but it is no longer supported because it is not compatible with the upcoming Ethereum Merge.\nPlease run `rocketpool service config` and select a full Execution client.%s\n", colorRed, colorReset)
return nil
}
}
// Force all Docker or all Hybrid
if cfg.ExecutionClientMode.Value.(cfgtypes.Mode) == cfgtypes.Mode_Local && cfg.ConsensusClientMode.Value.(cfgtypes.Mode) == cfgtypes.Mode_External {
fmt.Printf("%sYou are using a locally-managed Execution client and an externally-managed Consensus client.\nThis configuration is not compatible with The Merge; please select either locally-managed or externally-managed for both the EC and CC.%s\n", colorRed, colorReset)
} else if cfg.ExecutionClientMode.Value.(cfgtypes.Mode) == cfgtypes.Mode_External && cfg.ConsensusClientMode.Value.(cfgtypes.Mode) == cfgtypes.Mode_Local {
fmt.Printf("%sYou are using an externally-managed Execution client and a locally-managed Consensus client.\nThis configuration is not compatible with The Merge; please select either locally-managed or externally-managed for both the EC and CC.%s\n", colorRed, colorReset)
}
if isNew {
return fmt.Errorf("No configuration detected. Please run `rocketpool service config` to set up your Smartnode before running it.")
}
// Check if this is a new install
isUpdate, err := rp.IsFirstRun()
if err != nil {
return fmt.Errorf("error checking for first-run status: %w", err)
}
if isUpdate && !ignoreConfigSuggestion {
if c.Bool("yes") || cliutils.Confirm("Smartnode upgrade detected - starting will overwrite certain settings with the latest defaults (such as container versions).\nYou may want to run `service config` first to see what's changed.\n\nWould you like to continue starting the service?") {
err = cfg.UpdateDefaults()
if err != nil {
return fmt.Errorf("error upgrading configuration with the latest parameters: %w", err)
}
rp.SaveConfig(cfg)
fmt.Printf("%sUpdated settings successfully.%s\n", colorGreen, colorReset)
} else {
fmt.Println("Cancelled.")
return nil
}
}
// Update the Prometheus template with the assigned ports
metricsEnabled := cfg.EnableMetrics.Value.(bool)
if metricsEnabled {
err := rp.UpdatePrometheusConfiguration(cfg.GenerateEnvironmentVariables())
if err != nil {
return err
}
}
// Validate the config
errors := cfg.Validate()
if len(errors) > 0 {
fmt.Printf("%sYour configuration encountered errors. You must correct the following in order to start Rocket Pool:\n\n", colorRed)
for _, err := range errors {
fmt.Printf("%s\n\n", err)
}
fmt.Println(colorReset)
return nil
}
if !c.Bool("ignore-slash-timer") {
// Do the client swap check
err := checkForValidatorChange(rp, cfg)
if err != nil {
fmt.Printf("%sWARNING: couldn't verify that the validator container can be safely restarted:\n\t%s\n", colorYellow, err.Error())
fmt.Println("If you are changing to a different consensus client, it may resubmit an attestation you have already submitted.")
fmt.Println("This will slash your validator!")
fmt.Println("To prevent slashing, you must wait 15 minutes from the time you stopped the clients before starting them again.\n")
fmt.Println("**If you did NOT change clients, you can safely ignore this warning.**\n")
if !cliutils.Confirm(fmt.Sprintf("Press y when you understand the above warning, have waited, and are ready to start Rocket Pool:%s", colorReset)) {
fmt.Println("Cancelled.")
return nil
}
}
} else {
fmt.Printf("%sIgnoring anti-slashing safety delay.%s\n", colorYellow, colorReset)
}
// Force a delay if using Teku and upgrading from v1.3.0 or below because of the slashing protection DB migration in v1.3.1+
isLocalTeku := (cfg.ConsensusClientMode.Value.(cfgtypes.Mode) == cfgtypes.Mode_Local && cfg.ConsensusClient.Value.(cfgtypes.ConsensusClient) == cfgtypes.ConsensusClient_Teku)
isExternalTeku := (cfg.ConsensusClientMode.Value.(cfgtypes.Mode) == cfgtypes.Mode_External && cfg.ExternalConsensusClient.Value.(cfgtypes.ConsensusClient) == cfgtypes.ConsensusClient_Teku)
if isUpdate && !isNew && !cfg.IsNativeMode && (isLocalTeku || isExternalTeku) && !c.Bool("ignore-slash-timer") {
previousVersion := "0.0.0"
backupCfg, err := rp.LoadBackupConfig()
if err != nil {
fmt.Printf("WARNING: Couldn't determine previous Smartnode version from backup settings: %s\n", err.Error())
} else if backupCfg != nil {
previousVersion = backupCfg.Version
}
oldVersion, err := version.NewVersion(strings.TrimPrefix(previousVersion, "v"))
if err != nil {
fmt.Printf("WARNING: Backup configuration states the previous Smartnode installation used version %s, which is not a valid version\n", previousVersion)
oldVersion, _ = version.NewVersion("0.0.0")
}
vulnerableConstraint, _ := version.NewConstraint("<= 1.3.0")
if vulnerableConstraint.Check(oldVersion) {
err = handleTekuSlashProtectionMigrationDelay(rp, cfg)
if err != nil {
return err
}
}
}
// Force stop eth2 if using Nimbus prior to v1.8.0 so it ensures the container is shut down and thus lets go of the validator keys and slashing database
isLocalNimbus := (cfg.ConsensusClientMode.Value.(cfgtypes.Mode) == cfgtypes.Mode_Local && cfg.ConsensusClient.Value.(cfgtypes.ConsensusClient) == cfgtypes.ConsensusClient_Nimbus)
if isUpdate && !isNew && !cfg.IsNativeMode && isLocalNimbus {
proceed, err := handleNimbusSplitConversion(rp, cfg)
if err != nil {
return fmt.Errorf("error handling Nimbus split-mode upgrade: %w", err)
}
if !proceed {
return nil
}
}
// Write a note on doppelganger protection
doppelgangerEnabled, err := cfg.IsDoppelgangerEnabled()
if err != nil {
fmt.Printf("%sCouldn't check if you have Doppelganger Protection enabled: %s\nIf you do, your validator will miss up to 3 attestations when it starts.\nThis is *intentional* and does not indicate a problem with your node.%s\n\n", colorYellow, err.Error(), colorReset)
} else if doppelgangerEnabled {
fmt.Printf("%sNOTE: You currently have Doppelganger Protection enabled.\nYour validator will miss up to 3 attestations when it starts.\nThis is *intentional* and does not indicate a problem with your node.%s\n\n", colorYellow, colorReset)
}
// Start service
err = rp.StartService(getComposeFiles(c))
if err != nil {
return err
}
// Remove the upgrade flag if it's there
return rp.RemoveUpgradeFlagFile()
}
// Versions prior to v1.9.0 had Nimbus in single mode instead of split mode, so handle the conversion to ensure the user doesn't get slashed
func handleNimbusSplitConversion(rp *rocketpool.Client, cfg *config.RocketPoolConfig) (bool, error) {
previousVersion := "0.0.0"
backupCfg, err := rp.LoadBackupConfig()
if err != nil {
fmt.Printf("%sWARNING: Couldn't determine previous Smartnode version from backup settings: %s%s\n", colorYellow, err.Error(), colorReset)
fmt.Printf("%sYou are configured to use Nimbus in local mode. Starting with v1.9.0, Nimbus is now configured to use a split-process configuration, which means the Beacon Node (the `eth2` container) no longer loads your validator keys - now the `validator` container does.\n\nDue to this, we must restart Nimbus as part of the upgrade.\n\nIf you were previously running Smartnode v1.7.5 or earlier, you **MUST** shut down the Docker containers with `rocketpool service stop` and wait **at least 15 minutes** to ensure that you've missed at least two attestations before proceeding to prevent being slashed. Please use an explorer such as https://beaconcha.in to confirm at least one of the missed attestations has been finalized before proceeding.%s\n\n", colorYellow, colorReset)
fmt.Println()
if !cliutils.Confirm(fmt.Sprintf("Press y when you understand the above warning, have waited, and are ready to start Rocket Pool:%s", colorReset)) {
fmt.Println("Cancelled.")
return false, nil
}
return true, nil
} else if backupCfg != nil {
previousVersion = backupCfg.Version
} else {
fmt.Printf("%sWARNING: Couldn't determine previous Smartnode version from backup settings because the backup configuration didn't exist.%s\n", colorYellow, colorReset)
fmt.Printf("%sYou are configured to use Nimbus in local mode. Starting with v1.9.0, Nimbus is now configured to use a split-process configuration, which means the Beacon Node (the `eth2` container) no longer loads your validator keys - now the `validator` container does.\n\nDue to this, we must restart Nimbus as part of the upgrade.\n\nIf you were previously running Smartnode v1.7.5 or earlier, you **MUST** shut down the Docker containers with `rocketpool service stop` and wait **at least 15 minutes** to ensure that you've missed at least two attestations before proceeding to prevent being slashed. Please use an explorer such as https://beaconcha.in to confirm at least one of the missed attestations has been finalized before proceeding.%s\n\n", colorYellow, colorReset)
fmt.Println()
if !cliutils.Confirm(fmt.Sprintf("Press y when you understand the above warning, have waited, and are ready to start Rocket Pool:%s", colorReset)) {
fmt.Println("Cancelled.")
return false, nil
}
return true, nil
}
oldVersion, err := version.NewVersion(strings.TrimPrefix(previousVersion, "v"))
if err != nil {
fmt.Printf("%sWARNING: Backup configuration states the previous Smartnode installation used version %s, which is not a valid version%s\n", colorYellow, previousVersion, colorReset)
fmt.Printf("%sYou are configured to use Nimbus in local mode. Starting with v1.9.0, Nimbus is now configured to use a split-process configuration, which means the Beacon Node (the `eth2` container) no longer loads your validator keys - now the `validator` container does.\n\nDue to this, we must restart Nimbus as part of the upgrade.\n\nIf you were previously running Smartnode v1.7.5 or earlier, you **MUST** shut down the Docker containers with `rocketpool service stop` and wait **at least 15 minutes** to ensure that you've missed at least two attestations before proceeding to prevent being slashed. Please use an explorer such as https://beaconcha.in to confirm at least one of the missed attestations has been finalized before proceeding.%s\n\n", colorYellow, colorReset)
fmt.Println()
if !cliutils.Confirm(fmt.Sprintf("Press y when you understand the above warning, have waited, and are ready to start Rocket Pool:%s", colorReset)) {
fmt.Println("Cancelled.")
return false, nil
}
return true, nil
}
vulnerableConstraint, _ := version.NewConstraint("< 1.8.0")
if vulnerableConstraint.Check(oldVersion) {
fmt.Println()
fmt.Printf("%sNOTE: You are configured to use Nimbus in local mode. Starting with v1.9.0, Nimbus is now configured to use a split-process configuration, which means the Beacon Node (the `eth2` container) no longer loads your validator keys - now the `validator` container does.\n\nDue to this, we must restart Nimbus as part of the upgrade. Your client's slashing database will be moved from the `eth2` container to the `validator` container automatically to ensure your node doesn't attest to the same duty twice and get slashed.\n\nIf you have *any concern at all* about this process, you may want to voluntarily shut down the Docker containers with `rocketpool service stop` and wait 15 minutes to ensure that you've missed at least two attestations before proceeding. If you do this, please use an explorer such as https://beaconcha.in to confirm at least one of the missed attestations has been finalized before proceeding.%s\n\n", colorYellow, colorReset)
fmt.Println()
if !cliutils.Confirm("Do you want to continue starting the service?") {
fmt.Println("Cancelled.")
return false, nil
}
// Ensure the eth2 and validator containers have stopped
prefix, err := getContainerPrefix(rp)
if err != nil {
return false, fmt.Errorf("error getting container prefix: %w", err)
}
successfulStop := true
eth2ContainerName := prefix + BeaconContainerSuffix
fmt.Printf("Stopping %s...\n", eth2ContainerName)
out, err := rp.StopContainer(eth2ContainerName)
if err != nil {
exitErr, isExitErr := err.(*exec.ExitError)
if isExitErr && exitErr.ProcessState.ExitCode() == 1 && strings.Contains(string(exitErr.Stderr), "No such container:") {
// Handle errors where the container didn't exist
fmt.Printf("%sNOTE: couldn't shut down %s because it didn't exist.%s\n", colorYellow, eth2ContainerName, colorReset)
successfulStop = false
} else {
return false, fmt.Errorf("error stopping %s: %w", eth2ContainerName, err)
}
} else if out != eth2ContainerName {
return false, fmt.Errorf("unexpected output when trying to stop %s: [%s]", eth2ContainerName, out)
}
validatorContainerName := prefix + ValidatorContainerSuffix
fmt.Printf("Stopping %s...\n", validatorContainerName)
out, err = rp.StopContainer(validatorContainerName)
if err != nil {
exitErr, isExitErr := err.(*exec.ExitError)
if isExitErr && exitErr.ProcessState.ExitCode() == 1 && strings.Contains(string(exitErr.Stderr), "No such container:") {
// Handle errors where the container didn't exist
fmt.Printf("%sNOTE: couldn't shut down %s because it didn't exist.%s\n", colorYellow, validatorContainerName, colorReset)
successfulStop = false
} else {
return false, fmt.Errorf("error stopping %s: %w", validatorContainerName, err)
}
} else if out != validatorContainerName {
return false, fmt.Errorf("unexpected output when trying to stop %s: [%s]", validatorContainerName, out)
}
if !successfulStop {
fmt.Println()
fmt.Printf("%sWARNING: Some of the Nimbus containers couldn't be shut down safely.\nThe Smartnode can't guarantee the safe transfer of the slashing database. If you have active validators, you **must ensure** you have waited 15 minutes since your last attestation and **missed at least two attestations** before continuing.\nIf you don't, you %sMAY BE SLASHED!%s\n\n", colorYellow, colorRed, colorReset)
fmt.Println()
if !cliutils.Confirm(fmt.Sprintf("Press y when you understand the above warning, have waited, and are ready to start Rocket Pool:%s", colorReset)) {
fmt.Println("Cancelled.")
return false, nil
}
}
}
return true, nil
}
// Versions prior to v1.3.1 didn't preserve Teku's slashing DB, so force a delay when upgrading to ensure the user doesn't get slashed by accident
func handleTekuSlashProtectionMigrationDelay(rp *rocketpool.Client, cfg *config.RocketPoolConfig) error {
fmt.Printf("%s=== NOTICE ===\n", colorYellow)
fmt.Printf("You are currently using Teku as your Consensus client.\nv1.3.1+ fixes an issue that would cause Teku's slashing protection database to be lost after an upgrade.\nIt will now be rebuilt.\n\nFor the absolute safety of your funds, your node will wait for 15 minutes before starting.\nYou will miss a few attestations during this process; this is expected.\n\nThis delay only needs to happen the first time you start the Smartnode after upgrading to v1.3.1 or higher.%s\n\nIf you are installing the Smartnode for the first time or don't have any validators yet, you can skip this with `rocketpool service start --ignore-slash-timer`. Otherwise, we strongly recommend you wait for the full delay.\n\n", colorReset)
// Get the container prefix
prefix, err := getContainerPrefix(rp)
if err != nil {
return fmt.Errorf("Error getting validator container prefix: %w", err)
}
// Get the current validator client
currentValidatorImageString, err := rp.GetDockerImage(prefix + ValidatorContainerSuffix)
if err != nil {
return fmt.Errorf("Error getting current validator image: %w", err)
}
currentValidatorName, err := getDockerImageName(currentValidatorImageString)
if err != nil {
return fmt.Errorf("Error getting current validator image name: %w", err)
}
// Get the time that the container responsible for validator duties exited
validatorDutyContainerName, err := getContainerNameForValidatorDuties(currentValidatorName, rp)
if err != nil {
return fmt.Errorf("Error getting validator container name: %w", err)
}
validatorFinishTime, err := rp.GetDockerContainerShutdownTime(validatorDutyContainerName)
if err != nil {
return fmt.Errorf("Error getting validator shutdown time: %w", err)
}
// If it hasn't exited yet, shut it down
zeroTime := time.Time{}
status, err := rp.GetDockerStatus(validatorDutyContainerName)
if err != nil {
return fmt.Errorf("Error getting container [%s] status: %w", validatorDutyContainerName, err)
}
if validatorFinishTime == zeroTime || status == "running" {
fmt.Printf("%sValidator is currently running, stopping it...%s\n", colorYellow, colorReset)
response, err := rp.StopContainer(validatorDutyContainerName)
validatorFinishTime = time.Now()
if err != nil {
return fmt.Errorf("Error stopping container [%s]: %w", validatorDutyContainerName, err)
}
if response != validatorDutyContainerName {
return fmt.Errorf("Unexpected response when stopping container [%s]: %s", validatorDutyContainerName, response)
}
}
// Print the warning and start the time lockout
safeStartTime := validatorFinishTime.Add(15 * time.Minute)
remainingTime := time.Until(safeStartTime)
if remainingTime <= 0 {
fmt.Printf("The validator has been offline for %s, which is long enough to prevent slashing.\n", time.Since(validatorFinishTime))
fmt.Println("The new client can be safely started.")
} else {
// Wait for 15 minutes
for remainingTime > 0 {
fmt.Printf("Remaining time: %s", remainingTime)
time.Sleep(1 * time.Second)
remainingTime = time.Until(safeStartTime)
fmt.Printf("%s\r", clearLine)
}
fmt.Println(colorReset)
fmt.Println("You may now safely start the validator without fear of being slashed.")
}
return nil
}
func checkForValidatorChange(rp *rocketpool.Client, cfg *config.RocketPoolConfig) error {
// Get the container prefix
prefix, err := getContainerPrefix(rp)
if err != nil {
return fmt.Errorf("Error getting validator container prefix: %w", err)
}
// Get the current validator client
currentValidatorImageString, err := rp.GetDockerImage(prefix + ValidatorContainerSuffix)
if err != nil {
return fmt.Errorf("Error getting current validator image: %w", err)
}
currentValidatorName, err := getDockerImageName(currentValidatorImageString)
if err != nil {
return fmt.Errorf("Error getting current validator image name: %w", err)
}
// Get the new validator client according to the settings file
selectedConsensusClientConfig, err := cfg.GetSelectedConsensusClientConfig()
if err != nil {
return fmt.Errorf("Error getting selected consensus client config: %w", err)
}
pendingValidatorName, err := getDockerImageName(selectedConsensusClientConfig.GetValidatorImage())
if err != nil {
return fmt.Errorf("Error getting pending validator image name: %w", err)
}
// Compare the clients and warn if necessary
if currentValidatorName == pendingValidatorName {
fmt.Printf("Validator client [%s] was previously used - no slashing prevention delay necessary.\n", currentValidatorName)
} else if currentValidatorName == "" {
fmt.Println("This is the first time starting Rocket Pool - no slashing prevention delay necessary.")
} else if (currentValidatorName == "nimbus-eth2" && pendingValidatorName == "nimbus-validator-client") || (pendingValidatorName == "nimbus-eth2" && currentValidatorName == "nimbus-validator-client") {
// Handle the transition from Nimbus v22.11.x to Nimbus v22.12.x where they split the VC into its own container
fmt.Printf("Validator client [%s] was previously used, you are changing to [%s] but the Smartnode will migrate your slashing database automatically to this new client. No slashing prevention delay is necessary.\n", currentValidatorName, pendingValidatorName)
} else {
consensusClient, _ := cfg.GetSelectedConsensusClient()
// Warn about Lodestar
if consensusClient == cfgtypes.ConsensusClient_Lodestar {
fmt.Printf("%sNOTE:\nIf this is your first time running Lodestar and you have existing minipools, you must run `rocketpool wallet rebuild` after the Smartnode starts to generate the validator keys for it.\nIf you have run it before or you don't have any minipools, you can ignore this message.%s\n\n", colorYellow, colorReset)
}
// Get the time that the container responsible for validator duties exited
validatorDutyContainerName, err := getContainerNameForValidatorDuties(currentValidatorName, rp)
if err != nil {
return fmt.Errorf("Error getting validator container name: %w", err)
}
validatorFinishTime, err := rp.GetDockerContainerShutdownTime(validatorDutyContainerName)
if err != nil {
return fmt.Errorf("Error getting validator shutdown time: %w", err)
}
// If it hasn't exited yet, shut it down
zeroTime := time.Time{}
status, err := rp.GetDockerStatus(validatorDutyContainerName)
if err != nil {
return fmt.Errorf("Error getting container [%s] status: %w", validatorDutyContainerName, err)
}
if validatorFinishTime == zeroTime || status == "running" {
fmt.Printf("%sValidator is currently running, stopping it...%s\n", colorYellow, colorReset)
response, err := rp.StopContainer(validatorDutyContainerName)
validatorFinishTime = time.Now()
if err != nil {
return fmt.Errorf("Error stopping container [%s]: %w", validatorDutyContainerName, err)
}
if response != validatorDutyContainerName {
return fmt.Errorf("Unexpected response when stopping container [%s]: %s", validatorDutyContainerName, response)
}
}
// Print the warning and start the time lockout
safeStartTime := validatorFinishTime.Add(15 * time.Minute)
remainingTime := time.Until(safeStartTime)
if remainingTime <= 0 {
fmt.Printf("The validator has been offline for %s, which is long enough to prevent slashing.\n", time.Since(validatorFinishTime))
fmt.Println("The new client can be safely started.")
} else {
fmt.Printf("%s=== WARNING ===\n", colorRed)
fmt.Printf("You have changed your validator client from %s to %s. Only %s has elapsed since you stopped %s.\n", currentValidatorName, pendingValidatorName, time.Since(validatorFinishTime), currentValidatorName)
fmt.Printf("If you were actively validating while using %s, starting %s without waiting will cause your validators to be slashed due to duplicate attestations!", currentValidatorName, pendingValidatorName)
fmt.Println("To prevent slashing, Rocket Pool will delay activating the new client for 15 minutes.")
fmt.Println("See the documentation for a more detailed explanation: https://docs.rocketpool.net/guides/node/maintenance/node-migration.html#slashing-and-the-slashing-database")
fmt.Printf("If you have read the documentation, understand the risks, and want to bypass this cooldown, run `rocketpool service start --ignore-slash-timer`.%s\n\n", colorReset)
// Wait for 15 minutes
for remainingTime > 0 {
fmt.Printf("Remaining time: %s", remainingTime)
time.Sleep(1 * time.Second)
remainingTime = time.Until(safeStartTime)
fmt.Printf("%s\r", clearLine)
}
fmt.Println(colorReset)
fmt.Println("You may now safely start the validator without fear of being slashed.")
}
}
return nil
}
// Get the name of the container responsible for validator duties based on the client name
// TODO: this is temporary and can change, clean it up when Nimbus supports split mode
func getContainerNameForValidatorDuties(CurrentValidatorClientName string, rp *rocketpool.Client) (string, error) {
prefix, err := getContainerPrefix(rp)
if err != nil {
return "", err
}
if CurrentValidatorClientName == "nimbus" {
return prefix + BeaconContainerSuffix, nil
}
return prefix + ValidatorContainerSuffix, nil
}
// Get the time that the container responsible for validator duties exited
func getValidatorFinishTime(CurrentValidatorClientName string, rp *rocketpool.Client) (time.Time, error) {
prefix, err := getContainerPrefix(rp)
if err != nil {
return time.Time{}, err
}
var validatorFinishTime time.Time
if CurrentValidatorClientName == "nimbus" {
validatorFinishTime, err = rp.GetDockerContainerShutdownTime(prefix + BeaconContainerSuffix)
} else {
validatorFinishTime, err = rp.GetDockerContainerShutdownTime(prefix + ValidatorContainerSuffix)
}
return validatorFinishTime, err
}
// Extract the image name from a Docker image string
func getDockerImageName(imageString string) (string, error) {
// Return the empty string if the validator didn't exist (probably because this is the first time starting it up)
if imageString == "" {
return "", nil
}
reg := regexp.MustCompile(dockerImageRegex)
matches := reg.FindStringSubmatch(imageString)
if matches == nil {
return "", fmt.Errorf("Couldn't parse the Docker image string [%s]", imageString)
}
imageIndex := reg.SubexpIndex("image")
if imageIndex == -1 {
return "", fmt.Errorf("Image name not found in Docker image [%s]", imageString)
}
imageName := matches[imageIndex]
return imageName, nil
}
// Gets the prefix specified for Rocket Pool's Docker containers
func getContainerPrefix(rp *rocketpool.Client) (string, error) {
cfg, isNew, err := rp.LoadConfig()
if err != nil {
return "", err
}
if isNew {
return "", fmt.Errorf("Settings file not found. Please run `rocketpool service config` to set up your Smartnode.")
}
return cfg.Smartnode.ProjectName.Value.(string), nil
}
// Prepares the execution client for pruning
func pruneExecutionClient(c *cli.Context) error {
// Get RP client
rp := rocketpool.NewClientFromCtx(c)
defer rp.Close()
// Get the config
cfg, isNew, err := rp.LoadConfig()
if err != nil {
return err
}
if isNew {
return fmt.Errorf("Settings file not found. Please run `rocketpool service config` to set up your Smartnode.")
}
// Sanity checks
if cfg.ExecutionClientMode.Value.(cfgtypes.Mode) == cfgtypes.Mode_External {
fmt.Println("You are using an externally managed Execution client.\nThe Smartnode cannot prune it for you.")
return nil
}
if cfg.IsNativeMode {
fmt.Println("You are using Native Mode.\nThe Smartnode cannot prune your Execution client for you, you'll have to do it manually.")