Skip to content

Commit f06c4f1

Browse files
authored
feat: helper functions for generating blake2b hashes (#692)
1 parent 9eff0ee commit f06c4f1

File tree

1 file changed

+54
-3
lines changed

1 file changed

+54
-3
lines changed

ledger/common/common.go

Lines changed: 54 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -25,7 +25,13 @@ import (
2525
"golang.org/x/crypto/blake2b"
2626
)
2727

28-
type Blake2b256 [32]byte
28+
const (
29+
Blake2b256Size = 32
30+
Blake2b224Size = 28
31+
Blake2b160Size = 20
32+
)
33+
34+
type Blake2b256 [Blake2b256Size]byte
2935

3036
func NewBlake2b256(data []byte) Blake2b256 {
3137
b := Blake2b256{}
@@ -41,7 +47,22 @@ func (b Blake2b256) Bytes() []byte {
4147
return b[:]
4248
}
4349

44-
type Blake2b224 [28]byte
50+
// Blake2b256Hash generates a Blake2b-256 hash from the provided data
51+
func Blake2b256Hash(data []byte) Blake2b256 {
52+
tmpHash, err := blake2b.New(Blake2b256Size, nil)
53+
if err != nil {
54+
panic(
55+
fmt.Sprintf(
56+
"unexpected error generating empty blake2b hash: %s",
57+
err,
58+
),
59+
)
60+
}
61+
tmpHash.Write(data)
62+
return Blake2b256(tmpHash.Sum(nil))
63+
}
64+
65+
type Blake2b224 [Blake2b224Size]byte
4566

4667
func NewBlake2b224(data []byte) Blake2b224 {
4768
b := Blake2b224{}
@@ -57,7 +78,22 @@ func (b Blake2b224) Bytes() []byte {
5778
return b[:]
5879
}
5980

60-
type Blake2b160 [20]byte
81+
// Blake2b224Hash generates a Blake2b-224 hash from the provided data
82+
func Blake2b224Hash(data []byte) Blake2b224 {
83+
tmpHash, err := blake2b.New(Blake2b224Size, nil)
84+
if err != nil {
85+
panic(
86+
fmt.Sprintf(
87+
"unexpected error generating empty blake2b hash: %s",
88+
err,
89+
),
90+
)
91+
}
92+
tmpHash.Write(data)
93+
return Blake2b224(tmpHash.Sum(nil))
94+
}
95+
96+
type Blake2b160 [Blake2b160Size]byte
6197

6298
func NewBlake2b160(data []byte) Blake2b160 {
6399
b := Blake2b160{}
@@ -73,6 +109,21 @@ func (b Blake2b160) Bytes() []byte {
73109
return b[:]
74110
}
75111

112+
// Blake2b160Hash generates a Blake2b-160 hash from the provided data
113+
func Blake2b160Hash(data []byte) Blake2b160 {
114+
tmpHash, err := blake2b.New(Blake2b160Size, nil)
115+
if err != nil {
116+
panic(
117+
fmt.Sprintf(
118+
"unexpected error generating empty blake2b hash: %s",
119+
err,
120+
),
121+
)
122+
}
123+
tmpHash.Write(data)
124+
return Blake2b160(tmpHash.Sum(nil))
125+
}
126+
76127
type MultiAssetTypeOutput = uint64
77128
type MultiAssetTypeMint = int64
78129

0 commit comments

Comments
 (0)