Improve the creation of nodes and move all to the main khashmir class.
[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 datetime import datetime, MINYEAR
5 from types import InstanceType
6
7 from twisted.trial import unittest
8
9 import khash
10
11 # magic id to use before we know a peer's id
12 NULL_ID = 20 * '\0'
13
14 class Node:
15     """encapsulate contact info"""
16     def __init__(self, id, host = None, port = None):
17         self.fails = 0
18         self.lastSeen = datetime(MINYEAR, 1, 1)
19
20         # Alternate method, init Node from dictionary
21         if isinstance(id, dict):
22             host = id['host']
23             port = id['port']
24             id = id['id']
25
26         assert(isinstance(id, str))
27         assert(isinstance(host, str))
28         self.id = id
29         self.num = khash.intify(id)
30         self.host = host
31         self.port = int(port)
32         self._senderDict = {'id': self.id, 'port' : self.port, 'host' : self.host}
33     
34     def updateLastSeen(self):
35         self.lastSeen = datetime.now()
36         self.fails = 0
37     
38     def msgFailed(self):
39         self.fails = self.fails + 1
40         return self.fails
41     
42     def senderDict(self):
43         return self._senderDict
44     
45     def __repr__(self):
46         return `(self.id, self.host, self.port)`
47     
48     ## these comparators let us bisect/index a list full of nodes with either a node or an int/long
49     def __lt__(self, a):
50         if type(a) == InstanceType:
51             a = a.num
52         return self.num < a
53     def __le__(self, a):
54         if type(a) == InstanceType:
55             a = a.num
56         return self.num <= a
57     def __gt__(self, a):
58         if type(a) == InstanceType:
59             a = a.num
60         return self.num > a
61     def __ge__(self, a):
62         if type(a) == InstanceType:
63             a = a.num
64         return self.num >= a
65     def __eq__(self, a):
66         if type(a) == InstanceType:
67             a = a.num
68         return self.num == a
69     def __ne__(self, a):
70         if type(a) == InstanceType:
71             a = a.num
72         return self.num != a
73
74
75 class TestNode(unittest.TestCase):
76     def setUp(self):
77         self.node = Node(khash.newID(), 'localhost', 2002)
78     def testUpdateLastSeen(self):
79         t = self.node.lastSeen
80         self.node.updateLastSeen()
81         assert t < self.node.lastSeen
82