From 5b30f46ccfeb3cd4285f282c7fdc0cf92468d925 Mon Sep 17 00:00:00 2001 From: Ilya Date: Wed, 13 Dec 2023 17:38:18 +0200 Subject: [PATCH 1/2] add linter; fix linter; fix comments --- .golangci.yml | 67 ++++++++++++++++++++++++++++++++ logger/logger.go | 1 + main.go | 7 ++-- packagemanager/packagemanager.go | 15 ++++--- providers/flexiblehttp/http.go | 7 ++-- server/middleware.go | 1 - service/agent.go | 2 +- service/issuer.go | 12 +++--- service/refresh.go | 32 +++++++-------- 9 files changed, 107 insertions(+), 37 deletions(-) create mode 100644 .golangci.yml diff --git a/.golangci.yml b/.golangci.yml new file mode 100644 index 0000000..a89c11d --- /dev/null +++ b/.golangci.yml @@ -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 ] diff --git a/logger/logger.go b/logger/logger.go index db5e5a0..8be72c5 100644 --- a/logger/logger.go +++ b/logger/logger.go @@ -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 { diff --git a/main.go b/main.go index 7b3b568..6be6e03 100644 --- a/main.go +++ b/main.go @@ -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" @@ -84,7 +83,7 @@ func main() { documentLoader := loaders.NewDocumentLoader(ipfsCli, "", loaders.WithCacheEngine(memoryCacheEngine)) - flexiblehttp, err := flexiblehttp.NewFactoryFlexibleHTTP( + flexhttp, err := flexiblehttp.NewFactoryFlexibleHTTP( cfg.HTTPConfigPath, nil, ) @@ -95,7 +94,7 @@ func main() { refreshService := service.NewRefreshService( issuerService, documentLoader, - flexiblehttp, + flexhttp, ) agentService := service.NewAgentService( diff --git a/packagemanager/packagemanager.go b/packagemanager/packagemanager.go index ea08d64..06867cd 100644 --- a/packagemanager/packagemanager.go +++ b/packagemanager/packagemanager.go @@ -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 @@ -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{ diff --git a/providers/flexiblehttp/http.go b/providers/flexiblehttp/http.go index ef9e1fc..5cff733 100644 --- a/providers/flexiblehttp/http.go +++ b/providers/flexiblehttp/http.go @@ -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 @@ -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 @@ -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, ".") @@ -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, "]") diff --git a/server/middleware.go b/server/middleware.go index 9821295..927753e 100644 --- a/server/middleware.go +++ b/server/middleware.go @@ -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) diff --git a/service/agent.go b/service/agent.go index cf51306..b742662 100644 --- a/service/agent.go +++ b/service/agent.go @@ -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, diff --git a/service/issuer.go b/service/issuer.go index 3785543..2cc9c33 100644 --- a/service/issuer.go +++ b/service/issuer.go @@ -33,11 +33,10 @@ 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) @@ -45,15 +44,16 @@ func (is *IssuerService) GetClaimByID(issuerDID, claimID string) ( 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) diff --git a/service/refresh.go b/service/refresh.go index 9a6271c..a2c77a9 100644 --- a/service/refresh.go +++ b/service/refresh.go @@ -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) } @@ -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{ @@ -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 @@ -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") } @@ -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") } @@ -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, From 23d8c95124faaa21b3df5b9b4a32f102c6864919 Mon Sep 17 00:00:00 2001 From: Ilya Date: Wed, 13 Dec 2023 17:40:37 +0200 Subject: [PATCH 2/2] add workflows for linter --- .github/workflows/linter.yaml | 24 ++++++++++++++++++++++++ 1 file changed, 24 insertions(+) create mode 100644 .github/workflows/linter.yaml diff --git a/.github/workflows/linter.yaml b/.github/workflows/linter.yaml new file mode 100644 index 0000000..75c3b10 --- /dev/null +++ b/.github/workflows/linter.yaml @@ -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