Compare commits

...

24 Commits

Author SHA1 Message Date
Jim McDonald
c7adf03aeb Bump version. 2023-04-13 18:15:43 +01:00
Jim McDonald
35944ca8c5 Update changelog. 2023-04-13 18:12:45 +01:00
Jim McDonald
083d625813 Allow use of validator index in account specifier.
Fixes #83
2023-04-13 18:11:46 +01:00
Jim McDonald
263db812b3 Update dependencies. 2023-04-09 23:24:48 +01:00
Jim McDonald
2c01d18195 Update parameter names; add fallback connection.
Update parameter names to meet newer standards.

Provide a fallback beacon node if none other supplied.
2023-04-09 23:19:19 +01:00
Jim McDonald
df99d43415 Merge branch 'master' of github.com:wealdtech/ethdo 2023-04-09 19:23:08 +01:00
Jim McDonald
d81546f2de Update docs to match new validator info options. 2023-04-09 19:20:02 +01:00
Jim McDonald
3d87a917af Merge pull request #75 from nflaig/patch-1
Document Lodestar settings in README
2023-03-31 19:06:41 +01:00
Nico Flaig
9240ed4857 Document Lodestar settings in README 2023-03-31 17:54:06 +02:00
Jim McDonald
18f9e8dca2 Fix test. 2023-03-21 08:42:01 +00:00
Jim McDonald
fbc24b81d2 Linting. 2023-03-21 08:36:39 +00:00
Jim McDonald
f898466395 Increase timeout for fetching offline preparation. 2023-03-21 08:04:33 +00:00
Jim McDonald
e496fa1977 Do not mask account errors. 2023-03-07 13:50:50 +00:00
Jim McDonald
d016326779 Merge pull request #71 from lastperson/patch-1
Fix the 'credentials set' example.
2023-03-03 11:16:45 +00:00
Oleksii Matiiasevych
ee14b5ee8e Fix the 'credentials set' example. 2023-03-03 14:03:05 +07:00
Jim McDonald
9ae927feab Handle keystore in validator credentials set. 2023-02-27 22:07:45 +00:00
Jim McDonald
7087a0a55c Allow keystore without path. 2023-02-27 11:16:36 +00:00
Jim McDonald
793a8d6d79 Allow keystore as source of validator. 2023-02-26 22:43:45 +00:00
Jim McDonald
e15b22dc3c Updates for go 1.20. 2023-02-26 19:45:47 +00:00
Jim McDonald
6ddd453900 Update dependencies. 2023-02-26 12:58:49 +00:00
Jim McDonald
24755099c0 Update workflow. 2023-02-26 12:57:22 +00:00
Jim McDonald
a5f97c2765 Update dependencies. 2023-02-26 12:44:45 +00:00
Jim McDonald
df59bc22de Unlock validator account for exit generation. 2023-02-26 12:42:19 +00:00
Jim McDonald
5fdd59dee2 Update changelog. 2023-02-21 22:17:55 +00:00
134 changed files with 1102 additions and 1166 deletions

View File

@@ -46,7 +46,7 @@ jobs:
- name: Set up Go
uses: actions/setup-go@v3
with:
go-version: ^1.19
go-version: '^1.20'
- name: Check out repository into the Go module directory
uses: actions/checkout@v3
@@ -59,6 +59,10 @@ jobs:
- name: Compile
run: |
# Do not attempt to upgrade grub, as it errors on github (24th Feb 2023)
sudo apt-mark hold grub-efi-amd64-signed grub-efi-amd64-bin
sudo apt-get update
sudo apt-get upgrade
go build -tags osusergo,netgo -v -ldflags="-X github.com/${{ github.repository }}/cmd.ReleaseVersion=${{ needs.env_vars.outputs.release_version }} -extldflags -static"
tar zcf ${{ needs.env_vars.outputs.binary }}-${{ needs.env_vars.outputs.release_version }}-linux-amd64.tar.gz ${{ needs.env_vars.outputs.binary }}
sha256sum ${{ needs.env_vars.outputs.binary }}-${{ needs.env_vars.outputs.release_version }}-linux-amd64.tar.gz | sed -e 's/ .*//' >${{ needs.env_vars.outputs.binary }}-${{ needs.env_vars.outputs.release_version }}-linux-amd64.tar.gz.sha256
@@ -84,8 +88,6 @@ jobs:
- name: Cross compile (ARM64)
run: |
sudo apt-get update
sudo apt-get upgrade
sudo apt install -y gcc-aarch64-linux-gnu libstdc++-11-pic-arm64-cross
CGO_ENABLED=1 CC=aarch64-linux-gnu-gcc GOOS=linux GOARCH=arm64 go build -tags osusergo,netgo -v -ldflags="-X github.com/${{ github.repository }}/cmd.ReleaseVersion=${{ needs.env_vars.outputs.release_version }} -extldflags -static"
tar zcf ${{ needs.env_vars.outputs.binary }}-${{ needs.env_vars.outputs.release_version }}-linux-arm64.tar.gz ${{ needs.env_vars.outputs.binary }}
@@ -119,7 +121,7 @@ jobs:
- name: Set up Go
uses: actions/setup-go@v3
with:
go-version: ^1.19
go-version: '^1.20'
- name: Check out repository into the Go module directory
uses: actions/checkout@v3
@@ -164,7 +166,7 @@ jobs:
- name: Set up Go
uses: actions/setup-go@v3
with:
go-version: ^1.19
go-version: '^1.20'
- name: Check out repository into the Go module directory
uses: actions/checkout@v3

View File

@@ -1,4 +1,18 @@
dev:
1.29.2:
- fix regression where validator index could not be used as an account specifier
1.29.0:
- allow use of keystores with validator credentials set
- tidy up various command options to provide more standard usage
- add mainnet fallback beacon node
1.28.4:
- allow validator exit to use a keystore as its validator parameter
1.28.2:
- fix bix stopping validator exit creation by direct validator specification
1.28.1:
- generate error message if "validator credentials set" process fails to generate any credentials
- allow import of accounts with null name field in their keystore
- show text of execution payload extra data if available

View File

@@ -1,4 +1,4 @@
FROM golang:1.18-bullseye as builder
FROM golang:1.20-bullseye as builder
WORKDIR /app

View File

@@ -86,6 +86,11 @@ Teku disables the REST API by default. To enable it, the beacon node must be st
The default port for the REST API is 5051, which can be changed with the `--rest-api-port` parameter.
### Lodestar
Lodestar enables the REST API by default and should just work locally. If you want to access the REST API from a remote server then you should also look to change the `--rest.address` to `0.0.0.0` as per the Lodestar documentation.
The default port for the REST API is 9596, which can be changed with the `--rest.port` parameter.
## Usage
`ethdo` contains a large number of features that are useful for day-to-day interactions with the different consensus clients.

View File

