prysm-pulse/validator/node/node_test.go
Manu NALEPA ef21d3adf8
Implement EIP-3076 minimal slashing protection, using a filesystem database (#13360)
* `EpochFromString`: Use already defined `Uint64FromString` function.

* `Test_uint64FromString` => `Test_FromString`

This test function tests more functions than `Uint64FromString`.

* Slashing protection history: Remove unreachable code.

The function `NewKVStore` creates, via `kv.UpdatePublicKeysBuckets`,
a new item in the `proposal-history-bucket-interchange`.

IMO there is no real reason to prefer `proposal` than `attestation`
as a prefix for this bucket, but this is the way it is done right now
and renaming the bucket will probably be backward incompatible.

An `attestedPublicKey` cannot exist without
the corresponding `proposedPublicKey`.

Thus, the `else` portion of code removed in this commit is not reachable.
We raise an error if we get there.

This is also probably the reason why the removed `else` portion was not
tested.

* `NewKVStore`: Switch items in `createBuckets`.

So the order corresponds to `schema.go`

* `slashableAttestationCheck`: Fix comments and logs.

* `ValidatorClient.db`: Use `iface.ValidatorDB`.

* BoltDB database: Implement `GraffitiFileHash`.

* Filesystem database: Creates `db.go`.

This file defines the following structs:
- `Store`
- `Graffiti`
- `Configuration`
- `ValidatorSlashingProtection`

This files implements the following public functions:
- `NewStore`
- `Close`
- `Backup`
- `DatabasePath`
- `ClearDB`
- `UpdatePublicKeysBuckets`

This files implements the following private functions:
- `slashingProtectionDirPath`
- `configurationFilePath`
- `configuration`
- `saveConfiguration`
- `validatorSlashingProtection`
- `saveValidatorSlashingProtection`
- `publicKeys`

* Filesystem database: Creates `genesis.go`.

This file defines the following public functions:
- `GenesisValidatorsRoot`
- `SaveGenesisValidatorsRoot`

* Filesystem database: Creates `graffiti.go`.

This file defines the following public functions:
- `SaveGraffitiOrderedIndex`
- `GraffitiOrderedIndex`

* Filesystem database: Creates `migration.go`.

This file defines the following public functions:
- `RunUpMigrations`
- `RunDownMigrations`

* Filesystem database: Creates proposer_settings.go.

This file defines the following public functions:
- `ProposerSettings`
- `ProposerSettingsExists`
- `SaveProposerSettings`

* Filesystem database: Creates `attester_protection.go`.

This file defines the following public functions:
- `EIPImportBlacklistedPublicKeys`
- `SaveEIPImportBlacklistedPublicKeys`
- `SigningRootAtTargetEpoch`
- `LowestSignedTargetEpoch`
- `LowestSignedSourceEpoch`
- `AttestedPublicKeys`
- `CheckSlashableAttestation`
- `SaveAttestationForPubKey`
- `SaveAttestationsForPubKey`
- `AttestationHistoryForPubKey`

* Filesystem database: Creates `proposer_protection.go`.

This file defines the following public functions:
- `HighestSignedProposal`
- `LowestSignedProposal`
- `ProposalHistoryForPubKey`
- `ProposalHistoryForSlot`
- `ProposedPublicKeys`

* Ensure that the filesystem store implements the `ValidatorDB` interface.

* `slashableAttestationCheck`: Check the database type.

* `slashableProposalCheck`: Check the database type.

* `slashableAttestationCheck`: Allow usage of minimal slashing protection.

* `slashableProposalCheck`: Allow usage of minimal slashing protection.

* `ImportStandardProtectionJSON`: Check the database type.

* `ImportStandardProtectionJSON`: Allow usage of min slashing protection.

* Implement `RecursiveDirFind`.

* Implement minimal<->complete DB conversion.

3 public functions are implemented:
- `IsCompleteDatabaseExisting`
- `IsMinimalDatabaseExisting`
- `ConvertDatabase`

* `setupDB`: Add `isSlashingProtectionMinimal` argument.

The feature addition is located in `validator/node/node_test.go`.
The rest of this commit consists in minimal slashing protection testing.

* `setupWithKey`: Add `isSlashingProtectionMinimal` argument.

The feature addition is located in `validator/client/propose_test.go`.

The rest of this commit consists in tests wrapping.

* `setup`: Add `isSlashingProtectionMinimal` argument.

The added feature is located in the `validator/client/propose_test.go`
file.

The rest of this commit consists in tests wrapping.

* `initializeFromCLI` and `initializeForWeb`: Factorize db init.

* Add `convert-complete-to-minimal` command.

* Creates `--enable-minimal-slashing-protection` flag.

* `importSlashingProtectionJSON`: Check database type.

* `exportSlashingProtectionJSON`: Check database type.

* `TestClearDB`: Test with minimal slashing protection.

* KeyManager: Test with minimal slashing protection.

* RPC: KeyManager: Test with minimal slashing protection.

* `convert-complete-to-minimal`: Change option names.

Options were:
- `--source` (for source data directory), and
- `--target` (for target data directory)

However, since this command deals with slashing protection, which has
source (epochs) and target (epochs), the initial option names may confuse
the user.

In this commit:
`--source` ==> `--source-data-dir`
`--target` ==> `--target-data-dir`

* Set `SlashableAttestationCheck` as an iface method.

And delete `CheckSlashableAttestation` from iface.

* Move helpers functions in a more general directory.

No functional change.

* Extract common structs out of `kv`.

==> `filesystem` does not depend anymore on `kv`.
==> `iface` does not depend anymore on `kv`.
==> `slashing-protection` does not depend anymore on `kv`.

* Move `ValidateMetadata` in `validator/helpers`.

* `ValidateMetadata`: Test with mock.

This way, we can:
- Avoid any circular import for tests.
- Implement once for all `iface.ValidatorDB` implementations
  the `ValidateMetadata`function.
- Have tests (and coverage) of `ValidateMetadata`in
  its own package.

The ideal solution would have been to implement `ValidateMetadata` as
a method with the `iface.ValidatorDB`receiver.
Unfortunately, golang does not allow that.

* `iface.ValidatorDB`: Implement ImportStandardProtectionJSON.

The whole purpose of this commit is to avoid the `switch validatorDB.(type)`
in `ImportStandardProtectionJSON`.

* `iface.ValidatorDB`: Implement `SlashableProposalCheck`.

* Remove now useless `slashableProposalCheck`.

* Delete useless `ImportStandardProtectionJSON`.

* `file.Exists`: Detect directories and return an error.

Before, `Exists` was only able to detect if a file exists.
Now, this function takes an extra `File` or `Directory` argument.
It detects either if a file or a directory exists.

Before, if an error was returned by `os.Stat`, the the file was
considered as non existing.
Now, it is treated as a real error.

* Replace `os.Stat` by `file.Exists`.

* Remove `Is{Complete,Minimal}DatabaseExisting`.

* `publicKeys`: Add log if unexpected file found.

* Move `{Source,Target}DataDirFlag`in `db.go`.

* `failedAttLocalProtectionErr`: `var`==> `const`

* `signingRoot`: `32`==> `fieldparams.RootLength`.

* `validatorClientData`==> `validator-client-data`.

To be consistent with `slashing-protection`.

* Add progress bars for `import` and `convert`.

* `parseBlocksForUniquePublicKeys`: Move in `db/kv`.

* helpers: Remove unused `initializeProgressBar` function.
2024-03-05 15:27:15 +00:00

344 lines
12 KiB
Go

package node
import (
"context"
"flag"
"fmt"
"os"
"path"
"path/filepath"
"testing"
"github.com/ethereum/go-ethereum/common/hexutil"
"github.com/prysmaticlabs/prysm/v5/cmd"
"github.com/prysmaticlabs/prysm/v5/cmd/validator/flags"
"github.com/prysmaticlabs/prysm/v5/encoding/bytesutil"
"github.com/prysmaticlabs/prysm/v5/io/file"
"github.com/prysmaticlabs/prysm/v5/testing/assert"
"github.com/prysmaticlabs/prysm/v5/testing/require"
"github.com/prysmaticlabs/prysm/v5/validator/accounts"
"github.com/prysmaticlabs/prysm/v5/validator/accounts/wallet"
"github.com/prysmaticlabs/prysm/v5/validator/db/kv"
"github.com/prysmaticlabs/prysm/v5/validator/keymanager"
remoteweb3signer "github.com/prysmaticlabs/prysm/v5/validator/keymanager/remote-web3signer"
logtest "github.com/sirupsen/logrus/hooks/test"
"github.com/urfave/cli/v2"
)
// Test that the sharding node can build with default flag values.
func TestNode_Builds(t *testing.T) {
app := cli.App{}
set := flag.NewFlagSet("test", 0)
set.String("datadir", t.TempDir()+"/datadir", "the node data directory")
dir := t.TempDir() + "/walletpath"
passwordDir := t.TempDir() + "/password"
require.NoError(t, os.MkdirAll(passwordDir, os.ModePerm))
passwordFile := filepath.Join(passwordDir, "password.txt")
walletPassword := "$$Passw0rdz2$$"
require.NoError(t, os.WriteFile(
passwordFile,
[]byte(walletPassword),
os.ModePerm,
))
set.String("wallet-dir", dir, "path to wallet")
set.String("wallet-password-file", passwordFile, "path to wallet password")
set.String("keymanager-kind", "imported", "keymanager kind")
set.String("verbosity", "debug", "log verbosity")
require.NoError(t, set.Set(flags.WalletPasswordFileFlag.Name, passwordFile))
ctx := cli.NewContext(&app, set, nil)
opts := []accounts.Option{
accounts.WithWalletDir(dir),
accounts.WithKeymanagerType(keymanager.Local),
accounts.WithWalletPassword(walletPassword),
accounts.WithSkipMnemonicConfirm(true),
}
acc, err := accounts.NewCLIManager(opts...)
require.NoError(t, err)
_, err = acc.WalletCreate(ctx.Context)
require.NoError(t, err)
valClient, err := NewValidatorClient(ctx)
require.NoError(t, err, "Failed to create ValidatorClient")
err = valClient.db.Close()
require.NoError(t, err)
}
func TestGetLegacyDatabaseLocation(t *testing.T) {
dataDir := t.TempDir()
dataFile := path.Join(dataDir, "dataFile")
nonExistingDataFile := path.Join(dataDir, "nonExistingDataFile")
_, err := os.Create(dataFile)
require.NoError(t, err, "Failed to create data file")
walletDir := t.TempDir()
derivedDir := path.Join(walletDir, "derived")
err = file.MkdirAll(derivedDir)
require.NoError(t, err, "Failed to create derived dir")
derivedDbFile := path.Join(derivedDir, kv.ProtectionDbFileName)
_, err = os.Create(derivedDbFile)
require.NoError(t, err, "Failed to create derived db file")
dbFile := path.Join(walletDir, kv.ProtectionDbFileName)
_, err = os.Create(dbFile)
require.NoError(t, err, "Failed to create db file")
nonExistingWalletDir := t.TempDir()
testCases := []struct {
name string
isInteropNumValidatorsSet bool
isWeb3SignerURLFlagSet bool
dataDir string
dataFile string
walletDir string
validatorClient *ValidatorClient
wallet *wallet.Wallet
expectedDataDir string
expectedDataFile string
}{
{
name: "interop num validators set",
isInteropNumValidatorsSet: true,
dataDir: dataDir,
dataFile: dataFile,
expectedDataDir: dataDir,
expectedDataFile: dataFile,
},
{
name: "dataDir differs from default",
dataDir: dataDir,
dataFile: dataFile,
expectedDataDir: dataDir,
expectedDataFile: dataFile,
},
{
name: "dataFile exists",
dataDir: cmd.DefaultDataDir(),
dataFile: dataFile,
expectedDataDir: cmd.DefaultDataDir(),
expectedDataFile: dataFile,
},
{
name: "wallet is nil",
dataDir: cmd.DefaultDataDir(),
dataFile: nonExistingDataFile,
expectedDataDir: cmd.DefaultDataDir(),
expectedDataFile: nonExistingDataFile,
},
{
name: "web3signer url is not set and legacy data file does not exist",
dataDir: cmd.DefaultDataDir(),
dataFile: nonExistingDataFile,
wallet: wallet.New(&wallet.Config{
WalletDir: nonExistingWalletDir,
KeymanagerKind: keymanager.Derived,
}),
expectedDataDir: cmd.DefaultDataDir(),
expectedDataFile: nonExistingDataFile,
},
{
name: "web3signer url is not set and legacy data file does exist",
dataDir: cmd.DefaultDataDir(),
dataFile: nonExistingDataFile,
wallet: wallet.New(&wallet.Config{
WalletDir: walletDir,
KeymanagerKind: keymanager.Derived,
}),
expectedDataDir: path.Join(walletDir, "derived"),
expectedDataFile: path.Join(walletDir, "derived", kv.ProtectionDbFileName),
},
{
name: "web3signer url is set and legacy data file does not exist",
isWeb3SignerURLFlagSet: true,
dataDir: cmd.DefaultDataDir(),
dataFile: nonExistingDataFile,
walletDir: nonExistingWalletDir,
wallet: wallet.New(&wallet.Config{
WalletDir: walletDir,
KeymanagerKind: keymanager.Derived,
}),
expectedDataDir: cmd.DefaultDataDir(),
expectedDataFile: nonExistingDataFile,
},
{
name: "web3signer url is set and legacy data file does exist",
isWeb3SignerURLFlagSet: true,
dataDir: cmd.DefaultDataDir(),
dataFile: nonExistingDataFile,
walletDir: walletDir,
wallet: wallet.New(&wallet.Config{
WalletDir: walletDir,
KeymanagerKind: keymanager.Derived,
}),
expectedDataDir: walletDir,
expectedDataFile: path.Join(walletDir, kv.ProtectionDbFileName),
},
}
for _, tt := range testCases {
t.Run(tt.name, func(t *testing.T) {
validatorClient := &ValidatorClient{wallet: tt.wallet}
actualDataDir, actualDataFile, err := validatorClient.getLegacyDatabaseLocation(
tt.isInteropNumValidatorsSet,
tt.isWeb3SignerURLFlagSet,
tt.dataDir,
tt.dataFile,
tt.walletDir,
)
require.NoError(t, err, "Failed to get legacy database location")
assert.Equal(t, tt.expectedDataDir, actualDataDir, "data dir should be equal")
assert.Equal(t, tt.expectedDataFile, actualDataFile, "data file should be equal")
})
}
}
// TestClearDB tests clearing the database
func TestClearDB(t *testing.T) {
for _, isMinimalDatabase := range []bool{false, true} {
t.Run(fmt.Sprintf("isMinimalDatabase=%v", isMinimalDatabase), func(t *testing.T) {
hook := logtest.NewGlobal()
tmp := filepath.Join(t.TempDir(), "datadirtest")
require.NoError(t, clearDB(context.Background(), tmp, true, isMinimalDatabase))
require.LogsContain(t, hook, "Removing database")
})
}
}
// TestWeb3SignerConfig tests the web3 signer config returns the correct values.
func TestWeb3SignerConfig(t *testing.T) {
pubkey1decoded, err := hexutil.Decode("0xa99a76ed7796f7be22d5b7e85deeb7c5677e88e511e0b337618f8c4eb61349b4bf2d153f649f7b53359fe8b94a38e44c")
require.NoError(t, err)
bytepubkey1 := bytesutil.ToBytes48(pubkey1decoded)
pubkey2decoded, err := hexutil.Decode("0xb89bebc699769726a318c8e9971bd3171297c61aea4a6578a7a4f94b547dcba5bac16a89108b6b6a1fe3695d1a874a0b")
require.NoError(t, err)
bytepubkey2 := bytesutil.ToBytes48(pubkey2decoded)
type args struct {
baseURL string
publicKeysOrURLs []string
}
tests := []struct {
name string
args *args
want *remoteweb3signer.SetupConfig
wantErrMsg string
}{
{
name: "happy path with public keys",
args: &args{
baseURL: "http://localhost:8545",
publicKeysOrURLs: []string{"0xa99a76ed7796f7be22d5b7e85deeb7c5677e88e511e0b337618f8c4eb61349b4bf2d153f649f7b53359fe8b94a38e44c," +
"0xb89bebc699769726a318c8e9971bd3171297c61aea4a6578a7a4f94b547dcba5bac16a89108b6b6a1fe3695d1a874a0b"},
},
want: &remoteweb3signer.SetupConfig{
BaseEndpoint: "http://localhost:8545",
GenesisValidatorsRoot: nil,
PublicKeysURL: "",
ProvidedPublicKeys: [][48]byte{
bytepubkey1,
bytepubkey2,
},
},
},
{
name: "happy path with external url",
args: &args{
baseURL: "http://localhost:8545",
publicKeysOrURLs: []string{"http://localhost:8545/api/v1/eth2/publicKeys"},
},
want: &remoteweb3signer.SetupConfig{
BaseEndpoint: "http://localhost:8545",
GenesisValidatorsRoot: nil,
PublicKeysURL: "http://localhost:8545/api/v1/eth2/publicKeys",
ProvidedPublicKeys: nil,
},
},
{
name: "Bad base URL",
args: &args{
baseURL: "0xa99a76ed7796f7be22d5b7e85deeb7c5677e88,",
publicKeysOrURLs: []string{"0xa99a76ed7796f7be22d5b7e85deeb7c5677e88e511e0b337618f8c4eb61349b4bf2d153f649f7b53359fe8b94a38e44c," +
"0xb89bebc699769726a318c8e9971bd3171297c61aea4a6578a7a4f94b547dcba5bac16a89108b6b6a1fe3695d1a874a0b"},
},
want: nil,
wantErrMsg: "web3signer url 0xa99a76ed7796f7be22d5b7e85deeb7c5677e88, is invalid: parse \"0xa99a76ed7796f7be22d5b7e85deeb7c5677e88,\": invalid URI for request",
},
{
name: "Bad publicKeys",
args: &args{
baseURL: "http://localhost:8545",
publicKeysOrURLs: []string{"0xa99a76ed7796f7be22c," +
"0xb89bebc699769726a318c8e9971bd3171297c61aea4a6578a7a4f94b547dcba5bac16a89108b6b6a1fe3695d1a874a0b"},
},
want: nil,
wantErrMsg: "could not decode public key for web3signer: 0xa99a76ed7796f7be22c: hex string of odd length",
},
{
name: "Bad publicKeysURL",
args: &args{
baseURL: "http://localhost:8545",
publicKeysOrURLs: []string{"localhost"},
},
want: nil,
wantErrMsg: "could not decode public key for web3signer: localhost: hex string without 0x prefix",
},
{
name: "Base URL missing scheme or host",
args: &args{
baseURL: "localhost:8545",
publicKeysOrURLs: []string{"localhost"},
},
want: nil,
wantErrMsg: "web3signer url must be in the format of http(s)://host:port url used: localhost:8545",
},
{
name: "Public Keys URL missing scheme or host",
args: &args{
baseURL: "http://localhost:8545",
publicKeysOrURLs: []string{"localhost:8545"},
},
want: nil,
wantErrMsg: "could not decode public key for web3signer: localhost:8545: hex string without 0x prefix",
},
{
name: "incorrect amount of flag calls used with url",
args: &args{
baseURL: "http://localhost:8545",
publicKeysOrURLs: []string{"0xa99a76ed7796f7be22d5b7e85deeb7c5677e88e511e0b337618f8c4eb61349b4bf2d153f649f7b53359fe8b94a38e44c," +
"0xb89bebc699769726a318c8e9971bd3171297c61aea4a6578a7a4f94b547dcba5bac16a89108b6b6a1fe3695d1a874a0b", "http://localhost:8545/api/v1/eth2/publicKeys"},
},
want: nil,
wantErrMsg: "could not decode public key for web3signer",
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
app := cli.App{}
set := flag.NewFlagSet(tt.name, 0)
set.String("validators-external-signer-url", tt.args.baseURL, "baseUrl")
c := &cli.StringSliceFlag{
Name: "validators-external-signer-public-keys",
}
err := c.Apply(set)
require.NoError(t, err)
require.NoError(t, set.Set(flags.Web3SignerURLFlag.Name, tt.args.baseURL))
for _, key := range tt.args.publicKeysOrURLs {
require.NoError(t, set.Set(flags.Web3SignerPublicValidatorKeysFlag.Name, key))
}
cliCtx := cli.NewContext(&app, set, nil)
got, err := Web3SignerConfig(cliCtx)
if tt.wantErrMsg != "" {
require.ErrorContains(t, tt.wantErrMsg, err)
return
}
require.DeepEqual(t, tt.want, got)
})
}
}