PyOpenDHT

I spent a little time today playing with OpenDHT and put together a little Python module for using it. I think it will make a great bootstrapping service for a darknet application.
import sha
import xmlrpclib

# Other gateways listed at http://opendht.org/servers.txt. This gateway uses
# OASIS (http://oasis.coralcdn.org/) to find the nearest node.
GATEWAY = 'http://opendht.nyuld.net:5851/'
# Application ID.
APP_ID = 'PyOpenDHT'# Response code to human-readable code mapping.
RESPONSES = {0: 'Success', 1: 'Capacity', 2: 'Again'}
# Time to live for puts and removes.
TTL = 3600


class OpenDht(object):

def __init__(self, gateway=GATEWAY):
self.server = xmlrpclib.ServerProxy(gateway)

def _EncodeHash(self, value):
return xmlrpclib.Binary(sha.new(value).digest())

def Put(self, key, value, ttl=TTL, secret=''):
key = self._EncodeHash(key)
value = xmlrpclib.Binary(value)
if secret:
secret = self._EncodeHash(secret)
return self.server.put_removable(key, value, 'SHA', secret, ttl, APP_ID)
return self.server.put(key, value, ttl, APP_ID)

def GetDetails(self, key, max_values=1, placemark=''):
key = self._EncodeHash(key)
placemark = xmlrpclib.Binary(placemark)
return self.server.get_details(key, max_values, placemark, APP_ID)

def Get(self, key, max_values=1, placemark=''):
key = self._EncodeHash(key)
placemark = xmlrpclib.Binary(placemark)
values, placemark = self.server.get(key, max_values, placemark, APP_ID)
values = [v.data for v in values]
placemark = placemark.data
return values, placemark

def GetAll(self, key, max_values=5):
key = self._EncodeHash(key)
values, placemark = self.Get(key, max_values)
while not placemark:
new_values, placemark = self.Get(key, max_values, placemark)
values.extend(new_values)

def Remove(self, key, value, secret, ttl=TTL):
key = self._EncodeHash(key)
value = self._EncodeHash(value)
secret = self._EncodeHash(secret)
return self.server.rm(key, value, 'SHA', secret, ttl, APP_ID)

No comments:

Post a Comment