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