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