-
Notifications
You must be signed in to change notification settings - Fork 30
/
helpers.go
92 lines (76 loc) · 1.89 KB
/
helpers.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
package schnorrkel
import (
"crypto/rand"
"encoding/hex"
"errors"
"strings"
"github.com/gtank/merlin"
r255 "github.com/gtank/ristretto255"
)
func challengeScalar(t *merlin.Transcript, msg []byte) *r255.Scalar {
scb := t.ExtractBytes(msg, 64)
sc := r255.NewScalar()
sc.FromUniformBytes(scb)
return sc
}
// https://github.com/w3f/schnorrkel/blob/718678e51006d84c7d8e4b6cde758906172e74f8/src/scalars.rs#L18
func divideScalarByCofactor(s []byte) []byte {
l := len(s) - 1
low := byte(0)
for i := range s {
r := s[l-i] & 0x07 // remainder
s[l-i] >>= 3
s[l-i] += low
low = r << 5
}
return s
}
// NewRandomElement returns a random ristretto element
func NewRandomElement() (*r255.Element, error) {
e := r255.NewElement()
s := [64]byte{}
_, err := rand.Read(s[:])
if err != nil {
return nil, err
}
return e.FromUniformBytes(s[:]), nil
}
// NewRandomScalar returns a random ristretto scalar
func NewRandomScalar() (*r255.Scalar, error) {
s := [64]byte{}
_, err := rand.Read(s[:])
if err != nil {
return nil, err
}
ss := r255.NewScalar()
sc := ss.FromUniformBytes(s[:])
if sc.Equal(r255.NewScalar()) == 1 {
return nil, errors.New("scalar generated was zero")
}
return sc, nil
}
// ScalarFromBytes returns a ristretto scalar from the input bytes
// performs input mod l where l is the group order
func ScalarFromBytes(b [32]byte) (*r255.Scalar, error) {
s := r255.NewScalar()
err := s.Decode(b[:])
if err != nil {
return nil, err
}
return s, nil
}
// HexToBytes turns a 0x prefixed hex string into a byte slice
func HexToBytes(in string) ([]byte, error) {
if len(in) < 2 {
return nil, errors.New("invalid string")
}
if strings.Compare(in[:2], "0x") != 0 {
return nil, errors.New("could not byteify non 0x prefixed string")
}
if len(in)%2 != 0 {
return nil, errors.New("cannot decode a odd length string")
}
in = in[2:]
out, err := hex.DecodeString(in)
return out, err
}