forked from tuneinsight/lattigo
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
401 lines (318 loc) · 10.2 KB
/
main.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
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
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
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
package main
import (
"log"
"os"
"strconv"
"sync"
"time"
"github.com/fedejinich/lattigo/v6/bfv"
"github.com/fedejinich/lattigo/v6/dbfv"
"github.com/fedejinich/lattigo/v6/drlwe"
"github.com/fedejinich/lattigo/v6/rlwe"
"github.com/fedejinich/lattigo/v6/utils"
)
func check(err error) {
if err != nil {
panic(err)
}
}
func runTimed(f func()) time.Duration {
start := time.Now()
f()
return time.Since(start)
}
func runTimedParty(f func(), N int) time.Duration {
start := time.Now()
f()
return time.Duration(time.Since(start).Nanoseconds() / int64(N))
}
type party struct {
sk *rlwe.SecretKey
rlkEphemSk *rlwe.SecretKey
ckgShare *drlwe.CKGShare
rkgShareOne *drlwe.RKGShare
rkgShareTwo *drlwe.RKGShare
pcksShare *drlwe.PCKSShare
input []uint64
}
type multTask struct {
wg *sync.WaitGroup
op1 *rlwe.Ciphertext
op2 *rlwe.Ciphertext
res *rlwe.Ciphertext
elapsedmultTask time.Duration
}
var elapsedEncryptParty time.Duration
var elapsedEncryptCloud time.Duration
var elapsedCKGCloud time.Duration
var elapsedCKGParty time.Duration
var elapsedRKGCloud time.Duration
var elapsedRKGParty time.Duration
var elapsedPCKSCloud time.Duration
var elapsedPCKSParty time.Duration
var elapsedEvalCloudCPU time.Duration
var elapsedEvalCloud time.Duration
var elapsedEvalParty time.Duration
func main() {
// For more details about the PSI example see
// Multiparty Homomorphic Encryption: From Theory to Practice (<https://eprint.iacr.org/2020/304>)
l := log.New(os.Stderr, "", 0)
// $go run main.go arg1 arg2
// arg1: number of parties
// arg2: number of Go routines
// Largest for n=8192: 512 parties
N := 8 // Default number of parties
var err error
if len(os.Args[1:]) >= 1 {
N, err = strconv.Atoi(os.Args[1])
check(err)
}
NGoRoutine := 1 // Default number of Go routines
if len(os.Args[1:]) >= 2 {
NGoRoutine, err = strconv.Atoi(os.Args[2])
check(err)
}
// Creating encryption parameters from a default params with logN=14, logQP=438 with a plaintext modulus T=65537
paramsDef := bfv.PN14QP438
paramsDef.T = 65537
params, err := bfv.NewParametersFromLiteral(paramsDef)
if err != nil {
panic(err)
}
crs, err := utils.NewKeyedPRNG([]byte{'l', 'a', 't', 't', 'i', 'g', 'o'})
if err != nil {
panic(err)
}
encoder := bfv.NewEncoder(params)
// Target private and public keys
tsk, tpk := bfv.NewKeyGenerator(params).GenKeyPair()
// Create each party, and allocate the memory for all the shares that the protocols will need
P := genparties(params, N)
// Inputs & expected result
expRes := genInputs(params, P)
// 1) Collective public key generation
pk := ckgphase(params, crs, P)
// 2) Collective relinearization key generation
rlk := rkgphase(params, crs, P)
l.Printf("\tdone (cloud: %s, party: %s)\n",
elapsedRKGCloud, elapsedRKGParty)
l.Printf("\tSetup done (cloud: %s, party: %s)\n",
elapsedRKGCloud+elapsedCKGCloud, elapsedRKGParty+elapsedCKGParty)
encInputs := encPhase(params, P, pk, encoder)
encRes := evalPhase(params, NGoRoutine, encInputs, rlk)
encOut := pcksPhase(params, tpk, encRes, P)
// Decrypt the result with the target secret key
l.Println("> Result:")
decryptor := bfv.NewDecryptor(params, tsk)
ptres := bfv.NewPlaintext(params, params.MaxLevel())
elapsedDecParty := runTimed(func() {
decryptor.Decrypt(encOut, ptres)
})
// Check the result
res := encoder.DecodeUintNew(ptres)
l.Printf("\t%v\n", res[:16])
for i := range expRes {
if expRes[i] != res[i] {
//l.Printf("\t%v\n", expRes)
l.Println("\tincorrect")
return
}
}
l.Println("\tcorrect")
l.Printf("> Finished (total cloud: %s, total party: %s)\n",
elapsedCKGCloud+elapsedRKGCloud+elapsedEncryptCloud+elapsedEvalCloud+elapsedPCKSCloud,
elapsedCKGParty+elapsedRKGParty+elapsedEncryptParty+elapsedEvalParty+elapsedPCKSParty+elapsedDecParty)
}
func encPhase(params bfv.Parameters, P []*party, pk *rlwe.PublicKey, encoder bfv.Encoder) (encInputs []*rlwe.Ciphertext) {
l := log.New(os.Stderr, "", 0)
encInputs = make([]*rlwe.Ciphertext, len(P))
for i := range encInputs {
encInputs[i] = bfv.NewCiphertext(params, 1, params.MaxLevel())
}
// Each party encrypts its input vector
l.Println("> Encrypt Phase")
encryptor := bfv.NewEncryptor(params, pk)
pt := bfv.NewPlaintext(params, params.MaxLevel())
elapsedEncryptParty = runTimedParty(func() {
for i, pi := range P {
encoder.Encode(pi.input, pt)
encryptor.Encrypt(pt, encInputs[i])
}
}, len(P))
elapsedEncryptCloud = time.Duration(0)
l.Printf("\tdone (cloud: %s, party: %s)\n", elapsedEncryptCloud, elapsedEncryptParty)
return
}
func evalPhase(params bfv.Parameters, NGoRoutine int, encInputs []*rlwe.Ciphertext, rlk *rlwe.RelinearizationKey) (encRes *rlwe.Ciphertext) {
l := log.New(os.Stderr, "", 0)
encLvls := make([][]*rlwe.Ciphertext, 0)
encLvls = append(encLvls, encInputs)
for nLvl := len(encInputs) / 2; nLvl > 0; nLvl = nLvl >> 1 {
encLvl := make([]*rlwe.Ciphertext, nLvl)
for i := range encLvl {
encLvl[i] = bfv.NewCiphertext(params, 2, params.MaxLevel())
}
encLvls = append(encLvls, encLvl)
}
encRes = encLvls[len(encLvls)-1][0]
evaluator := bfv.NewEvaluator(params, rlwe.EvaluationKey{Rlk: rlk, Rtks: nil})
// Split the task among the Go routines
tasks := make(chan *multTask)
workers := &sync.WaitGroup{}
workers.Add(NGoRoutine)
//l.Println("> Spawning", NGoRoutine, "evaluator goroutine")
for i := 1; i <= NGoRoutine; i++ {
go func(i int) {
evaluator := evaluator.ShallowCopy() // creates a shallow evaluator copy for this goroutine
for task := range tasks {
task.elapsedmultTask = runTimed(func() {
// 1) Multiplication of two input vectors
evaluator.Mul(task.op1, task.op2, task.res)
// 2) Relinearization
evaluator.Relinearize(task.res, task.res)
})
task.wg.Done()
}
//l.Println("\t evaluator", i, "down")
workers.Done()
}(i)
//l.Println("\t evaluator", i, "started")
}
// Start the tasks
taskList := make([]*multTask, 0)
l.Println("> Eval Phase")
elapsedEvalCloud = runTimed(func() {
for i, lvl := range encLvls[:len(encLvls)-1] {
nextLvl := encLvls[i+1]
l.Println("\tlevel", i, len(lvl), "->", len(nextLvl))
wg := &sync.WaitGroup{}
wg.Add(len(nextLvl))
for j, nextLvlCt := range nextLvl {
task := multTask{wg, lvl[2*j], lvl[2*j+1], nextLvlCt, 0}
taskList = append(taskList, &task)
tasks <- &task
}
wg.Wait()
}
})
elapsedEvalCloudCPU = time.Duration(0)
for _, t := range taskList {
elapsedEvalCloudCPU += t.elapsedmultTask
}
elapsedEvalParty = time.Duration(0)
l.Printf("\tdone (cloud: %s (wall: %s), party: %s)\n",
elapsedEvalCloudCPU, elapsedEvalCloud, elapsedEvalParty)
//l.Println("> Shutting down workers")
close(tasks)
workers.Wait()
return
}
func genparties(params bfv.Parameters, N int) []*party {
// Create each party, and allocate the memory for all the shares that the protocols will need
P := make([]*party, N)
for i := range P {
pi := &party{}
pi.sk = bfv.NewKeyGenerator(params).GenSecretKey()
P[i] = pi
}
return P
}
func genInputs(params bfv.Parameters, P []*party) (expRes []uint64) {
expRes = make([]uint64, params.N())
for i := range expRes {
expRes[i] = 1
}
for _, pi := range P {
pi.input = make([]uint64, params.N())
for i := range pi.input {
if utils.RandFloat64(0, 1) > 0.3 || i == 4 {
pi.input[i] = 1
}
expRes[i] *= pi.input[i]
}
}
return
}
func pcksPhase(params bfv.Parameters, tpk *rlwe.PublicKey, encRes *rlwe.Ciphertext, P []*party) (encOut *rlwe.Ciphertext) {
l := log.New(os.Stderr, "", 0)
// Collective key switching from the collective secret key to
// the target public key
pcks := dbfv.NewPCKSProtocol(params, 3.19)
for _, pi := range P {
pi.pcksShare = pcks.AllocateShare(params.MaxLevel())
}
l.Println("> PCKS Phase")
elapsedPCKSParty = runTimedParty(func() {
for _, pi := range P {
pcks.GenShare(pi.sk, tpk, encRes, pi.pcksShare)
}
}, len(P))
pcksCombined := pcks.AllocateShare(params.MaxLevel())
encOut = bfv.NewCiphertext(params, 1, params.MaxLevel())
elapsedPCKSCloud = runTimed(func() {
for _, pi := range P {
pcks.AggregateShares(pi.pcksShare, pcksCombined, pcksCombined)
}
pcks.KeySwitch(encRes, pcksCombined, encOut)
})
l.Printf("\tdone (cloud: %s, party: %s)\n", elapsedPCKSCloud, elapsedPCKSParty)
return
}
func rkgphase(params bfv.Parameters, crs utils.PRNG, P []*party) *rlwe.RelinearizationKey {
l := log.New(os.Stderr, "", 0)
l.Println("> RKG Phase")
rkg := dbfv.NewRKGProtocol(params) // Relineariation key generation
_, rkgCombined1, rkgCombined2 := rkg.AllocateShare()
for _, pi := range P {
pi.rlkEphemSk, pi.rkgShareOne, pi.rkgShareTwo = rkg.AllocateShare()
}
crp := rkg.SampleCRP(crs)
elapsedRKGParty = runTimedParty(func() {
for _, pi := range P {
rkg.GenShareRoundOne(pi.sk, crp, pi.rlkEphemSk, pi.rkgShareOne)
}
}, len(P))
elapsedRKGCloud = runTimed(func() {
for _, pi := range P {
rkg.AggregateShares(pi.rkgShareOne, rkgCombined1, rkgCombined1)
}
})
elapsedRKGParty += runTimedParty(func() {
for _, pi := range P {
rkg.GenShareRoundTwo(pi.rlkEphemSk, pi.sk, rkgCombined1, pi.rkgShareTwo)
}
}, len(P))
rlk := rlwe.NewRelinearizationKey(params.Parameters, 1)
elapsedRKGCloud += runTimed(func() {
for _, pi := range P {
rkg.AggregateShares(pi.rkgShareTwo, rkgCombined2, rkgCombined2)
}
rkg.GenRelinearizationKey(rkgCombined1, rkgCombined2, rlk)
})
l.Printf("\tdone (cloud: %s, party: %s)\n", elapsedRKGCloud, elapsedRKGParty)
return rlk
}
func ckgphase(params bfv.Parameters, crs utils.PRNG, P []*party) *rlwe.PublicKey {
l := log.New(os.Stderr, "", 0)
l.Println("> CKG Phase")
ckg := dbfv.NewCKGProtocol(params) // Public key generation
ckgCombined := ckg.AllocateShare()
for _, pi := range P {
pi.ckgShare = ckg.AllocateShare()
}
crp := ckg.SampleCRP(crs)
elapsedCKGParty = runTimedParty(func() {
for _, pi := range P {
ckg.GenShare(pi.sk, crp, pi.ckgShare)
}
}, len(P))
pk := rlwe.NewPublicKey(params.Parameters)
elapsedCKGCloud = runTimed(func() {
for _, pi := range P {
ckg.AggregateShares(pi.ckgShare, ckgCombined, ckgCombined)
}
ckg.GenPublicKey(ckgCombined, crp, pk)
})
l.Printf("\tdone (cloud: %s, party: %s)\n", elapsedCKGCloud, elapsedCKGParty)
return pk
}