2019-02-25 22:44:14 +00:00
|
|
|
package checksum
|
|
|
|
|
|
|
|
import (
|
|
|
|
"bytes"
|
|
|
|
"encoding/binary"
|
|
|
|
|
|
|
|
"github.com/CityOfZion/neo-go/pkg/crypto/hash"
|
|
|
|
)
|
|
|
|
|
2019-03-17 18:26:35 +00:00
|
|
|
// Compare calculates the checksum of b
|
|
|
|
// then compares it with the `have` checksum passed as a parameter
|
2019-02-25 22:44:14 +00:00
|
|
|
func Compare(have uint32, b []byte) bool {
|
|
|
|
want := FromBytes(b)
|
|
|
|
return have == want
|
|
|
|
}
|
|
|
|
|
2019-03-17 18:26:35 +00:00
|
|
|
// FromBuf calculates the checksum of a buffer
|
2019-02-25 22:44:14 +00:00
|
|
|
func FromBuf(buf *bytes.Buffer) uint32 {
|
|
|
|
|
|
|
|
return FromBytes(buf.Bytes())
|
|
|
|
}
|
|
|
|
|
2019-03-17 18:26:35 +00:00
|
|
|
// FromBytes calculates the checksum of a byte slice
|
2019-02-25 22:44:14 +00:00
|
|
|
func FromBytes(buf []byte) uint32 {
|
|
|
|
b, err := hash.DoubleSha256(buf)
|
|
|
|
|
|
|
|
if err != nil {
|
|
|
|
return 0
|
|
|
|
}
|
|
|
|
|
|
|
|
// checksum := SumSHA256(SumSHA256(buf.Bytes()))
|
|
|
|
return binary.LittleEndian.Uint32(b.Bytes()[:4])
|
|
|
|
}
|