diff --git a/.gitlab-ci.yml b/.gitlab-ci.yml index c7b122572752ef38fea0fd92c05b064202189f9d..f0e054b0e691822c84a12af216e22db31e078977 100644 --- a/.gitlab-ci.yml +++ b/.gitlab-ci.yml @@ -1,5 +1,6 @@ stages: - build + - code-quality variables: IMAGE_PATH: "${CI_REGISTRY_IMAGE}" @@ -21,14 +22,23 @@ variables: build-ekms: script: - - IMAGE_NAME="$IMAGE_PATH/ekms" - - TAG=$CI_COMMIT_REF_SLUG - - docker buildx build --push -t "$IMAGE_NAME:$TAG" -f ekms/Dockerfile --build-arg "GITLAB_PROXY=${CI_DEPENDENCY_PROXY_GROUP_IMAGE_PREFIX}/" --build-arg GITLAB_LOGIN=${GITLAB_LOGIN} --build-arg GITLAB_TOKEN=${GITLAB_TOKEN} --build-arg GOLANG_VERSION=${GOLANG_VERSION} . + - IMAGE_NAME="$IMAGE_PATH/ekms" + - TAG=$CI_COMMIT_REF_SLUG + - docker buildx build --push -t "$IMAGE_NAME:$TAG" -f ekms/Dockerfile --build-arg "GITLAB_PROXY=${CI_DEPENDENCY_PROXY_GROUP_IMAGE_PREFIX}/" --build-arg GITLAB_LOGIN=${GITLAB_LOGIN} --build-arg GITLAB_TOKEN=${GITLAB_TOKEN} --build-arg GOLANG_VERSION=${GOLANG_VERSION} . <<: *build build-quantumlayer: script: - - IMAGE_NAME="$IMAGE_PATH/quantumlayer" - - TAG=$CI_COMMIT_REF_SLUG - - docker buildx build --push -t "$IMAGE_NAME:$TAG" -f quantumlayer/Dockerfile --build-arg "GITLAB_PROXY=${CI_DEPENDENCY_PROXY_GROUP_IMAGE_PREFIX}/" --build-arg GITLAB_LOGIN=${GITLAB_LOGIN} --build-arg GITLAB_TOKEN=${GITLAB_TOKEN} --build-arg GOLANG_VERSION=${GOLANG_VERSION} . + - IMAGE_NAME="$IMAGE_PATH/quantumlayer" + - TAG=$CI_COMMIT_REF_SLUG + - docker buildx build --push -t "$IMAGE_NAME:$TAG" -f quantumlayer/Dockerfile --build-arg "GITLAB_PROXY=${CI_DEPENDENCY_PROXY_GROUP_IMAGE_PREFIX}/" --build-arg GITLAB_LOGIN=${GITLAB_LOGIN} --build-arg GITLAB_TOKEN=${GITLAB_TOKEN} --build-arg GOLANG_VERSION=${GOLANG_VERSION} . <<: *build + +lint: + stage: code-quality + image: ${CI_DEPENDENCY_PROXY_GROUP_IMAGE_PREFIX}/golangci/golangci-lint:v1.55.2-alpine + script: + - apk add --update make jq + - echo "machine code.fbi.h-da.de login ${GITLAB_LOGIN} password ${GITLAB_TOKEN}" > ~/.netrc + - make lint + needs: [] diff --git a/.golangci.yml b/.golangci.yml new file mode 100644 index 0000000000000000000000000000000000000000..6e56a1c19e01e0f958299813accb800e54ef8906 --- /dev/null +++ b/.golangci.yml @@ -0,0 +1,77 @@ +variables: + GOLANG_VERSION: "1.21" +run: + go: $GOLANG_VERSION + concurrency: 8 + timeout: 20m + issues-exit-code: 1 + # directories to be ignored by linters + skip-dirs: + - .git/ + - ekms/model + - ekms/models + - artifacts/ + - ekms/api/go + skip-dirs-default: true + #skip-files: + # - http.go + modules-download-mode: readonly + +# output settings -> code-climate for GitLab +output: + format: code-climate + print-issued-lines: true + print-linter-name: true + uniq-by-line: true + path-prefix: "" + +issues: + exclude-use-default: false + max-issues-per-linter: 0 + max-same-issues: 0 + +linters: + # enable the specific needed linters + # see here for full list: https://golangci-lint.run/usage/linters/ + # linters to consider: gosimple, containedctx, contextcheck, depguard, errchkjson, exhaustive, exhaustruct, forbidigo, + # gochecknoinits, gocognit, goconst, gocritic, gofumpt, gomnd, gosec, importas, lll, nestif, nilerr, nlreturn, noctx, nolintlint, + # nosnakecase, paralleltest, prealloc, structcheck, testpackage, tparallel, unparam, wastedassign, wrapcheck, wsl + disable-all: true + enable: + - gofmt + - goimports + - gocyclo + - govet + - unused + - staticcheck + - typecheck + - revive + - whitespace + - errcheck + - ineffassign + - bidichk + - durationcheck + - errorlint + - exportloopref + - grouper + - makezero + - misspell + - nilnil + - predeclared + - godot + - errname + +# custom settings for linters +linters-settings: + gocyclo: + min-complexity: 15 + golint: + min-confidence: 0.8 + errcheck: + # Report about not checking of errors in type assertions: `a := b.(MyStruct)`. + # Such cases aren't reported by default. + # Default: false + check-type-assertions: true + revive: + severity: warning + confidence: 0.8 diff --git a/Makefile b/Makefile index 1e7b4b39c5c85a7f16bb91b6524a37b058ac4399..eef0ff6f16197950fb11e0c0261a175c3de05104 100644 --- a/Makefile +++ b/Makefile @@ -7,7 +7,9 @@ TOOLS_DIR:= build-tools GOSDN_PRG := $(MAKEFILE_DIR)$(TOOLS_DIR) GOPATH := $(~/go) GOBIN := $(GOSDN_PRG) + GOLANG_VERSION := 1.21 +GOLANGCI_LINT_VERSION=v1.55.0 GOCMD=go GOBUILD=$(GOCMD) build @@ -24,10 +26,18 @@ pre: install-tools: @echo Install development tooling mkdir -p $(GOSDN_PRG) - export GOBIN=$(GOSDN_PRG) && go install github.com/openconfig/ygot/generator@v0.28.3 &&\ - go install github.com/andresterba/go-ygot-generator-generator@v0.0.4 + export GOBIN=$(GOSDN_PRG) &&\ + go install github.com/openconfig/ygot/generator@v0.28.3 &&\ + go install github.com/andresterba/go-ygot-generator-generator@v0.0.4 &&\ + go install github.com/golangci/golangci-lint/cmd/golangci-lint@$(GOLANGCI_LINT_VERSION) @echo Finished installing development tooling +lint: install-tools + ./$(TOOLS_DIR)/golangci-lint run --config .golangci.yml | jq + +lint-fix: install-tools + ./$(TOOLS_DIR)/golangci-lint run --config .golangci.yml --fix | jq + build-ekms: pre CGO_ENABLED=0 $(GOBUILD) -o $(BUILD_ARTIFACTS_PATH)/ekms ./ekms/main.go diff --git a/ekms/api/go/rest/etsi/server/go/api.go b/ekms/api/go/rest/etsi/server/go/api.go index c75b26b50069c77252e3bd6b4d9c66e8a570240e..b7ba63cfa303d80b3420a407d1829ee876575d1d 100644 --- a/ekms/api/go/rest/etsi/server/go/api.go +++ b/ekms/api/go/rest/etsi/server/go/api.go @@ -14,12 +14,10 @@ import ( "net/http" ) - - // DefaultAPIRouter defines the required methods for binding the api requests to a responses for the DefaultAPI // The DefaultAPIRouter implementation should parse necessary information from the http request, // pass the data to a DefaultAPIServicer to perform the required actions, then write the service results to the http response. -type DefaultAPIRouter interface { +type DefaultAPIRouter interface { GetKey(http.ResponseWriter, *http.Request) GetKeyPost(http.ResponseWriter, *http.Request) GetKeyWithIds(http.ResponseWriter, *http.Request) @@ -27,12 +25,11 @@ type DefaultAPIRouter interface { GetStatus(http.ResponseWriter, *http.Request) } - // DefaultAPIServicer defines the api actions for the DefaultAPI service // This interface intended to stay up to date with the openapi yaml used to generate it, // while the service implementation can be ignored with the .openapi-generator-ignore file // and updated with the logic required for the API. -type DefaultAPIServicer interface { +type DefaultAPIServicer interface { GetKey(context.Context, interface{}, int64, int64) (ImplResponse, error) GetKeyPost(context.Context, interface{}, KeyRequest) (ImplResponse, error) GetKeyWithIds(context.Context, interface{}, string) (ImplResponse, error) diff --git a/ekms/api/go/rest/etsi/server/go/api_default.go b/ekms/api/go/rest/etsi/server/go/api_default.go index ffa0da4d0aea28b4e0b12375a5bc9fa0e3288219..cdec2d3f3e170ab9b651c7d6baf24ca4319d979a 100644 --- a/ekms/api/go/rest/etsi/server/go/api_default.go +++ b/ekms/api/go/rest/etsi/server/go/api_default.go @@ -19,7 +19,7 @@ import ( "github.com/gorilla/mux" ) -// DefaultAPIController binds http requests to an api service and writes the service results to the http response +// DefaultAPIController binds http requests to an api service and writes the service results to the http response. type DefaultAPIController struct { service DefaultAPIServicer errorHandler ErrorHandler @@ -28,14 +28,14 @@ type DefaultAPIController struct { // DefaultAPIOption for how the controller is set up. type DefaultAPIOption func(*DefaultAPIController) -// WithDefaultAPIErrorHandler inject ErrorHandler into controller +// WithDefaultAPIErrorHandler inject ErrorHandler into controller. func WithDefaultAPIErrorHandler(h ErrorHandler) DefaultAPIOption { return func(c *DefaultAPIController) { c.errorHandler = h } } -// NewDefaultAPIController creates a default api controller +// NewDefaultAPIController creates a default api controller. func NewDefaultAPIController(s DefaultAPIServicer, opts ...DefaultAPIOption) Router { controller := &DefaultAPIController{ service: s, @@ -49,7 +49,7 @@ func NewDefaultAPIController(s DefaultAPIServicer, opts ...DefaultAPIOption) Rou return controller } -// Routes returns all the api routes for the DefaultAPIController +// Routes returns all the api routes for the DefaultAPIController. func (c *DefaultAPIController) Routes() Routes { return Routes{ "GetKey": Route{ @@ -80,22 +80,22 @@ func (c *DefaultAPIController) Routes() Routes { } } -// GetKey - TBD +// GetKey - TBD. func (c *DefaultAPIController) GetKey(w http.ResponseWriter, r *http.Request) { params := mux.Vars(r) query := r.URL.Query() slaveSAEIDParam := params["slave_SAE_ID"] - numberParam, err := parseNumericParameter[int64]( + numberParam, err := ParseNumericParameter[int64]( query.Get("number"), - WithParse[int64](parseInt64), + WithParse[int64](ParseInt64), ) if err != nil { c.errorHandler(w, r, &ParsingError{Err: err}, nil) return } - sizeParam, err := parseNumericParameter[int64]( + sizeParam, err := ParseNumericParameter[int64]( query.Get("size"), - WithParse[int64](parseInt64), + WithParse[int64](ParseInt64), ) if err != nil { c.errorHandler(w, r, &ParsingError{Err: err}, nil) @@ -111,7 +111,7 @@ func (c *DefaultAPIController) GetKey(w http.ResponseWriter, r *http.Request) { EncodeJSONResponse(result.Body, &result.Code, w) } -// GetKeyPost - +// GetKeyPost -. func (c *DefaultAPIController) GetKeyPost(w http.ResponseWriter, r *http.Request) { params := mux.Vars(r) slaveSAEIDParam := params["slave_SAE_ID"] @@ -140,7 +140,7 @@ func (c *DefaultAPIController) GetKeyPost(w http.ResponseWriter, r *http.Request EncodeJSONResponse(result.Body, &result.Code, w) } -// GetKeyWithIds - TBD +// GetKeyWithIds - TBD. func (c *DefaultAPIController) GetKeyWithIds(w http.ResponseWriter, r *http.Request) { params := mux.Vars(r) query := r.URL.Query() @@ -156,7 +156,7 @@ func (c *DefaultAPIController) GetKeyWithIds(w http.ResponseWriter, r *http.Requ EncodeJSONResponse(result.Body, &result.Code, w) } -// GetKeyWithIdsPost - TBD +// GetKeyWithIdsPost - TBD. func (c *DefaultAPIController) GetKeyWithIdsPost(w http.ResponseWriter, r *http.Request) { params := mux.Vars(r) masterSAEIDParam := params["master_SAE_ID"] @@ -185,7 +185,7 @@ func (c *DefaultAPIController) GetKeyWithIdsPost(w http.ResponseWriter, r *http. EncodeJSONResponse(result.Body, &result.Code, w) } -// GetStatus - TBD +// GetStatus - TBD. func (c *DefaultAPIController) GetStatus(w http.ResponseWriter, r *http.Request) { params := mux.Vars(r) slaveSAEIDParam := params["slave_SAE_ID"] diff --git a/ekms/api/go/rest/etsi/server/go/api_default_service.go b/ekms/api/go/rest/etsi/server/go/api_default_service.go index 90a01d276ac8a3a58d34bbf6faa9e87e7fb21745..ee7e943c9b1a3bf327cc4a628ec2311f0dfa79d5 100644 --- a/ekms/api/go/rest/etsi/server/go/api_default_service.go +++ b/ekms/api/go/rest/etsi/server/go/api_default_service.go @@ -11,8 +11,8 @@ package etsi14 import ( "context" - "net/http" "errors" + "net/http" ) // DefaultAPIService is a service that implements the logic for the DefaultAPIServicer @@ -21,12 +21,12 @@ import ( type DefaultAPIService struct { } -// NewDefaultAPIService creates a default api service +// NewDefaultAPIService creates a default api service. func NewDefaultAPIService() DefaultAPIServicer { return &DefaultAPIService{} } -// GetKey - TBD +// GetKey - TBD. func (s *DefaultAPIService) GetKey(ctx context.Context, slaveSAEID interface{}, number int64, size int64) (ImplResponse, error) { // TODO - update GetKey with the required logic for this service method. // Add api_default_service.go to the .openapi-generator-ignore to avoid overwriting this service implementation when updating open api generation. @@ -46,7 +46,7 @@ func (s *DefaultAPIService) GetKey(ctx context.Context, slaveSAEID interface{}, return Response(http.StatusNotImplemented, nil), errors.New("GetKey method not implemented") } -// GetKeyPost - +// GetKeyPost -. func (s *DefaultAPIService) GetKeyPost(ctx context.Context, slaveSAEID interface{}, keyRequest KeyRequest) (ImplResponse, error) { // TODO - update GetKeyPost with the required logic for this service method. // Add api_default_service.go to the .openapi-generator-ignore to avoid overwriting this service implementation when updating open api generation. @@ -66,7 +66,7 @@ func (s *DefaultAPIService) GetKeyPost(ctx context.Context, slaveSAEID interface return Response(http.StatusNotImplemented, nil), errors.New("GetKeyPost method not implemented") } -// GetKeyWithIds - TBD +// GetKeyWithIds - TBD. func (s *DefaultAPIService) GetKeyWithIds(ctx context.Context, masterSAEID interface{}, keyID string) (ImplResponse, error) { // TODO - update GetKeyWithIds with the required logic for this service method. // Add api_default_service.go to the .openapi-generator-ignore to avoid overwriting this service implementation when updating open api generation. @@ -86,7 +86,7 @@ func (s *DefaultAPIService) GetKeyWithIds(ctx context.Context, masterSAEID inter return Response(http.StatusNotImplemented, nil), errors.New("GetKeyWithIds method not implemented") } -// GetKeyWithIdsPost - TBD +// GetKeyWithIdsPost - TBD. func (s *DefaultAPIService) GetKeyWithIdsPost(ctx context.Context, masterSAEID interface{}, keyIdsRequest KeyIdsRequest) (ImplResponse, error) { // TODO - update GetKeyWithIdsPost with the required logic for this service method. // Add api_default_service.go to the .openapi-generator-ignore to avoid overwriting this service implementation when updating open api generation. @@ -106,7 +106,7 @@ func (s *DefaultAPIService) GetKeyWithIdsPost(ctx context.Context, masterSAEID i return Response(http.StatusNotImplemented, nil), errors.New("GetKeyWithIdsPost method not implemented") } -// GetStatus - TBD +// GetStatus - TBD. func (s *DefaultAPIService) GetStatus(ctx context.Context, slaveSAEID interface{}) (ImplResponse, error) { // TODO - update GetStatus with the required logic for this service method. // Add api_default_service.go to the .openapi-generator-ignore to avoid overwriting this service implementation when updating open api generation. diff --git a/ekms/api/go/rest/etsi/server/go/error.go b/ekms/api/go/rest/etsi/server/go/error.go index 01347b652fc272969c6db4d9028a8f30fc6ad9ac..9bc45a0d888e0217096d87e89bbcdcf8c390eebc 100644 --- a/ekms/api/go/rest/etsi/server/go/error.go +++ b/ekms/api/go/rest/etsi/server/go/error.go @@ -16,11 +16,11 @@ import ( ) var ( - // ErrTypeAssertionError is thrown when type an interface does not match the asserted type + // ErrTypeAssertionError is thrown when type an interface does not match the asserted type. ErrTypeAssertionError = errors.New("unable to assert type") ) -// ParsingError indicates that an error has occurred when parsing request parameters +// ParsingError indicates that an error has occurred when parsing request parameters. type ParsingError struct { Err error } @@ -33,7 +33,7 @@ func (e *ParsingError) Error() string { return e.Err.Error() } -// RequiredError indicates that an error has occurred when parsing request parameters +// RequiredError indicates that an error has occurred when parsing request parameters. type RequiredError struct { Field string } @@ -43,7 +43,7 @@ func (e *RequiredError) Error() string { } // ErrorHandler defines the required method for handling error. You may implement it and inject this into a controller if -// you would like errors to be handled differently from the DefaultErrorHandler +// you would like errors to be handled differently from the DefaultErrorHandler. type ErrorHandler func(w http.ResponseWriter, r *http.Request, err error, result *ImplResponse) // DefaultErrorHandler defines the default logic on how to handle errors from the controller. Any errors from parsing diff --git a/ekms/api/go/rest/etsi/server/go/helpers.go b/ekms/api/go/rest/etsi/server/go/helpers.go index 36316ddd1c7f64acc91525a64d7b4cdbb0f0c17c..217cccbb9b6dadae79d74215a08ba8d5333c4d2f 100644 --- a/ekms/api/go/rest/etsi/server/go/helpers.go +++ b/ekms/api/go/rest/etsi/server/go/helpers.go @@ -13,9 +13,9 @@ import ( "reflect" ) -// Response return a ImplResponse struct filled +// Response return a ImplResponse struct filled. func Response(code int, body interface{}) ImplResponse { - return ImplResponse { + return ImplResponse{ Code: code, Body: body, } diff --git a/ekms/api/go/rest/etsi/server/go/impl.go b/ekms/api/go/rest/etsi/server/go/impl.go index 3d098aa7d22df563a55bc4ddad7515f903210812..0c47d7d8759128812cc6efc3ded6de46584a6700 100644 --- a/ekms/api/go/rest/etsi/server/go/impl.go +++ b/ekms/api/go/rest/etsi/server/go/impl.go @@ -9,7 +9,7 @@ package etsi14 -// ImplResponse defines an implementation response with error code and the associated body +// ImplResponse defines an implementation response with error code and the associated body. type ImplResponse struct { Code int Body interface{} diff --git a/ekms/api/go/rest/etsi/server/go/model_error_format.go b/ekms/api/go/rest/etsi/server/go/model_error_format.go index 875b9b4f222cfb6de02a261526d184dca4fec543..7a675f17ffcab1d6b41d7b92943f3bd3a29c1e8f 100644 --- a/ekms/api/go/rest/etsi/server/go/model_error_format.go +++ b/ekms/api/go/rest/etsi/server/go/model_error_format.go @@ -9,22 +9,18 @@ package etsi14 - - - type ErrorFormat struct { - Message string `json:"message,omitempty"` Details []map[string]string `json:"details,omitempty"` } -// AssertErrorFormatRequired checks if the required fields are not zero-ed +// AssertErrorFormatRequired checks if the required fields are not zero-ed. func AssertErrorFormatRequired(obj ErrorFormat) error { return nil } -// AssertErrorFormatConstraints checks if the values respects the defined constraints +// AssertErrorFormatConstraints checks if the values respects the defined constraints. func AssertErrorFormatConstraints(obj ErrorFormat) error { return nil } diff --git a/ekms/api/go/rest/etsi/server/go/model_key_container.go b/ekms/api/go/rest/etsi/server/go/model_key_container.go index ec5244a13b81d82563b708cbddf00c372d395888..609f2a505d5ff37256abb678b1739cc0e3844994 100644 --- a/ekms/api/go/rest/etsi/server/go/model_key_container.go +++ b/ekms/api/go/rest/etsi/server/go/model_key_container.go @@ -9,15 +9,11 @@ package etsi14 - - - type KeyContainer struct { - Keys []KeyContainerKeysInner `json:"Keys,omitempty"` } -// AssertKeyContainerRequired checks if the required fields are not zero-ed +// AssertKeyContainerRequired checks if the required fields are not zero-ed. func AssertKeyContainerRequired(obj KeyContainer) error { for _, el := range obj.Keys { if err := AssertKeyContainerKeysInnerRequired(el); err != nil { @@ -27,7 +23,7 @@ func AssertKeyContainerRequired(obj KeyContainer) error { return nil } -// AssertKeyContainerConstraints checks if the values respects the defined constraints +// AssertKeyContainerConstraints checks if the values respects the defined constraints. func AssertKeyContainerConstraints(obj KeyContainer) error { return nil } diff --git a/ekms/api/go/rest/etsi/server/go/model_key_container_keys_inner.go b/ekms/api/go/rest/etsi/server/go/model_key_container_keys_inner.go index 41269aa7c94f644ff96559f3a4580ae412fa89a9..3a62cde09f06b70ea291d882f2c50f5c17b863c3 100644 --- a/ekms/api/go/rest/etsi/server/go/model_key_container_keys_inner.go +++ b/ekms/api/go/rest/etsi/server/go/model_key_container_keys_inner.go @@ -9,22 +9,18 @@ package etsi14 - - - type KeyContainerKeysInner struct { - KeyID string `json:"key_ID,omitempty"` Key string `json:"key,omitempty"` } -// AssertKeyContainerKeysInnerRequired checks if the required fields are not zero-ed +// AssertKeyContainerKeysInnerRequired checks if the required fields are not zero-ed. func AssertKeyContainerKeysInnerRequired(obj KeyContainerKeysInner) error { return nil } -// AssertKeyContainerKeysInnerConstraints checks if the values respects the defined constraints +// AssertKeyContainerKeysInnerConstraints checks if the values respects the defined constraints. func AssertKeyContainerKeysInnerConstraints(obj KeyContainerKeysInner) error { return nil } diff --git a/ekms/api/go/rest/etsi/server/go/model_key_ids_request.go b/ekms/api/go/rest/etsi/server/go/model_key_ids_request.go index 20f94d231ab3b104af1adda908348896a1c7650d..60bbe5566acb2cd28104fe9f16d2f72f7342b86b 100644 --- a/ekms/api/go/rest/etsi/server/go/model_key_ids_request.go +++ b/ekms/api/go/rest/etsi/server/go/model_key_ids_request.go @@ -9,15 +9,11 @@ package etsi14 - - - type KeyIdsRequest struct { - KeyIDs []KeyIdsRequestKeyIdsInner `json:"key_IDs,omitempty"` } -// AssertKeyIdsRequestRequired checks if the required fields are not zero-ed +// AssertKeyIdsRequestRequired checks if the required fields are not zero-ed. func AssertKeyIdsRequestRequired(obj KeyIdsRequest) error { for _, el := range obj.KeyIDs { if err := AssertKeyIdsRequestKeyIdsInnerRequired(el); err != nil { @@ -27,7 +23,7 @@ func AssertKeyIdsRequestRequired(obj KeyIdsRequest) error { return nil } -// AssertKeyIdsRequestConstraints checks if the values respects the defined constraints +// AssertKeyIdsRequestConstraints checks if the values respects the defined constraints. func AssertKeyIdsRequestConstraints(obj KeyIdsRequest) error { return nil } diff --git a/ekms/api/go/rest/etsi/server/go/model_key_ids_request_key_ids_inner.go b/ekms/api/go/rest/etsi/server/go/model_key_ids_request_key_ids_inner.go index 4b2ab370d87792c96d7542999612f9d6256c8361..48f6a25e5e6fad109221dd0a343e26262dceb08c 100644 --- a/ekms/api/go/rest/etsi/server/go/model_key_ids_request_key_ids_inner.go +++ b/ekms/api/go/rest/etsi/server/go/model_key_ids_request_key_ids_inner.go @@ -9,15 +9,11 @@ package etsi14 - - - type KeyIdsRequestKeyIdsInner struct { - KeyID string `json:"key_ID"` } -// AssertKeyIdsRequestKeyIdsInnerRequired checks if the required fields are not zero-ed +// AssertKeyIdsRequestKeyIdsInnerRequired checks if the required fields are not zero-ed. func AssertKeyIdsRequestKeyIdsInnerRequired(obj KeyIdsRequestKeyIdsInner) error { elements := map[string]interface{}{ "key_ID": obj.KeyID, @@ -31,7 +27,7 @@ func AssertKeyIdsRequestKeyIdsInnerRequired(obj KeyIdsRequestKeyIdsInner) error return nil } -// AssertKeyIdsRequestKeyIdsInnerConstraints checks if the values respects the defined constraints +// AssertKeyIdsRequestKeyIdsInnerConstraints checks if the values respects the defined constraints. func AssertKeyIdsRequestKeyIdsInnerConstraints(obj KeyIdsRequestKeyIdsInner) error { return nil } diff --git a/ekms/api/go/rest/etsi/server/go/model_key_request.go b/ekms/api/go/rest/etsi/server/go/model_key_request.go index b6d4d075a7517952d8a69a70aea149835c6b38b3..6a4c685c285a0af106ebe0eb761949be46bdf8c7 100644 --- a/ekms/api/go/rest/etsi/server/go/model_key_request.go +++ b/ekms/api/go/rest/etsi/server/go/model_key_request.go @@ -9,11 +9,7 @@ package etsi14 - - - type KeyRequest struct { - Number int64 `json:"number,omitempty"` Size int64 `json:"size,omitempty"` @@ -25,12 +21,12 @@ type KeyRequest struct { ExtensionOptional []map[string]string `json:"extension_optional,omitempty"` } -// AssertKeyRequestRequired checks if the required fields are not zero-ed +// AssertKeyRequestRequired checks if the required fields are not zero-ed. func AssertKeyRequestRequired(obj KeyRequest) error { return nil } -// AssertKeyRequestConstraints checks if the values respects the defined constraints +// AssertKeyRequestConstraints checks if the values respects the defined constraints. func AssertKeyRequestConstraints(obj KeyRequest) error { return nil } diff --git a/ekms/api/go/rest/etsi/server/go/model_status.go b/ekms/api/go/rest/etsi/server/go/model_status.go index a0c25dec47bfcf097e4062477246cc09425d4b68..496e1831bfeb3bcb736a51e15a656a4e17fa20e7 100644 --- a/ekms/api/go/rest/etsi/server/go/model_status.go +++ b/ekms/api/go/rest/etsi/server/go/model_status.go @@ -9,11 +9,7 @@ package etsi14 - - - type Status struct { - SourceKMEID string `json:"source_KME_ID,omitempty"` TargetKMEID string `json:"target_KME_ID,omitempty"` @@ -37,12 +33,12 @@ type Status struct { MaxSAEIDCount int64 `json:"max_SAE_ID_count,omitempty"` } -// AssertStatusRequired checks if the required fields are not zero-ed +// AssertStatusRequired checks if the required fields are not zero-ed. func AssertStatusRequired(obj Status) error { return nil } -// AssertStatusConstraints checks if the values respects the defined constraints +// AssertStatusConstraints checks if the values respects the defined constraints. func AssertStatusConstraints(obj Status) error { return nil } diff --git a/ekms/api/go/rest/etsi/server/go/routers.go b/ekms/api/go/rest/etsi/server/go/routers.go index acc4360ed07a65d2db8353379a561b0d541a5bc0..f0e0cf0e54d9778a8ffb5613fdc833e837878d78 100644 --- a/ekms/api/go/rest/etsi/server/go/routers.go +++ b/ekms/api/go/rest/etsi/server/go/routers.go @@ -12,26 +12,27 @@ package etsi14 import ( "encoding/json" "errors" - "github.com/gorilla/mux" "io/ioutil" "mime/multipart" "net/http" "os" "strconv" "strings" + + "github.com/gorilla/mux" ) -// A Route defines the parameters for an api endpoint +// A Route defines the parameters for an api endpoint. type Route struct { - Method string - Pattern string + Method string + Pattern string HandlerFunc http.HandlerFunc } -// Routes is a map of defined api endpoints +// Routes is a map of defined api endpoints. type Routes map[string]Route -// Router defines the required methods for retrieving api routes +// Router defines the required methods for retrieving api routes. type Router interface { Routes() Routes } @@ -40,7 +41,7 @@ const errMsgRequiredMissing = "required parameter is missing" const errMsgMinValueConstraint = "provided parameter is not respecting minimum value constraint" const errMsgMaxValueConstraint = "provided parameter is not respecting maximum value constraint" -// NewRouter creates a new router for any number of api routers +// NewRouter creates a new router for any number of api routers. func NewRouter(routers ...Router) *mux.Router { router := mux.NewRouter().StrictSlash(true) for _, api := range routers { @@ -60,7 +61,7 @@ func NewRouter(routers ...Router) *mux.Router { return router } -// EncodeJSONResponse uses the json encoder to write an interface to the http response with an optional status code +// EncodeJSONResponse uses the json encoder to write an interface to the http response with an optional status code. func EncodeJSONResponse(i interface{}, status *int, w http.ResponseWriter) error { w.Header().Set("Content-Type", "application/json; charset=UTF-8") if status != nil { @@ -76,7 +77,7 @@ func EncodeJSONResponse(i interface{}, status *int, w http.ResponseWriter) error return nil } -// ReadFormFileToTempFile reads file data from a request form and writes it to a temporary file +// ReadFormFileToTempFile reads file data from a request form and writes it to a temporary file. func ReadFormFileToTempFile(r *http.Request, key string) (*os.File, error) { _, fileHeader, err := r.FormFile(key) if err != nil { @@ -86,7 +87,7 @@ func ReadFormFileToTempFile(r *http.Request, key string) (*os.File, error) { return readFileHeaderToTempFile(fileHeader) } -// ReadFormFilesToTempFiles reads files array data from a request form and writes it to a temporary files +// ReadFormFilesToTempFiles reads files array data from a request form and writes it to a temporary files. func ReadFormFilesToTempFiles(r *http.Request, key string) ([]*os.File, error) { if err := r.ParseMultipartForm(32 << 20); err != nil { return nil, err @@ -106,7 +107,7 @@ func ReadFormFilesToTempFiles(r *http.Request, key string) ([]*os.File, error) { return files, nil } -// readFileHeaderToTempFile reads multipart.FileHeader and writes it to a temporary file +// readFileHeaderToTempFile reads multipart.FileHeader and writes it to a temporary file. func readFileHeaderToTempFile(fileHeader *multipart.FileHeader) (*os.File, error) { formFile, err := fileHeader.Open() if err != nil { @@ -138,8 +139,8 @@ type Number interface { type ParseString[T Number | string | bool] func(v string) (T, error) -// parseFloat64 parses a string parameter to an float64. -func parseFloat64(param string) (float64, error) { +// ParseFloat64 parses a string parameter to an float64. +func ParseFloat64(param string) (float64, error) { if param == "" { return 0, nil } @@ -147,8 +148,8 @@ func parseFloat64(param string) (float64, error) { return strconv.ParseFloat(param, 64) } -// parseFloat32 parses a string parameter to an float32. -func parseFloat32(param string) (float32, error) { +// ParseFloat32 parses a string parameter to an float32. +func ParseFloat32(param string) (float32, error) { if param == "" { return 0, nil } @@ -157,8 +158,8 @@ func parseFloat32(param string) (float32, error) { return float32(v), err } -// parseInt64 parses a string parameter to an int64. -func parseInt64(param string) (int64, error) { +// ParseInt64 parses a string parameter to an int64. +func ParseInt64(param string) (int64, error) { if param == "" { return 0, nil } @@ -166,8 +167,8 @@ func parseInt64(param string) (int64, error) { return strconv.ParseInt(param, 10, 64) } -// parseInt32 parses a string parameter to an int32. -func parseInt32(param string) (int32, error) { +// ParseInt32 parses a string parameter to an int32. +func ParseInt32(param string) (int32, error) { if param == "" { return 0, nil } @@ -176,8 +177,8 @@ func parseInt32(param string) (int32, error) { return int32(val), err } -// parseBool parses a string parameter to an bool. -func parseBool(param string) (bool, error) { +// ParseBool parses a string parameter to an bool. +func ParseBool(param string) (bool, error) { if param == "" { return false, nil } @@ -239,8 +240,8 @@ func WithMaximum[T Number](expected T) Constraint[T] { } } -// parseNumericParameter parses a numeric parameter to its respective type. -func parseNumericParameter[T Number](param string, fn Operation[T], checks ...Constraint[T]) (T, error) { +// ParseNumericParameter parses a numeric parameter to its respective type. +func ParseNumericParameter[T Number](param string, fn Operation[T], checks ...Constraint[T]) (T, error) { v, ok, err := fn(param) if err != nil { return 0, err @@ -257,14 +258,14 @@ func parseNumericParameter[T Number](param string, fn Operation[T], checks ...Co return v, nil } -// parseBoolParameter parses a string parameter to a bool -func parseBoolParameter(param string, fn Operation[bool]) (bool, error) { +// ParseBoolParameter parses a string parameter to a bool. +func ParseBoolParameter(param string, fn Operation[bool]) (bool, error) { v, _, err := fn(param) return v, err } -// parseNumericArrayParameter parses a string parameter containing array of values to its respective type. -func parseNumericArrayParameter[T Number](param, delim string, required bool, fn Operation[T], checks ...Constraint[T]) ([]T, error) { +// ParseNumericArrayParameter parses a string parameter containing array of values to its respective type. +func ParseNumericArrayParameter[T Number](param, delim string, required bool, fn Operation[T], checks ...Constraint[T]) ([]T, error) { if param == "" { if required { return nil, errors.New(errMsgRequiredMissing) diff --git a/ekms/cmd/root.go b/ekms/cmd/root.go index c701b72a655888591190125b317b4e296da2387d..8220fa9505b7778054c512c19187b6cb1faf8bd1 100644 --- a/ekms/cmd/root.go +++ b/ekms/cmd/root.go @@ -34,7 +34,7 @@ import ( "github.com/spf13/cobra" ) -// rootCmd represents the base command when called without any subcommands +// rootCmd represents the base command when called without any subcommands. var rootCmd = &cobra.Command{ Use: "ekms", Short: "A brief description of your application", diff --git a/ekms/cmd/start.go b/ekms/cmd/start.go index b2c374124ce3752bfdfed8d6cb26f34fba40b05d..b5ac5162962fb08f672c706c3b85d56d2587673b 100644 --- a/ekms/cmd/start.go +++ b/ekms/cmd/start.go @@ -56,16 +56,16 @@ var ( caFile string // the location of the file containing the ca certificate to verify client certificates keyFile string // the location of the file containing the key for the certificates for the gnmi server insecure *bool // set to true if insecure operations is needed, i.e., do not use TLS - // Below is qkdn specific information + // Below is qkdn specific information. udpQL1AddrString string ql1Name string udpQL2AddrString string ql2Name string kmsConfig string - // End of qkdn specific information + // End of qkdn specific information. ) -// startCmd represents the start command +// startCmd represents the start command. var startCmd = &cobra.Command{ Use: "start", Short: "Start gnmi server", @@ -142,19 +142,58 @@ func init() { startCmd.Flags().StringVarP(&ql2Name, "remote_name", "", "ekms-ql2", "The name of the remote quantumlayer") startCmd.Flags().StringVarP(&kmsConfig, "kms_config", "", "", "Path to the kms config file (yaml)") - viper.BindPFlag("bindAddress", startCmd.Flags().Lookup("bind_address")) - viper.BindPFlag("configFile", startCmd.Flags().Lookup("config")) - viper.BindPFlag("logLevel", startCmd.Flags().Lookup("log")) - viper.BindPFlag("insecure", startCmd.Flags().Lookup("insecure")) - viper.BindPFlag("certFile", startCmd.Flags().Lookup("cert")) - viper.BindPFlag("keyFile", startCmd.Flags().Lookup("key")) - viper.BindPFlag("caFile", startCmd.Flags().Lookup("ca_file")) - viper.BindPFlag("osclient", startCmd.Flags().Lookup("osclient")) - viper.BindPFlag("my_QLE_socket", startCmd.Flags().Lookup("my-address")) - viper.BindPFlag("my_name", startCmd.Flags().Lookup("my-name")) - viper.BindPFlag("remote_QLE_socket", startCmd.Flags().Lookup("remote-address")) - viper.BindPFlag("remote_name", startCmd.Flags().Lookup("remote-name")) - viper.BindPFlag("kms-config", startCmd.Flags().Lookup("kms_config")) + err := viper.BindPFlag("bindAddress", startCmd.Flags().Lookup("bind_address")) + if err != nil { + fmt.Println(err) + } + err = viper.BindPFlag("configFile", startCmd.Flags().Lookup("config")) + if err != nil { + fmt.Println(err) + } + err = viper.BindPFlag("logLevel", startCmd.Flags().Lookup("log")) + if err != nil { + fmt.Println(err) + } + err = viper.BindPFlag("insecure", startCmd.Flags().Lookup("insecure")) + if err != nil { + fmt.Println(err) + } + err = viper.BindPFlag("certFile", startCmd.Flags().Lookup("cert")) + if err != nil { + fmt.Println(err) + } + err = viper.BindPFlag("keyFile", startCmd.Flags().Lookup("key")) + if err != nil { + fmt.Println(err) + } + err = viper.BindPFlag("caFile", startCmd.Flags().Lookup("ca_file")) + if err != nil { + fmt.Println(err) + } + err = viper.BindPFlag("osclient", startCmd.Flags().Lookup("osclient")) + if err != nil { + fmt.Println(err) + } + err = viper.BindPFlag("my_QLE_socket", startCmd.Flags().Lookup("my-address")) + if err != nil { + fmt.Println(err) + } + err = viper.BindPFlag("my_name", startCmd.Flags().Lookup("my-name")) + if err != nil { + fmt.Println(err) + } + err = viper.BindPFlag("remote_QLE_socket", startCmd.Flags().Lookup("remote-address")) + if err != nil { + fmt.Println(err) + } + err = viper.BindPFlag("remote_name", startCmd.Flags().Lookup("remote-name")) + if err != nil { + fmt.Println(err) + } + err = viper.BindPFlag("kms-config", startCmd.Flags().Lookup("kms_config")) + if err != nil { + fmt.Println(err) + } rootCmd.AddCommand(startCmd) } diff --git a/ekms/etsiqkdnclient/etsi-qkdn-client.go b/ekms/etsiqkdnclient/etsi-qkdn-client.go index fd0179d492561683f59b5d1fed61584dc19a76e1..177efe2b21f72b00ad4602c0ba8a974b9e124634 100644 --- a/ekms/etsiqkdnclient/etsi-qkdn-client.go +++ b/ekms/etsiqkdnclient/etsi-qkdn-client.go @@ -70,7 +70,7 @@ type EkmsClient interface { } // TODO: change this in the future -// This provides some static information +// This provides some static information. type ekmsInfo struct { // Information used to fill the ETSI GS QKD 15 yang model id uuid.UUID @@ -97,7 +97,7 @@ func (evi *ekmsVersionInformation) HardwareVersion() string { return evi.hwVersion } -// A QkdnClient for the emulated KMS +// A QkdnClient for the emulated KMS. func NewEkmsClient(bootInfo *Config) (myInfo *ekmsInfo) { var ekmsId uuid.UUID if bootInfo.Id != "" { @@ -122,7 +122,7 @@ func NewEkmsClient(bootInfo *Config) (myInfo *ekmsInfo) { return myInfo } -// TODO: return an error +// TODO: return an error. func emulatedKMS(config *Config, id uuid.UUID, peerChannel chan string) *kms.EKMS { // Attach to eKMS emuKMS := kms.NewEKMS(config.Name, id, os.Stdout, log.TraceLevel, false, config.InterComAddr) @@ -137,6 +137,8 @@ func emulatedKMS(config *Config, id uuid.UUID, peerChannel chan string) *kms.EKM case "etsi": qm, err = kms.NewETSI014HTTPQuantumModule(pqm.Address, pqm.SlaveSAEID, pqm.MasterSAEID, pqm.MasterMode) if err != nil { + log.Fatalf("Failed to create ETSI QKD module: %s", err) + return nil } default: log.Fatalf("Unknown type: %s for quantum module", qmt) @@ -145,7 +147,7 @@ func emulatedKMS(config *Config, id uuid.UUID, peerChannel chan string) *kms.EKM err := emuKMS.AddQuantumElement(qm) if err != nil { - log.Fatalf("Failed to add quantum element", err) + log.Fatalf("Failed to add quantum element: %s", err) return nil } diff --git a/ekms/handlers/system/hostnameHandler.go b/ekms/handlers/system/hostnameHandler.go index 3cd079b0db67edb323201a8888fcf6e80a6fcfc7..e03e5776fa92c793b8812583a06a3f953115b815 100644 --- a/ekms/handlers/system/hostnameHandler.go +++ b/ekms/handlers/system/hostnameHandler.go @@ -15,7 +15,6 @@ type HostnameHandler struct { name string paths map[string]struct{} osClient osclient.Osclient - weight int } func NewHostnameHandler() *HostnameHandler { diff --git a/ekms/internal/kms/event/bus.go b/ekms/internal/kms/event/bus.go index 562e4a1e3750cbc07161fe28afbc32fb0bbb7ead..301b883b09fa8d71d10cfae043415fc5adad0e80 100644 --- a/ekms/internal/kms/event/bus.go +++ b/ekms/internal/kms/event/bus.go @@ -18,7 +18,7 @@ func (b *EventBus) Subscribe(topic Topic) (<-chan Event, error) { subs, ok := b.subscribers[topic] if !ok { initialSub := map[chan<- Event]struct{}{ - newSubChan: struct{}{}, + newSubChan: {}, } b.subscribers[topic] = initialSub } else if subs != nil { @@ -35,7 +35,7 @@ func (b *EventBus) Publish(event Event) error { if !ok { return fmt.Errorf("There are no active subscribers for topic: %d", event.Topic()) } - for sub, _ := range subs { + for sub := range subs { sub <- event } return nil diff --git a/ekms/internal/kms/kms-keystore.go b/ekms/internal/kms/kms-keystore.go index 466d1ea62c351cb86a6402c94bf99214a41ead2a..3541211e9eee8018a526e332741f6ecd62a85799 100644 --- a/ekms/internal/kms/kms-keystore.go +++ b/ekms/internal/kms/kms-keystore.go @@ -17,7 +17,7 @@ const ( USED ) -// holds a single ready to bit key, length can be configured +// holds a single ready to bit key, length can be configured. type kmsKSElement struct { keyID uuid.UUID key []byte // a key @@ -44,7 +44,7 @@ func (ks *kmsKeyStore) addKey(keyId uuid.UUID, keyToadd []byte) { // test for collisions if _, notThere := ks.keyStore[keyId]; notThere { - log.Errorf("Whop: addKey collission of key id %s", keyId) + log.Errorf("Whop: addKey collisions of key id %s", keyId) return } diff --git a/ekms/internal/kms/kms.go b/ekms/internal/kms/kms.go index 6868480fd557950076076cd4cfbfd569a2324056..93cdb536663d9427d10517f55b2b3e535e8255e4 100644 --- a/ekms/internal/kms/kms.go +++ b/ekms/internal/kms/kms.go @@ -1,4 +1,4 @@ -// This package kms implements a simplistic key managment system (kms) for +// This package kms implements a simplistic key management system (kms) for // Quantum Key Distribution Networks (QKDN) which is a simple emulated KMS. x // It relies on the emulated quantum link out of the quantumlayer package @@ -36,7 +36,7 @@ const ( BitKeyLen512 BitKeyLength = "512" ) -// The general emulated KMS +// The general emulated KMS. type EKMS struct { kmsName string kmsUUID uuid.UUID @@ -46,8 +46,6 @@ type EKMS struct { quantumModulesMutex sync.RWMutex kmsPeersMutex sync.Mutex // TODO(maba): find a better name for this - // TODO: add mutex - keysForPathId map[uuid.UUID]string routingTable map[uuid.UUID]*Route routingTableMutex sync.RWMutex KmsPeers map[string]*kmsPeer @@ -167,7 +165,7 @@ func (kms *EKMS) AddPeer(peerKmsId string, kmsPeerSocket string, servingQLE Quan func (kms *EKMS) AssignForwardingRoute(pId, pHop, nHop string) error { pathId, err := uuid.Parse(pId) if err != nil { - return fmt.Errorf("The given path id %s is no uuid; err = ", pathId, err) + return fmt.Errorf("The given path id %s is no uuid; err = %w", pathId, err) } var previousHop *kmsPeer @@ -207,7 +205,7 @@ func (kms *EKMS) EventBus() *event.EventBus { return kms.eventBus } -// TODO/XXX error handling +// TODO/XXX error handling. func (kms *EKMS) RemovePeer(kmsPeerSocket string) { if _, there := kms.KmsPeers[kmsPeerSocket]; there { // peer.quit <- true @@ -215,7 +213,6 @@ func (kms *EKMS) RemovePeer(kmsPeerSocket string) { return } log.Errorf("%s: Can not find a peer with socket: %s", kms.kmsName, kmsPeerSocket) - return } func (kms *EKMS) FindPeerUuid(lookup uuid.UUID) (peer *kmsPeer) { @@ -231,25 +228,25 @@ func (kms *EKMS) FindPeerUuid(lookup uuid.UUID) (peer *kmsPeer) { } func (kms *EKMS) RoutingTableDeepCopy() map[uuid.UUID]*Route { - copy := make(map[uuid.UUID]*Route, len(kms.KmsPeers)) + routingTableCopy := make(map[uuid.UUID]*Route, len(kms.KmsPeers)) kms.routingTableMutex.Lock() for k, v := range kms.routingTable { - copy[k] = v + routingTableCopy[k] = v } kms.routingTableMutex.Unlock() - return copy + return routingTableCopy } func (kms *EKMS) PeersDeepCopy() map[string]*kmsPeer { - copy := make(map[string]*kmsPeer, len(kms.KmsPeers)) + peersCopy := make(map[string]*kmsPeer, len(kms.KmsPeers)) kms.kmsPeersMutex.Lock() for k, v := range kms.KmsPeers { - copy[k] = v + peersCopy[k] = v } kms.kmsPeersMutex.Unlock() - return copy + return peersCopy } diff --git a/ekms/internal/kms/kmsetsi.go b/ekms/internal/kms/kmsetsi.go index 767d4a919c0965c3369163e3e34474ac79b4a94e..205e9d3a70082b8c3856810bf1147a4c72cb863d 100644 --- a/ekms/internal/kms/kmsetsi.go +++ b/ekms/internal/kms/kmsetsi.go @@ -2,7 +2,6 @@ package kms import ( "context" - "errors" "flag" "fmt" "net" @@ -18,9 +17,7 @@ import ( "google.golang.org/grpc/status" ) -var etsiPort = flag.Int("port", 50900, "The server port") - -// TODO: remove etsiServer +// TODO: remove etsiServer. type etsiServer struct { pb.UnimplementedKmsETSIServer handlingEkms *EKMS @@ -35,7 +32,7 @@ func (es *etsiServer) ETSICapabilities(ctx context.Context, in *pb.ETSICapabilit } func (es *etsiServer) ETSIGetQuantumInterfaces(ctx context.Context, in *pb.ETSIKMSQuantumInterfaceListRequest) (qleReply *pb.ETSIKMSQuantumInterfaceListReply, err error) { - qleList := make([]*pb.QuantumElementInfo, 1) + var qleList []*pb.QuantumElementInfo // Walk through QuantumLayerInterfaces and return their information for _, qlWorks := range es.handlingEkms.quantumModules { @@ -50,23 +47,26 @@ func (es *etsiServer) ETSIGetQuantumInterfaces(ctx context.Context, in *pb.ETSIK }, nil } -// TODO: reimplement +// TODO: reimplement. func (es *etsiServer) ETSIAddKMSPeer(ctx context.Context, in *pb.ETSIKMSPeerRequest) (*pb.ETSIKMSPeerReply, error) { // determine the kms structure to call log.Debugf("AddKMSPeer called.") // Check first if KmsLocalQLEId is actually one of ours... qleID := uuid.MustParse(in.KmsLocalQLEId) - servingQLE, _ := es.handlingEkms.quantumModules[""] + servingQLE := es.handlingEkms.quantumModules[""] if servingQLE == nil { // no such element! - err := errors.New(fmt.Sprintf("Unknown local quantum element with ID %d", qleID)) + err := fmt.Errorf("Unknown local quantum element with ID %d", qleID) return &pb.ETSIKMSPeerReply{}, err } // TODO: remove hardcoded id - es.handlingEkms.AddPeer("default", in.GetKmsPeerSocket(), servingQLE) + _, err := es.handlingEkms.AddPeer("default", in.GetKmsPeerSocket(), servingQLE) + if err != nil { + return nil, err + } return &pb.ETSIKMSPeerReply{ KmsPeerName: es.handlingEkms.kmsName, @@ -101,7 +101,7 @@ func (es *etsiServer) ETSIGetPeerList(ctx context.Context, in *pb.ETSIKMSPeerLis func (es *etsiServer) ETSIAssignForwarding(ctx context.Context, in *pb.ETSIAssignForwardingRequest) (*pb.ETSIAssignForwardingReply, error) { pathId, err := uuid.Parse(in.GetPathId()) if err != nil { - return nil, status.Errorf(codes.InvalidArgument, "The given path id %s is no uuid; err = ", in.GetPathId(), err) + return nil, status.Errorf(codes.InvalidArgument, "The given path id %s is no uuid; err = %s", in.GetPathId(), err) } var previousHop *kmsPeer @@ -142,7 +142,7 @@ func (es *etsiServer) ETSIAssignForwarding(ctx context.Context, in *pb.ETSIAssig func (es *etsiServer) ETSISendPayload(ctx context.Context, in *pb.ETSISendPayloadRequest) (*pb.ETSISendPayloadResponse, error) { pathId, err := uuid.Parse(in.GetPathId()) if err != nil { - return nil, status.Errorf(codes.InvalidArgument, "The given path id %s is no uuid; err = ", in.GetPathId(), err) + return nil, status.Errorf(codes.InvalidArgument, "The given path id %s is no uuid; err = %s ", in.GetPathId(), err) } route, ok := es.handlingEkms.routingTable[pathId] @@ -166,7 +166,7 @@ func (es *etsiServer) ETSISendPayload(ctx context.Context, in *pb.ETSISendPayloa //} if err := route.Next.SendPayload([]byte(in.GetPayload()), pathId); err != nil { - return nil, status.Errorf(codes.Internal, "Failed to send payload: ", err) + return nil, status.Errorf(codes.Internal, "Failed to send payload: %s", err) } return &pb.ETSISendPayloadResponse{ diff --git a/ekms/internal/kms/kmsintercom.go b/ekms/internal/kms/kmsintercom.go index a941444e5c60eee8fd3a51d5cf2dd32f43646621..bb35c92bea20712de617ddcc2a6e46c439038771 100644 --- a/ekms/internal/kms/kmsintercom.go +++ b/ekms/internal/kms/kmsintercom.go @@ -22,7 +22,7 @@ type kmsTalkerServer struct { eKMS *EKMS } -// This must somehow find out and agree to a specific key lenght +// This must somehow find out and agree to a specific key length. func (s *kmsTalkerServer) InterComCapabilities(ctx context.Context, in *pb.InterComCapabilitiesRequest) (capReply *pb.InterComCapabilitiesReply, err error) { log.Debugf("Received: %v", in.GetMyKmsName()) @@ -61,7 +61,11 @@ func (s *kmsTalkerServer) KeyIdNotification(ctx context.Context, in *pb.KeyIdNot return nil, err } - defer resp.Body.Close() + defer func() { + if closeError := resp.Body.Close(); closeError != nil { + log.Errorf("KeyIdNotification: response closing failure: %s", err) + } + }() // TODO: add proper status code handling if resp.StatusCode != 200 { @@ -83,7 +87,7 @@ func (s *kmsTalkerServer) KeyIdNotification(ctx context.Context, in *pb.KeyIdNot } // TODO: should be removed as soon as the emulated quantum module has been -// changed; is specific for emulated quantum module +// changed; is specific for emulated quantum module. func (s *kmsTalkerServer) SyncQkdBulk(ctx context.Context, in *pb.SyncQkdBulkRequest) (*pb.SyncQkdBulkResponse, error) { // NOTE: with "google.golang.org/grpc/peer" it would be possible to get the client ip directly @@ -227,7 +231,9 @@ func (s *kmsTalkerServer) KeyForwarding(ctx context.Context, in *pb.KeyForwardin if route.Next != nil { log.Infof("%s forwards payload to : %s", s.eKMS.kmsName, route.Next.tcpSocketStr) - go route.Next.SendPayload(decryptedPayload, pathId) + // TODO: find a better way of handling this; ignore the lint error for + // now. + go route.Next.SendPayload(decryptedPayload, pathId) //nolint:errcheck } else { log.Infof("%s received the final payload: %s", s.eKMS.kmsName, string(decryptedPayload)) } diff --git a/ekms/internal/kms/kmspeers.go b/ekms/internal/kms/kmspeers.go index 70d8e3472b3849cb6bb22b9c12653539af76e2ac..2b7ed0a5ea8f5a00ed2f17d42c4aedf9c4544345 100644 --- a/ekms/internal/kms/kmspeers.go +++ b/ekms/internal/kms/kmspeers.go @@ -20,16 +20,17 @@ type KmsPeerStatus int16 const ( KmsPeerUp KmsPeerStatus = iota // peer was seen up lately KmsPeerDown // peer not reachable anymore - KmsPeerPending // peer was added and has to be succesfully contacted once + KmsPeerPending // peer was added and has to be successfully contacted once KmsPeerUnknown // not known, not initialized ) -type kmsPeerInfo interface { - GetKmsPeerStatus() KmsPeerStatus - GetKmsPeerId() uuid.UUID - GetKmsPeerQkdiId() uint32 - KmsPeerKeyInit() -} +// NOTE: currently not used, could be of usage later on +// type kmsPeerInfo interface { +// GetKmsPeerStatus() KmsPeerStatus +// GetKmsPeerId() uuid.UUID +// GetKmsPeerQkdiId() uint32 +// KmsPeerKeyInit() +// } type kmsPeer struct { peerClient pbIC.KmsTalkerClient @@ -40,15 +41,16 @@ type kmsPeer struct { tcpSocket *net.TCPAddr // the IP address and TCP port (aka socket) of the kms peer tcpSocketStr string // string rep. of tcpSocket et CryptoAlgorithm - name string // the name of the kms peer - id uuid.UUID // uuid of the peer - quit chan bool // cancel the peer goroutine - eventBus *event.EventBus + // NOTE: currently not used, could be of usage later on + // name string // the name of the kms peer + id uuid.UUID // uuid of the peer + quit chan bool // cancel the peer goroutine + eventBus *event.EventBus } func NewKmsPeer(peerKmsId string, servQM QuantumModule, tcpSocketStr string, interComAddr string, eventBus *event.EventBus) (*kmsPeer, error) { if servQM.Peer() != nil { - return nil, fmt.Errorf("QuantumModule with ID: , already has a peer", servQM.ID()) + return nil, fmt.Errorf("QuantumModule with ID: %s, already has a peer", servQM.ID()) } peerKmsIdUUID, err := uuid.Parse(peerKmsId) diff --git a/ekms/internal/kms/module.go b/ekms/internal/kms/module.go index 4d5fa386112aca7a3d4c744994d53e56edc597d2..a2fc337c7693a1e90e6ed597c1ec319f584d7ed9 100644 --- a/ekms/internal/kms/module.go +++ b/ekms/internal/kms/module.go @@ -161,7 +161,7 @@ func (eqe *EmulatedQuantumModule) SetPeer(peer *kmsPeer) { // Takes a bulk of keys and chops them in chopFactor keys each // Any remainder is discarded -// If keyIds is empty, uuids are generated +// If keyIds is empty, uuids are generated. func (eqe *EmulatedQuantumModule) KeyChopper(bulkKey *quantumlayer.QuantumLayerBulkKey, keyIds []string) ([]string, map[uuid.UUID][]byte, error) { if eqe.keyStore.keySingleSize == 0 { return nil, nil, errors.New("KeyChopper: no keySingleSize set") @@ -291,7 +291,6 @@ func (eqe *ETSI014HTTPQuantumModule) Initialize() error { if err := addETSIKeysToKeystore(eqe.keyStore, container.GetKeys()); err != nil { log.Error(err) - break } } } diff --git a/ekms/internal/kms/quipsec.go b/ekms/internal/kms/quipsec.go index d3971c74be10a0abd3e278b0320d2aefa7e4b749..77fe1a4106653c7eae0adce1704609392b3c7a54 100644 --- a/ekms/internal/kms/quipsec.go +++ b/ekms/internal/kms/quipsec.go @@ -23,6 +23,7 @@ func (qs *quipSecServer) PushKeys(ctx context.Context, req *pb.PushKeysRequest) p, _ := peer.FromContext(ctx) host, _, err := net.SplitHostPort(p.Addr.String()) if err != nil { + return nil, status.Errorf(codes.Internal, "could not get host from peer") } for _, qm := range qs.eKMS.quantumModules { diff --git a/ekms/internal/kms/util.go b/ekms/internal/kms/util.go index 8a9949e6226deec5d3a99a4f43f0001c4b7af00a..ebd74c40b62c77bf389cf5da93ed23e2b2cdca0e 100644 --- a/ekms/internal/kms/util.go +++ b/ekms/internal/kms/util.go @@ -8,9 +8,10 @@ import ( etsi14 "code.fbi.h-da.de/danet/quant/ekms/api/go/rest/etsi/client" "github.com/google/uuid" + "github.com/hashicorp/go-multierror" ) -func randomItemFromMap[T comparable, M any](m map[T]M) (M, error) { +func RandomItemFromMap[T comparable, M any](m map[T]M) (M, error) { for _, item := range m { return item, nil } @@ -19,14 +20,14 @@ func randomItemFromMap[T comparable, M any](m map[T]M) (M, error) { return r, fmt.Errorf("Could not return a random item from map %v", m) } -func randomItemFromMapAndRemove[T comparable, M any](m map[T]M) (M, error) { +func RandomItemFromMapAndRemove[T comparable, M any](m map[T]M) (M, error) { for key, item := range m { delete(m, key) return item, nil } var r M - return r, fmt.Errorf("Could not return a random item from map %v and delete it.", m) + return r, fmt.Errorf("Could not return a random item from map %v and delete it", m) } func keysOfMap[T comparable, M any](m map[T]M) []T { @@ -58,8 +59,8 @@ func addETSIKeysToKeystore(keyStore *kmsKeyStore, keyContainer []etsi14.KeyConta return nil } -// NOTE: For demo purpose only -func sendKmsInfoMessage(url string, json []byte) error { +// NOTE: For demo purpose only. +func SendKmsInfoMessage(url string, json []byte) (err error) { request, err := http.NewRequest("POST", url, bytes.NewBuffer(json)) if err != nil { return err @@ -67,10 +68,17 @@ func sendKmsInfoMessage(url string, json []byte) error { request.Header.Set("Content-Type", "application/json; charset=UTF-8") client := &http.Client{} response, err := client.Do(request) - defer response.Body.Close() if err != nil { + if closeError := response.Body.Close(); closeError != nil { + err = multierror.Append(err, closeError) + } return err } + defer func() { + if closeError := response.Body.Close(); closeError != nil { + err = multierror.Append(err, closeError) + } + }() return nil } diff --git a/ekms/osclient/additions/system_linux.go b/ekms/osclient/additions/system_linux.go index 5d348023ef4fa87fe3e8ba198c90d8fecc93c210..b2ddd6c91d3002b900cbf961c6ab4575cba2de52 100644 --- a/ekms/osclient/additions/system_linux.go +++ b/ekms/osclient/additions/system_linux.go @@ -15,7 +15,7 @@ type system struct { pfs procfs.FS } -// NewSystem() Initalizes OS specific interfaces +// NewSystem() Initializes OS specific interfaces // Linux: // - Access to procfs func NewSystem() (System, error) { @@ -46,7 +46,6 @@ func (sys *system) GetFreeMemory() uint64 { } func (sys *system) GetTotalMemory() uint64 { - memInfo, err := sys.pfs.Meminfo() if err != nil { // TODO: better error handling is required @@ -69,7 +68,6 @@ func (sys *system) GetUsedMemory() uint64 { } func (sys *system) GetSoftwareVersion() (string, error) { - var returnString string var osID string var osVersion string diff --git a/ekms/osclient/additions/system_linux_test.go b/ekms/osclient/additions/system_linux_test.go index e6d1dc04226e6f43de334c5c4cf369f0e915b60d..f583231793f651a1d266a211f0b9e96f8d3c3766 100644 --- a/ekms/osclient/additions/system_linux_test.go +++ b/ekms/osclient/additions/system_linux_test.go @@ -6,7 +6,6 @@ import ( ) func TestSystemLinux(t *testing.T) { - // Retrieve new system for testin sys, err := NewSystem() if err != nil { diff --git a/ekms/osclient/client.go b/ekms/osclient/client.go index 6c235555f5681bba9c3f76f2c2b76a6cbe879a0f..c37ec4addfaf707b9115e2645e032d7a127e3f76 100644 --- a/ekms/osclient/client.go +++ b/ekms/osclient/client.go @@ -5,7 +5,7 @@ import ( "github.com/openconfig/ygot/ygot" ) -// Osclient describes +// Osclient describes. type Osclient interface { additions.System UpdateConfig(config *ygot.ValidatedGoStruct) error diff --git a/ekms/restserver/restserver.go b/ekms/restserver/restserver.go index 2ba5a8d3bc8f3bd7e32664510c09a6f5a3dd4cff..26c38ed7ab8b8a8813cf9e96ce937df5f9f697c3 100644 --- a/ekms/restserver/restserver.go +++ b/ekms/restserver/restserver.go @@ -22,11 +22,12 @@ func SetupETSI14RestServer(etsi14RESTService *ETSI14RESTService) { etsi14APIController := restserver.NewDefaultAPIController(etsi14RESTService) router := restserver.NewRouter(etsi14APIController) - go http.ListenAndServe(etsi14RESTService.serviceAddress, router) + // NOTE check again, currently ignoring + go http.ListenAndServe(etsi14RESTService.serviceAddress, router) //nolint:errcheck logrus.Info("Server started") } -// GetKey - TBD +// GetKey - TBD. func (s *ETSI14RESTService) GetKey(ctx context.Context, slaveSAEID interface{}, number int64, size int64) (restserver.ImplResponse, error) { // TODO - update GetKey with the required logic for this service method. // Add api_default_service.go to the .openapi-generator-ignore to avoid overwriting this service implementation when updating open api generation. @@ -56,7 +57,7 @@ func (s *ETSI14RESTService) GetKey(ctx context.Context, slaveSAEID interface{}, return restserver.Response(http.StatusOK, keyContainer), nil } -// GetKeyPost - +// GetKeyPost -. func (s *ETSI14RESTService) GetKeyPost(ctx context.Context, slaveSAEID interface{}, keyRequest restserver.KeyRequest) (restserver.ImplResponse, error) { // TODO - update GetKeyPost with the required logic for this service method. // Add api_default_service.go to the .openapi-generator-ignore to avoid overwriting this service implementation when updating open api generation. @@ -82,7 +83,7 @@ func (s *ETSI14RESTService) GetKeyPost(ctx context.Context, slaveSAEID interface return restserver.Response(http.StatusOK, keyContainer), nil } -// GetKeyWithIds - TBD +// GetKeyWithIds - TBD. func (s *ETSI14RESTService) GetKeyWithIds(ctx context.Context, masterSAEID interface{}, keyID string) (restserver.ImplResponse, error) { // TODO - update GetKeyWithIds with the required logic for this service method. // Add api_default_service.go to the .openapi-generator-ignore to avoid overwriting this service implementation when updating open api generation. @@ -108,7 +109,7 @@ func (s *ETSI14RESTService) GetKeyWithIds(ctx context.Context, masterSAEID inter return restserver.Response(http.StatusOK, keyContainer), nil } -// GetKeyWithIdsPost - TBD +// GetKeyWithIdsPost - TBD. func (s *ETSI14RESTService) GetKeyWithIdsPost(ctx context.Context, masterSAEID interface{}, keyIdsRequest restserver.KeyIdsRequest) (restserver.ImplResponse, error) { // TODO - update GetKeyWithIdsPost with the required logic for this service method. // Add api_default_service.go to the .openapi-generator-ignore to avoid overwriting this service implementation when updating open api generation. @@ -134,7 +135,7 @@ func (s *ETSI14RESTService) GetKeyWithIdsPost(ctx context.Context, masterSAEID i return restserver.Response(http.StatusOK, keyContainer), nil } -// GetStatus - TBD +// GetStatus - TBD. func (s *ETSI14RESTService) GetStatus(ctx context.Context, slaveSAEID interface{}) (restserver.ImplResponse, error) { // TODO - update GetStatus with the required logic for this service method. // Add api_default_service.go to the .openapi-generator-ignore to avoid overwriting this service implementation when updating open api generation. diff --git a/go.mod b/go.mod index 61ac342c5f5ab59a0a20ed27278c661a5ca1019a..eb9752a045a7e4dd94aba873b529cdfecbeaf047 100644 --- a/go.mod +++ b/go.mod @@ -8,6 +8,7 @@ require ( github.com/google/uuid v1.3.1 github.com/gorilla/mux v1.8.0 github.com/grpc-ecosystem/grpc-gateway/v2 v2.18.0 + github.com/hashicorp/go-multierror v1.1.1 github.com/openconfig/gnmi v0.10.0 github.com/openconfig/goyang v1.4.2 github.com/openconfig/ygot v0.29.12 @@ -32,6 +33,7 @@ require ( github.com/golang/glog v1.1.2 // indirect github.com/golang/protobuf v1.5.3 // indirect github.com/google/go-cmp v0.5.9 // indirect + github.com/hashicorp/errwrap v1.0.0 // indirect github.com/hashicorp/hcl v1.0.0 // indirect github.com/inconshreveable/mousetrap v1.1.0 // indirect github.com/kylelemons/godebug v1.1.0 // indirect diff --git a/go.sum b/go.sum index c2832d8c09c9c682c0851a7d2b6544eddb162620..188786223d6c21b77a5ad43b267d321107726e66 100644 --- a/go.sum +++ b/go.sum @@ -142,6 +142,10 @@ github.com/gorilla/mux v1.8.0 h1:i40aqfkR1h2SlN9hojwV5ZA91wcXFOvkdNIeFDP5koI= github.com/gorilla/mux v1.8.0/go.mod h1:DVbg23sWSpFRCP0SfiEN6jmj59UnW/n46BH5rLB71So= github.com/grpc-ecosystem/grpc-gateway/v2 v2.18.0 h1:RtRsiaGvWxcwd8y3BiRZxsylPT8hLWZ5SPcfI+3IDNk= github.com/grpc-ecosystem/grpc-gateway/v2 v2.18.0/go.mod h1:TzP6duP4Py2pHLVPPQp42aoYI92+PCrVotyR5e8Vqlk= +github.com/hashicorp/errwrap v1.0.0 h1:hLrqtEDnRye3+sgx6z4qVLNuviH3MR5aQ0ykNJa/UYA= +github.com/hashicorp/errwrap v1.0.0/go.mod h1:YH+1FKiLXxHSkmPseP+kNlulaMuP3n2brvKWEqk/Jc4= +github.com/hashicorp/go-multierror v1.1.1 h1:H5DkEtf6CXdFp0N0Em5UCwQpXMWke8IA0+lD48awMYo= +github.com/hashicorp/go-multierror v1.1.1/go.mod h1:iw975J/qwKPdAO1clOe2L8331t/9/fmwbPZ6JB6eMoM= github.com/hashicorp/golang-lru v0.5.0/go.mod h1:/m3WP610KZHVQ1SGc6re/UDhFvYD7pJ4Ao+sR/qLZy8= github.com/hashicorp/golang-lru v0.5.1/go.mod h1:/m3WP610KZHVQ1SGc6re/UDhFvYD7pJ4Ao+sR/qLZy8= github.com/hashicorp/hcl v1.0.0 h1:0Anlzjpi4vEasTeNFn2mLJgTSwt0+6sfsiTG8qcWGx4= diff --git a/quantumlayer/example/main.go b/quantumlayer/example/main.go index 686ccc87b872c74708db1dce0cf6c277de185a01..f29635658d51596bd8435a0bb892fc1ddf4e7b9d 100644 --- a/quantumlayer/example/main.go +++ b/quantumlayer/example/main.go @@ -52,7 +52,7 @@ func main() { return } - stopChan := make(chan os.Signal) + stopChan := make(chan os.Signal, 1) signal.Notify(stopChan, os.Interrupt, syscall.SIGTERM) ql := quantumlayer.NewQuantumlayerEmuPRNG(kmsClient, os.Stdout, logrus.GetLevel(), false) diff --git a/quantumlayer/quantumlayer-emu-prng.go b/quantumlayer/quantumlayer-emu-prng.go index d70095adf735004b54a684d632d6f2844470e52f..d989fc102a6caf4be35c3673447c6fdecad79c48 100644 --- a/quantumlayer/quantumlayer-emu-prng.go +++ b/quantumlayer/quantumlayer-emu-prng.go @@ -7,7 +7,7 @@ package quantumlayer * sender to a quantum receiver. * This relies on crypto/rand to generate the random numbers that will be * transmitted to the other end. - * + *. */ import ( "context" @@ -56,7 +56,7 @@ func NewQuantumlayerEmuPRNG(client pb.KmsQkdmCommunicationServiceClient, logOutp * Setup logging */ - //What level + // What level log.SetLevel(logLevel) // Where to send log out put log.SetOutput(logOutput) @@ -86,9 +86,8 @@ func NewQuantumlayerEmuPRNG(client pb.KmsQkdmCommunicationServiceClient, logOutp } } -// Configure the quantum emulation, but do not start if yet +// Configure the quantum emulation, but do not start if yet. func (qlemuprng *QuantumlayerEmuPRNG) Configure(enableKeyGeneration bool, localQLAddress ...string) { - // Start receiving numberstores go qlemuprng.peerNumbers.receiveNumbers(qlemuprng.incomingRandNums, qlemuprng.client) @@ -104,14 +103,14 @@ func (qlemuprng *QuantumlayerEmuPRNG) Configure(enableKeyGeneration bool, localQ } // Power on the quantum layer, i.e., open up the communication ports for the -// other quantum module +// other quantum module. func (qlemuprng *QuantumlayerEmuPRNG) PowerOn() { if !qlemuprng.configured { // nothing do here move on log.Errorf("QuantumlayerEmuPRNG: Sorry, the quantum layer is not configured for action. You've missed Configure()") return } - //qlemuprng.poweron = false + // qlemuprng.poweron = false log.Infof("QuantumlayerEmuPRNG: is powering on...charging.") if qlemuprng.generateKeys { @@ -135,10 +134,19 @@ func (qlemuprng *QuantumlayerEmuPRNG) PowerOn() { log.Fatalf("QuantumlayerEmuPRNG: UDP failure: %s", err) return } - defer qlemuprng.udpSrvConn.Close() + defer func() { + if closeError := qlemuprng.udpSrvConn.Close(); closeError != nil { + log.Errorf("QuantumlayerEmuPRNG: udpSrvConn closing failure: %s", err) + } + }() // Retrieve local UDP address and store it for further actions. - qlemuprng.qlLocalPort = qlemuprng.udpSrvConn.LocalAddr().(*net.UDPAddr) + tempPort, ok := qlemuprng.udpSrvConn.LocalAddr().(*net.UDPAddr) + if !ok { + return + } + + qlemuprng.qlLocalPort = tempPort // TODO: This does not seem to be necessary if the gle is not generating rands // serve UDP incoming @@ -156,7 +164,7 @@ func (qlemuprng *QuantumlayerEmuPRNG) PowerOn() { // Warning this is not checking the validity of the sender, i.e., spoofing is possible if addr.String() == qlemuprng.qlPeer { log.Debugf("QuantumlayerEmuPRNG: Peer %s listed", addr) - //dumb the received data into the channel and carry on + // dumb the received data into the channel and carry on // TODO/XXX: no vetting for anything // Unmarshall out of JSON var inQBuffer QuantumPayloadElement @@ -174,6 +182,7 @@ func (qlemuprng *QuantumlayerEmuPRNG) PowerOn() { // Wait for listening UDP socket in the above go-routine to get ready for qlemuprng.udpSrvConn == nil { + time.Sleep(10 * time.Millisecond) } // Ready, set, go! @@ -183,7 +192,7 @@ func (qlemuprng *QuantumlayerEmuPRNG) PowerOn() { } // Power off the quantum layer, i.e., close the communication ports for the -// other quantum module +// other quantum module. func (qlemuprng *QuantumlayerEmuPRNG) PowerOff() { qlemuprng.poweron = false log.Println("QuantumlayerEmuPRNG: is powered off...discharging.") @@ -193,7 +202,7 @@ func (qlemuprng *QuantumlayerEmuPRNG) AddPeer(addr *net.UDPAddr) { if !qlemuprng.poweron { return } - //TODO/XXX check the incoming addr + // TODO/XXX check the incoming addr // Add peer to the .... qlemuprng.qlPeerMutex.Lock() @@ -216,7 +225,7 @@ func (qlemuprng *QuantumlayerEmuPRNG) AddPeer(addr *net.UDPAddr) { // retrieve a new back of random numbers newNumberBatch := qlemuprng.GenerateRandomNumbers() // TODO: Replace this by some generic encapsulation reader and not just JSON - //Get JSON for transmission ready + // Get JSON for transmission ready qpe := QuantumPayloadElement{time.Now().UnixNano(), len(newNumberBatch), &newNumberBatch} // XXX/TODO: error must be handled @@ -292,7 +301,7 @@ type NumberStore struct { topOfStorage int } -// Generates a new store with given maximum number of bytes +// Generates a new store with given maximum number of bytes. func NewNumberStore(maxBytes int) (newNS *NumberStore) { return &NumberStore{ maxBytes: maxBytes, @@ -353,7 +362,7 @@ func (store *NumberStore) receiveNumbers(incoming chan QuantumPayloadElement, cl BulkKeyLength: receivedNumbers.BulkKeyLength, BulkKey: receivedNumbers.BulkKey, } - //store.bulkKeyStorage[receivedNumbers.BulkKeyId] = mem + // store.bulkKeyStorage[receivedNumbers.BulkKeyId] = mem store.bulkKeyStorage = append(store.bulkKeyStorage, mem) store.mu.Unlock() diff --git a/quantumlayer/quantumlayer-emu-prng_test.go b/quantumlayer/quantumlayer-emu-prng_test.go index 55854214246986afb98ba77fb37b00bf49ecbf93..fdaa5e77b746fe3443ac3de4020319c119d1a16a 100644 --- a/quantumlayer/quantumlayer-emu-prng_test.go +++ b/quantumlayer/quantumlayer-emu-prng_test.go @@ -13,7 +13,6 @@ import ( ) func TestQuantumLayer(t *testing.T) { - // Generate UDPAddr for ql1 peer udpQL2AddrString := fmt.Sprintf("127.0.0.1:%d", 5002) udpQL2Addr, err := net.ResolveUDPAddr("udp", udpQL2AddrString) @@ -57,6 +56,5 @@ func TestQuantumLayer(t *testing.T) { // TODO: Calculate checksum of BulkKey and double-check time.Sleep(5 * time.Second) - } }