diff --git a/.changelog/3095.internal.md b/.changelog/3095.internal.md new file mode 100644 index 00000000000..9edc70889e5 --- /dev/null +++ b/.changelog/3095.internal.md @@ -0,0 +1 @@ +go: Use gofumpt instead of gofmt to format Go diff --git a/docker/development/Dockerfile b/docker/development/Dockerfile index d23bb71b8de..ef556c5cb65 100644 --- a/docker/development/Dockerfile +++ b/docker/development/Dockerfile @@ -4,8 +4,9 @@ FROM ubuntu:18.04 ARG GO_VERSION=1.14.3 ARG GO_PROTOC_VERSION=3.6.1 ARG GO_PROTOC_GEN_GO_VERSION=1.21.0 -ARG GOLANGCILINT_VERSION=1.23.6 +ARG GOLANGCILINT_VERSION=1.28.2 ARG GOCOVMERGE_VERSION=b5bfa59ec0adc420475f97f89b58045c721d761c +ARG GOFUMPT_VERSION=abc0db2c416aca0f60ea33c23c76665f6e7ba0b6 ARG RUST_NIGHTLY_VERSION=2020-06-09 ARG DEBIAN_FRONTEND=noninteractive @@ -64,7 +65,10 @@ RUN wget https://dl.google.com/go/go${GO_VERSION}.linux-amd64.tar.gz && \ curl -sfL -o nancy https://github.com/sonatype-nexus-community/nancy/releases/download/v0.0.39/nancy-linux.amd64-v0.0.39 && \ echo 'eb3a93d7db24d115e6e67a2b17dba402978f856c891fa6f0ff09ad17ac53ebb5 nancy' | sha256sum -c && \ mv nancy /go/bin/nancy && \ - chmod +x /go/bin/nancy + chmod +x /go/bin/nancy && \ + # Install gofumpt for code formatting. + GO111MODULE=on go get mvdan.cc/gofumpt@${GOFUMPT_VERSION} && \ + GO111MODULE=on go get mvdan.cc/gofumpt/gofumports@${GOFUMPT_VERSION} # Install bubblewrap (we need version 0.3.3 which is not available for 18.04). RUN wget http://archive.ubuntu.com/ubuntu/pool/main/b/bubblewrap/bubblewrap_0.3.3-2_amd64.deb && \ diff --git a/docs/setup/prerequisites.md b/docs/setup/prerequisites.md index 1b2eb0a6440..eecbd0a2963 100644 --- a/docs/setup/prerequisites.md +++ b/docs/setup/prerequisites.md @@ -132,6 +132,19 @@ Core: rustup target add x86_64-fortanix-unknown-sgx ``` +* (**OPTIONAL**) [gofumpt and gofumports]. + + Required if you plan to change any of the Go code in order for automated code + formatting (`make fmt`) to work. + + Download and install it with: + + ``` + export GOFUMPT_VERSION=abc0db2c416aca0f60ea33c23c76665f6e7ba0b6 + GO111MODULE=on ${OASIS_GO:-go} get mvdan.cc/gofumpt@${GOFUMPT_VERSION} + GO111MODULE=on ${OASIS_GO:-go} get mvdan.cc/gofumpt/gofumports@${GOFUMPT_VERSION} + ``` + * (**OPTIONAL**) [protoc-gen-go]. Download and install it with: @@ -173,6 +186,7 @@ where the code has been checked out. [rust-toolchain-precedence]: https://github.com/rust-lang/rustup/blob/master/README.md#override-precedence [Fortanix Rust EDP]: https://edp.fortanix.com +[gofumpt and gofumports]: https://github.com/mvdan/gofumpt [protoc-gen-go]: https://github.com/golang/protobuf ## Using the development Docker image diff --git a/go/.golangci.yml b/go/.golangci.yml index ba389d19762..dbdfb35b7c5 100644 --- a/go/.golangci.yml +++ b/go/.golangci.yml @@ -13,7 +13,7 @@ linters: - errcheck - goconst - gocyclo - - gofmt + - gofumpt - golint - gas - typecheck diff --git a/go/Makefile b/go/Makefile index 9ba1247d835..eda1e206a5f 100644 --- a/go/Makefile +++ b/go/Makefile @@ -12,6 +12,7 @@ all: build generate: @$(ECHO) "$(MAGENTA)*** Running go generate...$(OFF)" @$(GO) generate ./... + @$(MAKE) fmt # Build. # List of Go binaries to build. @@ -48,8 +49,9 @@ $(test-vectors-targets): # Format code. fmt: - @$(ECHO) "$(CYAN)*** Running go fmt...$(OFF)" - @$(GO) fmt ./... + @$(ECHO) "$(CYAN)*** Running Go formatters...$(OFF)" + @gofumpt -s -w . + @gofumports -w -local github.com/oasisprotocol/oasis-core . # Lint. lint: diff --git a/go/common/crypto/mrae/deoxysii/asymmetric_test.go b/go/common/crypto/mrae/deoxysii/asymmetric_test.go index 9759628ebbb..0ccbf868fc6 100644 --- a/go/common/crypto/mrae/deoxysii/asymmetric_test.go +++ b/go/common/crypto/mrae/deoxysii/asymmetric_test.go @@ -4,6 +4,7 @@ import ( "testing" "github.com/oasisprotocol/deoxysii" + "github.com/oasisprotocol/oasis-core/go/common/crypto/mrae/api" ) diff --git a/go/common/crypto/signature/signature.go b/go/common/crypto/signature/signature.go index e89bb090b4c..e04dd2835dc 100644 --- a/go/common/crypto/signature/signature.go +++ b/go/common/crypto/signature/signature.go @@ -33,7 +33,7 @@ const ( pubPEMType = "ED25519 PUBLIC KEY" sigPEMType = "ED25519 SIGNATURE" - filePerm = 0600 + filePerm = 0o600 ) var ( diff --git a/go/common/crypto/signature/signers/file/file_signer.go b/go/common/crypto/signature/signers/file/file_signer.go index 306cf50cc0d..b012bdcb263 100644 --- a/go/common/crypto/signature/signers/file/file_signer.go +++ b/go/common/crypto/signature/signers/file/file_signer.go @@ -18,7 +18,7 @@ import ( const ( privateKeyPemType = "ED25519 PRIVATE KEY" - filePerm = 0600 + filePerm = 0o600 // SignerName is the name used to identify the file backed signer. SignerName = "file" diff --git a/go/common/crypto/tls/cert.go b/go/common/crypto/tls/cert.go index 1f657ca4874..66fbdd86024 100644 --- a/go/common/crypto/tls/cert.go +++ b/go/common/crypto/tls/cert.go @@ -142,11 +142,11 @@ func Save(certPath, keyPath string, cert *tls.Certificate) error { return err } - if err = ioutil.WriteFile(keyPath, keyPEM, 0600); err != nil { + if err = ioutil.WriteFile(keyPath, keyPEM, 0o600); err != nil { return fmt.Errorf("tls: failed to write private key: %w", err) } - if err = ioutil.WriteFile(certPath, certPEM, 0644); err != nil { + if err = ioutil.WriteFile(certPath, certPEM, 0o644); err != nil { // nolint: gosec return fmt.Errorf("tls: failed to write certificate: %w", err) } diff --git a/go/common/encoding/bech32/bech32_test.go b/go/common/encoding/bech32/bech32_test.go index 7763fec2151..1cc8fd86a2b 100644 --- a/go/common/encoding/bech32/bech32_test.go +++ b/go/common/encoding/bech32/bech32_test.go @@ -31,16 +31,20 @@ func TestBIP173(t *testing.T) { // HRP character out of range. {"\x801eym55h", false, "decoding bech32 failed: invalid character in string: '\u0080'"}, // Overall max length exceeded. - {"an84characterslonghumanreadablepartthatcontainsthenumber1andtheexcludedcharactersbio1569pvx", + { + "an84characterslonghumanreadablepartthatcontainsthenumber1andtheexcludedcharactersbio1569pvx", false, - "decoding bech32 failed: invalid bech32 string length 91"}, + "decoding bech32 failed: invalid bech32 string length 91", + }, // No separator character. {"pzry9x0s0muk", false, "decoding bech32 failed: invalid index of 1"}, // Empty HRP. {"1pzry9x0s0muk", false, "decoding bech32 failed: invalid index of 1"}, // Invalid data character. - {"x1b4n0q5v", false, - "decoding bech32 failed: failed converting data to bytes: invalid character not part of charset: 98"}, + { + "x1b4n0q5v", false, + "decoding bech32 failed: failed converting data to bytes: invalid character not part of charset: 98", + }, // Too short checksum. {"li1dgmt3", false, "decoding bech32 failed: invalid index of 1"}, // Invalid character in checksum. diff --git a/go/common/entity/entity.go b/go/common/entity/entity.go index dac3ff11550..7e27b305735 100644 --- a/go/common/entity/entity.go +++ b/go/common/entity/entity.go @@ -18,7 +18,7 @@ import ( const ( entityFilename = "entity.json" - fileMode = 0600 + fileMode = 0o600 ) var ( diff --git a/go/common/fuzz/fuzz.go b/go/common/fuzz/fuzz.go index ea9553c6377..5326f7a73aa 100644 --- a/go/common/fuzz/fuzz.go +++ b/go/common/fuzz/fuzz.go @@ -33,11 +33,11 @@ type InterfaceFuzzer struct { methodList []int - typeOverrides map[string]func()interface{} + typeOverrides map[string]func() interface{} } // OverrideType registers a custom callback for creating instances of a given type. -func (i *InterfaceFuzzer) OverrideType(typeName string, factory func()interface{}) { +func (i *InterfaceFuzzer) OverrideType(typeName string, factory func() interface{}) { i.typeOverrides[typeName] = factory } @@ -110,11 +110,11 @@ FilterLoop: func NewInterfaceFuzzer(instance interface{}) *InterfaceFuzzer { val := reflect.ValueOf(instance) ret := &InterfaceFuzzer{ - instance: instance, - typeObject: val.Type(), - valObject: val, - typeOverrides: map[string]func()interface{}{ - "context.Context": func()interface{}{ + instance: instance, + typeObject: val.Type(), + valObject: val, + typeOverrides: map[string]func() interface{}{ + "context.Context": func() interface{} { return context.Background() }, }, diff --git a/go/common/grpc/auth/auth.go b/go/common/grpc/auth/auth.go index 7e62e1291d9..8c8b54397f7 100644 --- a/go/common/grpc/auth/auth.go +++ b/go/common/grpc/auth/auth.go @@ -33,7 +33,6 @@ func UnaryServerInterceptor(authFunc AuthenticationFunction) grpc.UnaryServerInt req interface{}, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (interface{}, error) { - overrideSrv, ok := info.Server.(ServerAuth) if !ok { // Server doesn't implement Authentication. @@ -61,7 +60,6 @@ func StreamServerInterceptor(authFunc AuthenticationFunction) grpc.StreamServerI stream grpc.ServerStream, info *grpc.StreamServerInfo, handler grpc.StreamHandler) error { - overrideSrv, ok := srv.(ServerAuth) if !ok { // Server doesn't implement Authentication. diff --git a/go/common/grpc/auth/auth_test.go b/go/common/grpc/auth/auth_test.go index e9d6625ca63..d96db95b677 100644 --- a/go/common/grpc/auth/auth_test.go +++ b/go/common/grpc/auth/auth_test.go @@ -141,5 +141,4 @@ func testAuth(t *testing.T, testCase *testCase) { } } - } diff --git a/go/common/grpc/errors.go b/go/common/grpc/errors.go index 30470081d09..3fa70f22804 100644 --- a/go/common/grpc/errors.go +++ b/go/common/grpc/errors.go @@ -38,7 +38,7 @@ func errorToGrpc(err error) error { Code: int32(status.Code(err)), Message: err.Error(), Details: []*any.Any{ - &any.Any{ + { // Double serialization seems ugly, but there is no way around // it as the format for errors is predefined. Value: cbor.Marshal(&grpcError{Module: module, Code: code}), diff --git a/go/common/grpc/proxy/proxy.go b/go/common/grpc/proxy/proxy.go index 9db125b28d9..473eba3a6c2 100644 --- a/go/common/grpc/proxy/proxy.go +++ b/go/common/grpc/proxy/proxy.go @@ -99,7 +99,6 @@ func (p *proxy) handler(srv interface{}, stream grpc.ServerStream) error { p.upstreamConn, method, ) - if err != nil { return err } diff --git a/go/common/grpc/testing/ping.go b/go/common/grpc/testing/ping.go index b805f4c2a09..ad7127dfcc4 100644 --- a/go/common/grpc/testing/ping.go +++ b/go/common/grpc/testing/ping.go @@ -111,7 +111,6 @@ func (s *pingServer) WatchPings(ctx context.Context, query *PingQuery) (<-chan * case <-ctx.Done(): return } - } }() typedCh := make(chan *PingResponse) diff --git a/go/common/grpc/wrapper.go b/go/common/grpc/wrapper.go index 8c6a40a425f..69023dd2f03 100644 --- a/go/common/grpc/wrapper.go +++ b/go/common/grpc/wrapper.go @@ -9,11 +9,9 @@ import ( "google.golang.org/grpc" ) -var ( - // ErrServiceClosed is the error returned when the wrapper receives a message for a service whose - // interceptor has been removed. - ErrServiceClosed = errors.New("grpc/wrapper: received message for wrapped service with deregistered wrapper") -) +// ErrServiceClosed is the error returned when the wrapper receives a message for a service whose +// interceptor has been removed. +var ErrServiceClosed = errors.New("grpc/wrapper: received message for wrapped service with deregistered wrapper") type wrappedResponse struct { resp interface{} diff --git a/go/common/identity/identity.go b/go/common/identity/identity.go index 45cfbb78797..23f5698bd43 100644 --- a/go/common/identity/identity.go +++ b/go/common/identity/identity.go @@ -184,7 +184,7 @@ func LoadOrGenerate(dataDir string, signerFactory signature.SignerFactory, persi return doLoadOrGenerate(dataDir, signerFactory, true, persistTLS) } -func doLoadOrGenerate(dataDir string, signerFactory signature.SignerFactory, shouldGenerate bool, persistTLS bool) (*Identity, error) { +func doLoadOrGenerate(dataDir string, signerFactory signature.SignerFactory, shouldGenerate, persistTLS bool) (*Identity, error) { var signers []signature.Signer for _, v := range []struct { role signature.SignerRole diff --git a/go/common/ledger/ledger.go b/go/common/ledger/ledger.go index 788ee392892..12bb800457b 100644 --- a/go/common/ledger/ledger.go +++ b/go/common/ledger/ledger.go @@ -28,12 +28,10 @@ const ( ListingPathIndex uint32 = 0 ) -var ( - // ListingDerivationPath is the path used to list and connect to devices by address. - ListingDerivationPath = []uint32{ - PathPurposeBIP44, ListingPathCoinType, ListingPathAccount, ListingPathChange, ListingPathIndex, - } -) +// ListingDerivationPath is the path used to list and connect to devices by address. +var ListingDerivationPath = []uint32{ + PathPurposeBIP44, ListingPathCoinType, ListingPathAccount, ListingPathChange, ListingPathIndex, +} // Device is a Ledger device. type Device = ledger.LedgerOasis diff --git a/go/common/mkdir.go b/go/common/mkdir.go index ce9a55bfb6b..5903945e8c9 100644 --- a/go/common/mkdir.go +++ b/go/common/mkdir.go @@ -9,7 +9,7 @@ import ( // Mkdir creates a directory iff it does not exist, and otherwise // ensures that the filesystem permissions are sufficiently restrictive. func Mkdir(d string) error { - const permDir = os.FileMode(0700) + const permDir = os.FileMode(0o700) fi, err := os.Lstat(d) if err != nil { diff --git a/go/common/pubsub/pubsub_test.go b/go/common/pubsub/pubsub_test.go index 1840b286ef5..e81145976b1 100644 --- a/go/common/pubsub/pubsub_test.go +++ b/go/common/pubsub/pubsub_test.go @@ -137,7 +137,6 @@ func testSubscribeEx(t *testing.T) { require.NotNil(t, sub.ch, "Subscription, inner channel") require.Equal(t, sub.ch, callbackCh, "Callback channel != Subscription, inner channel") } - } func testNewBrokerEx(t *testing.T) { diff --git a/go/common/sgx/aesm/aesm_proto.pb.go b/go/common/sgx/aesm/aesm_proto.pb.go index abbf2107343..95b747c24ea 100644 --- a/go/common/sgx/aesm/aesm_proto.pb.go +++ b/go/common/sgx/aesm/aesm_proto.pb.go @@ -37,11 +37,12 @@ package aesm import ( + reflect "reflect" + sync "sync" + proto "github.com/golang/protobuf/proto" protoreflect "google.golang.org/protobuf/reflect/protoreflect" protoimpl "google.golang.org/protobuf/runtime/protoimpl" - reflect "reflect" - sync "sync" ) const ( @@ -633,7 +634,7 @@ func (x *Request_ReportAttestationErrorRequest) GetTimeout() uint32 { return 0 } -//private API +// private API type Request_CreateSessionRequest struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache @@ -1385,7 +1386,7 @@ func (x *Response_ReportAttestationErrorResponse) GetPlatformUpdateInfo() []byte return nil } -//private API +// private API type Response_CreateSessionResponse struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache @@ -2237,37 +2238,40 @@ func file_aesm_proto_proto_rawDescGZIP() []byte { return file_aesm_proto_proto_rawDescData } -var file_aesm_proto_proto_msgTypes = make([]protoimpl.MessageInfo, 28) -var file_aesm_proto_proto_goTypes = []interface{}{ - (*Request)(nil), // 0: aesm.Request - (*Response)(nil), // 1: aesm.Response - (*Request_InitQuoteRequest)(nil), // 2: aesm.Request.InitQuoteRequest - (*Request_GetQuoteRequest)(nil), // 3: aesm.Request.GetQuoteRequest - (*Request_GetLaunchTokenRequest)(nil), // 4: aesm.Request.GetLaunchTokenRequest - (*Request_ReportAttestationErrorRequest)(nil), // 5: aesm.Request.ReportAttestationErrorRequest - (*Request_CreateSessionRequest)(nil), // 6: aesm.Request.CreateSessionRequest - (*Request_InvokeServiceRequest)(nil), // 7: aesm.Request.InvokeServiceRequest - (*Request_ExchangeReportRequest)(nil), // 8: aesm.Request.ExchangeReportRequest - (*Request_CloseSessionRequest)(nil), // 9: aesm.Request.CloseSessionRequest - (*Request_GetPsCapRequest)(nil), // 10: aesm.Request.GetPsCapRequest - (*Request_GetWhiteListSizeRequest)(nil), // 11: aesm.Request.GetWhiteListSizeRequest - (*Request_GetWhiteListRequest)(nil), // 12: aesm.Request.GetWhiteListRequest - (*Request_SGXGetExtendedEpidGroupIdRequest)(nil), // 13: aesm.Request.SGXGetExtendedEpidGroupIdRequest - (*Request_SGXSwitchExtendedEpidGroupRequest)(nil), // 14: aesm.Request.SGXSwitchExtendedEpidGroupRequest - (*Response_InitQuoteResponse)(nil), // 15: aesm.Response.InitQuoteResponse - (*Response_GetQuoteResponse)(nil), // 16: aesm.Response.GetQuoteResponse - (*Response_GetLaunchTokenResponse)(nil), // 17: aesm.Response.GetLaunchTokenResponse - (*Response_ReportAttestationErrorResponse)(nil), // 18: aesm.Response.ReportAttestationErrorResponse - (*Response_CreateSessionResponse)(nil), // 19: aesm.Response.CreateSessionResponse - (*Response_InvokeServiceResponse)(nil), // 20: aesm.Response.InvokeServiceResponse - (*Response_ExchangeReportResponse)(nil), // 21: aesm.Response.ExchangeReportResponse - (*Response_CloseSessionResponse)(nil), // 22: aesm.Response.CloseSessionResponse - (*Response_GetPsCapResponse)(nil), // 23: aesm.Response.GetPsCapResponse - (*Response_GetWhiteListSizeResponse)(nil), // 24: aesm.Response.GetWhiteListSizeResponse - (*Response_GetWhiteListResponse)(nil), // 25: aesm.Response.GetWhiteListResponse - (*Response_SGXGetExtendedEpidGroupIdResponse)(nil), // 26: aesm.Response.SGXGetExtendedEpidGroupIdResponse - (*Response_SGXSwitchExtendedEpidGroupResponse)(nil), // 27: aesm.Response.SGXSwitchExtendedEpidGroupResponse -} +var ( + file_aesm_proto_proto_msgTypes = make([]protoimpl.MessageInfo, 28) + file_aesm_proto_proto_goTypes = []interface{}{ + (*Request)(nil), // 0: aesm.Request + (*Response)(nil), // 1: aesm.Response + (*Request_InitQuoteRequest)(nil), // 2: aesm.Request.InitQuoteRequest + (*Request_GetQuoteRequest)(nil), // 3: aesm.Request.GetQuoteRequest + (*Request_GetLaunchTokenRequest)(nil), // 4: aesm.Request.GetLaunchTokenRequest + (*Request_ReportAttestationErrorRequest)(nil), // 5: aesm.Request.ReportAttestationErrorRequest + (*Request_CreateSessionRequest)(nil), // 6: aesm.Request.CreateSessionRequest + (*Request_InvokeServiceRequest)(nil), // 7: aesm.Request.InvokeServiceRequest + (*Request_ExchangeReportRequest)(nil), // 8: aesm.Request.ExchangeReportRequest + (*Request_CloseSessionRequest)(nil), // 9: aesm.Request.CloseSessionRequest + (*Request_GetPsCapRequest)(nil), // 10: aesm.Request.GetPsCapRequest + (*Request_GetWhiteListSizeRequest)(nil), // 11: aesm.Request.GetWhiteListSizeRequest + (*Request_GetWhiteListRequest)(nil), // 12: aesm.Request.GetWhiteListRequest + (*Request_SGXGetExtendedEpidGroupIdRequest)(nil), // 13: aesm.Request.SGXGetExtendedEpidGroupIdRequest + (*Request_SGXSwitchExtendedEpidGroupRequest)(nil), // 14: aesm.Request.SGXSwitchExtendedEpidGroupRequest + (*Response_InitQuoteResponse)(nil), // 15: aesm.Response.InitQuoteResponse + (*Response_GetQuoteResponse)(nil), // 16: aesm.Response.GetQuoteResponse + (*Response_GetLaunchTokenResponse)(nil), // 17: aesm.Response.GetLaunchTokenResponse + (*Response_ReportAttestationErrorResponse)(nil), // 18: aesm.Response.ReportAttestationErrorResponse + (*Response_CreateSessionResponse)(nil), // 19: aesm.Response.CreateSessionResponse + (*Response_InvokeServiceResponse)(nil), // 20: aesm.Response.InvokeServiceResponse + (*Response_ExchangeReportResponse)(nil), // 21: aesm.Response.ExchangeReportResponse + (*Response_CloseSessionResponse)(nil), // 22: aesm.Response.CloseSessionResponse + (*Response_GetPsCapResponse)(nil), // 23: aesm.Response.GetPsCapResponse + (*Response_GetWhiteListSizeResponse)(nil), // 24: aesm.Response.GetWhiteListSizeResponse + (*Response_GetWhiteListResponse)(nil), // 25: aesm.Response.GetWhiteListResponse + (*Response_SGXGetExtendedEpidGroupIdResponse)(nil), // 26: aesm.Response.SGXGetExtendedEpidGroupIdResponse + (*Response_SGXSwitchExtendedEpidGroupResponse)(nil), // 27: aesm.Response.SGXSwitchExtendedEpidGroupResponse + } +) + var file_aesm_proto_proto_depIdxs = []int32{ 2, // 0: aesm.Request.initQuoteReq:type_name -> aesm.Request.InitQuoteRequest 3, // 1: aesm.Request.getQuoteReq:type_name -> aesm.Request.GetQuoteRequest diff --git a/go/common/sgx/ias/quote_test.go b/go/common/sgx/ias/quote_test.go index fc8287f5153..b76e2ab7265 100644 --- a/go/common/sgx/ias/quote_test.go +++ b/go/common/sgx/ias/quote_test.go @@ -1,12 +1,11 @@ package ias import ( + "encoding/hex" "testing" "time" "github.com/stretchr/testify/require" - - "encoding/hex" ) func TestQuote(t *testing.T) { diff --git a/go/common/sgx/sigstruct/sigstruct.go b/go/common/sgx/sigstruct/sigstruct.go index 5188f0a4588..0a33f4eb00c 100644 --- a/go/common/sgx/sigstruct/sigstruct.go +++ b/go/common/sgx/sigstruct/sigstruct.go @@ -124,7 +124,7 @@ func postProcessSignature(raw []byte, modulus *big.Int) (sigBytes, q1Bytes, q2By return } -func deriveQ1Q2(sig *big.Int, modulus *big.Int) (*big.Int, *big.Int) { +func deriveQ1Q2(sig, modulus *big.Int) (*big.Int, *big.Int) { // q1 = floor(Signature^2 / Modulus); // q2 = floor((Signature^3 - q1 * Signature * Modulus) / Modulus); var q1, q2, toSub big.Int diff --git a/go/common/sgx/sigstruct/sigstruct_test.go b/go/common/sgx/sigstruct/sigstruct_test.go index c8b070e5f62..031e6513bfb 100644 --- a/go/common/sgx/sigstruct/sigstruct_test.go +++ b/go/common/sgx/sigstruct/sigstruct_test.go @@ -25,7 +25,7 @@ func TestSigstruct(t *testing.T) { // Generate a SIGSTRUCT. builder := New( - WithBuildDate(time.Date(2016, 01, 9, 0, 0, 0, 0, time.UTC)), + WithBuildDate(time.Date(2016, 1, 9, 0, 0, 0, 0, time.UTC)), WithAttributes(sgx.Attributes{ Flags: 0x04, Xfrm: 0x03, diff --git a/go/common/tracing/tracing.go b/go/common/tracing/tracing.go index 2b896e71279..85718d71292 100644 --- a/go/common/tracing/tracing.go +++ b/go/common/tracing/tracing.go @@ -39,7 +39,7 @@ func SpanContextToBinary(sc opentracing.SpanContext) ([]byte, error) { // SpanContext in binary format. // Returns a new SpanContext instance using the global tracer. func SpanContextFromBinary(scBinary []byte) (opentracing.SpanContext, error) { - var scReader = bytes.NewReader(scBinary) + scReader := bytes.NewReader(scBinary) sc, err := opentracing.GlobalTracer().Extract(opentracing.Binary, scReader) return sc, err diff --git a/go/consensus/tendermint/abci/state/state.go b/go/consensus/tendermint/abci/state/state.go index 575031599a0..103f47bf5a1 100644 --- a/go/consensus/tendermint/abci/state/state.go +++ b/go/consensus/tendermint/abci/state/state.go @@ -11,12 +11,10 @@ import ( "github.com/oasisprotocol/oasis-core/go/storage/mkvs" ) -var ( - // parametersKeyFmt is the key format used for consensus parameters. - // - // Value is CBOR-serialized consensusGenesis.Parameters. - parametersKeyFmt = keyformat.New(0xF1) -) +// parametersKeyFmt is the key format used for consensus parameters. +// +// Value is CBOR-serialized consensusGenesis.Parameters. +var parametersKeyFmt = keyformat.New(0xF1) // ImmutableState is an immutable consensus backend state wrapper. type ImmutableState struct { diff --git a/go/consensus/tendermint/abci/timer.go b/go/consensus/tendermint/abci/timer.go index 67c395fbb43..39144421dcd 100644 --- a/go/consensus/tendermint/abci/timer.go +++ b/go/consensus/tendermint/abci/timer.go @@ -66,7 +66,7 @@ type Timer struct { } // NewTimer creates a new timer. -func NewTimer(ctx *api.Context, app Application, kind uint8, id []byte, data []byte) *Timer { +func NewTimer(ctx *api.Context, app Application, kind uint8, id, data []byte) *Timer { if data == nil { data = []byte{} } else { diff --git a/go/consensus/tendermint/api/state.go b/go/consensus/tendermint/api/state.go index 8156b2ccd2e..6a03a70a2ff 100644 --- a/go/consensus/tendermint/api/state.go +++ b/go/consensus/tendermint/api/state.go @@ -19,10 +19,8 @@ import ( "github.com/oasisprotocol/oasis-core/go/storage/mkvs" ) -var ( - // ErrNoState is the error returned when state is nil. - ErrNoState = errors.New("tendermint: no state available (app not registered?)") -) +// ErrNoState is the error returned when state is nil. +var ErrNoState = errors.New("tendermint: no state available (app not registered?)") // ApplicationState is the overall past, present and future state of all multiplexed applications. type ApplicationState interface { diff --git a/go/consensus/tendermint/apps/beacon/beacon.go b/go/consensus/tendermint/apps/beacon/beacon.go index 59ca9d103a2..58536973d42 100644 --- a/go/consensus/tendermint/apps/beacon/beacon.go +++ b/go/consensus/tendermint/apps/beacon/beacon.go @@ -157,7 +157,7 @@ func New() abci.Application { return &beaconApplication{} } -func GetBeacon(beaconEpoch epochtime.EpochTime, entropyCtx []byte, entropy []byte) []byte { +func GetBeacon(beaconEpoch epochtime.EpochTime, entropyCtx, entropy []byte) []byte { var tmp [8]byte binary.LittleEndian.PutUint64(tmp[:], uint64(beaconEpoch)) diff --git a/go/consensus/tendermint/apps/keymanager/state/state.go b/go/consensus/tendermint/apps/keymanager/state/state.go index 3f982dc3453..4853e1a73b0 100644 --- a/go/consensus/tendermint/apps/keymanager/state/state.go +++ b/go/consensus/tendermint/apps/keymanager/state/state.go @@ -11,12 +11,10 @@ import ( "github.com/oasisprotocol/oasis-core/go/storage/mkvs" ) -var ( - // statusKeyFmt is the key manager status key format. - // - // Value is CBOR-serialized key manager status. - statusKeyFmt = keyformat.New(0x70, keyformat.H(&common.Namespace{})) -) +// statusKeyFmt is the key manager status key format. +// +// Value is CBOR-serialized key manager status. +var statusKeyFmt = keyformat.New(0x70, keyformat.H(&common.Namespace{})) // ImmutableState is the immutable key manager state wrapper. type ImmutableState struct { diff --git a/go/consensus/tendermint/apps/registry/state/state.go b/go/consensus/tendermint/apps/registry/state/state.go index 84576ef726a..fdb268cbca7 100644 --- a/go/consensus/tendermint/apps/registry/state/state.go +++ b/go/consensus/tendermint/apps/registry/state/state.go @@ -552,7 +552,7 @@ func (s *MutableState) RemoveEntity(ctx context.Context, id signature.PublicKey) } // SetNode sets a signed node descriptor for a registered node. -func (s *MutableState) SetNode(ctx context.Context, existingNode *node.Node, node *node.Node, signedNode *node.MultiSignedNode) error { +func (s *MutableState) SetNode(ctx context.Context, existingNode, node *node.Node, signedNode *node.MultiSignedNode) error { rawNodeID, err := node.ID.MarshalBinary() if err != nil { return err diff --git a/go/consensus/tendermint/apps/registry/transactions_test.go b/go/consensus/tendermint/apps/registry/transactions_test.go index 49d847c1f18..7418c91dc9c 100644 --- a/go/consensus/tendermint/apps/registry/transactions_test.go +++ b/go/consensus/tendermint/apps/registry/transactions_test.go @@ -130,7 +130,7 @@ func TestRegisterNode(t *testing.T) { tcd.node.AddRoles(node.RoleComputeWorker) tcd.node.Runtimes = []*node.Runtime{ - &node.Runtime{ID: rt.ID}, + {ID: rt.ID}, } }, nil, @@ -158,7 +158,7 @@ func TestRegisterNode(t *testing.T) { tcd.node.AddRoles(node.RoleComputeWorker) tcd.node.Runtimes = []*node.Runtime{ - &node.Runtime{ID: rt.ID}, + {ID: rt.ID}, } }, nil, @@ -195,7 +195,7 @@ func TestRegisterNode(t *testing.T) { tcd.node.AddRoles(node.RoleComputeWorker) tcd.node.Runtimes = []*node.Runtime{ - &node.Runtime{ID: rt.ID}, + {ID: rt.ID}, } }, nil, @@ -239,8 +239,8 @@ func TestRegisterNode(t *testing.T) { tcd.node.AddRoles(node.RoleComputeWorker) tcd.node.Runtimes = []*node.Runtime{ - &node.Runtime{ID: rt1.ID}, - &node.Runtime{ID: rt2.ID}, + {ID: rt1.ID}, + {ID: rt2.ID}, } }, nil, @@ -279,8 +279,8 @@ func TestRegisterNode(t *testing.T) { tcd.node.AddRoles(node.RoleComputeWorker) tcd.node.Runtimes = []*node.Runtime{ - &node.Runtime{ID: rt1.ID}, - &node.Runtime{ID: rt2.ID}, + {ID: rt1.ID}, + {ID: rt2.ID}, } }, &staking.ConsensusParameters{ diff --git a/go/consensus/tendermint/apps/roothash/transactions.go b/go/consensus/tendermint/apps/roothash/transactions.go index 74817bcd61c..6e45cc7d63a 100644 --- a/go/consensus/tendermint/apps/roothash/transactions.go +++ b/go/consensus/tendermint/apps/roothash/transactions.go @@ -125,7 +125,7 @@ func (app *rootHashApplication) executorCommit( pools := make(map[*commitment.Pool]bool) for _, commit := range cc.Commits { var pool *commitment.Pool - if pool, err = rtState.Round.AddExecutorCommitment(ctx, &commit, sv, nl); err != nil { + if pool, err = rtState.Round.AddExecutorCommitment(ctx, &commit, sv, nl); err != nil { // nolint: gosec ctx.Logger().Error("failed to add compute commitment to round", "err", err, "round", rtState.CurrentBlock.Header.Round, @@ -192,7 +192,7 @@ func (app *rootHashApplication) mergeCommit( // Add commitments. for _, commit := range mc.Commits { - if err = rtState.Round.AddMergeCommitment(ctx, &commit, sv, nl); err != nil { + if err = rtState.Round.AddMergeCommitment(ctx, &commit, sv, nl); err != nil { // nolint: gosec ctx.Logger().Error("failed to add merge commitment to round", "err", err, "round", rtState.CurrentBlock.Header.Round, diff --git a/go/consensus/tendermint/apps/scheduler/scheduler.go b/go/consensus/tendermint/apps/scheduler/scheduler.go index c05d81683ec..b31b8d9f153 100644 --- a/go/consensus/tendermint/apps/scheduler/scheduler.go +++ b/go/consensus/tendermint/apps/scheduler/scheduler.go @@ -213,7 +213,7 @@ func (app *schedulerApplication) ForeignExecuteTx(ctx *api.Context, other abci.A return nil } -func diffValidators(logger *logging.Logger, current map[signature.PublicKey]int64, pending map[signature.PublicKey]int64) []types.ValidatorUpdate { +func diffValidators(logger *logging.Logger, current, pending map[signature.PublicKey]int64) []types.ValidatorUpdate { var updates []types.ValidatorUpdate for v := range current { if _, ok := pending[v]; !ok { diff --git a/go/consensus/tendermint/apps/scheduler/scheduler_test.go b/go/consensus/tendermint/apps/scheduler/scheduler_test.go index 0ee480a15c9..4a3de29b9bb 100644 --- a/go/consensus/tendermint/apps/scheduler/scheduler_test.go +++ b/go/consensus/tendermint/apps/scheduler/scheduler_test.go @@ -14,10 +14,10 @@ import ( func TestDiffValidators(t *testing.T) { logger := logging.GetLogger("TestDiffValidators") powerOne := map[signature.PublicKey]int64{ - signature.PublicKey{}: 1, + {}: 1, } powerTwo := map[signature.PublicKey]int64{ - signature.PublicKey{}: 2, + {}: 2, } for _, tt := range []struct { msg string diff --git a/go/consensus/tendermint/apps/staking/api.go b/go/consensus/tendermint/apps/staking/api.go index 36507c43d1b..72b91efc438 100644 --- a/go/consensus/tendermint/apps/staking/api.go +++ b/go/consensus/tendermint/apps/staking/api.go @@ -14,7 +14,7 @@ var ( // AppName is the ABCI application name. AppName = stakingState.AppName - //EventType is the ABCI event type for staking events. + // EventType is the ABCI event type for staking events. EventType = api.EventTypeForApp(AppName) // QueryApp is a query for filtering events processed by the diff --git a/go/consensus/tendermint/apps/staking/slashing_test.go b/go/consensus/tendermint/apps/staking/slashing_test.go index 6cec7d9c33e..b9b488cefca 100644 --- a/go/consensus/tendermint/apps/staking/slashing_test.go +++ b/go/consensus/tendermint/apps/staking/slashing_test.go @@ -79,7 +79,7 @@ func TestOnEvidenceDoubleSign(t *testing.T) { _ = slashAmount.FromUint64(100) err = stakeState.SetConsensusParameters(ctx, &staking.ConsensusParameters{ Slashing: map[staking.SlashReason]staking.Slash{ - staking.SlashDoubleSigning: staking.Slash{ + staking.SlashDoubleSigning: { Amount: slashAmount, FreezeInterval: registry.FreezeForever, }, diff --git a/go/consensus/tendermint/apps/staking/state/state.go b/go/consensus/tendermint/apps/staking/state/state.go index 85c80882dd7..abe7f7599d1 100644 --- a/go/consensus/tendermint/apps/staking/state/state.go +++ b/go/consensus/tendermint/apps/staking/state/state.go @@ -757,9 +757,9 @@ func (s *MutableState) AddRewards( return err } var activeStep *staking.RewardStep - for _, step := range steps { + for i, step := range steps { if time < step.Until { - activeStep = &step + activeStep = &steps[i] break } } @@ -873,9 +873,9 @@ func (s *MutableState) AddRewardSingleAttenuated( return fmt.Errorf("failed to query reward schedule: %w", err) } var activeStep *staking.RewardStep - for _, step := range steps { + for i, step := range steps { if time < step.Until { - activeStep = &step + activeStep = &steps[i] break } } diff --git a/go/consensus/tendermint/apps/staking/transactions_test.go b/go/consensus/tendermint/apps/staking/transactions_test.go index bde7b9fbf3f..f5a5c5285f5 100644 --- a/go/consensus/tendermint/apps/staking/transactions_test.go +++ b/go/consensus/tendermint/apps/staking/transactions_test.go @@ -39,7 +39,7 @@ func TestIsTransferPermitted(t *testing.T) { &staking.ConsensusParameters{ DisableTransfers: true, UndisableTransfersFrom: map[staking.Address]bool{ - staking.Address{1}: true, + {1}: true, }, }, staking.Address{}, @@ -50,7 +50,7 @@ func TestIsTransferPermitted(t *testing.T) { &staking.ConsensusParameters{ DisableTransfers: true, UndisableTransfersFrom: map[staking.Address]bool{ - staking.Address{}: true, + {}: true, }, }, staking.Address{}, diff --git a/go/consensus/tendermint/crypto/priv_val.go b/go/consensus/tendermint/crypto/priv_val.go index 9769eae9320..e1fb166d0d9 100644 --- a/go/consensus/tendermint/crypto/priv_val.go +++ b/go/consensus/tendermint/crypto/priv_val.go @@ -337,7 +337,7 @@ func (pv *privVal) save() error { if err != nil { return err } - if err = tempfile.WriteFileAtomic(pv.filePath, b, 0600); err != nil { + if err = tempfile.WriteFileAtomic(pv.filePath, b, 0o600); err != nil { return fmt.Errorf("tendermint/crypto: failed to save private validator file: %w", err) } diff --git a/go/consensus/tendermint/fuzz/fuzz.go b/go/consensus/tendermint/fuzz/fuzz.go index 26c9e09fae3..bfcbc41dcae 100644 --- a/go/consensus/tendermint/fuzz/fuzz.go +++ b/go/consensus/tendermint/fuzz/fuzz.go @@ -13,7 +13,7 @@ import ( "github.com/oasisprotocol/oasis-core/go/common/fuzz" "github.com/oasisprotocol/oasis-core/go/consensus/api/transaction" "github.com/oasisprotocol/oasis-core/go/consensus/tendermint/abci" - "github.com/oasisprotocol/oasis-core/go/consensus/tendermint/apps/epochtime_mock" + epochtimemock "github.com/oasisprotocol/oasis-core/go/consensus/tendermint/apps/epochtime_mock" registryApp "github.com/oasisprotocol/oasis-core/go/consensus/tendermint/apps/registry" stakingApp "github.com/oasisprotocol/oasis-core/go/consensus/tendermint/apps/staking" "github.com/oasisprotocol/oasis-core/go/upgrade" @@ -75,7 +75,7 @@ func Fuzz(data []byte) int { tx := &transaction.Transaction{ Method: methodName, - Body: cbor.Marshal(blob), + Body: cbor.Marshal(blob), } signedTx, err := transaction.Sign(txSigner, tx) @@ -87,7 +87,7 @@ func Fuzz(data []byte) int { // Check the transaction. checkReq := types.RequestCheckTx{ - Tx: txBlob, + Tx: txBlob, Type: types.CheckTxType_New, } muxer.CheckTx(checkReq) diff --git a/go/consensus/tendermint/pubsub.go b/go/consensus/tendermint/pubsub.go index 77c0ba2bfa5..6a8e0fe9767 100644 --- a/go/consensus/tendermint/pubsub.go +++ b/go/consensus/tendermint/pubsub.go @@ -7,9 +7,7 @@ import ( tmtypes "github.com/tendermint/tendermint/types" ) -var ( - _ tmtypes.Subscription = (*tendermintPubsubBuffer)(nil) -) +var _ tmtypes.Subscription = (*tendermintPubsubBuffer)(nil) // tendermintPubsubBuffer is a wrapper around tendermint subscriptions. // Because unbuffered subscriptions are dangerous and can lead to deadlocks diff --git a/go/consensus/tendermint/staking/staking.go b/go/consensus/tendermint/staking/staking.go index 32d9242aa80..d922e075de4 100644 --- a/go/consensus/tendermint/staking/staking.go +++ b/go/consensus/tendermint/staking/staking.go @@ -210,6 +210,7 @@ func (tb *tendermintBackend) ConsensusParameters(ctx context.Context, height int return q.ConsensusParameters(ctx) } + func (tb *tendermintBackend) Cleanup() { <-tb.closedCh } diff --git a/go/consensus/tendermint/tendermint.go b/go/consensus/tendermint/tendermint.go index c38e360ecc3..a221c9f67f5 100644 --- a/go/consensus/tendermint/tendermint.go +++ b/go/consensus/tendermint/tendermint.go @@ -53,7 +53,7 @@ import ( "github.com/oasisprotocol/oasis-core/go/consensus/tendermint/crypto" "github.com/oasisprotocol/oasis-core/go/consensus/tendermint/db" "github.com/oasisprotocol/oasis-core/go/consensus/tendermint/epochtime" - "github.com/oasisprotocol/oasis-core/go/consensus/tendermint/epochtime_mock" + epochtimemock "github.com/oasisprotocol/oasis-core/go/consensus/tendermint/epochtime_mock" tmkeymanager "github.com/oasisprotocol/oasis-core/go/consensus/tendermint/keymanager" tmregistry "github.com/oasisprotocol/oasis-core/go/consensus/tendermint/registry" tmroothash "github.com/oasisprotocol/oasis-core/go/consensus/tendermint/roothash" diff --git a/go/consensus/tendermint/tests/evidence.go b/go/consensus/tendermint/tests/evidence.go index cb0004f4e40..0ccdc299edf 100644 --- a/go/consensus/tendermint/tests/evidence.go +++ b/go/consensus/tendermint/tests/evidence.go @@ -28,12 +28,12 @@ func MakeDoubleSignEvidence(t *testing.T, ident *identity.Identity) consensus.Ev // Create two private validators that share the same key as otherwise // double signing will fail. pv1Path := filepath.Join(tmpDir, "pv1") - err = os.Mkdir(pv1Path, 0700) + err = os.Mkdir(pv1Path, 0o700) require.NoError(err, "Mkdir") pv1, err := tmcrypto.LoadOrGeneratePrivVal(pv1Path, ident.ConsensusSigner) require.NoError(err, "LoadOrGeneratePrivVal") pv2Path := filepath.Join(tmpDir, "pv2") - err = os.Mkdir(pv2Path, 0700) + err = os.Mkdir(pv2Path, 0o700) require.NoError(err, "Mkdir") pv2, err := tmcrypto.LoadOrGeneratePrivVal(pv2Path, ident.ConsensusSigner) require.NoError(err, "LoadOrGeneratePrivVal") diff --git a/go/consensus/tests/tester.go b/go/consensus/tests/tester.go index 8a80679e59e..00560d332b9 100644 --- a/go/consensus/tests/tester.go +++ b/go/consensus/tests/tester.go @@ -12,7 +12,7 @@ import ( memorySigner "github.com/oasisprotocol/oasis-core/go/common/crypto/signature/signers/memory" consensus "github.com/oasisprotocol/oasis-core/go/consensus/api" "github.com/oasisprotocol/oasis-core/go/consensus/api/transaction" - "github.com/oasisprotocol/oasis-core/go/consensus/tendermint/apps/epochtime_mock" + epochtimemock "github.com/oasisprotocol/oasis-core/go/consensus/tendermint/apps/epochtime_mock" staking "github.com/oasisprotocol/oasis-core/go/staking/api" "github.com/oasisprotocol/oasis-core/go/storage/mkvs" ) diff --git a/go/control/debug.go b/go/control/debug.go index 9ca557e0af8..c3e5f0db367 100644 --- a/go/control/debug.go +++ b/go/control/debug.go @@ -2,6 +2,7 @@ package control import ( "context" + consensus "github.com/oasisprotocol/oasis-core/go/consensus/api" "github.com/oasisprotocol/oasis-core/go/control/api" diff --git a/go/extra/stats/cmd/stats.go b/go/extra/stats/cmd/stats.go index 0cc884cc019..86495dd73a3 100644 --- a/go/extra/stats/cmd/stats.go +++ b/go/extra/stats/cmd/stats.go @@ -246,7 +246,7 @@ func getTmBlockMetaOrExit(ctx context.Context, consensus consensusAPI.ClientBack } // getStats queries node for entity stats between 'start' and 'end' block heights. -func getStats(ctx context.Context, consensus consensusAPI.ClientBackend, registry registryAPI.Backend, start int64, end int64) *stats { +func getStats(ctx context.Context, consensus consensusAPI.ClientBackend, registry registryAPI.Backend, start, end int64) *stats { // Init stats. stats := newStats() diff --git a/go/genesis/api/api.go b/go/genesis/api/api.go index 9ef6b4cfb06..55255eaf84d 100644 --- a/go/genesis/api/api.go +++ b/go/genesis/api/api.go @@ -19,7 +19,7 @@ import ( staking "github.com/oasisprotocol/oasis-core/go/staking/api" ) -const filePerm = 0600 +const filePerm = 0o600 // Document is a genesis document. type Document struct { diff --git a/go/genesis/genesis_test.go b/go/genesis/genesis_test.go index fd3925daf19..d89777d8c58 100644 --- a/go/genesis/genesis_test.go +++ b/go/genesis/genesis_test.go @@ -341,7 +341,7 @@ func TestGenesisSanityCheck(t *testing.T) { d.RootHash.RuntimeStates[validNS] = ®istry.RuntimeGenesis{ StateRoot: nonEmptyHash, // List with one empty (invalid) storage receipt. - StorageReceipts: []signature.Signature{signature.Signature{}}, + StorageReceipts: []signature.Signature{{}}, } require.Error(rtsSanityCheck(d.RootHash, false), "empty StorageReceipt for StateRoot should be rejected") require.NoError(rtsSanityCheck(d.RootHash, true), "empty StorageReceipt for StateRoot should be ignored, if isGenesis=true") @@ -560,7 +560,7 @@ func TestGenesisSanityCheck(t *testing.T) { tn = *testNode tn.Roles = node.RoleKeyManager tn.Runtimes = []*node.Runtime{ - &node.Runtime{ + { ID: testKMRuntime.ID, }, } @@ -574,7 +574,7 @@ func TestGenesisSanityCheck(t *testing.T) { tn = *testNode tn.Roles = node.RoleKeyManager tn.Runtimes = []*node.Runtime{ - &node.Runtime{ + { ID: testRuntime.ID, }, } @@ -588,7 +588,7 @@ func TestGenesisSanityCheck(t *testing.T) { tn = *testNode tn.Roles = node.RoleKeyManager tn.Runtimes = []*node.Runtime{ - &node.Runtime{ + { ID: testRuntime.ID, }, } @@ -602,7 +602,7 @@ func TestGenesisSanityCheck(t *testing.T) { tn = *testNode tn.Roles = node.RoleComputeWorker tn.Runtimes = []*node.Runtime{ - &node.Runtime{ + { ID: testKMRuntime.ID, }, } @@ -616,7 +616,7 @@ func TestGenesisSanityCheck(t *testing.T) { tn = *testNode tn.Roles = node.RoleComputeWorker tn.Runtimes = []*node.Runtime{ - &node.Runtime{ + { ID: testRuntime.ID, }, } @@ -630,7 +630,7 @@ func TestGenesisSanityCheck(t *testing.T) { tn = *testNode tn.Roles = node.RoleStorageWorker tn.Runtimes = []*node.Runtime{ - &node.Runtime{ + { ID: testRuntime.ID, }, } @@ -677,8 +677,8 @@ func TestGenesisSanityCheck(t *testing.T) { d = *testDoc d.Staking.Delegations = map[staking.Address]map[staking.Address]*staking.Delegation{ - stakingTests.DebugStateSrcAddress: map[staking.Address]*staking.Delegation{ - stakingTests.DebugStateDestAddress: &staking.Delegation{ + stakingTests.DebugStateSrcAddress: { + stakingTests.DebugStateDestAddress: { Shares: stakingTests.QtyFromInt(1), }, }, @@ -687,9 +687,9 @@ func TestGenesisSanityCheck(t *testing.T) { d = *testDoc d.Staking.DebondingDelegations = map[staking.Address]map[staking.Address][]*staking.DebondingDelegation{ - stakingTests.DebugStateSrcAddress: map[staking.Address][]*staking.DebondingDelegation{ - stakingTests.DebugStateDestAddress: []*staking.DebondingDelegation{ - &staking.DebondingDelegation{ + stakingTests.DebugStateSrcAddress: { + stakingTests.DebugStateDestAddress: { + { Shares: stakingTests.QtyFromInt(1), DebondEndTime: 10, }, diff --git a/go/ias/http/http.go b/go/ias/http/http.go index d2fbcce5bcc..7dfd0bc726a 100644 --- a/go/ias/http/http.go +++ b/go/ias/http/http.go @@ -51,7 +51,7 @@ type httpEndpoint struct { spidInfo api.SPIDInfo } -func (e *httpEndpoint) doIASRequest(ctx context.Context, method string, uPath string, bodyType string, body io.Reader) (*http.Response, error) { +func (e *httpEndpoint) doIASRequest(ctx context.Context, method, uPath, bodyType string, body io.Reader) (*http.Response, error) { u := *e.baseURL u.Path = path.Join(u.Path, uPath) diff --git a/go/oasis-net-runner/cmd/root.go b/go/oasis-net-runner/cmd/root.go index 3676d63be56..905befce330 100644 --- a/go/oasis-net-runner/cmd/root.go +++ b/go/oasis-net-runner/cmd/root.go @@ -88,7 +88,7 @@ func initRootEnv(cmd *cobra.Command) (*env.Env, error) { // Initialize logging. logFile := filepath.Join(env.Dir(), "net-runner.log") - w, err := os.OpenFile(logFile, os.O_CREATE|os.O_APPEND|os.O_WRONLY, 0600) + w, err := os.OpenFile(logFile, os.O_CREATE|os.O_APPEND|os.O_WRONLY, 0o600) if err != nil { return nil, fmt.Errorf("root: failed to open log file: %w", err) } diff --git a/go/oasis-net-runner/fixtures/default.go b/go/oasis-net-runner/fixtures/default.go index 0a5585c1430..79750a8ec1f 100644 --- a/go/oasis-net-runner/fixtures/default.go +++ b/go/oasis-net-runner/fixtures/default.go @@ -57,12 +57,12 @@ func newDefaultFixture() (*oasis.NetworkFixture, error) { }, }, Entities: []oasis.EntityCfg{ - oasis.EntityCfg{IsDebugTestEntity: true}, - oasis.EntityCfg{}, + {IsDebugTestEntity: true}, + {}, }, Runtimes: []oasis.RuntimeFixture{ // Key manager runtime. - oasis.RuntimeFixture{ + { ID: keymanagerID, Kind: registry.KindKeyManager, Entity: 0, @@ -73,7 +73,7 @@ func newDefaultFixture() (*oasis.NetworkFixture, error) { }, }, // Compute runtime. - oasis.RuntimeFixture{ + { ID: runtimeID, Kind: registry.KindCompute, Entity: 0, @@ -112,24 +112,24 @@ func newDefaultFixture() (*oasis.NetworkFixture, error) { }, }, Validators: []oasis.ValidatorFixture{ - oasis.ValidatorFixture{Entity: 1}, + {Entity: 1}, }, KeymanagerPolicies: []oasis.KeymanagerPolicyFixture{ - oasis.KeymanagerPolicyFixture{Runtime: 0, Serial: 1}, + {Runtime: 0, Serial: 1}, }, Keymanagers: []oasis.KeymanagerFixture{ - oasis.KeymanagerFixture{Runtime: 0, Entity: 1}, + {Runtime: 0, Entity: 1}, }, StorageWorkers: []oasis.StorageWorkerFixture{ - oasis.StorageWorkerFixture{Backend: "badger", Entity: 1}, + {Backend: "badger", Entity: 1}, }, ComputeWorkers: []oasis.ComputeWorkerFixture{ - oasis.ComputeWorkerFixture{Entity: 1}, - oasis.ComputeWorkerFixture{Entity: 1}, - oasis.ComputeWorkerFixture{Entity: 1}, + {Entity: 1}, + {Entity: 1}, + {Entity: 1}, }, Clients: []oasis.ClientFixture{ - oasis.ClientFixture{}, + {}, }, }, nil } diff --git a/go/oasis-node/cmd/common/common.go b/go/oasis-node/cmd/common/common.go index 3280dc7be5a..dea559545b0 100644 --- a/go/oasis-node/cmd/common/common.go +++ b/go/oasis-node/cmd/common/common.go @@ -248,7 +248,7 @@ func GetInputReader(cmd *cobra.Command, cfg string) (io.ReadCloser, bool, error) } // LoadEntity loads the entity and it's signer. -func LoadEntity(signerBackend string, entityDir string) (*entity.Entity, signature.Signer, error) { +func LoadEntity(signerBackend, entityDir string) (*entity.Entity, signature.Signer, error) { if flags.DebugTestEntity() { return entity.TestEntity() } @@ -263,7 +263,7 @@ func LoadEntity(signerBackend string, entityDir string) (*entity.Entity, signatu // ExportEntity creates an empty entity from the public key of the signer // generated with the specified backend, and writes it to a file in entityDir. -func ExportEntity(signerBackend string, entityDir string) error { +func ExportEntity(signerBackend, entityDir string) error { factory, err := cmdSigner.NewFactory(signerBackend, entityDir, signature.SignerEntity) if err != nil { return err diff --git a/go/oasis-node/cmd/common/consensus/consensus.go b/go/oasis-node/cmd/common/consensus/consensus.go index 336b7235743..7ba276df329 100644 --- a/go/oasis-node/cmd/common/consensus/consensus.go +++ b/go/oasis-node/cmd/common/consensus/consensus.go @@ -92,7 +92,7 @@ func GetTxNonceAndFee() (uint64, *transaction.Fee) { func SignAndSaveTx(tx *transaction.Transaction) { if viper.GetBool(CfgTxUnsigned) { rawUnsignedTx := cbor.Marshal(tx) - if err := ioutil.WriteFile(viper.GetString(CfgTxFile), rawUnsignedTx, 0600); err != nil { + if err := ioutil.WriteFile(viper.GetString(CfgTxFile), rawUnsignedTx, 0o600); err != nil { logger.Error("failed to save unsigned transaction", "err", err, ) @@ -132,7 +132,7 @@ func SignAndSaveTx(tx *transaction.Transaction) { ) os.Exit(1) } - if err = ioutil.WriteFile(viper.GetString(CfgTxFile), rawTx, 0600); err != nil { + if err = ioutil.WriteFile(viper.GetString(CfgTxFile), rawTx, 0o600); err != nil { logger.Error("failed to save transaction", "err", err, ) diff --git a/go/oasis-node/cmd/common/logging.go b/go/oasis-node/cmd/common/logging.go index 471f0025519..39e29d4c8ac 100644 --- a/go/oasis-node/cmd/common/logging.go +++ b/go/oasis-node/cmd/common/logging.go @@ -25,7 +25,7 @@ func initLogging() error { logFile := viper.GetString(cfgLogFile) var logLevel logging.Level - var moduleLevels = map[string]logging.Level{} + moduleLevels := map[string]logging.Level{} if err := logLevel.Set(viper.GetString(cfgLogLevel)); err != nil { if errDefault := logLevel.Set(viper.GetString(cfgLogLevel + ".default")); errDefault != nil { return errDefault @@ -54,7 +54,7 @@ func initLogging() error { logFile = normalizePath(logFile) var err error - if w, err = os.OpenFile(logFile, os.O_CREATE|os.O_APPEND|os.O_WRONLY, 0600); err != nil { + if w, err = os.OpenFile(logFile, os.O_CREATE|os.O_APPEND|os.O_WRONLY, 0o600); err != nil { return err } } diff --git a/go/oasis-node/cmd/common/signer/signer.go b/go/oasis-node/cmd/common/signer/signer.go index 8d437c1da0b..5b4d1d2ccba 100644 --- a/go/oasis-node/cmd/common/signer/signer.go +++ b/go/oasis-node/cmd/common/signer/signer.go @@ -81,7 +81,7 @@ func LedgerIndex() uint32 { } // NewFactory returns the appropriate SignerFactory based on flags. -func NewFactory(signerBackend string, signerDir string, roles ...signature.SignerRole) (signature.SignerFactory, error) { +func NewFactory(signerBackend, signerDir string, roles ...signature.SignerRole) (signature.SignerFactory, error) { signerBackend = strings.ToLower(signerBackend) if signerBackend != compositeSigner.SignerName { return doNewFactory(signerBackend, signerDir, roles...) @@ -93,7 +93,7 @@ func NewFactory(signerBackend string, signerDir string, roles ...signature.Signe return doNewComposite(signerDir, roles...) } -func doNewFactory(signerBackend string, signerDir string, roles ...signature.SignerRole) (signature.SignerFactory, error) { +func doNewFactory(signerBackend, signerDir string, roles ...signature.SignerRole) (signature.SignerFactory, error) { switch signerBackend { case fileSigner.SignerName: return fileSigner.NewFactory(signerDir, roles...) diff --git a/go/oasis-node/cmd/debug/byzantine/byzantine.go b/go/oasis-node/cmd/debug/byzantine/byzantine.go index 77f4999c149..c2ded51ea9c 100644 --- a/go/oasis-node/cmd/debug/byzantine/byzantine.go +++ b/go/oasis-node/cmd/debug/byzantine/byzantine.go @@ -629,7 +629,7 @@ func doMergeWrong(cmd *cobra.Command, args []string) { var emptyRoot hash.Hash emptyRoot.Empty() mbc.commitments = []*commitment.OpenExecutorCommitment{ - &commitment.OpenExecutorCommitment{ + { Body: &commitment.ComputeBody{ Header: commitment.ComputeResultsHeader{ IORoot: emptyRoot, diff --git a/go/oasis-node/cmd/debug/byzantine/executor.go b/go/oasis-node/cmd/debug/byzantine/executor.go index af486ca8b76..ee90a1bd84b 100644 --- a/go/oasis-node/cmd/debug/byzantine/executor.go +++ b/go/oasis-node/cmd/debug/byzantine/executor.go @@ -137,13 +137,13 @@ func (cbc *computeBatchContext) commitTrees(ctx context.Context) error { func (cbc *computeBatchContext) uploadBatch(ctx context.Context, hnss []*honestNodeStorage) error { var err error cbc.storageReceipts, err = storageBroadcastApplyBatch(ctx, hnss, cbc.bd.Header.Namespace, cbc.bd.Header.Round+1, []storage.ApplyOp{ - storage.ApplyOp{ + { SrcRound: cbc.bd.Header.Round + 1, SrcRoot: cbc.bd.IORoot, DstRoot: cbc.newIORoot, WriteLog: cbc.ioWriteLog, }, - storage.ApplyOp{ + { SrcRound: cbc.bd.Header.Round, SrcRoot: cbc.bd.Header.StateRoot, DstRoot: cbc.newStateRoot, diff --git a/go/oasis-node/cmd/debug/byzantine/merge.go b/go/oasis-node/cmd/debug/byzantine/merge.go index 11ce15bb954..a494ddce797 100644 --- a/go/oasis-node/cmd/debug/byzantine/merge.go +++ b/go/oasis-node/cmd/debug/byzantine/merge.go @@ -91,11 +91,11 @@ func (mbc *mergeBatchContext) process(ctx context.Context, hnss []*honestNodeSto var err error mbc.storageReceipts, err = storageBroadcastMergeBatch(ctx, hnss, mbc.currentBlock.Header.Namespace, mbc.currentBlock.Header.Round, []storage.MergeOp{ - storage.MergeOp{ + { Base: emptyRoot, Others: ioRoots, }, - storage.MergeOp{ + { Base: mbc.currentBlock.Header.StateRoot, Others: stateRoots, }, diff --git a/go/oasis-node/cmd/debug/byzantine/registry.go b/go/oasis-node/cmd/debug/byzantine/registry.go index 4fef8f39cca..1bde8fa876e 100644 --- a/go/oasis-node/cmd/debug/byzantine/registry.go +++ b/go/oasis-node/cmd/debug/byzantine/registry.go @@ -15,7 +15,7 @@ import ( "github.com/oasisprotocol/oasis-core/go/worker/registration" ) -func registryRegisterNode(svc service.TendermintService, id *identity.Identity, dataDir string, addresses []node.Address, p2pAddresses []node.Address, runtimeID common.Namespace, capabilities *node.Capabilities, roles node.RolesMask) error { +func registryRegisterNode(svc service.TendermintService, id *identity.Identity, dataDir string, addresses, p2pAddresses []node.Address, runtimeID common.Namespace, capabilities *node.Capabilities, roles node.RolesMask) error { entityID, registrationSigner, err := registration.GetRegistrationSigner(logging.GetLogger("cmd/byzantine/registration"), dataDir, id) if err != nil { return fmt.Errorf("registration GetRegistrationSigner: %w", err) @@ -27,7 +27,7 @@ func registryRegisterNode(svc service.TendermintService, id *identity.Identity, var runtimes []*node.Runtime if roles®istry.RuntimesRequiredRoles != 0 { runtimes = []*node.Runtime{ - &node.Runtime{ + { ID: runtimeID, }, } diff --git a/go/oasis-node/cmd/debug/byzantine/steps.go b/go/oasis-node/cmd/debug/byzantine/steps.go index ebb9c25bfc8..4e550af1e43 100644 --- a/go/oasis-node/cmd/debug/byzantine/steps.go +++ b/go/oasis-node/cmd/debug/byzantine/steps.go @@ -27,7 +27,7 @@ const ( var ( defaultRuntimeID common.Namespace fakeAddresses = []node.Address{ - node.Address{ + { TCPAddr: net.TCPAddr{ IP: net.IPv4(127, 0, 0, 1), Port: 11004, diff --git a/go/oasis-node/cmd/debug/consim/xfer_workload.go b/go/oasis-node/cmd/debug/consim/xfer_workload.go index 97cdf0dfcec..d0dbccfdede 100644 --- a/go/oasis-node/cmd/debug/consim/xfer_workload.go +++ b/go/oasis-node/cmd/debug/consim/xfer_workload.go @@ -149,7 +149,7 @@ func (w *xferWorkload) worker(cancelCh <-chan struct{}, errCh chan<- error) { errCh <- err return } - w.ch <- []BlockTx{BlockTx{Tx: tx}} + w.ch <- []BlockTx{{Tx: tx}} } numAccounts, numIterations := len(w.accounts), viper.GetInt(cfgXferIterations) diff --git a/go/oasis-node/cmd/debug/dumpdb/dumpdb.go b/go/oasis-node/cmd/debug/dumpdb/dumpdb.go index d660197a907..28c6b805b5b 100644 --- a/go/oasis-node/cmd/debug/dumpdb/dumpdb.go +++ b/go/oasis-node/cmd/debug/dumpdb/dumpdb.go @@ -3,6 +3,7 @@ package dumpdb import ( "context" + "encoding/json" "fmt" "os" "path/filepath" @@ -37,8 +38,6 @@ import ( staking "github.com/oasisprotocol/oasis-core/go/staking/api" storage "github.com/oasisprotocol/oasis-core/go/storage/api" storageDB "github.com/oasisprotocol/oasis-core/go/storage/database" - - "encoding/json" ) const ( diff --git a/go/oasis-node/cmd/debug/storage/storage.go b/go/oasis-node/cmd/debug/storage/storage.go index 14708d5276d..53eb2bee6c3 100644 --- a/go/oasis-node/cmd/debug/storage/storage.go +++ b/go/oasis-node/cmd/debug/storage/storage.go @@ -83,7 +83,7 @@ func ValidateRuntimeIDStr(idStr string) error { return ns.UnmarshalHex(idStr) } -func checkDiff(ctx context.Context, storageClient storageAPI.Backend, root string, oldRoot node.Root, newRoot node.Root) { +func checkDiff(ctx context.Context, storageClient storageAPI.Backend, root string, oldRoot, newRoot node.Root) { it, err := storageClient.GetDiff(ctx, &storageAPI.GetDiffRequest{StartRoot: oldRoot, EndRoot: newRoot}) if err != nil { logger.Error("error getting write log from the syncing node", diff --git a/go/oasis-node/cmd/debug/txsource/workload/commission.go b/go/oasis-node/cmd/debug/txsource/workload/commission.go index bcc1b410edf..66f55bf64a1 100644 --- a/go/oasis-node/cmd/debug/txsource/workload/commission.go +++ b/go/oasis-node/cmd/debug/txsource/workload/commission.go @@ -56,7 +56,7 @@ func currentBound(cs *staking.CommissionSchedule, now epochtime.EpochTime) *stak // rules between start and end epoch. The function panics in case a rate step // cannot satisfy all bound rules so the caller should make sure that bounds // are not exclusive. -func genValidRateStep(rng *rand.Rand, logger *logging.Logger, schedule staking.CommissionSchedule, startEpoch epochtime.EpochTime, endEpoch epochtime.EpochTime) staking.CommissionRateStep { +func genValidRateStep(rng *rand.Rand, logger *logging.Logger, schedule staking.CommissionSchedule, startEpoch, endEpoch epochtime.EpochTime) staking.CommissionRateStep { startBound := currentBound(&schedule, startEpoch) minBound := startBound.RateMin.ToBigInt().Int64() maxBound := startBound.RateMax.ToBigInt().Int64() diff --git a/go/oasis-node/cmd/debug/txsource/workload/parallel.go b/go/oasis-node/cmd/debug/txsource/workload/parallel.go index 337daf1ffc5..5464d6777ad 100644 --- a/go/oasis-node/cmd/debug/txsource/workload/parallel.go +++ b/go/oasis-node/cmd/debug/txsource/workload/parallel.go @@ -122,7 +122,6 @@ func (parallel) Run( errCh <- fmt.Errorf("cnsc.SubmitTx: %w", err) return } - }(accounts[c], nonce) } diff --git a/go/oasis-node/cmd/debug/txsource/workload/queries.go b/go/oasis-node/cmd/debug/txsource/workload/queries.go index 480194bae13..958239b9c41 100644 --- a/go/oasis-node/cmd/debug/txsource/workload/queries.go +++ b/go/oasis-node/cmd/debug/txsource/workload/queries.go @@ -378,7 +378,8 @@ func (q *queries) doRegistryQueries(ctx context.Context, rng *rand.Rand, height node, err = q.registry.GetNodeByConsensusAddress( ctx, ®istry.ConsensusAddressQuery{ - Address: []byte(tmcrypto.PublicKeyToTendermint(&nod.Consensus.ID).Address()), Height: height}, + Address: []byte(tmcrypto.PublicKeyToTendermint(&nod.Consensus.ID).Address()), Height: height, + }, ) if err != nil { return fmt.Errorf("GetNodeByConsensusAddress error at height %d: %w", height, err) diff --git a/go/oasis-node/cmd/debug/txsource/workload/transfer.go b/go/oasis-node/cmd/debug/txsource/workload/transfer.go index b65d5027fd6..4294a101d92 100644 --- a/go/oasis-node/cmd/debug/txsource/workload/transfer.go +++ b/go/oasis-node/cmd/debug/txsource/workload/transfer.go @@ -41,7 +41,7 @@ type transfer struct { fundingAccount signature.Signer } -func (t *transfer) doTransferTx(ctx context.Context, fromIdx int, toIdx int) error { +func (t *transfer) doTransferTx(ctx context.Context, fromIdx, toIdx int) error { from := &t.accounts[fromIdx] to := &t.accounts[toIdx] diff --git a/go/oasis-node/cmd/genesis/genesis.go b/go/oasis-node/cmd/genesis/genesis.go index f7a2d4ce614..9353095b154 100644 --- a/go/oasis-node/cmd/genesis/genesis.go +++ b/go/oasis-node/cmd/genesis/genesis.go @@ -261,7 +261,7 @@ func doInitGenesis(cmd *cobra.Command, args []string) { } b, _ := json.Marshal(doc) - if err := ioutil.WriteFile(f, b, 0600); err != nil { + if err := ioutil.WriteFile(f, b, 0o600); err != nil { logger.Error("failed to save generated genesis document", "err", err, ) @@ -557,8 +557,8 @@ func AppendStakingState(doc *genesis.Document, state string, l *logging.Logger) }, } stakingSt.Delegations = map[staking.Address]map[staking.Address]*staking.Delegation{ - entAddr: map[staking.Address]*staking.Delegation{ - entAddr: &staking.Delegation{ + entAddr: { + entAddr: { Shares: stakingTests.QtyFromInt(1), }, }, diff --git a/go/oasis-node/cmd/identity/tendermint/tendermint.go b/go/oasis-node/cmd/identity/tendermint/tendermint.go index c3adf7576aa..8268e61dae0 100644 --- a/go/oasis-node/cmd/identity/tendermint/tendermint.go +++ b/go/oasis-node/cmd/identity/tendermint/tendermint.go @@ -43,7 +43,7 @@ var ( tmFlags = flag.NewFlagSet("", flag.ContinueOnError) ) -func printTmAddress(desc string, keyFile string) { +func printTmAddress(desc, keyFile string) { if err := cmdCommon.Init(); err != nil { cmdCommon.EarlyLogAndExit(err) } diff --git a/go/oasis-node/cmd/keymanager/keymanager.go b/go/oasis-node/cmd/keymanager/keymanager.go index 615a033bbba..e72c8605263 100644 --- a/go/oasis-node/cmd/keymanager/keymanager.go +++ b/go/oasis-node/cmd/keymanager/keymanager.go @@ -102,7 +102,7 @@ func doInitPolicy(cmd *cobra.Command, args []string) { } c := cbor.Marshal(p) - if err = ioutil.WriteFile(viper.GetString(CfgPolicyFile), c, 0666); err != nil { + if err = ioutil.WriteFile(viper.GetString(CfgPolicyFile), c, 0o644); err != nil { // nolint: gosec logger.Error("failed to write key manager policy cbor file", "err", err, "CfgPolicyFile", viper.GetString(CfgPolicyFile), @@ -200,7 +200,6 @@ func policyFromFlags() (*kmApi.PolicySGX, error) { } } } - } return &kmApi.PolicySGX{ @@ -231,7 +230,7 @@ func doSignPolicy(cmd *cobra.Command, args []string) { os.Exit(1) } - if err = ioutil.WriteFile(viper.GetStringSlice(CfgPolicySigFile)[0], sigBytes, 0600); err != nil { + if err = ioutil.WriteFile(viper.GetStringSlice(CfgPolicySigFile)[0], sigBytes, 0o600); err != nil { logger.Error("failed to write policy file signature", "err", err, "CfgPolicySigFile", viper.GetStringSlice(CfgPolicySigFile), @@ -373,7 +372,7 @@ func doInitStatus(cmd *cobra.Command, args []string) { } c, _ := json.Marshal(s) - if err = ioutil.WriteFile(viper.GetString(CfgStatusFile), c, 0666); err != nil { + if err = ioutil.WriteFile(viper.GetString(CfgStatusFile), c, 0o644); err != nil { // nolint: gosec logger.Error("failed to write key manager status json file", "err", err, "CfgStatusFile", viper.GetString(CfgStatusFile), diff --git a/go/oasis-node/cmd/node/node.go b/go/oasis-node/cmd/node/node.go index 7ca7926d39c..6de22819d80 100644 --- a/go/oasis-node/cmd/node/node.go +++ b/go/oasis-node/cmd/node/node.go @@ -439,7 +439,6 @@ func (n *Node) startWorkers(logger *logging.Logger) error { n.MergeWorker.Enabled() || n.KeymanagerWorker.Enabled() || n.ConsensusWorker.Enabled() { - if err := n.CommonWorker.Grpc.Start(); err != nil { logger.Error("failed to start external gRPC server", "err", err, diff --git a/go/oasis-node/cmd/registry/entity/entity.go b/go/oasis-node/cmd/registry/entity/entity.go index 581ab849e2f..7148624ba79 100644 --- a/go/oasis-node/cmd/registry/entity/entity.go +++ b/go/oasis-node/cmd/registry/entity/entity.go @@ -259,7 +259,7 @@ func signAndWriteEntityGenesis(dataDir string, signer signature.Signer, ent *ent // Write out the signed entity registration. b, _ := json.Marshal(signed) - if err = ioutil.WriteFile(filepath.Join(dataDir, entityGenesisFilename), b, 0600); err != nil { + if err = ioutil.WriteFile(filepath.Join(dataDir, entityGenesisFilename), b, 0o600); err != nil { logger.Error("failed to write signed entity genesis registration", "err", err, ) diff --git a/go/oasis-node/cmd/registry/node/node.go b/go/oasis-node/cmd/registry/node/node.go index 9552ae65546..300d684dba4 100644 --- a/go/oasis-node/cmd/registry/node/node.go +++ b/go/oasis-node/cmd/registry/node/node.go @@ -292,7 +292,7 @@ func doInit(cmd *cobra.Command, args []string) { // nolint: gocyclo os.Exit(1) } b, _ := json.Marshal(signed) - if err = ioutil.WriteFile(filepath.Join(dataDir, NodeGenesisFilename), b, 0600); err != nil { + if err = ioutil.WriteFile(filepath.Join(dataDir, NodeGenesisFilename), b, 0o600); err != nil { logger.Error("failed to write signed node genesis registration", "err", err, ) diff --git a/go/oasis-node/cmd/registry/registry.go b/go/oasis-node/cmd/registry/registry.go index 56fe84535e7..229cd82bc0c 100644 --- a/go/oasis-node/cmd/registry/registry.go +++ b/go/oasis-node/cmd/registry/registry.go @@ -9,12 +9,10 @@ import ( "github.com/oasisprotocol/oasis-core/go/oasis-node/cmd/registry/runtime" ) -var ( - registryCmd = &cobra.Command{ - Use: "registry", - Short: "registry backend utilities", - } -) +var registryCmd = &cobra.Command{ + Use: "registry", + Short: "registry backend utilities", +} // Register registers the registry sub-command and all of it's children. func Register(parentCmd *cobra.Command) { diff --git a/go/oasis-node/cmd/registry/runtime/runtime.go b/go/oasis-node/cmd/registry/runtime/runtime.go index 2667e0132c6..0cf7bf17752 100644 --- a/go/oasis-node/cmd/registry/runtime/runtime.go +++ b/go/oasis-node/cmd/registry/runtime/runtime.go @@ -158,7 +158,7 @@ func doInitGenesis(cmd *cobra.Command, args []string) { // Write out the signed runtime registration. b, _ := json.Marshal(signed) - if err = ioutil.WriteFile(filepath.Join(dataDir, viper.GetString(cfgOutput)), b, 0600); err != nil { + if err = ioutil.WriteFile(filepath.Join(dataDir, viper.GetString(cfgOutput)), b, 0o600); err != nil { logger.Error("failed to write signed runtime genesis registration", "err", err, ) @@ -220,7 +220,7 @@ func doList(cmd *cobra.Command, args []string) { var s string switch cmdFlags.Verbose() { case true: - b, _ := json.Marshal(&rt) + b, _ := json.Marshal(rt) s = string(b) default: s = rt.ID.String() diff --git a/go/oasis-node/cmd/root.go b/go/oasis-node/cmd/root.go index d7636fbf9de..69ba16cf8a8 100644 --- a/go/oasis-node/cmd/root.go +++ b/go/oasis-node/cmd/root.go @@ -21,14 +21,12 @@ import ( "github.com/oasisprotocol/oasis-core/go/oasis-node/cmd/stake" ) -var ( - rootCmd = &cobra.Command{ - Use: "oasis-node", - Short: "Oasis Node", - Version: version.SoftwareVersion, - Run: node.Run, - } -) +var rootCmd = &cobra.Command{ + Use: "oasis-node", + Short: "Oasis Node", + Version: version.SoftwareVersion, + Run: node.Run, +} // RootCommand returns the root (top level) cobra.Command. func RootCommand() *cobra.Command { @@ -40,7 +38,7 @@ func RootCommand() *cobra.Command { func Execute() { // Only the owner should have read/write/execute permissions for // anything created by the oasis-node binary. - syscall.Umask(0077) + syscall.Umask(0o077) if err := rootCmd.Execute(); err != nil { cmdCommon.EarlyLogAndExit(err) diff --git a/go/oasis-test-runner/cmd/cmp/cmp.go b/go/oasis-test-runner/cmd/cmp/cmp.go index 2f3d45b2b6d..1dc81656ec9 100644 --- a/go/oasis-test-runner/cmd/cmp/cmp.go +++ b/go/oasis-test-runner/cmd/cmp/cmp.go @@ -43,32 +43,32 @@ min_threshold..{avg|max}_ratio, ba exits with error code 1.`, } allMetrics = map[string]*Metric{ - "time": &Metric{ + "time": { getter: getDuration, maxThresholdAvgRatio: 1.1, maxThresholdMaxRatio: 1.1, }, - "du": &Metric{ + "du": { getter: getDiskUsage, maxThresholdAvgRatio: 1.06, maxThresholdMaxRatio: 1.15, }, - "io": &Metric{ + "io": { getter: getIOWork, maxThresholdAvgRatio: 1.2, maxThresholdMaxRatio: 1.2, }, - "mem": &Metric{ + "mem": { getter: getRssAnonMemory, maxThresholdAvgRatio: 1.1, maxThresholdMaxRatio: 1.1, }, - "cpu": &Metric{ + "cpu": { getter: getCPUTime, maxThresholdAvgRatio: 1.05, maxThresholdMaxRatio: 1.05, }, - "net": &Metric{ + "net": { getter: getNetwork, // Network stats suffer effects from other processes too and varies. maxThresholdAvgRatio: 1.3, @@ -186,7 +186,7 @@ func getCPUTime(ctx context.Context, test string, bi *model.SampleStream) (float // getSummableMetric returns average and maximum sum of metrics for all workers of the given coarse benchmark instance // ("oasis_up" metric). -func getSummableMetric(ctx context.Context, metric string, test string, bi *model.SampleStream) (float64, float64, error) { +func getSummableMetric(ctx context.Context, metric, test string, bi *model.SampleStream) (float64, float64, error) { instance := string(bi.Metric[metrics.MetricsLabelInstance]) labels := bi.Metric.Clone() @@ -343,7 +343,7 @@ func instanceName(s *model.SampleStream) string { // fetchAndCompare fetches the given metric from prometheus and compares the results. // // Returns false, if metric-specific ratios are exceeded or there is a problem obtaining time series. Otherwise true. -func fetchAndCompare(ctx context.Context, m string, test string, sInstance *model.SampleStream, tInstance *model.SampleStream) (succ bool) { +func fetchAndCompare(ctx context.Context, m, test string, sInstance, tInstance *model.SampleStream) (succ bool) { getMetric := allMetrics[m].getter succ = true diff --git a/go/oasis-test-runner/cmd/root.go b/go/oasis-test-runner/cmd/root.go index d334502c923..39a527b17a5 100644 --- a/go/oasis-test-runner/cmd/root.go +++ b/go/oasis-test-runner/cmd/root.go @@ -235,7 +235,7 @@ func initRootEnv(cmd *cobra.Command) (*env.Env, error) { // Initialize logging. logFile := filepath.Join(env.Dir(), "test-runner.log") - w, err := os.OpenFile(logFile, os.O_CREATE|os.O_APPEND|os.O_WRONLY, 0600) + w, err := os.OpenFile(logFile, os.O_CREATE|os.O_APPEND|os.O_WRONLY, 0o600) if err != nil { return nil, fmt.Errorf("root: failed to open log file: %w", err) } diff --git a/go/oasis-test-runner/cmd/root_test.go b/go/oasis-test-runner/cmd/root_test.go index cf7f3def3b1..e009d4f5783 100644 --- a/go/oasis-test-runner/cmd/root_test.go +++ b/go/oasis-test-runner/cmd/root_test.go @@ -17,10 +17,10 @@ func TestComputeParamSets(t *testing.T) { // Single element, multiple parameters. zippedParams = map[string][]string{ - "testParam1": []string{"1"}, - "testParam2": []string{"a"}, - "testParam3": []string{"one"}, - "testParam4": []string{"ena"}, + "testParam1": {"1"}, + "testParam2": {"a"}, + "testParam3": {"one"}, + "testParam4": {"ena"}, } expectedParamSets = []map[string]string{ {"testParam1": "1", "testParam2": "a", "testParam3": "one", "testParam4": "ena"}, @@ -29,8 +29,8 @@ func TestComputeParamSets(t *testing.T) { // Single element, empty string slice hack test. zippedParams = map[string][]string{ - "testParam1": []string{"1"}, - "testParam2": []string{}, + "testParam1": {"1"}, + "testParam2": {}, } expectedParamSets = []map[string]string{ {"testParam1": "1", "testParam2": ""}, @@ -39,8 +39,8 @@ func TestComputeParamSets(t *testing.T) { // Combinations of two elements. zippedParams = map[string][]string{ - "testParam1": []string{"1", "2", "3"}, - "testParam2": []string{"a", "b"}, + "testParam1": {"1", "2", "3"}, + "testParam2": {"a", "b"}, } expectedParamSets = []map[string]string{ {"testParam1": "1", "testParam2": "a"}, @@ -54,8 +54,8 @@ func TestComputeParamSets(t *testing.T) { // Duplicated elements - should not affect the outcome. zippedParams = map[string][]string{ - "testParam1": []string{"1", "1", "1"}, - "testParam2": []string{"a", "b"}, + "testParam1": {"1", "1", "1"}, + "testParam2": {"a", "b"}, } expectedParamSets = []map[string]string{ {"testParam1": "1", "testParam2": "a"}, diff --git a/go/oasis-test-runner/env/dir.go b/go/oasis-test-runner/env/dir.go index 042cb438301..e4cb6a1b959 100644 --- a/go/oasis-test-runner/env/dir.go +++ b/go/oasis-test-runner/env/dir.go @@ -86,7 +86,7 @@ func (d *Dir) NewSubDir(subDirName string) (*Dir, error) { // NewLogWriter creates a log file under a Dir with the provided name. func (d *Dir) NewLogWriter(name string) (io.WriteCloser, error) { fn := filepath.Join(d.String(), name) - w, err := os.OpenFile(fn, os.O_CREATE|os.O_APPEND|os.O_WRONLY, 0600) + w, err := os.OpenFile(fn, os.O_CREATE|os.O_APPEND|os.O_WRONLY, 0o600) if err != nil { return nil, fmt.Errorf("env: failed to create file for append: %w", err) } diff --git a/go/oasis-test-runner/env/env.go b/go/oasis-test-runner/env/env.go index 36692410cc3..4cf1bbafeb3 100644 --- a/go/oasis-test-runner/env/env.go +++ b/go/oasis-test-runner/env/env.go @@ -239,7 +239,7 @@ func (env *Env) WriteTestInfo() error { if err != nil { return err } - if err = ioutil.WriteFile(filepath.Join(env.Dir(), "test_info.json"), b, 0644); err != nil { + if err = ioutil.WriteFile(filepath.Join(env.Dir(), "test_info.json"), b, 0o644); err != nil { // nolint: gosec return err } diff --git a/go/oasis-test-runner/oasis/cli/cli.go b/go/oasis-test-runner/oasis/cli/cli.go index 42836a7d01c..ebf43d70b2a 100644 --- a/go/oasis-test-runner/oasis/cli/cli.go +++ b/go/oasis-test-runner/oasis/cli/cli.go @@ -70,7 +70,7 @@ func New(env *env.Env, factory Factory, logger *logging.Logger) *Helpers { // StartSubCommand launches an oasis-node subcommand. // // It does not wait for the subcommand to complete. -func StartSubCommand(childEnv *env.Env, logger *logging.Logger, name, binary string, args []string, stdout io.Writer, stderr io.Writer) (*exec.Cmd, error) { +func StartSubCommand(childEnv *env.Env, logger *logging.Logger, name, binary string, args []string, stdout, stderr io.Writer) (*exec.Cmd, error) { cmd := exec.Command(binary, args...) cmd.SysProcAttr = env.CmdAttrs cmd.Stdout = stdout diff --git a/go/oasis-test-runner/oasis/cli/keymanager.go b/go/oasis-test-runner/oasis/cli/keymanager.go index 6281205e8bc..419b58585a3 100644 --- a/go/oasis-test-runner/oasis/cli/keymanager.go +++ b/go/oasis-test-runner/oasis/cli/keymanager.go @@ -62,7 +62,7 @@ func (k *KeymanagerHelpers) InitPolicy(runtimeID common.Namespace, serial uint32 } // SignPolicy signs the KM policy file using the given test key ("1", "2", or "3"). -func (k *KeymanagerHelpers) SignPolicy(testKey string, polPath string, polSigPath string) error { +func (k *KeymanagerHelpers) SignPolicy(testKey, polPath, polSigPath string) error { k.logger.Info("signing KM policy", "policy_path", polPath, "policy_signature_path", polSigPath, diff --git a/go/oasis-test-runner/oasis/fixture.go b/go/oasis-test-runner/oasis/fixture.go index 28b7761c03d..6d1fab6e954 100644 --- a/go/oasis-test-runner/oasis/fixture.go +++ b/go/oasis-test-runner/oasis/fixture.go @@ -46,7 +46,7 @@ func (f *NetworkFixture) Create(env *env.Env) (*Network, error) { // Provision entities. for _, entCfg := range f.Entities { - if _, err = net.NewEntity(&entCfg); err != nil { + if _, err = net.NewEntity(&entCfg); err != nil { // nolint: gosec return nil, fmt.Errorf("failed to provision entity: %w", err) } } diff --git a/go/oasis-test-runner/scenario/e2e/e2e.go b/go/oasis-test-runner/scenario/e2e/e2e.go index 40d73d65997..3dfae8e7795 100644 --- a/go/oasis-test-runner/scenario/e2e/e2e.go +++ b/go/oasis-test-runner/scenario/e2e/e2e.go @@ -25,10 +25,8 @@ const ( cfgNodeBinary = "node.binary" ) -var ( - // E2eParamsDummy is a dummy instance of E2E used to register global e2e flags. - E2eParamsDummy *E2E = NewE2E("") -) +// E2eParamsDummy is a dummy instance of E2E used to register global e2e flags. +var E2eParamsDummy *E2E = NewE2E("") // E2E is a base scenario for oasis-node end-to-end tests. type E2E struct { @@ -92,13 +90,13 @@ func (sc *E2E) Fixture() (*oasis.NetworkFixture, error) { ConsensusGasCostsTxByte: 1, }, Entities: []oasis.EntityCfg{ - oasis.EntityCfg{IsDebugTestEntity: true}, - oasis.EntityCfg{}, + {IsDebugTestEntity: true}, + {}, }, Validators: []oasis.ValidatorFixture{ - oasis.ValidatorFixture{Entity: 1, Consensus: oasis.ConsensusFixture{EnableConsensusRPCWorker: true}}, - oasis.ValidatorFixture{Entity: 1, Consensus: oasis.ConsensusFixture{EnableConsensusRPCWorker: true}}, - oasis.ValidatorFixture{Entity: 1, Consensus: oasis.ConsensusFixture{EnableConsensusRPCWorker: true}}, + {Entity: 1, Consensus: oasis.ConsensusFixture{EnableConsensusRPCWorker: true}}, + {Entity: 1, Consensus: oasis.ConsensusFixture{EnableConsensusRPCWorker: true}}, + {Entity: 1, Consensus: oasis.ConsensusFixture{EnableConsensusRPCWorker: true}}, }, }, nil } diff --git a/go/oasis-test-runner/scenario/e2e/early_query.go b/go/oasis-test-runner/scenario/e2e/early_query.go index ad77b77aa0d..9531009d545 100644 --- a/go/oasis-test-runner/scenario/e2e/early_query.go +++ b/go/oasis-test-runner/scenario/e2e/early_query.go @@ -12,13 +12,11 @@ import ( "github.com/oasisprotocol/oasis-core/go/oasis-test-runner/scenario" ) -var ( - // EarlyQuery is the early query scenario where we query a validator node before the network - // has started and there are no committed blocks. - EarlyQuery scenario.Scenario = &earlyQueryImpl{ - E2E: *NewE2E("early-query"), - } -) +// EarlyQuery is the early query scenario where we query a validator node before the network +// has started and there are no committed blocks. +var EarlyQuery scenario.Scenario = &earlyQueryImpl{ + E2E: *NewE2E("early-query"), +} type earlyQueryImpl struct { E2E diff --git a/go/oasis-test-runner/scenario/e2e/gas_fees_staking.go b/go/oasis-test-runner/scenario/e2e/gas_fees_staking.go index 4c193cd2bd3..5d1c10756a4 100644 --- a/go/oasis-test-runner/scenario/e2e/gas_fees_staking.go +++ b/go/oasis-test-runner/scenario/e2e/gas_fees_staking.go @@ -69,17 +69,17 @@ func (sc *gasFeesImpl) Fixture() (*oasis.NetworkFixture, error) { ConsensusGasCostsTxByte: 0, // So we can control gas more easily. }, Entities: []oasis.EntityCfg{ - oasis.EntityCfg{IsDebugTestEntity: true}, - oasis.EntityCfg{}, - oasis.EntityCfg{}, - oasis.EntityCfg{}, + {IsDebugTestEntity: true}, + {}, + {}, + {}, }, Validators: []oasis.ValidatorFixture{ // Create three validators, each with its own entity so we can test // if gas disbursement works correctly. - oasis.ValidatorFixture{Entity: 1, Consensus: oasis.ConsensusFixture{MinGasPrice: 1}}, - oasis.ValidatorFixture{Entity: 2, Consensus: oasis.ConsensusFixture{MinGasPrice: 1}}, - oasis.ValidatorFixture{Entity: 3, Consensus: oasis.ConsensusFixture{MinGasPrice: 1}}, + {Entity: 1, Consensus: oasis.ConsensusFixture{MinGasPrice: 1}}, + {Entity: 2, Consensus: oasis.ConsensusFixture{MinGasPrice: 1}}, + {Entity: 3, Consensus: oasis.ConsensusFixture{MinGasPrice: 1}}, }, }, nil } diff --git a/go/oasis-test-runner/scenario/e2e/identity_cli.go b/go/oasis-test-runner/scenario/e2e/identity_cli.go index 13d845cf23e..c2df66a9280 100644 --- a/go/oasis-test-runner/scenario/e2e/identity_cli.go +++ b/go/oasis-test-runner/scenario/e2e/identity_cli.go @@ -13,12 +13,10 @@ import ( "github.com/oasisprotocol/oasis-core/go/oasis-test-runner/scenario" ) -var ( - // IdentityCLI is the identity CLI scenario. - IdentityCLI scenario.Scenario = &identityCLIImpl{ - E2E: *NewE2E("identity-cli"), - } -) +// IdentityCLI is the identity CLI scenario. +var IdentityCLI scenario.Scenario = &identityCLIImpl{ + E2E: *NewE2E("identity-cli"), +} type identityCLIImpl struct { E2E diff --git a/go/oasis-test-runner/scenario/e2e/registry_cli.go b/go/oasis-test-runner/scenario/e2e/registry_cli.go index 781c3644b35..dbda0f5b785 100644 --- a/go/oasis-test-runner/scenario/e2e/registry_cli.go +++ b/go/oasis-test-runner/scenario/e2e/registry_cli.go @@ -35,12 +35,10 @@ import ( staking "github.com/oasisprotocol/oasis-core/go/staking/api" ) -var ( - // RegistryCLI is the registry CLI test scenario. - RegistryCLI scenario.Scenario = ®istryCLIImpl{ - E2E: *NewE2E("registry-cli"), - } -) +// RegistryCLI is the registry CLI test scenario. +var RegistryCLI scenario.Scenario = ®istryCLIImpl{ + E2E: *NewE2E("registry-cli"), +} type registryCLIImpl struct { E2E @@ -433,7 +431,7 @@ func (sc *registryCLIImpl) newTestNode(entityID signature.PublicKey) (*node.Node } // initNode very "thoroughly" initializes new node and returns its instance. -func (sc *registryCLIImpl) initNode(childEnv *env.Env, ent *entity.Entity, entDir string, dataDir string) (*node.Node, error) { +func (sc *registryCLIImpl) initNode(childEnv *env.Env, ent *entity.Entity, entDir, dataDir string) (*node.Node, error) { sc.Logger.Info("initializing new node") // testNode will be our fixture for testing the CLI. @@ -545,7 +543,7 @@ func (sc *registryCLIImpl) initNode(childEnv *env.Env, ent *entity.Entity, entDi } // genRegisterEntityTx calls registry entity gen_register. -func (sc *registryCLIImpl) genRegisterEntityTx(childEnv *env.Env, nonce int, txPath string, entDir string) error { +func (sc *registryCLIImpl) genRegisterEntityTx(childEnv *env.Env, nonce int, txPath, entDir string) error { sc.Logger.Info("generating register entity tx") args := []string{ @@ -568,7 +566,7 @@ func (sc *registryCLIImpl) genRegisterEntityTx(childEnv *env.Env, nonce int, txP } // genDeregisterEntityTx calls registry entity gen_deregister. -func (sc *registryCLIImpl) genDeregisterEntityTx(childEnv *env.Env, nonce int, txPath string, entDir string) error { +func (sc *registryCLIImpl) genDeregisterEntityTx(childEnv *env.Env, nonce int, txPath, entDir string) error { sc.Logger.Info("generating deregister entity tx") args := []string{ @@ -663,7 +661,7 @@ func (sc *registryCLIImpl) testRuntime(childEnv *env.Env, cli *cli.Helpers) erro registerTxPath := filepath.Join(childEnv.Dir(), "registry_runtime_register.json") genesisStatePath := filepath.Join(childEnv.Dir(), "registry_runtime_register_genesis_state.json") genesisStateStr, _ := json.Marshal(testRuntime.Genesis.State) - if err = ioutil.WriteFile(genesisStatePath, genesisStateStr, 0600); err != nil { + if err = ioutil.WriteFile(genesisStatePath, genesisStateStr, 0o600); err != nil { return err } if err = cli.Registry.GenerateRegisterRuntimeTx(0, testRuntime, registerTxPath, genesisStatePath); err != nil { diff --git a/go/oasis-test-runner/scenario/e2e/runtime/byzantine.go b/go/oasis-test-runner/scenario/e2e/runtime/byzantine.go index 12065b9d018..969a157f423 100644 --- a/go/oasis-test-runner/scenario/e2e/runtime/byzantine.go +++ b/go/oasis-test-runner/scenario/e2e/runtime/byzantine.go @@ -102,7 +102,7 @@ func (sc *byzantineImpl) Fixture() (*oasis.NetworkFixture, error) { } // Provision a Byzantine node. f.ByzantineNodes = []oasis.ByzantineFixture{ - oasis.ByzantineFixture{ + { Script: sc.script, IdentitySeed: sc.identitySeed, Entity: 1, diff --git a/go/oasis-test-runner/scenario/e2e/runtime/dump_restore.go b/go/oasis-test-runner/scenario/e2e/runtime/dump_restore.go index dbd5ab1b818..ab86b49029d 100644 --- a/go/oasis-test-runner/scenario/e2e/runtime/dump_restore.go +++ b/go/oasis-test-runner/scenario/e2e/runtime/dump_restore.go @@ -5,10 +5,8 @@ import ( "github.com/oasisprotocol/oasis-core/go/oasis-test-runner/scenario" ) -var ( - // DumpRestore is the dump and restore scenario. - DumpRestore scenario.Scenario = newDumpRestoreImpl() -) +// DumpRestore is the dump and restore scenario. +var DumpRestore scenario.Scenario = newDumpRestoreImpl() type dumpRestoreImpl struct { runtimeImpl diff --git a/go/oasis-test-runner/scenario/e2e/runtime/gas_fees.go b/go/oasis-test-runner/scenario/e2e/runtime/gas_fees.go index 03843cf1c82..ef2fbed0976 100644 --- a/go/oasis-test-runner/scenario/e2e/runtime/gas_fees.go +++ b/go/oasis-test-runner/scenario/e2e/runtime/gas_fees.go @@ -8,12 +8,10 @@ import ( "github.com/oasisprotocol/oasis-core/go/oasis-test-runner/scenario" ) -var ( - // GasFeesRuntimes is the runtime gas fees scenario. - GasFeesRuntimes scenario.Scenario = &gasFeesRuntimesImpl{ - runtimeImpl: *newRuntimeImpl("gas-fees/runtimes", "", nil), - } -) +// GasFeesRuntimes is the runtime gas fees scenario. +var GasFeesRuntimes scenario.Scenario = &gasFeesRuntimesImpl{ + runtimeImpl: *newRuntimeImpl("gas-fees/runtimes", "", nil), +} // gasPrice is the gas price used during the test. const gasPrice = 1 diff --git a/go/oasis-test-runner/scenario/e2e/runtime/keymanager_replicate.go b/go/oasis-test-runner/scenario/e2e/runtime/keymanager_replicate.go index d9ca5d18635..53d6e4c4ae0 100644 --- a/go/oasis-test-runner/scenario/e2e/runtime/keymanager_replicate.go +++ b/go/oasis-test-runner/scenario/e2e/runtime/keymanager_replicate.go @@ -44,8 +44,8 @@ func (sc *kmReplicateImpl) Fixture() (*oasis.NetworkFixture, error) { // This requires multiple keymanagers. f.Keymanagers = []oasis.KeymanagerFixture{ - oasis.KeymanagerFixture{Runtime: 0, Entity: 1}, - oasis.KeymanagerFixture{Runtime: 0, Entity: 1}, + {Runtime: 0, Entity: 1}, + {Runtime: 0, Entity: 1}, } return f, nil diff --git a/go/oasis-test-runner/scenario/e2e/runtime/keymanager_restart.go b/go/oasis-test-runner/scenario/e2e/runtime/keymanager_restart.go index 462b761a965..7ff54efedaa 100644 --- a/go/oasis-test-runner/scenario/e2e/runtime/keymanager_restart.go +++ b/go/oasis-test-runner/scenario/e2e/runtime/keymanager_restart.go @@ -8,10 +8,8 @@ import ( "github.com/oasisprotocol/oasis-core/go/oasis-test-runner/scenario" ) -var ( - // KeymanagerRestart is the keymanager restart scenario. - KeymanagerRestart scenario.Scenario = newKmRestartImpl() -) +// KeymanagerRestart is the keymanager restart scenario. +var KeymanagerRestart scenario.Scenario = newKmRestartImpl() type kmRestartImpl struct { runtimeImpl diff --git a/go/oasis-test-runner/scenario/e2e/runtime/late_start.go b/go/oasis-test-runner/scenario/e2e/runtime/late_start.go index b77e1ce7522..ad4aa2f30b8 100644 --- a/go/oasis-test-runner/scenario/e2e/runtime/late_start.go +++ b/go/oasis-test-runner/scenario/e2e/runtime/late_start.go @@ -8,10 +8,8 @@ import ( "github.com/oasisprotocol/oasis-core/go/oasis-test-runner/scenario" ) -var ( - // LateStart is the LateStart node basic scenario. - LateStart scenario.Scenario = newLateStartImpl("late-start", "simple-keyvalue-client", nil) -) +// LateStart is the LateStart node basic scenario. +var LateStart scenario.Scenario = newLateStartImpl("late-start", "simple-keyvalue-client", nil) const lateStartInitialWait = 2 * time.Minute diff --git a/go/oasis-test-runner/scenario/e2e/runtime/multiple_runtimes.go b/go/oasis-test-runner/scenario/e2e/runtime/multiple_runtimes.go index 2b4638513bd..2211bc82440 100644 --- a/go/oasis-test-runner/scenario/e2e/runtime/multiple_runtimes.go +++ b/go/oasis-test-runner/scenario/e2e/runtime/multiple_runtimes.go @@ -24,20 +24,18 @@ const ( cfgExecutorGroupSize = "executor_group_size" ) -var ( - // MultipleRuntimes is a scenario which tests running multiple runtimes on one node. - MultipleRuntimes = func() scenario.Scenario { - sc := &multipleRuntimesImpl{ - runtimeImpl: *newRuntimeImpl("multiple-runtimes", "simple-keyvalue-client", nil), - } - sc.Flags.Int(cfgNumComputeRuntimes, 2, "number of compute runtimes per worker") - sc.Flags.Int(cfgNumComputeRuntimeTxns, 2, "number of transactions to perform") - sc.Flags.Int(cfgNumComputeWorkers, 2, "number of workers to initiate") - sc.Flags.Int(cfgExecutorGroupSize, 2, "number of executor workers in committee") +// MultipleRuntimes is a scenario which tests running multiple runtimes on one node. +var MultipleRuntimes = func() scenario.Scenario { + sc := &multipleRuntimesImpl{ + runtimeImpl: *newRuntimeImpl("multiple-runtimes", "simple-keyvalue-client", nil), + } + sc.Flags.Int(cfgNumComputeRuntimes, 2, "number of compute runtimes per worker") + sc.Flags.Int(cfgNumComputeRuntimeTxns, 2, "number of transactions to perform") + sc.Flags.Int(cfgNumComputeWorkers, 2, "number of workers to initiate") + sc.Flags.Int(cfgExecutorGroupSize, 2, "number of executor workers in committee") - return sc - }() -) + return sc +}() type multipleRuntimesImpl struct { runtimeImpl diff --git a/go/oasis-test-runner/scenario/e2e/runtime/node_shutdown.go b/go/oasis-test-runner/scenario/e2e/runtime/node_shutdown.go index 390c5a3636d..1d785cbbf7e 100644 --- a/go/oasis-test-runner/scenario/e2e/runtime/node_shutdown.go +++ b/go/oasis-test-runner/scenario/e2e/runtime/node_shutdown.go @@ -10,10 +10,8 @@ import ( "github.com/oasisprotocol/oasis-core/go/oasis-test-runner/scenario" ) -var ( - // NodeShutdown is the keymanager restart scenario. - NodeShutdown scenario.Scenario = newNodeShutdownImpl() -) +// NodeShutdown is the keymanager restart scenario. +var NodeShutdown scenario.Scenario = newNodeShutdownImpl() type nodeShutdownImpl struct { runtimeImpl diff --git a/go/oasis-test-runner/scenario/e2e/runtime/runtime.go b/go/oasis-test-runner/scenario/e2e/runtime/runtime.go index a9bfba85597..178987d04d8 100644 --- a/go/oasis-test-runner/scenario/e2e/runtime/runtime.go +++ b/go/oasis-test-runner/scenario/e2e/runtime/runtime.go @@ -136,12 +136,12 @@ func (sc *runtimeImpl) Fixture() (*oasis.NetworkFixture, error) { }, }, Entities: []oasis.EntityCfg{ - oasis.EntityCfg{IsDebugTestEntity: true}, - oasis.EntityCfg{}, + {IsDebugTestEntity: true}, + {}, }, Runtimes: []oasis.RuntimeFixture{ // Key manager runtime. - oasis.RuntimeFixture{ + { ID: keymanagerID, Kind: registry.KindKeyManager, Entity: 0, @@ -152,7 +152,7 @@ func (sc *runtimeImpl) Fixture() (*oasis.NetworkFixture, error) { Binaries: []string{keyManagerBinary}, }, // Compute runtime. - oasis.RuntimeFixture{ + { ID: runtimeID, Kind: registry.KindCompute, Entity: 0, @@ -189,28 +189,28 @@ func (sc *runtimeImpl) Fixture() (*oasis.NetworkFixture, error) { }, }, Validators: []oasis.ValidatorFixture{ - oasis.ValidatorFixture{Entity: 1, Consensus: oasis.ConsensusFixture{EnableConsensusRPCWorker: true}}, - oasis.ValidatorFixture{Entity: 1, Consensus: oasis.ConsensusFixture{EnableConsensusRPCWorker: true}}, - oasis.ValidatorFixture{Entity: 1, Consensus: oasis.ConsensusFixture{EnableConsensusRPCWorker: true}}, + {Entity: 1, Consensus: oasis.ConsensusFixture{EnableConsensusRPCWorker: true}}, + {Entity: 1, Consensus: oasis.ConsensusFixture{EnableConsensusRPCWorker: true}}, + {Entity: 1, Consensus: oasis.ConsensusFixture{EnableConsensusRPCWorker: true}}, }, KeymanagerPolicies: []oasis.KeymanagerPolicyFixture{ - oasis.KeymanagerPolicyFixture{Runtime: 0, Serial: 1}, + {Runtime: 0, Serial: 1}, }, Keymanagers: []oasis.KeymanagerFixture{ - oasis.KeymanagerFixture{Runtime: 0, Entity: 1}, + {Runtime: 0, Entity: 1}, }, StorageWorkers: []oasis.StorageWorkerFixture{ - oasis.StorageWorkerFixture{Backend: database.BackendNameBadgerDB, Entity: 1}, - oasis.StorageWorkerFixture{Backend: database.BackendNameBadgerDB, Entity: 1}, + {Backend: database.BackendNameBadgerDB, Entity: 1}, + {Backend: database.BackendNameBadgerDB, Entity: 1}, }, ComputeWorkers: []oasis.ComputeWorkerFixture{ - oasis.ComputeWorkerFixture{Entity: 1}, - oasis.ComputeWorkerFixture{Entity: 1}, - oasis.ComputeWorkerFixture{Entity: 1}, + {Entity: 1}, + {Entity: 1}, + {Entity: 1}, }, Sentries: []oasis.SentryFixture{}, Clients: []oasis.ClientFixture{ - oasis.ClientFixture{}, + {}, }, }, nil } diff --git a/go/oasis-test-runner/scenario/e2e/runtime/runtime_dynamic.go b/go/oasis-test-runner/scenario/e2e/runtime/runtime_dynamic.go index 392369082dd..eeb4ba1da62 100644 --- a/go/oasis-test-runner/scenario/e2e/runtime/runtime_dynamic.go +++ b/go/oasis-test-runner/scenario/e2e/runtime/runtime_dynamic.go @@ -23,10 +23,8 @@ import ( staking "github.com/oasisprotocol/oasis-core/go/staking/api" ) -var ( - // RuntimeDynamic is the dynamic runtime registration scenario. - RuntimeDynamic scenario.Scenario = newRuntimeDynamicImpl() -) +// RuntimeDynamic is the dynamic runtime registration scenario. +var RuntimeDynamic scenario.Scenario = newRuntimeDynamicImpl() type runtimeDynamicImpl struct { runtimeImpl diff --git a/go/oasis-test-runner/scenario/e2e/runtime/runtime_prune.go b/go/oasis-test-runner/scenario/e2e/runtime/runtime_prune.go index c6975ae844b..9ef90697da3 100644 --- a/go/oasis-test-runner/scenario/e2e/runtime/runtime_prune.go +++ b/go/oasis-test-runner/scenario/e2e/runtime/runtime_prune.go @@ -12,10 +12,8 @@ import ( "github.com/oasisprotocol/oasis-core/go/runtime/history" ) -var ( - // RuntimePrune is the runtime prune scenario. - RuntimePrune scenario.Scenario = newRuntimePruneImpl() -) +// RuntimePrune is the runtime prune scenario. +var RuntimePrune scenario.Scenario = newRuntimePruneImpl() const ( // pruneNumKept is the number of last blocks the pruner should keep. diff --git a/go/oasis-test-runner/scenario/e2e/runtime/storage_sync.go b/go/oasis-test-runner/scenario/e2e/runtime/storage_sync.go index b77def956f0..8bdb1e48fe8 100644 --- a/go/oasis-test-runner/scenario/e2e/runtime/storage_sync.go +++ b/go/oasis-test-runner/scenario/e2e/runtime/storage_sync.go @@ -14,10 +14,8 @@ import ( "github.com/oasisprotocol/oasis-core/go/storage/mkvs/checkpoint" ) -var ( - // StorageSync is the storage sync scenario. - StorageSync scenario.Scenario = newStorageSyncImpl() -) +// StorageSync is the storage sync scenario. +var StorageSync scenario.Scenario = newStorageSyncImpl() type storageSyncImpl struct { runtimeImpl diff --git a/go/oasis-test-runner/scenario/e2e/runtime/txsource.go b/go/oasis-test-runner/scenario/e2e/runtime/txsource.go index 8fc7cc39cea..d2dd7f909d0 100644 --- a/go/oasis-test-runner/scenario/e2e/runtime/txsource.go +++ b/go/oasis-test-runner/scenario/e2e/runtime/txsource.go @@ -161,10 +161,10 @@ func (sc *txSourceImpl) Fixture() (*oasis.NetworkFixture, error) { // Use at least 4 validators so that consensus can keep making progress // when a node is being killed and restarted. f.Validators = []oasis.ValidatorFixture{ - oasis.ValidatorFixture{Entity: 1}, - oasis.ValidatorFixture{Entity: 1}, - oasis.ValidatorFixture{Entity: 1}, - oasis.ValidatorFixture{Entity: 1}, + {Entity: 1}, + {Entity: 1}, + {Entity: 1}, + {Entity: 1}, } // Update validators to require fee payments. diff --git a/go/oasis-test-runner/scenario/e2e/stake_cli.go b/go/oasis-test-runner/scenario/e2e/stake_cli.go index 051ba07cab3..1ed226c6399 100644 --- a/go/oasis-test-runner/scenario/e2e/stake_cli.go +++ b/go/oasis-test-runner/scenario/e2e/stake_cli.go @@ -216,7 +216,7 @@ func (sc *stakeCLIImpl) Run(childEnv *env.Env) error { return nil } -func (sc *stakeCLIImpl) testPubkey2Address(childEnv *env.Env, publicKeyText string, addressText string) error { +func (sc *stakeCLIImpl) testPubkey2Address(childEnv *env.Env, publicKeyText, addressText string) error { args := []string{ "stake", "pubkey2address", "--" + stake.CfgPublicKey, publicKeyText, @@ -242,7 +242,7 @@ func (sc *stakeCLIImpl) testPubkey2Address(childEnv *env.Env, publicKeyText stri } // testTransfer tests transfer of transferAmount tokens from src to dst. -func (sc *stakeCLIImpl) testTransfer(childEnv *env.Env, cli *cli.Helpers, src api.Address, dst api.Address) error { +func (sc *stakeCLIImpl) testTransfer(childEnv *env.Env, cli *cli.Helpers, src, dst api.Address) error { var srcNonce, dstNonce uint64 = 0, 0 unsignedTransferTxPath := filepath.Join(childEnv.Dir(), "stake_transfer_unsigned.cbor") @@ -287,13 +287,15 @@ func (sc *stakeCLIImpl) testTransfer(childEnv *env.Env, cli *cli.Helpers, src ap expectedSrcBalance = mustInitQuantity(initBalance - transferAmount - feeAmount) if err = sc.checkGeneralAccount(childEnv, src, &api.GeneralAccount{ - Balance: expectedSrcBalance, Nonce: srcNonce + 1}, + Balance: expectedSrcBalance, Nonce: srcNonce + 1, + }, ); err != nil { return err } expectedDstBalance := mustInitQuantity(transferAmount) if err = sc.checkGeneralAccount(childEnv, dst, &api.GeneralAccount{ - Balance: expectedDstBalance, Nonce: dstNonce}, + Balance: expectedDstBalance, Nonce: dstNonce, + }, ); err != nil { return err } @@ -343,7 +345,7 @@ func (sc *stakeCLIImpl) testBurn(childEnv *env.Env, cli *cli.Helpers, src api.Ad } // testEscrow tests escrowing escrowAmount tokens from src to dst. -func (sc *stakeCLIImpl) testEscrow(childEnv *env.Env, cli *cli.Helpers, src api.Address, escrow api.Address) error { +func (sc *stakeCLIImpl) testEscrow(childEnv *env.Env, cli *cli.Helpers, src, escrow api.Address) error { var srcNonce uint64 = 2 escrowTxPath := filepath.Join(childEnv.Dir(), "stake_escrow.json") @@ -388,7 +390,7 @@ func (sc *stakeCLIImpl) testEscrow(childEnv *env.Env, cli *cli.Helpers, src api. } // testReclaimEscrow test reclaiming reclaimEscrowShares shares from an escrow account. -func (sc *stakeCLIImpl) testReclaimEscrow(childEnv *env.Env, cli *cli.Helpers, src api.Address, escrow api.Address) error { +func (sc *stakeCLIImpl) testReclaimEscrow(childEnv *env.Env, cli *cli.Helpers, src, escrow api.Address) error { var srcNonce uint64 = 3 reclaimEscrowTxPath := filepath.Join(childEnv.Dir(), "stake_reclaim_escrow.json") @@ -406,7 +408,6 @@ func (sc *stakeCLIImpl) testReclaimEscrow(childEnv *env.Env, cli *cli.Helpers, s if err := cli.Consensus.SubmitTx(reclaimEscrowTxPath); err != nil { return err - } expectedEscrowDebondingBalance := mustInitQuantity(reclaimEscrowAmount) @@ -687,7 +688,7 @@ func (sc *stakeCLIImpl) showTx(childEnv *env.Env, txPath string) error { return nil } -func (sc *stakeCLIImpl) genUnsignedTransferTx(childEnv *env.Env, amount int, nonce int, dst api.Address, txPath string) error { +func (sc *stakeCLIImpl) genUnsignedTransferTx(childEnv *env.Env, amount, nonce int, dst api.Address, txPath string) error { sc.Logger.Info("generating unsigned stake transfer tx", stake.CfgTransferDestination, dst) args := []string{ diff --git a/go/oasis-test-runner/scenario/e2e/upgrade.go b/go/oasis-test-runner/scenario/e2e/upgrade.go index 38256b387da..cddc6c6cb9a 100644 --- a/go/oasis-test-runner/scenario/e2e/upgrade.go +++ b/go/oasis-test-runner/scenario/e2e/upgrade.go @@ -65,7 +65,7 @@ type nodeUpgradeImpl struct { func (sc *nodeUpgradeImpl) writeDescriptor(name string, content []byte) (string, error) { filePath := path.Join(sc.Net.BasePath(), "upgrade-"+name+".json") - if err := ioutil.WriteFile(filePath, content, 0644); err != nil { //nolint: gosec + if err := ioutil.WriteFile(filePath, content, 0o644); err != nil { //nolint: gosec sc.Logger.Error("can't write descriptor to network directory", "err", err, "name", name, @@ -138,14 +138,14 @@ func (sc *nodeUpgradeImpl) Fixture() (*oasis.NetworkFixture, error) { }, }, Entities: []oasis.EntityCfg{ - oasis.EntityCfg{IsDebugTestEntity: true}, - oasis.EntityCfg{}, + {IsDebugTestEntity: true}, + {}, }, Validators: []oasis.ValidatorFixture{ - oasis.ValidatorFixture{Entity: 1, AllowErrorTermination: true}, - oasis.ValidatorFixture{Entity: 1, AllowErrorTermination: true}, - oasis.ValidatorFixture{Entity: 1, AllowErrorTermination: true}, - oasis.ValidatorFixture{Entity: 1, AllowErrorTermination: true}, + {Entity: 1, AllowErrorTermination: true}, + {Entity: 1, AllowErrorTermination: true}, + {Entity: 1, AllowErrorTermination: true}, + {Entity: 1, AllowErrorTermination: true}, }, }, nil } diff --git a/go/oasis-test-runner/scenario/e2e/upgrade_cancel.go b/go/oasis-test-runner/scenario/e2e/upgrade_cancel.go index c97f7711c58..3895e9b8d18 100644 --- a/go/oasis-test-runner/scenario/e2e/upgrade_cancel.go +++ b/go/oasis-test-runner/scenario/e2e/upgrade_cancel.go @@ -69,14 +69,14 @@ func (sc *nodeUpgradeCancelImpl) Fixture() (*oasis.NetworkFixture, error) { EpochtimeMock: true, }, Entities: []oasis.EntityCfg{ - oasis.EntityCfg{IsDebugTestEntity: true}, - oasis.EntityCfg{}, + {IsDebugTestEntity: true}, + {}, }, Validators: []oasis.ValidatorFixture{ - oasis.ValidatorFixture{Entity: 1}, - oasis.ValidatorFixture{Entity: 1}, - oasis.ValidatorFixture{Entity: 1}, - oasis.ValidatorFixture{Entity: 1}, + {Entity: 1}, + {Entity: 1}, + {Entity: 1}, + {Entity: 1}, }, }, nil } @@ -112,7 +112,7 @@ func (sc *nodeUpgradeCancelImpl) Run(childEnv *env.Env) error { descriptor := fmt.Sprintf(descriptorTemplate, nodeHash.String()) filePath := path.Join(sc.Net.BasePath(), "upgrade-descriptor.json") - if err = ioutil.WriteFile(filePath, []byte(descriptor), 0644); err != nil { //nolint: gosec + if err = ioutil.WriteFile(filePath, []byte(descriptor), 0o644); err != nil { //nolint: gosec return fmt.Errorf("can't write descriptor to network directory: %w", err) } diff --git a/go/oasis-test-runner/scenario/remotesigner/basic.go b/go/oasis-test-runner/scenario/remotesigner/basic.go index 0a54599a8c5..8132e12ba36 100644 --- a/go/oasis-test-runner/scenario/remotesigner/basic.go +++ b/go/oasis-test-runner/scenario/remotesigner/basic.go @@ -15,10 +15,8 @@ import ( "github.com/oasisprotocol/oasis-core/go/oasis-test-runner/scenario" ) -var ( - // Basic is the basic test case. - Basic scenario.Scenario = newBasicImpl() -) +// Basic is the basic test case. +var Basic scenario.Scenario = newBasicImpl() func newBasicImpl() *basicImpl { return &basicImpl{ diff --git a/go/oasis-test-runner/scenario/remotesigner/remotesigner.go b/go/oasis-test-runner/scenario/remotesigner/remotesigner.go index d24992a8808..b777d97e444 100644 --- a/go/oasis-test-runner/scenario/remotesigner/remotesigner.go +++ b/go/oasis-test-runner/scenario/remotesigner/remotesigner.go @@ -16,11 +16,9 @@ const ( cfgServerBinary = "binary" ) -var ( - // RemoteSignerParamsDummy is a dummy instance of remoteSignerImpl used to register global - // remote-signer flags. - RemoteSignerParamsDummy *remoteSignerImpl = newRemoteSignerImpl("") -) +// RemoteSignerParamsDummy is a dummy instance of remoteSignerImpl used to register global +// remote-signer flags. +var RemoteSignerParamsDummy *remoteSignerImpl = newRemoteSignerImpl("") type remoteSignerImpl struct { name string diff --git a/go/registry/api/api.go b/go/registry/api/api.go index a6cf8c04814..af9b7c00a34 100644 --- a/go/registry/api/api.go +++ b/go/registry/api/api.go @@ -350,7 +350,7 @@ type RuntimeLookup interface { } // VerifyRegisterEntityArgs verifies arguments for RegisterEntity. -func VerifyRegisterEntityArgs(logger *logging.Logger, sigEnt *entity.SignedEntity, isGenesis bool, isSanityCheck bool) (*entity.Entity, error) { +func VerifyRegisterEntityArgs(logger *logging.Logger, sigEnt *entity.SignedEntity, isGenesis, isSanityCheck bool) (*entity.Entity, error) { var ent entity.Entity if sigEnt == nil { return nil, ErrInvalidArgument @@ -867,7 +867,7 @@ func verifyAddresses(params *ConsensusParameters, addressRequired bool, addresse } // verifyNodeRuntimeChanges verifies node runtime changes. -func verifyNodeRuntimeChanges(logger *logging.Logger, currentRuntimes []*node.Runtime, newRuntimes []*node.Runtime) bool { +func verifyNodeRuntimeChanges(logger *logging.Logger, currentRuntimes, newRuntimes []*node.Runtime) bool { if len(newRuntimes) < len(currentRuntimes) { logger.Error("RegisterNode: trying to update runtimes, cannot remove existing runtimes", "current_runtimes", currentRuntimes, @@ -905,7 +905,7 @@ func verifyNodeRuntimeChanges(logger *logging.Logger, currentRuntimes []*node.Ru } // verifyRuntimeCapabilities verifies node runtime capabilities changes. -func verifyRuntimeCapabilities(logger *logging.Logger, currentCaps *node.Capabilities, newCaps *node.Capabilities) bool { +func verifyRuntimeCapabilities(logger *logging.Logger, currentCaps, newCaps *node.Capabilities) bool { // TEE capability. if (currentCaps.TEE == nil) != (newCaps.TEE == nil) { logger.Error("RegisterNode: trying to change between TEE/non-TEE capability", diff --git a/go/registry/api/sanity_check.go b/go/registry/api/sanity_check.go index aa0530472a8..01f7a3fc682 100644 --- a/go/registry/api/sanity_check.go +++ b/go/registry/api/sanity_check.go @@ -323,7 +323,7 @@ func SanityCheckStake( } for i, expectedThreshold := range expectedThresholds { threshold := thresholds[i] - if !threshold.Equal(&expectedThreshold) { + if !threshold.Equal(&expectedThreshold) { // nolint: gosec return fmt.Errorf("incorrect threshold in position %d for claim %s for account %s (expected: %s got: %s)", i, claim, @@ -347,7 +347,7 @@ type sanityCheckRuntimeLookup struct { allRuntimes []*Runtime } -func newSanityCheckRuntimeLookup(runtimes []*Runtime, suspendedRuntimes []*Runtime) (RuntimeLookup, error) { +func newSanityCheckRuntimeLookup(runtimes, suspendedRuntimes []*Runtime) (RuntimeLookup, error) { rtsMap := make(map[common.Namespace]*Runtime) sRtsMap := make(map[common.Namespace]*Runtime) allRts := []*Runtime{} diff --git a/go/registry/gen_vectors/main.go b/go/registry/gen_vectors/main.go index 25b22877c65..274ea8b4e5c 100644 --- a/go/registry/gen_vectors/main.go +++ b/go/registry/gen_vectors/main.go @@ -26,10 +26,10 @@ func main() { // Generate different gas fees. for _, fee := range []*transaction.Fee{ - &transaction.Fee{}, - &transaction.Fee{Amount: *quantity.NewFromUint64(100000000), Gas: 1000}, - &transaction.Fee{Amount: *quantity.NewFromUint64(0), Gas: 1000}, - &transaction.Fee{Amount: *quantity.NewFromUint64(4242), Gas: 1000}, + {}, + {Amount: *quantity.NewFromUint64(100000000), Gas: 1000}, + {Amount: *quantity.NewFromUint64(0), Gas: 1000}, + {Amount: *quantity.NewFromUint64(4242), Gas: 1000}, } { // Generate different nonces. for _, nonce := range []uint64{0, 1, 10, 42, 1000, 1_000_000, 10_000_000, math.MaxUint64} { diff --git a/go/registry/tests/tester.go b/go/registry/tests/tester.go index ba45b409dc6..d3d19e4597e 100644 --- a/go/registry/tests/tester.go +++ b/go/registry/tests/tester.go @@ -151,7 +151,7 @@ func testRegistryEntityNodes( // nolint: gocyclo }) // We rely on the runtime tests running before this registering a runtime. - nodeRuntimes := []*node.Runtime{&node.Runtime{ID: runtimeID}} + nodeRuntimes := []*node.Runtime{{ID: runtimeID}} // Node tests, because there needs to be entities. var numNodes int @@ -165,7 +165,7 @@ func testRegistryEntityNodes( // nolint: gocyclo nodes = append(nodes, entityNodes) numNodes += len(entityNodes) } - nodeRuntimesEW := []*node.Runtime{&node.Runtime{ID: runtimeEWID}} + nodeRuntimesEW := []*node.Runtime{{ID: runtimeEWID}} whitelistedNodes, err := entities[1].NewTestNodes(1, 1, []byte("whitelistedNodes"), nodeRuntimesEW, epoch+2, consensus) require.NoError(t, err, "NewTestNodes whitelisted") nonWhitelistedNodes, err := entities[0].NewTestNodes(1, 1, []byte("nonWhitelistedNodes"), nodeRuntimesEW, epoch+2, consensus) @@ -223,7 +223,8 @@ func testRegistryEntityNodes( // nolint: gocyclo ctx, &api.ConsensusAddressQuery{ Address: []byte(tmcrypto.PublicKeyToTendermint(&tn.Node.Consensus.ID).Address()), - Height: consensusAPI.HeightLatest}, + Height: consensusAPI.HeightLatest, + }, ) require.NoError(err, "GetNodeByConsensusAddress") require.EqualValues(tn.Node, nodeByConsensus, "retrieved node by Consensus Address") @@ -814,7 +815,7 @@ func randomIdentity(rng *drbg.Drbg) *identity.Identity { // NewTestNodes returns the specified number of TestNodes, generated // deterministically using the entity's public key as the seed. -func (ent *TestEntity) NewTestNodes(nCompute int, nStorage int, idNonce []byte, runtimes []*node.Runtime, expiration epochtime.EpochTime, consensus consensusAPI.Backend) ([]*TestNode, error) { // nolint: gocyclo +func (ent *TestEntity) NewTestNodes(nCompute, nStorage int, idNonce []byte, runtimes []*node.Runtime, expiration epochtime.EpochTime, consensus consensusAPI.Backend) ([]*TestNode, error) { // nolint: gocyclo if nCompute <= 0 || nStorage <= 0 || nCompute > 254 || nStorage > 254 { return nil, errors.New("registry/tests: test node count out of bounds") } @@ -868,7 +869,7 @@ func (ent *TestEntity) NewTestNodes(nCompute int, nStorage int, idNonce []byte, // Generate dummy TLS certificate. nod.Node.TLS.PubKey = nodeIdentity.GetTLSSigner().Public() nod.Node.TLS.Addresses = []node.TLSAddress{ - node.TLSAddress{ + { PubKey: nod.Node.TLS.PubKey, Address: addr, }, @@ -992,7 +993,7 @@ func (ent *TestEntity) NewTestNodes(nCompute int, nStorage int, idNonce []byte, descr: "register node with invalid runtimes", } invNode8 := *nod.Node - invNode8.Runtimes = []*node.Runtime{&node.Runtime{ID: publicKeyToNamespace(ent.Signer.Public(), false)}} + invNode8.Runtimes = []*node.Runtime{{ID: publicKeyToNamespace(ent.Signer.Public(), false)}} invalid8.signed, err = node.MultiSignNode(nodeSigners, api.RegisterNodeSignatureContext, &invNode8) if err != nil { return nil, err @@ -1005,7 +1006,7 @@ func (ent *TestEntity) NewTestNodes(nCompute int, nStorage int, idNonce []byte, } invNode9 := *nod.Node invNode9.Consensus.Addresses = []node.ConsensusAddress{ - node.ConsensusAddress{ + { // ID: invalid Address: addr, }, @@ -1161,7 +1162,7 @@ func (ent *TestEntity) NewTestNodes(nCompute int, nStorage int, idNonce []byte, } testRuntimeSigner := memorySigner.NewTestSigner("invalid-registration-runtime-seed") newRuntimes := []*node.Runtime{ - &node.Runtime{ID: publicKeyToNamespace(testRuntimeSigner.Public(), false)}, + {ID: publicKeyToNamespace(testRuntimeSigner.Public(), false)}, } newNode := &node.Node{ DescriptorVersion: node.LatestNodeDescriptorVersion, diff --git a/go/roothash/api/commitment/pool_test.go b/go/roothash/api/commitment/pool_test.go index fdfff52a14d..da0fcb1528d 100644 --- a/go/roothash/api/commitment/pool_test.go +++ b/go/roothash/api/commitment/pool_test.go @@ -128,7 +128,7 @@ func TestPoolSingleCommitment(t *testing.T) { committee := &scheduler.Committee{ Kind: scheduler.KindComputeExecutor, Members: []*scheduler.CommitteeNode{ - &scheduler.CommitteeNode{ + { Role: scheduler.Worker, PublicKey: sk.Public(), }, @@ -244,7 +244,7 @@ func TestPoolSingleCommitmentTEE(t *testing.T) { committee := &scheduler.Committee{ Kind: scheduler.KindComputeExecutor, Members: []*scheduler.CommitteeNode{ - &scheduler.CommitteeNode{ + { Role: scheduler.Worker, PublicKey: sk.Public(), }, @@ -472,7 +472,7 @@ func TestPoolSerialization(t *testing.T) { committee := &scheduler.Committee{ Kind: scheduler.KindComputeExecutor, Members: []*scheduler.CommitteeNode{ - &scheduler.CommitteeNode{ + { Role: scheduler.Worker, PublicKey: sk.Public(), }, @@ -529,11 +529,11 @@ func TestMultiPoolSerialization(t *testing.T) { // Create a multi-pool. pool := MultiPool{ Committees: map[hash.Hash]*Pool{ - com1ID: &Pool{ + com1ID: { Runtime: rt, Committee: committee1, }, - com2ID: &Pool{ + com2ID: { Runtime: rt, Committee: committee2, }, @@ -606,7 +606,7 @@ func TestPoolMergeCommitment(t *testing.T) { // Create a executor commitment multi-pool. executorPool := MultiPool{ Committees: map[hash.Hash]*Pool{ - executorCommitteeID: &Pool{ + executorCommitteeID: { Runtime: rt, Committee: executorCommittee, }, @@ -686,7 +686,7 @@ func TestPoolMergeCommitment(t *testing.T) { // Create a executor commitment multi-pool. executorPool := MultiPool{ Committees: map[hash.Hash]*Pool{ - executorCommitteeID: &Pool{ + executorCommitteeID: { Runtime: rt, Committee: executorCommittee, }, @@ -767,11 +767,11 @@ func TestMultiPool(t *testing.T) { // Create a multi-pool. pool := MultiPool{ Committees: map[hash.Hash]*Pool{ - com1ID: &Pool{ + com1ID: { Runtime: rt, Committee: committee1, }, - com2ID: &Pool{ + com2ID: { Runtime: rt, Committee: committee2, }, @@ -852,11 +852,11 @@ func TestMultiPool(t *testing.T) { // Create a multi-pool. pool := MultiPool{ Committees: map[hash.Hash]*Pool{ - com1ID: &Pool{ + com1ID: { Runtime: rt, Committee: committee1, }, - com2ID: &Pool{ + com2ID: { Runtime: rt, Committee: committee2, }, @@ -1137,15 +1137,15 @@ func generateMockCommittee(t *testing.T) ( committee = &scheduler.Committee{ Kind: scheduler.KindComputeExecutor, Members: []*scheduler.CommitteeNode{ - &scheduler.CommitteeNode{ + { Role: scheduler.Worker, PublicKey: sk1.Public(), }, - &scheduler.CommitteeNode{ + { Role: scheduler.Worker, PublicKey: sk2.Public(), }, - &scheduler.CommitteeNode{ + { Role: scheduler.BackupWorker, PublicKey: sk3.Public(), }, diff --git a/go/roothash/tests/tester.go b/go/roothash/tests/tester.go index 0d58a93d538..03665dcf545 100644 --- a/go/roothash/tests/tester.go +++ b/go/roothash/tests/tester.go @@ -287,9 +287,9 @@ func (s *runtimeState) testSuccessfulRound(t *testing.T, backend api.Backend, co child.Header.Namespace, child.Header.Round+1, []storageAPI.ApplyOp{ - storageAPI.ApplyOp{SrcRound: child.Header.Round + 1, SrcRoot: emptyRoot, DstRoot: ioRootHash, WriteLog: ioWriteLog}, + {SrcRound: child.Header.Round + 1, SrcRoot: emptyRoot, DstRoot: ioRootHash, WriteLog: ioWriteLog}, // NOTE: Twice to get a receipt over both roots which we set to the same value. - storageAPI.ApplyOp{SrcRound: child.Header.Round, SrcRoot: emptyRoot, DstRoot: ioRootHash, WriteLog: ioWriteLog}, + {SrcRound: child.Header.Round, SrcRoot: emptyRoot, DstRoot: ioRootHash, WriteLog: ioWriteLog}, }, ) diff --git a/go/runtime/client/tests/tester.go b/go/runtime/client/tests/tester.go index 9b7e8e39108..77aca63ae59 100644 --- a/go/runtime/client/tests/tester.go +++ b/go/runtime/client/tests/tester.go @@ -158,7 +158,7 @@ func testQuery( RoundMin: 0, RoundMax: 4, Conditions: []api.QueryCondition{ - api.QueryCondition{Key: []byte("txn_foo"), Values: [][]byte{[]byte("txn_bar")}}, + {Key: []byte("txn_foo"), Values: [][]byte{[]byte("txn_bar")}}, }, } results, err := c.QueryTxs(ctx, &api.QueryTxsRequest{RuntimeID: runtimeID, Query: query}) @@ -178,5 +178,4 @@ func testQuery( genBlk2, err := c.GetGenesisBlock(ctx, runtimeID) require.NoError(t, err, "GetGenesisBlock2") require.EqualValues(t, genBlk, genBlk2, "GetGenesisBlock should match previous GetGenesisBlock") - } diff --git a/go/runtime/host/mock/mock.go b/go/runtime/host/mock/mock.go index 6aeb8e8ab51..2ca94a136d9 100644 --- a/go/runtime/host/mock/mock.go +++ b/go/runtime/host/mock/mock.go @@ -105,7 +105,6 @@ func (r *runtime) Start() error { Started: &host.StartedEvent{}, }) return nil - } // Implements host.Runtime. diff --git a/go/runtime/host/protocol/connection.go b/go/runtime/host/protocol/connection.go index dcf168ab386..0010587484c 100644 --- a/go/runtime/host/protocol/connection.go +++ b/go/runtime/host/protocol/connection.go @@ -380,7 +380,6 @@ func (c *connection) handleMessage(ctx context.Context, message *Message) { } // Import runtime-provided span. - var span = opentracing.SpanFromContext(ctx) if len(message.SpanContext) != 0 { sc, err := tracing.SpanContextFromBinary(message.SpanContext) if err != nil { @@ -388,7 +387,7 @@ func (c *connection) handleMessage(ctx context.Context, message *Message) { "err", err, ) } else { - span = opentracing.StartSpan("RHP", opentracingExt.RPCServerOption(sc)) + span := opentracing.StartSpan("RHP", opentracingExt.RPCServerOption(sc)) defer span.Finish() ctx = opentracing.ContextWithSpan(ctx, span) diff --git a/go/runtime/host/sandbox/process/naked.go b/go/runtime/host/sandbox/process/naked.go index 61f1ef75811..ea85c1cd849 100644 --- a/go/runtime/host/sandbox/process/naked.go +++ b/go/runtime/host/sandbox/process/naked.go @@ -91,10 +91,10 @@ func NewNaked(cfg Config) (Process, error) { // Write any bound data to respective files. for path, reader := range cfg.BindData { - if err := os.MkdirAll(filepath.Dir(path), 0700); err != nil { + if err := os.MkdirAll(filepath.Dir(path), 0o700); err != nil { return nil, fmt.Errorf("failed to create directory for bound data: %w", err) } - file, err := os.OpenFile(path, os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0600) + file, err := os.OpenFile(path, os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0o600) if err != nil { return nil, fmt.Errorf("failed to write bound data: %w", err) } diff --git a/go/runtime/host/sandbox/process/seccomp_linux.go b/go/runtime/host/sandbox/process/seccomp_linux.go index 6cc26137cb1..ac10914d55a 100644 --- a/go/runtime/host/sandbox/process/seccomp_linux.go +++ b/go/runtime/host/sandbox/process/seccomp_linux.go @@ -6,7 +6,7 @@ import ( "os" "syscall" - "github.com/seccomp/libseccomp-golang" + seccomp "github.com/seccomp/libseccomp-golang" ) // A list of syscalls allowed with any arguments. @@ -348,7 +348,7 @@ func generateSeccompPolicy(out *os.File) error { } // Disallow clone in a new namespace, otherwise allow. err = filter.AddRuleConditional(cloneID, seccomp.ActAllow, []seccomp.ScmpCondition{ - seccomp.ScmpCondition{Argument: 0, Op: seccomp.CompareMaskedEqual, Operand1: 0, Operand2: 0x7c020000}, + {Argument: 0, Op: seccomp.CompareMaskedEqual, Operand1: 0, Operand2: 0x7c020000}, }) if err != nil { return err diff --git a/go/runtime/host/sandbox/sandbox.go b/go/runtime/host/sandbox/sandbox.go index f5f872f49b0..4e2e2cf5537 100644 --- a/go/runtime/host/sandbox/sandbox.go +++ b/go/runtime/host/sandbox/sandbox.go @@ -37,7 +37,7 @@ const ( type Config struct { // GetSandboxConfig is a function that generates the sandbox configuration. In case it is not // specified a default function is used. - GetSandboxConfig func(cfg host.Config, socketPath string, runtimeDir string) (process.Config, error) + GetSandboxConfig func(cfg host.Config, socketPath, runtimeDir string) (process.Config, error) // HostInitializer is a function that additionally initializes the runtime host. In case it is // not specified a default function is used. @@ -497,7 +497,7 @@ func (r *sandboxedRuntime) manager() { func New(cfg Config) (host.Provisioner, error) { // Use a default GetSandboxConfig if none was provided. if cfg.GetSandboxConfig == nil { - cfg.GetSandboxConfig = func(hostCfg host.Config, socketPath string, runtimeDir string) (process.Config, error) { + cfg.GetSandboxConfig = func(hostCfg host.Config, socketPath, runtimeDir string) (process.Config, error) { return process.Config{ Path: hostCfg.Path, Env: map[string]string{ diff --git a/go/runtime/host/sgx/sgx.go b/go/runtime/host/sgx/sgx.go index 91c5e643e00..c3ac068e9f8 100644 --- a/go/runtime/host/sgx/sgx.go +++ b/go/runtime/host/sgx/sgx.go @@ -142,7 +142,7 @@ func (s *sgxProvisioner) loadEnclaveBinaries(rtCfg host.Config) ([]byte, []byte, return sgxs, sig, nil } -func (s *sgxProvisioner) getSandboxConfig(rtCfg host.Config, socketPath string, runtimeDir string) (process.Config, error) { +func (s *sgxProvisioner) getSandboxConfig(rtCfg host.Config, socketPath, runtimeDir string) (process.Config, error) { // To try to avoid bad things from happening if the signature/enclave // binaries change out from under us, and because the enclave binary // needs to be loaded into memory anyway, this always injects diff --git a/go/runtime/tagindexer/backend_test.go b/go/runtime/tagindexer/backend_test.go index 8e7397b8fb4..920eada8942 100644 --- a/go/runtime/tagindexer/backend_test.go +++ b/go/runtime/tagindexer/backend_test.go @@ -35,8 +35,8 @@ func testOperations(t *testing.T, backend Backend) { blockHash1, // Transactions. []*transaction.Transaction{ - &transaction.Transaction{Input: tx1, Output: tx1}, - &transaction.Transaction{Input: tx2, Output: tx2}, + {Input: tx1, Output: tx1}, + {Input: tx2, Output: tx2}, }, // Tags. transaction.Tags{ @@ -96,7 +96,7 @@ func testOperations(t *testing.T, backend Backend) { blockHash2, // Transactions. []*transaction.Transaction{ - &transaction.Transaction{Input: tx3, Output: tx3}, + {Input: tx3, Output: tx3}, }, // Tags. transaction.Tags{ @@ -124,7 +124,7 @@ func testOperations(t *testing.T, backend Backend) { RoundMin: 40, RoundMax: 50, Conditions: []api.QueryCondition{ - api.QueryCondition{Key: []byte("hello"), Values: [][]byte{[]byte("world")}}, + {Key: []byte("hello"), Values: [][]byte{[]byte("world")}}, }, } results, err := backend.QueryTxns(ctx, query) @@ -137,7 +137,7 @@ func testOperations(t *testing.T, backend Backend) { query = api.Query{ Conditions: []api.QueryCondition{ - api.QueryCondition{Key: []byte("hello"), Values: [][]byte{[]byte("worlx"), []byte("world")}}, + {Key: []byte("hello"), Values: [][]byte{[]byte("worlx"), []byte("world")}}, }, } results, err = backend.QueryTxns(ctx, query) diff --git a/go/runtime/transaction/transaction.go b/go/runtime/transaction/transaction.go index 2201bd6e44e..5618d2b9a05 100644 --- a/go/runtime/transaction/transaction.go +++ b/go/runtime/transaction/transaction.go @@ -89,7 +89,7 @@ var ( // // These are the artifacts that are stored CBOR-serialized in the Merkle tree. type inputArtifacts struct { - _ struct{} `cbor:",toarray"` //nolint + _ struct{} `cbor:",toarray"` // nolint // Input is the transaction input. Input []byte @@ -105,7 +105,7 @@ type inputArtifacts struct { // // These are the artifacts that are stored CBOR-serialized in the Merkle tree. type outputArtifacts struct { - _ struct{} `cbor:",toarray"` //nolint + _ struct{} `cbor:",toarray"` // nolint // Output is the transaction output (if available). Output []byte @@ -358,7 +358,7 @@ func (t *Tree) GetTransactionMultiple(ctx context.Context, txHashes []hash.Hash) // don't need to do multiple round trips. var keys [][]byte for _, txHash := range txHashes { - keys = append(keys, txnKeyFmt.Encode(&txHash)) + keys = append(keys, txnKeyFmt.Encode(&txHash)) // nolint: gosec } if err := t.tree.PrefetchPrefixes(ctx, keys, prefetchArtifactCount); err != nil { return nil, fmt.Errorf("transaction: prefetch failed: %w", err) diff --git a/go/runtime/transaction/transaction_test.go b/go/runtime/transaction/transaction_test.go index e7b2712d701..f287e639445 100644 --- a/go/runtime/transaction/transaction_test.go +++ b/go/runtime/transaction/transaction_test.go @@ -78,7 +78,7 @@ func TestTransaction(t *testing.T) { for _, checkTx := range testTxns { require.Contains(t, txnsByHash, checkTx.Hash(), "transaction should exist") - require.True(t, txnsByHash[checkTx.Hash()].Equal(&checkTx), "transaction should have the correct artifacts") + require.True(t, txnsByHash[checkTx.Hash()].Equal(&checkTx), "transaction should have the correct artifacts") // nolint: gosec } // Fetching a single transaction should work. @@ -150,6 +150,6 @@ func TestTransaction(t *testing.T) { for _, checkTx := range testTxns { require.Contains(t, txnsByHash, checkTx.Hash(), "transaction should exist") - require.True(t, txnsByHash[checkTx.Hash()].Equal(&checkTx), "transaction should have the correct artifacts") + require.True(t, txnsByHash[checkTx.Hash()].Equal(&checkTx), "transaction should have the correct artifacts") // nolint: gosec } } diff --git a/go/staking/api/commission.go b/go/staking/api/commission.go index ab837b3c9bc..36dd7964b8c 100644 --- a/go/staking/api/commission.go +++ b/go/staking/api/commission.go @@ -107,7 +107,6 @@ type CommissionSchedule struct { func (cs CommissionSchedule) PrettyPrint(prefix string, w io.Writer) { if cs.Rates == nil { fmt.Fprintf(w, "%sRates: (none)\n", prefix) - } else { fmt.Fprintf(w, "%sRates:\n", prefix) for _, rate := range cs.Rates { @@ -117,7 +116,6 @@ func (cs CommissionSchedule) PrettyPrint(prefix string, w io.Writer) { if cs.Bounds == nil { fmt.Fprintf(w, "%sRate Bounds: (none)\n", prefix) - } else { fmt.Fprintf(w, "%sRate Bounds:\n", prefix) for _, rateBound := range cs.Bounds { diff --git a/go/staking/gen_vectors/main.go b/go/staking/gen_vectors/main.go index 6195047cf6a..5d7cec1f6e8 100644 --- a/go/staking/gen_vectors/main.go +++ b/go/staking/gen_vectors/main.go @@ -26,10 +26,10 @@ func main() { // Generate different gas fees. for _, fee := range []*transaction.Fee{ - &transaction.Fee{}, - &transaction.Fee{Amount: *quantity.NewFromUint64(100000000), Gas: 1000}, - &transaction.Fee{Amount: *quantity.NewFromUint64(0), Gas: 1000}, - &transaction.Fee{Amount: *quantity.NewFromUint64(4242), Gas: 1000}, + {}, + {Amount: *quantity.NewFromUint64(100000000), Gas: 1000}, + {Amount: *quantity.NewFromUint64(0), Gas: 1000}, + {Amount: *quantity.NewFromUint64(4242), Gas: 1000}, } { // Generate different nonces. for _, nonce := range []uint64{0, 1, 10, 42, 1000, 1_000_000, 10_000_000, math.MaxUint64} { diff --git a/go/staking/tests/debug/debug_stake.go b/go/staking/tests/debug/debug_stake.go index dcb4b80a893..0a33a48a1d4 100644 --- a/go/staking/tests/debug/debug_stake.go +++ b/go/staking/tests/debug/debug_stake.go @@ -30,7 +30,7 @@ var ( api.KindRuntimeKeyManager: QtyFromInt(7), }, Slashing: map[api.SlashReason]api.Slash{ - api.SlashDoubleSigning: api.Slash{ + api.SlashDoubleSigning: { Amount: QtyFromInt(math.MaxInt64), // Slash everything. FreezeInterval: 1, }, @@ -42,7 +42,7 @@ var ( }, TotalSupply: DebugStateTotalSupply, Ledger: map[api.Address]*api.Account{ - DebugStateSrcAddress: &api.Account{ + DebugStateSrcAddress: { General: api.GeneralAccount{ Balance: DebugStateSrcGeneralBalance, }, @@ -55,8 +55,8 @@ var ( }, }, Delegations: map[api.Address]map[api.Address]*api.Delegation{ - DebugStateSrcAddress: map[api.Address]*api.Delegation{ - DebugStateSrcAddress: &api.Delegation{ + DebugStateSrcAddress: { + DebugStateSrcAddress: { Shares: DebugStateSrcEscrowActiveShares, }, }, diff --git a/go/storage/client/client.go b/go/storage/client/client.go index 56f5dd15a54..2f72d52b852 100644 --- a/go/storage/client/client.go +++ b/go/storage/client/client.go @@ -31,10 +31,8 @@ var ( _ api.ClientBackend = (*storageClientBackend)(nil) ) -var ( - // ErrStorageNotAvailable is the error returned when no storage node is available. - ErrStorageNotAvailable = errors.New("storage/client: storage not available") -) +// ErrStorageNotAvailable is the error returned when no storage node is available. +var ErrStorageNotAvailable = errors.New("storage/client: storage not available") const ( retryInterval = 1 * time.Second diff --git a/go/storage/fuzz/fuzz.go b/go/storage/fuzz/fuzz.go index c56dfebd16d..3d0f4485e01 100644 --- a/go/storage/fuzz/fuzz.go +++ b/go/storage/fuzz/fuzz.go @@ -16,7 +16,7 @@ import ( ) const ( - dataDir string = "/tmp/oasis-node-fuzz-storage" + dataDir string = "/tmp/oasis-node-fuzz-storage" identityDir string = dataDir + "/identity" ) diff --git a/go/storage/mkvs/cache.go b/go/storage/mkvs/cache.go index 7f9fe621df5..9e8bc159c9f 100644 --- a/go/storage/mkvs/cache.go +++ b/go/storage/mkvs/cache.go @@ -121,7 +121,7 @@ func (c *cache) newInternalNodePtr(n *node.InternalNode) *node.Pointer { } } -func (c *cache) newInternalNode(label node.Key, labelBitLength node.Depth, leafNode *node.Pointer, left *node.Pointer, right *node.Pointer) *node.Pointer { +func (c *cache) newInternalNode(label node.Key, labelBitLength node.Depth, leafNode, left, right *node.Pointer) *node.Pointer { return c.newInternalNodePtr(&node.InternalNode{ Label: label, LabelBitLength: labelBitLength, @@ -155,7 +155,7 @@ func (c *cache) markPosition() { c.lruLeafPos = c.lruLeaf.Front() } -func (c *cache) tryCommitNode(ptr *node.Pointer, lockedPtr *node.Pointer) error { +func (c *cache) tryCommitNode(ptr, lockedPtr *node.Pointer) error { if !ptr.IsClean() { panic("mkvs: commitNode called on dirty node") } @@ -232,7 +232,7 @@ func (c *cache) rollbackNode(ptr *node.Pointer) { ptr.LRU = nil } -func (c *cache) tryRemoveNode(ptr *node.Pointer, lockedPtr *node.Pointer) error { +func (c *cache) tryRemoveNode(ptr, lockedPtr *node.Pointer) error { if lockedPtr != nil && lockedPtr == ptr { return errRemoveLocked } diff --git a/go/storage/mkvs/checkpoint/file.go b/go/storage/mkvs/checkpoint/file.go index 06c01b431af..a91a295bf0c 100644 --- a/go/storage/mkvs/checkpoint/file.go +++ b/go/storage/mkvs/checkpoint/file.go @@ -98,7 +98,7 @@ func (fc *fileCreator) CreateCheckpoint(ctx context.Context, root node.Root, chu Chunks: chunks, } - if err = ioutil.WriteFile(filepath.Join(checkpointDir, checkpointMetadataFile), cbor.Marshal(meta), 0600); err != nil { + if err = ioutil.WriteFile(filepath.Join(checkpointDir, checkpointMetadataFile), cbor.Marshal(meta), 0o600); err != nil { return nil, fmt.Errorf("checkpoint: failed to create checkpoint metadata: %w", err) } return meta, nil diff --git a/go/storage/mkvs/db/api/api.go b/go/storage/mkvs/db/api/api.go index 189630f9adc..31ff5851564 100644 --- a/go/storage/mkvs/db/api/api.go +++ b/go/storage/mkvs/db/api/api.go @@ -77,7 +77,7 @@ type NodeDB interface { GetNode(root node.Root, ptr *node.Pointer) (node.Node, error) // GetWriteLog retrieves a write log between two storage instances from the database. - GetWriteLog(ctx context.Context, startRoot node.Root, endRoot node.Root) (writelog.Iterator, error) + GetWriteLog(ctx context.Context, startRoot, endRoot node.Root) (writelog.Iterator, error) // GetLatestVersion returns the most recent version in the node database. GetLatestVersion(ctx context.Context) (uint64, error) @@ -189,7 +189,7 @@ func (d *nopNodeDB) GetNode(root node.Root, ptr *node.Pointer) (node.Node, error return nil, ErrNodeNotFound } -func (d *nopNodeDB) GetWriteLog(ctx context.Context, startRoot node.Root, endRoot node.Root) (writelog.Iterator, error) { +func (d *nopNodeDB) GetWriteLog(ctx context.Context, startRoot, endRoot node.Root) (writelog.Iterator, error) { return nil, ErrWriteLogNotFound } diff --git a/go/storage/mkvs/db/badger/badger.go b/go/storage/mkvs/db/badger/badger.go index e4ae7eecf7e..f7f77f50961 100644 --- a/go/storage/mkvs/db/badger/badger.go +++ b/go/storage/mkvs/db/badger/badger.go @@ -204,7 +204,7 @@ func (d *badgerNodeDB) GetNode(root node.Root, ptr *node.Pointer) (node.Node, er return n, nil } -func (d *badgerNodeDB) GetWriteLog(ctx context.Context, startRoot node.Root, endRoot node.Root) (writelog.Iterator, error) { +func (d *badgerNodeDB) GetWriteLog(ctx context.Context, startRoot, endRoot node.Root) (writelog.Iterator, error) { if d.discardWriteLogs { return nil, api.ErrWriteLogNotFound } @@ -246,7 +246,7 @@ func (d *badgerNodeDB) GetWriteLog(ctx context.Context, startRoot node.Root, end } // NOTE: We could use a proper deque, but as long as we keep the number of hops and // forks low, this should not be a problem. - queue := []*wlItem{&wlItem{depth: 0, endRootHash: endRoot.Hash}} + queue := []*wlItem{{depth: 0, endRootHash: endRoot.Hash}} for len(queue) > 0 { if ctx.Err() != nil { return nil, ctx.Err() diff --git a/go/storage/mkvs/debug.go b/go/storage/mkvs/debug.go index 7096d299484..eb448a1bccd 100644 --- a/go/storage/mkvs/debug.go +++ b/go/storage/mkvs/debug.go @@ -14,7 +14,7 @@ func (t *tree) DumpLocal(ctx context.Context, w io.Writer, maxDepth node.Depth) t.doDumpLocal(ctx, w, t.cache.pendingRoot, 0, maxDepth) } -func (t *tree) doDumpLocal(ctx context.Context, w io.Writer, ptr *node.Pointer, depth node.Depth, maxDepth node.Depth) { +func (t *tree) doDumpLocal(ctx context.Context, w io.Writer, ptr *node.Pointer, depth, maxDepth node.Depth) { prefix := strings.Repeat(" ", int(depth)*2) if ptr == nil { fmt.Fprint(w, prefix+"") diff --git a/go/storage/mkvs/fuzz/node.go b/go/storage/mkvs/fuzz/node.go index 5cf4356cdb4..7ee7c31de75 100644 --- a/go/storage/mkvs/fuzz/node.go +++ b/go/storage/mkvs/fuzz/node.go @@ -5,14 +5,14 @@ package fuzz import "github.com/oasisprotocol/oasis-core/go/storage/mkvs/node" func FuzzNode(data []byte) int { - n, err := node.UnmarshalBinary(data) - if err != nil { - return 0 - } + n, err := node.UnmarshalBinary(data) + if err != nil { + return 0 + } - _, err = n.CompactMarshalBinary() - if err != nil { - panic(err) - } - return 1 + _, err = n.CompactMarshalBinary() + if err != nil { + panic(err) + } + return 1 } diff --git a/go/storage/mkvs/fuzz/proof.go b/go/storage/mkvs/fuzz/proof.go index f3c542de41f..03b90608211 100644 --- a/go/storage/mkvs/fuzz/proof.go +++ b/go/storage/mkvs/fuzz/proof.go @@ -3,40 +3,40 @@ package fuzz import ( - "context" + "context" - commonFuzz "github.com/oasisprotocol/oasis-core/go/common/fuzz" - "github.com/oasisprotocol/oasis-core/go/storage/mkvs/syncer" + commonFuzz "github.com/oasisprotocol/oasis-core/go/common/fuzz" + "github.com/oasisprotocol/oasis-core/go/storage/mkvs/syncer" ) var proofFuzzer *commonFuzz.InterfaceFuzzer // ProofFuzz is a wrapper for fuzzing syncer proof decoding. -type ProofFuzz struct {} +type ProofFuzz struct{} func (p *ProofFuzz) DecodeProof(ctx context.Context, entries [][]byte) { - var proof syncer.Proof - proof.Entries = entries + var proof syncer.Proof + proof.Entries = entries - var verifier syncer.ProofVerifier - _, _ = verifier.VerifyProof(ctx, proof.UntrustedRoot, &proof) + var verifier syncer.ProofVerifier + _, _ = verifier.VerifyProof(ctx, proof.UntrustedRoot, &proof) } func NewProofFuzz() (*ProofFuzz, *commonFuzz.InterfaceFuzzer) { - pf := &ProofFuzz{} - fz := commonFuzz.NewInterfaceFuzzer(pf) - return pf, fz + pf := &ProofFuzz{} + fz := commonFuzz.NewInterfaceFuzzer(pf) + return pf, fz } func init() { - _, proofFuzzer = NewProofFuzz() + _, proofFuzzer = NewProofFuzz() } func FuzzProof(data []byte) int { - _, result := proofFuzzer.DispatchBlob(data) - if !result { - return -1 - } + _, result := proofFuzzer.DispatchBlob(data) + if !result { + return -1 + } - return 0 + return 0 } diff --git a/go/storage/mkvs/fuzz/tree.go b/go/storage/mkvs/fuzz/tree.go index afe68f6abf4..05fae0b616d 100644 --- a/go/storage/mkvs/fuzz/tree.go +++ b/go/storage/mkvs/fuzz/tree.go @@ -8,8 +8,8 @@ import ( "encoding/hex" "encoding/json" "fmt" - "sort" "io/ioutil" + "sort" "github.com/oasisprotocol/oasis-core/go/common" commonFuzz "github.com/oasisprotocol/oasis-core/go/common/fuzz" @@ -36,8 +36,8 @@ var treeFuzzer *commonFuzz.InterfaceFuzzer // fuzzer to generate histories where multiple mutation operations are performed against the remote // tree. type TreeFuzz struct { - inner mkvs.Tree - remote mkvs.Tree + inner mkvs.Tree + remote mkvs.Tree reference map[string][]byte history mkvsTests.TestVector @@ -55,7 +55,7 @@ func (t *TreeFuzz) commitRemote(ctx context.Context) { t.remote = mkvs.NewWithRoot(t.inner, nil, mkvsNode.Root{Hash: rootHash}, mkvs.Capacity(0, 0)) } -func (t *TreeFuzz) insert(ctx context.Context, tree mkvs.Tree, key []byte, value []byte) { +func (t *TreeFuzz) insert(ctx context.Context, tree mkvs.Tree, key, value []byte) { if tree == nil { return } @@ -65,7 +65,7 @@ func (t *TreeFuzz) insert(ctx context.Context, tree mkvs.Tree, key []byte, value } } -func (t *TreeFuzz) Insert(ctx context.Context, key []byte, value []byte) int { +func (t *TreeFuzz) Insert(ctx context.Context, key, value []byte) int { if len(key) == 0 { // Ignore zero-length keys as they are invalid. return -1 diff --git a/go/storage/mkvs/insert.go b/go/storage/mkvs/insert.go index de03b238967..9e80ea2e208 100644 --- a/go/storage/mkvs/insert.go +++ b/go/storage/mkvs/insert.go @@ -9,7 +9,7 @@ import ( ) // Implements Tree. -func (t *tree) Insert(ctx context.Context, key []byte, value []byte) error { +func (t *tree) Insert(ctx context.Context, key, value []byte) error { if value == nil { value = []byte{} } diff --git a/go/storage/mkvs/interop/cmd/root.go b/go/storage/mkvs/interop/cmd/root.go index 008ff95c9fa..0faa54eee37 100644 --- a/go/storage/mkvs/interop/cmd/root.go +++ b/go/storage/mkvs/interop/cmd/root.go @@ -7,13 +7,11 @@ import ( "github.com/oasisprotocol/oasis-core/go/common/version" ) -var ( - rootCmd = &cobra.Command{ - Use: "mkvs-test-helpers", - Short: "MKVS interoperability test helpers", - Version: version.SoftwareVersion, - } -) +var rootCmd = &cobra.Command{ + Use: "mkvs-test-helpers", + Short: "MKVS interoperability test helpers", + Version: version.SoftwareVersion, +} // RootCommand returns the root (top level) cobra.Command. func RootCommand() *cobra.Command { diff --git a/go/storage/mkvs/iterator.go b/go/storage/mkvs/iterator.go index 5ea7ea19e3a..fb80f48a974 100644 --- a/go/storage/mkvs/iterator.go +++ b/go/storage/mkvs/iterator.go @@ -242,7 +242,7 @@ func (it *treeIterator) Next() { it.value = nil } -func (it *treeIterator) doNext(ptr *node.Pointer, bitDepth node.Depth, path node.Key, key node.Key, state visitState) error { // nolint: gocyclo +func (it *treeIterator) doNext(ptr *node.Pointer, bitDepth node.Depth, path, key node.Key, state visitState) error { // nolint: gocyclo // Dereference the node, possibly making a remote request. nd, err := it.tree.cache.derefNodePtr(it.ctx, ptr, it.tree.newFetcherSyncIterate(key, it.prefetch)) if err != nil { diff --git a/go/storage/mkvs/mkvs.go b/go/storage/mkvs/mkvs.go index 07b31aa455b..021330fe6d4 100644 --- a/go/storage/mkvs/mkvs.go +++ b/go/storage/mkvs/mkvs.go @@ -36,7 +36,7 @@ type KeyValueTree interface { ImmutableKeyValueTree // Insert inserts a key/value pair into the tree. - Insert(ctx context.Context, key []byte, value []byte) error + Insert(ctx context.Context, key, value []byte) error // RemoveExisting removes a key from the tree and returns the previous value. RemoveExisting(ctx context.Context, key []byte) ([]byte, error) diff --git a/go/storage/mkvs/node/key.go b/go/storage/mkvs/node/key.go index d991d7d4011..b87a24ede7a 100644 --- a/go/storage/mkvs/node/key.go +++ b/go/storage/mkvs/node/key.go @@ -88,7 +88,7 @@ func (k Key) GetBit(bit Depth) bool { // // This function is immutable and returns a new instance of Key func (k Key) SetBit(bit Depth, val bool) Key { - var kb = make(Key, len(k)) + kb := make(Key, len(k)) copy(kb[:], k[:]) mask := byte(1 << (7 - (bit % 8))) if val { @@ -104,7 +104,7 @@ func (k Key) SetBit(bit Depth, val bool) Key { // keyLen is the length of the key in bits and splitPoint is the index of the // first suffix bit. // This function is immutable and returns two new instances of Key. -func (k Key) Split(splitPoint Depth, keyLen Depth) (prefix Key, suffix Key) { +func (k Key) Split(splitPoint, keyLen Depth) (prefix, suffix Key) { if splitPoint > keyLen { panic(fmt.Sprintf("mkvs: splitPoint %+v greater than keyLen %+v", splitPoint, keyLen)) } diff --git a/go/storage/mkvs/node/node_test.go b/go/storage/mkvs/node/node_test.go index cf874e557da..c6e69b3e4f4 100644 --- a/go/storage/mkvs/node/node_test.go +++ b/go/storage/mkvs/node/node_test.go @@ -33,7 +33,7 @@ func TestSerializationLeafNode(t *testing.T) { } func TestSerializationInternalNode(t *testing.T) { - var leafNode = &LeafNode{ + leafNode := &LeafNode{ Key: []byte("a golden key"), Value: []byte("value"), } @@ -41,8 +41,8 @@ func TestSerializationInternalNode(t *testing.T) { leftHash := hash.NewFromBytes([]byte("everyone move to the left")) rightHash := hash.NewFromBytes([]byte("everyone move to the right")) - var label = Key("abc") - var labelBitLength = Depth(24) + label := Key("abc") + labelBitLength := Depth(24) intNode := &InternalNode{ Version: 0xDEADBEEF, diff --git a/go/storage/mkvs/overlay.go b/go/storage/mkvs/overlay.go index 00dc26a8dda..efad1ca62dc 100644 --- a/go/storage/mkvs/overlay.go +++ b/go/storage/mkvs/overlay.go @@ -33,7 +33,7 @@ func NewOverlay(inner Tree) OverlayTree { } // Implements KeyValueTree. -func (o *treeOverlay) Insert(ctx context.Context, key []byte, value []byte) error { +func (o *treeOverlay) Insert(ctx context.Context, key, value []byte) error { err := o.overlay.Insert(ctx, key, value) if err != nil { return err diff --git a/go/storage/mkvs/tree.go b/go/storage/mkvs/tree.go index 8ca84dc7dd2..c1ebb4ae396 100644 --- a/go/storage/mkvs/tree.go +++ b/go/storage/mkvs/tree.go @@ -41,7 +41,7 @@ type Option func(t *tree) // // If a capacity of 0 is specified, the cache will have an unlimited size // (not recommended, as this will cause unbounded memory growth). -func Capacity(nodeCapacity uint64, valueCapacityBytes uint64) Option { +func Capacity(nodeCapacity, valueCapacityBytes uint64) Option { return func(t *tree) { t.cache.nodeCapacity = nodeCapacity t.cache.valueCapacity = valueCapacityBytes diff --git a/go/storage/mkvs/writelog/writelog.go b/go/storage/mkvs/writelog/writelog.go index d763285feec..948b42a2a2d 100644 --- a/go/storage/mkvs/writelog/writelog.go +++ b/go/storage/mkvs/writelog/writelog.go @@ -27,7 +27,7 @@ func (wl WriteLog) Equal(cmp WriteLog) bool { // LogEntry is a write log entry. type LogEntry struct { - _ struct{} `cbor:",toarray"` //nolint + _ struct{} `cbor:",toarray"` // nolint Key []byte Value []byte diff --git a/go/storage/tests/tester.go b/go/storage/tests/tester.go index a45aebc0dda..e7f2f749ef5 100644 --- a/go/storage/tests/tester.go +++ b/go/storage/tests/tester.go @@ -137,8 +137,8 @@ func testBasic(t *testing.T, localBackend api.LocalBackend, backend api.Backend, wl2 := prepareWriteLog(testValues[0:2]) expectedNewRoot2 := CalculateExpectedNewRoot(t, wl2, namespace, round) applyOps := []api.ApplyOp{ - api.ApplyOp{SrcRound: round, SrcRoot: rootHash, DstRoot: expectedNewRoot, WriteLog: wl}, - api.ApplyOp{SrcRound: round, SrcRoot: rootHash, DstRoot: expectedNewRoot2, WriteLog: wl2}, + {SrcRound: round, SrcRoot: rootHash, DstRoot: expectedNewRoot, WriteLog: wl}, + {SrcRound: round, SrcRoot: rootHash, DstRoot: expectedNewRoot2, WriteLog: wl2}, } // Apply a batch of operations against the MKVS. @@ -269,19 +269,19 @@ func testMerge(t *testing.T, backend api.Backend, namespace common.Namespace, ro writeLogs := []api.WriteLog{ // Base root. - api.WriteLog{ + { api.LogEntry{Key: []byte("foo"), Value: []byte("i am base")}, }, // First root. - api.WriteLog{ + { api.LogEntry{Key: []byte("first"), Value: []byte("i am first root")}, }, // Second root. - api.WriteLog{ + { api.LogEntry{Key: []byte("second"), Value: []byte("i am second root")}, }, // Third root. - api.WriteLog{ + { api.LogEntry{Key: []byte("third"), Value: []byte("i am third root")}, }, } diff --git a/go/upgrade/dummy.go b/go/upgrade/dummy.go index 5c892bf47ec..b9c1ab0bd1d 100644 --- a/go/upgrade/dummy.go +++ b/go/upgrade/dummy.go @@ -7,9 +7,7 @@ import ( "github.com/oasisprotocol/oasis-core/go/upgrade/api" ) -var ( - _ api.Backend = (*dummyUpgradeManager)(nil) -) +var _ api.Backend = (*dummyUpgradeManager)(nil) type dummyUpgradeManager struct{} diff --git a/go/upgrade/migrations/migrations.go b/go/upgrade/migrations/migrations.go index 4bd88bb5aad..dc93029f02f 100644 --- a/go/upgrade/migrations/migrations.go +++ b/go/upgrade/migrations/migrations.go @@ -11,11 +11,9 @@ const ( ModuleName = "upgrade-migrations" ) -var ( - registeredHandlers = map[string]Handler{ - DummyUpgradeName: &dummyMigrationHandler{}, - } -) +var registeredHandlers = map[string]Handler{ + DummyUpgradeName: &dummyMigrationHandler{}, +} // Handler is the interface used by migration handlers. type Handler interface { diff --git a/go/worker/common/committee/group.go b/go/worker/common/committee/group.go index af95982bef6..4a4d021089e 100644 --- a/go/worker/common/committee/group.go +++ b/go/worker/common/committee/group.go @@ -106,7 +106,7 @@ func NewMockEpochSnapshot() *EpochSnapshot { return &EpochSnapshot{ executorCommitteeID: executorCommitteeID, executorCommittees: map[hash.Hash]*CommitteeInfo{ - executorCommitteeID: &CommitteeInfo{}, + executorCommitteeID: {}, }, } } diff --git a/go/worker/common/config.go b/go/worker/common/config.go index cb25daa56b1..7ff5d3295f3 100644 --- a/go/worker/common/config.go +++ b/go/worker/common/config.go @@ -238,7 +238,7 @@ func NewConfig(ias ias.Endpoint) (*Config, error) { func init() { Flags.Uint16(CfgClientPort, 9100, "Port to use for incoming gRPC client connections") Flags.StringSlice(cfgClientAddresses, []string{}, "Address/port(s) to use for client connections when registering this node (if not set, all non-loopback local interfaces will be used)") - Flags.StringSlice(CfgSentryAddresses, []string{}, fmt.Sprintf("Address(es) of sentry node(s) to connect to of the form [PubKey@]ip:port (where PubKey@ part represents base64 encoded node TLS public key)")) + Flags.StringSlice(CfgSentryAddresses, []string{}, "Address(es) of sentry node(s) to connect to of the form [PubKey@]ip:port (where PubKey@ part represents base64 encoded node TLS public key)") Flags.String(CfgRuntimeProvisioner, RuntimeProvisionerSandboxed, "Runtime provisioner to use") Flags.String(CfgRuntimeSGXLoader, "", "(for SGX runtimes) Path to SGXS runtime loader binary") diff --git a/go/worker/common/p2p/crypto.go b/go/worker/common/p2p/crypto.go index 9cce861db56..e899f8c647a 100644 --- a/go/worker/common/p2p/crypto.go +++ b/go/worker/common/p2p/crypto.go @@ -103,7 +103,7 @@ func (k *libp2pPublicKey) Type() libp2pCryptoPb.KeyType { return libp2pCryptoPb.KeyType_Ed25519 } -func (k *libp2pPublicKey) Verify(data []byte, sig []byte) (bool, error) { +func (k *libp2pPublicKey) Verify(data, sig []byte) (bool, error) { return k.inner.Verify(libp2pContext, data, sig), nil } diff --git a/go/worker/common/p2p/dispatch.go b/go/worker/common/p2p/dispatch.go index 1506f3b5e84..c8ad2fd4899 100644 --- a/go/worker/common/p2p/dispatch.go +++ b/go/worker/common/p2p/dispatch.go @@ -6,8 +6,8 @@ import ( "sync/atomic" "github.com/cenkalti/backoff/v4" - "github.com/libp2p/go-libp2p-core" - "github.com/libp2p/go-libp2p-pubsub" + core "github.com/libp2p/go-libp2p-core" + pubsub "github.com/libp2p/go-libp2p-pubsub" "github.com/oasisprotocol/oasis-core/go/common" "github.com/oasisprotocol/oasis-core/go/common/cbor" @@ -190,7 +190,6 @@ func (h *topicHandler) retryWorker(m *queuedMsg) { } return derr }, bctx) - if err != nil { h.logger.Error("failed to re-dispatch message, not retrying", "err", err, diff --git a/go/worker/common/p2p/p2p.go b/go/worker/common/p2p/p2p.go index 7a7e366e6ac..0eba4d71147 100644 --- a/go/worker/common/p2p/p2p.go +++ b/go/worker/common/p2p/p2p.go @@ -9,12 +9,12 @@ import ( "time" "github.com/libp2p/go-libp2p" - "github.com/libp2p/go-libp2p-core" + core "github.com/libp2p/go-libp2p-core" "github.com/libp2p/go-libp2p-core/network" "github.com/libp2p/go-libp2p-core/transport" - "github.com/libp2p/go-libp2p-pubsub" + pubsub "github.com/libp2p/go-libp2p-pubsub" "github.com/multiformats/go-multiaddr" - "github.com/multiformats/go-multiaddr-net" + manet "github.com/multiformats/go-multiaddr-net" "github.com/spf13/viper" "github.com/oasisprotocol/oasis-core/go/common" @@ -96,6 +96,7 @@ func (p *P2P) Publish(ctx context.Context, runtimeID common.Namespace, msg *Mess p.logger.Error("attempted to publish message for unknown runtime ID", "runtime_id", runtimeID, ) + return } if err := h.topic.Publish(h.ctx, rawMsg); err != nil { diff --git a/go/worker/common/p2p/peermgmt.go b/go/worker/common/p2p/peermgmt.go index f7f5d978f26..3b6e5e1084c 100644 --- a/go/worker/common/p2p/peermgmt.go +++ b/go/worker/common/p2p/peermgmt.go @@ -6,9 +6,9 @@ import ( "sync" "github.com/cenkalti/backoff/v4" - "github.com/libp2p/go-libp2p-core" + core "github.com/libp2p/go-libp2p-core" "github.com/libp2p/go-libp2p-core/peer" - "github.com/multiformats/go-multiaddr-net" + manet "github.com/multiformats/go-multiaddr-net" "github.com/oasisprotocol/oasis-core/go/common/crypto/hash" "github.com/oasisprotocol/oasis-core/go/common/crypto/signature" diff --git a/go/worker/compute/executor/committee/node.go b/go/worker/compute/executor/committee/node.go index 288759c1321..4aafa4e5283 100644 --- a/go/worker/compute/executor/committee/node.go +++ b/go/worker/compute/executor/committee/node.go @@ -624,14 +624,14 @@ func (n *Node) proposeBatchLocked(batch *protocol.ComputedBatch) { // NOTE: Order is important for verifying the receipt. applyOps := []storage.ApplyOp{ // I/O root. - storage.ApplyOp{ + { SrcRound: lastHeader.Round + 1, SrcRoot: state.batch.ioRoot.Hash, DstRoot: batch.Header.IORoot, WriteLog: batch.IOWriteLog, }, // State root. - storage.ApplyOp{ + { SrcRound: lastHeader.Round, SrcRoot: lastHeader.StateRoot, DstRoot: batch.Header.StateRoot, diff --git a/go/worker/compute/merge/committee/node.go b/go/worker/compute/merge/committee/node.go index 1bfb1e810fa..206215db314 100644 --- a/go/worker/compute/merge/committee/node.go +++ b/go/worker/compute/merge/committee/node.go @@ -489,12 +489,12 @@ func (n *Node) startMergeLocked(commitments []commitment.ExecutorCommitment, res // NOTE: Order is important for verifying the receipt. mergeOps := []storage.MergeOp{ // I/O root. - storage.MergeOp{ + { Base: emptyRoot, Others: ioRoots, }, // State root. - storage.MergeOp{ + { Base: prevBlk.Header.StateRoot, Others: stateRoots, }, diff --git a/go/worker/sentry/grpc/worker.go b/go/worker/sentry/grpc/worker.go index 500fbe1aae2..6ba218dc6e7 100644 --- a/go/worker/sentry/grpc/worker.go +++ b/go/worker/sentry/grpc/worker.go @@ -44,7 +44,6 @@ func (g *Worker) authFunction() auth.AuthenticationFunction { return func(ctx context.Context, fullMethodName string, req interface{}) error { - serviceName := cmnGrpc.ServiceNameFromMethod(fullMethodName) if serviceName == "" { g.logger.Error("error getting service name from method", diff --git a/go/worker/storage/committee/node.go b/go/worker/storage/committee/node.go index 3474f1ba9dd..cf5b2a3554b 100644 --- a/go/worker/storage/committee/node.go +++ b/go/worker/storage/committee/node.go @@ -471,7 +471,7 @@ func (n *Node) ForceFinalize(ctx context.Context, round uint64) error { }) } -func (n *Node) fetchDiff(round uint64, prevRoot *mkvsNode.Root, thisRoot *mkvsNode.Root, fetchMask outstandingMask) { +func (n *Node) fetchDiff(round uint64, prevRoot, thisRoot *mkvsNode.Root, fetchMask outstandingMask) { result := &fetchedDiff{ fetchMask: fetchMask, fetched: false, diff --git a/go/worker/storage/worker.go b/go/worker/storage/worker.go index 46c9bfc01a3..47c55fd3490 100644 --- a/go/worker/storage/worker.go +++ b/go/worker/storage/worker.go @@ -76,7 +76,6 @@ func New( genesis genesis.Provider, commonStore *persistent.CommonStore, ) (*Worker, error) { - s := &Worker{ enabled: viper.GetBool(CfgWorkerEnabled), commonWorker: commonWorker,