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.

87 lines
2.3 KiB

  1. package arbo
  2. import (
  3. "crypto/sha256"
  4. "math/big"
  5. "github.com/iden3/go-iden3-crypto/poseidon"
  6. )
  7. var (
  8. // TypeHashSha256 represents the label for the HashFunction of Sha256
  9. TypeHashSha256 = []byte("sha256")
  10. // TypeHashPoseidon represents the label for the HashFunction of
  11. // Poseidon
  12. TypeHashPoseidon = []byte("poseidon")
  13. // HashFunctionSha256 contains the HashSha256 struct which implements
  14. // the HashFunction interface
  15. HashFunctionSha256 HashSha256
  16. // HashFunctionPoseidon contains the HashPoseidon struct which implements
  17. // the HashFunction interface
  18. HashFunctionPoseidon HashPoseidon
  19. )
  20. // Once Generics are at Go, this will be updated (August 2021
  21. // https://blog.golang.org/generics-next-step)
  22. // HashFunction defines the interface that is expected for a hash function to be
  23. // used in a generic way in the Tree.
  24. type HashFunction interface {
  25. Type() []byte
  26. Len() int
  27. Hash(...[]byte) ([]byte, error)
  28. // CheckInputs checks if the inputs are valid without computing the hash
  29. // CheckInputs(...[]byte) error
  30. }
  31. // HashSha256 implements the HashFunction interface for the Sha256 hash
  32. type HashSha256 struct{}
  33. // Type returns the type of HashFunction for the HashSha256
  34. func (f HashSha256) Type() []byte {
  35. return TypeHashSha256
  36. }
  37. // Len returns the length of the Hash output
  38. func (f HashSha256) Len() int {
  39. return 32 //nolint:gomnd
  40. }
  41. // Hash implements the hash method for the HashFunction HashSha256
  42. func (f HashSha256) Hash(b ...[]byte) ([]byte, error) {
  43. var toHash []byte
  44. for i := 0; i < len(b); i++ {
  45. toHash = append(toHash, b[i]...)
  46. }
  47. h := sha256.Sum256(toHash)
  48. return h[:], nil
  49. }
  50. // HashPoseidon implements the HashFunction interface for the Poseidon hash
  51. type HashPoseidon struct{}
  52. // Type returns the type of HashFunction for the HashPoseidon
  53. func (f HashPoseidon) Type() []byte {
  54. return TypeHashPoseidon
  55. }
  56. // Len returns the length of the Hash output
  57. func (f HashPoseidon) Len() int {
  58. return 32 //nolint:gomnd
  59. }
  60. // Hash implements the hash method for the HashFunction HashPoseidon
  61. func (f HashPoseidon) Hash(b ...[]byte) ([]byte, error) {
  62. var toHash []*big.Int
  63. for i := 0; i < len(b); i++ {
  64. bi := BytesToBigInt(b[i])
  65. toHash = append(toHash, bi)
  66. }
  67. h, err := poseidon.Hash(toHash)
  68. if err != nil {
  69. return nil, err
  70. }
  71. hB := BigIntToBytes(h)
  72. return hB, nil
  73. }