-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathmyRoutingTable.py
77 lines (62 loc) · 2.19 KB
/
myRoutingTable.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
from utils import HashLen;
def distance(peer1ID, peer2ID):
return HashLen - (peer1ID ^ peer2ID).bit_length;
class KadTable(object):
def __init__(self, ID, k=8):
self.ID = ID;
self.k = k;
self.buckets = {};
for i in range(HashLen+1):
self.buckets[i] = {};
super(KadTable, self).__init__();
def add(self, peerID, peer):
bucket = self.buckets[self.distance(peerID)];
# if(len(bucket) < self.k):
if peerID in bucket:
del bucket[peerID];
bucket[peerID] = peer;
def getPeerById(self,peerID):
bucket = self.buckets[self.distance(peerID)];
if peerID in bucket:
return bucket[peerID];
return None;
def getPeerByIP(self,IP):
for i in self.buckets.keys():
for ID in self.buckets[i].keys():
if self.buckets[i][ID][0] == IP:
return self.buckets[i][ID];
return None;
def getPeerIDByIP(self,IP):
for i in self.buckets.keys():
for ID in self.buckets[i].keys():
if self.buckets[i][ID][0] == IP:
return ID;
return None;
def remove(self, peerID):
bucket = self.buckets[self.distance(peerID)];
if peerID in bucket:
del bucket[peerID];
#TODO
def getKpeers(self, peerID):
peers = {};
for i in self.buckets.keys():
for ID in self.buckets[i].keys():
if(ID != peerID):
peers[ID] = self.buckets[i][ID];
return peers;
# TODO
def getNeighborhoods(self):
peers = {};
for i in self.buckets.keys():
for ID in self.buckets[i].keys():
if (ID != self.ID):
peers[ID] = self.buckets[i][ID];
return peers;
def distance(self,peerID):
# print(self.ID," ",peerID)
return HashLen - (self.ID ^ peerID).bit_length();
def printTable(self):
print("======================print my routing table============================")
for i in self.buckets.keys():
for ID in self.buckets[i].keys():
print(ID, " : ", self.buckets[i][ID]);