forked from data61/MP-SPDZ
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathtypes.py
5230 lines (4410 loc) · 172 KB
/
types.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
"""
This module defines all types availabe in high-level programs. These
include basic types such as secret integers or floating-point numbers
and container types. A single instance of the former uses one or more
so-called registers in the virtual machine while the latter use the
so-called memory. For every register type, there is a corresponding
dedicated memory.
Registers are used for computation, allocated on an ongoing basis,
and thread-specific. The memory is allocated statically and shared
between threads. This means that memory-based types such as
:py:class:`Array` can be used to transfer information between threads.
Note that creating memory-based types outside the main thread is not
supported.
If viewing this documentation in processed form, many function signatures
appear generic because of the use of decorators. See the source code for the
correct signature.
Basic types
-----------
Basic types contain many special methods such as :py:func:`__add__`. This is
used for operator overloading in Python. In some operations such as
secure comparison, the secure computation protocols allows for more
parameters than just the operands which influence the performance. In
this case, we provide an alias for better code readability. For
example, :meth:`sint.greater_than` is an alias of
:py:meth:`sint.__gt__`. When using operator overloading, the
parameters default to the globally defined ones.
Methods of basic types generally return instances of the respective type.
Note that the data model of Python operates with reverse operators
such as :py:func:`__radd__`. This means that if for the usual operator of the
first operand does not support the second operand, the reverse
operator of the second operand is used. For example,
:py:meth:`_clear.__sub__` does not support secret values as second
operand but :py:meth:`_secret.__rsub__` does support clear values, so
``cint(3) - sint(2)`` will result in a secret integer of value 1.
.. autosummary::
:nosignatures:
sint
cint
regint
sfix
cfix
sfloat
sgf2n
cgf2n
Container types
---------------
.. autosummary::
:nosignatures:
MemValue
Array
Matrix
MultiArray
"""
from Compiler.program import Tape
from Compiler.exceptions import *
from Compiler.instructions import *
from Compiler.instructions_base import *
from .floatingpoint import two_power
from . import comparison, floatingpoint
import math
from . import util
from . import instructions
from .util import is_zero, is_one
import operator
from functools import reduce
import re
class ClientMessageType:
""" Enum to define type of message sent to external client. Each may be array of length n."""
# No client message type to be sent, for backwards compatibility - virtual machine relies on this value
NoType = 0
# 3 x sint x n
TripleShares = 1
# 1 x cint x n
ClearModpInt = 2
# 1 x regint x n
Int32 = 3
# 1 x cint (fixed point left shifted by precision) x n
ClearModpFix = 4
class MPCThread(object):
def __init__(self, target, name, args = [], runtime_arg = 0,
single_thread = False):
""" Create a thread from a callable object. """
if not callable(target):
raise CompilerError('Target %s for thread %s is not callable' % (target,name))
self.name = name
self.tape = Tape(program.name + '-' + name, program)
self.target = target
self.args = args
self.runtime_arg = runtime_arg
self.running = 0
self.tape_handle = program.new_tape(target, args, name,
single_thread=single_thread)
self.run_handles = []
def start(self, runtime_arg = None):
self.running += 1
self.run_handles.append(program.run_tape(self.tape_handle, \
runtime_arg or self.runtime_arg))
def join(self):
if not self.running:
raise CompilerError('Thread %s is not running' % self.name)
self.running -= 1
program.join_tape(self.run_handles.pop(0))
def copy_doc(a, b):
try:
a.__doc__ = b.__doc__
except:
pass
def no_doc(operation):
def wrapper(*args, **kwargs):
return operation(*args, **kwargs)
return wrapper
def vectorize(operation):
def vectorized_operation(self, *args, **kwargs):
if len(args):
from .GC.types import bits
if (isinstance(args[0], Tape.Register) or isinstance(args[0], sfloat)) \
and not isinstance(args[0], bits) \
and args[0].size != self.size:
raise CompilerError('Different vector sizes of operands: %d/%d'
% (self.size, args[0].size))
set_global_vector_size(self.size)
res = operation(self, *args, **kwargs)
reset_global_vector_size()
return res
copy_doc(vectorized_operation, operation)
return vectorized_operation
def vectorize_max(operation):
def vectorized_operation(self, *args, **kwargs):
size = self.size
for arg in args:
try:
size = max(size, arg.size)
except AttributeError:
pass
set_global_vector_size(size)
res = operation(self, *args, **kwargs)
reset_global_vector_size()
return res
copy_doc(vectorized_operation, operation)
return vectorized_operation
def vectorized_classmethod(function):
def vectorized_function(cls, *args, **kwargs):
size = None
if 'size' in kwargs:
size = kwargs.pop('size')
if size:
set_global_vector_size(size)
res = function(cls, *args, **kwargs)
reset_global_vector_size()
else:
res = function(cls, *args, **kwargs)
return res
copy_doc(vectorized_function, function)
return classmethod(vectorized_function)
def vectorize_init(function):
def vectorized_init(*args, **kwargs):
size = None
if len(args) > 1 and (isinstance(args[1], Tape.Register) or \
isinstance(args[1], sfloat)):
size = args[1].size
if 'size' in kwargs and kwargs['size'] is not None \
and kwargs['size'] != size:
raise CompilerError('Mismatch in vector size')
if 'size' in kwargs and kwargs['size']:
size = kwargs['size']
if size is not None:
set_global_vector_size(size)
res = function(*args, **kwargs)
reset_global_vector_size()
else:
res = function(*args, **kwargs)
return res
copy_doc(vectorized_init, function)
return vectorized_init
def set_instruction_type(operation):
def instruction_typed_operation(self, *args, **kwargs):
set_global_instruction_type(self.instruction_type)
res = operation(self, *args, **kwargs)
reset_global_instruction_type()
return res
copy_doc(instruction_typed_operation, operation)
return instruction_typed_operation
def read_mem_value(operation):
def read_mem_operation(self, *args, **kwargs):
if len(args) > 0 and isinstance(args[0], MemValue):
args = (args[0].read(),) + args[1:]
return operation(self, *args, **kwargs)
copy_doc(read_mem_operation, operation)
return read_mem_operation
def inputmixed(*args):
# helper to cover both cases
if isinstance(args[-1], int):
instructions.inputmixed(*args)
else:
instructions.inputmixedreg(*(args[:-1] + (regint.conv(args[-1]),)))
class _number(object):
""" Number functionality. """
def square(self):
""" Square. """
return self * self
def __add__(self, other):
""" Optimized addition.
:param other: any compatible type """
if is_zero(other):
return self
else:
return self.add(other)
def __mul__(self, other):
""" Optimized multiplication.
:param other: any compatible type """
if is_zero(other):
return 0
elif is_one(other):
return self
else:
return self.mul(other)
__radd__ = __add__
__rmul__ = __mul__
@vectorize
def __pow__(self, exp):
""" Exponentation through square-and-multiply.
:param exp: compile-time (int) """
if isinstance(exp, int) and exp >= 0:
if exp == 0:
return self.__class__(1)
exp = bin(exp)[3:]
res = self
for i in exp:
res = res.square()
if i == '1':
res *= self
return res
else:
return NotImplemented
def mul_no_reduce(self, other, res_params=None):
return self * other
def reduce_after_mul(self):
return self
def pow2(self, bit_length=None, security=None):
return 2**self
def min(self, other):
""" Minimum.
:param other: any compatible type """
return (self < other).if_else(self, other)
def max(self, other):
""" Maximum.
:param other: any compatible type """
return (self < other).if_else(other, self)
@classmethod
def dot_product(cls, a, b):
from Compiler.library import for_range_opt_multithread
res = MemValue(cls(0))
l = min(len(a), len(b))
xx = [a, b]
for i, x in enumerate((a, b)):
if not isinstance(x, Array):
xx[i] = Array(l, cls)
xx[i].assign(x)
aa, bb = xx
@for_range_opt_multithread(None, l)
def _(i):
res.iadd(res.value_type.conv(aa[i] * bb[i]))
return res.read()
def __abs__(self):
""" Absolute value. """
return (self < 0).if_else(-self, self)
@staticmethod
def popcnt_bits(bits):
return sum(bits)
class _int(object):
""" Integer functionality. """
@staticmethod
def bit_adder(*args, **kwargs):
return intbitint.bit_adder(*args, **kwargs)
@staticmethod
def ripple_carry_adder(*args, **kwargs):
return intbitint.ripple_carry_adder(*args, **kwargs)
def if_else(self, a, b):
""" MUX on bit in arithmetic circuits.
:param a/b: any type supporting the necessary operations
:return: a if :py:obj:`self` is 1, b if :py:obj:`self` is 0, undefined otherwise
:rtype: depending on operands, secret if any of them is """
if hasattr(a, 'for_mux'):
f, a, b = a.for_mux(b)
else:
f = lambda x: x
return f(self * (a - b) + b)
def cond_swap(self, a, b):
""" Swapping in arithmetic circuits.
:param a/b: any type supporting the necessary operations
:return: ``(a, b)`` if :py:obj:`self` is 0, ``(b, a)`` if :py:obj:`self` is 1, and undefined otherwise
:rtype: depending on operands, secret if any of them is """
prod = self * (a - b)
return a - prod, b + prod
def bit_xor(self, other):
""" XOR in arithmetic circuits.
:param self/other: 0 or 1 (any compatible type)
:return: type depends on inputs (secret if any of them is) """
return self + other - 2 * self * other
def bit_and(self, other):
""" AND in arithmetic circuits.
:param self/other: 0 or 1 (any compatible type)
:rtype: depending on inputs (secret if any of them is) """
return self * other
def half_adder(self, other):
""" Half adder in arithmetic circuits.
:param self/other: 0 or 1 (any compatible type)
:return: binary sum, carry
:rtype: depending on inputs, secret if any is """
carry = self * other
return self + other - 2 * carry, carry
class _bit(object):
""" Binary functionality. """
def bit_xor(self, other):
""" XOR in binary circuits.
:param self/other: 0 or 1 (any compatible type)
:rtype: depending on inputs (secret if any of them is) """
return self ^ other
def bit_and(self, other):
""" AND in binary circuits.
:param self/other: 0 or 1 (any compatible type)
:rtype: depending on inputs (secret if any of them is) """
return self & other
def half_adder(self, other):
""" Half adder in binary circuits.
:param self/other: 0 or 1 (any compatible type)
:return: binary sum, carry
:rtype: depending on inputs (secret if any of them is) """
return self ^ other, self & other
class _gf2n(_bit):
""" GF(2^n) functionality. """
def if_else(self, a, b):
""" MUX in GF(2^n) circuits. Similar to :py:meth:`_int.if_else`. """
return b ^ self * self.hard_conv(a ^ b)
def cond_swap(self, a, b, t=None):
""" Swapping in GF(2^n). Similar to :py:meth:`_int.if_else`. """
prod = self * self.hard_conv(a ^ b)
res = a ^ prod, b ^ prod
if t is None:
return res
else:
return tuple(t.conv(r) for r in res)
def bit_xor(self, other):
""" XOR in GF(2^n) circuits.
:param self/other: 0 or 1 (any compatible type)
:rtype: depending on inputs (secret if any of them is) """
return self ^ other
class _structure(object):
""" Interface for type-dependent container types. """
MemValue = classmethod(lambda cls, value: MemValue(cls.conv(value)))
""" Type-dependent memory value. """
@classmethod
def Array(cls, size, *args, **kwargs):
""" Type-dependent array. Example:
.. code::
a = sint.Array(10)
"""
return Array(size, cls, *args, **kwargs)
@classmethod
def Matrix(cls, rows, columns, *args, **kwargs):
""" Type-dependent matrix. Example:
.. code::
a = sint.Matrix(10, 10)
"""
return Matrix(rows, columns, cls, *args, **kwargs)
@classmethod
def row_matrix_mul(cls, row, matrix, res_params=None):
return sum(row[k].mul_no_reduce(matrix[k].get_vector(),
res_params) \
for k in range(len(row))).reduce_after_mul()
class _vec(object):
pass
class _register(Tape.Register, _number, _structure):
@staticmethod
def n_elements():
return 1
@vectorized_classmethod
def conv(cls, val):
if isinstance(val, MemValue):
val = val.read()
if isinstance(val, cls):
return val
elif not isinstance(val, (_register, _vec)):
try:
return type(val)(cls.conv(v) for v in val)
except TypeError:
pass
except CompilerError:
pass
return cls(val)
@vectorized_classmethod
@read_mem_value
def hard_conv(cls, val):
if type(val) == cls:
return val
elif not isinstance(val, _register):
try:
return val.hard_conv_me(cls)
except AttributeError:
try:
return type(val)(cls.hard_conv(v) for v in val)
except TypeError:
pass
return cls(val)
@vectorized_classmethod
@set_instruction_type
def _load_mem(cls, address, direct_inst, indirect_inst):
if isinstance(address, _register):
if address.size > 1:
size = address.size
else:
size = get_global_vector_size()
res = cls(size=size)
indirect_inst(res, cls._expand_address(address,
get_global_vector_size()))
else:
res = cls()
direct_inst(res, address)
return res
@staticmethod
def _expand_address(address, size):
address = regint.conv(address)
if size > 1 and address.size == 1:
res = regint(size=size)
incint(res, address, 1)
return res
else:
return address
@set_instruction_type
def _store_in_mem(self, address, direct_inst, indirect_inst):
if isinstance(address, _register):
indirect_inst(self, self._expand_address(address, self.size))
else:
direct_inst(self, address)
@classmethod
def prep_res(cls, other):
return cls()
@staticmethod
def bit_compose(bits):
""" Compose value from bits.
:param bits: iterable of any type implementing left shift """
return sum(b << i for i,b in enumerate(bits))
@classmethod
def malloc(cls, size, creator_tape=None):
""" Allocate memory (statically).
:param size: compile-time (int) """
return program.malloc(size, cls, creator_tape=creator_tape)
@classmethod
def free(cls, addr):
program.free(addr, cls.reg_type)
@set_instruction_type
def __init__(self, reg_type, val, size):
if isinstance(val, (tuple, list)):
size = len(val)
super(_register, self).__init__(reg_type, program.curr_tape, size=size)
if isinstance(val, int):
self.load_int(val)
elif isinstance(val, (tuple, list)):
for i, x in enumerate(val):
if util.is_constant(x):
self[i].load_int(x)
else:
self[i].load_other(x)
elif val is not None:
self.load_other(val)
def _new_by_number(self, i, size=1):
res = type(self)(size=size)
res.i = i
res.program = self.program
return res
def sizeof(self):
return self.size
def extend(self, n):
return self
def expand_to_vector(self, size=None):
if size is None:
size = get_global_vector_size()
if self.size == size:
return self
assert self.size == 1
res = type(self)(size=size)
for i in range(size):
movs(res[i], self)
return res
class _clear(_register):
""" Clear domain-dependent type. """
__slots__ = []
mov = staticmethod(movc)
@vectorized_classmethod
@set_instruction_type
def protect_memory(cls, start, end):
program.curr_tape.start_new_basicblock(name='protect-memory')
protectmemc(regint(start), regint(end))
@set_instruction_type
@vectorize
def load_other(self, val):
if isinstance(val, type(self)):
movc(self, val)
else:
self.convert_from(val)
@vectorize
@read_mem_value
def convert_from(self, val):
if not isinstance(val, regint):
val = regint(val)
convint(self, val)
@set_instruction_type
@vectorize
def print_reg(self, comment=''):
print_reg(self, comment)
@set_instruction_type
@vectorize
def print_reg_plain(self):
""" Output. """
print_reg_plain(self)
@set_instruction_type
@vectorize
def raw_output(self):
raw_output(self)
@set_instruction_type
@read_mem_value
@vectorize
def clear_op(self, other, c_inst, ci_inst, reverse=False):
cls = self.__class__
res = self.prep_res(other)
if isinstance(other, cls):
c_inst(res, self, other)
elif isinstance(other, int):
if self.in_immediate_range(other):
ci_inst(res, self, other)
else:
if reverse:
c_inst(res, cls(other), self)
else:
c_inst(res, self, cls(other))
else:
return NotImplemented
return res
@set_instruction_type
@read_mem_value
@vectorize
def coerce_op(self, other, inst, reverse=False):
cls = self.__class__
res = cls()
if isinstance(other, int):
other = cls(other)
elif not isinstance(other, cls):
return NotImplemented
if reverse:
inst(res, other, self)
else:
inst(res, self, other)
return res
def add(self, other):
""" Addition of public values.
:param other: convertible type (at least same as :py:obj:`self` and regint/int) """
return self.clear_op(other, addc, addci)
def mul(self, other):
""" Multiplication of public values.
:param other: convertible type (at least same as :py:obj:`self` and regint/int) """
return self.clear_op(other, mulc, mulci)
def __sub__(self, other):
""" Subtraction of public values.
:param other: convertible type (at least same as :py:obj:`self` and regint/int) """
return self.clear_op(other, subc, subci)
def __rsub__(self, other):
return self.clear_op(other, subc, subcfi, True)
__rsub__.__doc__ = __sub__.__doc__
def __truediv__(self, other):
""" Field division of public values. Not available for
computation modulo a power of two.
:param other: convertible type (at least same as :py:obj:`self` and regint/int) """
return self.clear_op(other, divc, divci)
def __rtruediv__(self, other):
return self.coerce_op(other, divc, True)
__rtruediv__.__doc__ = __truediv__.__doc__
def __eq__(self, other):
""" Equality check of public values.
:param other: convertible type (at least same as :py:obj:`self` and regint/int)
:return: 0/1 (regint) """
if isinstance(other, (_clear,int)):
return regint(self) == other
else:
return NotImplemented
def __ne__(self, other):
return 1 - (self == other)
__ne__.__doc__ = __eq__.__doc__
def __and__(self, other):
""" Bit-wise AND of public values.
:param other: convertible type (at least same as :py:obj:`self` and regint/int) """
return self.clear_op(other, andc, andci)
def __xor__(self, other):
""" Bit-wise XOR of public values.
:param other: convertible type (at least same as :py:obj:`self` and regint/int) """
return self.clear_op(other, xorc, xorci)
def __or__(self, other):
""" Bit-wise OR of public values.
:param other: convertible type (at least same as :py:obj:`self` and regint/int) """
return self.clear_op(other, orc, orci)
__rand__ = __and__
__rxor__ = __xor__
__ror__ = __or__
def reveal(self):
""" Identity. """
return self
class cint(_clear, _int):
"""
Clear integer in same domain as secure computation
(depends on protocol).
"""
__slots__ = []
instruction_type = 'modp'
reg_type = 'c'
@vectorized_classmethod
def read_from_socket(cls, client_id, n=1):
""" Read a list of clear values from socket. """
res = [cls() for i in range(n)]
readsocketc(client_id, *res)
if n == 1:
return res[0]
else:
return res
@vectorize
def write_to_socket(self, client_id, message_type=ClientMessageType.NoType):
writesocketc(client_id, message_type, self)
@vectorized_classmethod
def write_to_socket(self, client_id, values, message_type=ClientMessageType.NoType):
""" Send a list of clear values to socket """
writesocketc(client_id, message_type, *values)
@vectorized_classmethod
def load_mem(cls, address, mem_type=None):
""" Load from memory by public address. """
return cls._load_mem(address, ldmc, ldmci)
def store_in_mem(self, address):
""" Store in memory by public address. """
self._store_in_mem(address, stmc, stmci)
@staticmethod
def in_immediate_range(value):
return value < 2**31 and value >= -2**31
def __init__(self, val=None, size=None):
"""
:param val: initialization (cint/regint/int/cgf2n or list thereof)
:param size: vector size (int), defaults to 1 or size of list
"""
super(cint, self).__init__('c', val=val, size=size)
@vectorize
def load_int(self, val):
if val:
# +1 for sign
bit_length = 1 + int(math.ceil(math.log(abs(val))))
if program.options.ring:
assert(bit_length <= int(program.options.ring))
elif program.options.field:
program.curr_tape.require_bit_length(bit_length)
if self.in_immediate_range(val):
ldi(self, val)
else:
max = 2**31 - 1
sign = abs(val) // val
val = abs(val)
chunks = []
while val:
mod = val % max
val = (val - mod) // max
chunks.append(mod)
sum = cint(sign * chunks.pop())
for i,chunk in enumerate(reversed(chunks)):
sum *= max
if i == len(chunks) - 1:
addci(self, sum, sign * chunk)
elif chunk:
sum += sign * chunk
@vectorize
def to_regint(self, n_bits=64, dest=None):
""" Convert to regint.
:param n_bits: bit length (int)
:return: regint """
dest = regint() if dest is None else dest
convmodp(dest, self, bitlength=n_bits)
return dest
def __mod__(self, other):
""" Clear modulo.
:param other: cint/regint/int """
return self.clear_op(other, modc, modci)
def __rmod__(self, other):
""" Clear modulo.
:param other: cint/regint/int """
return self.coerce_op(other, modc, True)
def less_than(self, other, bit_length):
""" Clear comparison for particular bit length.
:param other: cint/regint/int
:param bit_length: signed bit length of inputs
:return: 0/1 (regint), undefined if inputs outside range """
if bit_length <= 64:
return self < other
else:
diff = self - other
shifted = diff >> (bit_length - 1)
res = regint(shifted & 1)
return res
def __lt__(self, other):
""" Clear 64-bit comparison.
:param other: cint/regint/int
:return: 0/1 (regint) """
if isinstance(other, (type(self),int)):
return regint(self) < other
else:
return NotImplemented
def __gt__(self, other):
if isinstance(other, (type(self),int)):
return regint(self) > other
else:
return NotImplemented
def __le__(self, other):
return 1 - (self > other)
def __ge__(self, other):
return 1 - (self < other)
for op in __gt__, __le__, __ge__:
op.__doc__ = __lt__.__doc__
del op
@vectorize
def __eq__(self, other):
""" Clear equality test.
:param other: cint/regint/int
:return: 0/1 (regint) """
if not isinstance(other, (_clear, int)):
return NotImplemented
res = 1
remaining = program.bit_length
while remaining > 0:
if isinstance(other, cint):
o = other.to_regint(min(remaining, 64))
else:
o = other % 2 ** 64
res *= (self.to_regint(min(remaining, 64)) == o)
self >>= 64
other >>= 64
remaining -= 64
return res
def __lshift__(self, other):
""" Clear left shift.
:param other: cint/regint/int """
return self.clear_op(other, shlc, shlci)
def __rshift__(self, other):
""" Clear right shift.
:param other: cint/regint/int """
return self.clear_op(other, shrc, shrci)
def __neg__(self):
""" Clear negation. """
return 0 - self
def __abs__(self):
""" Clear absolute. """
return (self >= 0).if_else(self, -self)
@vectorize
def __invert__(self):
""" Clear inversion using global bit length. """
res = cint()
notc(res, self, program.bit_length)
return res
def __rpow__(self, base):
""" Clear power of two.
:param other: 2 """
if base == 2:
return 1 << self
else:
return NotImplemented
@vectorize
def __rlshift__(self, other):
""" Clear shift.
:param other: cint/regint/int """
return cint(other) << self
@vectorize
def __rrshift__(self, other):
""" Clear shift.
:param other: cint/regint/int """
return cint(other) >> self
@read_mem_value
def mod2m(self, other, bit_length=None, signed=None):
""" Clear modulo a power of two.
:param other: cint/regint/int """
return self % 2**other
@read_mem_value
def right_shift(self, other, bit_length=None):
""" Clear shift.
:param other: cint/regint/int """
return self >> other
@read_mem_value
def greater_than(self, other, bit_length=None):
return self > other
@vectorize
def bit_decompose(self, bit_length=None):
""" Clear bit decomposition.
:param bit_length: number of bits (default is global bit length)
:return: list of cint """
if bit_length == 0:
return []
bit_length = bit_length or program.bit_length
return floatingpoint.bits(self, bit_length)
def legendre(self):
""" Clear Legendre symbol computation. """
res = cint()
legendrec(res, self)
return res
def digest(self, num_bytes):
""" Clear hashing (libsodium default). """
res = cint()
digestc(res, self, num_bytes)
return res
def print_if(self, string):
""" Output if value is non-zero.
:param string: Python string """
cond_print_str(self, string)
def output_if(self, cond):
cond_print_plain(cond, self, cint(0))
class cgf2n(_clear, _gf2n):
"""
Clear GF(2^n) value. n is 40 or 128,