b84d253c59485bf6eef8e1fc5fc425d4034d807a
[p2pool.git] / p2pool / bitcoin / skiplists.py
1 from p2pool.util import skiplist
2
3 class DistanceSkipList(skiplist.SkipList):
4     def __init__(self, tracker):
5         skiplist.SkipList.__init__(self)
6         self.tracker = tracker
7     
8     def previous(self, element):
9         return self.tracker.shares[element].previous_hash
10     
11     def get_delta(self, element):
12         return element, 1, self.tracker.shares[element].previous_hash
13     
14     def combine_deltas(self, (from_hash1, dist1, to_hash1), (from_hash2, dist2, to_hash2)):
15         if to_hash1 != from_hash2:
16             raise AssertionError()
17         return from_hash1, dist1 + dist2, to_hash2
18     
19     def initial_solution(self, start, (n,)):
20         return 0, start
21     
22     def apply_delta(self, (dist1, to_hash1), (from_hash2, dist2, to_hash2), (n,)):
23         if to_hash1 != from_hash2:
24             raise AssertionError()
25         return dist1 + dist2, to_hash2
26     
27     def judge(self, (dist, hash), (n,)):
28         if dist > n:
29             return 1
30         elif dist == n:
31             return 0
32         else:
33             return -1
34     
35     def finalize(self, (dist, hash)):
36         return hash
37
38 if __name__ == '__main__':
39     import random
40     from p2pool.bitcoin import data
41     t = data.Tracker()
42     d = DistanceSkipList(t)
43     for i in xrange(2000):
44         t.add(data.FakeShare(hash=i, previous_hash=i - 1 if i > 0 else None))
45     for i in xrange(2000):
46         a = random.randrange(2000)
47         b = random.randrange(a + 1)
48         res = d(a, b)
49         assert res == a - b, (a, b, res)