From 24da2dac1282345b5c5a056b40191410aaf13559 Mon Sep 17 00:00:00 2001 From: pablomendezroyo <41727368+pablomendezroyo@users.noreply.github.com> Date: Wed, 15 May 2024 13:51:15 +0200 Subject: [PATCH] Review logging (#39) * add missing logging * remove os exit --- listener/internal/api/api.go | 4 +-- .../internal/api/handlers/postNewSignature.go | 2 +- listener/internal/api/types/types.go | 23 ------------- .../api/validation/GetActiveValidators.go | 25 +++++++++++++- .../api/validation/VerifySignature.go | 5 --- listener/internal/config/config.go | 34 +++++++------------ 6 files changed, 40 insertions(+), 53 deletions(-) diff --git a/listener/internal/api/api.go b/listener/internal/api/api.go index 8607999..8e397c6 100644 --- a/listener/internal/api/api.go +++ b/listener/internal/api/api.go @@ -29,13 +29,13 @@ func NewApi(port string, dbClient *mongo.Client, dbCollection *mongo.Collection, } func (s *httpApi) Start() { + logger.Info("Server is running on port " + s.port) + // if somehow s.server is not nil, it means the server is already running, this should never happen if s.server != nil { logger.Fatal("HTTP server already started") } - logger.Info("Server is running on port " + s.port) - s.server = &http.Server{ Addr: ":" + s.port, Handler: routes.SetupRouter(s.dbCollection, s.beaconNodeUrls, s.bypassValidatorFiltering), diff --git a/listener/internal/api/handlers/postNewSignature.go b/listener/internal/api/handlers/postNewSignature.go index 3447d38..94ee60b 100644 --- a/listener/internal/api/handlers/postNewSignature.go +++ b/listener/internal/api/handlers/postNewSignature.go @@ -66,7 +66,7 @@ func PostNewSignature(w http.ResponseWriter, r *http.Request, dbCollection *mong continue } if !isValidSignature { - logger.Debug("Invalid signature: " + req.Signature) + logger.Warn("Invalid signature: " + req.Signature) continue } validSignatures = append(validSignatures, req) diff --git a/listener/internal/api/types/types.go b/listener/internal/api/types/types.go index aec06f6..85abae3 100644 --- a/listener/internal/api/types/types.go +++ b/listener/internal/api/types/types.go @@ -22,26 +22,3 @@ type DecodedPayload struct { Platform string `json:"platform"` Timestamp string `json:"timestamp"` } - -type ActiveValidator struct { - Pubkey string `json:"pubkey"` - WithdrawalCredentials string `json:"withdrawal_credentials"` - EffectiveBalance string `json:"effective_balance"` - Slashed bool `json:"slashed"` - ActivationEligibilityEpoch string `json:"activation_eligibility_epoch"` - ActivationEpoch string `json:"activation_epoch"` - ExitEpoch string `json:"exit_epoch"` - WithdrawableEpoch string `json:"withdrawable_epoch"` -} - -// https://ethereum.github.io/beacon-APIs/#/Beacon /eth/v1/beacon/states/{state_id}/validators -type ActiveValidatorsApiResponse struct { - ExecutionOptimistic bool `json:"execution_optimistic"` - Finalized bool `json:"finalized"` - Data []struct { - Index string `json:"index"` - Balance string `json:"balance"` - Status string `json:"status"` - Validator ActiveValidator `json:"validator"` - } `json:"data"` -} diff --git a/listener/internal/api/validation/GetActiveValidators.go b/listener/internal/api/validation/GetActiveValidators.go index 6fe2263..fafe1f3 100644 --- a/listener/internal/api/validation/GetActiveValidators.go +++ b/listener/internal/api/validation/GetActiveValidators.go @@ -10,6 +10,29 @@ import ( "github.com/dappnode/validator-monitoring/listener/internal/api/types" ) +type activeValidator struct { + Pubkey string `json:"pubkey"` + WithdrawalCredentials string `json:"withdrawal_credentials"` + EffectiveBalance string `json:"effective_balance"` + Slashed bool `json:"slashed"` + ActivationEligibilityEpoch string `json:"activation_eligibility_epoch"` + ActivationEpoch string `json:"activation_epoch"` + ExitEpoch string `json:"exit_epoch"` + WithdrawableEpoch string `json:"withdrawable_epoch"` +} + +// https://ethereum.github.io/beacon-APIs/#/Beacon /eth/v1/beacon/states/{state_id}/validators +type activeValidatorsApiResponse struct { + ExecutionOptimistic bool `json:"execution_optimistic"` + Finalized bool `json:"finalized"` + Data []struct { + Index string `json:"index"` + Balance string `json:"balance"` + Status string `json:"status"` + Validator activeValidator `json:"validator"` + } `json:"data"` +} + // GetActiveValidators checks the active status of validators from a specific beacon node. // If bypass is true, it simply returns all decoded requests. func GetActiveValidators(requestsDecoded []types.SignatureRequestDecoded, beaconNodeUrl string) []types.SignatureRequestDecoded { @@ -61,7 +84,7 @@ func GetActiveValidators(requestsDecoded []types.SignatureRequestDecoded, beacon } // Decode the API response directly into the ApiResponse struct - var apiResponse types.ActiveValidatorsApiResponse + var apiResponse activeValidatorsApiResponse if err := json.NewDecoder(resp.Body).Decode(&apiResponse); err != nil { fmt.Printf("error decoding response data: %v\n", err) return nil diff --git a/listener/internal/api/validation/VerifySignature.go b/listener/internal/api/validation/VerifySignature.go index 39a742e..bfec7bb 100644 --- a/listener/internal/api/validation/VerifySignature.go +++ b/listener/internal/api/validation/VerifySignature.go @@ -14,13 +14,11 @@ func VerifySignature(req types.SignatureRequestDecoded) (bool, error) { // Decode the public key from hex, remove the 0x prefix ONLY if exists from req.Pubkey req.Pubkey = strings.TrimPrefix(req.Pubkey, "0x") req.Pubkey = strings.TrimSpace(req.Pubkey) - pubkeyBytes, err := hex.DecodeString(req.Pubkey) if err != nil { logger.Error("Failed to decode public key from hex: " + err.Error()) return false, err } - var pubkeyDes bls.PublicKey if err := pubkeyDes.Deserialize(pubkeyBytes); err != nil { logger.Error("Failed to deserialize public key: " + err.Error()) @@ -30,13 +28,11 @@ func VerifySignature(req types.SignatureRequestDecoded) (bool, error) { // Decode the signature from hex, remove the 0x prefix ONLY if exists from req.Signature req.Signature = strings.TrimPrefix(req.Signature, "0x") req.Signature = strings.TrimSpace(req.Signature) - sigBytes, err := hex.DecodeString(req.Signature) if err != nil { logger.Error("Failed to decode signature from hex: " + err.Error()) return false, err } - var sig bls.Sign if err := sig.Deserialize(sigBytes); err != nil { logger.Error("Failed to deserialize signature: " + err.Error()) @@ -49,7 +45,6 @@ func VerifySignature(req types.SignatureRequestDecoded) (bool, error) { logger.Error("Failed to serialize payload to string: " + err.Error()) return false, err } - // Verify the signature if !sig.VerifyByte(&pubkeyDes, payloadBytes) { logger.Debug("Failed to verify signature") diff --git a/listener/internal/config/config.go b/listener/internal/config/config.go index e2d9ad8..d58bc5b 100644 --- a/listener/internal/config/config.go +++ b/listener/internal/config/config.go @@ -1,6 +1,7 @@ package config import ( + "fmt" "os" "strings" @@ -22,11 +23,6 @@ type Config struct { } func LoadConfig() (*Config, error) { - mongoDBURI := os.Getenv("MONGO_DB_URI") - if mongoDBURI == "" { - logger.Fatal("MONGO_DB_URI is not set") - } - logLevel := os.Getenv("LOG_LEVEL") if logLevel == "" { logger.Info("LOG_LEVEL is not set, using default INFO") @@ -35,7 +31,8 @@ func LoadConfig() (*Config, error) { apiPort := os.Getenv("API_PORT") if apiPort == "" { - logger.Fatal("API_PORT is not set") + logger.Info("API_PORT is not set, using default 8080") + apiPort = "8080" } // Load bypassValidatorsFiltering boolean from env. Defaults to false unless explicitly set to "true". @@ -46,36 +43,31 @@ func LoadConfig() (*Config, error) { } bypassValidatorsFiltering := strings.ToLower(bypassValidatorsFilteringStr) == "true" - // beacon node urls per network + mongoDBURI := os.Getenv("MONGO_DB_URI") + if mongoDBURI == "" { + return nil, fmt.Errorf("MONGO_DB_URI is not set") + } + // beacon node urls per network beaconMainnet := os.Getenv("BEACON_NODE_URL_MAINNET") if beaconMainnet == "" { - logger.Fatal("BEACON_NODE_URL_MAINNET is not set") + return nil, fmt.Errorf("BEACON_NODE_URL_MAINNET is not set") } beaconHolesky := os.Getenv("BEACON_NODE_URL_HOLESKY") if beaconHolesky == "" { logger.Fatal("BEACON_NODE_URL_HOLESKY is not set") } - beaconGnosis := os.Getenv("BEACON_NODE_URL_GNOSIS") if beaconGnosis == "" { - logger.Fatal("BEACON_NODE_URL_GNOSIS is not set") + return nil, fmt.Errorf("BEACON_NODE_URL_GNOSIS is not set") } - beaconLukso := os.Getenv("BEACON_NODE_URL_LUKSO") if beaconLukso == "" { - logger.Fatal("BEACON_NODE_URL_LUKSO is not set") + return nil, fmt.Errorf("BEACON_NODE_URL_LUKSO is not set") } - // print all envs - logger.Info("MONGO_DB_URI: " + mongoDBURI) - logger.Info("LOG_LEVEL: " + logLevel) - logger.Info("API_PORT: " + apiPort) - logger.Info("BYPASS_VALIDATORS_FILTERING: " + bypassValidatorsFilteringStr) - logger.Info("BEACON_NODE_URL_MAINNET: " + beaconMainnet) - logger.Info("BEACON_NODE_URL_HOLESKY: " + beaconHolesky) - logger.Info("BEACON_NODE_URL_GNOSIS: " + beaconGnosis) - logger.Info("BEACON_NODE_URL_LUKSO: " + beaconLukso) + // print all envs in a single line + logger.Info("Loaded config: LOG_LEVEL=" + logLevel + " API_PORT=" + apiPort + " MONGO_DB_URI=" + mongoDBURI + " BYPASS_VALIDATORS_FILTERING=" + bypassValidatorsFilteringStr + " BEACON_NODE_URL_MAINNET=" + beaconMainnet + " BEACON_NODE_URL_HOLESKY=" + beaconHolesky + " BEACON_NODE_URL_GNOSIS=" + beaconGnosis + " BEACON_NODE_URL_LUKSO=" + beaconLukso) beaconNodeURLs := map[string]string{ "mainnet": beaconMainnet,