mirror of
https://gitlab.com/pulsechaincom/prysm-pulse.git
synced 2024-12-22 11:32:09 +00:00
ef21d3adf8
* `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.
211 lines
5.8 KiB
Go
211 lines
5.8 KiB
Go
package rpc
|
|
|
|
import (
|
|
"bufio"
|
|
"bytes"
|
|
"context"
|
|
"encoding/hex"
|
|
"fmt"
|
|
"io"
|
|
"net/url"
|
|
"os"
|
|
"path/filepath"
|
|
"strings"
|
|
|
|
"github.com/fsnotify/fsnotify"
|
|
"github.com/golang-jwt/jwt/v4"
|
|
"github.com/pkg/errors"
|
|
"github.com/prysmaticlabs/prysm/v5/crypto/rand"
|
|
"github.com/prysmaticlabs/prysm/v5/io/file"
|
|
)
|
|
|
|
const (
|
|
AuthTokenFileName = "auth-token"
|
|
)
|
|
|
|
// CreateAuthToken generates a new jwt key, token and writes them
|
|
// to a file in the specified directory. Also, it logs out a prepared URL
|
|
// for the user to navigate to and authenticate with the Prysm web interface.
|
|
func CreateAuthToken(walletDirPath, validatorWebAddr string) error {
|
|
jwtKey, err := createRandomJWTSecret()
|
|
if err != nil {
|
|
return err
|
|
}
|
|
token, err := createTokenString(jwtKey)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
authTokenPath := filepath.Join(walletDirPath, AuthTokenFileName)
|
|
log.Infof("Generating auth token and saving it to %s", authTokenPath)
|
|
if err := saveAuthToken(walletDirPath, jwtKey, token); err != nil {
|
|
return err
|
|
}
|
|
logValidatorWebAuth(validatorWebAddr, token, authTokenPath)
|
|
return nil
|
|
}
|
|
|
|
// Upon launch of the validator client, we initialize an auth token by either creating
|
|
// one from scratch or reading it from a file. This token can then be shown to the
|
|
// user via stdout and the validator client should then attempt to open the default
|
|
// browser. The web interface authenticates by looking for this token in the query parameters
|
|
// of the URL. This token is then used as the bearer token for jwt auth.
|
|
func (s *Server) initializeAuthToken(walletDir string) (string, error) {
|
|
authTokenFile := filepath.Join(walletDir, AuthTokenFileName)
|
|
exists, err := file.Exists(authTokenFile, file.Regular)
|
|
if err != nil {
|
|
return "", errors.Wrapf(err, "could not check if file exists: %s", authTokenFile)
|
|
}
|
|
|
|
if exists {
|
|
// #nosec G304
|
|
f, err := os.Open(authTokenFile)
|
|
if err != nil {
|
|
return "", err
|
|
}
|
|
defer func() {
|
|
if err := f.Close(); err != nil {
|
|
log.Error(err)
|
|
}
|
|
}()
|
|
secret, token, err := readAuthTokenFile(f)
|
|
if err != nil {
|
|
return "", err
|
|
}
|
|
s.jwtSecret = secret
|
|
return token, nil
|
|
}
|
|
jwtKey, err := createRandomJWTSecret()
|
|
if err != nil {
|
|
return "", err
|
|
}
|
|
s.jwtSecret = jwtKey
|
|
token, err := createTokenString(s.jwtSecret)
|
|
if err != nil {
|
|
return "", err
|
|
}
|
|
if err := saveAuthToken(walletDir, jwtKey, token); err != nil {
|
|
return "", err
|
|
}
|
|
return token, nil
|
|
}
|
|
|
|
func (s *Server) refreshAuthTokenFromFileChanges(ctx context.Context, authTokenPath string) {
|
|
watcher, err := fsnotify.NewWatcher()
|
|
if err != nil {
|
|
log.WithError(err).Error("Could not initialize file watcher")
|
|
return
|
|
}
|
|
defer func() {
|
|
if err := watcher.Close(); err != nil {
|
|
log.WithError(err).Error("Could not close file watcher")
|
|
}
|
|
}()
|
|
if err := watcher.Add(authTokenPath); err != nil {
|
|
log.WithError(err).Errorf("Could not add file %s to file watcher", authTokenPath)
|
|
return
|
|
}
|
|
for {
|
|
select {
|
|
case <-watcher.Events:
|
|
// If a file was modified, we attempt to read that file
|
|
// and parse it into our accounts store.
|
|
token, err := s.initializeAuthToken(s.walletDir)
|
|
if err != nil {
|
|
log.WithError(err).Errorf("Could not watch for file changes for: %s", authTokenPath)
|
|
continue
|
|
}
|
|
validatorWebAddr := fmt.Sprintf("%s:%d", s.validatorGatewayHost, s.validatorGatewayPort)
|
|
logValidatorWebAuth(validatorWebAddr, token, authTokenPath)
|
|
case err := <-watcher.Errors:
|
|
log.WithError(err).Errorf("Could not watch for file changes for: %s", authTokenPath)
|
|
case <-ctx.Done():
|
|
return
|
|
}
|
|
}
|
|
}
|
|
|
|
func logValidatorWebAuth(validatorWebAddr, token string, tokenPath string) {
|
|
webAuthURLTemplate := "http://%s/initialize?token=%s"
|
|
webAuthURL := fmt.Sprintf(
|
|
webAuthURLTemplate,
|
|
validatorWebAddr,
|
|
url.QueryEscape(token),
|
|
)
|
|
log.Infof(
|
|
"Once your validator process is running, navigate to the link below to authenticate with " +
|
|
"the Prysm web interface",
|
|
)
|
|
log.Info(webAuthURL)
|
|
log.Infof("Validator CLient JWT for RPC and REST authentication set at:%s", tokenPath)
|
|
}
|
|
|
|
func saveAuthToken(walletDirPath string, jwtKey []byte, token string) error {
|
|
hashFilePath := filepath.Join(walletDirPath, AuthTokenFileName)
|
|
bytesBuf := new(bytes.Buffer)
|
|
if _, err := bytesBuf.WriteString(fmt.Sprintf("%x", jwtKey)); err != nil {
|
|
return err
|
|
}
|
|
if _, err := bytesBuf.WriteString("\n"); err != nil {
|
|
return err
|
|
}
|
|
if _, err := bytesBuf.WriteString(token); err != nil {
|
|
return err
|
|
}
|
|
if _, err := bytesBuf.WriteString("\n"); err != nil {
|
|
return err
|
|
}
|
|
|
|
if err := file.MkdirAll(walletDirPath); err != nil {
|
|
return errors.Wrapf(err, "could not create directory %s", walletDirPath)
|
|
}
|
|
|
|
if err := file.WriteFile(hashFilePath, bytesBuf.Bytes()); err != nil {
|
|
return errors.Wrapf(err, "could not write to file %s", hashFilePath)
|
|
}
|
|
|
|
return nil
|
|
}
|
|
|
|
func readAuthTokenFile(r io.Reader) (secret []byte, token string, err error) {
|
|
br := bufio.NewReader(r)
|
|
var jwtKeyHex string
|
|
jwtKeyHex, err = br.ReadString('\n')
|
|
if err != nil {
|
|
return
|
|
}
|
|
secret, err = hex.DecodeString(strings.TrimSpace(jwtKeyHex))
|
|
if err != nil {
|
|
return
|
|
}
|
|
tokenBytes, _, err := br.ReadLine()
|
|
if err != nil {
|
|
return
|
|
}
|
|
token = strings.TrimSpace(string(tokenBytes))
|
|
return
|
|
}
|
|
|
|
// Creates a JWT token string using the JWT key.
|
|
func createTokenString(jwtKey []byte) (string, error) {
|
|
token := jwt.NewWithClaims(jwt.SigningMethodHS256, jwt.RegisteredClaims{})
|
|
// Sign and get the complete encoded token as a string using the secret
|
|
tokenString, err := token.SignedString(jwtKey)
|
|
if err != nil {
|
|
return "", err
|
|
}
|
|
return tokenString, nil
|
|
}
|
|
|
|
func createRandomJWTSecret() ([]byte, error) {
|
|
r := rand.NewGenerator()
|
|
jwtKey := make([]byte, 32)
|
|
n, err := r.Read(jwtKey)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
if n != len(jwtKey) {
|
|
return nil, errors.New("could not create appropriately sized random JWT secret")
|
|
}
|
|
return jwtKey, nil
|
|
}
|