issuer-keyprove.go 7.3 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
var issuerKeyproveCmd = &cobra.Command{
21
22
23
24
25
26
27
	Use:   "keyprove [<path>]",
	Short: "Generate validity proof for an IRMA issuer keypair",
	Long: `Generate validity proof for an IRMA issuer keypair.

The keyprove command generates a proof that an issuer private/public keypair was generated
correctly. By default, it acts on the newest keypair in the <path>/PrivateKeys and <path>/PublicKeys
folders, and then stores the proof in the <path>/Proofs folder. If not specified, <path> is taken to
28
29
30
31
32
be the current working directory.

For 2048 bit keys, keyprove will output a proof of about 700 MB. On machines of 2 - 3 GHz generating
will take some 5 - 15 minutes, during which CPU usage will be 100% most of the time. Up to 8 GB RAM
may be used.`,
33
	Args: cobra.MaximumNArgs(1),
34
	Run: func(cmd *cobra.Command, args []string) {
35
		flags := cmd.Flags()
36
		counter, _ := flags.GetUint("counter")
37
38
39
40
41
42
43
44
45
46
47
48
49
		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 {
50
				die("", err)
51
52
			}
		}
53
		if err = common.AssertPathExists(path); err != nil {
54
			die("Nonexisting path specified", err)
55
56
57
		}

		// Determine counter if needed
58
		if !flags.Changed("counter") {
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
			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 {
75
			die("Could not read public key", err)
76
77
78
		}

		// Try to read private key
79
		sk, err := gabi.NewPrivateKeyFromFile(privkeyfile, false)
80
		if err != nil {
81
			die("Could not read private key", err)
82
83
84
85
		}

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

89
90
91
		// Validate that the key is eligble to proving
		if !keyproof.CanProve(sk.PPrime, sk.QPrime) {
			die("Private key not eligible to proving", nil)
92
		}
93

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

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

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

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

121
		// Build the proof
122
123
124
125
126
127
128
129
		bases := append([]*big.Int{pk.Z, pk.S})
		if pk.G != nil {
			bases = append(bases, pk.G)
		}
		if pk.H != nil {
			bases = append(bases, pk.H)
		}
		s := keyproof.NewValidKeyProofStructure(pk.N, append(bases, pk.R...))
130
131
132
133
134
135
136
137
		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 {
138
			die("Could not write proof", err)
139
140
141
142
143
		}
	},
}

func init() {
144
	issuerCmd.AddCommand(issuerKeyproveCmd)
145

146
147
148
149
	issuerKeyproveCmd.Flags().StringP("privatekey", "s", "", `File to get private key from (default "<path>/PrivateKeys/$counter.xml")`)
	issuerKeyproveCmd.Flags().StringP("publickey", "p", "", `File to get public key from (default "<path>/PublicKeys/$counter.xml")`)
	issuerKeyproveCmd.Flags().StringP("proof", "o", "", `File to write proof to (default "<path>/Proofs/$index.json.gz")`)
	issuerKeyproveCmd.Flags().UintP("counter", "c", 0, "Counter of key to prove (defaults to latest)")
150
}
Sietse Ringers's avatar
Sietse Ringers committed
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167

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
}

168
169
170
171
172
173
174
175
176
177
178
179
type (
	stepStartMessage struct {
		desc          string
		intermediates int
	}
	stepDoneMessage struct{}
	tickMessage     struct{}
	quitMessage     struct{}
	finishMessage   struct{}
	setFinalMessage struct {
		message string
	}
Sietse Ringers's avatar
Sietse Ringers committed
180

181
182
183
184
185
186
187
188
189
	logFollower struct {
		stepStartEvents chan<- stepStartMessage
		stepDoneEvents  chan<- stepDoneMessage
		tickEvents      chan<- tickMessage
		quitEvents      chan<- quitMessage
		finalEvents     chan<- setFinalMessage
		finished        <-chan finishMessage
	}
)
Sietse Ringers's avatar
Sietse Ringers committed
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
283
284
285
286
287
288
289
290

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
}