2 """Functions to deal with hashes (node IDs and keys).
4 @var HASH_LENGTH: the length of the hash to use in bytes
10 from twisted.trial import unittest
15 """Convert a hash (big-endian) to a long python integer."""
16 assert len(hstr) == HASH_LENGTH
17 return long(hstr.encode('hex'), 16)
20 """Convert a long python integer to a hash."""
26 str = str.decode('hex')
27 return (HASH_LENGTH - len(str)) *'\x00' + str
30 """Calculate the distance between two hashes expressed as strings."""
31 return intify(a) ^ intify(b)
34 """Get a new pseudorandom globally unique hash string."""
36 h.update(urandom(HASH_LENGTH))
39 def newIDInRange(min, max):
40 """Get a new pseudorandom globally unique hash string in the range."""
41 return stringify(randRange(min,max))
43 def randRange(min, max):
44 """Get a new pseudorandom globally unique hash number in the range."""
45 return min + intify(newID()) % (max - min)
48 """Get a new pseudorandom transaction ID number."""
49 return randRange(-2**30, 2**30)
51 class TestNewID(unittest.TestCase):
52 """Test the newID function."""
54 self.failUnlessEqual(len(newID()), HASH_LENGTH)
55 def testHundreds(self):
59 class TestIntify(unittest.TestCase):
60 """Test the intify function."""
61 known = [('\0' * HASH_LENGTH, 0),
62 ('\xff' * HASH_LENGTH, 2L**(HASH_LENGTH*8) - 1),
65 for str, value in self.known:
66 self.failUnlessEqual(intify(str), value)
67 def testEndianessOnce(self):
69 while h[-1] == '\xff':
71 k = h[:-1] + chr(ord(h[-1]) + 1)
72 self.failUnlessEqual(intify(k) - intify(h), 1)
73 def testEndianessLots(self):
75 self.testEndianessOnce()
77 class TestDisantance(unittest.TestCase):
78 """Test the distance function."""
80 (("\0" * HASH_LENGTH, "\xff" * HASH_LENGTH), 2L**(HASH_LENGTH*8) -1),
81 ((sha("foo").digest(), sha("foo").digest()), 0),
82 ((sha("bar").digest(), sha("bar").digest()), 0)
85 for pair, dist in self.known:
86 self.failUnlessEqual(distance(pair[0], pair[1]), dist)
87 def testCommutitive(self):
89 x, y, z = newID(), newID(), newID()
90 self.failUnlessEqual(distance(x,y) ^ distance(y, z), distance(x, z))
92 class TestRandRange(unittest.TestCase):
93 """Test the randRange function."""
99 self.failUnlessEqual(a <= c < b, True, "output out of range %d %d %d" % (b, c, a))
102 self.failUnlessEqual(b <= c < a, True, "output out of range %d %d %d" % (b, c, a))
104 def testOneHundredTimes(self):
105 for i in xrange(100):