forked from bristolcrypto/SPDZ-2
-
Notifications
You must be signed in to change notification settings - Fork 0
/
oram.py
1695 lines (1595 loc) · 67.1 KB
/
oram.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
# (C) 2017 University of Bristol. See License.txt
import random
import math
import collections
import itertools
import operator
import sys
from Compiler.types import *
from Compiler.types import _secret
from Compiler.library import *
from Compiler.program import Program
from Compiler import floatingpoint,comparison,permutation
from Compiler.util import *
print_access = False
sint_bit_length = 6
max_demux_bits = 3
debug = False
use_binary_search = False
n_parallel = 1024
n_threads = None
detailed_timing = False
optimal_threshold = None
n_threads_for_tree = None
debug_online = False
crash_on_overflow = False
use_insecure_randomness = False
debug_ram_size = False
def maybe_start_timer(n):
if detailed_timing:
start_timer(n)
def maybe_stop_timer(n):
if detailed_timing:
stop_timer(n)
class Block(object):
def __init__(self, value, lengths):
self.value = self.value_type.hard_conv(value)
self.lengths = tuplify(lengths)
def get_slice(self):
res = []
for length,start in zip(self.lengths, series(self.lengths)):
res.append(util.bit_compose((self.bits[start:start+length])))
return res
def __repr__(self):
return '<' + str(self.value) + '>'
class intBlock(Block):
""" Bit slicing for modp. """
value_type = sint
def __init__(self, value, start, lengths, entries_per_block):
Block.__init__(self, value, lengths)
length = sum(self.lengths)
self.n_bits = length * entries_per_block
self.start = self.value_type.hard_conv(start * length)
self.lower, self.shift = \
floatingpoint.Trunc(self.value, self.n_bits, self.start, \
Program.prog.security, True)
trunc = (self.value - self.lower) / self.shift
self.slice = trunc.mod2m(length, self.n_bits, False)
self.upper = (trunc - self.slice) * self.shift
def get_slice(self):
total_length = sum(self.lengths)
if len(self.lengths) == 1:
self.bits = self.slice.bit_decompose(total_length)
return super(intBlock, self).get_slice()
else:
res = []
remainder = self.slice
for length,start in zip(self.lengths[:-1],series(self.lengths)):
res.append(remainder.mod2m(length, total_length - start, False))
remainder -= res[-1]
remainder /= floatingpoint.two_power(length)
res.append(remainder)
return res
def set_slice(self, value):
value = sum(v << start for v,start in zip(value, series(self.lengths)))
self.value = self.upper + self.lower + value * self.shift
return self
class gf2nBlock(Block):
""" Bit slicing for GF2n. """
value_type = sgf2n
def __init__(self, value, start, lengths, entries_per_block):
Block.__init__(self, value, lengths)
length = sum(self.lengths)
Program.prog.curr_tape.\
start_new_basicblock(name='gf2n-block-init-%d' % entries_per_block)
used_bits = entries_per_block * length
if entries_per_block == 2:
value_bits = bit_decompose(self.value, used_bits)
prod_bits = [start * bit for bit in value_bits]
anti_bits = [v - p for v,p in zip(value_bits,prod_bits)]
self.lower = sum(bit << i for i,bit in enumerate(prod_bits[:length]))
self.bits = map(operator.add, anti_bits[:length], prod_bits[length:]) + \
anti_bits[length:]
self.adjust = if_else(start, 1 << length, cgf2n(1))
elif entries_per_block < 4:
value_bits = bit_decompose(self.value, used_bits)
l = log2(entries_per_block)
start_bits = bit_decompose(start, l)
choice_bits = demux(start_bits)
inv_bits = [1 - bit for bit in floatingpoint.PreOR(choice_bits, None)]
mask_bits = sum(([x] * length for x in inv_bits), [])
lower_bits = map(operator.mul, value_bits, mask_bits)
self.lower = sum(bit << i for i,bit in enumerate(lower_bits))
self.bits = [sum(map(operator.mul, choice_bits, value_bits[i::length])) \
for i in range(length)]
self.adjust = sum(bit << (i * length) \
for i,bit in enumerate(choice_bits))
else:
value_bits = bit_decompose(self.value, used_bits)
l = log2(entries_per_block)
start_bits = bit_decompose(start, l)
powers = [2**(2**i) for i in range(l)]
selected = [power * bit + (1 - bit) \
for bit,power in zip(start_bits,powers)]
power_start = floatingpoint.KOpL(operator.mul, selected)
bits = bit_decompose(power_start, entries_per_block)
adjust = sum(bit << (i * length) for i,bit in enumerate(bits))
pre_bits = floatingpoint.PreOpL(lambda x,y,z=None: x + y, bits)
inv_bits = [1 - bit for bit in pre_bits]
mask_bits = sum(([x] * length for x in inv_bits), [])
lower_bits = map(operator.mul, value_bits, mask_bits)
masked = self.value - sum(bit << i for i,bit in enumerate(lower_bits))
self.lower = sum(bit << i for i,bit in enumerate(lower_bits))
self.bits = (masked / adjust).bit_decompose(used_bits)
self.adjust = adjust
Program.prog.curr_tape.\
start_new_basicblock(name='gf2n-block-init-end-%d' % entries_per_block)
def set_slice(self, value):
upper_bits = self.bits[sum(self.lengths):]
upper = (sum(b << i for i,b in enumerate(upper_bits)) * \
self.adjust) << sum(self.lengths)
value = sum(v << start for v,start in zip(value, series(self.lengths)))
self.value = self.lower + value * self.adjust + upper
return self
block_types = { sint: intBlock,
sgf2n: gf2nBlock,
}
def get_block(x, y, *args):
for t in block_types:
if isinstance(x, t):
return block_types[t](x, y, *args)
elif isinstance(y, t):
return block_types[t](x, y, *args)
raise CompilerError('appropiate block type not found')
def get_bit(x, index, bit_length):
if isinstance(x, sgf2n):
bits = x.bit_decompose(bit_length)
choice_bits = cgf2n(1 << index).bit_decompose(bit_length)
return sum(map(operator.mul, bits, choice_bits))
else:
return get_block(x, index, 1, bit_length).get_slice()[0]
def demux(x):
""" Demuxing like in the Galois paper. """
# res = Array(2**len(x), x[0].reg_type)
# for i,v in enumerate(demux_list(x)):
# res[i] = v
# return res
if 2**len(x) <= n_parallel:
return demux_list(x)
else:
return demux_array(x)
def demux_list(x):
n = len(x)
if n == 0:
return [1]
elif n == 1:
return [1 - x[0], x[0]]
a = demux_list(x[:n/2])
b = demux_list(x[n/2:])
n_a = len(a)
a *= len(b)
b = reduce(operator.add, ([i] * n_a for i in b))
res = map(operator.mul, a, b)
return res
def demux_array(x):
n = len(x)
res = Array(2**n, type(x[0]))
if n == 1:
res[0] = 1 - x[0]
res[1] = x[0]
else:
a = Array(2**(n/2), type(x[0]))
a.assign(demux(x[:n/2]))
b = Array(2**(n-n/2), type(x[0]))
b.assign(demux(x[n/2:]))
@for_range_multithread(get_n_threads(len(res)), \
max(1, n_parallel / len(b)), len(a))
def f(i):
@for_range_parallel(n_parallel, len(b))
def f(j):
res[j * len(a) + i] = a[i] * b[j]
return res
def get_first_one(x):
prefix_list = [0] + floatingpoint.PreOR(x, Program.prog.security)
return [prefix_list[i+1] - prefix_list[i] for i in range(len(x))]
class Value(object):
def __init__(self, value=None, empty=None):
if value is None:
self.empty = 1
self.value = 0
else:
try:
self.value = next(value)
self.empty = next(value)
except TypeError:
self.empty = 0 if empty is None else empty
self.value = value
def __iter__(self):
yield self.value
yield self.empty
def __add__(self, other):
return Value(self.value + other.value, self.empty + other.empty)
def __sub__(self, other):
return Value(self.value - other.value, self.empty - other.empty)
def __xor__(self, other):
return Value(self.value ^ other.value, self.empty ^ other.empty)
def __mul__(self, other):
return Value(other * self.value, other * self.empty)
__rmul__ = __mul__
def equal(self, other, length=None):
if isinstance(other, (int, long)) and isinstance(self.value, (int, long)):
return (1 - self.empty) * (other == self.value)
return (1 - self.empty) * self.value.equal(other, length)
def reveal(self):
return Value(reveal(self.value), reveal(self.empty))
def output(self):
# @if_e(self.empty)
# def f():
# print_str('<>')
# @else_
# def f():
print_str('<%s:%s>', self.empty, self.value)
def __index__(self):
return int(self.value)
def __repr__(self):
try:
value = self.empty
while True:
if value in (1, 1L):
return '<>'
if value in (0, 0L):
return '<%s>' % str(self.value)
value = value.value
except:
pass
return '<%s:%s>' % (str(self.value), str(self.empty))
class ValueTuple(tuple):
""" Works like a vector. """
def skip(self, skip):
return ValueTuple(self[skip:])
def __add__(self, other):
return ValueTuple(i + j for i,j in zip(self, other))
def __sub__(self, other):
return ValueTuple(i - j for i,j in zip(self, other))
def __xor__(self, other):
return ValueTuple(i ^ j for i,j in zip(self, other))
def __mul__(self, other):
return ValueTuple(other * i for i in self)
__rmul__ = __mul__
__rxor__ = __xor__
def output(self):
print_str('(' + ', '.join('%s' for i in range(len(self))) + ')', *self)
class Entry(object):
""" An (O)RAM entry with empty bit, index, and value. """
@staticmethod
def get_empty(value_type, value_length, apply_type=True):
t = value_type if apply_type else lambda x: x
bt = value_type if apply_type else lambda x: x
return Entry(t(0), tuple(t(0) for i in range(value_length)), bt(True), t)
def __init__(self, v, x=None, empty=None, value_type=None):
self.created_non_empty = False
if x is None:
v = iter(v)
self.is_empty = v.next()
self.v = v.next()
self.x = ValueTuple(v)
else:
if empty is None:
self.created_non_empty = True
empty = value_type(False)
self.is_empty = empty
self.v = v
if not isinstance(x, (tuple, list)):
x = (x,)
self.x = ValueTuple(x)
def empty(self):
return self.is_empty
def types(self):
return tuple(type(i) for i in self)
def values(self):
yield self.is_empty
yield self.v
for i in self.x:
yield i
def __iter__(self):
yield self.is_empty
yield self.v
for i in self.x:
yield i
def __len__(self):
return 2 + len(self.x)
def __repr__(self):
return '{empty=%s}' % self.is_empty if self.is_empty \
else '{%s: %s}' % (self.v, self.x)
def __add__(self, other):
try:
return Entry(i + j for i,j in zip(self, other))
except:
print self, other
raise
def __sub__(self, other):
return Entry(i - j for i,j in zip(self, other))
def __xor__(self, other):
return Entry(i ^ j for i,j in zip(self, other))
def __mul__(self, other):
try:
return Entry(other * i for i in self)
except:
print self, other
raise
__rmul__ = __mul__
def reveal(self):
return Entry(x.reveal() for x in self)
def output(self):
# @if_e(self.is_empty)
# def f():
# print_str('{empty=%s}', self.is_empty)
# @else_
# def f():
# print_str('{%s: %s}', self.v, self.x)\
print_str('{%s: %s,empty=%s}', self.v, self.x, self.is_empty)
class RefRAM(object):
""" RAM reference. """
def __init__(self, index, oram):
if debug_ram_size:
@if_(index >= oram.n_buckets())
def f():
print_ln('invalid bucket index %s for %s buckets', \
index, oram.n_buckets())
crash()
self.size = oram.bucket_size
self.entry_type = oram.entry_type
self.l = [t.dynamic_array(self.size, t, array.address + \
index * oram.bucket_size) \
for t,array in zip(self.entry_type,oram.ram.l)]
self.index = index
def init_mem(self, empty_entry):
print 'init ram'
for a,value in zip(self.l, empty_entry.values()):
a.assign_all(value)
def get_empty_bits(self):
return self.l[0]
def get_indices(self):
return self.l[1]
def get_values(self, skip=0):
return [ValueTuple(x) for x in zip(*self.l[2+skip:])]
def get_value(self, index, skip=0):
return ValueTuple(a[index] for a in self.l[2+skip:])
def get_value_length(self):
return len(self.l) - 2
def get_value_arrays(self):
return self.l[2:]
def get_value_array(self, index):
return [Value(self.l[2+index][i], self.l[0][i]) for i in range(self.size)]
def __getitem__(self, index):
if print_access:
print 'get', id(self), index
return Entry(a[index] for a in self.l)
def __setitem__(self, index, value):
if print_access:
print 'set', id(self), index
if not isinstance(value, Entry):
raise Exception('entries only please: %s' % str(value))
for i,(a,v) in enumerate(zip(self.l, value.values())):
a[index] = v
def __len__(self):
return self.size
def has_empty_entry(self):
return 1 - tree_reduce(operator.mul, [1 - bit for bit in self.get_empty_bits()])
def is_empty(self):
return tree_reduce(operator.mul, list(self.get_empty_bits()))
def reveal(self):
Program.prog.curr_tape.start_new_basicblock()
res = RAM(self.size, [t.clear_type for t in self.entry_type], self.index)
for i,a in enumerate(self.l):
for j,x in enumerate(a):
res.l[i][j] = x.reveal()
Program.prog.curr_tape.start_new_basicblock()
return res
def output(self):
print_ln('%s', [x.reveal() for x in self])
def print_reg(self):
print_ln('listing of RAM at index %s', self.index)
Program.prog.curr_tape.start_new_basicblock()
for i,array in enumerate(self.l):
for j,reg in enumerate(array):
print_str('%s:%s ', j, reg)
print_ln()
Program.prog.curr_tape.start_new_basicblock()
def __repr__(self):
return repr(self.l)
class RAM(RefRAM):
""" List of entries in memory. """
def __init__(self, size, entry_type, index=0):
#print_reg(cint(0), 'r in')
self.size = size
self.entry_type = entry_type
self.l = [t.dynamic_array(self.size, t) for t in entry_type]
self.index = index
class AbstractORAM(object):
""" Implements reading and writing using read_and_remove and add. """
def read(self, index):
return self._read(self.value_type.hard_conv(index))
def write(self, index, value):
new_value = [self.value_type.hard_conv(v) \
for v in (value if isinstance(value, (tuple, list)) \
else (value,))]
return self._write(self.value_type.hard_conv(index), *new_value)
def access(self, index, new_value, write, new_empty=False):
return self._access(self.value_type.hard_conv(index),
self.value_type.hard_conv(write),
self.value_type.hard_conv(new_empty),
*[self.value_type.hard_conv(v) for v in tuplify(new_value)])
def read_and_maybe_remove(self, index):
return self.read_and_remove(self.value_type.hard_conv(index)), \
self.state.read()
@method_block
def _read(self, index):
return self.access(index, (self.value_type(0),) * self.value_length, \
False)
@method_block
def _write(self, index, *value):
self.access(index, value, True)
@method_block
def _access(self, index, write, new_empty, *new_value):
Program.prog.curr_tape.\
start_new_basicblock(name='abstract-access-remove-%d' % self.size)
index = MemValue(self.value_type.hard_conv(index))
read_value, read_empty = self.read_and_remove(index)
if len(read_value) != self.value_length:
raise Exception('read_and_remove() of %s returns wrong length of ' \
'read value: %d, should be %d' % \
(type(self), len(read_value), \
self.value_length))
Program.prog.curr_tape.\
start_new_basicblock(name='abstract-access-add-%d' % self.size)
new_value = ValueTuple(new_value) \
if isinstance(new_value, (tuple, list)) \
else ValueTuple((new_value,))
if len(new_value) != self.value_length:
raise Exception('wrong length of new value')
value = tuple(MemValue(i) for i in if_else(write, new_value, read_value))
empty = self.value_type.hard_conv(new_empty)
self.add(Entry(index, value, if_else(write, empty, read_empty), \
value_type=self.value_type))
return read_value, read_empty
@method_block
def delete(self, index, for_real=True):
self.access(index, (self.value_type(0),) * self.value_length, \
for_real, True)
def __getitem__(self, index):
res, empty = self.read(index)
if len(res) == 1:
res = res[0]
return res
__setitem__ = write
class EmptyException(Exception):
pass
class RefTrivialORAM(object):
""" Trivial ORAM reference. """
contiguous = False
def empty_entry(self, apply_type=True):
return Entry.get_empty(self.value_type, self.value_length, apply_type)
def __init__(self, index, oram):
self.ram = RefRAM(index, oram)
self.index_size = oram.index_size
self.value_type, self.value_length = oram.internal_value_type()
self.size = oram.bucket_size
def init_mem(self):
print 'init trivial oram'
self.ram.init_mem(self.empty_entry())
def search(self, read_index):
if use_binary_search and self.value_type == sgf2n:
return self.binary_search(read_index)
else:
indices = self.ram.get_indices()
empty_bits = self.ram.get_empty_bits()
parallel = 1024
if comparison.const_rounds:
parallel /= 4
if self.size >= 128:
#n_threads = 8 if self.size >= 8 * parallel else 1
found = Array(self.size, self.value_type)
read_index = MemValue(read_index)
@for_range_multithread(n_threads, parallel, self.size)
def f(j):
found[j] = indices[j].equal(read_index, self.index_size) * \
(1 - empty_bits[j])
else:
found = [indices[j].equal(read_index, self.index_size) * \
(1 - empty_bits[j]) for j in range(self.size)]
# at most one 1 in found
empty = 1 - sum(found)
return found, empty
def read_and_remove(self, read_index, skip=0):
empty_entry = self.empty_entry(False)
self.last_index = read_index
found, empty = self.search(read_index)
entries = [entry for entry in self.ram]
prod_entries = map(operator.mul, found, entries)
read_value = sum((entry.x.skip(skip) for entry in prod_entries), \
empty * empty_entry.x.skip(skip))
for i,(entry, prod_entry) in enumerate(zip(entries, prod_entries)):
self.ram[i] = entry - prod_entry + found[i] * empty_entry
self.check(index=read_index, op='rar')
return read_value, empty
def read_and_maybe_remove(self, index):
return self.read_and_remove(index), 0
def read_and_remove_by_public(self, index):
empty_entry = self.empty_entry(False)
entries = [entry for entry in self.ram]
prod_entries = map(operator.mul, index, entries)
read_entry = reduce(operator.add, prod_entries)
for i,(entry, prod_entry) in enumerate(zip(entries, prod_entries)):
self.ram[i] = entry - prod_entry + index[i] * empty_entry
return read_entry
@method_block
def _read(self, index):
found, empty = self.search(index)
read_value = sum(map(operator.mul, found, self.ram.get_values()), \
empty * self.empty_entry(False).x)
return read_value, empty
@method_block
def _access(self, index, write, new_empty, *new_value):
empty_entry = self.empty_entry(False)
found, not_found = self.search(index)
add_here = self.find_first_empty()
entries = [entry for entry in self.ram]
prod_values = map(operator.mul, found, \
(entry.x for entry in entries))
read_value = sum(prod_values, not_found * empty_entry.x)
new_value = ValueTuple(new_value) \
if isinstance(new_value, (tuple, list)) \
else ValueTuple((new_value,))
for i,(entry,prod_value) in enumerate(zip(entries, prod_values)):
access_here = found[i] + not_found * add_here[i]
delta_entry = Entry(access_here * (index - entry.v), \
access_here * (new_value - entry.x), \
found[i] - \
if_else(new_empty, 0, access_here))
self.ram[i] = entry + write * delta_entry
return read_value, not_found
def check(self, found=None, index=None, new_entry=None, op=''):
if debug:
if found is None:
found = set()
for i,entry in enumerate(self.ram):
if not entry.empty():
if entry.v in found:
raise Exception('found double %s in %s' % (str(entry.v), str(self.ram.l)))
found.add(entry.v)
if index is not None:
for i,entry in enumerate(self.ram):
if not entry.empty() and index == entry.v:
raise Exception('not removed %s in %s' % \
(str(index), str(self.ram.l)))
if debug_online or debug:
#cint(0).print_reg(op)
entries = self.ram.reveal()
if index is not None:
index = index.reveal()
if new_entry is not None:
new_entry = Entry(x.reveal() for x in new_entry)
n_found = MemValue(0)
@for_range(self.size)
def f(i):
entry = entries[i]
@if_(entry.empty() != 1)
def f():
@if_e(entry.empty() == 0)
def f():
if index is not None:
@if_(entry.v == index)
def f():
entries.print_reg()
cint(0).print_reg(op)
cint(i).print_reg('trre')
entry.empty().print_reg('empt')
entry.v.print_reg('v')
index.print_reg('idx')
crash()
if new_entry is not None:
@if_(regint(1 - new_entry.empty()))
def f():
comps = Entry(x == y for x,y in \
zip(entry,new_entry))
@if_(reduce(operator.mul, comps))
def f():
n_found.iadd(1)
@else_
def f():
entries.print_reg()
cint(0).print_reg(op)
cint(i).print_reg('trem')
entry.empty().print_reg('empt')
crash()
if new_entry is not None:
@if_((n_found != 1) * (1 - new_entry.empty()))
def f():
entries.print_reg()
cint(0).print_reg(op)
cint(0).print_reg('trad')
cint(n_found).print_reg('n')
new_entry.v.print_reg('v')
for i,x in enumerate(new_entry.x):
x.print_reg('x%d' % i)
crash()
def binary_search(self, index):
if (self.size & (self.size-1)) != 0:
n = 2**(int(math.log(self.size,2)) + 1)
else:
n = self.size
indices = [i for i in self.ram.get_indices()]
if self.contiguous and n <= 256:
logn = int(math.log(n,2))
expand = 5
for i,x in enumerate(indices):
indices[i] = sum(y << (j * expand) for j,y in \
enumerate(x.bit_decompose(logn)))
index = sum(y << (j * expand) for j,y in \
enumerate(index.bit_decompose(logn)))
else:
expand = 1
# now search for zero
logn = int(round(math.log(n,2)))
mult_tree = [1] * 2*n
bit_prods = [None] * 2*n
for i in range(n-1, n-1 + self.size):
mult_tree[i] = indices[i - n + 1] - index
for i in range(n-2, -1, -1):
mult_tree[i] = mult_tree[2*i+1] * mult_tree[2*i+2]
b = 1 - mult_tree[0].equal(0, 40, expand)
bit_prods[0] = 1 - b
for j in range(1,logn+1):
M = 0
for k in range(2**(j)):
t = k + 2**(j) - 1
if k % 2 == 0:
M += bit_prods[(t-1)/2] * mult_tree[t]
b = 1 - M.equal(0, 40, expand)
for k in range(2**j):
t = k + 2**j - 1
if k % 2 == 0:
v = bit_prods[(t-1)/2] * b
bit_prods[t] = bit_prods[(t-1)/2] - v
else:
bit_prods[t] = v
return bit_prods[n-1:n-1+self.size], 1 - bit_prods[0]
def find_first_empty(self):
prefix_empty = [0] + \
floatingpoint.PreOR([empty for empty in self.ram.get_empty_bits()], \
Program.prog.security)
return [prefix_empty[i+1] - prefix_empty[i] \
for i in range(len(self.ram))]
def add(self, new_entry, state=None):
# if self.last_index != new_entry.v:
# raise Exception('index mismatch: %s / %s' %
# (str(self.last_index), str(new_entry.v)))
add_here = self.find_first_empty()
for i,entry in enumerate(self.ram):
self.ram[i] = if_else(add_here[i], new_entry, entry)
if crash_on_overflow:
@if_(or_op(sum(add_here), new_entry.is_empty).reveal() == 0)
def f():
self.output()
print_ln('New entry: %s:%s (empty: %s)', new_entry.v.reveal(),
new_entry.x[0].reveal(), new_entry.is_empty.reveal())
print_ln('Bucket overflow')
crash()
if debug and not sum(add_here) and not new_entry.empty():
print self.empty_entry()
raise Exception('no space for %s in %s' % (str(new_entry), str(self)))
self.check(new_entry=new_entry, op='add')
def pop(self):
self.last_index = None
empty_entry = self.empty_entry(False)
prefix_empty = [0] + \
floatingpoint.PreOR([1 - empty for empty in self.ram.get_empty_bits()], \
Program.prog.security)
pop_here = [prefix_empty[i+1] - prefix_empty[i] \
for i in range(len(self.ram))]
entries = [entry for entry in self.ram]
prod_entries = map(operator.mul, pop_here, self.ram)
result = (1 - sum(pop_here)) * empty_entry
result = sum(prod_entries, result)
for i,(entry, prod_entry) in enumerate(zip(entries, prod_entries)):
self.ram[i] = entry - prod_entry + pop_here[i] * empty_entry
self.check(index=result.v, op='pop')
if debug_online:
entry = Entry(x.reveal() for x in result)
@if_(entry.empty())
def f():
for i,x in enumerate((entry.v,) + entry.x):
@if_(x != 0)
def f():
print_ln('pop error:' + ' %s' * len(entry), *entry)
print_ln('%s ' * len(pop_here), \
*(x.reveal() for x in pop_here))
crash()
return result
def output(self):
self.ram.output()
def __repr__(self):
return repr(self.ram)
def batch_init(self, values):
for i,value in enumerate(values):
index = MemValue(self.value_type.hard_conv(i))
new_value = [MemValue(self.value_type.hard_conv(v)) \
for v in (value if isinstance(value, (tuple, list)) \
else (value,))]
self.ram[i] = Entry(index, new_value, value_type=self.value_type)
class TrivialORAM(RefTrivialORAM, AbstractORAM):
""" Trivial ORAM (obviously). """
ref_type = RefTrivialORAM
def __init__(self, size, value_type=sint, value_length=1, index_size=None, \
entry_size=None, contiguous=True, init_rounds=-1):
self.index_size = index_size or log2(size)
self.value_type = value_type
if entry_size is None:
self.value_length = value_length
else:
self.value_length = len(tuplify(entry_size))
self.contiguous = contiguous
entry_type = self.empty_entry().types()
self.size = size
self.ram = RAM(size, entry_type)
if init_rounds != -1:
# put memory initialization in different timer
stop_timer()
start_timer(1)
self.init_mem()
if init_rounds != -1:
stop_timer(1)
start_timer()
def get_n_threads(n_loops):
if n_threads is None:
if n_loops > 2048:
return 8
else:
return 1
else:
return n_threads
class LinearORAM(TrivialORAM):
""" Contiguous ORAM that stores entries in order. """
def read_and_maybe_remove(self, index):
return self.read(index), 0
def add(self, entry, state=None):
if entry.created_non_empty is True:
self.write(entry.v, entry.x)
else:
self.access(entry.v, entry.x, True, entry.empty())
def read_and_remove(self, *args):
raise CompilerError('not implemented')
@method_block
def _read(self, index):
maybe_start_timer(6)
empty_entry = self.empty_entry(False)
index_vector = \
demux_array(bit_decompose(index, self.index_size))
@map_sum(get_n_threads(self.size), n_parallel, self.size, \
self.value_length + 1, [self.value_type] + \
[self.value_type] * self.value_length)
def f(i):
entry = self.ram[i]
access_here = index_vector[i]
return access_here * ValueTuple((entry.empty(),) + entry.x)
not_found = f()[0]
read_value = ValueTuple(f()[1:]) + not_found * empty_entry.x
maybe_stop_timer(6)
return read_value, not_found
@method_block
def _write(self, index, *new_value):
maybe_start_timer(7)
empty_entry = self.empty_entry(False)
index_vector = \
demux_array(bit_decompose(index, self.index_size))
new_value = make_array(new_value)
@for_range_multithread(get_n_threads(self.size), n_parallel, self.size)
def f(i):
entry = self.ram[i]
access_here = index_vector[i]
nv = ValueTuple(new_value)
delta_entry = \
Entry(0, access_here * (nv - entry.x), \
- access_here * entry.empty())
self.ram[i] = entry + delta_entry
maybe_stop_timer(7)
@method_block
def _access(self, index, write, new_empty, *new_value):
empty_entry = self.empty_entry(False)
index_vector = \
demux_array(bit_decompose(index, self.index_size))
new_value = make_array(new_value)
new_empty = MemValue(new_empty)
write = MemValue(write)
@map_sum(get_n_threads(self.size), n_parallel, self.size, \
self.value_length + 1, [self.value_type] + \
[self.value_type] * self.value_length)
def f(i):
entry = self.ram[i]
access_here = index_vector[i]
nv = ValueTuple(new_value)
delta_entry = \
Entry(0, access_here * (nv - entry.x), \
access_here * (new_empty - entry.empty()))
self.ram[i] = entry + write * delta_entry
return access_here * ValueTuple((entry.empty(),) + entry.x)
not_found = f()[0]
read_value = ValueTuple(f()[1:]) + not_found * empty_entry.x
return read_value, not_found
class RefBucket(object):
""" Bucket for tree ORAM. Contains an ORAM of some type and
possibly two children. """
def __init__(self, index, oram):
self.bucket = oram.bucket_oram.ref_type(index, oram)
self.p_children = lambda i: regint.conv((index << 1) + i)
self.ref_children = lambda i: RefBucket(self.p_children(i), oram)
self.oram = oram
def check(self, depth, found=None, index=None):
if found is None:
found = set()
self.bucket.check(found, index)
if depth:
for i in (0,1):
self.ref_children(i).check(depth - 1, found, index)
def __repr__(self, depth=0):
result = ' ' * depth + repr(self.bucket) + '\n'
if depth < self.oram.D:
result += self.ref_children(0).__repr__(depth + 1) + \
self.ref_children(1).__repr__(depth + 1)
return result
def output(self):
print_reg(cint(self.depth), 'buck')
Program.prog.curr_tape.start_new_basicblock()
self.bucket.output()
print_reg(cint(self.depth), 'dep')
Program.prog.curr_tape.start_new_basicblock()
@if_(self.p_children(1) < oram.n_buckets())
def f():
for i in (0,1):
child = self.ref_children(i)
print_reg(cint(i), 'chil')
Program.prog.curr_tape.start_new_basicblock()
child.output()
def random_block(length, value_type):
return sum(value_type.get_random_bit() << i for i in range(length))
class List(object):
""" Debugging only. List which accepts secret values as indices
and *reveals* them. """
def __init__(self, size, value_type, value_length=1, init_rounds=None):
self.value_type = value_type
self.value_length = value_length
self.l = [value_type.dynamic_array(size, value_type) \
for i in range(value_length)]
for l in self.l:
l.assign_all(0)
__getitem__ = lambda self,index: [self.l[i][regint(reveal(index))] \
for i in range(self.value_length)]
def __setitem__(self, index, value):
# print 'set', index, value, cint(reveal(index))
# print self.l
Program.prog.curr_tape.start_new_basicblock(name='List-pre-write')
for i in range(self.value_length):
self.l[i][regint(reveal(index))] = value[i]
Program.prog.curr_tape.start_new_basicblock(name='List-post-write')
read_and_remove = lambda self,i: (self[i], None)
def read_and_maybe_remove(self, *args, **kwargs):
return self.read_and_remove(*args, **kwargs), 0
add = lambda self,entry: self.__setitem__(entry.v.read(), \
[v.read() for v in entry.x])
def batch_init(self, values):
for i,value in enumerate(values):
index = self.value_type.hard_conv(i)
new_value = [self.value_type.hard_conv(v) \
for v in (value if isinstance(value, (tuple, list)) \
else (value,))]
self.__setitem__(index, new_value)
def __repr__(self):
return repr(self.l)
class LocalIndexStructure(List):
""" Debugging only. Implements a tree ORAM index as list of
values, *revealing* which elements are accessed. """
def __init__(self, size, entry_size, value_type=sint, init_rounds=-1, \
random_init=False):
List.__init__(self, size, value_type)
if init_rounds:
@for_range(init_rounds if init_rounds > 0 else size)
def f(i):
self.l[0][i] = random_block(entry_size, value_type)
print 'index size:', size
def update(self, index, value):
read_value = self[index]
#print 'read', index, read_value
#print self.l
self[index] = (value,)
return self.value_type(read_value)
def output(self):
for i,v in enumerate(self):
print_reg(v.reveal(), 'i %d' % i)
__getitem__ = lambda self,index: List.__getitem__(self, index)[0]
def get_n_threads_for_tree(size):
if n_threads_for_tree is None:
if size >= 2**13:
return 8
else:
return 1
else:
return n_threads_for_tree
class TreeORAM(AbstractORAM):
""" Tree ORAM. """
def __init__(self, size, value_type=sint, value_length=1, entry_size=None, \
bucket_oram=TrivialORAM, init_rounds=-1):
print 'create oram of size', size
self.bucket_oram = bucket_oram
# heuristic bucket size
delta = 3
k = (math.log(size * size * log2(size) * 100, 2) + 21) / (1 + delta)
# size + 1 for bucket overflow check
self.bucket_size = min(int(math.ceil((1 + delta) * k)), size + 1)
self.D = log2(max(size / k, 2))
print 'bucket size:', self.bucket_size
print 'depth:', self.D
print 'complexity:', self.bucket_size * (self.D + 1)
self.value_type = value_type
if entry_size is not None:
self.value_length = len(tuplify(entry_size))
else:
self.value_length = value_length
self.index_size = log2(size)
self.size = size
empty_entry = Entry.get_empty(*self.internal_value_type())
self.entry_type = empty_entry.types()
self.ram = RAM(self.n_buckets() * self.bucket_size, self.entry_type)
if init_rounds != -1:
# put memory initialization in different timer
stop_timer()
start_timer(1)
self.ram.init_mem(empty_entry)
if init_rounds != -1:
stop_timer(1)
start_timer()
self.root = RefBucket(1, self)
self.index = self.index_structure(size, self.D, value_type, init_rounds, True)
self.read_value = Array(self.value_length, value_type)
self.read_non_empty = MemValue(self.value_type(0))
self.state = MemValue(self.value_type(0))