-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathSDLtoECConvert.py
More file actions
1948 lines (1443 loc) · 79.5 KB
/
SDLtoECConvert.py
File metadata and controls
1948 lines (1443 loc) · 79.5 KB
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
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import copy
import sdlpath
from sdlparser.SDLParser import *
import re, importlib
symmetricPairingSettingKeyword_SDL = "symmetric"
asymmetricPairingSettingKeyword_SDL = "asymmetric"
generatorVarNameToNewName = {}
gameEndChar_EC = "."
memKeyword_EC = "mem"
notOperator_EC = "!"
andOperator_EC = "&&"
#constantGeneratorVarName_EC = "g_1"
initFuncName_EC = "Init"
dummyVarInMain_EC = "dummy"
vVarInMain_EC = "v"
additionOperator_EC = "+"
intType_EC = "int"
countVarPrefix = "count_"
advPubKeyVarName_EC = "adv_public_key"
adversaryVarName_EC = "Adv"
adversaryKeyword_EC = "adversary"
funcNamesAdvDoesntNeed = ["types", "count", "precompute", "NONE_FUNC_NAME"]
sVarInMain_EC = "s"
messageVarNameInMain_EC = "m"
emptyMapSymbol_EC = "[]"
emptyMapName_EC = "empty_map"
randomOracleVarName_EC = "rand_oracle"
randomG1GenerationStmt_EC = "Rand_G_1()"
randomG2GenerationStmt_EC = "Rand_G_2()"
randomZRGenerationStmt_EC = "Rand_exp()"
funcName_EC = "fun"
trueKeyword_EC = "true"
trueKeyword_SDL = "True"
falseKeyword_EC = "false"
falseKeyword_SDL = "False"
numSpacesForIndent = 2
templateFileName = "ECTemplate_SymmOrAsymm"
templateFileExt = ".txt"
#configFileName = "SDLtoECConfig"
booleanType_EC = "bool"
varKeyword_EC = "var"
abstractKeyword_EC = "abs"
adversaryIdentifier_EC = "A"
adversarySignatureIdentifier_EC = "Adv"
hashFuncName_EC = "Hash"
signFuncName_EC = "Sign"
verifyFuncName_EC = "Verify"
messageName_EC = "m"
messageType_EC = "message"
secretKeyName_EC = "secret_key"
queriedName_EC = "queried"
varNameForVerifyBoolRetVal_EC = "v"
appendOperator_EC = "::"
funcStartChar_EC = "{"
funcEndChar_EC = "}"
assignmentOperator_EC = "="
returnKeyword_EC = "return"
multOp_EC = "*"
expOp_EC = "^"
endOfLineOperator_EC = ";"
eqTstOperator_EC = "="
validGroupTypes = ["G1", "G2", "GT", "ZR"]
validHashGroupTypes = ["G1", "G2", "ZR"]
validRandomGroupTypes = ["G1", "G2", "ZR"]
DEBUG = False
def writeNumOfSpacesToString(numSpaces):
outputString = ""
for space in range(0, numSpaces):
outputString += " "
return outputString
def addTemplateLinesFromOneTemplateFileToOutputECFile(outputECFile, generatorCounter):
templateFile = open(templateFileName + str(generatorCounter) + templateFileExt, 'r')
outputString = ""
for templateLine in templateFile:
outputString += templateLine
outputECFile.write(outputString)
def addTemplateLinesToOutputECFile_SymmetricOrAsymmetric(outputECFile, assignInfo, generatorsList, pairingSetting, config):
global generatorVarNameToNewName
#generatorVarNameToNewName["g"] = "g_1"
#generatorVarNameToNewName["var2"] = "g_2"
#addTemplateLinesFromOneTemplateFileToOutputECFile(outputECFile, 1)
outputString = ""
outputString += "prover alt-ergo, z3, cvc3.\n\n"
if (pairingSetting == symmetricPairingSettingKeyword_SDL):
outputString += "type G_1.\n"
else:
outputString += "type G_1.\n"
outputString += "type G_2.\n"
#outputECFile.write(outputString)
outputString += "type G_T.\n"
outputString += "type message.\n\n"
outputString += "cnst g_1_i : G_1.\n"
#addTemplateLinesFromOneTemplateFileToOutputECFile(outputECFile, 2)
#outputString = ""
if (pairingSetting == asymmetricPairingSettingKeyword_SDL):
outputString += "cnst g_2_i : G_2.\n"
outputString += "cnst g_T_i : G_T.\n"
generatorCounter = 1
for generator in generatorsList:
#print(generator)
outputString += "cnst g_" + str(generatorCounter) + " : "
typeForThisGenerator = getVarTypeFromVarName_EC(generator, config.keygenFuncName_SDL, pairingSetting)
outputString += typeForThisGenerator + ".\n"
generatorVarNameToNewName[generator] = "g_" + str(generatorCounter)
generatorCounter += 1
outputString += "cnst g_T : G_T.\n"
outputString += "cnst q_1 : int.\n"
if (pairingSetting == asymmetricPairingSettingKeyword_SDL):
outputString += "cnst q_2 : int.\n"
outputString += "cnst q_T : int.\n\n"
outputString += "cnst q : int.\n\n"
outputString += "cnst limit_" + hashFuncName_EC + " : int.\n"
outputString += "cnst limit_" + signFuncName_EC + " : int.\n"
extraFuncsForAdversary = getExtraFuncsForAdversary(assignInfo, config)
for extraFuncForAdversary in extraFuncsForAdversary:
outputString += "cnst limit_" + extraFuncForAdversary + " : int.\n"
outputString += "\n"
outputString += "op [*] : (G_1, G_1) -> G_1 as G_1_mul.\n"
if (pairingSetting == asymmetricPairingSettingKeyword_SDL):
outputString += "op [*] : (G_2, G_2) -> G_2 as G_2_mul.\n"
if (pairingSetting == symmetricPairingSettingKeyword_SDL):
outputString += "op [^] : (G_1, int) -> G_1 as G_1_pow.\n\n"
else:
outputString += "op [^] : (G_1, int) -> G_1 as G_1_pow.\n"
outputString += "op [^] : (G_2, int) -> G_2 as G_2_pow.\n\n"
outputString += "op [*] : (G_T, G_T) -> G_T as G_T_mul.\n"
outputString += "op [^] : (G_T, int) -> G_T as G_T_pow.\n\n"
outputString += "op G_1_log : G_1 -> int.\n"
if (pairingSetting == asymmetricPairingSettingKeyword_SDL):
outputString += "op G_2_log : G_2 -> int.\n"
outputString += "op G_T_log : G_T -> int.\n\n"
if (pairingSetting == symmetricPairingSettingKeyword_SDL):
outputString += "op e : (G_1, G_1) -> G_T as G_1_pair.\n\n"
else:
outputString += "op e : (G_1, G_2) -> G_T as G_1_G_2_pair.\n\n"
outputString += "(*\n"
outputString += " From easycrypt ElGamal:\n"
outputString += " If we use the native modulo alt-ergo is not able\n"
outputString += " to perform the proof.\n"
outputString += " So we declare an operator (%%) which stand for the modulo ...\n"
outputString += "*)\n\n"
outputString += "op [%%] : (int,int) -> int as int_mod.\n\n"
outputString += "axiom limit_" + hashFuncName_EC + "_pos : 0 < limit_" + hashFuncName_EC + ".\n"
outputString += "axiom limit_" + signFuncName_EC + "_pos : 0 < limit_" + signFuncName_EC + ".\n"
extraFuncsForAdversary = getExtraFuncsForAdversary(assignInfo, config)
for extraFuncForAdversary in extraFuncsForAdversary:
outputString += "axiom limit_" + extraFuncForAdversary + "_pos : 0 < limit_" + extraFuncForAdversary + ".\n"
outputString += "\n"
if (pairingSetting == symmetricPairingSettingKeyword_SDL):
outputString += "axiom q_1_pos : 0 < q_1.\n"
else:
outputString += "axiom q_1_pos : 0 < q_1.\n"
outputString += "axiom q_2_pos : 0 < q_2.\n"
outputString += "axiom q_T_pos : 0 < q_T.\n\n"
outputString += "axiom q_pos : 0 < q.\n\n"
if (pairingSetting == symmetricPairingSettingKeyword_SDL):
outputString += "(* Axioms largely pulled from ElGamal. Note that G_1 and G_T have the same order if the order is prime. *)\n\n"
else:
outputString += "(* Axioms largely pulled from ElGamal. Note that G_1, G_2, and G_T have the same order if the order is prime. *)\n\n"
outputString += "axiom G_1_mult_1 : forall (x : G_1), x * g_1_i = x.\n"
outputString += "axiom G_1_exp_0 : forall (x : G_1), x ^ 0 = g_1_i.\n"
outputString += "axiom G_1_exp_S : forall (x : G_1, k : int), k > 0 => x ^ k = x * (x^(k-1)).\n\n"
if (pairingSetting == asymmetricPairingSettingKeyword_SDL):
outputString += "axiom G_2_mult_1 : forall (x : G_2), x * g_2_i = x.\n"
outputString += "axiom G_2_exp_0 : forall (x : G_2), x ^ 0 = g_2_i.\n"
outputString += "axiom G_2_exp_S : forall (x : G_2, k : int), k > 0 => x ^ k = x * (x^(k-1)).\n\n"
outputString += "axiom G_T_mult_1 : forall (x : G_T), x * g_T_i = x.\n"
outputString += "axiom G_T_exp_0 : forall (x : G_T), x ^ 0 = g_T_i.\n"
outputString += "axiom G_T_exp_S : forall (x : G_T, k : int), k > 0 => x ^ k = x * (x^(k-1)).\n\n"
if (pairingSetting == symmetricPairingSettingKeyword_SDL):
outputString += "axiom bilinearity : forall (x : G_1, y : G_1, a : int, b : int), e(x ^ a, y ^ b) = e(x, y) ^ (a * b).\n"
outputString += "(* axiom non_degenerate : !(e(g_1, g_1) = g_T_i). *)\n\n"
else:
outputString += "axiom bilinearity : forall (x : G_1, y : G_2, a : int, b : int), e(x ^ a, y ^ b) = e(x, y) ^ (a * b).\n"
outputString += "(* axiom non_degenerate : !(e(g_1, g_2) = g_T_i). *)\n\n"
generatorCounter = 1
for generator in generatorsList:
outputString += "axiom "
typeForThisGenerator = getVarTypeFromVarName_EC(generator, config.keygenFuncName_SDL, pairingSetting)
outputString += typeForThisGenerator + "_pow_add_" + str(generatorCounter) + " :\n"
outputString += " forall (x, y:int), g_" + str(generatorCounter) + " ^ (x + y) = g_"
outputString += str(generatorCounter) + " ^ x * g_" + str(generatorCounter) + " ^ y.\n\n"
generatorCounter += 1
outputString += "axiom G_T_pow_add :\n"
outputString += " forall (x, y:int), g_T ^ (x + y) = g_T ^ x * g_T ^ y.\n\n"
generatorCounter = 1
for generator in generatorsList:
outputString += "axiom "
typeForThisGenerator = getVarTypeFromVarName_EC(generator, config.keygenFuncName_SDL, pairingSetting)
outputString += typeForThisGenerator + "_pow_mult_" + str(generatorCounter) + " :\n"
outputString += " forall (x, y:int), (g_" + str(generatorCounter) + " ^ x) ^ y = g_"
outputString += str(generatorCounter) + " ^ (x * y).\n\n"
generatorCounter += 1
outputString += "axiom G_T_pow_mult :\n"
outputString += " forall (x, y:int), (g_T ^ x) ^ y = g_T ^ (x * y).\n\n"
generatorCounter = 1
for generator in generatorsList:
outputString += "axiom "
typeForThisGenerator = getVarTypeFromVarName_EC(generator, config.keygenFuncName_SDL, pairingSetting)
outputString += typeForThisGenerator + "_log_pow_" + str(generatorCounter) + " :\n"
outputString += " forall (g_" + str(generatorCounter) + "': " + typeForThisGenerator + "), g_"
outputString += str(generatorCounter) + " ^ " + typeForThisGenerator + "_log(g_"
outputString += str(generatorCounter) + "') = g_" + str(generatorCounter) + "'.\n\n"
generatorCounter += 1
outputString += "axiom G_T_log_pow :\n"
outputString += " forall (g_T':G_T), g_T ^ G_T_log(g_T') = g_T'.\n\n"
generatorCounter = 1
for generator in generatorsList:
outputString += "axiom "
typeForThisGenerator = getVarTypeFromVarName_EC(generator, config.keygenFuncName_SDL, pairingSetting)
outputString += typeForThisGenerator + "_pow_mod_" + str(generatorCounter) + " :\n"
if (typeForThisGenerator == "G_1"):
outputString += " forall (z:int), g_" + str(generatorCounter) + " ^ (z%%q_1) = g_"
outputString += str(generatorCounter) + " ^ z.\n\n"
elif (typeForThisGenerator == "G_2"):
outputString += " forall (z:int), g_" + str(generatorCounter) + " ^ (z%%q_2) = g_"
outputString += str(generatorCounter) + " ^ z.\n\n"
else:
sys.exit("addTemplateLinesToOutputECFile_SymmetricOrAsymmetric in SDLtoECConvert.py: one of the generators is not of type G1 or G2.")
generatorCounter += 1
outputString += "axiom G_T_pow_mod :\n"
outputString += " forall (z:int), g_T ^ (z%%q_T) = g_T ^ z.\n\n"
outputString += "axiom mod_add :\n"
outputString += " forall (x,y:int), (x%%q + y)%%q = (x + y)%%q.\n\n"
outputString += "axiom mod_small :\n"
outputString += " forall (x:int), 0 <= x => x < q => x%%q = x.\n\n"
outputString += "axiom mod_sub :\n"
outputString += " forall (x, y:int), (x%%q - y)%%q = (x - y)%%q.\n\n"
outputString += "axiom mod_bound :\n"
outputString += " forall (x:int), 0 <= x%%q && x%%q < q.\n\n"
outputString += "pop Rand_exp : () -> (int).\n"
outputString += "pop Rand_G_1 : () -> (G_1).\n"
if (pairingSetting == asymmetricPairingSettingKeyword_SDL):
outputString += "pop Rand_G_2 : () -> (G_2).\n"
outputString += "\n"
outputString += "(* axiom Rand_G_1_exp_def() : x = Rand_G_1_exp() ~ y = [0..q-1] : true ==> x = y. *)\n"
outputString += "axiom Rand_G_1_def() : x = Rand_G_1() ~ y = Rand_exp() : true ==> x = g_"
# this is questionable. Not sure how best to do this. Basically, we're just finding the first
# generator in the group we want, but I don't know if that is technically correct.
generatorCounter = 1
foundIt = False
for generator in generatorsList:
typeForThisGenerator = getVarTypeFromVarName_EC(generator, config.keygenFuncName_SDL, pairingSetting)
if (typeForThisGenerator == "G_1"):
foundIt = True
break
generatorCounter += 1
if (foundIt == False):
sys.exit("addTemplateLinesToOutputECFile_SymmetricOrAsymmetric in SDLtoECConvert.py: could not locate a generator of type G1.")
outputString += str(generatorCounter) + " ^ y.\n\n"
if (pairingSetting == asymmetricPairingSettingKeyword_SDL):
outputString += "axiom Rand_G_2_def() : x = Rand_G_2() ~ y = Rand_exp() : true ==> x = g_"
# again, this is questionable. Not sure how best to do this. Basically, we're just finding the first
# generator in the group we want, but I don't know if that is technically correct.
generatorCounter = 1
foundIt = False
for generator in generatorsList:
typeForThisGenerator = getVarTypeFromVarName_EC(generator, config.keygenFuncName_SDL, pairingSetting)
if (typeForThisGenerator == "G_2"):
foundIt = True
break
generatorCounter += 1
if (foundIt == False):
sys.exit("addTemplateLinesToOutputECFile_SymmetricOrAsymmetric in SDLtoECConvert.py: could not locate a generator of type G2, even though the pairing setting is asymmetric.")
outputString += str(generatorCounter) + " ^ y.\n\n"
outputECFile.write(outputString)
#ENDSHERE
# the following function is defunct and is not used. Ignore it.
def addTemplateLinesToOutputECFile(outputECFile, assignInfo, generatorsList, pairingSetting):
global generatorVarNameToNewName
addTemplateLinesFromOneTemplateFileToOutputECFile(outputECFile, 1)
outputString = ""
generatorCounter = 1
for generator in generatorsList:
outputString += "cnst g_" + str(generatorCounter) + " : G_1.\n"
generatorVarNameToNewName[generator] = "g_" + str(generatorCounter)
generatorCounter += 1
outputECFile.write(outputString)
addTemplateLinesFromOneTemplateFileToOutputECFile(outputECFile, 2)
outputString = ""
generatorCounter = 1
for generator in generatorsList:
outputString += "axiom G_1_pow_add_" + str(generatorCounter) + " :\n"
outputString += " forall (x, y:int), g_" + str(generatorCounter) + " ^ (x + y) = g_"
outputString += str(generatorCounter) + " ^ x * g_" + str(generatorCounter) + " ^ y.\n\n"
generatorCounter += 1
outputECFile.write(outputString)
addTemplateLinesFromOneTemplateFileToOutputECFile(outputECFile, 3)
outputString = ""
generatorCounter = 1
for generator in generatorsList:
outputString += "axiom G_1_pow_mult_" + str(generatorCounter) + " :\n"
outputString += " forall (x, y:int), (g_" + str(generatorCounter) + " ^ x) ^ y = g_"
outputString += str(generatorCounter) + " ^ (x * y).\n\n"
generatorCounter += 1
outputECFile.write(outputString)
addTemplateLinesFromOneTemplateFileToOutputECFile(outputECFile, 4)
outputString = ""
generatorCounter = 1
for generator in generatorsList:
outputString += "axiom G_1_log_pow_" + str(generatorCounter) + " :\n"
outputString += " forall (g_" + str(generatorCounter) + "':G_1), g_" + str(generatorCounter)
outputString += " ^ G_1_log(g_" + str(generatorCounter) + "') = g_" + str(generatorCounter)
outputString += "'.\n\n"
generatorCounter += 1
outputECFile.write(outputString)
addTemplateLinesFromOneTemplateFileToOutputECFile(outputECFile, 5)
outputString = ""
generatorCounter = 1
for generator in generatorsList:
outputString += "axiom G_1_pow_mod_" + str(generatorCounter) + " :\n"
outputString += " forall (z:int), g_" + str(generatorCounter) + " ^ (z%%q) = g_"
outputString += str(generatorCounter) + " ^ z.\n\n"
generatorCounter += 1
outputECFile.write(outputString)
addTemplateLinesFromOneTemplateFileToOutputECFile(outputECFile, 6)
outputString = ""
generatorCounter = 1
for generator in generatorsList:
outputString += "axiom Rand_G_1_def_" + str(generatorCounter)
outputString += "() : x = Rand_G_1() ~ y = Rand_G_1_exp() : " + trueKeyword_EC + " ==> x = g_"
outputString += str(generatorCounter) + " ^ y.\n\n"
generatorCounter += 1
outputECFile.write(outputString)
def removeChars(inputString, inputChars):
inputStringSplit = inputString.split(inputChars)
outputString = ""
for inputStringSplitInd in inputStringSplit:
outputString += inputStringSplitInd
return outputString
def getSchemeName(SDLFileName):
SDLFileNameSplit = SDLFileName.split("/")
lenSplit = len(SDLFileNameSplit)
SDLFileName = SDLFileNameSplit[(lenSplit - 1)]
SDLFileName = SDLFileName.split(".")[0]
SDLFileName = removeChars(SDLFileName, "-")
return SDLFileName
def addGameDeclLine(SDLFileName, outputECFile):
schemeName = getSchemeName(SDLFileName)
outputString = "game "
outputString += schemeName
outputString += "_EF " + assignmentOperator_EC + " " + funcStartChar_EC + "\n"
outputECFile.write(outputString)
def getAtLeastOneHashCallOrNot(inputSDLFile):
atLeastOneHashCall = False
for inputSDLLine in inputSDLFile:
inputSDLLine = inputSDLLine.lstrip().rstrip()
if (inputSDLLine.startswith("#") == True):
continue
splitLine = inputSDLLine.split(":=")
# if it's not an assignment node, then there won't be any hash calls
if (len(splitLine) == 1):
continue
if (len(splitLine) > 2):
sys.exit("getAtLeastOneHashCallOrNot in SDLtoECConvert.py: line in input SDL file contains more than one := symbols; not allowed in SDL.")
rightSide = splitLine[1]
rightSide = rightSide.lstrip().rstrip()
if (rightSide.startswith("H(") == True):
return True
reResult = re.search('[^a-zA-Z0-9_]H\(', rightSide)
if (reResult != None):
return True
return False
def getVarDeps(assignInfo, config, varName, funcName):
# NOTE: this function gets variable dependencies in a very specific way. If the variable name passed
# in is comprised of a list, all of the members of that list are returned. Otherwise, the variable
# name passed in is returned. Example:
#
# pk := list{g, x}
# would return [g, x]
#
# sk := x ^ y
# would return sk
#NOTE: I AM CONSIDERING CHANGING THIS!!!!!!!!! DON'T PAY ATTENTION TO WHAT I WROTE ABOVE.
if (funcName not in assignInfo):
sys.exit("getVarDeps in SDLtoECConvert.py: function name passed in isn't in assignInfo.")
if (varName not in assignInfo[funcName]):
sys.exit("getVarDeps in SDLtoECConvert.py: variable name passed in isn't in the entry of assignInfo for the function name passed in.")
#varDeps = assignInfo[funcName][varName].getListNodesList()
#if (len(varDeps) == 0):
#return [varName]
#return varDeps
return assignInfo[funcName][varName].getVarDeps()
def getVarDepsOrJustVarItself(assignInfo, config, varName, funcName):
# NOTE: this function gets variable dependencies in a very specific way. If the variable name passed
# in is comprised of a list, all of the members of that list are returned. Otherwise, the variable
# name passed in is returned. Example:
#
# pk := list{g, x}
# would return [g, x]
#
# sk := x ^ y
# would return sk
if (funcName not in assignInfo):
sys.exit("getVarDepsOrJustVarItself in SDLtoECConvert.py: function name passed in isn't in assignInfo.")
if (varName not in assignInfo[funcName]):
sys.exit("getVarDepsOrJustVarItself in SDLtoECConvert.py: variable name passed in isn't in the entry of assignInfo for the function name passed in.")
varDeps = assignInfo[funcName][varName].getListNodesList()
if (len(varDeps) == 0):
return [varName]
return varDeps
def addGlobalVars(outputECFile, assignInfo, config, generatorsList, pairingSetting):
#outputString = " " + varKeyword_EC + " " + secretKeyName_EC + " : int\n"
outputString = ""
secretKeyVars = getVarDepsOrJustVarItself(assignInfo, config, config.secretKeyName_SDL, config.keygenFuncName_SDL)
for secretKeyVar in secretKeyVars:
# generators are generators, so they don't get declared
if (secretKeyVar in generatorsList):
continue
currentVarType = getVarTypeFromVarName_EC(secretKeyVar, config.keygenFuncName_SDL, pairingSetting)
outputString += " " + varKeyword_EC + " " + secretKeyVar + " : " + currentVarType + "\n"
publicKeyVars = getVarDepsOrJustVarItself(assignInfo, config, config.publicKeyName_SDL, config.keygenFuncName_SDL)
for publicKeyVar in publicKeyVars:
# generators are generators, so they don't get declared
if (publicKeyVar in generatorsList):
continue
currentVarType = getVarTypeFromVarName_EC(publicKeyVar, config.keygenFuncName_SDL, pairingSetting)
outputString += " " + varKeyword_EC + " " + publicKeyVar + " : " + currentVarType + "\n"
outputString += " " + varKeyword_EC + " " + queriedName_EC + " : message list\n"
outputECFile.write(outputString)
def addGlobalVarsForHashes(outputECFile, assignInfo, config, pairingSetting):
hashGroupTypeOfSigFunc_SDL = getHashGroupTypeOfFunc(config.signFuncName_SDL, assignInfo, config)
hashGroupTypeOfSigFunc_EC = convertTypeSDLtoEC_Strings(hashGroupTypeOfSigFunc_SDL, pairingSetting)
outputString = " " + varKeyword_EC + " " + randomOracleVarName_EC + " : (" + messageType_EC
outputString += ", " + hashGroupTypeOfSigFunc_EC + ") map\n"
outputECFile.write(outputString)
def addHashFuncDef(outputECFile, assignInfo, config, pairingSetting):
hashGroupTypeOfSigFunc_SDL = getHashGroupTypeOfFunc(config.signFuncName_SDL, assignInfo, config)
hashGroupTypeOfSigFunc_EC = convertTypeSDLtoEC_Strings(hashGroupTypeOfSigFunc_SDL, pairingSetting)
outputString = "\n " + funcName_EC + " " + hashFuncName_EC + "(m : message) : "
outputString += hashGroupTypeOfSigFunc_EC + " = {\n"
outputECFile.write(outputString)
writeCountVarIncrement(outputECFile, hashFuncName_EC)
outputString = ""
outputString += " if(!in_dom(m, " + randomOracleVarName_EC + ")) {\n"
outputString += " " + randomOracleVarName_EC + "[m] = Rand_"
if (hashGroupTypeOfSigFunc_EC == "G_1"):
outputString += "G_1"
elif (hashGroupTypeOfSigFunc_EC == "G_2"):
outputString += "G_2"
else:
sys.exit("addHashFuncDef in SDLtoECConvert.py: hash group type of signature function obtained isn't of group type G1 or G2.")
outputString += "();\n"
outputString += " }\n"
outputString += " return " + randomOracleVarName_EC + "[m];\n"
outputString += " }\n\n"
outputECFile.write(outputString)
def addStatementsForPresenceOfHashes(outputECFile, assignInfo, config, pairingSetting):
addGlobalVarsForHashes(outputECFile, assignInfo, config, pairingSetting)
addHashFuncDef(outputECFile, assignInfo, config, pairingSetting)
def getInputSDLFileMetadata(inputSDLFileName):
parseFile(inputSDLFileName, False, True)
assignInfo = getAssignInfo()
astNodes = getAstNodes()
return (assignInfo, astNodes)
'''
def getHashGroupTypesRecursive(currentAssignNode, retList):
if (currentAssignNode == None):
return
if (currentAssignNode.type == ops.HASH):
currentHashGroupType = str(currentAssignNode.right)
if (len(retList) == 0):
retList.append(currentHashGroupType)
else:
if (currentHashGroupType != retList[0]):
sys.exit("getHashGroupTypesRecursive in SDLtoECConvert.py: found hash calls that hash to different group types. Not currently supported.")
if (currentAssignNode.left != None):
getHashGroupTypesRecursive(currentAssignNode.left, retList)
if (currentAssignNode.right != None):
getHashGroupTypesRecursive(currentAssignNode.right, retList)
def getHashGroupTypes(currentAssignNode):
retList = []
getHashGroupTypesRecursive(currentAssignNode, retList)
return retList
def getAtLeastOneHashCallOrNot_WithSDLParser(assignInfo):
for funcName in assignInfo:
for varName in assignInfo[funcName]:
varInfoObj = assignInfo[funcName][varName]
currentAssignNode = varInfoObj.getAssignNode()
hashGroupTypes = getHashGroupTypes(currentAssignNode)
'''
def getAtLeastOneHashCallOrNot_WithSDLParser(assignInfo):
for funcName in assignInfo:
for varName in assignInfo[funcName]:
varInfoObj = assignInfo[funcName][varName]
if (len(varInfoObj.getHashArgsInAssignNode()) > 0):
return True
return False
def getVarTypeFromVarName_EC(varName, funcName, pairingSetting):
if DEBUG : print("getVarTypeFromVarName_EC: varName and funcName are ", varName, " and ", funcName)
varType_SDL = getVarTypeFromVarName(varName, funcName, False, False)
if (varType_SDL == types.NO_TYPE):
sys.exit("getVarTypeFromVarName_EC in SDLtoECConvert.py: getVarTypeFromVarName returned types.NO_TYPE for variable name " + str(varName) + " and function name " + str(funcName) + ".")
varType_EC = convertTypeSDLtoEC(varType_SDL, pairingSetting)
return varType_EC
def writeVarDecls(outputECFile, oldFuncName, assignInfo, config, generatorsList, varsToNotDeclareInputParam, pairingSetting):
#if DEBUG : print("writeVarDecls: funcName is ", oldFuncName, " and varsToNotDeclare: ", varsToNotDeclareInputParam)
if (oldFuncName not in assignInfo):
sys.exit("writeVarDecls in SDLtoECConvert.py: oldFuncName not in assignInfo.")
outputString = ""
# public key variables and secret key variables are all declared globally, so don't declare them
# locally.
publicKeyVars = getVarDepsOrJustVarItself(assignInfo, config, config.publicKeyName_SDL, config.keygenFuncName_SDL)
secretKeyVars = getVarDepsOrJustVarItself(assignInfo, config, config.secretKeyName_SDL, config.keygenFuncName_SDL)
listOfVarsToNotDeclare = []
for publicKeyVar in publicKeyVars:
if (publicKeyVar not in listOfVarsToNotDeclare):
listOfVarsToNotDeclare.append(publicKeyVar)
for secretKeyVar in secretKeyVars:
if (secretKeyVar not in listOfVarsToNotDeclare):
listOfVarsToNotDeclare.append(secretKeyVar)
for varToNotDeclareInputParam in varsToNotDeclareInputParam:
if (varToNotDeclareInputParam not in listOfVarsToNotDeclare):
listOfVarsToNotDeclare.append(varToNotDeclareInputParam)
#if (outputKeyword not in listOfVarsToNotDeclare):
#listOfVarsToNotDeclare.append(outputKeyword)
if (config.publicKeyName_SDL not in listOfVarsToNotDeclare):
listOfVarsToNotDeclare.append(config.publicKeyName_SDL)
if (config.secretKeyName_SDL not in listOfVarsToNotDeclare):
listOfVarsToNotDeclare.append(config.secretKeyName_SDL)
if DEBUG : print("writeVarDecls: funcName is ", oldFuncName, " and varsToNotDeclare: ", listOfVarsToNotDeclare)
for varName in assignInfo[oldFuncName]:
if (varName == inputKeyword):
continue
if (varName in listOfVarsToNotDeclare):
continue
# generators don't need to be declared
if (varName in generatorsList):
continue
#for some reason, SDLParser says variables of type "bool" are actually of type "int".
#Here's a workaround to fix that
assignNodeRight = str(assignInfo[oldFuncName][varName].getAssignNode().right)
if ( (assignNodeRight == trueKeyword_SDL) or (assignNodeRight == falseKeyword_SDL) ):
outputString += " " + varKeyword_EC + " " + varName + " : " + booleanType_EC + ";\n"
continue
varType_EC = getVarTypeFromVarName_EC(varName, oldFuncName, pairingSetting)
outputString += " " + varKeyword_EC + " " + varName + " : " + varType_EC + ";\n"
if (len(outputString) > 0):
outputECFile.write(outputString)
def writeBodyOfFunc(outputECFile, oldFuncName, astNodes, config, assignStmtsToNotInclude, generatorsList):
startLineNoOfFunc = getStartLineNoOfFunc(oldFuncName)
endLineNoOfFunc = getEndLineNoOfFunc(oldFuncName)
startLineNoOfBody = startLineNoOfFunc + 2
endLineNoOfBody = endLineNoOfFunc - 1
writeAstNodesToFile(outputECFile, astNodes, startLineNoOfBody, endLineNoOfBody, config, assignStmtsToNotInclude, generatorsList)
def isAssignStmt(astNode):
if (astNode.type == ops.EQ):
return True
return False
def makeSDLtoECVarNameReplacements(attrAsString, config):
if (attrAsString == config.messageName_SDL):
return messageName_EC
if (attrAsString == config.secretKeyName_SDL):
return secretKeyName_EC
return attrAsString
def getAssignStmtAsString(astNode, config, generatorsList):
if (astNode.type == ops.ATTR):
attrAsString = str(astNode)
#attrAsString = makeSDLtoECVarNameReplacements(attrAsString, config)
if (attrAsString in generatorsList):
return generatorVarNameToNewName[attrAsString]
#if (len(generatorsList) == 1):
# if there's only one generator, that's our generator. Make the replacement so that our
# variable name is replaced by the one EC generator generator.
#return constantGeneratorVarName_EC
#return constantGeneratorVarName_EC
#sys.exit("getAssignStmtAsString in SDLtoECConvert.py: there are multiple constants in the SDL input file. We don't currently handle that right now.")
if (attrAsString == trueKeyword_SDL):
return trueKeyword_EC
if (attrAsString == falseKeyword_SDL):
return falseKeyword_EC
#print(attrAsString)
#if (attrAsString == NONE_STRING):
#return ""
return attrAsString
elif (astNode.type == ops.TYPE):
groupTypeAsString = str(astNode)
if (groupTypeAsString not in validGroupTypes):
sys.exit("getAssignStmtAsString in SDLtoECConvert.py: received node of type ops.TYPE, but it is not a valid type.")
return groupTypeAsString
elif (astNode.type == ops.EXP):
leftSide = getAssignStmtAsString(astNode.left, config, generatorsList)
rightSide = getAssignStmtAsString(astNode.right, config, generatorsList)
return "(" + leftSide + " " + expOp_EC + " " + rightSide + ")"
elif (astNode.type == ops.PAIR):
leftSide = getAssignStmtAsString(astNode.left, config, generatorsList)
rightSide = getAssignStmtAsString(astNode.right, config, generatorsList)
return "e(" + leftSide + ", " + rightSide + ")"
elif (astNode.type == ops.EQ):
leftSide = getAssignStmtAsString(astNode.left, config, generatorsList)
rightSide = getAssignStmtAsString(astNode.right, config, generatorsList)
return leftSide + " " + assignmentOperator_EC + " " + rightSide
elif (astNode.type == ops.EQ_TST):
leftSide = getAssignStmtAsString(astNode.left, config, generatorsList)
rightSide = getAssignStmtAsString(astNode.right, config, generatorsList)
return "(" + leftSide + " " + eqTstOperator_EC + " " + rightSide + ")"
elif (astNode.type == ops.HASH):
leftSide = getAssignStmtAsString(astNode.left, config, generatorsList)
rightSide = getAssignStmtAsString(astNode.right, config, generatorsList)
if (rightSide not in validHashGroupTypes):
sys.exit("getAssignStmtAsString in SDLtoECConvert.py: received invalid type for hash call.")
#return hashFuncName_EC + "(" + leftSide + ", " + rightSide + ")"
return hashFuncName_EC + "(" + leftSide + ")"
elif (astNode.type == ops.RANDOM):
randomGroupType = getAssignStmtAsString(astNode.left, config, generatorsList)
if (randomGroupType not in validRandomGroupTypes):
sys.exit("getAssignStmtAsString in SDLtoECConvert.py: received invalid type for random call.")
if (randomGroupType == str(types.G1)):
return randomG1GenerationStmt_EC
elif (randomGroupType == str(types.G2)):
return randomG2GenerationStmt_EC
elif (randomGroupType == str(types.ZR)):
return randomZRGenerationStmt_EC
else:
sys.exit("getAssignStmtAsString in SDLtoECConvert.py: error in system logic for random calls.")
elif (astNode.type == ops.FUNC):
funcReturnString = ""
userFuncName = getFullVarName(astNode, True)
funcReturnString += userFuncName + "("
funcListNodes = getListNodeNames(astNode)
atLeastOneFuncListNode = False
for funcListNode in funcListNodes:
if (funcListNode == NONE_STRING):
continue
funcReturnString += funcListNode + ", "
atLeastOneFuncListNode = True
if (atLeastOneFuncListNode == True):
lenFuncReturnString = len(funcReturnString)
funcReturnString = funcReturnString[0:(lenFuncReturnString - len(", "))]
funcReturnString += ")"
return funcReturnString
else:
sys.exit("getAssignStmtAsString in SDLtoECConvert.py: could not handle this type (" + str(astNode.type) + ") of node (" + str(astNode) + "). Need to add more logic to support it.")
def isUnnecessaryNode(astNode):
if ( (astNode.type == ops.BEGIN) and (astNode.left.attr == IF_BRANCH_HEADER) ):
return True
return False
def isIfStmtStart(astNode):
if (astNode.type == ops.IF):
return True
return False
def getIfStmtDecl(astNode, config, generatorsList):
outputString = ""
outputString += "if("
outputString += getAssignStmtAsString(astNode.left, config, generatorsList)
outputString += ") {"
return outputString
def getIfStmtEnd(astNode):
return "}"
def isIfStmtEnd(astNode):
if ( (astNode.type == ops.END) and (astNode.left.attr == IF_BRANCH_HEADER) ):
return True
return False
def isElseStmtStart(astNode):
if (astNode.type == ops.ELSE):
return True
return False
def isNONENode(astNode):
if (astNode.type == ops.NONE):
return True
return False
def getElseStmtStart(astNode, config):
outputString = ""
if (astNode.left == None):
outputString += "else {"
else:
outputString += "else if ("
outputString += getAssignStmtAsString(astNode.left, config, generatorsList)
outputString += ") {"
return outputString
def isAssignStmtToNotInclude(astNode, config, assignStmtsToNotInclude, generatorsList):
if (isAssignStmt(astNode) == False):
return False
varNameToBeAssigned = getAssignStmtAsString(astNode.left, config, generatorsList)
if (varNameToBeAssigned in assignStmtsToNotInclude):
return True
if (astNode.right.type == ops.EXPAND):
return True
if (astNode.right.type == ops.LIST):
return True
return False
def writeAstNodesToFile(outputECFile, astNodes, startLineNo, endLineNo, config, assignStmtsToNotInclude, generatorsList):
outputString = ""
currentNumSpaces = (numSpacesForIndent * 2)
for lineNo in range(startLineNo, (endLineNo + 1)):
currentAstNode = astNodes[(lineNo - 1)]
if (isAssignStmtToNotInclude(currentAstNode, config, assignStmtsToNotInclude, generatorsList) == True):
continue
elif (isAssignStmt(currentAstNode) == True):
# generators don't get assignment statements
if (str(currentAstNode.left) in generatorsList):
continue
outputString += writeNumOfSpacesToString(currentNumSpaces)
outputString += getAssignStmtAsString(currentAstNode, config, generatorsList)
outputString += endOfLineOperator_EC
elif (isIfStmtStart(currentAstNode) == True):
outputString += writeNumOfSpacesToString(currentNumSpaces)
outputString += getIfStmtDecl(currentAstNode, config, generatorsList)
currentNumSpaces += numSpacesForIndent
elif (isIfStmtEnd(currentAstNode) == True):
currentNumSpaces -= numSpacesForIndent
outputString += writeNumOfSpacesToString(currentNumSpaces)
outputString += getIfStmtEnd(currentAstNode)
elif (isElseStmtStart(currentAstNode) == True):
currentNumSpaces -= numSpacesForIndent
outputString += writeNumOfSpacesToString(currentNumSpaces)
outputString += "}\n"
outputString += writeNumOfSpacesToString(currentNumSpaces)
outputString += getElseStmtStart(currentAstNode, config)
currentNumSpaces += numSpacesForIndent
elif (isUnnecessaryNode(currentAstNode) == True):
continue
elif (isNONENode(currentAstNode) == True):
continue
else:
sys.exit("writeAstNodesToFile in SDLtoECConvert.py: cannot handle this type of AST node (" + str(currentAstNode) + "). Need to add logic to support it.")
outputString += "\n"
outputECFile.write(outputString)
def writeMessageAdditionToQueriedList(outputECFile, config):
outputString = ""
outputString += writeNumOfSpacesToString(numSpacesForIndent * 2)
outputString += queriedName_EC + " " + assignmentOperator_EC + " "
outputString += config.messageName_SDL + " " + appendOperator_EC + " "
outputString += queriedName_EC + endOfLineOperator_EC + "\n"
outputECFile.write(outputString)
def writeReturnValue(outputECFile, funcName, assignInfo):
if (funcName not in assignInfo):
sys.exit("writeReturnValue in SDLtoECConvert.py: funcName parameter passed in is not in assignInfo parameter passed in.")
if (outputKeyword not in assignInfo[funcName]):
sys.exit("writeReturnValue in SDLtoECConvert.py: outputKeyword not in assignInfo[funcName].")
'''
outputVarInfoObj = assignInfo[funcName][outputKeyword]
outputVarDeps = outputVarInfoObj.getVarDeps()
if ( (len(outputVarDeps) != 1) and (outputVarDeps != [trueKeyword_SDL, falseKeyword_SDL]) ):
sys.exit("writeReturnValue in SDLtoECConvert.py: variable dependencies of output keyword does not consist of a list of one element OR a list of [\"True\", \"False\"], which is what is expected.")
'''
outputString = ""
outputString += writeNumOfSpacesToString(numSpacesForIndent * 2)
outputString += returnKeyword_EC + " "
'''
if (len(outputVarDeps) == 1):
outputString += str(outputVarDeps[0]) + endOfLineOperator_EC + "\n"
else:
outputString += outputKeyword + endOfLineOperator_EC + "\n"
'''
outputString += outputKeyword + endOfLineOperator_EC + "\n"
outputECFile.write(outputString)
def writeFuncEnd(outputECFile):
outputString = ""
outputString += writeNumOfSpacesToString(numSpacesForIndent)
outputString += funcEndChar_EC + "\n\n"
outputECFile.write(outputString)
def addBoolRetVarForVerifyFunc(outputECFile):
outputString = ""
outputString += writeNumOfSpacesToString(numSpacesForIndent * 2)
outputString += varKeyword_EC + " " + varNameForVerifyBoolRetVal_EC + " : "
outputString += booleanType_EC + endOfLineOperator_EC + "\n"
outputECFile.write(outputString)
def convertSignFunc(outputECFile, config, assignInfo, astNodes, generatorsList, pairingSetting):
writeFuncDecl(outputECFile, config.signFuncName_SDL, signFuncName_EC, config, assignInfo, generatorsList, pairingSetting)
writeVarDecls(outputECFile, config.signFuncName_SDL, assignInfo, config, generatorsList, [], pairingSetting)
writeCountVarIncrement(outputECFile, signFuncName_EC)
writeBodyOfFunc(outputECFile, config.signFuncName_SDL, astNodes, config, [], generatorsList)
writeMessageAdditionToQueriedList(outputECFile, config)
writeReturnValue(outputECFile, config.signFuncName_SDL, assignInfo)
writeFuncEnd(outputECFile)
def convertVerifyFunc(outputECFile, config, assignInfo, astNodes, generatorsList, pairingSetting):
writeFuncDecl(outputECFile, config.verifyFuncName_SDL, verifyFuncName_EC, config, assignInfo, generatorsList, pairingSetting)
writeVarDecls(outputECFile, config.verifyFuncName_SDL, assignInfo, config, generatorsList, [], pairingSetting)
#addBoolRetVarForVerifyFunc(outputECFile)
writeCountVarIncrement(outputECFile, verifyFuncName_EC)
writeBodyOfFunc(outputECFile, config.verifyFuncName_SDL, astNodes, config, [], generatorsList)