You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

60 lines
1.2 KiB

  1. package poseidon
  2. import (
  3. "bytes"
  4. "errors"
  5. "hash"
  6. )
  7. type digest struct {
  8. buf *bytes.Buffer
  9. frameSize int
  10. }
  11. // Sum returns the Poseidon hash of the input bytes.
  12. // use frame size of 16 inputs by default
  13. func Sum(b []byte) []byte {
  14. h, _ := New(16)
  15. h.Write(b)
  16. return h.Sum(nil)
  17. }
  18. // New returns a new hash.Hash computing the Poseidon hash.
  19. func New(frameSize int) (hash.Hash, error) {
  20. if frameSize < 2 || frameSize > 16 {
  21. return nil, errors.New("incorrect frame size")
  22. }
  23. return &digest{
  24. buf: bytes.NewBuffer([]byte{}),
  25. frameSize: frameSize,
  26. }, nil
  27. }
  28. // Write (via the embedded io.Writer interface) adds more data to the running hash.
  29. func (d *digest) Write(p []byte) (n int, err error) {
  30. return d.buf.Write(p)
  31. }
  32. // Sum returns the Poseidon checksum of the data.
  33. func (d *digest) Sum(b []byte) []byte {
  34. hahs, err := HashBytesX(d.buf.Bytes(), d.frameSize)
  35. if err != nil {
  36. panic(err)
  37. }
  38. return append(b, hahs.Bytes()...)
  39. }
  40. // Reset resets the Hash to its initial state.
  41. func (d *digest) Reset() {
  42. d.buf.Reset()
  43. }
  44. // Size returns the number of bytes Sum will return.
  45. func (d *digest) Size() int {
  46. return 32
  47. }
  48. // BlockSize returns the hash block size.
  49. func (d *digest) BlockSize() int {
  50. return spongeChunkSize
  51. }