Add ReverseString, ToReverseScriptHash method (#281)

* Added
1) ReverseString method to the Uint160 type
2) ToReverseScriptHash method to convert a base58 address to a reverse script hash

* Simplified ToScriptHash method
This commit is contained in:
dauTT 2019-08-05 09:34:31 +02:00 committed by Anthony De Meulemeester
parent fb672c00ad
commit b9b118d3ea
4 changed files with 46 additions and 7 deletions

View file

@ -1,22 +1,27 @@
package address package address
import ( import (
"encoding/hex"
"github.com/CityOfZion/neo-go/pkg/crypto/base58" "github.com/CityOfZion/neo-go/pkg/crypto/base58"
"github.com/CityOfZion/neo-go/pkg/wire/util" "github.com/CityOfZion/neo-go/pkg/wire/util"
) )
// ToScriptHash converts an address to a script hash // ToScriptHash converts an address to a script hash
func ToScriptHash(address string) string { func ToScriptHash(address string) string {
a, err := Uint160Decode(address)
decodedAddressAsBytes, err := base58.Decode(address)
if err != nil { if err != nil {
return "" return ""
} }
decodedAddressAsHex := hex.EncodeToString(decodedAddressAsBytes) return a.String()
scriptHash := (decodedAddressAsHex[2:42])
return scriptHash }
// ToReverseScriptHash converts an address to a reverse script hash
func ToReverseScriptHash(address string) string {
a, err := Uint160Decode(address)
if err != nil {
return ""
}
return a.ReverseString()
} }
// FromUint160 returns the "NEO address" from the given // FromUint160 returns the "NEO address" from the given

View file

@ -0,0 +1,17 @@
package address
import (
"testing"
"github.com/stretchr/testify/assert"
)
func TestScriptHash(t *testing.T) {
address := "AJeAEsmeD6t279Dx4n2HWdUvUmmXQ4iJvP"
hash := ToScriptHash(address)
reverseHash := ToReverseScriptHash(address)
assert.Equal(t, "b28427088a3729b2536d10122960394e8be6721f", reverseHash)
assert.Equal(t, "1f72e68b4e39602912106d53b229378a082784b2", hash)
}

View file

@ -68,6 +68,11 @@ func (u Uint160) String() string {
return hex.EncodeToString(u.Bytes()) return hex.EncodeToString(u.Bytes())
} }
// ReverseString implements the stringer interface.
func (u Uint160) ReverseString() string {
return hex.EncodeToString(u.BytesReverse())
}
// Equals returns true if both Uint256 values are the same. // Equals returns true if both Uint256 values are the same.
func (u Uint160) Equals(other Uint160) bool { func (u Uint160) Equals(other Uint160) bool {
for i := 0; i < uint160Size; i++ { for i := 0; i < uint160Size; i++ {

View file

@ -48,3 +48,15 @@ func TestUInt160Equals(t *testing.T) {
t.Fatalf("%s and %s must be equal", ua, ua) t.Fatalf("%s and %s must be equal", ua, ua)
} }
} }
func TestUInt160String(t *testing.T) {
hexStr := "b28427088a3729b2536d10122960394e8be6721f"
hexRevStr := "1f72e68b4e39602912106d53b229378a082784b2"
val, err := Uint160DecodeString(hexStr)
assert.Nil(t, err)
assert.Equal(t, hexStr, val.String())
assert.Equal(t, hexRevStr, val.ReverseString())
}