diff --git a/.golangci.yml b/.golangci.yml index c4fe2303ca..674122ebac 100644 --- a/.golangci.yml +++ b/.golangci.yml @@ -1,65 +1,144 @@ -# Copyright (C) 2023, Ava Labs, Inc. All rights reserved. -# See the file LICENSE for licensing terms. - # https://golangci-lint.run/usage/configuration/ run: timeout: 10m - # skip auto-generated files. - skip-files: - - ".*\\.pb\\.go$" - - ".*mock.*" + + # Enables skipping of directories: + # - vendor$, third_party$, testdata$, examples$, Godeps$, builtin$ + # Default: true + skip-dirs-use-default: false + + # If set we pass it to "go list -mod={option}". From "go help modules": + # If invoked with -mod=readonly, the go command is disallowed from the implicit + # automatic updating of go.mod described above. Instead, it fails when any changes + # to go.mod are needed. This setting is most useful to check that go.mod does + # not need updates, such as in a continuous integration and testing system. + # If invoked with -mod=vendor, the go command assumes that the vendor + # directory holds the correct copies of dependencies and ignores + # the dependency descriptions in go.mod. + # + # Allowed values: readonly|vendor|mod + # By default, it isn't set. + modules-download-mode: readonly + +output: + # Make issues output unique by line. + # Default: true + uniq-by-line: false issues: - # Maximum count of issues with the same text. Set to 0 to disable. Default is 3. + # Maximum issues count per one linter. + # Set to 0 to disable. + # Default: 50 + max-issues-per-linter: 0 + + # Maximum count of issues with the same text. + # Set to 0 to disable. + # Default: 3 max-same-issues: 0 linters: - # please, do not use `enable-all`: it's deprecated and will be removed soon. - # inverted configuration with `enable-all` and `disable` is not scalable during updates of golangci-lint disable-all: true enable: - asciicheck + - bodyclose - depguard + - dupword - errcheck - errorlint - exportloopref + - forbidigo + - gci - goconst - gocritic + # - goerr113 - gofmt - gofumpt - - goimports - - revive + # - gomnd + - goprintffuncname - gosec - gosimple - govet + - importas - ineffassign + # - lll - misspell - nakedret + - noctx - nolintlint + - perfsprint - prealloc + - predeclared + - revive + - spancheck + - staticcheck - stylecheck + - tagalign + - testifylint + - typecheck - unconvert - unparam - unused - - unconvert + - usestdlibvars - whitespace - - staticcheck - - bodyclose - - structcheck - # - lll - # - gomnd - - goprintffuncname - - interfacer - - typecheck - # - goerr113 - - noctx linters-settings: + depguard: + rules: + packages: + deny: + - pkg: "io/ioutil" + desc: io/ioutil is deprecated. Use package io or os instead. + - pkg: "github.com/stretchr/testify/assert" + desc: github.com/stretchr/testify/require should be used instead. + - pkg: "github.com/golang/mock/gomock" + desc: go.uber.org/mock/gomock should be used instead. errorlint: # Check for plain type assertions and type switches. asserts: false # Check for plain error comparisons. comparison: false + forbidigo: + # Forbid the following identifiers (list of regexp). + forbid: + - 'require\.Error$(# ErrorIs should be used instead)?' + - 'require\.ErrorContains$(# ErrorIs should be used instead)?' + - 'require\.EqualValues$(# Equal should be used instead)?' + - 'require\.NotEqualValues$(# NotEqual should be used instead)?' + - '^(t|b|tb|f)\.(Fatal|Fatalf|Error|Errorf)$(# the require library should be used instead)?' + # Exclude godoc examples from forbidigo checks. + exclude_godoc_examples: false + gci: + sections: + - standard + - default + - blank + - dot + - prefix(github.com/ava-labs/hypersdk) + - alias + skip-generated: true + custom-order: true + gosec: + excludes: + - G107 # Url provided to HTTP request as taint input https://securego.io/docs/rules/g107 + importas: + # Do not allow unaliased imports of aliased packages. + no-unaliased: false + # Do not allow non-required aliases. + no-extra-aliases: false + # List of aliases + alias: + - pkg: github.com/ava-labs/avalanchego/utils/math + alias: safemath + - pkg: github.com/ava-labs/avalanchego/utils + alias: avautils + - pkg: github.com/ava-labs/avalanchego/trace + alias: avatrace + - pkg: github.com/ava-labs/avalanchego/api/metrics + alias: avametrics + - pkg: github.com/ava-labs/avalanchego/cache + alias: avacache + - pkg: github.com/ava-labs/avalanchego/x/sync + alias: avasync revive: rules: # https://github.com/mgechev/revive/blob/master/RULES_DESCRIPTIONS.md#bool-literal-in-expr @@ -71,6 +150,11 @@ linters-settings: # https://github.com/mgechev/revive/blob/master/RULES_DESCRIPTIONS.md#empty-lines - name: empty-lines disabled: false + # https://github.com/mgechev/revive/blob/master/RULES_DESCRIPTIONS.md#string-format + - name: string-format + disabled: false + arguments: + - ["fmt.Errorf[0]", "/.*%.*/", "no format directive, use errors.New instead"] # https://github.com/mgechev/revive/blob/master/RULES_DESCRIPTIONS.md#struct-tag - name: struct-tag disabled: false @@ -81,13 +165,13 @@ linters-settings: - name: unhandled-error disabled: false arguments: - - "fmt.Fprint" - - "fmt.Fprintf" - - "fmt.Print" - - "fmt.Printf" - - "fmt.Println" - - "rand.Read" - - "sb.WriteString" + - "fmt\\.Fprint" + - "fmt\\.Fprintf" + - "fmt\\.Print" + - "fmt\\.Printf" + - "fmt\\.Println" + - "math/rand\\.Read" + - "strings\\.Builder\\.WriteString" # https://github.com/mgechev/revive/blob/master/RULES_DESCRIPTIONS.md#unused-parameter - name: unused-parameter disabled: false @@ -97,19 +181,30 @@ linters-settings: # https://github.com/mgechev/revive/blob/master/RULES_DESCRIPTIONS.md#useless-break - name: useless-break disabled: false + spancheck: + # https://github.com/jjti/go-spancheck#checks + checks: + - end + # - record-error # check that `span.RecordError(err)` is called when an error is returned + # - set-status # check that `span.SetStatus(codes.Error, msg)` is called when an error is returned staticcheck: # https://staticcheck.io/docs/options#checks checks: - "all" - - "-SA6002" # argument should be pointer-like to avoid allocation, for sync.Pool - - "-SA1019" # deprecated packages e.g., golang.org/x/crypto/ripemd160 - # https://golangci-lint.run/usage/linters#gosec - gosec: - excludes: - - G107 # https://securego.io/docs/rules/g107.html - depguard: - list-type: blacklist - packages-with-error-message: - - io/ioutil: 'io/ioutil is deprecated. Use package io or os instead.' - - github.com/stretchr/testify/assert: 'github.com/stretchr/testify/require should be used instead.' - include-go-root: true + - "-SA6002" # Storing non-pointer values in sync.Pool allocates memory + - "-SA1019" # Using a deprecated function, variable, constant or field + tagalign: + align: true + sort: true + strict: true + testifylint: + # Enable all checkers (https://github.com/Antonboom/testifylint#checkers). + # Default: false + enable-all: true + # Disable checkers by name + # (in addition to default + # suite-thelper + # ). + disable: + - go-require + - float-compare diff --git a/builder/dependencies.go b/builder/dependencies.go index 0b0cddb423..f4590f0377 100644 --- a/builder/dependencies.go +++ b/builder/dependencies.go @@ -8,6 +8,7 @@ import ( "github.com/ava-labs/avalanchego/snow/engine/common" "github.com/ava-labs/avalanchego/utils/logging" + "github.com/ava-labs/hypersdk/chain" ) diff --git a/chain/auth_batch.go b/chain/auth_batch.go index 981517b273..ea2b060db1 100644 --- a/chain/auth_batch.go +++ b/chain/auth_batch.go @@ -7,6 +7,7 @@ import ( "context" "github.com/ava-labs/avalanchego/utils/logging" + "github.com/ava-labs/hypersdk/workers" ) diff --git a/chain/base.go b/chain/base.go index f7862bf7d3..b400a51995 100644 --- a/chain/base.go +++ b/chain/base.go @@ -7,6 +7,7 @@ import ( "fmt" "github.com/ava-labs/avalanchego/ids" + "github.com/ava-labs/hypersdk/codec" "github.com/ava-labs/hypersdk/consts" ) diff --git a/chain/block.go b/chain/block.go index 2ec2371492..7be9c7ec6f 100644 --- a/chain/block.go +++ b/chain/block.go @@ -18,7 +18,7 @@ import ( "github.com/ava-labs/avalanchego/vms/platformvm/warp" "github.com/ava-labs/avalanchego/x/merkledb" "go.opentelemetry.io/otel/attribute" - oteltrace "go.opentelemetry.io/otel/trace" + "go.opentelemetry.io/otel/trace" "go.uber.org/zap" "github.com/ava-labs/hypersdk/codec" @@ -161,10 +161,10 @@ func (b *StatelessBlock) populateTxs(ctx context.Context) error { defer span.End() // Setup signature verification job - _, sigVerifySpan := b.vm.Tracer().Start(ctx, "StatelessBlock.verifySignatures") + _, sigVerifySpan := b.vm.Tracer().Start(ctx, "StatelessBlock.verifySignatures") //nolint:spancheck job, err := b.vm.AuthVerifiers().NewJob(len(b.Txs)) if err != nil { - return err + return err //nolint:spancheck } b.sigJob = job batchVerifier := NewAuthBatch(b.vm, b.sigJob, b.authCounts) @@ -312,7 +312,7 @@ func (b *StatelessBlock) VerifyWithContext(ctx context.Context, bctx *block.Cont stateReady := b.vm.StateReady() ctx, span := b.vm.Tracer().Start( ctx, "StatelessBlock.VerifyWithContext", - oteltrace.WithAttributes( + trace.WithAttributes( attribute.Int("txs", len(b.Txs)), attribute.Int64("height", int64(b.Hght)), attribute.Bool("stateReady", stateReady), @@ -339,7 +339,7 @@ func (b *StatelessBlock) Verify(ctx context.Context) error { stateReady := b.vm.StateReady() ctx, span := b.vm.Tracer().Start( ctx, "StatelessBlock.Verify", - oteltrace.WithAttributes( + trace.WithAttributes( attribute.Int("txs", len(b.Txs)), attribute.Int64("height", int64(b.Hght)), attribute.Bool("stateReady", stateReady), @@ -526,7 +526,7 @@ func (b *StatelessBlock) innerVerify(ctx context.Context, vctx VerifyContext) er ) return ErrMissingBlockContext } - _, warpVerifySpan := b.vm.Tracer().Start(ctx, "StatelessBlock.verifyWarpMessages") + _, warpVerifySpan := b.vm.Tracer().Start(ctx, "StatelessBlock.verifyWarpMessages") //nolint:spancheck b.vdrState = b.vm.ValidatorState() go func() { defer warpVerifySpan.End() @@ -572,7 +572,7 @@ func (b *StatelessBlock) innerVerify(ctx context.Context, vctx VerifyContext) er feeKey := FeeKey(b.vm.StateManager().FeeKey()) feeRaw, err := parentView.GetValue(ctx, feeKey) if err != nil { - return err + return err //nolint:spancheck } parentFeeManager := fees.NewManager(feeRaw) feeManager, err := parentFeeManager.ComputeNext(parentTimestamp, b.Tmstmp, r) @@ -804,7 +804,7 @@ func (b *StatelessBlock) Processed() bool { // it will result in undefined behavior. func (b *StatelessBlock) View(ctx context.Context, verify bool) (state.View, error) { ctx, span := b.vm.Tracer().Start(ctx, "StatelessBlock.View", - oteltrace.WithAttributes( + trace.WithAttributes( attribute.Bool("processed", b.Processed()), attribute.Bool("verify", verify), ), diff --git a/chain/builder.go b/chain/builder.go index 0a01bd16a3..4681a2905a 100644 --- a/chain/builder.go +++ b/chain/builder.go @@ -13,7 +13,7 @@ import ( "github.com/ava-labs/avalanchego/database" "github.com/ava-labs/avalanchego/ids" - smblock "github.com/ava-labs/avalanchego/snow/engine/snowman/block" + "github.com/ava-labs/avalanchego/snow/engine/snowman/block" "github.com/ava-labs/avalanchego/utils/logging" "github.com/ava-labs/avalanchego/utils/set" "go.opentelemetry.io/otel/attribute" @@ -64,7 +64,7 @@ func BuildBlock( ctx context.Context, vm VM, parent *StatelessBlock, - blockContext *smblock.Context, + blockContext *block.Context, ) (*StatelessBlock, error) { ctx, span := vm.Tracer().Start(ctx, "chain.BuildBlock") defer span.End() @@ -148,7 +148,7 @@ func BuildBlock( b.vm.RecordClearedMempool() break } - ctx, executeSpan := vm.Tracer().Start(ctx, "chain.BuildBlock.Execute") + ctx, executeSpan := vm.Tracer().Start(ctx, "chain.BuildBlock.Execute") //nolint:spancheck // Perform a batch repeat check dup, err := parent.IsRepeat(ctx, oldestAllowed, txs, set.NewBits(), false) @@ -434,7 +434,7 @@ func BuildBlock( // Perform basic validity checks to make sure the block is well-formatted if len(b.Txs) == 0 { if nextTime < parent.Tmstmp+r.GetMinEmptyBlockGap() { - return nil, fmt.Errorf("%w: allowed in %d ms", ErrNoTxs, parent.Tmstmp+r.GetMinEmptyBlockGap()-nextTime) + return nil, fmt.Errorf("%w: allowed in %d ms", ErrNoTxs, parent.Tmstmp+r.GetMinEmptyBlockGap()-nextTime) //nolint:spancheck } vm.RecordEmptyBlockBuilt() } diff --git a/chain/consts.go b/chain/consts.go index c06b25f725..e018cc52a7 100644 --- a/chain/consts.go +++ b/chain/consts.go @@ -7,6 +7,7 @@ import ( "time" "github.com/ava-labs/avalanchego/utils/units" + "github.com/ava-labs/hypersdk/keys" ) diff --git a/chain/result.go b/chain/result.go index 9006d3474e..40b1604796 100644 --- a/chain/result.go +++ b/chain/result.go @@ -5,6 +5,7 @@ package chain import ( "github.com/ava-labs/avalanchego/vms/platformvm/warp" + "github.com/ava-labs/hypersdk/codec" "github.com/ava-labs/hypersdk/consts" "github.com/ava-labs/hypersdk/fees" diff --git a/cli/chain.go b/cli/chain.go index bb08f7ba53..c105932902 100644 --- a/cli/chain.go +++ b/cli/chain.go @@ -10,10 +10,12 @@ import ( "strings" "time" - runner "github.com/ava-labs/avalanche-network-runner/client" + "github.com/ava-labs/avalanche-network-runner/client" "github.com/ava-labs/avalanchego/ids" "github.com/ava-labs/avalanchego/utils/logging" "github.com/ava-labs/avalanchego/utils/units" + "gopkg.in/yaml.v2" + "github.com/ava-labs/hypersdk/chain" "github.com/ava-labs/hypersdk/consts" "github.com/ava-labs/hypersdk/fees" @@ -21,7 +23,6 @@ import ( "github.com/ava-labs/hypersdk/rpc" "github.com/ava-labs/hypersdk/utils" "github.com/ava-labs/hypersdk/window" - "gopkg.in/yaml.v2" ) func (h *Handler) ImportChain() error { @@ -55,7 +56,7 @@ func (h *Handler) ImportANR() error { } // Load new items from ANR - anrCli, err := runner.New(runner.Config{ + anrCli, err := client.New(client.Config{ Endpoint: "0.0.0.0:12352", DialTimeout: 10 * time.Second, }, logging.NoLog{}) diff --git a/cli/cli.go b/cli/cli.go index ef23d139ca..0e0bde97ee 100644 --- a/cli/cli.go +++ b/cli/cli.go @@ -5,6 +5,7 @@ package cli import ( "github.com/ava-labs/avalanchego/database" + "github.com/ava-labs/hypersdk/pebble" ) diff --git a/cli/key.go b/cli/key.go index 28b2d38316..f70fddb6bd 100644 --- a/cli/key.go +++ b/cli/key.go @@ -7,6 +7,7 @@ import ( "context" "github.com/ava-labs/avalanchego/ids" + "github.com/ava-labs/hypersdk/codec" "github.com/ava-labs/hypersdk/rpc" "github.com/ava-labs/hypersdk/utils" diff --git a/cli/prometheus.go b/cli/prometheus.go index aa33c7dfc3..4e56efddf3 100644 --- a/cli/prometheus.go +++ b/cli/prometheus.go @@ -13,9 +13,10 @@ import ( "time" "github.com/ava-labs/avalanchego/ids" - "github.com/ava-labs/hypersdk/utils" "github.com/pkg/browser" "gopkg.in/yaml.v2" + + "github.com/ava-labs/hypersdk/utils" ) const ( @@ -102,7 +103,7 @@ func (h *Handler) GeneratePrometheus(baseURI string, openBrowser bool, startProm // We must manually encode the params because prometheus skips any panels // that are not numerically sorted and `url.params` only sorts // lexicographically. - dashboard := fmt.Sprintf("%s/graph", baseURI) + dashboard := baseURI + "/graph" for i, panel := range getPanels(chainID) { appendChar := "&" if i == 0 { @@ -126,7 +127,7 @@ func (h *Handler) GeneratePrometheus(baseURI string, openBrowser bool, startProm // // Attempting to exit from the terminal will gracefully // stop this process. - cmd := exec.CommandContext(context.Background(), "/tmp/prometheus", fmt.Sprintf("--config.file=%s", prometheusFile), fmt.Sprintf("--storage.tsdb.path=%s", prometheusData)) + cmd := exec.CommandContext(context.Background(), "/tmp/prometheus", "--config.file="+prometheusFile, "--storage.tsdb.path="+prometheusData) cmd.Stdout = os.Stdout cmd.Stderr = os.Stderr errChan := make(chan error) diff --git a/cli/prompt.go b/cli/prompt.go index a00ed69b9a..127da4c73e 100644 --- a/cli/prompt.go +++ b/cli/prompt.go @@ -10,10 +10,11 @@ import ( "github.com/ava-labs/avalanchego/ids" "github.com/ava-labs/avalanchego/utils/set" + "github.com/manifoldco/promptui" + "github.com/ava-labs/hypersdk/codec" "github.com/ava-labs/hypersdk/fees" "github.com/ava-labs/hypersdk/utils" - "github.com/manifoldco/promptui" ) func (h *Handler) PromptAddress(label string) (codec.Address, error) { @@ -230,7 +231,7 @@ func (*Handler) PromptContinue() (bool, error) { func (*Handler) PromptBool(label string) (bool, error) { promptText := promptui.Prompt{ - Label: fmt.Sprintf("%s (y/n)", label), + Label: label + " (y/n)", Validate: func(input string) error { if len(input) == 0 { return ErrInputEmpty diff --git a/cli/spam.go b/cli/spam.go index 4dc7ab0037..90afdbba82 100644 --- a/cli/spam.go +++ b/cli/spam.go @@ -16,9 +16,9 @@ import ( "syscall" "time" + "github.com/ava-labs/avalanchego/ids" "golang.org/x/sync/errgroup" - "github.com/ava-labs/avalanchego/ids" "github.com/ava-labs/hypersdk/chain" "github.com/ava-labs/hypersdk/codec" "github.com/ava-labs/hypersdk/consts" diff --git a/cli/storage.go b/cli/storage.go index 7fa2fbc700..49878ff52d 100644 --- a/cli/storage.go +++ b/cli/storage.go @@ -9,6 +9,7 @@ import ( "github.com/ava-labs/avalanchego/database" "github.com/ava-labs/avalanchego/ids" + "github.com/ava-labs/hypersdk/codec" "github.com/ava-labs/hypersdk/consts" "github.com/ava-labs/hypersdk/utils" diff --git a/codec/address_test.go b/codec/address_test.go index f372fbb630..b00aa96355 100644 --- a/codec/address_test.go +++ b/codec/address_test.go @@ -8,6 +8,7 @@ import ( "testing" "github.com/ava-labs/avalanchego/ids" + "github.com/btcsuite/btcd/btcutil/bech32" "github.com/stretchr/testify/require" ) @@ -39,5 +40,9 @@ func TestInvalidAddressChecksum(t *testing.T) { addr := "blah1859dz2uwazfgahey3j53ef2kqrans0c8cv4l78tda3rjkfw0txns8u2e7k" _, err := ParseAddressBech32(hrp, addr) - require.ErrorContains(err, "invalid checksum") + require.ErrorIs(err, bech32.ErrInvalidChecksum{ + Expected: "8u2e8k", + ExpectedM: "8u2e8kjq64z5", + Actual: "8u2e7k", + }) } diff --git a/codec/optional_packer.go b/codec/optional_packer.go index 41eaea3f40..d90736d3bf 100644 --- a/codec/optional_packer.go +++ b/codec/optional_packer.go @@ -6,6 +6,7 @@ package codec import ( "github.com/ava-labs/avalanchego/ids" "github.com/ava-labs/avalanchego/utils/set" + "github.com/ava-labs/hypersdk/consts" ) diff --git a/codec/optional_packer_test.go b/codec/optional_packer_test.go index 86cefbfb7c..cfe2b9b7f9 100644 --- a/codec/optional_packer_test.go +++ b/codec/optional_packer_test.go @@ -9,8 +9,9 @@ import ( "testing" "github.com/ava-labs/avalanchego/ids" - "github.com/ava-labs/hypersdk/consts" "github.com/stretchr/testify/require" + + "github.com/ava-labs/hypersdk/consts" ) // toReader returns an OptionalPacker that is a reader of [o]. @@ -26,13 +27,15 @@ func (o *OptionalPacker) toReader() *OptionalPacker { } func TestOptionalPackerID(t *testing.T) { - require := require.New(t) opw := NewOptionalWriter(10_000) id := ids.GenerateTestID() t.Run("Pack", func(t *testing.T) { + require := require.New(t) + // Pack empty opw.PackID(ids.Empty) require.Empty(opw.ip.Bytes(), "PackID packed an empty ID.") + // Pack ID opw.PackID(id) bytes, err := ids.ToID(opw.ip.Bytes()) @@ -40,10 +43,11 @@ func TestOptionalPackerID(t *testing.T) { require.Equal(id, bytes, "PackID did not set bytes correctly.") }) t.Run("Unpack", func(t *testing.T) { - // Setup optional reader + require := require.New(t) + opr := opw.toReader() var unpackedID ids.ID - // // Unpack + // Unpack opr.UnpackID(&unpackedID) require.Equal(ids.Empty, unpackedID, "ID unpacked correctly") opr.UnpackID(&unpackedID) @@ -54,13 +58,15 @@ func TestOptionalPackerID(t *testing.T) { } func TestOptionalPackerUint64(t *testing.T) { - require := require.New(t) opw := NewOptionalWriter(10_000) val := uint64(900) t.Run("Pack", func(t *testing.T) { + require := require.New(t) + // Pack empty opw.PackUint64(0) require.Empty(opw.ip.Bytes(), "PackUint64 packed a zero uint.") + // Pack ID opw.PackUint64(val) require.Equal( @@ -70,9 +76,9 @@ func TestOptionalPackerUint64(t *testing.T) { ) }) t.Run("Unpack", func(t *testing.T) { - // Setup optional reader + require := require.New(t) + opr := opw.toReader() - // Unpack require.Equal(uint64(0), opr.UnpackUint64(), "Uint64 unpacked correctly") require.Equal(val, opr.UnpackUint64(), "Uint64 unpacked correctly") opr.Done() @@ -81,23 +87,25 @@ func TestOptionalPackerUint64(t *testing.T) { } func TestOptionalPackerAddress(t *testing.T) { - require := require.New(t) opw := NewOptionalWriter(10_000) id := ids.GenerateTestID() addr := CreateAddress(1, id) t.Run("Pack", func(t *testing.T) { + require := require.New(t) + // Pack empty opw.PackAddress(EmptyAddress) require.Empty(opw.ip.Bytes(), "PackAddress packed an empty Address.") + // Pack address opw.PackAddress(addr) require.True(bytes.Equal(addr[:], opw.ip.Bytes()), "PackPublickey did not set bytes correctly.") }) t.Run("Unpack", func(t *testing.T) { - // Setup optional reader + require := require.New(t) + opr := opw.toReader() var unpackedAddr Address - // Unpack opr.UnpackAddress(&unpackedAddr) require.True(bytes.Equal(EmptyAddress[:], unpackedAddr[:]), "AddressBytes unpacked correctly") opr.UnpackAddress(&unpackedAddr) @@ -108,13 +116,15 @@ func TestOptionalPackerAddress(t *testing.T) { } func TestOptionalPackerInvalidSet(t *testing.T) { - require := require.New(t) opw := NewOptionalWriter(10_000) val := uint64(900) t.Run("Pack", func(t *testing.T) { + require := require.New(t) + // Pack empty opw.PackUint64(0) require.Empty(opw.ip.Bytes(), "PackUint64 packed a zero uint.") + // Pack ID opw.PackUint64(val) require.Equal( @@ -124,6 +134,8 @@ func TestOptionalPackerInvalidSet(t *testing.T) { ) }) t.Run("Unpack", func(t *testing.T) { + require := require.New(t) + // Setup optional reader (expects no entries) opr := opw.toReader() opr.Done() diff --git a/codec/packer_test.go b/codec/packer_test.go index 06daeeb739..001e902604 100644 --- a/codec/packer_test.go +++ b/codec/packer_test.go @@ -7,9 +7,11 @@ import ( "testing" "github.com/ava-labs/avalanchego/ids" + "github.com/ava-labs/avalanchego/utils/wrappers" + "github.com/stretchr/testify/require" + "github.com/ava-labs/hypersdk/consts" "github.com/ava-labs/hypersdk/window" - "github.com/stretchr/testify/require" ) var ( @@ -28,74 +30,75 @@ func TestNewWriter(t *testing.T) { require.Equal(bytes, wr.Bytes(), "Bytes not packed correctly.") // Pack past limit wr.PackFixedBytes(bytes) - require.Equal(2, len(wr.Bytes()), "Bytes overpacked.") - require.Error(wr.Err(), "Error not set.") + require.Len(wr.Bytes(), 2, "Bytes overpacked.") + require.ErrorIs(wr.Err(), wrappers.ErrInsufficientLength) } func TestPackerID(t *testing.T) { - require := require.New(t) wp := NewWriter(consts.IDLen, consts.IDLen) - // Pack id := ids.GenerateTestID() t.Run("Pack", func(t *testing.T) { + require := require.New(t) + wp.PackID(id) - // Check packed returnedID, err := ids.ToID(wp.Bytes()) require.NoError(err, "Error retrieving ID.") require.Equal(id, returnedID, "ids.ID not packed correctly.") require.NoError(wp.Err(), "Error packing ID.") }) t.Run("Unpack", func(t *testing.T) { - // Unpack + require := require.New(t) + rp := NewReader(wp.Bytes(), consts.IDLen) require.Equal(wp.Bytes(), rp.Bytes(), "Reader not initialized correctly.") unpackedID := ids.Empty rp.UnpackID(true, &unpackedID) require.Equal(id, unpackedID, "UnpackID unpacked incorrectly.") require.NoError(rp.Err(), "UnpackID set an error.") - // Unpack again + + // Unpacking again should error unpackedID = ids.Empty rp.UnpackID(true, &unpackedID) require.Equal(ids.Empty, unpackedID, "UnpackID unpacked incorrectly.") - require.Error(rp.Err(), "UnpackID did not set error.") + require.ErrorIs(rp.Err(), wrappers.ErrInsufficientLength) }) } func TestPackerWindow(t *testing.T) { - require := require.New(t) wp := NewWriter(window.WindowSliceSize, window.WindowSliceSize) var wind window.Window // Fill window copy(wind[:], TestWindow) - // Pack - t.Run("Unpack", func(t *testing.T) { + t.Run("Pack", func(t *testing.T) { + require := require.New(t) + wp.PackWindow(wind) - // Check packed require.Equal(TestWindow, wp.Bytes()[:len(TestWindow)], "Window not packed correctly.") - require.Equal(window.WindowSliceSize, len(wp.Bytes()), "Window not packed correctly.") + require.Len(wp.Bytes(), window.WindowSliceSize, "Window not packed correctly.") require.NoError(wp.Err(), "Error packing window.") }) t.Run("Unpack", func(t *testing.T) { - // Unpack + require := require.New(t) + rp := NewReader(wp.Bytes(), window.WindowSliceSize) require.Equal(wp.Bytes(), rp.Bytes(), "Reader not initialized correctly.") var unpackedWindow window.Window rp.UnpackWindow(&unpackedWindow) require.Equal(wind, unpackedWindow, "UnpackWindow unpacked incorrectly.") require.NoError(rp.Err(), "UnpackWindow set an error.") - // Unpack again + // Unpacking again should error rp.UnpackWindow(&unpackedWindow) - require.Error(rp.Err(), "UnpackWindow did not set error.") + require.ErrorIs(rp.Err(), wrappers.ErrInsufficientLength) }) } func TestPackerAddress(t *testing.T) { - require := require.New(t) wp := NewWriter(AddressLen, AddressLen) id := ids.GenerateTestID() addr := CreateAddress(1, id) t.Run("Pack", func(t *testing.T) { - // Pack + require := require.New(t) + wp.PackAddress(addr) b := wp.Bytes() require.NoError(wp.Err()) @@ -104,7 +107,8 @@ func TestPackerAddress(t *testing.T) { require.Equal(id[:], b[1:]) }) t.Run("Unpack", func(t *testing.T) { - // Unpack + require := require.New(t) + rp := NewReader(wp.Bytes(), AddressLen) require.Equal(wp.Bytes(), rp.Bytes()) var unpackedAddr Address @@ -129,6 +133,6 @@ func TestNewReader(t *testing.T) { require.True(rp.UnpackBool(), "Reader unpacked correctly.") require.NoError(rp.Err(), "Reader set error during unpack.") // Unpacked not packed with required - require.Equal(uint64(0), rp.UnpackUint64(true), "Reader unpacked correctly.") - require.Error(rp.Err(), "Reader error not set.") + require.Zero(rp.UnpackUint64(true), "Reader unpacked correctly.") + require.ErrorIs(rp.Err(), wrappers.ErrInsufficientLength) } diff --git a/codec/type_parser_test.go b/codec/type_parser_test.go index 763032b747..76f6b04ad7 100644 --- a/codec/type_parser_test.go +++ b/codec/type_parser_test.go @@ -7,8 +7,9 @@ import ( "errors" "testing" - "github.com/ava-labs/hypersdk/consts" "github.com/stretchr/testify/require" + + "github.com/ava-labs/hypersdk/consts" ) type Blah interface { @@ -48,17 +49,19 @@ func TestTypeParser(t *testing.T) { blah1 := &Blah1{} blah2 := &Blah2{} + errBlah1 := errors.New("blah1") + errBlah2 := errors.New("blah2") require.NoError( tp.Register( blah1.GetTypeID(), - func(p *Packer, a any) (Blah, error) { return nil, errors.New("blah1") }, + func(*Packer, any) (Blah, error) { return nil, errBlah1 }, true, ), ) require.NoError( tp.Register( blah2.GetTypeID(), - func(p *Packer, a any) (Blah, error) { return nil, errors.New("blah2") }, + func(*Packer, any) (Blah, error) { return nil, errBlah2 }, false, ), ) @@ -68,14 +71,14 @@ func TestTypeParser(t *testing.T) { require.True(b) res, err := f(nil, nil) require.Nil(res) - require.ErrorContains(err, "blah1") + require.ErrorIs(err, errBlah1) f, b, ok = tp.LookupIndex(blah2.GetTypeID()) require.True(ok) require.False(b) res, err = f(nil, nil) require.Nil(res) - require.ErrorContains(err, "blah2") + require.ErrorIs(err, errBlah2) }) t.Run("duplicate item", func(t *testing.T) { diff --git a/config/config.go b/config/config.go index 296fec699c..4af09f6877 100644 --- a/config/config.go +++ b/config/config.go @@ -10,6 +10,7 @@ import ( "github.com/ava-labs/avalanchego/utils/logging" "github.com/ava-labs/avalanchego/utils/profiler" "github.com/ava-labs/avalanchego/utils/units" + "github.com/ava-labs/hypersdk/codec" "github.com/ava-labs/hypersdk/trace" ) diff --git a/crypto/bls/private_test.go b/crypto/bls/private_test.go index 50a3764709..c0ce99b7a9 100644 --- a/crypto/bls/private_test.go +++ b/crypto/bls/private_test.go @@ -6,9 +6,8 @@ package bls import ( "testing" - "github.com/stretchr/testify/require" - "github.com/ava-labs/avalanchego/utils" + "github.com/stretchr/testify/require" ) func TestPrivateKeyFromBytesZero(t *testing.T) { diff --git a/crypto/bls/public_test.go b/crypto/bls/public_test.go index e7493bcf3b..e909a89ec9 100644 --- a/crypto/bls/public_test.go +++ b/crypto/bls/public_test.go @@ -6,10 +6,9 @@ package bls import ( "testing" - "github.com/stretchr/testify/require" - "github.com/ava-labs/avalanchego/utils" "github.com/ava-labs/avalanchego/utils/crypto/bls" + "github.com/stretchr/testify/require" ) func TestPublicKeyFromBytesWrongSize(t *testing.T) { diff --git a/crypto/bls/signature_test.go b/crypto/bls/signature_test.go index d014225b15..b380fb269c 100644 --- a/crypto/bls/signature_test.go +++ b/crypto/bls/signature_test.go @@ -6,9 +6,8 @@ package bls import ( "testing" - "github.com/stretchr/testify/require" - "github.com/ava-labs/avalanchego/utils" + "github.com/stretchr/testify/require" ) func TestSignatureBytes(t *testing.T) { diff --git a/crypto/ed25519/ed25519_test.go b/crypto/ed25519/ed25519_test.go index f0904d50d3..c8ee55267b 100644 --- a/crypto/ed25519/ed25519_test.go +++ b/crypto/ed25519/ed25519_test.go @@ -10,10 +10,10 @@ import ( "testing" "github.com/hdevalence/ed25519consensus" - oed25519 "github.com/oasisprotocol/curve25519-voi/primitives/ed25519" "github.com/oasisprotocol/curve25519-voi/primitives/ed25519/extra/cache" - "github.com/stretchr/testify/require" + + oed25519 "github.com/oasisprotocol/curve25519-voi/primitives/ed25519" ) var ( @@ -93,7 +93,7 @@ func TestSignSignatureValid(t *testing.T) { copy(expectedSig[:], ed25519Sign) // Sign using crypto sig := Sign(msg, TestPrivateKey) - require.Equal(sig, expectedSig, "Signature was incorrect") + require.Equal(expectedSig, sig, "Signature was incorrect") } func TestVerifyValidParams(t *testing.T) { @@ -117,6 +117,7 @@ func TestVerifyInvalidParams(t *testing.T) { } func TestBatchAddVerifyValid(t *testing.T) { + require := require.New(t) var ( numItems = 1024 pubs = make([]PublicKey, numItems) @@ -125,15 +126,11 @@ func TestBatchAddVerifyValid(t *testing.T) { ) for i := 0; i < numItems; i++ { priv, err := GeneratePrivateKey() - if err != nil { - t.Fatal(err) - } + require.NoError(err) pubs[i] = priv.PublicKey() msg := make([]byte, 128) _, err = rand.Read(msg) - if err != nil { - t.Fatal(err) - } + require.NoError(err) msgs[i] = msg sig := Sign(msg, priv) sigs[i] = sig @@ -142,12 +139,11 @@ func TestBatchAddVerifyValid(t *testing.T) { for i := 0; i < numItems; i++ { bv.Add(msgs[i], pubs[i], sigs[i]) } - if !bv.Verify() { - t.Fatal("invalid signature") - } + require.True(bv.Verify(), "invalid signature") } func TestBatchAddVerifyInvalid(t *testing.T) { + require := require.New(t) var ( numItems = 1024 pubs = make([]PublicKey, numItems) @@ -156,15 +152,11 @@ func TestBatchAddVerifyInvalid(t *testing.T) { ) for i := 0; i < numItems; i++ { priv, err := GeneratePrivateKey() - if err != nil { - t.Fatal(err) - } + require.NoError(err) pubs[i] = priv.PublicKey() msg := make([]byte, 128) _, err = rand.Read(msg) - if err != nil { - t.Fatal(err) - } + require.NoError(err) msgs[i] = msg sig := Sign(msg, priv) if i == 10 { @@ -176,115 +168,90 @@ func TestBatchAddVerifyInvalid(t *testing.T) { for i := 0; i < numItems; i++ { bv.Add(msgs[i], pubs[i], sigs[i]) } - if bv.Verify() { - t.Fatal("valid signature") - } + require.False(bv.Verify(), "valid signature") } func BenchmarkStdLibVerifySingle(b *testing.B) { + require := require.New(b) b.StopTimer() msg := make([]byte, 128) _, err := rand.Read(msg) - if err != nil { - b.Fatal(err) - } + require.NoError(err) pub, priv, err := ed25519.GenerateKey(nil) - if err != nil { - b.Fatal(err) - } + require.NoError(err) sig := ed25519.Sign(priv, msg) b.StartTimer() b.ReportAllocs() for i := 0; i < b.N; i++ { - if !ed25519.Verify(pub, msg, sig) { - b.Fatal("invalid signature") - } + require.True(ed25519.Verify(pub, msg, sig), "invalid signature") } } func BenchmarkConsensusVerifySingle(b *testing.B) { + require := require.New(b) b.StopTimer() msg := make([]byte, 128) _, err := rand.Read(msg) - if err != nil { - b.Fatal(err) - } + require.NoError(err) pub, priv, err := ed25519.GenerateKey(nil) - if err != nil { - b.Fatal(err) - } + require.NoError(err) sig := ed25519.Sign(priv, msg) b.StartTimer() b.ReportAllocs() for i := 0; i < b.N; i++ { - if !ed25519consensus.Verify(pub, msg, sig) { - b.Fatal("invalid signature") - } + require.True(ed25519consensus.Verify(pub, msg, sig), "invalid signature") } } func BenchmarkOasisVerifySingle(b *testing.B) { + require := require.New(b) b.StopTimer() msg := make([]byte, 128) _, err := rand.Read(msg) - if err != nil { - b.Fatal(err) - } + require.NoError(err) pub, priv, err := oed25519.GenerateKey(nil) - if err != nil { - b.Fatal(err) - } + require.NoError(err) sig := oed25519.Sign(priv, msg) b.StartTimer() b.ReportAllocs() for i := 0; i < b.N; i++ { - if !oed25519.VerifyWithOptions(pub, msg, sig, oed25519options) { - b.Fatal("invalid signature") - } + require.True(oed25519.VerifyWithOptions(pub, msg, sig, oed25519options), "invalid signature") } } func BenchmarkOasisVerifyCache(b *testing.B) { + require := require.New(b) b.StopTimer() cacheVerifier := cache.NewVerifier(cache.NewLRUCache(10000)) msg := make([]byte, 128) _, err := rand.Read(msg) - if err != nil { - b.Fatal(err) - } + require.NoError(err) pub, priv, err := oed25519.GenerateKey(nil) - if err != nil { - b.Fatal(err) - } + require.NoError(err) sig := oed25519.Sign(priv, msg) cacheVerifier.AddPublicKey(pub) b.StartTimer() b.ReportAllocs() for i := 0; i < b.N; i++ { - if !cacheVerifier.VerifyWithOptions(pub, msg, sig, oed25519options) { - b.Fatal("invalid signature") - } + require.True(cacheVerifier.VerifyWithOptions(pub, msg, sig, oed25519options), "invalid signature") } } func BenchmarkConsensusBatchAddVerify(b *testing.B) { for _, numItems := range []int{1, 4, 16, 64, 128, 512, 1024, 4096, 16384} { b.Run(strconv.Itoa(numItems), func(b *testing.B) { + require := require.New(b) b.StopTimer() pubs := make([][]byte, numItems) msgs := make([][]byte, numItems) sigs := make([][]byte, numItems) for i := 0; i < numItems; i++ { pub, priv, err := ed25519.GenerateKey(nil) - if err != nil { - b.Fatal(err) - } + require.NoError(err) pubs[i] = pub[:] msg := make([]byte, 128) _, err = rand.Read(msg) - if err != nil { - b.Fatal(err) - } + require.NoError(err) msgs[i] = msg sig := ed25519.Sign(priv, msg) sigs[i] = sig @@ -296,9 +263,7 @@ func BenchmarkConsensusBatchAddVerify(b *testing.B) { for j := 0; j < numItems; j++ { bv.Add(pubs[j], msgs[j], sigs[j]) } - if !bv.Verify() { - b.Fatal("invalid signature") - } + require.True(bv.Verify(), "invalid signature") } }) } @@ -307,21 +272,18 @@ func BenchmarkConsensusBatchAddVerify(b *testing.B) { func BenchmarkConsensusBatchVerify(b *testing.B) { for _, numItems := range []int{1, 4, 16, 64, 128, 512, 1024, 4096, 16384} { b.Run(strconv.Itoa(numItems), func(b *testing.B) { + require := require.New(b) b.StopTimer() pubs := make([][]byte, numItems) msgs := make([][]byte, numItems) sigs := make([][]byte, numItems) for i := 0; i < numItems; i++ { pub, priv, err := ed25519.GenerateKey(nil) - if err != nil { - b.Fatal(err) - } + require.NoError(err) pubs[i] = pub[:] msg := make([]byte, 128) _, err = rand.Read(msg) - if err != nil { - b.Fatal(err) - } + require.NoError(err) msgs[i] = msg sig := ed25519.Sign(priv, msg) sigs[i] = sig @@ -333,9 +295,7 @@ func BenchmarkConsensusBatchVerify(b *testing.B) { b.StartTimer() b.ReportAllocs() for i := 0; i < b.N; i++ { - if !bv.Verify() { - b.Fatal("invalid signature") - } + require.True(bv.Verify(), "invalid signature") } }) } @@ -344,21 +304,18 @@ func BenchmarkConsensusBatchVerify(b *testing.B) { func BenchmarkOasisBatchAddVerify(b *testing.B) { for _, numItems := range []int{1, 4, 16, 64, 128, 512, 1024, 4096, 16384} { b.Run(strconv.Itoa(numItems), func(b *testing.B) { + require := require.New(b) b.StopTimer() pubs := make([][]byte, numItems) msgs := make([][]byte, numItems) sigs := make([][]byte, numItems) for i := 0; i < numItems; i++ { pub, priv, err := oed25519.GenerateKey(nil) - if err != nil { - b.Fatal(err) - } + require.NoError(err) pubs[i] = pub msg := make([]byte, 128) _, err = rand.Read(msg) - if err != nil { - b.Fatal(err) - } + require.NoError(err) msgs[i] = msg sig := oed25519.Sign(priv, msg) sigs[i] = sig @@ -370,9 +327,7 @@ func BenchmarkOasisBatchAddVerify(b *testing.B) { for j := 0; j < numItems; j++ { bv.AddWithOptions(pubs[j], msgs[j], sigs[j], oed25519options) } - if !bv.VerifyBatchOnly(nil) { - b.Fatal("invalid signature") - } + require.True(bv.VerifyBatchOnly(nil), "invalid signature") } }) } @@ -381,21 +336,18 @@ func BenchmarkOasisBatchAddVerify(b *testing.B) { func BenchmarkOasisBatchVerify(b *testing.B) { for _, numItems := range []int{1, 4, 16, 64, 128, 512, 1024, 4096, 16384} { b.Run(strconv.Itoa(numItems), func(b *testing.B) { + require := require.New(b) b.StopTimer() pubs := make([][]byte, numItems) msgs := make([][]byte, numItems) sigs := make([][]byte, numItems) for i := 0; i < numItems; i++ { pub, priv, err := oed25519.GenerateKey(nil) - if err != nil { - b.Fatal(err) - } + require.NoError(err) pubs[i] = pub msg := make([]byte, 128) _, err = rand.Read(msg) - if err != nil { - b.Fatal(err) - } + require.NoError(err) msgs[i] = msg sig := oed25519.Sign(priv, msg) sigs[i] = sig @@ -407,9 +359,7 @@ func BenchmarkOasisBatchVerify(b *testing.B) { b.StartTimer() b.ReportAllocs() for i := 0; i < b.N; i++ { - if !bv.VerifyBatchOnly(nil) { - b.Fatal("invalid signature") - } + require.True(bv.VerifyBatchOnly(nil), "invalid signature") } }) } @@ -418,6 +368,7 @@ func BenchmarkOasisBatchVerify(b *testing.B) { func BenchmarkOasisBatchAddVerifyCache(b *testing.B) { for _, numItems := range []int{1, 4, 16, 64, 128, 512, 1024, 4096, 16384} { b.Run(strconv.Itoa(numItems), func(b *testing.B) { + require := require.New(b) b.StopTimer() cacheVerifier := cache.NewVerifier(cache.NewLRUCache(30000)) pubs := make([][]byte, numItems) @@ -425,16 +376,12 @@ func BenchmarkOasisBatchAddVerifyCache(b *testing.B) { sigs := make([][]byte, numItems) for i := 0; i < numItems; i++ { pub, priv, err := oed25519.GenerateKey(nil) - if err != nil { - b.Fatal(err) - } + require.NoError(err) cacheVerifier.AddPublicKey(pub) pubs[i] = pub msg := make([]byte, 128) _, err = rand.Read(msg) - if err != nil { - b.Fatal(err) - } + require.NoError(err) msgs[i] = msg sig := oed25519.Sign(priv, msg) sigs[i] = sig @@ -446,9 +393,7 @@ func BenchmarkOasisBatchAddVerifyCache(b *testing.B) { for j := 0; j < numItems; j++ { cacheVerifier.AddWithOptions(bv, pubs[j], msgs[j], sigs[j], oed25519options) } - if !bv.VerifyBatchOnly(nil) { - b.Fatal("invalid signature") - } + require.True(bv.VerifyBatchOnly(nil), "invalid signature") } }) } @@ -457,6 +402,7 @@ func BenchmarkOasisBatchAddVerifyCache(b *testing.B) { func BenchmarkOasisBatchVerifyCache(b *testing.B) { for _, numItems := range []int{1, 4, 16, 64, 128, 512, 1024, 4096, 16384} { b.Run(strconv.Itoa(numItems), func(b *testing.B) { + require := require.New(b) b.StopTimer() cacheVerifier := cache.NewVerifier(cache.NewLRUCache(30000)) pubs := make([][]byte, numItems) @@ -464,16 +410,12 @@ func BenchmarkOasisBatchVerifyCache(b *testing.B) { sigs := make([][]byte, numItems) for i := 0; i < numItems; i++ { pub, priv, err := oed25519.GenerateKey(nil) - if err != nil { - b.Fatal(err) - } + require.NoError(err) cacheVerifier.AddPublicKey(pub) pubs[i] = pub msg := make([]byte, 128) _, err = rand.Read(msg) - if err != nil { - b.Fatal(err) - } + require.NoError(err) msgs[i] = msg sig := oed25519.Sign(priv, msg) sigs[i] = sig @@ -485,9 +427,7 @@ func BenchmarkOasisBatchVerifyCache(b *testing.B) { b.StartTimer() b.ReportAllocs() for i := 0; i < b.N; i++ { - if !bv.VerifyBatchOnly(nil) { - b.Fatal("invalid signature") - } + require.True(bv.VerifyBatchOnly(nil), "invalid signature") } }) } diff --git a/eheap/eheap_test.go b/eheap/eheap_test.go index fef8a6d6fa..bbdc0716d1 100644 --- a/eheap/eheap_test.go +++ b/eheap/eheap_test.go @@ -6,9 +6,8 @@ package eheap import ( "testing" - "github.com/stretchr/testify/require" - "github.com/ava-labs/avalanchego/ids" + "github.com/stretchr/testify/require" ) const testSponsor = "testSponsor" @@ -44,7 +43,7 @@ func TestExpiryHeapNew(t *testing.T) { // Creates empty min and max heaps require := require.New(t) eheap := New[*TestItem](0) - require.Equal(eheap.minHeap.Len(), 0, "MinHeap not initialized correctly") + require.Zero(eheap.minHeap.Len(), "MinHeap not initialized correctly") } func TestExpiryHeapAdd(t *testing.T) { @@ -53,7 +52,7 @@ func TestExpiryHeapAdd(t *testing.T) { eheap := New[*TestItem](0) item := GenerateTestItem("sponsor", 1) eheap.Add(item) - require.Equal(eheap.minHeap.Len(), 1, "MinHeap not pushed correctly") + require.Equal(1, eheap.minHeap.Len(), "MinHeap not pushed correctly") require.True(eheap.minHeap.Has(item.ID()), "MinHeap does not have ID") } @@ -64,11 +63,11 @@ func TestExpiryHeapRemove(t *testing.T) { item := GenerateTestItem("sponsor", 1) // Add first eheap.Add(item) - require.Equal(eheap.minHeap.Len(), 1, "MinHeap not pushed correctly") + require.Equal(1, eheap.minHeap.Len(), "MinHeap not pushed correctly") require.True(eheap.minHeap.Has(item.ID()), "MinHeap does not have ID") // Remove eheap.Remove(item.ID()) - require.Equal(eheap.minHeap.Len(), 0, "MinHeap not removed") + require.Zero(eheap.minHeap.Len(), "MinHeap not removed") require.False(eheap.minHeap.Has(item.ID()), "MinHeap still has ID") } @@ -94,11 +93,11 @@ func TestSetMin(t *testing.T) { } // Remove half removed := eheap.SetMin(5) - require.Equal(5, len(removed), "Returned an incorrect number of txs.") + require.Len(removed, 5, "Returned an incorrect number of txs.") // All timestamps less than 5 seen := make(map[int64]bool) for _, item := range removed { - require.True(item.Expiry() < 5) + require.Less(item.Expiry(), int64(5)) _, ok := seen[item.Expiry()] require.False(ok, "Incorrect item removed.") seen[item.Expiry()] = true @@ -120,8 +119,8 @@ func TestSetMinRemovesAll(t *testing.T) { } // Remove more than exists removed := eheap.SetMin(10) - require.Equal(5, len(removed), "Returned an incorrect number of txs.") - require.Equal(0, eheap.Len(), "ExpiryHeap has incorrect number of txs.") + require.Len(removed, 5, "Returned an incorrect number of txs.") + require.Zero(eheap.Len(), "ExpiryHeap has incorrect number of txs.") require.Equal(items, removed, "Removed items are not as expected.") } diff --git a/emap/emap.go b/emap/emap.go index b881776587..a5d1d3e083 100644 --- a/emap/emap.go +++ b/emap/emap.go @@ -8,6 +8,7 @@ import ( "github.com/ava-labs/avalanchego/ids" "github.com/ava-labs/avalanchego/utils/set" + "github.com/ava-labs/hypersdk/heap" ) diff --git a/emap/emap_test.go b/emap/emap_test.go index b3086a17d8..bb04963a87 100644 --- a/emap/emap_test.go +++ b/emap/emap_test.go @@ -8,8 +8,9 @@ import ( "github.com/ava-labs/avalanchego/ids" "github.com/ava-labs/avalanchego/utils/set" - "github.com/ava-labs/hypersdk/heap" "github.com/stretchr/testify/require" + + "github.com/ava-labs/hypersdk/heap" ) type TestTx struct { @@ -75,7 +76,7 @@ func TestEmapAddIDNewBucket(t *testing.T) { // get bucket b, okBucket := e.times[timestamp] require.True(okBucket, "Could not find time bucket") - require.Equal(len(b.items), 1, "Bucket length is incorrect") + require.Len(b.items, 1, "Bucket length is incorrect") // Check bucket heap was updated require.True(e.bh.Has(id), "BH does not have ID") @@ -111,7 +112,7 @@ func TestEmapAddIDExists(t *testing.T) { // get bucket b, okBucket := e.times[timestamp] require.True(okBucket, "Could not find time bucket") - require.Equal(len(b.items), 1, "Bucket length is incorrect") + require.Len(b.items, 1, "Bucket length is incorrect") entry, ok = e.bh.Get(id) // Check bh @@ -150,7 +151,7 @@ func TestEmapAddIDBucketExists(t *testing.T) { b, okBucket := e.times[timestamp] require.True(okBucket, "Could not find time bucket") require.Equal(1, e.bh.Len(), "Number of buckets is incorrect.") - require.Equal(len(b.items), 2, "Bucket length is incorrect") + require.Len(b.items, 2, "Bucket length is incorrect") entry, ok := e.bh.Get(id1) // Check bh diff --git a/examples/morpheusvm/go.sum b/examples/morpheusvm/go.sum index 28ea5a3bdb..1639238303 100644 --- a/examples/morpheusvm/go.sum +++ b/examples/morpheusvm/go.sum @@ -251,8 +251,6 @@ github.com/golang/mock v1.4.0/go.mod h1:UOMv5ysSaYNkG+OFQykRIcU/QvvxJf3p21QfJ2Bt github.com/golang/mock v1.4.1/go.mod h1:UOMv5ysSaYNkG+OFQykRIcU/QvvxJf3p21QfJ2Bt3cw= github.com/golang/mock v1.4.3/go.mod h1:UOMv5ysSaYNkG+OFQykRIcU/QvvxJf3p21QfJ2Bt3cw= github.com/golang/mock v1.4.4/go.mod h1:l3mdAwkq5BuhzHwde/uurv3sEJeZMXNpwsxVWU71h+4= -github.com/golang/mock v1.6.0 h1:ErTB+efbowRARo13NNdxyJji2egdxLGQhRaY+DUumQc= -github.com/golang/mock v1.6.0/go.mod h1:p6yTPP+5HYm5mzsMV8JkE6ZKdX+/wYM6Hr+LicevLPs= github.com/golang/protobuf v1.2.0/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U= github.com/golang/protobuf v1.3.1/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U= github.com/golang/protobuf v1.3.2/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U= diff --git a/examples/tokenvm/go.sum b/examples/tokenvm/go.sum index 9a7a8070cf..b621942fba 100644 --- a/examples/tokenvm/go.sum +++ b/examples/tokenvm/go.sum @@ -253,8 +253,6 @@ github.com/golang/mock v1.4.0/go.mod h1:UOMv5ysSaYNkG+OFQykRIcU/QvvxJf3p21QfJ2Bt github.com/golang/mock v1.4.1/go.mod h1:UOMv5ysSaYNkG+OFQykRIcU/QvvxJf3p21QfJ2Bt3cw= github.com/golang/mock v1.4.3/go.mod h1:UOMv5ysSaYNkG+OFQykRIcU/QvvxJf3p21QfJ2Bt3cw= github.com/golang/mock v1.4.4/go.mod h1:l3mdAwkq5BuhzHwde/uurv3sEJeZMXNpwsxVWU71h+4= -github.com/golang/mock v1.6.0 h1:ErTB+efbowRARo13NNdxyJji2egdxLGQhRaY+DUumQc= -github.com/golang/mock v1.6.0/go.mod h1:p6yTPP+5HYm5mzsMV8JkE6ZKdX+/wYM6Hr+LicevLPs= github.com/golang/protobuf v1.2.0/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U= github.com/golang/protobuf v1.3.1/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U= github.com/golang/protobuf v1.3.2/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U= diff --git a/executor/executor.go b/executor/executor.go index 059d173056..c694413473 100644 --- a/executor/executor.go +++ b/executor/executor.go @@ -7,6 +7,7 @@ import ( "sync" "github.com/ava-labs/avalanchego/utils/set" + "github.com/ava-labs/hypersdk/state" ) diff --git a/executor/executor_test.go b/executor/executor_test.go index 9bec8ea137..53faba7366 100644 --- a/executor/executor_test.go +++ b/executor/executor_test.go @@ -167,7 +167,7 @@ func TestEarlyExit(t *testing.T) { return nil }) } - require.True(len(completed) < 500) + require.Less(len(completed), 500) require.ErrorIs(e.Wait(), terr) // no task running } @@ -194,6 +194,6 @@ func TestStop(t *testing.T) { return nil }) } - require.True(len(completed) < 500) + require.Less(len(completed), 500) require.ErrorIs(e.Wait(), ErrStopped) // no task running } diff --git a/fees/manager.go b/fees/manager.go index 311c99c990..2b308606e1 100644 --- a/fees/manager.go +++ b/fees/manager.go @@ -10,6 +10,7 @@ import ( "sync" "github.com/ava-labs/avalanchego/utils/math" + "github.com/ava-labs/hypersdk/consts" "github.com/ava-labs/hypersdk/window" ) diff --git a/go.mod b/go.mod index 78117f4230..4dfb5c76bd 100644 --- a/go.mod +++ b/go.mod @@ -6,9 +6,9 @@ require ( github.com/NYTimes/gziphandler v1.1.1 github.com/ava-labs/avalanche-network-runner v1.7.4-rc.0 github.com/ava-labs/avalanchego v1.10.18 + github.com/btcsuite/btcd/btcutil v1.1.3 github.com/bytecodealliance/wasmtime-go/v14 v14.0.0 github.com/cockroachdb/pebble v0.0.0-20230224221607-fccb83b60d5c - github.com/golang/mock v1.6.0 github.com/gorilla/mux v1.8.0 github.com/gorilla/rpc v1.2.0 github.com/gorilla/websocket v1.5.0 @@ -38,7 +38,6 @@ require ( filippo.io/edwards25519 v1.0.0 // indirect github.com/DataDog/zstd v1.5.2 // indirect github.com/beorn7/perks v1.0.1 // indirect - github.com/btcsuite/btcd/btcutil v1.1.3 // indirect github.com/cenkalti/backoff/v4 v4.2.0 // indirect github.com/cespare/xxhash/v2 v2.2.0 // indirect github.com/chzyer/readline v1.5.1 // indirect diff --git a/go.sum b/go.sum index 47dabd744d..346d64da58 100644 --- a/go.sum +++ b/go.sum @@ -191,8 +191,6 @@ github.com/golang/mock v1.4.0/go.mod h1:UOMv5ysSaYNkG+OFQykRIcU/QvvxJf3p21QfJ2Bt github.com/golang/mock v1.4.1/go.mod h1:UOMv5ysSaYNkG+OFQykRIcU/QvvxJf3p21QfJ2Bt3cw= github.com/golang/mock v1.4.3/go.mod h1:UOMv5ysSaYNkG+OFQykRIcU/QvvxJf3p21QfJ2Bt3cw= github.com/golang/mock v1.4.4/go.mod h1:l3mdAwkq5BuhzHwde/uurv3sEJeZMXNpwsxVWU71h+4= -github.com/golang/mock v1.6.0 h1:ErTB+efbowRARo13NNdxyJji2egdxLGQhRaY+DUumQc= -github.com/golang/mock v1.6.0/go.mod h1:p6yTPP+5HYm5mzsMV8JkE6ZKdX+/wYM6Hr+LicevLPs= github.com/golang/protobuf v1.2.0/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U= github.com/golang/protobuf v1.3.1/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U= github.com/golang/protobuf v1.3.2/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U= @@ -693,7 +691,6 @@ golang.org/x/tools v0.0.0-20200729194436-6467de6f59a7/go.mod h1:njjCfa9FT2d7l9Bc golang.org/x/tools v0.0.0-20200804011535-6c149bb5ef0d/go.mod h1:njjCfa9FT2d7l9Bc6FUM5FLjQPp3cFF28FI3qnDFljA= golang.org/x/tools v0.0.0-20200825202427-b303f430e36d/go.mod h1:njjCfa9FT2d7l9Bc6FUM5FLjQPp3cFF28FI3qnDFljA= golang.org/x/tools v0.0.0-20210106214847-113979e3529a/go.mod h1:emZCQorbCU4vsT4fOWvOPXz4eW1wZW4PmDk9uLelYpA= -golang.org/x/tools v0.1.1/go.mod h1:o0xws9oXOQQZyjljx8fwUC0k7L1pTE6eaCbjGeHmOkk= golang.org/x/tools v0.1.3/go.mod h1:o0xws9oXOQQZyjljx8fwUC0k7L1pTE6eaCbjGeHmOkk= golang.org/x/tools v0.16.0 h1:GO788SKMRunPIBCXiQyo2AaexLstOrVhuAL5YwsckQM= golang.org/x/tools v0.16.0/go.mod h1:kYVVN6I1mBNoB1OX+noeBjbRk4IUEPa7JJ+TJMEooJ0= diff --git a/gossiper/dependencies.go b/gossiper/dependencies.go index 0b5f33fbdf..e3cada2b3e 100644 --- a/gossiper/dependencies.go +++ b/gossiper/dependencies.go @@ -11,6 +11,7 @@ import ( "github.com/ava-labs/avalanchego/trace" "github.com/ava-labs/avalanchego/utils/logging" "github.com/ava-labs/avalanchego/utils/set" + "github.com/ava-labs/hypersdk/chain" ) diff --git a/gossiper/manual.go b/gossiper/manual.go index 3b73fcc60b..1669d2a160 100644 --- a/gossiper/manual.go +++ b/gossiper/manual.go @@ -9,9 +9,10 @@ import ( "github.com/ava-labs/avalanchego/ids" "github.com/ava-labs/avalanchego/snow/engine/common" + "go.uber.org/zap" + "github.com/ava-labs/hypersdk/chain" "github.com/ava-labs/hypersdk/consts" - "go.uber.org/zap" ) var _ Gossiper = (*Manual)(nil) @@ -46,7 +47,7 @@ func (g *Manual) Force(ctx context.Context) error { mempoolErr := g.vm.Mempool().Top( ctx, g.vm.GetTargetGossipDuration(), - func(ictx context.Context, next *chain.Transaction) (cont bool, rest bool, err error) { + func(_ context.Context, next *chain.Transaction) (cont bool, rest bool, err error) { // Remove txs that are expired if next.Base.Timestamp < now { return true, false, nil diff --git a/gossiper/proposer.go b/gossiper/proposer.go index 4e9bf2f141..5dd961a997 100644 --- a/gossiper/proposer.go +++ b/gossiper/proposer.go @@ -15,11 +15,12 @@ import ( "github.com/ava-labs/avalanchego/utils/set" "github.com/ava-labs/avalanchego/utils/timer" "github.com/ava-labs/avalanchego/vms/proposervm/proposer" + "go.uber.org/zap" + "github.com/ava-labs/hypersdk/cache" "github.com/ava-labs/hypersdk/chain" "github.com/ava-labs/hypersdk/consts" "github.com/ava-labs/hypersdk/workers" - "go.uber.org/zap" ) var _ Gossiper = (*Proposer)(nil) @@ -115,7 +116,7 @@ func (g *Proposer) Force(ctx context.Context) error { mempoolErr := g.vm.Mempool().Top( ctx, g.vm.GetTargetGossipDuration(), - func(ictx context.Context, next *chain.Transaction) (cont bool, rest bool, err error) { + func(_ context.Context, next *chain.Transaction) (cont bool, rest bool, err error) { // Remove txs that are expired if next.Base.Timestamp < now { return true, false, nil diff --git a/heap/heap_test.go b/heap/heap_test.go index 6cb3dc71f9..bdf3198411 100644 --- a/heap/heap_test.go +++ b/heap/heap_test.go @@ -18,7 +18,7 @@ type testItem struct { func TestUnit64HeapPushPopMin(t *testing.T) { require := require.New(t) minHeap := New[*testItem, uint64](0, true) - require.Equal(minHeap.Len(), 0, "heap not initialized properly.") + require.Zero(minHeap.Len(), "heap not initialized properly.") mempoolItem1 := &testItem{ids.GenerateTestID(), 10} mempoolItem2 := &testItem{ids.GenerateTestID(), 7} mempoolItem3 := &testItem{ids.GenerateTestID(), 15} @@ -48,7 +48,7 @@ func TestUnit64HeapPushPopMin(t *testing.T) { minHeap.Push(low) minHeap.Push(high) // Added all three - require.Equal(minHeap.Len(), 3, "Not pushed correctly.") + require.Equal(3, minHeap.Len(), "Not pushed correctly.") // Check if added to lookup table ok := minHeap.Has(med.ID) require.True(ok, "Item not found in lookup.") @@ -68,7 +68,7 @@ func TestUnit64HeapPushPopMin(t *testing.T) { func TestUnit64HeapPushPopMax(t *testing.T) { require := require.New(t) maxHeap := New[*testItem, uint64](0, false) - require.Equal(maxHeap.Len(), 0, "heap not initialized properly.") + require.Zero(maxHeap.Len(), "heap not initialized properly.") mempoolItem1 := &testItem{ids.GenerateTestID(), 10} mempoolItem2 := &testItem{ids.GenerateTestID(), 7} @@ -99,7 +99,7 @@ func TestUnit64HeapPushPopMax(t *testing.T) { maxHeap.Push(low) maxHeap.Push(high) // Added all three - require.Equal(maxHeap.Len(), 3, "Not pushed correctly.") + require.Equal(3, maxHeap.Len(), "Not pushed correctly.") // Check if added to lookup table ok := maxHeap.Has(med.ID) require.True(ok, "Item not found in lookup.") @@ -120,7 +120,7 @@ func TestUnit64HeapPushExists(t *testing.T) { // Push an item already in heap require := require.New(t) minHeap := New[*testItem, uint64](0, true) - require.Equal(minHeap.Len(), 0, "heap not initialized properly.") + require.Zero(minHeap.Len(), "heap not initialized properly.") mempoolItem := &testItem{ids.GenerateTestID(), 10} entry := &Entry[*testItem, uint64]{ ID: mempoolItem.id, @@ -130,20 +130,20 @@ func TestUnit64HeapPushExists(t *testing.T) { } minHeap.Push(entry) // Pushed correctly - require.Equal(minHeap.Len(), 1, "Not pushed correctly.") + require.Equal(1, minHeap.Len(), "Not pushed correctly.") // Check if added to lookup table ok := minHeap.Has(entry.ID) require.True(ok, "Item not found in lookup.") minHeap.Push(entry) // Only 1 item - require.Equal(minHeap.Len(), 1, "Not pushed correctly.") + require.Equal(1, minHeap.Len(), "Not pushed correctly.") } func TestUnit64HeapGetID(t *testing.T) { // Push an item and grab its ID require := require.New(t) minHeap := New[*testItem, uint64](0, true) - require.Equal(minHeap.Len(), 0, "heap not initialized properly.") + require.Zero(minHeap.Len(), "heap not initialized properly.") mempoolItem := &testItem{ids.GenerateTestID(), 10} entry := &Entry[*testItem, uint64]{ @@ -156,7 +156,7 @@ func TestUnit64HeapGetID(t *testing.T) { require.False(ok, "Entry returned before pushing.") minHeap.Push(entry) // Pushed correctly - require.Equal(minHeap.Len(), 1, "Not pushed correctly.") + require.Equal(1, minHeap.Len(), "Not pushed correctly.") entryReturned, ok := minHeap.Get(mempoolItem.id) require.True(ok, "Entry not returned.") require.Equal(entry, entryReturned, "Returned incorrect entry") @@ -165,7 +165,7 @@ func TestUnit64HeapGetID(t *testing.T) { func TestUnit64HeapHasID(t *testing.T) { require := require.New(t) minHeap := New[*testItem, uint64](0, true) - require.Equal(minHeap.Len(), 0, "heap not initialized properly.") + require.Zero(minHeap.Len(), "heap not initialized properly.") mempoolItem := &testItem{ids.GenerateTestID(), 10} entry := &Entry[*testItem, uint64]{ ID: mempoolItem.id, @@ -177,7 +177,7 @@ func TestUnit64HeapHasID(t *testing.T) { require.False(ok, "Entry has ID before pushing.") minHeap.Push(entry) // Pushed correctly - require.Equal(minHeap.Len(), 1, "Not pushed correctly.") + require.Equal(1, minHeap.Len(), "Not pushed correctly.") ok = minHeap.Has(mempoolItem.id) require.True(ok, "Entry was not found in heap.") } diff --git a/mempool/mempool.go b/mempool/mempool.go index f19aa6431d..c78c4a5299 100644 --- a/mempool/mempool.go +++ b/mempool/mempool.go @@ -11,10 +11,11 @@ import ( "github.com/ava-labs/avalanchego/ids" "github.com/ava-labs/avalanchego/trace" "github.com/ava-labs/avalanchego/utils/set" + "go.opentelemetry.io/otel/attribute" + "github.com/ava-labs/hypersdk/codec" "github.com/ava-labs/hypersdk/eheap" "github.com/ava-labs/hypersdk/list" - "go.opentelemetry.io/otel/attribute" ) const maxPrealloc = 4_096 diff --git a/mempool/mempool_test.go b/mempool/mempool_test.go index d6287c004d..40b5c38731 100644 --- a/mempool/mempool_test.go +++ b/mempool/mempool_test.go @@ -8,10 +8,11 @@ import ( "testing" "github.com/ava-labs/avalanchego/ids" + "github.com/stretchr/testify/require" + "go.uber.org/mock/gomock" + "github.com/ava-labs/hypersdk/codec" "github.com/ava-labs/hypersdk/trace" - "github.com/golang/mock/gomock" - "github.com/stretchr/testify/require" ) var testSponsor = codec.CreateAddress(1, ids.GenerateTestID()) @@ -179,11 +180,11 @@ func TestMempoolSetMinTimestamp(t *testing.T) { } // Remove half removed := txm.SetMinTimestamp(ctx, 5) - require.Equal(5, len(removed), "Mempool has incorrect number of txs.") + require.Len(removed, 5, "Mempool has incorrect number of txs.") // All timestamps less than 5 seen := make(map[int64]bool) for _, item := range removed { - require.True(item.Expiry() < 5) + require.Less(item.Expiry(), int64(5)) _, ok := seen[item.Expiry()] require.False(ok) seen[item.Expiry()] = true diff --git a/pubsub/consts.go b/pubsub/consts.go index b1411175e5..379758b37b 100644 --- a/pubsub/consts.go +++ b/pubsub/consts.go @@ -7,6 +7,7 @@ import ( "time" "github.com/ava-labs/avalanchego/utils/units" + "github.com/ava-labs/hypersdk/consts" ) diff --git a/pubsub/message_buffer.go b/pubsub/message_buffer.go index c35ab184e1..53142e3adb 100644 --- a/pubsub/message_buffer.go +++ b/pubsub/message_buffer.go @@ -9,9 +9,10 @@ import ( "github.com/ava-labs/avalanchego/utils/logging" "github.com/ava-labs/avalanchego/utils/timer" + "go.uber.org/zap" + "github.com/ava-labs/hypersdk/codec" "github.com/ava-labs/hypersdk/consts" - "go.uber.org/zap" ) type MessageBuffer struct { diff --git a/pubsub/server.go b/pubsub/server.go index d2e7126ca7..fa58709c5f 100644 --- a/pubsub/server.go +++ b/pubsub/server.go @@ -8,11 +8,9 @@ import ( "sync/atomic" "time" + "github.com/ava-labs/avalanchego/utils/logging" "github.com/gorilla/websocket" - "go.uber.org/zap" - - "github.com/ava-labs/avalanchego/utils/logging" ) type ServerConfig struct { diff --git a/pubsub/server_test.go b/pubsub/server_test.go index e80978abd7..60e6c28a83 100644 --- a/pubsub/server_test.go +++ b/pubsub/server_test.go @@ -14,9 +14,10 @@ import ( "github.com/ava-labs/avalanchego/ids" "github.com/ava-labs/avalanchego/utils/logging" - "github.com/ava-labs/hypersdk/consts" "github.com/gorilla/websocket" "github.com/stretchr/testify/require" + + "github.com/ava-labs/hypersdk/consts" ) const dummyAddr = "localhost:8080" @@ -257,7 +258,7 @@ func TestServerPublishSpecific(t *testing.T) { require.NoError(err, "Error setting connection deadline.") // Make sure connection wasn't written too _, _, err = webCon2.ReadMessage() - require.Error(err, "Error not thrown.") + require.Error(err, "Error not thrown.") //nolint:forbidigo netErr, ok := err.(net.Error) require.True(ok, "Error is not a net.Error") require.True(netErr.Timeout(), "Error is not a timeout error") diff --git a/requester/requester.go b/requester/requester.go index af0c18028d..c0c74694ea 100644 --- a/requester/requester.go +++ b/requester/requester.go @@ -119,7 +119,7 @@ func SendJSONRequest( request, err := http.NewRequestWithContext( ctx, - "POST", + http.MethodPost, uri.String(), bytes.NewBuffer(requestBodyBytes), ) diff --git a/rpc/dependencies.go b/rpc/dependencies.go index 3e5a65da9e..d9cde2e5bf 100644 --- a/rpc/dependencies.go +++ b/rpc/dependencies.go @@ -11,6 +11,7 @@ import ( "github.com/ava-labs/avalanchego/trace" "github.com/ava-labs/avalanchego/utils/logging" "github.com/ava-labs/avalanchego/vms/platformvm/warp" + "github.com/ava-labs/hypersdk/chain" "github.com/ava-labs/hypersdk/fees" ) diff --git a/rpc/jsonrpc_client.go b/rpc/jsonrpc_client.go index 0288d971ed..fa14d6f91d 100644 --- a/rpc/jsonrpc_client.go +++ b/rpc/jsonrpc_client.go @@ -11,7 +11,6 @@ import ( "github.com/ava-labs/avalanchego/ids" "github.com/ava-labs/avalanchego/snow/validators" - autils "github.com/ava-labs/avalanchego/utils" "github.com/ava-labs/avalanchego/utils/crypto/bls" "github.com/ava-labs/avalanchego/utils/math" "github.com/ava-labs/avalanchego/utils/set" @@ -22,6 +21,8 @@ import ( "github.com/ava-labs/hypersdk/fees" "github.com/ava-labs/hypersdk/requester" "github.com/ava-labs/hypersdk/utils" + + avautils "github.com/ava-labs/avalanchego/utils" ) const ( @@ -286,7 +287,7 @@ func getCanonicalValidatorSet( // Sort validators by public key vdrList := maps.Values(vdrs) - autils.Sort(vdrList) + avautils.Sort(vdrList) return vdrList, totalWeight, nil } diff --git a/rpc/jsonrpc_server.go b/rpc/jsonrpc_server.go index cb654b33ab..f18211abbc 100644 --- a/rpc/jsonrpc_server.go +++ b/rpc/jsonrpc_server.go @@ -12,11 +12,12 @@ import ( "github.com/ava-labs/avalanchego/ids" "github.com/ava-labs/avalanchego/utils/crypto/bls" "github.com/ava-labs/avalanchego/vms/platformvm/warp" + "go.uber.org/zap" + "github.com/ava-labs/hypersdk/chain" "github.com/ava-labs/hypersdk/codec" "github.com/ava-labs/hypersdk/consts" "github.com/ava-labs/hypersdk/fees" - "go.uber.org/zap" ) type JSONRPCServer struct { diff --git a/rpc/websocket_client.go b/rpc/websocket_client.go index 34a1bac405..7b33be646a 100644 --- a/rpc/websocket_client.go +++ b/rpc/websocket_client.go @@ -12,11 +12,12 @@ import ( "github.com/ava-labs/avalanchego/ids" "github.com/ava-labs/avalanchego/utils/logging" + "github.com/gorilla/websocket" + "github.com/ava-labs/hypersdk/chain" "github.com/ava-labs/hypersdk/fees" "github.com/ava-labs/hypersdk/pubsub" "github.com/ava-labs/hypersdk/utils" - "github.com/gorilla/websocket" ) type WebSocketClient struct { diff --git a/rpc/websocket_packer.go b/rpc/websocket_packer.go index c039b40e59..cf0ff95a15 100644 --- a/rpc/websocket_packer.go +++ b/rpc/websocket_packer.go @@ -7,6 +7,7 @@ import ( "errors" "github.com/ava-labs/avalanchego/ids" + "github.com/ava-labs/hypersdk/chain" "github.com/ava-labs/hypersdk/codec" "github.com/ava-labs/hypersdk/consts" diff --git a/scripts/tests.lint.sh b/scripts/tests.lint.sh index 7b2be53ef5..17c1931f08 100755 --- a/scripts/tests.lint.sh +++ b/scripts/tests.lint.sh @@ -28,7 +28,7 @@ TESTS=${TESTS:-"golangci_lint license_header"} # https://github.com/golangci/golangci-lint/releases function test_golangci_lint { - go install -v github.com/golangci/golangci-lint/cmd/golangci-lint@v1.51.2 + go install -v github.com/golangci/golangci-lint/cmd/golangci-lint@v1.56.1 golangci-lint run --config .golangci.yml } diff --git a/server/server.go b/server/server.go index 9a763a0270..699a26e498 100644 --- a/server/server.go +++ b/server/server.go @@ -11,12 +11,9 @@ import ( "time" "github.com/NYTimes/gziphandler" - + "github.com/ava-labs/avalanchego/utils/logging" "github.com/rs/cors" - "go.uber.org/zap" - - "github.com/ava-labs/avalanchego/utils/logging" ) var _ Server = (*server)(nil) diff --git a/storage/storage.go b/storage/storage.go index 739f9e1d9f..6763a9e48f 100644 --- a/storage/storage.go +++ b/storage/storage.go @@ -7,6 +7,7 @@ import ( "github.com/ava-labs/avalanchego/api/metrics" "github.com/ava-labs/avalanchego/database" "github.com/ava-labs/avalanchego/database/corruptabledb" + "github.com/ava-labs/hypersdk/pebble" "github.com/ava-labs/hypersdk/utils" ) diff --git a/trace/noop.go b/trace/noop.go index b02f4f3dc1..1c2197517a 100644 --- a/trace/noop.go +++ b/trace/noop.go @@ -6,9 +6,9 @@ package trace import ( "context" - oteltrace "go.opentelemetry.io/otel/trace" - "github.com/ava-labs/avalanchego/trace" + + oteltrace "go.opentelemetry.io/otel/trace" ) var _ trace.Tracer = (*noOpTracer)(nil) @@ -23,7 +23,7 @@ func (n noOpTracer) Start( spanName string, opts ...oteltrace.SpanStartOption, ) (context.Context, oteltrace.Span) { - return n.t.Start(ctx, spanName, opts...) + return n.t.Start(ctx, spanName, opts...) //nolint:spancheck } func (noOpTracer) Close() error { diff --git a/trace/tracer.go b/trace/tracer.go index b53de2c256..6b9cfe8a01 100644 --- a/trace/tracer.go +++ b/trace/tracer.go @@ -7,14 +7,14 @@ import ( "context" "time" + "github.com/ava-labs/avalanchego/trace" "go.opentelemetry.io/otel/attribute" "go.opentelemetry.io/otel/exporters/zipkin" "go.opentelemetry.io/otel/sdk/resource" + sdktrace "go.opentelemetry.io/otel/sdk/trace" semconv "go.opentelemetry.io/otel/semconv/v1.4.0" oteltrace "go.opentelemetry.io/otel/trace" - - "github.com/ava-labs/avalanchego/trace" ) const ( diff --git a/tstate/tstate.go b/tstate/tstate.go index 66aaa695ef..b526a1f7e4 100644 --- a/tstate/tstate.go +++ b/tstate/tstate.go @@ -10,8 +10,10 @@ import ( "github.com/ava-labs/avalanchego/trace" "github.com/ava-labs/avalanchego/utils/maybe" "github.com/ava-labs/avalanchego/x/merkledb" - "github.com/ava-labs/hypersdk/state" "go.opentelemetry.io/otel/attribute" + + "github.com/ava-labs/hypersdk/state" + oteltrace "go.opentelemetry.io/otel/trace" ) diff --git a/tstate/tstate_test.go b/tstate/tstate_test.go index dcd9ebf86f..f8ebdea974 100644 --- a/tstate/tstate_test.go +++ b/tstate/tstate_test.go @@ -13,11 +13,11 @@ import ( "github.com/ava-labs/avalanchego/utils/maybe" "github.com/ava-labs/avalanchego/utils/units" "github.com/ava-labs/avalanchego/x/merkledb" + "github.com/stretchr/testify/require" + "github.com/ava-labs/hypersdk/keys" "github.com/ava-labs/hypersdk/state" "github.com/ava-labs/hypersdk/trace" - - "github.com/stretchr/testify/require" ) var ( @@ -196,58 +196,58 @@ func TestInsertRemoveInsert(t *testing.T) { // Insert key for first time require.NoError(tsv.Insert(ctx, key2, testVal)) allocates, writes := tsv.KeyOperations() - require.EqualValues(map[string]uint16{key2str: 2}, allocates) - require.EqualValues(map[string]uint16{key2str: 1}, writes) + require.Equal(map[string]uint16{key2str: 2}, allocates) + require.Equal(map[string]uint16{key2str: 1}, writes) require.Equal(tsv.pendingChangedKeys[key2str], maybe.Some(testVal)) // Remove key require.NoError(tsv.Remove(ctx, key2)) allocates, writes = tsv.KeyOperations() - require.EqualValues(map[string]uint16{}, allocates) - require.EqualValues(map[string]uint16{}, writes) + require.Equal(map[string]uint16{}, allocates) + require.Equal(map[string]uint16{}, writes) require.NotContains(tsv.pendingChangedKeys, key2str) // Insert key again require.NoError(tsv.Insert(ctx, key2, testVal)) allocates, writes = tsv.KeyOperations() - require.EqualValues(map[string]uint16{key2str: 2}, allocates) - require.EqualValues(map[string]uint16{key2str: 1}, writes) + require.Equal(map[string]uint16{key2str: 2}, allocates) + require.Equal(map[string]uint16{key2str: 1}, writes) require.Equal(tsv.pendingChangedKeys[key2str], maybe.Some(testVal)) // Modify key testVal2 := []byte("blah") require.NoError(tsv.Insert(ctx, key2, testVal2)) allocates, writes = tsv.KeyOperations() - require.EqualValues(map[string]uint16{key2str: 2}, allocates) - require.EqualValues(map[string]uint16{key2str: 1}, writes) + require.Equal(map[string]uint16{key2str: 2}, allocates) + require.Equal(map[string]uint16{key2str: 1}, writes) require.Equal(tsv.pendingChangedKeys[key2str], maybe.Some(testVal2)) // Rollback modify tsv.Rollback(ctx, tsv.OpIndex()-1) allocates, writes = tsv.KeyOperations() - require.EqualValues(map[string]uint16{key2str: 2}, allocates) - require.EqualValues(map[string]uint16{key2str: 1}, writes) + require.Equal(map[string]uint16{key2str: 2}, allocates) + require.Equal(map[string]uint16{key2str: 1}, writes) require.Equal(tsv.pendingChangedKeys[key2str], maybe.Some(testVal)) // Rollback second insert tsv.Rollback(ctx, tsv.OpIndex()-1) allocates, writes = tsv.KeyOperations() - require.EqualValues(map[string]uint16{}, allocates) - require.EqualValues(map[string]uint16{}, writes) + require.Equal(map[string]uint16{}, allocates) + require.Equal(map[string]uint16{}, writes) require.NotContains(tsv.pendingChangedKeys, key2str) // Rollback remove tsv.Rollback(ctx, tsv.OpIndex()-1) allocates, writes = tsv.KeyOperations() - require.EqualValues(map[string]uint16{key2str: 2}, allocates) - require.EqualValues(map[string]uint16{key2str: 1}, writes) + require.Equal(map[string]uint16{key2str: 2}, allocates) + require.Equal(map[string]uint16{key2str: 1}, writes) require.Equal(tsv.pendingChangedKeys[key2str], maybe.Some(testVal)) // Rollback insert tsv.Rollback(ctx, tsv.OpIndex()-1) allocates, writes = tsv.KeyOperations() - require.EqualValues(map[string]uint16{}, allocates) - require.EqualValues(map[string]uint16{}, writes) + require.Equal(map[string]uint16{}, allocates) + require.Equal(map[string]uint16{}, writes) require.NotContains(tsv.pendingChangedKeys, key2str) require.Equal(0, tsv.OpIndex()) @@ -269,43 +269,43 @@ func TestModifyRemoveInsert(t *testing.T) { testVal2 := []byte("blah") require.NoError(tsv.Insert(ctx, key2, testVal2)) allocates, writes := tsv.KeyOperations() - require.EqualValues(map[string]uint16{}, allocates) - require.EqualValues(map[string]uint16{key2str: 1}, writes) + require.Equal(map[string]uint16{}, allocates) + require.Equal(map[string]uint16{key2str: 1}, writes) require.Equal(tsv.pendingChangedKeys[key2str], maybe.Some(testVal2)) // Remove modified key require.NoError(tsv.Remove(ctx, key2)) allocates, writes = tsv.KeyOperations() - require.EqualValues(map[string]uint16{}, allocates) - require.EqualValues(map[string]uint16{key2str: 0}, writes) + require.Equal(map[string]uint16{}, allocates) + require.Equal(map[string]uint16{key2str: 0}, writes) require.Equal(tsv.pendingChangedKeys[key2str], maybe.Nothing[[]byte]()) // Insert key again (with original value) require.NoError(tsv.Insert(ctx, key2, testVal)) allocates, writes = tsv.KeyOperations() - require.EqualValues(map[string]uint16{}, allocates) - require.EqualValues(map[string]uint16{}, writes) + require.Equal(map[string]uint16{}, allocates) + require.Equal(map[string]uint16{}, writes) require.NotContains(tsv.pendingChangedKeys, key2str) // Rollback insert tsv.Rollback(ctx, tsv.OpIndex()-1) allocates, writes = tsv.KeyOperations() - require.EqualValues(map[string]uint16{}, allocates) - require.EqualValues(map[string]uint16{key2str: 0}, writes) + require.Equal(map[string]uint16{}, allocates) + require.Equal(map[string]uint16{key2str: 0}, writes) require.Equal(tsv.pendingChangedKeys[key2str], maybe.Nothing[[]byte]()) // Rollback remove tsv.Rollback(ctx, tsv.OpIndex()-1) allocates, writes = tsv.KeyOperations() - require.EqualValues(map[string]uint16{}, allocates) - require.EqualValues(map[string]uint16{key2str: 1}, writes) + require.Equal(map[string]uint16{}, allocates) + require.Equal(map[string]uint16{key2str: 1}, writes) require.Equal(tsv.pendingChangedKeys[key2str], maybe.Some(testVal2)) // Rollback modify tsv.Rollback(ctx, tsv.OpIndex()-1) allocates, writes = tsv.KeyOperations() - require.EqualValues(map[string]uint16{}, allocates) - require.EqualValues(map[string]uint16{}, writes) + require.Equal(map[string]uint16{}, allocates) + require.Equal(map[string]uint16{}, writes) require.NotContains(tsv.pendingChangedKeys, key2str) require.Equal(0, tsv.OpIndex()) } @@ -323,29 +323,29 @@ func TestModifyRevert(t *testing.T) { testVal2 := []byte("blah") require.NoError(tsv.Insert(ctx, key2, testVal2)) allocates, writes := tsv.KeyOperations() - require.EqualValues(map[string]uint16{}, allocates) - require.EqualValues(map[string]uint16{key2str: 1}, writes) + require.Equal(map[string]uint16{}, allocates) + require.Equal(map[string]uint16{key2str: 1}, writes) require.Equal(tsv.pendingChangedKeys[key2str], maybe.Some(testVal2)) // Revert modification require.NoError(tsv.Insert(ctx, key2, testVal)) allocates, writes = tsv.KeyOperations() - require.EqualValues(map[string]uint16{}, allocates) - require.EqualValues(map[string]uint16{}, writes) + require.Equal(map[string]uint16{}, allocates) + require.Equal(map[string]uint16{}, writes) require.NotContains(tsv.pendingChangedKeys, key2str) // Rollback revert modification tsv.Rollback(ctx, tsv.OpIndex()-1) allocates, writes = tsv.KeyOperations() - require.EqualValues(map[string]uint16{}, allocates) - require.EqualValues(map[string]uint16{key2str: 1}, writes) + require.Equal(map[string]uint16{}, allocates) + require.Equal(map[string]uint16{key2str: 1}, writes) require.Equal(tsv.pendingChangedKeys[key2str], maybe.Some(testVal2)) // Rollback modification tsv.Rollback(ctx, tsv.OpIndex()-1) allocates, writes = tsv.KeyOperations() - require.EqualValues(map[string]uint16{}, allocates) - require.EqualValues(map[string]uint16{}, writes) + require.Equal(map[string]uint16{}, allocates) + require.Equal(map[string]uint16{}, writes) require.NotContains(tsv.pendingChangedKeys, key2str) require.Equal(0, tsv.OpIndex()) } @@ -363,36 +363,36 @@ func TestModifyModify(t *testing.T) { testVal2 := []byte("blah") require.NoError(tsv.Insert(ctx, key2, testVal2)) allocates, writes := tsv.KeyOperations() - require.EqualValues(map[string]uint16{}, allocates) - require.EqualValues(map[string]uint16{key2str: 1}, writes) + require.Equal(map[string]uint16{}, allocates) + require.Equal(map[string]uint16{key2str: 1}, writes) require.Equal(tsv.pendingChangedKeys[key2str], maybe.Some(testVal2)) // Perform same modification (no change) require.NoError(tsv.Insert(ctx, key2, testVal2)) allocates, writes = tsv.KeyOperations() - require.EqualValues(map[string]uint16{}, allocates) - require.EqualValues(map[string]uint16{key2str: 1}, writes) + require.Equal(map[string]uint16{}, allocates) + require.Equal(map[string]uint16{key2str: 1}, writes) require.Equal(tsv.pendingChangedKeys[key2str], maybe.Some(testVal2)) // Revert modification require.NoError(tsv.Insert(ctx, key2, testVal)) allocates, writes = tsv.KeyOperations() - require.EqualValues(map[string]uint16{}, allocates) - require.EqualValues(map[string]uint16{}, writes) + require.Equal(map[string]uint16{}, allocates) + require.Equal(map[string]uint16{}, writes) require.NotContains(tsv.pendingChangedKeys, key2str) // Rollback revert modification tsv.Rollback(ctx, tsv.OpIndex()-1) allocates, writes = tsv.KeyOperations() - require.EqualValues(map[string]uint16{}, allocates) - require.EqualValues(map[string]uint16{key2str: 1}, writes) + require.Equal(map[string]uint16{}, allocates) + require.Equal(map[string]uint16{key2str: 1}, writes) require.Equal(tsv.pendingChangedKeys[key2str], maybe.Some(testVal2)) // Rollback modification tsv.Rollback(ctx, tsv.OpIndex()-1) allocates, writes = tsv.KeyOperations() - require.EqualValues(map[string]uint16{}, allocates) - require.EqualValues(map[string]uint16{}, writes) + require.Equal(map[string]uint16{}, allocates) + require.Equal(map[string]uint16{}, writes) require.NotContains(tsv.pendingChangedKeys, key2str) require.Equal(0, tsv.OpIndex()) } @@ -458,8 +458,8 @@ func TestRestoreInsert(t *testing.T) { allocMap := map[string]uint16{key1str: 1, key2str: 2, key3str: 3} writeMap := map[string]uint16{key1str: 1, key2str: 1, key3str: 1} allocates, writes := tsv.KeyOperations() - require.EqualValues(allocMap, allocates) - require.EqualValues(writeMap, writes) + require.Equal(allocMap, allocates) + require.Equal(writeMap, writes) // Update keys[0] updatedVal := []byte("newVal") @@ -471,8 +471,8 @@ func TestRestoreInsert(t *testing.T) { // No change to KeyOperations allocates, writes = tsv.KeyOperations() - require.EqualValues(allocMap, allocates) - require.EqualValues(writeMap, writes) + require.Equal(allocMap, allocates) + require.Equal(writeMap, writes) // Rollback inserting updatedVal and key[2] tsv.Rollback(ctx, 2) @@ -489,8 +489,8 @@ func TestRestoreInsert(t *testing.T) { // Modifications rolled back allocates, writes = tsv.KeyOperations() - require.EqualValues(map[string]uint16{key1str: 1, key2str: 2}, allocates) - require.EqualValues(map[string]uint16{key1str: 1, key2str: 1}, writes) + require.Equal(map[string]uint16{key1str: 1, key2str: 2}, allocates) + require.Equal(map[string]uint16{key1str: 1, key2str: 1}, writes) } func TestRestoreDelete(t *testing.T) { @@ -542,7 +542,8 @@ func TestCreateView(t *testing.T) { ctx := context.TODO() ts := New(10) - tracer, _ := trace.New(&trace.Config{Enabled: false}) + tracer, err := trace.New(&trace.Config{Enabled: false}) + require.NoError(err) db, err := merkledb.New(ctx, memdb.New(), merkledb.Config{ BranchFactor: merkledb.BranchFactor16, RootGenConcurrency: 1, @@ -553,9 +554,7 @@ func TestCreateView(t *testing.T) { IntermediateWriteBatchSize: units.KiB, Tracer: tracer, }) - if err != nil { - t.Fatal(err) - } + require.NoError(err) keys := [][]byte{key1, key2, key3} keySet := state.Keys{ key1str: state.Read | state.Write, @@ -578,15 +577,15 @@ func TestCreateView(t *testing.T) { allocMap := map[string]uint16{key1str: 1, key2str: 2, key3str: 3} writeMap := map[string]uint16{key1str: 1, key2str: 1, key3str: 1} allocates, writes := tsv.KeyOperations() - require.EqualValues(allocMap, allocates) - require.EqualValues(writeMap, writes) + require.Equal(allocMap, allocates) + require.Equal(writeMap, writes) // Test warm modification tsvM := ts.NewView(keySet, map[string][]byte{}) require.NoError(tsvM.Insert(ctx, keys[0], vals[2])) allocates, writes = tsvM.KeyOperations() require.Empty(allocates) - require.EqualValues(map[string]uint16{key1str: 1}, writes) + require.Equal(map[string]uint16{key1str: 1}, writes) // Create merkle view view, err := ts.ExportMerkleDBView(ctx, tracer, db) diff --git a/tstate/tstate_view.go b/tstate/tstate_view.go index 00a6ebcd5b..b4e5c6b94d 100644 --- a/tstate/tstate_view.go +++ b/tstate/tstate_view.go @@ -9,6 +9,7 @@ import ( "github.com/ava-labs/avalanchego/database" "github.com/ava-labs/avalanchego/utils/maybe" + "github.com/ava-labs/hypersdk/keys" "github.com/ava-labs/hypersdk/state" ) diff --git a/utils/utils.go b/utils/utils.go index 2635e1aa4b..c19c780abb 100644 --- a/utils/utils.go +++ b/utils/utils.go @@ -16,8 +16,9 @@ import ( "github.com/ava-labs/avalanchego/ids" "github.com/ava-labs/avalanchego/utils/hashing" "github.com/ava-labs/avalanchego/utils/perms" + "github.com/onsi/ginkgo/v2/formatter" + "github.com/ava-labs/hypersdk/consts" - formatter "github.com/onsi/ginkgo/v2/formatter" ) func ToID(bytes []byte) ids.ID { diff --git a/utils/utils_test.go b/utils/utils_test.go index be9915fb1d..099eee3430 100644 --- a/utils/utils_test.go +++ b/utils/utils_test.go @@ -61,7 +61,7 @@ func TestLoadKeyInvalidFile(t *testing.T) { filename := "FileNameDoesntExist" _, err := LoadBytes(filename, ids.IDLen) - require.Error(err) + require.ErrorIs(err, os.ErrNotExist) } func TestLoadBytes(t *testing.T) { diff --git a/vm/dependencies.go b/vm/dependencies.go index a68c8b9ee3..a8d3211ea1 100644 --- a/vm/dependencies.go +++ b/vm/dependencies.go @@ -8,10 +8,8 @@ import ( "net/http" "time" - ametrics "github.com/ava-labs/avalanchego/api/metrics" "github.com/ava-labs/avalanchego/database" "github.com/ava-labs/avalanchego/snow" - atrace "github.com/ava-labs/avalanchego/trace" "github.com/ava-labs/avalanchego/utils/profiler" "github.com/ava-labs/avalanchego/x/merkledb" @@ -20,7 +18,10 @@ import ( "github.com/ava-labs/hypersdk/codec" "github.com/ava-labs/hypersdk/gossiper" "github.com/ava-labs/hypersdk/state" - trace "github.com/ava-labs/hypersdk/trace" + "github.com/ava-labs/hypersdk/trace" + + avametrics "github.com/ava-labs/avalanchego/api/metrics" + avatrace "github.com/ava-labs/avalanchego/trace" ) type Handlers map[string]http.Handler @@ -38,7 +39,7 @@ type Config interface { GetStateHistoryLength() int // how many roots back of data to keep to serve state queries GetIntermediateNodeCacheSize() int // how many bytes to keep in intermediate cache GetStateIntermediateWriteBufferSize() int // how many bytes to keep unwritten in intermediate cache - GetStateIntermediateWriteBatchSize() int // how many bytes to to write from intermediate cache at once + GetStateIntermediateWriteBatchSize() int // how many bytes to write from intermediate cache at once GetValueNodeCacheSize() int // how many bytes to keep in value cache GetAcceptorSize() int // how far back we can fall in processing accepted blocks GetStateSyncParallelism() int @@ -55,7 +56,7 @@ type Config interface { } type Genesis interface { - Load(context.Context, atrace.Tracer, state.Mutable) error + Load(context.Context, avatrace.Tracer, state.Mutable) error GetStateBranchFactor() merkledb.BranchFactor } @@ -69,7 +70,7 @@ type Controller interface { Initialize( inner *VM, // hypersdk VM snowCtx *snow.Context, - gatherer ametrics.MultiGatherer, + gatherer avametrics.MultiGatherer, genesisBytes []byte, upgradeBytes []byte, configBytes []byte, diff --git a/vm/metrics.go b/vm/metrics.go index 34d4d09f7c..faaae259db 100644 --- a/vm/metrics.go +++ b/vm/metrics.go @@ -6,8 +6,9 @@ package vm import ( "github.com/ava-labs/avalanchego/utils/metric" "github.com/ava-labs/avalanchego/utils/wrappers" - "github.com/ava-labs/hypersdk/executor" "github.com/prometheus/client_golang/prometheus" + + "github.com/ava-labs/hypersdk/executor" ) type executorMetrics struct { diff --git a/vm/resolutions.go b/vm/resolutions.go index 3ea54b5213..7a7146243c 100644 --- a/vm/resolutions.go +++ b/vm/resolutions.go @@ -15,7 +15,6 @@ import ( "github.com/ava-labs/avalanchego/utils/logging" "github.com/ava-labs/avalanchego/utils/set" "github.com/ava-labs/avalanchego/x/merkledb" - "go.uber.org/zap" "github.com/ava-labs/hypersdk/builder" diff --git a/vm/syncervm_client.go b/vm/syncervm_client.go index 2e829c861c..0e4b8c68e0 100644 --- a/vm/syncervm_client.go +++ b/vm/syncervm_client.go @@ -8,20 +8,21 @@ import ( "errors" "sync" - ametrics "github.com/ava-labs/avalanchego/api/metrics" "github.com/ava-labs/avalanchego/database" "github.com/ava-labs/avalanchego/snow/engine/snowman/block" - syncEng "github.com/ava-labs/avalanchego/x/sync" "github.com/prometheus/client_golang/prometheus" "go.uber.org/zap" "github.com/ava-labs/hypersdk/chain" + + avametrics "github.com/ava-labs/avalanchego/api/metrics" + avasync "github.com/ava-labs/avalanchego/x/sync" ) type stateSyncerClient struct { vm *VM - gatherer ametrics.MultiGatherer - syncManager *syncEng.Manager + gatherer avametrics.MultiGatherer + syncManager *avasync.Manager // tracks the sync target so we can update last accepted // block when sync completes. @@ -38,7 +39,7 @@ type stateSyncerClient struct { // TODO: break out into own package func (vm *VM) NewStateSyncClient( - gatherer ametrics.MultiGatherer, + gatherer avametrics.MultiGatherer, ) *stateSyncerClient { return &stateSyncerClient{ vm: vm, @@ -120,14 +121,14 @@ func (s *stateSyncerClient) AcceptedSyncableBlock( // Initialize metrics for sync client r := prometheus.NewRegistry() - metrics, err := syncEng.NewMetrics("sync_client", r) + metrics, err := avasync.NewMetrics("sync_client", r) if err != nil { return block.StateSyncSkipped, err } if err := s.gatherer.Register("syncer", r); err != nil { return block.StateSyncSkipped, err } - syncClient, err := syncEng.NewClient(&syncEng.ClientConfig{ + syncClient, err := avasync.NewClient(&avasync.ClientConfig{ BranchFactor: s.vm.genesis.GetStateBranchFactor(), NetworkClient: s.vm.stateSyncNetworkClient, Log: s.vm.snowCtx.Log, @@ -137,7 +138,7 @@ func (s *stateSyncerClient) AcceptedSyncableBlock( if err != nil { return block.StateSyncSkipped, err } - s.syncManager, err = syncEng.NewManager(syncEng.ManagerConfig{ + s.syncManager, err = avasync.NewManager(avasync.ManagerConfig{ BranchFactor: s.vm.genesis.GetStateBranchFactor(), DB: s.vm.stateDB, Client: syncClient, @@ -258,7 +259,7 @@ func (s *stateSyncerClient) StateReady() bool { // updated and an error if one occurred while updating the root. func (s *stateSyncerClient) UpdateSyncTarget(b *chain.StatelessBlock) (bool, error) { err := s.syncManager.UpdateSyncTarget(b.StateRoot) - if errors.Is(err, syncEng.ErrAlreadyClosed) { + if errors.Is(err, avasync.ErrAlreadyClosed) { <-s.done // Wait for goroutine to exit for consistent return values with IsSyncing return false, nil // Sync finished before update } diff --git a/vm/syncervm_server.go b/vm/syncervm_server.go index 9ba1011a7f..d36f9fedef 100644 --- a/vm/syncervm_server.go +++ b/vm/syncervm_server.go @@ -8,8 +8,9 @@ import ( "github.com/ava-labs/avalanchego/snow/choices" "github.com/ava-labs/avalanchego/snow/engine/snowman/block" - "github.com/ava-labs/hypersdk/chain" "go.uber.org/zap" + + "github.com/ava-labs/hypersdk/chain" ) // GetLastStateSummary returns the latest state summary. diff --git a/vm/verify_context.go b/vm/verify_context.go index 8d35912ee9..734189806e 100644 --- a/vm/verify_context.go +++ b/vm/verify_context.go @@ -9,6 +9,7 @@ import ( "github.com/ava-labs/avalanchego/ids" "github.com/ava-labs/avalanchego/utils/set" + "github.com/ava-labs/hypersdk/chain" "github.com/ava-labs/hypersdk/state" ) diff --git a/vm/vm.go b/vm/vm.go index 760e8a8c59..c47fec0f19 100644 --- a/vm/vm.go +++ b/vm/vm.go @@ -11,29 +11,23 @@ import ( "sync" "time" - ametrics "github.com/ava-labs/avalanchego/api/metrics" - "github.com/ava-labs/avalanchego/cache" "github.com/ava-labs/avalanchego/database" "github.com/ava-labs/avalanchego/ids" "github.com/ava-labs/avalanchego/snow" "github.com/ava-labs/avalanchego/snow/choices" "github.com/ava-labs/avalanchego/snow/consensus/snowman" "github.com/ava-labs/avalanchego/snow/engine/common" - smblock "github.com/ava-labs/avalanchego/snow/engine/snowman/block" - "github.com/ava-labs/avalanchego/trace" - "github.com/ava-labs/avalanchego/utils" + "github.com/ava-labs/avalanchego/snow/engine/snowman/block" "github.com/ava-labs/avalanchego/utils/crypto/bls" "github.com/ava-labs/avalanchego/utils/profiler" "github.com/ava-labs/avalanchego/utils/set" "github.com/ava-labs/avalanchego/version" "github.com/ava-labs/avalanchego/x/merkledb" - syncEng "github.com/ava-labs/avalanchego/x/sync" - hcache "github.com/ava-labs/hypersdk/cache" "github.com/prometheus/client_golang/prometheus" - "go.uber.org/zap" "github.com/ava-labs/hypersdk/builder" + "github.com/ava-labs/hypersdk/cache" "github.com/ava-labs/hypersdk/chain" "github.com/ava-labs/hypersdk/emap" "github.com/ava-labs/hypersdk/fees" @@ -42,9 +36,15 @@ import ( "github.com/ava-labs/hypersdk/network" "github.com/ava-labs/hypersdk/rpc" "github.com/ava-labs/hypersdk/state" - htrace "github.com/ava-labs/hypersdk/trace" - hutils "github.com/ava-labs/hypersdk/utils" + "github.com/ava-labs/hypersdk/trace" + "github.com/ava-labs/hypersdk/utils" "github.com/ava-labs/hypersdk/workers" + + avametrics "github.com/ava-labs/avalanchego/api/metrics" + avacache "github.com/ava-labs/avalanchego/cache" + avatrace "github.com/ava-labs/avalanchego/trace" + avautils "github.com/ava-labs/avalanchego/utils" + avasync "github.com/ava-labs/avalanchego/x/sync" ) type VM struct { @@ -68,7 +68,7 @@ type VM struct { authRegistry chain.AuthRegistry authEngine map[uint8]AuthEngine - tracer trace.Tracer + tracer avatrace.Tracer mempool *mempool.Mempool[*chain.Transaction] // track all accepted but still valid txs (replay protection) @@ -78,7 +78,7 @@ type VM struct { seenValidityWindow chan struct{} // We cannot use a map here because we may parse blocks up in the ancestry - parsedBlocks *cache.LRU[ids.ID, *chain.StatelessBlock] + parsedBlocks *avacache.LRU[ids.ID, *chain.StatelessBlock] // Each element is a block that passed verification but // hasn't yet been accepted/rejected @@ -87,8 +87,8 @@ type VM struct { // We store the last [AcceptedBlockWindowCache] blocks in memory // to avoid reading blocks from disk. - acceptedBlocksByID *hcache.FIFO[ids.ID, *chain.StatelessBlock] - acceptedBlocksByHeight *hcache.FIFO[uint64, ids.ID] + acceptedBlocksByID *cache.FIFO[ids.ID, *chain.StatelessBlock] + acceptedBlocksByHeight *cache.FIFO[uint64, ids.ID] // Accepted block queue acceptedQueue chan *chain.StatelessBlock @@ -101,7 +101,7 @@ type VM struct { // with limited parallelism authVerifiers workers.Workers - bootstrapped utils.Atomic[bool] + bootstrapped avautils.Atomic[bool] genesisBlk *chain.StatelessBlock preferred ids.ID lastAccepted *chain.StatelessBlock @@ -109,8 +109,8 @@ type VM struct { // State Sync client and AppRequest handlers stateSyncClient *stateSyncerClient - stateSyncNetworkClient syncEng.NetworkClient - stateSyncNetworkServer *syncEng.NetworkServer + stateSyncNetworkClient avasync.NetworkClient + stateSyncNetworkServer *avasync.NetworkServer // Warp manager fetches signatures from other validators for a given accepted // txID @@ -152,7 +152,7 @@ func (vm *VM) Initialize( vm.seenValidityWindow = make(chan struct{}) vm.ready = make(chan struct{}) vm.stop = make(chan struct{}) - gatherer := ametrics.NewMultiGatherer() + gatherer := avametrics.NewMultiGatherer() if err := vm.snowCtx.Metrics.Register(gatherer); err != nil { return err } @@ -188,7 +188,7 @@ func (vm *VM) Initialize( } // Setup tracer - vm.tracer, err = htrace.New(vm.config.GetTraceConfig()) + vm.tracer, err = trace.New(vm.config.GetTraceConfig()) if err != nil { return err } @@ -233,13 +233,13 @@ func (vm *VM) Initialize( // Init channels before initializing other structs vm.toEngine = toEngine - vm.parsedBlocks = &cache.LRU[ids.ID, *chain.StatelessBlock]{Size: vm.config.GetParsedBlockCacheSize()} + vm.parsedBlocks = &avacache.LRU[ids.ID, *chain.StatelessBlock]{Size: vm.config.GetParsedBlockCacheSize()} vm.verifiedBlocks = make(map[ids.ID]*chain.StatelessBlock) - vm.acceptedBlocksByID, err = hcache.NewFIFO[ids.ID, *chain.StatelessBlock](vm.config.GetAcceptedBlockWindowCache()) + vm.acceptedBlocksByID, err = cache.NewFIFO[ids.ID, *chain.StatelessBlock](vm.config.GetAcceptedBlockWindowCache()) if err != nil { return err } - vm.acceptedBlocksByHeight, err = hcache.NewFIFO[uint64, ids.ID](vm.config.GetAcceptedBlockWindowCache()) + vm.acceptedBlocksByHeight, err = cache.NewFIFO[uint64, ids.ID](vm.config.GetAcceptedBlockWindowCache()) if err != nil { return err } @@ -362,7 +362,7 @@ func (vm *VM) Initialize( // Setup state syncing stateSyncHandler, stateSyncSender := vm.networkManager.Register() syncRegistry := prometheus.NewRegistry() - vm.stateSyncNetworkClient, err = syncEng.NewNetworkClient( + vm.stateSyncNetworkClient, err = avasync.NewNetworkClient( stateSyncSender, vm.snowCtx.NodeID, int64(vm.config.GetStateSyncParallelism()), @@ -377,7 +377,7 @@ func (vm *VM) Initialize( return err } vm.stateSyncClient = vm.NewStateSyncClient(gatherer) - vm.stateSyncNetworkServer = syncEng.NewNetworkServer(stateSyncSender, vm.stateDB, vm.Logger()) + vm.stateSyncNetworkServer = avasync.NewNetworkServer(stateSyncSender, vm.stateDB, vm.Logger()) vm.networkManager.SetHandler(stateSyncHandler, NewStateSyncHandler(vm)) // Setup gossip networking @@ -465,7 +465,7 @@ func (vm *VM) BaseDB() database.Database { func (vm *VM) ReadState(ctx context.Context, keys [][]byte) ([][]byte, []error) { if !vm.isReady() { - return hutils.Repeat[[]byte](nil, len(keys)), hutils.Repeat(ErrNotReady, len(keys)) + return utils.Repeat[[]byte](nil, len(keys)), utils.Repeat(ErrNotReady, len(keys)) } // Atomic read to ensure consistency return vm.stateDB.GetValues(ctx, keys) @@ -675,7 +675,7 @@ func (vm *VM) ParseBlock(ctx context.Context, source []byte) (snowman.Block, err defer span.End() // Check to see if we've already parsed - id := hutils.ToID(source) + id := utils.ToID(source) // If we have seen this block before, return it with the most // up-to-date info @@ -708,7 +708,7 @@ func (vm *VM) ParseBlock(ctx context.Context, source []byte) (snowman.Block, err return newBlk, nil } -func (vm *VM) buildBlock(ctx context.Context, blockContext *smblock.Context) (snowman.Block, error) { +func (vm *VM) buildBlock(ctx context.Context, blockContext *block.Context) (snowman.Block, error) { // If the node isn't ready, we should exit. // // We call [QueueNotify] when the VM becomes ready, so exiting @@ -763,7 +763,7 @@ func (vm *VM) BuildBlock(ctx context.Context) (snowman.Block, error) { } // implements "block.BuildBlockWithContextChainVM" -func (vm *VM) BuildBlockWithContext(ctx context.Context, blockContext *smblock.Context) (snowman.Block, error) { +func (vm *VM) BuildBlockWithContext(ctx context.Context, blockContext *block.Context) (snowman.Block, error) { start := time.Now() defer func() { vm.metrics.blockBuild.Observe(float64(time.Since(start))) diff --git a/vm/vm_test.go b/vm/vm_test.go index 450b4bc63a..623abe2684 100644 --- a/vm/vm_test.go +++ b/vm/vm_test.go @@ -7,7 +7,7 @@ import ( "context" "testing" - ametrics "github.com/ava-labs/avalanchego/api/metrics" + "github.com/ava-labs/avalanchego/api/metrics" "github.com/ava-labs/avalanchego/database/memdb" "github.com/ava-labs/avalanchego/ids" "github.com/ava-labs/avalanchego/snow" @@ -15,7 +15,7 @@ import ( "github.com/stretchr/testify/require" "go.uber.org/mock/gomock" - hcache "github.com/ava-labs/hypersdk/cache" + "github.com/ava-labs/hypersdk/cache" "github.com/ava-labs/hypersdk/chain" "github.com/ava-labs/hypersdk/config" "github.com/ava-labs/hypersdk/emap" @@ -38,11 +38,11 @@ func TestBlockCache(t *testing.T) { blkID := blk.ID() tracer, _ := trace.New(&trace.Config{Enabled: false}) - bByID, _ := hcache.NewFIFO[ids.ID, *chain.StatelessBlock](3) - bByHeight, _ := hcache.NewFIFO[uint64, ids.ID](3) + bByID, _ := cache.NewFIFO[ids.ID, *chain.StatelessBlock](3) + bByHeight, _ := cache.NewFIFO[uint64, ids.ID](3) controller := NewMockController(ctrl) vm := VM{ - snowCtx: &snow.Context{Log: logging.NoLog{}, Metrics: ametrics.NewOptionalGatherer()}, + snowCtx: &snow.Context{Log: logging.NoLog{}, Metrics: metrics.NewOptionalGatherer()}, config: &config.Config{}, vmDB: memdb.New(), @@ -59,7 +59,7 @@ func TestBlockCache(t *testing.T) { } // Init metrics (called in [Accepted]) - gatherer := ametrics.NewMultiGatherer() + gatherer := metrics.NewMultiGatherer() reg, m, err := newMetrics() require.NoError(err) vm.metrics = m diff --git a/vm/warp_manager.go b/vm/warp_manager.go index 1ae4cf5fad..13c851e277 100644 --- a/vm/warp_manager.go +++ b/vm/warp_manager.go @@ -14,12 +14,13 @@ import ( "github.com/ava-labs/avalanchego/snow/engine/common" "github.com/ava-labs/avalanchego/utils/crypto/bls" "github.com/ava-labs/avalanchego/utils/set" + "go.uber.org/zap" + "github.com/ava-labs/hypersdk/chain" "github.com/ava-labs/hypersdk/codec" "github.com/ava-labs/hypersdk/consts" "github.com/ava-labs/hypersdk/heap" "github.com/ava-labs/hypersdk/utils" - "go.uber.org/zap" ) const ( diff --git a/window/window.go b/window/window.go index ae14ce6b6b..f77847e454 100644 --- a/window/window.go +++ b/window/window.go @@ -7,6 +7,7 @@ import ( "encoding/binary" "github.com/ava-labs/avalanchego/utils/math" + "github.com/ava-labs/hypersdk/consts" ) diff --git a/window/window_test.go b/window/window_test.go index 03823d4146..34ed5b2da2 100644 --- a/window/window_test.go +++ b/window/window_test.go @@ -7,10 +7,13 @@ import ( "encoding/binary" "testing" + "github.com/stretchr/testify/require" + "github.com/ava-labs/hypersdk/consts" ) func testRollup(t *testing.T, uint64s []uint64, roll int) { + require := require.New(t) slice := [WindowSliceSize]byte{} numUint64s := len(uint64s) for i := 0; i < numUint64s; i++ { @@ -18,9 +21,7 @@ func testRollup(t *testing.T, uint64s []uint64, roll int) { } newSlice, err := Roll(slice, roll) - if err != nil { - t.Fatal(err) - } + require.NoError(err) // numCopies is the number of uint64s that should have been copied over from the previous // slice as opposed to being left empty. numCopies := numUint64s - roll @@ -31,20 +32,12 @@ func testRollup(t *testing.T, uint64s []uint64, roll int) { // over from the previous slice, assert that the value encoded in [newSlice] // is 0 if i >= numCopies { - if num != 0 { - t.Errorf( - "Expected num encoded in newSlice at position %d to be 0, but found %d", - i, - num, - ) - } + require.Zero(num, "position=%d", i) } else { // Otherwise, check that the value was copied over correctly prevIndex := i + roll prevNum := uint64s[prevIndex] - if prevNum != num { - t.Errorf("Expected num encoded in new slice at position %d to be %d, but found %d", i, prevNum, num) - } + require.Equal(prevNum, num, "position=%d", i) } } } @@ -92,6 +85,7 @@ func TestRollupWindow(t *testing.T) { } func TestUint64Window(t *testing.T) { + require := require.New(t) uint64s := []uint64{1, 2, 3, 4, 5, 6, 7, 8, 9, 10} sumUint64s := uint64(0) uint64Window := Window{} @@ -101,9 +95,7 @@ func TestUint64Window(t *testing.T) { } sum := Sum(uint64Window) - if sum != sumUint64s { - t.Fatalf("Expected sum to be %d but found %d", sumUint64s, sum) - } + require.Equal(sumUint64s, sum) for i := 0; i < 10; i++ { iu64 := uint64(i) @@ -111,13 +103,12 @@ func TestUint64Window(t *testing.T) { sum = Sum(uint64Window) sumUint64s += iu64 - if sum != sumUint64s { - t.Fatalf("Expected sum to be %d but found %d (iteration: %d)", sumUint64s, sum, i) - } + require.Equal(sumUint64s, sum, "i=%d", i) } } func TestUint64WindowOverflow(t *testing.T) { + require := require.New(t) uint64s := []uint64{0, 0, 0, 0, 0, 0, 0, 0, 2, consts.MaxUint64 - 1} uint64Window := Window{} for i, uint64 := range uint64s { @@ -125,16 +116,12 @@ func TestUint64WindowOverflow(t *testing.T) { } sum := Sum(uint64Window) - if sum != consts.MaxUint64 { - t.Fatalf("Expected sum to be maxUint64 (%d), but found %d", consts.MaxUint64, sum) - } + require.Equal(consts.MaxUint64, sum) for i := 0; i < 10; i++ { Update(&uint64Window, i*8, uint64(i)) sum = Sum(uint64Window) - if sum != consts.MaxUint64 { - t.Fatalf("Expected sum to be maxUint64 (%d), but found %d", consts.MaxUint64, sum) - } + require.Equal(consts.MaxUint64, sum) } } diff --git a/workers/parallel_workers_test.go b/workers/parallel_workers_test.go index 275652e559..faafae99b7 100644 --- a/workers/parallel_workers_test.go +++ b/workers/parallel_workers_test.go @@ -13,10 +13,9 @@ import ( "testing" "time" - "github.com/stretchr/testify/require" - "github.com/ava-labs/avalanchego/utils/hashing" "github.com/neilotoole/errgroup" + "github.com/stretchr/testify/require" "golang.org/x/sync/semaphore" ) diff --git a/x/programs/engine/config.go b/x/programs/engine/config.go index 6604c7d151..31d6feb7e0 100644 --- a/x/programs/engine/config.go +++ b/x/programs/engine/config.go @@ -5,7 +5,6 @@ package engine import ( "github.com/ava-labs/avalanchego/utils/units" - "github.com/bytecodealliance/wasmtime-go/v14" ) @@ -202,37 +201,37 @@ type ConfigBuilder struct { // memory.copy instruction, passive data/table segments, etc, being in a // module. // This is false by default. - EnableBulkMemory bool `yaml:"enable_bulk_memory,omitempty" json:"enableBulkMemory,omitempty"` + EnableBulkMemory bool `json:"enableBulkMemory,omitempty" yaml:"enable_bulk_memory,omitempty"` // Configures whether the WebAssembly multi-value proposal will be enabled for compilation. // This feature gates functions and blocks returning multiple values in a module, for example. // This is false by default. - EnableWasmMultiValue bool `yaml:"enable_wasm_multi_value,omitempty" json:"enableWasmMultiValue,omitempty"` + EnableWasmMultiValue bool `json:"enableWasmMultiValue,omitempty" yaml:"enable_wasm_multi_value,omitempty"` // Configures whether the WebAssembly reference types proposal will be // enabled for compilation. This feature gates items such as the externref // and funcref types as well as allowing a module to define multiple tables. // Note that the reference types proposal depends on the bulk memory // proposal. // This is false by default. - EnableWasmReferenceTypes bool `yaml:"enable_wasm_reference_types,omitempty" json:"enableWasmReferenceTypes,omitempty"` + EnableWasmReferenceTypes bool `json:"enableWasmReferenceTypes,omitempty" yaml:"enable_wasm_reference_types,omitempty"` // Configures whether the WebAssembly SIMD proposal will be enabled for // compilation. The WebAssembly SIMD proposal. This feature gates items // such as the v128 type and all of its operators being in a module. Note // that this does not enable the relaxed simd proposal. // This is false by default. - EnableWasmSIMD bool `yaml:"enable_wasm_simd,omitempty" json:"enableWasmSIMD,omitempty"` + EnableWasmSIMD bool `json:"enableWasmSIMD,omitempty" yaml:"enable_wasm_simd,omitempty"` // EnableDefaultCache enables compiled code caching for this `Config` using the default settings // configuration can be found. // // For more information about caching see // https://bytecodealliance.github.io/wasmtime/cli-cache.html // This is false by default. - EnableDefaultCache bool `yaml:"enable_default_cache,omitempty" json:"enableDefaultCache,omitempty"` + EnableDefaultCache bool `json:"enableDefaultCache,omitempty" yaml:"enable_default_cache,omitempty"` // SetMaxWasmStack configures the maximum stack size, in bytes, that JIT code can use. // The amount of stack space that wasm takes is always relative to the first invocation of wasm on the stack. // Recursive calls with host frames in the middle will all need to fit within this setting. // Note that this setting is not interpreted with 100% precision. // This is 256 MiB by default. - MaxWasmStack int `yaml:"max_wasm_stack,omitempty" json:"maxWasmStack,omitempty"` + MaxWasmStack int `json:"maxWasmStack,omitempty" yaml:"max_wasm_stack,omitempty"` // ProfilingStrategy decides what sort of profiling to enable, if any. // Default is `wasmtime.ProfilingStrategyNone`. ProfilingStrategy wasmtime.ProfilingStrategy diff --git a/x/programs/engine/engine.go b/x/programs/engine/engine.go index 35da2ab0aa..9891381b74 100644 --- a/x/programs/engine/engine.go +++ b/x/programs/engine/engine.go @@ -4,7 +4,7 @@ package engine import ( - "fmt" + "errors" "github.com/bytecodealliance/wasmtime-go/v14" ) @@ -67,6 +67,6 @@ func NewModule(engine *Engine, bytes []byte, strategy CompileStrategy) (*wasmtim case PrecompiledWasm: return engine.PreCompileModule(bytes) default: - return nil, fmt.Errorf("unknown compile strategy") + return nil, errors.New("unknown compile strategy") } } diff --git a/x/programs/engine/engine_test.go b/x/programs/engine/engine_test.go index fe46f5e575..d0724f494b 100644 --- a/x/programs/engine/engine_test.go +++ b/x/programs/engine/engine_test.go @@ -4,11 +4,12 @@ package engine import ( - _ "embed" "testing" "github.com/stretchr/testify/require" + _ "embed" + "github.com/ava-labs/hypersdk/x/programs/tests" ) diff --git a/x/programs/engine/store.go b/x/programs/engine/store.go index dabea94fda..e8bd12f264 100644 --- a/x/programs/engine/store.go +++ b/x/programs/engine/store.go @@ -81,7 +81,7 @@ func (s *Store) GetMaxUnits() uint64 { func (s *Store) GetBalanceUnits() (uint64, error) { consumed, ok := s.UnitsConsumed() if !ok { - return 0, fmt.Errorf("failed to get units consumed: metering not enabled") + return 0, errors.New("failed to get units consumed: metering not enabled") } return (s.maxUnits - consumed), nil } diff --git a/x/programs/examples/counter_test.go b/x/programs/examples/counter_test.go index bee659dfc9..9ed2c8bb14 100644 --- a/x/programs/examples/counter_test.go +++ b/x/programs/examples/counter_test.go @@ -8,11 +8,11 @@ import ( "os" "testing" + "github.com/ava-labs/avalanchego/ids" + "github.com/ava-labs/avalanchego/utils/logging" "github.com/stretchr/testify/require" "go.uber.org/zap" - "github.com/ava-labs/avalanchego/ids" - "github.com/ava-labs/avalanchego/utils/logging" "github.com/ava-labs/hypersdk/x/programs/engine" "github.com/ava-labs/hypersdk/x/programs/examples/imports/program" "github.com/ava-labs/hypersdk/x/programs/examples/imports/pstate" @@ -70,11 +70,11 @@ func TestCounterProgram(t *testing.T) { require.NoError(err) // generate alice keys - _, aliceKey, err := newKey() + alicePublicKey, err := newKey() require.NoError(err) // write alice's key to stack and get pointer - alicePtr, err := argumentToSmartPtr(aliceKey, mem) + alicePtr, err := argumentToSmartPtr(alicePublicKey, mem) require.NoError(err) // create counter for alice on program 1 @@ -113,7 +113,7 @@ func TestCounterProgram(t *testing.T) { require.NoError(err) // write alice's key to stack and get pointer - alicePtr2, err := argumentToSmartPtr(aliceKey, mem2) + alicePtr2, err := argumentToSmartPtr(alicePublicKey, mem2) require.NoError(err) // initialize counter for alice on runtime 2 diff --git a/x/programs/examples/imports/program/program.go b/x/programs/examples/imports/program/program.go index fcd5337522..f2f6428d63 100644 --- a/x/programs/examples/imports/program/program.go +++ b/x/programs/examples/imports/program/program.go @@ -7,15 +7,13 @@ import ( "context" "encoding/binary" - "go.uber.org/zap" - "github.com/ava-labs/avalanchego/ids" "github.com/ava-labs/avalanchego/utils/logging" "github.com/bytecodealliance/wasmtime-go/v14" + "go.uber.org/zap" "github.com/ava-labs/hypersdk/consts" "github.com/ava-labs/hypersdk/state" - "github.com/ava-labs/hypersdk/x/programs/engine" "github.com/ava-labs/hypersdk/x/programs/examples/storage" "github.com/ava-labs/hypersdk/x/programs/host" @@ -47,7 +45,7 @@ func New(log logging.Logger, engine *engine.Engine, mu state.Mutable, cfg *runti } } -func (i *Import) Name() string { +func (*Import) Name() string { return Name } @@ -166,8 +164,7 @@ func (i *Import) callProgramFn( return -1 } - function_name := string(functionBytes) - res, err := rt.Call(ctx, function_name, params...) + res, err := rt.Call(ctx, string(functionBytes), params...) if err != nil { i.log.Error("failed to call entry function", zap.Error(err), @@ -175,17 +172,17 @@ func (i *Import) callProgramFn( return -1 } - return int64(res[0]) + return res[0] } // getCallArgs returns the arguments to be passed to the program being invoked from [buffer]. -func getCallArgs(ctx context.Context, memory *program.Memory, buffer []byte, programIDBytes []byte) ([]program.SmartPtr, error) { +func getCallArgs(_ context.Context, memory *program.Memory, buffer []byte, programIDBytes []byte) ([]program.SmartPtr, error) { // first arg contains id of program to call invokeProgramIDPtr, err := program.WriteBytes(memory, programIDBytes) if err != nil { return nil, err } - argPtr, err := program.NewSmartPtr(uint32(invokeProgramIDPtr), len(programIDBytes)) + argPtr, err := program.NewSmartPtr(invokeProgramIDPtr, len(programIDBytes)) if err != nil { return nil, err } @@ -205,7 +202,7 @@ func getCallArgs(ctx context.Context, memory *program.Memory, buffer []byte, pro if err != nil { return nil, err } - argPtr, err := program.NewSmartPtr(uint32(ptr), int(length)) + argPtr, err := program.NewSmartPtr(ptr, int(length)) if err != nil { return nil, err } diff --git a/x/programs/examples/imports/pstate/pstate.go b/x/programs/examples/imports/pstate/pstate.go index 3f442d0e1f..3e586f3d14 100644 --- a/x/programs/examples/imports/pstate/pstate.go +++ b/x/programs/examples/imports/pstate/pstate.go @@ -7,10 +7,9 @@ import ( "context" "errors" - "go.uber.org/zap" - "github.com/ava-labs/avalanchego/database" "github.com/ava-labs/avalanchego/utils/logging" + "go.uber.org/zap" "github.com/ava-labs/hypersdk/state" "github.com/ava-labs/hypersdk/x/programs/engine" @@ -37,7 +36,7 @@ type Import struct { meter *engine.Meter } -func (i *Import) Name() string { +func (*Import) Name() string { return Name } @@ -90,7 +89,6 @@ func (i *Import) putFn(caller *program.Caller, id int64, key int64, value int64) } valueBytes, err := program.SmartPtr(value).Bytes(memory) - if err != nil { i.log.Error("failed to read value from memory", zap.Error(err), @@ -163,7 +161,7 @@ func (i *Import) getFn(caller *program.Caller, id int64, key int64) (*types.Val, } return nil, err } - argPtr, err := program.NewSmartPtr(uint32(ptr), len(val)) + argPtr, err := program.NewSmartPtr(ptr, len(val)) if err != nil { i.log.Error("failed to convert ptr to argument", zap.Error(err), diff --git a/x/programs/examples/imports/wrap/wrap.go b/x/programs/examples/imports/wrap/wrap.go index 9ec3b5f6d7..deb8f71213 100644 --- a/x/programs/examples/imports/wrap/wrap.go +++ b/x/programs/examples/imports/wrap/wrap.go @@ -4,7 +4,7 @@ package wrap import ( - "fmt" + "errors" "github.com/bytecodealliance/wasmtime-go/v14" @@ -45,7 +45,7 @@ func (i ImportFn[F]) Invoke(c *program.Caller, args ...int64) (*types.Val, error case AnyParamFn: return fn.Call(c, args...) default: - return nil, fmt.Errorf("unsupported function type") + return nil, errors.New("unsupported function type") } } diff --git a/x/programs/examples/storage/storage.go b/x/programs/examples/storage/storage.go index 9cf6ab3a96..7fef5ae0e4 100644 --- a/x/programs/examples/storage/storage.go +++ b/x/programs/examples/storage/storage.go @@ -9,6 +9,7 @@ import ( "github.com/ava-labs/avalanchego/database" "github.com/ava-labs/avalanchego/ids" + "github.com/ava-labs/hypersdk/consts" "github.com/ava-labs/hypersdk/state" ) @@ -20,8 +21,8 @@ const ( func ProgramPrefixKey(id []byte, key []byte) (k []byte) { k = make([]byte, consts.IDLen+1+len(key)) k[0] = programPrefix - copy(k, id[:]) - copy(k[consts.IDLen:], (key[:])) + copy(k, id) + copy(k[consts.IDLen:], (key)) return } diff --git a/x/programs/examples/token.go b/x/programs/examples/token.go index a30ddecdf8..a412714aea 100644 --- a/x/programs/examples/token.go +++ b/x/programs/examples/token.go @@ -7,10 +7,9 @@ import ( "context" "fmt" - "go.uber.org/zap" - "github.com/ava-labs/avalanchego/ids" "github.com/ava-labs/avalanchego/utils/logging" + "go.uber.org/zap" "github.com/ava-labs/hypersdk/crypto/ed25519" "github.com/ava-labs/hypersdk/state" @@ -105,25 +104,25 @@ func (t *Token) Run(ctx context.Context) error { ) // generate alice keys - _, aliceKey, err := newKey() + alicePublicKey, err := newKey() if err != nil { return err } // write alice's key to stack and get pointer - alicePtr, err := argumentToSmartPtr(aliceKey, mem) + alicePtr, err := argumentToSmartPtr(alicePublicKey, mem) if err != nil { return err } // generate bob keys - _, bobKey, err := newKey() + bobPublicKey, err := newKey() if err != nil { return err } // write bob's key to stack and get pointer - bobPtr, err := argumentToSmartPtr(bobKey, mem) + bobPtr, err := argumentToSmartPtr(bobPublicKey, mem) if err != nil { return err } @@ -134,7 +133,7 @@ func (t *Token) Run(ctx context.Context) error { return err } t.log.Debug("balance", - zap.Int64("bob", int64(result[0])), + zap.Int64("bob", result[0]), ) // mint 100 tokens to alice @@ -227,11 +226,11 @@ func (t *Token) Run(ctx context.Context) error { // combine alice and bobs addresses minters := []minter{ { - To: aliceKey, + To: alicePublicKey, Amount: 10, }, { - To: bobKey, + To: bobPublicKey, Amount: 12, }, } diff --git a/x/programs/examples/token_test.go b/x/programs/examples/token_test.go index 4441976a1a..d7bf46a9ea 100644 --- a/x/programs/examples/token_test.go +++ b/x/programs/examples/token_test.go @@ -8,9 +8,8 @@ import ( "os" "testing" - "github.com/stretchr/testify/require" - "github.com/ava-labs/avalanchego/utils/logging" + "github.com/stretchr/testify/require" "github.com/ava-labs/hypersdk/x/programs/engine" "github.com/ava-labs/hypersdk/x/programs/examples/imports/pstate" @@ -25,16 +24,13 @@ func TestTokenProgram(t *testing.T) { require := require.New(t) maxUnits := uint64(80000) eng := engine.New(engine.NewConfig()) - program, err := newTokenProgram(maxUnits, eng, runtime.NewConfig(), wasmBytes) - require.NoError(err) - err = program.Run(context.Background()) - require.NoError(err) + program := newTokenProgram(maxUnits, eng, runtime.NewConfig(), wasmBytes) + require.NoError(program.Run(context.Background())) } // go test -v -benchmem -run=^$ -bench ^BenchmarkTokenProgram$ github.com/ava-labs/hypersdk/x/programs/examples -memprofile benchvset.mem -cpuprofile benchvset.cpu func BenchmarkTokenProgram(b *testing.B) { wasmBytes := tests.ReadFixture(b, "../tests/fixture/token.wasm") - require := require.New(b) maxUnits := uint64(80000) cfg := runtime.NewConfig(). @@ -43,28 +39,24 @@ func BenchmarkTokenProgram(b *testing.B) { ecfg, err := engine.NewConfigBuilder(). WithDefaultCache(true). Build() - require.NoError(err) + require.NoError(b, err) eng := engine.New(ecfg) b.Run("benchmark_token_program_compile_and_cache", func(b *testing.B) { for i := 0; i < b.N; i++ { b.StopTimer() - program, err := newTokenProgram(maxUnits, eng, cfg, wasmBytes) - require.NoError(err) + program := newTokenProgram(maxUnits, eng, cfg, wasmBytes) b.StartTimer() - err = program.Run(context.Background()) - require.NoError(err) + require.NoError(b, program.Run(context.Background())) } }) b.Run("benchmark_token_program_compile_and_cache_short", func(b *testing.B) { for i := 0; i < b.N; i++ { b.StopTimer() - program, err := newTokenProgram(maxUnits, eng, cfg, wasmBytes) - require.NoError(err) + program := newTokenProgram(maxUnits, eng, cfg, wasmBytes) b.StartTimer() - err = program.RunShort(context.Background()) - require.NoError(err) + require.NoError(b, program.RunShort(context.Background())) } }) @@ -74,35 +66,31 @@ func BenchmarkTokenProgram(b *testing.B) { WithDefaultCache(true). Build() eng = engine.New(ecfg) - require.NoError(err) + require.NoError(b, err) preCompiledTokenProgramBytes, err := engine.PreCompileWasmBytes(eng, wasmBytes, cfg.LimitMaxMemory) - require.NoError(err) + require.NoError(b, err) b.ResetTimer() b.Run("benchmark_token_program_precompile", func(b *testing.B) { for i := 0; i < b.N; i++ { b.StopTimer() - program, err := newTokenProgram(maxUnits, eng, cfg, preCompiledTokenProgramBytes) - require.NoError(err) + program := newTokenProgram(maxUnits, eng, cfg, preCompiledTokenProgramBytes) b.StartTimer() - err = program.Run(context.Background()) - require.NoError(err) + require.NoError(b, program.Run(context.Background())) } }) b.Run("benchmark_token_program_precompile_short", func(b *testing.B) { for i := 0; i < b.N; i++ { b.StopTimer() - program, err := newTokenProgram(maxUnits, eng, cfg, preCompiledTokenProgramBytes) - require.NoError(err) + program := newTokenProgram(maxUnits, eng, cfg, preCompiledTokenProgramBytes) b.StartTimer() - err = program.RunShort(context.Background()) - require.NoError(err) + require.NoError(b, program.RunShort(context.Background())) } }) } -func newTokenProgram(maxUnits uint64, engine *engine.Engine, cfg *runtime.Config, programBytes []byte) (*Token, error) { +func newTokenProgram(maxUnits uint64, engine *engine.Engine, cfg *runtime.Config, programBytes []byte) *Token { db := newTestDB() log := logging.NewLogger( @@ -119,5 +107,5 @@ func newTokenProgram(maxUnits uint64, engine *engine.Engine, cfg *runtime.Config return pstate.New(log, db) }) - return NewToken(log, engine, programBytes, db, cfg, importsBuilder.Build(), maxUnits), nil + return NewToken(log, engine, programBytes, db, cfg, importsBuilder.Build(), maxUnits) } diff --git a/x/programs/examples/utils.go b/x/programs/examples/utils.go index 5b6c063f86..b35e174605 100644 --- a/x/programs/examples/utils.go +++ b/x/programs/examples/utils.go @@ -8,19 +8,20 @@ import ( "os" "github.com/ava-labs/avalanchego/database/memdb" + "github.com/near/borsh-go" + "github.com/ava-labs/hypersdk/crypto/ed25519" "github.com/ava-labs/hypersdk/state" "github.com/ava-labs/hypersdk/x/programs/program" - "github.com/near/borsh-go" ) -func newKey() (ed25519.PrivateKey, ed25519.PublicKey, error) { +func newKey() (ed25519.PublicKey, error) { priv, err := ed25519.GeneratePrivateKey() if err != nil { - return ed25519.EmptyPrivateKey, ed25519.EmptyPublicKey, err + return ed25519.EmptyPublicKey, err } - return priv, priv.PublicKey(), nil + return priv.PublicKey(), nil } // SerializeParameter serializes [obj] using Borsh diff --git a/x/programs/host/link.go b/x/programs/host/link.go index 02ff6bad99..aec20a1e8e 100644 --- a/x/programs/host/link.go +++ b/x/programs/host/link.go @@ -7,12 +7,10 @@ import ( "errors" "fmt" + "github.com/ava-labs/avalanchego/utils/logging" "github.com/bytecodealliance/wasmtime-go/v14" - "go.uber.org/zap" - "github.com/ava-labs/avalanchego/utils/logging" - "github.com/ava-labs/hypersdk/x/programs/engine" "github.com/ava-labs/hypersdk/x/programs/program" "github.com/ava-labs/hypersdk/x/programs/program/types" diff --git a/x/programs/host/link_test.go b/x/programs/host/link_test.go index bdd2fbcf27..87a0577623 100644 --- a/x/programs/host/link_test.go +++ b/x/programs/host/link_test.go @@ -6,11 +6,9 @@ package host import ( "testing" - "github.com/stretchr/testify/require" - - "github.com/bytecodealliance/wasmtime-go/v14" - "github.com/ava-labs/avalanchego/utils/logging" + "github.com/bytecodealliance/wasmtime-go/v14" + "github.com/stretchr/testify/require" "github.com/ava-labs/hypersdk/x/programs/engine" ) @@ -35,14 +33,12 @@ func TestLinkMissingImport(t *testing.T) { } func TestLinkImport(t *testing.T) { - require := require.New(t) - wasm, err := wasmtime.Wat2Wasm(` (module (import "env" "one" (func $one (param i64) (result i64))) ) `) - require.NoError(err) + require.NoError(t, err) tests := []struct { name, @@ -70,6 +66,8 @@ func TestLinkImport(t *testing.T) { } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { + require := require.New(t) + imports := NewImportsBuilder() imports.Register(tt.module, func() Import { return newTestImport(tt.module, tt.fn) @@ -83,7 +81,7 @@ func TestLinkImport(t *testing.T) { require.NoError(err) _, err = link.Instantiate(store, mod, ImportFnCallback{}) if tt.errMsg != "" { - require.ErrorContains(err, tt.errMsg) // can't use ErrorIs because the error message is not owned by us. + require.ErrorContains(err, tt.errMsg) //nolint:forbidigo return } require.NoError(err) diff --git a/x/programs/program/errors.go b/x/programs/program/errors.go index 6d2de2e7b3..85fedd4b57 100644 --- a/x/programs/program/errors.go +++ b/x/programs/program/errors.go @@ -14,10 +14,10 @@ var ( ErrMissingExportedFunction = errors.New("failed to find exported function") ErrMissingInvalidMemoryFunction = errors.New("memory function is invalid") ErrRuntimeStoreSet = errors.New("runtime store has already been set") - ErrOverflow = fmt.Errorf("overflow") - ErrUnderflow = fmt.Errorf("underflow") - ErrInvalidType = fmt.Errorf("invalid type") - ErrNegativeValue = fmt.Errorf("negative value") + ErrOverflow = errors.New("overflow") + ErrUnderflow = errors.New("underflow") + ErrInvalidType = errors.New("invalid type") + ErrNegativeValue = errors.New("negative value") // Memory ErrInvalidMemorySize = errors.New("invalid memory size") diff --git a/x/programs/program/memory.go b/x/programs/program/memory.go index ada2d44e68..a149983ec2 100644 --- a/x/programs/program/memory.go +++ b/x/programs/program/memory.go @@ -4,6 +4,7 @@ package program import ( + "errors" "fmt" "math" "runtime" @@ -197,14 +198,14 @@ func BytesToSmartPtr(bytes []byte, memory *Memory) (SmartPtr, error) { return NewSmartPtr(ptr, len(bytes)) } -// NewSmartPtr returns a SmartPtr from [ptr] and [len]. -func NewSmartPtr(ptr uint32, len int) (SmartPtr, error) { +// NewSmartPtr returns a SmartPtr from [ptr] and [byteLen]. +func NewSmartPtr(ptr uint32, byteLen int) (SmartPtr, error) { // ensure length of bytes is not greater than int32 to prevent overflow - if !EnsureIntToInt32(len) { - return 0, fmt.Errorf("length of bytes is greater than int32") + if !EnsureIntToInt32(byteLen) { + return 0, errors.New("length of bytes is greater than int32") } - lenUpperBits := int64(len) << 32 + lenUpperBits := int64(byteLen) << 32 ptrLowerBits := int64(ptr) return SmartPtr(lenUpperBits | ptrLowerBits), nil diff --git a/x/programs/program/memory_test.go b/x/programs/program/memory_test.go index 31cddb9082..eb6d051a86 100644 --- a/x/programs/program/memory_test.go +++ b/x/programs/program/memory_test.go @@ -7,7 +7,6 @@ import ( "testing" "github.com/bytecodealliance/wasmtime-go/v14" - "github.com/stretchr/testify/require" "github.com/ava-labs/hypersdk/x/programs/engine" @@ -19,16 +18,16 @@ func TestMemory(t *testing.T) { mem := newTestMemory(t) // verify memory size set by program is 17 pages - len, err := mem.Len() + memLen, err := mem.Len() require.NoError(err) - require.Equal(uint32(17*MemoryPageSize), len) + require.Equal(uint32(17*MemoryPageSize), memLen) // grow memory by 1 page which is the default max memory (18 pages) // _, err = mem.Grow(1) // require.NoError(err) - // len, err = mem.Len() + // memLen, err = mem.Len() // require.NoError(err) - // require.Equal(uint32(engine.DefaultLimitMaxMemory), len) + // require.Equal(uint32(engine.DefaultLimitMaxMemory), memLen) // allocate entire memory ptr, err := mem.Alloc(1) diff --git a/x/programs/runtime/config.go b/x/programs/runtime/config.go index cb5e9045a5..33664ff432 100644 --- a/x/programs/runtime/config.go +++ b/x/programs/runtime/config.go @@ -13,15 +13,15 @@ type Config struct { // This should not be set for a live system as it has both performance and security considerations. // Note: This requires associated Engine to enable support for BulkMemory. // This is false by default. - EnableDebugMode bool `yaml:"enable_testing_only_mode,omitempty" json:"enableTestingOnlyMode,omitempty"` + EnableDebugMode bool `json:"enableTestingOnlyMode,omitempty" yaml:"enable_testing_only_mode,omitempty"` // LimitMaxMemory defines the maximum number of pages of memory that can be used. // Each page represents 64KiB of memory. // This is 18 pages by default. - LimitMaxMemory uint32 `yaml:"limit_max_memory,omitempty" json:"limitMaxMemory,omitempty"` + LimitMaxMemory uint32 `json:"limitMaxMemory,omitempty" yaml:"limit_max_memory,omitempty"` // CompileStrategy helps the engine to understand if the files has been precompiled. - CompileStrategy engine.CompileStrategy `yaml:"compile_strategy,omitempty" json:"compileStrategy,omitempty"` + CompileStrategy engine.CompileStrategy `json:"compileStrategy,omitempty" yaml:"compile_strategy,omitempty"` // ImportFnCallback is a global callback for all import function requests and responses. - ImportFnCallback host.ImportFnCallback `yaml:"-" json:"-"` + ImportFnCallback host.ImportFnCallback `json:"-" yaml:"-"` } // NewConfig returns a new runtime configuration with default settings. diff --git a/x/programs/runtime/instance.go b/x/programs/runtime/instance.go index c68ae6b288..b52a1c5492 100644 --- a/x/programs/runtime/instance.go +++ b/x/programs/runtime/instance.go @@ -6,9 +6,10 @@ package runtime import ( "fmt" + "github.com/bytecodealliance/wasmtime-go/v14" + "github.com/ava-labs/hypersdk/x/programs/engine" "github.com/ava-labs/hypersdk/x/programs/program" - "github.com/bytecodealliance/wasmtime-go/v14" ) var _ program.Instance = (*Instance)(nil) diff --git a/x/programs/runtime/runtime.go b/x/programs/runtime/runtime.go index 252255e820..c3e0c6dc35 100644 --- a/x/programs/runtime/runtime.go +++ b/x/programs/runtime/runtime.go @@ -7,9 +7,9 @@ import ( "context" "sync" + "github.com/ava-labs/avalanchego/utils/logging" "github.com/bytecodealliance/wasmtime-go/v14" - "github.com/ava-labs/avalanchego/utils/logging" "github.com/ava-labs/hypersdk/x/programs/engine" "github.com/ava-labs/hypersdk/x/programs/host" "github.com/ava-labs/hypersdk/x/programs/program" diff --git a/x/programs/runtime/runtime_test.go b/x/programs/runtime/runtime_test.go index bc6e64427d..0b8fef824a 100644 --- a/x/programs/runtime/runtime_test.go +++ b/x/programs/runtime/runtime_test.go @@ -9,9 +9,7 @@ import ( "github.com/ava-labs/avalanchego/utils" "github.com/ava-labs/avalanchego/utils/logging" - "github.com/bytecodealliance/wasmtime-go/v14" - "github.com/stretchr/testify/require" "github.com/ava-labs/hypersdk/x/programs/engine" @@ -144,7 +142,7 @@ func TestMetering(t *testing.T) { } balance, err = runtime.Meter().GetBalance() require.NoError(err) - require.Equal(balance, uint64(0)) + require.Zero(balance) } func TestMeterAfterStop(t *testing.T) { @@ -205,7 +203,7 @@ func TestLimitMaxMemory(t *testing.T) { eng := engine.New(engine.NewConfig()) runtime := New(logging.NoLog{}, eng, host.NoSupportedImports, cfg) err = runtime.Initialize(context.Background(), wasm, maxUnits) - require.ErrorContains(err, "memory minimum size of 2 pages exceeds memory limits") + require.ErrorContains(err, "memory minimum size of 2 pages exceeds memory limits") //nolint:forbidigo } func TestLimitMaxMemoryGrow(t *testing.T) { @@ -240,7 +238,7 @@ func TestLimitMaxMemoryGrow(t *testing.T) { // attempt to grow memory to 2 pages which exceeds the limit _, err = mem.Grow(1) - require.ErrorContains(err, "failed to grow memory by `1`") + require.ErrorContains(err, "failed to grow memory by `1`") //nolint:forbidigo } func TestWriteExceedsLimitMaxMemory(t *testing.T) { @@ -272,7 +270,7 @@ func TestWriteExceedsLimitMaxMemory(t *testing.T) { bytes := utils.RandomBytes(int(maxMemory) + 1) err = mem.Write(0, bytes) - require.Error(err, "write memory failed: invalid memory size") + require.ErrorIs(err, program.ErrOverflow) } func TestWithMaxWasmStack(t *testing.T) { diff --git a/x/programs/tests/utils.go b/x/programs/tests/utils.go index f493adfff2..0807dd58ae 100644 --- a/x/programs/tests/utils.go +++ b/x/programs/tests/utils.go @@ -7,18 +7,17 @@ import ( "os" "path/filepath" "testing" + + "github.com/stretchr/testify/require" ) // ReadFixture reads a file from this fixture directory and returns its content. func ReadFixture(tb testing.TB, filename string) []byte { + require := require.New(tb) tb.Helper() dir, err := os.Getwd() - if err != nil { - tb.Error(err) - } + require.NoError(err) bytes, err := os.ReadFile(filepath.Join(dir, filename)) - if err != nil { - tb.Error(err) - } + require.NoError(err) return bytes }