From 9e2842b4ad239c1f997df4c88cff922973501c83 Mon Sep 17 00:00:00 2001 From: Pavel Karpy Date: Tue, 23 Nov 2021 16:19:58 +0300 Subject: [PATCH] [#174] subnet: Add `UserAllowed` method Signed-off-by: Pavel Karpy --- subnet/subnet_contract.go | 26 ++++++++++++++++++++++++++ tests/subnet_test.go | 19 +++++++++++++++++++ 2 files changed, 45 insertions(+) diff --git a/subnet/subnet_contract.go b/subnet/subnet_contract.go index 601577f..52ad553 100644 --- a/subnet/subnet_contract.go +++ b/subnet/subnet_contract.go @@ -442,6 +442,32 @@ func RemoveUser(subnetID []byte, groupID []byte, userID []byte) { deleteKeyFromList(ctx, userID, stKey) } +const groupIDSize = 4 + +// UserAllowed returns bool that indicates if node is included in the +// specified subnet or not. +func UserAllowed(subnetID []byte, user []byte) bool { + ctx := storage.GetContext() + + stKey := append([]byte{ownerPrefix}, subnetID...) + if storage.Get(ctx, stKey) == nil { + panic("userAllowed: " + ErrSubNotExist) + } + + stKey[0] = userPrefix + prefixLen := len(stKey) + groupIDSize + + iter := storage.Find(ctx, stKey, storage.KeysOnly) + for iterator.Next(iter) { + key := iterator.Value(iter).([]byte) + if common.BytesEqual(user, key[prefixLen:]) { + return true + } + } + + return false +} + // Version returns version of the contract. func Version() int { return common.Version diff --git a/tests/subnet_test.go b/tests/subnet_test.go index b1a6e52..19a0533 100644 --- a/tests/subnet_test.go +++ b/tests/subnet_test.go @@ -285,6 +285,25 @@ func TestSubnet_RemoveUser(t *testing.T) { cAdm.InvokeFail(t, method+errSeparator+subnet.ErrUserNotExist, method, id, groupId, user) } +func TestSubnet_UserAllowed(t *testing.T) { + e := newSubnetInvoker(t) + + id, owner := createSubnet(t, e) + + groupId := randomBytes(4) + + user := randomBytes(27) + + const method = "userAllowed" + + cOwn := e.WithSigners(owner) + cOwn.InvokeFail(t, method+errSeparator+subnet.ErrSubNotExist, method, []byte{0, 0, 0, 0}, user) + + cOwn.Invoke(t, stackitem.NewBool(false), method, id, user) + cOwn.Invoke(t, stackitem.Null{}, "addUser", id, groupId, user) + cOwn.Invoke(t, stackitem.NewBool(true), method, id, user) +} + func createSubnet(t *testing.T, e *neotest.ContractInvoker) (id []byte, owner neotest.Signer) { var ( ok bool