finished generation and added sharestore and p2p logic for new-style shares
[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_tx_type = ComposedType([
443     ('tx', tx_type),
444     ('block_hash', HashType()),
445     ('merkle_branch', ListType(HashType())),
446     ('index', StructType('<i')),
447 ])
448
449 block_header_type = ComposedType([
450     ('version', StructType('<I')),
451     ('previous_block', PossiblyNoneType(0, HashType())),
452     ('merkle_root', HashType()),
453     ('timestamp', StructType('<I')),
454     ('target', FloatingIntegerType()),
455     ('nonce', StructType('<I')),
456 ])
457
458 block_type = ComposedType([
459     ('header', block_header_type),
460     ('txs', ListType(tx_type)),
461 ])
462
463 aux_pow_type = ComposedType([
464     ('merkle_tx', merkle_tx_type),
465     ('merkle_branch', ListType(HashType())),
466     ('index', StructType('<i')),
467     ('parent_block_header', block_header_type),
468 ])
469
470
471 merkle_record_type = ComposedType([
472     ('left', HashType()),
473     ('right', HashType()),
474 ])
475
476 def merkle_hash(tx_list):
477     if not tx_list:
478         return 0
479     hash_list = map(tx_type.hash256, tx_list)
480     while len(hash_list) > 1:
481         hash_list = [merkle_record_type.hash256(dict(left=left, right=left if right is None else right))
482             for left, right in zip(hash_list[::2], hash_list[1::2] + [None])]
483     return hash_list[0]
484
485 def target_to_average_attempts(target):
486     return 2**256//(target + 1)
487
488 def target_to_difficulty(target):
489     return (0xffff0000 * 2**(256-64) + 1)/(target + 1)
490
491 # tx
492
493 def tx_get_sigop_count(tx):
494     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'])
495
496 # human addresses
497
498 human_address_type = ChecksummedType(ComposedType([
499     ('version', StructType('<B')),
500     ('pubkey_hash', ShortHashType()),
501 ]))
502
503 pubkey_type = FixedStrType(65)
504
505 def pubkey_hash_to_address(pubkey_hash, net):
506     return human_address_type.pack_base58(dict(version=net.BITCOIN_ADDRESS_VERSION, pubkey_hash=pubkey_hash))
507
508 def pubkey_to_address(pubkey, net):
509     return pubkey_hash_to_address(pubkey_type.hash160(pubkey), net)
510
511 def address_to_pubkey_hash(address, net):
512     x = human_address_type.unpack_base58(address)
513     if x['version'] != net.BITCOIN_ADDRESS_VERSION:
514         raise ValueError('address not for this net!')
515     return x['pubkey_hash']
516
517 # transactions
518
519 def pubkey_to_script2(pubkey):
520     return ('\x41' + pubkey_type.pack(pubkey)) + '\xac'
521
522 def pubkey_hash_to_script2(pubkey_hash):
523     return '\x76\xa9' + ('\x14' + ShortHashType().pack(pubkey_hash)) + '\x88\xac'
524
525 def script2_to_human(script2, net):
526     try:
527         pubkey = script2[1:-1]
528         script2_test = pubkey_to_script2(pubkey)
529     except:
530         pass
531     else:
532         if script2_test == script2:
533             return 'Pubkey. Address: %s' % (pubkey_to_address(pubkey, net),)
534     
535     try:
536         pubkey_hash = ShortHashType().unpack(script2[3:-2])
537         script2_test2 = pubkey_hash_to_script2(pubkey_hash)
538     except:
539         pass
540     else:
541         if script2_test2 == script2:
542             return 'Address. Address: %s' % (pubkey_hash_to_address(pubkey_hash, net),)
543     
544     return 'Unknown. Script: %s'  % (script2.encode('hex'),)
545
546 # linked list tracker
547
548 class Tracker(object):
549     def __init__(self):
550         self.shares = {} # hash -> share
551         #self.ids = {} # hash -> (id, height)
552         self.reverse_shares = {} # previous_hash -> set of share_hashes
553         
554         self.heads = {} # head hash -> tail_hash
555         self.tails = {} # tail hash -> set of head hashes
556         
557         self.heights = {} # share_hash -> height_to, ref, work_inc
558         self.reverse_heights = {} # ref -> set of share_hashes
559         
560         self.ref_generator = itertools.count()
561         self.height_refs = {} # ref -> height, share_hash, work_inc
562         self.reverse_height_refs = {} # share_hash -> ref
563         
564         self.get_nth_parent_hash = skiplists.DistanceSkipList(self)
565         
566         self.added = variable.Event()
567         self.removed = variable.Event()
568     
569     def add(self, share):
570         assert not isinstance(share, (int, long, type(None)))
571         if share.hash in self.shares:
572             raise ValueError('share already present')
573         
574         if share.hash in self.tails:
575             heads = self.tails.pop(share.hash)
576         else:
577             heads = set([share.hash])
578         
579         if share.previous_hash in self.heads:
580             tail = self.heads.pop(share.previous_hash)
581         else:
582             tail = self.get_last(share.previous_hash)
583             #tail2 = share.previous_hash
584             #while tail2 in self.shares:
585             #    tail2 = self.shares[tail2].previous_hash
586             #assert tail == tail2
587         
588         self.shares[share.hash] = share
589         self.reverse_shares.setdefault(share.previous_hash, set()).add(share.hash)
590         
591         self.tails.setdefault(tail, set()).update(heads)
592         if share.previous_hash in self.tails[tail]:
593             self.tails[tail].remove(share.previous_hash)
594         
595         for head in heads:
596             self.heads[head] = tail
597         
598         self.added.happened(share)
599     
600     def test(self):
601         t = Tracker()
602         for s in self.shares.itervalues():
603             t.add(s)
604         
605         assert self.shares == t.shares, (self.shares, t.shares)
606         assert self.reverse_shares == t.reverse_shares, (self.reverse_shares, t.reverse_shares)
607         assert self.heads == t.heads, (self.heads, t.heads)
608         assert self.tails == t.tails, (self.tails, t.tails)
609     
610     def remove(self, share_hash):
611         assert isinstance(share_hash, (int, long, type(None)))
612         if share_hash not in self.shares:
613             raise KeyError()
614         
615         share = self.shares[share_hash]
616         del share_hash
617         
618         children = self.reverse_shares.get(share.hash, set())
619         
620         # move height refs referencing children down to this, so they can be moved up in one step
621         if share.previous_hash in self.reverse_height_refs:
622             if share.previous_hash not in self.tails:
623                 for x in list(self.reverse_heights.get(self.reverse_height_refs.get(share.previous_hash, object()), set())):
624                     self.get_last(x)
625             for x in list(self.reverse_heights.get(self.reverse_height_refs.get(share.hash, object()), set())):
626                 self.get_last(x)
627             assert share.hash not in self.reverse_height_refs, list(self.reverse_heights.get(self.reverse_height_refs.get(share.hash, None), set()))
628         
629         if share.hash in self.heads and share.previous_hash in self.tails:
630             tail = self.heads.pop(share.hash)
631             self.tails[tail].remove(share.hash)
632             if not self.tails[share.previous_hash]:
633                 self.tails.pop(share.previous_hash)
634         elif share.hash in self.heads:
635             tail = self.heads.pop(share.hash)
636             self.tails[tail].remove(share.hash)
637             if self.reverse_shares[share.previous_hash] != set([share.hash]):
638                 pass # has sibling
639             else:
640                 self.tails[tail].add(share.previous_hash)
641                 self.heads[share.previous_hash] = tail
642         elif share.previous_hash in self.tails:
643             heads = self.tails[share.previous_hash]
644             if len(self.reverse_shares[share.previous_hash]) > 1:
645                 raise NotImplementedError()
646             else:
647                 del self.tails[share.previous_hash]
648                 for head in heads:
649                     self.heads[head] = share.hash
650                 self.tails[share.hash] = set(heads)
651         else:
652             raise NotImplementedError()
653         
654         # move ref pointing to this up
655         if share.previous_hash in self.reverse_height_refs:
656             assert share.hash not in self.reverse_height_refs, list(self.reverse_heights.get(self.reverse_height_refs.get(share.hash, object()), set()))
657             
658             ref = self.reverse_height_refs[share.previous_hash]
659             cur_height, cur_hash, cur_work = self.height_refs[ref]
660             assert cur_hash == share.previous_hash
661             self.height_refs[ref] = cur_height - 1, share.hash, cur_work - target_to_average_attempts(share.target)
662             del self.reverse_height_refs[share.previous_hash]
663             self.reverse_height_refs[share.hash] = ref
664         
665         # delete height entry, and ref if it is empty
666         if share.hash in self.heights:
667             _, ref, _ = self.heights.pop(share.hash)
668             self.reverse_heights[ref].remove(share.hash)
669             if not self.reverse_heights[ref]:
670                 del self.reverse_heights[ref]
671                 _, ref_hash, _ = self.height_refs.pop(ref)
672                 del self.reverse_height_refs[ref_hash]
673         
674         self.shares.pop(share.hash)
675         self.reverse_shares[share.previous_hash].remove(share.hash)
676         if not self.reverse_shares[share.previous_hash]:
677             self.reverse_shares.pop(share.previous_hash)
678         
679         #assert self.test() is None
680         self.removed.happened(share)
681     
682     def get_height(self, share_hash):
683         height, work, last = self.get_height_work_and_last(share_hash)
684         return height
685     
686     def get_work(self, share_hash):
687         height, work, last = self.get_height_work_and_last(share_hash)
688         return work
689     
690     def get_last(self, share_hash):
691         height, work, last = self.get_height_work_and_last(share_hash)
692         return last
693     
694     def get_height_and_last(self, share_hash):
695         height, work, last = self.get_height_work_and_last(share_hash)
696         return height, last
697     
698     def _get_height_jump(self, share_hash):
699         if share_hash in self.heights:
700             height_to1, ref, work_inc1 = self.heights[share_hash]
701             height_to2, share_hash, work_inc2 = self.height_refs[ref]
702             height_inc = height_to1 + height_to2
703             work_inc = work_inc1 + work_inc2
704         else:
705             height_inc, share_hash, work_inc = 1, self.shares[share_hash].previous_hash, target_to_average_attempts(self.shares[share_hash].target)
706         return height_inc, share_hash, work_inc
707     
708     def _set_height_jump(self, share_hash, height_inc, other_share_hash, work_inc):
709         if other_share_hash not in self.reverse_height_refs:
710             ref = self.ref_generator.next()
711             assert ref not in self.height_refs
712             self.height_refs[ref] = 0, other_share_hash, 0
713             self.reverse_height_refs[other_share_hash] = ref
714             del ref
715         
716         ref = self.reverse_height_refs[other_share_hash]
717         ref_height_to, ref_share_hash, ref_work_inc = self.height_refs[ref]
718         assert ref_share_hash == other_share_hash
719         
720         if share_hash in self.heights:
721             prev_ref = self.heights[share_hash][1]
722             self.reverse_heights[prev_ref].remove(share_hash)
723             if not self.reverse_heights[prev_ref] and prev_ref != ref:
724                 self.reverse_heights.pop(prev_ref)
725                 _, x, _ = self.height_refs.pop(prev_ref)
726                 self.reverse_height_refs.pop(x)
727         self.heights[share_hash] = height_inc - ref_height_to, ref, work_inc - ref_work_inc
728         self.reverse_heights.setdefault(ref, set()).add(share_hash)
729     
730     def get_height_work_and_last(self, share_hash):
731         assert isinstance(share_hash, (int, long, type(None)))
732         orig = share_hash
733         height = 0
734         work = 0
735         updates = []
736         while share_hash in self.shares:
737             updates.append((share_hash, height, work))
738             height_inc, share_hash, work_inc = self._get_height_jump(share_hash)
739             height += height_inc
740             work += work_inc
741         for update_hash, height_then, work_then in updates:
742             self._set_height_jump(update_hash, height - height_then, share_hash, work - work_then)
743         return height, work, share_hash
744     
745     def get_chain_known(self, start_hash):
746         assert isinstance(start_hash, (int, long, type(None)))
747         '''
748         Chain starting with item of hash I{start_hash} of items that this Tracker contains
749         '''
750         item_hash_to_get = start_hash
751         while True:
752             if item_hash_to_get not in self.shares:
753                 break
754             share = self.shares[item_hash_to_get]
755             assert not isinstance(share, long)
756             yield share
757             item_hash_to_get = share.previous_hash
758     
759     def get_chain_to_root(self, start_hash, root=None):
760         assert isinstance(start_hash, (int, long, type(None)))
761         assert isinstance(root, (int, long, type(None)))
762         '''
763         Chain of hashes starting with share_hash of shares to the root (doesn't include root)
764         Raises an error if one is missing
765         '''
766         share_hash_to_get = start_hash
767         while share_hash_to_get != root:
768             share = self.shares[share_hash_to_get]
769             yield share
770             share_hash_to_get = share.previous_hash
771     
772     def get_best_hash(self):
773         '''
774         Returns hash of item with the most items in its chain
775         '''
776         if not self.heads:
777             return None
778         return max(self.heads, key=self.get_height_and_last)
779     
780     def get_highest_height(self):
781         return max(self.get_height_and_last(head)[0] for head in self.heads) if self.heads else 0
782     
783     def is_child_of(self, share_hash, possible_child_hash):
784         height, last = self.get_height_and_last(share_hash)
785         child_height, child_last = self.get_height_and_last(possible_child_hash)
786         if child_last != last:
787             return None # not connected, so can't be determined
788         height_up = child_height - height
789         return height_up >= 0 and self.get_nth_parent_hash(possible_child_hash, height_up) == share_hash
790
791 class FakeShare(object):
792     def __init__(self, **kwargs):
793         self.__dict__.update(kwargs)
794
795 if __name__ == '__main__':
796     
797     t = Tracker()
798     
799     for i in xrange(10000):
800         t.add(FakeShare(hash=i, previous_hash=i - 1 if i > 0 else None))
801     
802     #t.remove(99)
803     
804     print 'HEADS', t.heads
805     print 'TAILS', t.tails
806     
807     import random
808     
809     while False:
810         print
811         print '-'*30
812         print
813         t = Tracker()
814         for i in xrange(random.randrange(100)):
815             x = random.choice(list(t.shares) + [None])
816             print i, '->', x
817             t.add(FakeShare(i, x))
818         while t.shares:
819             x = random.choice(list(t.shares))
820             print 'DEL', x, t.__dict__
821             try:
822                 t.remove(x)
823             except NotImplementedError:
824                 print 'aborted; not implemented'
825         import time
826         time.sleep(.1)
827         print 'HEADS', t.heads
828         print 'TAILS', t.tails
829     
830     #for share_hash, share in sorted(t.shares.iteritems()):
831     #    print share_hash, share.previous_hash, t.heads.get(share_hash), t.tails.get(share_hash)
832     
833     #import sys;sys.exit()
834     
835     print t.get_nth_parent_hash(9000, 5000)
836     print t.get_nth_parent_hash(9001, 412)
837     #print t.get_nth_parent_hash(90, 51)
838     
839     for share_hash in sorted(t.shares):
840         print str(share_hash).rjust(4),
841         x = t.skips.get(share_hash, None)
842         if x is not None:
843             print str(x[0]).rjust(4),
844             for a in x[1]:
845                 print str(a).rjust(10),
846         print
847
848 # network definitions
849
850 class Mainnet(object):
851     BITCOIN_P2P_PREFIX = 'f9beb4d9'.decode('hex')
852     BITCOIN_P2P_PORT = 8333
853     BITCOIN_ADDRESS_VERSION = 0
854     BITCOIN_RPC_PORT = 8332
855     BITCOIN_RPC_CHECK = staticmethod(defer.inlineCallbacks(lambda bitcoind: defer.returnValue(
856         'name_firstupdate' not in (yield bitcoind.rpc_help()) and
857         'ixcoinaddress' not in (yield bitcoind.rpc_help()) and
858         not (yield bitcoind.rpc_getinfo())['testnet']
859     )))
860     BITCOIN_SUBSIDY_FUNC = staticmethod(lambda height: 50*100000000 >> (height + 1)//210000)
861     BITCOIN_SYMBOL = 'BTC'
862
863 class Testnet(object):
864     BITCOIN_P2P_PREFIX = 'fabfb5da'.decode('hex')
865     BITCOIN_P2P_PORT = 18333
866     BITCOIN_ADDRESS_VERSION = 111
867     BITCOIN_RPC_PORT = 8332
868     BITCOIN_RPC_CHECK = staticmethod(defer.inlineCallbacks(lambda bitcoind: defer.returnValue(
869         'name_firstupdate' not in (yield bitcoind.rpc_help()) and
870         'ixcoinaddress' not in (yield bitcoind.rpc_help()) and
871         (yield bitcoind.rpc_getinfo())['testnet']
872     )))
873     BITCOIN_SUBSIDY_FUNC = staticmethod(lambda height: 50*100000000 >> (height + 1)//210000)
874     BITCOIN_SYMBOL = 'tBTC'