Skip to content

Commit

Permalink
(NOBIDS) rename api error func (#2697)
Browse files Browse the repository at this point in the history
  • Loading branch information
LuccaBitfly authored Nov 14, 2023
1 parent f5b2ace commit 931be96
Show file tree
Hide file tree
Showing 7 changed files with 197 additions and 216 deletions.
317 changes: 149 additions & 168 deletions handlers/api.go

Large diffs are not rendered by default.

44 changes: 22 additions & 22 deletions handlers/api_eth1.go
Original file line number Diff line number Diff line change
Expand Up @@ -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()
Expand Down Expand Up @@ -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
Expand All @@ -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),
Expand All @@ -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",
Expand Down Expand Up @@ -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...)
Expand All @@ -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...)
Expand Down Expand Up @@ -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
}

Expand All @@ -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
Expand All @@ -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
}

Expand All @@ -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
}
}
Expand All @@ -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")
Expand All @@ -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
}
}
Expand Down Expand Up @@ -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
Expand All @@ -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
}

Expand Down Expand Up @@ -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 {
Expand Down
2 changes: 1 addition & 1 deletion handlers/base.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
}
Expand Down
6 changes: 3 additions & 3 deletions handlers/charts.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
}

Expand All @@ -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
Expand Down
2 changes: 1 addition & 1 deletion handlers/dashboard.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
}

Expand Down
4 changes: 2 additions & 2 deletions handlers/ens.go
Original file line number Diff line number Diff line change
Expand Up @@ -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) {
Expand Down
38 changes: 19 additions & 19 deletions handlers/user.go
Original file line number Diff line number Diff line change
Expand Up @@ -1572,15 +1572,15 @@ 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
}

errFields["jsonObjects"] = jsonObjects

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
}

Expand Down Expand Up @@ -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
}

Expand Down Expand Up @@ -1813,15 +1813,15 @@ 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
}

errFields["jsonObjects"] = jsonObjects

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
}

Expand Down Expand Up @@ -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
}

Expand All @@ -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
}

Expand Down Expand Up @@ -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")
}
}

Expand All @@ -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)
}
Expand All @@ -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) {
Expand All @@ -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
Expand Down

0 comments on commit 931be96

Please sign in to comment.