github.com/nspcc-dev/neo-go@v0.105.2-0.20240517133400-6be757af3eba/pkg/crypto/hash/hash.go (about) 1 package hash 2 3 import ( 4 "crypto/sha256" 5 "encoding/binary" 6 7 "github.com/nspcc-dev/neo-go/pkg/util" 8 "golang.org/x/crypto/ripemd160" //nolint:staticcheck // SA1019: package golang.org/x/crypto/ripemd160 is deprecated 9 ) 10 11 // Hashable represents an object which can be hashed. Usually, these objects 12 // are io.Serializable and signable. They tend to cache the hash inside for 13 // effectiveness, providing this accessor method. Anything that can be 14 // identified with a hash can then be signed and verified. 15 type Hashable interface { 16 Hash() util.Uint256 17 } 18 19 // GetSignedData returns the concatenated byte slice containing of the network 20 // magic in constant-length 4-bytes LE representation and hashable item hash in BE 21 // representation. 22 func GetSignedData(net uint32, hh Hashable) []byte { 23 var b = make([]byte, 4+util.Uint256Size) 24 binary.LittleEndian.PutUint32(b, net) 25 h := hh.Hash() 26 copy(b[4:], h[:]) 27 return b 28 } 29 30 // NetSha256 calculates a network-specific hash of the Hashable item that can then 31 // be signed/verified. 32 func NetSha256(net uint32, hh Hashable) util.Uint256 { 33 return Sha256(GetSignedData(net, hh)) 34 } 35 36 // Sha256 hashes the incoming byte slice 37 // using the sha256 algorithm. 38 func Sha256(data []byte) util.Uint256 { 39 hash := sha256.Sum256(data) 40 return hash 41 } 42 43 // DoubleSha256 performs sha256 twice on the given data. 44 func DoubleSha256(data []byte) util.Uint256 { 45 var hash util.Uint256 46 47 h1 := Sha256(data) 48 hash = Sha256(h1.BytesBE()) 49 return hash 50 } 51 52 // RipeMD160 performs the RIPEMD160 hash algorithm 53 // on the given data. 54 func RipeMD160(data []byte) util.Uint160 { 55 var hash util.Uint160 56 hasher := ripemd160.New() 57 _, _ = hasher.Write(data) 58 59 hasher.Sum(hash[:0]) 60 return hash 61 } 62 63 // Hash160 performs sha256 and then ripemd160 64 // on the given data. 65 func Hash160(data []byte) util.Uint160 { 66 h1 := Sha256(data) 67 h2 := RipeMD160(h1.BytesBE()) 68 69 return h2 70 } 71 72 // Checksum returns the checksum for a given piece of data 73 // using DoubleSha256 as the hash algorithm. It returns the 74 // first 4 bytes of the resulting slice. 75 func Checksum(data []byte) []byte { 76 hash := DoubleSha256(data) 77 return hash[:4] 78 }