diff --git a/.github/workflows/go.yml b/.github/workflows/go.yml index e2494e1863..9b02f89d48 100644 --- a/.github/workflows/go.yml +++ b/.github/workflows/go.yml @@ -69,14 +69,5 @@ jobs: run: go test -race ./... lint: - runs-on: ubuntu-latest - steps: - - uses: actions/checkout@v4 - - uses: actions/setup-go@v5 - with: - go-version-file: 'go.mod' - - name: golangci-lint - uses: golangci/golangci-lint-action@v4 - with: - version: latest - args: --timeout=5m + name: Lint + uses: nspcc-dev/.github/.github/workflows/go-linter.yml@master diff --git a/.gitignore b/.gitignore index 232cc00619..a3c82f212d 100644 --- a/.gitignore +++ b/.gitignore @@ -28,6 +28,7 @@ testfile # misc .neofs-cli.yml +.golangci.yml # debhelpers **/.debhelper diff --git a/.golangci.yml b/.golangci.yml deleted file mode 100644 index 2dd8db66b3..0000000000 --- a/.golangci.yml +++ /dev/null @@ -1,68 +0,0 @@ -# This file contains all available configuration options -# with their default values. - -# options for analysis running -run: - # timeout for analysis, e.g. 30s, 5m, default is 1m - timeout: 5m - - # include test files or not, default is true - tests: false - -# output configuration options -output: - # colored-line-number|line-number|json|tab|checkstyle|code-climate, default is "colored-line-number" - formats: - - format: tab - -# all available settings of specific linters -linters-settings: - exhaustive: - # indicates that switch statements are to be considered exhaustive if a - # 'default' case is present, even if all enum members aren't listed in the - # switch - default-signifies-exhaustive: true - gofmt: - rewrite-rules: - - pattern: 'interface{}' - replacement: 'any' - gomodguard: - blocked: - modules: - - github.com/pkg/errors: - reason: "Obsolete after the 1.13 release; use the standard `errors` package" - revive: - rules: - - name: duplicated-imports - -linters: - enable: - # mandatory linters - - govet - - revive - - # some default golangci-lint linters - - errcheck - - gosimple - - godot - - ineffassign - - staticcheck - - typecheck - - unused - - # extra linters - - bidichk - - copyloopvar - - durationcheck - - exhaustive - - gofmt - - goimports - - gomodguard - - intrange - - misspell - - predeclared - - reassign - - whitespace - disable-all: true - fast: false - diff --git a/CHANGELOG.md b/CHANGELOG.md index e90ccf3be4..12cbec7aab 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -19,6 +19,7 @@ attribute, which is used for container domain name in NNS contracts (#2954) - `ObjectService`'s `Put` RPC handler caches up to 10K lists of per-object sorted container nodes (#2901) - Metabase graveyard scheme (#2929) - When an error is returned, no additional help output is displayed in cobra-based programs (#2942) +- Use org-wide linter (#2943) ### Removed - Support for node.key configuration (#2959) diff --git a/Makefile b/Makefile index eac1b61fb8..4be9c3d6fb 100644 --- a/Makefile +++ b/Makefile @@ -128,8 +128,11 @@ test: @echo "⇒ Running go test" @go test ./... +.golangci.yml: + wget -O $@ https://github.com/nspcc-dev/.github/raw/master/.golangci.yml + # Run linters -lint: +lint: .golangci.yml @golangci-lint --timeout=5m run # Run linters in Docker diff --git a/cmd/neofs-adm/internal/modules/morph/container.go b/cmd/neofs-adm/internal/modules/morph/container.go index f8d485aa07..7c0437aa41 100644 --- a/cmd/neofs-adm/internal/modules/morph/container.go +++ b/cmd/neofs-adm/internal/modules/morph/container.go @@ -189,7 +189,7 @@ func restoreContainers(cmd *cobra.Command, _ []string) error { var id cid.ID b := smartcontract.NewBuilder() for _, cnt := range containers { - id.FromBinary(cnt.Value) + id = cid.NewFromMarshalledContainer(cnt.Value) if _, ok := requested[id]; !ok { continue } diff --git a/cmd/neofs-adm/internal/modules/morph/estimation.go b/cmd/neofs-adm/internal/modules/morph/estimation.go index 552d03c369..a75dad27c3 100644 --- a/cmd/neofs-adm/internal/modules/morph/estimation.go +++ b/cmd/neofs-adm/internal/modules/morph/estimation.go @@ -1,7 +1,6 @@ package morph import ( - "crypto/sha256" "fmt" "github.com/google/uuid" @@ -75,10 +74,7 @@ func estimationsFunc(cmd *cobra.Command, _ []string) error { return fmt.Errorf("container contract hash resolution: %w", err) } - cIDBytes := make([]byte, sha256.Size) - cID.Encode(cIDBytes) - - sID, iter, err := unwrap.SessionIterator(inv.Call(cnrHash, "iterateContainerSizes", epoch, cIDBytes)) + sID, iter, err := unwrap.SessionIterator(inv.Call(cnrHash, "iterateContainerSizes", epoch, cID[:])) if err != nil { return fmt.Errorf("iterator expansion: %w", err) } diff --git a/cmd/neofs-cli/internal/common/token.go b/cmd/neofs-cli/internal/common/token.go index 5bb5fc955c..92e08b8674 100644 --- a/cmd/neofs-cli/internal/common/token.go +++ b/cmd/neofs-cli/internal/common/token.go @@ -27,7 +27,7 @@ func ReadBearerToken(cmd *cobra.Command, flagname string) (*bearer.Token, error) err = ReadBinaryOrJSON(cmd, &tok, path) if err != nil { - return nil, fmt.Errorf("invalid bearer token: %v", err) + return nil, fmt.Errorf("invalid bearer token: %w", err) } return &tok, nil diff --git a/cmd/neofs-cli/modules/accounting/balance.go b/cmd/neofs-cli/modules/accounting/balance.go index 2f8181d530..19fce48b5e 100644 --- a/cmd/neofs-cli/modules/accounting/balance.go +++ b/cmd/neofs-cli/modules/accounting/balance.go @@ -37,7 +37,7 @@ var accountingBalanceCmd = &cobra.Command{ balanceOwner, _ := cmd.Flags().GetString(ownerFlag) if balanceOwner == "" { - idUser = user.ResolveFromECDSAPublicKey(pk.PublicKey) + idUser = user.NewFromECDSAPublicKey(pk.PublicKey) } else { return fmt.Errorf("can't decode owner ID wallet address: %w", idUser.DecodeString(balanceOwner)) } diff --git a/cmd/neofs-cli/modules/acl/extended/create.go b/cmd/neofs-cli/modules/acl/extended/create.go index d2cd5f2a30..ef31776464 100644 --- a/cmd/neofs-cli/modules/acl/extended/create.go +++ b/cmd/neofs-cli/modules/acl/extended/create.go @@ -72,13 +72,13 @@ func createEACL(cmd *cobra.Command, _ []string) error { var containerID cid.ID if cidArg != "" { if err := containerID.DecodeString(cidArg); err != nil { - return fmt.Errorf("invalid container ID: %v\n", err) + return fmt.Errorf("invalid container ID: %w\n", err) } } rulesFile, err := getRulesFromFile(fileArg) if err != nil { - return fmt.Errorf("can't read rules from file: %v\n", err) + return fmt.Errorf("can't read rules from file: %w\n", err) } rules = append(rules, rulesFile...) diff --git a/cmd/neofs-cli/modules/acl/extended/create_test.go b/cmd/neofs-cli/modules/acl/extended/create_test.go index 0fe7829469..5d4a4e7798 100644 --- a/cmd/neofs-cli/modules/acl/extended/create_test.go +++ b/cmd/neofs-cli/modules/acl/extended/create_test.go @@ -68,21 +68,21 @@ func TestParseTable(t *testing.T) { }, } - eaclTable := eacl.NewTable() + var eaclTable eacl.Table for _, test := range tests { t.Run(test.name, func(t *testing.T) { - err := util.ParseEACLRule(eaclTable, test.rule) + err := util.ParseEACLRule(&eaclTable, test.rule) ok := len(test.jsonRecord) > 0 require.Equal(t, ok, err == nil, err) if ok { - expectedRecord := eacl.NewRecord() + var expectedRecord eacl.Record err = expectedRecord.UnmarshalJSON([]byte(test.jsonRecord)) require.NoError(t, err) actualRecord := eaclTable.Records()[len(eaclTable.Records())-1] - equalRecords(t, expectedRecord, &actualRecord) + equalRecords(t, &expectedRecord, &actualRecord) } }) } diff --git a/cmd/neofs-cli/modules/container/create.go b/cmd/neofs-cli/modules/container/create.go index cfcffdb594..6828d54127 100644 --- a/cmd/neofs-cli/modules/container/create.go +++ b/cmd/neofs-cli/modules/container/create.go @@ -108,7 +108,7 @@ It will be stored in sidechain when inner ring will accepts it.`, issuer := tok.Issuer() cnr.SetOwner(issuer) } else { - cnr.SetOwner(user.ResolveFromECDSAPublicKey(key.PublicKey)) + cnr.SetOwner(user.NewFromECDSAPublicKey(key.PublicKey)) } cnr.SetPlacementPolicy(*placementPolicy) @@ -157,7 +157,7 @@ It will be stored in sidechain when inner ring will accepts it.`, for ; ; t.Reset(waitInterval) { select { case <-ctx.Done(): - return fmt.Errorf("container creation: %s", common.ErrAwaitTimeout) + return fmt.Errorf("container creation: %w", common.ErrAwaitTimeout) case <-t.C: } diff --git a/cmd/neofs-cli/modules/container/delete.go b/cmd/neofs-cli/modules/container/delete.go index 43406634ed..83e7114a4b 100644 --- a/cmd/neofs-cli/modules/container/delete.go +++ b/cmd/neofs-cli/modules/container/delete.go @@ -59,15 +59,15 @@ Only owner of the container has a permission to remove container.`, if tok != nil { common.PrintVerbose(cmd, "Checking session issuer...") - if !tok.Issuer().Equals(owner) { + if tok.Issuer() != owner { return fmt.Errorf("session issuer differs with the container owner: expected %s, has %s", owner, tok.Issuer()) } } else { common.PrintVerbose(cmd, "Checking provided account...") - acc := user.ResolveFromECDSAPublicKey(pk.PublicKey) + acc := user.NewFromECDSAPublicKey(pk.PublicKey) - if !acc.Equals(owner) { + if acc != owner { return fmt.Errorf("provided account differs with the container owner: expected %s, has %s", owner, acc) } } @@ -132,7 +132,7 @@ Only owner of the container has a permission to remove container.`, for ; ; t.Reset(waitInterval) { select { case <-ctx.Done(): - return fmt.Errorf("container deletion: %s", common.ErrAwaitTimeout) + return fmt.Errorf("container deletion: %w", common.ErrAwaitTimeout) case <-t.C: } diff --git a/cmd/neofs-cli/modules/container/get.go b/cmd/neofs-cli/modules/container/get.go index 50d65b1c12..4f480663c9 100644 --- a/cmd/neofs-cli/modules/container/get.go +++ b/cmd/neofs-cli/modules/container/get.go @@ -94,8 +94,7 @@ func prettyPrintContainer(cmd *cobra.Command, cnr container.Container, jsonEncod return nil } - var id cid.ID - cnr.CalculateID(&id) + id := cid.NewFromMarshalledContainer(cnr.Marshal()) cmd.Println("container ID:", id) cmd.Println("owner ID:", cnr.Owner()) diff --git a/cmd/neofs-cli/modules/container/list.go b/cmd/neofs-cli/modules/container/list.go index a876f629d8..256645dfe0 100644 --- a/cmd/neofs-cli/modules/container/list.go +++ b/cmd/neofs-cli/modules/container/list.go @@ -39,7 +39,7 @@ var listContainersCmd = &cobra.Command{ } if flagVarListContainerOwner == "" { - idUser = user.ResolveFromECDSAPublicKey(key.PublicKey) + idUser = user.NewFromECDSAPublicKey(key.PublicKey) } else { err := idUser.DecodeString(flagVarListContainerOwner) if err != nil { diff --git a/cmd/neofs-cli/modules/container/nodes.go b/cmd/neofs-cli/modules/container/nodes.go index 7d90b8480c..755e0b6e69 100644 --- a/cmd/neofs-cli/modules/container/nodes.go +++ b/cmd/neofs-cli/modules/container/nodes.go @@ -40,8 +40,7 @@ var containerNodesCmd = &cobra.Command{ return fmt.Errorf("unable to get netmap snapshot: %w", err) } - var id cid.ID - cnr.CalculateID(&id) + id := cid.NewFromMarshalledContainer(cnr.Marshal()) policy := cnr.PlacementPolicy() diff --git a/cmd/neofs-cli/modules/container/set_eacl.go b/cmd/neofs-cli/modules/container/set_eacl.go index 330210e39d..b9687196ca 100644 --- a/cmd/neofs-cli/modules/container/set_eacl.go +++ b/cmd/neofs-cli/modules/container/set_eacl.go @@ -79,15 +79,15 @@ Container ID in EACL table will be substituted with ID from the CLI.`, if tok != nil { common.PrintVerbose(cmd, "Checking session issuer...") - if !tok.Issuer().Equals(owner) { + if tok.Issuer() != owner { return fmt.Errorf("session issuer differs with the container owner: expected %s, has %s", owner, tok.Issuer()) } } else { common.PrintVerbose(cmd, "Checking provided account...") - acc := user.ResolveFromECDSAPublicKey(pk.PublicKey) + acc := user.NewFromECDSAPublicKey(pk.PublicKey) - if !acc.Equals(owner) { + if acc != owner { return fmt.Errorf("provided account differs with the container owner: expected %s, has %s", owner, acc) } } @@ -136,7 +136,7 @@ Container ID in EACL table will be substituted with ID from the CLI.`, for ; ; t.Reset(waitInterval) { select { case <-ctx.Done(): - return fmt.Errorf("eACL setting: %s", common.ErrAwaitTimeout) + return fmt.Errorf("eACL setting: %w", common.ErrAwaitTimeout) case <-t.C: } diff --git a/cmd/neofs-cli/modules/container/util.go b/cmd/neofs-cli/modules/container/util.go index c984d5cd60..0df0e76b96 100644 --- a/cmd/neofs-cli/modules/container/util.go +++ b/cmd/neofs-cli/modules/container/util.go @@ -49,7 +49,7 @@ func getSession(cmd *cobra.Command) (*session.Container, error) { err := common.ReadBinaryOrJSON(cmd, &res, path) if err != nil { - return nil, fmt.Errorf("read container session: %v", err) + return nil, fmt.Errorf("read container session: %w", err) } common.PrintVerbose(cmd, "Session successfully read.") diff --git a/cmd/neofs-cli/modules/control/synchronize_tree.go b/cmd/neofs-cli/modules/control/synchronize_tree.go index f2e1540974..e7d94279ab 100644 --- a/cmd/neofs-cli/modules/control/synchronize_tree.go +++ b/cmd/neofs-cli/modules/control/synchronize_tree.go @@ -1,7 +1,6 @@ package control import ( - "crypto/sha256" "errors" "fmt" @@ -55,12 +54,9 @@ func synchronizeTree(cmd *cobra.Command, _ []string) error { height, _ := cmd.Flags().GetUint64("height") - rawCID := make([]byte, sha256.Size) - cnr.Encode(rawCID) - req := &control.SynchronizeTreeRequest{ Body: &control.SynchronizeTreeRequest_Body{ - ContainerId: rawCID, + ContainerId: cnr[:], TreeId: treeID, Height: height, }, diff --git a/cmd/neofs-cli/modules/object/head.go b/cmd/neofs-cli/modules/object/head.go index 5494ca9e2a..7eedebfd8c 100644 --- a/cmd/neofs-cli/modules/object/head.go +++ b/cmd/neofs-cli/modules/object/head.go @@ -135,11 +135,11 @@ func marshalHeader(cmd *cobra.Command, hdr *object.Object) ([]byte, error) { } } -func printObjectID(cmd *cobra.Command, recv func() (oid.ID, bool)) { +func printObjectID(cmd *cobra.Command, recv func() oid.ID) { var strID string - id, ok := recv() - if ok { + id := recv() + if !id.IsZero() { strID = id.String() } else { strID = "" @@ -148,11 +148,11 @@ func printObjectID(cmd *cobra.Command, recv func() (oid.ID, bool)) { cmd.Printf("ID: %s\n", strID) } -func printContainerID(cmd *cobra.Command, recv func() (cid.ID, bool)) { +func printContainerID(cmd *cobra.Command, recv func() cid.ID) { var strID string - id, ok := recv() - if ok { + id := recv() + if !id.IsZero() { strID = id.String() } else { strID = "" @@ -162,8 +162,8 @@ func printContainerID(cmd *cobra.Command, recv func() (cid.ID, bool)) { } func printHeader(cmd *cobra.Command, obj *object.Object) error { - printObjectID(cmd, obj.ID) - printContainerID(cmd, obj.ContainerID) + printObjectID(cmd, obj.GetID) + printContainerID(cmd, obj.GetContainerID) cmd.Printf("Owner: %s\n", obj.OwnerID()) cmd.Printf("CreatedAt: %d\n", obj.CreationEpoch()) cmd.Printf("Size: %d\n", obj.PayloadSize()) @@ -197,11 +197,11 @@ func printSplitHeader(cmd *cobra.Command, obj *object.Object) error { cmd.Printf("Split ID: %s\n", splitID) } - if oid, ok := obj.ParentID(); ok { - cmd.Printf("Split ParentID: %s\n", oid) + if oID := obj.GetParentID(); !oID.IsZero() { + cmd.Printf("Split ParentID: %s\n", oID) } - if prev, ok := obj.PreviousID(); ok { + if prev := obj.GetPreviousID(); !prev.IsZero() { cmd.Printf("Split PreviousID: %s\n", prev) } diff --git a/cmd/neofs-cli/modules/object/lock.go b/cmd/neofs-cli/modules/object/lock.go index 4b0e597a22..2fa3e693b4 100644 --- a/cmd/neofs-cli/modules/object/lock.go +++ b/cmd/neofs-cli/modules/object/lock.go @@ -32,7 +32,7 @@ var objectLockCmd = &cobra.Command{ var cnr cid.ID err := cnr.DecodeString(cidRaw) if err != nil { - return fmt.Errorf("Incorrect container arg: %v", err) + return fmt.Errorf("Incorrect container arg: %w", err) } oidsRaw, _ := cmd.Flags().GetStringSlice(commonflags.OIDFlag) @@ -51,7 +51,7 @@ var objectLockCmd = &cobra.Command{ return err } - idOwner := user.ResolveFromECDSAPublicKey(key.PublicKey) + idOwner := user.NewFromECDSAPublicKey(key.PublicKey) var lock objectSDK.Lock lock.WriteMembers(lockList) diff --git a/cmd/neofs-cli/modules/object/put.go b/cmd/neofs-cli/modules/object/put.go index e3176d0f1d..12d2ac7c15 100644 --- a/cmd/neofs-cli/modules/object/put.go +++ b/cmd/neofs-cli/modules/object/put.go @@ -94,7 +94,7 @@ func putObject(cmd *cobra.Command, _ []string) error { return fmt.Errorf("can't unmarshal object from given file: %w", err) } payloadReader = bytes.NewReader(objTemp.Payload()) - cnr, _ = objTemp.ContainerID() + cnr = objTemp.GetContainerID() ownerID = *objTemp.OwnerID() } else { fi, err := f.Stat() @@ -108,7 +108,7 @@ func putObject(cmd *cobra.Command, _ []string) error { if err != nil { return err } - ownerID = user.ResolveFromECDSAPublicKey(pk.PublicKey) + ownerID = user.NewFromECDSAPublicKey(pk.PublicKey) } attrs, err := parseObjectAttrs(cmd) diff --git a/cmd/neofs-cli/modules/object/range.go b/cmd/neofs-cli/modules/object/range.go index 96fbd2b0a4..b5b3aabcb1 100644 --- a/cmd/neofs-cli/modules/object/range.go +++ b/cmd/neofs-cli/modules/object/range.go @@ -166,10 +166,10 @@ func marshalSplitInfo(cmd *cobra.Command, info *object.SplitInfo) ([]byte, error if splitID := info.SplitID(); splitID != nil { b.WriteString("Split ID: " + splitID.String() + "\n") } - if link, ok := info.Link(); ok { + if link := info.GetLink(); !link.IsZero() { b.WriteString("Linking object: " + link.String() + "\n") } - if last, ok := info.LastPart(); ok { + if last := info.GetLastPart(); !last.IsZero() { b.WriteString("Last object: " + last.String() + "\n") } return b.Bytes(), nil diff --git a/cmd/neofs-cli/modules/object/util.go b/cmd/neofs-cli/modules/object/util.go index 2b9b372232..a765a2288f 100644 --- a/cmd/neofs-cli/modules/object/util.go +++ b/cmd/neofs-cli/modules/object/util.go @@ -106,8 +106,8 @@ func readObjectAddressBin(cnr *cid.ID, obj *oid.ID, filename string) (oid.Addres } var addr oid.Address - *cnr, _ = objTemp.ContainerID() - *obj, _ = objTemp.ID() + *cnr = objTemp.GetContainerID() + *obj = objTemp.GetID() addr.SetContainer(*cnr) addr.SetObject(*obj) return addr, nil @@ -162,7 +162,7 @@ func getSession(cmd *cobra.Command) (*session.Object, error) { err := common.ReadBinaryOrJSON(cmd, &tok, path) if err != nil { - return nil, fmt.Errorf("read session: %v", err) + return nil, fmt.Errorf("read session: %w", err) } return &tok, nil diff --git a/cmd/neofs-cli/modules/storagegroup/get.go b/cmd/neofs-cli/modules/storagegroup/get.go index f399f7d9e4..d51c125349 100644 --- a/cmd/neofs-cli/modules/storagegroup/get.go +++ b/cmd/neofs-cli/modules/storagegroup/get.go @@ -2,6 +2,7 @@ package storagegroup import ( "bytes" + "errors" "fmt" internalclient "github.com/nspcc-dev/neofs-node/cmd/neofs-cli/internal/client" @@ -9,6 +10,7 @@ import ( "github.com/nspcc-dev/neofs-node/cmd/neofs-cli/internal/commonflags" "github.com/nspcc-dev/neofs-node/cmd/neofs-cli/internal/key" objectCli "github.com/nspcc-dev/neofs-node/cmd/neofs-cli/modules/object" + "github.com/nspcc-dev/neofs-node/pkg/core/object" cid "github.com/nspcc-dev/neofs-sdk-go/container/id" oid "github.com/nspcc-dev/neofs-sdk-go/object/id" storagegroupSDK "github.com/nspcc-dev/neofs-sdk-go/storagegroup" @@ -89,7 +91,16 @@ func getSG(cmd *cobra.Command, _ []string) error { return fmt.Errorf("could not read storage group from the obj: %w", err) } - cmd.Printf("The last active epoch: %d\n", sg.ExpirationEpoch()) + expiration, err := object.Expiration(*rawObj) + if err != nil && !errors.Is(err, object.ErrNoExpiration) { + return fmt.Errorf("storage group's expiration: %w", err) + } + + if errors.Is(err, object.ErrNoExpiration) { + cmd.Printf("No expiration epoch") + } else { + cmd.Printf("The last active epoch: %d\n", expiration) + } cmd.Printf("Group size: %d\n", sg.ValidationDataSize()) common.PrintChecksum(cmd, "Group hash", sg.ValidationDataHash) diff --git a/cmd/neofs-cli/modules/storagegroup/put.go b/cmd/neofs-cli/modules/storagegroup/put.go index b19eec9311..b3a3d022ad 100644 --- a/cmd/neofs-cli/modules/storagegroup/put.go +++ b/cmd/neofs-cli/modules/storagegroup/put.go @@ -5,6 +5,7 @@ import ( "crypto/ecdsa" "errors" "fmt" + "strconv" internalclient "github.com/nspcc-dev/neofs-node/cmd/neofs-cli/internal/client" "github.com/nspcc-dev/neofs-node/cmd/neofs-cli/internal/commonflags" @@ -60,7 +61,7 @@ func putSG(cmd *cobra.Command, _ []string) error { return err } - ownerID := user.ResolveFromECDSAPublicKey(pk.PublicKey) + ownerID := user.NewFromECDSAPublicKey(pk.PublicKey) var cnr cid.ID err = readCID(cmd, &cnr) @@ -149,14 +150,35 @@ func putSG(cmd *cobra.Command, _ []string) error { exp = currEpoch + lifetime } - sg.SetExpirationEpoch(exp) - obj := object.New() obj.SetContainerID(cnr) obj.SetOwnerID(&ownerID) storagegroupSDK.WriteToObject(*sg, obj) + if exp > 0 { + attrs := obj.Attributes() + var expAttrFound bool + expAttrValue := strconv.FormatUint(exp, 10) + + for i := range attrs { + if attrs[i].Key() == object.AttributeExpirationEpoch { + attrs[i].SetValue(expAttrValue) + expAttrFound = true + break + } + } + + if !expAttrFound { + index := len(attrs) + attrs = append(attrs, object.Attribute{}) + attrs[index].SetKey(object.AttributeExpirationEpoch) + attrs[index].SetValue(expAttrValue) + } + + obj.SetAttributes(attrs...) + } + putPrm.SetPrivateKey(*pk) putPrm.SetHeader(obj) diff --git a/cmd/neofs-cli/modules/tree/add.go b/cmd/neofs-cli/modules/tree/add.go index 464a39dea5..ae10e9762a 100644 --- a/cmd/neofs-cli/modules/tree/add.go +++ b/cmd/neofs-cli/modules/tree/add.go @@ -1,7 +1,6 @@ package tree import ( - "crypto/sha256" "fmt" "strings" @@ -61,12 +60,9 @@ func add(cmd *cobra.Command, _ []string) error { return fmt.Errorf("client: %w", err) } - rawCID := make([]byte, sha256.Size) - cnr.Encode(rawCID) - req := new(tree.AddRequest) req.Body = &tree.AddRequest_Body{ - ContainerId: rawCID, + ContainerId: cnr[:], TreeId: tid, ParentId: pid, Meta: meta, diff --git a/cmd/neofs-cli/modules/tree/add_by_path.go b/cmd/neofs-cli/modules/tree/add_by_path.go index 8d080063dc..4d19c8ab54 100644 --- a/cmd/neofs-cli/modules/tree/add_by_path.go +++ b/cmd/neofs-cli/modules/tree/add_by_path.go @@ -1,7 +1,6 @@ package tree import ( - "crypto/sha256" "fmt" "strings" @@ -65,9 +64,6 @@ func addByPath(cmd *cobra.Command, _ []string) error { return fmt.Errorf("client: %w", err) } - rawCID := make([]byte, sha256.Size) - cnr.Encode(rawCID) - meta, err := parseMeta(cmd) if err != nil { return fmt.Errorf("meta data parsing: %w", err) @@ -78,7 +74,7 @@ func addByPath(cmd *cobra.Command, _ []string) error { req := new(tree.AddByPathRequest) req.Body = &tree.AddByPathRequest_Body{ - ContainerId: rawCID, + ContainerId: cnr[:], TreeId: tid, PathAttribute: object.AttributeFileName, //PathAttribute: pAttr, diff --git a/cmd/neofs-cli/modules/tree/get_by_path.go b/cmd/neofs-cli/modules/tree/get_by_path.go index 9e1c981bfd..422d882fa1 100644 --- a/cmd/neofs-cli/modules/tree/get_by_path.go +++ b/cmd/neofs-cli/modules/tree/get_by_path.go @@ -1,7 +1,6 @@ package tree import ( - "crypto/sha256" "fmt" "strings" @@ -65,16 +64,13 @@ func getByPath(cmd *cobra.Command, _ []string) error { return fmt.Errorf("client: %w", err) } - rawCID := make([]byte, sha256.Size) - cnr.Encode(rawCID) - latestOnly, _ := cmd.Flags().GetBool(latestOnlyFlagKey) path, _ := cmd.Flags().GetString(pathFlagKey) //pAttr, _ := cmd.Flags().GetString(pathAttributeFlagKey) req := new(tree.GetNodeByPathRequest) req.Body = &tree.GetNodeByPathRequest_Body{ - ContainerId: rawCID, + ContainerId: cnr[:], TreeId: tid, PathAttribute: object.AttributeFileName, //PathAttribute: pAttr, diff --git a/cmd/neofs-cli/modules/tree/list.go b/cmd/neofs-cli/modules/tree/list.go index c6eec1f57f..728c6221e7 100644 --- a/cmd/neofs-cli/modules/tree/list.go +++ b/cmd/neofs-cli/modules/tree/list.go @@ -1,7 +1,6 @@ package tree import ( - "crypto/sha256" "fmt" "github.com/nspcc-dev/neofs-node/cmd/neofs-cli/internal/commonflags" @@ -52,12 +51,9 @@ func list(cmd *cobra.Command, _ []string) error { return fmt.Errorf("client: %w", err) } - rawCID := make([]byte, sha256.Size) - cnr.Encode(rawCID) - req := &tree.TreeListRequest{ Body: &tree.TreeListRequest_Body{ - ContainerId: rawCID, + ContainerId: cnr[:], }, } diff --git a/cmd/neofs-cli/modules/util/acl.go b/cmd/neofs-cli/modules/util/acl.go index 59658679d8..92fb321240 100644 --- a/cmd/neofs-cli/modules/util/acl.go +++ b/cmd/neofs-cli/modules/util/acl.go @@ -83,7 +83,8 @@ func PrettyPrintTableEACL(cmd *cobra.Command, table *eacl.Table) { func eaclTargetsToString(ts []eacl.Target) string { b := bytes.NewBuffer(nil) for _, t := range ts { - keysExists := len(t.BinaryKeys()) > 0 + rawSubjects := t.RawSubjects() + keysExists := len(rawSubjects) > 0 switch t.Role() { case eacl.RoleUser: b.WriteString("User") @@ -107,11 +108,11 @@ func eaclTargetsToString(ts []eacl.Target) string { } } - for i, pub := range t.BinaryKeys() { + for i, rawSubject := range rawSubjects { if i != 0 { b.WriteString(" ") } - b.WriteString(hex.EncodeToString(pub)) + b.WriteString(hex.EncodeToString(rawSubject)) b.WriteString("\n") } } @@ -286,8 +287,10 @@ func parseEACLRecord(args []string) (eacl.Record, error) { continue } - var target eacl.Target - eacl.SetTargetECDSAKeys(&target, pubs...) + target := eacl.NewTargetByRole(eacl.RoleUnspecified) + for _, pub := range pubs { + target.SetRawSubjects(append(target.RawSubjects(), (*keys.PublicKey)(pub).Bytes())) + } targets = append(targets, target) case "address": // targets var ( diff --git a/cmd/neofs-cli/modules/util/acl_test.go b/cmd/neofs-cli/modules/util/acl_test.go index dc2a12e918..72a5fa024c 100644 --- a/cmd/neofs-cli/modules/util/acl_test.go +++ b/cmd/neofs-cli/modules/util/acl_test.go @@ -85,18 +85,18 @@ func anyValidEACL() eacl.Table { func TestValidateEACL(t *testing.T) { t.Run("absence matcher", func(t *testing.T) { - var r eacl.Record - r.AddObjectAttributeFilter(eacl.MatchNotPresent, "any_key", "any_value") + r := eacl.ConstructRecord(eacl.ActionUnspecified, eacl.OperationUnspecified, []eacl.Target{}, + eacl.NewObjectPropertyFilter("any_key", eacl.MatchNotPresent, "any_value")) tb := anyValidEACL() - tb.AddRecord(&r) + tb.SetRecords([]eacl.Record{r}) err := ValidateEACLTable(tb) require.ErrorContains(t, err, "non-empty value in absence filter") - r = eacl.Record{} - r.AddObjectAttributeFilter(eacl.MatchNotPresent, "any_key", "") + r = eacl.ConstructRecord(eacl.ActionUnspecified, eacl.OperationUnspecified, []eacl.Target{}, + eacl.NewObjectPropertyFilter("any_key", eacl.MatchNotPresent, "")) tb = anyValidEACL() - tb.AddRecord(&r) + tb.SetRecords([]eacl.Record{r}) err = ValidateEACLTable(tb) require.NoError(t, err) @@ -119,10 +119,10 @@ func TestValidateEACL(t *testing.T) { {true, "-1111111111111111111111111111111111111111111111"}, } { for _, m := range allNumMatchers { - var r eacl.Record - r.AddObjectAttributeFilter(m, "any_key", tc.v) + r := eacl.ConstructRecord(eacl.ActionUnspecified, eacl.OperationUnspecified, []eacl.Target{}, + eacl.NewObjectPropertyFilter("any_key", m, tc.v)) tb := anyValidEACL() - tb.AddRecord(&r) + tb.SetRecords([]eacl.Record{r}) err := ValidateEACLTable(tb) if tc.ok { diff --git a/cmd/neofs-cli/modules/util/sign_bearer.go b/cmd/neofs-cli/modules/util/sign_bearer.go index e94aa09848..5cf121944a 100644 --- a/cmd/neofs-cli/modules/util/sign_bearer.go +++ b/cmd/neofs-cli/modules/util/sign_bearer.go @@ -47,7 +47,7 @@ func signBearerToken(cmd *cobra.Command, _ []string) error { signer := user.NewAutoIDSignerRFC6979(*pk) var zeroUsr user.ID - if issuer := btok.Issuer(); !issuer.Equals(zeroUsr) { + if issuer := btok.Issuer(); issuer != zeroUsr { // issuer is already set, don't corrupt it signer = user.NewSigner(signer, issuer) } diff --git a/cmd/neofs-cli/modules/util/sign_session.go b/cmd/neofs-cli/modules/util/sign_session.go index 92341b7125..33b1da5f61 100644 --- a/cmd/neofs-cli/modules/util/sign_session.go +++ b/cmd/neofs-cli/modules/util/sign_session.go @@ -63,7 +63,7 @@ func signSessionToken(cmd *cobra.Command, _ []string) error { } if errLast != nil { - return fmt.Errorf("decode session: %v", errLast) + return fmt.Errorf("decode session: %w", errLast) } pk, err := key.GetOrGenerate(cmd) diff --git a/cmd/neofs-lens/internal/meta/get.go b/cmd/neofs-lens/internal/meta/get.go index fd52d632b8..f7f3c194c1 100644 --- a/cmd/neofs-lens/internal/meta/get.go +++ b/cmd/neofs-lens/internal/meta/get.go @@ -60,16 +60,16 @@ func getFunc(cmd *cobra.Command, _ []string) error { res, err := db.Get(prm) if errors.As(err, &siErr) { - link, linkSet := siErr.SplitInfo().Link() - last, lastSet := siErr.SplitInfo().LastPart() + link := siErr.SplitInfo().GetLink() + last := siErr.SplitInfo().GetLastPart() fmt.Println("Object is split") cmd.Println("\tSplitID:", siErr.SplitInfo().SplitID().String()) - if linkSet { + if !link.IsZero() { cmd.Println("\tLink:", link) } - if lastSet { + if !last.IsZero() { cmd.Println("\tLast:", last) } diff --git a/cmd/neofs-lens/internal/meta/put.go b/cmd/neofs-lens/internal/meta/put.go index 622b99e116..8bcabc08f0 100644 --- a/cmd/neofs-lens/internal/meta/put.go +++ b/cmd/neofs-lens/internal/meta/put.go @@ -46,13 +46,13 @@ func writeObject(cmd *cobra.Command, _ []string) error { return fmt.Errorf("can't unmarshal object from given file: %w", err) } - id, ok := obj.ID() - if !ok { + id := obj.GetID() + if id.IsZero() { return errors.New("missing ID in object") } - cnr, ok := obj.ContainerID() - if !ok { + cnr := obj.GetContainerID() + if cnr.IsZero() { return errors.New("missing container ID in object") } diff --git a/cmd/neofs-lens/internal/printers.go b/cmd/neofs-lens/internal/printers.go index 52b9bfbcf2..a736dc1df3 100644 --- a/cmd/neofs-lens/internal/printers.go +++ b/cmd/neofs-lens/internal/printers.go @@ -17,8 +17,8 @@ import ( func PrintObjectHeader(cmd *cobra.Command, h object.Object) { cmd.Println("Version:", h.Version()) cmd.Println("Type:", h.Type()) - printContainerID(cmd, h.ContainerID) - printObjectID(cmd, h.ID) + printContainerID(cmd, h.GetContainerID) + printObjectID(cmd, h.GetID) cmd.Println("Owner:", h.OwnerID()) cmd.Println("CreatedAt:", h.CreationEpoch()) cmd.Println("PayloadSize:", h.PayloadSize()) @@ -28,11 +28,11 @@ func PrintObjectHeader(cmd *cobra.Command, h object.Object) { } } -func printContainerID(cmd *cobra.Command, recv func() (cid.ID, bool)) { +func printContainerID(cmd *cobra.Command, recv func() cid.ID) { var val string - id, ok := recv() - if ok { + id := recv() + if !id.IsZero() { val = id.String() } else { val = "" @@ -41,11 +41,11 @@ func printContainerID(cmd *cobra.Command, recv func() (cid.ID, bool)) { cmd.Println("CID:", val) } -func printObjectID(cmd *cobra.Command, recv func() (oid.ID, bool)) { +func printObjectID(cmd *cobra.Command, recv func() oid.ID) { var val string - id, ok := recv() - if ok { + id := recv() + if !id.IsZero() { val = id.String() } else { val = "" diff --git a/cmd/neofs-node/cache.go b/cmd/neofs-node/cache.go index ae3411063f..1b5cf6a24f 100644 --- a/cmd/neofs-node/cache.go +++ b/cmd/neofs-node/cache.go @@ -380,7 +380,7 @@ func (s *ttlContainerLister) update(owner user.ID, cnr cid.ID, add bool) { found := false for i := range item.list { - if found = item.list[i].Equals(cnr); found { + if found = item.list[i] == cnr; found { if !add { item.list = append(item.list[:i], item.list[i+1:]...) // if list became empty we don't remove the value from the cache diff --git a/cmd/neofs-node/config.go b/cmd/neofs-node/config.go index a7ae8ea03c..d345c8a6aa 100644 --- a/cmd/neofs-node/config.go +++ b/cmd/neofs-node/config.go @@ -620,7 +620,7 @@ func initCfg(appCfg *config.Config) *cfg { c.cfgNetmap.reBoostrapTurnedOff.Store(nodeconfig.Relay(appCfg)) - c.ownerIDFromKey = user.ResolveFromECDSAPublicKey(key.PrivateKey.PublicKey) + c.ownerIDFromKey = user.NewFromECDSAPublicKey(key.PrivateKey.PublicKey) if metricsconfig.Enabled(c.cfgReader) { c.metricsCollector = metrics.NewNodeMetrics(misc.Version) diff --git a/cmd/neofs-node/container.go b/cmd/neofs-node/container.go index aa434c990f..8af3b200c1 100644 --- a/cmd/neofs-node/container.go +++ b/cmd/neofs-node/container.go @@ -4,7 +4,6 @@ import ( "bytes" "context" "crypto/ecdsa" - "crypto/sha256" "encoding/binary" "errors" "fmt" @@ -391,9 +390,8 @@ func (l *loadPlacementBuilder) BuildPlacement(epoch uint64, cnr cid.ID) ([][]net return nil, err } - buf := make([]byte, sha256.Size) + buf := cnr[:] - cnr.Encode(buf) binary.LittleEndian.PutUint64(buf, epoch) var pivot oid.ID @@ -664,7 +662,7 @@ func (m morphContainerWriter) PutEACL(eaclInfo containerCore.EACL) error { } if m.cacheEnabled { - id, _ := eaclInfo.Value.CID() + id := eaclInfo.Value.GetCID() m.eacls.InvalidateEACL(id) } diff --git a/cmd/neofs-node/policy_test.go b/cmd/neofs-node/policy_test.go index 2aaee2737e..50a7c0ba8d 100644 --- a/cmd/neofs-node/policy_test.go +++ b/cmd/neofs-node/policy_test.go @@ -38,7 +38,7 @@ func (x testContainer) assertCalledNTimesWith(t testing.TB, n int, id cid.ID) { func (x *testContainer) Get(id cid.ID) (*containercore.Container, error) { x.calls = append(x.calls, id) - if !id.Equals(x.id) { + if id != x.id { return nil, fmt.Errorf("unexpected container requested %s!=%s", id, x.id) } if x.err != nil { diff --git a/pkg/core/object/fmt.go b/pkg/core/object/fmt.go index b05c565469..5088a35050 100644 --- a/pkg/core/object/fmt.go +++ b/pkg/core/object/fmt.go @@ -109,13 +109,11 @@ func (v *FormatValidator) Validate(obj *object.Object, unprepared bool) error { return errNilObject } - _, idSet := obj.ID() - if !unprepared && !idSet { + if !unprepared && obj.GetID().IsZero() { return errNilID } - _, cnrSet := obj.ContainerID() - if !cnrSet { + if obj.GetContainerID().IsZero() { return errNilCID } @@ -151,7 +149,7 @@ func (v *FormatValidator) Validate(obj *object.Object, unprepared bool) error { return errors.New("v2 split: incorrect link object's parent header") } - if _, hasPrevious := obj.PreviousID(); typ != object.TypeLink && !hasPrevious { + if prevID := obj.GetPreviousID(); typ != object.TypeLink && prevID.IsZero() { return errors.New("v2 split: middle part does not have previous object ID") } } @@ -205,7 +203,7 @@ func (v *FormatValidator) validateSignatureKey(obj *object.Object) error { return errors.New("incorrect session token signature") } - if issuer, owner := token.Issuer(), obj.OwnerID(); !issuer.Equals(*owner) { // nil check was performed above + if issuer, owner := token.Issuer(), obj.OwnerID(); issuer != *owner { // nil check was performed above return fmt.Errorf("different object owner %s and session issuer %s", owner, issuer) } @@ -257,8 +255,8 @@ func (v *FormatValidator) ValidateContent(o *object.Object) (ContentMeta, error) return ContentMeta{}, errors.New("link object does not have first object ID") } - cnr, set := o.ContainerID() - if !set { + cnr := o.GetContainerID() + if cnr.IsZero() { return ContentMeta{}, errors.New("link object does not have container ID") } @@ -294,8 +292,8 @@ func (v *FormatValidator) ValidateContent(o *object.Object) (ContentMeta, error) return ContentMeta{}, errTombstoneExpiration } - cnr, ok := o.ContainerID() - if !ok { + cnr := o.GetContainerID() + if cnr.IsZero() { return ContentMeta{}, errors.New("missing container ID") } @@ -339,13 +337,13 @@ func (v *FormatValidator) ValidateContent(o *object.Object) (ContentMeta, error) return ContentMeta{}, errors.New("empty payload in lock") } - _, ok := o.ContainerID() - if !ok { + cnr := o.GetContainerID() + if cnr.IsZero() { return ContentMeta{}, errors.New("missing container") } - _, ok = o.ID() - if !ok { + objID := o.GetID() + if objID.IsZero() { return ContentMeta{}, errors.New("missing ID") } @@ -396,8 +394,8 @@ func (v *FormatValidator) checkExpiration(obj object.Object) error { // an object could be expired but locked; // put such an object is a correct operation - cID, _ := obj.ContainerID() - oID, _ := obj.ID() + cID := obj.GetContainerID() + oID := obj.GetID() var addr oid.Address addr.SetContainer(cID) @@ -446,7 +444,7 @@ func (v *FormatValidator) checkAttributes(obj *object.Object) error { var errIncorrectOwner = errors.New("incorrect object owner") func (v *FormatValidator) checkOwner(obj *object.Object) error { - if idOwner := obj.OwnerID(); idOwner == nil || len(idOwner.WalletBytes()) == 0 { + if idOwner := obj.OwnerID(); idOwner == nil { return errIncorrectOwner } diff --git a/pkg/core/object/fmt_test.go b/pkg/core/object/fmt_test.go index 22000a720b..51f8ead1fa 100644 --- a/pkg/core/object/fmt_test.go +++ b/pkg/core/object/fmt_test.go @@ -212,7 +212,7 @@ func TestFormatValidator_Validate(t *testing.T) { }) var content storagegroup.StorageGroup - content.SetExpirationEpoch(1) // some non-default value + content.SetValidationDataSize(1) // some non-default value t.Run("empty members", func(t *testing.T) { obj.SetPayload(content.Marshal()) @@ -279,8 +279,8 @@ func TestFormatValidator_Validate(t *testing.T) { t.Run("locked", func(t *testing.T) { var addr oid.Address - oID, _ := obj.ID() - cID, _ := obj.ContainerID() + oID := obj.GetID() + cID := obj.GetContainerID() addr.SetContainer(cID) addr.SetObject(oID) diff --git a/pkg/core/object/object.go b/pkg/core/object/object.go index 24c9f2451d..7cbb25227d 100644 --- a/pkg/core/object/object.go +++ b/pkg/core/object/object.go @@ -13,19 +13,7 @@ var ErrInvalidSearchQuery = errors.New("invalid search query") // AddressOf returns the address of the object. func AddressOf(obj *object.Object) oid.Address { - var addr oid.Address - - id, ok := obj.ID() - if ok { - addr.SetObject(id) - } - - cnr, ok := obj.ContainerID() - if ok { - addr.SetContainer(cnr) - } - - return addr + return oid.NewAddress(obj.GetContainerID(), obj.GetID()) } // ErrNoExpiration means no expiration was set. diff --git a/pkg/innerring/processors/container/common.go b/pkg/innerring/processors/container/common.go index 076fd13ad3..d1caa491f4 100644 --- a/pkg/innerring/processors/container/common.go +++ b/pkg/innerring/processors/container/common.go @@ -102,9 +102,9 @@ func (cp *Processor) verifySignature(v signatureVerificationData) error { if keyProvided { // TODO(@cthulhu-rider): #1387 use another approach after neofs-sdk-go#233 - idFromKey := user.ResolveFromECDSAPublicKey(ecdsa.PublicKey(key)) + idFromKey := user.NewFromECDSAPublicKey(ecdsa.PublicKey(key)) - if v.ownerContainer.Equals(idFromKey) { + if v.ownerContainer == idFromKey { if key.Verify(v.signedData, v.signature) { return nil } diff --git a/pkg/innerring/processors/container/process_eacl.go b/pkg/innerring/processors/container/process_eacl.go index 650572f783..bfca0f6cba 100644 --- a/pkg/innerring/processors/container/process_eacl.go +++ b/pkg/innerring/processors/container/process_eacl.go @@ -44,8 +44,8 @@ func (cp *Processor) checkSetEACL(e container.SetEACL) error { return fmt.Errorf("table validation: %w", err) } - idCnr, ok := table.CID() - if !ok { + idCnr := table.GetCID() + if idCnr.IsZero() { return errors.New("missing container ID in eACL table") } diff --git a/pkg/innerring/processors/container/process_eacl_test.go b/pkg/innerring/processors/container/process_eacl_test.go index 309a26e49a..dbdd32d915 100644 --- a/pkg/innerring/processors/container/process_eacl_test.go +++ b/pkg/innerring/processors/container/process_eacl_test.go @@ -15,18 +15,18 @@ func anyValidEACL() eacl.Table { func TestValidateEACL(t *testing.T) { t.Run("absence matcher", func(t *testing.T) { - var r eacl.Record - r.AddObjectAttributeFilter(eacl.MatchNotPresent, "any_key", "any_value") + r := eacl.ConstructRecord(eacl.ActionUnspecified, eacl.OperationUnspecified, []eacl.Target{}, + eacl.NewObjectPropertyFilter("any_key", eacl.MatchNotPresent, "any_value")) tb := anyValidEACL() - tb.AddRecord(&r) + tb.SetRecords([]eacl.Record{r}) err := validateEACL(tb) require.ErrorContains(t, err, "non-empty value in absence filter") - r = eacl.Record{} - r.AddObjectAttributeFilter(eacl.MatchNotPresent, "any_key", "") + r = eacl.ConstructRecord(eacl.ActionUnspecified, eacl.OperationUnspecified, []eacl.Target{}, + eacl.NewObjectPropertyFilter("any_key", eacl.MatchNotPresent, "")) tb = anyValidEACL() - tb.AddRecord(&r) + tb.SetRecords([]eacl.Record{r}) err = validateEACL(tb) require.NoError(t, err) @@ -49,10 +49,10 @@ func TestValidateEACL(t *testing.T) { {true, "-1111111111111111111111111111111111111111111111"}, } { for _, m := range allNumMatchers { - var r eacl.Record - r.AddObjectAttributeFilter(m, "any_key", tc.v) + r := eacl.ConstructRecord(eacl.ActionUnspecified, eacl.OperationUnspecified, []eacl.Target{}, + eacl.NewObjectPropertyFilter("any_key", m, tc.v)) tb := anyValidEACL() - tb.AddRecord(&r) + tb.SetRecords([]eacl.Record{r}) err := validateEACL(tb) if tc.ok { diff --git a/pkg/innerring/processors/neofs/process_assets.go b/pkg/innerring/processors/neofs/process_assets.go index 164988a9ab..4e324ea763 100644 --- a/pkg/innerring/processors/neofs/process_assets.go +++ b/pkg/innerring/processors/neofs/process_assets.go @@ -53,15 +53,15 @@ func (np *Processor) processDeposit(deposit *neofsEvent.Deposit) { // get gas balance of the node // before gas transfer check if the balance is greater than the threshold - balance, err := np.morphClient.GasBalance() + gasBalance, err := np.morphClient.GasBalance() if err != nil { np.log.Error("can't get gas balance of the node", zap.Error(err)) return } - if balance < np.gasBalanceThreshold { + if gasBalance < np.gasBalanceThreshold { np.log.Warn("gas balance threshold has been reached", - zap.Int64("balance", balance), + zap.Int64("balance", gasBalance), zap.Int64("threshold", np.gasBalanceThreshold)) return diff --git a/pkg/innerring/processors/neofs/process_bind.go b/pkg/innerring/processors/neofs/process_bind.go index 6beb98d87e..706765b734 100644 --- a/pkg/innerring/processors/neofs/process_bind.go +++ b/pkg/innerring/processors/neofs/process_bind.go @@ -84,11 +84,10 @@ func (np *Processor) approveBindCommon(e *bindCommonContext) { return } - var id user.ID - id.SetScriptHash(u160) + id := user.NewFromScriptHash(u160) prm := neofsid.CommonBindPrm{} - prm.SetOwnerID(id.WalletBytes()) + prm.SetOwnerID(id[:]) prm.SetKeys(e.Keys()) prm.SetHash(e.bindCommon.TxHash()) diff --git a/pkg/innerring/processors/settlement/audit/calculate.go b/pkg/innerring/processors/settlement/audit/calculate.go index e9a9a03a7a..65a424f165 100644 --- a/pkg/innerring/processors/settlement/audit/calculate.go +++ b/pkg/innerring/processors/settlement/audit/calculate.go @@ -284,7 +284,7 @@ func (c *Calculator) fillTransferTable(ctx *singleResultCtx) bool { From: cnrOwner, Amount: ctx.auditFee, } - transferTx.To = user.ResolveFromECDSAPublicKey(ecdsa.PublicKey(*auditorKey)) + transferTx.To = user.NewFromECDSAPublicKey(ecdsa.PublicKey(*auditorKey)) ctx.txTable.Transfer(transferTx) diff --git a/pkg/innerring/processors/settlement/basic/context.go b/pkg/innerring/processors/settlement/basic/context.go index 0b2b04c91e..74426ff96b 100644 --- a/pkg/innerring/processors/settlement/basic/context.go +++ b/pkg/innerring/processors/settlement/basic/context.go @@ -71,9 +71,8 @@ func NewIncomeSettlementContext(p *IncomeSettlementContextPrms) *IncomeSettlemen exchange: p.Exchange, accounts: p.Accounts, distributeTable: NewNodeSizeTable(), + bankOwner: user.NewFromScriptHash(util.Uint160{1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1}), } - res.bankOwner.SetScriptHash(util.Uint160{1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1}) - return res } diff --git a/pkg/innerring/processors/settlement/common/util.go b/pkg/innerring/processors/settlement/common/util.go index 6b5db23370..e4ad045b92 100644 --- a/pkg/innerring/processors/settlement/common/util.go +++ b/pkg/innerring/processors/settlement/common/util.go @@ -23,7 +23,7 @@ func NewTransferTable() *TransferTable { } func (t *TransferTable) Transfer(tx *TransferTx) { - if tx.From.Equals(tx.To) { + if tx.From == tx.To { return } diff --git a/pkg/innerring/settlement.go b/pkg/innerring/settlement.go index 0bae3e9b3d..f7ed3831f9 100644 --- a/pkg/innerring/settlement.go +++ b/pkg/innerring/settlement.go @@ -199,7 +199,7 @@ func (s settlementDeps) ResolveKey(ni common.NodeInfo) (*user.ID, error) { return nil, fmt.Errorf("decode public key: %w", err) } - id := user.ResolveFromECDSAPublicKey(ecdsa.PublicKey(*pubKey)) + id := user.NewFromECDSAPublicKey(ecdsa.PublicKey(*pubKey)) return &id, nil } diff --git a/pkg/local_object_storage/blobstor/internal/blobstortest/common.go b/pkg/local_object_storage/blobstor/internal/blobstortest/common.go index 165fad1de7..873b26234a 100644 --- a/pkg/local_object_storage/blobstor/internal/blobstortest/common.go +++ b/pkg/local_object_storage/blobstor/internal/blobstortest/common.go @@ -1,7 +1,8 @@ package blobstortest import ( - "math/rand" + crand "crypto/rand" + "math/rand/v2" "testing" objectCore "github.com/nspcc-dev/neofs-node/pkg/core/object" @@ -53,7 +54,7 @@ func prepare(t *testing.T, count int, s common.Storage, minSize, maxSize uint64) objects := make([]objectDesc, count) for i := range objects { - objects[i].obj = NewObject(minSize + uint64(rand.Intn(int(maxSize-minSize+1)))) // not too large + objects[i].obj = NewObject(minSize + uint64(rand.IntN(int(maxSize-minSize+1)))) // not too large objects[i].addr = objectCore.AddressOf(objects[i].obj) objects[i].raw = objects[i].obj.Marshal() } @@ -81,8 +82,7 @@ func NewObject(sz uint64) *objectSDK.Object { raw.SetContainerID(cidtest.ID()) payload := make([]byte, sz) - //nolint:staticcheck - rand.Read(payload) + _, _ = crand.Read(payload) raw.SetPayload(payload) // fit the binary size to the required diff --git a/pkg/local_object_storage/blobstor/peapod/peapod.go b/pkg/local_object_storage/blobstor/peapod/peapod.go index 79e9a02a6c..9f5c010c29 100644 --- a/pkg/local_object_storage/blobstor/peapod/peapod.go +++ b/pkg/local_object_storage/blobstor/peapod/peapod.go @@ -161,8 +161,10 @@ const objectAddressKeySize = 2 * sha256.Size func keyForObject(addr oid.Address) []byte { b := make([]byte, objectAddressKeySize) - addr.Container().Encode(b) - addr.Object().Encode(b[sha256.Size:]) + cnr := addr.Container() + obj := addr.Object() + n := copy(b, cnr[:]) + copy(b[n:], obj[:]) return b } diff --git a/pkg/local_object_storage/engine/delete_test.go b/pkg/local_object_storage/engine/delete_test.go index 09f4ecb4be..6207d0ac13 100644 --- a/pkg/local_object_storage/engine/delete_test.go +++ b/pkg/local_object_storage/engine/delete_test.go @@ -38,7 +38,7 @@ func TestDeleteBigObject(t *testing.T) { } children[i].SetSplitID(splitID) children[i].SetPayload([]byte{byte(i), byte(i + 1), byte(i + 2)}) - childIDs[i], _ = children[i].ID() + childIDs[i] = children[i].GetID() } link := generateObjectWithCID(cnr) diff --git a/pkg/local_object_storage/engine/engine_test.go b/pkg/local_object_storage/engine/engine_test.go index 1e8dbb1667..f25d42ca5d 100644 --- a/pkg/local_object_storage/engine/engine_test.go +++ b/pkg/local_object_storage/engine/engine_test.go @@ -181,8 +181,7 @@ func generateObjectWithCID(cnr cid.ID) *object.Object { csum := checksumtest.Checksum() - var csumTZ checksum.Checksum - csumTZ.SetTillichZemor(tz.Sum(csum.Value())) + csumTZ := checksum.NewTillichZemor(tz.Sum(csum.Value())) obj := object.New() obj.SetID(oidtest.ID()) diff --git a/pkg/local_object_storage/engine/gc_test.go b/pkg/local_object_storage/engine/gc_test.go index 5ec981e8be..15c5ff283c 100644 --- a/pkg/local_object_storage/engine/gc_test.go +++ b/pkg/local_object_storage/engine/gc_test.go @@ -68,20 +68,20 @@ func TestChildrenExpiration(t *testing.T) { splitID := objectSDK.NewSplitID() parent := generateObjectWithCID(cnr) - parentID, _ := parent.ID() + parentID := parent.GetID() parent.SetAttributes(expAttr) child1 := generateObjectWithCID(cnr) - child1ID, _ := child1.ID() + child1ID := child1.GetID() child1.SetSplitID(splitID) child2 := generateObjectWithCID(cnr) - child2ID, _ := child2.ID() + child2ID := child2.GetID() child2.SetSplitID(splitID) child2.SetPreviousID(child1ID) child3 := generateObjectWithCID(cnr) - child3ID, _ := child3.ID() + child3ID := child3.GetID() child3.SetSplitID(splitID) child3.SetPreviousID(child2ID) child3.SetParent(parent) @@ -107,20 +107,20 @@ func TestChildrenExpiration(t *testing.T) { cnr := cidtest.ID() parent := generateObjectWithCID(cnr) - parentID, _ := parent.ID() + parentID := parent.GetID() parent.SetAttributes(expAttr) child1 := generateObjectWithCID(cnr) - child1ID, _ := child1.ID() + child1ID := child1.GetID() child1.SetParent(parent) child2 := generateObjectWithCID(cnr) - child2ID, _ := child2.ID() + child2ID := child2.GetID() child2.SetFirstID(child1ID) child2.SetPreviousID(child1ID) child3 := generateObjectWithCID(cnr) - child3ID, _ := child3.ID() + child3ID := child3.GetID() child3.SetFirstID(child1ID) child3.SetPreviousID(child2ID) child3.SetParent(parent) diff --git a/pkg/local_object_storage/engine/get.go b/pkg/local_object_storage/engine/get.go index e5bcfbfbe8..43ed90eb10 100644 --- a/pkg/local_object_storage/engine/get.go +++ b/pkg/local_object_storage/engine/get.go @@ -102,15 +102,8 @@ func (e *StorageEngine) get(addr oid.Address, shardFunc func(s *shard.Shard, ign util.MergeSplitInfo(siErr.SplitInfo(), outSI) - _, withLink := outSI.Link() - _, withLast := outSI.LastPart() - // stop iterating over shards if SplitInfo structure is complete - if withLink && withLast { - return true - } - - return false + return !outSI.GetLink().IsZero() && !outSI.GetLastPart().IsZero() case shard.IsErrRemoved(err): outError = err diff --git a/pkg/local_object_storage/engine/head.go b/pkg/local_object_storage/engine/head.go index 5f78515429..0319b5854d 100644 --- a/pkg/local_object_storage/engine/head.go +++ b/pkg/local_object_storage/engine/head.go @@ -93,15 +93,8 @@ func (e *StorageEngine) head(prm HeadPrm) (HeadRes, error) { util.MergeSplitInfo(siErr.SplitInfo(), outSI) - _, withLink := outSI.Link() - _, withLast := outSI.LastPart() - // stop iterating over shards if SplitInfo structure is complete - if withLink && withLast { - return true - } - - return false + return !outSI.GetLink().IsZero() && !outSI.GetLastPart().IsZero() case shard.IsErrRemoved(err): outError = err diff --git a/pkg/local_object_storage/engine/head_test.go b/pkg/local_object_storage/engine/head_test.go index 5cd5a66f4a..50d162c552 100644 --- a/pkg/local_object_storage/engine/head_test.go +++ b/pkg/local_object_storage/engine/head_test.go @@ -23,7 +23,7 @@ func TestHeadRaw(t *testing.T) { var parentAddr oid.Address parentAddr.SetContainer(cnr) - idParent, _ := parent.ID() + idParent := parent.GetID() parentAddr.SetObject(idParent) child := generateObjectWithCID(cnr) @@ -35,7 +35,7 @@ func TestHeadRaw(t *testing.T) { link.SetParent(parent) link.SetParentID(idParent) - idChild, _ := child.ID() + idChild := child.GetID() link.SetChildren(idChild) link.SetSplitID(splitID) @@ -74,12 +74,12 @@ func TestHeadRaw(t *testing.T) { // SplitInfoError should contain info from both shards require.Equal(t, splitID, si.SplitInfo().SplitID()) - id1, _ := child.ID() - id2, _ := si.SplitInfo().LastPart() + id1 := child.GetID() + id2 := si.SplitInfo().GetLastPart() require.Equal(t, id1, id2) - id1, _ = link.ID() - id2, _ = si.SplitInfo().Link() + id1 = link.GetID() + id2 = si.SplitInfo().GetLink() require.Equal(t, id1, id2) }) } diff --git a/pkg/local_object_storage/engine/inhume.go b/pkg/local_object_storage/engine/inhume.go index f39ac404f5..bd21f1def7 100644 --- a/pkg/local_object_storage/engine/inhume.go +++ b/pkg/local_object_storage/engine/inhume.go @@ -175,8 +175,8 @@ func (e *StorageEngine) inhumeAddr(addr oid.Address, prm shard.InhumePrm) (bool, // object is root; every container node is expected to store // link object and link object existence (root object upload // has been finished) should be ensured on the upper levels - linkID, set := siErr.SplitInfo().Link() - if !set { + linkID := siErr.SplitInfo().GetLink() + if linkID.IsZero() { // keep searching for the link object return false } diff --git a/pkg/local_object_storage/engine/inhume_test.go b/pkg/local_object_storage/engine/inhume_test.go index 2028368e75..ce3d985243 100644 --- a/pkg/local_object_storage/engine/inhume_test.go +++ b/pkg/local_object_storage/engine/inhume_test.go @@ -28,14 +28,14 @@ func TestStorageEngine_Inhume(t *testing.T) { child := generateObjectWithCID(cnr) child.SetParent(parent) - idParent, _ := parent.ID() + idParent := parent.GetID() child.SetParentID(idParent) child.SetSplitID(splitID) link := generateObjectWithCID(cnr) link.SetParent(parent) link.SetParentID(idParent) - idChild, _ := child.ID() + idChild := child.GetID() link.SetChildren(idChild) link.SetSplitID(splitID) @@ -100,7 +100,7 @@ func TestStorageEngine_Inhume(t *testing.T) { _, err = Get(e, addr) require.ErrorAs(t, err, new(apistatus.ObjectAlreadyRemoved)) - linkID, _ := link.ID() + linkID := link.GetID() addr.SetObject(linkID) _, err = Get(e, addr) diff --git a/pkg/local_object_storage/engine/lock_test.go b/pkg/local_object_storage/engine/lock_test.go index 3f07e4b63f..baeb1039cb 100644 --- a/pkg/local_object_storage/engine/lock_test.go +++ b/pkg/local_object_storage/engine/lock_test.go @@ -1,7 +1,6 @@ package engine import ( - "context" "os" "strconv" "testing" @@ -20,14 +19,6 @@ import ( "github.com/stretchr/testify/require" ) -type tss struct { - expEpoch uint64 -} - -func (t tss) IsTombstoneAvailable(ctx context.Context, _ oid.Address, epoch uint64) bool { - return t.expEpoch >= epoch -} - func TestLockUserScenario(t *testing.T) { // Tested user actions: // 1. stores some object @@ -87,7 +78,7 @@ func TestLockUserScenario(t *testing.T) { // 1. obj := generateObjectWithCID(cnr) - id, _ := obj.ID() + id := obj.GetID() objAddr.SetObject(id) err = Put(e, obj) @@ -180,8 +171,8 @@ func TestLockExpiration(t *testing.T) { err = Put(e, lock) require.NoError(t, err) - id, _ := obj.ID() - idLock, _ := lock.ID() + id := obj.GetID() + idLock := lock.GetID() err = e.Lock(cnr, idLock, []oid.ID{id}) require.NoError(t, err) @@ -246,8 +237,8 @@ func TestLockForceRemoval(t *testing.T) { err = Put(e, lock) require.NoError(t, err) - id, _ := obj.ID() - idLock, _ := lock.ID() + id := obj.GetID() + idLock := lock.GetID() err = e.Lock(cnr, idLock, []oid.ID{id}) require.NoError(t, err) diff --git a/pkg/local_object_storage/engine/range.go b/pkg/local_object_storage/engine/range.go index 6ade45aa76..907f05450c 100644 --- a/pkg/local_object_storage/engine/range.go +++ b/pkg/local_object_storage/engine/range.go @@ -110,15 +110,8 @@ func (e *StorageEngine) getRange(prm RngPrm) (RngRes, error) { util.MergeSplitInfo(siErr.SplitInfo(), outSI) - _, withLink := outSI.Link() - _, withLast := outSI.LastPart() - // stop iterating over shards if SplitInfo structure is complete - if withLink && withLast { - return true - } - - return false + return !outSI.GetLink().IsZero() && !outSI.GetLastPart().IsZero() case shard.IsErrRemoved(err), shard.IsErrOutOfRange(err): diff --git a/pkg/local_object_storage/metabase/containers.go b/pkg/local_object_storage/metabase/containers.go index 1b2ae529ae..60ec058dcf 100644 --- a/pkg/local_object_storage/metabase/containers.go +++ b/pkg/local_object_storage/metabase/containers.go @@ -63,18 +63,14 @@ func (db *DB) ContainerSize(id cid.ID) (size uint64, err error) { func (db *DB) containerSize(tx *bbolt.Tx, id cid.ID) (uint64, error) { containerVolume := tx.Bucket(containerVolumeBucketName) - key := make([]byte, cidSize) - id.Encode(key) - return parseContainerSize(containerVolume.Get(key)), nil + return parseContainerSize(containerVolume.Get(id[:])), nil } func resetContainerSize(tx *bbolt.Tx, cID cid.ID) error { containerVolume := tx.Bucket(containerVolumeBucketName) - key := make([]byte, cidSize) - cID.Encode(key) - return containerVolume.Put(key, make([]byte, 8)) + return containerVolume.Put(cID[:], make([]byte, 8)) } func parseContainerID(dst *cid.ID, name []byte, ignore map[string]struct{}) bool { @@ -97,8 +93,7 @@ func parseContainerSize(v []byte) uint64 { func changeContainerSize(tx *bbolt.Tx, id cid.ID, delta uint64, increase bool) error { containerVolume := tx.Bucket(containerVolumeBucketName) - key := make([]byte, cidSize) - id.Encode(key) + key := id[:] size := parseContainerSize(containerVolume.Get(key)) @@ -129,8 +124,7 @@ func (db *DB) DeleteContainer(cID cid.ID) error { return ErrReadOnlyMode } - cIDRaw := make([]byte, cidSize) - cID.Encode(cIDRaw) + cIDRaw := cID[:] buff := make([]byte, addressKeySize) return db.boltDB.Update(func(tx *bbolt.Tx) error { diff --git a/pkg/local_object_storage/metabase/containers_test.go b/pkg/local_object_storage/metabase/containers_test.go index 65cfc77e5e..3ab02bdb24 100644 --- a/pkg/local_object_storage/metabase/containers_test.go +++ b/pkg/local_object_storage/metabase/containers_test.go @@ -26,7 +26,7 @@ func TestDB_Containers(t *testing.T) { for range N { obj := generateObject(t) - cnr, _ := obj.ContainerID() + cnr := obj.GetContainerID() cids[cnr.EncodeToString()] = 0 @@ -49,7 +49,7 @@ func TestDB_Containers(t *testing.T) { assertContains := func(cnrs []cid.ID, cnr cid.ID) { found := false for i := 0; !found && i < len(cnrs); i++ { - found = cnrs[i].Equals(cnr) + found = cnrs[i] == cnr } require.True(t, found) @@ -62,7 +62,7 @@ func TestDB_Containers(t *testing.T) { cnrs, err := db.Containers() require.NoError(t, err) - cnr, _ := obj.ContainerID() + cnr := obj.GetContainerID() assertContains(cnrs, cnr) @@ -80,7 +80,7 @@ func TestDB_Containers(t *testing.T) { cnrs, err := db.Containers() require.NoError(t, err) - cnr, _ := obj.ContainerID() + cnr := obj.GetContainerID() assertContains(cnrs, cnr) require.NoError(t, metaToMoveIt(db, object.AddressOf(obj))) @@ -116,7 +116,7 @@ func TestDB_ContainersCount(t *testing.T) { err := putBig(db, obj) require.NoError(t, err) - cnr, _ := obj.ContainerID() + cnr := obj.GetContainerID() expected = append(expected, cnr) } } @@ -158,7 +158,7 @@ func TestDB_ContainerSize(t *testing.T) { obj := generateObjectWithCID(t, cnr) obj.SetPayloadSize(uint64(size)) - idParent, _ := parent.ID() + idParent := parent.GetID() obj.SetParentID(idParent) obj.SetParent(parent) diff --git a/pkg/local_object_storage/metabase/delete.go b/pkg/local_object_storage/metabase/delete.go index 24d350c7e4..c069db89cb 100644 --- a/pkg/local_object_storage/metabase/delete.go +++ b/pkg/local_object_storage/metabase/delete.go @@ -187,7 +187,7 @@ func (db *DB) delete(tx *bbolt.Tx, addr oid.Address, currEpoch uint64) (bool, bo // if object is an only link to a parent, then remove parent if parent := obj.Parent(); parent != nil { - if _, fullParent := parent.ID(); !fullParent { + if id := parent.GetID(); id.IsZero() { // unfinished header from the first part return false, false, 0, nil } diff --git a/pkg/local_object_storage/metabase/delete_test.go b/pkg/local_object_storage/metabase/delete_test.go index 764f6d4e19..8159a466f5 100644 --- a/pkg/local_object_storage/metabase/delete_test.go +++ b/pkg/local_object_storage/metabase/delete_test.go @@ -23,7 +23,7 @@ func TestDB_Delete(t *testing.T) { child := generateObjectWithCID(t, cnr) child.SetParent(parent) - idParent, _ := parent.ID() + idParent := parent.GetID() child.SetParentID(idParent) // put object with parent @@ -82,7 +82,7 @@ func TestDeleteAllChildren(t *testing.T) { // generate 2 children child1 := generateObjectWithCID(t, cnr) child1.SetParent(parent) - idParent, _ := parent.ID() + idParent := parent.GetID() child1.SetParentID(idParent) child2 := generateObjectWithCID(t, cnr) diff --git a/pkg/local_object_storage/metabase/exists_test.go b/pkg/local_object_storage/metabase/exists_test.go index d773ceeede..86c72b4cf2 100644 --- a/pkg/local_object_storage/metabase/exists_test.go +++ b/pkg/local_object_storage/metabase/exists_test.go @@ -86,7 +86,7 @@ func TestDB_Exists(t *testing.T) { child := generateObjectWithCID(t, cnr) child.SetParent(parent) - idParent, _ := parent.ID() + idParent := parent.GetID() child.SetParentID(idParent) err := putBig(db, child) @@ -107,14 +107,14 @@ func TestDB_Exists(t *testing.T) { child := generateObjectWithCID(t, cnr) child.SetParent(parent) - idParent, _ := parent.ID() + idParent := parent.GetID() child.SetParentID(idParent) child.SetSplitID(splitID) link := generateObjectWithCID(t, cnr) link.SetParent(parent) link.SetParentID(idParent) - idChild, _ := child.ID() + idChild := child.GetID() link.SetChildren(idChild) link.SetSplitID(splitID) @@ -132,12 +132,12 @@ func TestDB_Exists(t *testing.T) { require.ErrorAs(t, err, &si) require.Equal(t, splitID, si.SplitInfo().SplitID()) - id1, _ := child.ID() - id2, _ := si.SplitInfo().LastPart() + id1 := child.GetID() + id2 := si.SplitInfo().GetLastPart() require.Equal(t, id1, id2) - id1, _ = link.ID() - id2, _ = si.SplitInfo().Link() + id1 = link.GetID() + id2 = si.SplitInfo().GetLink() require.Equal(t, id1, id2) }) @@ -155,12 +155,12 @@ func TestDB_Exists(t *testing.T) { require.ErrorAs(t, err, &si) require.Equal(t, splitID, si.SplitInfo().SplitID()) - id1, _ := child.ID() - id2, _ := si.SplitInfo().LastPart() + id1 := child.GetID() + id2 := si.SplitInfo().GetLastPart() require.Equal(t, id1, id2) - id1, _ = link.ID() - id2, _ = si.SplitInfo().Link() + id1 = link.GetID() + id2 = si.SplitInfo().GetLink() require.Equal(t, id1, id2) }) }) diff --git a/pkg/local_object_storage/metabase/get_test.go b/pkg/local_object_storage/metabase/get_test.go index b2ff3d78ae..107cdf55b5 100644 --- a/pkg/local_object_storage/metabase/get_test.go +++ b/pkg/local_object_storage/metabase/get_test.go @@ -87,7 +87,7 @@ func TestDB_Get(t *testing.T) { child := generateObjectWithCID(t, cnr) child.SetParent(parent) - idParent, _ := parent.ID() + idParent := parent.GetID() child.SetParentID(idParent) child.SetSplitID(splitID) @@ -102,12 +102,12 @@ func TestDB_Get(t *testing.T) { require.ErrorAs(t, err, &siErr) require.Equal(t, splitID, siErr.SplitInfo().SplitID()) - id1, _ := child.ID() - id2, _ := siErr.SplitInfo().LastPart() + id1 := child.GetID() + id2 := siErr.SplitInfo().GetLastPart() require.Equal(t, id1, id2) - _, ok := siErr.SplitInfo().Link() - require.False(t, ok) + link := siErr.SplitInfo().GetLink() + require.True(t, link.IsZero()) }) newParent, err := metaGet(db, object.AddressOf(parent), false) @@ -257,7 +257,7 @@ func TestDB_GetContainer(t *testing.T) { o5 := oidtest.ID() o6 := oidtest.ID() - id4, _ := o4.ID() + id4 := o4.GetID() err = db.Lock(cID, id4, []oid.ID{o5, o6}) // locked object have not been put to meta, no new objects require.NoError(t, err) diff --git a/pkg/local_object_storage/metabase/index_test.go b/pkg/local_object_storage/metabase/index_test.go index 1d25778a0a..39a4eff158 100644 --- a/pkg/local_object_storage/metabase/index_test.go +++ b/pkg/local_object_storage/metabase/index_test.go @@ -1,8 +1,9 @@ package meta import ( + crand "crypto/rand" "math" - "math/rand" + "math/rand/v2" "testing" "github.com/nspcc-dev/neo-go/pkg/io" @@ -42,8 +43,7 @@ func Test_decodeList(t *testing.T) { expected := make([][]byte, 20) for i := range expected { expected[i] = make([]byte, rand.Uint32()%10) - //nolint:staticcheck - rand.Read(expected[i]) + _, _ = crand.Read(expected[i]) } data, err := encodeList(expected) diff --git a/pkg/local_object_storage/metabase/inhume.go b/pkg/local_object_storage/metabase/inhume.go index fcb5f7bf13..8c4db6da3c 100644 --- a/pkg/local_object_storage/metabase/inhume.go +++ b/pkg/local_object_storage/metabase/inhume.go @@ -266,8 +266,7 @@ func (db *DB) InhumeContainer(cID cid.ID) (uint64, error) { } var removedAvailable uint64 - rawCID := make([]byte, cidSize) - cID.Encode(rawCID) + rawCID := cID[:] err := db.boltDB.Update(func(tx *bbolt.Tx) error { garbageContainersBKT := tx.Bucket(garbageContainersBucketName) diff --git a/pkg/local_object_storage/metabase/list_test.go b/pkg/local_object_storage/metabase/list_test.go index 2fa8617f87..f8853d34f6 100644 --- a/pkg/local_object_storage/metabase/list_test.go +++ b/pkg/local_object_storage/metabase/list_test.go @@ -121,7 +121,7 @@ func TestLisObjectsWithCursor(t *testing.T) { addAttribute(parent, "foo", "bar") child := generateObjectWithCID(t, containerID) child.SetParent(parent) - idParent, _ := parent.ID() + idParent := parent.GetID() child.SetParentID(idParent) child.SetSplitID(splitID) err = putBig(db, child) diff --git a/pkg/local_object_storage/metabase/lock.go b/pkg/local_object_storage/metabase/lock.go index 676008ddcd..63fa62d9dd 100644 --- a/pkg/local_object_storage/metabase/lock.go +++ b/pkg/local_object_storage/metabase/lock.go @@ -53,7 +53,7 @@ func (db *DB) Lock(cnr cid.ID, locker oid.ID, locked []oid.ID) error { bucketLocked := tx.Bucket(bucketNameLocked) - cnr.Encode(key) + copy(key, cnr[:]) bucketLockedContainer, err := bucketLocked.CreateBucketIfNotExists(key) if err != nil { return fmt.Errorf("create container bucket for locked objects %v: %w", cnr, err) @@ -125,8 +125,7 @@ func (db *DB) FreeLockedBy(lockers []oid.Address) ([]oid.Address, error) { func objectLocked(tx *bbolt.Tx, idCnr cid.ID, idObj oid.ID) bool { bucketLocked := tx.Bucket(bucketNameLocked) if bucketLocked != nil { - key := make([]byte, cidSize) - idCnr.Encode(key) + key := idCnr[:] bucketLockedContainer := bucketLocked.Bucket(key) if bucketLockedContainer != nil { return bucketLockedContainer.Get(objectKey(idObj, key)) != nil @@ -154,7 +153,7 @@ func freePotentialLocks(tx *bbolt.Tx, idCnr cid.ID, locker oid.ID) ([]oid.Addres } key := make([]byte, cidSize) - idCnr.Encode(key) + copy(key, idCnr[:]) bucketLockedContainer := bucketLocked.Bucket(key) if bucketLockedContainer == nil { diff --git a/pkg/local_object_storage/metabase/lock_test.go b/pkg/local_object_storage/metabase/lock_test.go index 85d00ec3c5..1cfbb24166 100644 --- a/pkg/local_object_storage/metabase/lock_test.go +++ b/pkg/local_object_storage/metabase/lock_test.go @@ -40,7 +40,7 @@ func TestDB_Lock(t *testing.T) { var e apistatus.LockNonRegularObject - id, _ := obj.ID() + id := obj.GetID() // try to lock it err = db.Lock(cnr, oidtest.ID(), []oid.ID{id}) @@ -248,14 +248,14 @@ func putAndLockObj(t *testing.T, db *meta.DB, numOfLockedObjs int) ([]*object.Ob err := putBig(db, obj) require.NoError(t, err) - id, _ := obj.ID() + id := obj.GetID() lockedObjs = append(lockedObjs, obj) lockedObjIDs = append(lockedObjIDs, id) } lockObj := generateObjectWithCID(t, cnr) - lockID, _ := lockObj.ID() + lockID := lockObj.GetID() lockObj.SetType(object.TypeLock) err := putBig(db, lockObj) diff --git a/pkg/local_object_storage/metabase/put.go b/pkg/local_object_storage/metabase/put.go index 21d3f97a06..9d8311ba2a 100644 --- a/pkg/local_object_storage/metabase/put.go +++ b/pkg/local_object_storage/metabase/put.go @@ -88,8 +88,8 @@ func (db *DB) Put(prm PutPrm) (res PutRes, err error) { func (db *DB) put( tx *bbolt.Tx, obj *objectSDK.Object, id []byte, si *objectSDK.SplitInfo, currEpoch uint64, hdrBin []byte) error { - cnr, ok := obj.ContainerID() - if !ok { + cnr := obj.GetContainerID() + if cnr.IsZero() { return errors.New("missing container in object") } @@ -123,7 +123,7 @@ func (db *DB) put( } if par := obj.Parent(); par != nil && !isParent { // limit depth by two - if _, set := par.ID(); set { // skip the first object without useful info + if parID := par.GetID(); !parID.IsZero() { // skip the first object without useful info parentSI, err := splitInfoFromObject(obj) if err != nil { return err @@ -260,8 +260,8 @@ func putUniqueIndexes( type updateIndexItemFunc = func(tx *bbolt.Tx, item namedBucketItem) error func updateListIndexes(tx *bbolt.Tx, obj *objectSDK.Object, f updateIndexItemFunc) error { - idObj, _ := obj.ID() - cnr, _ := obj.ContainerID() + idObj := obj.GetID() + cnr := obj.GetContainerID() objKey := objectKey(idObj, make([]byte, objectKeySize)) bucketName := make([]byte, bucketKeySize) @@ -277,10 +277,10 @@ func updateListIndexes(tx *bbolt.Tx, obj *objectSDK.Object, f updateIndexItemFun return err } - idParent, ok := obj.ParentID() + idParent := obj.GetParentID() // index parent ids - if ok { + if !idParent.IsZero() { err := f(tx, namedBucketItem{ name: parentBucketName(cnr, bucketName), key: objectKey(idParent, make([]byte, objectKeySize)), @@ -305,12 +305,9 @@ func updateListIndexes(tx *bbolt.Tx, obj *objectSDK.Object, f updateIndexItemFun // index first object id if firstID, set := obj.FirstID(); set { - rawFirstID := make([]byte, objectKeySize) - firstID.Encode(rawFirstID) - err := f(tx, namedBucketItem{ name: firstObjectIDBucketName(cnr, bucketName), - key: rawFirstID, + key: firstID[:], val: objKey, }) if err != nil { @@ -322,8 +319,8 @@ func updateListIndexes(tx *bbolt.Tx, obj *objectSDK.Object, f updateIndexItemFun } func updateFKBTIndexes(tx *bbolt.Tx, obj *objectSDK.Object, f updateIndexItemFunc) error { - id, _ := obj.ID() - cnr, _ := obj.ContainerID() + id := obj.GetID() + cnr := obj.GetContainerID() objKey := objectKey(id, make([]byte, objectKeySize)) attrs := obj.Attributes() @@ -526,15 +523,15 @@ func splitInfoFromObject(obj *objectSDK.Object) (*objectSDK.SplitInfo, error) { switch { case isLinkObject(obj): - id, ok := obj.ID() - if !ok { + id := obj.GetID() + if id.IsZero() { return nil, errors.New("missing object ID") } info.SetLink(id) case isLastObject(obj): - id, ok := obj.ID() - if !ok { + id := obj.GetID() + if id.IsZero() { return nil, errors.New("missing object ID") } diff --git a/pkg/local_object_storage/metabase/select.go b/pkg/local_object_storage/metabase/select.go index c174d65cae..bc4403792b 100644 --- a/pkg/local_object_storage/metabase/select.go +++ b/pkg/local_object_storage/metabase/select.go @@ -93,7 +93,7 @@ func (db *DB) selectObjects(tx *bbolt.Tx, cnr cid.ID, fs object.SearchFilters, c // if there are conflicts in query and container then it means that there is no // objects to match this query. - if group.withCnrFilter && !cnr.Equals(group.cnr) { + if group.withCnrFilter && cnr != group.cnr { return nil, nil } @@ -484,9 +484,7 @@ func (db *DB) selectObjectID( ok, err := db.exists(tx, addr, currEpoch) if (err == nil && ok) || errors.As(err, &splitInfoError) { - raw := make([]byte, objectKeySize) - id.Encode(raw) - markAddressInCache(to, fNum, string(raw)) + markAddressInCache(to, fNum, string(id[:])) } } diff --git a/pkg/local_object_storage/metabase/select_test.go b/pkg/local_object_storage/metabase/select_test.go index 3e0c65d3ea..6a3a694b0f 100644 --- a/pkg/local_object_storage/metabase/select_test.go +++ b/pkg/local_object_storage/metabase/select_test.go @@ -181,7 +181,7 @@ func TestDB_SelectRootPhyParent(t *testing.T) { rightChild := generateObjectWithCID(t, cnr) rightChild.SetParent(parent) rightChild.SetFirstID(firstChild) - idParent, _ := parent.ID() + idParent := parent.GetID() rightChild.SetParentID(idParent) err = putBig(db, rightChild) require.NoError(t, err) @@ -190,8 +190,8 @@ func TestDB_SelectRootPhyParent(t *testing.T) { link.SetParent(parent) link.SetParentID(idParent) link.SetFirstID(firstChild) - idLeftChild, _ := leftChild.ID() - idRightChild, _ := rightChild.ID() + idLeftChild := leftChild.GetID() + idRightChild := rightChild.GetID() link.SetChildren(idLeftChild, idRightChild) err = putBig(db, link) @@ -289,7 +289,7 @@ func TestDB_SelectRootPhyParent(t *testing.T) { }) t.Run("objects with parent", func(t *testing.T) { - idParent, _ := parent.ID() + idParent := parent.GetID() fs := objectSDK.SearchFilters{} fs.AddParentIDFilter(objectSDK.MatchStringEqual, idParent) @@ -535,7 +535,7 @@ func TestDB_SelectObjectID(t *testing.T) { parent := generateObjectWithCID(t, cnr) regular := generateObjectWithCID(t, cnr) - idParent, _ := parent.ID() + idParent := parent.GetID() regular.SetParentID(idParent) regular.SetParent(parent) @@ -560,7 +560,7 @@ func TestDB_SelectObjectID(t *testing.T) { t.Run("not found objects", func(t *testing.T) { raw := generateObjectWithCID(t, cnr) - id, _ := raw.ID() + id := raw.GetID() fs := objectSDK.SearchFilters{} fs.AddObjectIDFilter(objectSDK.MatchStringEqual, id) @@ -591,7 +591,7 @@ func TestDB_SelectObjectID(t *testing.T) { }) t.Run("regular objects", func(t *testing.T) { - id, _ := regular.ID() + id := regular.GetID() fs := objectSDK.SearchFilters{} fs.AddObjectIDFilter(objectSDK.MatchStringEqual, id) @@ -608,7 +608,7 @@ func TestDB_SelectObjectID(t *testing.T) { }) t.Run("tombstone objects", func(t *testing.T) { - id, _ := ts.ID() + id := ts.GetID() fs := objectSDK.SearchFilters{} fs.AddObjectIDFilter(objectSDK.MatchStringEqual, id) @@ -625,7 +625,7 @@ func TestDB_SelectObjectID(t *testing.T) { }) t.Run("storage group objects", func(t *testing.T) { - id, _ := sg.ID() + id := sg.GetID() fs := objectSDK.SearchFilters{} fs.AddObjectIDFilter(objectSDK.MatchStringEqual, id) @@ -642,7 +642,7 @@ func TestDB_SelectObjectID(t *testing.T) { }) t.Run("parent objects", func(t *testing.T) { - id, _ := parent.ID() + id := parent.GetID() fs := objectSDK.SearchFilters{} fs.AddObjectIDFilter(objectSDK.MatchStringEqual, id) @@ -659,7 +659,7 @@ func TestDB_SelectObjectID(t *testing.T) { }) t.Run("lock objects", func(t *testing.T) { - id, _ := lock.ID() + id := lock.GetID() fs := objectSDK.SearchFilters{} fs.AddObjectIDFilter(objectSDK.MatchStringEqual, id) @@ -811,8 +811,8 @@ func TestExpiredObjects(t *testing.T) { db := newDB(t, meta.WithEpochState(epochState{currEpoch})) checkExpiredObjects(t, db, func(exp, nonExp *objectSDK.Object) { - cidExp, _ := exp.ContainerID() - cidNonExp, _ := nonExp.ContainerID() + cidExp := exp.GetContainerID() + cidNonExp := nonExp.GetContainerID() objs, err := metaSelect(db, cidExp, objectSDK.SearchFilters{}) require.NoError(t, err) @@ -1117,7 +1117,7 @@ func TestSelectNotFilledBucket(t *testing.T) { raw1 := generateObjectWithCID(t, cnr) raw1.SetType(objectSDK.TypeRegular) addAttribute(raw1, "attr", "value") - oID1, _ := raw1.ID() + oID1 := raw1.GetID() raw2 := generateObjectWithCID(t, cnr) raw2.SetType(objectSDK.TypeTombstone) diff --git a/pkg/local_object_storage/metabase/util.go b/pkg/local_object_storage/metabase/util.go index a26f37684e..cd5e67c497 100644 --- a/pkg/local_object_storage/metabase/util.go +++ b/pkg/local_object_storage/metabase/util.go @@ -143,7 +143,7 @@ var splitInfoError *object.SplitInfoError // for errors.As comparisons func bucketName(cnr cid.ID, prefix byte, key []byte) []byte { key[0] = prefix - cnr.Encode(key[1:]) + copy(key[1:], cnr[:]) return key[:bucketKeySize] } @@ -175,7 +175,7 @@ func linkObjectsBucketName(cnr cid.ID, key []byte) []byte { // attributeBucketName returns _attr_. func attributeBucketName(cnr cid.ID, attributeKey string, key []byte) []byte { key[0] = userAttributePrefix - cnr.Encode(key[1:]) + copy(key[1:], cnr[:]) return append(key[:bucketKeySize], attributeKey...) } @@ -219,8 +219,10 @@ func firstObjectIDBucketName(cnr cid.ID, key []byte) []byte { // addressKey returns key for K-V tables when key is a whole address. func addressKey(addr oid.Address, key []byte) []byte { - addr.Container().Encode(key) - addr.Object().Encode(key[cidSize:]) + cnr := addr.Container() + obj := addr.Object() + n := copy(key, cnr[:]) + copy(key[n:], obj[:]) return key[:addressKeySize] } @@ -247,13 +249,13 @@ func decodeAddressFromKey(dst *oid.Address, k []byte) error { // objectKey returns key for K-V tables when key is an object id. func objectKey(obj oid.ID, key []byte) []byte { - obj.Encode(key) + copy(key, obj[:]) return key[:objectKeySize] } // containerKey returns key for K-V tables when key is a container ID. func containerKey(cID cid.ID, key []byte) []byte { - cID.Encode(key) + copy(key, cID[:]) return key[:cidSize] } diff --git a/pkg/local_object_storage/pilorama/boltdb.go b/pkg/local_object_storage/pilorama/boltdb.go index 32047ba1c4..ccf0ace2a0 100644 --- a/pkg/local_object_storage/pilorama/boltdb.go +++ b/pkg/local_object_storage/pilorama/boltdb.go @@ -351,7 +351,7 @@ func (t *boltForest) addBatch(d CIDDescriptor, treeID string, m *Move, ch chan e continue } - found := t.batches[i].cid.Equals(d.CID) && t.batches[i].treeID == treeID + found := t.batches[i].cid == d.CID && t.batches[i].treeID == treeID if found { t.batches[i].results = append(t.batches[i].results, ch) t.batches[i].operations = append(t.batches[i].operations, m) @@ -720,8 +720,7 @@ func (t *boltForest) TreeList(cid cidSDK.ID) ([]string, error) { } var ids []string - cidRaw := make([]byte, 32) - cid.Encode(cidRaw) + cidRaw := cid[:] cidLen := len(cidRaw) @@ -788,8 +787,7 @@ func (t *boltForest) TreeDrop(cid cidSDK.ID, treeID string) error { return t.db.Batch(func(tx *bbolt.Tx) error { if treeID == "" { c := tx.Cursor() - prefix := make([]byte, 32) - cid.Encode(prefix) + prefix := cid[:] for k, _ := c.Seek(prefix); k != nil && bytes.HasPrefix(k, prefix); k, _ = c.Next() { err := tx.DeleteBucket(k) if err != nil { @@ -862,9 +860,8 @@ func (t *boltForest) logToBytes(lm *LogMove) []byte { } func bucketName(cid cidSDK.ID, treeID string) []byte { - treeRoot := make([]byte, 32+len(treeID)) - cid.Encode(treeRoot) - copy(treeRoot[32:], treeID) + treeRoot := make([]byte, cidSDK.Size+len(treeID)) + copy(treeRoot[copy(treeRoot, cid[:]):], treeID) return treeRoot } diff --git a/pkg/local_object_storage/pilorama/meta_test.go b/pkg/local_object_storage/pilorama/meta_test.go index ebca793700..6204f6b1a7 100644 --- a/pkg/local_object_storage/pilorama/meta_test.go +++ b/pkg/local_object_storage/pilorama/meta_test.go @@ -1,7 +1,7 @@ package pilorama import ( - "math/rand" + "crypto/rand" "testing" "github.com/stretchr/testify/require" @@ -55,8 +55,7 @@ func TestMeta_GetAttr(t *testing.T) { make([]byte, 10), } for i := range attr { - //nolint:staticcheck - rand.Read(attr[i]) + _, _ = rand.Read(attr[i]) } m := Meta{Items: []KeyValue{{"abc", attr[0]}, {"xyz", attr[1]}}} diff --git a/pkg/local_object_storage/shard/control.go b/pkg/local_object_storage/shard/control.go index d2917598b5..e626555537 100644 --- a/pkg/local_object_storage/shard/control.go +++ b/pkg/local_object_storage/shard/control.go @@ -213,9 +213,7 @@ func (s *Shard) refillMetabase() error { locked := make([]oid.ID, lock.NumberOfMembers()) lock.ReadMembers(locked) - cnr, _ := obj.ContainerID() - id, _ := obj.ID() - err = s.metaBase.Lock(cnr, id, locked) + err = s.metaBase.Lock(obj.GetContainerID(), obj.GetID(), locked) if err != nil { return fmt.Errorf("could not lock objects: %w", err) } diff --git a/pkg/local_object_storage/shard/control_test.go b/pkg/local_object_storage/shard/control_test.go index 64dd3afcbe..132b5ecf52 100644 --- a/pkg/local_object_storage/shard/control_test.go +++ b/pkg/local_object_storage/shard/control_test.go @@ -181,7 +181,7 @@ func TestRefillMetabase(t *testing.T) { if len(locked) < 2 { obj.SetContainerID(cnrLocked) - id, _ := obj.ID() + id := obj.GetID() locked = append(locked, id) } @@ -208,7 +208,7 @@ func TestRefillMetabase(t *testing.T) { for i := range tombstone.Members() { var a oid.Address a.SetObject(members[i]) - cnr, _ := tombObj.ContainerID() + cnr := tombObj.GetContainerID() a.SetContainer(cnr) tombMembers = append(tombMembers, a) @@ -240,7 +240,7 @@ func TestRefillMetabase(t *testing.T) { _, err = sh.Put(putPrm) require.NoError(t, err) - lockID, _ := lockObj.ID() + lockID := lockObj.GetID() require.NoError(t, sh.Lock(cnrLocked, lockID, locked)) var inhumePrm InhumePrm diff --git a/pkg/local_object_storage/shard/gc_test.go b/pkg/local_object_storage/shard/gc_test.go index 50875eff80..56b590faa2 100644 --- a/pkg/local_object_storage/shard/gc_test.go +++ b/pkg/local_object_storage/shard/gc_test.go @@ -89,14 +89,14 @@ func TestGC_ExpiredObjectWithExpiredLock(t *testing.T) { obj := generateObjectWithCID(cnr) obj.SetAttributes(expAttr) - objID, _ := obj.ID() + objID := obj.GetID() expAttr.SetValue("3") lock := generateObjectWithCID(cnr) lock.SetType(object.TypeLock) lock.SetAttributes(expAttr) - lockID, _ := lock.ID() + lockID := lock.GetID() var putPrm shard.PutPrm putPrm.SetObject(obj) diff --git a/pkg/local_object_storage/shard/get_test.go b/pkg/local_object_storage/shard/get_test.go index 0376f72bff..93c7b10b4c 100644 --- a/pkg/local_object_storage/shard/get_test.go +++ b/pkg/local_object_storage/shard/get_test.go @@ -86,7 +86,7 @@ func testShardGet(t *testing.T, hasWriteCache bool) { child := generateObjectWithCID(cnr) child.SetParent(parent) - idParent, _ := parent.ID() + idParent := parent.GetID() child.SetParentID(idParent) child.SetSplitID(splitID) addPayload(child, 1<<5) @@ -109,10 +109,10 @@ func testShardGet(t *testing.T, hasWriteCache bool) { var si *objectSDK.SplitInfoError require.True(t, errors.As(err, &si)) - _, ok := si.SplitInfo().Link() - require.False(t, ok) - id1, _ := child.ID() - id2, _ := si.SplitInfo().LastPart() + link := si.SplitInfo().GetLink() + require.True(t, link.IsZero()) + id1 := child.GetID() + id2 := si.SplitInfo().GetLastPart() require.Equal(t, id1, id2) require.Equal(t, splitID, si.SplitInfo().SplitID()) }) diff --git a/pkg/local_object_storage/shard/head_test.go b/pkg/local_object_storage/shard/head_test.go index c9bf80c064..31d9b7b567 100644 --- a/pkg/local_object_storage/shard/head_test.go +++ b/pkg/local_object_storage/shard/head_test.go @@ -54,7 +54,7 @@ func testShardHead(t *testing.T, hasWriteCache bool) { child := generateObjectWithCID(cnr) child.SetParent(parent) - idParent, _ := parent.ID() + idParent := parent.GetID() child.SetParentID(idParent) child.SetSplitID(splitID) diff --git a/pkg/local_object_storage/shard/list_test.go b/pkg/local_object_storage/shard/list_test.go index 9ebffe2be1..6b959d3aad 100644 --- a/pkg/local_object_storage/shard/list_test.go +++ b/pkg/local_object_storage/shard/list_test.go @@ -43,7 +43,7 @@ func testShardList(t *testing.T, sh *shard.Shard) { // add parent as virtual object, it must be ignored in List() parent := generateObjectWithCID(cnr) - idParent, _ := parent.ID() + idParent := parent.GetID() obj.SetParentID(idParent) obj.SetParent(parent) diff --git a/pkg/local_object_storage/shard/lock_test.go b/pkg/local_object_storage/shard/lock_test.go index f9e71b6cac..713387061b 100644 --- a/pkg/local_object_storage/shard/lock_test.go +++ b/pkg/local_object_storage/shard/lock_test.go @@ -59,11 +59,11 @@ func TestShard_Lock(t *testing.T) { cnr := cidtest.ID() obj := generateObjectWithCID(cnr) - objID, _ := obj.ID() + objID := obj.GetID() lock := generateObjectWithCID(cnr) lock.SetType(object.TypeLock) - lockID, _ := lock.ID() + lockID := lock.GetID() // put the object @@ -142,8 +142,8 @@ func TestShard_IsLocked(t *testing.T) { cnr := cidtest.ID() obj := generateObjectWithCID(cnr) - cnrID, _ := obj.ContainerID() - objID, _ := obj.ID() + cnrID := obj.GetContainerID() + objID := obj.GetID() lockID := oidtest.ID() diff --git a/pkg/local_object_storage/shard/metrics_test.go b/pkg/local_object_storage/shard/metrics_test.go index 54e1c0b565..959a39f819 100644 --- a/pkg/local_object_storage/shard/metrics_test.go +++ b/pkg/local_object_storage/shard/metrics_test.go @@ -97,7 +97,7 @@ func TestCounters(t *testing.T) { expectedSizes := make(map[string]int64) for i := range oo { - cnr, _ := oo[i].ContainerID() + cnr := oo[i].GetContainerID() oSize := int64(oo[i].PayloadSize()) expectedSizes[cnr.EncodeToString()] += oSize totalPayload += oSize @@ -178,7 +178,7 @@ func TestCounters(t *testing.T) { removedPayload := oo[i].PayloadSize() totalRemovedpayload += removedPayload - cnr, _ := oo[i].ContainerID() + cnr := oo[i].GetContainerID() expectedSizes[cnr.EncodeToString()] -= int64(removedPayload) } require.Equal(t, expectedSizes, mm.containerSize) diff --git a/pkg/local_object_storage/shard/shard_test.go b/pkg/local_object_storage/shard/shard_test.go index df0e5bc896..1a01a8494e 100644 --- a/pkg/local_object_storage/shard/shard_test.go +++ b/pkg/local_object_storage/shard/shard_test.go @@ -110,11 +110,7 @@ func generateObjectWithPayload(cnr cid.ID, data []byte) *object.Object { ver.SetMajor(2) ver.SetMinor(1) - var csum checksum.Checksum - csum.SetSHA256(sha256.Sum256(data)) - - var csumTZ checksum.Checksum - csumTZ.SetTillichZemor(tz.Sum(csum.Value())) + csum := checksum.NewSHA256(sha256.Sum256(data)) obj := object.New() obj.SetID(oidtest.ID()) @@ -124,7 +120,7 @@ func generateObjectWithPayload(cnr cid.ID, data []byte) *object.Object { obj.SetVersion(&ver) obj.SetPayload(data) obj.SetPayloadChecksum(csum) - obj.SetPayloadHomomorphicHash(csumTZ) + obj.SetPayloadHomomorphicHash(checksum.NewTillichZemor(tz.Sum(csum.Value()))) return obj } diff --git a/pkg/local_object_storage/util/splitinfo.go b/pkg/local_object_storage/util/splitinfo.go index 5311cf2950..97160788dc 100644 --- a/pkg/local_object_storage/util/splitinfo.go +++ b/pkg/local_object_storage/util/splitinfo.go @@ -9,15 +9,15 @@ import ( func MergeSplitInfo(from, to *object.SplitInfo) *object.SplitInfo { to.SetSplitID(from.SplitID()) // overwrite SplitID and ignore conflicts - if lp, ok := from.LastPart(); ok { + if lp := from.GetLastPart(); !lp.IsZero() { to.SetLastPart(lp) } - if link, ok := from.Link(); ok { + if link := from.GetLink(); !link.IsZero() { to.SetLink(link) } - if init, ok := from.FirstPart(); ok { + if init := from.GetFirstPart(); !init.IsZero() { to.SetFirstPart(init) } diff --git a/pkg/local_object_storage/util/splitinfo_test.go b/pkg/local_object_storage/util/splitinfo_test.go index 9c9d349e04..3e6224b1ca 100644 --- a/pkg/local_object_storage/util/splitinfo_test.go +++ b/pkg/local_object_storage/util/splitinfo_test.go @@ -1,13 +1,12 @@ package util_test import ( - "math/rand" "testing" "github.com/google/uuid" "github.com/nspcc-dev/neofs-node/pkg/local_object_storage/util" "github.com/nspcc-dev/neofs-sdk-go/object" - oid "github.com/nspcc-dev/neofs-sdk-go/object/id" + oidtest "github.com/nspcc-dev/neofs-sdk-go/object/id/test" "github.com/stretchr/testify/require" ) @@ -18,17 +17,8 @@ func TestMergeSplitInfo(t *testing.T) { splitID := object.NewSplitID() splitID.SetUUID(uid) - var rawLinkID, rawLastID [32]byte - var linkID oid.ID - var lastID oid.ID - //nolint:staticcheck - _, err = rand.Read(rawLinkID[:]) - require.NoError(t, err) - linkID.SetSHA256(rawLinkID) - //nolint:staticcheck - _, err = rand.Read(rawLastID[:]) - require.NoError(t, err) - lastID.SetSHA256(rawLastID) + linkID := oidtest.ID() + lastID := oidtest.ID() target := object.NewSplitInfo() // target is SplitInfo struct with all fields set target.SetSplitID(splitID) diff --git a/pkg/morph/client/audit/list_results.go b/pkg/morph/client/audit/list_results.go index 6f30cf1537..fd96965682 100644 --- a/pkg/morph/client/audit/list_results.go +++ b/pkg/morph/client/audit/list_results.go @@ -1,7 +1,6 @@ package audit import ( - "crypto/sha256" "fmt" "github.com/nspcc-dev/neo-go/pkg/vm/stackitem" @@ -38,8 +37,7 @@ func (c *Client) ListAuditResultIDByEpoch(epoch uint64) ([]ResultID, error) { // ListAuditResultIDByCID returns a list of audit result IDs inside audit // contract for specific epoch number and container ID. func (c *Client) ListAuditResultIDByCID(epoch uint64, cnr cid.ID) ([]ResultID, error) { - binCnr := make([]byte, sha256.Size) - cnr.Encode(binCnr) + binCnr := cnr[:] prm := client.TestInvokePrm{} prm.SetMethod(listByCIDResultsMethod) @@ -55,12 +53,9 @@ func (c *Client) ListAuditResultIDByCID(epoch uint64, cnr cid.ID) ([]ResultID, e // ListAuditResultIDByNode returns a list of audit result IDs inside audit // contract for specific epoch number, container ID and inner ring public key. func (c *Client) ListAuditResultIDByNode(epoch uint64, cnr cid.ID, nodeKey []byte) ([]ResultID, error) { - binCnr := make([]byte, sha256.Size) - cnr.Encode(binCnr) - prm := client.TestInvokePrm{} prm.SetMethod(listByNodeResultsMethod) - prm.SetArgs(epoch, binCnr, nodeKey) + prm.SetArgs(epoch, cnr[:], nodeKey) items, err := c.client.TestInvoke(prm) if err != nil { diff --git a/pkg/morph/client/container/delete.go b/pkg/morph/client/container/delete.go index 5cba5b65a0..a9bc7c682a 100644 --- a/pkg/morph/client/container/delete.go +++ b/pkg/morph/client/container/delete.go @@ -1,7 +1,6 @@ package container import ( - "crypto/sha256" "fmt" core "github.com/nspcc-dev/neofs-node/pkg/core/container" @@ -13,8 +12,8 @@ import ( // // Returns error if container ID is nil. func Delete(c *Client, witness core.RemovalWitness) error { - binCnr := make([]byte, sha256.Size) - witness.ContainerID().Encode(binCnr) + id := witness.ContainerID() + binCnr := id[:] var prm DeletePrm diff --git a/pkg/morph/client/container/eacl.go b/pkg/morph/client/container/eacl.go index 984707956b..e38cf78aeb 100644 --- a/pkg/morph/client/container/eacl.go +++ b/pkg/morph/client/container/eacl.go @@ -1,7 +1,6 @@ package container import ( - "crypto/sha256" "fmt" "github.com/nspcc-dev/neofs-node/pkg/core/container" @@ -17,12 +16,9 @@ import ( // // Returns apistatus.EACLNotFound if eACL table is missing in the contract. func (c *Client) GetEACL(cnr cid.ID) (*container.EACL, error) { - binCnr := make([]byte, sha256.Size) - cnr.Encode(binCnr) - prm := client.TestInvokePrm{} prm.SetMethod(eaclMethod) - prm.SetArgs(binCnr) + prm.SetArgs(cnr[:]) prms, err := c.client.TestInvoke(prm) if err != nil { diff --git a/pkg/morph/client/container/get.go b/pkg/morph/client/container/get.go index 94c5c3f27f..24838baccf 100644 --- a/pkg/morph/client/container/get.go +++ b/pkg/morph/client/container/get.go @@ -1,7 +1,6 @@ package container import ( - "crypto/sha256" "fmt" "strings" @@ -27,10 +26,7 @@ func AsContainerSource(w *Client) containercore.Source { // Get marshals container ID, and passes it to Wrapper's Get method. func Get(c *Client, cnr cid.ID) (*containercore.Container, error) { - binCnr := make([]byte, sha256.Size) - cnr.Encode(binCnr) - - return c.Get(binCnr) + return c.Get(cnr[:]) } // Get reads the container from NeoFS system by binary identifier diff --git a/pkg/morph/client/container/list.go b/pkg/morph/client/container/list.go index 8fb37c266b..823e1d1b4c 100644 --- a/pkg/morph/client/container/list.go +++ b/pkg/morph/client/container/list.go @@ -18,7 +18,7 @@ func (c *Client) List(idUser *user.ID) ([]cid.ID, error) { var rawID []byte if idUser != nil { - rawID = idUser.WalletBytes() + rawID = idUser[:] } prm := client.TestInvokePrm{} diff --git a/pkg/morph/client/container/load.go b/pkg/morph/client/container/load.go index a723b58f62..1ab3214511 100644 --- a/pkg/morph/client/container/load.go +++ b/pkg/morph/client/container/load.go @@ -33,12 +33,11 @@ func (a2 *AnnounceLoadPrm) SetReporter(key []byte) { // // Returns any error encountered that caused the saving to interrupt. func (c *Client) AnnounceLoad(p AnnounceLoadPrm) error { - binCnr := make([]byte, sha256.Size) - p.a.Container().Encode(binCnr) + cnr := p.a.Container() prm := client.InvokePrm{} prm.SetMethod(putSizeMethod) - prm.SetArgs(p.a.Epoch(), binCnr, p.a.Value(), p.key) + prm.SetArgs(p.a.Epoch(), cnr[:], p.a.Value(), p.key) prm.InvokePrmOptional = p.InvokePrmOptional err := c.client.Invoke(prm) diff --git a/pkg/morph/client/container/put.go b/pkg/morph/client/container/put.go index 00f81cc0d2..aec2665fd2 100644 --- a/pkg/morph/client/container/put.go +++ b/pkg/morph/client/container/put.go @@ -34,8 +34,7 @@ func Put(c *Client, cnr containercore.Container) (*cid.ID, error) { return nil, err } - var id cid.ID - id.FromBinary(data) + id := cid.NewFromMarshalledContainer(data) return &id, nil } diff --git a/pkg/morph/client/neofsid/keys.go b/pkg/morph/client/neofsid/keys.go index d0aa9fe2d1..3b58100c54 100644 --- a/pkg/morph/client/neofsid/keys.go +++ b/pkg/morph/client/neofsid/keys.go @@ -23,7 +23,7 @@ func (a *AccountKeysPrm) SetID(id user.ID) { func (x *Client) AccountKeys(p AccountKeysPrm) (keys.PublicKeys, error) { prm := client.TestInvokePrm{} prm.SetMethod(keyListingMethod) - prm.SetArgs(p.id.WalletBytes()) + prm.SetArgs(p.id[:]) items, err := x.client.TestInvoke(prm) if err != nil { diff --git a/pkg/morph/client/netmap/netmap_test.go b/pkg/morph/client/netmap/netmap_test.go index 51be127708..91454e80a6 100644 --- a/pkg/morph/client/netmap/netmap_test.go +++ b/pkg/morph/client/netmap/netmap_test.go @@ -1,8 +1,8 @@ package netmap import ( + "crypto/rand" "math/big" - "math/rand" "strconv" "testing" @@ -16,8 +16,7 @@ func Test_stackItemsToNodeInfos(t *testing.T) { expected := make([]netmap.NodeInfo, 4) for i := range expected { pub := make([]byte, 33) - //nolint:staticcheck - rand.Read(pub) + _, _ = rand.Read(pub) switch i % 3 { default: diff --git a/pkg/morph/event/container/put_test.go b/pkg/morph/event/container/put_test.go index 601f577178..4d928bb6de 100644 --- a/pkg/morph/event/container/put_test.go +++ b/pkg/morph/event/container/put_test.go @@ -1,7 +1,6 @@ package container import ( - "crypto/sha256" "testing" "github.com/nspcc-dev/neo-go/pkg/core/state" @@ -32,8 +31,7 @@ func TestParsePutSuccess(t *testing.T) { id := cidtest.ID() - binID := make([]byte, sha256.Size) - id.Encode(binID) + binID := id[:] t.Run("wrong public key parameter", func(t *testing.T) { _, err := ParsePutSuccess(createNotifyEventFromItems([]stackitem.Item{ diff --git a/pkg/network/transport/object/grpc/replication_test.go b/pkg/network/transport/object/grpc/replication_test.go index a8d4490517..ba4c31e2ec 100644 --- a/pkg/network/transport/object/grpc/replication_test.go +++ b/pkg/network/transport/object/grpc/replication_test.go @@ -108,7 +108,7 @@ func newTestNode(tb testing.TB, serverPubKey, clientPubKey []byte, cnr cid.ID, o } func (x *testNode) ForEachContainerNodePublicKeyInLastTwoEpochs(cnr cid.ID, f func(pubKey []byte) bool) error { - require.True(x.tb, cnr.Equals(x.cnr)) + require.True(x.tb, cnr == x.cnr) require.NotNil(x.tb, f) if x.cnrErr != nil { return x.cnrErr diff --git a/pkg/services/audit/auditor/context.go b/pkg/services/audit/auditor/context.go index 863418b7ba..138190bf0a 100644 --- a/pkg/services/audit/auditor/context.go +++ b/pkg/services/audit/auditor/context.go @@ -273,8 +273,8 @@ func (c *Context) objectHomoHash(id oid.ID) []byte { } func (c *Context) updateHeadResponses(hdr *object.Object) { - id, ok := hdr.ID() - if !ok { + id := hdr.GetID() + if id.IsZero() { return } diff --git a/pkg/services/container/morph/executor.go b/pkg/services/container/morph/executor.go index ff5ca44191..4c9059453b 100644 --- a/pkg/services/container/morph/executor.go +++ b/pkg/services/container/morph/executor.go @@ -383,7 +383,8 @@ func (s *morphExecutor) validateToken(t *sessionV2.Token, cIDV2 *refs.ContainerI return fmt.Errorf("reading container from the network: %w", err) } - if issuer := t.GetBody().GetOwnerID().GetValue(); !bytes.Equal(cnr.Value.Owner().WalletBytes(), issuer) { + owner := cnr.Value.Owner() + if issuer := t.GetBody().GetOwnerID().GetValue(); !bytes.Equal(owner[:], issuer) { return fmt.Errorf("session was not issued by the container owner, issuer: %s", base58.Encode(issuer)) } @@ -394,8 +395,8 @@ func (s *morphExecutor) validateToken(t *sessionV2.Token, cIDV2 *refs.ContainerI return fmt.Errorf("decoding key from signature: %w", err) } - userFromToken := user.ResolveFromECDSAPublicKey(ecdsa.PublicKey(keyFromToken)) - if !cnr.Value.Owner().Equals(userFromToken) { + userFromToken := user.NewFromECDSAPublicKey(ecdsa.PublicKey(keyFromToken)) + if cnr.Value.Owner() != userFromToken { return fmt.Errorf("session token signer differs container owner: signer: %s, owner: %s", userFromToken, cnr.Value.Owner()) } diff --git a/pkg/services/control/server/evacuate.go b/pkg/services/control/server/evacuate.go index 4071994f88..56794a3d44 100644 --- a/pkg/services/control/server/evacuate.go +++ b/pkg/services/control/server/evacuate.go @@ -55,8 +55,8 @@ func (s *Server) EvacuateShard(_ context.Context, req *control.EvacuateShardRequ } func (s *Server) replicate(addr oid.Address, obj *objectSDK.Object) error { - cid, ok := obj.ContainerID() - if !ok { + cid := obj.GetContainerID() + if cid.IsZero() { // Return nil to prevent situations where a shard can't be evacuated // because of a single bad/corrupted object. return nil diff --git a/pkg/services/object/acl/acl.go b/pkg/services/object/acl/acl.go index 60e19dda9c..071b3d66fa 100644 --- a/pkg/services/object/acl/acl.go +++ b/pkg/services/object/acl/acl.go @@ -238,13 +238,13 @@ func isValidBearer(reqInfo v2.RequestInfo, st netmap.State) error { } // 3. Then check if container is either empty or equal to the container in the request. - cnr, isSet := token.EACLTable().CID() - if isSet && !cnr.Equals(reqInfo.ContainerID()) { + cnr := token.EACLTable().GetCID() + if !cnr.IsZero() && cnr != reqInfo.ContainerID() { return errBearerInvalidContainerID } // 4. Then check if container owner signed this token. - if !token.ResolveIssuer().Equals(ownerCnr) { + if token.ResolveIssuer() != ownerCnr { // TODO: #767 in this case we can issue all owner keys from neofs.id and check once again return errBearerNotSignedByOwner } @@ -255,7 +255,7 @@ func isValidBearer(reqInfo v2.RequestInfo, st netmap.State) error { return fmt.Errorf("decode sender public key: %w", err) } - usrSender := user.ResolveFromECDSAPublicKey(ecdsa.PublicKey(*pubKey)) + usrSender := user.NewFromECDSAPublicKey(ecdsa.PublicKey(*pubKey)) if !token.AssertUser(usrSender) { // TODO: #767 in this case we can issue all owner keys from neofs.id and check once again @@ -275,5 +275,5 @@ func isOwnerFromKey(id user.ID, key []byte) bool { return false } - return id.Equals(user.ResolveFromECDSAPublicKey(ecdsa.PublicKey(*pubKey))) + return id == user.NewFromECDSAPublicKey(ecdsa.PublicKey(*pubKey)) } diff --git a/pkg/services/object/acl/eacl/v2/eacl_test.go b/pkg/services/object/acl/eacl/v2/eacl_test.go index 931c91b793..4c5e1e1e7d 100644 --- a/pkg/services/object/acl/eacl/v2/eacl_test.go +++ b/pkg/services/object/acl/eacl/v2/eacl_test.go @@ -15,6 +15,7 @@ import ( oid "github.com/nspcc-dev/neofs-sdk-go/object/id" oidtest "github.com/nspcc-dev/neofs-sdk-go/object/id/test" objecttest "github.com/nspcc-dev/neofs-sdk-go/object/test" + "github.com/nspcc-dev/neofs-sdk-go/user" "github.com/stretchr/testify/require" ) @@ -37,8 +38,8 @@ func (t *testHeaderSource) Head(_ oid.Address) (*object.Object, error) { } func (s *testLocalStorage) Head(addr oid.Address) (*object.Object, error) { - require.True(s.t, addr.Container().Equals(s.expAddr.Container())) - require.True(s.t, addr.Object().Equals(s.expAddr.Object())) + require.True(s.t, addr.Container() == s.expAddr.Container()) + require.True(s.t, addr.Object() == s.expAddr.Object()) return s.obj, s.err } @@ -87,20 +88,20 @@ func TestHeadRequest(t *testing.T) { attr.SetValue(attrVal) obj.SetAttributes(attr) - table := new(eaclSDK.Table) - priv, err := keys.NewPrivateKey() require.NoError(t, err) senderKey := priv.PublicKey() + userID := user.NewFromECDSAPublicKey((ecdsa.PublicKey)(*senderKey)) - r := eaclSDK.NewRecord() - r.SetOperation(eaclSDK.OperationHead) - r.SetAction(eaclSDK.ActionDeny) - r.AddFilter(eaclSDK.HeaderFromObject, eaclSDK.MatchStringEqual, attrKey, attrVal) - r.AddFilter(eaclSDK.HeaderFromRequest, eaclSDK.MatchStringEqual, xKey, xVal) - eaclSDK.AddFormedTarget(r, eaclSDK.RoleUnknown, (ecdsa.PublicKey)(*senderKey)) + tgt := eaclSDK.NewTargetByAccounts([]user.ID{userID}) - table.AddRecord(r) + r := eaclSDK.ConstructRecord( + eaclSDK.ActionDeny, + eaclSDK.OperationHead, + []eaclSDK.Target{tgt}, + eaclSDK.NewObjectPropertyFilter(attrKey, eaclSDK.MatchStringEqual, attrVal), + eaclSDK.NewRequestHeaderFilter(xKey, eaclSDK.MatchStringEqual, xVal)) + table := eaclSDK.ConstructTable([]eaclSDK.Record{r}) lStorage := &testLocalStorage{ t: t, @@ -125,8 +126,8 @@ func TestHeadRequest(t *testing.T) { unit := new(eaclSDK.ValidationUnit). WithContainerID(&cnr). WithOperation(eaclSDK.OperationHead). - WithSenderKey(senderKey.Bytes()). - WithEACLTable(table) + WithAccount(userID). + WithEACLTable(&table) validator := eaclSDK.NewValidator() @@ -148,17 +149,16 @@ func TestHeadRequest(t *testing.T) { r.SetAction(eaclSDK.ActionAllow) - rID := eaclSDK.NewRecord() - rID.SetOperation(eaclSDK.OperationHead) - rID.SetAction(eaclSDK.ActionDeny) - rID.AddObjectIDFilter(eaclSDK.MatchStringEqual, addr.Object()) - eaclSDK.AddFormedTarget(rID, eaclSDK.RoleUnknown, (ecdsa.PublicKey)(*senderKey)) + rID := eaclSDK.ConstructRecord( + eaclSDK.ActionDeny, + eaclSDK.OperationHead, + []eaclSDK.Target{tgt}, + eaclSDK.NewFilterObjectWithID(addr.Object()), + ) - table = eaclSDK.NewTable() - table.AddRecord(r) - table.AddRecord(rID) + table = eaclSDK.ConstructTable([]eaclSDK.Record{r, rID}) - unit.WithEACLTable(table) + unit.WithEACLTable(&table) checkDefaultAction(t, validator, unit.WithHeaderSource(newSource(t))) } @@ -195,7 +195,7 @@ func TestV2Split(t *testing.T) { require.NoError(t, firstObject.CalculateAndSetID()) var firstIDV2 refs.ObjectID - firstID, _ := firstObject.ID() + firstID := firstObject.GetID() firstID.WriteToV2(&firstIDV2) splitV2 := new(objectV2.SplitHeader) @@ -219,15 +219,17 @@ func TestV2Split(t *testing.T) { priv, err := keys.NewPrivateKey() require.NoError(t, err) senderKey := priv.PublicKey() + userID := user.NewFromECDSAPublicKey((ecdsa.PublicKey)(*senderKey)) + + tgt := eaclSDK.NewTargetByAccounts([]user.ID{userID}) + r := eaclSDK.ConstructRecord( + eaclSDK.ActionDeny, + eaclSDK.OperationPut, + []eaclSDK.Target{tgt}, + eaclSDK.NewObjectPropertyFilter(attrKey, eaclSDK.MatchStringEqual, attrVal), + ) - r := eaclSDK.NewRecord() - r.SetOperation(eaclSDK.OperationPut) - r.SetAction(eaclSDK.ActionDeny) - r.AddFilter(eaclSDK.HeaderFromObject, eaclSDK.MatchStringEqual, attrKey, attrVal) - eaclSDK.AddFormedTarget(r, eaclSDK.RoleUnknown, (ecdsa.PublicKey)(*senderKey)) - - table := new(eaclSDK.Table) - table.AddRecord(r) + table := eaclSDK.ConstructTable([]eaclSDK.Record{r}) hdrSrc := &testHeaderSource{} @@ -242,8 +244,8 @@ func TestV2Split(t *testing.T) { unit := new(eaclSDK.ValidationUnit). WithOperation(eaclSDK.OperationPut). - WithEACLTable(table). - WithSenderKey(senderKey.Bytes()) + WithEACLTable(&table). + WithAccount(userID) validator := eaclSDK.NewValidator() diff --git a/pkg/services/object/acl/v2/classifier.go b/pkg/services/object/acl/v2/classifier.go index 3d48f9747d..6205898ba7 100644 --- a/pkg/services/object/acl/v2/classifier.go +++ b/pkg/services/object/acl/v2/classifier.go @@ -38,7 +38,7 @@ func (c senderClassifier) classify( // TODO: #767 get owner from neofs.id if present // if request owner is the same as container owner, return RoleUser - if ownerID.Equals(cnr.Owner()) { + if *ownerID == cnr.Owner() { return &classifyResult{ role: acl.RoleOwner, key: ownerKey, diff --git a/pkg/services/object/acl/v2/request.go b/pkg/services/object/acl/v2/request.go index ff74351f89..b2faca6a5a 100644 --- a/pkg/services/object/acl/v2/request.go +++ b/pkg/services/object/acl/v2/request.go @@ -139,7 +139,7 @@ func (r MetaWithToken) RequestOwner() (*user.ID, []byte, error) { return nil, nil, fmt.Errorf("decode public key: %w", err) } - idSender := user.ResolveFromECDSAPublicKey(ecdsa.PublicKey(*pubKey)) + idSender := user.NewFromECDSAPublicKey(ecdsa.PublicKey(*pubKey)) return &idSender, key, nil } diff --git a/pkg/services/object/acl/v2/util.go b/pkg/services/object/acl/v2/util.go index 38143007f1..fc77b97990 100644 --- a/pkg/services/object/acl/v2/util.go +++ b/pkg/services/object/acl/v2/util.go @@ -151,7 +151,7 @@ func isOwnerFromKey(id user.ID, key []byte) bool { return false } - return id.Equals(user.ResolveFromECDSAPublicKey(ecdsa.PublicKey(*pubKey))) + return id == user.NewFromECDSAPublicKey(ecdsa.PublicKey(*pubKey)) } // assertVerb checks that token verb corresponds to op. diff --git a/pkg/services/object/acl/v2/util_test.go b/pkg/services/object/acl/v2/util_test.go index 852fe52a48..dcc6d72e2d 100644 --- a/pkg/services/object/acl/v2/util_test.go +++ b/pkg/services/object/acl/v2/util_test.go @@ -118,8 +118,8 @@ func TestAssertSessionRelation(t *testing.T) { objOther := oidtest.ID() // make sure ids differ, otherwise test won't work correctly - require.False(t, cnrOther.Equals(cnr)) - require.False(t, objOther.Equals(obj)) + require.False(t, cnrOther == cnr) + require.False(t, objOther == obj) // bind session to the container (required) tok.BindContainer(cnr) diff --git a/pkg/services/object/delete/exec.go b/pkg/services/object/delete/exec.go index 04d6ee0363..a483443d81 100644 --- a/pkg/services/object/delete/exec.go +++ b/pkg/services/object/delete/exec.go @@ -80,7 +80,7 @@ func (exec *execCtx) addMembers(incoming []oid.ID) { for i := range members { for j := 0; j < len(incoming); j++ { // don't use range, slice mutates in body - if members[i].Equals(incoming[j]) { + if members[i] == incoming[j] { incoming = append(incoming[:j], incoming[j+1:]...) j-- } diff --git a/pkg/services/object/get/assemble.go b/pkg/services/object/get/assemble.go index 343cdcd295..ff98bf90ea 100644 --- a/pkg/services/object/get/assemble.go +++ b/pkg/services/object/get/assemble.go @@ -35,10 +35,10 @@ func (exec *execCtx) assemble() { splitInfo := exec.splitInfo() - childID, ok := splitInfo.Link() - if !ok { - childID, ok = splitInfo.LastPart() - if !ok { + childID := splitInfo.GetLink() + if childID.IsZero() { + childID = splitInfo.GetLastPart() + if childID.IsZero() { exec.log.Debug("neither linking nor last part of split-chain is presented in split info") return } @@ -145,8 +145,8 @@ func (exec *execCtx) initFromChild(obj oid.ID) (prev *oid.ID, children []oid.ID) exec.collectedObject.SetPayload(payload) - idPrev, ok := child.PreviousID() - if ok { + idPrev := child.GetPreviousID() + if !idPrev.IsZero() { return &idPrev, child.Children() } @@ -243,20 +243,21 @@ func (exec *execCtx) buildChainInReverse(prev oid.ID) ([]oid.ID, []objectSDK.Ran rngs[index].SetOffset(off) rngs[index].SetLength(sz) - id, _ := head.ID() + id := head.GetID() chain = append(chain, id) } } else { - id, _ := head.ID() + id := head.GetID() chain = append(chain, id) } - prev, withPrev = head.PreviousID() + prev = head.GetPreviousID() + withPrev = !prev.IsZero() } return chain, rngs, true } func equalAddresses(a, b oid.Address) bool { - return a.Container().Equals(b.Container()) && a.Object().Equals(b.Object()) + return a.Container() == b.Container() && a.Object() == b.Object() } diff --git a/pkg/services/object/get/assembly_v2.go b/pkg/services/object/get/assembly_v2.go index 2407fd621d..a0a4bbbe2e 100644 --- a/pkg/services/object/get/assembly_v2.go +++ b/pkg/services/object/get/assembly_v2.go @@ -10,21 +10,21 @@ import ( ) func (exec *execCtx) processV2Split(si *objectSDK.SplitInfo) { - if _, set := si.FirstPart(); !set { + if si.GetFirstPart().IsZero() { exec.log.Debug("no first ID found in V2 split") exec.err = errors.New("v2 split without first object ID") return } - linkID, set := si.Link() - if set && exec.processV2Link(linkID) { + linkID := si.GetLink() + if !linkID.IsZero() && exec.processV2Link(linkID) { return } // fallback to the full chain assembly from the last part - prev, set := si.LastPart() - if !set { + prev := si.GetLastPart() + if prev.IsZero() { exec.log.Debug("neither link, not last part is set in the v2 split information") return } diff --git a/pkg/services/object/get/exec.go b/pkg/services/object/get/exec.go index ada3e44017..428e13f706 100644 --- a/pkg/services/object/get/exec.go +++ b/pkg/services/object/get/exec.go @@ -251,15 +251,15 @@ func (exec execCtx) remoteClient(info clientcore.NodeInfo) (getClient, bool) { } func mergeSplitInfo(dst, src *objectSDK.SplitInfo) { - if last, ok := src.LastPart(); ok { + if last := src.GetLastPart(); !last.IsZero() { dst.SetLastPart(last) } - if link, ok := src.Link(); ok { + if link := src.GetLink(); !link.IsZero() { dst.SetLink(link) } - if first, ok := src.FirstPart(); ok { + if first := src.GetFirstPart(); !first.IsZero() { dst.SetFirstPart(first) } diff --git a/pkg/services/object/get/get_test.go b/pkg/services/object/get/get_test.go index 0e5d80dc1e..79d09b1431 100644 --- a/pkg/services/object/get/get_test.go +++ b/pkg/services/object/get/get_test.go @@ -482,8 +482,7 @@ func TestGetRemoteSmall(t *testing.T) { var cnr container.Container cnr.SetPlacementPolicy(netmaptest.PlacementPolicy()) - var idCnr cid.ID - cnr.CalculateID(&idCnr) + idCnr := cid.NewFromMarshalledContainer(cnr.Marshal()) newSvc := func(b *testPlacementBuilder, c *testClientCache) *Service { svc := &Service{cfg: new(cfg)} @@ -710,7 +709,7 @@ func TestGetRemoteSmall(t *testing.T) { var splitAddr oid.Address splitAddr.SetContainer(idCnr) - idLink, _ := splitInfo.Link() + idLink := splitInfo.GetLink() splitAddr.SetObject(idLink) c1 := newTestClient() @@ -768,7 +767,7 @@ func TestGetRemoteSmall(t *testing.T) { var linkAddr oid.Address linkAddr.SetContainer(idCnr) - idLink, _ := splitInfo.Link() + idLink := splitInfo.GetLink() linkAddr.SetObject(idLink) linkingObj := generateObject(linkAddr, nil, nil, childIDs...) @@ -846,7 +845,7 @@ func TestGetRemoteSmall(t *testing.T) { var linkAddr oid.Address linkAddr.SetContainer(idCnr) - idLink, _ := splitInfo.Link() + idLink := splitInfo.GetLink() linkAddr.SetObject(idLink) linkingObj := generateObject(linkAddr, nil, nil, childIDs...) @@ -929,7 +928,7 @@ func TestGetRemoteSmall(t *testing.T) { var splitAddr oid.Address splitAddr.SetContainer(idCnr) - idLast, _ := splitInfo.LastPart() + idLast := splitInfo.GetLastPart() splitAddr.SetObject(idLast) c1 := newTestClient() @@ -987,7 +986,7 @@ func TestGetRemoteSmall(t *testing.T) { var rightAddr oid.Address rightAddr.SetContainer(idCnr) - idLast, _ := splitInfo.LastPart() + idLast := splitInfo.GetLastPart() rightAddr.SetObject(idLast) rightObj := children[len(children)-1] @@ -1057,7 +1056,7 @@ func TestGetRemoteSmall(t *testing.T) { rightObj := children[len(children)-1] - idLast, _ := splitInfo.LastPart() + idLast := splitInfo.GetLastPart() rightObj.SetID(idLast) rightObj.SetParentID(addr.Object()) rightObj.SetParent(srcObj) diff --git a/pkg/services/object/get/remote.go b/pkg/services/object/get/remote.go index 2cadb23976..566ec6f25e 100644 --- a/pkg/services/object/get/remote.go +++ b/pkg/services/object/get/remote.go @@ -17,12 +17,12 @@ func (exec *execCtx) processNode(info client.NodeInfo) bool { l.Debug("processing node...") - client, ok := exec.remoteClient(info) + remoteClient, ok := exec.remoteClient(info) if !ok { return true } - obj, err := client.getObject(exec, info) + obj, err := remoteClient.getObject(exec, info) var errSplitInfo *objectSDK.SplitInfoError diff --git a/pkg/services/object/put/distributed.go b/pkg/services/object/put/distributed.go index 0fe937c20a..a8a08341f8 100644 --- a/pkg/services/object/put/distributed.go +++ b/pkg/services/object/put/distributed.go @@ -143,7 +143,7 @@ func (t *distributedTarget) Close() (oid.ID, error) { t.objSharedMeta = object.EncodeReplicationMetaInfo(t.obj.GetContainerID(), t.obj.GetID(), t.obj.PayloadSize(), deletedObjs, lockedObjs, t.obj.CreationEpoch(), t.networkMagicNumber) - id, _ := t.obj.ID() + id := t.obj.GetID() return id, t.placementIterator.iterateNodesForObject(id, t.sendObject) } diff --git a/pkg/services/object/put/local.go b/pkg/services/object/put/local.go index cb65806930..bf156d715a 100644 --- a/pkg/services/object/put/local.go +++ b/pkg/services/object/put/local.go @@ -54,7 +54,7 @@ func (t *localTarget) Close() (oid.ID, *neofscrypto.Signature, error) { return oid.ID{}, nil, err } - id, _ := t.obj.ID() + id := t.obj.GetID() return id, nil, nil } @@ -98,8 +98,8 @@ func putObjectLocally(storage ObjectStorage, obj *object.Object, meta objectCore // correct, stores it in the underlying local object storage. Serves operation // similar to local-only [Service.Put] one. func (p *Service) ValidateAndStoreObjectLocally(obj object.Object) error { - cnrID, ok := obj.ContainerID() - if !ok { + cnrID := obj.GetContainerID() + if cnrID.IsZero() { return errors.New("missing container ID") } @@ -114,7 +114,7 @@ func (p *Service) ValidateAndStoreObjectLocally(obj object.Object) error { return errors.New("unsupported payload checksum type") case checksum.SHA256, - checksum.TZ: + checksum.TillichZemor: } maxPayloadSz := p.maxSizeSrc.MaxObjectSize() @@ -142,8 +142,8 @@ func (p *Service) ValidateAndStoreObjectLocally(obj object.Object) error { switch { case !csHomoSet: return errors.New("missing homomorphic payload checksum") - case csHomo.Type() != checksum.TZ: - return fmt.Errorf("wrong/unsupported type of homomorphic payload checksum, expected %s", checksum.TZ) + case csHomo.Type() != checksum.TillichZemor: + return fmt.Errorf("wrong/unsupported type of homomorphic payload checksum, expected %s", checksum.TillichZemor) case len(csHomo.Value()) != tz.Size: return fmt.Errorf("invalid/unsupported length of %s homomorphic payload checksum, expected %d", csHomo.Type(), tz.Size) @@ -166,7 +166,7 @@ func (p *Service) ValidateAndStoreObjectLocally(obj object.Object) error { if !bytes.Equal(h[:], cs.Value()) { return errors.New("payload SHA-256 checksum mismatch") } - case checksum.TZ: + case checksum.TillichZemor: h := tz.Sum(payload) if !bytes.Equal(h[:], cs.Value()) { return errors.New("payload Tillich-Zemor checksum mismatch") diff --git a/pkg/services/object/put/proto.go b/pkg/services/object/put/proto.go index 5cc3c4eccf..3178cff6ea 100644 --- a/pkg/services/object/put/proto.go +++ b/pkg/services/object/put/proto.go @@ -69,8 +69,8 @@ func encodeObjectWithoutPayload(hdr object.Object, pldLen int) (encodedObject, e func encodeReplicateRequestWithoutPayload(signer neofscrypto.Signer, hdr object.Object, pldLen int, signObjectMeta bool) (encodedObject, error) { var res encodedObject - id, ok := hdr.ID() - if !ok { + id := hdr.GetID() + if id.IsZero() { return res, errors.New("missing object ID") } diff --git a/pkg/services/object/put/streamer.go b/pkg/services/object/put/streamer.go index 46517b6bf5..598e9b7ce0 100644 --- a/pkg/services/object/put/streamer.go +++ b/pkg/services/object/put/streamer.go @@ -114,9 +114,9 @@ func (p *Streamer) initTarget(prm *PutInitPrm) error { return errors.New("missing object owner") } - ownerSession := user.ResolveFromECDSAPublicKey(signer.PublicKey) + ownerSession := user.NewFromECDSAPublicKey(signer.PublicKey) - if !ownerObj.Equals(ownerSession) { + if *ownerObj != ownerSession { return fmt.Errorf("(%T) session token is missing but object owner id is different from the default key", p) } } @@ -147,8 +147,8 @@ func (p *Streamer) preparePrm(prm *PutInitPrm) error { return fmt.Errorf("get local node's private key: %w", err) } - idCnr, ok := prm.hdr.ContainerID() - if !ok { + idCnr := prm.hdr.GetContainerID() + if idCnr.IsZero() { return errors.New("missing container ID") } diff --git a/pkg/services/object/put/validation.go b/pkg/services/object/put/validation.go index 2f3fc373d9..4f858865f0 100644 --- a/pkg/services/object/put/validation.go +++ b/pkg/services/object/put/validation.go @@ -63,9 +63,9 @@ func (t *validatingTarget) WriteHeader(obj *objectSDK.Object) error { switch { case !csSet: return errors.New("missing homomorphic payload checksum") - case cs.Type() != checksum.TZ: + case cs.Type() != checksum.TillichZemor: return fmt.Errorf("wrong/unsupported type of homomorphic payload checksum: %s instead of %s", - cs.Type(), checksum.TZ) + cs.Type(), checksum.TillichZemor) case len(cs.Value()) != tz.Size: return fmt.Errorf("invalid/unsupported length of %s homomorphic payload checksum: %d instead of %d", cs.Type(), len(cs.Value()), tz.Size) @@ -82,7 +82,7 @@ func (t *validatingTarget) WriteHeader(obj *objectSDK.Object) error { return fmt.Errorf("(%T) unsupported payload checksum type %v", t, typ) case checksum.SHA256: t.hash = sha256.New() - case checksum.TZ: + case checksum.TillichZemor: t.hash = tz.New() } diff --git a/pkg/services/object/search/search_test.go b/pkg/services/object/search/search_test.go index 1ade31d071..683c6d48d5 100644 --- a/pkg/services/object/search/search_test.go +++ b/pkg/services/object/search/search_test.go @@ -3,7 +3,6 @@ package searchsvc import ( "context" "crypto/rand" - "crypto/sha256" "errors" "fmt" "strconv" @@ -22,6 +21,7 @@ import ( "github.com/nspcc-dev/neofs-sdk-go/netmap" objectsdk "github.com/nspcc-dev/neofs-sdk-go/object" oid "github.com/nspcc-dev/neofs-sdk-go/object/id" + oidtest "github.com/nspcc-dev/neofs-sdk-go/object/id/test" "github.com/stretchr/testify/require" ) @@ -131,21 +131,6 @@ func (ts *testStorage) addResult(addr cid.ID, ids []oid.ID, err error) { } } -func testSHA256() (cs [sha256.Size]byte) { - _, _ = rand.Read(cs[:]) - return cs -} - -func generateIDs(num int) []oid.ID { - res := make([]oid.ID, num) - - for i := range num { - res[i].SetSHA256(testSHA256()) - } - - return res -} - func TestGetLocalOnly(t *testing.T) { ctx := context.Background() @@ -171,7 +156,7 @@ func TestGetLocalOnly(t *testing.T) { svc := newSvc(storage) cnr := cidtest.ID() - ids := generateIDs(10) + ids := oidtest.IDs(10) storage.addResult(cnr, ids, nil) w := new(simpleIDWriter) @@ -252,8 +237,7 @@ func TestGetRemoteSmall(t *testing.T) { var cnr container.Container cnr.SetPlacementPolicy(pp) - var id cid.ID - cnr.CalculateID(&id) + id := cid.NewFromMarshalledContainer(cnr.Marshal()) newSvc := func(b *testPlacementBuilder, c *testClientCache) *Service { svc := &Service{cfg: new(cfg)} @@ -291,11 +275,11 @@ func TestGetRemoteSmall(t *testing.T) { } c1 := newTestStorage() - ids1 := generateIDs(10) + ids1 := oidtest.IDs(10) c1.addResult(id, ids1, nil) c2 := newTestStorage() - ids2 := generateIDs(10) + ids2 := oidtest.IDs(10) c2.addResult(id, ids2, nil) svc := newSvc(builder, &testClientCache{ diff --git a/pkg/services/object/split/verify.go b/pkg/services/object/split/verify.go index 4108a0a886..47c0a4fd62 100644 --- a/pkg/services/object/split/verify.go +++ b/pkg/services/object/split/verify.go @@ -47,8 +47,8 @@ func (v *Verifier) VerifySplit(ctx context.Context, cnr cid.ID, firstID oid.ID, uncheckedChildren = uncheckedChildren[:bound] if leftChild != nil { - leftChildID, _ := leftChild.ID() - prevRead, _ := leftChild.PreviousID() + leftChildID := leftChild.GetID() + prevRead := leftChild.GetPreviousID() prevGot := uncheckedChildren[len(uncheckedChildren)-1].ObjectID() if prevRead != prevGot { @@ -103,7 +103,7 @@ func (v *Verifier) verifyChildGroup(ctx context.Context, cnr cid.ID, firstID oid // check children order for i, o := range receivedObjects { - id, _ := o.ID() + id := o.GetID() if firstObjIncluded && i == 0 { // first object check only @@ -113,13 +113,12 @@ func (v *Verifier) verifyChildGroup(ctx context.Context, cnr cid.ID, firstID oid return nil, fmt.Errorf("link: first object has split firstID: %s", id) } - _, prevSet := o.PreviousID() - if prevSet { + if !o.GetPreviousID().IsZero() { return nil, fmt.Errorf("link: first object has split previousID: %s", id) } } else { - prevRead, prevSet := o.PreviousID() - if !prevSet { + prevRead := o.GetPreviousID() + if prevRead.IsZero() { return nil, fmt.Errorf("link: non-first object does not have previous ID: %s", id) } @@ -128,7 +127,7 @@ func (v *Verifier) verifyChildGroup(ctx context.Context, cnr cid.ID, firstID oid return o, nil } - prevGot, _ := receivedObjects[i-1].ID() + prevGot := receivedObjects[i-1].GetID() if prevRead != prevGot { return nil, fmt.Errorf("link: object %s has wrong previous object: got %s, want: %s", id, prevGot, prevRead) } diff --git a/pkg/services/object/tombstone/verify_test.go b/pkg/services/object/tombstone/verify_test.go index 53327f4de7..8fb9097a58 100644 --- a/pkg/services/object/tombstone/verify_test.go +++ b/pkg/services/object/tombstone/verify_test.go @@ -101,7 +101,7 @@ func TestVerifier_VerifyTomb(t *testing.T) { cnr := cidtest.ID() child := objectWithCnr(cnr, true) - childID, _ := child.ID() + childID := child.GetID() splitID := child.SplitID() var addr oid.Address @@ -126,7 +126,7 @@ func TestVerifier_VerifyTomb(t *testing.T) { t.Run("LINKs can be found", func(t *testing.T) { link := objectWithCnr(cnr, false) link.SetChildren(childID) - linkID, _ := link.ID() + linkID := link.GetID() objectcore.AddressOf(&link) @@ -231,7 +231,7 @@ func childrenResMap(cnr cid.ID, heads []object.Object) map[oid.Address]headRes { addr.SetContainer(cnr) for _, obj := range heads { - oID, _ := obj.ID() + oID := obj.GetID() addr.SetObject(oID) obj.SetContainerID(cnr) @@ -248,7 +248,7 @@ func childrenResMap(cnr cid.ID, heads []object.Object) map[oid.Address]headRes { func objectsToOIDs(oo []object.Object) []oid.ID { res := make([]oid.ID, len(oo)) for _, obj := range oo { - oID, _ := obj.ID() + oID := obj.GetID() res = append(res, oID) } diff --git a/pkg/services/object/util/chain.go b/pkg/services/object/util/chain.go index ad280c7c3c..52082875bb 100644 --- a/pkg/services/object/util/chain.go +++ b/pkg/services/object/util/chain.go @@ -65,8 +65,8 @@ func iterateV1Split(r ObjectSource, info *object.SplitInfo, cID cid.ID, handler var addr oid.Address addr.SetContainer(cID) - linkID, ok := info.Link() - if ok { + linkID := info.GetLink() + if !linkID.IsZero() { addr.SetObject(linkID) linkObj, err := headFromReceiver(r, addr) @@ -92,8 +92,8 @@ func iterateV1Split(r ObjectSource, info *object.SplitInfo, cID cid.ID, handler return nil } - lastID, ok := info.LastPart() - if ok { + lastID := info.GetLastPart() + if !lastID.IsZero() { addr.SetObject(lastID) return iterateFromLastObject(r, addr, handler) } @@ -105,8 +105,8 @@ func iterateV2Split(r ObjectSource, info *object.SplitInfo, cID cid.ID, handler var addr oid.Address addr.SetContainer(cID) - linkID, ok := info.Link() - if ok { + linkID := info.GetLink() + if !linkID.IsZero() { addr.SetObject(linkID) linkObjRaw, err := r.Get(addr) @@ -140,8 +140,8 @@ func iterateV2Split(r ObjectSource, info *object.SplitInfo, cID cid.ID, handler return nil } - lastID, ok := info.LastPart() - if ok { + lastID := info.GetLastPart() + if !lastID.IsZero() { addr.SetObject(lastID) return iterateFromLastObject(r, addr, handler) } @@ -159,11 +159,11 @@ func iterateFromLastObject(r ObjectSource, lastAddr oid.Address, handler func(*o return err } - oID, _ := obj.ID() + oID := obj.GetID() idBuff = append(idBuff, oID) - prevOID, set := obj.PreviousID() - if !set { + prevOID := obj.GetPreviousID() + if prevOID.IsZero() { break } @@ -224,13 +224,13 @@ func traverseSplitChain(r ObjectSource, addr oid.Address, h SplitMemberHandler) case *object.Object: return h(res, false), nil case *object.SplitInfo: - link, withLink := res.Link() - last, withLast := res.LastPart() + link := res.GetLink() + last := res.GetLastPart() switch { default: return false, errors.New("lack of split information") - case withLink: + case !link.IsZero(): var addr oid.Address addr.SetContainer(cnr) addr.SetObject(link) @@ -273,18 +273,18 @@ func traverseSplitChain(r ObjectSource, addr oid.Address, h SplitMemberHandler) return true, nil } } - case withLast: + case !last.IsZero(): var addr oid.Address addr.SetContainer(cnr) - for last, withLast = res.LastPart(); withLast; { + for last = res.GetLastPart(); !last.IsZero(); { addr.SetObject(last) var directChain []*object.Object if _, err := traverseSplitChain(r, addr, func(member *object.Object, reverseDirection bool) (stop bool) { if reverseDirection { - last, withLast = member.PreviousID() + last = member.GetPreviousID() return h(member, true) } @@ -302,7 +302,7 @@ func traverseSplitChain(r ObjectSource, addr oid.Address, h SplitMemberHandler) } if len(directChain) > 0 { - last, withLast = directChain[len(directChain)-1].PreviousID() + last = directChain[len(directChain)-1].GetPreviousID() } } } diff --git a/pkg/services/object_manager/placement/netmap.go b/pkg/services/object_manager/placement/netmap.go index 6e275ed985..4a5e2a5b64 100644 --- a/pkg/services/object_manager/placement/netmap.go +++ b/pkg/services/object_manager/placement/netmap.go @@ -1,7 +1,6 @@ package placement import ( - "crypto/sha256" "fmt" "slices" "sync" @@ -58,8 +57,7 @@ func (b *netMapBuilder) BuildPlacement(cnr cid.ID, obj *oid.ID, p netmapSDK.Plac return nil, fmt.Errorf("could not get network map: %w", err) } - binCnr := make([]byte, sha256.Size) - cnr.Encode(binCnr) + binCnr := cnr[:] b.mtx.Lock() if nm == b.lastNm { diff --git a/pkg/services/object_manager/placement/traverser.go b/pkg/services/object_manager/placement/traverser.go index 6fca550931..4e3af6c5cb 100644 --- a/pkg/services/object_manager/placement/traverser.go +++ b/pkg/services/object_manager/placement/traverser.go @@ -254,7 +254,7 @@ func ForContainer(cnr container.Container) Option { return func(c *cfg) { c.policy = cnr.PlacementPolicy() c.policySet = true - cnr.CalculateID(&c.cnr) + c.cnr = cid.NewFromMarshalledContainer(cnr.Marshal()) } } diff --git a/pkg/services/object_manager/storagegroup/collect.go b/pkg/services/object_manager/storagegroup/collect.go index ae489556a8..67b7cca504 100644 --- a/pkg/services/object_manager/storagegroup/collect.go +++ b/pkg/services/object_manager/storagegroup/collect.go @@ -40,8 +40,8 @@ func CollectMembers(r objutil.ObjectSource, cnr cid.ID, members []oid.ID, calcHo var errMember error if err := objutil.IterateSplitLeaves(r, addr, func(leaf *object.Object) bool { - id, ok := leaf.ID() - if !ok { + id := leaf.GetID() + if id.IsZero() { errMember = errMissingSplitMemberID return true } @@ -54,8 +54,8 @@ func CollectMembers(r objutil.ObjectSource, cnr cid.ID, members []oid.ID, calcHo if !csSet { errMember = fmt.Errorf("%w '%s'", errMissingHomomorphicChecksum, id) return true - } else if cs.Type() != checksum.TZ { - errMember = fmt.Errorf("%w: type '%s' instead of '%s'", errInvalidHomomorphicChecksum, cs.Type(), checksum.TZ) + } else if cs.Type() != checksum.TillichZemor { + errMember = fmt.Errorf("%w: type '%s' instead of '%s'", errInvalidHomomorphicChecksum, cs.Type(), checksum.TillichZemor) return true } phyHashes = append(phyHashes, cs.Value()) @@ -76,11 +76,10 @@ func CollectMembers(r objutil.ObjectSource, cnr cid.ID, members []oid.ID, calcHo if calcHomoHash { sumHash, err := tz.Concat(phyHashes) if err != nil { - return nil, fmt.Errorf("concatenate '%s' checksums of all members: %w", checksum.TZ, err) + return nil, fmt.Errorf("concatenate '%s' checksums of all members: %w", checksum.TillichZemor, err) } - var cs checksum.Checksum - cs.SetTillichZemor([tz.Size]byte(sumHash)) + cs := checksum.NewTillichZemor([tz.Size]byte(sumHash)) sg.SetValidationDataHash(cs) } diff --git a/pkg/services/object_manager/storagegroup/collect_test.go b/pkg/services/object_manager/storagegroup/collect_test.go index e075c8a2f2..f135752fb0 100644 --- a/pkg/services/object_manager/storagegroup/collect_test.go +++ b/pkg/services/object_manager/storagegroup/collect_test.go @@ -39,8 +39,7 @@ func TestCollectMembers(t *testing.T) { var child object.Object child.SetID(oidtest.ID()) - var cs checksum.Checksum - cs.SetSHA256([sha256.Size]byte{1}) // any non-homomorphic + cs := checksum.NewSHA256([sha256.Size]byte{1}) // any non-homomorphic child.SetPayloadHomomorphicHash(cs) @@ -53,8 +52,8 @@ func TestCollectMembers(t *testing.T) { t.Run("missing member's child ID", func(t *testing.T) { var child object.Object - _, ok := child.ID() - require.False(t, ok) + id := child.GetID() + require.True(t, id.IsZero()) src := &mockedObjects{hdr: &child} diff --git a/pkg/services/session/storage/persistent/executor.go b/pkg/services/session/storage/persistent/executor.go index 0f3abd6ef9..331995c058 100644 --- a/pkg/services/session/storage/persistent/executor.go +++ b/pkg/services/session/storage/persistent/executor.go @@ -48,7 +48,7 @@ func (s *TokenStore) Create(_ context.Context, body *session.CreateRequestBody) err = s.db.Update(func(tx *bbolt.Tx) error { rootBucket := tx.Bucket(sessionsBucket) - ownerBucket, err := rootBucket.CreateBucketIfNotExists(id.WalletBytes()) + ownerBucket, err := rootBucket.CreateBucketIfNotExists(id[:]) if err != nil { return fmt.Errorf( "could not get/create %s owner bucket: %w", id, err) diff --git a/pkg/services/session/storage/persistent/storage.go b/pkg/services/session/storage/persistent/storage.go index 66c02fddb1..3452886139 100644 --- a/pkg/services/session/storage/persistent/storage.go +++ b/pkg/services/session/storage/persistent/storage.go @@ -87,7 +87,7 @@ func (s *TokenStore) Get(ownerID user.ID, tokenID []byte) (t *storage.PrivateTok err := s.db.View(func(tx *bbolt.Tx) error { rootBucket := tx.Bucket(sessionsBucket) - ownerBucket := rootBucket.Bucket(ownerID.WalletBytes()) + ownerBucket := rootBucket.Bucket(ownerID[:]) if ownerBucket == nil { return nil } diff --git a/pkg/services/session/storage/temporary/executor.go b/pkg/services/session/storage/temporary/executor.go index 873e677b0a..3f207baffb 100644 --- a/pkg/services/session/storage/temporary/executor.go +++ b/pkg/services/session/storage/temporary/executor.go @@ -38,7 +38,7 @@ func (s *TokenStore) Create(_ context.Context, body *session.CreateRequestBody) s.mtx.Lock() s.tokens[key{ tokenID: base58.Encode(uidBytes), - ownerID: base58.Encode(id.WalletBytes()), + ownerID: base58.Encode(id[:]), }] = storage.NewPrivateToken(&sk.PrivateKey, body.GetExpiration()) s.mtx.Unlock() diff --git a/pkg/services/session/storage/temporary/storage.go b/pkg/services/session/storage/temporary/storage.go index 67f3f57170..9b25f2ebb4 100644 --- a/pkg/services/session/storage/temporary/storage.go +++ b/pkg/services/session/storage/temporary/storage.go @@ -41,7 +41,7 @@ func (s *TokenStore) Get(ownerID user.ID, tokenID []byte) *storage.PrivateToken s.mtx.RLock() t := s.tokens[key{ tokenID: base58.Encode(tokenID), - ownerID: base58.Encode(ownerID.WalletBytes()), + ownerID: base58.Encode(ownerID[:]), }] s.mtx.RUnlock() diff --git a/pkg/services/tree/replicator.go b/pkg/services/tree/replicator.go index 253d444a49..d7aab6d834 100644 --- a/pkg/services/tree/replicator.go +++ b/pkg/services/tree/replicator.go @@ -2,7 +2,6 @@ package tree import ( "context" - "crypto/sha256" "encoding/hex" "errors" "fmt" @@ -155,12 +154,9 @@ func (s *Service) pushToQueue(cid cidSDK.ID, treeID string, op *pilorama.LogMove } func newApplyRequest(op *movePair) *ApplyRequest { - rawCID := make([]byte, sha256.Size) - op.cid.Encode(rawCID) - return &ApplyRequest{ Body: &ApplyRequest_Body{ - ContainerId: rawCID, + ContainerId: op.cid[:], TreeId: op.treeID, Operation: &LogMove{ ParentId: op.op.Parent, diff --git a/pkg/services/tree/signature.go b/pkg/services/tree/signature.go index d8476103af..c3f64923f6 100644 --- a/pkg/services/tree/signature.go +++ b/pkg/services/tree/signature.go @@ -90,7 +90,7 @@ func (s *Service) verifyClient(req message, cid cidSDK.ID, rawBearer []byte, op if err = bt.Unmarshal(rawBearer); err != nil { return eACLErr(eaclOp, fmt.Errorf("invalid bearer token: %w", err)) } - if !bt.ResolveIssuer().Equals(cnr.Value.Owner()) { + if bt.ResolveIssuer() != cnr.Value.Owner() { return eACLErr(eaclOp, errBearerWrongOwner) } if !bt.AssertContainer(cid) { @@ -172,9 +172,9 @@ func roleFromReq(cnr *core.Container, req message) (acl.Role, error) { return role, fmt.Errorf("decode public key from signature: %w", err) } - reqSigner := user.ResolveFromECDSAPublicKey(ecdsa.PublicKey(*pubKey)) + reqSigner := user.NewFromECDSAPublicKey(ecdsa.PublicKey(*pubKey)) - if reqSigner.Equals(owner) { + if reqSigner == owner { role = acl.RoleOwner } @@ -240,9 +240,9 @@ func checkEACL(tb eacl.Table, signer []byte, role eacl.Role, op eacl.Operation) func targetMatches(rec eacl.Record, role eacl.Role, signer []byte) bool { for _, target := range rec.Targets() { - // check public key match - if pubs := target.BinaryKeys(); len(pubs) != 0 { - for _, key := range pubs { + // check raw subjects match + if rawSubjects := target.RawSubjects(); len(rawSubjects) != 0 { + for _, key := range rawSubjects { if bytes.Equal(key, signer) { return true } diff --git a/pkg/services/tree/signature_test.go b/pkg/services/tree/signature_test.go index fb68d9c466..cf51d92839 100644 --- a/pkg/services/tree/signature_test.go +++ b/pkg/services/tree/signature_test.go @@ -1,7 +1,6 @@ package tree import ( - "crypto/sha256" "errors" "testing" @@ -78,7 +77,7 @@ func TestMessageSign(t *testing.T) { signer := user.NewAutoIDSignerRFC6979(privs[0].PrivateKey) - ownerID := user.ResolveFromECDSAPublicKey(privs[0].PrivateKey.PublicKey) + ownerID := user.NewFromECDSAPublicKey(privs[0].PrivateKey.PublicKey) cnr := &containercore.Container{ Value: testContainer(ownerID), @@ -95,12 +94,9 @@ func TestMessageSign(t *testing.T) { }, } - rawCID1 := make([]byte, sha256.Size) - cid1.Encode(rawCID1) - req := &MoveRequest{ Body: &MoveRequest_Body{ - ContainerId: rawCID1, + ContainerId: cid1[:], ParentId: 1, NodeId: 2, Meta: []*KeyValue{ @@ -201,43 +197,29 @@ func TestMessageSign(t *testing.T) { } func testBearerToken(cid cid.ID, forPutGet, forGet *keys.PublicKey) bearer.Token { - tgtGet := eaclSDK.NewTarget() - tgtGet.SetRole(eaclSDK.RoleUnknown) - tgtGet.SetBinaryKeys([][]byte{forPutGet.Bytes(), forGet.Bytes()}) + tgtGet := eaclSDK.NewTargetByRole(eaclSDK.RoleUnspecified) + tgtGet.SetRawSubjects([][]byte{forPutGet.Bytes(), forGet.Bytes()}) - rGet := eaclSDK.NewRecord() - rGet.SetAction(eaclSDK.ActionAllow) - rGet.SetOperation(eaclSDK.OperationGet) - rGet.SetTargets(*tgtGet) + rGet := eaclSDK.ConstructRecord(eaclSDK.ActionAllow, eaclSDK.OperationGet, []eaclSDK.Target{tgtGet}) - tgtPut := eaclSDK.NewTarget() - tgtPut.SetRole(eaclSDK.RoleUnknown) - tgtPut.SetBinaryKeys([][]byte{forPutGet.Bytes()}) + tgtPut := eaclSDK.NewTargetByRole(eaclSDK.RoleUnspecified) + tgtPut.SetRawSubjects([][]byte{forPutGet.Bytes()}) - rPut := eaclSDK.NewRecord() - rPut.SetAction(eaclSDK.ActionAllow) - rPut.SetOperation(eaclSDK.OperationPut) - rPut.SetTargets(*tgtPut) + rPut := eaclSDK.ConstructRecord(eaclSDK.ActionAllow, eaclSDK.OperationPut, []eaclSDK.Target{tgtPut}) - tb := eaclSDK.NewTable() - tb.AddRecord(rGet) - tb.AddRecord(rPut) + tb := eaclSDK.ConstructTable([]eaclSDK.Record{rGet, rPut}) - tgt := eaclSDK.NewTarget() - tgt.SetRole(eaclSDK.RoleOthers) + tgt := eaclSDK.NewTargetByRole(eaclSDK.RoleOthers) for _, op := range []eaclSDK.Operation{eaclSDK.OperationGet, eaclSDK.OperationPut} { - r := eaclSDK.NewRecord() - r.SetAction(eaclSDK.ActionDeny) - r.SetTargets(*tgt) - r.SetOperation(op) - tb.AddRecord(r) + r := eaclSDK.ConstructRecord(eaclSDK.ActionDeny, op, []eaclSDK.Target{tgt}) + tb.SetRecords(append(tb.Records(), r)) } tb.SetCID(cid) var b bearer.Token - b.SetEACLTable(*tb) + b.SetEACLTable(tb) return b } diff --git a/pkg/services/tree/sync.go b/pkg/services/tree/sync.go index 1ea238c26f..7e320594ad 100644 --- a/pkg/services/tree/sync.go +++ b/pkg/services/tree/sync.go @@ -2,7 +2,6 @@ package tree import ( "context" - "crypto/sha256" "errors" "fmt" "io" @@ -51,12 +50,9 @@ func (s *Service) synchronizeAllTrees(ctx context.Context, cid cid.ID) error { return nil } - rawCID := make([]byte, sha256.Size) - cid.Encode(rawCID) - req := &TreeListRequest{ Body: &TreeListRequest_Body{ - ContainerId: rawCID, + ContainerId: cid[:], }, } @@ -188,14 +184,11 @@ func (s *Service) synchronizeTree(ctx context.Context, d pilorama.CIDDescriptor, } func (s *Service) synchronizeSingle(ctx context.Context, d pilorama.CIDDescriptor, treeID string, height uint64, treeClient TreeServiceClient) (uint64, error) { - rawCID := make([]byte, sha256.Size) - d.CID.Encode(rawCID) - for { newHeight := height req := &GetOpLogRequest{ Body: &GetOpLogRequest_Body{ - ContainerId: rawCID, + ContainerId: d.CID[:], TreeId: treeID, Height: newHeight, },