github.com/gnolang/gno@v0.0.0-20240520182011-228e9d0192ce/tm2/pkg/crypto/tmhash/hash.go (about) 1 package tmhash 2 3 import ( 4 "crypto/sha256" 5 "hash" 6 ) 7 8 const ( 9 Size = sha256.Size 10 BlockSize = sha256.BlockSize 11 ) 12 13 // New returns a new hash.Hash. 14 func New() hash.Hash { 15 return sha256.New() 16 } 17 18 // Sum returns the SHA256 of the bz. 19 func Sum(bz []byte) []byte { 20 h := sha256.Sum256(bz) 21 return h[:] 22 } 23 24 //------------------------------------------------------------- 25 26 const ( 27 TruncatedSize = 20 28 ) 29 30 type sha256trunc struct { 31 sha256 hash.Hash 32 } 33 34 func (h sha256trunc) Write(p []byte) (n int, err error) { 35 return h.sha256.Write(p) 36 } 37 38 func (h sha256trunc) Sum(b []byte) []byte { 39 shasum := h.sha256.Sum(b) 40 return shasum[:TruncatedSize] 41 } 42 43 func (h sha256trunc) Reset() { 44 h.sha256.Reset() 45 } 46 47 func (h sha256trunc) Size() int { 48 return TruncatedSize 49 } 50 51 func (h sha256trunc) BlockSize() int { 52 return h.sha256.BlockSize() 53 } 54 55 // NewTruncated returns a new hash.Hash. 56 func NewTruncated() hash.Hash { 57 return sha256trunc{ 58 sha256: sha256.New(), 59 } 60 } 61 62 // SumTruncated returns the first 20 bytes of SHA256 of the bz. 63 func SumTruncated(bz []byte) []byte { 64 hash := sha256.Sum256(bz) 65 return hash[:TruncatedSize] 66 }