forked from bristolcrypto/SPDZ-2
-
Notifications
You must be signed in to change notification settings - Fork 0
/
util.py
134 lines (112 loc) · 2.88 KB
/
util.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
# (C) 2017 University of Bristol. See License.txt
import math
import operator
def format_trace(trace, prefix=' '):
if trace is None:
return '<omitted>'
else:
return ''.join('\n%sFile "%s", line %s, in %s\n%s %s' %
(prefix,i[0],i[1],i[2],prefix,i[3][0].strip()) \
for i in reversed(trace))
def tuplify(x):
if isinstance(x, (list, tuple)):
return tuple(x)
else:
return (x,)
def untuplify(x):
if len(x) == 1:
return x[0]
else:
return x
def greater_than(a, b, bits):
if isinstance(a, int) and isinstance(b, int):
return a > b
else:
return a.greater_than(b, bits)
def pow2(a, bits):
if isinstance(a, int):
return 2**a
else:
return a.pow2(bits)
def mod2m(a, b, bits, signed):
if isinstance(a, int):
return a % 2**b
else:
return a.mod2m(b, bits, signed=signed)
def right_shift(a, b, bits):
if isinstance(a, int):
return a >> b
else:
return a.right_shift(b, bits)
def bit_decompose(a, bits):
if isinstance(a, (int,long)):
return [int((a >> i) & 1) for i in range(bits)]
else:
return a.bit_decompose(bits)
def bit_compose(bits):
bits = list(bits)
try:
if bits:
return bits[0].bit_compose(bits)
else:
return 0
except AttributeError:
return sum(b << i for i,b in enumerate(bits))
def series(a):
sum = 0
for i in a:
yield sum
sum += i
yield sum
def if_else(cond, a, b):
try:
if isinstance(cond, (bool, int)):
if cond:
return a
else:
return b
return cond.if_else(a, b)
except:
print cond, a, b
raise
def cond_swap(cond, a, b):
if isinstance(cond, (bool, int)):
if cond:
return a, b
else:
return b, a
return cond.cond_swap(a, b)
def log2(x):
#print 'Compute log2 of', x
return int(math.ceil(math.log(x, 2)))
def tree_reduce(function, sequence):
n = len(sequence)
if n == 1:
return sequence[0]
else:
reduced = [function(sequence[2*i], sequence[2*i+1]) for i in range(n/2)]
return tree_reduce(function, reduced + sequence[n/2*2:])
def or_op(a, b):
return a + b - a * b
OR = or_op
def pow2(bits):
powers = [b.if_else(2**2**i, 1) for i,b in enumerate(bits)]
return tree_reduce(operator.mul, powers)
def irepeat(l, n):
return reduce(operator.add, ([i] * n for i in l))
def int_len(x):
return len(bin(x)) - 2
def reveal(x):
if isinstance(x, str):
return x
try:
return x.reveal()
except AttributeError:
pass
try:
return [reveal(y) for y in x]
except TypeError:
pass
return x
def is_constant(x):
return isinstance(x, (int, long, bool))