-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathsboxanalyzer.py
executable file
·2470 lines (2219 loc) · 130 KB
/
sboxanalyzer.py
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
# -*- coding: utf-8 -*-
#!/usr/local/bin/sage
"""
SA: S-box Analyzer
AUTHORS:
- Hosein Hadipour (2022-05-26)
EXAMPLES::
sage: from sboxanalyzer import *
sage: from sage.crypto.sboxes import PRINTcipher as sb
sage: sa = SboxAnalyzer(sb)
sage: cnf, milp = sa.minimized_diff_constraints()
Simplifying the MILP/SAT constraints ...
Time used to simplify the constraints: 0.01 seconds
Number of constraints: 17
Input: a0||a1||a2; a0: msb
Output: b0||b1||b2; b0: msb
Weight: 2.0000 p0
sage: print(milp)
['- a1 + p0 >= 0',
'- b0 + p0 >= 0',
'- b2 + p0 >= 0',
'a0 + a1 - a2 + b2 >= 0',
'a1 + b0 - b1 + b2 >= 0',
'- a0 + b0 + b1 + b2 >= 0',
'a0 + a1 + a2 - p0 >= 0',
'a1 + a2 + b0 - p0 >= 0',
'a0 + a2 + b1 - p0 >= 0',
'a2 + b0 + b1 - p0 >= 0',
'a0 + b1 + b2 - p0 >= 0',
'- a1 - a2 + b0 - b1 - b2 >= -3',
'a0 - a1 - a2 - b1 - b2 >= -3',
'- a0 - a2 - b0 + b1 - b2 >= -3',
'- a0 - a1 - b0 - b1 + b2 >= -3',
'- a0 + a1 - a2 - b0 - b2 >= -3',
'- a0 - a1 + a2 - b0 - b1 >= -3']
sage: print(cnf)
(~a1 | p0) & (~b0 | p0) & (~b2 | p0) & (a0 | a1 | ~a2 | b2) &
(a1 | b0 | ~b1 | b2) & (~a0 | b0 | b1 | b2) & (a0 | a1 | a2 | ~p0) &
(a1 | a2 | b0 | ~p0) & (a0 | a2 | b1 | ~p0) & (a2 | b0 | b1 | ~p0) & (a0 | b1 | b2 | ~p0) &
(~a1 | ~a2 | b0 | ~b1 | ~b2) & (a0 | ~a1 | ~a2 | ~b1 | ~b2) & (~a0 | ~a2 | ~b0 | b1 | ~b2) &
(~a0 | ~a1 | ~b0 | ~b1 | b2) & (~a0 | a1 | ~a2 | ~b0 | ~b2) & (~a0 | ~a1 | a2 | ~b0 | ~b1)
"""
#*****************************************************************************
# Copyright (C) 2022 Hosein Hadipour <hsn.hadipour@gmail.com>
# MIT License
# Copyright (c) 2022 Hosein Hadipour
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
#*****************************************************************************
import subprocess
import os
import time
from sage.all import *
from sage.crypto.sboxes import SBox
import itertools
# ESPRESO_BIN_PATH = os.path.join(os.environ['SAGE_ROOT'], 'local/bin/espresso')
ESPRESO_BIN_PATH = os.path.join(os.getcwd(), 'espresso', 'build', 'espresso')
class SboxAnalyzer(SBox):
r"""
This module encodes the DDT, LAT and MPT [HE22]_ of a given S-box with MILP/SAT constraints and
then simplifies the extracted constraints using logic minimization tools
EXAMPLES:
We consider the S-box of block cipher PRINTcipher [KLPR2010]_::
sage: from sboxanalyzer import *
sage: from sage.crypto.sboxes import PRINTcipher as sb
sage: sa = SboxAnalyzer(sb)
sage: cnf, milp = sa.minimized_diff_constraints()
Simplifying the MILP/SAT constraints ...
Time used to simplify the constraints: 0.01 seconds
Number of constraints: 17
Input: a0||a1||a2; a0: msb
Output: b0||b1||b2; b0: msb
Weight: 2.0000 p0
sage: print(milp)
['- a1 + p0 >= 0',
'- b0 + p0 >= 0',
'- b2 + p0 >= 0',
'a0 + a1 - a2 + b2 >= 0',
'a1 + b0 - b1 + b2 >= 0',
'- a0 + b0 + b1 + b2 >= 0',
'a0 + a1 + a2 - p0 >= 0',
'a1 + a2 + b0 - p0 >= 0',
'a0 + a2 + b1 - p0 >= 0',
'a2 + b0 + b1 - p0 >= 0',
'a0 + b1 + b2 - p0 >= 0',
'- a1 - a2 + b0 - b1 - b2 >= -3',
'a0 - a1 - a2 - b1 - b2 >= -3',
'- a0 - a2 - b0 + b1 - b2 >= -3',
'- a0 - a1 - b0 - b1 + b2 >= -3',
'- a0 + a1 - a2 - b0 - b2 >= -3',
'- a0 - a1 + a2 - b0 - b1 >= -3']
sage: print(cnf)
(~a1 | p0) & (~b0 | p0) & (~b2 | p0) & (a0 | a1 | ~a2 | b2) &
(a1 | b0 | ~b1 | b2) & (~a0 | b0 | b1 | b2) & (a0 | a1 | a2 | ~p0) &
(a1 | a2 | b0 | ~p0) & (a0 | a2 | b1 | ~p0) & (a2 | b0 | b1 | ~p0) & (a0 | b1 | b2 | ~p0) &
(~a1 | ~a2 | b0 | ~b1 | ~b2) & (a0 | ~a1 | ~a2 | ~b1 | ~b2) & (~a0 | ~a2 | ~b0 | b1 | ~b2) &
(~a0 | ~a1 | ~b0 | ~b1 | b2) & (~a0 | a1 | ~a2 | ~b0 | ~b2) & (~a0 | ~a1 | a2 | ~b0 | ~b1)
AUTHORS:
- Hosein Hadipour (2022-05-26)
REFERENCES:
- [KLPR2010]_
- [HE22]_
"""
sbox_counter = 0
def __init__(self, lookuptable):
"""
Initialize the lookup table of S-box
:param lookuptable list: list of integers or hexadecimal numbers specifying the S-box mapping
"""
super().__init__(lookuptable)
SboxAnalyzer.sbox_counter += 1
if not os.path.exists(os.path.join(os.getcwd(), 'tmp')):
os.makedirs(os.path.join(os.getcwd(), 'tmp'))
self.truth_table_filename = os.path.join(os.getcwd(), 'tmp', 'tt_' + str(SboxAnalyzer.sbox_counter) + '.txt')
self.simplified_truth_table_filename = os.path.join(os.getcwd(), 'tmp', 'stt_' + str(SboxAnalyzer.sbox_counter) + '.txt')
# A flag to check if the data required for differential analysis are present in memory
self._data_required_for_differential_analysis = None
# A flag to check if the data required for linear analysis are present in memory
self._data_required_for_linear_analysis = None
# A flag to check if the data required for integral analysis are presenet in memory
self._data_required_for_integral_analysis = None
# A flag to check if the data required for differential-linear analysis are presenet in memory
self._data_required_for_difflin_analysis = None
# define a dictionalry to encode deterministic behavior
self.unknown, self.zero, self.one = -1, 0, 1
self.zero_binary = [0, 0]
self.one_binary = [0, 1]
self.unknown_binary = [1, 0]
self.deterministic_mask = {self.zero: {0}, self.one:{1}, self.unknown:{0, 1}}
@staticmethod
def print_table(table):
"""
Prints the table in a nice format
"""
column_widths = [max(len(str(row[i])) for row in table) for i in range(len(table[0]))]
for row in table:
formatted_row = [str(value).rjust(width) for value, width in zip(row, column_widths)]
print(" ".join(formatted_row))
def monomial_prediction_table(self):
"""
Compute the Monomial Prediction Table (MPT) based on [HE22]:
https://tosc.iacr.org/index.php/ToSC/article/view/9715
"""
"""
SageMath's naming convention for Sbox:
x0: MSB
SageMath's naming convention for the ANF of Boolean function:
x0: LSB
Example:
x1, x0 | y
-----------
0 , 0 | 1
0 , 1 | 0
1 , 0 | 1
1 , 1 | 0
y = 1 + x0
----------
from sage.crypto.boolean_function import BooleanFunction
f = BooleanFunction([1, 0, 1, 0])
anf = f.algebraic_normal_form()
Sage output: x0 + 1
"""
mpt = [[0 for i in range(2**self.output_size())] for j in range(2**self.input_size())]
BPR = BooleanPolynomialRing(n=self.input_size(), names="x")
output_components = [0]*self.output_size()
for i in range(self.output_size()):
shift_value = 1 << (self.output_size() - i - 1)
output_mask = self.to_bits(x=shift_value, n=self.output_size())
output_components[i] = self.component_function(output_mask).algebraic_normal_form()
input_vars = list(BPR.gens())
input_vars.reverse()
for u in range(2**self.input_size()):
input_mask = self.to_bits(x=u, n=self.input_size())
monomial = product([input_vars[i]**input_mask[i] for i in range(self.input_size())])
for v in range(2**self.output_size()):
output_mask = self.to_bits(x=v, n=self.output_size())
f = product([output_components[i]**output_mask[i] for i in range(self.output_size())])
if monomial in f.monomials():
mpt[u][v] = 1
return mpt
###############################################################################################################
###############################################################################################################
###############################################################################################################
# ___ _ __ _ _____ ____ ____ ____ _____ ____ ____ ___
# |_ _| _ __ | |_ ___ _ __ / _| __ _ ___ ___ | |_ ___ | ____|/ ___| | _ \ | _ \ | ____|/ ___|/ ___| / _ \
# | | | '_ \ | __|/ _ \| '__|| |_ / _` | / __|/ _ \ | __|/ _ \ | _| \___ \ | |_) || |_) || _| \___ \\___ \ | | | |
# | | | | | || |_| __/| | | _|| (_| || (__| __/ | |_| (_) | | |___ ___) || __/ | _ < | |___ ___) |___) || |_| |
# |___||_| |_| \__|\___||_| |_| \__,_| \___|\___| \__|\___/ |_____||____/ |_| |_| \_\|_____||____/|____/ \___/
# Interface to ESPRESSO
###############################################################################################################
@staticmethod
def _write_truth_table(filename, boolean_function, input_output_variables=None):
"""
Write the Boolean function encoding the DDT of S-box into
a text file according to the input format of
the ESPRESSO
:param filename str: an string specifying the filename
"""
if input_output_variables is None:
no_of_input_vars = len(next(iter(boolean_function.keys())))
file_contents = f".i {no_of_input_vars}\n"
file_contents += ".o 1\n"
file_contents += ".ilb {0}\n".format(" ".join(f"x{i}" for i in range(no_of_input_vars)))
else:
file_contents = f".i {len(input_output_variables)}\n"
file_contents += ".o 1\n"
file_contents += ".ilb {0}\n".format(" ".join(input_output_variables))
file_contents += ".ob F\n"
for key, value in boolean_function.items():
file_contents += "{0}{1}\n".format("".join(map(str, key)), str(value))
with open(filename, "w") as fileobj:
fileobj.write(file_contents)
fileobj.write(".e\n")
@staticmethod
def simplify_by_espresso(input_file, output_file, mode):
"""
Simplify the CNF formula using the ESPRESSO
"""
valid_values_for_mode = list(range(8))
if mode not in valid_values_for_mode:
raise ValueError("Invalid value for mode! mode must be in [0, 1, 2, 3, 4, 5, 6, 7].")
# If reverse = 1 choose ON-SET and if reverse = 0 choose OFF-SET
espresso_options = [[], # 0 ON-SET : Derived constraints exclude point p such that f(p) = 1
["-Dexact", "-estrong", "-s", "-t", "-or"], # 1 OFF-SET:* Derived constraints exclude point p such that f(p) = 0
["-Dexact", "-estrong", "-s", "-t", "-of"], # 2 ON-SET : Derived constraints exclude point p such that f(p) = 1 *
["-Dexact", "-efast", "-s", "-t", "-or"], # 3 OFF-SET:* Derived constraints exclude point p such that f(p) = 0
["-Dexact", "-efast", "-s", "-t", "-of"]] # 4 ON-SET : Derived constraints exclude point p such that f(p) = 1
# ATTENTION!
# -epos: complements the boolean function
# Therefore, instead of reverse=1 we can use -epos
# If so, we should make sure that reverse=0 in this case
espresso_options += [["-Dexact", "-estrong", "-epos", "-s", "-t", "-of"], # 5 ON-SET :* Derived constraints exclude point p such that f(p) = 1]
["-Dmany", "-estrong", "-epos", "-s", "-t", "-of"], # 6 ON-SET :* Derived constraints exclude point p such that f(p) = 1]
["-Dmany", "-efast", "-epos", "-s", "-t", "-of"]] # 7 ON-SET :* Derived constraints exclude point p such that f(p) = 1]
# Best options (not always), in terms of optimality: 5, then 6, then 7, then 1 (6 is good and fast enough in cases 5 is too slow)
with open(output_file, 'w') as fileobj:
subprocess.call([ESPRESO_BIN_PATH, *espresso_options[mode], input_file], stdout=fileobj)
@staticmethod
def _parse_the_output_of_espresso(filename, alphabet):
"""
Parse the output of ESPRESSO
"""
with open(filename, 'r') as fileobj:
espresso_output = fileobj.readlines()
milp_constraints = []
sat_clauses = []
starting_point = 0
end_point = 0
for i in range(len(espresso_output)):
if ".p" in espresso_output[i]:
starting_point = i + 1
# number_of_constraints = espresso_output[i].split(" ")[1]
if ".e" in espresso_output[i]:
end_point = i
for l in espresso_output[starting_point:end_point]:
line = l[0:len(alphabet)]
orclause = []
lp = []
lp_rhs = 0
for i in range(len(alphabet)):
if line[i] == '0':
orclause.append(alphabet[i])
lp.append(" + {}".format(alphabet[i]))
elif line[i] == '1':
orclause.append("~{}".format(alphabet[i]))
lp.append(" - {}".format(alphabet[i]))
lp_rhs += 1
sat_clauses.append("({})".format(' | '.join(orclause)))
lp_rhs = -(lp_rhs - 1)
lp_constraint = "".join(lp) + " >= {}".format(lp_rhs)
if lp_constraint[0:3] == " + ":
lp_constraint = lp_constraint[3:]
else:
lp_constraint = lp_constraint[1:]
milp_constraints.append("{}".format(lp_constraint))
sat_clauses = ' & '.join(sat_clauses)
return (sat_clauses, milp_constraints)
###############################################################################################################
###############################################################################################################
###############################################################################################################
# ____ _ _____ _ _ _ ____ _ __ ____ _ __ __ _
# | __ ) ___ ___ | | ___ __ _ _ __ __ _ | ___|_ _ _ __ ___ | |_ (_) ___ _ __ ___ __ _ _ __ __| | / ___| ___ | |_ ___ / _| | __ ) (_) _ __ __ _ _ __ _ _ \ \ / /___ ___ | |_ ___ _ __ ___
# | _ \ / _ \ / _ \ | | / _ \ / _` || '_ \ / _` | | |_ | | | || '_ \ / __|| __|| | / _ \ | '_ \ / __| / _` || '_ \ / _` | \___ \ / _ \| __| / _ \ | |_ | _ \ | || '_ \ / _` || '__|| | | | \ \ / // _ \ / __|| __|/ _ \ | '__|/ __|
# | |_) || (_) || (_) || || __/| (_| || | | || (_| | | _| | |_| || | | || (__ | |_ | || (_) || | | |\__ \ | (_| || | | || (_| | ___) || __/| |_ | (_) || _| | |_) || || | | || (_| || | | |_| | \ V /| __/| (__ | |_| (_) || | \__ \
# |____/ \___/ \___/ |_| \___| \__,_||_| |_| \__, | |_| \__,_||_| |_| \___| \__||_| \___/ |_| |_||___/ \__,_||_| |_| \__,_| |____/ \___| \__| \___/ |_| |____/ |_||_| |_| \__,_||_| \__, | \_/ \___| \___| \__|\___/ |_| |___/
# |___/ |___/
# Encoding Booleann functions and set of binary vectors into MILP/SAT constraints
@staticmethod
def encode_boolean_function(truth_table, input_variables=None, mode=6):
"""
Encode the Boolean function into MILP/SAT constraints
"""
if mode in [1, 3, 5, 6, 7]:
reverse = 0
else:
reverse = 1
if any([i not in {0, 1} for i in truth_table]):
raise ValueError("Each element of the truth table must be either 0 or 1.")
log2_length = log(len(truth_table), 2)
if log2_length != int(log2_length):
raise ValueError("The length of the truth table must be a power of 2.")
boolean_function = dict()
for i in range(len(truth_table)):
key = tuple(map(int, list(bin(i)[2:].zfill(log2_length))))
boolean_function[key] = truth_table[i] ^ reverse
input_file = os.path.join(os.getcwd(), 'tt_' + hex(randint(0, 65536))[2:] + '.txt')
output_file = os.path.join(os.getcwd(), 'stt_' + hex(randint(0, 65536))[2:] + '.txt')
if input_variables is None:
input_variables = [f"x{i}" for i in range(log2_length)]
else:
if len(input_variables) != log2_length:
raise ValueError("The length of input variables must be equal to the number of input variables.")
SboxAnalyzer._write_truth_table(filename=input_file,
boolean_function=boolean_function,
input_output_variables=input_variables)
print("Generateing and simplifying the MILP/SAT constraints ...")
starting_time = time.time()
SboxAnalyzer.simplify_by_espresso(input_file=input_file,
output_file=output_file,
mode=mode)
elapsed_time = time.time() - starting_time
print("Time used to simplify the constraints: {:.2f} seconds".format(elapsed_time))
sat_clauses, milp_constraints = SboxAnalyzer._parse_the_output_of_espresso(filename=output_file,
alphabet=input_variables)
print("Number of constraints: {}".format(len(milp_constraints)))
print("Variables: {}; msb: {}".format("||".join(input_variables), input_variables[0]))
os.remove(input_file)
os.remove(output_file)
return (sat_clauses, milp_constraints)
@staticmethod
def encode_set_of_binary_vectors(set_of_binary_vectors, input_variables=None, mode=6):
"""
Encode the set of binary vectors into MILP/SAT constraints
"""
if mode in [1, 3, 5, 6, 7]:
reverse = 0
else:
reverse = 1
set_of_binary_vectors = list(set(set_of_binary_vectors))
# check if each element of the set has the same length
if len(set_of_binary_vectors) == 0:
raise ValueError("The set of binary vectors is empty.")
num_of_elements = len(set_of_binary_vectors)
num_of_bits = len(set_of_binary_vectors[0])
if not all([num_of_bits == len(v) for v in set_of_binary_vectors]):
raise ValueError("All elements of the set must have the same length.")
boolean_function = dict()
for v in range(2**num_of_bits):
key = tuple(map(int, list(bin(v)[2:].zfill(num_of_bits))))
boolean_function[key] = int(key in set_of_binary_vectors) ^ reverse
input_file = os.path.join(os.getcwd(), 'tt_' + hex(randint(0, 65536))[2:] + '.txt')
output_file = os.path.join(os.getcwd(), 'stt_' + hex(randint(0, 65536))[2:] + '.txt')
if input_variables is None:
input_variables = [f"x{i}" for i in range(num_of_bits)]
else:
if len(input_variables) != num_of_bits:
raise ValueError("The length of input variables must be equal to the length of the bit vectors.")
SboxAnalyzer._write_truth_table(filename=input_file,
boolean_function=boolean_function,
input_output_variables=input_variables)
print("Generateing and simplifying the MILP/SAT constraints ...")
starting_time = time.time()
SboxAnalyzer.simplify_by_espresso(input_file=input_file,
output_file=output_file,
mode=mode)
elapsed_time = time.time() - starting_time
print("Time used to simplify the constraints: {:.2f} seconds".format(elapsed_time))
sat_clauses, milp_constraints = SboxAnalyzer._parse_the_output_of_espresso(filename=output_file,
alphabet=input_variables)
print("Number of constraints: {}".format(len(milp_constraints)))
print("Variables: {}; msb: {}".format("||".join(input_variables), input_variables[0]))
os.remove(input_file)
os.remove(output_file)
return (sat_clauses, milp_constraints)
###############################################################################################################
###############################################################################################################
###############################################################################################################
# ____ _ __ __ _ _ _ _ _ _ ____ _
# | _ \ (_) / _| / _| ___ _ __ ___ _ __ | |_ (_) __ _ | | / \ _ __ __ _ | | _ _ ___ (_) ___ | _ \ __ _ _ __ | |_
# | | | || || |_ | |_ / _ \| '__|/ _ \| '_ \ | __|| | / _` || | / _ \ | '_ \ / _` || || | | |/ __|| |/ __| | |_) |/ _` || '__|| __|
# | |_| || || _|| _|| __/| | | __/| | | || |_ | || (_| || | / ___ \ | | | || (_| || || |_| |\__ \| |\__ \ | __/| (_| || | | |_
# |____/ |_||_| |_| \___||_| \___||_| |_| \__||_| \__,_||_| /_/ \_\|_| |_| \__,_||_| \__, ||___/|_||___/ |_| \__,_||_| \__|
# |___/
# Differential Analysis
###############################################################################################################
def _compute_data_for_differential_analysis(self):
"""
Compute the data required for differential analysis
"""
self.ddt = self.difference_distribution_table()
self._diff_spectrum = set([self.ddt[i][j] for i in range(2**self.input_size()) for j in range(2**self.output_size())]) - {0, 2**self.input_size()}
self._diff_spectrum = sorted(list(self._diff_spectrum))
self._len_diff_spectrum = len(self._diff_spectrum)
self._diff_weights = [abs(float(log(d/(2**self.input_size()), 2))) for d in self._diff_spectrum]
if len(self._diff_spectrum) > 0:
self._max_diff_weights = int(max(self._diff_weights))
else:
self._max_diff_weights = 0
self._data_required_for_differential_analysis = "Data for differential analysis are computed and stored in memory."
def get_differential_spectrum(self):
"""
Return the differential spectrum
"""
if self._data_required_for_differential_analysis is None:
self._compute_data_for_differential_analysis()
return self._diff_spectrum
def get_star_ddt(self):
"""
Generate the *-DDT (or 0/1 DDT)
Star DDT is a 2^m*2^n binary array describing the possibility of differential transitions through the S-box
"""
if self._data_required_for_differential_analysis is None:
self._compute_data_for_differential_analysis()
star_ddt = [[0 for i in range(2**self.output_size())] for j in range(2**self.input_size())]
for dx in range(2**self.input_size()):
for dy in range(2**self.output_size()):
if self.ddt[dx][dy] != 0:
star_ddt[dx][dy] = 1 #reverse ^ 1
else:
star_ddt[dx][dy] = 0 #reverse
return star_ddt
def _star_ddt_to_boolean_function(self, reverse=1, inverse=0):
"""
Convert the star-DDT into a Boolean function
"""
self.star_ddt = self.get_star_ddt()
boolean_func = dict()
for dx in range(2**self.input_size()):
x = tuple(map(int, list(bin(dx)[2:].zfill(self.input_size()))))
for dy in range(2**self.output_size()):
y = tuple(map(int, list(bin(dy)[2:].zfill(self.output_size()))))
key = x + y
boolean_func[key] = self.star_ddt[dx][dy] ^ reverse ^ inverse
return boolean_func
def _ddt_to_boolean_function(self, reverse=1):
"""
Convert the DDT into a Boolean function
To encode the probabilities, we define as many new binary variables as the
number of different (non-zero and non-one) probabilities in DDT and
then encode the whole of DDT as a Boolean function.
Let dx, and dy denote the input and output differences, respectively.
Assuming that the DDT of S-box includes for example three (non-zero and non-one) elements:
e0, e1, and e2, we define three new binary variables p0, p1, and p2 and then
encode the DDT as a Boolean function f such that f(Bin(dx) || Bin(dy) || p0 || p1 || p2) = 1
if and only if:
DDT[dx][dy] = e0 and (p0, p1, p2) = (1, 0, 0),
or DDT[dx][dy] = e1 and (p0, p1, p2) = (0, 1, 0),
or DDT[dx][dy] = e2 and (p0, p1, p2) = (0, 0, 1),
or dx = dy = 0 and (p0, p1, p2) = (0, 0, 0),
otherwise, f(Bin(dx) || Bin(dy) || p0 || p1 || p2) = 0.
If reverse = True, then we compute the complement of the derived Boolean function.
"""
if self._data_required_for_differential_analysis is None:
self._compute_data_for_differential_analysis()
boolean_function = dict()
complexity = self.input_size() + self.output_size()
for dx in range(2**self.input_size()):
x = tuple(map(int, list(bin(dx)[2:].zfill(self.input_size()))))
for dy in range(2**self.output_size()):
y = tuple(map(int, list(bin(dy)[2:].zfill(self.output_size()))))
# Specifying 0 points is not necessary at the input of ESPRESSO
if self.ddt[dx][dy] in self._diff_spectrum:
p = tuple([int(i == self.ddt[dx][dy]) for i in self._diff_spectrum])
key = x + y + p
boolean_function[key] = 1
elif self.ddt[dx][dy] == 2**self.input_size():
key = x + y + tuple([0]*self._len_diff_spectrum)
boolean_function[key] = 1
if reverse == 1:
complexity = self.input_size() + self.output_size() + self._len_diff_spectrum
for dx in range(2**complexity):
x = tuple(map(int, list(bin(dx)[2:].zfill(complexity))))
boolean_function[x] = boolean_function.get(x, 0) ^ 1
return boolean_function
def _ddt_to_cryptosmt_compatible_boolean_function(self, reverse=1):
"""
Encode the DDT as a Boolean function in SAT/SMT-compatible form
All transition's weights should be integers in this case.
To encode the DDT/LAT of S-box in this method we define the auxiliary binary variables p0, p1, ..., pn
such that p0 + ... + pn is equal to the weight of the corresponding transition.
For example, we encode the DDT of a 4-uniform S-box with an 11-bit Boolean function f(x||y||p),
where x and y are the 4-bit input and output differences and p = (p0, p1, p2) such that:
f(x||y||p) = 0 if DDT[x, y] = 0
f(x||y||p) = 1 if DDT[x, y] = 2^(-3) and p = (1, 1, 1)
f(x||y||p) = 0 if DDT[x, y] = 2^(-3) and p != (1, 1, 1)
f(x||y||p) = 1 if DDT[x, y] = 2^(-2) and p = (0, 1, 1)
f(x||y||p) = 0 if DDT[x, y] = 2^(-2) and p != (0, 1, 1)
f(x||y||p) = 1 if DDT[x, y] = 1 and p = (0, 0, 0)
f(x||y||p) = 0 if DDT[x, y] = 1 and p != (0, 0, 0)
This method is suitable for encoding the DDT of an S-box in CryptoSMT.
"""
if self._data_required_for_differential_analysis is None:
self._compute_data_for_differential_analysis()
if any([i != int(i) for i in self._diff_weights]):
raise ValueError("All transition's weights should be integers")
boolean_function = dict()
complexity = self.input_size() + self.output_size()
for dx in range(2**self.input_size()):
x = tuple(map(int, list(bin(dx)[2:].zfill(self.input_size()))))
for dy in range(2**self.output_size()):
y = tuple(map(int, list(bin(dy)[2:].zfill(self.output_size()))))
# Specifying 0 points is not necessary at the input of ESPRESSO
if self.ddt[dx][dy] != 0:
w = int(abs(float(log(self.ddt[dx][dy]/(2**self.input_size()), 2))))
p = tuple([0]*(self._max_diff_weights - w) + [1]*w)
key = x + y + p
boolean_function[key] = 1
if reverse == 1:
complexity = self.input_size() + self.output_size() + self._len_diff_spectrum
for dx in range(2**complexity):
x = tuple(map(int, list(bin(dx)[2:].zfill(complexity))))
boolean_function[x] = boolean_function.get(x, 0) ^ 1
return boolean_function
def _pddt_to_booleanfunction(self, p, reverse=1):
"""
Convert the p-DDT into a Boolean function
"""
if self._data_required_for_differential_analysis is None:
self._compute_data_for_differential_analysis()
boolean_function = dict()
for dx in range(2**self.input_size()):
x = tuple(map(int, list(bin(dx)[2:].zfill(self.input_size()))))
for dy in range(2**self.output_size()):
y = tuple(map(int, list(bin(dy)[2:].zfill(self.output_size()))))
# Specifying 0 points is not necessary at the input of ESPRESSO
key = x + y
if self.ddt[dx][dy] == p:
boolean_function[key] = reverse ^ 1
else:
boolean_function[key] = reverse
return boolean_function
def minimized_diff_constraints(self, mode=6, subtable=None, cryptosmt_compatible=False, input_variables=None, output_variables=None):
"""
This method takes a given Boolean function and records its truth table in a file,
adhering to the ESPRESSO input format. It then invokes ESPRESSO to obtain a minimized
representation of the function. Following that, it interprets ESPRESSO's output and
converts the simplified representation into the language recognized by MILP and SAT solvers.
"""
if self._data_required_for_differential_analysis is None:
self._compute_data_for_differential_analysis()
valid_values_for_subtable = ["star", "star_inverse", None] + list(self._diff_spectrum)
if subtable not in valid_values_for_subtable:
raise ValueError("Invalid value for subtable! subtable must be in {0}.".format(list(map(str, valid_values_for_subtable))))
self.cryptosmt_compatible = cryptosmt_compatible
self.ddt_subtable = subtable
if mode in [1, 3, 5, 6, 7]:
reverse = 0
else:
reverse = 1
if input_variables is None:
input_variables = [f"a{i}" for i in range(self.input_size())]
else:
if len(input_variables) != self.input_size():
raise ValueError("The length of input variables must be equal to the number of input variables.")
if output_variables is None:
output_variables = [f"b{i}" for i in range(self.output_size())]
else:
if len(output_variables) != self.output_size():
raise ValueError("The length of output variables must be equal to the number of output variables.")
input_output_variables = input_variables + output_variables
self.diff_objective = ""
if subtable == "star":
boolean_function = self._star_ddt_to_boolean_function(reverse=reverse)
elif subtable == "star_inverse":
boolean_function = self._star_ddt_to_boolean_function(reverse=reverse, inverse=1)
elif subtable in self._diff_spectrum:
boolean_function = self._pddt_to_booleanfunction(p=subtable, reverse=reverse)
elif cryptosmt_compatible:
boolean_function = self._ddt_to_cryptosmt_compatible_boolean_function(reverse=reverse)
if self._max_diff_weights == 0:
self.diff_objective = "0"
else:
self.diff_objective = ["p{:d}".format(i) for i in range(self._max_diff_weights)]
self.diff_objective = "\nWeight: {}".format(" + ".join(self.diff_objective))
input_output_variables.extend([f"p{i}" for i in range(self._max_diff_weights)])
else:
boolean_function = self._ddt_to_boolean_function(reverse=reverse)
if self._max_diff_weights == 0:
self.diff_objective = "0"
else:
self.diff_objective = ["{:0.04f} p{:d}".format(self._diff_weights[i], i) for i in range(self._len_diff_spectrum)]
self.diff_objective = "\nWeight: {}".format(" + ".join(self.diff_objective))
input_output_variables.extend([f"p{i}" for i in range(self._len_diff_spectrum)])
self._write_truth_table(filename=self.truth_table_filename,
boolean_function=boolean_function,
input_output_variables=input_output_variables)
starting_time = time.time()
print("Simplifying the MILP/SAT constraints ...")
self.simplify_by_espresso(input_file=self.truth_table_filename, output_file=self.simplified_truth_table_filename, mode=mode)
elapsed_time = time.time() - starting_time
sat_clauses, milp_constraints = self._parse_the_output_of_espresso(filename=self.simplified_truth_table_filename, alphabet=input_output_variables)
os.remove(self.simplified_truth_table_filename)
os.remove(self.truth_table_filename)
print("Time used to simplify the constraints: {:0.02f} seconds".format(elapsed_time))
print("Number of constraints: {0}".format(len(milp_constraints)))
variables_mapping = "Input: {0}; msb: {1}".format("||".join(input_variables), input_variables[0])
variables_mapping += "\nOutput: {0}; msb: {1}".format("||".join(output_variables), output_variables[0])
print("{}".format(variables_mapping + self.diff_objective))
return sat_clauses, milp_constraints
###############################################################################################################
###############################################################################################################
###############################################################################################################
# _ _ _ _ _ ____ _
# | | (_) _ __ ___ __ _ _ __ / \ _ __ __ _ | | _ _ ___ (_) ___ | _ \ __ _ _ __ | |_
# | | | || '_ \ / _ \ / _` || '__| / _ \ | '_ \ / _` || || | | |/ __|| |/ __| | |_) |/ _` || '__|| __|
# | |___ | || | | || __/| (_| || | / ___ \ | | | || (_| || || |_| |\__ \| |\__ \ | __/| (_| || | | |_
# |_____||_||_| |_| \___| \__,_||_| /_/ \_\|_| |_| \__,_||_| \__, ||___/|_||___/ |_| \__,_||_| \__|
# |___/
# Linear Analysis
###############################################################################################################
def _compute_data_for_linear_analysis(self):
"""
Compute the data required for linear analysis
"""
input_size = self.input_size()
output_size = self.output_size()
self.lat = self.linear_approximation_table(scale='correlation')
self._squared_lat = [[x**2 for x in y] for y in self.lat]
self.lat_scaled_by_absolute_correlation = [[2**input_size * lxy for lxy in ly] for ly in self.lat]
self._squared_correlation_spectrum = sorted(list(set(flatten(self._squared_lat)) - {0, 1}))
self._linear_weights = [abs(float(log(x, 2))) for x in self._squared_correlation_spectrum]
self._len_linear_weights = len(self._linear_weights)
if self._len_linear_weights > 0:
self._max_linear_weights = int(max(self._linear_weights))
else:
self._max_linear_weights = 0
self._data_required_for_linear_analysis = "Data for linear analysis are computed and stored in memory."
def get_squared_lat(self):
"""
Return the squared LAT
"""
if self._data_required_for_linear_analysis is None:
self._compute_data_for_linear_analysis()
return self._squared_lat
def get_squared_correlation_spectrum(self):
"""
Return the squared correlation spectrum
"""
if self._data_required_for_linear_analysis is None:
self._compute_data_for_linear_analysis()
return self._squared_correlation_spectrum
def get_star_lat(self):
"""
Generate the *-LAT (or 0/1 LAT)
Star LAT is a 2^m*2^n binary array describing the possibility of linear transitions through the S-box
"""
if self._data_required_for_linear_analysis is None:
self._compute_data_for_linear_analysis()
star_lat = [[0 for i in range(2**self.output_size())] for j in range(2**self.input_size())]
for lx in range(2**self.input_size()):
for ly in range(2**self.output_size()):
if self.lat[lx][ly] != 0:
star_lat[lx][ly] = 1 #reverse ^ 1
else:
star_lat[lx][ly] = 0 #reverse
return star_lat
def _star_lat_to_boolean_function(self, reverse=1):
"""
Convert the star-LAT into a Boolean function
"""
self.star_lat = self.get_star_lat()
boolean_func = dict()
for lx in range(2**self.input_size()):
x = tuple(map(int, list(bin(lx)[2:].zfill(self.input_size()))))
for ly in range(2**self.output_size()):
y = tuple(map(int, list(bin(ly)[2:].zfill(self.output_size()))))
key = x + y
boolean_func[key] = self.star_lat[lx][ly] ^ reverse
boolean_func[tuple([0]*self.input_size() + [0]*self.output_size())] = 1 ^ reverse
return boolean_func
def _sqlat_to_boolean_function(self, reverse=1):
"""
Convert the squared LAT into a Boolean function
To encode the squared correlations, we define as many new binary variables as the
number of different (non-zero and non-one) entries in squared LAT and
then encode the whole of LAT as a Boolean function.
Let lx, and ly denote the input and output masks, respectively.
Assuming that the squared LAT of S-box includes for example three (non-zero and non-one) elements:
e0, e1, and e2, we define three new binary variables p0, p1, and p2 and then
encode the squared LAT as a Boolean function f such that f(Bin(lx) || Bin(ly) || p0 || p1 || p2) = 1
if and only if:
DDT[lx][ly] = e0 and (p0, p1, p2) = (1, 0, 0),
or DDT[lx][ly] = e1 and (p0, p1, p2) = (0, 1, 0),
or DDT[lx][ly] = e2 and (p0, p1, p2) = (0, 0, 1),
or lx = ly = 0 and (p0, p1, p2) = (0, 0, 0),
otherwise, f(Bin(lx) || Bin(ly) || p0 || p1 || p2) = 0.
If reverse = True, then we compute the complement of the derived Boolean function.
"""
if self._data_required_for_linear_analysis is None:
self._compute_data_for_linear_analysis()
boolean_function = dict()
complexity = self.input_size() + self.output_size()
for lx in range(2**self.input_size()):
x = tuple(map(int, list(bin(lx)[2:].zfill(self.input_size()))))
for ly in range(2**self.output_size()):
y = tuple(map(int, list(bin(ly)[2:].zfill(self.output_size()))))
# Specifying 0 points is not necessary at the input of ESPRESSO
if self._squared_lat[lx][ly] in self._squared_correlation_spectrum:
p = tuple([int(i == self._squared_lat[lx][ly]) for i in self._squared_correlation_spectrum])
key = x + y + p
boolean_function[key] = 1
elif self._squared_lat[lx][ly] == 1:
key = x + y + tuple([0]*self._len_linear_weights)
boolean_function[key] = 1
if reverse == 1:
complexity = self.input_size() + self.output_size() + self._len_linear_weights
for lx in range(2**complexity):
x = tuple(map(int, list(bin(lx)[2:].zfill(complexity))))
boolean_function[x] = boolean_function.get(x, 0) ^ 1
return boolean_function
def _psqlat_to_booleanfunction(self, p, reverse=1):
"""
Convert the p-SquaredLAT into a Boolean function
"""
if self._data_required_for_linear_analysis is None:
self._compute_data_for_linear_analysis()
boolean_function = dict()
for lx in range(2**self.input_size()):
x = tuple(map(int, list(bin(lx)[2:].zfill(self.input_size()))))
for ly in range(2**self.output_size()):
y = tuple(map(int, list(bin(ly)[2:].zfill(self.output_size()))))
# Specifying 0 points is not necessary at the input of ESPRESSO
key = x + y
if self._squared_lat[lx][ly] == p:
boolean_function[key] = reverse ^ 1
else:
boolean_function[key] = reverse
return boolean_function
def minimized_linear_constraints(self, mode=6, subtable=None, input_variables=None, output_variables=None):
"""
This method takes a given Boolean function and records its truth table in a file,
adhering to the ESPRESSO input format. It then invokes ESPRESSO to obtain a minimized
representation of the function. Following that, it interprets ESPRESSO's output and
converts the simplified representation into the language recognized by MILP and SAT solvers.
"""
if self._data_required_for_linear_analysis is None:
self._compute_data_for_linear_analysis()
valid_values_for_subtable = ["star", None] + list(self._squared_correlation_spectrum)
if subtable not in valid_values_for_subtable:
raise ValueError("Invalid value for subtable! subtable must be in {0}.".format(list(map(str, valid_values_for_subtable))))
if mode in [1, 3, 5, 6, 7]:
reverse = 0
else:
reverse = 1
if input_variables is None:
input_variables = [f"a{i}" for i in range(self.input_size())]
else:
if len(input_variables) != self.input_size():
raise ValueError("The length of input variables must be equal to the number of input variables.")
if output_variables is None:
output_variables = [f"b{i}" for i in range(self.output_size())]
else:
if len(output_variables) != self.output_size():
raise ValueError("The length of output variables must be equal to the number of output variables.")
input_output_variables = input_variables + output_variables
self.linear_objective = ""
if subtable == "star":
boolean_function = self._star_lat_to_boolean_function(reverse=reverse)
elif subtable in self._squared_correlation_spectrum:
boolean_function = self._psqlat_to_booleanfunction(p=subtable, reverse=reverse)
else:
boolean_function = self._sqlat_to_boolean_function(reverse=reverse)
if self._len_linear_weights != []:
self.linear_objective = ["{:0.04f} p{:d}".format(self._linear_weights[i], i) for i in range(self._len_linear_weights)]
else:
self.linear_objective = "0"
self.linear_objective = "\nWeight: {}".format(" + ".join(self.linear_objective))
input_output_variables += [f"p{i}" for i in range(self._len_linear_weights)]
self._write_truth_table(filename=self.truth_table_filename,
boolean_function=boolean_function,
input_output_variables=input_output_variables)
starting_time = time.time()
print("Simplifying the MILP/SAT constraints ...")
self.simplify_by_espresso(input_file=self.truth_table_filename, output_file=self.simplified_truth_table_filename, mode=mode)
elapsed_time = time.time() - starting_time
sat_clauses, milp_constraints = self._parse_the_output_of_espresso(filename=self.simplified_truth_table_filename, alphabet=input_output_variables)
os.remove(self.simplified_truth_table_filename)
os.remove(self.truth_table_filename)
print("Time used to simplify the constraints: {:0.02f} seconds".format(elapsed_time))
print("Number of constraints: {0}".format(len(milp_constraints)))
variables_mapping = "Input: {0}; msb: {1}".format("||".join(input_variables), input_variables[0])
variables_mapping += "\nOutput: {0}; msb: {1}".format("||".join(output_variables), output_variables[0])
print("{}".format(variables_mapping + self.linear_objective))
return sat_clauses, milp_constraints
###############################################################################################################
###############################################################################################################
###############################################################################################################
# ___ _ _ _ _ _ ____ _
# |_ _| _ __ | |_ ___ __ _ _ __ __ _ | | / \ _ __ __ _ | | _ _ ___ (_) ___ | _ \ __ _ _ __ | |_
# | | | '_ \ | __|/ _ \ / _` || '__|/ _` || | / _ \ | '_ \ / _` || || | | |/ __|| |/ __| | |_) |/ _` || '__|| __|
# | | | | | || |_| __/| (_| || | | (_| || | / ___ \ | | | || (_| || || |_| |\__ \| |\__ \ | __/| (_| || | | |_
# |___||_| |_| \__|\___| \__, ||_| \__,_||_| /_/ \_\|_| |_| \__,_||_| \__, ||___/|_||___/ |_| \__,_||_| \__|
# |___/ |___/
# Integral Analysis
###############################################################################################################
def _compute_data_for_integral_analysis(self):
"""
Compute the data required for integral analysis
"""
# compute monomial prediction table
self.mpt = self.monomial_prediction_table()
def _mpt_to_boolean_function(self, reverse=1):
"""
Convert the star-LAT into a Boolean function
"""
if self._data_required_for_integral_analysis is None:
self._compute_data_for_integral_analysis()
boolean_func = dict()
for mx in range(2**self.input_size()):
x = tuple(map(int, list(bin(mx)[2:].zfill(self.input_size()))))
for my in range(2**self.output_size()):
y = tuple(map(int, list(bin(my)[2:].zfill(self.output_size()))))
key = x + y
boolean_func[key] = self.mpt[mx][my] ^ reverse
boolean_func[tuple([0]*self.input_size() + [0]*self.output_size())] = 1 ^ reverse
return boolean_func
def minimized_integral_constraints(self, mode=6, input_variables=None, output_variables=None):
"""
This method takes a given Boolean function and records its truth table in a file,
adhering to the ESPRESSO input format. It then invokes ESPRESSO to obtain a minimized
representation of the function. Following that, it interprets ESPRESSO's output and
converts the simplified representation into the language recognized by MILP and SAT solvers.
"""
if self._data_required_for_integral_analysis is None:
self._compute_data_for_integral_analysis()
if mode in [1, 3, 5, 6, 7]:
reverse = 0
else:
reverse = 1
if input_variables is None:
input_variables = [f"a{i}" for i in range(self.input_size())]
else:
if len(input_variables) != self.input_size():
raise ValueError("The length of input variables must be equal to the number of input variables.")
if output_variables is None:
output_variables = [f"b{i}" for i in range(self.output_size())]
else:
if len(output_variables) != self.output_size():
raise ValueError("The length of output variables must be equal to the number of output variables.")
self.integral_objective = ""
input_output_variables = input_variables + output_variables
boolean_function = self._mpt_to_boolean_function(reverse=reverse)
self._write_truth_table(filename=self.truth_table_filename,
boolean_function=boolean_function,
input_output_variables=input_output_variables)
starting_time = time.time()
print("Simplifying the MILP/SAT constraints ...")
self.simplify_by_espresso(input_file=self.truth_table_filename, output_file=self.simplified_truth_table_filename, mode=mode)
elapsed_time = time.time() - starting_time
sat_clauses, milp_constraints = self._parse_the_output_of_espresso(filename=self.simplified_truth_table_filename, alphabet=input_output_variables)
os.remove(self.simplified_truth_table_filename)
os.remove(self.truth_table_filename)
print("Time used to simplify the constraints: {:0.02f} seconds".format(elapsed_time))
print("Number of constraints: {0}".format(len(milp_constraints)))
variables_mapping = "Input: {0}; msb: {1}".format("||".join(input_variables), input_variables[0])
variables_mapping += "\nOutput: {0}; msb: {1}".format("||".join(output_variables), output_variables[0])
print("{}".format(variables_mapping + self.integral_objective))
return sat_clauses, milp_constraints
###############################################################################################################
###############################################################################################################
###############################################################################################################
# ____ _ _ _ _ _ ____ _ _
# | _ \ ___ | |_ ___ _ __ _ __ ___ (_) _ __ (_) ___ | |_ (_) ___ | __ ) ___ | |__ __ _ __ __(_) ___ _ __
# | | | | / _ \| __|/ _ \| '__|| '_ ` _ \ | || '_ \ | |/ __|| __|| | / __| | _ \ / _ \| '_ \ / _` |\ \ / /| | / _ \ | '__|
# | |_| || __/| |_| __/| | | | | | | || || | | || |\__ \| |_ | || (__ | |_) || __/| | | || (_| | \ V / | || (_) || |
# |____/ \___| \__|\___||_| |_| |_| |_||_||_| |_||_||___/ \__||_| \___| |____/ \___||_| |_| \__,_| \_/ |_| \___/ |_|
#
# Deteministic Behavior
###############################################################################################################
def truncated_to_binvectors(self, input_vector):
"""
Converts a truncated vector to a list of binary vectors
"""