hash: simplify Sha256 implementations

Use sha256.Sum256() and drop duplicating Sum() completely.
This commit is contained in:
Roman Khimov 2019-08-23 17:08:19 +03:00
parent 5c5878968b
commit 80c3c9035a
2 changed files with 15 additions and 47 deletions

View file

@ -10,33 +10,18 @@ import (
// Sha256 hashes the incoming byte slice
// using the sha256 algorithm
func Sha256(data []byte) (util.Uint256, error) {
var hash util.Uint256
hasher := sha256.New()
hasher.Reset()
_, err := hasher.Write(data)
hash, err = util.Uint256DecodeBytes(hasher.Sum(nil))
if err != nil {
return hash, err
}
return hash, nil
func Sha256(data []byte) util.Uint256 {
hash := sha256.Sum256(data)
return hash
}
// DoubleSha256 performs sha256 twice on the given data
func DoubleSha256(data []byte) (util.Uint256, error) {
func DoubleSha256(data []byte) util.Uint256 {
var hash util.Uint256
h1, err := Sha256(data)
if err != nil {
return hash, err
}
hash, err = Sha256(h1.Bytes())
if err != nil {
return hash, err
}
return hash, nil
h1 := Sha256(data)
hash = Sha256(h1.Bytes())
return hash
}
// RipeMD160 performs the RIPEMD160 hash algorithm
@ -58,7 +43,7 @@ func RipeMD160(data []byte) (util.Uint160, error) {
// on the given data
func Hash160(data []byte) (util.Uint160, error) {
var hash util.Uint160
h1, err := Sha256(data)
h1 := Sha256(data)
h2, err := RipeMD160(h1.Bytes())
@ -72,17 +57,7 @@ func Hash160(data []byte) (util.Uint160, error) {
// Checksum returns the checksum for a given piece of data
// using sha256 twice as the hash algorithm
func Checksum(data []byte) ([]byte, error) {
hash, err := Sum(data)
if err != nil {
return nil, err
}
return hash[:4], nil
}
// Sum performs sha256 twice on the given data
// XXX(issue): We should remove this and just do doublesha256
func Sum(b []byte) (util.Uint256, error) {
hash, err := DoubleSha256((b))
return hash, err
func Checksum(data []byte) []byte {
hash := DoubleSha256(data)
return hash[:4]
}

View file

@ -9,11 +9,8 @@ import (
func TestSha256(t *testing.T) {
input := []byte("hello")
data, err := Sha256(input)
data := Sha256(input)
if err != nil {
t.Fatal(err)
}
expected := "2cf24dba5fb0a30e26e83b2ac5b9e29e1b161e5c1fa7425e73043362938b9824"
actual := hex.EncodeToString(data.Bytes())
@ -22,14 +19,10 @@ func TestSha256(t *testing.T) {
func TestHashDoubleSha256(t *testing.T) {
input := []byte("hello")
data, err := DoubleSha256(input)
data := DoubleSha256(input)
if err != nil {
t.Fatal(err)
}
firstSha, _ := Sha256(input)
doubleSha, _ := Sha256(firstSha.Bytes())
firstSha := Sha256(input)
doubleSha := Sha256(firstSha.Bytes())
expected := hex.EncodeToString(doubleSha.Bytes())
actual := hex.EncodeToString(data.Bytes())