1 ## Copyright 2002-2003 Andrew Loewenstern, All Rights Reserved
2 # see LICENSE.txt for license information
4 """Functions to deal with hashes (node IDs and keys).
6 @var HASH_LENGTH: the length of the hash to use in bytes
10 from os import urandom
12 from twisted.trial import unittest
17 """Convert a hash (big-endian) to a long python integer."""
18 assert len(hstr) == HASH_LENGTH
19 return long(hstr.encode('hex'), 16)
22 """Convert a long python integer to a hash."""
28 str = str.decode('hex')
29 return (HASH_LENGTH - len(str)) *'\x00' + str
32 """Calculate the distance between two hashes expressed as strings."""
33 return intify(a) ^ intify(b)
36 """Get a new pseudorandom globally unique hash string."""
38 h.update(urandom(HASH_LENGTH))
41 def newIDInRange(min, max):
42 """Get a new pseudorandom globally unique hash string in the range."""
43 return stringify(randRange(min,max))
45 def randRange(min, max):
46 """Get a new pseudorandom globally unique hash number in the range."""
47 return min + intify(newID()) % (max - min)
50 """Get a new pseudorandom transaction ID number."""
51 return randRange(-2**30, 2**30)
53 class TestNewID(unittest.TestCase):
54 """Test the newID function."""
56 self.failUnlessEqual(len(newID()), HASH_LENGTH)
57 def testHundreds(self):
61 class TestIntify(unittest.TestCase):
62 """Test the intify function."""
63 known = [('\0' * HASH_LENGTH, 0),
64 ('\xff' * HASH_LENGTH, 2L**(HASH_LENGTH*8) - 1),
67 for str, value in self.known:
68 self.failUnlessEqual(intify(str), value)
69 def testEndianessOnce(self):
71 while h[-1] == '\xff':
73 k = h[:-1] + chr(ord(h[-1]) + 1)
74 self.failUnlessEqual(intify(k) - intify(h), 1)
75 def testEndianessLots(self):
77 self.testEndianessOnce()
79 class TestDisantance(unittest.TestCase):
80 """Test the distance function."""
82 (("\0" * HASH_LENGTH, "\xff" * HASH_LENGTH), 2L**(HASH_LENGTH*8) -1),
83 ((sha("foo").digest(), sha("foo").digest()), 0),
84 ((sha("bar").digest(), sha("bar").digest()), 0)
87 for pair, dist in self.known:
88 self.failUnlessEqual(distance(pair[0], pair[1]), dist)
89 def testCommutitive(self):
91 x, y, z = newID(), newID(), newID()
92 self.failUnlessEqual(distance(x,y) ^ distance(y, z), distance(x, z))
94 class TestRandRange(unittest.TestCase):
95 """Test the randRange function."""
101 self.failUnlessEqual(a <= c < b, True, "output out of range %d %d %d" % (b, c, a))
104 self.failUnlessEqual(b <= c < a, True, "output out of range %d %d %d" % (b, c, a))
106 def testOneHundredTimes(self):
107 for i in xrange(100):