-
Notifications
You must be signed in to change notification settings - Fork 0
/
schnorr.go
124 lines (92 loc) · 2.42 KB
/
schnorr.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
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
package ecdaa
import (
"fmt"
"github.com/akakou-fork/amcl-go/miracl/core"
"github.com/akakou-fork/amcl-go/miracl/core/FP256BN"
amcl_utils "github.com/akakou/fp256bn-amcl-utils"
)
type SchnorrProof struct {
SmallC *FP256BN.BIG
SmallS *FP256BN.BIG
SmallN *FP256BN.BIG
K *FP256BN.ECP
}
type SchnorrProver struct{}
func commit(sk *FP256BN.BIG, B, S *FP256BN.ECP, rng *core.RAND, calcK bool) (*FP256BN.BIG, *FP256BN.ECP, *FP256BN.ECP, *FP256BN.ECP) {
r := amcl_utils.RandomBig(rng)
E := S.Mul(r)
L := B.Mul(r)
var K *FP256BN.ECP
if calcK {
K = B.Mul(sk)
} else {
K = nil
}
return r, E, L, K
}
func sign(r, cDash, sk *FP256BN.BIG, rng *core.RAND) (*FP256BN.BIG, *FP256BN.BIG, *FP256BN.BIG) {
n := amcl_utils.RandomBig(rng)
hash := amcl_utils.NewHash()
hash.WriteBIG(n, cDash)
c := hash.SumToBIG()
s := FP256BN.Modmul(c, sk, amcl_utils.P())
s = FP256BN.Modadd(r, s, amcl_utils.P())
return n, c, s
}
func proveSchnorr(message, basename []byte, sk *FP256BN.BIG, S, W *FP256BN.ECP, rng *core.RAND) *SchnorrProof {
hash := amcl_utils.NewHash()
hash.WriteBytes(basename)
B, _, _ := hash.HashToECP()
r, E, L, K := commit(sk, B, S, rng, true)
// c' = H(E, S, W, L, B, K, basename, message)
hash = amcl_utils.NewHash()
if basename == nil {
hash.WriteECP(E, S, W)
} else {
hash.WriteECP(E, S, W, L, B, K)
}
hash.WriteBytes(basename, message)
cDash := hash.SumToBIG()
n, c, s := sign(r, cDash, sk, rng)
return &SchnorrProof{
SmallC: c,
SmallS: s,
SmallN: n,
K: K,
}
}
func verifySchnorr(message, basename []byte, proof *SchnorrProof, S, W *FP256BN.ECP) error {
// E = S^s W ^ (-c)
E := S.Mul(proof.SmallS)
tmp := W.Mul(proof.SmallC)
E.Sub(tmp)
// c' = H(E, S, W, L, B, K, basename, message)
hash := amcl_utils.NewHash()
if basename == nil {
hash.WriteECP(E, S, W)
} else {
bHash := amcl_utils.NewHash()
bHash.WriteBytes(basename)
B, _, err := bHash.HashToECP()
if err != nil {
return err
}
// L = B^s - K^c
L := B.Mul(proof.SmallS)
tmp = proof.K.Mul(proof.SmallC)
L.Sub(tmp)
hash.WriteECP(E, S, W, L, B, proof.K)
}
hash.WriteBytes(basename, message)
cDash := hash.SumToBIG()
// c = H( n | c' )
cDashBuf := amcl_utils.BigToBytes(cDash)
hash = amcl_utils.NewHash()
hash.WriteBIG(proof.SmallN)
hash.WriteBytes(cDashBuf)
c := hash.SumToBIG()
if FP256BN.Comp(proof.SmallC, c) != 0 {
return fmt.Errorf("c is not match: %v != %v", proof.SmallC, c)
}
return nil
}