issuer-keyprove.go 7.21 KB
Newer Older
1
2
3
package cmd

import (
4
5
	"compress/gzip"
	"encoding/json"
6
7
8
9
	"fmt"
	"os"
	"path/filepath"
	"strconv"
10
	"strings"
11
	"time"
12
13
14
15

	"github.com/privacybydesign/gabi"
	"github.com/privacybydesign/gabi/big"
	"github.com/privacybydesign/gabi/keyproof"
16
17
	"github.com/privacybydesign/irmago/internal/common"
	"github.com/sietseringers/cobra"
18
19
)

20
21
var issuerKeyproveCmd = &cobra.Command{
	Use:   "keyprove [path]",
22
	Short: "Generate proof of correct generation for an IRMA issuer keypair",
23
	Long: `Generate proof of correct generation for an IRMA issuer keypair.
24

25
The keyprove command generates a proof that an issuer key was generated correctly. By default, it generates a proof for the newest private key in the PrivateKeys folder, and then stores the proof in the Proofs folder.`,
26
	Args: cobra.MaximumNArgs(1),
27
	Run: func(cmd *cobra.Command, args []string) {
28
		flags := cmd.Flags()
29
		counter, _ := flags.GetUint("counter")
30
31
32
33
34
35
36
37
38
39
40
41
42
		pubkeyfile, _ := flags.GetString("publickey")
		privkeyfile, _ := flags.GetString("privatekey")
		prooffile, _ := flags.GetString("proof")

		var err error

		// Determine path for key
		var path string
		if len(args) != 0 {
			path = args[0]
		} else {
			path, err = os.Getwd()
			if err != nil {
43
				die("", err)
44
45
			}
		}
46
		if err = common.AssertPathExists(path); err != nil {
47
			die("Nonexisting path specified", err)
48
49
50
		}

		// Determine counter if needed
51
		if !flags.Changed("counter") {
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
			counter = uint(lastPrivateKeyIndex(path))
		}

		// Fill in pubkey if needed
		if pubkeyfile == "" {
			pubkeyfile = filepath.Join(path, "PublicKeys", strconv.Itoa(int(counter))+".xml")
		}

		// Fill in privkey if needed
		if privkeyfile == "" {
			privkeyfile = filepath.Join(path, "PrivateKeys", strconv.Itoa(int(counter))+".xml")
		}

		// Try to read public key
		pk, err := gabi.NewPublicKeyFromFile(pubkeyfile)
		if err != nil {
68
			die("Could not read public key", err)
69
70
71
		}

		// Try to read private key
72
		sk, err := gabi.NewPrivateKeyFromFile(privkeyfile, false)
73
		if err != nil {
74
			die("Could not read private key", err)
75
76
77
78
		}

		// Validate that they match
		if pk.N.Cmp(new(big.Int).Mul(sk.P, sk.Q)) != 0 {
79
			die("Private and public key do not match", nil)
80
		}
81

82
83
84
85
86
87
88
89
90
91
		// Validate that the key is amenable to proving
		ConstEight := big.NewInt(8)
		ConstOne := big.NewInt(1)
		PMod := new(big.Int).Mod(sk.P, ConstEight)
		QMod := new(big.Int).Mod(sk.Q, ConstEight)
		PPrimeMod := new(big.Int).Mod(sk.PPrime, ConstEight)
		QPrimeMod := new(big.Int).Mod(sk.QPrime, ConstEight)
		if PMod.Cmp(ConstOne) == 0 || QMod.Cmp(ConstOne) == 0 ||
			PPrimeMod.Cmp(ConstOne) == 0 || QPrimeMod.Cmp(ConstOne) == 0 ||
			PMod.Cmp(QMod) == 0 || PPrimeMod.Cmp(QPrimeMod) == 0 {
92
			die("Private key not amenable to proving", nil)
93
		}
94

95
96
97
98
		// Prepare storage for proof if needed
		if prooffile == "" {
			proofpath := filepath.Join(path, "Proofs")
			if err = common.EnsureDirectoryExists(proofpath); err != nil {
99
				die("Failed to create"+proofpath, err)
100
101
102
103
			}
			prooffile = filepath.Join(proofpath, strconv.Itoa(int(counter))+".json.gz")
		}

104
105
106
		// Open proof file for writing
		proofOut, err := os.Create(prooffile)
		if err != nil {
107
			die("Error opening proof file for writing", err)
108
		}
109
		defer closeCloser(proofOut)
110

111
112
		// Wrap it for gzip compression
		proofWriter := gzip.NewWriter(proofOut)
113
		defer closeCloser(proofWriter)
114

115
116
117
118
119
120
		// Start log follower
		follower := startLogFollower()
		defer func() {
			follower.quitEvents <- quitMessage{}
			<-follower.finished
		}()
121

122
123
124
125
126
127
128
129
130
131
		// Build the proof
		s := keyproof.NewValidKeyProofStructure(pk.N, pk.Z, pk.S, pk.R)
		proof := s.BuildProof(sk.PPrime, sk.QPrime)

		// And write it to file
		follower.StepStart("Writing proof", 0)
		proofEncoder := json.NewEncoder(proofWriter)
		err = proofEncoder.Encode(proof)
		follower.StepDone()
		if err != nil {
132
			die("Could not write proof", err)
133
134
135
136
137
		}
	},
}

