Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Minor refactroing #2

Merged
merged 2 commits into from
Dec 13, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
24 changes: 24 additions & 0 deletions .github/workflows/linter.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
name: Lint
on:
push:
branches:
- master
- develop
pull_request:
workflow_dispatch:

jobs:
lint:
runs-on: ubuntu-latest
steps:
- name: Install Go
uses: actions/setup-go@v4
with:
go-version: 1.21.x
- name: Checkout code
uses: actions/checkout@v4
- name: golangci-lint
uses: golangci/golangci-lint-action@v3
with:
version: v1.55.2
args: --timeout=5m
67 changes: 67 additions & 0 deletions .golangci.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
service:
golangci-lint-version: 1.x.x

run:
tests: false

timeout: 2m
skip-dirs:
- vendor

linters-settings:
govet:
check-shadowing: false
goconst:
min-len: 2
min-occurrences: 2
misspell:
locale: US
lll:
line-length: 140
gocritic:
enabled-tags:
- diagnostic
- style
- performance
gci:
skip-generated: false

linters:
enable:
- bodyclose
- megacheck
- revive
- govet
- unconvert
- structcheck
- gas
- gocyclo
- dupl
- misspell
- unparam
- varcheck
- deadcode
- typecheck
- ineffassign
- varcheck
- stylecheck
- gochecknoinits
- exportloopref
- gocritic
- nakedret
- gosimple
- prealloc
- gci
- errcheck
- gofmt
- goimports
fast: false
disable-all: true

