-
Notifications
You must be signed in to change notification settings - Fork 358
Expand file tree
/
Copy pathtypes.py
More file actions
7925 lines (6683 loc) · 266 KB
/
types.py
File metadata and controls
7925 lines (6683 loc) · 266 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
"""
This module defines all types available 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
-----------
All basic types can be used as vectors, that is one instance representing
several values, with all operations being executed element-wise. For
example, the following computes ten multiplications of integers input
by party 0 and 1::
sint.get_input_from(0, size=10) * sint.get_input_from(1, size=10)
The following types are available in arithmetic circuits and with
reduced functionality in binary circuits.
.. autosummary::
:nosignatures:
sint
sfix
regint
The following types are only available in arithmetic circuits.
.. autosummary::
:nosignatures:
cint
cfix
sfloat
sgf2n
cgf2n
personal
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, finalize = True):
""" 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.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,
finalize=finalize)
self.tape = program.tapes[self.tape_handle]
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:
if min(args[0].size, self.size) == 1:
size = max(args[0].size, self.size)
self = self.expand_to_vector(size)
args = list(args)
args[0] = args[0].expand_to_vector(size)
else:
raise VectorMismatch('Different vector sizes of operands: %d/%d'
% (self.size, args[0].size))
set_global_vector_size(self.size)
try:
res = operation(self, *args, **kwargs)
finally:
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)
try:
res = operation(self, *args, **kwargs)
finally:
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 is not None:
set_global_vector_size(size)
try:
res = function(cls, *args, **kwargs)
finally:
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], (_register, sfloat, cfix)):
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'] is not None:
size = kwargs['size']
if size is not None:
set_global_vector_size(size)
try:
res = function(*args, **kwargs)
finally:
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)
try:
res = operation(self, *args, **kwargs)
finally:
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 type_comp(operation):
def type_check(self, other, *args, **kwargs):
if not isinstance(other, (type(self), int, regint, self.clear_type)):
return NotImplemented
return operation(self, other, *args, **kwargs)
copy_doc(type_check, operation)
return type_check
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(Tape._no_truth):
""" 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:
try:
return self.mul(other)
except VectorMismatch:
if type(self) != type(other) and 1 in (self.size, other.size):
# try reverse multiplication
return NotImplemented
else:
raise
__radd__ = __add__
__rmul__ = __mul__
@vectorize
def __pow__(self, exp):
""" Exponentation through square-and-multiply.
:param exp: any type allowing bit decomposition """
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
elif isinstance(exp, _int):
bits = exp.bit_decompose()
powers = [self]
while len(powers) < len(bits):
powers.append(powers[-1] ** 2)
multiplicands = [b.if_else(p, 1) for b, p in zip(bits, powers)]
res = util.tree_reduce(operator.mul, multiplicands)
return res
else:
from .mpc_math import pow_fx
return pow_fx(self, exp)
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):
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)
def zero_if_not(self, condition):
return condition * self
def iadd(self, other):
""" Addition assignment. This uses :py:func:`update` internally. """
self.update(self + other)
class _int(Tape._no_truth):
""" Integer functionality. """
@staticmethod
def bit_adder(*args, **kwargs):
""" Binary adder in arithmetic circuits.
:param a: summand (list of 0/1 in compatible type)
:param b: summand (list of 0/1 in compatible type)
:param carry_in: input carry (default 0)
:param get_carry: add final carry to output
:returns: list of 0/1 in relevant type
"""
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::
print_ln('%s', sint(0).if_else(sint(2), sint(3)).reveal())
print_ln('%s', sint(1).if_else(sint(4), sint(5)).reveal())
This will output::
3
4
: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):
""" Single-bit XOR in arithmetic circuits.
:param self/other: 0 or 1 (any compatible type)
:return: type depends on inputs (secret if any of them is) """
if util.is_constant(other):
if other:
return 1 - self
else:
return self
return self + other - 2 * self * other
def bit_or(self, other):
""" Single-bit OR in arithmetic circuits.
:param self/other: 0 or 1 (any compatible type)
:return: type depends on inputs (secret if any of them is) """
if util.is_constant(other):
if other:
return 1
else:
return 0
return self + other - self * other
def bit_and(self, other):
""" Single-bit 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 bit_not(self):
""" Single-bit NOT in arithmetic circuits. """
return 1 - self
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
@staticmethod
def long_one():
return 1
class _bit(Tape._no_truth):
""" 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 bit_or(self, other):
""" OR in binary circuits.
:param self/other: 0 or 1 (any compatible type)
:return: type depends on inputs (secret if any of them is) """
return self ^ other - self & other
def bit_not(self):
""" NOT in binary circuits. """
return ~self
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
def carry_out(self, a, b):
s = a ^ b
return a ^ (s & (self ^ a))
def cond_swap(self, a, b):
prod = self * (a ^ b)
return a ^ prod, b ^ prod
class _gf2n(_bit):
r""" :math:`\mathrm{GF}(2^n)` functionality. """
def if_else(self, a, b):
r""" MUX in :math:`\mathrm{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):
r""" Swapping in :math:`\mathrm{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):
r""" XOR in :math:`\mathrm{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
def bit_not(self):
return self ^ 1
class _structure(Tape._no_truth):
""" 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 Tensor(cls, shape, **kwargs):
"""
Type-dependent tensor of any dimension::
a = sfix.Tensor([10, 10])
"""
if len(shape) == 1:
return Array(shape[0], cls, **kwargs)
elif len(shape) == 2:
return Matrix(*shape, cls, **kwargs)
else:
return MultiArray(shape, cls, **kwargs)
@classmethod
def row_matrix_mul(cls, row, matrix, res_params=None):
res = type(row[0].mul_no_reduce(
matrix[0][0], res_params=res_params))(0, size=matrix.sizes[1])
@library.for_range_opt(len(row))
def _(k):
res.iadd(row[k].mul_no_reduce(matrix[k].get_vector(), res_params))
return res.reduce_after_mul()
@staticmethod
def mem_size():
return 1
def size_for_mem(self):
return self.size
@classmethod
def arg_type(cls):
if issubclass(cls, _register):
return cls.reg_type
if issubclass(cls, (cfix, sfix)):
return cls.int_type.reg_type
raise CompilerError('type not supported as argument: %s' % cls)
class _secret_structure(_structure):
@classmethod
def input_tensor_from(cls, player, shape):
""" Input tensor secretly from player.
:param player: int/regint/cint
:param shape: tensor shape
"""
res = cls.Tensor(shape)
res.input_from(player)
return res
@classmethod
def input_tensor_from_client(cls, client_id, shape):
""" Input tensor secretly from client.
:param client_id: client identifier (public)
:param shape: tensor shape
"""
res = cls.Tensor(shape)
res.assign_vector(cls.receive_from_client(1, client_id,
size=res.total_size())[0])
return res
@classmethod
def input_tensor_via(cls, player, content=None, shape=None, binary=True,
one_hot=False, skip_input=False, n_bytes=None):
"""
Input tensor-like data via a player. This overwrites the input
file for the relevant player. The following returns an
:py:class:`sint` matrix of dimension 2 by 2::
M = [[1, 2], [3, 4]]
sint.input_tensor_via(0, M)
Make sure to copy ``Player-Data/Input-P<player>-0`` or
``Player-Data/Input-Binary-P<player>-0`` if running
on another host.
:param player: player to input via (int)
:param content: nested Python list or numpy array (binary mode only) or
left out if not available
:param shape: shape if content not given
:param binary: binary mode (bool)
:param one_hot: one-hot encoding (bool)
"""
if program.curr_tape != program.tapes[0]:
raise CompilerError('only available in main thread')
if content is not None:
if isinstance(content, (_vectorizable, Tape.Register)):
raise CompilerError('cannot input data already in the VM')
requested_shape = shape
if binary:
import numpy
content = numpy.array(content)
if issubclass(cls, _fix):
min_k = \
math.ceil(math.log(abs(content).max() or 1, 2)) + cls.f + 1
if cls.k < min_k:
raise CompilerError(
"data outside fixed-point range, "
"use 'sfix.set_precision(%d, %d)'" % (cls.f, min_k))
if binary == 2:
t = numpy.double
else:
t = numpy.single
else:
if n_bytes == 1:
t = numpy.int8
else:
t = numpy.int64
if one_hot:
content = numpy.eye(content.max() + 1)[content]
content = content.astype(t)
f = program.get_binary_input_file(player)
f.write(content.tobytes())
f.flush()
shape = content.shape
else:
shape = []
tmp = content
while True:
try:
shape.append(len(tmp))
tmp = tmp[0]
except:
break
if not program.input_files.get(player, None):
program.input_files[player] = open(
'Player-Data/Input-P%d-0' % player, 'w')
f = program.input_files[player]
def traverse(content, level):
assert len(content) == shape[level]
if level == len(shape) - 1:
for x in content:
f.write(' ')
f.write(str(x))
else:
for x in content:
traverse(x, level + 1)
traverse(content, 0)
f.write('\n')
f.flush()
if requested_shape is not None and \
list(shape) != list(requested_shape):
raise CompilerError('content contradicts shape')
if not skip_input:
res = cls.Tensor(shape)
res.input_from(player, binary=binary, n_bytes=n_bytes)
return res
class _vec(Tape._no_truth):
def link(self, other):
assert len(self.v) == len(other.v)
for x, y in zip(self.v, other.v):
x.link(y)
class _register(Tape.Register, _number, _structure):
@staticmethod
def n_elements():
return 1
@classmethod
def new_vector(cls, size):
return cls(size=size)
def vector_size(self):
return self.size
@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, CompilerError):
pass
return cls(val)
@vectorized_classmethod
@set_instruction_type
@read_mem_value
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
@read_mem_value
@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()
@classmethod
def bit_compose(cls, bits):
""" Compose value from bits.
:param bits: iterable of any type implementing left shift """
return sum(cls.conv(b) << i for i,b in enumerate(bits))
@classmethod
def malloc(cls, size, creator_tape=None, **kwargs):
""" Allocate memory (statically).
:param size: compile-time (int) """
return program.malloc(size, cls, creator_tape=creator_tape, **kwargs)
@classmethod
def free(cls, addr):
program.free(addr, cls.reg_type)
@set_instruction_type
def __init__(self, reg_type, val, size):
from .GC.types import sbits
if isinstance(val, (tuple, list)):
size = len(val)
elif isinstance(val, sbits):
size = val.n
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:
try:
self.load_other(val)
except:
raise CompilerError(
"cannot convert '%s' to '%s'" % (type(val), type(self)))
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
return self._expand_to_vector(size)
def _expand_to_vector(self, size):
res = type(self)(size=size)
for i in range(size):
self.mov(res[i], self)
return res
def copy_from_part(self, source, base, size):
set_global_vector_size(size)
self.mov(self, source.get_vector(base, size))
reset_global_vector_size()
@classmethod
def concat(cls, parts):
parts = list(parts)
res = cls(size=sum(len(part) for part in parts))
base = 0
for reg in parts:
set_global_vector_size(reg.size)
reg.mov(res.get_vector(base, reg.size), reg)
reset_global_vector_size()
base += reg.size
return res
class _arithmetic_register(_register):
""" Arithmetic circuit type. """
def __init__(self, *args, **kwargs):
if program.options.garbled:
raise CompilerError('functionality only available in arithmetic circuits')
super(_arithmetic_register, self).__init__(*args, **kwargs)
@classmethod
def get_type(cls, length):
return cls
@staticmethod
def two_power(n, size=None):
return floatingpoint.two_power(n)
def Norm(self, k, f, simplex_flag=False):
return library.Norm(self, k, f, simplex_flag=simplex_flag)
class _clear(_arithmetic_register):
""" Clear domain-dependent type. """
__slots__ = []
mov = staticmethod(movc)
@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)
@vectorize
def binary_output(self, player=None):
""" Write 64-bit signed integer to
``Player-Data/Binary-Output-P<playerno>-<threadno>``.
:param player: only output on given player (default all)
"""
regint(self).binary_output(player)
@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, regint):
other = cls(other)
if isinstance(other, cls):
if reverse:
c_inst(res, other, self)
else:
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, regint)):
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)