Modify khashmir's config system to not use the const module.
[quix0rs-apt-p2p.git] / apt_dht_Khashmir / node.py
1 ## Copyright 2002-2003 Andrew Loewenstern, All Rights Reserved
2 # see LICENSE.txt for license information
3
4 from time import time
5 from types import InstanceType
6
7 import khash
8
9 # magic id to use before we know a peer's id
10 NULL_ID = 20 * '\0',
11
12 class Node:
13     """encapsulate contact info"""
14     def __init__(self):
15         self.fails = 0
16         self.lastSeen = 0
17         self.id = self.host = self.port = ''
18     
19     def init(self, id, host, port):
20         self.id = id
21         self.num = khash.intify(id)
22         self.host = host
23         self.port = port
24         self._senderDict = {'id': self.id, 'port' : self.port, 'host' : self.host}
25         return self
26     
27     def initWithDict(self, dict):
28         self._senderDict = dict
29         self.id = dict['id']
30         self.num = khash.intify(self.id)
31         self.port = dict['port']
32         self.host = dict['host']
33         return self
34     
35     def updateLastSeen(self):
36         self.lastSeen = time()
37         self.fails = 0
38     
39     def msgFailed(self):
40         self.fails = self.fails + 1
41         return self.fails
42     
43     def senderDict(self):
44         return self._senderDict
45     
46     def __repr__(self):
47         return `(self.id, self.host, self.port)`
48     
49     ## these comparators let us bisect/index a list full of nodes with either a node or an int/long
50     def __lt__(self, a):
51         if type(a) == InstanceType:
52             a = a.num
53         return self.num < a
54     def __le__(self, a):
55         if type(a) == InstanceType:
56             a = a.num
57         return self.num <= a
58     def __gt__(self, a):
59         if type(a) == InstanceType:
60             a = a.num
61         return self.num > a
62     def __ge__(self, a):
63         if type(a) == InstanceType:
64             a = a.num
65         return self.num >= a
66     def __eq__(self, a):
67         if type(a) == InstanceType:
68             a = a.num
69         return self.num == a
70     def __ne__(self, a):
71         if type(a) == InstanceType:
72             a = a.num
73         return self.num != a
74
75
76 import unittest
77
78 class TestNode(unittest.TestCase):
79     def setUp(self):
80         self.node = Node().init(khash.newID(), 'localhost', 2002)
81     def testUpdateLastSeen(self):
82         t = self.node.lastSeen
83         self.node.updateLastSeen()
84         assert t < self.node.lastSeen
85