issues:
exclude-rules:
- text: "unexported-return:"
linters:
- revive
- text: 'shadow: declaration of "(err|ctx)" shadows declaration at'
linters: [ govet ]
1 change: 1 addition & 0 deletions logger/logger.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import (

var DefaultLogger *zap.SugaredLogger

// nolint:gochecknoinits // this is the simplest way to initialize the logger
func init() {
logger, err := zap.NewDevelopment()
if err != nil {
Expand Down
7 changes: 3 additions & 4 deletions main.go
Original file line number Diff line number Diff line change
@@ -1,11 +1,10 @@
package main

import (
_ "embed"
"log"
"strings"

_ "embed"

_ "github.com/0xPolygonID/refresh-service/logger"
"github.com/0xPolygonID/refresh-service/packagemanager"
"github.com/0xPolygonID/refresh-service/providers/flexiblehttp"
Expand Down Expand Up @@ -84,7 +83,7 @@ func main() {
documentLoader := loaders.NewDocumentLoader(ipfsCli, "",
loaders.WithCacheEngine(memoryCacheEngine))

flexiblehttp, err := flexiblehttp.NewFactoryFlexibleHTTP(
flexhttp, err := flexiblehttp.NewFactoryFlexibleHTTP(
cfg.HTTPConfigPath,
nil,
)
Expand All @@ -95,7 +94,7 @@ func main() {
refreshService := service.NewRefreshService(
issuerService,
documentLoader,
flexiblehttp,
flexhttp,
)

agentService := service.NewAgentService(
Expand Down
15 changes: 9 additions & 6 deletions packagemanager/packagemanager.go
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@ type state struct {
contracts map[int]*abi.State
}

func (s *state) verify(circuitID circuits.CircuitID, pubsignals []string) error {
func (s *state) verify(_ circuits.CircuitID, pubsignals []string) error {
bytePubsig, err := json.Marshal(pubsignals)
if err != nil {
return err
Expand Down Expand Up @@ -100,17 +100,20 @@ func NewPackageManager(
circuitsFolderPath string,
) (*iden3comm.PackageManager, error) {
circuitsPath := fmt.Sprintf("%s/%s", circuitsFolderPath, "authV2")
_, err := os.ReadFile(fmt.Sprintf("%s/circuit_final.zkey", circuitsPath))
_, err := os.Stat(fmt.Sprintf("%s/circuit_final.zkey", circuitsPath))
if err != nil {
return nil, err
return nil, errors.Errorf(
"issuer with the file circuit_final.zkey by path '%s': %v", circuitsPath, err)
}
_, err = os.ReadFile(fmt.Sprintf("%s/circuit.wasm", circuitsPath))
_, err = os.Stat(fmt.Sprintf("%s/circuit.wasm", circuitsPath))
if err != nil {
return nil, err
return nil, errors.Errorf(
"issuer with the file circuit.wasm by path '%s': %v", circuitsPath, err)
}
verificationKey, err := os.ReadFile(fmt.Sprintf("%s/verification_key.json", circuitsPath))
if err != nil {
return nil, err
return nil, errors.Errorf(
"issuer with the file verification_key.json by path '%s': %v", circuitsPath, err)
}

states := state{
Expand Down
7 changes: 4 additions & 3 deletions providers/flexiblehttp/http.go
Original file line number Diff line number Diff line change
Expand Up @@ -81,7 +81,7 @@ func (fh *FlexibleHTTP) Provide(credentialSubject map[string]interface{}) (map[s
return decodedResponse, nil
}

func (fh FlexibleHTTP) BuildRequest(credentialSubject map[string]interface{}) (*http.Request, error) {
func (fh *FlexibleHTTP) BuildRequest(credentialSubject map[string]interface{}) (*http.Request, error) {
u, err := url.Parse(fh.Provider.URL)
if err != nil {
return nil, err
Expand Down Expand Up @@ -115,7 +115,7 @@ func (fh FlexibleHTTP) BuildRequest(credentialSubject map[string]interface{}) (*
request, err := http.NewRequest(
fh.Provider.Method,
u.String(),
nil,
http.NoBody,
)
if err != nil {
return nil, err
Expand All @@ -127,7 +127,7 @@ func (fh FlexibleHTTP) BuildRequest(credentialSubject map[string]interface{}) (*
return request, nil
}

func (fh FlexibleHTTP) DecodeResponse(response map[string]interface{}) (map[string]interface{}, error) {
func (fh *FlexibleHTTP) DecodeResponse(response map[string]interface{}) (map[string]interface{}, error) {
parsedFields := make(map[string]interface{})
for propertyKey, propertyValue := range fh.ResponseSchema.Properties {
parts := strings.Split(propertyKey, ".")
Expand Down Expand Up @@ -187,6 +187,7 @@ func isPlaceholder(v string) bool {
return strings.HasPrefix(v, "{{") && strings.HasSuffix(v, "}}")
}

// nolint:gocritic // clear with named return
func processKey(key string) (string, int) {
startIdx := strings.Index(key, "[")
endIdx := strings.Index(key, "]")
Expand Down
1 change: 0 additions & 1 deletion server/middleware.go
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,6 @@ func zapContextLogger(next http.Handler) http.Handler {
"remoteAddr", r.RemoteAddr,
"responseTime", fmt.Sprintf("%d ms", time.Since(t1).Milliseconds()),
"status", ww.Status())
_ = logger.DefaultLogger.Sync()
}()

next.ServeHTTP(ww, r)
Expand Down
2 changes: 1 addition & 1 deletion service/agent.go
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,7 @@ func (as *AgentService) Process(envelop []byte) (
Type: iden3Protocol.CredentialIssuanceResponseMessageType,
ThreadID: message.ThreadID,
Body: iden3Protocol.IssuanceMessageBody{
Credential: refreshed,
Credential: *refreshed,
},
From: message.To,
To: message.From,
Expand Down
12 changes: 6 additions & 6 deletions service/issuer.go
Original file line number Diff line number Diff line change
Expand Up @@ -33,27 +33,27 @@ func NewIssuerService(supportedIssuers map[string]string, client *http.Client) *
}
}

func (is *IssuerService) GetClaimByID(issuerDID, claimID string) (
credential verifiable.W3CCredential, error error) {
func (is *IssuerService) GetClaimByID(issuerDID, claimID string) (*verifiable.W3CCredential, error) {
issuerNode, err := is.getIssuerURL(issuerDID)
if err != nil {
return credential, err
return nil, err
}
logger.DefaultLogger.Infof("use issuer node '%s' for issuer '%s'", issuerNode, issuerDID)

resp, err := is.do.Get(
fmt.Sprintf("%s/api/v1/identities/%s/claims/%s", issuerNode, issuerDID, claimID),
)
if err != nil {
return credential, errors.Wrapf(ErrGetClaim,
return nil, errors.Wrapf(ErrGetClaim,
"failed http GET request: '%v'", err)
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return credential, errors.Wrapf(ErrGetClaim,
return nil, errors.Wrapf(ErrGetClaim,
"invalid status code: '%d'", resp.StatusCode)
}
err = json.NewDecoder(resp.Body).Decode(&credential)
credential := &verifiable.W3CCredential{}
err = json.NewDecoder(resp.Body).Decode(credential)
if err != nil {
return credential, errors.Wrapf(ErrGetClaim,
"failed to decode response: '%v'", err)
Expand Down
32 changes: 16 additions & 16 deletions service/refresh.go
Original file line number Diff line number Diff line change
Expand Up @@ -47,55 +47,55 @@ type credentialRequest struct {

func (rs *RefreshService) Process(issuer string,
owner string, id string) (
verifiable.W3CCredential, error) {
*verifiable.W3CCredential, error) {
credential, err := rs.issuerService.GetClaimByID(issuer, id)
if err != nil {
return verifiable.W3CCredential{}, err
return nil, err
}

err = isUpdatable(credential)
if err != nil {
return verifiable.W3CCredential{},
return nil,
errors.Wrapf(ErrCredentialNotUpdatable,
"credential '%s': %v", credential.ID, err)
}
err = checkOwnerShip(credential, owner)
if err != nil {
return verifiable.W3CCredential{},
return nil,
errors.Wrapf(ErrCredentialNotUpdatable, "credential '%s': %v", credential.ID, err)
}

credentialBytes, err := json.Marshal(credential)
if err != nil {
return verifiable.W3CCredential{}, err
return nil, err
}
credentialType, err := merklize.Options{
DocumentLoader: rs.documentLoader,
}.TypeIDFromContext(credentialBytes, credential.CredentialSubject["type"].(string))
if err != nil {
return verifiable.W3CCredential{}, err
return nil, err
}

flexibleHTTP, err := rs.providers.ProduceFlexibleHTTP(credentialType)
if err != nil {
return verifiable.W3CCredential{},
return nil,
errors.Wrapf(ErrCredentialNotUpdatable,
"for credential '%s' not possible to find a data provider: %v", credential.ID, err)

}
updatedFields, err := flexibleHTTP.Provide(credential.CredentialSubject)
if err != nil {
return verifiable.W3CCredential{}, err
return nil, err
}

uploadedContexts, err := rs.loadContexts(credential.Context)
if err != nil {
return verifiable.W3CCredential{}, err
return nil, err
}

if err := isUpdatedIndexSlots(uploadedContexts,
credential.CredentialSubject, updatedFields); err != nil {
return verifiable.W3CCredential{},
return nil,
errors.Wrapf(ErrCredentialNotUpdatable,
"for credential '%s' index slots parsing process error: %v", credential.ID, err)
}
Expand All @@ -106,7 +106,7 @@ func (rs *RefreshService) Process(issuer string,

revNonce, err := extractRevocationNonce(credential)
if err != nil {
return verifiable.W3CCredential{}, err
return nil, err
}

credentialRequest := credentialRequest{
Expand All @@ -120,11 +120,11 @@ func (rs *RefreshService) Process(issuer string,

refreshedID, err := rs.issuerService.CreateCredential(issuer, credentialRequest)
if err != nil {
return verifiable.W3CCredential{}, err
return nil, err
}
rc, err := rs.issuerService.GetClaimByID(issuer, refreshedID)
if err != nil {
return verifiable.W3CCredential{}, err
return nil, err
}

return rc, nil
Expand Down Expand Up @@ -157,7 +157,7 @@ func (rs *RefreshService) loadContexts(contexts []string) ([]byte, error) {
return json.Marshal(res)
}

func isUpdatable(credential verifiable.W3CCredential) error {
func isUpdatable(credential *verifiable.W3CCredential) error {
if credential.Expiration.After(time.Now()) {
return errors.New("expired")
}
Expand All @@ -167,7 +167,7 @@ func isUpdatable(credential verifiable.W3CCredential) error {
return nil
}

func checkOwnerShip(credential verifiable.W3CCredential, owner string) error {
func checkOwnerShip(credential *verifiable.W3CCredential, owner string) error {
if credential.CredentialSubject["id"] != owner {
return errors.New("not owner of the credential")
}
Expand Down Expand Up @@ -197,7 +197,7 @@ func isUpdatedIndexSlots(credentialBytes []byte,
return errIndexSlotsNotUpdated
}

func extractRevocationNonce(credential verifiable.W3CCredential) (uint64, error) {
func extractRevocationNonce(credential *verifiable.W3CCredential) (uint64, error) {
credentialStatusInfo, ok := credential.CredentialStatus.(map[string]interface{})
if !ok {
return 0,
Expand Down
Loading