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.

58 lines
1.5 KiB

3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
  1. package merkletree
  2. import (
  3. "math/big"
  4. "github.com/iden3/go-iden3-crypto/poseidon"
  5. )
  6. // HashElems performs a poseidon hash over the array of ElemBytes, currently we
  7. // are using 2 elements. Uses poseidon.Hash to be compatible with the circom
  8. // circuits implementations.
  9. func HashElems(elems ...*big.Int) (*Hash, error) {
  10. poseidonHash, err := poseidon.Hash(elems)
  11. if err != nil {
  12. return nil, err
  13. }
  14. return NewHashFromBigInt(poseidonHash), nil
  15. }
  16. // HashElemsKey performs a poseidon hash over the array of ElemBytes, currently
  17. // we are using 2 elements.
  18. func HashElemsKey(key *big.Int, elems ...*big.Int) (*Hash, error) {
  19. if key == nil {
  20. key = new(big.Int).SetInt64(0)
  21. }
  22. bi := make([]*big.Int, 3)
  23. copy(bi[:], elems)
  24. bi[2] = key
  25. poseidonHash, err := poseidon.Hash(bi)
  26. if err != nil {
  27. return nil, err
  28. }
  29. return NewHashFromBigInt(poseidonHash), nil
  30. }
  31. // SetBitBigEndian sets the bit n in the bitmap to 1, in Big Endian.
  32. func SetBitBigEndian(bitmap []byte, n uint) {
  33. bitmap[uint(len(bitmap))-n/8-1] |= 1 << (n % 8)
  34. }
  35. // TestBit tests whether the bit n in bitmap is 1.
  36. func TestBit(bitmap []byte, n uint) bool {
  37. return bitmap[n/8]&(1<<(n%8)) != 0
  38. }
  39. // TestBitBigEndian tests whether the bit n in bitmap is 1, in Big Endian.
  40. func TestBitBigEndian(bitmap []byte, n uint) bool {
  41. return bitmap[uint(len(bitmap))-n/8-1]&(1<<(n%8)) != 0
  42. }
  43. // SwapEndianness swaps the order of the bytes in the slice.
  44. func SwapEndianness(b []byte) []byte {
  45. o := make([]byte, len(b))
  46. for i := range b {
  47. o[len(b)-1-i] = b[i]
  48. }
  49. return o
  50. }