From c9d38aa2e1d659e4c0b9d934c7b9e5fd64059e50 Mon Sep 17 00:00:00 2001 From: Leonard Lyubich Date: Mon, 31 Aug 2020 10:46:10 +0300 Subject: [PATCH] [#128] sdk: Implement owner ID type Signed-off-by: Leonard Lyubich --- pkg/owner/id.go | 52 ++++++++++++++++++++++++++++++++++++++++++++ pkg/owner/id_test.go | 27 +++++++++++++++++++++++ 2 files changed, 79 insertions(+) create mode 100644 pkg/owner/id.go create mode 100644 pkg/owner/id_test.go diff --git a/pkg/owner/id.go b/pkg/owner/id.go new file mode 100644 index 0000000..d00cd9e --- /dev/null +++ b/pkg/owner/id.go @@ -0,0 +1,52 @@ +package owner + +import ( + "crypto/sha256" + + "github.com/nspcc-dev/neofs-api-go/pkg/refs" + refsV2 "github.com/nspcc-dev/neofs-api-go/v2/refs" + "github.com/pkg/errors" +) + +// ID represents owner identifier that +// supports different type of values. +type ID struct { + val []byte +} + +// SetNeo3Wallet sets owner identifier value to NEO3 wallet address. +func (id *ID) SetNeo3Wallet(v *refs.NEO3Wallet) { + if id != nil { + id.val = v.Bytes() + } +} + +// ToV2 returns the v2 owner ID message. +func (id *ID) ToV2() *refsV2.OwnerID { + if id != nil { + idV2 := new(refsV2.OwnerID) + idV2.SetValue(id.val) + + return idV2 + } + + return nil +} + +func IDFromV2(idV2 *refsV2.OwnerID) (*ID, error) { + if idV2 == nil { + return nil, nil + } + + val := idV2.GetValue() + if ln := len(val); ln != 25 { + return nil, errors.Errorf( + "could not convert %T to %T: expected length %d, received %d", + idV2, (*ID)(nil), sha256.Size, ln, + ) + } + + return &ID{ + val: val, + }, nil +} diff --git a/pkg/owner/id_test.go b/pkg/owner/id_test.go new file mode 100644 index 0000000..56c39a6 --- /dev/null +++ b/pkg/owner/id_test.go @@ -0,0 +1,27 @@ +package owner + +import ( + "crypto/rand" + "testing" + + "github.com/nspcc-dev/neofs-api-go/pkg/refs" + "github.com/stretchr/testify/require" +) + +func TestIDV2(t *testing.T) { + id := new(ID) + + wallet := new(refs.NEO3Wallet) + + _, err := rand.Read(wallet.Bytes()) + require.NoError(t, err) + + id.SetNeo3Wallet(wallet) + + idV2 := id.ToV2() + + id2, err := IDFromV2(idV2) + require.NoError(t, err) + + require.Equal(t, id, id2) +}