very preliminary merged mining support. has never produced a merged block but definit...
[p2pool.git] / p2pool / bitcoin / data.py
1 from __future__ import division
2
3 import hashlib
4 import itertools
5 import struct
6
7 from twisted.internet import defer
8
9 from . import base58, skiplists
10 from p2pool.util import bases, math, variable, expiring_dict, memoize, dicts
11 import p2pool
12
13 class EarlyEnd(Exception):
14     pass
15
16 class LateEnd(Exception):
17     pass
18
19 def read((data, pos), length):
20     data2 = data[pos:pos + length]
21     if len(data2) != length:
22         raise EarlyEnd()
23     return data2, (data, pos + length)
24
25 def size((data, pos)):
26     return len(data) - pos
27
28 class Type(object):
29     # the same data can have only one unpacked representation, but multiple packed binary representations
30     
31     def __hash__(self):
32         rval = getattr(self, '_hash', None)
33         if rval is None:
34             try:
35                 rval = self._hash = hash((type(self), frozenset(self.__dict__.items())))
36             except:
37                 print self.__dict__
38                 raise
39         return rval
40     
41     def __eq__(self, other):
42         return type(other) is type(self) and other.__dict__ == self.__dict__
43     
44     def __ne__(self, other):
45         return not (self == other)
46     
47     def _unpack(self, data):
48         obj, (data2, pos) = self.read((data, 0))
49         
50         assert data2 is data
51         
52         if pos != len(data):
53             raise LateEnd()
54         
55         return obj
56     
57     def _pack(self, obj):
58         f = self.write(None, obj)
59         
60         res = []
61         while f is not None:
62             res.append(f[1])
63             f = f[0]
64         res.reverse()
65         return ''.join(res)
66     
67     
68     def unpack(self, data):
69         obj = self._unpack(data)
70         
71         if p2pool.DEBUG:
72             data2 = self._pack(obj)
73             if data2 != data:
74                 if self._unpack(data2) != obj:
75                     raise AssertionError()
76         
77         return obj
78     
79     def pack2(self, obj):
80         data = self._pack(obj)
81         
82         if p2pool.DEBUG:
83             if self._unpack(data) != obj:
84                 raise AssertionError((self._unpack(data), obj))
85         
86         return data
87     
88     _backing = expiring_dict.ExpiringDict(100)
89     pack2 = memoize.memoize_with_backing(_backing, [unpack])(pack2)
90     unpack = memoize.memoize_with_backing(_backing)(unpack) # doesn't have an inverse
91     
92     def pack(self, obj):
93         return self.pack2(dicts.immutify(obj))
94     
95     
96     def pack_base58(self, obj):
97         return base58.base58_encode(self.pack(obj))
98     
99     def unpack_base58(self, base58_data):
100         return self.unpack(base58.base58_decode(base58_data))
101     
102     
103     def hash160(self, obj):
104         return ShortHashType().unpack(hashlib.new('ripemd160', hashlib.sha256(self.pack(obj)).digest()).digest())
105     
106     def hash256(self, obj):
107         return HashType().unpack(hashlib.sha256(hashlib.sha256(self.pack(obj)).digest()).digest())
108
109 class VarIntType(Type):
110     # redundancy doesn't matter here because bitcoin and p2pool both reencode before hashing
111     def read(self, file):
112         data, file = read(file, 1)
113         first = ord(data)
114         if first < 0xfd:
115             return first, file
116         elif first == 0xfd:
117             desc, length = '<H', 2
118         elif first == 0xfe:
119             desc, length = '<I', 4
120         elif first == 0xff:
121             desc, length = '<Q', 8
122         else:
123             raise AssertionError()
124         data, file = read(file, length)
125         return struct.unpack(desc, data)[0], file
126     
127     def write(self, file, item):
128         if item < 0xfd:
129             file = file, struct.pack('<B', item)
130         elif item <= 0xffff:
131             file = file, struct.pack('<BH', 0xfd, item)
132         elif item <= 0xffffffff:
133             file = file, struct.pack('<BI', 0xfe, item)
134         elif item <= 0xffffffffffffffff:
135             file = file, struct.pack('<BQ', 0xff, item)
136         else:
137             raise ValueError('int too large for varint')
138         return file
139
140 class VarStrType(Type):
141     _inner_size = VarIntType()
142     
143     def read(self, file):
144         length, file = self._inner_size.read(file)
145         return read(file, length)
146     
147     def write(self, file, item):
148         return self._inner_size.write(file, len(item)), item
149
150 class FixedStrType(Type):
151     def __init__(self, length):
152         self.length = length
153     
154     def read(self, file):
155         return read(file, self.length)
156     
157     def write(self, file, item):
158         if len(item) != self.length:
159             raise ValueError('incorrect length item!')
160         return file, item
161
162 class EnumType(Type):
163     def __init__(self, inner, values):
164         self.inner = inner
165         self.values = dicts.frozendict(values)
166         
167         keys = {}
168         for k, v in values.iteritems():
169             if v in keys:
170                 raise ValueError('duplicate value in values')
171             keys[v] = k
172         self.keys = dicts.frozendict(keys)
173     
174     def read(self, file):
175         data, file = self.inner.read(file)
176         if data not in self.keys:
177             raise ValueError('enum data (%r) not in values (%r)' % (data, self.values))
178         return self.keys[data], file
179     
180     def write(self, file, item):
181         if item not in self.values:
182             raise ValueError('enum item (%r) not in values (%r)' % (item, self.values))
183         return self.inner.write(file, self.values[item])
184
185 class HashType(Type):
186     def read(self, file):
187         data, file = read(file, 256//8)
188         return int(data[::-1].encode('hex'), 16), file
189     
190     def write(self, file, item):
191         if not 0 <= item < 2**256:
192             raise ValueError('invalid hash value - %r' % (item,))
193         if item != 0 and item < 2**160:
194             print 'Very low hash value - maybe you meant to use ShortHashType? %x' % (item,)
195         return file, ('%064x' % (item,)).decode('hex')[::-1]
196
197 class ShortHashType(Type):
198     def read(self, file):
199         data, file = read(file, 160//8)
200         return int(data[::-1].encode('hex'), 16), file
201     
202     def write(self, file, item):
203         if not 0 <= item < 2**160:
204             raise ValueError('invalid hash value - %r' % (item,))
205         return file, ('%040x' % (item,)).decode('hex')[::-1]
206
207 class ListType(Type):
208     _inner_size = VarIntType()
209     
210     def __init__(self, type):
211         self.type = type
212     
213     def read(self, file):
214         length, file = self._inner_size.read(file)
215         res = []
216         for i in xrange(length):
217             item, file = self.type.read(file)
218             res.append(item)
219         return res, file
220     
221     def write(self, file, item):
222         file = self._inner_size.write(file, len(item))
223         for subitem in item:
224             file = self.type.write(file, subitem)
225         return file
226
227 class StructType(Type):
228     def __init__(self, desc):
229         self.desc = desc
230         self.length = struct.calcsize(self.desc)
231     
232     def read(self, file):
233         data, file = read(file, self.length)
234         res, = struct.unpack(self.desc, data)
235         return res, file
236     
237     def write(self, file, item):
238         data = struct.pack(self.desc, item)
239         if struct.unpack(self.desc, data)[0] != item:
240             # special test because struct doesn't error on some overflows
241             raise ValueError('''item didn't survive pack cycle (%r)''' % (item,))
242         return file, data
243
244 class IPV6AddressType(Type):
245     def read(self, file):
246         data, file = read(file, 16)
247         if data[:12] != '00000000000000000000ffff'.decode('hex'):
248             raise ValueError('ipv6 addresses not supported yet')
249         return '.'.join(str(ord(x)) for x in data[12:]), file
250     
251     def write(self, file, item):
252         bits = map(int, item.split('.'))
253         if len(bits) != 4:
254             raise ValueError('invalid address: %r' % (bits,))
255         data = '00000000000000000000ffff'.decode('hex') + ''.join(chr(x) for x in bits)
256         assert len(data) == 16, len(data)
257         return file, data
258
259 _record_types = {}
260
261 def get_record(fields):
262     fields = tuple(sorted(fields))
263     if 'keys' in fields:
264         raise ValueError()
265     if fields not in _record_types:
266         class _Record(object):
267             __slots__ = fields
268             def __repr__(self):
269                 return repr(dict(self))
270             def __getitem__(self, key):
271                 return getattr(self, key)
272             def __setitem__(self, key, value):
273                 setattr(self, key, value)
274             #def __iter__(self):
275             #    for field in self.__slots__:
276             #        yield field, getattr(self, field)
277             def keys(self):
278                 return self.__slots__
279             def __eq__(self, other):
280                 if isinstance(other, dict):
281                     return dict(self) == other
282                 elif isinstance(other, _Record):
283                     return all(self[k] == other[k] for k in self.keys())
284                 raise TypeError()
285             def __ne__(self, other):
286                 return not (self == other)
287         _record_types[fields] = _Record
288     return _record_types[fields]()
289
290 class ComposedType(Type):
291     def __init__(self, fields):
292         self.fields = tuple(fields)
293     
294     def read(self, file):
295         item = get_record(k for k, v in self.fields)
296         for key, type_ in self.fields:
297             item[key], file = type_.read(file)
298         return item, file
299     
300     def write(self, file, item):
301         for key, type_ in self.fields:
302             file = type_.write(file, item[key])
303         return file
304
305 class ChecksummedType(Type):
306     def __init__(self, inner):
307         self.inner = inner
308     
309     def read(self, file):
310         obj, file = self.inner.read(file)
311         data = self.inner.pack(obj)
312         
313         checksum, file = read(file, 4)
314         if checksum != hashlib.sha256(hashlib.sha256(data).digest()).digest()[:4]:
315             raise ValueError('invalid checksum')
316         
317         return obj, file
318     
319     def write(self, file, item):
320         data = self.inner.pack(item)
321         return (file, data), hashlib.sha256(hashlib.sha256(data).digest()).digest()[:4]
322
323 class FloatingInteger(object):
324     __slots__ = ['_bits']
325     
326     @classmethod
327     def from_target_upper_bound(cls, target):
328         n = bases.natural_to_string(target)
329         if n and ord(n[0]) >= 128:
330             n = '\x00' + n
331         bits2 = (chr(len(n)) + (n + 3*chr(0))[:3])[::-1]
332         bits = struct.unpack('<I', bits2)[0]
333         return cls(bits)
334     
335     def __init__(self, bits):
336         self._bits = bits
337     
338     @property
339     def _value(self):
340         return math.shift_left(self._bits & 0x00ffffff, 8 * ((self._bits >> 24) - 3))
341     
342     def __hash__(self):
343         return hash(self._value)
344     
345     def __cmp__(self, other):
346         if isinstance(other, FloatingInteger):
347             return cmp(self._value, other._value)
348         elif isinstance(other, (int, long)):
349             return cmp(self._value, other)
350         else:
351             raise NotImplementedError()
352     
353     def __int__(self):
354         return self._value
355     
356     def __repr__(self):
357         return 'FloatingInteger(bits=%s (%x))' % (hex(self._bits), self)
358     
359     def __add__(self, other):
360         if isinstance(other, (int, long)):
361             return self._value + other
362         raise NotImplementedError()
363     __radd__ = __add__
364     def __mul__(self, other):
365         if isinstance(other, (int, long)):
366             return self._value * other
367         raise NotImplementedError()
368     __rmul__ = __mul__
369     def __truediv__(self, other):
370         if isinstance(other, (int, long)):
371             return self._value / other
372         raise NotImplementedError()
373     def __floordiv__(self, other):
374         if isinstance(other, (int, long)):
375             return self._value // other
376         raise NotImplementedError()
377     __div__ = __truediv__
378     def __rtruediv__(self, other):
379         if isinstance(other, (int, long)):
380             return other / self._value
381         raise NotImplementedError()
382     def __rfloordiv__(self, other):
383         if isinstance(other, (int, long)):
384             return other // self._value
385         raise NotImplementedError()
386     __rdiv__ = __rtruediv__
387
388 class FloatingIntegerType(Type):
389     _inner = StructType('<I')
390     
391     def read(self, file):
392         bits, file = self._inner.read(file)
393         return FloatingInteger(bits), file
394     
395     def write(self, file, item):
396         return self._inner.write(file, item._bits)
397
398 class PossiblyNoneType(Type):
399     def __init__(self, none_value, inner):
400         self.none_value = none_value
401         self.inner = inner
402     
403     def read(self, file):
404         value, file = self.inner.read(file)
405         return None if value == self.none_value else value, file
406     
407     def write(self, file, item):
408         if item == self.none_value:
409             raise ValueError('none_value used')
410         return self.inner.write(file, self.none_value if item is None else item)
411
412 address_type = ComposedType([
413     ('services', StructType('<Q')),
414     ('address', IPV6AddressType()),
415     ('port', StructType('>H')),
416 ])
417
418 tx_type = ComposedType([
419     ('version', StructType('<I')),
420     ('tx_ins', ListType(ComposedType([
421         ('previous_output', PossiblyNoneType(dicts.frozendict(hash=0, index=2**32 - 1), ComposedType([
422             ('hash', HashType()),
423             ('index', StructType('<I')),
424         ]))),
425         ('script', VarStrType()),
426         ('sequence', PossiblyNoneType(2**32 - 1, StructType('<I'))),
427     ]))),
428     ('tx_outs', ListType(ComposedType([
429         ('value', StructType('<Q')),
430         ('script', VarStrType()),
431     ]))),
432     ('lock_time', StructType('<I')),
433 ])
434
435 merkle_tx_type = ComposedType([
436     ('tx', tx_type),
437     ('block_hash', HashType()),
438     ('merkle_branch', ListType(HashType())),
439     ('index', StructType('<i')),
440 ])
441
442 block_header_type = ComposedType([
443     ('version', StructType('<I')),
444     ('previous_block', PossiblyNoneType(0, HashType())),
445     ('merkle_root', HashType()),
446     ('timestamp', StructType('<I')),
447     ('target', FloatingIntegerType()),
448     ('nonce', StructType('<I')),
449 ])
450
451 block_type = ComposedType([
452     ('header', block_header_type),
453     ('txs', ListType(tx_type)),
454 ])
455
456 aux_pow_type = ComposedType([
457     ('merkle_tx', merkle_tx_type),
458     ('merkle_branch', ListType(HashType())),
459     ('index', StructType('<i')),
460     ('parent_block_header', block_header_type),
461 ])
462
463
464 merkle_record_type = ComposedType([
465     ('left', HashType()),
466     ('right', HashType()),
467 ])
468
469 def merkle_hash(tx_list):
470     if not tx_list:
471         return 0
472     hash_list = map(tx_type.hash256, tx_list)
473     while len(hash_list) > 1:
474         hash_list = [merkle_record_type.hash256(dict(left=left, right=left if right is None else right))
475             for left, right in zip(hash_list[::2], hash_list[1::2] + [None])]
476     return hash_list[0]
477
478 def target_to_average_attempts(target):
479     return 2**256//(target + 1)
480
481 # tx
482
483 def tx_get_sigop_count(tx):
484     return sum(script.get_sigop_count(txin['script']) for txin in tx['tx_ins']) + sum(script.get_sigop_count(txout['script']) for txout in tx['tx_outs'])
485
486 # human addresses
487
488 human_address_type = ChecksummedType(ComposedType([
489     ('version', StructType('<B')),
490     ('pubkey_hash', ShortHashType()),
491 ]))
492
493 pubkey_type = FixedStrType(65)
494
495 def pubkey_hash_to_address(pubkey_hash, net):
496     return human_address_type.pack_base58(dict(version=net.BITCOIN_ADDRESS_VERSION, pubkey_hash=pubkey_hash))
497
498 def pubkey_to_address(pubkey, net):
499     return pubkey_hash_to_address(pubkey_type.hash160(pubkey), net)
500
501 def address_to_pubkey_hash(address, net):
502     x = human_address_type.unpack_base58(address)
503     if x['version'] != net.BITCOIN_ADDRESS_VERSION:
504         raise ValueError('address not for this net!')
505     return x['pubkey_hash']
506
507 # transactions
508
509 def pubkey_to_script2(pubkey):
510     return ('\x41' + pubkey_type.pack(pubkey)) + '\xac'
511
512 def pubkey_hash_to_script2(pubkey_hash):
513     return '\x76\xa9' + ('\x14' + ShortHashType().pack(pubkey_hash)) + '\x88\xac'
514
515 def script2_to_human(script2, net):
516     try:
517         pubkey = script2[1:-1]
518         script2_test = pubkey_to_script2(pubkey)
519     except:
520         pass
521     else:
522         if script2_test == script2:
523             return 'Pubkey. Address: %s' % (pubkey_to_address(pubkey, net),)
524     
525     try:
526         pubkey_hash = ShortHashType().unpack(script2[3:-2])
527         script2_test2 = pubkey_hash_to_script2(pubkey_hash)
528     except:
529         pass
530     else:
531         if script2_test2 == script2:
532             return 'Address. Address: %s' % (pubkey_hash_to_address(pubkey_hash, net),)
533     
534     return 'Unknown. Script: %s'  % (script2.encode('hex'),)
535
536 # linked list tracker
537
538 class Tracker(object):
539     def __init__(self):
540         self.shares = {} # hash -> share
541         #self.ids = {} # hash -> (id, height)
542         self.reverse_shares = {} # previous_hash -> set of share_hashes
543         
544         self.heads = {} # head hash -> tail_hash
545         self.tails = {} # tail hash -> set of head hashes
546         
547         self.heights = {} # share_hash -> height_to, ref, work_inc
548         self.reverse_heights = {} # ref -> set of share_hashes
549         
550         self.ref_generator = itertools.count()
551         self.height_refs = {} # ref -> height, share_hash, work_inc
552         self.reverse_height_refs = {} # share_hash -> ref
553         
554         self.get_nth_parent_hash = skiplists.DistanceSkipList(self)
555         
556         self.added = variable.Event()
557         self.removed = variable.Event()
558     
559     def add(self, share):
560         assert not isinstance(share, (int, long, type(None)))
561         if share.hash in self.shares:
562             raise ValueError('share already present')
563         
564         if share.hash in self.tails:
565             heads = self.tails.pop(share.hash)
566         else:
567             heads = set([share.hash])
568         
569         if share.previous_hash in self.heads:
570             tail = self.heads.pop(share.previous_hash)
571         else:
572             tail = self.get_last(share.previous_hash)
573             #tail2 = share.previous_hash
574             #while tail2 in self.shares:
575             #    tail2 = self.shares[tail2].previous_hash
576             #assert tail == tail2
577         
578         self.shares[share.hash] = share
579         self.reverse_shares.setdefault(share.previous_hash, set()).add(share.hash)
580         
581         self.tails.setdefault(tail, set()).update(heads)
582         if share.previous_hash in self.tails[tail]:
583             self.tails[tail].remove(share.previous_hash)
584         
585         for head in heads:
586             self.heads[head] = tail
587         
588         self.added.happened(share)
589     
590     def test(self):
591         t = Tracker()
592         for s in self.shares.itervalues():
593             t.add(s)
594         
595         assert self.shares == t.shares, (self.shares, t.shares)
596         assert self.reverse_shares == t.reverse_shares, (self.reverse_shares, t.reverse_shares)
597         assert self.heads == t.heads, (self.heads, t.heads)
598         assert self.tails == t.tails, (self.tails, t.tails)
599     
600     def remove(self, share_hash):
601         assert isinstance(share_hash, (int, long, type(None)))
602         if share_hash not in self.shares:
603             raise KeyError()
604         
605         share = self.shares[share_hash]
606         del share_hash
607         
608         children = self.reverse_shares.get(share.hash, set())
609         
610         # move height refs referencing children down to this, so they can be moved up in one step
611         if share.previous_hash in self.reverse_height_refs:
612             if share.previous_hash not in self.tails:
613                 for x in list(self.reverse_heights.get(self.reverse_height_refs.get(share.previous_hash, object()), set())):
614                     self.get_last(x)
615             for x in list(self.reverse_heights.get(self.reverse_height_refs.get(share.hash, object()), set())):
616                 self.get_last(x)
617             assert share.hash not in self.reverse_height_refs, list(self.reverse_heights.get(self.reverse_height_refs.get(share.hash, None), set()))
618         
619         if share.hash in self.heads and share.previous_hash in self.tails:
620             tail = self.heads.pop(share.hash)
621             self.tails[tail].remove(share.hash)
622             if not self.tails[share.previous_hash]:
623                 self.tails.pop(share.previous_hash)
624         elif share.hash in self.heads:
625             tail = self.heads.pop(share.hash)
626             self.tails[tail].remove(share.hash)
627             if self.reverse_shares[share.previous_hash] != set([share.hash]):
628                 pass # has sibling
629             else:
630                 self.tails[tail].add(share.previous_hash)
631                 self.heads[share.previous_hash] = tail
632         elif share.previous_hash in self.tails:
633             heads = self.tails[share.previous_hash]
634             if len(self.reverse_shares[share.previous_hash]) > 1:
635                 raise NotImplementedError()
636             else:
637                 del self.tails[share.previous_hash]
638                 for head in heads:
639                     self.heads[head] = share.hash
640                 self.tails[share.hash] = set(heads)
641         else:
642             raise NotImplementedError()
643         
644         # move ref pointing to this up
645         if share.previous_hash in self.reverse_height_refs:
646             assert share.hash not in self.reverse_height_refs, list(self.reverse_heights.get(self.reverse_height_refs.get(share.hash, object()), set()))
647             
648             ref = self.reverse_height_refs[share.previous_hash]
649             cur_height, cur_hash, cur_work = self.height_refs[ref]
650             assert cur_hash == share.previous_hash
651             self.height_refs[ref] = cur_height - 1, share.hash, cur_work - target_to_average_attempts(share.target)
652             del self.reverse_height_refs[share.previous_hash]
653             self.reverse_height_refs[share.hash] = ref
654         
655         # delete height entry, and ref if it is empty
656         if share.hash in self.heights:
657             _, ref, _ = self.heights.pop(share.hash)
658             self.reverse_heights[ref].remove(share.hash)
659             if not self.reverse_heights[ref]:
660                 del self.reverse_heights[ref]
661                 _, ref_hash, _ = self.height_refs.pop(ref)
662                 del self.reverse_height_refs[ref_hash]
663         
664         self.shares.pop(share.hash)
665         self.reverse_shares[share.previous_hash].remove(share.hash)
666         if not self.reverse_shares[share.previous_hash]:
667             self.reverse_shares.pop(share.previous_hash)
668         
669         #assert self.test() is None
670         self.removed.happened(share)
671     
672     def get_height(self, share_hash):
673         height, work, last = self.get_height_work_and_last(share_hash)
674         return height
675     
676     def get_work(self, share_hash):
677         height, work, last = self.get_height_work_and_last(share_hash)
678         return work
679     
680     def get_last(self, share_hash):
681         height, work, last = self.get_height_work_and_last(share_hash)
682         return last
683     
684     def get_height_and_last(self, share_hash):
685         height, work, last = self.get_height_work_and_last(share_hash)
686         return height, last
687     
688     def _get_height_jump(self, share_hash):
689         if share_hash in self.heights:
690             height_to1, ref, work_inc1 = self.heights[share_hash]
691             height_to2, share_hash, work_inc2 = self.height_refs[ref]
692             height_inc = height_to1 + height_to2
693             work_inc = work_inc1 + work_inc2
694         else:
695             height_inc, share_hash, work_inc = 1, self.shares[share_hash].previous_hash, target_to_average_attempts(self.shares[share_hash].target)
696         return height_inc, share_hash, work_inc
697     
698     def _set_height_jump(self, share_hash, height_inc, other_share_hash, work_inc):
699         if other_share_hash not in self.reverse_height_refs:
700             ref = self.ref_generator.next()
701             assert ref not in self.height_refs
702             self.height_refs[ref] = 0, other_share_hash, 0
703             self.reverse_height_refs[other_share_hash] = ref
704             del ref
705         
706         ref = self.reverse_height_refs[other_share_hash]
707         ref_height_to, ref_share_hash, ref_work_inc = self.height_refs[ref]
708         assert ref_share_hash == other_share_hash
709         
710         if share_hash in self.heights:
711             prev_ref = self.heights[share_hash][1]
712             self.reverse_heights[prev_ref].remove(share_hash)
713             if not self.reverse_heights[prev_ref] and prev_ref != ref:
714                 self.reverse_heights.pop(prev_ref)
715                 _, x, _ = self.height_refs.pop(prev_ref)
716                 self.reverse_height_refs.pop(x)
717         self.heights[share_hash] = height_inc - ref_height_to, ref, work_inc - ref_work_inc
718         self.reverse_heights.setdefault(ref, set()).add(share_hash)
719     
720     def get_height_work_and_last(self, share_hash):
721         assert isinstance(share_hash, (int, long, type(None)))
722         orig = share_hash
723         height = 0
724         work = 0
725         updates = []
726         while share_hash in self.shares:
727             updates.append((share_hash, height, work))
728             height_inc, share_hash, work_inc = self._get_height_jump(share_hash)
729             height += height_inc
730             work += work_inc
731         for update_hash, height_then, work_then in updates:
732             self._set_height_jump(update_hash, height - height_then, share_hash, work - work_then)
733         return height, work, share_hash
734     
735     def get_chain_known(self, start_hash):
736         assert isinstance(start_hash, (int, long, type(None)))
737         '''
738         Chain starting with item of hash I{start_hash} of items that this Tracker contains
739         '''
740         item_hash_to_get = start_hash
741         while True:
742             if item_hash_to_get not in self.shares:
743                 break
744             share = self.shares[item_hash_to_get]
745             assert not isinstance(share, long)
746             yield share
747             item_hash_to_get = share.previous_hash
748     
749     def get_chain_to_root(self, start_hash, root=None):
750         assert isinstance(start_hash, (int, long, type(None)))
751         assert isinstance(root, (int, long, type(None)))
752         '''
753         Chain of hashes starting with share_hash of shares to the root (doesn't include root)
754         Raises an error if one is missing
755         '''
756         share_hash_to_get = start_hash
757         while share_hash_to_get != root:
758             share = self.shares[share_hash_to_get]
759             yield share
760             share_hash_to_get = share.previous_hash
761     
762     def get_best_hash(self):
763         '''
764         Returns hash of item with the most items in its chain
765         '''
766         if not self.heads:
767             return None
768         return max(self.heads, key=self.get_height_and_last)
769     
770     def get_highest_height(self):
771         return max(self.get_height_and_last(head)[0] for head in self.heads) if self.heads else 0
772     
773     def is_child_of(self, share_hash, possible_child_hash):
774         height, last = self.get_height_and_last(share_hash)
775         child_height, child_last = self.get_height_and_last(possible_child_hash)
776         if child_last != last:
777             return None # not connected, so can't be determined
778         height_up = child_height - height
779         return height_up >= 0 and self.get_nth_parent_hash(possible_child_hash, height_up) == share_hash
780
781 class FakeShare(object):
782     def __init__(self, **kwargs):
783         self.__dict__.update(kwargs)
784
785 if __name__ == '__main__':
786     
787     t = Tracker()
788     
789     for i in xrange(10000):
790         t.add(FakeShare(hash=i, previous_hash=i - 1 if i > 0 else None))
791     
792     #t.remove(99)
793     
794     print 'HEADS', t.heads
795     print 'TAILS', t.tails
796     
797     import random
798     
799     while False:
800         print
801         print '-'*30
802         print
803         t = Tracker()
804         for i in xrange(random.randrange(100)):
805             x = random.choice(list(t.shares) + [None])
806             print i, '->', x
807             t.add(FakeShare(i, x))
808         while t.shares:
809             x = random.choice(list(t.shares))
810             print 'DEL', x, t.__dict__
811             try:
812                 t.remove(x)
813             except NotImplementedError:
814                 print 'aborted; not implemented'
815         import time
816         time.sleep(.1)
817         print 'HEADS', t.heads
818         print 'TAILS', t.tails
819     
820     #for share_hash, share in sorted(t.shares.iteritems()):
821     #    print share_hash, share.previous_hash, t.heads.get(share_hash), t.tails.get(share_hash)
822     
823     #import sys;sys.exit()
824     
825     print t.get_nth_parent_hash(9000, 5000)
826     print t.get_nth_parent_hash(9001, 412)
827     #print t.get_nth_parent_hash(90, 51)
828     
829     for share_hash in sorted(t.shares):
830         print str(share_hash).rjust(4),
831         x = t.skips.get(share_hash, None)
832         if x is not None:
833             print str(x[0]).rjust(4),
834             for a in x[1]:
835                 print str(a).rjust(10),
836         print
837
838 # network definitions
839
840 class Mainnet(object):
841     BITCOIN_P2P_PREFIX = 'f9beb4d9'.decode('hex')
842     BITCOIN_P2P_PORT = 8333
843     BITCOIN_ADDRESS_VERSION = 0
844     BITCOIN_RPC_PORT = 8332
845     BITCOIN_RPC_CHECK = staticmethod(defer.inlineCallbacks(lambda bitcoind: defer.returnValue(
846         'name_firstupdate' not in (yield bitcoind.rpc_help()) and
847         'ixcoinaddress' not in (yield bitcoind.rpc_help()) and
848         not (yield bitcoind.rpc_getinfo())['testnet']
849     )))
850     BITCOIN_SUBSIDY_FUNC = staticmethod(lambda height: 50*100000000 >> (height + 1)//210000)
851     BITCOIN_SYMBOL = 'BTC'
852
853 class Testnet(object):
854     BITCOIN_P2P_PREFIX = 'fabfb5da'.decode('hex')
855     BITCOIN_P2P_PORT = 18333
856     BITCOIN_ADDRESS_VERSION = 111
857     BITCOIN_RPC_PORT = 8332
858     BITCOIN_RPC_CHECK = staticmethod(defer.inlineCallbacks(lambda bitcoind: defer.returnValue(
859         'name_firstupdate' not in (yield bitcoind.rpc_help()) and
860         'ixcoinaddress' not in (yield bitcoind.rpc_help()) and
861         (yield bitcoind.rpc_getinfo())['testnet']
862     )))
863     BITCOIN_SUBSIDY_FUNC = staticmethod(lambda height: 50*100000000 >> (height + 1)//210000)
864     BITCOIN_SYMBOL = 'tBTC'