@@ -28,5 +28,5 @@ func init() {
RootCmd.AddCommand(accountCmd)
}
func accountFlags(cmd *cobra.Command) {
func accountFlags(_ *cobra.Command) {
}

View File

@@ -25,7 +25,7 @@ type dataOut struct {
account e2wtypes.Account
}
func output(ctx context.Context, data *dataOut) (string, error) {
func output(_ context.Context, data *dataOut) (string, error) {
if data == nil {
return "", errors.New("no data")
}

View File

@@ -30,7 +30,7 @@ type dataIn struct {
showWithdrawalCredentials bool
}
func input(ctx context.Context) (*dataIn, error) {
func input(_ context.Context) (*dataIn, error) {
data := &dataIn{}
// Quiet.

View File

@@ -29,7 +29,7 @@ type dataOut struct {
key *e2types.BLSPrivateKey
}
func output(ctx context.Context, data *dataOut) (string, error) {
func output(_ context.Context, data *dataOut) (string, error) {
if data == nil {
return "", errors.New("no data")
}

View File

@@ -25,7 +25,7 @@ type dataOut struct {
account e2wtypes.Account
}
func output(ctx context.Context, data *dataOut) (string, error) {
func output(_ context.Context, data *dataOut) (string, error) {
if data == nil {
return "", errors.New("no data")
}

View File

@@ -24,7 +24,7 @@ type dataOut struct {
key []byte
}
func output(ctx context.Context, data *dataOut) (string, error) {
func output(_ context.Context, data *dataOut) (string, error) {
if data == nil {
return "", errors.New("no data")
}

View File

@@ -28,5 +28,5 @@ func init() {
RootCmd.AddCommand(attesterCmd)
}
func attesterFlags(cmd *cobra.Command) {
func attesterFlags(_ *cobra.Command) {
}

View File

@@ -18,9 +18,11 @@ import (
"time"
eth2client "github.com/attestantio/go-eth2-client"
spec "github.com/attestantio/go-eth2-client/spec/phase0"
"github.com/attestantio/go-eth2-client/spec/phase0"
"github.com/pkg/errors"
"github.com/spf13/viper"
"github.com/wealdtech/ethdo/services/chaintime"
standardchaintime "github.com/wealdtech/ethdo/services/chaintime/standard"
"github.com/wealdtech/ethdo/util"
)
@@ -31,13 +33,11 @@ type dataIn struct {
verbose bool
debug bool
json bool
// Chain information.
slotsPerEpoch uint64
// Operation.
account string
pubKey string
validator string
eth2Client eth2client.Service
epoch spec.Epoch
chainTime chaintime.Service
epoch phase0.Epoch
}
func input(ctx context.Context) (*dataIn, error) {
@@ -52,38 +52,37 @@ func input(ctx context.Context) (*dataIn, error) {
data.debug = viper.GetBool("debug")
data.json = viper.GetBool("json")
// Account or pubkey.
if viper.GetString("account") == "" && viper.GetString("pubkey") == "" {
return nil, errors.New("account or pubkey is required")
// Validator.
data.validator = viper.GetString("validator")
if data.validator == "" {
return nil, errors.New("validator is required")
}
data.account = viper.GetString("account")
data.pubKey = viper.GetString("pubkey")
// Ethereum 2 client.
var err error
data.eth2Client, err = util.ConnectToBeaconNode(ctx, viper.GetString("connection"), viper.GetDuration("timeout"), viper.GetBool("allow-insecure-connections"))
data.eth2Client, err = util.ConnectToBeaconNode(ctx, &util.ConnectOpts{
Address: viper.GetString("connection"),
Timeout: viper.GetDuration("timeout"),
AllowInsecure: viper.GetBool("allow-insecure-connections"),
LogFallback: !data.quiet,
})
if err != nil {
return nil, err
}
// Required data.
config, err := data.eth2Client.(eth2client.SpecProvider).Spec(ctx)
data.chainTime, err = standardchaintime.New(ctx,
standardchaintime.WithSpecProvider(data.eth2Client.(eth2client.SpecProvider)),
standardchaintime.WithGenesisTimeProvider(data.eth2Client.(eth2client.GenesisTimeProvider)),
)
if err != nil {
return nil, errors.Wrap(err, "failed to obtain beacon chain configuration")
return nil, errors.Wrap(err, "failed to set up chaintime service")
}
data.slotsPerEpoch = config["SLOTS_PER_EPOCH"].(uint64)
// Epoch
epoch := viper.GetInt64("epoch")
if epoch == -1 {
slotDuration := config["SECONDS_PER_SLOT"].(time.Duration)
genesis, err := data.eth2Client.(eth2client.GenesisProvider).Genesis(ctx)
if err != nil {
return nil, errors.Wrap(err, "failed to obtain genesis data")
}
epoch = int64(time.Since(genesis.GenesisTime).Seconds()) / (int64(slotDuration.Seconds()) * int64(data.slotsPerEpoch))
// Epoch.
data.epoch, err = util.ParseEpoch(ctx, data.chainTime, viper.GetString("epoch"))
if err != nil {
return nil, err
}
data.epoch = spec.Epoch(epoch)
return data, nil
}

View File

@@ -17,6 +17,7 @@ import (
"context"
"os"
"testing"
"time"
"github.com/spf13/viper"
"github.com/stretchr/testify/require"
@@ -61,19 +62,21 @@ func TestInput(t *testing.T) {
err: "timeout is required",
},
{
name: "AccountMissing",
name: "ValidatorMissing",
vars: map[string]interface{}{
"timeout": "5s",
},
err: "account or pubkey is required",
err: "validator is required",
},
{
name: "ConnectionMissing",
name: "Good",
vars: map[string]interface{}{
"timeout": "5s",
"pubkey": "0xa99a76ed7796f7be22d5b7e85deeb7c5677e88e511e0b337618f8c4eb61349b4bf2d153f649f7b53359fe8b94a38e44c",
"timeout": "5s",
"validator": "0xa99a76ed7796f7be22d5b7e85deeb7c5677e88e511e0b337618f8c4eb61349b4bf2d153f649f7b53359fe8b94a38e44c",
},
res: &dataIn{
timeout: 5 * time.Second,
},
err: "failed to connect to any beacon node",
},
}

View File

@@ -30,7 +30,7 @@ type dataOut struct {
duty *api.AttesterDuty
}
func output(ctx context.Context, data *dataOut) (string, error) {
func output(_ context.Context, data *dataOut) (string, error) {
if data == nil {
return "", errors.New("no data")
}

View File

@@ -15,16 +15,12 @@ package attesterduties
import (
"context"
"encoding/hex"
"fmt"
"strings"
eth2client "github.com/attestantio/go-eth2-client"
api "github.com/attestantio/go-eth2-client/api/v1"
spec "github.com/attestantio/go-eth2-client/spec/phase0"
"github.com/pkg/errors"
"github.com/wealdtech/ethdo/util"
e2wtypes "github.com/wealdtech/go-eth2-wallet-types/v2"
)
func process(ctx context.Context, data *dataIn) (*dataOut, error) {
@@ -32,43 +28,9 @@ func process(ctx context.Context, data *dataIn) (*dataOut, error) {
return nil, errors.New("no data")
}
var account e2wtypes.Account
var err error
if data.account != "" {
ctx, cancel := context.WithTimeout(ctx, data.timeout)
defer cancel()
_, account, err = util.WalletAndAccountFromPath(ctx, data.account)
if err != nil {
return nil, errors.Wrap(err, "failed to obtain account")
}
} else {
pubKeyBytes, err := hex.DecodeString(strings.TrimPrefix(data.pubKey, "0x"))
if err != nil {
return nil, errors.Wrap(err, fmt.Sprintf("failed to decode public key %s", data.pubKey))
}
account, err = util.NewScratchAccount(nil, pubKeyBytes)
if err != nil {
return nil, errors.Wrap(err, fmt.Sprintf("invalid public key %s", data.pubKey))
}
}
// Fetch validator
pubKeys := make([]spec.BLSPubKey, 1)
pubKey, err := util.BestPublicKey(account)
validator, err := util.ParseValidator(ctx, data.eth2Client.(eth2client.ValidatorsProvider), data.validator, "head")
if err != nil {
return nil, errors.Wrap(err, "failed to obtain public key for account")
}
copy(pubKeys[0][:], pubKey.Marshal())
validators, err := data.eth2Client.(eth2client.ValidatorsProvider).ValidatorsByPubKey(ctx, fmt.Sprintf("%d", uint64(data.epoch)*data.slotsPerEpoch), pubKeys)
if err != nil {
return nil, errors.New("failed to obtain validator information")
}
if len(validators) == 0 {
return nil, errors.New("validator is not known")
}
var validator *api.Validator
for _, v := range validators {
validator = v
return nil, err
}
results := &dataOut{
@@ -77,7 +39,7 @@ func process(ctx context.Context, data *dataIn) (*dataOut, error) {
verbose: data.verbose,
}
duty, err := duty(ctx, data.eth2Client, validator, data.epoch, data.slotsPerEpoch)
duty, err := duty(ctx, data.eth2Client, validator, data.epoch)
if err != nil {
return nil, errors.Wrap(err, "failed to obtain duty for validator")
}
@@ -87,7 +49,7 @@ func process(ctx context.Context, data *dataIn) (*dataOut, error) {
return results, nil
}
func duty(ctx context.Context, eth2Client eth2client.Service, validator *api.Validator, epoch spec.Epoch, slotsPerEpoch uint64) (*api.AttesterDuty, error) {
func duty(ctx context.Context, eth2Client eth2client.Service, validator *api.Validator, epoch spec.Epoch) (*api.AttesterDuty, error) {
// Find the attesting slot for the given epoch.
duties, err := eth2Client.(eth2client.AttesterDutiesProvider).AttesterDuties(ctx, epoch, []spec.ValidatorIndex{validator.Index})
if err != nil {

View File

@@ -18,9 +18,11 @@ import (
"os"
"testing"
eth2client "github.com/attestantio/go-eth2-client"
"github.com/attestantio/go-eth2-client/auto"
"github.com/rs/zerolog"
"github.com/stretchr/testify/require"
standardchaintime "github.com/wealdtech/ethdo/services/chaintime/standard"
)
func TestProcess(t *testing.T) {
@@ -33,6 +35,12 @@ func TestProcess(t *testing.T) {
)
require.NoError(t, err)
chainTime, err := standardchaintime.New(context.Background(),
standardchaintime.WithSpecProvider(eth2Client.(eth2client.SpecProvider)),
standardchaintime.WithGenesisTimeProvider(eth2Client.(eth2client.GenesisTimeProvider)),
)
require.NoError(t, err)
tests := []struct {
name string
dataIn *dataIn
@@ -45,10 +53,9 @@ func TestProcess(t *testing.T) {
{
name: "Client",
dataIn: &dataIn{
eth2Client: eth2Client,
slotsPerEpoch: 32,
pubKey: "0x933ad9491b62059dd065b560d256d8957a8c402cc6e8d8ee7290ae11e8f7329267a8811c397529dac52ae1342ba58c95",
epoch: 100,
eth2Client: eth2Client,
chainTime: chainTime,
validator: "0x933ad9491b62059dd065b560d256d8957a8c402cc6e8d8ee7290ae11e8f7329267a8811c397529dac52ae1342ba58c95",
},
},
}

View File

@@ -15,7 +15,6 @@ package attesterinclusion
import (
"context"
"fmt"
"time"
eth2client "github.com/attestantio/go-eth2-client"
@@ -23,6 +22,7 @@ import (
"github.com/pkg/errors"
"github.com/spf13/viper"
"github.com/wealdtech/ethdo/services/chaintime"
standardchaintime "github.com/wealdtech/ethdo/services/chaintime/standard"
"github.com/wealdtech/ethdo/util"
)
@@ -32,15 +32,11 @@ type dataIn struct {
quiet bool
verbose bool
debug bool
// Chain information.
slotsPerEpoch uint64
// Operation.
eth2Client eth2client.Service
chainTime chaintime.Service
epoch spec.Epoch
account string
pubKey string
index string
validator string
}
func input(ctx context.Context) (*dataIn, error) {
@@ -54,48 +50,35 @@ func input(ctx context.Context) (*dataIn, error) {
data.verbose = viper.GetBool("verbose")
data.debug = viper.GetBool("debug")
// Account.
data.account = viper.GetString("account")
// PubKey.
data.pubKey = viper.GetString("pubkey")
// ID.
data.index = viper.GetString("index")
if viper.GetString("account") == "" && viper.GetString("index") == "" && viper.GetString("pubkey") == "" {
return nil, errors.New("account, index or pubkey is required")
data.validator = viper.GetString("validator")
if data.validator == "" {
return nil, errors.New("validator is required")
}
// Ethereum 2 client.
var err error
data.eth2Client, err = util.ConnectToBeaconNode(ctx, viper.GetString("connection"), viper.GetDuration("timeout"), viper.GetBool("allow-insecure-connections"))
data.eth2Client, err = util.ConnectToBeaconNode(ctx, &util.ConnectOpts{
Address: viper.GetString("connection"),
Timeout: viper.GetDuration("timeout"),
AllowInsecure: viper.GetBool("allow-insecure-connections"),
LogFallback: !data.quiet,
})
if err != nil {
return nil, err
}
config, err := data.eth2Client.(eth2client.SpecProvider).Spec(ctx)
data.chainTime, err = standardchaintime.New(ctx,
standardchaintime.WithSpecProvider(data.eth2Client.(eth2client.SpecProvider)),
standardchaintime.WithGenesisTimeProvider(data.eth2Client.(eth2client.GenesisTimeProvider)),
)
if err != nil {
return nil, errors.Wrap(err, "failed to obtain beacon chain configuration")
return nil, errors.Wrap(err, "failed to set up chaintime service")
}
data.slotsPerEpoch = config["SLOTS_PER_EPOCH"].(uint64)
// Epoch.
epoch := viper.GetInt64("epoch")
if epoch == -1 {
slotDuration := config["SECONDS_PER_SLOT"].(time.Duration)
genesis, err := data.eth2Client.(eth2client.GenesisProvider).Genesis(ctx)
if err != nil {
return nil, errors.Wrap(err, "failed to obtain genesis data")
}
epoch = int64(time.Since(genesis.GenesisTime).Seconds()) / (int64(slotDuration.Seconds()) * int64(data.slotsPerEpoch))
if epoch > 0 {
epoch--
}
}
data.epoch = spec.Epoch(epoch)
if data.debug {
fmt.Printf("Epoch is %d\n", data.epoch)
data.epoch, err = util.ParseEpoch(ctx, data.chainTime, viper.GetString("epoch"))
if err != nil {
return nil, err
}
return data, nil

View File

@@ -17,6 +17,7 @@ import (
"context"
"os"
"testing"
"time"
"github.com/spf13/viper"
"github.com/stretchr/testify/require"
@@ -61,19 +62,21 @@ func TestInput(t *testing.T) {
err: "timeout is required",
},
{
name: "IndexMissing",
name: "ValidatorMissing",
vars: map[string]interface{}{
"timeout": "5s",
},
err: "account, index or pubkey is required",
err: "validator is required",
},
{
name: "ConnectionMissing",
name: "Good",
vars: map[string]interface{}{
"timeout": "5s",
"pubkey": "0xa99a76ed7796f7be22d5b7e85deeb7c5677e88e511e0b337618f8c4eb61349b4bf2d153f649f7b53359fe8b94a38e44c",
"timeout": "5s",
"validator": "0xa99a76ed7796f7be22d5b7e85deeb7c5677e88e511e0b337618f8c4eb61349b4bf2d153f649f7b53359fe8b94a38e44c",
},
res: &dataIn{
timeout: 5 * time.Second,
},
err: "failed to connect to any beacon node",
},
}

View File

@@ -38,7 +38,7 @@ type dataOut struct {
targetTimely bool
}
func output(ctx context.Context, data *dataOut) (string, error) {
func output(_ context.Context, data *dataOut) (string, error) {
buf := strings.Builder{}
if data == nil {
return buf.String(), errors.New("no data")

View File

@@ -31,7 +31,10 @@ func process(ctx context.Context, data *dataIn) (*dataOut, error) {
return nil, errors.New("no data")
}
var err error
validator, err := util.ParseValidator(ctx, data.eth2Client.(eth2client.ValidatorsProvider), data.validator, "head")
if err != nil {
return nil, err
}
data.chainTime, err = standardchaintime.New(ctx,
standardchaintime.WithSpecProvider(data.eth2Client.(eth2client.SpecProvider)),
@@ -41,30 +44,13 @@ func process(ctx context.Context, data *dataIn) (*dataOut, error) {
return nil, errors.Wrap(err, "failed to set up chaintime service")
}
validatorIndex, err := util.ValidatorIndex(ctx, data.eth2Client, data.account, data.pubKey, data.index)
if err != nil {
return nil, errors.Wrap(err, "failed to obtain validator index")
}
validators, err := data.eth2Client.(eth2client.ValidatorsProvider).Validators(ctx, fmt.Sprintf("%d", uint64(data.epoch)*data.slotsPerEpoch), []phase0.ValidatorIndex{validatorIndex})
if err != nil {
return nil, errors.New("failed to obtain validator information")
}
if len(validators) == 0 {
return nil, errors.New("validator is not known")
}
var validator *api.Validator
for _, v := range validators {
validator = v
}
results := &dataOut{
debug: data.debug,
quiet: data.quiet,
verbose: data.verbose,
}
duty, err := duty(ctx, data.eth2Client, validator, data.epoch, data.slotsPerEpoch)
duty, err := duty(ctx, data.eth2Client, validator, data.epoch)
if err != nil {
return nil, errors.Wrap(err, "failed to obtain duty for validator")
}
@@ -175,7 +161,7 @@ func calcTargetCorrect(ctx context.Context, data *dataIn, attestation *phase0.At
}
}
func duty(ctx context.Context, eth2Client eth2client.Service, validator *api.Validator, epoch phase0.Epoch, slotsPerEpoch uint64) (*api.AttesterDuty, error) {
func duty(ctx context.Context, eth2Client eth2client.Service, validator *api.Validator, epoch phase0.Epoch) (*api.AttesterDuty, error) {
// Find the attesting slot for the given epoch.
duties, err := eth2Client.(eth2client.AttesterDutiesProvider).AttesterDuties(ctx, epoch, []phase0.ValidatorIndex{validator.Index})
if err != nil {

View File

@@ -18,18 +18,26 @@ import (
"os"
"testing"
"github.com/attestantio/go-eth2-client/auto"
eth2client "github.com/attestantio/go-eth2-client"
"github.com/attestantio/go-eth2-client/http"
"github.com/rs/zerolog"
"github.com/stretchr/testify/require"
standardchaintime "github.com/wealdtech/ethdo/services/chaintime/standard"
)
func TestProcess(t *testing.T) {
if os.Getenv("ETHDO_TEST_CONNECTION") == "" {
t.Skip("ETHDO_TEST_CONNECTION not configured; cannot run tests")
}
eth2Client, err := auto.New(context.Background(),
auto.WithLogLevel(zerolog.Disabled),
auto.WithAddress(os.Getenv("ETHDO_TEST_CONNECTION")),
eth2Client, err := http.New(context.Background(),
http.WithLogLevel(zerolog.Disabled),
http.WithAddress(os.Getenv("ETHDO_TEST_CONNECTION")),
)
require.NoError(t, err)
chainTime, err := standardchaintime.New(context.Background(),
standardchaintime.WithSpecProvider(eth2Client.(eth2client.SpecProvider)),
standardchaintime.WithGenesisTimeProvider(eth2Client.(eth2client.GenesisTimeProvider)),
)
require.NoError(t, err)
@@ -45,10 +53,9 @@ func TestProcess(t *testing.T) {
{
name: "Client",
dataIn: &dataIn{
eth2Client: eth2Client,
slotsPerEpoch: 32,
pubKey: "0x933ad9491b62059dd065b560d256d8957a8c402cc6e8d8ee7290ae11e8f7329267a8811c397529dac52ae1342ba58c95",
epoch: 100,
eth2Client: eth2Client,
chainTime: chainTime,
validator: "0x933ad9491b62059dd065b560d256d8957a8c402cc6e8d8ee7290ae11e8f7329267a8811c397529dac52ae1342ba58c95",
},
},
}

View File

@@ -26,7 +26,7 @@ var attesterDutiesCmd = &cobra.Command{
Short: "Obtain information about duties of an attester",
Long: `Obtain information about dutes of an attester. For example:
ethdo attester duties --account=Validators/00001 --epoch=12345
ethdo attester duties --validator=Validators/00001 --epoch=12345
In quiet mode this will return 0 if a duty from the attester is found, otherwise 1.`,
RunE: func(cmd *cobra.Command, args []string) error {
@@ -47,8 +47,8 @@ In quiet mode this will return 0 if a duty from the attester is found, otherwise
func init() {
attesterCmd.AddCommand(attesterDutiesCmd)
attesterFlags(attesterDutiesCmd)
attesterDutiesCmd.Flags().Int64("epoch", -1, "the last complete epoch")
attesterDutiesCmd.Flags().String("pubkey", "", "the public key of the attester")
attesterDutiesCmd.Flags().String("epoch", "head", "the epoch for which to obtain the duties")
attesterDutiesCmd.Flags().String("validator", "", "the index, public key, or acount of the validator")
attesterDutiesCmd.Flags().Bool("json", false, "Generate JSON data for an exit; do not broadcast to network")
}
@@ -56,7 +56,7 @@ func attesterDutiesBindings() {
if err := viper.BindPFlag("epoch", attesterDutiesCmd.Flags().Lookup("epoch")); err != nil {
panic(err)
}
if err := viper.BindPFlag("pubkey", attesterDutiesCmd.Flags().Lookup("pubkey")); err != nil {
if err := viper.BindPFlag("validator", attesterDutiesCmd.Flags().Lookup("validator")); err != nil {
panic(err)
}
if err := viper.BindPFlag("json", attesterDutiesCmd.Flags().Lookup("json")); err != nil {

View File

@@ -26,7 +26,7 @@ var attesterInclusionCmd = &cobra.Command{
Short: "Obtain information about attester inclusion",
Long: `Obtain information about attester inclusion. For example:
ethdo attester inclusion --account=Validators/00001 --epoch=12345
ethdo attester inclusion --validator=Validators/00001 --epoch=12345
In quiet mode this will return 0 if an attestation from the attester is found on the block of the given epoch, otherwise 1.`,
RunE: func(cmd *cobra.Command, args []string) error {
@@ -47,8 +47,8 @@ In quiet mode this will return 0 if an attestation from the attester is found on
func init() {
attesterCmd.AddCommand(attesterInclusionCmd)
attesterFlags(attesterInclusionCmd)
attesterInclusionCmd.Flags().Int64("epoch", -1, "the last complete epoch")
attesterInclusionCmd.Flags().String("pubkey", "", "the public key of the attester")
attesterInclusionCmd.Flags().String("epoch", "-1", "the epoch for which to obtain the inclusion")
attesterInclusionCmd.Flags().String("validator", "", "the index, public key, or account of the validator")
attesterInclusionCmd.Flags().String("index", "", "the index of the attester")
}
@@ -56,7 +56,7 @@ func attesterInclusionBindings() {
if err := viper.BindPFlag("epoch", attesterInclusionCmd.Flags().Lookup("epoch")); err != nil {
panic(err)
}
if err := viper.BindPFlag("pubkey", attesterInclusionCmd.Flags().Lookup("pubkey")); err != nil {
if err := viper.BindPFlag("validator", attesterInclusionCmd.Flags().Lookup("validator")); err != nil {
panic(err)
}
if err := viper.BindPFlag("index", attesterInclusionCmd.Flags().Lookup("index")); err != nil {

View File

@@ -28,5 +28,5 @@ func init() {
RootCmd.AddCommand(blockCmd)
}
func blockFlags(cmd *cobra.Command) {
func blockFlags(_ *cobra.Command) {
}

View File

@@ -105,7 +105,7 @@ type attestationData struct {
Index int `json:"index"`
}
func newCommand(ctx context.Context) (*command, error) {
func newCommand(_ context.Context) (*command, error) {
c := &command{
quiet: viper.GetBool("quiet"),
verbose: viper.GetBool("verbose"),

View File

@@ -106,9 +106,8 @@ func (c *command) outputTxt(_ context.Context) (string, error) {
if attestation.NewVotes == 0 {
builder.WriteString("\n")
continue
} else {
builder.WriteString(", ")
}
builder.WriteString(", ")
switch {
case !attestation.HeadCorrect:
builder.WriteString("head vote incorrect, ")

View File

@@ -77,11 +77,7 @@ func (c *command) analyze(ctx context.Context, block *spec.VersionedSignedBeacon
return err
}
if err := c.analyzeSyncCommittees(ctx, block); err != nil {
return err
}
return nil
return c.analyzeSyncCommittees(ctx, block)
}
func (c *command) analyzeAttestations(ctx context.Context, block *spec.VersionedSignedBeaconBlock) error {
@@ -213,7 +209,7 @@ func (c *command) fetchParents(ctx context.Context, block *spec.VersionedSignedB
return c.fetchParents(ctx, parentBlock, minSlot)
}
func (c *command) processParentBlock(ctx context.Context, block *spec.VersionedSignedBeaconBlock) error {
func (c *command) processParentBlock(_ context.Context, block *spec.VersionedSignedBeaconBlock) error {
attestations, err := block.Attestations()
if err != nil {
return err
@@ -259,7 +255,12 @@ func (c *command) setup(ctx context.Context) error {
var err error
// Connect to the client.
c.eth2Client, err = util.ConnectToBeaconNode(ctx, c.connection, c.timeout, c.allowInsecureConnections)
c.eth2Client, err = util.ConnectToBeaconNode(ctx, &util.ConnectOpts{
Address: c.connection,
Timeout: c.timeout,
AllowInsecure: c.allowInsecureConnections,
LogFallback: !c.quiet,
})
if err != nil {
return errors.Wrap(err, "failed to connect to beacon node")
}
@@ -412,7 +413,7 @@ func (c *command) calcTargetCorrect(ctx context.Context, attestation *phase0.Att
return bytes.Equal(root[:], attestation.Data.Target.Root[:]), nil
}
func (c *command) analyzeSyncCommittees(ctx context.Context, block *spec.VersionedSignedBeaconBlock) error {
func (c *command) analyzeSyncCommittees(_ context.Context, block *spec.VersionedSignedBeaconBlock) error {
c.analysis.SyncCommitee = &syncCommitteeAnalysis{}
switch block.Version {
case spec.DataVersionPhase0:

View File

@@ -39,7 +39,7 @@ func TestProcess(t *testing.T) {
"connection": os.Getenv("ETHDO_TEST_CONNECTION"),
"blockid": "invalid",
},
err: "failed to obtain beacon block: failed to request signed beacon block: GET failed with status 400: {\"code\":400,\"message\":\"Invalid block: invalid\"}",
err: "failed to obtain beacon block: failed to request signed beacon block: GET failed with status 400: {\"code\":400,\"message\":\"BAD_REQUEST: Unsupported endpoint version: v2\",\"stacktraces\":[]}",
},
}

View File

@@ -54,7 +54,12 @@ func input(ctx context.Context) (*dataIn, error) {
data.stream = viper.GetBool("stream")
var err error
data.eth2Client, err = util.ConnectToBeaconNode(ctx, viper.GetString("connection"), viper.GetDuration("timeout"), viper.GetBool("allow-insecure-connections"))
data.eth2Client, err = util.ConnectToBeaconNode(ctx, &util.ConnectOpts{
Address: viper.GetString("connection"),
Timeout: viper.GetDuration("timeout"),
AllowInsecure: viper.GetBool("allow-insecure-connections"),
LogFallback: !data.quiet,
})
if err != nil {
return nil, err
}

View File

@@ -61,13 +61,6 @@ func TestInput(t *testing.T) {
vars: map[string]interface{}{},
err: "timeout is required",
},
{
name: "ConnectionMissing",
vars: map[string]interface{}{
"timeout": "5s",
},
err: "failed to connect to any beacon node",
},
{
name: "ConnectionBad",
vars: map[string]interface{}{

View File

@@ -43,7 +43,7 @@ type dataOut struct {
slotsPerEpoch uint64
}
func output(ctx context.Context, data *dataOut) (string, error) {
func output(_ context.Context, data *dataOut) (string, error) {
if data == nil {
return "", errors.New("no data")
}
@@ -51,7 +51,7 @@ func output(ctx context.Context, data *dataOut) (string, error) {
return "", nil
}
func outputBlockGeneral(ctx context.Context,
func outputBlockGeneral(_ context.Context,
verbose bool,
slot phase0.Slot,
blockRoot phase0.Root,
@@ -89,7 +89,7 @@ func outputBlockGeneral(ctx context.Context,
return res.String(), nil
}
func outputBlockETH1Data(ctx context.Context, eth1Data *phase0.ETH1Data) (string, error) {
func outputBlockETH1Data(_ context.Context, eth1Data *phase0.ETH1Data) (string, error) {
res := strings.Builder{}
res.WriteString(fmt.Sprintf("Ethereum 1 deposit count: %d\n", eth1Data.DepositCount))
@@ -194,7 +194,7 @@ func outputBlockAttesterSlashings(ctx context.Context, eth2Client eth2client.Ser
return res.String(), nil
}
func outputBlockDeposits(ctx context.Context, verbose bool, deposits []*phase0.Deposit) (string, error) {
func outputBlockDeposits(_ context.Context, verbose bool, deposits []*phase0.Deposit) (string, error) {
res := strings.Builder{}
// Deposits.
@@ -638,7 +638,7 @@ func outputPhase0BlockText(ctx context.Context, data *dataOut, signedBlock *phas
return res.String(), nil
}
func outputCapellaBlockExecutionPayload(ctx context.Context,
func outputCapellaBlockExecutionPayload(_ context.Context,
verbose bool,
payload *capella.ExecutionPayload,
) (
@@ -706,7 +706,7 @@ func outputCapellaBlockExecutionPayload(ctx context.Context,
return res.String(), nil
}
func outputBellatrixBlockExecutionPayload(ctx context.Context,
func outputBellatrixBlockExecutionPayload(_ context.Context,
verbose bool,
payload *bellatrix.ExecutionPayload,
) (

View File

@@ -1,4 +1,4 @@
// Copyright © 2019, 2020 Weald Technology Trading
// Copyright © 2019 - 2023 Weald Technology Trading.
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
@@ -39,6 +39,9 @@ func process(ctx context.Context, data *dataIn) (*dataOut, error) {
if data == nil {
return nil, errors.New("no data")
}
if data.blockID == "" {
return nil, errors.New("no block ID")
}
results = &dataOut{
debug: data.debug,

View File

@@ -1,4 +1,4 @@
// Copyright © 2019, 2020 Weald Technology Trading
// Copyright © 2019 - 2023 Weald Technology Trading.
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
@@ -43,11 +43,11 @@ func TestProcess(t *testing.T) {
err: "no data",
},
{
name: "Client",
name: "NoBlockID",
dataIn: &dataIn{
eth2Client: eth2Client,
},
err: "empty beacon block",
err: "no block ID",
},
}

View File

@@ -28,5 +28,5 @@ func init() {
RootCmd.AddCommand(chainCmd)
}
func chainFlags(cmd *cobra.Command) {
func chainFlags(_ *cobra.Command) {
}

View File

@@ -60,7 +60,7 @@ type vote struct {
Count int `json:"count"`
}
func newCommand(ctx context.Context) (*command, error) {
func newCommand(_ context.Context) (*command, error) {
c := &command{
quiet: viper.GetBool("quiet"),
verbose: viper.GetBool("verbose"),

View File

@@ -42,7 +42,7 @@ func (c *command) output(ctx context.Context) (string, error) {
return c.outputText(ctx)
}
func (c *command) outputJSON(ctx context.Context) (string, error) {
func (c *command) outputJSON(_ context.Context) (string, error) {
votes := make([]*vote, 0, len(c.votes))
totalVotes := 0
for _, vote := range c.votes {
@@ -71,7 +71,7 @@ func (c *command) outputJSON(ctx context.Context) (string, error) {
return string(data), nil
}
func (c *command) outputText(ctx context.Context) (string, error) {
func (c *command) outputText(_ context.Context) (string, error) {
builder := strings.Builder{}
builder.WriteString("Voting period: ")

View File

@@ -114,7 +114,12 @@ func (c *command) setup(ctx context.Context) error {
var err error
// Connect to the client.
c.eth2Client, err = util.ConnectToBeaconNode(ctx, c.connection, c.timeout, c.allowInsecureConnections)
c.eth2Client, err = util.ConnectToBeaconNode(ctx, &util.ConnectOpts{
Address: c.connection,
Timeout: c.timeout,
AllowInsecure: c.allowInsecureConnections,
LogFallback: !c.quiet,
})
if err != nil {
return errors.Wrap(err, "failed to connect to beacon node")
}

View File

@@ -47,7 +47,7 @@ type command struct {
exitQueue int
}
func newCommand(ctx context.Context) (*command, error) {
func newCommand(_ context.Context) (*command, error) {
c := &command{
quiet: viper.GetBool("quiet"),
verbose: viper.GetBool("verbose"),

View File

@@ -36,7 +36,7 @@ func (c *command) output(ctx context.Context) (string, error) {
return c.outputText(ctx)
}
func (c *command) outputJSON(ctx context.Context) (string, error) {
func (c *command) outputJSON(_ context.Context) (string, error) {
output := &jsonOutput{
ActivationQueue: c.activationQueue,
ExitQueue: c.exitQueue,
@@ -49,7 +49,7 @@ func (c *command) outputJSON(ctx context.Context) (string, error) {
return string(data), nil
}
func (c *command) outputText(ctx context.Context) (string, error) {
func (c *command) outputText(_ context.Context) (string, error) {
builder := strings.Builder{}
if c.activationQueue > 0 {

View File

@@ -58,7 +58,12 @@ func (c *command) setup(ctx context.Context) error {
var err error
// Connect to the client.
c.eth2Client, err = util.ConnectToBeaconNode(ctx, c.connection, c.timeout, c.allowInsecureConnections)
c.eth2Client, err = util.ConnectToBeaconNode(ctx, &util.ConnectOpts{
Address: c.connection,
Timeout: c.timeout,
AllowInsecure: c.allowInsecureConnections,
LogFallback: !c.quiet,
})
if err != nil {
return errors.Wrap(err, "failed to connect to beacon node")
}

View File

@@ -36,7 +36,7 @@ type dataIn struct {
epoch string
}
func input(ctx context.Context) (*dataIn, error) {
func input(_ context.Context) (*dataIn, error) {
data := &dataIn{}
if viper.GetDuration("timeout") == 0 {

View File

@@ -34,6 +34,7 @@ type dataOut struct {
slot spec.Slot
slotStart time.Time
slotEnd time.Time
hasSyncCommittees bool
syncCommitteePeriod uint64
syncCommitteePeriodStart time.Time
syncCommitteePeriodEpochStart spec.Epoch
@@ -41,7 +42,7 @@ type dataOut struct {
syncCommitteePeriodEpochEnd spec.Epoch
}
func output(ctx context.Context, data *dataOut) (string, error) {
func output(_ context.Context, data *dataOut) (string, error) {
if data == nil {
return "", errors.New("no data")
}
@@ -56,27 +57,59 @@ func output(ctx context.Context, data *dataOut) (string, error) {
builder.WriteString(fmt.Sprintf("%d", data.epoch))
builder.WriteString("\n Epoch start ")
builder.WriteString(data.epochStart.Format("2006-01-02 15:04:05"))
if data.verbose {
builder.WriteString(" (")
builder.WriteString(fmt.Sprintf("%d", data.epochStart.Unix()))
builder.WriteString(")")
}
builder.WriteString("\n Epoch end ")
builder.WriteString(data.epochEnd.Format("2006-01-02 15:04:05"))
if data.verbose {
builder.WriteString(" (")
builder.WriteString(fmt.Sprintf("%d", data.epochEnd.Unix()))
builder.WriteString(")")
}
builder.WriteString("\nSlot ")
builder.WriteString(fmt.Sprintf("%d", data.slot))
builder.WriteString("\n Slot start ")
builder.WriteString(data.slotStart.Format("2006-01-02 15:04:05"))
if data.verbose {
builder.WriteString(" (")
builder.WriteString(fmt.Sprintf("%d", data.slotStart.Unix()))
builder.WriteString(")")
}
builder.WriteString("\n Slot end ")
builder.WriteString(data.slotEnd.Format("2006-01-02 15:04:05"))
if data.verbose {
builder.WriteString(" (")
builder.WriteString(fmt.Sprintf("%d", data.slotEnd.Unix()))
builder.WriteString(")")
}
builder.WriteString("\nSync committee period ")
builder.WriteString(fmt.Sprintf("%d", data.syncCommitteePeriod))
builder.WriteString("\n Sync committee period start ")
builder.WriteString(data.syncCommitteePeriodStart.Format("2006-01-02 15:04:05"))
builder.WriteString(" (epoch ")
builder.WriteString(fmt.Sprintf("%d", data.syncCommitteePeriodEpochStart))
builder.WriteString(")\n Sync committee period end ")
builder.WriteString(data.syncCommitteePeriodEnd.Format("2006-01-02 15:04:05"))
builder.WriteString(" (epoch ")
builder.WriteString(fmt.Sprintf("%d", data.syncCommitteePeriodEpochEnd))
builder.WriteString(")\n")
if data.hasSyncCommittees {
builder.WriteString("\nSync committee period ")
builder.WriteString(fmt.Sprintf("%d", data.syncCommitteePeriod))
builder.WriteString("\n Sync committee period start ")
builder.WriteString(data.syncCommitteePeriodStart.Format("2006-01-02 15:04:05"))
builder.WriteString(" (epoch ")
builder.WriteString(fmt.Sprintf("%d", data.syncCommitteePeriodEpochStart))
if data.verbose {
builder.WriteString(", ")
builder.WriteString(fmt.Sprintf("%d", data.syncCommitteePeriodStart.Unix()))
}
builder.WriteString(")\n Sync committee period end ")
builder.WriteString(data.syncCommitteePeriodEnd.Format("2006-01-02 15:04:05"))
builder.WriteString(" (epoch ")
builder.WriteString(fmt.Sprintf("%d", data.syncCommitteePeriodEpochEnd))
if data.verbose {
builder.WriteString(", ")
builder.WriteString(fmt.Sprintf("%d", data.syncCommitteePeriodEnd.Unix()))
}
builder.WriteString(")")
}
builder.WriteString("\n")
return builder.String(), nil
}

View File

@@ -21,6 +21,7 @@ import (
eth2client "github.com/attestantio/go-eth2-client"
"github.com/attestantio/go-eth2-client/spec/phase0"
"github.com/pkg/errors"
standardchaintime "github.com/wealdtech/ethdo/services/chaintime/standard"
"github.com/wealdtech/ethdo/util"
)
@@ -29,22 +30,22 @@ func process(ctx context.Context, data *dataIn) (*dataOut, error) {
return nil, errors.New("no data")
}
eth2Client, err := util.ConnectToBeaconNode(ctx, data.connection, data.timeout, data.allowInsecureConnections)
eth2Client, err := util.ConnectToBeaconNode(ctx, &util.ConnectOpts{
Address: data.connection,
Timeout: data.timeout,
AllowInsecure: data.allowInsecureConnections,
LogFallback: !data.quiet,
})
if err != nil {
return nil, errors.Wrap(err, "failed to connect to Ethereum 2 beacon node")
}
config, err := eth2Client.(eth2client.SpecProvider).Spec(ctx)
chainTime, err := standardchaintime.New(ctx,
standardchaintime.WithSpecProvider(eth2Client.(eth2client.SpecProvider)),
standardchaintime.WithGenesisTimeProvider(eth2Client.(eth2client.GenesisTimeProvider)),
)
if err != nil {
return nil, errors.Wrap(err, "failed to obtain beacon chain configuration")
}
slotsPerEpoch := config["SLOTS_PER_EPOCH"].(uint64)
slotDuration := config["SECONDS_PER_SLOT"].(time.Duration)
epochsPerSyncCommitteePeriod := config["EPOCHS_PER_SYNC_COMMITTEE_PERIOD"].(uint64)
genesis, err := eth2Client.(eth2client.GenesisProvider).Genesis(ctx)
if err != nil {
return nil, errors.Wrap(err, "failed to obtain genesis data")
return nil, errors.Wrap(err, "failed to set up chaintime service")
}
results := &dataOut{
@@ -62,34 +63,33 @@ func process(ctx context.Context, data *dataIn) (*dataOut, error) {
}
results.slot = phase0.Slot(slot)
case data.epoch != "":
epoch, err := strconv.ParseUint(data.epoch, 10, 64)
epoch, err := util.ParseEpoch(ctx, chainTime, data.epoch)
if err != nil {
return nil, errors.Wrap(err, "failed to parse epoch")
}
results.slot = phase0.Slot(epoch * slotsPerEpoch)
results.slot = chainTime.FirstSlotOfEpoch(epoch)
case data.timestamp != "":
timestamp, err := time.Parse("2006-01-02T15:04:05-0700", data.timestamp)
if err != nil {
return nil, errors.Wrap(err, "failed to parse timestamp")
}
secs := timestamp.Sub(genesis.GenesisTime)
if secs < 0 {
return nil, errors.New("timestamp prior to genesis")
}
results.slot = phase0.Slot(secs / slotDuration)
results.slot = chainTime.TimestampToSlot(timestamp)
}
// Fill in the info given the slot.
results.slotStart = genesis.GenesisTime.Add(time.Duration(results.slot) * slotDuration)
results.slotEnd = genesis.GenesisTime.Add(time.Duration(results.slot+1) * slotDuration)
results.epoch = phase0.Epoch(uint64(results.slot) / slotsPerEpoch)
results.epochStart = genesis.GenesisTime.Add(time.Duration(uint64(results.epoch)*slotsPerEpoch) * slotDuration)
results.epochEnd = genesis.GenesisTime.Add(time.Duration(uint64(results.epoch+1)*slotsPerEpoch) * slotDuration)
results.syncCommitteePeriod = uint64(results.epoch) / epochsPerSyncCommitteePeriod
results.syncCommitteePeriodEpochStart = phase0.Epoch(results.syncCommitteePeriod * epochsPerSyncCommitteePeriod)
results.syncCommitteePeriodEpochEnd = phase0.Epoch((results.syncCommitteePeriod+1)*epochsPerSyncCommitteePeriod) - 1
results.syncCommitteePeriodStart = genesis.GenesisTime.Add(time.Duration(uint64(results.syncCommitteePeriodEpochStart)*slotsPerEpoch) * slotDuration)
results.syncCommitteePeriodEnd = genesis.GenesisTime.Add(time.Duration(uint64(results.syncCommitteePeriodEpochEnd)*slotsPerEpoch) * slotDuration)
results.slotStart = chainTime.StartOfSlot(results.slot)
results.slotEnd = chainTime.StartOfSlot(results.slot + 1)
results.epoch = chainTime.SlotToEpoch(results.slot)
results.epochStart = chainTime.StartOfEpoch(results.epoch)
results.epochEnd = chainTime.StartOfEpoch(results.epoch + 1)
if results.epoch >= chainTime.FirstEpochOfSyncPeriod(chainTime.AltairInitialSyncCommitteePeriod()) {
results.hasSyncCommittees = true
results.syncCommitteePeriod = chainTime.SlotToSyncCommitteePeriod(results.slot)
results.syncCommitteePeriodEpochStart = chainTime.FirstEpochOfSyncPeriod(results.syncCommitteePeriod)
results.syncCommitteePeriodEpochEnd = chainTime.FirstEpochOfSyncPeriod(results.syncCommitteePeriod + 1)
results.syncCommitteePeriodStart = chainTime.StartOfEpoch(results.syncCommitteePeriodEpochStart)
results.syncCommitteePeriodEnd = chainTime.StartOfEpoch(results.syncCommitteePeriodEpochEnd)
}
return results, nil
}

View File

@@ -1,4 +1,4 @@
// Copyright © 2021 Weald Technology Trading
// Copyright © 2021 - 2023 Weald Technology Trading.
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
@@ -15,7 +15,6 @@ package chaintime
import (
"context"
"fmt"
"os"
"testing"
"time"
@@ -47,16 +46,11 @@ func TestProcess(t *testing.T) {
slot: "1",
},
expected: &dataOut{
epochStart: time.Unix(1606824023, 0),
epochEnd: time.Unix(1606824407, 0),
slot: 1,
slotStart: time.Unix(1606824035, 0),
slotEnd: time.Unix(1606824047, 0),
syncCommitteePeriod: 0,
syncCommitteePeriodStart: time.Unix(1606824023, 0),
syncCommitteePeriodEnd: time.Unix(1606921943, 0),
syncCommitteePeriodEpochStart: 0,
syncCommitteePeriodEpochEnd: 255,
epochStart: time.Unix(1606824023, 0),
epochEnd: time.Unix(1606824407, 0),
slot: 1,
slotStart: time.Unix(1606824035, 0),
slotEnd: time.Unix(1606824047, 0),
},
},
{
@@ -68,17 +62,12 @@ func TestProcess(t *testing.T) {
epoch: "2",
},
expected: &dataOut{
epoch: 2,
epochStart: time.Unix(1606824791, 0),
epochEnd: time.Unix(1606825175, 0),
slot: 64,
slotStart: time.Unix(1606824791, 0),
slotEnd: time.Unix(1606824803, 0),
syncCommitteePeriod: 0,
syncCommitteePeriodStart: time.Unix(1606824023, 0),
syncCommitteePeriodEnd: time.Unix(1606921943, 0),
syncCommitteePeriodEpochStart: 0,
syncCommitteePeriodEpochEnd: 255,
epoch: 2,
epochStart: time.Unix(1606824791, 0),
epochEnd: time.Unix(1606825175, 0),
slot: 64,
slotStart: time.Unix(1606824791, 0),
slotEnd: time.Unix(1606824803, 0),
},
},
{
@@ -87,20 +76,21 @@ func TestProcess(t *testing.T) {
connection: os.Getenv("ETHDO_TEST_CONNECTION"),
timeout: 10 * time.Second,
allowInsecureConnections: true,
timestamp: "2021-01-01T00:00:00+0000",
timestamp: "2023-01-01T00:00:00+0000",
},
expected: &dataOut{
epoch: 6862,
epochStart: time.Unix(1609459031, 0),
epochEnd: time.Unix(1609459415, 0),
slot: 219598,
slotStart: time.Unix(1609459199, 0),
slotEnd: time.Unix(1609459211, 0),
syncCommitteePeriod: 26,
syncCommitteePeriodStart: time.Unix(1609379927, 0),
syncCommitteePeriodEnd: time.Unix(1609477847, 0),
syncCommitteePeriodEpochStart: 6656,
syncCommitteePeriodEpochEnd: 6911,
epoch: 171112,
epochStart: time.Unix(1672531031, 0),
epochEnd: time.Unix(1672531415, 0),
slot: 5475598,
slotStart: time.Unix(1672531199, 0),
slotEnd: time.Unix(1672531211, 0),
hasSyncCommittees: true,
syncCommitteePeriod: 668,
syncCommitteePeriodStart: time.Unix(1672491095, 0),
syncCommitteePeriodEnd: time.Unix(1672589399, 0),
syncCommitteePeriodEpochStart: 171008,
syncCommitteePeriodEpochEnd: 171264,
},
},
}
@@ -112,7 +102,6 @@ func TestProcess(t *testing.T) {
require.EqualError(t, err, test.err)
} else {
require.NoError(t, err)
fmt.Printf("****** %d %d\n", res.syncCommitteePeriodStart.Unix(), res.syncCommitteePeriodEnd.Unix())
require.Equal(t, test.expected, res)
}
})

View File

@@ -58,7 +58,7 @@ type command struct {
additionalInfo string
}
func newCommand(ctx context.Context) (*command, error) {
func newCommand(_ context.Context) (*command, error) {
c := &command{
quiet: viper.GetBool("quiet"),
verbose: viper.GetBool("verbose"),

View File

@@ -18,7 +18,7 @@ import (
"strings"
)
func (c *command) output(ctx context.Context) (string, error) {
func (c *command) output(_ context.Context) (string, error) {
if c.quiet {
return "", nil
}

View File

@@ -85,7 +85,12 @@ func (c *command) setup(ctx context.Context) error {
var err error
// Connect to the client.
c.eth2Client, err = util.ConnectToBeaconNode(ctx, c.connection, c.timeout, c.allowInsecureConnections)
c.eth2Client, err = util.ConnectToBeaconNode(ctx, &util.ConnectOpts{
Address: c.connection,
Timeout: c.timeout,
AllowInsecure: c.allowInsecureConnections,
LogFallback: !c.quiet,
})
if err != nil {
return errors.Wrap(err, "failed to connect to beacon node")
}

View File

@@ -37,7 +37,12 @@ In quiet mode this will return 0 if the chain information can be obtained, other
Run: func(cmd *cobra.Command, args []string) {
ctx := context.Background()
eth2Client, err := util.ConnectToBeaconNode(ctx, viper.GetString("connection"), viper.GetDuration("timeout"), viper.GetBool("allow-insecure-connections"))
eth2Client, err := util.ConnectToBeaconNode(ctx, &util.ConnectOpts{
Address: viper.GetString("connection"),
Timeout: viper.GetDuration("timeout"),
AllowInsecure: viper.GetBool("allow-insecure-connections"),
LogFallback: !viper.GetBool("quiet"),
})
errCheck(err, "Failed to connect to Ethereum 2 beacon node")
config, err := eth2Client.(eth2client.SpecProvider).Spec(ctx)

View File

@@ -41,7 +41,12 @@ In quiet mode this will return 0 if the chain status can be obtained, otherwise
Run: func(cmd *cobra.Command, args []string) {
ctx := context.Background()
eth2Client, err := util.ConnectToBeaconNode(ctx, viper.GetString("connection"), viper.GetDuration("timeout"), viper.GetBool("allow-insecure-connections"))
eth2Client, err := util.ConnectToBeaconNode(ctx, &util.ConnectOpts{
Address: viper.GetString("connection"),
Timeout: viper.GetDuration("timeout"),
AllowInsecure: viper.GetBool("allow-insecure-connections"),
LogFallback: !viper.GetBool("quiet"),
})
errCheck(err, "Failed to connect to Ethereum 2 beacon node")
chainTime, err := standardchaintime.New(ctx,

View File

@@ -28,5 +28,5 @@ func init() {
RootCmd.AddCommand(depositCmd)
}
func depositFlags(cmd *cobra.Command) {
func depositFlags(_ *cobra.Command) {
}

View File

@@ -29,7 +29,7 @@ func init() {
RootCmd.AddCommand(epochCmd)
}
func epochFlags(cmd *cobra.Command) {
func epochFlags(_ *cobra.Command) {
epochSummaryCmd.Flags().String("epoch", "", "the epoch for which to obtain information (default current, can be 'current', 'last' or a number)")
}

View File

@@ -86,7 +86,7 @@ type nonParticipatingValidator struct {
Committee phase0.CommitteeIndex `json:"committee_index"`
}
func newCommand(ctx context.Context) (*command, error) {
func newCommand(_ context.Context) (*command, error) {
c := &command{
quiet: viper.GetBool("quiet"),
verbose: viper.GetBool("verbose"),

View File

@@ -48,11 +48,7 @@ func (c *command) process(ctx context.Context) error {
if err := c.processAttesterDuties(ctx); err != nil {
return err
}
if err := c.processSyncCommitteeDuties(ctx); err != nil {
return err
}
return nil
return c.processSyncCommitteeDuties(ctx)
}
func (c *command) processProposerDuties(ctx context.Context) error {
@@ -328,7 +324,12 @@ func (c *command) setup(ctx context.Context) error {
var err error
// Connect to the client.
c.eth2Client, err = util.ConnectToBeaconNode(ctx, c.connection, c.timeout, c.allowInsecureConnections)
c.eth2Client, err = util.ConnectToBeaconNode(ctx, &util.ConnectOpts{
Address: c.connection,
Timeout: c.timeout,
AllowInsecure: c.allowInsecureConnections,
LogFallback: !c.quiet,
})
if err != nil {
return errors.Wrap(err, "failed to connect to beacon node")
}

View File

@@ -28,5 +28,5 @@ func init() {
RootCmd.AddCommand(exitCmd)
}
func exitFlags(cmd *cobra.Command) {
func exitFlags(_ *cobra.Command) {
}

View File

@@ -14,80 +14,97 @@
package cmd
import (
"bytes"
"context"
"encoding/hex"
"encoding/json"
"fmt"
"os"
"strings"
eth2client "github.com/attestantio/go-eth2-client"
spec "github.com/attestantio/go-eth2-client/spec/phase0"
consensusclient "github.com/attestantio/go-eth2-client"
v1 "github.com/attestantio/go-eth2-client/api/v1"
"github.com/attestantio/go-eth2-client/spec/phase0"
"github.com/pkg/errors"
"github.com/spf13/cobra"
"github.com/spf13/viper"
"github.com/wealdtech/ethdo/util"
e2types "github.com/wealdtech/go-eth2-types/v2"
e2wtypes "github.com/wealdtech/go-eth2-wallet-types/v2"
)
var exitVerifyPubKey string
var exitVerifyCmd = &cobra.Command{
Use: "verify",
Short: "Verify exit data is valid",
Long: `Verify that exit data generated by "ethdo validator exit" is correct for a given account. For example:
ethdo exit verify --data=exitdata.json --account=primary/current
ethdo exit verify --signed-operation=exitdata.json --validator=primary/current
In quiet mode this will return 0 if the exit is verified correctly, otherwise 1.`,
Run: func(cmd *cobra.Command, args []string) {
ctx := context.Background()
assert(viper.GetString("account") != "" || exitVerifyPubKey != "", "account or public key is required")
account, err := exitVerifyAccount(ctx)
errCheck(err, "Failed to obtain account")
assert(viper.GetString("signed-operation") != "", "signed-operation is required")
signedOp, err := obtainSignedOperation(viper.GetString("signed-operation"))
errCheck(err, "Failed to obtain signed operation")
assert(viper.GetString("exit") != "", "exit is required")
data, err := obtainExitData(viper.GetString("exit"))
errCheck(err, "Failed to obtain exit data")
// Confirm signature is good.
eth2Client, err := util.ConnectToBeaconNode(ctx, viper.GetString("connection"), viper.GetDuration("timeout"), viper.GetBool("allow-insecure-connections"))
eth2Client, err := util.ConnectToBeaconNode(ctx, &util.ConnectOpts{
Address: viper.GetString("connection"),
Timeout: viper.GetDuration("timeout"),
AllowInsecure: viper.GetBool("allow-insecure-connections"),
LogFallback: !viper.GetBool("quiet"),
})
errCheck(err, "Failed to connect to Ethereum 2 beacon node")
genesis, err := eth2Client.(eth2client.GenesisProvider).Genesis(ctx)
validator, err := util.ParseValidator(ctx, eth2Client.(consensusclient.ValidatorsProvider), fmt.Sprintf("%d", signedOp.Message.ValidatorIndex), "head")
errCheck(err, "failed to obtain validator")
pubkey, err := validator.PubKey(ctx)
errCheck(err, "failed to obtain validator public key")
account, err := util.ParseAccount(ctx, pubkey.String(), nil, false)
errCheck(err, "failed to obtain account")
// Ensure the validator is in a suitable state.
assert(validator.Status == v1.ValidatorStateActiveOngoing, "validator not in a suitable state to exit")
// Obtain the hash tree root of the message to check the signature.
opRoot, err := signedOp.Message.HashTreeRoot()
errCheck(err, "Failed to obtain exit hash tree root")
genesis, err := eth2Client.(consensusclient.GenesisProvider).Genesis(ctx)
errCheck(err, "Failed to obtain beacon chain genesis")
domain := e2types.Domain(e2types.DomainVoluntaryExit, data.ForkVersion[:], genesis.GenesisValidatorsRoot[:])
var exitDomain spec.Domain
copy(exitDomain[:], domain)
exit := &spec.VoluntaryExit{
Epoch: data.Exit.Message.Epoch,
ValidatorIndex: data.Exit.Message.ValidatorIndex,
}
exitRoot, err := exit.HashTreeRoot()
errCheck(err, "Failed to obtain exit hash tree root")
fork, err := eth2Client.(consensusclient.ForkProvider).Fork(ctx, "head")
errCheck(err, "Failed to obtain fork information")
// Check against current and prior fork versions.
signatureBytes := make([]byte, 96)
copy(signatureBytes, data.Exit.Signature[:])
copy(signatureBytes, signedOp.Signature[:])
sig, err := e2types.BLSSignatureFromBytes(signatureBytes)
errCheck(err, "Invalid signature")
verified, err := util.VerifyRoot(account, exitRoot, exitDomain, sig)
errCheck(err, "Failed to verify voluntary exit")
assert(verified, "Voluntary exit failed to verify")
fork, err := eth2Client.(eth2client.ForkProvider).Fork(ctx, "head")
errCheck(err, "Failed to obtain current fork")
assert(bytes.Equal(data.ForkVersion[:], fork.CurrentVersion[:]) || bytes.Equal(data.ForkVersion[:], fork.PreviousVersion[:]), "Exit is for an old fork version and is no longer valid")
verified := false
// Try with the current fork.
domain := phase0.Domain{}
currentExitDomain, err := e2types.ComputeDomain(e2types.DomainVoluntaryExit, fork.CurrentVersion[:], genesis.GenesisValidatorsRoot[:])
errCheck(err, "Failed to compute domain")
copy(domain[:], currentExitDomain)
verified, err = util.VerifyRoot(account, opRoot, domain, sig)
errCheck(err, "Failed to verify voluntary exit")
if !verified {
// Try again with the previous fork.
previousExitDomain, err := e2types.ComputeDomain(e2types.DomainVoluntaryExit, fork.PreviousVersion[:], genesis.GenesisValidatorsRoot[:])
copy(domain[:], previousExitDomain)
errCheck(err, "Failed to compute domain")
verified, err = util.VerifyRoot(account, opRoot, domain, sig)
errCheck(err, "Failed to verify voluntary exit")
}
assert(verified, "Voluntary exit failed to verify against current and previous fork versions")
outputIf(verbose, "Verified")
os.Exit(_exitSuccess)
},
}
// obtainExitData obtains exit data from an input, could be JSON itself or a path to JSON.
func obtainExitData(input string) (*util.ValidatorExitData, error) {
// obtainSignedOperation obtains exit data from an input, could be JSON itself or a path to JSON.
func obtainSignedOperation(input string) (*phase0.SignedVoluntaryExit, error) {
var err error
var data []byte
// Input could be JSON or a path to JSON
@@ -101,46 +118,23 @@ func obtainExitData(input string) (*util.ValidatorExitData, error) {
return nil, errors.Wrap(err, "failed to find deposit data file")
}
}
exitData := &util.ValidatorExitData{}
err = json.Unmarshal(data, exitData)
signedOp := &phase0.SignedVoluntaryExit{}
err = json.Unmarshal(data, signedOp)
if err != nil {
return nil, errors.Wrap(err, "data is not valid JSON")
}
return exitData, nil
}
// exitVerifyAccount obtains the account for the exitVerify command.
func exitVerifyAccount(ctx context.Context) (e2wtypes.Account, error) {
var account e2wtypes.Account
var err error
if viper.GetString("account") != "" {
_, account, err = walletAndAccountFromPath(ctx, viper.GetString("account"))
if err != nil {
return nil, errors.Wrap(err, "failed to obtain account")
}
} else {
pubKeyBytes, err := hex.DecodeString(strings.TrimPrefix(exitVerifyPubKey, "0x"))
if err != nil {
return nil, errors.Wrap(err, fmt.Sprintf("failed to decode public key %s", exitVerifyPubKey))
}
account, err = util.NewScratchAccount(nil, pubKeyBytes)
if err != nil {
return nil, errors.Wrap(err, fmt.Sprintf("invalid public key %s", exitVerifyPubKey))
}
}
return account, nil
return signedOp, nil
}
func init() {
exitCmd.AddCommand(exitVerifyCmd)
exitFlags(exitVerifyCmd)
exitVerifyCmd.Flags().String("exit", "", "JSON data, or path to JSON data")
exitVerifyCmd.Flags().StringVar(&exitVerifyPubKey, "pubkey", "", "Public key for which to verify exit")
exitVerifyCmd.Flags().String("signed-operation", "", "JSON data, or path to JSON data")
}
func exitVerifyBindings() {
if err := viper.BindPFlag("exit", exitVerifyCmd.Flags().Lookup("exit")); err != nil {
if err := viper.BindPFlag("signed-operation", exitVerifyCmd.Flags().Lookup("signed-operation")); err != nil {
panic(err)
}
}

View File

@@ -28,5 +28,5 @@ func init() {
RootCmd.AddCommand(nodeCmd)
}
func nodeFlags(cmd *cobra.Command) {
func nodeFlags(_ *cobra.Command) {
}

View File

@@ -50,7 +50,12 @@ func input(ctx context.Context) (*dataIn, error) {
data.topics = viper.GetStringSlice("topics")
var err error
data.eth2Client, err = util.ConnectToBeaconNode(ctx, viper.GetString("connection"), viper.GetDuration("timeout"), viper.GetBool("allow-insecure-connections"))
data.eth2Client, err = util.ConnectToBeaconNode(ctx, &util.ConnectOpts{
Address: viper.GetString("connection"),
Timeout: viper.GetDuration("timeout"),
AllowInsecure: viper.GetBool("allow-insecure-connections"),
LogFallback: !data.quiet,
})
if err != nil {
return nil, err
}

View File

@@ -61,13 +61,6 @@ func TestInput(t *testing.T) {
vars: map[string]interface{}{},
err: "timeout is required",
},
{
name: "ConnectionMissing",
vars: map[string]interface{}{
"timeout": "5s",
},
err: "failed to connect to any beacon node",
},
{
name: "ConnectionBad",
vars: map[string]interface{}{

View File

@@ -24,9 +24,6 @@ import (
"github.com/wealdtech/ethdo/util"
)
// defaultBeaconNode is used if no other connection is supplied.
var defaultBeaconNode = "http://mainnet-consensus.attestant.io/"
var nodeInfoCmd = &cobra.Command{
Use: "info",
Short: "Obtain information about a node",
@@ -38,27 +35,13 @@ In quiet mode this will return 0 if the node information can be obtained, otherw
Run: func(cmd *cobra.Command, args []string) {
ctx := context.Background()
eth2Client, err := util.ConnectToBeaconNode(ctx, viper.GetString("connection"), viper.GetDuration("timeout"), viper.GetBool("allow-insecure-connections"))
if err != nil {
if viper.GetString("connection") != "" {
// The user provided a connection, so don't second-guess them by using a different node.
fmt.Fprintln(os.Stderr, err.Error())
return
}
// The user did not provide a connection, so attempt to use the default node.
if viper.GetBool("debug") {
fmt.Fprintf(os.Stderr, "No node connection, attempting to use %s\n", defaultBeaconNode)
}
eth2Client, err = util.ConnectToBeaconNode(ctx, defaultBeaconNode, viper.GetDuration("timeout"), viper.GetBool("allow-insecure-connections"))
if err != nil {
fmt.Fprintln(os.Stderr, err.Error())
return
}
if !viper.GetBool("quiet") {
fmt.Fprintf(os.Stderr, "No connection supplied; using mainnet public access endpoint\n")
}
}
eth2Client, err := util.ConnectToBeaconNode(ctx, &util.ConnectOpts{
Address: viper.GetString("connection"),
Timeout: viper.GetDuration("timeout"),
AllowInsecure: viper.GetBool("allow-insecure-connections"),
LogFallback: !viper.GetBool("quiet"),
})
errCheck(err, "Failed to connect to Ethereum 2 beacon node")
if quiet {
os.Exit(_exitSuccess)

View File

@@ -28,5 +28,5 @@ func init() {
RootCmd.AddCommand(proposerCmd)
}
func proposerFlags(cmd *cobra.Command) {
func proposerFlags(_ *cobra.Command) {
}

View File

@@ -53,7 +53,7 @@ type results struct {
Duties []*apiv1.ProposerDuty `json:"duties"`
}
func newCommand(ctx context.Context) (*command, error) {
func newCommand(_ context.Context) (*command, error) {
c := &command{
quiet: viper.GetBool("quiet"),
verbose: viper.GetBool("verbose"),

View File

@@ -46,7 +46,12 @@ func (c *command) setup(ctx context.Context) error {
var err error
// Connect to the client.
c.eth2Client, err = util.ConnectToBeaconNode(ctx, c.connection, c.timeout, c.allowInsecureConnections)
c.eth2Client, err = util.ConnectToBeaconNode(ctx, &util.ConnectOpts{
Address: c.connection,
Timeout: c.timeout,
AllowInsecure: c.allowInsecureConnections,
LogFallback: !c.quiet,
})
if err != nil {
return errors.Wrap(err, "failed to connect to beacon node")
}

View File

@@ -48,7 +48,7 @@ var RootCmd = &cobra.Command{
PersistentPreRunE: persistentPreRunE,
}
func persistentPreRunE(cmd *cobra.Command, args []string) error {
func persistentPreRunE(cmd *cobra.Command, _ []string) error {
if cmd.Name() == "help" {
// User just wants help
return nil

View File

@@ -28,5 +28,5 @@ func init() {
RootCmd.AddCommand(slotCmd)
}
func slotFlags(cmd *cobra.Command) {
func slotFlags(_ *cobra.Command) {
}

View File

@@ -52,7 +52,12 @@ func input(ctx context.Context) (*dataIn, error) {
// Ethereum 2 client.
var err error
data.eth2Client, err = util.ConnectToBeaconNode(ctx, viper.GetString("connection"), viper.GetDuration("timeout"), viper.GetBool("allow-insecure-connections"))
data.eth2Client, err = util.ConnectToBeaconNode(ctx, &util.ConnectOpts{
Address: viper.GetString("connection"),
Timeout: viper.GetDuration("timeout"),
AllowInsecure: viper.GetBool("allow-insecure-connections"),
LogFallback: !data.quiet,
})
if err != nil {
return nil, err
}

View File

@@ -67,14 +67,6 @@ func TestInput(t *testing.T) {
},
err: "slot is required",
},
{
name: "ConnectionMissing",
vars: map[string]interface{}{
"timeout": "5s",
"slot": "1",
},
err: "failed to connect to any beacon node",
},
}
for _, test := range tests {

View File

@@ -29,7 +29,7 @@ type dataOut struct {
endTime time.Time
}
func output(ctx context.Context, data *dataOut) (string, error) {
func output(_ context.Context, data *dataOut) (string, error) {
if data == nil {
return "", errors.New("no data")
}

View File

@@ -28,5 +28,5 @@ func init() {
RootCmd.AddCommand(synccommitteeCmd)
}
func synccommitteeFlags(cmd *cobra.Command) {
func synccommitteeFlags(_ *cobra.Command) {
}

View File

@@ -18,6 +18,7 @@ import (
"time"
eth2client "github.com/attestantio/go-eth2-client"
"github.com/attestantio/go-eth2-client/spec/phase0"
"github.com/pkg/errors"
"github.com/spf13/viper"
"github.com/wealdtech/ethdo/services/chaintime"
@@ -34,22 +35,21 @@ type command struct {
allowInsecureConnections bool
// Input.
account string
pubKey string
index string
epoch int64
validator string
epochStr string
// Data access.
eth2Client eth2client.Service
chainTime chaintime.Service
// Output.
epoch phase0.Epoch
inCommittee bool
committeeIndex uint64
inclusions []int
}
func newCommand(ctx context.Context) (*command, error) {
func newCommand(_ context.Context) (*command, error) {
c := &command{
quiet: viper.GetBool("quiet"),
verbose: viper.GetBool("verbose"),
@@ -67,15 +67,13 @@ func newCommand(ctx context.Context) (*command, error) {
c.allowInsecureConnections = viper.GetBool("allow-insecure-connections")
// Validator.
c.account = viper.GetString("account")
c.pubKey = viper.GetString("pubkey")
c.index = viper.GetString("index")
if c.account == "" && c.pubKey == "" && c.index == "" {
return nil, errors.New("account, pubkey or index required")
c.validator = viper.GetString("validator")
if c.validator == "" {
return nil, errors.New("validator is required")
}
// Epoch.
c.epoch = viper.GetInt64("epoch")
c.epochStr = viper.GetString("epoch")
return c, nil
}

View File

@@ -43,14 +43,14 @@ func TestInput(t *testing.T) {
"timeout": "5s",
"connection": os.Getenv("ETHDO_TEST_CONNECTION"),
},
err: "account, pubkey or index required",
err: "validator is required",
},
{
name: "Good",
vars: map[string]interface{}{
"validators": "1",
"timeout": "5s",
"index": "1",
"validator": "1",
"connection": os.Getenv("ETHDO_TEST_CONNECTION"),
},
},

View File

@@ -19,7 +19,7 @@ import (
"strings"
)
func (c *command) output(ctx context.Context) (string, error) {
func (c *command) output(_ context.Context) (string, error) {
if c.quiet {
return "", nil
}

View File

@@ -20,7 +20,6 @@ import (
eth2client "github.com/attestantio/go-eth2-client"
"github.com/attestantio/go-eth2-client/spec"
"github.com/attestantio/go-eth2-client/spec/altair"
"github.com/attestantio/go-eth2-client/spec/phase0"
"github.com/pkg/errors"
standardchaintime "github.com/wealdtech/ethdo/services/chaintime/standard"
"github.com/wealdtech/ethdo/util"
@@ -32,14 +31,17 @@ func (c *command) process(ctx context.Context) error {
return err
}
firstSlot, lastSlot := c.calculateSlots(ctx)
validatorIndex, err := util.ValidatorIndex(ctx, c.eth2Client, c.account, c.pubKey, c.index)
validator, err := util.ParseValidator(ctx, c.eth2Client.(eth2client.ValidatorsProvider), c.validator, "head")
if err != nil {
return err
}
syncCommittee, err := c.eth2Client.(eth2client.SyncCommitteesProvider).SyncCommitteeAtEpoch(ctx, "head", phase0.Epoch(c.epoch))
c.epoch, err = util.ParseEpoch(ctx, c.chainTime, c.epochStr)
if err != nil {
return err
}
syncCommittee, err := c.eth2Client.(eth2client.SyncCommitteesProvider).SyncCommitteeAtEpoch(ctx, "head", c.epoch)
if err != nil {
return errors.Wrap(err, "failed to obtain sync committee information")
}
@@ -49,7 +51,7 @@ func (c *command) process(ctx context.Context) error {
}
for i := range syncCommittee.Validators {
if syncCommittee.Validators[i] == validatorIndex {
if syncCommittee.Validators[i] == validator.Index {
c.inCommittee = true
c.committeeIndex = uint64(i)
break
@@ -57,6 +59,8 @@ func (c *command) process(ctx context.Context) error {
}
if c.inCommittee {
firstSlot := c.chainTime.FirstSlotOfEpoch(c.epoch)
lastSlot := c.chainTime.LastSlotOfEpoch(c.epoch)
// This validator is in the sync committee. Check blocks to see where it has been included.
c.inclusions = make([]int, 0)
if lastSlot > c.chainTime.CurrentSlot() {
@@ -107,7 +111,12 @@ func (c *command) setup(ctx context.Context) error {
var err error
// Connect to the client.
c.eth2Client, err = util.ConnectToBeaconNode(ctx, c.connection, c.timeout, c.allowInsecureConnections)
c.eth2Client, err = util.ConnectToBeaconNode(ctx, &util.ConnectOpts{
Address: c.connection,
Timeout: c.timeout,
AllowInsecure: c.allowInsecureConnections,
LogFallback: !c.quiet,
})
if err != nil {
return err
}
@@ -122,15 +131,3 @@ func (c *command) setup(ctx context.Context) error {
return nil
}
func (c *command) calculateSlots(ctx context.Context) (phase0.Slot, phase0.Slot) {
var firstSlot phase0.Slot
var lastSlot phase0.Slot
if c.epoch == -1 {
c.epoch = int64(c.chainTime.CurrentEpoch()) - 1
}
firstSlot = c.chainTime.FirstSlotOfEpoch(phase0.Epoch(c.epoch))
lastSlot = c.chainTime.FirstSlotOfEpoch(phase0.Epoch(c.epoch) + 1)
return firstSlot, lastSlot
}

View File

@@ -32,28 +32,20 @@ func TestProcess(t *testing.T) {
vars map[string]interface{}
err string
}{
{
name: "MissingConnection",
vars: map[string]interface{}{
"timeout": "5s",
"index": "1",
},
err: "failed to connect to any beacon node",
},
{
name: "InvalidConnection",
vars: map[string]interface{}{
"timeout": "5s",
"index": "1",
"validator": "1",
"connection": "invalid",
},
err: "failed to connect to beacon node: failed to confirm node connection: failed to fetch genesis: failed to request genesis: failed to call GET endpoint: Get \"http://invalid/eth/v1/beacon/genesis\": dial tcp: lookup invalid: no such host",
err: "failed to connect to beacon node: failed to confirm node connection: failed to fetch genesis: failed to request genesis: failed to call GET endpoint: Get \"http://invalid/eth/v1/beacon/genesis\": dial tcp: lookup invalid on 127.0.0.53:53: no such host",
},
{
name: "Good",
vars: map[string]interface{}{
"timeout": "5s",
"index": "1",
"validator": "1",
"epoch": "-1",
"connection": os.Getenv("ETHDO_TEST_CONNECTION"),
},

View File

@@ -34,7 +34,7 @@ type dataIn struct {
// Operation.
eth2Client eth2client.Service
chainTime chaintime.Service
epoch int64
epoch string
period string
}
@@ -51,7 +51,12 @@ func input(ctx context.Context) (*dataIn, error) {
// Ethereum 2 client.
var err error
data.eth2Client, err = util.ConnectToBeaconNode(ctx, viper.GetString("connection"), viper.GetDuration("timeout"), viper.GetBool("allow-insecure-connections"))
data.eth2Client, err = util.ConnectToBeaconNode(ctx, &util.ConnectOpts{
Address: viper.GetString("connection"),
Timeout: viper.GetDuration("timeout"),
AllowInsecure: viper.GetBool("allow-insecure-connections"),
LogFallback: !data.quiet,
})
if err != nil {
return nil, err
}
@@ -66,7 +71,7 @@ func input(ctx context.Context) (*dataIn, error) {
}
// Epoch
data.epoch = viper.GetInt64("epoch")
data.epoch = viper.GetString("epoch")
data.period = viper.GetString("period")
return data, nil

View File

@@ -60,13 +60,6 @@ func TestInput(t *testing.T) {
vars: map[string]interface{}{},
err: "timeout is required",
},
{
name: "ConnectionMissing",
vars: map[string]interface{}{
"timeout": "5s",
},
err: "failed to connect to any beacon node",
},
{
name: "ConnectionInvalid",
vars: map[string]interface{}{

View File

@@ -31,7 +31,7 @@ type dataOut struct {
validators []phase0.ValidatorIndex
}
func output(ctx context.Context, data *dataOut) (string, error) {
func output(_ context.Context, data *dataOut) (string, error) {
if data == nil {
return "", errors.New("no data")
}

View File

@@ -21,6 +21,7 @@ import (
eth2client "github.com/attestantio/go-eth2-client"
"github.com/attestantio/go-eth2-client/spec/phase0"
"github.com/pkg/errors"
"github.com/wealdtech/ethdo/util"
)
func process(ctx context.Context, data *dataIn) (*dataOut, error) {
@@ -54,8 +55,9 @@ func process(ctx context.Context, data *dataIn) (*dataOut, error) {
func calculateEpoch(ctx context.Context, data *dataIn) (phase0.Epoch, error) {
var epoch phase0.Epoch
if data.epoch != -1 {
epoch = phase0.Epoch(data.epoch)
var err error
if data.epoch != "" {
epoch, err = util.ParseEpoch(ctx, data.chainTime, data.epoch)
} else {
switch strings.ToLower(data.period) {
case "", "current":
@@ -68,6 +70,9 @@ func calculateEpoch(ctx context.Context, data *dataIn) (phase0.Epoch, error) {
return 0, fmt.Errorf("period %s not known", data.period)
}
}
if err != nil {
return 0, err
}
if data.debug {
fmt.Printf("epoch is %d\n", epoch)

View File

@@ -55,7 +55,7 @@ func TestProcess(t *testing.T) {
dataIn: &dataIn{
eth2Client: eth2Client,
chainTime: chainTime,
epoch: -1,
epoch: "-1",
},
},
}

View File

@@ -49,19 +49,15 @@ epoch can be a specific epoch; If not supplied all slots for the current sync co
func init() {
synccommitteeCmd.AddCommand(synccommitteeInclusionCmd)
synccommitteeFlags(synccommitteeInclusionCmd)
synccommitteeInclusionCmd.Flags().Int64("epoch", -1, "the epoch for which to fetch sync committee inclusion")
synccommitteeInclusionCmd.Flags().String("pubkey", "", "validator public key for sync committee")
synccommitteeInclusionCmd.Flags().String("index", "", "validator index for sync committee")
synccommitteeInclusionCmd.Flags().String("epoch", "", "the epoch for which to fetch sync committee inclusion")
synccommitteeInclusionCmd.Flags().String("validator", "", "the index, public key, or acount of the validator")
}
func synccommitteeInclusionBindings() {
if err := viper.BindPFlag("epoch", synccommitteeInclusionCmd.Flags().Lookup("epoch")); err != nil {
panic(err)
}
if err := viper.BindPFlag("pubkey", synccommitteeInclusionCmd.Flags().Lookup("pubkey")); err != nil {
panic(err)
}
if err := viper.BindPFlag("index", synccommitteeInclusionCmd.Flags().Lookup("index")); err != nil {
if err := viper.BindPFlag("validator", synccommitteeInclusionCmd.Flags().Lookup("validator")); err != nil {
panic(err)
}
}

View File

@@ -28,7 +28,7 @@ func init() {
RootCmd.AddCommand(validatorCmd)
}
func validatorFlags(cmd *cobra.Command) {
func validatorFlags(_ *cobra.Command) {
}
func validatorBindings() {

View File

@@ -44,7 +44,7 @@ type command struct {
validatorInfo *apiv1.Validator
}
func newCommand(ctx context.Context) (*command, error) {
func newCommand(_ context.Context) (*command, error) {
c := &command{
quiet: viper.GetBool("quiet"),
verbose: viper.GetBool("verbose"),

View File

@@ -43,24 +43,14 @@ func TestInput(t *testing.T) {
"timeout": "5s",
"connection": os.Getenv("ETHDO_TEST_CONNECTION"),
},
err: "one of account, index or pubkey required",
},
{
name: "MultipleValidatorInfo",
vars: map[string]interface{}{
"timeout": "5s",
"connection": os.Getenv("ETHDO_TEST_CONNECTION"),
"index": "1",
"pubkey": "0x000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000",
},
err: "only one of account, index and pubkey allowed",
err: "validator is required",
},
{
name: "Good",
vars: map[string]interface{}{
"timeout": "5s",
"connection": os.Getenv("ETHDO_TEST_CONNECTION"),
"index": "1",
"validator": "1",
},
},
}

View File

@@ -21,7 +21,7 @@ import (
ethutil "github.com/wealdtech/go-eth2-util"
)
func (c *command) output(ctx context.Context) (string, error) {
func (c *command) output(_ context.Context) (string, error) {
if c.quiet {
return "", nil
}

View File

@@ -48,7 +48,12 @@ func (c *command) setup(ctx context.Context) error {
var err error
// Connect to the consensus node.
c.consensusClient, err = util.ConnectToBeaconNode(ctx, c.connection, c.timeout, c.allowInsecureConnections)
c.consensusClient, err = util.ConnectToBeaconNode(ctx, &util.ConnectOpts{
Address: c.connection,
Timeout: c.timeout,
AllowInsecure: c.allowInsecureConnections,
LogFallback: !c.quiet,
})
if err != nil {
return errors.Wrap(err, "failed to connect to consensus node")
}
@@ -57,7 +62,7 @@ func (c *command) setup(ctx context.Context) error {
var isProvider bool
c.validatorsProvider, isProvider = c.consensusClient.(eth2client.ValidatorsProvider)
if !isProvider {
return errors.New("consensu node does not provide validator information")
return errors.New("consensus node does not provide validator information")
}
return nil

View File

@@ -19,6 +19,7 @@ import (
"fmt"
"os"
"github.com/pkg/errors"
"github.com/wealdtech/ethdo/beacon"
)
@@ -37,11 +38,7 @@ func (c *command) obtainChainInfo(ctx context.Context) error {
return fmt.Errorf("failed to obtain offline preparation file: %w", err)
}
if err := c.obtainChainInfoFromNode(ctx); err != nil {
return err
}
return nil
return c.obtainChainInfoFromNode(ctx)
}
// obtainChainInfoFromFile obtains chain information from a pre-generated file.
@@ -95,10 +92,10 @@ func (c *command) obtainChainInfoFromNode(ctx context.Context) error {
func (c *command) writeChainInfoToFile(_ context.Context) error {
data, err := json.Marshal(c.chainInfo)
if err != nil {
return err
return errors.Wrap(err, "failed to generate chain info JSON")
}
if err := os.WriteFile(offlinePreparationFilename, data, 0o600); err != nil {
return err
return errors.Wrap(err, "failed write chain info JSON")
}
return nil

View File

@@ -37,30 +37,12 @@ func TestInput(t *testing.T) {
vars: map[string]interface{}{},
err: "timeout is required",
},
{
name: "NoValidatorInfo",
vars: map[string]interface{}{
"timeout": "5s",
"connection": os.Getenv("ETHDO_TEST_CONNECTION"),
},
err: "one of account, index or pubkey required",
},
{
name: "MultipleValidatorInfo",
vars: map[string]interface{}{
"timeout": "5s",
"connection": os.Getenv("ETHDO_TEST_CONNECTION"),
"index": "1",
"pubkey": "0x000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000",
},
err: "only one of account, index and pubkey allowed",
},
{
name: "Good",
vars: map[string]interface{}{
"timeout": "5s",
"connection": os.Getenv("ETHDO_TEST_CONNECTION"),
"index": "1",
"validator": "1",
},
},
}

View File

@@ -42,14 +42,14 @@ import (
// minTimeout is the minimum timeout for this command.
// It needs to be set here as we want timeouts to be low in general, but this can be pulling
// a lot of data for an unsophisticated audience so it's easier to set a higher timeout..
var minTimeout = 2 * time.Minute
// defaultBeaconNode is used if no other connection is supplied.
var defaultBeaconNode = "http://mainnet-consensus.attestant.io/"
var minTimeout = 5 * time.Minute
// validatorPath is the regular expression that matches a validator path.
var validatorPath = regexp.MustCompile("^m/12381/3600/[0-9]+/0/0$")
// numeric is the regular expression that matches a number.
var numeric = regexp.MustCompile(`^[0-9]+$`)
var (
offlinePreparationFilename = "offline-preparation.json"
changeOperationsFilename = "change-operations.json"
@@ -294,11 +294,7 @@ func (c *command) generateOperationsFromAccountAndWithdrawalAccount(ctx context.
return errors.Wrap(err, "failed to obtain validator info")
}
if err := c.generateOperationFromAccount(ctx, validatorInfo, withdrawalAccount); err != nil {
return err
}
return nil
return c.generateOperationFromAccount(ctx, validatorInfo, withdrawalAccount)
}
func (c *command) generateOperationsFromAccountAndPrivateKey(ctx context.Context) error {
@@ -321,15 +317,11 @@ func (c *command) generateOperationsFromAccountAndPrivateKey(ctx context.Context
return errors.Wrap(err, "failed to obtain validator info")
}
if err := c.generateOperationFromAccount(ctx, validatorInfo, withdrawalAccount); err != nil {
return err
}
return nil
return c.generateOperationFromAccount(ctx, validatorInfo, withdrawalAccount)
}
func (c *command) generateOperationsFromValidatorAndPrivateKey(ctx context.Context) error {
validatorInfo, err := c.chainInfo.FetchValidatorInfo(ctx, c.validator)
validatorInfo, err := c.obtainValidatorInfoFromValidatorSpecifier(ctx)
if err != nil {
return err
}
@@ -339,11 +331,29 @@ func (c *command) generateOperationsFromValidatorAndPrivateKey(ctx context.Conte
return err
}
if err := c.generateOperationFromAccount(ctx, validatorInfo, withdrawalAccount); err != nil {
return err
return c.generateOperationFromAccount(ctx, validatorInfo, withdrawalAccount)
}
func (c *command) obtainValidatorInfoFromValidatorSpecifier(ctx context.Context) (*beacon.ValidatorInfo, error) {
if numeric.MatchString(c.validator) {
// The validator specifier looks like an on-chain index. Fetch directly from the
// chain information.
return c.chainInfo.FetchValidatorInfo(ctx, c.validator)
}
return nil
// The validator specifier Looks like some sort of account specifier. Fetch the account first,
// and then the validator information from its public key.
validatorAccount, err := util.ParseAccount(ctx, c.validator, nil, false)
if err != nil {
return nil, err
}
validatorPubkey, err := util.BestPublicKey(validatorAccount)
if err != nil {
return nil, err
}
return c.chainInfo.FetchValidatorInfo(ctx, fmt.Sprintf("%#x", validatorPubkey.Marshal()))
}
func (c *command) generateOperationsFromPrivateKey(ctx context.Context) error {
@@ -624,7 +634,7 @@ func (c *command) validateOperations(ctx context.Context) (bool, string) {
return true, ""
}
func (c *command) verifyOperation(ctx context.Context, op *capella.SignedBLSToExecutionChange) error {
func (c *command) verifyOperation(_ context.Context, op *capella.SignedBLSToExecutionChange) error {
root, err := op.Message.HashTreeRoot()
if err != nil {
return errors.Wrap(err, "failed to generate message root")
@@ -710,24 +720,14 @@ func (c *command) setup(ctx context.Context) error {
// Connect to the consensus node.
var err error
c.consensusClient, err = util.ConnectToBeaconNode(ctx, c.connection, c.timeout, c.allowInsecureConnections)
c.consensusClient, err = util.ConnectToBeaconNode(ctx, &util.ConnectOpts{
Address: c.connection,
Timeout: c.timeout,
AllowInsecure: c.allowInsecureConnections,
LogFallback: !c.quiet,
})
if err != nil {
if c.connection != "" {
// The user provided a connection, so don't second-guess them by using a different node.
return err
}
// The user did not provide a connection, so attempt to use the default node.
if c.debug {
fmt.Fprintf(os.Stderr, "No node connection, attempting to use %s\n", defaultBeaconNode)
}
c.consensusClient, err = util.ConnectToBeaconNode(ctx, defaultBeaconNode, c.timeout, c.allowInsecureConnections)
if err != nil {
return err
}
if !c.quiet {
fmt.Fprintf(os.Stderr, "No connection supplied; using mainnet public access endpoint\n")
}
return err
}
// Set up chaintime.
@@ -769,7 +769,7 @@ func (c *command) generateDomain(ctx context.Context) error {
return nil
}
func (c *command) obtainGenesisValidatorsRoot(ctx context.Context) (phase0.Root, error) {
func (c *command) obtainGenesisValidatorsRoot(_ context.Context) (phase0.Root, error) {
genesisValidatorsRoot := phase0.Root{}
if c.genesisValidatorsRoot != "" {
@@ -797,7 +797,7 @@ func (c *command) obtainGenesisValidatorsRoot(ctx context.Context) (phase0.Root,
return genesisValidatorsRoot, nil
}
func (c *command) obtainForkVersion(ctx context.Context) (phase0.Version, error) {
func (c *command) obtainForkVersion(_ context.Context) (phase0.Version, error) {
forkVersion := phase0.Version{}
if c.forkVersion != "" {

View File

@@ -332,7 +332,8 @@ func TestGenerateOperationFromMnemonicAndPath(t *testing.T) {
},
{
name: "WithdrawalAddressNo0xPrefix",
command: &command{mnemonic: "abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon art",
command: &command{
mnemonic: "abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon art",
path: "m/12381/3600/0/0/0",
chainInfo: chainInfo,
signedOperations: make([]*capella.SignedBLSToExecutionChange, 0),
@@ -342,7 +343,8 @@ func TestGenerateOperationFromMnemonicAndPath(t *testing.T) {
},
{
name: "WithdrawalAddressInvalidLength",
command: &command{mnemonic: "abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon art",
command: &command{
mnemonic: "abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon art",
path: "m/12381/3600/0/0/0",
chainInfo: chainInfo,
signedOperations: make([]*capella.SignedBLSToExecutionChange, 0),
@@ -352,7 +354,8 @@ func TestGenerateOperationFromMnemonicAndPath(t *testing.T) {
},
{
name: "WithdrawalAddressMissing",
command: &command{mnemonic: "abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon art",
command: &command{
mnemonic: "abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon art",
path: "m/12381/3600/0/0/0",
chainInfo: chainInfo,
signedOperations: make([]*capella.SignedBLSToExecutionChange, 0),
@@ -777,3 +780,94 @@ func TestGenerateOperationFromSeedAndPath(t *testing.T) {
})
}
}
func TestObtainValidatorInfoFromValidatorSpecifier(t *testing.T) {
ctx := context.Background()
require.NoError(t, e2types.InitBLS())
chainInfo := &beacon.ChainInfo{
Version: 1,
Validators: []*beacon.ValidatorInfo{
{
Index: 0,
Pubkey: phase0.BLSPubKey{0xb3, 0x84, 0xf7, 0x67, 0xd9, 0x64, 0xe1, 0x00, 0xc8, 0xa9, 0xb2, 0x10, 0x18, 0xd0, 0x8c, 0x25, 0xff, 0xeb, 0xae, 0x26, 0x8b, 0x3a, 0xb6, 0xd6, 0x10, 0x35, 0x38, 0x97, 0x54, 0x19, 0x71, 0x72, 0x6d, 0xbf, 0xc3, 0xc7, 0x46, 0x38, 0x84, 0xc6, 0x8a, 0x53, 0x15, 0x15, 0xaa, 0xb9, 0x4c, 0x87},
WithdrawalCredentials: []byte{0x00, 0x8b, 0xa1, 0xcc, 0x4b, 0x09, 0x1b, 0x91, 0xc1, 0x20, 0x2b, 0xba, 0x3f, 0x50, 0x80, 0x75, 0xd6, 0xff, 0x56, 0x5c, 0x77, 0xe5, 0x59, 0xf0, 0x80, 0x3c, 0x07, 0x92, 0xe0, 0x30, 0x2b, 0xf1},
},
{
Index: 1,
Pubkey: phase0.BLSPubKey{0xb3, 0xd8, 0x9e, 0x2f, 0x29, 0xc7, 0x12, 0xc6, 0xa9, 0xf8, 0xe5, 0xa2, 0x69, 0xb9, 0x76, 0x17, 0xc4, 0xa9, 0x4d, 0xd6, 0xf6, 0x66, 0x2a, 0xb3, 0xb0, 0x7c, 0xe9, 0xe5, 0x43, 0x45, 0x73, 0xf1, 0x5b, 0x5c, 0x98, 0x8c, 0xd1, 0x4b, 0xbd, 0x58, 0x04, 0xf7, 0x71, 0x56, 0xa8, 0xaf, 0x1c, 0xfa},
WithdrawalCredentials: []byte{0x00, 0x78, 0x6c, 0xb0, 0x2e, 0xd2, 0x8e, 0x5f, 0xbb, 0x1f, 0x7f, 0x9e, 0x93, 0x1a, 0x2b, 0x72, 0x69, 0x29, 0x06, 0xe6, 0xb1, 0x2c, 0xe4, 0x64, 0x39, 0x75, 0xe3, 0x2b, 0x51, 0x76, 0x91, 0xf2},
},
{
Index: 2,
Pubkey: phase0.BLSPubKey{0xaf, 0x9c, 0xe4, 0x4f, 0x50, 0x14, 0x8d, 0xb4, 0x12, 0x19, 0x4a, 0xf0, 0xba, 0xf0, 0xba, 0xb3, 0x6b, 0xd5, 0xc3, 0xe0, 0xc4, 0x93, 0x89, 0x11, 0xa4, 0xe5, 0x02, 0xe3, 0x98, 0xb5, 0x9e, 0x5c, 0xca, 0x7c, 0x78, 0xe3, 0xfe, 0x03, 0x41, 0x95, 0x47, 0x88, 0x79, 0xee, 0xb2, 0x3d, 0xb0, 0xa6},
WithdrawalCredentials: []byte{0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x0f, 0x00, 0x00, 0x00, 0x00, 0x93, 0x1a, 0x2b, 0x72, 0x69, 0x29, 0x06, 0xe6, 0xb1, 0x2c, 0xe4, 0x64, 0x39, 0x75, 0xe3, 0x2b, 0x51, 0x76, 0x91, 0xf2},
},
{
Index: 3,
Pubkey: phase0.BLSPubKey{0x86, 0xd3, 0x30, 0xaf, 0x51, 0xfa, 0x59, 0x3f, 0xa9, 0xf9, 0x3e, 0xdb, 0x9d, 0x16, 0x64, 0x01, 0x86, 0xbe, 0x2e, 0x93, 0xea, 0x94, 0xd2, 0x59, 0x78, 0x1e, 0x1e, 0xb3, 0x4d, 0xeb, 0x84, 0x4c, 0x39, 0x68, 0xd7, 0x5e, 0xa9, 0x1d, 0x19, 0xf1, 0x59, 0xdb, 0xd0, 0x52, 0x3c, 0x6c, 0x5b, 0xa5},
WithdrawalCredentials: []byte{0x00, 0x81, 0x68, 0x45, 0x6b, 0x6d, 0x9a, 0x32, 0x83, 0x93, 0x1f, 0xea, 0x52, 0x10, 0xda, 0x12, 0x2d, 0x1e, 0x65, 0xe8, 0xed, 0x50, 0xb8, 0xe8, 0xf5, 0x91, 0x11, 0x83, 0xb0, 0x2f, 0xd1, 0x25},
},
},
GenesisValidatorsRoot: phase0.Root{},
Epoch: 1,
CurrentForkVersion: phase0.Version{},
}
validators := make(map[string]*beacon.ValidatorInfo, len(chainInfo.Validators))
for i := range chainInfo.Validators {
validators[fmt.Sprintf("%#x", chainInfo.Validators[i].Pubkey)] = chainInfo.Validators[i]
}
tests := []struct {
name string
command *command
pubkey phase0.BLSPubKey
err string
}{
{
name: "KnownPubkey",
command: &command{
chainInfo: chainInfo,
validator: "0xb3d89e2f29c712c6a9f8e5a269b97617c4a94dd6f6662ab3b07ce9e5434573f15b5c988cd14bbd5804f77156a8af1cfa",
},
pubkey: phase0.BLSPubKey{0xb3, 0xd8, 0x9e, 0x2f, 0x29, 0xc7, 0x12, 0xc6, 0xa9, 0xf8, 0xe5, 0xa2, 0x69, 0xb9, 0x76, 0x17, 0xc4, 0xa9, 0x4d, 0xd6, 0xf6, 0x66, 0x2a, 0xb3, 0xb0, 0x7c, 0xe9, 0xe5, 0x43, 0x45, 0x73, 0xf1, 0x5b, 0x5c, 0x98, 0x8c, 0xd1, 0x4b, 0xbd, 0x58, 0x04, 0xf7, 0x71, 0x56, 0xa8, 0xaf, 0x1c, 0xfa},
},
{
name: "KnownIndex",
command: &command{
chainInfo: chainInfo,
validator: "1",
},
pubkey: phase0.BLSPubKey{0xb3, 0xd8, 0x9e, 0x2f, 0x29, 0xc7, 0x12, 0xc6, 0xa9, 0xf8, 0xe5, 0xa2, 0x69, 0xb9, 0x76, 0x17, 0xc4, 0xa9, 0x4d, 0xd6, 0xf6, 0x66, 0x2a, 0xb3, 0xb0, 0x7c, 0xe9, 0xe5, 0x43, 0x45, 0x73, 0xf1, 0x5b, 0x5c, 0x98, 0x8c, 0xd1, 0x4b, 0xbd, 0x58, 0x04, 0xf7, 0x71, 0x56, 0xa8, 0xaf, 0x1c, 0xfa},
},
{
name: "UnknownPubkey",
command: &command{
chainInfo: chainInfo,
validator: "0x80773a007f9e496a196b8f28fae04ddaa72fa65c0f8a98145a1e192082c3edcf7cee891ccf1d6b6fee0abe0045b9f61b",
},
err: "unknown validator",
},
{
name: "UnknownIndex",
command: &command{
chainInfo: chainInfo,
validator: "999",
},
err: "unknown validator",
},
}
for _, test := range tests {
t.Run(test.name, func(t *testing.T) {
info, err := test.command.obtainValidatorInfoFromValidatorSpecifier(ctx)
if test.err != "" {
require.EqualError(t, err, test.err)
} else {
require.NoError(t, err)
require.Equal(t, test.pubkey, info.Pubkey)
}
})
}
}

View File

@@ -121,7 +121,7 @@ func input() (*dataIn, error) {
return data, nil
}
func inputForkVersion(ctx context.Context) (*spec.Version, error) {
func inputForkVersion(_ context.Context) (*spec.Version, error) {
// Default to mainnet.
forkVersion := &spec.Version{0x00, 0x00, 0x00, 0x00}

View File

@@ -36,7 +36,7 @@ type dataIn struct {
index string
}
func input(ctx context.Context) (*dataIn, error) {
func input(_ context.Context) (*dataIn, error) {
data := &dataIn{}
if viper.GetDuration("timeout") == 0 {

View File

@@ -35,7 +35,7 @@ type dataOut struct {
nextEpochAttesterDuty *api.AttesterDuty
}
func output(ctx context.Context, data *dataOut) (string, error) {
func output(_ context.Context, data *dataOut) (string, error) {
if data == nil {
return "", errors.New("no data")
}

View File

@@ -30,7 +30,12 @@ func process(ctx context.Context, data *dataIn) (*dataOut, error) {
}
// Ethereum 2 client.
eth2Client, err := util.ConnectToBeaconNode(ctx, data.eth2Client, data.timeout, data.allowInsecure)
eth2Client, err := util.ConnectToBeaconNode(ctx, &util.ConnectOpts{
Address: data.eth2Client,
Timeout: data.timeout,
AllowInsecure: data.allowInsecure,
LogFallback: !data.quiet,
})
if err != nil {
return nil, err
}

View File

@@ -19,6 +19,7 @@ import (
"fmt"
"os"
"github.com/pkg/errors"
"github.com/wealdtech/ethdo/beacon"
)
@@ -37,11 +38,7 @@ func (c *command) obtainChainInfo(ctx context.Context) error {
return fmt.Errorf("failed to obtain offline preparation file: %w", err)
}
if err := c.obtainChainInfoFromNode(ctx); err != nil {
return err
}
return nil
return c.obtainChainInfoFromNode(ctx)
}
// obtainChainInfoFromFile obtains chain information from a pre-generated file.
@@ -95,10 +92,10 @@ func (c *command) obtainChainInfoFromNode(ctx context.Context) error {
func (c *command) writeChainInfoToFile(_ context.Context) error {
data, err := json.Marshal(c.chainInfo)
if err != nil {
return err
return errors.Wrap(err, "failed to generate chain info JSON")
}
if err := os.WriteFile(offlinePreparationFilename, data, 0o600); err != nil {
return err
return errors.Wrap(err, "failed write chain info JSON")
}
return nil

View File

@@ -41,7 +41,7 @@ import (
// minTimeout is the minimum timeout for this command.
// It needs to be set here as we want timeouts to be low in general, but this can be pulling
// a lot of data for an unsophisticated audience so it's easier to set a higher timeout..
var minTimeout = 2 * time.Minute
var minTimeout = 5 * time.Minute
// validatorPath is the regular expression that matches a validator path.
var validatorPath = regexp.MustCompile("^m/12381/3600/[0-9]+/0/0$")
@@ -131,19 +131,13 @@ func (c *command) generateOperationFromMnemonicAndPath(ctx context.Context) erro
return err
}
// Turn the validators in to a map for easy lookup.
validators := make(map[string]*beacon.ValidatorInfo, 0)
for _, validator := range c.chainInfo.Validators {
validators[fmt.Sprintf("%#x", validator.Pubkey)] = validator
}
validatorKeyPath := c.path
match := validatorPath.Match([]byte(c.path))
if !match {
return fmt.Errorf("path %s does not match EIP-2334 format for a validator", c.path)
}
if err := c.generateOperationFromSeedAndPath(ctx, validators, seed, validatorKeyPath); err != nil {
if err := c.generateOperationFromSeedAndPath(ctx, seed, validatorKeyPath); err != nil {
return errors.Wrap(err, "failed to generate operation from seed and path")
}
@@ -199,24 +193,16 @@ func (c *command) generateOperationFromPrivateKey(ctx context.Context) error {
return errors.Wrap(err, "failed to parse validator account")
}
if err = c.generateOperationFromAccount(ctx, validatorAccount); err != nil {
return err
}
return nil
return c.generateOperationFromAccount(ctx, validatorAccount)
}
func (c *command) generateOperationFromValidator(ctx context.Context) error {
validatorAccount, err := util.ParseAccount(ctx, c.validator, nil, true)
validatorAccount, err := util.ParseAccount(ctx, c.validator, c.passphrases, true)
if err != nil {
return errors.Wrap(err, "failed to parse validator account")
}
if err := c.generateOperationFromAccount(ctx, validatorAccount); err != nil {
return err
}
return nil
return c.generateOperationFromAccount(ctx, validatorAccount)
}
func (c *command) obtainOperationFromFileOrInput(ctx context.Context) error {
@@ -244,11 +230,7 @@ func (c *command) obtainOperationFromFile(ctx context.Context) error {
return errors.Wrap(err, "failed to parse exit operation file")
}
if err := c.verifySignedOperation(ctx, c.signedOperation); err != nil {
return err
}
return nil
return c.verifySignedOperation(ctx, c.signedOperation)
}
func (c *command) obtainOperationFromInput(ctx context.Context) error {
@@ -265,15 +247,10 @@ func (c *command) obtainOperationFromInput(ctx context.Context) error {
return errors.Wrap(err, "failed to parse exit operation input")
}
if err := c.verifySignedOperation(ctx, c.signedOperation); err != nil {
return err
}
return nil
return c.verifySignedOperation(ctx, c.signedOperation)
}
func (c *command) generateOperationFromSeedAndPath(ctx context.Context,
validators map[string]*beacon.ValidatorInfo,
seed []byte,
path string,
) error {
@@ -440,9 +417,14 @@ func (c *command) setup(ctx context.Context) error {
// Connect to the consensus node.
var err error
c.consensusClient, err = util.ConnectToBeaconNode(ctx, c.connection, c.timeout, c.allowInsecureConnections)
c.consensusClient, err = util.ConnectToBeaconNode(ctx, &util.ConnectOpts{
Address: c.connection,
Timeout: c.timeout,
AllowInsecure: c.allowInsecureConnections,
LogFallback: !c.quiet,
})
if err != nil {
return errors.Wrap(err, "failed to connect to consensus node")
return err
}
// Set up chaintime.
@@ -484,7 +466,7 @@ func (c *command) generateDomain(ctx context.Context) error {
return nil
}
func (c *command) obtainGenesisValidatorsRoot(ctx context.Context) (phase0.Root, error) {
func (c *command) obtainGenesisValidatorsRoot(_ context.Context) (phase0.Root, error) {
genesisValidatorsRoot := phase0.Root{}
if c.genesisValidatorsRoot != "" {
@@ -512,7 +494,7 @@ func (c *command) obtainGenesisValidatorsRoot(ctx context.Context) (phase0.Root,
return genesisValidatorsRoot, nil
}
func (c *command) obtainForkVersion(ctx context.Context) (phase0.Version, error) {
func (c *command) obtainForkVersion(_ context.Context) (phase0.Version, error) {
forkVersion := phase0.Version{}
if c.forkVersion != "" {

View File

@@ -15,7 +15,6 @@ package validatorexit
import (
"context"
"fmt"
"testing"
"github.com/attestantio/go-eth2-client/spec/phase0"
@@ -227,10 +226,6 @@ func TestGenerateOperationFromSeedAndPath(t *testing.T) {
Epoch: 1,
CurrentForkVersion: phase0.Version{},
}
validators := make(map[string]*beacon.ValidatorInfo, len(chainInfo.Validators))
for i := range chainInfo.Validators {
validators[fmt.Sprintf("%#x", chainInfo.Validators[i].Pubkey)] = chainInfo.Validators[i]
}
tests := []struct {
name string
@@ -301,7 +296,7 @@ func TestGenerateOperationFromSeedAndPath(t *testing.T) {
for _, test := range tests {
t.Run(test.name, func(t *testing.T) {
err := test.command.generateOperationFromSeedAndPath(ctx, validators, test.seed, test.path)
err := test.command.generateOperationFromSeedAndPath(ctx, test.seed, test.path)
if test.err != "" {
require.EqualError(t, err, test.err)
} else {

View File

@@ -45,7 +45,7 @@ type command struct {
timeBetweenSyncCommittees time.Duration
}
func newCommand(ctx context.Context) (*command, error) {
func newCommand(_ context.Context) (*command, error) {
c := &command{
quiet: viper.GetBool("quiet"),
verbose: viper.GetBool("verbose"),

View File

@@ -20,7 +20,7 @@ import (
"github.com/hako/durafmt"
)
func (c *command) output(ctx context.Context) (string, error) {
func (c *command) output(_ context.Context) (string, error) {
if c.quiet {
return "", nil
}

View File

@@ -123,7 +123,12 @@ func (c *command) setup(ctx context.Context) error {
var err error
// Connect to the client.
c.eth2Client, err = util.ConnectToBeaconNode(ctx, c.connection, c.timeout, c.allowInsecureConnections)
c.eth2Client, err = util.ConnectToBeaconNode(ctx, &util.ConnectOpts{
Address: c.connection,
Timeout: c.timeout,
AllowInsecure: c.allowInsecureConnections,
LogFallback: !c.quiet,
})
if err != nil {
return errors.Wrap(err, "failed to connect to beacon node")
}

View File

@@ -32,7 +32,7 @@ type dataIn struct {
privKey string
}
func input(ctx context.Context) (*dataIn, error) {
func input(_ context.Context) (*dataIn, error) {
data := &dataIn{}
data.quiet = viper.GetBool("quiet")

View File

@@ -29,7 +29,7 @@ type dataOut struct {
path string
}
func output(ctx context.Context, data *dataOut) (string, int, error) {
func output(_ context.Context, data *dataOut) (string, int, error) {
if data == nil {
return "", 1, errors.New("no data")
}

Some files were not shown because too many files have changed in this diff Show More