Skip to content

Commit

Permalink
Review logging (#39)
Browse files Browse the repository at this point in the history
* add missing logging

* remove os exit
  • Loading branch information
pablomendezroyo authored May 15, 2024
1 parent 7f00dbc commit 24da2da
Show file tree
Hide file tree
Showing 6 changed files with 40 additions and 53 deletions.
4 changes: 2 additions & 2 deletions listener/internal/api/api.go
Original file line number Diff line number Diff line change
Expand Up @@ -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),
Expand Down
2 changes: 1 addition & 1 deletion listener/internal/api/handlers/postNewSignature.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
23 changes: 0 additions & 23 deletions listener/internal/api/types/types.go
Original file line number Diff line number Diff line change
Expand Up @@ -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"`
}
25 changes: 24 additions & 1 deletion listener/internal/api/validation/GetActiveValidators.go
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down Expand Up @@ -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
Expand Down
5 changes: 0 additions & 5 deletions listener/internal/api/validation/VerifySignature.go
Original file line number Diff line number Diff line change
Expand Up @@ -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())
Expand All @@ -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())
Expand All @@ -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")
Expand Down
34 changes: 13 additions & 21 deletions listener/internal/config/config.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package config

import (
"fmt"
"os"
"strings"

Expand All @@ -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")
Expand All @@ -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".
Expand All @@ -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,
Expand Down

0 comments on commit 24da2da

Please sign in to comment.