func init() {
138
	issuerCmd.AddCommand(issuerKeyproveCmd)
139

140
141
142
143
	issuerKeyproveCmd.Flags().StringP("privatekey", "s", "", `File to get private key from (default "PrivateKeys/$counter.xml")`)
	issuerKeyproveCmd.Flags().StringP("publickey", "p", "", `File to get public key from (default "PublicKeys/$counter.xml")`)
	issuerKeyproveCmd.Flags().StringP("proof", "o", "", `File to write proof to (default "Proofs/$index.json.gz")`)
	issuerKeyproveCmd.Flags().UintP("counter", "c", 0, "Counter of key to prove (default to latest)")
144
}
Sietse Ringers's avatar
Sietse Ringers committed
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282

func lastPrivateKeyIndex(path string) (counter int) {
	matches, _ := filepath.Glob(filepath.Join(path, "PrivateKeys", "*.xml"))
	for _, match := range matches {
		filename := filepath.Base(match)
		c, err := strconv.Atoi(filename[:len(filename)-4])
		if err != nil {
			fmt.Println(err.Error())
			continue
		}
		if c > counter {
			counter = c
		}
	}
	return
}

type stepStartMessage struct {
	desc          string
	intermediates int
}
type stepDoneMessage struct{}
type tickMessage struct{}
type quitMessage struct{}
type finishMessage struct{}
type setFinalMessage struct {
	message string
}

type logFollower struct {
	stepStartEvents chan<- stepStartMessage
	stepDoneEvents  chan<- stepDoneMessage
	tickEvents      chan<- tickMessage
	quitEvents      chan<- quitMessage
	finalEvents     chan<- setFinalMessage
	finished        <-chan finishMessage
}

func (l *logFollower) StepStart(desc string, intermediates int) {
	l.stepStartEvents <- stepStartMessage{desc, intermediates}
}

func (l *logFollower) StepDone() {
	l.stepDoneEvents <- stepDoneMessage{}
}

func (l *logFollower) Tick() {
	l.tickEvents <- tickMessage{}
}

func printProofStatus(status string, count, limit int, done bool) {
	var tail string
	if done {
		tail = "done"
	} else if limit > 0 {
		tail = fmt.Sprintf("%v/%v", count, limit)
	} else {
		tail = ""
	}

	tlen := len(tail)
	if tlen == 0 {
		tlen = 4
	}

	fmt.Printf("\r%s%s%s", status, strings.Repeat(".", 60-len(status)-tlen), tail)
}

func startLogFollower() *logFollower {
	var result = new(logFollower)

	starts := make(chan stepStartMessage)
	dones := make(chan stepDoneMessage)
	ticks := make(chan tickMessage)
	quit := make(chan quitMessage)
	finished := make(chan finishMessage)
	finalmessage := make(chan setFinalMessage)

	result.stepStartEvents = starts
	result.stepDoneEvents = dones
	result.tickEvents = ticks
	result.quitEvents = quit
	result.finished = finished
	result.finalEvents = finalmessage

	go func() {
		doneMissing := 0
		curStatus := ""
		curCount := 0
		curLimit := 0
		curDone := true
		finalMessage := ""
		ticker := time.NewTicker(time.Second / 4)
		defer ticker.Stop()

		for {
			select {
			case <-ticks:
				curCount++
			case <-dones:
				if doneMissing > 0 {
					doneMissing--
					continue // Swallow quietly
				} else {
					curDone = true
					printProofStatus(curStatus, curCount, curLimit, true)
					fmt.Printf("\n")
				}
			case stepstart := <-starts:
				if !curDone {
					printProofStatus(curStatus, curCount, curLimit, true)
					fmt.Printf("\n")
					doneMissing++
				}
				curDone = false
				curCount = 0
				curLimit = stepstart.intermediates
				curStatus = stepstart.desc
			case messageevent := <-finalmessage:
				finalMessage = messageevent.message
			case <-quit:
				if finalMessage != "" {
					fmt.Printf("%s\n", finalMessage)
				}
				finished <- finishMessage{}
				return
			case <-ticker.C:
				if !curDone {
					printProofStatus(curStatus, curCount, curLimit, false)
				}
			}
		}
	}()

	keyproof.Follower = result

	return result
}