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.

88 lines
2.3 KiB

  1. package babyjub
  2. import (
  3. "bytes"
  4. "encoding/hex"
  5. "fmt"
  6. "math/big"
  7. "strings"
  8. "github.com/dchest/blake512" // I have personally reviewed that this module doesn't do anything suspicious
  9. )
  10. // SwapEndianness swaps the endianness of the value encoded in xs. If xs is
  11. // Big-Endian, the result will be Little-Endian and viceversa.
  12. func SwapEndianness(xs []byte) []byte {
  13. ys := make([]byte, len(xs))
  14. for i, b := range xs {
  15. ys[len(xs)-1-i] = b
  16. }
  17. return ys
  18. }
  19. // BigIntLEBytes encodes a big.Int into an array in Little-Endian.
  20. func BigIntLEBytes(v *big.Int) [32]byte {
  21. le := SwapEndianness(v.Bytes())
  22. res := [32]byte{}
  23. copy(res[:], le)
  24. return res
  25. }
  26. // SetBigIntFromLEBytes sets the value of a big.Int from a Little-Endian
  27. // encoded value.
  28. func SetBigIntFromLEBytes(v *big.Int, leBuf []byte) *big.Int {
  29. beBuf := SwapEndianness(leBuf)
  30. return v.SetBytes(beBuf)
  31. }
  32. // Blake512 performs the blake-512 hash over the buffer m. Note that this is
  33. // the original blake from the SHA3 competition and not the new blake2 version.
  34. func Blake512(m []byte) []byte {
  35. h := blake512.New()
  36. h.Write(m[:])
  37. return h.Sum(nil)
  38. }
  39. // Hex is a byte slice type that can be marshalled and unmarshaled in hex
  40. type Hex []byte
  41. // MarshalText encodes buf as hex
  42. func (buf Hex) MarshalText() ([]byte, error) {
  43. return []byte(hex.EncodeToString(buf)), nil
  44. }
  45. // String encodes buf as hex
  46. func (buf Hex) String() string {
  47. return hex.EncodeToString(buf)
  48. }
  49. // HexEncode encodes an array of bytes into a string in hex.
  50. func HexEncode(bs []byte) string {
  51. return fmt.Sprintf("0x%s", hex.EncodeToString(bs))
  52. }
  53. // HexDecode decodes a hex string into an array of bytes.
  54. func HexDecode(h string) ([]byte, error) {
  55. if strings.HasPrefix(h, "0x") {
  56. h = h[2:]
  57. }
  58. return hex.DecodeString(h)
  59. }
  60. // HexDecodeInto decodes a hex string into an array of bytes (dst), verifying
  61. // that the decoded array has the same length as dst.
  62. func HexDecodeInto(dst []byte, h []byte) error {
  63. if bytes.HasPrefix(h, []byte("0x")) {
  64. h = h[2:]
  65. }
  66. if len(h)/2 != len(dst) {
  67. return fmt.Errorf("expected %v bytes in hex string, got %v", len(dst), len(h)/2)
  68. }
  69. n, err := hex.Decode(dst, h)
  70. if err != nil {
  71. return err
  72. } else if n != len(dst) {
  73. return fmt.Errorf("expected %v bytes when decoding hex string, got %v", len(dst), n)
  74. }
  75. return nil
  76. }