[#134] owner: Add helpers for working script hash

Signed-off-by: Evgenii Stratonikov <evgeniy@nspcc.ru>
This commit is contained in:
Evgenii Stratonikov 2022-02-24 15:30:47 +03:00 committed by LeL
parent 5ed064eba5
commit 32af7251f2
3 changed files with 32 additions and 0 deletions

View file

@ -32,3 +32,15 @@ func TestPublicKeyToBytes(t *testing.T) {
require.Equal(t, expected, actual)
require.Equal(t, NEO3WalletSize, len(actual))
}
func TestScriptHashToIDBytes(t *testing.T) {
p, err := keys.NewPrivateKey()
require.NoError(t, err)
expected, err := base58.Decode(p.PublicKey().Address())
require.NoError(t, err)
actual := ScriptHashToIDBytes(p.GetScriptHash())
require.Equal(t, expected, actual)
require.Equal(t, NEO3WalletSize, len(actual))
}

View file

@ -10,6 +10,7 @@ import (
"github.com/nspcc-dev/neo-go/pkg/crypto/hash"
"github.com/nspcc-dev/neo-go/pkg/crypto/keys"
"github.com/nspcc-dev/neo-go/pkg/encoding/address"
"github.com/nspcc-dev/neo-go/pkg/util"
"github.com/nspcc-dev/neo-go/pkg/wallet"
"github.com/nspcc-dev/neofs-api-go/v2/refs"
)
@ -47,6 +48,11 @@ func (id *ID) SetPublicKey(pub *ecdsa.PublicKey) {
(*refs.OwnerID)(id).SetValue(PublicKeyToIDBytes(pub))
}
// SetScriptHash sets owner identifier value to the provided NEO3 script hash.
func (id *ID) SetScriptHash(u util.Uint160) {
(*refs.OwnerID)(id).SetValue(ScriptHashToIDBytes(u))
}
// ToV2 returns the v2 owner ID message.
//
// Nil ID converts to nil.
@ -144,6 +150,11 @@ func (id *ID) UnmarshalJSON(data []byte) error {
// make it clear that no errors can occur.
func PublicKeyToIDBytes(pub *ecdsa.PublicKey) []byte {
sh := (*keys.PublicKey)(pub).GetScriptHash()
return ScriptHashToIDBytes(sh)
}
// ScriptHashToIDBytes converts NEO3 script hash to a byte slice of NEO3WalletSize length.
func ScriptHashToIDBytes(sh util.Uint160) []byte {
b := make([]byte, NEO3WalletSize)
b[0] = address.Prefix
copy(b[1:], sh.BytesBE())

View file

@ -163,3 +163,12 @@ func TestNewID(t *testing.T) {
require.Nil(t, idV2.GetValue())
})
}
func TestID_SetScriptHash(t *testing.T) {
p, err := keys.NewPrivateKey()
require.NoError(t, err)
id := NewID()
id.SetScriptHash(p.GetScriptHash())
require.Equal(t, p.Address(), id.String())
}