import random
import math
class ObliviousRAM:
def __init__(self, size):
self.size = size
self.data = [None] * size
self.position_map = {}
def access(self, op, addr, value=None):
real_addr = self.position_map.get(addr, None)
if real_addr is None: # Randomly assign a new position for the address
while True:
real_addr = random.randint(0, self.size - 1)
if self.data[real_addr] is None:
self.data[real_addr] = (addr, value if op == 'write' else 0)
self.position_map[addr] = real_addr
break
else:
if op == 'read':
value = self.data[real_addr][1]
else: # 'write' operation
self.data[real_addr] = (addr, value)
fake_addr = random.randint(0, self.size - 1)
if fake_addr != real_addr:
if self.data[fake_addr] is None: # Empty block
self.data[fake_addr] = (None, 0)
else:
fake_addr_data = self.data[fake_addr]
self.position_map[fake_addr_data[0]] = real_addr
self.data[real_addr] = fake_addr_data
self.data[fake_addr] = (real_addr, value)
return value
def test_oram():
oram = ObliviousRAM(10)
oram.access('write', 1, 5)
assert oram.access('read', 1) == 5
oram.access('write', 2, 7)
assert oram.access('read', 2) == 7
oram.access('write', 1, 9)
assert oram.access('read', 1) == 9
print("Oblivious RAM tests passed!")
if __name__ == "__main__":
test_oram()
This implementation uses a simple random eviction strategy, which is not considered optimally secure, but it demonstrates the basic concept of Oblivious RAM. For more secure and performant implementations, refer to existing ORAM schemes such as Path ORAM, Square-root ORAM, etc.