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