fixed deadlock bug
[p2prfd.git] / entangled_network.py
blob6124217baa58aacd608308966d5e5ca2937cc6d1
1 import hashlib
3 import entangled.kademlia.protocol
4 import entangled.node
6 class EntangledNetwork:
7 """a class representing an Entangled network"""
8 def __init__(self, udp_port, known_node = None):
9 self.node = entangled.node.EntangledNode(udp_port)
10 if known_node is not None:
11 known_nodes = [known_node]
12 else:
13 known_nodes = []
14 print 'joining %s' % (known_nodes)
15 self.node.joinNetwork(known_nodes)
16 pass
17 def delete_key(self, url):
18 def success_cb(result):
19 print 'success deleting'
20 pass
21 def error_cb(failure):
22 print 'error deleting'
23 pass
24 sh = hashlib.sha1()
25 sh.update(url)
26 hex_key = sh.hexdigest()
27 print 'deleting key %s from DHT' % (url)
28 h_key = sh.digest()
29 df = self.node.iterativeDelete(h_key)
30 df.addCallback(success_cb)
31 df.addErrback(error_cb)
32 def set_value(self, key, value):
33 sh = hashlib.sha1()
34 sh.update(key)
35 hex_key = sh.hexdigest()
36 print 'inserting key %s into DHT' % (key)
37 h_key = sh.digest()
38 df = self.node.iterativeStore(h_key, value)
39 def set_success(result):
40 print 'completed inserting key %s into DHT' % (key)
41 def set_failed(failure):
42 #failure.trap(entangled.kademlia.protocol.TimeoutError)
43 print 'failed inserting key %s into DHT' % (key)
44 df.addCallback(set_success)
45 df.addErrback(set_failed)
46 def get_value(self, key, callback):
47 sh = hashlib.sha1()
48 sh.update(key)
49 h_key = sh.digest()
50 hex_key = sh.hexdigest()
51 print 'retrieving value of key %s from DHT' % (key)
52 self.found = False
53 def returning(result):
54 if type(result) == dict:
55 print 'DHT response: key %s found' % key
56 #print 'value retrieved is %s' % (repr(result[h_key]))
57 callback(result[h_key])
58 else:
59 print 'DHT response: key %s not found' % key
60 callback(None)
61 self.found = result
62 def error_returning(failure):
63 print 'DHT error'
64 print repr(failure)
65 print str(failure)
66 #failure.trap(Exception)
67 self.found = 'error lho'
68 df = self.node.iterativeFindValue(h_key)
69 df.addCallback(returning)
70 df.addErrback(error_returning)