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 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
  1. package poseidon
  2. import (
  3. "bytes"
  4. "errors"
  5. "hash"
  6. )
  7. type hasher 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 &hasher{
  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 (h *hasher) Write(p []byte) (n int, err error) {
  30. return h.buf.Write(p)
  31. }
  32. // Sum returns the Poseidon digest of the data.
  33. func (h *hasher) Sum(b []byte) []byte {
  34. hahs, err := HashBytesX(h.buf.Bytes(), h.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 (h *hasher) Reset() {
  42. h.buf.Reset()
  43. }
  44. // Size returns the number of bytes Sum will return.
  45. func (h *hasher) Size() int {
  46. return 32
  47. }
  48. // BlockSize returns the hash block size.
  49. func (h *hasher) BlockSize() int {
  50. return spongeChunkSize
  51. }