undid pointless FrozenList
[p2pool.git] / p2pool / bitcoin / data.py
1 from __future__ import division
2
3 import hashlib
4 import itertools
5 import struct
6
7 from . import base58, skiplists
8 from p2pool.util import bases, math, skiplist
9 import p2pool
10
11 class EarlyEnd(Exception):
12     pass
13
14 class LateEnd(Exception):
15     pass
16
17 def read((data, pos), length):
18     data2 = data[pos:pos + length]
19     if len(data2) != length:
20         raise EarlyEnd()
21     return data2, (data, pos + length)
22
23 def size((data, pos)):
24     return len(data) - pos
25
26 class Type(object):
27     # the same data can have only one unpacked representation, but multiple packed binary representations
28     
29     #def __hash__(self):
30     #    return hash(tuple(self.__dict__.items()))
31     
32     #def __eq__(self, other):
33     #    if not isinstance(other, Type):
34     #        raise NotImplementedError()
35     #    return self.__dict__ == other.__dict__
36     
37     def _unpack(self, data):
38         obj, (data2, pos) = self.read((data, 0))
39         
40         assert data2 is data
41         
42         if pos != len(data):
43             raise LateEnd()
44         
45         return obj
46     
47     def _pack(self, obj):
48         f = self.write(None, obj)
49         
50         res = []
51         while f is not None:
52             res.append(f[1])
53             f = f[0]
54         res.reverse()
55         return ''.join(res)
56     
57     
58     def unpack(self, data):
59         obj = self._unpack(data)
60         
61         if p2pool.DEBUG:
62             data2 = self._pack(obj)
63             if data2 != data:
64                 if self._unpack(data2) != obj:
65                     raise AssertionError()
66         
67         return obj
68     
69     def pack(self, obj):
70         data = self._pack(obj)
71         
72         if p2pool.DEBUG:
73             if self._unpack(data) != obj:
74                 raise AssertionError()
75         
76         return data
77     
78     
79     def pack_base58(self, obj):
80         return base58.base58_encode(self.pack(obj))
81     
82     def unpack_base58(self, base58_data):
83         return self.unpack(base58.base58_decode(base58_data))
84     
85     
86     def hash160(self, obj):
87         return ShortHashType().unpack(hashlib.new('ripemd160', hashlib.sha256(self.pack(obj)).digest()).digest())
88     
89     def hash256(self, obj):
90         return HashType().unpack(hashlib.sha256(hashlib.sha256(self.pack(obj)).digest()).digest())
91
92 class VarIntType(Type):
93     # redundancy doesn't matter here because bitcoin and p2pool both reencode before hashing
94     def read(self, file):
95         data, file = read(file, 1)
96         first = ord(data)
97         if first < 0xfd:
98             return first, file
99         elif first == 0xfd:
100             desc, length = '<H', 2
101         elif first == 0xfe:
102             desc, length = '<I', 4
103         elif first == 0xff:
104             desc, length = '<Q', 8
105         else:
106             raise AssertionError()
107         data, file = read(file, length)
108         return struct.unpack(desc, data)[0], file
109     
110     def write(self, file, item):
111         if item < 0xfd:
112             file = file, struct.pack('<B', item)
113         elif item <= 0xffff:
114             file = file, struct.pack('<BH', 0xfd, item)
115         elif item <= 0xffffffff:
116             file = file, struct.pack('<BI', 0xfe, item)
117         elif item <= 0xffffffffffffffff:
118             file = file, struct.pack('<BQ', 0xff, item)
119         else:
120             raise ValueError('int too large for varint')
121         return file
122
123 class VarStrType(Type):
124     _inner_size = VarIntType()
125     
126     def read(self, file):
127         length, file = self._inner_size.read(file)
128         return read(file, length)
129     
130     def write(self, file, item):
131         return self._inner_size.write(file, len(item)), item
132
133 class FixedStrType(Type):
134     def __init__(self, length):
135         self.length = length
136     
137     def read(self, file):
138         return read(file, self.length)
139     
140     def write(self, file, item):
141         if len(item) != self.length:
142             raise ValueError('incorrect length item!')
143         return file, item
144
145 class EnumType(Type):
146     def __init__(self, inner, values):
147         self.inner = inner
148         self.values = values
149         
150         self.keys = {}
151         for k, v in values.iteritems():
152             if v in self.keys:
153                 raise ValueError('duplicate value in values')
154             self.keys[v] = k
155     
156     def read(self, file):
157         data, file = self.inner.read(file)
158         return self.keys[data], file
159     
160     def write(self, file, item):
161         return self.inner.write(file, self.values[item])
162
163 class HashType(Type):
164     def read(self, file):
165         data, file = read(file, 256//8)
166         return int(data[::-1].encode('hex'), 16), file
167     
168     def write(self, file, item):
169         if not 0 <= item < 2**256:
170             raise ValueError('invalid hash value - %r' % (item,))
171         if item != 0 and item < 2**160:
172             print 'Very low hash value - maybe you meant to use ShortHashType? %x' % (item,)
173         return file, ('%064x' % (item,)).decode('hex')[::-1]
174
175 class ShortHashType(Type):
176     def read(self, file):
177         data, file = read(file, 160//8)
178         return int(data[::-1].encode('hex'), 16), file
179     
180     def write(self, file, item):
181         if not 0 <= item < 2**160:
182             raise ValueError('invalid hash value - %r' % (item,))
183         return file, ('%040x' % (item,)).decode('hex')[::-1]
184
185 class ListType(Type):
186     _inner_size = VarIntType()
187     
188     def __init__(self, type):
189         self.type = type
190     
191     def read(self, file):
192         length, file = self._inner_size.read(file)
193         res = []
194         for i in xrange(length):
195             item, file = self.type.read(file)
196             res.append(item)
197         return res, file
198     
199     def write(self, file, item):
200         file = self._inner_size.write(file, len(item))
201         for subitem in item:
202             file = self.type.write(file, subitem)
203         return file
204
205 class StructType(Type):
206     def __init__(self, desc):
207         self.desc = desc
208         self.length = struct.calcsize(self.desc)
209     
210     def read(self, file):
211         data, file = read(file, self.length)
212         res, = struct.unpack(self.desc, data)
213         return res, file
214     
215     def write(self, file, item):
216         data = struct.pack(self.desc, item)
217         if struct.unpack(self.desc, data)[0] != item:
218             # special test because struct doesn't error on some overflows
219             raise ValueError('''item didn't survive pack cycle (%r)''' % (item,))
220         return file, data
221
222 class IPV6AddressType(Type):
223     def read(self, file):
224         data, file = read(file, 16)
225         if data[:12] != '00000000000000000000ffff'.decode('hex'):
226             raise ValueError('ipv6 addresses not supported yet')
227         return '.'.join(str(ord(x)) for x in data[12:]), file
228     
229     def write(self, file, item):
230         bits = map(int, item.split('.'))
231         if len(bits) != 4:
232             raise ValueError('invalid address: %r' % (bits,))
233         data = '00000000000000000000ffff'.decode('hex') + ''.join(chr(x) for x in bits)
234         assert len(data) == 16, len(data)
235         return file, data
236
237 _record_types = {}
238
239 def get_record(fields):
240     fields = tuple(sorted(fields))
241     if 'keys' in fields:
242         raise ValueError()
243     if fields not in _record_types:
244         class _Record(object):
245             __slots__ = fields
246             def __getitem__(self, key):
247                 return getattr(self, key)
248             def __setitem__(self, key, value):
249                 setattr(self, key, value)
250             #def __iter__(self):
251             #    for field in self.__slots__:
252             #        yield field, getattr(self, field)
253             def keys(self):
254                 return self.__slots__
255             def __eq__(self, other):
256                 if isinstance(other, dict):
257                     return dict(self) == other
258                 elif isinstance(other, _Record):
259                     return all(self[k] == other[k] for k in self.keys())
260                 raise TypeError()
261             def __ne__(self, other):
262                 return not (self == other)
263         _record_types[fields] = _Record
264     return _record_types[fields]()
265
266 class ComposedType(Type):
267     def __init__(self, fields):
268         self.fields = fields
269     
270     def read(self, file):
271         item = get_record(k for k, v in self.fields)
272         for key, type_ in self.fields:
273             item[key], file = type_.read(file)
274         return item, file
275     
276     def write(self, file, item):
277         for key, type_ in self.fields:
278             file = type_.write(file, item[key])
279         return file
280
281 class ChecksummedType(Type):
282     def __init__(self, inner):
283         self.inner = inner
284     
285     def read(self, file):
286         obj, file = self.inner.read(file)
287         data = self.inner.pack(obj)
288         
289         checksum, file = read(file, 4)
290         if checksum != hashlib.sha256(hashlib.sha256(data).digest()).digest()[:4]:
291             raise ValueError('invalid checksum')
292         
293         return obj, file
294     
295     def write(self, file, item):
296         data = self.inner.pack(item)
297         return (file, data), hashlib.sha256(hashlib.sha256(data).digest()).digest()[:4]
298
299 class FloatingIntegerType(Type):
300     # redundancy doesn't matter here because bitcoin checks binary bits against its own computed bits
301     # so it will always be encoded 'normally' in blocks (they way bitcoin does it)
302     _inner = StructType('<I')
303     
304     def read(self, file):
305         bits, file = self._inner.read(file)
306         target = self._bits_to_target(bits)
307         if p2pool.DEBUG:
308             if self._target_to_bits(target) != bits:
309                 raise ValueError('bits in non-canonical form')
310         return target, file
311     
312     def write(self, file, item):
313         return self._inner.write(file, self._target_to_bits(item))
314     
315     def truncate_to(self, x):
316         return self._bits_to_target(self._target_to_bits(x, _check=False))
317     
318     def _bits_to_target(self, bits2):
319         target = math.shift_left(bits2 & 0x00ffffff, 8 * ((bits2 >> 24) - 3))
320         if p2pool.DEBUG:
321             assert target == self._bits_to_target1(struct.pack('<I', bits2))
322             assert self._target_to_bits(target, _check=False) == bits2
323         return target
324     
325     def _bits_to_target1(self, bits):
326         bits = bits[::-1]
327         length = ord(bits[0])
328         return bases.string_to_natural((bits[1:] + '\0'*length)[:length])
329     
330     def _target_to_bits(self, target, _check=True):
331         n = bases.natural_to_string(target)
332         if n and ord(n[0]) >= 128:
333             n = '\x00' + n
334         bits2 = (chr(len(n)) + (n + 3*chr(0))[:3])[::-1]
335         bits = struct.unpack('<I', bits2)[0]
336         if _check:
337             if self._bits_to_target(bits) != target:
338                 raise ValueError(repr((target, self._bits_to_target(bits, _check=False))))
339         return bits
340
341 class PossiblyNone(Type):
342     def __init__(self, none_value, inner):
343         self.none_value = none_value
344         self.inner = inner
345     
346     def read(self, file):
347         value, file = self.inner.read(file)
348         return None if value == self.none_value else value, file
349     
350     def write(self, file, item):
351         if item == self.none_value:
352             raise ValueError('none_value used')
353         return self.inner.write(file, self.none_value if item is None else item)
354
355 address_type = ComposedType([
356     ('services', StructType('<Q')),
357     ('address', IPV6AddressType()),
358     ('port', StructType('>H')),
359 ])
360
361 tx_type = ComposedType([
362     ('version', StructType('<I')),
363     ('tx_ins', ListType(ComposedType([
364         ('previous_output', PossiblyNone(dict(hash=0, index=2**32 - 1), ComposedType([
365             ('hash', HashType()),
366             ('index', StructType('<I')),
367         ]))),
368         ('script', VarStrType()),
369         ('sequence', PossiblyNone(2**32 - 1, StructType('<I'))),
370     ]))),
371     ('tx_outs', ListType(ComposedType([
372         ('value', StructType('<Q')),
373         ('script', VarStrType()),
374     ]))),
375     ('lock_time', StructType('<I')),
376 ])
377
378 block_header_type = ComposedType([
379     ('version', StructType('<I')),
380     ('previous_block', PossiblyNone(0, HashType())),
381     ('merkle_root', HashType()),
382     ('timestamp', StructType('<I')),
383     ('target', FloatingIntegerType()),
384     ('nonce', StructType('<I')),
385 ])
386
387 block_type = ComposedType([
388     ('header', block_header_type),
389     ('txs', ListType(tx_type)),
390 ])
391
392
393 merkle_record_type = ComposedType([
394     ('left', HashType()),
395     ('right', HashType()),
396 ])
397
398 def merkle_hash(tx_list):
399     if not tx_list:
400         return 0
401     hash_list = map(tx_type.hash256, tx_list)
402     while len(hash_list) > 1:
403         hash_list = [merkle_record_type.hash256(dict(left=left, right=left if right is None else right))
404             for left, right in zip(hash_list[::2], hash_list[1::2] + [None])]
405     return hash_list[0]
406
407 def target_to_average_attempts(target):
408     return 2**256//(target + 1)
409
410 # tx
411
412 def tx_get_sigop_count(tx):
413     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'])
414
415 # human addresses
416
417 human_address_type = ChecksummedType(ComposedType([
418     ('version', StructType('<B')),
419     ('pubkey_hash', ShortHashType()),
420 ]))
421
422 pubkey_type = FixedStrType(65)
423
424 def pubkey_hash_to_address(pubkey_hash, net):
425     return human_address_type.pack_base58(dict(version=net.BITCOIN_ADDRESS_VERSION, pubkey_hash=pubkey_hash))
426
427 def pubkey_to_address(pubkey, net):
428     return pubkey_hash_to_address(pubkey_type.hash160(pubkey), net)
429
430 def address_to_pubkey_hash(address, net):
431     x = human_address_type.unpack_base58(address)
432     if x['version'] != net.BITCOIN_ADDRESS_VERSION:
433         raise ValueError('address not for this net!')
434     return x['pubkey_hash']
435
436 # transactions
437
438 def pubkey_to_script2(pubkey):
439     return ('\x41' + pubkey_type.pack(pubkey)) + '\xac'
440
441 def pubkey_hash_to_script2(pubkey_hash):
442     return '\x76\xa9' + ('\x14' + ShortHashType().pack(pubkey_hash)) + '\x88\xac'
443
444 # linked list tracker
445
446 class Tracker(object):
447     def __init__(self):
448         self.shares = {} # hash -> share
449         #self.ids = {} # hash -> (id, height)
450         self.reverse_shares = {} # previous_hash -> set of share_hashes
451         
452         self.heads = {} # head hash -> tail_hash
453         self.tails = {} # tail hash -> set of head hashes
454         
455         self.heights = {} # share_hash -> height_to, other_share_hash
456         
457         '''
458         self.id_generator = itertools.count()
459         self.tails_by_id = {}
460         '''
461         
462         self.get_nth_parent_hash = skiplists.DistanceSkipList(self)
463     
464     def add(self, share):
465         assert not isinstance(share, (int, long, type(None)))
466         if share.hash in self.shares:
467             return # XXX raise exception?
468         
469         '''
470         parent_id = self.ids.get(share.previous_hash, None)
471         children_ids = set(self.ids.get(share2_hash) for share2_hash in self.reverse_shares.get(share.hash, set()))
472         infos = set()
473         if parent_id is not None:
474             infos.add((parent_id[0], parent_id[1] + 1))
475         for child_id in children_ids:
476             infos.add((child_id[0], child_id[1] - 1))
477         if not infos:
478             infos.add((self.id_generator.next(), 0))
479         chosen = min(infos)
480         self.ids[share.hash] = chosen
481         '''
482         
483         self.shares[share.hash] = share
484         self.reverse_shares.setdefault(share.previous_hash, set()).add(share.hash)
485         
486         if share.hash in self.tails:
487             heads = self.tails.pop(share.hash)
488         else:
489             heads = set([share.hash])
490         
491         if share.previous_hash in self.heads:
492             tail = self.heads.pop(share.previous_hash)
493         else:
494             #dist, tail = self.get_height_and_last(share.previous_hash) # XXX this should be moved out of the critical area even though it shouldn't matter
495             tail = share.previous_hash
496             while tail in self.shares:
497                 tail = self.shares[tail].previous_hash
498         
499         self.tails.setdefault(tail, set()).update(heads)
500         if share.previous_hash in self.tails[tail]:
501             self.tails[tail].remove(share.previous_hash)
502         
503         for head in heads:
504             self.heads[head] = tail
505     
506     def test(self):
507         t = Tracker()
508         for s in self.shares.itervalues():
509             t.add(s)
510         
511         assert self.shares == t.shares, (self.shares, t.shares)
512         assert self.reverse_shares == t.reverse_shares, (self.reverse_shares, t.reverse_shares)
513         assert self.heads == t.heads, (self.heads, t.heads)
514         assert self.tails == t.tails, (self.tails, t.tails)
515     
516     def remove(self, share_hash):
517         assert isinstance(share_hash, (int, long, type(None)))
518         if share_hash not in self.shares:
519             raise KeyError()
520         share = self.shares[share_hash]
521         del share_hash
522         
523         if share.hash in self.heads and share.previous_hash in self.tails:
524             tail = self.heads.pop(share.hash)
525             self.tails[tail].remove(share.hash)
526             if not self.tails[share.previous_hash]:
527                 self.tails.pop(share.previous_hash)
528         elif share.hash in self.heads:
529             tail = self.heads.pop(share.hash)
530             self.tails[tail].remove(share.hash)
531             if self.reverse_shares[share.previous_hash] != set([share.hash]):
532                 pass # has sibling
533             else:
534                 self.tails[tail].add(share.previous_hash)
535                 self.heads[share.previous_hash] = tail
536         elif share.previous_hash in self.tails:
537             raise NotImplementedError() # will break other things..
538             heads = self.tails[share.previous_hash]
539             if len(self.reverse_shares[share.previous_hash]) > 1:
540                 raise NotImplementedError()
541             else:
542                 del self.tails[share.previous_hash]
543                 for head in heads:
544                     self.heads[head] = share.hash
545                 self.tails[share.hash] = set(heads)
546         else:
547             raise NotImplementedError()
548         
549         '''
550         height, tail = self.get_height_and_last(share.hash)
551         
552         if share.hash in self.heads:
553             my_heads = set([share.hash])
554         elif share.previous_hash in self.tails:
555             my_heads = self.tails[share.previous_hash]
556         else:
557             some_heads = self.tails[tail]
558             some_heads_heights = dict((that_head, self.get_height_and_last(that_head)[0]) for that_head in some_heads)
559             my_heads = set(that_head for that_head in some_heads
560                 if some_heads_heights[that_head] > height and
561                 self.get_nth_parent_hash(that_head, some_heads_heights[that_head] - height) == share.hash)
562         
563         if share.previous_hash != tail:
564             self.heads[share.previous_hash] = tail
565         
566         for head in my_heads:
567             if head != share.hash:
568                 self.heads[head] = share.hash
569             else:
570                 self.heads.pop(head)
571         
572         if share.hash in self.heads:
573             self.heads.pop(share.hash)
574         
575         
576         self.tails[tail].difference_update(my_heads)
577         if share.previous_hash != tail:
578             self.tails[tail].add(share.previous_hash)
579         if not self.tails[tail]:
580             self.tails.pop(tail)
581         if my_heads != set([share.hash]):
582             self.tails[share.hash] = set(my_heads) - set([share.hash])
583         '''
584         
585         self.shares.pop(share.hash)
586         self.reverse_shares[share.previous_hash].remove(share.hash)
587         if not self.reverse_shares[share.previous_hash]:
588             self.reverse_shares.pop(share.previous_hash)
589         
590         #assert self.test() is None
591     
592     def get_height(self, share_hash):
593         height, work, last = self.get_height_work_and_last(share_hash)
594         return height
595     
596     def get_work(self, share_hash):
597         height, work, last = self.get_height_work_and_last(share_hash)
598         return work
599     
600     def get_height_and_last(self, share_hash):
601         height, work, last = self.get_height_work_and_last(share_hash)
602         return height, last
603     
604     def get_height_work_and_last(self, share_hash):
605         assert isinstance(share_hash, (int, long, type(None)))
606         orig = share_hash
607         height = 0
608         work = 0
609         updates = []
610         while True:
611             if share_hash is None or share_hash not in self.shares:
612                 break
613             updates.append((share_hash, height, work))
614             if share_hash in self.heights:
615                 height_inc, share_hash, work_inc = self.heights[share_hash]
616             else:
617                 height_inc, share_hash, work_inc = 1, self.shares[share_hash].previous_hash, target_to_average_attempts(self.shares[share_hash].target)
618             height += height_inc
619             work += work_inc
620         for update_hash, height_then, work_then in updates:
621             self.heights[update_hash] = height - height_then, share_hash, work - work_then
622         return height, work, share_hash
623     
624     def get_chain_known(self, start_hash):
625         assert isinstance(start_hash, (int, long, type(None)))
626         '''
627         Chain starting with item of hash I{start_hash} of items that this Tracker contains
628         '''
629         item_hash_to_get = start_hash
630         while True:
631             if item_hash_to_get not in self.shares:
632                 break
633             share = self.shares[item_hash_to_get]
634             assert not isinstance(share, long)
635             yield share
636             item_hash_to_get = share.previous_hash
637     
638     def get_chain_to_root(self, start_hash, root=None):
639         assert isinstance(start_hash, (int, long, type(None)))
640         assert isinstance(root, (int, long, type(None)))
641         '''
642         Chain of hashes starting with share_hash of shares to the root (doesn't include root)
643         Raises an error if one is missing
644         '''
645         share_hash_to_get = start_hash
646         while share_hash_to_get != root:
647             share = self.shares[share_hash_to_get]
648             yield share
649             share_hash_to_get = share.previous_hash
650     
651     def get_best_hash(self):
652         '''
653         Returns hash of item with the most items in its chain
654         '''
655         if not self.heads:
656             return None
657         return max(self.heads, key=self.get_height_and_last)
658     
659     def get_highest_height(self):
660         return max(self.get_height_and_last(head)[0] for head in self.heads) if self.heads else 0
661
662 class FakeShare(object):
663     def __init__(self, **kwargs):
664         self.__dict__.update(kwargs)
665
666 if __name__ == '__main__':
667     
668     t = Tracker()
669     
670     for i in xrange(10000):
671         t.add(FakeShare(hash=i, previous_hash=i - 1 if i > 0 else None))
672     
673     #t.remove(99)
674     
675     print 'HEADS', t.heads
676     print 'TAILS', t.tails
677     
678     import random
679     
680     while False:
681         print
682         print '-'*30
683         print
684         t = Tracker()
685         for i in xrange(random.randrange(100)):
686             x = random.choice(list(t.shares) + [None])
687             print i, '->', x
688             t.add(FakeShare(i, x))
689         while t.shares:
690             x = random.choice(list(t.shares))
691             print 'DEL', x, t.__dict__
692             try:
693                 t.remove(x)
694             except NotImplementedError:
695                 print 'aborted; not implemented'
696         import time
697         time.sleep(.1)
698         print 'HEADS', t.heads
699         print 'TAILS', t.tails
700     
701     #for share_hash, share in sorted(t.shares.iteritems()):
702     #    print share_hash, share.previous_hash, t.heads.get(share_hash), t.tails.get(share_hash)
703     
704     #import sys;sys.exit()
705     
706     print t.get_nth_parent_hash(9000, 5000)
707     print t.get_nth_parent_hash(9001, 412)
708     #print t.get_nth_parent_hash(90, 51)
709     
710     for share_hash in sorted(t.shares):
711         print str(share_hash).rjust(4),
712         x = t.skips.get(share_hash, None)
713         if x is not None:
714             print str(x[0]).rjust(4),
715             for a in x[1]:
716                 print str(a).rjust(10),
717         print
718
719 # network definitions
720
721 class Mainnet(object):
722     BITCOIN_P2P_PREFIX = 'f9beb4d9'.decode('hex')
723     BITCOIN_P2P_PORT = 8333
724     BITCOIN_ADDRESS_VERSION = 0
725
726 class Testnet(object):
727     BITCOIN_P2P_PREFIX = 'fabfb5da'.decode('hex')
728     BITCOIN_P2P_PORT = 18333
729     BITCOIN_ADDRESS_VERSION = 111