diff --git a/handlers/api.go b/handlers/api.go index bc75d14e81..f5424faa9d 100644 --- a/handlers/api.go +++ b/handlers/api.go @@ -230,7 +230,7 @@ func ApiEthStoreDay(w http.ResponseWriter, r *http.Request) { } else { day, e := strconv.ParseInt(vars["day"], 10, 64) if e != nil { - sendErrorResponse(w, r.URL.String(), "invalid day provided") + SendBadRequestResponse(w, r.URL.String(), "invalid day provided") return } rows, err = db.ReaderDb.Query(query+` AND day = $1;`, day) @@ -238,7 +238,7 @@ func ApiEthStoreDay(w http.ResponseWriter, r *http.Request) { if err != nil { logger.Errorf("error retrieving eth.store data: %v", err) - sendErrorResponse(w, r.URL.String(), "could not retrieve db results") + SendBadRequestResponse(w, r.URL.String(), "could not retrieve db results") return } defer rows.Close() @@ -274,16 +274,11 @@ func ApiEpoch(w http.ResponseWriter, r *http.Request) { epoch, err := strconv.ParseInt(vars["epoch"], 10, 64) if err != nil && vars["epoch"] != "latest" && vars["epoch"] != "finalized" { - sendErrorResponse(w, r.URL.String(), "invalid epoch provided") + SendBadRequestResponse(w, r.URL.String(), "invalid epoch provided") return } if vars["epoch"] == "latest" { - // err = db.ReaderDb.Get(&epoch, "SELECT MAX(epoch) FROM epochs") - // if err != nil { - // sendErrorResponse(w, r.URL.String(), "unable to retrieve latest epoch number") - // return - // } epoch = int64(services.LatestEpoch()) } @@ -293,12 +288,12 @@ func ApiEpoch(w http.ResponseWriter, r *http.Request) { } if epoch > int64(services.LatestEpoch()) { - sendErrorResponse(w, r.URL.String(), fmt.Sprintf("epoch is in the future. The latest epoch is %v", services.LatestEpoch())) + SendBadRequestResponse(w, r.URL.String(), fmt.Sprintf("epoch is in the future. The latest epoch is %v", services.LatestEpoch())) return } if epoch < 0 { - sendErrorResponse(w, r.URL.String(), "epoch must be a positive number") + SendBadRequestResponse(w, r.URL.String(), "epoch must be a positive number") return } @@ -338,7 +333,7 @@ func ApiEpochSlots(w http.ResponseWriter, r *http.Request) { epoch, err := strconv.ParseInt(vars["epoch"], 10, 64) if err != nil && vars["epoch"] != "latest" && vars["epoch"] != "finalized" { - sendErrorResponse(w, r.URL.String(), "invalid epoch provided") + SendBadRequestResponse(w, r.URL.String(), "invalid epoch provided") return } @@ -351,12 +346,12 @@ func ApiEpochSlots(w http.ResponseWriter, r *http.Request) { } if epoch > int64(services.LatestEpoch()) { - sendErrorResponse(w, r.URL.String(), fmt.Sprintf("epoch is in the future. The latest epoch is %v", services.LatestEpoch())) + SendBadRequestResponse(w, r.URL.String(), fmt.Sprintf("epoch is in the future. The latest epoch is %v", services.LatestEpoch())) return } if epoch < 0 { - sendErrorResponse(w, r.URL.String(), "epoch must be a positive number") + SendBadRequestResponse(w, r.URL.String(), "epoch must be a positive number") return } @@ -395,7 +390,7 @@ func ApiSlots(w http.ResponseWriter, r *http.Request) { // retrieve the slot containing the head block of the chain blockRootHash = services.Eth1HeadBlockRootHash() if len(blockRootHash) != 32 { - sendErrorResponse(w, r.URL.String(), "could not retrieve db results") + SendBadRequestResponse(w, r.URL.String(), "could not retrieve db results") return } } else { @@ -406,7 +401,7 @@ func ApiSlots(w http.ResponseWriter, r *http.Request) { blockRootHash = []byte{} blockSlot, err = strconv.ParseInt(vars["slotOrHash"], 10, 64) if err != nil { - sendErrorResponse(w, r.URL.String(), "could not parse slot number") + SendBadRequestResponse(w, r.URL.String(), "could not parse slot number") return } } @@ -416,7 +411,7 @@ func ApiSlots(w http.ResponseWriter, r *http.Request) { err := db.ReaderDb.Get(&blockRootHash, `SELECT blockroot FROM blocks WHERE slot = $1`, blockSlot) if err != nil || len(blockRootHash) != 32 { - sendErrorResponse(w, r.URL.String(), "could not retrieve db results") + SendBadRequestResponse(w, r.URL.String(), "could not retrieve db results") return } } @@ -470,7 +465,7 @@ func ApiSlots(w http.ResponseWriter, r *http.Request) { if err != nil { logger.WithError(err).Error("could not retrieve db results") - sendErrorResponse(w, r.URL.String(), "could not retrieve db results") + SendBadRequestResponse(w, r.URL.String(), "could not retrieve db results") return } defer rows.Close() @@ -495,7 +490,7 @@ func ApiSlotAttestations(w http.ResponseWriter, r *http.Request) { slot, err := strconv.ParseInt(vars["slot"], 10, 64) if err != nil && vars["slot"] != "latest" { - sendErrorResponse(w, r.URL.String(), "invalid block slot provided") + SendBadRequestResponse(w, r.URL.String(), "invalid block slot provided") return } @@ -504,19 +499,19 @@ func ApiSlotAttestations(w http.ResponseWriter, r *http.Request) { } if slot > int64(services.LatestSlot()) { - sendErrorResponse(w, r.URL.String(), fmt.Sprintf("slot is in the future. The latest slot is %v", services.LatestSlot())) + SendBadRequestResponse(w, r.URL.String(), fmt.Sprintf("slot is in the future. The latest slot is %v", services.LatestSlot())) return } if slot < 0 { - sendErrorResponse(w, r.URL.String(), "slot must be a positive number") + SendBadRequestResponse(w, r.URL.String(), "slot must be a positive number") return } rows, err := db.ReaderDb.Query("SELECT aggregationbits, beaconblockroot, block_index, block_root, block_slot, committeeindex, signature, slot, source_epoch, source_root, target_epoch, target_root, validators FROM blocks_attestations WHERE block_slot = $1 ORDER BY block_index", slot) if err != nil { logger.WithError(err).Error("could not retrieve db results") - sendErrorResponse(w, r.URL.String(), "could not retrieve db results") + SendBadRequestResponse(w, r.URL.String(), "could not retrieve db results") return } defer rows.Close() @@ -540,13 +535,13 @@ func ApiSlotAttesterSlashings(w http.ResponseWriter, r *http.Request) { slot, err := strconv.ParseInt(vars["slot"], 10, 64) if err != nil { - sendErrorResponse(w, r.URL.String(), "invalid block slot provided") + SendBadRequestResponse(w, r.URL.String(), "invalid block slot provided") return } rows, err := db.ReaderDb.Query("SELECT attestation1_beaconblockroot, attestation1_index, attestation1_indices, attestation1_signature, attestation1_slot, attestation1_source_epoch, attestation1_source_root, attestation1_target_epoch, attestation1_target_root, attestation2_beaconblockroot, attestation2_index, attestation2_indices, attestation2_signature, attestation2_slot, attestation2_source_epoch, attestation2_source_root, attestation2_target_epoch, attestation2_target_root, block_index, block_root, block_slot FROM blocks_attesterslashings WHERE block_slot = $1 ORDER BY block_index DESC", slot) if err != nil { - sendErrorResponse(w, r.URL.String(), "could not retrieve db results") + SendBadRequestResponse(w, r.URL.String(), "could not retrieve db results") return } defer rows.Close() @@ -594,14 +589,14 @@ func ApiSlotDeposits(w http.ResponseWriter, r *http.Request) { slot, err := strconv.ParseInt(vars["slot"], 10, 64) if err != nil { - sendErrorResponse(w, r.URL.String(), "invalid block slot provided") + SendBadRequestResponse(w, r.URL.String(), "invalid block slot provided") return } rows, err := db.ReaderDb.Query("SELECT amount, block_index, block_root, block_slot, proof, publickey, signature, withdrawalcredentials FROM blocks_deposits WHERE block_slot = $1 ORDER BY block_index DESC limit $2 offset $3", slot, limit, offset) if err != nil { logger.WithError(err).Error("could not retrieve db results") - sendErrorResponse(w, r.URL.String(), "could not retrieve db results") + SendBadRequestResponse(w, r.URL.String(), "could not retrieve db results") return } defer rows.Close() @@ -626,14 +621,14 @@ func ApiSlotProposerSlashings(w http.ResponseWriter, r *http.Request) { slot, err := strconv.ParseInt(vars["slot"], 10, 64) if err != nil { - sendErrorResponse(w, r.URL.String(), "invalid block slot provided") + SendBadRequestResponse(w, r.URL.String(), "invalid block slot provided") return } rows, err := db.ReaderDb.Query("SELECT block_index, block_root, block_slot, header1_bodyroot, header1_parentroot, header1_signature, header1_slot, header1_stateroot, header2_bodyroot, header2_parentroot, header2_signature, header2_slot, header2_stateroot, proposerindex FROM blocks_proposerslashings WHERE block_slot = $1 ORDER BY block_index DESC", slot) if err != nil { logger.WithError(err).Error("could not retrieve db results") - sendErrorResponse(w, r.URL.String(), "could not retrieve db results") + SendBadRequestResponse(w, r.URL.String(), "could not retrieve db results") return } defer rows.Close() @@ -658,14 +653,14 @@ func ApiSlotVoluntaryExits(w http.ResponseWriter, r *http.Request) { slot, err := strconv.ParseInt(vars["slot"], 10, 64) if err != nil { - sendErrorResponse(w, r.URL.String(), "invalid block slot provided") + SendBadRequestResponse(w, r.URL.String(), "invalid block slot provided") return } rows, err := db.ReaderDb.Query("SELECT block_slot, block_index, block_root, epoch, validatorindex, signature FROM blocks_voluntaryexits WHERE block_slot = $1 ORDER BY block_index DESC", slot) if err != nil { logger.WithError(err).Error("could not retrieve db results") - sendErrorResponse(w, r.URL.String(), "could not retrieve db results") + SendBadRequestResponse(w, r.URL.String(), "could not retrieve db results") return } defer rows.Close() @@ -688,14 +683,14 @@ func ApiSlotWithdrawals(w http.ResponseWriter, r *http.Request) { slot, err := strconv.ParseInt(vars["slot"], 10, 64) if err != nil { - sendErrorResponse(w, r.URL.String(), "invalid block slot provided") + SendBadRequestResponse(w, r.URL.String(), "invalid block slot provided") return } rows, err := db.ReaderDb.Query("SELECT block_slot, withdrawalindex, validatorindex, address, amount FROM blocks_withdrawals WHERE block_slot = $1 ORDER BY withdrawalindex", slot) if err != nil { logger.WithError(err).Error("error getting blocks_withdrawals") - sendErrorResponse(w, r.URL.String(), "could not retrieve db results") + SendBadRequestResponse(w, r.URL.String(), "could not retrieve db results") return } defer rows.Close() @@ -721,7 +716,7 @@ func ApiSyncCommittee(w http.ResponseWriter, r *http.Request) { period, err := strconv.ParseUint(vars["period"], 10, 64) if err != nil && vars["period"] != "latest" && vars["period"] != "next" { - sendErrorResponse(w, r.URL.String(), "invalid epoch provided") + SendBadRequestResponse(w, r.URL.String(), "invalid epoch provided") return } @@ -734,7 +729,7 @@ func ApiSyncCommittee(w http.ResponseWriter, r *http.Request) { rows, err := db.ReaderDb.Query(`SELECT period, GREATEST(period*$2, $3) AS start_epoch, ((period+1)*$2)-1 AS end_epoch, ARRAY_AGG(validatorindex ORDER BY committeeindex) AS validators FROM sync_committees WHERE period = $1 GROUP BY period`, period, utils.Config.Chain.ClConfig.EpochsPerSyncCommitteePeriod, utils.Config.Chain.ClConfig.AltairForkEpoch) if err != nil { logger.WithError(err).WithField("url", r.URL.String()).Errorf("error querying db") - sendErrorResponse(w, r.URL.String(), "could not retrieve db results") + SendBadRequestResponse(w, r.URL.String(), "could not retrieve db results") return } defer rows.Close() @@ -755,7 +750,7 @@ func ApiValidatorQueue(w http.ResponseWriter, r *http.Request) { rows, err := db.ReaderDb.Query("SELECT e.validatorscount, q.entering_validators_count as beaconchain_entering, q.exiting_validators_count as beaconchain_exiting FROM epochs e, queue q ORDER BY e.epoch DESC, q.ts DESC LIMIT 1") if err != nil { - sendErrorResponse(w, r.URL.String(), "could not retrieve db results") + SendBadRequestResponse(w, r.URL.String(), "could not retrieve db results") return } defer rows.Close() @@ -779,11 +774,11 @@ func ApiRocketpoolStats(w http.ResponseWriter, r *http.Request) { stats, err := getRocketpoolStats() if err != nil { - sendErrorResponse(w, r.URL.String(), "could not parse db results") + SendBadRequestResponse(w, r.URL.String(), "could not parse db results") return } - sendOKResponse(j, r.URL.String(), stats) + SendOKResponse(j, r.URL.String(), stats) } // ApiRocketpoolValidators godoc @@ -804,18 +799,18 @@ func ApiRocketpoolValidators(w http.ResponseWriter, r *http.Request) { queryIndices, err := parseApiValidatorParamToIndices(vars["indexOrPubkey"], maxValidators) if err != nil { - sendErrorResponse(w, r.URL.String(), err.Error()) + SendBadRequestResponse(w, r.URL.String(), err.Error()) return } stats, err := getRocketpoolValidators(queryIndices) if err != nil { - sendErrorResponse(w, r.URL.String(), "could not parse db results") + SendBadRequestResponse(w, r.URL.String(), "could not parse db results") return } - sendOKResponse(j, r.URL.String(), stats) + SendOKResponse(j, r.URL.String(), stats) } /* @@ -830,7 +825,7 @@ func ApiDashboard(w http.ResponseWriter, r *http.Request) { body, err := io.ReadAll(r.Body) if err != nil { utils.LogError(err, "reading body", 0) - sendErrorResponse(w, r.URL.String(), "could not read body") + SendBadRequestResponse(w, r.URL.String(), "could not read body") return } @@ -863,7 +858,7 @@ func ApiDashboard(w http.ResponseWriter, r *http.Request) { if getValidators { queryIndices, err := parseApiValidatorParamToIndices(parsedBody.IndicesOrPubKey, maxValidators) if err != nil { - sendErrorResponse(w, r.URL.String(), err.Error()) + SendBadRequestResponse(w, r.URL.String(), err.Error()) return } @@ -997,7 +992,7 @@ func ApiDashboard(w http.ResponseWriter, r *http.Request) { err = g.Wait() if err != nil { utils.LogError(err, "dashboard", 0) - sendErrorResponse(w, r.URL.String(), err.Error()) + SendBadRequestResponse(w, r.URL.String(), err.Error()) return } @@ -1015,7 +1010,7 @@ func ApiDashboard(w http.ResponseWriter, r *http.Request) { ProposalLuckStats: proposalLuckStats, } - sendOKResponse(j, r.URL.String(), []interface{}{data}) + SendOKResponse(j, r.URL.String(), []interface{}{data}) } func getSyncCommitteeInfoForValidators(validators []uint64, period uint64) ([]interface{}, error) { @@ -1557,7 +1552,7 @@ func getApiValidator(w http.ResponseWriter, r *http.Request) { err := decoder.Decode(req) if err != nil { - sendErrorResponse(w, r.URL.String(), "error decoding request body") + SendBadRequestResponse(w, r.URL.String(), "error decoding request body") return } param = req.IndicesOrPubKey @@ -1566,7 +1561,7 @@ func getApiValidator(w http.ResponseWriter, r *http.Request) { queryIndices, err := parseApiValidatorParamToIndices(param, maxValidators) if err != nil { - sendErrorResponse(w, r.URL.String(), err.Error()) + SendBadRequestResponse(w, r.URL.String(), err.Error()) return } @@ -1622,13 +1617,13 @@ func getApiValidator(w http.ResponseWriter, r *http.Request) { `, pq.Array(queryIndices), cutoffSlot, lastExportedDay) if err != nil { logger.Warnf("error retrieving validator data from db: %v", err) - sendErrorResponse(w, r.URL.String(), "could not retrieve db results") + SendBadRequestResponse(w, r.URL.String(), "could not retrieve db results") return } balances, err := db.BigtableClient.GetValidatorBalanceHistory(queryIndices, services.LatestEpoch(), services.LatestEpoch()) if err != nil { - sendErrorResponse(w, r.URL.String(), "could not retrieve validator balance data") + SendBadRequestResponse(w, r.URL.String(), "could not retrieve validator balance data") return } @@ -1646,7 +1641,7 @@ func getApiValidator(w http.ResponseWriter, r *http.Request) { lastAttestationSlots, err := db.BigtableClient.GetLastAttestationSlots(queryIndices) if err != nil { - sendErrorResponse(w, r.URL.String(), fmt.Sprintf("error getting validator last attestation slots from bigtable: %v", err)) + SendBadRequestResponse(w, r.URL.String(), fmt.Sprintf("error getting validator last attestation slots from bigtable: %v", err)) return } @@ -1714,7 +1709,7 @@ func ApiValidatorDailyStats(w http.ResponseWriter, r *http.Request) { if q.Get("end_day") != "" { end, err := strconv.ParseInt(q.Get("end_day"), 10, 64) if err != nil { - sendErrorResponse(w, r.URL.String(), "invalid end_day parameter") + SendBadRequestResponse(w, r.URL.String(), "invalid end_day parameter") return } if end < endDay { @@ -1725,11 +1720,11 @@ func ApiValidatorDailyStats(w http.ResponseWriter, r *http.Request) { if q.Get("start_day") != "" { start, err := strconv.ParseInt(q.Get("start_day"), 10, 64) if err != nil { - sendErrorResponse(w, r.URL.String(), "invalid start_day parameter") + SendBadRequestResponse(w, r.URL.String(), "invalid start_day parameter") return } if start > endDay { - sendErrorResponse(w, r.URL.String(), "start_day must be less than end_day") + SendBadRequestResponse(w, r.URL.String(), "start_day must be less than end_day") return } if start > startDay { @@ -1739,7 +1734,7 @@ func ApiValidatorDailyStats(w http.ResponseWriter, r *http.Request) { index, err := strconv.ParseUint(vars["index"], 10, 64) if err != nil { - sendErrorResponse(w, r.URL.String(), "invalid validator index") + SendBadRequestResponse(w, r.URL.String(), "invalid validator index") return } @@ -1771,7 +1766,7 @@ func ApiValidatorDailyStats(w http.ResponseWriter, r *http.Request) { COALESCE(orphaned_sync, 0) AS orphaned_sync FROM validator_stats WHERE validatorindex = $1 and day <= $2 and day >= $3 ORDER BY day DESC`, index, endDay, startDay) if err != nil { - sendErrorResponse(w, r.URL.String(), "could not retrieve db results") + SendBadRequestResponse(w, r.URL.String(), "could not retrieve db results") return } defer rows.Close() @@ -1829,13 +1824,13 @@ func ApiValidatorByEth1Address(w http.ResponseWriter, r *http.Request) { search := ReplaceEnsNameWithAddress(vars["address"]) eth1Address, err := hex.DecodeString(strings.Replace(search, "0x", "", -1)) if err != nil { - sendErrorResponse(w, r.URL.String(), "invalid eth1 address provided") + SendBadRequestResponse(w, r.URL.String(), "invalid eth1 address provided") return } rows, err := db.ReaderDb.Query("SELECT publickey, validatorindex, valid_signature FROM eth1_deposits LEFT JOIN validators ON eth1_deposits.publickey = validators.pubkey WHERE from_address = $1 GROUP BY publickey, validatorindex, valid_signature ORDER BY validatorindex OFFSET $2 LIMIT $3;", eth1Address, offset, limit) if err != nil { - sendErrorResponse(w, r.URL.String(), "could not retrieve db results") + SendBadRequestResponse(w, r.URL.String(), "could not retrieve db results") return } defer rows.Close() @@ -1864,24 +1859,24 @@ func ApiValidatorIncomeDetailsHistory(w http.ResponseWriter, r *http.Request) { latestEpoch, limit, err := getIncomeDetailsHistoryQueryParameters(r.URL.Query()) if err != nil { - sendErrorResponse(w, r.URL.String(), err.Error()) + SendBadRequestResponse(w, r.URL.String(), err.Error()) return } queryIndices, err := parseApiValidatorParamToIndices(vars["indexOrPubkey"], maxValidators) if err != nil { - sendErrorResponse(w, r.URL.String(), err.Error()) + SendBadRequestResponse(w, r.URL.String(), err.Error()) return } if len(queryIndices) == 0 { - sendErrorResponse(w, r.URL.String(), "no validators provided") + SendBadRequestResponse(w, r.URL.String(), "no validators provided") return } history, err := db.BigtableClient.GetValidatorIncomeDetailsHistory(queryIndices, latestEpoch-(limit-1), latestEpoch) if err != nil { - sendErrorResponse(w, r.URL.String(), "could not retrieve db results") + SendBadRequestResponse(w, r.URL.String(), "could not retrieve db results") return } @@ -1995,12 +1990,12 @@ func ApiValidatorWithdrawals(w http.ResponseWriter, r *http.Request) { queryIndices, err := parseApiValidatorParamToIndices(vars["indexOrPubkey"], maxValidators) if err != nil { - sendErrorResponse(w, r.URL.String(), err.Error()) + SendBadRequestResponse(w, r.URL.String(), err.Error()) return } if len(queryIndices) == 0 { - sendErrorResponse(w, r.URL.String(), "no or invalid validator indicies provided") + SendBadRequestResponse(w, r.URL.String(), "no or invalid validator indicies provided") } q := r.URL.Query() @@ -2019,7 +2014,7 @@ func ApiValidatorWithdrawals(w http.ResponseWriter, r *http.Request) { data, err := db.GetValidatorsWithdrawals(queryIndices, endEpoch, epoch) if err != nil { logger.Errorf("error retrieving withdrawals for %v route: %v", r.URL.String(), err) - sendErrorResponse(w, r.URL.String(), "could not retrieve db results") + SendBadRequestResponse(w, r.URL.String(), "could not retrieve db results") return } @@ -2064,18 +2059,18 @@ func ApiValidatorBlsChange(w http.ResponseWriter, r *http.Request) { queryIndices, err := parseApiValidatorParamToIndices(vars["indexOrPubkey"], maxValidators) if err != nil { - sendErrorResponse(w, r.URL.String(), err.Error()) + SendBadRequestResponse(w, r.URL.String(), err.Error()) return } if len(queryIndices) == 0 { - sendErrorResponse(w, r.URL.String(), "no or invalid validator indicies provided") + SendBadRequestResponse(w, r.URL.String(), "no or invalid validator indicies provided") } data, err := db.GetValidatorsBLSChange(queryIndices) if err != nil { logger.Errorf("error retrieving validators bls change for %v route: %v", r.URL.String(), err) - sendErrorResponse(w, r.URL.String(), "could not retrieve db results") + SendBadRequestResponse(w, r.URL.String(), "could not retrieve db results") return } @@ -2128,23 +2123,23 @@ func ApiValidatorBalanceHistory(w http.ResponseWriter, r *http.Request) { latestEpoch, limit, err := getBalanceHistoryQueryParameters(r.URL.Query()) if err != nil { - sendErrorResponse(w, r.URL.String(), err.Error()) + SendBadRequestResponse(w, r.URL.String(), err.Error()) return } queryIndices, err := parseApiValidatorParamToIndices(vars["indexOrPubkey"], maxValidators) if err != nil { - sendErrorResponse(w, r.URL.String(), err.Error()) + SendBadRequestResponse(w, r.URL.String(), err.Error()) return } if len(queryIndices) == 0 { - sendErrorResponse(w, r.URL.String(), "no or invalid validator indicies provided") + SendBadRequestResponse(w, r.URL.String(), "no or invalid validator indicies provided") } history, err := db.BigtableClient.GetValidatorBalanceHistory(queryIndices, latestEpoch-(limit-1), latestEpoch) if err != nil { - sendErrorResponse(w, r.URL.String(), "could not retrieve db results") + SendBadRequestResponse(w, r.URL.String(), "could not retrieve db results") return } @@ -2236,7 +2231,7 @@ func ApiValidatorPerformance(w http.ResponseWriter, r *http.Request) { queryIndices, err := parseApiValidatorParamToIndices(vars["indexOrPubkey"], maxValidators) if err != nil { - sendErrorResponse(w, r.URL.String(), err.Error()) + SendBadRequestResponse(w, r.URL.String(), err.Error()) return } @@ -2255,27 +2250,27 @@ func ApiValidatorPerformance(w http.ResponseWriter, r *http.Request) { WHERE validator_performance.validatorindex = ANY($1) ORDER BY validatorindex`, pq.Array(queryIndices)) if err != nil { - sendErrorResponse(w, r.URL.String(), "could not retrieve db results") + SendBadRequestResponse(w, r.URL.String(), "could not retrieve db results") return } defer rows.Close() data, err := utils.SqlRowsToJSON(rows) if err != nil { - sendErrorResponse(w, r.URL.String(), "could not parse db results") + SendBadRequestResponse(w, r.URL.String(), "could not parse db results") return } currentDayIncome, err := db.GetCurrentDayClIncome(queryIndices) if err != nil { - sendErrorResponse(w, r.URL.String(), "error retrieving current day income") + SendBadRequestResponse(w, r.URL.String(), "error retrieving current day income") return } latestEpoch := int64(services.LatestFinalizedEpoch()) latestBalances, err := db.BigtableClient.GetValidatorBalanceHistory(queryIndices, uint64(latestEpoch), uint64(latestEpoch)) if err != nil { - sendErrorResponse(w, r.URL.String(), "error retrieving balances") + SendBadRequestResponse(w, r.URL.String(), "error retrieving balances") return } @@ -2328,7 +2323,7 @@ func ApiValidatorPerformance(w http.ResponseWriter, r *http.Request) { } j := json.NewEncoder(w) - sendOKResponse(j, r.URL.String(), []any{data}) + SendOKResponse(j, r.URL.String(), []any{data}) } // ApiValidatorExecutionPerformance godoc @@ -2348,18 +2343,18 @@ func ApiValidatorExecutionPerformance(w http.ResponseWriter, r *http.Request) { queryIndices, err := parseApiValidatorParamToIndices(vars["indexOrPubkey"], maxValidators) if err != nil { - sendErrorResponse(w, r.URL.String(), err.Error()) + SendBadRequestResponse(w, r.URL.String(), err.Error()) return } result, err := getValidatorExecutionPerformance(queryIndices) if err != nil { - sendErrorResponse(w, r.URL.String(), err.Error()) + SendBadRequestResponse(w, r.URL.String(), err.Error()) logger.WithError(err).Error("can not getValidatorExecutionPerformance") return } - sendOKResponse(j, r.URL.String(), []any{result}) + SendOKResponse(j, r.URL.String(), []any{result}) } // ApiValidatorAttestationEffectiveness godoc @@ -2381,13 +2376,13 @@ func ApiValidatorAttestationEffectiveness(w http.ResponseWriter, r *http.Request queryIndices, err := parseApiValidatorParamToIndices(vars["indexOrPubkey"], maxValidators) if err != nil { - sendErrorResponse(w, r.URL.String(), err.Error()) + SendBadRequestResponse(w, r.URL.String(), err.Error()) return } data, err := getValidatorEffectiveness(services.LatestEpoch()-1, queryIndices) if err != nil { - sendErrorResponse(w, r.URL.String(), "could not retrieve db results") + SendBadRequestResponse(w, r.URL.String(), "could not retrieve db results") return } @@ -2423,13 +2418,13 @@ func ApiValidatorAttestationEfficiency(w http.ResponseWriter, r *http.Request) { queryIndices, err := parseApiValidatorParamToIndices(vars["indexOrPubkey"], maxValidators) if err != nil { - sendErrorResponse(w, r.URL.String(), err.Error()) + SendBadRequestResponse(w, r.URL.String(), err.Error()) return } data, err := getValidatorEffectiveness(services.LatestEpoch()-1, queryIndices) if err != nil { - sendErrorResponse(w, r.URL.String(), "could not retrieve db results") + SendBadRequestResponse(w, r.URL.String(), "could not retrieve db results") return } @@ -2488,7 +2483,7 @@ func ApiValidatorLeaderboard(w http.ResponseWriter, r *http.Request) { FROM validator_performance ORDER BY rank7d DESC LIMIT 100`) if err != nil { - sendErrorResponse(w, r.URL.String(), "could not retrieve db results") + SendBadRequestResponse(w, r.URL.String(), "could not retrieve db results") return } defer rows.Close() @@ -2512,7 +2507,7 @@ func ApiValidatorDeposits(w http.ResponseWriter, r *http.Request) { pubkeys, err := parseApiValidatorParamToPubkeys(vars["indexOrPubkey"], maxValidators) if err != nil { - sendErrorResponse(w, r.URL.String(), err.Error()) + SendBadRequestResponse(w, r.URL.String(), err.Error()) return } @@ -2522,7 +2517,7 @@ func ApiValidatorDeposits(w http.ResponseWriter, r *http.Request) { ) if err != nil { logger.WithError(err).Error("could not retrieve db results") - sendErrorResponse(w, r.URL.String(), "could not retrieve db results") + SendBadRequestResponse(w, r.URL.String(), "could not retrieve db results") return } defer rows.Close() @@ -2548,13 +2543,13 @@ func ApiValidatorAttestations(w http.ResponseWriter, r *http.Request) { queryIndices, err := parseApiValidatorParamToIndices(vars["indexOrPubkey"], maxValidators) if err != nil { - sendErrorResponse(w, r.URL.String(), err.Error()) + SendBadRequestResponse(w, r.URL.String(), err.Error()) return } history, err := db.BigtableClient.GetValidatorAttestationHistory(queryIndices, services.LatestEpoch()-99, services.LatestEpoch()) if err != nil { - sendErrorResponse(w, r.URL.String(), "could not retrieve db results") + SendBadRequestResponse(w, r.URL.String(), "could not retrieve db results") return } @@ -2622,14 +2617,14 @@ func ApiValidatorProposals(w http.ResponseWriter, r *http.Request) { var err error epochQuery, err = strconv.ParseUint(q.Get("epoch"), 10, 64) if err != nil { - sendErrorResponse(w, r.URL.String(), err.Error()) + SendBadRequestResponse(w, r.URL.String(), err.Error()) return } } queryIndices, err := parseApiValidatorParamToIndices(vars["indexOrPubkey"], maxValidators) if err != nil { - sendErrorResponse(w, r.URL.String(), err.Error()) + SendBadRequestResponse(w, r.URL.String(), err.Error()) return } if epochQuery < 100 { @@ -2680,7 +2675,7 @@ func ApiValidatorProposals(w http.ResponseWriter, r *http.Request) { ORDER BY proposer, epoch desc, slot desc`, pq.Array(queryIndices), epochQuery, epochQuery-100) if err != nil { logger.Errorf("could not retrieve db results: %v", err) - sendErrorResponse(w, r.URL.String(), "could not retrieve db results") + SendBadRequestResponse(w, r.URL.String(), "could not retrieve db results") return } @@ -2719,7 +2714,7 @@ func ApiGraffitiwall(w http.ResponseWriter, r *http.Request) { endSlot, err = strconv.ParseUint(q.Get("slot"), 10, 64) if err != nil { // logger.WithError(err).Errorf("invalid slot provided: %v", err) - sendErrorResponse(w, r.URL.String(), "invalid slot provided") + SendBadRequestResponse(w, r.URL.String(), "invalid slot provided") return } } @@ -2732,12 +2727,12 @@ func ApiGraffitiwall(w http.ResponseWriter, r *http.Request) { startSlot, err = strconv.ParseUint(q.Get("startSlot"), 10, 64) if err != nil { // logger.WithError(err).Errorf("invalid startSlot provided: %v", err) - sendErrorResponse(w, r.URL.String(), "invalid startSlot provided") + SendBadRequestResponse(w, r.URL.String(), "invalid startSlot provided") return } if startSlot > endSlot { // logger.Errorf("start slot greater than end slot") - sendErrorResponse(w, r.URL.String(), "start slot greater than end slot") + SendBadRequestResponse(w, r.URL.String(), "start slot greater than end slot") return } } @@ -2752,7 +2747,7 @@ func ApiGraffitiwall(w http.ResponseWriter, r *http.Request) { if startX > endX || startY > endY { // logger.Error("invalid area provided by the coordinates") - sendErrorResponse(w, r.URL.String(), "invalid area provided by the coordinates") + SendBadRequestResponse(w, r.URL.String(), "invalid area provided by the coordinates") return } @@ -2763,7 +2758,7 @@ func ApiGraffitiwall(w http.ResponseWriter, r *http.Request) { summarize, err = strconv.ParseBool(summarizeParam) if err != nil { // logger.WithError(err).Errorf("invalid value for summarize provided: %v", err) - sendErrorResponse(w, r.URL.String(), "invalid value for summarize provided") + SendBadRequestResponse(w, r.URL.String(), "invalid value for summarize provided") return } } @@ -2788,7 +2783,7 @@ func ApiGraffitiwall(w http.ResponseWriter, r *http.Request) { if !errors.Is(err, sql.ErrNoRows) { logger.WithError(err).Error("could not retrieve db results") } - sendErrorResponse(w, r.URL.String(), "could not retrieve db results") + SendBadRequestResponse(w, r.URL.String(), "could not retrieve db results") return } defer rows.Close() @@ -2813,7 +2808,7 @@ func ApiChart(w http.ResponseWriter, r *http.Request) { var image []byte err := db.ReaderDb.Get(&image, "SELECT image FROM chart_images WHERE name = $1", chartName) if err != nil { - sendErrorResponse(w, r.URL.String(), "no data available for the requested chart") + SendBadRequestResponse(w, r.URL.String(), "no data available for the requested chart") return } @@ -2821,7 +2816,7 @@ func ApiChart(w http.ResponseWriter, r *http.Request) { _, err = w.Write(image) if err != nil { - sendErrorResponse(w, r.URL.String(), "error writing chart data") + SendBadRequestResponse(w, r.URL.String(), "error writing chart data") return } } @@ -3021,7 +3016,7 @@ func MobileNotificationUpdatePOST(w http.ResponseWriter, r *http.Request) { err2 := db.MobileNotificatonTokenUpdate(claims.UserID, claims.DeviceID, notifyToken) if err2 != nil { - sendErrorResponse(w, r.URL.String(), "Can not save notify token") + SendBadRequestResponse(w, r.URL.String(), "Can not save notify token") return } @@ -3039,7 +3034,7 @@ func RegisterEthpoolSubscription(w http.ResponseWriter, r *http.Request) { if signature != localSignature { w.WriteHeader(http.StatusBadRequest) logger.Errorf("signature mismatch %v | %v", signature, localSignature) - sendErrorResponse(w, r.URL.String(), "Unauthorized: signature not valid") + SendBadRequestResponse(w, r.URL.String(), "Unauthorized: signature not valid") return } @@ -3072,7 +3067,7 @@ func RegisterEthpoolSubscription(w http.ResponseWriter, r *http.Request) { if err != nil { logger.Errorf("could not save subscription data %v", err) w.WriteHeader(http.StatusInternalServerError) - sendErrorResponse(w, r.URL.String(), "Can not save subscription data") + SendBadRequestResponse(w, r.URL.String(), "Can not save subscription data") return } @@ -3095,7 +3090,7 @@ func RegisterMobileSubscriptions(w http.ResponseWriter, r *http.Request) { if err != nil { logger.Errorf("error parsing body | err: %v", err) - sendErrorResponse(w, r.URL.String(), "could not parse body") + SendBadRequestResponse(w, r.URL.String(), "could not parse body") return } @@ -3130,13 +3125,13 @@ func RegisterMobileSubscriptions(w http.ResponseWriter, r *http.Request) { err = db.InsertMobileSubscription(nil, claims.UserID, parsedBase, parsedBase.Transaction.Type, parsedBase.Transaction.Receipt, validationResult.ExpirationDate, validationResult.RejectReason, "") if err != nil { logger.Errorf("could not save subscription data %v", err) - sendErrorResponse(w, r.URL.String(), "Can not save subscription data") + SendBadRequestResponse(w, r.URL.String(), "Can not save subscription data") return } if !parsedBase.Valid { logger.Errorf("receipt is not valid %v", validationResult.RejectReason) - sendErrorResponse(w, r.URL.String(), "receipt is not valid") + SendBadRequestResponse(w, r.URL.String(), "receipt is not valid") return } @@ -3213,7 +3208,7 @@ func GetMobileWidgetStatsPost(w http.ResponseWriter, r *http.Request) { var parsedBody types.DashboardRequest err := decoder.Decode(&parsedBody) if err != nil { - sendErrorResponse(w, r.URL.String(), "could not read body") + SendBadRequestResponse(w, r.URL.String(), "could not read body") return } @@ -3232,14 +3227,10 @@ func GetMobileWidgetStats(w http.ResponseWriter, r *http.Request, indexOrPubkey epoch = 0 } prime := getUserPremium(r) - // if !prime.WidgetSupport { - // sendErrorResponse(w, r.URL.String(), "feature only available for premium users") - // return - // } queryIndices, err := parseApiValidatorParamToIndices(indexOrPubkey, prime.MaxValidators) if err != nil { - sendErrorResponse(w, r.URL.String(), err.Error()) + SendBadRequestResponse(w, r.URL.String(), err.Error()) return } @@ -3289,31 +3280,31 @@ func GetMobileWidgetStats(w http.ResponseWriter, r *http.Request, indexOrPubkey defer efficiencyRows.Close() } if err != nil { - sendErrorResponse(w, r.URL.String(), err.Error()) + SendBadRequestResponse(w, r.URL.String(), err.Error()) return } generalData, err := utils.SqlRowsToJSON(validatorRows) if err != nil { - sendErrorResponse(w, r.URL.String(), "could not parse db results") + SendBadRequestResponse(w, r.URL.String(), "could not parse db results") return } balances, err := db.BigtableClient.GetValidatorBalanceHistory(queryIndices, uint64(epoch), uint64(epoch)) if err != nil { - sendErrorResponse(w, r.URL.String(), "error retrieving validator balance data") + SendBadRequestResponse(w, r.URL.String(), "error retrieving validator balance data") return } lastAttestationSlots, err := db.BigtableClient.GetLastAttestationSlots(queryIndices) if err != nil { - sendErrorResponse(w, r.URL.String(), "error retrieving validator balance data") + SendBadRequestResponse(w, r.URL.String(), "error retrieving validator balance data") return } currentDayIncome, err := db.GetCurrentDayClIncome(queryIndices) if err != nil { - sendErrorResponse(w, r.URL.String(), "error retrieving current day income") + SendBadRequestResponse(w, r.URL.String(), "error retrieving current day income") return } @@ -3348,7 +3339,7 @@ func GetMobileWidgetStats(w http.ResponseWriter, r *http.Request, indexOrPubkey efficiencyData, err := getValidatorEffectiveness(services.LatestEpoch()-1, queryIndices) if err != nil { - sendErrorResponse(w, r.URL.String(), "could not parse db results") + SendBadRequestResponse(w, r.URL.String(), "could not parse db results") return } @@ -3360,7 +3351,7 @@ func GetMobileWidgetStats(w http.ResponseWriter, r *http.Request, indexOrPubkey } j := json.NewEncoder(w) - sendOKResponse(j, r.URL.String(), []any{data}) + SendOKResponse(j, r.URL.String(), []any{data}) } // MobileDeviceSettings godoc @@ -3380,7 +3371,7 @@ func MobileDeviceSettings(w http.ResponseWriter, r *http.Request) { rows, err := db.MobileDeviceSettingsSelect(claims.UserID, claims.DeviceID) if err != nil { - sendErrorResponse(w, r.URL.String(), "could not retrieve db results") + SendBadRequestResponse(w, r.URL.String(), "could not retrieve db results") return } @@ -3415,13 +3406,13 @@ func MobileDeviceSettingsPOST(w http.ResponseWriter, r *http.Request) { temp, err := strconv.ParseUint(customDeviceID, 10, 64) if err != nil { logger.Errorf("error parsing id %v | err: %v", customDeviceID, err) - sendErrorResponse(w, r.URL.String(), "could not parse id") + SendBadRequestResponse(w, r.URL.String(), "could not parse id") return } userDeviceID = temp sessionUser := getUser(r) if !sessionUser.Authenticated { - sendErrorResponse(w, r.URL.String(), "not authenticated") + SendBadRequestResponse(w, r.URL.String(), "not authenticated") return } userID = sessionUser.UserID @@ -3433,7 +3424,7 @@ func MobileDeviceSettingsPOST(w http.ResponseWriter, r *http.Request) { rows, err := db.MobileDeviceSettingsUpdate(userID, userDeviceID, notifyEnabled, active) if err != nil { logger.Errorf("could not retrieve db results err: %v", err) - sendErrorResponse(w, r.URL.String(), "could not retrieve db results") + SendBadRequestResponse(w, r.URL.String(), "could not retrieve db results") return } @@ -3468,7 +3459,7 @@ func MobileTagedValidators(w http.ResponseWriter, r *http.Request) { validators, err2 := db.GetTaggedValidators(filter) if err2 != nil { - sendErrorResponse(w, r.URL.String(), "could not retrieve db results") + SendBadRequestResponse(w, r.URL.String(), "could not retrieve db results") return } @@ -3480,7 +3471,7 @@ func MobileTagedValidators(w http.ResponseWriter, r *http.Request) { data[i] = temp } - sendOKResponse(j, r.URL.String(), data) + SendOKResponse(j, r.URL.String(), data) } func parseUintWithDefault(input string, defaultValue uint64) uint64 { @@ -3521,21 +3512,21 @@ func ClientStats(w http.ResponseWriter, r *http.Request) { system, err := db.BigtableClient.GetMachineMetricsSystem(claims.UserID, int(limit), int(offset)) if err != nil { logger.Errorf("sytem stat error : %v", err) - sendErrorResponse(w, r.URL.String(), "could not retrieve system stats from db") + SendBadRequestResponse(w, r.URL.String(), "could not retrieve system stats from db") return } validator, err := db.BigtableClient.GetMachineMetricsValidator(claims.UserID, int(limit), int(offset)) if err != nil { logger.Errorf("validator stat error : %v", err) - sendErrorResponse(w, r.URL.String(), "could not retrieve validator stats from db") + SendBadRequestResponse(w, r.URL.String(), "could not retrieve validator stats from db") return } node, err := db.BigtableClient.GetMachineMetricsNode(claims.UserID, int(limit), int(offset)) if err != nil { logger.Errorf("node stat error : %v", err) - sendErrorResponse(w, r.URL.String(), "could not retrieve beaconnode stats from db") + SendBadRequestResponse(w, r.URL.String(), "could not retrieve beaconnode stats from db") return } @@ -3545,7 +3536,7 @@ func ClientStats(w http.ResponseWriter, r *http.Request) { System: system, } - sendOKResponse(j, r.URL.String(), []interface{}{data}) + SendOKResponse(j, r.URL.String(), []interface{}{data}) } // ClientStatsPost godoc @@ -3580,20 +3571,20 @@ func clientStatsPost(w http.ResponseWriter, r *http.Request, apiKey, machine str w.Header().Set("Content-Type", "application/json") if utils.Config.Frontend.DisableStatsInserts { - sendErrorResponse(w, r.URL.String(), "service temporarily unavailable") + SendBadRequestResponse(w, r.URL.String(), "service temporarily unavailable") return } userData, err := db.GetUserIdByApiKey(apiKey) if err != nil { - sendErrorResponse(w, r.URL.String(), "no user found with api key") + SendBadRequestResponse(w, r.URL.String(), "no user found with api key") return } body, err := io.ReadAll(r.Body) if err != nil { logger.Warnf("error reading body | err: %v", err) - sendErrorResponse(w, r.URL.String(), "could not read body") + SendBadRequestResponse(w, r.URL.String(), "could not read body") return } @@ -3604,7 +3595,7 @@ func clientStatsPost(w http.ResponseWriter, r *http.Request, apiKey, machine str err = json.Unmarshal(body, &jsonObject) if err != nil { logger.Warnf("Could not parse stats (meta stats) general | %v ", err) - sendErrorResponse(w, r.URL.String(), "Invalid JSON format in request body") + SendBadRequestResponse(w, r.URL.String(), "Invalid JSON format in request body") return } jsonObjects = []map[string]interface{}{jsonObject} @@ -3612,7 +3603,7 @@ func clientStatsPost(w http.ResponseWriter, r *http.Request, apiKey, machine str if len(jsonObjects) >= 10 { logger.Info("Max number of stat entries are 10", err) - sendErrorResponse(w, r.URL.String(), "Max number of stat entries are 10") + SendBadRequestResponse(w, r.URL.String(), "Max number of stat entries are 10") return } @@ -3649,19 +3640,19 @@ func insertStats(userData *types.UserWithPremium, machine string, body *map[stri err := mapstructure.Decode(body, &parsedMeta) if err != nil { logger.Warnf("Could not parse stats (meta stats) | %v ", err) - sendErrorResponse(w, r.URL.String(), "could not parse meta") + SendBadRequestResponse(w, r.URL.String(), "could not parse meta") return err } parsedMeta.Machine = machine if parsedMeta.Version > 2 || parsedMeta.Version <= 0 { - sendErrorResponse(w, r.URL.String(), "this version is not supported") + SendBadRequestResponse(w, r.URL.String(), "this version is not supported") return fmt.Errorf("this version is not supported") } if parsedMeta.Process != "validator" && parsedMeta.Process != "beaconnode" && parsedMeta.Process != "slasher" && parsedMeta.Process != "system" { - sendErrorResponse(w, r.URL.String(), "unknown process") + SendBadRequestResponse(w, r.URL.String(), "unknown process") return fmt.Errorf("unknown process") } @@ -3670,7 +3661,7 @@ func insertStats(userData *types.UserWithPremium, machine string, body *map[stri count, err := db.BigtableClient.GetMachineMetricsMachineCount(userData.ID) if err != nil { logger.Errorf("Could not get max machine count| %v", err) - sendErrorResponse(w, r.URL.String(), "could not get machine count") + SendBadRequestResponse(w, r.URL.String(), "could not get machine count") return err } @@ -3685,13 +3676,13 @@ func insertStats(userData *types.UserWithPremium, machine string, body *map[stri err = DecodeMapStructure(body, &parsedResponse) if err != nil { logger.Warnf("Could not parse stats (system stats) | %v", err) - sendErrorResponse(w, r.URL.String(), "could not parse system") + SendBadRequestResponse(w, r.URL.String(), "could not parse system") return err } data, err = proto.Marshal(parsedResponse) if err != nil { logger.Errorf("Could not parse stats (system stats) | %v", err) - sendErrorResponse(w, r.URL.String(), "could marshal system") + SendBadRequestResponse(w, r.URL.String(), "could marshal system") return err } } else if parsedMeta.Process == "validator" { @@ -3699,13 +3690,13 @@ func insertStats(userData *types.UserWithPremium, machine string, body *map[stri err = DecodeMapStructure(body, &parsedResponse) if err != nil { logger.Warnf("Could not parse stats (validator stats) | %v", err) - sendErrorResponse(w, r.URL.String(), "could marshal validator") + SendBadRequestResponse(w, r.URL.String(), "could marshal validator") return err } data, err = proto.Marshal(parsedResponse) if err != nil { logger.Errorf("Could not parse stats (validator stats) | %v", err) - sendErrorResponse(w, r.URL.String(), "could marshal validator") + SendBadRequestResponse(w, r.URL.String(), "could marshal validator") return err } } else if parsedMeta.Process == "beaconnode" { @@ -3713,13 +3704,13 @@ func insertStats(userData *types.UserWithPremium, machine string, body *map[stri err = DecodeMapStructure(body, &parsedResponse) if err != nil { logger.Warnf("Could not parse stats (beaconnode stats) | %v", err) - sendErrorResponse(w, r.URL.String(), "could not parse beaconnode") + SendBadRequestResponse(w, r.URL.String(), "could not parse beaconnode") return err } data, err = proto.Marshal(parsedResponse) if err != nil { logger.Errorf("Could not parse stats (beaconnode stats) | %v", err) - sendErrorResponse(w, r.URL.String(), "could not parse beaconnode") + SendBadRequestResponse(w, r.URL.String(), "could not parse beaconnode") return err } } @@ -3730,7 +3721,7 @@ func insertStats(userData *types.UserWithPremium, machine string, body *map[stri return err } logger.Errorf("Could not store stats | %v", err) - sendErrorResponse(w, r.URL.String(), fmt.Sprintf("could not store stats: %v", err)) + SendBadRequestResponse(w, r.URL.String(), fmt.Sprintf("could not store stats: %v", err)) return err } return nil @@ -3758,7 +3749,7 @@ func ApiWithdrawalCredentialsValidators(w http.ResponseWriter, r *http.Request) if !utils.IsValidEth1Address(credentialsOrAddressString) && !utils.IsValidWithdrawalCredentials(credentialsOrAddressString) { - sendErrorResponse(w, r.URL.String(), "invalid withdrawal credentials or eth1 address provided") + SendBadRequestResponse(w, r.URL.String(), "invalid withdrawal credentials or eth1 address provided") return } @@ -3799,7 +3790,7 @@ func ApiWithdrawalCredentialsValidators(w http.ResponseWriter, r *http.Request) if err != nil { logger.Warnf("error retrieving validator data from db: %v", err) - sendErrorResponse(w, r.URL.String(), "could not retrieve db results") + SendBadRequestResponse(w, r.URL.String(), "could not retrieve db results") return } @@ -3811,7 +3802,7 @@ func ApiWithdrawalCredentialsValidators(w http.ResponseWriter, r *http.Request) }) } - sendOKResponse(json.NewEncoder(w), r.URL.String(), []interface{}{response}) + SendOKResponse(json.NewEncoder(w), r.URL.String(), []interface{}{response}) } // ApiProposalLuck godoc @@ -3832,20 +3823,20 @@ func ApiProposalLuck(w http.ResponseWriter, r *http.Request) { indices, pubkeys, err := parseValidatorsFromQueryString(q.Get("validators"), 100) if err != nil { - sendErrorResponse(w, r.URL.String(), "could not parse validators") + SendBadRequestResponse(w, r.URL.String(), "could not parse validators") return } if len(pubkeys) > 0 { indicesFromPubkeys, err := resolveIndices(pubkeys) if err != nil { - sendErrorResponse(w, r.URL.String(), "could not resolve pubkeys to indices") + SendBadRequestResponse(w, r.URL.String(), "could not resolve pubkeys to indices") return } indices = append(indices, indicesFromPubkeys...) } if len(indices) == 0 { - sendErrorResponse(w, r.URL.String(), "no validators provided") + SendBadRequestResponse(w, r.URL.String(), "no validators provided") return } @@ -3968,7 +3959,7 @@ func APIDashboardDataBalance(w http.ResponseWriter, r *http.Request) { } if len(queryValidatorIndices) == 0 { - sendErrorResponse(w, r.URL.String(), "no or invalid validator indicies provided") + SendBadRequestResponse(w, r.URL.String(), "no or invalid validator indicies provided") } balances, err := db.BigtableClient.GetValidatorBalanceHistory(queryValidatorIndices, latestEpoch-queryOffsetEpoch, latestEpoch) @@ -4037,17 +4028,17 @@ func returnQueryResults(rows *sql.Rows, w http.ResponseWriter, r *http.Request, j := json.NewEncoder(w) data, err := utils.SqlRowsToJSON(rows) if err != nil { - sendErrorResponse(w, r.URL.String(), "could not parse db results") + SendBadRequestResponse(w, r.URL.String(), "could not parse db results") return } err = adjustQueryResults(data, adjustQueryEntriesFuncs...) if err != nil { - sendErrorResponse(w, r.URL.String(), "could not adjust query results") + SendBadRequestResponse(w, r.URL.String(), "could not adjust query results") return } - sendOKResponse(j, r.URL.String(), data) + SendOKResponse(j, r.URL.String(), data) } // Saves the result of a query converted to JSON in the response writer as an array. @@ -4056,13 +4047,13 @@ func returnQueryResultsAsArray(rows *sql.Rows, w http.ResponseWriter, r *http.Re data, err := utils.SqlRowsToJSON(rows) if err != nil { - sendErrorResponse(w, r.URL.String(), "could not parse db results") + SendBadRequestResponse(w, r.URL.String(), "could not parse db results") return } err = adjustQueryResults(data, adjustQueryEntriesFuncs...) if err != nil { - sendErrorResponse(w, r.URL.String(), "could not adjust query results") + SendBadRequestResponse(w, r.URL.String(), "could not adjust query results") return } @@ -4095,17 +4086,12 @@ func adjustQueryResults(data []interface{}, adjustQueryEntriesFuncs ...func(map[ return nil } -// SendErrorResponse exposes sendErrorResponse -func SendErrorResponse(w http.ResponseWriter, route, message string) { - sendErrorResponse(w, route, message) -} - -func sendErrorResponse(w http.ResponseWriter, route, message string) { - sendErrorWithCodeResponse(w, route, message, 400) +func SendBadRequestResponse(w http.ResponseWriter, route, message string) { + sendErrorWithCodeResponse(w, route, message, http.StatusBadRequest) } func sendServerErrorResponse(w http.ResponseWriter, route, message string) { - sendErrorWithCodeResponse(w, route, message, 500) + sendErrorWithCodeResponse(w, route, message, http.StatusInternalServerError) } func sendErrorWithCodeResponse(w http.ResponseWriter, route, message string, errorcode int) { @@ -4120,12 +4106,7 @@ func sendErrorWithCodeResponse(w http.ResponseWriter, route, message string, err } } -// SendOKResponse exposes sendOKResponse func SendOKResponse(j *json.Encoder, route string, data []interface{}) { - sendOKResponse(j, route, data) -} - -func sendOKResponse(j *json.Encoder, route string, data []interface{}) { response := &types.ApiResponse{} response.Status = "OK" diff --git a/handlers/api_eth1.go b/handlers/api_eth1.go index fd824d28bc..d8508a87ea 100644 --- a/handlers/api_eth1.go +++ b/handlers/api_eth1.go @@ -39,13 +39,13 @@ func ApiEth1Deposit(w http.ResponseWriter, r *http.Request) { eth1TxHash, err := hex.DecodeString(strings.Replace(vars["txhash"], "0x", "", -1)) if err != nil { - sendErrorResponse(w, r.URL.String(), "invalid eth1 tx hash provided") + SendBadRequestResponse(w, r.URL.String(), "invalid eth1 tx hash provided") return } rows, err := db.ReaderDb.Query("SELECT amount, block_number, block_ts, from_address, merkletree_index, publickey, removed, signature, tx_hash, tx_index, tx_input, valid_signature, withdrawal_credentials FROM eth1_deposits WHERE tx_hash = $1", eth1TxHash) if err != nil { - sendErrorResponse(w, r.URL.String(), "could not retrieve db results") + SendBadRequestResponse(w, r.URL.String(), "could not retrieve db results") return } defer rows.Close() @@ -73,41 +73,41 @@ func ApiETH1ExecBlocks(w http.ResponseWriter, r *http.Request) { for _, split := range splits { temp, err := strconv.ParseUint(split, 10, 64) if err != nil { - sendErrorResponse(w, r.URL.String(), "invalid block number") + SendBadRequestResponse(w, r.URL.String(), "invalid block number") return } blockList = append(blockList, temp) } if len(blockList) > int(limit) { - sendErrorResponse(w, r.URL.String(), fmt.Sprintf("only a maximum of %d query parameters are allowed", limit)) + SendBadRequestResponse(w, r.URL.String(), fmt.Sprintf("only a maximum of %d query parameters are allowed", limit)) return } blocks, err := db.BigtableClient.GetBlocksIndexedMultiple(blockList, limit) if err != nil { logger.Errorf("Can not retrieve blocks from bigtable %v", err) - sendErrorResponse(w, r.URL.String(), "can not retrieve blocks from bigtable") + SendBadRequestResponse(w, r.URL.String(), "can not retrieve blocks from bigtable") return } _, beaconDataMap, err := findExecBlockNumbersByExecBlockNumber(blockList, 0, limit) if err != nil { - sendErrorResponse(w, r.URL.String(), "can not retrieve proposer information") + SendBadRequestResponse(w, r.URL.String(), "can not retrieve proposer information") return } relaysData, err := db.GetRelayDataForIndexedBlocks(blocks) if err != nil { logger.Errorf("can not load mev data %v", err) - sendErrorResponse(w, r.URL.String(), "can not retrieve mev data") + SendBadRequestResponse(w, r.URL.String(), "can not retrieve mev data") return } results := formatBlocksForApiResponse(blocks, relaysData, beaconDataMap, nil) j := json.NewEncoder(w) - sendOKResponse(j, r.URL.String(), []interface{}{results}) + SendOKResponse(j, r.URL.String(), []interface{}{results}) } // ApiETH1AccountProposedBlocks godoc @@ -131,7 +131,7 @@ func ApiETH1AccountProducedBlocks(w http.ResponseWriter, r *http.Request) { maxValidators := getUserPremium(r).MaxValidators addresses, indices, err := getAddressesOrIndicesFromAddressIndexOrPubkey(vars["addressIndexOrPubkey"], maxValidators) if err != nil { - sendErrorResponse( + SendBadRequestResponse( w, r.URL.String(), fmt.Sprintf("invalid address, validator index or pubkey or exceeded max of %v params", maxValidators), @@ -140,7 +140,7 @@ func ApiETH1AccountProducedBlocks(w http.ResponseWriter, r *http.Request) { } if len(addresses) > 20 { - sendErrorResponse( + SendBadRequestResponse( w, r.URL.String(), "you are only allowed to query up to max 20 addresses", @@ -177,7 +177,7 @@ func ApiETH1AccountProducedBlocks(w http.ResponseWriter, r *http.Request) { if len(addresses) > 0 { blockListSub, beaconDataMapSub, err := findExecBlockNumbersByFeeRecipient(addresses, offset, limit, isSortAsc) if err != nil { - sendErrorResponse(w, r.URL.String(), "can not retrieve blocks from database") + SendBadRequestResponse(w, r.URL.String(), "can not retrieve blocks from database") return } blockList = append(blockList, blockListSub...) @@ -189,7 +189,7 @@ func ApiETH1AccountProducedBlocks(w http.ResponseWriter, r *http.Request) { if len(indices) > 0 { blockListSub, beaconDataMapSub, err := findExecBlockNumbersByProposerIndex(indices, offset, limit, isSortAsc, false, 0) if err != nil { - sendErrorResponse(w, r.URL.String(), "can not retrieve blocks from database") + SendBadRequestResponse(w, r.URL.String(), "can not retrieve blocks from database") return } blockList = append(blockList, blockListSub...) @@ -222,14 +222,14 @@ func ApiETH1AccountProducedBlocks(w http.ResponseWriter, r *http.Request) { blocks, err := db.BigtableClient.GetBlocksIndexedMultiple(blockList, uint64(limit)) if err != nil { logger.Errorf("Can not retrieve blocks from bigtable %v", err) - sendErrorResponse(w, r.URL.String(), "can not retrieve blocks from bigtable") + SendBadRequestResponse(w, r.URL.String(), "can not retrieve blocks from bigtable") return } relaysData, err := db.GetRelayDataForIndexedBlocks(blocks) if err != nil { logger.Errorf("can not load mev data %v", err) - sendErrorResponse(w, r.URL.String(), "can not retrieve mev data") + SendBadRequestResponse(w, r.URL.String(), "can not retrieve mev data") return } @@ -241,7 +241,7 @@ func ApiETH1AccountProducedBlocks(w http.ResponseWriter, r *http.Request) { results := formatBlocksForApiResponse(blocks, relaysData, beaconDataMap, sortFunc) j := json.NewEncoder(w) - sendOKResponse(j, r.URL.String(), []interface{}{results}) + SendOKResponse(j, r.URL.String(), []interface{}{results}) } // ApiETH1GasNowData godoc @@ -261,7 +261,7 @@ func ApiEth1GasNowData(w http.ResponseWriter, r *http.Request) { if gasnowData == nil { logger.Errorf("error gasnow data is not defined. The frontend updater might not be running.") - sendErrorResponse(w, r.URL.String(), "error gasnow data is currently not available.") + SendBadRequestResponse(w, r.URL.String(), "error gasnow data is currently not available.") return } @@ -271,7 +271,7 @@ func ApiEth1GasNowData(w http.ResponseWriter, r *http.Request) { err := json.NewEncoder(w).Encode(gasnowData) if err != nil { logger.Errorf("error gasnow data is not defined. The frontend updater might not be running.") - sendErrorResponse(w, r.URL.String(), "error gasnow data is currently not available.") + SendBadRequestResponse(w, r.URL.String(), "error gasnow data is currently not available.") return } } @@ -298,7 +298,7 @@ func ApiEth1Address(w http.ResponseWriter, r *http.Request) { address = strings.ToLower(address) if !utils.IsEth1Address(address) { - sendErrorResponse(w, r.URL.String(), "error invalid address. An Ethereum address consists of an optional 0x prefix followed by 40 hexadecimal characters.") + SendBadRequestResponse(w, r.URL.String(), "error invalid address. An Ethereum address consists of an optional 0x prefix followed by 40 hexadecimal characters.") return } token := q.Get("token") @@ -307,7 +307,7 @@ func ApiEth1Address(w http.ResponseWriter, r *http.Request) { token = strings.Replace(token, "0x", "", -1) token = strings.ToLower(token) if !utils.IsEth1Address(token) { - sendErrorResponse(w, r.URL.String(), "error invalid token query param. A token address consists of an optional 0x prefix followed by 40 hexadecimal characters.") + SendBadRequestResponse(w, r.URL.String(), "error invalid token query param. A token address consists of an optional 0x prefix followed by 40 hexadecimal characters.") return } } @@ -336,7 +336,7 @@ func ApiEth1Address(w http.ResponseWriter, r *http.Request) { }) } - sendOKResponse(json.NewEncoder(w), r.URL.String(), []interface{}{response}) + SendOKResponse(json.NewEncoder(w), r.URL.String(), []interface{}{response}) } // ApiEth1AddressERC20Tokens godoc @@ -363,7 +363,7 @@ func ApiEth1AddressERC20Tokens(w http.ResponseWriter, r *http.Request) { address = strings.ToLower(address) if !utils.IsEth1Address(address) { - sendErrorResponse(w, r.URL.String(), "error invalid address. An Ethereum address consists of an optional 0x prefix followed by 40 hexadecimal characters.") + SendBadRequestResponse(w, r.URL.String(), "error invalid address. An Ethereum address consists of an optional 0x prefix followed by 40 hexadecimal characters.") return } @@ -405,7 +405,7 @@ func ApiEth1AddressERC20Tokens(w http.ResponseWriter, r *http.Request) { }) } - sendOKResponse(json.NewEncoder(w), r.URL.String(), []interface{}{response}) + SendOKResponse(json.NewEncoder(w), r.URL.String(), []interface{}{response}) } func formatBlocksForApiResponse(blocks []*types.Eth1BlockIndexed, relaysData map[common.Hash]types.RelaysData, beaconDataMap map[uint64]types.ExecBlockProposer, sortFunc func(i, j types.ExecutionBlockApiResponse) bool) []types.ExecutionBlockApiResponse { diff --git a/handlers/base.go b/handlers/base.go index f4840af7a4..a082dccd3d 100644 --- a/handlers/base.go +++ b/handlers/base.go @@ -50,7 +50,7 @@ func SetAutoContentType(w http.ResponseWriter, r *http.Request) { func ErrorOrJSONResponse(w http.ResponseWriter, r *http.Request, errorText string, statusCode int) { if IsMobileAuth(r) { w.WriteHeader(statusCode) - SendErrorResponse(w, r.URL.String(), errorText) + SendBadRequestResponse(w, r.URL.String(), errorText) } else { http.Error(w, errorText, statusCode) } diff --git a/handlers/charts.go b/handlers/charts.go index 8db3c05a16..e5fba0ba22 100644 --- a/handlers/charts.go +++ b/handlers/charts.go @@ -122,7 +122,7 @@ func GenericChartData(w http.ResponseWriter, r *http.Request) { chartsPageData := services.LatestChartsPageData() if chartsPageData == nil { utils.LogError(nil, "error getting chart page data", 0) - SendErrorResponse(w, r.URL.String(), "error getting chart page data") + SendBadRequestResponse(w, r.URL.String(), "error getting chart page data") return } @@ -135,11 +135,11 @@ func GenericChartData(w http.ResponseWriter, r *http.Request) { } if chartData == nil { - SendErrorResponse(w, r.URL.String(), fmt.Sprintf("error the chart you requested is not available. Chart: %v", chartVar)) + SendBadRequestResponse(w, r.URL.String(), fmt.Sprintf("error the chart you requested is not available. Chart: %v", chartVar)) return } - sendOKResponse(json.NewEncoder(w), r.URL.String(), []interface{}{chartData.Series}) + SendOKResponse(json.NewEncoder(w), r.URL.String(), []interface{}{chartData.Series}) } // SlotViz renders a single page with a d3 slot (block) visualisation diff --git a/handlers/dashboard.go b/handlers/dashboard.go index c2bfcc2a22..28c017d437 100644 --- a/handlers/dashboard.go +++ b/handlers/dashboard.go @@ -499,7 +499,7 @@ func DashboardDataBalanceCombined(w http.ResponseWriter, r *http.Request) { err = g.Wait() if err != nil { utils.LogError(err, "error while combining balance chart", 0, errFieldMap) - sendErrorResponse(w, r.URL.String(), err.Error()) + SendBadRequestResponse(w, r.URL.String(), err.Error()) return } diff --git a/handlers/ens.go b/handlers/ens.go index ba2922fb3a..9505c7bd5c 100644 --- a/handlers/ens.go +++ b/handlers/ens.go @@ -34,12 +34,12 @@ func ResolveEnsDomain(w http.ResponseWriter, r *http.Request) { if err != nil { logger.Warnf("failed to resolve ens %v: %v", search, err) - sendErrorResponse(w, r.URL.String(), "failed to resolve ens") + SendBadRequestResponse(w, r.URL.String(), "failed to resolve ens") return } j := json.NewEncoder(w) - sendOKResponse(j, r.URL.String(), []interface{}{data}) + SendOKResponse(j, r.URL.String(), []interface{}{data}) } func GetEnsDomain(search string) (*types.EnsDomainResponse, error) { diff --git a/handlers/user.go b/handlers/user.go index 926626419e..dc2d056070 100644 --- a/handlers/user.go +++ b/handlers/user.go @@ -1572,7 +1572,7 @@ func MultipleUsersNotificationsSubscribe(w http.ResponseWriter, r *http.Request) err := json.Unmarshal(context.Get(r, utils.JsonBodyNakedKey).([]byte), &jsonObjects) if err != nil { utils.LogError(err, "could not parse multiple notification subscription intent", 0, errFields) - sendErrorResponse(w, r.URL.String(), "could not parse request") + SendBadRequestResponse(w, r.URL.String(), "could not parse request") return } @@ -1580,7 +1580,7 @@ func MultipleUsersNotificationsSubscribe(w http.ResponseWriter, r *http.Request) if len(jsonObjects) > 100 { utils.LogError(nil, "multiple notification subscription: max number bundle subscribe is 100", 0) - sendErrorResponse(w, r.URL.String(), "Max number bundle subscribe is 100") + SendBadRequestResponse(w, r.URL.String(), "Max number bundle subscribe is 100") return } @@ -1619,20 +1619,20 @@ func MultipleUsersNotificationsSubscribeWeb(w http.ResponseWriter, r *http.Reque b, err := io.ReadAll(r.Body) if err != nil { logger.Errorf("error reading body %v URL: %v", err, r.URL.String()) - sendErrorResponse(w, r.URL.String(), "could not parse body") + SendBadRequestResponse(w, r.URL.String(), "could not parse body") return } err = json.Unmarshal(b, &jsonObjects) if err != nil { logger.Errorf("Could not parse multiple notification subscription intent | %v", err) - sendErrorResponse(w, r.URL.String(), "could not parse request") + SendBadRequestResponse(w, r.URL.String(), "could not parse request") return } if len(jsonObjects) > 100 { utils.LogError(nil, "Multiple notification subscription web: max number bundle subscribe is 100", 0) - sendErrorResponse(w, r.URL.String(), "Max number bundle subscribe is 100") + SendBadRequestResponse(w, r.URL.String(), "Max number bundle subscribe is 100") return } @@ -1813,7 +1813,7 @@ func MultipleUsersNotificationsUnsubscribe(w http.ResponseWriter, r *http.Reques err := json.Unmarshal(context.Get(r, utils.JsonBodyNakedKey).([]byte), &jsonObjects) if err != nil { utils.LogError(err, "Could not parse multiple notification unsubscription intent", 0, errFields) - sendErrorResponse(w, r.URL.String(), "could not parse request") + SendBadRequestResponse(w, r.URL.String(), "could not parse request") return } @@ -1821,7 +1821,7 @@ func MultipleUsersNotificationsUnsubscribe(w http.ResponseWriter, r *http.Reques if len(jsonObjects) > 100 { utils.LogError(nil, "multiple notification unsubscription: Max number bundle unsubscribe is 100", 0, errFields) - sendErrorResponse(w, r.URL.String(), "Max number bundle unsubscribe is 100") + SendBadRequestResponse(w, r.URL.String(), "Max number bundle unsubscribe is 100") return } @@ -2110,7 +2110,7 @@ func UserNotificationsSubscribed(w http.ResponseWriter, r *http.Request) { q := r.URL.Query() sessionUser := getUser(r) if !sessionUser.Authenticated { - sendErrorResponse(w, r.URL.String(), "not authenticated") + SendBadRequestResponse(w, r.URL.String(), "not authenticated") return } @@ -2120,7 +2120,7 @@ func UserNotificationsSubscribed(w http.ResponseWriter, r *http.Request) { err := decoder.Decode(req) if err != nil && err != io.EOF { logger.WithError(err).Error("error decoding request body") - sendErrorResponse(w, r.URL.String(), "error decoding request body") + SendBadRequestResponse(w, r.URL.String(), "error decoding request body") return } @@ -2150,14 +2150,14 @@ func UserNotificationsSubscribed(w http.ResponseWriter, r *http.Request) { if lim != "" { limit, err = strconv.ParseUint(lim, 10, 64) if err != nil { - sendErrorResponse(w, r.URL.String(), "error parsing limit") + SendBadRequestResponse(w, r.URL.String(), "error parsing limit") } } if off != "" { offset, err = strconv.ParseUint(off, 10, 64) if err != nil { - sendErrorResponse(w, r.URL.String(), "error parsing offset") + SendBadRequestResponse(w, r.URL.String(), "error parsing offset") } } @@ -2174,7 +2174,7 @@ func UserNotificationsSubscribed(w http.ResponseWriter, r *http.Request) { n, err := types.EventNameFromString(en) if err != nil { logger.WithError(err).Errorf("error parsing provided event %v to a known event name type", en) - sendErrorResponse(w, r.URL.String(), "error invalid event name provided") + SendBadRequestResponse(w, r.URL.String(), "error invalid event name provided") } eventNames = append(eventNames, n) } @@ -2194,11 +2194,11 @@ func UserNotificationsSubscribed(w http.ResponseWriter, r *http.Request) { subs, err := db.GetSubscriptions(queryFilter) if err != nil { - sendErrorResponse(w, r.URL.String(), "not authenticated") + SendBadRequestResponse(w, r.URL.String(), "not authenticated") return } - sendOKResponse(j, r.URL.String(), []interface{}{subs}) + SendOKResponse(j, r.URL.String(), []interface{}{subs}) } func MobileDeviceDeletePOST(w http.ResponseWriter, r *http.Request) { @@ -2215,29 +2215,29 @@ func MobileDeviceDeletePOST(w http.ResponseWriter, r *http.Request) { temp, err := strconv.ParseUint(customDeviceID, 10, 64) if err != nil { logger.Errorf("error parsing id %v | err: %v", customDeviceID, err) - sendErrorResponse(w, r.URL.String(), "could not parse id") + SendBadRequestResponse(w, r.URL.String(), "could not parse id") return } userDeviceID = temp sessionUser := getUser(r) if !sessionUser.Authenticated { - sendErrorResponse(w, r.URL.String(), "not authenticated") + SendBadRequestResponse(w, r.URL.String(), "not authenticated") return } userID = sessionUser.UserID } else { - sendErrorResponse(w, r.URL.String(), "you can not delete the device you are currently signed in with") + SendBadRequestResponse(w, r.URL.String(), "you can not delete the device you are currently signed in with") return } err := db.MobileDeviceDelete(userID, userDeviceID) if err != nil { logger.Errorf("could not retrieve db results err: %v", err) - sendErrorResponse(w, r.URL.String(), "could not retrieve db results") + SendBadRequestResponse(w, r.URL.String(), "could not retrieve db results") return } - sendOKResponse(j, r.URL.String(), nil) + SendOKResponse(j, r.URL.String(), nil) } // Imprint will show the imprint data using a go template