From 72fe884faab237ffe8f5f7ccef6ed939285e9fd4 Mon Sep 17 00:00:00 2001 From: Evgenii Stratonikov Date: Tue, 3 Dec 2019 16:14:44 +0300 Subject: [PATCH] util: add Uint160DecodeStringLE() --- pkg/util/uint160.go | 16 ++++++++++++++++ pkg/util/uint160_test.go | 10 ++++++++++ 2 files changed, 26 insertions(+) diff --git a/pkg/util/uint160.go b/pkg/util/uint160.go index 9e63f4dce..151685a57 100644 --- a/pkg/util/uint160.go +++ b/pkg/util/uint160.go @@ -26,6 +26,22 @@ func Uint160DecodeStringBE(s string) (Uint160, error) { return Uint160DecodeBytesBE(b) } +// Uint160DecodeStringLE attempts to decode the given string +// in little-endian hex encoding into an Uint160. +func Uint160DecodeStringLE(s string) (Uint160, error) { + var u Uint160 + if len(s) != Uint160Size*2 { + return u, fmt.Errorf("expected string size of %d got %d", Uint160Size*2, len(s)) + } + + b, err := hex.DecodeString(s) + if err != nil { + return u, err + } + + return Uint160DecodeBytesLE(b) +} + // Uint160DecodeBytesBE attempts to decode the given bytes into an Uint160. func Uint160DecodeBytesBE(b []byte) (u Uint160, err error) { if len(b) != Uint160Size { diff --git a/pkg/util/uint160_test.go b/pkg/util/uint160_test.go index 96edcca3a..c5c978a96 100644 --- a/pkg/util/uint160_test.go +++ b/pkg/util/uint160_test.go @@ -35,12 +35,22 @@ func TestUInt160DecodeString(t *testing.T) { assert.NoError(t, err) assert.Equal(t, hexStr, val.String()) + valLE, err := Uint160DecodeStringLE(hexStr) + assert.NoError(t, err) + assert.Equal(t, val, valLE.Reverse()) + _, err = Uint160DecodeStringBE(hexStr[1:]) assert.Error(t, err) + _, err = Uint160DecodeStringLE(hexStr[1:]) + assert.Error(t, err) + hexStr = "zz3b96ae1bcc5a585e075e3b81920210dec16302" _, err = Uint160DecodeStringBE(hexStr) assert.Error(t, err) + + _, err = Uint160DecodeStringLE(hexStr) + assert.Error(t, err) } func TestUint160DecodeBytes(t *testing.T) {